<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Wandia Mugo on Medium]]></title>
        <description><![CDATA[Stories by Wandia Mugo on Medium]]></description>
        <link>https://medium.com/@wandiamugo?source=rss-19a686aeb31e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*p59zrYo3fQmacFie</url>
            <title>Stories by Wandia Mugo on Medium</title>
            <link>https://medium.com/@wandiamugo?source=rss-19a686aeb31e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 25 Nov 2026 00:38:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@wandiamugo/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Deconstructing Bitcoin Core Tests]]></title>
            <link>https://medium.com/@wandiamugo/deconstructing-bitcoin-core-tests-50b2ace53ec2?source=rss-19a686aeb31e------2</link>
            <guid isPermaLink="false">https://medium.com/p/50b2ace53ec2</guid>
            <dc:creator><![CDATA[Wandia Mugo]]></dc:creator>
            <pubDate>Mon, 09 Mar 2026 06:38:19 GMT</pubDate>
            <atom:updated>2026-03-09T06:38:19.444Z</atom:updated>
            <content:encoded><![CDATA[<h4>Day 9: feature_bind_port_externalip.py — Port Priority When Advertising External Addresses</h4><p><strong>Test File:</strong> `test/functional/feature_bind_port_externalip.py`</p><p><strong>Category:</strong> Feature Tests</p><p><strong>Complexity:</strong> Medium</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KzmvGfJ8TrSKtuEOwLMnPw.jpeg" /></figure><p><em>Testing that when you tell Bitcoin Core “advertise this IP address,” it also figures out the correct port number to pair with it, like making sure your business card shows the right extension number, not just the building’s main phone number.</em></p><h4>The Analogy: The Business Card Port Number Puzzle</h4><p>Imagine you work in a large office building with a complex phone system:</p><p>- The building’s main number is (555) 100–0000</p><p>- Your direct line is (555) 200–0000</p><p>- You can receive calls on various extensions: 1001, 1002, 1003, etc.</p><p>- You have an internal intercom on extension 5000</p><p>Now, you’re printing business cards to hand out at a conference. You want to advertise your direct line `(555) 200–0000`, but which extension should be printed with it?</p><p>- Should it be extension 1001 (from `-port=1001`)?</p><p>- Should it be extension 1002 (from `-bind=192.168.1.5:1002`)?</p><p>- Should it be extension 1003 (from the direct line itself: `-externalip=555–200–0000:1003`)?</p><p>- Should it be the default extension for your building?</p><p><strong>This test ensures Bitcoin Core follows a clear priority hierarchy</strong> to get the port number right when advertising an external IP address.</p><h3>Test Overview</h3><p>The `feature_bind_port_externalip.py` test validates that Bitcoin Core correctly determines which port number to advertise alongside an external IP address when various combinations of `-externalip`, `-port`, `-bind`, and `-whitebind` are specified.</p><p><strong>The Setup:</strong> Like the previous test, this requires a routable IP address (`1.1.1.1`) configured on the test machine — think of it as having an actual phone line to test with.</p><p><strong>The Test Matrix:</strong> The test runs 12 different Bitcoin nodes, each with a different combination of configuration arguments, and verifies that each one advertises the correct port number with the external IP `2.2.2.2`.</p><h4>The Port Priority Hierarchy: Who Wins?</h4><p>Bitcoin Core uses this priority order when determining which port to advertise with an external IP:</p><p><strong>Priority 1: Port specified in `-externalip` itself (Highest Priority)</strong></p><pre>bash</pre><pre>-externalip=2.2.2.2:30006</pre><p><strong>Winner:</strong> Port 30006 — “You explicitly told me the extension to use with this number”</p><p><strong>Priority 2: Port from `-bind` if no port in `-externalip`</strong></p><pre>bash</pre><pre>-externalip=2.2.2.2 -bind=1.1.1.1:30005</pre><p><strong>Winner:</strong> Port 30005 — “You’re binding to this port, so that’s what you’re listening on”</p><p><strong>Priority 3: Port from `-whitebind` if no `-bind`</strong></p><pre>bash</pre><pre>-externalip=2.2.2.2 -whitebind=1.1.1.1:30020</pre><p><strong>Winner:</strong> Port 30020 — “Your whitelist bind has a port, use that”</p><p><strong>Priority 4: Port from `-port` if no specific bind port</strong></p><pre>bash</pre><pre>-externalip=2.2.2.2 -port=30001</pre><p><strong>Winner:</strong> Port 30001 — “You set a general port preference”</p><p><strong>Priority 5: Default P2P port (Lowest Priority)</strong></p><pre>bash</pre><pre>-externalip=2.2.2.2</pre><p><strong>Winner:</strong> 18444 (regtest) or 8333 (mainnet) — “No preference given, use the network default”</p><h3>The Test Cases: A Comprehensive Port Priority Matrix</h3><p>Let’s walk through the 12 test scenarios defined in the test file (feature_bind_port_externalip.py:23–38):</p><h4>Test Case 1: External IP with `-port` only</h4><pre>python</pre><pre>[‘-externalip=2.2.2.2’, ‘-port=30001’]</pre><pre>Expected port: 30001</pre><p><strong>The Logic:</strong> No port in `-externalip`, no `-bind`, so we fall through to `-port`.</p><p><strong>Real-world scenario:</strong> “I’m behind NAT(Network Address Translation). My router forwards external `2.2.2.2:30001` to my internal machine. I want to advertise that.”</p><h4>Test Case 2: External IP with `-port` and `-bind` (without port)</h4><pre>python</pre><pre>[‘-externalip=2.2.2.2’, ‘-port=30002’, ‘-bind=1.1.1.1’]</pre><pre>Expected port: 30002</pre><p><strong>The Logic:</strong> `-bind` doesn’t specify a port, so we use `-port`.</p><p><strong>Real-world scenario:</strong> “I want to bind to a specific interface (`1.1.1.1`) but still use my configured port number.”</p><h4>Test Case 3: External IP with `-bind` only (no port specified)</h4><pre>python</pre><pre>[‘-externalip=2.2.2.2’, ‘-bind=1.1.1.1’]</pre><pre>Expected port: default_p2p_port (18444 for regtest)</pre><p><strong>The Logic:</strong> No port anywhere, fall back to network default.</p><p><strong>Real-world scenario:</strong> “Simple setup — bind to this interface, use standard Bitcoin port.”</p><h4>Test Case 4: External IP with `-port` and `-bind` with port</h4><pre>python</pre><pre>[‘-externalip=2.2.2.2’, ‘-port=30003’, ‘-bind=1.1.1.1:30004’]</pre><pre>Expected port: 30004</pre><p><strong>The Logic:</strong> `-bind` has a port (30004), which takes priority over `-port` (30003).</p><p><strong>Key Insight:</strong> When `-bind` has a port, it beats `-port`. You’re saying “I’m listening on this specific interface:port combo.”</p><h4>Test Case 5: External IP with `-bind` with port only</h4><pre>python</pre><pre>[‘-externalip=2.2.2.2’, ‘-bind=1.1.1.1:30005’]</pre><pre>Expected port: 30005</pre><p><strong>The Logic:</strong> `-bind` port is the most specific binding information available.</p><h4>Test Case 6: External IP with port in the `-externalip` and `-port`</h4><pre>python</pre><pre>[‘-externalip=2.2.2.2:30006’, ‘-port=30007’]</pre><pre>Expected port: 30006</pre><p><strong>The Logic:</strong> Port in `-externalip` (30006) beats `-port` (30007).</p><p><strong>Critical Insight:</strong> This is like writing the extension number directly on the business card — it’s the most explicit statement of what port should be advertised with this specific IP.</p><h4>Test Case 7: External IP with port, `-port`, and `-bind` (no port)</h4><pre>python</pre><pre>[‘-externalip=2.2.2.2:30008’, ‘-port=30009’, ‘-bind=1.1.1.1’]</pre><pre>Expected port: 30008</pre><p><strong>The Logic:</strong> Port in `-externalip` (30008) beats both `-port` (30009) and the port-less `-bind`.</p><h4>Test Case 8: External IP with port and `-bind` without port</h4><pre>python</pre><pre>[‘-externalip=2.2.2.2:30010’, ‘-bind=1.1.1.1’]</pre><pre>Expected port: 30010</pre><p><strong>The Logic:</strong> Port in `-externalip` is explicit for this specific address.</p><h4>Test Case 9: External IP with port, `-port`, and `-bind` with port</h4><pre>python</pre><pre>[‘-externalip=2.2.2.2:30011’, ‘-port=30012’, ‘-bind=1.1.1.1:30013’]</pre><pre>Expected port: 30011</pre><p><strong>The Logic:</strong> Port in `-externalip` (30011) beats everything: `-port` (30012) and `-bind` port (30013).</p><p><strong>The Hierarchy Demonstrated:</strong> `-externalip` port &gt; `-bind` port &gt; `-port` flag &gt; default</p><h4>Test Case 10: External IP with port and `-bind` with different port</h4><pre>python</pre><pre>[‘-externalip=2.2.2.2:30014’, ‘-bind=1.1.1.1:30015’]</pre><pre>Expected port: 30014</pre><p><strong>The Logic:</strong> Even though you’re binding to port 30015, you’re explicitly advertising 30014 with the external IP.</p><p><strong>Real-world scenario:</strong> “I’m listening on port 30015 internally, but my NAT router forwards port 30014 to my 30015. Advertise 30014.”</p><h4>Test Case 11: Complex case with `-bind` and `-whitebind`</h4><pre>python</pre><pre>[‘-externalip=2.2.2.2’, ‘-port=30016’, ‘-bind=1.1.1.1:30017’, ‘-whitebind=1.1.1.1:30018’]</pre><pre>Expected port: 30017</pre><p><strong>The Logic:</strong> `-bind` port (30017) takes priority over `-whitebind` port (30018).</p><p><strong>Why?</strong> The test uses the first port it finds from the hierarchy. `GetListenPort()` checks `-bind` before `-whitebind`.</p><h4>Test Case 12: External IP with `-port` and `-whitebind` (no `-bind`)</h4><pre>python</pre><pre>[‘-externalip=2.2.2.2’, ‘-port=30019’, ‘-whitebind=1.1.1.1:30020’]</pre><pre>Expected port: 30020</pre><p><strong>The Logic:</strong> When there’s no `-bind`, `-whitebind` port (30020) beats `-port` (30019).</p><p><strong>The Pattern:</strong> If you specify a port on a binding option (bind or whitebind), that’s what you’re listening on, so that’s what should be advertised (unless `-externalip` has its own port).</p><h3>How It Works Under the Hood: The `GetListenPort()` Function</h3><p>The magic happens in `GetListenPort()` (net.cpp:137–161):</p><pre>cpp</pre><pre>uint16_t GetListenPort()</pre><pre>{</pre><pre>// Priority 1: If -bind= is provided with “:port” part, use that</pre><pre>for (const std::string&amp; bind_arg : gArgs.GetArgs(“-bind”)) {</pre><pre>constexpr uint16_t dummy_port = 0;</pre><pre>const std::optional&lt;CService&gt; bind_addr{Lookup(bind_arg, dummy_port, /*fAllowLookup=*/false)};</pre><pre>if (bind_addr.has_value() &amp;&amp; bind_addr-&gt;GetPort() != dummy_port)</pre><pre>return bind_addr-&gt;GetPort(); // Found a -bind with port!</pre><pre>}</pre><pre>// Priority 2: If -whitebind= without NoBan flag is provided, use that port</pre><pre>for (const std::string&amp; whitebind_arg : gArgs.GetArgs(“-whitebind”)) {</pre><pre>NetWhitebindPermissions whitebind;</pre><pre>bilingual_str error;</pre><pre>if (NetWhitebindPermissions::TryParse(whitebind_arg, whitebind, error)) {</pre><pre>if (!NetPermissions::HasFlag(whitebind.m_flags, NetPermissionFlags::NoBan)) {</pre><pre>return whitebind.m_service.GetPort(); // Found a -whitebind with port!</pre><pre>}</pre><pre>}</pre><pre>}</pre><pre>// Priority 3: Otherwise, use -port= or default</pre><pre>return static_cast&lt;uint16_t&gt;(gArgs.GetIntArg(“-port”, Params().GetDefaultPort()));</pre><pre>}</pre><p>This is like checking your office phone system configuration:</p><p>1. First, check if you specified a direct extension when setting up your desk phone (bind port)</p><p>2. Then, check if you specified an extension for your priority line (whitebind port)</p><p>3. Finally, use your general extension preference (port flag) or the building default</p><h4>The External IP Processing: Where the Port Gets Paired</h4><p>During initialization, `init.cpp:1709–1715` processes the `-externalip` arguments:</p><pre>cpp</pre><pre>for (const std::string&amp; strAddr : args.GetArgs(“-externalip”)) {</pre><pre>const std::optional&lt;CService&gt; addrLocal{Lookup(strAddr, GetListenPort(), fNameLookup)};</pre><pre>if (addrLocal.has_value() &amp;&amp; addrLocal-&gt;IsValid())</pre><pre>AddLocal(addrLocal.value(), LOCAL_MANUAL);</pre><pre>else</pre><pre>return InitError(ResolveErrMsg(“externalip”, strAddr));</pre><pre>}</pre><p><strong>The Key Line:</strong> `Lookup(strAddr, GetListenPort(), fNameLookup)`</p><p>This says: “Parse the external IP string. If it has a port, use that port. If it doesn’t have a port, call `GetListenPort()` to figure out what port to use.”</p><p><strong>The `Lookup()` Function Logic:</strong></p><pre>cpp</pre><pre>// Pseudocode for understanding</pre><pre>if (strAddr contains “:port”) {</pre><pre>use_the_port_from_strAddr; // e.g., “2.2.2.2:30006” → port 30006</pre><pre>} else {</pre><pre>use_GetListenPort_result; // e.g., “2.2.2.2” → port from GetListenPort()</pre><pre>}</pre><p>Then it adds this IP:port combination to `mapLocalHost` with `LOCAL_MANUAL` priority (the highest priority score) so it will definitely be advertised to peers.</p><h4>The Business Card Printing Process: How Peers Learn Your Address</h4><p>Once the external IP and port are added to `mapLocalHost`:</p><p><strong>Step 1: Peer Requests Your Address</strong></p><p>When you connect to a peer, they can ask “what’s your address?” via the Bitcoin P2P protocol.</p><p><strong>Step 2: Find Best Address to Advertise</strong></p><p>The `GetLocal()` function (net.cpp:164) scans `mapLocalHost` and picks the best address based on:</p><p>- Reachability from the peer’s network</p><p>- Priority score (`LOCAL_MANUAL` = 4 is highest)</p><p><strong>Step 3: Send Address to Peer</strong></p><p>Your node sends an `addr` message containing the IP:port pair.</p><p><strong>Step 4: Peer Gossips Your Address</strong></p><p>The peer shares your address with other peers, who share it further, populating the network’s address database.</p><p><strong>Step 5: Other Nodes Try to Connect</strong></p><p>Eventually, other nodes use your advertised IP:port to connect to you.</p><p><strong>The Critical Point:</strong> If you advertise the wrong port, other nodes will try to connect to you on that port and fail. It’s like printing the wrong extension on your business card — people call and can’t reach you.</p><h4>Why This Test Matters: The NAT Router Scenario</h4><p>The most common real-world use case for `-externalip` is <strong>NAT traversal</strong>:</p><p><strong>The Problem</strong></p><p>You run Bitcoin Core on your home computer:</p><p>- <strong>Internal IP:</strong> `192.168.1.100:8333` (your apartment number)</p><p>- <strong>Router’s External IP:</strong> `203.0.113.50` (the apartment building’s address)</p><p>- <strong>Port Forwarding:</strong> Router forwards `203.0.113.50:8333` → `192.168.1.100:8333`</p><p><strong>Without `-externalip`</strong></p><p>Bitcoin Core might advertise `192.168.1.100:8333` to peers. This is useless — no one on the internet can route to `192.168.x.x`.</p><p><strong>With `-externalip`</strong></p><pre>bash</pre><pre>bitcoind -externalip=203.0.113.50</pre><p>Bitcoin Core advertises `203.0.113.50:8333`, which other nodes can actually reach via the port forwarding.</p><h4>But What If You Use a Non-Standard Port?</h4><p><strong>Scenario:</strong> Your ISP blocks port 8333, so you forward port 18333 instead:</p><pre>bash</pre><pre># Router forwards: external 203.0.113.50:18333 → internal 192.168.1.100:8333</pre><p><strong>Wrong Configuration:</strong></p><pre>bash</pre><pre>bitcoind -externalip=203.0.113.50 -port=8333</pre><p>This advertises `203.0.113.50:8333`, but your router isn’t forwarding that port!</p><p><strong>Correct Configuration:</strong></p><pre>bash</pre><pre>bitcoind -externalip=203.0.113.50:18333 -bind=192.168.1.100:8333</pre><p>This:</p><p>- Binds to internal `192.168.1.100:8333` (where it actually listens)</p><p>- Advertises external `203.0.113.50:18333` (where others should connect)</p><p><strong>The test validates this works correctly</strong>: port 18333 from `-externalip` takes priority over the bind port 8333.</p><h4>Real-World Use Cases: When Ports Get Complicated</h4><p><strong>Use Case 1: The Cloud Server with Multiple IPs</strong></p><pre>bash</pre><pre>bitcoind -bind=10.0.1.5:8333 # Internal cloud network</pre><pre>-externalip=203.0.113.10:8333 # Public IP #1</pre><pre>-externalip=198.51.100.20:9333 # Public IP #2 (non-standard port)</pre><p>- Internal services connect via `10.0.1.5:8333`</p><p>- Public peers can use either `203.0.113.10:8333` or `198.51.100.20:9333`</p><p>- Each external IP can have its own port!</p><p><strong>Use Case 2: The Tor + Clearnet Hybrid</strong></p><pre>bash</pre><pre>bitcoind -externalip=203.0.113.5:8333 # Clearnet</pre><pre>-externalip=abc123…xyz.onion:8334 # Tor hidden service</pre><p>Different network types, different ports, all advertised correctly.</p><p><strong>Use Case 3: The Testing Lab</strong></p><pre>bash</pre><pre>bitcoind -port=18444 # Regtest default</pre><pre>-bind=127.0.0.1:18445 # Local bind with different port</pre><pre>-externalip=1.1.1.1:18446 # External with yet another port</pre><p>Each layer has its own port, and the test ensures the external advertisement gets the right one (18446).</p><h4>What Could Go Wrong Without This Test: The Unreachable Node</h4><p><strong>Scenario 1: The Ignored Externalip Port</strong></p><p><strong>Bug:</strong> Code ignores port in `-externalip`, always uses `-port` or default.</p><p><strong>Result:</strong></p><pre>bash</pre><pre>bitcoind -externalip=203.0.113.5:9000 -port=8333</pre><pre># Advertises: 203.0.113.5:8333 (WRONG!)</pre><pre># Actually listening on: 9000</pre><p>Other nodes try to connect to your port 8333, fail, mark you as unreachable.</p><p><strong>Scenario 2: The Bind Port Confusion</strong></p><p><strong>Bug:</strong> Code uses bind port even when externalip has its own port.</p><p><strong>Result:</strong></p><pre>bash</pre><pre>bitcoind -externalip=203.0.113.5:9000 -bind=192.168.1.5:8333</pre><pre># Advertises: 203.0.113.5:8333 (WRONG!)</pre><p>Your NAT router forwards port 9000, but you advertise 8333. Connections fail.</p><p><strong>Scenario 3: The Whitebind Priority Error</strong></p><p><strong>Bug:</strong> Code treats `-whitebind` same as `-bind` even when bind is specified.</p><p><strong>Result:</strong> Unpredictable behavior when both are specified.</p><h4>The Test Methodology: Exhaustive Combination Testing</h4><p>The test uses a brilliant approach:</p><p><strong>1. Define Test Matrix</strong> (feature_bind_port_externalip.py:23–38)</p><pre>python</pre><pre>EXPECTED = [</pre><pre>[[arguments], expected_port],</pre><pre>[[arguments], expected_port],</pre><pre># … 12 different combinations</pre><pre>]</pre><p><strong>2. Launch One Node Per Scenario</strong></p><pre>python</pre><pre>self.num_nodes = len(EXPECTED) # 12 nodes</pre><pre>self.extra_args = list(map(lambda e: e[0], EXPECTED)) # Each node gets different args</pre><p><strong>3. Verify Each Node Advertises Correct Port</strong></p><pre>python</pre><pre>for i in range(len(EXPECTED)):</pre><pre>expected_port = EXPECTED[i][1]</pre><pre>for local in self.nodes[i].getnetworkinfo()[‘localaddresses’]:</pre><pre>if local[‘address’] == ‘2.2.2.2’:</pre><pre>assert_equal(local[‘port’], expected_port) # Check the port!</pre><p>This is like testing 12 different business card printing configurations simultaneously to ensure each one prints the right phone number and extension combination.</p><h4>The Technical Requirement: Why Routable Addresses Again?</h4><p>Just like the previous test, this one requires `1.1.1.1` configured because:</p><pre>cpp</pre><pre>if (!addr.IsRoutable())</pre><pre>return false; // Won’t add to mapLocalHost</pre><p>Non-routable addresses (like `127.0.0.1` or `192.168.x.x`) won’t be advertised, so the test couldn’t verify anything.</p><p>It’s like testing business card printing with fake phone numbers — the printer might reject them before printing.</p><h4>The Special Case: `default_p2p_port` in Test Case 3</h4><p>Notice this test case (feature_bind_port_externalip.py:26):</p><pre>python</pre><pre>[[‘-externalip=2.2.2.2’, ‘-bind=1.1.1.1’], ‘default_p2p_port’]</pre><p>The expected port is a string, not a number! The test handles this (feature_bind_port_externalip.py:64–65):</p><pre>python</pre><pre>if expected_port == ‘default_p2p_port’:</pre><pre>expected_port = p2p_port(i) # Get the default port for this node’s network (regtest)</pre><p><strong>Why?</strong> Because the default port varies by network:</p><p>- Mainnet: 8333</p><p>- Testnet: 18333</p><p>- Regtest: 18444</p><p>- Signet: 38333</p><p>The test runs in regtest mode, so `p2p_port(i)` returns 18444.</p><h4>Conclusion: The Right Phone Number on the Right Business Card</h4><p>`feature_bind_port_externalip.py` ensures that Bitcoin Core’s port selection hierarchy works correctly when advertising external IP addresses. Like printing business cards with the correct phone number and extension combination, this test validates that:</p><p>1. <strong>Explicit beats implicit</strong> — Port in `-externalip` beats everything else</p><p>2. <strong>Specific beats general</strong> — Bind ports beat the generic `-port` flag</p><p>3. <strong>First specific wins</strong> — When multiple binds exist, the first one with a port wins</p><p>4. <strong>Defaults work</strong> — When nothing is specified, the network default is used</p><p>The test covers 12 different configuration combinations, ensuring that whether you’re running a simple home node or a complex multi-IP cloud setup, Bitcoin Core will advertise the port where peers can actually reach you.</p><p>Without this test, a subtle regression could cause your node to advertise an unreachable port, making your node invisible to the network — like handing out business cards with the wrong phone number.</p><p>The test embodies the principle: <strong>”When I say where others should connect to me, make sure you tell them the right port number.”</strong></p><h4>References</h4><p><strong>Test File: </strong><a href="https://github.com/bitcoin/bitcoin/blob/master/test/functional/feature_bind_port_externalip.py">https://github.com/bitcoin/bitcoin/blob/master/test/functional/feature_bind_port_externalip.py</a></p><p>- `test/functional/feature_bind_port_externalip.py:23–38` — Test matrix with 12 configuration combinations</p><p>- `test/functional/feature_bind_port_externalip.py:54–58` — Skip mechanism requiring manual setup</p><p>- `test/functional/feature_bind_port_externalip.py:62–72` — Port verification loop</p><p><strong>Source Code:</strong></p><p>- `src/init.cpp:1709–1715` — Processing `-externalip` arguments with port lookup</p><p>- `src/net.cpp:137–161` — `GetListenPort()` — Port priority hierarchy implementation</p><p>- `src/net.cpp:164–214` — `GetLocal()` — Finding best address to advertise to peer</p><p>- `src/net.cpp:304–307` — `AddLocal()` overload that uses `GetListenPort()`</p><p>- `src/net.h:147–154` — `LOCAL_*` priority score definitions</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50b2ace53ec2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deconstructing Bitcoin Core Tests]]></title>
            <link>https://medium.com/@wandiamugo/deconstructing-bitcoin-core-tests-8b2b9b2a9ef2?source=rss-19a686aeb31e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b2b9b2a9ef2</guid>
            <dc:creator><![CDATA[Wandia Mugo]]></dc:creator>
            <pubDate>Fri, 27 Feb 2026 09:33:41 GMT</pubDate>
            <atom:updated>2026-02-27T09:33:41.461Z</atom:updated>
            <content:encoded><![CDATA[<h4>Day 8: feature_bind_port_discover.py — Controlling Which Network Addresses Get Advertised</h4><p><strong>Test File:</strong> `test/functional/feature_bind_port_discover.py`</p><p><strong>Category:</strong> Feature Tests</p><p><strong>Complexity:</strong> Medium</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hdort4IfGMFEG70LaeSK3Q.jpeg" /></figure><h4>The Analogy: Choosing Which Phone Numbers to Print</h4><p>Imagine you’re a business owner with multiple phone numbers:</p><p>- A main office line</p><p>- A personal cell phone</p><p>- An internal intercom extension</p><p>- A fax line</p><p>When you print business cards to hand out at a networking event, you don’t want to list ALL your numbers especially not the internal intercom that outsiders can’t even call! You want to choose which numbers appear on your card.</p><p><strong>This test verifies that Bitcoin Core gives you the same control</strong>: when your computer has multiple network addresses, you can choose which ones to advertise to the Bitcoin network, not just broadcast all of them indiscriminately.</p><h3>Test Overview</h3><p>The `feature_bind_port_discover.py` test validates how Bitcoin Core advertises its local network addresses to peers based on the `-bind` and `-discover` configuration options. It ensures that when you explicitly bind to a specific interface, only that interface’s address is advertised to the network.</p><p><strong>The Setup:</strong> This test requires special network configuration — the test machine must have two routable IP addresses configured:</p><p>- `1.1.1.1` (configured as an interface alias)</p><p>- `2.2.2.2` (configured as another interface alias)</p><p>Think of this like temporarily installing two separate phone lines to test which ones get printed on your business card.</p><h4>What This Test Does</h4><p>The test creates two Bitcoin nodes with different configurations:</p><p><strong>Node 0: The Enthusiastic Networker (No `-bind` specified)</strong></p><pre>python</pre><pre>[‘-discover’, f’-port={BIND_PORT}’] # bind on any interface</pre><p>This node is like someone who puts ALL their phone numbers on their business card — office, cell, home, fax, everything. With `-discover` enabled but no specific `-bind`, the node advertises every network interface it finds.</p><p><strong>Test Verification (feature_bind_port_discover.py:59–67):</strong></p><pre>python</pre><pre>for local in self.nodes[0].getnetworkinfo()[‘localaddresses’]:</pre><pre>if local[‘address’] == ADDR1: # Found 1.1.1.1?</pre><pre>found_addr1 = True</pre><pre>if local[‘address’] == ADDR2: # Found 2.2.2.2?</pre><pre>found_addr2 = True</pre><pre>assert found_addr1</pre><pre>assert found_addr2</pre><p>Both addresses should appear in the `localaddresses` list — all phone numbers on the business card.</p><p><strong>Node 1: The Selective Networker (With `-bind` specified)</strong></p><pre>python</pre><pre>[‘-discover’, f’-bind={ADDR1}:{BIND_PORT}’] # bind only to 1.1.1.1</pre><p>This node is like someone who carefully chooses to only print their office number on their business card, even though they have other numbers. With `-bind=1.1.1.1:31001`, the node should ONLY advertise that specific address.</p><p><strong>Test Verification (feature_bind_port_discover.py:72–78):</strong></p><pre>python</pre><pre>for local in self.nodes[1].getnetworkinfo()[‘localaddresses’]:</pre><pre>if local[‘address’] == ADDR1: # Should find 1.1.1.1</pre><pre>found_addr1 = True</pre><pre>assert_not_equal(local[‘address’], ADDR2) # Should NOT find 2.2.2.2</pre><pre>assert found_addr1</pre><p>Only `1.1.1.1` should appear — just the chosen phone number on the business card.</p><h4>Why This Matters: The House with Multiple Doors Analogy</h4><p>Think of your Bitcoin node like a house with multiple doors:</p><p>- <strong>Front door</strong>: Your public-facing IP address</p><p>- <strong>Back door</strong>: A private network address</p><p>- <strong>Side door</strong>: Maybe a VPN connection</p><p>- <strong>Basement door</strong>: Perhaps a Tor connection</p><p>When Bitcoin Core runs with `-discover` but no `-bind`, it’s like putting signs on ALL the doors saying “Bitcoin node — come on in!” But here’s the problem:</p><p>1. <strong>The basement door (Tor) should stay secret</strong> — you don’t want that address announced to the whole network</p><p>2. <strong>The back door (private IP) is useless to strangers</strong> — addresses like `192.168.1.100` can’t be reached from the internet</p><p>3. <strong>You might only want visitors using the front door</strong> — your carefully chosen public interface</p><p>The `-bind` option is like saying: “Only put a ‘welcome’ sign on the front door, even though I have other doors.”</p><h3>The Address Discovery Dance: How It Works Under the Hood</h3><h4>The Automatic Discovery Process</h4><p>When Bitcoin Core starts with `-discover` enabled, it goes through this process:</p><p><strong>Step 1: Interface Enumeration</strong> — The `GetLocalAddresses()` function (common/netif.cpp:318) asks the operating system: “What network interfaces do we have?”</p><pre>cpp</pre><pre>std::vector&lt;CNetAddr&gt; GetLocalAddresses()</pre><pre>{</pre><pre>// On Windows: Uses GetAdaptersAddresses() API</pre><pre>// On Unix-like systems: Uses getifaddrs() system call</pre><pre>// Returns all network interfaces that are:</pre><pre>// — UP and running</pre><pre>// — NOT loopback (127.0.0.1)</pre><pre>// — NOT multicast or anycast</pre><pre>}</pre><p>This is like doing a house inspection and making a list of all the doors.</p><p><strong>Step 2: The Discovery Function</strong> — `Discover()` (net.cpp:3188) processes this list:</p><pre>cpp</pre><pre>void Discover()</pre><pre>{</pre><pre>if (!fDiscover)</pre><pre>return; // Discovery disabled, don’t advertise anything automatically</pre><pre>for (const CNetAddr &amp;addr: GetLocalAddresses()) {</pre><pre>if (AddLocal(addr, LOCAL_IF))</pre><pre>LogPrintf(“%s: %s\n”, __func__, addr.ToStringAddr());</pre><pre>}</pre><pre>}</pre><p>This is like taking your list of doors and deciding which ones get “welcome” signs.</p><h4>The Bind Override: Selective Advertisement</h4><p>When you use `-bind=&lt;specific-address&gt;`, the `CConnman::Bind()` function (net.cpp:3245) takes control:</p><pre>cpp</pre><pre>bool CConnman::Bind(const CService&amp; addr_, unsigned int flags, NetPermissionFlags permissions)</pre><pre>{</pre><pre>// First, actually bind to the socket (open the door)</pre><pre>if (!BindListenPort(addr, strError, permissions)) {</pre><pre>return false;</pre><pre>}</pre><pre>// Then, decide whether to advertise this address</pre><pre>if (addr.IsRoutable() &amp;&amp; fDiscover &amp;&amp; !(flags &amp; BF_DONT_ADVERTISE) &amp;&amp;</pre><pre>!NetPermissions::HasFlag(permissions, NetPermissionFlags::NoBan)) {</pre><pre>AddLocal(addr, LOCAL_BIND); // Add with BIND priority</pre><pre>}</pre><pre>return true;</pre><pre>}</pre><p><strong>The Key Insight:</strong> When you explicitly specify `-bind`, Bitcoin Core:</p><p>- <strong>Only</strong> calls `Bind()` for your specified address</p><p>- Does <strong>not</strong> run `Discover()` to enumerate all interfaces</p><p>- Therefore only that one address gets added to the advertisement list</p><p>It’s the difference between:</p><p>- “Put signs on all doors I can find” (automatic discovery)</p><p>- “Only put a sign on this specific door I’m pointing at” (explicit bind)</p><h4>The Address Book: `mapLocalHost`</h4><p>Bitcoin Core maintains a global map called `mapLocalHost` (net.cpp:118) — think of it as the “addresses to advertise” phonebook:</p><pre>cpp</pre><pre>std::map&lt;CNetAddr, LocalServiceInfo&gt; mapLocalHost;</pre><p>Every address in this map gets announced to peers. The `getnetworkinfo` RPC (rpc/net.cpp:627) that the test uses simply reads this map (rpc/net.cpp:718):</p><pre>cpp</pre><pre>UniValue localAddresses(UniValue::VARR);</pre><pre>{</pre><pre>LOCK(g_maplocalhost_mutex);</pre><pre>for (const std::pair&lt;const CNetAddr, LocalServiceInfo&gt; &amp;item : mapLocalHost)</pre><pre>{</pre><pre>UniValue rec(UniValue::VOBJ);</pre><pre>rec.pushKV(“address”, item.first.ToStringAddr());</pre><pre>rec.pushKV(“port”, item.second.nPort);</pre><pre>rec.pushKV(“score”, item.second.nScore);</pre><pre>localAddresses.push_back(std::move(rec));</pre><pre>}</pre><pre>}</pre><p>The test is essentially checking: “How many entries are in the phonebook?”</p><h4>The Address Reputation System: Scoring</h4><p>Bitcoin Core uses a priority scoring system for addresses — like having different categories of business cards:</p><p>- <strong>`LOCAL_NONE = 0`</strong>: Scratch paper (not actually advertised)</p><p>- <strong>`LOCAL_IF = 1`</strong>: Standard business card (auto-discovered from interfaces)</p><p>- <strong>`LOCAL_BIND = 2`</strong>: Premium business card (you specifically chose this)</p><p>- <strong>`LOCAL_MAPPED = 3`</strong>: Gold-embossed card (discovered via UPnP/NAT-PMP port mapping)</p><p>- <strong>`LOCAL_MANUAL = 4`</strong>: Platinum card (you manually specified with `-externalip`)</p><p>Higher scores mean “trust this address more” — if the same address appears multiple times with different scores, the highest score wins.</p><h4>Why This Test Requires Manual Setup: The Lab Experiment Problem</h4><p>The test includes this skip mechanism (feature_bind_port_discover.py:47):</p><pre>python</pre><pre>def skip_test_if_missing_module(self):</pre><pre>if not self.options.ihave1111and2222:</pre><pre>raise SkipTest(</pre><pre>f”To run this test make sure that {ADDR1} and {ADDR2} (routable addresses) are “</pre><pre>“assigned to the interfaces on this machine and rerun with — ihave1111and2222”)</pre><p><strong>Why can’t the test just configure the addresses itself?</strong></p><p>Think of it like a chemistry experiment that requires working with dangerous materials. The test <strong>could</strong> theoretically:</p><p>1. Run commands to add network interface aliases</p><p>2. Perform the test</p><p>3. Clean up the aliases</p><p>But this would require:</p><p>- <strong>Root/administrator privileges</strong> (like needing a special license)</p><p>- <strong>Risk of leaving the network broken</strong> if the test crashes (like a chemical spill)</p><p>- <strong>Platform-specific commands</strong> (different procedures for Linux, BSD, macOS, Windows)</p><p>- <strong>Potential conflicts</strong> with existing network configuration</p><p>Instead, the test documents the manual setup and skips itself unless you explicitly say “I’ve done the setup with ` — I have 1111and 2222`”.</p><p><strong>Setup Example (Linux):</strong></p><pre>bash</pre><pre># Add two temporary IP aliases to loopback interface</pre><pre>sudo ifconfig lo:0 1.1.1.1/32 up</pre><pre>sudo ifconfig lo:1 2.2.2.2/32 up</pre><pre># Run the test</pre><pre>./test/functional/feature_bind_port_discover.py — ihave1111and2222</pre><pre># Clean up afterward</pre><pre>sudo ifconfig lo:0 down</pre><pre>sudo ifconfig lo:1 down</pre><h3>Real-World Use Cases: When You Need This Control</h3><p><strong>Use Case 1: The Tor + Public IP Setup (The Secret Door and Public Door)</strong></p><p>Imagine a house with both a visible front entrance and a hidden underground tunnel (Tor):</p><pre>bash</pre><pre>bitcoind -bind=203.0.113.5:8333 # Public IP — advertise this</pre><pre>-bind=127.0.0.1:9050 # Tor SOCKS — DON’T advertise thi```</pre><p>You want the public IP advertised so clearnet peers can connect, but the Tor address should stay hidden (it’s only for outbound connections anyway).</p><p><strong>Use Case 2: The Multi-IP VPS (The Business with Multiple Storefronts)</strong></p><p>A VPS provider gives you 5 IP addresses, but you only want to advertise one:</p><pre>bash</pre><pre>bitcoind -bind=203.0.113.10:8333 # Only advertise this specific IP```</pre><p>Why not advertise all 5?</p><p>- Some might be temporary assignments</p><p>- Some might be on different networks with different routing costs</p><p>- You might rotate them for other services</p><p><strong>Use Case 3: The Corporate Firewall (The Building with Public and Private Wings)</strong></p><p>An organization runs Bitcoin Core on a server with both internal and external interfaces:</p><pre>bash</pre><pre>bitcoind -bind=192.168.1.100:8333 # Internal network only</pre><p>This prevents advertising the public interface, keeping the Bitcoin node as an internal-only service.</p><p><strong>Use Case 4: The Home Router Confusion (The Apartment Complex Problem)</strong></p><p>Home users behind NAT might have:</p><p>- External IP: `198.51.100.50` (the apartment building’s address)</p><p>- Internal IP: `192.168.1.5` (your apartment number)</p><p>Without `-bind`, Bitcoin Core might advertise `192.168.1.5` to the network, which is useless to external peers (they can’t route to your apartment directly). Using `-externalip` or UPnP helps, but `-bind` gives manual control.</p><h3>What Could Go Wrong Without This Test: The Cautionary Tales</h3><h4>Tale 1: The Privacy Leak</h4><p>Without this behavior, a user configuring `-bind=&lt;tor-address&gt;` might expect it to ONLY advertise that address, but if discovery also ran, their clearnet IP would leak to the network, defeating the privacy goal.</p><p><strong>Tale 2: The Network Pollution</strong></p><p>Every Bitcoin node gossips addresses to peers. If everyone’s node advertised unreachable addresses (internal IPs, link-local addresses, etc.), the network’s address database would be polluted with junk, making it harder to find connectable peers.</p><p><strong>Tale 3: The Configuration Confusion</strong></p><p>A user sees their node advertising addresses they didn’t expect. They file a bug report: “I used `-bind` but it’s still advertising all my IPs!” Without this test catching regressions, this could actually happen.</p><h4>The Test Philosophy: Trust But Verify</h4><p>This test embodies a core principle: <strong>”When a user says ‘only use this address,’ we mean ONLY this address — for both binding AND advertising.”</strong></p><p>The `-bind` option has an implicit contract:</p><p>- <strong>Explicit</strong>: Bind to this socket</p><p>- <strong>Implicit</strong>: Don’t advertise other addresses</p><p>Without this test, a code change might break the implicit part while keeping the explicit part working. The node would still <em>listen</em> on the right address but <em>advertise</em> the wrong addresses.</p><h4>The Technical Gotcha: Why Routable Addresses?</h4><p>You might wonder: “Why use `1.1.1.1` and `2.2.2.2` instead of `127.0.0.2` and `127.0.0.3`?”</p><p>Because of this filter in `AddLocal()` (net.cpp:276):</p><pre>cpp</pre><pre>if (!addr.IsRoutable())</pre><pre>return false;</pre><p>Bitcoin Core refuses to advertise non-routable addresses (loopback, private IPs, etc.) because they’re useless to remote peers. The test needs routable addresses to actually exercise the advertisement logic.</p><p>It’s like testing whether your business card printing process works — you need to use real phone numbers, not fake ones that would be filtered out before printing.</p><h4>Conclusion: The Business Card You Choose to Print</h4><p>`feature_bind_port_discover.py` validates that Bitcoin Core respects your choice of which network addresses to advertise. Like choosing which phone numbers appear on your business card, you should have precise control over your network presence.</p><p>The test may require manual setup and can’t run in standard CI, but it serves as both:</p><p>1. <strong>Validation</strong>: Ensures the feature works correctly</p><p>2. <strong>Documentation</strong>: Shows how `-bind` and `-discover` interact</p><p>In a world where network configurations are increasingly complex — with Tor, VPNs, cloud hosting, and multi-homed servers — this granular control isn’t a nice-to-have, it’s essential for privacy, functionality, and network health.</p><p>The test ensures that when you say “only this door gets a welcome sign,” Bitcoin Core doesn’t go putting signs on all the other doors behind your back.</p><h4>References</h4><p><strong>Test File: </strong><a href="https://github.com/bitcoin/bitcoin/blob/master/test/functional/feature_bind_port_discover.py">https://github.com/bitcoin/bitcoin/blob/master/test/functional/feature_bind_port_discover.py</a></p><p>- `test/functional/feature_bind_port_discover.py:47` — Skip mechanism requiring manual setup</p><p>- `test/functional/feature_bind_port_discover.py:59–67` — Node 0 verification (all addresses)</p><p>- `test/functional/feature_bind_port_discover.py:72–78` — Node 1 verification (selective address)</p><p><strong>Source Code:</strong></p><p>- `src/common/netif.cpp:318` — `GetLocalAddresses()` — Enumerates network interfaces</p><p>- `src/net.cpp:118` — `mapLocalHost` — Global map of advertised addresses</p><p>- `src/net.cpp:276` — `AddLocal()` — Routability filter</p><p>- `src/net.cpp:3188` — `Discover()` — Auto-discovery of local addresses</p><p>- `src/net.cpp:3245` — `CConnman::Bind()` — Explicit bind handling</p><p>- `src/rpc/net.cpp:627` — `getnetworkinfo` RPC implementation</p><p>- `src/rpc/net.cpp:718` — Reading `mapLocalHost` for RPC response</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b2b9b2a9ef2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deconstructing Bitcoin Core Tests]]></title>
            <link>https://medium.com/@wandiamugo/deconstructing-bitcoin-core-tests-2c30aa00a89f?source=rss-19a686aeb31e------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c30aa00a89f</guid>
            <dc:creator><![CDATA[Wandia Mugo]]></dc:creator>
            <pubDate>Mon, 23 Feb 2026 07:25:53 GMT</pubDate>
            <atom:updated>2026-02-23T07:25:53.115Z</atom:updated>
            <content:encoded><![CDATA[<h4>Day 7: Understanding feature_bind_extra.py — Network Binding and Tor Integration</h4><p><strong>Test File:</strong> `test/functional/feature_bind_extra.py`</p><p><strong>Category:</strong> Feature Tests</p><p><strong>Complexity:</strong> Medium</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jp2hQwfCo8IPmx6YhoZPsQ.jpeg" /></figure><h3>Introduction</h3><h4>The Port Authority Analogy</h4><p>Imagine you run a shipping company with multiple warehouses in the same city. Each warehouse needs its own loading dock so trucks can deliver goods. You can’t have all deliveries go to the same address, some customers need express delivery through warehouse A, others need standard delivery through warehouse B.</p><p>When you file your business license, you specify:</p><p>- <strong>Warehouse A:</strong> 123 Main Street (standard deliveries)</p><p>- <strong>Warehouse B:</strong> 456 Oak Avenue (express/premium deliveries)</p><p>The city verifies you actually have docks at both addresses. If you claim to have a dock at Oak Avenue but don’t, shipments fail and your business license is revoked.</p><p>Bitcoin Core’s `-bind` flag works the same way: it tells bitcoind which network interfaces and ports to “open for business” for different types of P2P connections. The `-bind=…=onion` variant specifically designates which address should handle Tor connections.</p><p>`feature_bind_extra.py` tests whether Bitcoin Core actually opens network sockets on the ports you specified — especially when you configure separate bindings for clearnet and Tor traffic.</p><h4>Why This Matters for Developers</h4><p>Network binding configuration is fundamental to any networked application. The pattern tested here appears across every server architecture:</p><p>- <strong>Web servers:</strong> Nginx/Apache bind to `:80` for HTTP, `:443` for HTTPS</p><p>- <strong>Databases:</strong> PostgreSQL binds to `:5432`, MySQL to `:3306`, with separate interfaces for local vs. remote access</p><p>- <strong>SSH servers:</strong> sshd binds to `:22`, but you might run a second instance on `:2222` for admin access</p><p>- <strong>Docker containers:</strong> Each container exposes specific ports, mapped to host interfaces</p><p>- <strong>Tor hidden services:</strong> Require binding a local port that the Tor daemon forwards to the hidden service</p><p>`feature_bind_extra.py` tests a specific requirement: <strong>verifying that the software actually binds to the ports it claims to, and that binding configuration correctly handles specialized network targets (like Tor)</strong>.</p><h4>The Technical Version</h4><p>Bitcoin Core accepts multiple `-bind` arguments to control which network interfaces and ports it listens on for P2P connections. The `-bind=&lt;addr&gt;:&lt;port&gt;=onion` syntax tells bitcoind: “This address/port is specifically for Tor connections.”</p><p>The test launches three nodes with different binding configurations:</p><p>1. <strong>Node 0:</strong> Only `-bind=127.0.0.1:port=onion` (Tor-only binding)</p><p>2. <strong>Node 1:</strong> Both `-bind=127.0.0.1:port` and `-bind=127.0.0.1:port2=onion` (clearnet + Tor)</p><p>3. <strong>Node 2:</strong> Only `-bind=127.0.0.1:port` (clearnet-only binding)</p><p>For each node, the test queries the operating system to see which ports the bitcoind process has actually bound to, then verifies they match the expected configuration.</p><p><strong>Platform constraint:</strong> This test only runs on Linux, because it uses Linux-specific `/proc` filesystem queries to inspect network bindings.</p><h4>What Is Network Binding?</h4><p>Before exploring the test, we need to understand what “binding to a port” means at the OS level.</p><h4>Sockets and Binding</h4><p>A network socket is an endpoint for sending/receiving data. Creating a server socket involves three steps:</p><p>1. <strong>Create a socket:</strong></p><pre>c</pre><pre>int sockfd = socket(AF_INET, SOCK_STREAM, 0);</pre><p>This allocates a socket descriptor but doesn’t associate it with any address yet.</p><p>2. <strong>Bind to an address/port:</strong></p><pre>c</pre><pre>struct sockaddr_in addr;</pre><pre>addr.sin_family = AF_INET;</pre><pre>addr.sin_addr.s_addr = inet_addr(“127.0.0.1”);</pre><pre>addr.sin_port = htons(8333);</pre><pre>bind(sockfd, (struct sockaddr*)&amp;addr, sizeof(addr));</pre><p>This tells the OS: “Any packets arriving at `127.0.0.1:8333` should be routed to this socket.”</p><p>3. <strong>Listen for connections:</strong></p><pre>c</pre><pre>listen(sockfd, 10); // queue up to 10 pending connections</pre><p>After `bind()` succeeds, the OS reserves that address/port combination for this process. No other process can bind to the same `127.0.0.1:8333` until this socket is closed.</p><h4>Why Multiple Bindings?</h4><p>Bitcoin Core may need to listen on multiple interfaces for different purposes:</p><p><strong>Clearnet vs. Tor:</strong></p><p>- <strong>Clearnet:</strong> Standard internet connections (IPv4/IPv6)</p><p>- <strong>Tor:</strong> Anonymous connections through the Tor network</p><p>If you want both types of connections, you need to bind to at least two ports: one for clearnet, one for Tor.</p><p><strong>Multiple network interfaces:</strong></p><p>A server might have:</p><p>- `127.0.0.1` (localhost only)</p><p>- `192.168.1.10` (local network)</p><p>- `203.0.113.42` (public internet)</p><p>You can choose to bind only to localhost (for testing), only to the public IP (for internet peers), or both.</p><h4>The `-bind` Flag</h4><p>Bitcoin Core’s `-bind` flag syntax:</p><blockquote>```</blockquote><blockquote>-bind=&lt;addr&gt;:&lt;port&gt;[=onion]</blockquote><blockquote>```</blockquote><p>Examples:</p><p>- `-bind=0.0.0.0:8333` — Bind to all interfaces on port 8333 (default P2P port)</p><p>- `-bind=127.0.0.1:18444` — Bind only to localhost on port 18444 (regtest)</p><p>- `-bind=192.168.1.10:8333=onion` — Bind to local network address, mark as Tor target</p><p>The `=onion` suffix tells Bitcoin Core: “This binding is for Tor connections. Route .onion peer connections through this address.”</p><h3>The Test: What Does It Do?</h3><h4>The Setup</h4><pre>python</pre><pre>def set_test_params(self):</pre><pre>self.setup_clean_chain = True</pre><pre>self.bind_to_localhost_only = False</pre><pre>self.num_nodes = 3</pre><p>Three nodes, clean chain. Crucially, `bind_to_localhost_only = False` prevents the test framework from automatically adding `-bind=127.0.0.1` to every node — we’re manually controlling all bind arguments.</p><pre>python</pre><pre>def skip_test_if_missing_module(self):</pre><pre>self.skip_if_platform_not_linux()</pre><p>This test only runs on Linux because the implementation uses Linux-specific system calls to query bound ports.</p><h4>Building the Node Configurations</h4><pre>python</pre><pre>def setup_network(self):</pre><pre>loopback_ipv4 = addr_to_hex(“127.0.0.1”)</pre><pre>port = p2p_port(self.num_nodes)</pre><pre>self.expected = []</pre><p>`addr_to_hex(“127.0.0.1”)` converts the IP address to a hexadecimal representation (for later comparison with `/proc` data).</p><p>`port = p2p_port(self.num_nodes)` picks an unused port number starting from the test framework’s port pool.</p><h4>Node 0: Tor-only binding</h4><pre>python</pre><pre>self.expected.append(</pre><pre>[</pre><pre>[f”-bind=127.0.0.1:{port}=onion”],</pre><pre>[(loopback_ipv4, port)]</pre><pre>],</pre><pre>)</pre><pre>port += 1</pre><p>Node 0 is configured with <strong>only</strong> a Tor binding. There’s no clearnet binding specified.</p><p><strong>Expected behavior:</strong> Bitcoin Core should bind to `127.0.0.1:port` (because it’s the only `-bind` specified), and that binding should be marked as the Tor target.</p><p>The expected bindings list contains one entry: `(loopback_ipv4, port)`.</p><h4>Node 1: Clearnet + Tor bindings</h4><pre>python</pre><pre>self.expected.append(</pre><pre>[</pre><pre>[f”-bind=127.0.0.1:{port}”, f”-bind=127.0.0.1:{port + 1}=onion”],</pre><pre>[(loopback_ipv4, port), (loopback_ipv4, port + 1)]</pre><pre>],</pre><pre>)</pre><pre>port += 2</pre><p>Node 1 has two `-bind` arguments:</p><p>1. `-bind=127.0.0.1:port` — standard clearnet P2P</p><p>2. `-bind=127.0.0.1:port+1=onion` — Tor connections</p><p><strong>Expected behavior:</strong> Two bindings, one for each specified port.</p><h4>Node 2: Clearnet-only binding</h4><pre>python</pre><pre>self.expected.append(</pre><pre>[</pre><pre>[f”-bind=127.0.0.1:{port}”],</pre><pre>[(loopback_ipv4, port)]</pre><pre>],</pre><pre>)</pre><pre>port += 1</pre><p>Node 2 has only a standard clearnet binding, no Tor target.</p><p><strong>Expected behavior:</strong> One binding on the specified port.</p><h4>Extracting Extra Args and Starting Nodes</h4><pre>python</pre><pre>self.extra_args = list(map(lambda e: e[0], self.expected))</pre><pre>self.setup_nodes()</pre><p>`self.extra_args` is set to the first element of each `self.expected` entry — the list of command-line arguments. The test framework passes these to `bitcoind` when starting each node.</p><p><strong>Example for node 1:</strong></p><pre>python</pre><pre>self.extra_args[1] = [“-bind=127.0.0.1:18446”, “-bind=127.0.0.1:18447=onion”]</pre><p>`self.setup_nodes()` starts all three nodes with their respective `-bind` configurations.</p><h3>The Actual Test: Verifying Bound Ports</h3><pre>python</pre><pre>def run_test(self):</pre><pre>for i, (args, expected_services) in enumerate(self.expected):</pre><pre>self.log.info(f”Checking listening ports of node {i} with {args}”)</pre><pre>pid = self.nodes[i].process.pid</pre><pre>binds = set(get_bind_addrs(pid))</pre><p>For each node, the test:</p><p>1. Gets the process ID (PID) of the running bitcoind instance</p><p>2. Calls `get_bind_addrs(pid)` to query which addresses/ports that process has bound</p><h4>The `get_bind_addrs()` Function</h4><p>This is the core of the test. It’s defined in `test_framework/netutil.py`:</p><pre>python</pre><pre>def get_bind_addrs(pid):</pre><pre>“””</pre><pre>Get the addresses a process is bound to.</pre><pre>Returns a list of tuples: (addr_hex, port)</pre><pre>“””</pre><pre># On Linux, parse /proc/&lt;pid&gt;/net/tcp and /proc/&lt;pid&gt;/net/tcp6</pre><pre>binds = []</pre><pre># Read IPv4 bindings from /proc/&lt;pid&gt;/net/tcp</pre><pre>with open(f’/proc/{pid}/net/tcp’, ‘r’) as f:</pre><pre>for line in f:</pre><pre># Each line: sl local_address rem_address st tx_queue:rx_queue …</pre><pre># Example: “0: 0100007F:1F90 00000000:0000 0A …”</pre><pre># -&gt; 0100007F = 127.0.0.1 in hex (reversed byte order)</pre><pre># -&gt; 1F90 = port 8080 in hex</pre><pre>parts = line.split()</pre><pre>if len(parts) &lt; 2:</pre><pre>continue</pre><pre>local_addr = parts[1]</pre><pre>if ‘:’ not in local_addr:</pre><pre>continue</pre><pre>addr_hex, port_hex = local_addr.split(‘:’)</pre><pre>port = int(port_hex, 16)</pre><pre># Only include LISTEN state (st = 0A)</pre><pre>if parts[3] == ‘0A’:</pre><pre>binds.append((addr_hex, port))</pre><pre># Similar parsing for /proc/&lt;pid&gt;/net/tcp6 …</pre><pre>return binds</pre><p>The `/proc/&lt;pid&gt;/net/tcp` file lists all TCP sockets for a process. Each line represents one socket. The second column `local_address` shows the bound address/port in hex format.</p><p><strong>Example `/proc/&lt;pid&gt;/net/tcp` entry:</strong></p><blockquote>```</blockquote><blockquote>sl local_address rem_address st tx_queue rx_queue tr tm-&gt;when retrnsmt uid timeout inode</blockquote><blockquote>0: 0100007F:47F0 00000000:0000 0A 00000000:00000000 00:00000000 00000000 999 0 12345</blockquote><blockquote>```</blockquote><p>Breaking down `0100007F:47F0`:</p><p>- `0100007F` → `127.0.0.1` (in little-endian hex: `7F 00 00 01`)</p><p>- `47F0` → port `18416` in decimal</p><p>The `st` field `0A` means the socket is in LISTEN state (waiting for connections).</p><p>`get_bind_addrs(pid)` parses these files and returns a list of `(addr_hex, port)` tuples for all listening sockets.</p><h4>Filtering Out Irrelevant Bindings</h4><pre>python</pre><pre># Remove IPv6 addresses</pre><pre>ipv6_addr_len_bytes = 32</pre><pre>binds = set(filter(lambda e: len(e[0]) != ipv6_addr_len_bytes, binds))</pre><pre># Remove RPC ports</pre><pre>binds = set(filter(lambda e: e[1] != rpc_port(i), binds))</pre><p><strong>Why remove IPv6?</strong></p><p>On some systems, IPv6 is configured but `::1` (loopback) isn’t available. Bitcoin Core may bind to `::` (all IPv6 interfaces) even when we didn’t explicitly request it. This creates unpredictable test results. To avoid flakiness, the test ignores all IPv6 bindings.</p><p><strong>Why remove RPC ports?</strong></p><p>Every Bitcoin Core node binds to an RPC port for JSON-RPC commands (e.g., `bitcoin-cli` connections). This isn’t part of the P2P network binding test, so it’s filtered out.</p><p>`rpc_port(i)` returns the RPC port for node `i` (assigned by the test framework).</p><h3>The Assertion</h3><pre>python</pre><pre>assert_equal(binds, set(expected_services))</pre><p>After filtering, the remaining bindings should exactly match the expected P2P bindings from `self.expected[i][1]`.</p><p><strong>Example for Node 1:</strong></p><p>- Expected: `{(0x7f000001, 18446), (0x7f000001, 18447)}`</p><p>- Actual (from `/proc`): `{(0x7f000001, 18446), (0x7f000001, 18447)}`</p><p>- Result: Pass ✓</p><p>If Bitcoin Core failed to bind to one of the requested ports, or bound to an extra unexpected port, this assertion would fail.</p><h4>The Three Test Cases in Detail</h4><p><strong><em>Node 0: `-bind=127.0.0.1:port=onion` (Tor-only)</em></strong></p><p><strong>Configuration:</strong></p><blockquote>```</blockquote><blockquote>-bind=127.0.0.1:18444=onion</blockquote><blockquote>```</blockquote><p><strong>Expected behavior:</strong></p><p>- Bitcoin Core should bind to exactly one port: `127.0.0.1:18444`</p><p>- That port should be designated as the Tor target</p><p>- No clearnet P2P port should be opened (since no non-`=onion` `-bind` was specified)</p><p><strong>What this tests:</strong></p><p>- When <strong>only</strong> a Tor binding is specified, Bitcoin Core doesn’t silently add a default clearnet binding</p><p>- The `=onion` suffix is correctly parsed and doesn’t prevent the binding from occurring</p><p><strong>Potential bug this catches:</strong></p><p>If Bitcoin Core had logic like:</p><pre>cpp</pre><pre>if (onion_bind_specified &amp;&amp; !regular_bind_specified) {</pre><pre>// ERROR: can’t have Tor without clearnet, ignore the bind</pre><pre>return;</pre><pre>}</pre><p>Node 0 would fail to bind to any ports, and the test would catch it.</p><p><strong><em>Node 1: Both clearnet and Tor</em></strong></p><p><strong>Configuration:</strong></p><blockquote>```</blockquote><blockquote>-bind=127.0.0.1:18446</blockquote><blockquote>-bind=127.0.0.1:18447=onion</blockquote><blockquote>```</blockquote><p><strong>Expected behavior:</strong></p><p>- Two bindings: `127.0.0.1:18446` (clearnet) and `127.0.0.1:18447` (Tor)</p><p>- Clearnet peers connect to `:18446`</p><p>- Tor peers connect to `:18447`</p><p><strong>What this tests:</strong></p><p>- Multiple `-bind` arguments are correctly processed</p><p>- The `=onion` suffix doesn’t interfere with the standard binding</p><p>- Both bindings can coexist on the same interface (just different ports)</p><p><strong>Potential bug this catches:</strong></p><p>If Bitcoin Core’s bind logic had a bug like:</p><pre>cpp</pre><pre>if (bind_addr_has_onion_flag) {</pre><pre>// Replace the previous binding instead of adding a new one</pre><pre>bindings[0] = onion_binding;</pre><pre>}</pre><p>Node 1 would only bind to one port instead of two, and the test would fail.</p><p><strong><em>Node 2: Clearnet-only</em></strong></p><p><strong>Configuration:</strong></p><blockquote>```</blockquote><blockquote>-bind=127.0.0.1:18448</blockquote><blockquote>```</blockquote><p><strong>Expected behavior:</strong></p><p>- One binding: `127.0.0.1:18448`</p><p>- No Tor target (since no `=onion` flag was used)</p><p><strong>What this tests:</strong></p><p>- Standard `-bind` behavior works as expected</p><p>- No unexpected extra bindings are created</p><p><strong>Potential bug this catches:</strong></p><p>If Bitcoin Core automatically added a Tor binding even when not requested:</p><pre>cpp</pre><pre>// Bug: always add a Tor binding on port+1</pre><pre>if (bind_specified) {</pre><pre>bind(addr, port);</pre><pre>bind(addr, port + 1); // Oops, this is wrong</pre><pre>}</pre><p>Node 2 would have two bindings instead of one, and the test would fail.</p><h3>The C++ Implementation</h3><h4>How Bitcoin Core Processes `-bind`</h4><p>In `src/init.cpp`, Bitcoin Core parses command-line arguments during startup:</p><pre>cpp</pre><pre>// src/init.cpp — AppInitParameterInteraction()</pre><pre>if (gArgs.IsArgSet(“-bind”)) {</pre><pre>for (const std::string&amp; strBind : gArgs.GetArgs(“-bind”)) {</pre><pre>// Parse the bind string: “addr:port” or “addr:port=onion”</pre><pre>std::string addr_str = strBind;</pre><pre>ConnectionDirection bind_type = ConnectionDirection::None;</pre><pre>// Check for “=onion” suffix</pre><pre>size_t onion_pos = strBind.find(“=onion”);</pre><pre>if (onion_pos != std::string::npos) {</pre><pre>bind_type = ConnectionDirection::In; // Tor incoming</pre><pre>addr_str = strBind.substr(0, onion_pos);</pre><pre>}</pre><pre>// Parse the address and port</pre><pre>CService bind_addr;</pre><pre>if (!Lookup(addr_str, bind_addr, /*default_port=*/0, /*allow_lookup=*/false)) {</pre><pre>return InitError(strprintf(“Cannot resolve -bind address: ‘%s’”, addr_str));</pre><pre>}</pre><pre>// Add to the bind list</pre><pre>if (bind_type == ConnectionDirection::In) {</pre><pre>// This is the Tor target</pre><pre>m_onion_binds.push_back(bind_addr);</pre><pre>} else {</pre><pre>// Standard clearnet binding</pre><pre>m_binds.push_back(bind_addr);</pre><pre>}</pre><pre>}</pre><pre>}</pre><p>The key distinction:</p><p>- <strong>Without `=onion`:</strong> Added to `m_binds` (standard P2P)</p><p>- <strong>With `=onion`:</strong> Added to `m_onion_binds` (Tor target)</p><h4>Actually Binding the Sockets</h4><p>Later in initialization, Bitcoin Core calls `Bind()` for each address:</p><pre>cpp</pre><pre>// src/net.cpp — CConnman::Start()</pre><pre>bool CConnman::Start(/* … */) {</pre><pre>// Bind to standard P2P addresses</pre><pre>for (const CService&amp; addr : m_binds) {</pre><pre>if (!BindListenPort(addr, /* is_onion= */ false)) {</pre><pre>return false;</pre><pre>}</pre><pre>}</pre><pre>// Bind to Tor target addresses</pre><pre>for (const CService&amp; addr : m_onion_binds) {</pre><pre>if (!BindListenPort(addr, /* is_onion= */ true)) {</pre><pre>return false;</pre><pre>}</pre><pre>}</pre><pre>return true;</pre><pre>}</pre><p>`BindListenPort()` calls the OS-level `bind()` syscall:</p><pre>cpp</pre><pre>bool CConnman::BindListenPort(const CService&amp; addr, bool is_onion) {</pre><pre>int sockfd = socket(addr.IsIPv4() ? AF_INET : AF_INET6, SOCK_STREAM, IPPROTO_TCP);</pre><pre>// Set socket options (SO_REUSEADDR, etc.)</pre><pre>// …</pre><pre>// Bind to the address</pre><pre>if (bind(sockfd, (struct sockaddr*)&amp;sockaddr, len) &lt; 0) {</pre><pre>LogPrintf(“ERROR: Unable to bind to %s on this computer (bind returned error %s)\n”,</pre><pre>addr.ToString(), NetworkErrorString(WSAGetLastError()));</pre><pre>return false;</pre><pre>}</pre><pre>// Listen for connections</pre><pre>if (listen(sockfd, SOMAXCONN) &lt; 0) {</pre><pre>LogPrintf(“ERROR: Listening for incoming connections failed (listen returned error %s)\n”,</pre><pre>NetworkErrorString(WSAGetLastError()));</pre><pre>return false;</pre><pre>}</pre><pre>// Store the socket for later use</pre><pre>if (is_onion) {</pre><pre>m_onion_listen_sockets.push_back(sockfd);</pre><pre>} else {</pre><pre>m_listen_sockets.push_back(sockfd);</pre><pre>}</pre><pre>return true;</pre><pre>}</pre><p>After this, the OS routes incoming TCP connections on those addresses/ports to Bitcoin Core.</p><h4>How Tor Connections Use the Onion Binding</h4><p>When Bitcoin Core wants to make an outbound Tor connection, it uses a SOCKS5 proxy (the local Tor daemon). But for <strong>incoming</strong> Tor connections (hidden services), the Tor daemon forwards connections to the local address/port specified by `-bind=…=onion`.</p><p>Example Tor hidden service configuration (`/var/lib/tor/hidden_service/hostname`):</p><blockquote>```</blockquote><blockquote>HiddenServiceDir /var/lib/tor/bitcoin-service/</blockquote><blockquote>HiddenServicePort 8333 127.0.0.1:18447</blockquote><blockquote>```</blockquote><p>This tells Tor: “Forward connections to `&lt;your-onion-address&gt;.onion:8333` to `127.0.0.1:18447`.”</p><p>Bitcoin Core’s `-bind=127.0.0.1:18447=onion` ensures that port is open and listening.</p><h4>Why This Test Only Runs on Linux</h4><p>The test uses Linux-specific `/proc` filesystem queries:</p><pre>python</pre><pre>def get_bind_addrs(pid):</pre><pre>with open(f’/proc/{pid}/net/tcp’, ‘r’) as f:</pre><pre># Parse the file…</pre><p><strong>macOS equivalent:</strong> `lsof -Pan -p &lt;pid&gt; -i`</p><p><strong>Windows equivalent:</strong> `netstat -ano | findstr &lt;pid&gt;`</p><p>Each platform has different output formats, making cross-platform support complex. Rather than maintaining three implementations, the test restricts itself to Linux.</p><p>In CI, this test runs on Linux builders but is skipped on macOS/Windows.</p><h4>Why This Test Matters</h4><p><strong>1. Network Configuration Correctness</strong></p><p>If Bitcoin Core claims to bind to a port but doesn’t actually do so, connections will fail silently. Users will report “my node isn’t receiving connections,” and debugging will be difficult because the configuration <strong>looks</strong> correct.</p><p>This test verifies: <strong>what you configure is what you get</strong>.</p><p><strong>2. Tor Integration</strong></p><p>Tor is a critical privacy feature for Bitcoin users. If the `=onion` binding is broken:</p><p>- Hidden services won’t work</p><p>- Users lose privacy (forced to use clearnet)</p><p>- Tor-only setups fail entirely</p><p>Testing the `=onion` flag separately from standard bindings ensures both paths work.</p><p><strong>3. Avoiding Port Conflicts</strong></p><p>If Bitcoin Core incorrectly binds to extra ports (e.g., both `:8333` and `:8334` when only `:8333` was requested), it could:</p><p>- Conflict with other software on the same machine</p><p>- Expose unexpected network services</p><p>- Create security vulnerabilities</p><p>The test ensures <strong>only</strong> the requested ports are bound.</p><p><strong>4. Regression Prevention</strong></p><p>Network binding logic is low-level code that rarely changes, but when it does, regressions can be subtle. A refactor that accidentally breaks multi-bind support might not be caught without this test.</p><h4>Comparison with Related Tests</h4><p>| Test | What it tests | Focus |</p><p>| — — — | — — — — — — — | — — — -|</p><p>| `feature_bind_extra.py` | <strong>Multiple bindings + Tor flag</strong> | Port binding correctness |</p><p>| `feature_bind_port_discover.py` | <strong>Port discovery</strong> | `-port` vs. `-bind` interaction |</p><p>| `feature_bind_port_externalip.py` | <strong>External IP announcement</strong> | What IP is advertised to peers |</p><p>| `feature_proxy.py` | <strong>SOCKS5 proxy for outbound Tor</strong> | Tor <strong>outbound</strong> connections |</p><p>| `p2p_i2p_*.py` | <strong>I2P network integration</strong> | Alternative anonymity network |</p><p>`feature_bind_extra.py` is narrowly focused: <strong>does Bitcoin Core bind to the ports you tell it to, especially when Tor is involved?</strong></p><h4>Key Takeaways</h4><p>1. <strong>`-bind` controls which network interfaces/ports Bitcoin Core listens on</strong> — not just a suggestion, but a binding commitment to the OS</p><p>2. <strong>The `=onion` suffix designates a binding as the Tor target</strong> — incoming Tor connections (via hidden service) route through that port</p><p>3. <strong>Multiple bindings can coexist</strong> — clearnet and Tor can use separate ports on the same interface</p><p>4. <strong>The test uses `/proc` to verify actual bindings</strong> — not just trusting Bitcoin Core’s logs, but querying the OS kernel directly</p><p>5. <strong>Three test cases cover the configuration space</strong> — Tor-only, clearnet+Tor, clearnet-only</p><p>6. <strong>Platform-specific testing is sometimes necessary</strong> — the `/proc` approach is Linux-only, and that’s acceptable for coverage</p><p>7. <strong>Network configuration correctness is critical</strong> — mismatched expectations (config says port X, but bound to port Y) cause hard-to-debug failures</p><h4>Conclusion</h4><p>`feature_bind_extra.py` tests a fundamental promise of any network service: <strong>when you configure it to listen on specific ports, it actually does so</strong>.</p><p>By querying the operating system directly (via `/proc` on Linux), the test bypasses Bitcoin Core’s logging and verifies the ground truth: which TCP sockets are actually open, which ports are bound, and whether the configuration matches expectations.</p><p>The three-node design cleanly covers the configuration space: Tor-only (node 0), dual clearnet+Tor (node 1), and clearnet-only (node 2). Each case tests a different code path in Bitcoin Core’s bind logic, ensuring that both standard and Tor-specific bindings work correctly, independently and together.</p><p>For developers, this test demonstrates an important testing principle: <strong>don’t just test the API, test the observable outcome</strong>. It’s not enough to call `bind()` and assume it worked — query the system afterward to confirm the socket actually exists. In distributed systems, networked applications, and anywhere configuration meets implementation, this verification pattern prevents silent failures and ensures your software does what users expect.</p><h4>References</h4><p>- <strong>Test file:</strong> `test/functional/feature_bind_extra.py`: <a href="https://github.com/bitcoin/bitcoin/blob/master/test/functional/feature_bind_extra.py">https://github.com/bitcoin/bitcoin/blob/master/test/functional/feature_bind_extra.py</a></p><p>- <strong>Network utilities:</strong> `test_framework/netutil.py` — `get_bind_addrs()`, `addr_to_hex()`</p><p>- <strong>Bitcoin Core init:</strong> `src/init.cpp` — `-bind` argument parsing</p><p>- <strong>Network manager:</strong> `src/net.cpp` — `CConnman::BindListenPort()`</p><p>- <strong>Tor documentation:</strong> <a href="https://2019.www.torproject.org/docs/tor-manual.html.en#HiddenServicePort">https://2019.www.torproject.org/docs/tor-manual.html.en#HiddenServicePort</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c30aa00a89f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deconstructing Bitcoin Core Tests]]></title>
            <link>https://medium.com/@wandiamugo/deconstructing-bitcoin-core-tests-8011d259610d?source=rss-19a686aeb31e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8011d259610d</guid>
            <dc:creator><![CDATA[Wandia Mugo]]></dc:creator>
            <pubDate>Wed, 18 Feb 2026 08:37:22 GMT</pubDate>
            <atom:updated>2026-02-18T08:37:22.285Z</atom:updated>
            <content:encoded><![CDATA[<h4>Day 6: Understanding feature_assumevalid.py — Skipping Signature Validation on Old Blocks</h4><p><strong>Test File:</strong> `test/functional/feature_assumevalid.py`</p><p><strong>Category:</strong> Feature Tests</p><p><strong>Complexity:</strong> Medium-High</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0RMR4elX2I2EmXDi0QQViQ.jpeg" /></figure><h3>Introduction</h3><h4>The Audit Analogy</h4><p>Imagine you’re a new accountant joining a company that’s been operating for 50 years. Your job is to verify the books are correct. You have two options:</p><p><strong>Option A (No Trust):</strong> Audit every single receipt, invoice, and ledger entry from the company’s founding in 1975 through today. This will take months.</p><p><strong>Option B (Selective Trust):</strong> The company has been publicly audited every quarter by reputable firms, with results on file. You trust those past audits and focus only on verifying entries from the last quarter — work that hasn’t been independently reviewed yet.</p><p>Option B doesn’t mean you’re being careless. It means you’re being efficient: the old work has already been verified by the market, by time, by scrutiny. What’s <em>*new*</em> hasn’t been, so that’s where your effort belongs.</p><p>Bitcoin’s `-assumevalid` parameter works exactly this way. For blocks deep in Bitcoin’s history — buried under years of work, reviewed by millions of nodes — Bitcoin Core can skip signature verification and trust that those blocks are valid. For recent blocks, full validation still occurs.</p><h4>Why This Matters for Developers</h4><p>The `-assumevalid` optimization touches on a universal principle in software engineering: <strong>trust proportional to evidence</strong>. The older a piece of data, the more it has been tested, scrutinized, and validated by independent parties. New data — sitting at the edge of what’s been verified — deserves more scrutiny.</p><p>You see this pattern across engineering:</p><p>- <strong>Caches:</strong> Frequently accessed data is assumed to be correct until a cache miss forces re-validation</p><p>- <strong>TLS Certificate Chains:</strong> Root CAs are trusted because they’ve been vetted; new leaves get more scrutiny</p><p>- <strong>Package signing:</strong> Packages from long-trusted publishers get less manual review than new ones</p><p>- <strong>Database checkpoints:</strong> Recovery skips re-validating blocks before the last checkpoint</p><p>- <strong>Git shallow clones:</strong> You trust that history before the shallow point was verified; only new commits need your attention</p><p>`feature_assumevalid.py` tests whether Bitcoin Core correctly implements this optimization — accepting old blocks while still catching invalid new ones.</p><h4>The Technical Version</h4><p>`-assumevalid` is a Bitcoin Core parameter that accepts a block hash. When set, Bitcoin Core skips script/signature validation for blocks in the chain up to and including that block — <em>but only if those blocks are buried by at least two weeks of proof-of-work</em>. If a block is flagged as assumevalid but is near the tip (not deeply buried), Bitcoin Core still validates it fully.</p><p>The test builds a 2202-block chain where block 102 contains a transaction with an <strong>intentionally invalid signature</strong>. Three nodes are tested under different configurations to verify that the assumevalid logic is applied correctly — accepting the bad block when it’s deeply buried and assumevalid-flagged, but rejecting it when it’s not.</p><h4>What Is Script Validation?</h4><p>Before exploring the test, we need to understand what’s being skipped.</p><h4>Bitcoin’s Script System</h4><p>Every Bitcoin transaction output is locked by a <strong>scriptPubKey</strong> — a small program that defines who can spend it. Every transaction input must provide a <strong>scriptSig</strong> (and for SegWit, a witness) that satisfies that script.</p><p>A simple Pay-to-Public-Key (P2PK) transaction works like this:</p><blockquote>```</blockquote><blockquote>scriptPubKey: &lt;pubkey&gt; OP_CHECKSIG</blockquote><blockquote>scriptSig: &lt;signature&gt;</blockquote><blockquote>Execution:</blockquote><blockquote>1. Push &lt;signature&gt; onto stack</blockquote><blockquote>2. Push &lt;pubkey&gt; onto stack</blockquote><blockquote>3. OP_CHECKSIG: pop pubkey and signature, verify signature, push 1 (success) or 0 (fail)</blockquote><blockquote>```</blockquote><p>Signature verification is <strong>cryptographic work</strong> — it requires:</p><p>1. Hashing the transaction data (SHA-256 twice)</p><p>2. Performing elliptic curve math (secp256k1 point operations)</p><p>3. Verifying the result matches the claimed signature</p><p>For Bitcoin’s entire transaction history, hundreds of millions of inputs — this verification adds up to significant CPU work during Initial Block Download (IBD).</p><h4>Why Skip Signature Verification for Old Blocks?</h4><p>For blocks buried deep in the chain, the economic argument for trusting them is overwhelming:</p><p>1. <strong>Proof-of-work commitment:</strong> Thousands of blocks worth of computational work sit on top of these blocks. Rewriting them would require outpacing the entire Bitcoin mining network.</p><p>2. <strong>Community verification:</strong> Every Bitcoin node that synced from genesis already validated these blocks. If they were invalid, they would have been rejected long ago.</p><p>3. <strong>Time:</strong> Bitcoin’s oldest blocks have been validated billions of times by independent nodes over 15 years.</p><p>4. <strong>The marginal risk is tiny:</strong> A malicious signature in block 100,000 is economically useless. Even if the signature was technically invalid, the coins are already “spent” in Bitcoin’s history — creating new valid transactions on top would require creating an entire alternative chain.</p><p>`-assumevalid` formalizes this reasoning: if you trust that a particular block hash is on the honest chain (based on its burial depth), you can skip re-verifying all the signatures in blocks up to that point.</p><h3>The Test: What Does It Do?</h3><h4>The Setup</h4><pre>python</pre><pre>def set_test_params(self):</pre><pre>self.setup_clean_chain = True</pre><pre>self.num_nodes = 3</pre><pre>self.rpc_timeout = 120</pre><p>A clean chain with 3 nodes, each playing a different role in verifying assumevalid behavior.</p><pre>python</pre><pre>def setup_network(self):</pre><pre>self.add_nodes(3)</pre><pre>self.start_node(0)</pre><p>Crucially, only node 0 is started initially. The test needs to mine the “bad block” with an invalid signature <em>before</em> starting nodes 1 and 2, so it can pass the hash of that block as their `-assumevalid` parameter.</p><h4>Building the Chain</h4><pre>python</pre><pre># Get a pubkey for the coinbase TXO</pre><pre>_, coinbase_pubkey = generate_keypair()</pre><pre># Create block 1 with a coinbase output to our key</pre><pre>height = 1</pre><pre>block = create_block(self.tip, create_coinbase(height, coinbase_pubkey), self.block_time)</pre><pre>block.solve()</pre><pre>self.block1 = block # save for later</pre><p>The test generates a keypair and creates block 1 with a coinbase transaction that pays to `coinbase_pubkey`. This is saved as `self.block1` because we’ll need to spend it later.</p><pre>python</pre><pre># Bury the block 100 deep so the coinbase output is spendable</pre><pre>for _ in range(100):</pre><pre>block = create_block(self.tip, create_coinbase(height), self.block_time)</pre><pre>block.solve()</pre><pre>self.blocks.append(block)</pre><p>Bitcoin’s coinbase maturity rule requires that coinbase outputs are buried by at least 100 blocks before they can be spent. The test mines 100 empty blocks to satisfy this.</p><h4>The Invalid Transaction (Block 102)</h4><pre>python</pre><pre># Create a transaction spending the coinbase output with an invalid (null) signature</pre><pre>tx = CTransaction()</pre><pre>tx.vin.append(CTxIn(COutPoint(self.block1.vtx[0].txid_int, 0), scriptSig=b””))</pre><pre>tx.vout.append(CTxOut(49 * 100000000, CScript([OP_TRUE])))</pre><pre>block102 = create_block(self.tip, create_coinbase(height), self.block_time, txlist=[tx])</pre><pre>block102.solve()</pre><p>This creates a transaction that:</p><p>- <strong>Spends</strong> the coinbase output from block 1 (the one locked to `coinbase_pubkey`)</p><p>- <strong>Provides an empty scriptSig</strong> (`b””`) — no signature at all</p><p>- <strong>Outputs</strong> 49 BTC locked with `OP_TRUE` (spendable by anyone)</p><p>This transaction is <strong>cryptographically invalid</strong>. Spending a P2PK output requires a valid ECDSA signature over the transaction data. An empty scriptSig will fail validation immediately.</p><p>The proof-of-work for block 102 is still valid (`.solve()` handles that). Only the transaction signature is wrong.</p><h4>Burying the Bad Block</h4><pre>python</pre><pre># Bury the assumed valid block 2100 deep</pre><pre>for _ in range(2100):</pre><pre>block = create_block(self.tip, create_coinbase(height), self.block_time)</pre><pre>block.solve()</pre><pre>self.blocks.append(block)</pre><p>2100 blocks are mined on top of block 102. This is the “burial” that makes assumevalid apply.</p><p><strong>Why 2100 blocks?</strong> Bitcoin’s assumevalid logic requires the assumed-valid block to be buried by at least two weeks of proof-of-work. On regtest, each block has a small target, so 2100 blocks provides sufficient burial. The final chain height is 2202 (1 genesis + 1 block1 + 100 maturity blocks + 1 block102 + 2100 burial blocks).</p><h4>Starting Nodes 1 and 2 with `-assumevalid`</h4><pre>python</pre><pre>self.start_node(1, extra_args=[“-assumevalid=” + block102.hash_hex])</pre><pre>self.start_node(2, extra_args=[“-assumevalid=” + block102.hash_hex])</pre><p>Now that we know `block102.hash_hex`, we can start nodes 1 and 2 configured to assume that block is valid.</p><h4>The Three Test Cases</h4><p><strong>Node 0 — No assumevalid (strict validation):</strong></p><pre>python</pre><pre>p2p0 = self.nodes[0].add_p2p_connection(BaseNode())</pre><pre>p2p0.send_header_for_blocks(self.blocks[0:2000])</pre><pre>p2p0.send_header_for_blocks(self.blocks[2000:])</pre><pre>self.send_blocks_until_disconnected(p2p0)</pre><pre>self.wait_until(lambda: self.nodes[0].getblockcount() &gt;= COINBASE_MATURITY + 1)</pre><pre>assert_equal(self.nodes[0].getblockcount(), COINBASE_MATURITY + 1)</pre><p>Node 0 has no `-assumevalid` and validates every signature. When it reaches block 102, it finds the invalid signature and <strong>rejects the block</strong>. The P2P connection is disconnected (Bitcoin Core disconnects peers that send invalid blocks). Node 0 ends up at height 101 — it accepted block 1 through 101, but stopped at 102.</p><p>`COINBASE_MATURITY + 1 = 101`: genesis block (height 0) + block 1 (height 1) + 100 maturity blocks = height 101.</p><p><strong>Node 1 — assumevalid with deep burial (2202 blocks):</strong></p><pre>python</pre><pre>p2p1 = self.nodes[1].add_p2p_connection(BaseNode())</pre><pre>p2p1.send_header_for_blocks(self.blocks[0:2000])</pre><pre>p2p1.send_header_for_blocks(self.blocks[2000:])</pre><pre>with self.nodes[1].assert_debug_log(expected_msgs=[</pre><pre>‘Disabling signature validations at block #1’,</pre><pre>‘Enabling signature validations at block #103’</pre><pre>]):</pre><pre>for i in range(2202):</pre><pre>p2p1.send_without_ping(msg_block(self.blocks[i]))</pre><pre>p2p1.sync_with_ping(timeout=960)</pre><pre>assert_equal(self.nodes[1].getblock(self.nodes[1].getbestblockhash())[‘height’], 2202)</pre><p>Node 1 has `-assumevalid=&lt;block102 hash&gt;` and receives all 2202 blocks. It syncs to height 2202, accepting block 102 despite the invalid signature.</p><p>The `assert_debug_log` check is critical — it verifies that Bitcoin Core actually <em>turned off</em> signature validation at some point (block #1, just after genesis) and turned it back on (block #103, just after block 102). This confirms the optimization is active, not just that the block happened to pass by chance.</p><p><strong>Node 2 — assumevalid but only syncing to block 200 (insufficient burial):</strong></p><pre>python</pre><pre>p2p2 = self.nodes[2].add_p2p_connection(BaseNode())</pre><pre>p2p2.send_header_for_blocks(self.blocks[0:200])</pre><pre>self.send_blocks_until_disconnected(p2p2)</pre><pre>self.wait_until(lambda: self.nodes[2].getblockcount() &gt;= COINBASE_MATURITY + 1)</pre><pre>assert_equal(self.nodes[2].getblockcount(), COINBASE_MATURITY + 1)</pre><p>Node 2 also has `-assumevalid=&lt;block102 hash&gt;`, but only receives headers and blocks up to block 200. At this point, block 102 is only buried by ~98 blocks — nowhere near two weeks of work.</p><p>Bitcoin Core’s logic: <strong>assumevalid only applies if the block is buried deeply enough.</strong> Since node 2 only has 200 blocks in its chain, block 102 is near the tip. Full signature validation runs, the invalid signature is caught, and block 102 is rejected. Node 2 also ends at height 101.</p><h3>The C++ Implementation</h3><h4>How `-assumevalid` is Stored</h4><p>In `src/kernel/chainparams.h`, the chainparams hold the assumed-valid block hash:</p><pre>cpp</pre><pre>class CChainParams {</pre><pre>public:</pre><pre>uint256 defaultAssumeValid; // Block hash to assume is valid</pre><pre>// …</pre><pre>};</pre><p>For mainnet, this is set to a hardcoded recent block hash in `src/kernel/chainparams.cpp`:</p><pre>cpp</pre><pre>// Mainnet (as of a recent release)</pre><pre>consensus.defaultAssumeValid = uint256S(</pre><pre>“00000000000000000002a7c4c1e48d76c5a37902165a270156b7a8d72728a054”</pre><pre>);</pre><p>Users can override this with `-assumevalid=&lt;hash&gt;` or disable it with `-assumevalid=0`.</p><h4>The Signature Check Gate (`src/validation.cpp`)</h4><p>Deep in block validation, Bitcoin Core calls script validation for each transaction input. The check is gated on whether the current block is within the assumevalid range:</p><pre>cpp</pre><pre>// src/validation.cpp — ConnectBlock()</pre><pre>bool fScriptChecks = true;</pre><pre>if (!hashAssumeValid.IsNull()) {</pre><pre>// Check if the block’s ancestor chain contains the assumevalid block</pre><pre>// AND if that block is buried by at least nMinimumChainWork</pre><pre>const CBlockIndex* pindexAssumeValid =</pre><pre>m_blockman.LookupBlockIndex(hashAssumeValid);</pre><pre>if (pindexAssumeValid &amp;&amp;</pre><pre>pindexAssumeValid-&gt;GetAncestor(pindex-&gt;nHeight) == pindex &amp;&amp;</pre><pre>pindexAssumeValid-&gt;nHeight &gt;= pindex-&gt;nHeight &amp;&amp;</pre><pre>pindexAssumeValid-&gt;nChainWork &gt;= nMinimumChainWork)</pre><pre>{</pre><pre>// This block is at or before the assumevalid point,</pre><pre>// and that point is buried by enough work. Skip scripts.</pre><pre>fScriptChecks = false;</pre><pre>}</pre><pre>}</pre><pre>// … later in ConnectBlock:</pre><pre>if (fScriptChecks) {</pre><pre>// Full script/signature validation</pre><pre>if (!CheckInputScripts(tx, state, view, flags, …)) {</pre><pre>return state.Invalid(</pre><pre>BlockValidationResult::BLOCK_CONSENSUS,</pre><pre>“bad-txns-inputs-missingorspent”</pre><pre>);</pre><pre>}</pre><pre>}</pre><pre>```</pre><p>This is the gate that the test probes. When `fScriptChecks = false`, the invalid signature in block 102 passes silently. When `fScriptChecks = true`, it fails and the block is rejected.</p><h4>The Burial Depth Check</h4><p>The condition `pindexAssumeValid-&gt;nChainWork &gt;= nMinimumChainWork` is the burial depth check:</p><pre>cpp</pre><pre>// src/kernel/chainparams.cpp</pre><pre>// Minimum amount of chain work required before assumevalid applies</pre><pre>consensus.nMinimumChainWork = uint256S(</pre><pre>“000000000000000000000000000000000000000052b2559353df4329b2e42b3a6”</pre><pre>);</pre><p>`nChainWork` is a cumulative measure of all proof-of-work in the chain. If the chain from genesis to the assumevalid block doesn’t meet the minimum work threshold, assumevalid is not applied. This prevents an attacker from creating a short chain with a fake “assumed valid” block and tricking a new node into accepting it without signature verification.</p><p>On regtest (used in tests), minimum chain work is very low, and the 2100-block burial satisfies it easily. With only 200 blocks, it doesn’t.</p><h4>The Debug Log Messages</h4><p>The test’s `assert_debug_log` check verifies two specific log messages:</p><blockquote>```</blockquote><blockquote>‘Disabling signature validations at block #1’</blockquote><blockquote>‘Enabling signature validations at block #103’</blockquote><blockquote>```</blockquote><p>These are emitted by Bitcoin Core when it transitions into and out of the assumevalid range:</p><pre>cpp</pre><pre>// src/validation.cpp</pre><pre>if (!fScriptChecks &amp;&amp; fScriptChecksWasPreviouslyEnabled) {</pre><pre>LogInfo(“Disabling signature validations at block #%d\n”, pindex-&gt;nHeight);</pre><pre>}</pre><pre>if (fScriptChecks &amp;&amp; !fScriptChecksWasPreviouslyEnabled) {</pre><pre>LogInfo(“Enabling signature validations at block #%d\n”, pindex-&gt;nHeight);</pre><pre>}</pre><p>- <strong>Disabling at block #1:</strong> Block 1 is the first block for which assumevalid applies (it’s before block 102 and the chain is buried deep enough)</p><p>- <strong>Enabling at block #103:</strong> Block 103 is the first block <em>after</em> block 102 (the assumevalid block), so full validation resumes</p><p>This confirms that the optimization actually engaged — the test isn’t just lucky that the bad block passed, it’s explicitly verifying the code path was taken.</p><h4>The Complete Execution Flow</h4><blockquote>```</blockquote><blockquote>1. Node 0 starts (no assumevalid)</blockquote><blockquote>↓</blockquote><blockquote>2. Mine block 1 with coinbase to coinbase_pubkey</blockquote><blockquote>↓</blockquote><blockquote>3. Mine 100 empty blocks (maturity)</blockquote><blockquote>↓</blockquote><blockquote>4. Construct transaction spending block1 coinbase with EMPTY scriptSig (invalid!)</blockquote><blockquote>↓</blockquote><blockquote>5. Mine block102 containing the invalid transaction</blockquote><blockquote>↓</blockquote><blockquote>6. Mine 2100 more blocks on top of block102</blockquote><blockquote>↓</blockquote><blockquote>7. Start node1 and node2 with -assumevalid=&lt;block102.hash&gt;</blockquote><blockquote>↓</blockquote><blockquote>8. [Node 0 test] Send all headers + all blocks</blockquote><blockquote>→ Node 0 validates signatures → rejects block102 → stops at height 101</blockquote><blockquote>↓</blockquote><blockquote>9. [Node 1 test] Send all headers + all 2202 blocks</blockquote><blockquote>→ Node 1 sees assumevalid with deep burial</blockquote><blockquote>→ Disables signatures for blocks 1–102</blockquote><blockquote>→ Accepts block102 despite invalid signature</blockquote><blockquote>→ Re-enables signatures at block 103</blockquote><blockquote>→ Syncs to height 2202</blockquote><blockquote>↓</blockquote><blockquote>10. [Node 2 test] Send first 200 headers + 200 blocks</blockquote><blockquote>→ Node 2 sees assumevalid but burial is only ~98 blocks (insufficient)</blockquote><blockquote>→ Full signature validation runs for block102</blockquote><blockquote>→ Rejects block102 → stops at height 101</blockquote><blockquote>```</blockquote><h4>Why This Test Matters</h4><p><strong>1. Significant IBD Performance Improvement</strong></p><p>Script validation is one of the most CPU-intensive parts of IBD. On a typical modern machine:</p><p>- <strong>Without assumevalid:</strong> Full IBD can take 1–7 days</p><p>- <strong>With assumevalid:</strong> IBD time is dramatically reduced because the cryptographic work for old blocks is skipped</p><p>The exact speedup depends on hardware and network, but signature verification represents a significant fraction of total IBD CPU time. Skipping it for millions of historical inputs is a meaningful optimization.</p><p><strong>2. No Security Compromise (When Used Correctly)</strong></p><p>The key invariant is: <strong>assumevalid blocks must be deeply buried</strong>.</p><p>A block buried under two weeks of proof-of-work is, for practical purposes, immutable. To rewrite it would require:</p><p>1. More computational power than the entire Bitcoin mining network</p><p>2. Outpacing that network continuously until the rewritten chain surpasses the honest chain</p><p>This is economically infeasible. The assumevalid optimization correctly identifies that the signature verification for such blocks is redundant.</p><p>The test with node 2 — where assumevalid is set but the block isn’t buried enough — is the critical safety check. It proves that Bitcoin Core doesn’t blindly trust the assumevalid flag; it also verifies the burial depth.</p><p><strong>3. The Subtle Attack Vector Being Tested</strong></p><p>Consider this attack scenario:</p><p>1. Attacker creates a fake chain of 100 blocks</p><p>2. Block 50 contains a transaction that “creates” coins out of thin air (or steals someone’s coins with a forged signature)</p><p>3. Attacker sets `-assumevalid=&lt;block50 hash&gt;` and tries to trick a node into accepting the chain</p><p>The node 2 test case verifies this attack fails: even if `-assumevalid` is set to block 50, if the chain is only 100 blocks long, signature validation still runs on block 50 and rejects the forgery.</p><p><strong>4. Correct vs. Incorrect Handling of Edge Cases</strong></p><p>The test carefully distinguishes between two scenarios that look similar but behave differently:</p><p>| Scenario | assumevalid set? | Block buried? | Result |</p><p>| — — — — — | — — — — — — — — -| — — — — — — — -| — — — — |</p><p>| Node 0 | No | N/A | Validate all signatures; reject block 102 |</p><p>| Node 1 | Yes | Yes (2100 blocks) | Skip signatures for blocks 1–102; accept |</p><p>| Node 2 | Yes | No (only ~98 blocks) | Still validate signatures; reject block 102 |</p><p>The test verifies all three cases, ensuring each code path is correct.</p><h4>Comparison with AssumeUTXO</h4><p>Having covered both `feature_assumevalid.py` and `feature_assumeutxo.py`, it’s worth contrasting these two related optimizations:</p><p>| Aspect | `-assumevalid` | AssumeUTXO |</p><p>| — — — — | — — — — — — — -| — — — — — — |</p><p>| What is skipped | Script/signature validation | Building the UTXO set from scratch |</p><p>| When is it verified | Never (trusted based on burial depth) | Background validation verifies it completely |</p><p>| Speed improvement | Moderate (CPU savings on old sigs) | Large (entire IBD from snapshot) |</p><p>| Trust requirement | Implicit (burial depth) | Explicit (hardcoded snapshot hashes) |</p><p>| Introduced in | Bitcoin Core 0.14 (2017) | Bitcoin Core 26.0 (2023) |</p><p>| What happens if wrong | You accepted a technically-invalid chain (extremely unlikely with deep burial) | Node detects mismatch and aborts |</p><p>Both optimizations target the same problem (slow IBD) but at different layers. `-assumevalid` skips cryptographic work but still validates the chain structure, proof-of-work, and UTXO set consistency. AssumeUTXO skips building the UTXO set entirely but validates it asynchronously.</p><p>Used together, they dramatically reduce IBD time while maintaining Bitcoin’s security model.</p><h4>Key Takeaways</h4><p>1. <strong>`-assumevalid` skips signature validation for old, deeply-buried blocks</strong> , not because those signatures don’t matter, but because the burial depth makes forgery economically impossible</p><p>2. <strong>Burial depth is a hard requirement</strong> — assumevalid without sufficient burial (as in the node 2 test) triggers full validation anyway, preventing abuse</p><p>3. <strong>The debug log messages are the test’s smoking gun*</strong>— “Disabling/enabling signature validations” proves the optimization actually engaged, not just that the block passed</p><p>4. <strong>Three nodes, three cases</strong> — no assumevalid (strict), assumevalid with deep burial (skipped), assumevalid with shallow burial (still strict)</p><p>5. <strong>This is a “trust proportional to evidence” pattern</strong> — old, widely-verified, heavily-buried data deserves more trust than new, unverified data at the chain tip</p><p>6. <strong>The optimization is significant</strong> — script validation is CPU-intensive; skipping it for hundreds of millions of historical inputs meaningfully speeds up IBD</p><h4>Conclusion</h4><p>`feature_assumevalid.py` tests one of Bitcoin Core’s most elegant performance optimizations. By formalizing the observation that deeply-buried blocks are effectively immutable, it allows nodes to skip millions of redundant cryptographic operations during IBD without compromising security.</p><p>The test’s three-node design is clean and complete: one node proves the invalid signature would normally fail (correctness baseline), one proves assumevalid works when properly applied (the optimization), and one proves assumevalid doesn’t apply blindly without sufficient burial (the safety check).</p><p>For developers, this test teaches an important lesson: <strong>not all validation is equally necessary at all times</strong>. Old, well-established data that has been independently verified thousands of times doesn’t need to be re-verified on every read. New data, sitting at the edge of what’s been confirmed, deserves full scrutiny. Designing systems that apply trust proportionally — more scrutiny for new/untested data, less for old/established data — is a pattern that appears across every layer of engineering.</p><p>Bitcoin’s `-assumevalid` implements this principle at the protocol level, and `feature_assumevalid.py` ensures it’s implemented correctly.</p><h4>References</h4><p>- <strong>Bitcoin Core PR #9484</strong> — Original `-assumevalid` implementation: <a href="https://github.com/bitcoin/bitcoin/pull/9484">https://github.com/bitcoin/bitcoin/pull/9484</a></p><p>- <strong>Test file:</strong> `test/functional/feature_assumevalid.py`</p><p>- <strong>Core validation logic:</strong> `src/validation.cpp` — `ConnectBlock()` (the `fScriptChecks` gate)</p><p>- <strong>Chain parameters:</strong> `src/kernel/chainparams.cpp` — `defaultAssumeValid`, `nMinimumChainWork`</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8011d259610d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deconstructing Bitcoin Core Tests]]></title>
            <link>https://medium.com/@wandiamugo/deconstructing-bitcoin-core-tests-f752987415e1?source=rss-19a686aeb31e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f752987415e1</guid>
            <dc:creator><![CDATA[Wandia Mugo]]></dc:creator>
            <pubDate>Tue, 17 Feb 2026 08:23:38 GMT</pubDate>
            <atom:updated>2026-02-17T08:37:35.473Z</atom:updated>
            <content:encoded><![CDATA[<h4>Day 5: Understanding feature_assumeutxo.py — Fast-Forward Sync with Trust Anchors</h4><p><strong>Test File:</strong> `test/functional/feature_assumeutxo.py`</p><p><strong>Category:</strong> Feature Tests</p><p><strong>Complexity:</strong> High</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U0JSHq0VWrDJ-1lqW4SvOQ.jpeg" /></figure><h3>Introduction</h3><h4>The Time Machine Analogy</h4><p>Imagine you want to watch a TV series with 10,000 episodes. To understand the current storyline, do you really need to watch every single episode from episode 1? What if someone gave you:</p><p>1. A comprehensive summary of everything up to episode 9,000</p><p>2. The actual recordings of episodes 9,001 to 10,000</p><p>3. A promise: “While you watch the recent episodes, we’ll verify the summary by watching all 10,000 episodes in the background”</p><p>You could start watching from episode 9,000 immediately and enjoy the current storyline, while the background verification ensures the summary was accurate. If the verification fails, you’d know something was wrong. But if it succeeds, you’ve saved hundreds of hours.</p><p><strong>AssumeUTXO</strong> brings this concept to Bitcoin. Instead of validating every transaction from Bitcoin’s genesis block in 2009 (which can take days or weeks), a new node can:</p><p>1. Load a snapshot of the UTXO set (the “summary” of who owns what coins) at a recent block</p><p>2. Start syncing from that point to the network tip</p><p>3. Validate the entire history in the background to verify the snapshot was correct</p><p>This means you can start using your Bitcoin node in hours instead of days, while still maintaining Bitcoin’s security model through full background validation.</p><h4>Why This Matters for Developers</h4><p>This test demonstrates several universal software engineering principles:</p><p>- <strong>Optimistic execution with verification</strong>: Start working with assumed-correct data, but verify it in parallel</p><p>- <strong>State snapshots for bootstrapping</strong>: Games save your progress, databases checkpoint their state, version control uses shallow clones</p><p>- <strong>Dual-phase validation</strong>: Trust initially, verify completely, then commit or rollback</p><p>- <strong>Graceful degradation</strong>: If the snapshot is invalid, fall back to traditional full validation</p><p>The pattern appears everywhere:</p><p>- <strong>Databases:</strong> MVCC (Multi-Version Concurrency Control) allows reads from a consistent snapshot while writes happen</p><p>- <strong>Virtual machines:</strong> VM snapshots let you restore to a known-good state instantly</p><p>- <strong>Package managers:</strong> Lock files provide reproducible builds from a known state</p><p>- <strong>Git:</strong> Shallow clones let you start working immediately, then fetch full history if needed</p><h4>The Technical Version</h4><p>Bitcoin Core traditionally requires Initial Block Download (IBD) — validating every block from genesis to the current chain tip — before a node can fully participate in the network. This process can take days on consumer hardware. <strong>AssumeUTXO</strong> is an optimization that allows nodes to bootstrap using a hardcoded snapshot of the UTXO (Unspent Transaction Output) set at a known block height. The node loads this snapshot, immediately syncs to the network tip using it, and simultaneously validates the entire blockchain history in the background. Once background validation reaches the snapshot block and confirms the UTXO set matches, the snapshot becomes fully validated. The `feature_assumeutxo.py` test verifies this entire lifecycle: snapshot loading, dual chainstate management, network synchronization, background validation, and cleanup.</p><h4>What Is the UTXO Set?</h4><p>Before diving into the test, we need to understand Bitcoin’s core data structure.</p><h4>The UTXO Set: Bitcoin’s State</h4><p>Bitcoin doesn’t have “account balances” like a traditional database. Instead, it maintains the <strong>UTXO set</strong> — a collection of all unspent transaction outputs. Each UTXO represents:</p><p>- An amount of bitcoin</p><p>- A locking script (who can spend it)</p><p>- The transaction and output index where it was created</p><p>When you “send bitcoin,” you’re actually:</p><p>1. Consuming one or more UTXOs (inputs)</p><p>2. Creating new UTXOs (outputs)</p><p>3. The difference goes to miners as fees</p><p><strong>Example:</strong></p><blockquote>```</blockquote><blockquote>Before transaction:</blockquote><blockquote>- Alice has UTXO: 5 BTC (output 0 of tx abc123)</blockquote><blockquote>Alice sends 3 BTC to Bob:</blockquote><blockquote>- Input: Spend UTXO abc123:0 (5 BTC)</blockquote><blockquote>- Output 0: Bob gets 3 BTC (new UTXO)</blockquote><blockquote>- Output 1: Alice gets 2 BTC change (new UTXO)</blockquote><blockquote>After transaction:</blockquote><blockquote>- UTXO abc123:0 is removed (spent)</blockquote><blockquote>- Two new UTXOs are added</blockquote><blockquote>```</blockquote><h4>The Problem: UTXO Set Takes Time to Build</h4><p>To know the current UTXO set, traditional nodes must:</p><p>1. Download every block from genesis (2009)</p><p>2. Process every transaction</p><p>3. Track which outputs are created and spent</p><p>This is <strong>Initial Block Download (IBD)</strong>, and it can take:</p><p>- <strong>Days</strong> on consumer hardware</p><p>- <strong>Weeks</strong> on low-end devices</p><p>- Significant bandwidth and CPU resources</p><h4>The Solution: UTXO Snapshots</h4><p>What if we could provide the UTXO set at block 800,000 as a file? New nodes could:</p><p>1. Load the snapshot (minutes)</p><p>2. Start syncing from block 800,000 to current tip (hours)</p><p>3. Validate blocks 0–800,000 in the background (days, but in parallel)</p><p>This is <strong>AssumeUTXO</strong>. The word “assume” is critical — we’re <em>assuming</em> the snapshot is correct initially, but we <em>verify</em> it completely in the background.</p><h3>The Test: What Does It Do?</h3><p>The `feature_assumeutxo.py` test is comprehensive, covering the entire AssumeUTXO lifecycle. Let’s break it down.</p><h4>Test Setup</h4><pre>python</pre><pre>def set_test_params(self):</pre><pre>self.num_nodes = 4</pre><pre>self.extra_args = [</pre><pre>[], # node0: Creates snapshot</pre><pre>[], # node1: Loads snapshot, syncs to tip</pre><pre>[], # node2: Loads snapshot, validates background</pre><pre>[“-checkpoints=0”], # node3: No checkpoints (edge case)</pre><pre>]</pre><p>The test uses 4 nodes with different roles:</p><p>- <strong>Node 0</strong>: The “reference” node that generates blocks and creates the snapshot</p><p>- <strong>Node 1</strong>: Tests snapshot loading and sync to network tip</p><p>- <strong>Node 2</strong>: Tests background validation completion</p><p>- <strong>Node 3</strong>: Tests edge cases (no checkpoints)</p><h4>Phase 1: Create the Initial Chain</h4><pre>python</pre><pre># Generate blocks to height 299</pre><pre>self.generate(n0, SNAPSHOT_BASE_HEIGHT — 1, sync_fun=self.no_op)</pre><p>Node 0 creates 299 blocks. This establishes a blockchain that will serve as the “history” for our test.</p><p><strong>Why 299 blocks?</strong> The test uses `SNAPSHOT_BASE_HEIGHT = 299` as the snapshot point. This is chosen because:</p><p>- It’s after the coinbase maturity period (100 blocks)</p><p>- It’s early enough to test background validation quickly</p><p>- It matches hardcoded test snapshot parameters</p><h4>Phase 2: Generate the UTXO Snapshot</h4><pre>python</pre><pre># Create snapshot at height 299</pre><pre>n0.dumptxoutset(dump_output_path)</pre><p>Node 0 creates a snapshot file containing:</p><p>- Every UTXO that exists at block 299</p><p>- Metadata: block hash, chainstate height, number of transactions</p><p>- A serialized, compressed representation of the UTXO set</p><p>The snapshot file looks like this internally:</p><blockquote>```</blockquote><blockquote>Header:</blockquote><blockquote>- Magic bytes</blockquote><blockquote>- Version</blockquote><blockquote>- Network (mainnet/testnet/regtest)</blockquote><blockquote>Metadata:</blockquote><blockquote>- Base block hash: 0x1a2b3c…</blockquote><blockquote>- nChainTx: 300 (total transactions)</blockquote><blockquote>- Coins count: 150 (number of UTXOs)</blockquote><blockquote>UTXO Data:</blockquote><blockquote>- Coin 1: txid=abc…, vout=0, amount=50 BTC, scriptPubKey=…</blockquote><blockquote>- Coin 2: txid=def…, vout=1, amount=25 BTC, scriptPubKey=…</blockquote><blockquote>- … (compressed and serialized)</blockquote><blockquote>Checksum:</blockquote><blockquote>- SHA256 hash of all data</blockquote><blockquote>```</blockquote><h4>Phase 3: Load Snapshot on Node 1</h4><pre>python</pre><pre># Node 1 starts fresh (no blocks)</pre><pre>n1.loadtxoutset(dump_output_path)</pre><p>This is where the magic happens. Node 1, which has no blockchain data, loads the snapshot:</p><p><strong>What happens internally:</strong></p><p>1. <strong>Validation</strong>: Verify snapshot file integrity (checksum, format)</p><p>2. <strong>Chainstate Creation</strong>: Create a new `chainstate_snapshot` directory</p><p>3. <strong>UTXO Loading</strong>: Deserialize and populate the UTXO database</p><p>4. <strong>Activation</strong>: Mark this chainstate as “active” for block validation</p><p>5. <strong>Background Chainstate</strong>: Keep the original (empty) chainstate for background validation</p><p>Now Node 1 has <strong>two chainstates</strong>:</p><p>- <strong>Snapshot chainstate</strong> (active): Starts at block 299, used for syncing to tip</p><p>- <strong>Background chainstate</strong> (inactive): Starts at block 0, validates history</p><h4>Phase 4: Sync to Network Tip</h4><pre>python</pre><pre># Node 0 generates more blocks (to height 399)</pre><pre>self.generate(n0, 100, sync_fun=self.no_op)</pre><pre># Connect nodes, Node 1 syncs using snapshot</pre><pre>self.connect_nodes(0, 1)</pre><pre>self.sync_blocks()</pre><p>Node 0 creates 100 more blocks (height 299 → 399). When nodes connect:</p><p><strong>Node 1’s behavior:</strong></p><p>1. Downloads blocks 300–399 from Node 0</p><p>2. Validates these blocks using the <strong>snapshot chainstate</strong></p><p>3. Simultaneously, validates blocks 0–299 in the <strong>background chainstate</strong></p><p>4. Both processes happen in parallel</p><p><strong>Key insight:</strong> Node 1 can serve the latest blocks to peers immediately because it has the snapshot chainstate synced to the tip. Meanwhile, background validation ensures the snapshot was correct.</p><h4>Phase 5: Test Invalid Snapshots</h4><p>The test includes several negative test cases to ensure error handling:</p><pre>python</pre><pre># Test 1: Snapshot with wrong block hash</pre><pre>bad_snapshot = tmp_path / “bad_snapshot.dat”</pre><pre># … modify snapshot base hash …</pre><pre>assert_raises_rpc_error(-32603, “Unable to load UTXO snapshot”, n1.loadtxoutset, bad_snapshot)</pre><pre># Test 2: Snapshot with wrong coin count</pre><pre># … modify coins_count in snapshot …</pre><pre>assert_raises_rpc_error(-32603, “Unable to load UTXO snapshot”, n1.loadtxoutset, bad_snapshot)</pre><pre># Test 3: Empty snapshot file</pre><pre>bad_snapshot.write_bytes(b””)</pre><pre>assert_raises_rpc_error(-32603, “Unable to load UTXO snapshot”, n1.loadtxoutset, bad_snapshot)</pre><p>These tests verify that Bitcoin Core detects corrupted or invalid snapshots and refuses to load them.</p><h4>Phase 6: Background Validation Completion</h4><pre>python</pre><pre># Node 2 loads snapshot and completes background validation</pre><pre>n2.loadtxoutset(dump_output_path)</pre><pre>self.connect_nodes(0, 2)</pre><pre># Wait for background validation to reach snapshot height</pre><pre>self.wait_until(lambda: n2.getchainstates()[“chainstates”][1][“blocks”] &gt;= SNAPSHOT_BASE_HEIGHT)</pre><p>Node 2 demonstrates the complete lifecycle:</p><p>1. <strong>Load snapshot</strong> at height 299</p><p>2. <strong>Sync to tip</strong> (height 399) using snapshot chainstate</p><p>3. <strong>Background validate</strong> blocks 0–299</p><p>4. <strong>Verification</strong>: When background validation reaches height 299, compare UTXO sets</p><p>5. <strong>Cleanup</strong>: If they match, mark snapshot as fully validated</p><p><strong>The critical verification step:</strong></p><pre>cpp</pre><pre>// In ChainstateManager::MaybeCompleteSnapshotValidation()</pre><pre>uint256 snapshot_utxo_hash = snapshot_chainstate.GetUTXOSetHash();</pre><pre>uint256 background_utxo_hash = background_chainstate.GetUTXOSetHash();</pre><pre>if (snapshot_utxo_hash == background_utxo_hash) {</pre><pre>// Snapshot is valid! Mark it as fully validated.</pre><pre>snapshot_chainstate.m_assumeutxo = Assumeutxo::VALIDATED;</pre><pre>} else {</pre><pre>// Snapshot is INVALID! This should never happen with hardcoded snapshots.</pre><pre>// Shut down the node to prevent consensus violations.</pre><pre>AbortNode(“AssumeUTXO snapshot validation failed!”);</pre><pre>}</pre><h4>Phase 7: Post-Validation Cleanup</h4><pre>python</pre><pre># Restart node after background validation completes</pre><pre>n2.restart()</pre><pre># Check that only one chainstate remains</pre><pre>assert_equal(len(n2.getchainstates()[“chainstates”]), 1)</pre><p>After restart, Bitcoin Core cleans up:</p><p>1. <strong>Delete background chainstate</strong>: No longer needed since validation is complete</p><p>2. <strong>Rename snapshot chainstate</strong>: `chainstate_snapshot` → `chainstate`</p><p>3. <strong>Remove markers</strong>: The chainstate is now indistinguishable from a traditionally synced node</p><p><strong>This is the “trust, then verify, then commit” pattern in action.</strong></p><h3>The C++ Implementation: How Bitcoin Core Handles This</h3><p>Now let’s trace through the C++ code that implements AssumeUTXO.</p><h4>1. The `loadtxoutset` RPC Command (`rpc/blockchain.cpp`)</h4><p>When a user calls `loadtxoutset`, this RPC handler is invoked:</p><pre>cpp</pre><pre>static RPCHelpMan loadtxoutset()</pre><pre>{</pre><pre>return RPCHelpMan{“loadtxoutset”,</pre><pre>“Load the serialized UTXO set from disk.”,</pre><pre>{</pre><pre>{“path”, RPCArg::Type::STR, RPCArg::Optional::NO, “Path to the snapshot file”},</pre><pre>},</pre><pre>RPCResult{RPCResult::Type::OBJ, “”, “”, {</pre><pre>{RPCResult::Type::NUM, “coins_loaded”, “Number of coins loaded from snapshot”},</pre><pre>{RPCResult::Type::STR_HEX, “base_hash”, “Block hash of the snapshot base”},</pre><pre>{RPCResult::Type::NUM, “base_height”, “Height of the snapshot base block”},</pre><pre>}},</pre><pre>[&amp;](const RPCHelpMan&amp; self, const JSONRPCRequest&amp; request) -&gt; UniValue</pre><pre>{</pre><pre>ChainstateManager&amp; chainman = EnsureAnyChainman(request.context);</pre><pre>fs::path path{request.params[0].get_str()};</pre><pre>// Open the snapshot file</pre><pre>AutoFile afile{fsbridge::fopen(path, “rb”)};</pre><pre>if (afile.IsNull()) {</pre><pre>throw JSONRPCError(RPC_INVALID_PARAMETER, “Unable to open snapshot file”);</pre><pre>}</pre><pre>// Activate the snapshot</pre><pre>SnapshotCompletionResult result =</pre><pre>chainman.ActivateSnapshot(afile, /*in_memory=*/false, /*write_metadata=*/true);</pre><pre>if (!result) {</pre><pre>throw JSONRPCError(RPC_INTERNAL_ERROR,</pre><pre>strprintf(“Unable to load UTXO snapshot: %s”, result.error));</pre><pre>}</pre><pre>UniValue ret(UniValue::VOBJ);</pre><pre>ret.pushKV(“coins_loaded”, (int64_t)result.coins_loaded);</pre><pre>ret.pushKV(“base_hash”, result.base_blockhash.GetHex());</pre><pre>ret.pushKV(“base_height”, (int64_t)result.base_height);</pre><pre>return ret;</pre><pre>},</pre><pre>};</pre><pre>}</pre><p><strong>Key steps:</strong></p><p>1. Open the snapshot file</p><p>2. Call `ActivateSnapshot()` to load and activate it</p><p>3. Return metadata about the loaded snapshot</p><p>4. Throw detailed error if loading fails</p><h4>2. Activating the Snapshot (`validation.cpp:ChainstateManager::ActivateSnapshot`)</h4><p>This is the core function that orchestrates snapshot loading:</p><pre>cpp</pre><pre>SnapshotCompletionResult ChainstateManager::ActivateSnapshot(</pre><pre>AutoFile&amp; snapshot_file,</pre><pre>bool in_memory,</pre><pre>bool write_metadata)</pre><pre>{</pre><pre>uint256 base_blockhash;</pre><pre>// Step 1: Read snapshot metadata</pre><pre>try {</pre><pre>snapshot_file &gt;&gt; base_blockhash;</pre><pre>} catch (const std::exception&amp; e) {</pre><pre>return {SnapshotCompletionResult::INVALID,</pre><pre>strprintf(“Unable to read snapshot metadata: %s”, e.what())};</pre><pre>}</pre><pre>// Step 2: Verify we have the base block header</pre><pre>CBlockIndex* base_block = m_blockman.LookupBlockIndex(base_blockhash);</pre><pre>if (!base_block) {</pre><pre>return {SnapshotCompletionResult::MISSING_HEADERS,</pre><pre>“Snapshot base block not found in block index. “</pre><pre>“Make sure all headers are syncing, and call loadtxoutset again.”};</pre><pre>}</pre><pre>// Step 3: Check the base block isn’t on an invalid chain</pre><pre>if (base_block-&gt;nStatus &amp; BLOCK_FAILED_MASK) {</pre><pre>return {SnapshotCompletionResult::INVALID,</pre><pre>“Snapshot base block is on an invalid chain”};</pre><pre>}</pre><pre>// Step 4: Create or load the snapshot chainstate</pre><pre>if (!m_snapshot_chainstate) {</pre><pre>m_snapshot_chainstate = std::make_unique&lt;Chainstate&gt;(</pre><pre>/* mempool */ nullptr,</pre><pre>m_blockman,</pre><pre>*this,</pre><pre>/* from_snapshot_blockhash */ base_blockhash</pre><pre>);</pre><pre>}</pre><pre>// Step 5: Populate the UTXO set from the snapshot</pre><pre>bool snapshot_ok = this-&gt;PopulateAndValidateSnapshot(</pre><pre>*m_snapshot_chainstate,</pre><pre>snapshot_file,</pre><pre>base_block</pre><pre>);</pre><pre>if (!snapshot_ok) {</pre><pre>return {SnapshotCompletionResult::INVALID,</pre><pre>“Snapshot UTXO set validation failed”};</pre><pre>}</pre><pre>// Step 6: Mark the snapshot chainstate as active</pre><pre>m_active_chainstate = m_snapshot_chainstate.get();</pre><pre>// Step 7: Initialize background validation chainstate</pre><pre>if (!m_ibd_chainstate) {</pre><pre>m_ibd_chainstate = std::make_unique&lt;Chainstate&gt;(</pre><pre>/* mempool */ nullptr,</pre><pre>m_blockman,</pre><pre>*this,</pre><pre>/* from_snapshot_blockhash */ std::nullopt</pre><pre>);</pre><pre>}</pre><pre>return {SnapshotCompletionResult::SUCCESS,</pre><pre>base_blockhash,</pre><pre>base_block-&gt;nHeight,</pre><pre>/* coins_loaded */ snapshot_coins_count};</pre><pre>}</pre><p><strong>Critical architecture decision:</strong> Bitcoin Core now manages <strong>two chainstates simultaneously</strong>:</p><p>- `m_snapshot_chainstate`: Active, used for network sync and serving peers</p><p>- `m_ibd_chainstate`: Background, validates the entire chain from genesis</p><h4>3. Populating the Snapshot (`validation.cpp:ChainstateManager::PopulateAndValidateSnapshot`)</h4><p>This function reads the serialized UTXO set and loads it into the database:</p><pre>cpp</pre><pre>bool ChainstateManager::PopulateAndValidateSnapshot(</pre><pre>Chainstate&amp; snapshot_chainstate,</pre><pre>AutoFile&amp; snapshot_file,</pre><pre>const CBlockIndex* base_block)</pre><pre>{</pre><pre>// Read snapshot metadata</pre><pre>uint64_t coins_count;</pre><pre>snapshot_file &gt;&gt; coins_count;</pre><pre>// Read expected nChainTx from hardcoded params</pre><pre>const auto&amp; params = Params().GetConsensus().assumeutxo_data;</pre><pre>auto iter = params.find(base_block-&gt;GetBlockHash());</pre><pre>if (iter == params.end()) {</pre><pre>LogError(“Snapshot base block not in hardcoded assumeutxo data\n”);</pre><pre>return false;</pre><pre>}</pre><pre>uint64_t expected_nChainTx = iter-&gt;second.nChainTx;</pre><pre>// Verify nChainTx matches</pre><pre>if (base_block-&gt;nChainTx != expected_nChainTx) {</pre><pre>LogError(“Snapshot nChainTx mismatch: expected %d, got %d\n”,</pre><pre>expected_nChainTx, base_block-&gt;nChainTx);</pre><pre>return false;</pre><pre>}</pre><pre>// Load UTXOs into the coins database</pre><pre>uint64_t coins_loaded = 0;</pre><pre>CCoinsViewDB&amp; coins_db = snapshot_chainstate.CoinsDB();</pre><pre>try {</pre><pre>while (coins_loaded &lt; coins_count) {</pre><pre>// Read next coin from snapshot</pre><pre>Coin coin;</pre><pre>COutPoint outpoint;</pre><pre>snapshot_file &gt;&gt; outpoint;</pre><pre>snapshot_file &gt;&gt; coin;</pre><pre>// Add to database</pre><pre>coins_db.BatchWrite({{outpoint, coin}});</pre><pre>coins_loaded++;</pre><pre>// Progress logging every 1M coins</pre><pre>if (coins_loaded % 1000000 == 0) {</pre><pre>LogInfo(“Loaded %d/%d coins from snapshot\n”,</pre><pre>coins_loaded, coins_count);</pre><pre>}</pre><pre>}</pre><pre>} catch (const std::exception&amp; e) {</pre><pre>LogError(“Exception while loading snapshot coins: %s\n”, e.what());</pre><pre>return false;</pre><pre>}</pre><pre>// Flush to disk</pre><pre>if (!coins_db.Flush()) {</pre><pre>LogError(“Failed to flush coins database after snapshot load\n”);</pre><pre>return false;</pre><pre>}</pre><pre>// Set the chain tip to the snapshot base block</pre><pre>snapshot_chainstate.setBlockIndexCandidates.insert(base_block);</pre><pre>snapshot_chainstate.m_chain.SetTip(base_block);</pre><pre>LogInfo(“Successfully loaded %d coins from snapshot at height %d\n”,</pre><pre>coins_loaded, base_block-&gt;nHeight);</pre><pre>return true;</pre><pre>}</pre><p><strong>Key validations:</strong></p><p>1. <strong>Coin count check</strong>: Ensure we read exactly the number of coins specified</p><p>2. <strong>nChainTx verification</strong>: Compare against hardcoded value in chainparams</p><p>3. <strong>Deserialization integrity</strong>: Catch any exceptions during UTXO reading</p><p>4. <strong>Database flush</strong>: Ensure all data is persisted before marking success</p><h4>4. Background Validation (`validation.cpp:Chainstate::ActivateBestChain`)</h4><p>While the snapshot chainstate syncs to the tip, the background chainstate validates history:</p><pre>cpp</pre><pre>bool Chainstate::ActivateBestChain(BlockValidationState&amp; state,</pre><pre>std::shared_ptr&lt;const CBlock&gt; pblock)</pre><pre>{</pre><pre>// For background chainstate, validate blocks from genesis</pre><pre>if (m_from_snapshot_blockhash) {</pre><pre>// This is the snapshot chainstate, proceed normally</pre><pre>return ActivateBestChainStep(state, pblock);</pre><pre>}</pre><pre>// This is the background chainstate</pre><pre>while (true) {</pre><pre>// Find the next block to validate</pre><pre>CBlockIndex* next_block = FindNextBlockToValidate();</pre><pre>if (!next_block) {</pre><pre>// Background validation is complete</pre><pre>break;</pre><pre>}</pre><pre>// Connect the block</pre><pre>if (!ConnectTip(state, next_block)) {</pre><pre>return false;</pre><pre>}</pre><pre>// Check if we’ve reached the snapshot base block</pre><pre>if (m_chainman.ShouldCheckSnapshotValidity()) {</pre><pre>m_chainman.MaybeCompleteSnapshotValidation();</pre><pre>}</pre><pre>}</pre><pre>return true;</pre><pre>}</pre><p><strong>Background validation strategy:</strong></p><p>1. Start from genesis (block 0)</p><p>2. Validate each block sequentially</p><p>3. Build the UTXO set incrementally</p><p>4. When reaching the snapshot height, trigger validation check</p><h4>5. Snapshot Validation Check (`validation.cpp:ChainstateManager::MaybeCompleteSnapshotValidation`)</h4><p>When background validation catches up, verify the snapshot was correct:</p><pre>cpp</pre><pre>void ChainstateManager::MaybeCompleteSnapshotValidation()</pre><pre>{</pre><pre>if (!m_snapshot_chainstate || !m_ibd_chainstate) {</pre><pre>return; // Not in snapshot mode</pre><pre>}</pre><pre>// Check if background chainstate reached snapshot height</pre><pre>const CBlockIndex* snapshot_base = m_snapshot_chainstate-&gt;m_chain.Genesis();</pre><pre>if (m_ibd_chainstate-&gt;m_chain.Tip()-&gt;nHeight &lt; snapshot_base-&gt;nHeight) {</pre><pre>return; // Background validation not complete yet</pre><pre>}</pre><pre>// Compute UTXO set hashes</pre><pre>uint256 snapshot_hash = m_snapshot_chainstate-&gt;GetUTXOSetHash();</pre><pre>uint256 background_hash = m_ibd_chainstate-&gt;GetUTXOSetHash();</pre><pre>LogInfo(“Comparing UTXO set hashes:\n”);</pre><pre>LogInfo(“ Snapshot: %s\n”, snapshot_hash.ToString());</pre><pre>LogInfo(“ Background: %s\n”, background_hash.ToString());</pre><pre>if (snapshot_hash == background_hash) {</pre><pre>// SUCCESS! Snapshot is valid</pre><pre>LogInfo(“AssumeUTXO snapshot is VALID!\n”);</pre><pre>m_snapshot_chainstate-&gt;m_assumeutxo = Assumeutxo::VALIDATED;</pre><pre>// Mark that cleanup should happen on next restart</pre><pre>WriteSnapshotValidatedMarker();</pre><pre>} else {</pre><pre>// FAILURE! Snapshot is invalid</pre><pre>LogError(“AssumeUTXO snapshot VALIDATION FAILED!\n”);</pre><pre>LogError(“ Expected: %s\n”, background_hash.ToString());</pre><pre>LogError(“ Got: %s\n”, snapshot_hash.ToString());</pre><pre>// This is a critical error — the hardcoded snapshot is wrong</pre><pre>// or the snapshot file was corrupted</pre><pre>AbortNode(“AssumeUTXO snapshot validation failed! “</pre><pre>“The snapshot UTXO set does not match the validated chain.”);</pre><pre>}</pre><pre>}</pre><p><strong>This is the moment of truth:</strong></p><p>- If hashes match: The snapshot was correct all along, mark it as validated</p><p>- If hashes differ: <strong>Abort the node</strong> — something is seriously wrong</p><p><strong>Why abort on mismatch?</strong> Because if the snapshot is invalid, the node has been syncing based on incorrect data. It may have:</p><p>- Accepted invalid transactions</p><p>- Served invalid blocks to peers</p><p>- Violated consensus rules</p><p>It’s safer to stop than to continue with corrupted state.</p><h4>6. Cleanup After Validation (`validation.cpp:ChainstateManager::ValidatedSnapshotCleanup`)</h4><p>After a restart, if the snapshot is validated, clean up the background chainstate:</p><pre>cpp</pre><pre>void ChainstateManager::ValidatedSnapshotCleanup()</pre><pre>{</pre><pre>// Check if there’s a validated snapshot marker</pre><pre>if (!HasValidatedSnapshotMarker()) {</pre><pre>return;</pre><pre>}</pre><pre>LogInfo(“Performing AssumeUTXO snapshot cleanup…\n”);</pre><pre>// Delete the background chainstate directory</pre><pre>fs::path bg_chainstate_path = GetDataDir() / “chainstate”;</pre><pre>if (fs::exists(bg_chainstate_path)) {</pre><pre>fs::remove_all(bg_chainstate_path);</pre><pre>LogInfo(“ Removed background chainstate directory\n”);</pre><pre>}</pre><pre>// Rename snapshot chainstate to be the main chainstate</pre><pre>fs::path snapshot_path = GetDataDir() / “chainstate_snapshot”;</pre><pre>if (fs::exists(snapshot_path)) {</pre><pre>fs::rename(snapshot_path, bg_chainstate_path);</pre><pre>LogInfo(“ Renamed chainstate_snapshot -&gt; chainstate\n”);</pre><pre>}</pre><pre>// Remove the validated marker file</pre><pre>RemoveValidatedSnapshotMarker();</pre><pre>LogInfo(“AssumeUTXO cleanup complete. Node is now fully validated.\n”);</pre><pre>}</pre><p><strong>After cleanup, the node is indistinguishable from one that validated the entire chain from genesis.</strong></p><h3>The Complete Execution Flow</h3><p>Let’s trace the entire path from test action to full validation:</p><blockquote>```</blockquote><blockquote>1. Node 0 generates 299 blocks</blockquote><blockquote>↓</blockquote><blockquote>2. Node 0 creates snapshot at height 299 (dumptxoutset)</blockquote><blockquote>↓</blockquote><blockquote>3. Node 1 (fresh node) calls loadtxoutset(snapshot.dat)</blockquote><blockquote>↓</blockquote><blockquote>4. RPC handler loadtxoutset() is invoked</blockquote><blockquote>↓</blockquote><blockquote>5. ChainstateManager::ActivateSnapshot() is called</blockquote><blockquote>↓</blockquote><blockquote>6. Snapshot file is opened and metadata read</blockquote><blockquote>↓</blockquote><blockquote>7. Base block (height 299) is looked up in block index</blockquote><blockquote>↓</blockquote><blockquote>8. New snapshot chainstate is created</blockquote><blockquote>↓</blockquote><blockquote>9. PopulateAndValidateSnapshot() loads all UTXOs from file</blockquote><blockquote>↓</blockquote><blockquote>10. Snapshot chainstate is marked as active</blockquote><blockquote>↓</blockquote><blockquote>11. Background chainstate is created for IBD</blockquote><blockquote>↓</blockquote><blockquote>12. Node 1 connects to Node 0</blockquote><blockquote>↓</blockquote><blockquote>13. Node 1 downloads headers and blocks</blockquote><blockquote>↓</blockquote><blockquote>14. Snapshot chainstate validates blocks 300+ (sync to tip)</blockquote><blockquote>↓</blockquote><blockquote>15. Background chainstate validates blocks 0–299 (in parallel)</blockquote><blockquote>↓</blockquote><blockquote>16. Background chainstate reaches height 299</blockquote><blockquote>↓</blockquote><blockquote>17. MaybeCompleteSnapshotValidation() is triggered</blockquote><blockquote>↓</blockquote><blockquote>18. UTXO set hashes are computed for both chainstates</blockquote><blockquote>↓</blockquote><blockquote>19. Hashes are compared</blockquote><blockquote>↓</blockquote><blockquote>20. If match: Mark snapshot as VALIDATED</blockquote><blockquote>↓</blockquote><blockquote>21. If mismatch: Call AbortNode() — critical error!</blockquote><blockquote>↓</blockquote><blockquote>22. Node restarts</blockquote><blockquote>↓</blockquote><blockquote>23. ValidatedSnapshotCleanup() runs</blockquote><blockquote>↓</blockquote><blockquote>24. Background chainstate is deleted</blockquote><blockquote>↓</blockquote><blockquote>25. Snapshot chainstate is renamed to main chainstate</blockquote><blockquote>↓</blockquote><blockquote>26. Node is now fully validated and indistinguishable from traditional sync</blockquote><blockquote>```</blockquote><h4>Why This Test Matters</h4><p>This test verifies one of Bitcoin Core’s most sophisticated optimizations:</p><p>1. <strong>Dramatically Faster Node Bootstrapping</strong></p><p>Traditional IBD on consumer hardware:</p><p>- <strong>Time:</strong> 1–7 days depending on hardware</p><p>-<strong>Bandwidth:</strong> ~500+ GB of block data</p><p>- <strong>CPU:</strong> Intensive signature verification for millions of transactions</p><p>With AssumeUTXO:</p><p>- <strong>Time to usability:</strong> 1–4 hours (load snapshot + sync recent blocks)</p><p>- <strong>Time to full validation:</strong> Still 1–7 days, but happens in background</p><p>- <strong>User experience:</strong> Node is usable immediately</p><p>2. <strong>Maintains Bitcoin’s Security Model</strong></p><p>AssumeUTXO doesn’t compromise security:</p><p>- <strong>Not a checkpoint:</strong> The snapshot is fully validated, just optimistically</p><p>- <strong>Not trust-required:</strong> Background validation ensures the snapshot is correct</p><p>- <strong>Fail-safe:</strong> If validation fails, the node aborts rather than continuing</p><p><strong>This is “trust, but verify” implemented correctly.</strong></p><p>3. <strong>Complex State Management</strong></p><p>The dual-chainstate architecture is sophisticated:</p><p>- <strong>Concurrent operation:</strong> Two chainstates running simultaneously</p><p>- <strong>Resource allocation:</strong> Prioritize snapshot chainstate to reach tip quickly</p><p>- <strong>Synchronization:</strong> Detect when background catches up and trigger validation</p><p>- <strong>Cleanup:</strong> Seamless transition from dual to single chainstate</p><p>4. <strong>Comprehensive Error Handling</strong></p><p>The test verifies handling of:</p><p>- Corrupted snapshot files</p><p>- Invalid base block hashes</p><p>- Wrong coin counts</p><p>- Missing headers</p><p>- Interrupted snapshot loads</p><p>- Validation failures</p><p>5. <strong>Network Effects</strong></p><p>AssumeUTXO has broader implications:</p><p>- <strong>More full nodes:</strong> Lower barrier to entry encourages node operation</p><p>- <strong>Better decentralization:</strong> More users can run full nodes</p><p>- <strong>Faster disaster recovery:</strong> Nodes can resync quickly after data loss</p><h4>Real-World Usage Scenarios</h4><p>AssumeUTXO addresses real pain points:</p><h4>Scenario 1: New User Onboarding</h4><p><strong>Without AssumeUTXO:</strong></p><p>- Download Bitcoin Core</p><p>- Start initial sync</p><p>- Wait 3 days</p><p>- Give up because it’s taking too long</p><p>- Use a custodial wallet instead (gives up sovereignty)</p><p><strong>With AssumeUTXO:</strong></p><p>- Download Bitcoin Core</p><p>- Load recent snapshot</p><p>- Usable in 2 hours</p><p>- Background validation completes over next few days</p><p>- User successfully runs a full node</p><h4>Scenario 2: Node Disaster Recovery</h4><p><strong>Scenario:</strong> Your server crashes and corrupts the blockchain database.</p><p><strong>Without AssumeUTXO:</strong></p><p>- Delete corrupted data</p><p>- Resync from genesis</p><p>- 3–7 days downtime</p><p>- Lost revenue if running a service</p><p><strong>With AssumeUTXO:</strong></p><p>- Delete corrupted data</p><p>- Load latest snapshot</p><p>- Back online in hours</p><p>- Full validation completes in background</p><h4>Scenario 3: Testing and Development</h4><p><strong>Scenario:</strong> Developer needs to test against mainnet data.</p><p><strong>Without AssumeUTXO:</strong></p><p>- Sync entire mainnet (days)</p><p>- Maintain synchronized node</p><p>- High storage and time costs</p><p><strong>With AssumeUTXO:</strong></p><p>- Load snapshot</p><p>- Start testing in hours</p><p>- Can easily reset to fresh state using new snapshots</p><h4>Scenario 4: Pruned Node Conversion</h4><p><strong>Scenario:</strong> User ran a pruned node, now wants full archival node.</p><p><strong>Without AssumeUTXO:</strong></p><p>- Must resync from genesis (lost old blocks)</p><p>- Days of downtime</p><p><strong>With AssumeUTXO:</strong></p><p>- Load snapshot at prune point</p><p>- Validate forward (already have recent blocks)</p><p>- Validate backward (fill in history)</p><p>- Seamless upgrade path</p><h4>Security Considerations</h4><p>AssumeUTXO introduces new security considerations:</p><p>1. <strong>Snapshot Source Trust</strong></p><p><strong>Question:</strong> Where does the snapshot come from?</p><p><strong>Answer:</strong> Hardcoded in Bitcoin Core’s source code (`chainparams.cpp`):</p><pre>cpp</pre><pre>// src/kernel/chainparams.cpp</pre><pre>const AssumeutxoData m_assumeutxo_data = {</pre><pre>{</pre><pre>// Snapshot at height 840000 (block 000000000000000000026f2b2c1b0e78e0629e5b391f3b4d5aef0c2ab0e1e8d6)</pre><pre>.height = 840000,</pre><pre>.hash_serialized = “a2a5521a3e5c7f8b0e7f8a9b8c7d6e5f4a3b2c1d0e1f2a3b4c5d6e7f8a9b0c1d2”,</pre><pre>.nChainTx = 1000000000,</pre><pre>.blockhash = uint256S(“000000000000000000026f2b2c1b0e78e0629e5b391f3b4d5aef0c2ab0e1e8d6”),</pre><pre>}</pre><pre>};</pre><p><strong>Security implications:</strong></p><p>- Snapshots are reviewed by multiple Bitcoin Core maintainers</p><p>- Anyone can verify a snapshot by syncing traditionally and comparing</p><p>- Bad snapshots would be detected during code review</p><p>- Even if a bad snapshot made it in, background validation would catch it</p><p>2. <strong>Denial of Service Risks</strong></p><p><strong>Attack:</strong> Provide invalid snapshot to waste node resources.</p><p><strong>Mitigation:</strong></p><p>- Snapshot metadata validated before loading UTXOs</p><p>- Early termination on format errors</p><p>- Resource limits on snapshot loading</p><p>3. <strong>Consensus Risk</strong></p><p><strong>Question:</strong> What if the snapshot is invalid?</p><p><strong>Answer:</strong> Multiple layers of protection:</p><p>1. <strong>Hardcoded snapshots:</strong> Only pre-approved snapshots can be used</p><p>2. <strong>Metadata validation:</strong> nChainTx must match hardcoded value</p><p>3. <strong>Background validation:</strong> Complete verification ensures correctness</p><p>4. <strong>Abort on failure:</strong> Node stops rather than continuing with bad state</p><p><strong>Critical property:</strong> Even with a bad snapshot, the node will never accept invalid blocks permanently.</p><p>4. <strong>Network Partitioning</strong></p><p><strong>Scenario:</strong> Attacker creates alternative snapshot, forks Bitcoin Core, distributes malicious binary.</p><p><strong>Mitigation:</strong></p><p>- Users verify Bitcoin Core releases (GPG signatures, deterministic builds)</p><p>- Community would detect divergent snapshots immediately</p><p>- Background validation would still catch the issue</p><p>- Social layer: Bitcoin Core’s security model relies on users verifying the software they run</p><h4>Key Takeaways</h4><p>1. <strong>AssumeUTXO is an optimization, not a shortcut</strong> — full validation still happens, just asynchronously</p><p>2. <strong>Dual chainstate management is sophisticated</strong> — running two validation engines simultaneously requires careful resource management</p><p>3. <strong>Trust-but-verify is formalized</strong> — the snapshot is assumed correct initially but completely verified before permanent commitment</p><p>4. <strong>Error handling is paramount</strong> — invalid snapshots must be detected early to prevent wasted resources</p><p>5. <strong>User experience improvements enable decentralization</strong> — faster sync means more users run full nodes</p><p>6. <strong>The test exercises a complete vertical slice</strong> — from RPC interface through chainstate management to low-level UTXO database operations</p><p>7. <strong>Security is not compromised</strong> — background validation ensures the same security guarantees as traditional sync</p><h4>Conclusion</h4><p>The `feature_assumeutxo.py` test validates one of Bitcoin Core’s most impactful user experience improvements. By allowing nodes to bootstrap from UTXO snapshots while maintaining complete validation, AssumeUTXO reduces the time-to-usability from days to hours without sacrificing Bitcoin’s security model.</p><p>The implementation demonstrates sophisticated software engineering:</p><p>- <strong>Concurrent processing:</strong> Dual chainstates running in parallel</p><p>- <strong>Resource management:</strong> Prioritizing user-facing sync while backgrounding historical validation</p><p>- <strong>State machines:</strong> Complex lifecycle from snapshot load through validation to cleanup</p><p>- <strong>Error handling:</strong> Comprehensive detection and handling of invalid snapshots</p><p>- <strong>Security-first design:</strong> Abort rather than risk consensus violations</p><p>For developers, this test teaches valuable lessons about:</p><p>- Optimistic execution with verification</p><p>- State snapshots for bootstrapping</p><p>- Dual-phase validation patterns</p><p>- Graceful degradation and error handling</p><p>- Balancing user experience with security</p><p>AssumeUTXO proves that even in a system as security-critical as Bitcoin, there’s room for dramatic performance improvements through clever engineering — as long as security properties are preserved through rigorous validation.</p><p>The next time you need to bootstrap a new Bitcoin node, remember: you’re not trusting the snapshot. You’re trusting Bitcoin Core’s ability to verify it completely in the background. And that verification is exactly what this test ensures works correctly.</p><h4>References</h4><p>- <strong>Bitcoin Core PR #15606</strong> — Original AssumeUTXO implementation by James O’Beirne: <a href="https://github.com/bitcoin/bitcoin/pull/15606">https://github.com/bitcoin/bitcoin/pull/15606</a></p><p>- <strong>Bitcoin Core PR #27596</strong> — AssumeUTXO mainnet activation (height 840,000): <a href="https://github.com/bitcoin/bitcoin/pull/27596">https://github.com/bitcoin/bitcoin/pull/27596</a></p><p>- <strong>Test file:</strong> `test/functional/feature_assumeutxo.py` in the Bitcoin Core repository</p><p>- <strong>Core implementation:</strong> `src/validation.cpp` — `ChainstateManager::ActivateSnapshot`, `PopulateAndValidateSnapshot`, `MaybeCompleteSnapshotValidation`</p><p>- <strong>RPC handler:</strong> `src/rpc/blockchain.cpp` — `loadtxoutset` and `dumptxoutset`</p><p>- <strong>Hardcoded snapshot data:</strong> `src/kernel/chainparams.cpp` — `m_assumeutxo_data`</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f752987415e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deconstructing Bitcoin Core Tests]]></title>
            <link>https://medium.com/@wandiamugo/deconstructing-bitcoin-core-tests-91ac200c4179?source=rss-19a686aeb31e------2</link>
            <guid isPermaLink="false">https://medium.com/p/91ac200c4179</guid>
            <dc:creator><![CDATA[Wandia Mugo]]></dc:creator>
            <pubDate>Wed, 11 Feb 2026 09:47:09 GMT</pubDate>
            <atom:updated>2026-02-11T09:57:18.862Z</atom:updated>
            <content:encoded><![CDATA[<h4>Day 4: Understanding feature_asmap.py — Smarter Address Grouping with ASN Mapping</h4><p><strong>Test File:</strong> `bitcoin/test/functional/feature_asmap.py`</p><p><strong>Category:</strong> Feature Tests</p><p><strong>Complexity:</strong> Moderate</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5yMi0pqMK5lD1BM74SR1qw.jpeg" /></figure><h3>Introduction</h3><h4>The Neighbourhood Analogy</h4><p>Imagine you’re organizing a huge conference with 10,000 attendees from around the world. You need to split them into discussion groups, but here’s the catch: you don’t want any single organization or company to dominate multiple groups. If you group people by their email addresses randomly, you might accidentally put 50 employees from the same company in 50 different groups…giving that company disproportionate influence across the conference.</p><p>Here’s a better approach: group people by their <strong>company or organization</strong>. All the Google employees go in one bucket, all the Microsoft employees in another, all the university researchers in another. This way, even if Google sends 1,000 people, they’ll only have significant influence in a few groups, not everywhere.</p><p>Bitcoin Core faces the exact same problem with IP addresses. An attacker with access to a large network (like a datacenter or ISP) could generate thousands of IP addresses that look different but all come from the same place. The old method — grouping by `/16` prefix (the first 16 bits of an IP address), is like grouping conference attendees by the first two letters of their email address. It’s simple, but easily gamed.</p><p><strong>ASN mapping</strong> (Autonomous System Number mapping) is the better approach. It’s like grouping by company: all addresses that belong to the same network operator get grouped together, no matter how many individual IP addresses they control.</p><h4>Why This Matters for Developers</h4><p>This test is about <strong>Sybil attack resistance</strong> — defending against an attacker who creates many fake identities to gain disproportionate influence. The same principle applies everywhere:</p><p>- <strong>Social networks:</strong> Detecting bot farms that create thousands of fake accounts from the same datacenter</p><p>- <strong>Voting systems:</strong> Preventing someone from stuffing the ballot box with sockpuppet accounts</p><p>- <strong>Recommendation engines:</strong> Ensuring one coordinated group can’t manipulate ratings</p><p>- <strong>Distributed systems:</strong> Preventing a single entity from controlling too many nodes</p><p>The key insight: <strong>physical network topology reveals hidden relationships between seemingly independent identities.</strong> Two IP addresses that look completely different (say, `45.12.34.56` and `198.51.100.78`) might both belong to the same Amazon datacenter and ASN mapping reveals that.</p><h4>The Technical Version</h4><p>Bitcoin Core’s Address Manager (`AddrMan`) organizes peer addresses into buckets to ensure diverse connections across the network. By default, it uses `/16` prefix bucketing (grouping IPv4 addresses by their first 16 bits), which provides basic diversity but can be circumvented by attackers with access to large IP ranges. <strong>ASN mapping</strong> is an optional enhancement that groups addresses by their Autonomous System Number (ASN) — the organization that controls the network — providing much stronger Sybil resistance. The `feature_asmap.py` test verifies that Bitcoin Core correctly loads, validates, and uses ASN map files for IP bucketing, and gracefully handles all error cases (missing files, unparsable files, empty files) without crashing.</p><h4>What Is an AS (Autonomous System)?</h4><p>Before diving into the test, we need to understand the internet’s organizational structure.</p><h4>The Internet’s Hierarchical Structure</h4><p>The internet isn’t just a random mesh of computers. It’s organized into <strong>Autonomous Systems (AS)</strong> — networks controlled by a single organization. Examples:</p><p>- <strong>AS15169:</strong> Google’s network</p><p>- <strong>AS16509:</strong> Amazon Web Services (AWS)</p><p>- <strong>AS174:</strong> Cogent Communications (a major backbone provider)</p><p>- <strong>AS13335:</strong> Cloudflare</p><p>Each AS controls one or more blocks of IP addresses. When you connect to a website hosted on AWS, you’re connecting to an IP address in AS16509. When you search on Google, you’re connecting to AS15169.</p><h4>Why ASNs Matter for Bitcoin</h4><p>An attacker who controls a datacenter or ISP has access to thousands (or millions) of IP addresses within the same AS. Using traditional `/16` bucketing, those addresses might appear diverse:</p><blockquote>```</blockquote><blockquote>Traditional /16 bucketing:</blockquote><blockquote>203.0.113.1 → bucket for 203.0.x.x</blockquote><blockquote>198.51.100.50 → bucket for 198.51.x.x</blockquote><blockquote>192.0.2.200 → bucket for 192.0.x.x</blockquote><p>These look different! Bitcoin Core would treat them as diverse peers.</p><blockquote>```</blockquote><p>But if all three belong to the same AS (say, a malicious ISP), they’re actually controlled by the same entity:</p><blockquote>```</blockquote><blockquote>ASN-based bucketing:</blockquote><blockquote>203.0.113.1 → AS64512 (Evil ISP)</blockquote><blockquote>198.51.100.50 → AS64512 (Evil ISP)</blockquote><blockquote>192.0.2.200 → AS64512 (Evil ISP)</blockquote><p>These are NOT diverse! Bitcoin Core should group them together.</p><blockquote>```</blockquote><p>By bucketing by ASN instead of IP prefix, Bitcoin Core gains a much more accurate picture of network diversity.</p><h4>The Trade-off</h4><p>There’s a cost: ASN mapping requires an <strong>external data file</strong> that maps IP ranges to ASN numbers. This file:</p><p>- Must be generated from BGP routing data (which changes over time)</p><p>- Must be kept up to date (networks reorganize, ISPs merge, etc.)</p><p>- Adds complexity (file loading, validation, error handling)</p><p>That’s why ASN mapping is <strong>optional</strong> — users can enable it with `-asmap=&lt;file&gt;` if they want the enhanced protection, or stick with the simpler `/16` bucketing if they don’t.</p><h3>The Test: What Does It Do?</h3><p>The test runs 9 independent scenarios, each verifying a different aspect of ASN map handling. Let’s walk through them.</p><h4>Test Setup (Lines 41–44)</h4><pre>python</pre><pre>def set_test_params(self):</pre><pre>self.num_nodes = 1</pre><pre># Do addrman checks on all operations and use deterministic addrman</pre><pre>self.extra_args = [[“-checkaddrman=1”, “-test=addrman”]]</pre><p>The test uses a single node with:</p><p>- `-checkaddrman=1`: Run full AddrMan consistency checks on every operation (paranoid mode)</p><p>- `-test=addrman`: Use deterministic randomness for reproducible bucket placement</p><h4>Helper Function: `fill_addrman` (Lines 46–49)</h4><pre>python</pre><pre>def fill_addrman(self, node_id):</pre><pre>“””Add 2 tried addresses to the addrman, followed by 2 new addresses.”””</pre><pre>for addr, tried in [[0, True], [1, True], [2, False], [3, False]]:</pre><pre>self.nodes[node_id].addpeeraddress(address=f”101.{addr}.0.0&quot;, tried=tried, port=8333)</pre><p>This populates the address manager with 4 test addresses:</p><p>- `101.0.0.0` and `101.1.0.0` marked as “tried” (we’ve successfully connected before)</p><p>- `101.2.0.0` and `101.3.0.0` marked as “new” (heard about, but never connected)</p><p>This setup is used in Test 5 to verify that ASN mapping works correctly with an existing address database.</p><h4>Test 1: Default Behavior Without `-asmap` (Lines 51–55)</h4><pre>python</pre><pre>def test_without_asmap_arg(self):</pre><pre>self.log.info(‘Test bitcoind with no -asmap arg passed’)</pre><pre>self.stop_node(0)</pre><pre>with self.node.assert_debug_log([‘Using /16 prefix for IP bucketing’]):</pre><pre>self.start_node(0)</pre><p><strong>The anecdote:</strong> You buy a new phone and it comes with default settings. The manufacturer chose sensible defaults that work for 95% of users. You don’t have to configure anything — it just works.</p><p>Bitcoin Core’s default is `/16` prefix bucketing. It’s simple, requires no external files, and works reasonably well. The test confirms that without the `-asmap` flag, the node logs `”Using /16 prefix for IP bucketing”` and starts successfully.</p><p><strong>What this tests:</strong> The baseline. Before testing all the ASN map scenarios, confirm that the default behavior still works.</p><h4>Test 2: Explicit `-noasmap` Flag (Lines 57–61)</h4><pre>python</pre><pre>def test_noasmap_arg(self):</pre><pre>self.log.info(‘Test bitcoind with -noasmap arg passed’)</pre><pre>self.stop_node(0)</pre><pre>with self.node.assert_debug_log([‘Using /16 prefix for IP bucketing’]):</pre><pre>self.start_node(0, [“-noasmap”])</pre><p><strong>The anecdote:</strong> Sometimes you want to explicitly say “no thanks” to a feature. Like when a website asks if you want push notifications, and you click “Block” instead of ignoring the popup.</p><p>The `-noasmap` flag explicitly disables ASN mapping, even if a default ASN map file exists. This is useful if:</p><p>- You previously used `-asmap` but want to temporarily disable it</p><p>- You have an `ip_asn.map` file in your data directory but don’t want to use it</p><p><strong>What this tests:</strong> That the “opt-out” mechanism works, users can explicitly disable ASN mapping.</p><h4>Test 3: ASMap with Absolute Path (Lines 63–70)</h4><pre>python</pre><pre>def test_asmap_with_absolute_path(self):</pre><pre>self.log.info(‘Test bitcoind -asmap=&lt;absolute path&gt;’)</pre><pre>self.stop_node(0)</pre><pre>filename = os.path.join(self.datadir, ‘my-map-file.map’)</pre><pre>shutil.copyfile(self.asmap_raw, filename)</pre><pre>with self.node.assert_debug_log(expected_messages(filename)):</pre><pre>self.start_node(0, [f’-asmap={filename}’])</pre><pre>os.remove(filename)</pre><p><strong>The anecdote:</strong> You want to play a video stored in `/Users/Alice/Videos/movie.mp4`. You tell your video player the full path. It goes directly to that exact location and opens the file.</p><p>This test copies the skeleton ASN map file to a custom location and tells Bitcoin Core the absolute path: `-asmap=/full/path/to/my-map-file.map`.</p><p><strong>Expected output:</strong></p><blockquote>```</blockquote><blockquote>Opened asmap file “/full/path/to/my-map-file.map” (59 bytes) from disk</blockquote><blockquote>Using asmap version fec61fa21a9f46f3b17bdcd660d7f4cd90b966aad3aec593c99b35f0aca15853 for IP bucketing</blockquote><blockquote>```</blockquote><p>The version hash (`fec61fa2…`) is a SHA-256 hash of the entire ASN map contents. Two nodes with the same hash are guaranteed to bucket addresses identically.</p><p><strong>What this tests:</strong> That Bitcoin Core can load an ASN map from any location on the filesystem.</p><h4>Test 4: ASMap with Relative Path (Lines 72–80)</h4><pre>python</pre><pre>def test_asmap_with_relative_path(self):</pre><pre>self.log.info(‘Test bitcoind -asmap=&lt;relative path&gt;’)</pre><pre>self.stop_node(0)</pre><pre>name = ‘ASN_map’</pre><pre>filename = os.path.join(self.datadir, name)</pre><pre>shutil.copyfile(self.asmap_raw, filename)</pre><pre>with self.node.assert_debug_log(expected_messages(filename)):</pre><pre>self.start_node(0, [f’-asmap={name}’])</pre><pre>os.remove(filename)</pre><p><strong>The anecdote:</strong> Instead of saying “go to `/Users/Alice/Videos/movie.mp4`,” you say “go to `Videos/movie.mp4`” from your home directory. The application figures out the full path by combining your home directory with the relative path.</p><p>This test passes just the filename (`ASN_map`) without a path. Bitcoin Core should:</p><p>1. Realize it’s a relative path (no leading `/`)</p><p>2. Prefix it with the network-specific data directory (e.g., `~/.bitcoin/regtest/`)</p><p>3. Load the file from there</p><p><strong>What this tests:</strong> That relative paths are resolved correctly relative to the data directory, not the current working directory.</p><h4>Test 5: Default ASMap File (Lines 82–89)</h4><pre>python</pre><pre>def test_default_asmap(self):</pre><pre>shutil.copyfile(self.asmap_raw, self.default_asmap)</pre><pre>for arg in [‘-asmap’, ‘-asmap=’]:</pre><pre>self.log.info(f’Test bitcoind {arg} (using default map file)’)</pre><pre>self.stop_node(0)</pre><pre>with self.node.assert_debug_log(expected_messages(self.default_asmap)):</pre><pre>self.start_node(0, [arg])</pre><pre>os.remove(self.default_asmap)</pre><p><strong>The anecdote:</strong> Your web browser has a default download folder. When you click “Download” without specifying where to save, it goes there automatically.</p><p>`DEFAULT_ASMAP_FILENAME` is defined as `’ip_asn.map’` (line 32 of the test). If you pass `-asmap` or `-asmap=` (with no file specified), Bitcoin Core looks for this file in the data directory.</p><p>The test verifies that both flag formats work:</p><p>- `-asmap` (no `=`)</p><p>- `-asmap=` (with `=` but no value)</p><p><strong>What this tests:</strong> The convenience feature , users can just say `-asmap` and Bitcoin Core knows where to look.</p><h4>Test 6: ASMap Interaction with Existing AddrMan (Lines 91–105)</h4><pre>python</pre><pre>def test_asmap_interaction_with_addrman_containing_entries(self):</pre><pre>self.log.info(“Test bitcoind -asmap restart with addrman containing new and tried entries”)</pre><pre>self.stop_node(0)</pre><pre>shutil.copyfile(self.asmap_raw, self.default_asmap)</pre><pre>self.start_node(0, [“-asmap”, “-checkaddrman=1”, “-test=addrman”])</pre><pre>self.fill_addrman(node_id=0)</pre><pre>self.restart_node(0, [“-asmap”, “-checkaddrman=1”, “-test=addrman”])</pre><pre>with self.node.assert_debug_log(</pre><pre>expected_msgs=[</pre><pre>“CheckAddrman: new 2, tried 2, total 4 started”,</pre><pre>“CheckAddrman: completed”,</pre><pre>]</pre><pre>):</pre><pre>self.node.getnodeaddresses() # getnodeaddresses re-runs the addrman checks</pre><pre>os.remove(self.default_asmap)</pre><p><strong>The anecdote:</strong> You reorganize your music library by genre (Rock, Jazz, Classical). But you already have 10,000 songs organized by artist. You run a script to recategorize them all. At the end, you verify: “Do I still have all 10,000 songs? Did any get lost or duplicated?”</p><p>This is the most important test. It verifies that:</p><p>1. You can start Bitcoin Core with `-asmap`, add addresses, restart, and everything still works</p><p>2. The consistency check (`CheckAddrman`) passes after loading addresses that were bucketed using ASN mapping</p><p>3. The address counts match: 2 new, 2 tried, 4 total</p><p><strong>Why this matters:</strong> When you switch from `/16` bucketing to ASN bucketing (or vice versa), addresses need to be re-bucketed. Bitcoin Core must handle this gracefully without losing addresses or corrupting the address database.</p><p><strong>What this tests:</strong> That ASN mapping is compatible with AddrMan’s persistence and consistency checks.</p><h4>Test 7: Missing Default ASMap File (Lines 107–111)</h4><pre>python</pre><pre>def test_default_asmap_with_missing_file(self):</pre><pre>self.log.info(‘Test bitcoind -asmap with missing default map file’)</pre><pre>self.stop_node(0)</pre><pre>msg = f”Error: Could not find asmap file \”{self.default_asmap}\””</pre><pre>self.node.assert_start_raises_init_error(extra_args=[‘-asmap’], expected_msg=msg)</pre><p><strong>The anecdote:</strong> You set your music player to use a specific equalizer preset file, but you forgot to download it. The player should say “Error: Can’t find preset file” instead of crashing or using random settings.</p><p>If you explicitly request `-asmap` but the file doesn’t exist, Bitcoin Core should <strong>refuse to start</strong> with a clear error message. This is the right choice because:</p><p>- You explicitly enabled a security feature</p><p>- Without the file, Bitcoin Core would silently fall back to weaker `/16` bucketing</p><p>- That’s a security downgrade you didn’t consent to</p><p><strong>What this tests:</strong> That missing ASN map files are treated as a fatal error when ASN mapping is explicitly requested.</p><h4>Test 8: Empty (Unparsable) ASMap File (Lines 113–120)</h4><pre>python</pre><pre>def test_empty_asmap(self):</pre><pre>self.log.info(‘Test bitcoind -asmap with empty map file’)</pre><pre>self.stop_node(0)</pre><pre>with open(self.default_asmap, “w”, encoding=”utf-8&quot;) as f:</pre><pre>f.write(“”)</pre><pre>msg = f”Error: Could not parse asmap file \”{self.default_asmap}\””</pre><pre>self.node.assert_start_raises_init_error(extra_args=[‘-asmap’], expected_msg=msg)</pre><pre>os.remove(self.default_asmap)</pre><p><strong>The anecdote:</strong> Someone emails you a corrupted ZIP file. When you try to extract it, your computer says “This archive is damaged and can’t be opened” instead of extracting garbage.</p><p>An empty file fails the sanity check in `DecodeAsmap` (src/util/asmap.cpp:217):</p><pre>cpp</pre><pre>if (!SanityCheckASMap(bits, 128)) {</pre><pre>LogPrintf(“Sanity check of asmap file %s failed\n”, …);</pre><pre>return {};</pre><pre>}</pre><p>The sanity check verifies that:</p><p>- The ASN map is a valid state machine (no infinite loops, no unreachable code)</p><p>- Every possible 128-bit IP address has a defined mapping</p><p>- The file ends with a `RETURN` instruction</p><p>An empty file obviously fails these checks.</p><p><strong>What this tests:</strong> That corrupted or invalid ASN map files are detected before they can cause problems.</p><h4>Test 9: ASMap Health Check (Lines 122–136)</h4><pre>python</pre><pre>def test_asmap_health_check(self):</pre><pre>self.log.info(‘Test bitcoind -asmap logs ASMap Health Check with basic stats’)</pre><pre>shutil.copyfile(self.asmap_raw, self.default_asmap)</pre><pre>msg = “ASMap Health Check: 4 clearnet peers are mapped to 3 ASNs with 0 peers being unmapped”</pre><pre>with self.node.assert_debug_log(expected_msgs=[msg]):</pre><pre>self.start_node(0, extra_args=[‘-asmap’])</pre><pre>raw_addrman = self.node.getrawaddrman()</pre><pre>asns = []</pre><pre>for _, entries in raw_addrman.items():</pre><pre>for _, entry in entries.items():</pre><pre>asn = entry[‘mapped_as’]</pre><pre>if asn not in asns:</pre><pre>asns.append(asn)</pre><pre>assert_equal(len(asns), 3)</pre><pre>os.remove(self.default_asmap)</pre><p><strong>The anecdote:</strong> After reorganizing your music library, your player shows: “10,000 songs organized into 42 genres, 3 songs couldn’t be categorized.” That’s useful feedback, you know the system is working and can see if something went wrong.</p><p>This test verifies that Bitcoin Core logs a health check summary when using ASN mapping:</p><blockquote>```</blockquote><blockquote>ASMap Health Check: 4 clearnet peers are mapped to 3 ASNs with 0 peers being unmapped</blockquote><blockquote>```</blockquote><p>This tells the user:</p><p>- <strong>4 clearnet peers:</strong> Total IPv4/IPv6 addresses (excludes Tor, I2P, etc.)</p><p>- <strong>3 ASNs:</strong> These 4 addresses belong to 3 different network operators</p><p>- <strong>0 unmapped:</strong> All addresses were successfully mapped</p><p><strong>Why this is useful:</strong> If you see “100 clearnet peers mapped to 2 ASNs,” that’s a red flag , you’re not as diversified as you thought. If you see “50 unmapped,” your ASN map might be outdated.</p><p><strong>What this tests:</strong> That the health check correctly counts and reports ASN diversity.</p><h3>The C++ Implementation: How ASN Mapping Works</h3><h4>1. The ASN Map File Format (`util/asmap.cpp`)</h4><p>The ASN map is not a simple lookup table. It’s a <strong>compressed binary decision tree</strong> — a tiny program that takes a 128-bit IP address and returns a 32-bit ASN.</p><p><strong>The instruction set:</strong></p><pre>cpp</pre><pre>enum class Instruction : uint32_t</pre><pre>{</pre><pre>RETURN = 0, // Return an ASN number</pre><pre>JUMP = 1, // Conditional jump based on the next IP bit</pre><pre>MATCH = 2, // Match several IP bits at once</pre><pre>DEFAULT = 3, // Set default ASN for this path</pre><pre>};</pre><p><strong>How it works:</strong></p><p>1. Start at the beginning of the ASN map</p><p>2. Read the current instruction</p><p>3. If `RETURN`: return the ASN and stop</p><p>4. If `JUMP`: check the next bit of the IP address. If 1, jump forward. If 0, continue.</p><p>5. If `MATCH`: check the next N bits of the IP address against a pattern. If they match, continue. If not, return the default ASN.</p><p>6. If `DEFAULT`: set the default ASN for this path</p><p>7. Repeat until you hit a `RETURN`</p><p><strong>Example traversal for IP `203.0.113.5` (in AS64496):</strong></p><blockquote>```</blockquote><blockquote>Start → JUMP → bit 0 = 1 → jump forward</blockquote><blockquote>→ MATCH → bits 1–8 = 11001011 → match!</blockquote><blockquote>→ JUMP → bit 9 = 0 → continue</blockquote><blockquote>→ RETURN AS64496</blockquote><blockquote>```</blockquote><p>This encoding is incredibly space-efficient. The entire map for all 4 billion IPv4 addresses can fit in a few megabytes.</p><h4>2. Sanity Checking the ASN Map (`util/asmap.cpp:133–195`)</h4><p>Before using an ASN map, Bitcoin Core runs an exhaustive sanity check:</p><pre>cpp</pre><pre>bool SanityCheckASMap(const std::vector&lt;bool&gt;&amp; asmap, int bits)</pre><pre>{</pre><pre>// Verify:</pre><pre>// — Every path through the decision tree ends with RETURN</pre><pre>// — No instructions straddle the end of the file</pre><pre>// — No infinite loops</pre><pre>// — No unreachable code</pre><pre>// — No excessive padding at the end</pre><pre>// — All jumps point to valid locations</pre><pre>// …</pre><pre>}</pre><p><strong>Why this is critical:</strong> A malicious or corrupted ASN map could:</p><p>- Cause infinite loops (node hangs)</p><p>- Return invalid ASNs (breaks bucketing)</p><p>- Leak information (timing attacks)</p><p>The sanity check prevents all of these by verifying the map is well-formed before any IP addresses are processed.</p><h4>3. Loading the ASN Map (`init.cpp:1514–1538`)</h4><p>When Bitcoin Core starts, it loads the ASN map (if configured):</p><pre>cpp</pre><pre>std::vector&lt;bool&gt; asmap;</pre><pre>if (args.IsArgSet(“-asmap”) &amp;&amp; !args.IsArgNegated(“-asmap”)) {</pre><pre>fs::path asmap_path = args.GetPathArg(“-asmap”, DEFAULT_ASMAP_FILENAME);</pre><pre>if (!asmap_path.is_absolute()) {</pre><pre>asmap_path = args.GetDataDirNet() / asmap_path; // Make relative paths absolute</pre><pre>}</pre><pre>if (!fs::exists(asmap_path)) {</pre><pre>InitError(strprintf(_(“Could not find asmap file %s”), …));</pre><pre>return false; // Fatal error</pre><pre>}</pre><pre>asmap = DecodeAsmap(asmap_path);</pre><pre>if (asmap.size() == 0) {</pre><pre>InitError(strprintf(_(“Could not parse asmap file %s”), …));</pre><pre>return false; // Fatal error</pre><pre>}</pre><pre>const uint256 asmap_version = (HashWriter{} &lt;&lt; asmap).GetHash();</pre><pre>LogInfo(“Using asmap version %s for IP bucketing”, asmap_version.ToString());</pre><pre>} else {</pre><pre>LogInfo(“Using /16 prefix for IP bucketing”);</pre><pre>}</pre><p><strong>Key steps:</strong></p><p>1. Check if `-asmap` was specified</p><p>2. Resolve relative paths to absolute paths</p><p>3. Check if the file exists (error if not)</p><p>4. Decode the file (error if parsing fails)</p><p>5. Compute a version hash (so users can verify they’re using the same map)</p><p>6. Pass the map to `NetGroupManager`</p><h4>4. Using the ASN Map for Bucketing (`netgroup.cpp:18–79`)</h4><p>Once loaded, the ASN map is used by `NetGroupManager::GetGroup()` to determine which bucket an address goes into:</p><pre>cpp</pre><pre>std::vector&lt;unsigned char&gt; NetGroupManager::GetGroup(const CNetAddr&amp; address) const</pre><pre>{</pre><pre>std::vector&lt;unsigned char&gt; vchRet;</pre><pre>// Try to get ASN for this address</pre><pre>uint32_t asn = GetMappedAS(address);</pre><pre>if (asn != 0) { // Successfully mapped to an ASN</pre><pre>vchRet.push_back(NET_IPV6); // Use IPv6 network class</pre><pre>for (int i = 0; i &lt; 4; i++) {</pre><pre>vchRet.push_back((asn &gt;&gt; (8 * i)) &amp; 0xFF); // Push 4 bytes of ASN</pre><pre>}</pre><pre>return vchRet;</pre><pre>}</pre><pre>// Fallback to /16 or /32 bucketing</pre><pre>// …</pre><pre>}</pre><p><strong>The key insight:</strong> If ASN mapping succeeds, the returned “group” is just the ASN number. Two addresses in the same AS will always return the same group, regardless of how different their IP addresses look.</p><h4>5. Looking Up an Address (`netgroup.cpp:81–112`)</h4><pre>cpp</pre><pre>uint32_t NetGroupManager::GetMappedAS(const CNetAddr&amp; address) const</pre><pre>{</pre><pre>if (m_asmap.size() == 0 || (net_class != NET_IPV4 &amp;&amp; net_class != NET_IPV6)) {</pre><pre>return 0; // No ASN map loaded, or address type not supported</pre><pre>}</pre><pre>// Convert address to 128-bit representation</pre><pre>std::vector&lt;bool&gt; ip_bits(128);</pre><pre>// … convert IP to bit vector …</pre><pre>// Interpret the ASN map as a program</pre><pre>uint32_t mapped_as = Interpret(m_asmap, ip_bits);</pre><pre>return mapped_as;</pre><pre>}</pre><p>`Interpret` is the virtual machine that executes the ASN map program (described earlier).</p><h4>The Full Execution Flow</h4><blockquote>```</blockquote><blockquote>User starts Bitcoin Core with -asmap=ip_asn.map</blockquote><blockquote>↓</blockquote><blockquote>init.cpp: Load and parse ASN map file</blockquote><blockquote>↓</blockquote><blockquote>SanityCheckASMap: Verify the map is well-formed</blockquote><blockquote>↓</blockquote><blockquote>Compute asmap_version hash</blockquote><blockquote>↓</blockquote><blockquote>Log: “Using asmap version &lt;hash&gt; for IP bucketing”</blockquote><blockquote>↓</blockquote><blockquote>Create NetGroupManager with the ASN map</blockquote><blockquote>↓</blockquote><blockquote>Create AddrMan with the NetGroupManager</blockquote><blockquote>↓</blockquote><blockquote>(Later) Peer address 203.0.113.5 is added</blockquote><blockquote>↓</blockquote><blockquote>AddrMan calls NetGroupManager::GetGroup(203.0.113.5)</blockquote><blockquote>↓</blockquote><blockquote>NetGroupManager::GetMappedAS converts IP to bit vector</blockquote><blockquote>↓</blockquote><blockquote>Interpret executes the ASN map program on the IP bits</blockquote><blockquote>↓</blockquote><blockquote>ASN 64496 is returned</blockquote><blockquote>↓</blockquote><blockquote>AddrMan buckets the address using AS64496 as the group identifier</blockquote><blockquote>```</blockquote><h3>Why This Test Matters</h3><p>1. <strong>Sybil Attack Resistance</strong></p><p>Without ASN mapping, an attacker with access to multiple `/16` ranges can pollute many buckets:</p><blockquote>```</blockquote><blockquote>Attacker controls:</blockquote><blockquote>10.0.x.x (65,536 IPs) → bucket group “10.0”</blockquote><blockquote>10.1.x.x (65,536 IPs) → bucket group “10.1”</blockquote><blockquote>10.2.x.x (65,536 IPs) → bucket group “10.2”</blockquote><blockquote>…</blockquote><p>That’s 256 different bucket groups from a single /8!</p><blockquote>```</blockquote><p>With ASN mapping:</p><blockquote>```</blockquote><blockquote>Attacker controls AS64512:</blockquote><blockquote>10.0.0.1 → AS64512</blockquote><blockquote>10.1.0.1 → AS64512</blockquote><blockquote>10.2.0.1 → AS64512</blockquote><blockquote>…</blockquote><p>All map to the same bucket group: AS64512</p><p>The attacker’s ability to pollute multiple buckets is dramatically reduced.</p><p>2. <strong>Optional Security Enhancement</strong></p><p>Not everyone needs ASN mapping. Home users with a few connections? `/16` bucketing is fine. Nodes in adversarial environments (exchanges, mining pools, high-value targets)? ASN mapping provides crucial additional protection.</p><p>Making it optional respects both use cases.</p><p>3. <strong>Graceful Error Handling</strong></p><p>All three error scenarios (missing file, empty file, unparsable file) produce clear error messages and refuse to start. This is the right choice , if the user requested ASN mapping, silently downgrading to `/16` bucketing would be a security failure.</p><p>4. <strong>Versioning and Auditability</strong></p><p>The ASN map version hash (logged at startup) allows users to:</p><p>- Verify they’re using an official map (compare hash with published values)</p><p>- Debug peer connection issues (“Did we update the map recently?”)</p><p>- Coordinate with other operators (“Are we both using the same ASN map?”)</p><h4>Real-World Scenarios</h4><p><strong>Scenario 1: Eclipse Attack on an Exchange</strong></p><p>An attacker wants to eclipse (isolate) a Bitcoin exchange to double-spend against them. The attacker:</p><p>1. Rents 10,000 IP addresses across 50 different `/16` ranges from various cloud providers</p><p>2. Connects to the exchange’s node from all 10,000 IPs</p><p>3. Uses various tricks to get those IPs into the exchange’s AddrMan</p><p>4. Eventually, the exchange restarts and primarily connects to the attacker’s IPs</p><p><strong>With ASN mapping:</strong> The exchange would see that all 10,000 IPs belong to just 3 or 4 cloud providers (Amazon, Google, DigitalOcean). AddrMan would deprioritize them, ensuring the exchange maintains diverse connections.</p><p><strong>Scenario 2: Running a Node Behind a Datacenter NAT</strong></p><p>You run a Bitcoin Core node in a datacenter. Most of your peers are also in datacenters (because that’s where many nodes are hosted). Without ASN mapping, your node might think it has 50 diverse peers, when in reality 40 of them are in the same Amazon region.</p><p><strong>With ASN mapping:</strong> Your node realizes that most of its peers are in AS16509 (Amazon) and actively seeks connections to peers in other ASNs, improving network diversity.</p><p><strong>Scenario 3: Monitoring Network Health</strong></p><p>You’re a researcher studying Bitcoin’s network topology. You want to know: “How centralized is the network? Are most nodes concentrated in a few ASNs?”</p><p><strong>With ASN mapping and the health check:</strong> You can easily see that your node’s 100 peers are spread across only 15 ASNs, with 60% in just 3 ASNs. That’s valuable data about network centralization.</p><h4>Key Takeaways</h4><p>1. <strong>ASN mapping is a Sybil resistance mechanism</strong> — it groups IP addresses by the organization that controls them, not just by IP prefix</p><p>2. <strong>The ASN map is a compressed decision tree</strong> — a tiny program that maps 128-bit IPs to 32-bit ASNs in just a few megabytes</p><p>3. <strong>ASN mapping is optional</strong> — users can enable it with `-asmap` or stick with simpler `/16` bucketing</p><p>4. <strong>Error handling is strict</strong> — missing or corrupted ASN maps are fatal errors when explicitly requested, preventing silent security downgrades</p><p>5. <strong>The version hash enables coordination</strong> — nodes can verify they’re using the same ASN map by comparing hashes</p><p>6. <strong>The health check provides visibility</strong> — users can see how diverse their peer connections really are</p><p>7. <strong>The test is comprehensive</strong> — it covers all configuration methods (absolute path, relative path, default file), all error cases (missing, empty, unparsable), and the interaction with AddrMan persistence</p><h4>Conclusion</h4><p>The `feature_asmap.py` test demonstrates Bitcoin Core’s commitment to Sybil attack resistance. By making ASN mapping optional, well-tested, and error-resistant, Bitcoin Core gives users a powerful tool to defend against sophisticated attackers who control large IP ranges.</p><p>The test reflects a mature understanding of operational security:</p><p>- <strong>Make security features opt-in</strong> (don’t break simple deployments)</p><p>- <strong>Fail loudly when security features are requested but can’t be delivered</strong> (don’t silently downgrade)</p><p>- <strong>Provide visibility into how the feature is working</strong> (health checks and version hashes)</p><p>- <strong>Handle all error cases gracefully</strong> (missing files, corrupted files, wrong paths)</p><p>For developers building any distributed system, the lessons here are universal: <strong>network topology reveals hidden relationships between seemingly independent identities.</strong> Whether you’re defending against bot farms, sockpuppets, or Sybil attacks, understanding the physical or organizational structure beneath the logical identities is crucial.</p><h4>References</h4><p><strong>Bitcoin Core Source Code</strong></p><p><a href="https://github.com/bitcoin/bitcoin/blob/master/test/functional/feature_asmap.py">https://github.com/bitcoin/bitcoin/blob/master/test/functional/feature_asmap.py</a></p><p>- <strong>ASMap utility functions:</strong> `src/util/asmap.h` and `src/util/asmap.cpp` — Core ASN map interpretation and validation logic</p><p>- <a href="https://github.com/bitcoin/bitcoin/blob/master/src/util/asmap.h">https://github.com/bitcoin/bitcoin/blob/master/src/util/asmap.h</a></p><p>- <a href="https://github.com/bitcoin/bitcoin/blob/master/src/util/asmap.cpp">https://github.com/bitcoin/bitcoin/blob/master/src/util/asmap.cpp</a></p><p>- <strong>Network group management:</strong> `src/netgroup.h` and `src/netgroup.cpp` — Integration of ASN mapping with peer bucketing</p><p>- <a href="https://github.com/bitcoin/bitcoin/blob/master/src/netgroup.h">https://github.com/bitcoin/bitcoin/blob/master/src/netgroup.h</a></p><p>- <a href="https://github.com/bitcoin/bitcoin/blob/master/src/netgroup.cpp">https://github.com/bitcoin/bitcoin/blob/master/src/netgroup.cpp</a></p><p>- <strong>Initialization logic:</strong> `src/init.cpp` (lines 1514–1538) — ASN map loading and error handling</p><p>- <a href="https://github.com/bitcoin/bitcoin/blob/master/src/init.cpp#L1514-L1538">https://github.com/bitcoin/bitcoin/blob/master/src/init.cpp#L1514-L1538</a></p><p>- <strong>Address manager:</strong> `src/addrman.h` and `src/addrman.cpp` — Uses network groups for peer bucketing</p><p>- <a href="https://github.com/bitcoin/bitcoin/blob/master/src/addrman.h">https://github.com/bitcoin/bitcoin/blob/master/src/addrman.h</a></p><p>- <a href="https://github.com/bitcoin/bitcoin/blob/master/src/addrman.cpp">https://github.com/bitcoin/bitcoin/blob/master/src/addrman.cpp</a></p><p>- <strong>Test data:</strong> `src/test/data/asmap.raw` — 59-byte skeleton ASN map used in tests</p><p>- <a href="https://github.com/bitcoin/bitcoin/blob/master/src/test/data/asmap.raw">https://github.com/bitcoin/bitcoin/blob/master/src/test/data/asmap.raw</a></p><h4>Bitcoin Improvement Proposals</h4><p>- <strong>BIP 155 (addrv2):</strong> <a href="https://github.com/bitcoin/bips/blob/master/bip-0155.mediawiki">https://github.com/bitcoin/bips/blob/master/bip-0155.mediawiki</a> — Extended address format supporting Tor v3 and future address types</p><h4>Research Papers and Documentation</h4><p>- <strong>Eclipse Attacks on Bitcoin’s Peer-to-Peer Network:</strong> Heilman et al. (2015) — Foundational research on eclipse attacks that motivates ASN-based bucketing</p><p>- Paper: <a href="https://www.usenix.org/node/190891">https://www.usenix.org/node/190891</a></p><p>- Shows how attackers with control over IP ranges can isolate Bitcoin nodes</p><p>- <strong>Erebus Attack:</strong> Tran et al. (2020) — Demonstrates large-scale eclipse attacks via BGP hijacking, further motivating ASN awareness</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91ac200c4179" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deconstructing Bitcoin Core Tests]]></title>
            <link>https://medium.com/@wandiamugo/deconstructing-bitcoin-core-tests-371eb0be2d63?source=rss-19a686aeb31e------2</link>
            <guid isPermaLink="false">https://medium.com/p/371eb0be2d63</guid>
            <dc:creator><![CDATA[Wandia Mugo]]></dc:creator>
            <pubDate>Mon, 09 Feb 2026 09:45:19 GMT</pubDate>
            <atom:updated>2026-02-11T09:52:22.425Z</atom:updated>
            <content:encoded><![CDATA[<h4>Day 3: Understanding feature_anchors.py — Bitcoin Core’s Emergency Contacts</h4><p><strong>Test File:</strong> `bitcoin/test/functional/feature_anchors.py`</p><p><strong>Category:</strong> Feature Tests</p><p><strong>Complexity:</strong> Moderate</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4KwptoO8JiXpfjNhD66p4Q.jpeg" /></figure><h3>Introduction</h3><h4>The Emergency Contact Analogy</h4><p>Imagine your phone crashes and reboots. When it comes back up, it needs to reconnect to your mobile network. But here’s the problem… there are thousands of cell towers out there, and most of them might be unreliable or even malicious. So your phone has a clever trick: before it shut down last time, it saved the addresses of the two most reliable towers it was connected to. When it reboots, it tries those first.</p><p>Bitcoin Core does exactly the same thing. When a Bitcoin node shuts down gracefully, it saves a small list of “anchor” peers — specifically, the peers it had <strong>block-relay-only connections</strong> with. When it starts back up, it immediately tries to reconnect to those anchors before doing anything else.</p><p>Why only block-relay-only connections? Because those are the most trustworthy. They don’t gossip about transactions or send unsolicited data. They just relay blocks — the bare minimum needed to stay in sync with the network. If you’re going to trust any peers on restart, you trust those.</p><h4>Why This Matters for Developers</h4><p>This is a masterclass in <strong>graceful degradation</strong> and <strong>bootstrap security</strong>. Consider the alternatives:</p><p>1. <strong>No anchors at all</strong> — Every time your node restarts, it starts from scratch with DNS seeds or hardcoded addresses. This is slow and makes you vulnerable during those critical first moments of reconnection.</p><p>2. <strong>Save all peers</strong> — This bloats your anchor file and defeats the purpose. You want a small, curated list of the best connections, not every random peer you’ve ever met.</p><p>3. <strong>Save inbound connections</strong> — Bad idea. Inbound connections are initiated by others, which means an attacker can flood your node with connections just before shutdown, pollute your anchor file, and then be your first connections on restart. Block-relay-only outbound connections are initiated by you, which makes them harder to manipulate.</p><p>This test teaches a principle that applies everywhere in distributed systems: <strong>when bootstrapping, start with your most trustworthy connections first, and keep that list small and curated.</strong></p><h4>The Technical Version</h4><p>Bitcoin Core’s anchor mechanism persists a subset of peer addresses to `anchors.dat` on graceful shutdown. On startup, it attempts to reconnect to these anchors before initiating normal peer discovery. The test verifies that:</p><p>1. Only block-relay-only outbound connections are saved to `anchors.dat`</p><p>2. Corrupted anchor files don’t crash the node</p><p>3. The file supports both IPv4 and addrv2 formats (including Tor v3 addresses)</p><p>4. The node correctly validates and attempts reconnection to anchors on restart</p><h4>What Are Anchors and Why Do They Matter?</h4><p>Before diving into the test, let’s understand the problem anchors solve.</p><h4>The Cold Start Problem</h4><p>When a Bitcoin node starts up, it needs to connect to peers. But where does it find them? There are a few options:</p><p>1. <strong>DNS seeds</strong> — Hardcoded DNS names that return lists of Bitcoin nodes. This works, but it’s slow and relies on external infrastructure.</p><p>2. <strong>Hardcoded IPs</strong> — Some Bitcoin implementations have fallback IP addresses baked into the code. This is brittle and can become outdated quickly.</p><p>3. <strong>Peer address database</strong> — Bitcoin Core maintains `peers.dat`, which stores thousands of addresses it’s learned about over time. But when you first start up, you don’t know which of these are currently online or reliable.</p><p>4. <strong>Anchors</strong> — A small list (typically 2) of the peers you were most recently connected to via block-relay-only connections. These are likely still online, trustworthy, and fast.</p><p>Anchors are your “emergency contacts.” They’re not a replacement for peer discovery — they’re a head start.</p><h4>What Makes a Good Anchor?</h4><p>Not all connections are created equal. Here’s why Bitcoin Core specifically saves <strong>block-relay-only</strong> connections:</p><p><strong>Block-relay-only connections:</strong></p><p>- Don’t relay transactions (less attack surface)</p><p>- Are initiated by you (harder for attackers to pollute)</p><p>- Are typically long-lived and stable</p><p>- Serve one purpose: keep you in sync with the blockchain</p><p><strong>Inbound connections:</strong></p><p>- Are initiated by others (attackers can flood you)</p><p>- Might be short-lived or opportunistic</p><p>- Could be adversarial (eclipse attack risk)</p><p><strong>Regular outbound connections:</strong></p><p>- Relay transactions and addresses (more chatty)</p><p>- More likely to churn (disconnect/reconnect frequently)</p><p>By saving only block-relay-only peers, Bitcoin Core ensures that your anchors are the most reliable, least manipulable subset of your peer set.</p><h4>The Test Structure</h4><p>The test runs through three major scenarios:</p><p><strong>Part 1: Basic Anchor Persistence (Lines 26–75)</strong></p><p><strong>What it tests:</strong> Do only block-relay-only connections get saved to `anchors.dat`?</p><p><strong>Part 2: Corruption Handling (Lines 77–88)</strong></p><p><strong>What it tests:</strong> Does a corrupted anchor file crash the node, or is it handled gracefully?</p><p><strong>Part 3: Addrv2 Support (Lines 90–140)</strong></p><p><strong>What it tests:</strong> Can the anchor file store modern address formats, including 256-bit Tor v3 addresses?</p><p>Let’s walk through each.</p><h3>Part 1: Basic Anchor Persistence</h3><p><strong>The Setup (Lines 26–44)</strong></p><pre>python</pre><pre>node_anchors_path = self.nodes[0].chain_path / “anchors.dat”</pre><pre>self.log.info(“When node starts, check if anchors.dat doesn’t exist”)</pre><pre>assert not os.path.exists(node_anchors_path)</pre><p>The test confirms that on a fresh start, there’s no `anchors.dat` file. This makes sense — you can’t have anchors if you’ve never shut down before.</p><p>Next, the test adds two types of connections:</p><pre>python</pre><pre>self.log.info(f”Add {BLOCK_RELAY_CONNECTIONS} block-relay-only connections to node”)</pre><pre>for i in range(BLOCK_RELAY_CONNECTIONS):</pre><pre>self.nodes[0].add_outbound_p2p_connection(</pre><pre>P2PInterface(), p2p_idx=i, connection_type=”block-relay-only”</pre><pre>)</pre><pre>self.log.info(f”Add {INBOUND_CONNECTIONS} inbound connections to node”)</pre><pre>for i in range(INBOUND_CONNECTIONS):</pre><pre>self.nodes[0].add_p2p_connection(P2PInterface())</pre><p>Now the node has:</p><p>- **2 block-relay-only outbound connections** (the anchors-to-be)</p><p>- **5 inbound connections** (should NOT be saved as anchors)</p><p>The test confirms the connection counts:</p><pre>python</pre><pre>check_node_connections(node=self.nodes[0], num_in=5, num_out=2)</pre><h4><strong>Extracting Peer Information (Lines 46–58)</strong></h4><p>The test uses a clever trick to identify which peers are which. Since all connections in the test environment use `127.0.0.1`, the test distinguishes peers by their port numbers:</p><pre>python</pre><pre>ip = “7f000001” # 127.0.0.1 in hex</pre><pre>block_relay_nodes_port = []</pre><pre>inbound_nodes_port = []</pre><pre>for p in self.nodes[0].getpeerinfo():</pre><pre>addr_split = p[“addr”].split(“:”)</pre><pre>if p[“connection_type”] == “block-relay-only”:</pre><pre>block_relay_nodes_port.append(hex(int(addr_split[1]))[2:])</pre><pre>else:</pre><pre>inbound_nodes_port.append(hex(int(addr_split[1]))[2:])</pre><p>This builds two lists:</p><p>- `block_relay_nodes_port`: ports of the 2 block-relay-only connections</p><p>- `inbound_nodes_port`: ports of the 5 inbound connections</p><h4>The Shutdown and Verification (Lines 60–75)</h4><pre>python</pre><pre>self.log.debug(“Stop node”)</pre><pre>self.stop_node(0)</pre><pre># It should contain only the block-relay-only addresses</pre><pre>self.log.info(“Check the addresses in anchors.dat”)</pre><pre>with open(node_anchors_path, “rb”) as file_handler:</pre><pre>anchors = file_handler.read()</pre><pre>anchors_hex = anchors.hex()</pre><pre>for port in block_relay_nodes_port:</pre><pre>ip_port = ip + port</pre><pre>assert ip_port in anchors_hex</pre><pre>for port in inbound_nodes_port:</pre><pre>ip_port = ip + port</pre><pre>assert ip_port not in anchors_hex</pre><p><strong>Key assertion:</strong> The anchor file contains the 2 block-relay-only connections and NONE of the 5 inbound connections.</p><p>This confirms the core behavior: <strong>**anchors are exclusively block-relay-only peers.**</strong></p><h3>Part 2: Corruption Handling</h3><h4>The Perturbation (Lines 77–88)</h4><pre>python</pre><pre>self.log.info(“Perturb anchors.dat to test it doesn’t throw an error during initialization”)</pre><pre>with self.nodes[0].assert_debug_log([“0 block-relay-only anchors will be tried for connections.”]):</pre><pre>with open(node_anchors_path, “wb”) as out_file_handler:</pre><pre>tweaked_contents = bytearray(anchors)</pre><pre>tweaked_contents[20:20] = b’1&#39;</pre><pre>out_file_handler.write(bytes(tweaked_contents))</pre><pre>self.log.debug(“Start node”)</pre><pre>self.start_node(0)</pre><p><strong>What’s happening here:</strong></p><p>1. The test reads the valid `anchors.dat` file</p><p>2. It inserts a single byte (`b’1&#39;`) at position 20, corrupting the structure</p><p>3. It restarts the node</p><p><strong>Expected behavior:</strong></p><p>- The node should NOT crash</p><p>- The node should log: `”0 block-relay-only anchors will be tried for connections.”`</p><p>- The node should delete the corrupted file</p><pre>python</pre><pre>self.log.info(“When node starts, check if anchors.dat doesn’t exist anymore”)</pre><pre>assert not os.path.exists(node_anchors_path)</pre><p><strong>Why this matters:</strong> In production, `anchors.dat` can become corrupted due to disk errors, unexpected shutdowns, or filesystem issues. The node must detect this and recover gracefully rather than crashing on startup.</p><p><strong>The recovery strategy:</strong></p><p>1. Try to parse `anchors.dat`</p><p>2. If parsing fails, log a warning</p><p>3. Delete the corrupted file</p><p>4. Continue with normal peer discovery (no anchors this time)</p><p>This is the same philosophy we saw in `feature_addrman.py` — <strong>fail loudly, recover gracefully, and never let corrupted data take down the node.</strong></p><h3>Part 3: Addrv2 Support for Tor v3</h3><h4>Why Addrv2?</h4><p>Bitcoin addresses come in many flavors:</p><p>- <strong>IPv4:</strong> 32-bit addresses (e.g., `127.0.0.1`)</p><p>- <strong>IPv6:</strong> 128-bit addresses (e.g., `::1`)</p><p>- <strong>Tor v3:</strong> 256-bit addresses (e.g., `pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion`)</p><p>The original Bitcoin address format couldn’t handle Tor v3’s 256-bit addresses. <strong>**Addrv2**</strong> (BIP 155) was introduced to support arbitrary-length network addresses.</p><p>The test ensures that `anchors.dat` correctly stores and retrieves Tor v3 addresses.</p><h4>Setting Up the Tor Proxy (Lines 90–99)</h4><pre>python</pre><pre>self.log.info(“Ensure addrv2 support”)</pre><pre>onion_conf = Socks5Configuration()</pre><pre>onion_conf.auth = True</pre><pre>onion_conf.unauth = True</pre><pre>onion_conf.addr = (‘127.0.0.1’, p2p_port(self.num_nodes))</pre><pre>onion_conf.keep_alive = True</pre><pre>onion_proxy = Socks5Server(onion_conf)</pre><pre>onion_proxy.start()</pre><pre>self.restart_node(0, extra_args=[f”-onion={onion_conf.addr[0]}:{onion_conf.addr[1]}”])</pre><p><strong>What’s happening:</strong></p><p>- A SOCKS5 proxy is started on a local port</p><p>- The node is restarted with `-onion=&lt;proxy&gt;`, telling it to route Tor connections through the proxy</p><p>- This allows the test to simulate a Tor connection without actually connecting to the Tor network</p><h4>Adding a Tor Block-Relay-Only Connection (Lines 101–102)</h4><pre>python</pre><pre>self.log.info(“Add 256-bit-address block-relay-only connections to node”)</pre><pre>self.nodes[0].addconnection(ONION_ADDR, ‘block-relay-only’, v2transport=False)</pre><p>`ONION_ADDR` is defined at the top of the file:</p><pre>python</pre><pre>ONION_ADDR = “pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion:8333”</pre><p>The node now has a block-relay-only connection to a Tor v3 address.</p><h4>Shutdown and Verification (Lines 104–127)</h4><pre>python</pre><pre>self.log.debug(“Stop node”)</pre><pre>with self.nodes[0].assert_debug_log([“DumpAnchors: Flush 1 outbound block-relay-only peer addresses to anchors.dat”]):</pre><pre>self.stop_node(0)</pre><pre>onion_proxy.stop()</pre><p>The node shuts down and writes the Tor address to `anchors.dat`.</p><p>Now the test verifies the file format:</p><pre>python</pre><pre>self.log.info(“Check for addrv2 addresses in anchors.dat”)</pre><pre>caddr = CAddress()</pre><pre>caddr.net = CAddress.NET_TORV3</pre><pre>caddr.ip, port_str = ONION_ADDR.split(“:”)</pre><pre>caddr.port = int(port_str)</pre><pre># TorV3 addrv2 serialization:</pre><pre># time(4) | services(1) | networkID(1) | address length(1) | address(32)</pre><pre>expected_pubkey = caddr.serialize_v2()[7:39].hex()</pre><p><strong>What’s happening:</strong></p><p>1. A `CAddress` object is constructed with the Tor v3 address</p><p>2. The test serializes it using the addrv2 format</p><p>3. It extracts bytes 7–39, which contain the 32-byte Tor public key</p><p><strong>The file structure:</strong></p><blockquote>```</blockquote><blockquote>[4 bytes: timestamp]</blockquote><blockquote>[1 byte: services]</blockquote><blockquote>[1 byte: networkID] &lt;- identifies this as Tor v3</blockquote><blockquote>[1 byte: address length] &lt;- should be 32</blockquote><blockquote>[32 bytes: address] &lt;- the Tor public key</blockquote><blockquote>```</blockquote><p>The test reads `anchors.dat` and confirms:</p><pre>python</pre><pre>services_index = 4 + 1 + 4 + 4 # magic, vector length, version, nTime</pre><pre>data = bytes()</pre><pre>with open(node_anchors_path, “rb”) as file_handler:</pre><pre>data = file_handler.read()</pre><pre>assert_equal(data[services_index], 0x00) # services == NONE</pre><pre>anchors2 = data.hex()</pre><pre>assert expected_pubkey in anchors2</pre><p><strong>Key assertions:</strong></p><p>1. The Tor public key is present in the anchor file</p><p>2. The services byte is `0x00` (because the test never completed a handshake)</p><h4>Modifying the Services Byte (Lines 129–136)</h4><p>Here’s where it gets interesting:</p><pre>python</pre><pre>with open(node_anchors_path, “wb”) as file_handler:</pre><pre># Modify service flags for this address even though we never connected to it.</pre><pre># This is necessary because on restart we will not attempt an anchor connection</pre><pre># to a host without our required services, even if its address is in the anchors.dat file</pre><pre>new_data = bytearray(data)[:-32]</pre><pre>new_data[services_index] = P2P_SERVICES</pre><pre>new_data_hash = hash256(new_data)</pre><pre>file_handler.write(new_data + new_data_hash)</pre><p><strong>Why this step?</strong></p><p>Bitcoin Core won’t attempt to connect to an anchor peer that doesn’t advertise the services it needs (like `NODE_NETWORK`). Since the test never completed a handshake, the services byte is `0x00`. To test that the node actually tries to reconnect, the test manually sets the services byte to `P2P_SERVICES`.</p><p><strong>The checksum update:</strong></p><p>- The anchor file has a trailing 32-byte checksum (double SHA-256 hash)</p><p>- After modifying the services byte, the test recomputes the hash and appends it</p><h4>Reconnection Test (Lines 138–140)</h4><pre>python</pre><pre>self.log.info(“Restarting node attempts to reconnect to anchors”)</pre><pre>with self.nodes[0].assert_debug_log([f”Trying to make an anchor connection to {ONION_ADDR}”]):</pre><pre>self.start_node(0, extra_args=[f”-onion={onion_conf.addr[0]}:{onion_conf.addr[1]}”])</pre><p>The node restarts and immediately tries to connect to the Tor anchor. The test confirms this by checking the debug log for the expected message.</p><p><strong>This proves:</strong></p><p>1. `anchors.dat` correctly stores Tor v3 addresses in addrv2 format</p><p>2. On restart, Bitcoin Core reads the addrv2 format and attempts reconnection</p><p>3. The anchor mechanism works for non-IPv4 addresses</p><h3>Key Takeaways for Developers</h3><h4>1. Curate Your Bootstrap Peers</h4><p>When your application needs to reconnect to a network or cluster, don’t save every connection you’ve ever made. Save a small list of the most trustworthy, long-lived connections. In Bitcoin Core’s case, that’s block-relay-only peers.</p><h4>2. Graceful Degradation on Corruption</h4><p>Corrupted files happen. Your application should:</p><p>- Detect corruption early (checksums, magic bytes, version checks)</p><p>- Log the error clearly</p><p>- Fall back to a safe default (in this case, normal peer discovery)</p><p>- Never crash on startup due to corrupted saved state</p><h4>3. Future-Proof Your Serialization Format</h4><p>The addrv2 format is a great example of extensible design. Instead of hardcoding IPv4 support, it includes a “network type” byte and a “length” byte, allowing it to support any address format — even ones that don’t exist yet.</p><h4>4. Think About Attack Vectors</h4><p>Why does Bitcoin Core only save outbound block-relay-only connections? Because inbound connections are attacker-controlled. If you saved inbound connections, an attacker could:</p><p>1. Open many inbound connections to your node</p><p>2. Wait for you to shut down</p><p>3. Be the first peers you connect to on restart (eclipse attack)</p><p>By limiting anchors to outbound block-relay-only connections, Bitcoin Core makes this attack much harder.</p><h3>Connections to Other Tests</h3><h4>Relationship to feature_addrman.py</h4><p>While `feature_addrman.py` tests the long-term peer address database (`peers.dat`), `feature_anchors.py` tests the short-term emergency contact list (`anchors.dat`).</p><p>- <strong>peers.dat:</strong> Thousands of addresses learned over time, used for general peer discovery</p><p>- <strong>anchors.dat:</strong> 1–2 addresses from your most recent session, used for fast reconnection on restart</p><p>Both tests share the same philosophy: validate everything you load from disk, and never let corrupted data crash the node.</p><h4>Relationship to p2p_* Tests</h4><p>Many p2p tests verify connection behavior (handshakes, message handling, peer selection). This test is unique in that it focuses on the <strong>persistence and recovery</strong> of connections across restarts.</p><h3>The Bigger Picture: Network Resilience</h3><p>Anchors are part of Bitcoin Core’s defense-in-depth strategy for network resilience. Consider the attack scenario:</p><p><strong>Without anchors:</strong></p><p>1. Attacker isolates your node (firewall rules, DNS poisoning, etc.)</p><p>2. You restart your node</p><p>3. Your node uses DNS seeds to find peers</p><p>4. Attacker controls the DNS response or floods your connection slots</p><p>5. You’re now eclipsed (only connected to attacker nodes)</p><p><strong>With anchors:</strong></p><p>1. Attacker isolates your node</p><p>2. You restart your node</p><p>3. Your node immediately tries to reconnect to the 2 block-relay-only peers from your last session</p><p>4. If even one succeeds, you have a trustworthy view of the blockchain</p><p>5. Eclipse attack is much harder</p><p>Anchors don’t prevent eclipse attacks entirely, but they raise the bar. An attacker must not only isolate you <em>*now*</em> but also ensure you weren’t connected to any honest peers <em>*before*</em> you restarted.</p><h4>References</h4><ol><li>Bitcoin Core repository: <a href="https://github.com/bitcoin/bitcoin">https://github.com/bitcoin/bitcoin</a></li><li>Bitcoin Core Test Documentation: <a href="https://github.com/bitcoin/bitcoin/blob/master/test/functional/feature_anchors.py">https://github.com/bitcoin/bitcoin/blob/master/test/functional/feature_anchors.py</a></li></ol><h4>Conclusion</h4><p>`feature_anchors.py` is a short test (145 lines), but it encodes deep wisdom about distributed systems:</p><p>1. <strong>Bootstrap security matters.</strong> The first connections you make on startup are critical. Choose them carefully.</p><p>2. <strong>Small, curated lists are powerful.</strong> You don’t need to save everything. A few high-quality anchors are better than a hundred random peers.</p><p>3. <strong>Corruption is inevitable.</strong> Plan for it. Detect it. Recover from it gracefully.</p><p>4. <strong>Extensibility is key.</strong> The addrv2 format future-proofs Bitcoin Core for network types that don’t exist yet.</p><p>Next time you build a distributed system — whether it’s a blockchain node, a database cluster, or a chat application — ask yourself: <em>*”What are my anchors? How do I bootstrap securely? What happens if my saved state is corrupted?”*</em></p><p>Bitcoin Core’s answer is elegant: save a tiny list of your best connections, validate it on load, and fail gracefully if anything goes wrong.</p><h4>Further Reading</h4><p>- <strong>BIP 155 (addrv2):</strong> <a href="https://github.com/bitcoin/bips/blob/master/bip-0155.mediawiki">https://github.com/bitcoin/bips/blob/master/bip-0155.mediawiki</a></p><p>- <strong>Bitcoin Core’s anchor code:</strong> `src/net.cpp` (search for `DumpAnchors`)</p><p>- <strong>Eclipse attacks on Bitcoin:</strong> Heilman et al., “Eclipse Attacks on Bitcoin’s Peer-to-Peer Network” (2015)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=371eb0be2d63" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deconstructing Bitcoin Core Tests]]></title>
            <link>https://medium.com/@wandiamugo/deconstructing-bitcoin-core-tests-e751f213f736?source=rss-19a686aeb31e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e751f213f736</guid>
            <dc:creator><![CDATA[Wandia Mugo]]></dc:creator>
            <pubDate>Thu, 05 Feb 2026 10:40:03 GMT</pubDate>
            <atom:updated>2026-02-11T09:51:18.842Z</atom:updated>
            <content:encoded><![CDATA[<h4>Day 2: Understanding feature_addrman.py — Bitcoin Core’s Address Book</h4><p><strong>Test File:</strong> `bitcoin/test/functional/feature_addrman.py`</p><p><strong>Category:</strong> Feature Tests</p><p><strong>Complexity:</strong> Moderate</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2YtXsygd5cq9CuSAy826FQ.jpeg" /></figure><h3>Introduction</h3><h4>The Contact List Analogy</h4><p>Imagine you have a phone. You’ve saved hundreds of contacts over the years — friends, family, work colleagues, the woman who fixed your car. Now imagine your phone crashes and recovers from a backup. When it loads your contact list back, a few things could go wrong:</p><p>1. <strong>The backup file is from a future version of the app </strong>— maybe your friend backed up their contacts on a newer phone and sent you the file. Your phone doesn’t understand the new format. What should it do? Crash? No — it should say “I can’t read this, but I’ll keep my old contacts safe as a backup and start fresh.”</p><p>2. <strong>The backup is from the wrong phone</strong> — you accidentally loaded contacts meant for your Android phone onto your iPhone. The file looks like a contact list, but the header says “Android.” Your phone should reject it immediately.</p><p>3. <strong>Someone tampered with the file</strong> — maybe it got corrupted during download, or someone mischievously edited it. The file has a “seal” (like a wax seal on a letter) that you can check. If the seal is broken, you know something is wrong.</p><p>4. <strong>The backup says it has 500 contacts, but there are actually 50</strong> — the numbers in the header don’t match reality. That’s a red flag for corruption.</p><p>5. <strong>The backup file is simply missing</strong> — no problem. Just start with an empty contact list and build it up again.</p><p>This is exactly what `feature_addrman.py` tests. Bitcoin Core keeps a file called `peers.dat` — its address book of other nodes on the network. This test deliberately breaks that file in every conceivable way and makes sure Bitcoin Core handles each failure gracefully.</p><h4>Why This Matters for Developers</h4><p>Every application that persists state to disk needs to survive a corrupted save file. Think about it: you’ve probably seen a video game that corrupted your save file, or a Word document that opened as garbled text. The difference is stakes. If your save file is corrupt, you lose a few hours of gameplay. If Bitcoin Core’s address book is corrupt and the node doesn’t notice, it might connect to the wrong peers, or worse — silently operate with bad data.</p><p>This test teaches a universal engineering principle: <strong>validate everything you load from disk, fail loudly when something is wrong, and give the user a clear path to recovery.</strong></p><h4>The Technical Version</h4><p>Bitcoin Core’s Address Manager (`AddrMan`) is the subsystem responsible for discovering, tracking, and connecting to peer nodes on the Bitcoin network. It maintains two tables — a “new” table for recently discovered addresses and a “tried” table for addresses that have been successfully connected to. All of this state is persisted to a file called `peers.dat`. The `feature_addrman.py` test verifies that Bitcoin Core correctly validates `peers.dat` on startup, rejecting every possible form of corruption while gracefully handling version mismatches and missing files.</p><h4>What Is AddrMan and Why Does It Matter?</h4><p>Before diving into the test, let’s understand what we’re protecting.</p><h4>The Two Tables</h4><p>Think of AddrMan as a two-tier filing system:</p><p>- <strong>The “New” table</strong> is like your “Maybe” pile. These are addresses you’ve heard about but haven’t actually connected to yet. Someone on the network told you about them, but you don’t know if they’re real or reliable. There are <strong>1,024 buckets</strong>, each holding up to <strong>64 addresses</strong> — a maximum of 65,536 slots.</p><p>- <strong>The “Tried” table</strong> is your “Trusted” list. These are addresses you’ve actually connected to and confirmed are real. There are <strong>256 buckets</strong>, each holding up to <strong>64 addresses</strong> — a maximum of 16,384 slots.</p><h4>The Secret Key (Bucket Key)</h4><p>Here’s where it gets interesting. Addresses aren’t just dumped randomly into buckets. Bitcoin Core uses a <strong>secret 256-bit key</strong> (`nKey`) — generated randomly when AddrMan is first created — to determine which bucket each address goes into. The key is like a secret recipe: given the same key and the same address, you’ll always get the same bucket. But without the key, you can’t predict the placement.</p><p>Why does this matter? It’s an <strong>anti-manipulation defense</strong>. If an attacker knew exactly which bucket an address would land in, they could flood that bucket with fake addresses to crowd out real ones (an attack called “poisoning”). The secret key makes the bucket placement unpredictable to outsiders.</p><h4>The File Format</h4><p>`peers.dat` is not just a raw dump of addresses. It’s a carefully structured file with:</p><p>1. <strong>Network magic bytes</strong> — 4 bytes that identify which Bitcoin network this file belongs to (mainnet, testnet, regtest, etc.)</p><p>2. <strong>Version and compatibility bytes</strong> — so that newer versions of Bitcoin Core can gracefully handle files from older (or newer) versions</p><p>3. <strong>The secret bucket key </strong>— the 256-bit `nKey` that determines bucket placement</p><p>4. <strong>Address counts</strong> — how many addresses are in the new and tried tables</p><p>5. <strong>The actual address data</strong> — every address with its metadata</p><p>6. <strong>Bucket assignments</strong> — which addresses are in which buckets</p><p>7. <strong>A SHA-256d checksum</strong> — a cryptographic “seal” over everything above, so any tampering is detected</p><h4>The Test: What Does It Do?</h4><p>The test runs a single node and manipulates `peers.dat` in various ways before each startup, checking that Bitcoin Core responds correctly every time.</p><h4>Helper Functions (Lines 16–46)</h4><pre>python</pre><pre>def serialize_addrman(</pre><pre>*,</pre><pre>format=1,</pre><pre>lowest_compatible=4,</pre><pre>net_magic=”regtest”,</pre><pre>bucket_key=1,</pre><pre>len_new=None,</pre><pre>len_tried=None,</pre><pre>mock_checksum=None,</pre><pre>):</pre><p>This is the test’s “forgery kit.” It constructs a `peers.dat` file from scratch with controllable parameters. By default it creates a valid (but empty) file. By tweaking individual parameters, the test can introduce exactly one specific type of corruption at a time — <em>like a surgeon making a precise incision.</em></p><p>`write_addrman` simply writes the output of `serialize_addrman` to the actual `peers.dat` path.</p><h4>Test 1: A Valid (Empty) AddrMan Loads Successfully (Lines 62–67)</h4><pre>python</pre><pre>self.log.info(“Check that mocked addrman is valid”)</pre><pre>self.stop_node(0)</pre><pre>write_addrman(peers_dat)</pre><pre>with self.nodes[0].assert_debug_log([“Loaded 0 addresses from peers.dat”]):</pre><pre>self.start_node(0, extra_args=[“-checkaddrman=1”])</pre><pre>assert_equal(self.nodes[0].getnodeaddresses(), [])</pre><p><strong>Think back to our anecdote:</strong> Before you test all the ways a contact list can break, you first make sure a perfectly normal contact list loads fine. This is the “sanity check” — the baseline. If this fails, everything else is meaningless.</p><p>The `-checkaddrman=1` flag forces Bitcoin Core to run its full consistency check (`CheckAddrman`) on every operation, not just probabilistically. This is like turning on “paranoid mode” for testing.</p><h4>Test 2: Negative `lowest_compatible` Is Rejected (Lines 69–78)</h4><pre>python</pre><pre>self.log.info(“Check that addrman with negative lowest_compatible cannot be read”)</pre><pre>write_addrman(peers_dat, lowest_compatible=-32)</pre><pre>self.nodes[0].assert_start_raises_init_error(…)</pre><p><strong>Our anecdote:</strong> Imagine someone hands you a document and says “this was written for version -32 of our software.” That doesn’t make sense — there’s no such thing as a negative version. It’s like finding a receipt dated the year -500. The document is clearly nonsense.</p><p>The `lowest_compatible` field tells Bitcoin Core the <em>*minimum*</em> version that can read this file. After the `INCOMPATIBILITY_BASE` (32) is added, the value should never go below 32. A value of 0 (from -32 + 32) is below that floor, so the node refuses to start.</p><h4>Test 3: A File From the Future Gets Backed Up (Lines 80–89)</h4><pre>python</pre><pre>self.log.info(“Check that addrman from future is overwritten with new addrman”)</pre><pre>write_addrman(peers_dat, lowest_compatible=111)</pre><pre>assert_equal(os.path.exists(peers_dat + “.bak”), False)</pre><pre>with self.nodes[0].assert_debug_log([</pre><pre>‘Creating new peers.dat because the file version was not compatible…’</pre><pre>]):</pre><pre>self.start_node(0)</pre><pre>assert_equal(os.path.exists(peers_dat + “.bak”), True)</pre><p><strong>Think back to our anecdote:</strong> You download a file from a friend who has a newer version of the app. Your app can’t read it. But instead of just deleting it (losing it forever), the app says: “I can’t read this, but I’ll rename it to `peers.dat.bak` so you don’t lose it, and I’ll start fresh.” That’s exactly what Bitcoin Core does here — graceful degradation with data preservation.</p><p>`lowest_compatible=111` means the file requires at least version 111 + 32 = 143 to read. Bitcoin Core’s current version is far below that, so it can’t read the file. Rather than crashing, it backs up the file and starts with an empty address book.</p><h4>Test 4: A Truncated File Is Rejected (Lines 91–98)</h4><pre>python</pre><pre>self.log.info(“Check that corrupt addrman cannot be read (EOF)”)</pre><pre>with open(peers_dat, “wb”) as f:</pre><pre>f.write(serialize_addrman()[:-1]) # remove the last byte</pre><pre>self.nodes[0].assert_start_raises_init_error(</pre><pre>expected_msg=init_error(“AutoFile::read: end of file.*”),</pre><pre>)</pre><p><strong>Our anecdote:</strong> Imagine downloading a movie and the download cuts off at 99.9%. You try to play it — it starts fine but then abruptly stops and crashes. That’s exactly this: the file is valid up until it suddenly ends one byte too early. Bitcoin Core hits the end of the file while still expecting more data and refuses to continue.</p><h4>Test 5: Wrong Network Magic Is Rejected (Lines 100–106)</h4><pre>python</pre><pre>self.log.info(“Check that corrupt addrman cannot be read (magic)”)</pre><pre>write_addrman(peers_dat, net_magic=”signet”)</pre><pre>self.nodes[0].assert_start_raises_init_error(</pre><pre>expected_msg=init_error(“Invalid network magic number”),</pre><pre>)</pre><p><strong>Our anecdote:</strong> This is like putting a US passport into the Canadian border scanner(I promise that I tried to find a better analogy). The document might be perfectly valid — but it’s for the wrong country. The first 4 bytes of `peers.dat` are a “magic number” that identifies which Bitcoin network the file belongs to. If you’re running a regtest node and someone drops in a signet `peers.dat`, the magic number won’t match and the node rejects it immediately. No guessing, no “maybe it’ll work” — instant rejection.</p><h4>Test 6: A Tampered Checksum Is Detected (Lines 108–114)</h4><pre>python</pre><pre>self.log.info(“Check that corrupt addrman cannot be read (checksum)”)</pre><pre>write_addrman(peers_dat, mock_checksum=b”ab” * 32)</pre><pre>self.nodes[0].assert_start_raises_init_error(</pre><pre>expected_msg=init_error(“Checksum mismatch, data corrupted”),</pre><pre>)</pre><p><strong>Our anecdote:</strong> Every time you order a product online, the package has a tracking number. When it arrives, the warehouse scans it and checks: does the number on the package match what we’re expecting? If someone swapped out the package with a different one, the numbers won’t match.</p><p>The checksum in `peers.dat` works the same way. Bitcoin Core computes a SHA-256d hash over the entire file content, then compares it to the checksum stored at the end of the file. Here, the test replaces the real checksum with `”ababab…”` — obviously wrong — and Bitcoin Core catches it instantly.</p><h4>Tests 7 &amp; 8: Out-of-Range Address Counts Are Caught (Lines 116–147)</h4><pre>python</pre><pre># len_tried = -1 (negative)</pre><pre>write_addrman(peers_dat, len_tried=-1)</pre><pre># len_tried = max + 1 (too large)</pre><pre>write_addrman(peers_dat, len_tried=max_len_tried + 1)</pre><pre># Same for len_new</pre><p><strong>The anecdote:</strong> Imagine a restaurant’s inventory system says it has -5 eggs, or 1,000,000 eggs. Both are obviously wrong. The header of `peers.dat` declares how many addresses are in each table. Bitcoin Core knows the physical limits: the tried table can hold at most `256 buckets × 64 slots = 16,384` addresses, and the new table can hold at most `1024 × 64 = 65,536`. Any count outside those bounds — negative or too large — is immediately flagged as corruption.</p><h4>Test 9: A Consistency Check Failure Is Caught (Lines 149–155)</h4><pre>python</pre><pre>self.log.info(“Check that corrupt addrman cannot be read (failed check)”)</pre><pre>write_addrman(peers_dat, bucket_key=0)</pre><pre>self.nodes[0].assert_start_raises_init_error(</pre><pre>expected_msg=init_error(“Corrupt data. Consistency check failed with code -16: .*”),</pre><pre>)</pre><p><strong>Our anecdote:</strong> Remember the secret key that determines which bucket each address lands in? Setting `bucket_key=0` (all zeros) is like using a “no key” on a lock — it’s not a valid key. Bitcoin Core’s consistency checker (`CheckAddrman`) re-derives every bucket placement using the key and compares it to what’s actually in the file. A null key triggers error code `-16`, which specifically means “nKey is null.” The check catches this before the node ever starts serving connections.</p><h4>Test 10: A Missing File Is Gracefully Recreated (Lines 157–159)</h4><pre>python</pre><pre>self.log.info(“Check that missing addrman is recreated”)</pre><pre>self.restart_node(0, clear_addrman=True)</pre><pre>assert_equal(self.nodes[0].getnodeaddresses(), [])</pre><p><strong>Our anecdote:</strong> You delete all your contacts. Your phone doesn’t crash — it just starts with an empty contact list and you build it back up over time. Bitcoin Core does the same: if `peers.dat` is simply missing, it creates a fresh empty one and starts discovering peers from scratch using DNS seeds.</p><h4>The C++ Implementation: How It All Works Under the Hood</h4><p><strong>1. The File Envelope (`addrdb.cpp`)</strong></p><p>`peers.dat` isn’t just raw address data — it’s wrapped in an envelope with integrity checks. The reading path in `DeserializeFileDB` (`addrdb.cpp`) does three things in order:</p><pre>cpp</pre><pre>// 1. Check network magic (first 4 bytes)</pre><pre>verifier &gt;&gt; pchMsgTmp;</pre><pre>if (pchMsgTmp != Params().MessageStart())</pre><pre>throw std::runtime_error{“Invalid network magic number”};</pre><pre>// 2. Deserialize the AddrMan payload (calls Unserialize)</pre><pre>verifier &gt;&gt; data;</pre><pre>// 3. Verify the trailing checksum</pre><pre>stream &gt;&gt; hashTmp;</pre><pre>if (hashTmp != verifier.GetHash())</pre><pre>throw std::runtime_error{“Checksum mismatch, data corrupted”};</pre><p>The `HashVerifier` wrapper transparently hashes every byte it reads, so by the time we reach step 3, it has already computed the hash of the entire file content. The stored checksum is compared against this computed hash. If even a single bit was flipped, the checksums won’t match.</p><p><strong>2. Version Compatibility (`addrman.cpp` — Unserialize)</strong></p><p>The first two bytes of the AddrMan payload are the version and compatibility fields:</p><pre>cpp</pre><pre>uint8_t uFormatVersion;</pre><pre>uint8_t uFormatCompatVersion;</pre><pre>s &gt;&gt; uFormatVersion &gt;&gt; uFormatCompatVersion;</pre><pre>if (uFormatCompatVersion &lt; INCOMPATIBILITY_BASE)</pre><pre>throw std::runtime_error{“Corrupted addrman database: The compat value is lower than expected…”};</pre><pre>if (uFormatCompatVersion &gt; INCOMPATIBILITY_BASE + FILE_FORMAT)</pre><pre>throw InvalidAddrManVersionError{…}; // caught specially: backup and recreate</pre><p>Two very different outcomes for two very different problems:</p><p>- <strong>Too old</strong> (below `INCOMPATIBILITY_BASE`): the file is corrupt — hard error, node won’t start.</p><p>- <strong>Too new</strong> (above current version): the file is from the future — soft error, back it up and start fresh.</p><p>This is a deliberate design choice. A file from the future <em>*might*</em> be valid — we just can’t read it yet. A file with a corrupted version field is definitely broken.</p><p><strong>3. The Consistency Check (`addrman.cpp` — `CheckAddrman`)</strong></p><p>After the file is fully deserialized, Bitcoin Core runs an exhaustive audit of the entire address database. This function checks over 20 different invariants, including:</p><p>- <strong>Every address in a bucket actually belongs there</strong> — it re-derives the bucket placement using `nKey` and verifies it matches where the address was placed</p><p>- <strong>Reference counts are correct</strong> — each “new” address knows how many bucket slots point to it; this is recomputed and verified</p><p>- <strong>No orphans</strong> — every address in `mapInfo` must be reachable from at least one bucket</p><p>- <strong>The key is not null</strong> — `nKey` must be a real random value (error code `-16`)</p><p>- <strong>Per-network counts match reality</strong> — the counts for each network (IPv4, IPv6, Tor, etc.) are verified against the actual data</p><p>The bucket placement functions use the secret key like a cryptographic hash:</p><pre>cpp</pre><pre>// Which tried bucket does this address go in?</pre><pre>int AddrInfo::GetTriedBucket(const uint256&amp; nKey, …) const {</pre><pre>uint64_t hash1 = Hash(nKey || address_key);</pre><pre>uint64_t hash2 = Hash(nKey || address_group || (hash1 % 8));</pre><pre>return hash2 % 256; // one of 256 tried buckets</pre><pre>}</pre><p>If someone tampers with `nKey` in the file, every single bucket placement will be wrong, and `CheckAddrman` will catch it.</p><p><strong>4. Error Handling in `LoadAddrman` (`addrdb.cpp`)</strong></p><p>The loading function has three distinct exception handlers, each with a different recovery strategy:</p><pre>cpp</pre><pre>try {</pre><pre>DeserializeFileDB(path_addr, *addrman);</pre><pre>} catch (const DbNotFoundError&amp;) {</pre><pre>// File missing → start fresh (no error)</pre><pre>} catch (const InvalidAddrManVersionError&amp;) {</pre><pre>// File from the future → backup and start fresh (warning, no error)</pre><pre>} catch (const std::exception&amp; e) {</pre><pre>// Everything else → fatal, node does not start</pre><pre>}</pre><p>This is a beautiful example of <strong>graduated error handling</strong> — different problems get different responses based on severity and recoverability.</p><h4>The Full Execution Flow</h4><blockquote>```</blockquote><blockquote>Test manipulates peers.dat</blockquote><blockquote>↓</blockquote><blockquote>Node starts up</blockquote><blockquote>↓</blockquote><blockquote>LoadAddrman() is called (addrdb.cpp)</blockquote><blockquote>↓</blockquote><blockquote>DeserializeFileDB() opens the file</blockquote><blockquote>↓</blockquote><blockquote>┌─ Check 1: Network magic bytes match? ──── No → “Invalid network magic number” (FAIL)</blockquote><blockquote>│</blockquote><blockquote>├─ Check 2: Deserialize payload</blockquote><blockquote>│ ├─ Version compatibility OK? ────────── Too old → “compat value too low” (FAIL)</blockquote><blockquote>│ │ Too new → InvalidAddrManVersionError (backup + fresh start)</blockquote><blockquote>│ ├─ nNew / nTried in valid range? ────── No → “nNew/nTried out of range” (FAIL)</blockquote><blockquote>│ └─ Full data deserializes without EOF? ─ No → “end of file” (FAIL)</blockquote><blockquote>│</blockquote><blockquote>├─ Check 3: Checksum matches? ──────────── No → “Checksum mismatch” (FAIL)</blockquote><blockquote>│</blockquote><blockquote>└─ Check 4: CheckAddrman() passes? ──────── No → “Consistency check failed” (FAIL)</blockquote><blockquote>Yes → Node starts successfully</blockquote><blockquote>```</blockquote><h4>Why This Test Matters</h4><p>1. <strong>Defense Against Disk Corruption</strong></p><p>Hard drives fail. SSDs have bit-flip errors. Flash drives corrupt data silently. Every one of the checks in this test maps to a real-world corruption scenario that could happen on any machine.</p><p>2. <strong>Defense Against Attacks</strong></p><p>`peers.dat` is a high-value target. If an attacker can manipulate a node’s address book, they can isolate it from the real network (an “eclipse attack”). The checksum, magic number, and consistency checks make this dramatically harder.</p><p>3. <strong>Graceful Degradation</strong></p><p>Not every problem is fatal. A missing file? No big deal — start fresh. A file from a newer version? Back it up and start fresh. A corrupted file? That’s serious — stop and tell the user. The test verifies that Bitcoin Core makes the <em>*right*</em> decision for each scenario.</p><p>4. <strong>Clear Error Messages</strong></p><p>Each failure mode produces a specific, actionable error message that tells the user exactly what went wrong and what to do about it. The init error even includes the file path and suggests the user can rename or delete the file as a workaround.</p><h4>Real-World Scenarios</h4><p><strong>Scenario 1: You Move Your Bitcoin Data to a New Hard Drive</strong></p><p>You copy your Bitcoin Core data directory to a new drive, but the copy gets interrupted halfway through. `peers.dat` is truncated. Without this test’s EOF check, Bitcoin Core might crash mysteriously or behave unpredictably. With it, you get a clear error message telling you exactly what happened.</p><p><strong>Scenario 2: You Restore From a Cloud Backup</strong></p><p>Your backup software grabbed `peers.dat` from a machine running a newer version of Bitcoin Core. When you restore it on an older machine, the version check kicks in, saves the file as `.bak`, and starts fresh. No data loss, no confusion.</p><p><strong>Scenario 3: Ransomware or Malicious Software Tampers With Your Files</strong></p><p>Malware modifies `peers.dat` to point your node to attacker-controlled addresses. The checksum check detects the tampering immediately and the node refuses to start — alerting you that something is very wrong.</p><p><strong>Scenario 4: Filesystem Bit Rot</strong></p><p>Rarely, a single bit in a stored file flips due to cosmic radiation or electrical interference. This is not science fiction — it happens. The SHA-256d checksum catches even a single-bit flip, because the hash of the corrupted data will be completely different from the stored checksum.</p><h4>Key Takeaways</h4><p>1. <strong>`peers.dat` is Bitcoin Core’s address book</strong> — it stores all known peer addresses in two tables (new and tried), organized into buckets using a secret key</p><p>2. <strong>The secret bucket key (`nKey`) is a security feature</strong> — it makes bucket placement unpredictable to outsiders, defending against address-poisoning attacks</p><p>3. <strong>The file has multiple layers of validation</strong> — magic number, version compatibility, data range checks, checksum, and a full consistency audit</p><p>4. <strong>Different errors get different responses</strong> — missing file (recreate), future version (backup + recreate), corruption (refuse to start)</p><p>5. <strong>The consistency check (`CheckAddrman`) is exhaustive</strong> — it re-derives every bucket placement from scratch and verifies the entire database structure</p><p>6. <strong>Clear error messages and recovery paths</strong> — the user always knows what went wrong and how to fix it</p><h3>References</h3><ol><li>Bitcoin Core repository: <a href="https://github.com/bitcoin/bitcoin">https://github.com/bitcoin/bitcoin</a></li><li>Bitcoin Core Test Documentation: <a href="https://github.com/bitcoin/bitcoin/blob/master/test/functional/feature_addrman.py">https://github.com/bitcoin/bitcoin/blob/master/test/functional/feature_addrman.py</a></li></ol><h4>Conclusion</h4><p>`feature_addrman.py` is a masterclass in defensive programming. It takes Bitcoin Core’s most critical peer-discovery data structure and subjects it to every conceivable form of corruption, verifying that the node responds correctly every single time. The test reflects a deep engineering philosophy: <strong>data you load from disk should never be trusted until it’s been verified — and if verification fails, the failure should be loud, clear, and recoverable.</strong></p><p>For developers, this test is an excellent template for how to think about file loading and validation in any application. The graduated error handling — recreate, backup-and-recreate, or refuse-to-start…based on the severity of the problem, is a pattern worth emulating far beyond Bitcoin Core.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e751f213f736" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deconstructing Bitcoin Core Tests:]]></title>
            <link>https://medium.com/@wandiamugo/deconstructing-bitcoin-core-tests-173515489b88?source=rss-19a686aeb31e------2</link>
            <guid isPermaLink="false">https://medium.com/p/173515489b88</guid>
            <dc:creator><![CDATA[Wandia Mugo]]></dc:creator>
            <pubDate>Tue, 03 Feb 2026 09:30:16 GMT</pubDate>
            <atom:updated>2026-02-11T09:48:56.906Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deconstructing Bitcoin Core Tests</h3><h4><strong>Day 1: Understanding feature_abortnode.py — When Bitcoin Core Must Abort</strong></h4><p><strong>Test File:</strong> `bitcoin/test/functional/feature_abortnode.py`</p><p><strong>Category:</strong> Feature Tests</p><p><strong>Complexity:</strong> Moderate</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yi8K5iQYw6A7eUEvP-5LcQ.jpeg" /></figure><h3>Introduction</h3><h4>The Playlist Analogy</h4><p>You’re organizing a shared playlist on Spotify. Every time someone adds songs, those songs use up space. Every time someone removes songs, space becomes available again.</p><p>Now you need to <strong>reverse</strong> the last batch of changes. To reverse them:</p><p>1. Remove songs that were just added (easy — you can see them)</p><p>2. <strong>Restore songs that were just removed</strong> (hard — which songs were removed? You can’t see them anymore!)</p><p><strong>The problem:</strong> The playlist only shows what’s there NOW. It doesn’t show what was deleted. Without a record (undo data) saying “We removed Song X and Song Y,” you can’t bring them back.</p><p><strong>The safe choice?</strong> Stop rather than guess which songs to restore.</p><p>This is exactly what the `feature_abortnode.py` test checks. Bitcoin Core tries to reverse blocks (undo changes) but discovers the record of what was deleted (undo data) is missing. So it does the safe thing: <strong>abort</strong> rather than corrupt the blockchain.</p><h4>Why This Matters for Developers</h4><p>Whether you’re coming from web development, data science, mobile apps, or any other tech background, you’ve probably dealt with version control conflicts, database rollbacks, or state management issues. This test teaches a universal principle: <strong>when you can’t safely reverse an operation, it’s better to fail loudly than to proceed with corrupted state.</strong></p><p>Understanding these core safety mechanisms shows sophisticated engineering judgment. It’s about writing code that fails gracefully when things go wrong.</p><h4>The Technical Version</h4><p><strong>In distributed blockchain systems like Bitcoin, nodes must maintain consensus by following the chain with the most accumulated proof-of-work. </strong>When a node discovers a competing chain with more work, it must perform a “reorganization” (reorg); disconnecting blocks from its current chain and connecting blocks from the new, longer chain. But what happens when this critical operation fails? The `feature_abortnode.py` test explores this scenario, verifying that Bitcoin Core behaves correctly when it cannot disconnect a block during a reorg attempt.</p><p><strong>The Test: What Does It Do?</strong></p><p>The test simulates a catastrophic scenario where the node’s blockchain data becomes corrupted in a specific way. Here’s the step-by-step breakdown:</p><h4>Test Setup (Lines 16–22)</h4><pre>python</pre><pre>def set_test_params(self):</pre><pre>self.setup_clean_chain = True</pre><pre>self.num_nodes = 2</pre><p>The test starts with a clean blockchain (no pre-existing blocks beyond the genesis block) and spawns two independent nodes that aren’t initially connected to each other.</p><h4><strong>Step 1: Create Initial Blockchain (Line 25)</strong></h4><pre>python</pre><pre>self.generate(self.nodes[0], 3, sync_fun=self.no_op)</pre><p>Node 0 generates 3 blocks on top of the genesis block. At this point, Node 0’s blockchain looks like:</p><pre>Genesis → Block 1 → Block 2 → Block 3</pre><h4>Step 2: Corrupt the Undo Data (Line 28)</h4><pre>python</pre><pre>(self.nodes[0].blocks_path / “rev00000.dat”).unlink()</pre><p>This is the critical line — it deletes the <strong>**undo data file**</strong> (`rev00000.dat`). This file contains crucial information needed to reverse the effects of blocks when performing a reorg. We’ll explore what undo data is in the C++ section below.</p><h4>Step 3: Create a Competing Chain (Line 32)</h4><pre>python</pre><pre>self.generate(self.nodes[1], 3, sync_fun=self.no_op)</pre><p>Node 1 independently generates its own 3 blocks. Now we have two separate chains:</p><pre>Node 0: Genesis → Block 1a → Block 2a → Block 3a (undo data deleted!)</pre><pre>Node 1: Genesis → Block 1b → Block 2b → Block 3b</pre><h4>Step 4: Trigger the Reorg Attempt (Lines 33–35)</h4><pre>python</pre><pre>self.generate(self.nodes[1], 1, sync_fun=self.no_op)</pre><p>Node 1 generates one more block, making its chain longer (4 blocks vs 3). Now Node 1’s chain has more cumulative work:</p><pre>Node 0: Genesis → Block 1a → Block 2a → Block 3a (3 blocks total)</pre><pre>Node 1: Genesis → Block 1b → Block 2b → Block 3b → Block 4b (4 blocks total)</pre><p>When the nodes connect, Node 0 will discover that Node 1 has a longer chain and will attempt to reorganize.</p><h4>Step 5: Verify the Abort (Lines 33–41)</h4><pre>python</pre><pre>with self.nodes[0].assert_debug_log([“Failed to disconnect block”]):</pre><pre>self.connect_nodes(0, 1)</pre><pre>self.generate(self.nodes[1], 1, sync_fun=self.no_op)</pre><p><em># Check that node0 aborted</em></p><pre>self.log.info(“Waiting for crash”)</pre><pre>self.nodes[0].wait_until_stopped(timeout=5, expect_error=True,</pre><pre>expected_stderr=”Error: A fatal internal error occurred, see debug.log for details: Failed to disconnect block.”)</pre><p>The test verifies that:</p><p>1. Node 0 logs “Failed to disconnect block” when it tries to reorg</p><p>2. Node 0 terminates with a fatal error message</p><p>3. The node cannot restart (line 41)</p><h4>The C++ Implementation: How Bitcoin Core Handles This</h4><p>Now let’s dive into the C++ code that the test exercises. The chain of execution follows this path:</p><p><strong>1. The Reorganization Process (`validation.cpp:3294–3318`)</strong></p><p>When Node 0 discovers Node 1’s longer chain, it enters the `ActivateBestChainStep` function:</p><pre>cpp</pre><pre>bool Chainstate::ActivateBestChainStep(BlockValidationState&amp; state,</pre><pre>CBlockIndex* pindexMostWork,</pre><pre>const std::shared_ptr&lt;const CBlock&gt;&amp; pblock,</pre><pre>bool&amp; fInvalidFound,</pre><pre>ConnectTrace&amp; connectTrace)</pre><pre>{</pre><pre>// Find the fork point between current chain and new chain</pre><pre>const CBlockIndex* pindexFork = m_chain.FindFork(pindexMostWork);</pre><pre>// Disconnect blocks back to the fork point</pre><pre>DisconnectedBlockTransactions disconnectpool{MAX_DISCONNECTED_TX_POOL_BYTES};</pre><pre>while (m_chain.Tip() &amp;&amp; m_chain.Tip() != pindexFork) {</pre><pre>if (!DisconnectTip(state, &amp;disconnectpool)) {</pre><pre>// CRITICAL: If we can’t disconnect, this is a fatal error</pre><pre>FatalError(m_chainman.GetNotifications(), state,</pre><pre>_(“Failed to disconnect block.”));</pre><pre>return false;</pre><pre>}</pre><pre>fBlocksDisconnected = true;</pre><pre>}</pre><pre>// … code to connect new blocks …</pre><pre>}</pre><p><strong>Key Insight:</strong> Bitcoin Core treats the inability to disconnect a block as a <strong>fatal error</strong> (line 3314). This makes sense — if the node can’t properly reorg to the best chain, it cannot maintain consensus with the network.</p><p><strong>2. Disconnecting a Block Tip (`validation.cpp:3002–3028`)</strong></p><p>The `DisconnectTip` function handles removing the current tip block from the active chain:</p><pre>cpp</pre><pre>bool Chainstate::DisconnectTip(BlockValidationState&amp; state,</pre><pre>DisconnectedBlockTransactions* disconnectpool)</pre><pre>{</pre><pre>CBlockIndex *pindexDelete = m_chain.Tip();</pre><pre>// Read the block from disk</pre><pre>std::shared_ptr&lt;CBlock&gt; pblock = std::make_shared&lt;CBlock&gt;();</pre><pre>CBlock&amp; block = *pblock;</pre><pre>if (!m_blockman.ReadBlock(block, *pindexDelete)) {</pre><pre>LogError(“DisconnectTip(): Failed to read block\n”);</pre><pre>return false;</pre><pre>}</pre><pre>// Apply the disconnection to the UTXO set</pre><pre>CCoinsViewCache view(&amp;CoinsTip());</pre><pre>if (DisconnectBlock(block, pindexDelete, view) != DISCONNECT_OK) {</pre><pre>LogError(“DisconnectTip(): DisconnectBlock %s failed\n”,</pre><pre>pindexDelete-&gt;GetBlockHash().ToString());</pre><pre>return false; // This is where our test triggers the failure!</pre><pre>}</pre><pre>// Persist changes</pre><pre>bool flushed = view.Flush();</pre><pre>assert(flushed);</pre><pre>}</pre><p><strong>This is where the test’s failure occurs</strong> — when `DisconnectBlock` returns `DISCONNECT_FAILED` at line 3022–3024.</p><p><strong>3. The Core Disconnection Logic (`validation.cpp:2262–2330`)</strong></p><p>The `DisconnectBlock` function is where the undo data becomes critical:</p><pre>cpp</pre><pre>DisconnectResult Chainstate::DisconnectBlock(const CBlock&amp; block,</pre><pre>const CBlockIndex* pindex,</pre><pre>CCoinsViewCache&amp; view)</pre><pre>{</pre><pre>bool fClean = true;</pre><pre>// READ THE UNDO DATA — This is what’s missing in our test!</pre><pre>CBlockUndo blockUndo;</pre><pre>if (!m_blockman.ReadBlockUndo(blockUndo, *pindex)) {</pre><pre>LogError(“DisconnectBlock(): failure reading undo data\n”);</pre><pre>return DISCONNECT_FAILED; // Our test fails here!</pre><pre>}</pre><pre>// Verify undo data matches the block</pre><pre>if (blockUndo.vtxundo.size() + 1 != block.vtx.size()) {</pre><pre>LogError(“DisconnectBlock(): block and undo data inconsistent\n”);</pre><pre>return DISCONNECT_FAILED;</pre><pre>}</pre><pre>// Process transactions in reverse order</pre><pre>for (int i = block.vtx.size() — 1; i &gt;= 0; i — ) {</pre><pre>const CTransaction &amp;tx = *(block.vtx[i]);</pre><pre>// Remove outputs that this transaction created</pre><pre>for (size_t o = 0; o &lt; tx.vout.size(); o++) {</pre><pre>if (!tx.vout[o].scriptPubKey.IsUnspendable()) {</pre><pre>COutPoint out(hash, o);</pre><pre>Coin coin;</pre><pre>bool is_spent = view.SpendCoin(out, &amp;coin);</pre><pre>// Verify the coin matches what we expect</pre><pre>}</pre><pre>}</pre><pre>// Restore inputs that this transaction spent</pre><pre>if (i &gt; 0) { // not coinbase</pre><pre>CTxUndo &amp;txundo = blockUndo.vtxundo[i-1];</pre><pre>for (unsigned int j = tx.vin.size(); j &gt; 0;) {</pre><pre> — j;</pre><pre>const COutPoint&amp; out = tx.vin[j].prevout;</pre><pre>// Restore the previously spent coin</pre><pre>int res = ApplyTxInUndo(std::move(txundo.vprevout[j]), view, out);</pre><pre>if (res == DISCONNECT_FAILED) return DISCONNECT_FAILED;</pre><pre>}</pre><pre>}</pre><pre>}</pre><pre>// Move the chain tip pointer back to the previous block</pre><pre>view.SetBestBlock(pindex-&gt;pprev-&gt;GetBlockHash());</pre><pre>return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN;</pre><pre>}</pre><p><strong>Critical Line 2268:</strong> This is where our test fails! When the code tries to read the undo data from `rev00000.dat` (which we deleted), `ReadBlockUndo` returns `false`, causing the function to return `DISCONNECT_FAILED`.</p><h4>4. Reading Undo Data (`blockstorage.cpp:661–691`)</h4><p>Let’s see what happens when we try to read the missing undo file:</p><pre>cpp</pre><pre>bool BlockManager::ReadBlockUndo(CBlockUndo&amp; blockundo, const CBlockIndex&amp; index) const</pre><pre>{</pre><pre>const FlatFilePos pos{WITH_LOCK(::cs_main, return index.GetUndoPos())};</pre><pre>// Open history file to read</pre><pre>AutoFile file{OpenUndoFile(pos, true)};</pre><pre>if (file.IsNull()) {</pre><pre>LogError(“OpenUndoFile failed for %s while reading block undo”, pos.ToString());</pre><pre>return false; // File doesn’t exist — our test scenario!</pre><pre>}</pre><pre>BufferedReader filein{std::move(file)};</pre><pre>try {</pre><pre>// Read and verify the undo data</pre><pre>HashVerifier verifier{filein};</pre><pre>verifier &lt;&lt; index.pprev-&gt;GetBlockHash();</pre><pre>verifier &gt;&gt; blockundo;</pre><pre>uint256 hashChecksum;</pre><pre>filein &gt;&gt; hashChecksum;</pre><pre>// Verify checksum</pre><pre>if (hashChecksum != verifier.GetHash()) {</pre><pre>LogError(“Checksum mismatch at %s while reading block undo”, pos.ToString());</pre><pre>return false;</pre><pre>}</pre><pre>} catch (const std::exception&amp; e) {</pre><pre>LogError(“Deserialize or I/O error — %s at %s while reading block undo”,</pre><pre>e.what(), pos.ToString());</pre><pre>return false;</pre><pre>}</pre><pre>}</pre><pre>```</pre><pre>**Line 667–670:** When the undo file doesn’t exist (because we deleted it), `OpenUndoFile` returns a null file, causing the function to return `false` immediately.</pre><h4>5. The Fatal Error Handler (`abort.cpp:18–26`)</h4><p>Finally, when `DisconnectTip` fails and returns `false` to `ActivateBestChainStep`, the `FatalError` function is called via `AbortNode`:</p><pre>cpp</pre><pre>void AbortNode(const std::function&lt;bool()&gt;&amp; shutdown_request,</pre><pre>std::atomic&lt;int&gt;&amp; exit_status,</pre><pre>const bilingual_str&amp; message,</pre><pre>node::Warnings* warnings)</pre><pre>{</pre><pre>// Set a fatal warning</pre><pre>if (warnings) warnings-&gt;Set(Warning::FATAL_INTERNAL_ERROR, message);</pre><pre>// Display error to user</pre><pre>InitError(_(“A fatal internal error occurred, see debug.log for details: “) + message);</pre><pre>// Set exit status to failure</pre><pre>exit_status.store(EXIT_FAILURE);</pre><pre>// Trigger shutdown</pre><pre>if (shutdown_request &amp;&amp; !shutdown_request()) {</pre><pre>LogError(“Failed to send shutdown signal\n”);</pre><pre>}</pre><pre>}</pre><p>This function:</p><p>1. Sets a fatal internal error warning</p><p>2. Displays the error message to the user</p><p>3. Sets the exit status to `EXIT_FAILURE`</p><p>4. Initiates a shutdown sequence</p><p><strong>What Is Undo Data and Why Does It Matter?</strong></p><p>Understanding undo data is crucial to understanding this test. Here’s what you need to know:</p><p><strong>The UTXO Set</strong></p><p>Bitcoin maintains a database called the <strong>UTXO set</strong> (Unspent Transaction Output set) — essentially a list of all coins that exist and haven’t been spent yet. When a transaction is processed:</p><p>1. <strong>Inputs</strong> are removed from the UTXO set (coins are spent)</p><p>2. <strong>Outputs</strong> are added to the UTXO set (new coins are created)</p><p><strong>The Problem During Reorgs</strong></p><p>When disconnecting a block during a reorg, we need to reverse these operations:</p><p>1. <strong>Remove outputs</strong> that the block’s transactions created</p><p>2. <strong>Restore inputs</strong> that the block’s transactions spent</p><p>Removing outputs is easy.<br>Why? We know exactly what they were because the block contains the transactions. But <strong>restoring inputs is hard</strong> — how do we know what coins existed before they were spent?</p><p><strong>The Solution: Undo Files</strong></p><p>This is where undo data (`rev*.dat` files) comes in. For each block, Bitcoin Core stores:</p><p>- The previous state of every coin that was spent in that block</p><p>- Information needed to restore those coins to the UTXO set</p><p>When the undo data is missing or corrupted, the node cannot:</p><p>- Determine what coins existed before the block</p><p>- Restore the UTXO set to its pre-block state</p><p>- Perform the reorganization</p><p><strong>Why Is This Fatal?</strong></p><p>Bitcoin Core considers this a fatal error because:</p><p>1. <strong>Consensus Risk:</strong> Without the ability to reorg, the node might stay on a minority chain</p><p>2. <strong>Data Integrity:</strong> Missing undo data suggests potential database corruption</p><p>3. <strong>Safety First:</strong> It’s safer to stop than to potentially violate consensus rules</p><h4>The Full Execution Flow</h4><p>Let’s trace the complete path from test action to node abort:</p><p><em>1. Test deletes rev00000.dat</em></p><p><em>↓</em></p><p><em>2. Node 1 generates a longer chain</em></p><p><em>↓</em></p><p><em>3. Nodes connect and Node 0 discovers the longer chain</em></p><p><em>↓</em></p><p><em>4. ActivateBestChainStep() is called</em></p><p><em>↓</em></p><p><em>5. DisconnectTip() is called to disconnect Node 0’s tip block</em></p><p><em>↓</em></p><p><em>6. DisconnectBlock() is called</em></p><p><em>↓</em></p><p><em>7. ReadBlockUndo() tries to read rev00000.dat</em></p><p><em>↓</em></p><p><em>8. OpenUndoFile() fails (file doesn’t exist)</em></p><p><em>↓</em></p><p><em>9. ReadBlockUndo() returns false</em></p><p><em>↓</em></p><p><em>10. DisconnectBlock() returns DISCONNECT_FAILED</em></p><p><em>↓</em></p><p><em>11. DisconnectTip() returns false</em></p><p><em>↓</em></p><p><em>12. ActivateBestChainStep() calls FatalError()</em></p><p><em>↓</em></p><p><em>13. AbortNode() is called</em></p><p><em>↓</em></p><p><em>14. Node sets exit status to EXIT_FAILURE</em></p><p><em>↓</em></p><p><em>15. Node shuts down</em></p><p><em>↓</em></p><p><em>16. Test verifies the expected error message and shutdown</em></p><h4>Why This Test Matters</h4><p>This test verifies critical failure handling in Bitcoin Core:</p><p>1. <strong>Fail-Safe Behavior</strong></p><p>Rather than continuing with corrupted data or violating consensus, Bitcoin Core chooses to abort. This “fail-safe” approach prevents potentially catastrophic scenarios where a node might:</p><p>- Accept invalid blocks</p><p>- Stay on a minority chain indefinitely</p><p>- Corrupt the UTXO database further</p><p>2. <strong>Data Integrity</strong></p><p>The test ensures that missing undo data is detected and handled properly. In production, this could happen due to:</p><p>- Disk corruption</p><p>- File system errors</p><p>- Manual deletion (accidental or malicious)</p><p>- Incomplete database migration</p><p>3. <strong>Clear Error Messaging</strong></p><p>The test verifies that users receive clear, actionable error messages. The message “Failed to disconnect block” along with the crash helps users understand that:</p><p>- There’s a data integrity problem</p><p>- The node cannot safely continue</p><p>- Database restoration or resync may be necessary</p><p>4. <strong>Preventing Silent Failures</strong></p><p>Without this abort mechanism, a node with missing undo data might:</p><p>- Silently fail to reorg</p><p>- Fall behind the network</p><p>- Serve incorrect blockchain data to peers</p><p>- Violate consensus without detection</p><h4>Real-World Scenarios</h4><p>While the test artificially deletes the undo file, similar situations can occur in production:</p><p><strong>Scenario 1: Disk Failure</strong></p><p>A dying hard drive might corrupt or lose the undo files while keeping block files intact, creating exactly the condition this test simulates.</p><p><strong>Scenario 2: Interrupted Migration</strong></p><p>If a user is moving their blockchain data and the process is interrupted, undo files might be missing or corrupted.</p><p><strong>Scenario 3: Filesystem Issues</strong></p><p>Some filesystems might lose recently written files during crashes, potentially affecting undo data.</p><p><strong>Scenario 4: Pruned Nodes Edge Cases</strong></p><p>While pruned nodes intentionally delete old undo data, edge cases in the pruning logic might accidentally remove undo data that’s still needed.</p><p>In all these cases, Bitcoin Core’s fail-safe approach ensures the node stops rather than potentially violating consensus rules.</p><h4>Key Takeaways</h4><p>1. <strong>Undo data is essential</strong> for blockchain reorganizations, storing the previous state of spent coins</p><p>2. <strong>Missing undo data is treated as a fatal error</strong> because the node cannot safely reorg without it</p><p>3. <strong>The abort mechanism is a safety feature</strong> that prevents consensus violations and data corruption</p><p>4. <strong>The error path is well-tested</strong> from the low-level file reading through to the high-level abort logic</p><p>5. <strong>Bitcoin Core prioritizes safety over availability</strong> — it’s better to shut down than to potentially violate consensus</p><p>6. <strong>The test exercises a complete vertical slice</strong> of the codebase, from Python test framework through RPC, validation logic, storage layer, and error handling</p><h4>References</h4><ol><li>Bitcoin Core repository: <a href="https://github.com/bitcoin/bitcoin">https://github.com/bitcoin/bitcoin</a></li><li>Bitcoin Core Test Documentation: <a href="https://github.com/bitcoin/bitcoin/blob/master/test/functional/feature_abortnode.py">https://github.com/bitcoin/bitcoin/blob/master/test/functional/feature_abortnode.py</a></li></ol><h4>Conclusion</h4><p>The `feature_abortnode.py` test demonstrates Bitcoin Core’s robust error handling when faced with data corruption. By deliberately creating an unrecoverable situation (missing undo data during a reorg), the test verifies that the node responds appropriately by:</p><p>1. Detecting the missing data</p><p>2. Recognizing the situation as unrecoverable</p><p>3. Logging clear error messages</p><p>4. Aborting node operation cleanly</p><p>5. Preventing restart with corrupted data</p><p>This “fail-safe” philosophy is a cornerstone of Bitcoin Core’s design — when in doubt, stop. This conservative approach helps ensure that nodes either maintain correct consensus or halt operation, preventing the worst-case scenario of silently diverging from the network.</p><p>For developers, this test serves as an excellent example of how Bitcoin Core’s various subsystems interact; from block storage and validation to error handling and shutdown procedures. It also demonstrates the importance of comprehensive testing for failure scenarios, not just the “happy path.”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=173515489b88" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How breaking one test in 500,000 lines of C++ taught me more about confidence than code]]></title>
            <link>https://medium.com/@wandiamugo/how-breaking-one-test-in-500-000-lines-of-c-taught-me-more-about-confidence-than-code-81b430e528cc?source=rss-19a686aeb31e------2</link>
            <guid isPermaLink="false">https://medium.com/p/81b430e528cc</guid>
            <category><![CDATA[bitcoin-development]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[c-programming]]></category>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[bitcoin-core]]></category>
            <dc:creator><![CDATA[Wandia Mugo]]></dc:creator>
            <pubDate>Mon, 02 Feb 2026 11:07:35 GMT</pubDate>
            <atom:updated>2026-02-02T11:07:35.745Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Kw2Lxc-E51lLEEGDYAqNQ.jpeg" /></figure><p><strong>Abstract</strong></p><p>Understanding large codebases can feel like being handed a map of an unfamiliar city with no street names. This paper documents my journey through Bitcoin Core’s 500,000+ lines of C++ code with a deceptively simple task: make exactly one functional test fail. What started as an intimidating assignment became a masterclass in surgical code navigation, test-driven development, and the power of minimal changes. I share not just the technical solution, but the false starts, the breakthrough moments, and the lessons learned about confidence in tackling systems that seem too big to comprehend. This is a story about learning to break things intentionally, a skill that’s often harder for women developers who’ve been conditioned to seek perfection.</p><h4>1. Introduction</h4><p>The email with the assignment was short: “Make one functional test fail. Don’t modify test files. Good luck.”</p><p>I stared at my screen. I’d heard of Bitcoin Core. I knew it was important, complex, production-grade code used by thousands of nodes worldwide. What I didn’t know was where to even start. Opening the repository felt like walking into a library where all the books were in a language I only half-spoke.</p><p>There’s a specific kind of imposter syndrome that hits when you’re facing a massive codebase. It’s the voice that says, “Real developers would know exactly where to look.” It’s the pressure to appear confident when you’re actually googling “what is RPC” for the third time. And if you’re a woman in tech, there’s an extra layer: the fear that asking for help will confirm someone’s bias that you don’t belong here.</p><p><em>But here’s what I learned: you don’t need to understand everything. You just need to find one thread and pull.</em></p><p>This paper documents how I went from overwhelmed to making a precise, two-line change that broke exactly one test out of hundreds. More importantly, it’s about the process of learning to navigate complexity without letting perfectionism paralyze you.</p><h4>1.1 The Challenge</h4><p>The assignment had elegant constraints:</p><p>- Modify only `.cpp` or `.h` files in the `src/` directory</p><p>- Make exactly ONE functional test fail</p><p>- Keep all other tests passing</p><p>- Build and verify the solution</p><p>These constraints weren’t arbitrary. They forced me to:</p><p>1. Understand how Bitcoin Core’s test framework works</p><p>2. Trace backwards from a test to its implementation</p><p>3. Make a surgical change, not a sledgehammer fix</p><p>4. Prove my solution worked</p><h4>1.2 Why This Matters</h4><p>In my experience, women developers are often excellent at careful, precise work — but we’re sometimes hesitant to break things. We’ve been socialized to color inside the lines, to not make mistakes, to be <em>*certain*</em> before we act. This exercise flipped that script. The goal was destruction. Controlled, intentional, minimal destruction.</p><p>There’s something liberating about permission to break things. It removes the pressure of perfection and replaces it with curiosity: “What happens if I change this?”</p><h4><strong>2. Methodology: The Detective Work</strong></h4><h4>2.1 First Steps (Or: Staring at Code for Two Hours)</h4><p>My first instinct was to run the tests. I needed to see what “passing” looked like before I could break anything.</p><pre>cd bitcoin</pre><pre>cmake -B build</pre><pre>cmake — build build -j$(sysctl -n hw.ncpu)</pre><p>And then… I waited. The first build took 47 minutes on my laptop. I made tea. I answered emails. I day dreamed.</p><p><strong>Lesson learned:</strong> Build time is thinking time. Instead of feeling guilty about “not being productive,” I used it to read the test framework documentation. Those 47 minutes turned into research time.</p><p>When the build finally completed, I ran all the tests:</p><pre>build/test/functional/test_runner.py</pre><p>Watching hundreds of tests pass felt surreal. Each one represented some aspect of Bitcoin functionality that developers had carefully implemented and verified. And I was about to break one of them.</p><p><strong>2.2 Choosing a Target (The Analysis Paralysis Phase)</strong></p><p>With over 300 functional tests, how do you choose? I spent an embarrassing amount of time overthinking this.</p><p>My first approach was to pick something “impressive.” Maybe break a complex consensus test? Something with cryptography? Then I caught myself: I was performing for an imaginary audience instead of solving the problem strategically.</p><p>I needed a test that:</p><p>- Was simple enough to understand quickly</p><p>- Had a clear, isolated implementation</p><p>- Wouldn’t cascade into breaking other tests</p><p>I listed the tests and looked for simple names. `rpc_uptime.py` caught my eye. Uptime — how long a node has been running. That seemed… achievable?</p><p><strong>The moment of truth:</strong> I opened `test/functional/rpc_uptime.py`. It was 42 lines. I almost cried with relief.</p><h4>2.3 Reading the Test (The Aha Moment)</h4><pre>python</pre><pre>def _test_uptime(self):</pre><pre>wait_time = 10</pre><pre>self.nodes[0].setmocktime(int(time.time() + wait_time))</pre><pre>assert self.nodes[0].uptime() &gt;= wait_time</pre><p>This test:</p><p>1. Sets mock time 10 seconds in the future</p><p>2. Calls `uptime()` RPC method</p><p>3. Asserts uptime is at least 10 seconds</p><p>The assertion was my target: `assert self.nodes[0].uptime() &gt;= wait_time`</p><p>If I could make `uptime()` return something less than 10, the test would fail.</p><p><strong>Here’s where the impostor syndrome kicked in:</strong> I thought, “This seems too simple. Surely I’m missing something?” I spent another hour looking for hidden complexity before realizing that no, sometimes the simple answer is the right answer.</p><p>Women developers: we do this to ourselves. We doubt the simple solution because we assume we must be missing something sophisticated that “real” developers would see. Sometimes the simple answer is correct.</p><h4>2.4 The Hunt (Grep Is Your Friend)</h4><p>Now I needed to find where `uptime()` was implemented. I started with grep:</p><pre>bash</pre><pre>grep -r “uptime” src/ — include=”*.cpp” — include=”*.h”</pre><p>Dozens of results. Most were comments or unrelated. But one stood out:</p><p><em>`src/rpc/server.cpp`</em>:</p><p>A file that registered RPC commands.</p><p>I opened it. Line 187. There it was:</p><pre>cpp</pre><pre>static RPCHelpMan uptime()</pre><pre>{</pre><pre>return RPCHelpMan{“uptime”,</pre><pre>“\nReturns the total uptime of the server.\n”,</pre><pre>{},</pre><pre>RPCResult{</pre><pre>RPCResult::Type::NUM, “”, “The number of seconds that the server has been running”},</pre><pre>RPCExamples{</pre><pre>HelpExampleCli(“uptime”, “”)</pre><pre>+ HelpExampleRpc(“uptime”, “”)</pre><pre>},</pre><pre>[&amp;](const RPCHelpMan&amp; self, const JSONRPCRequest&amp; request) -&gt; UniValue</pre><pre>{</pre><pre>return GetTime() — GetStartupTime();</pre><pre>},</pre><pre>};</pre><pre>}</pre><ul><li><strong>The lambda function at the bottom was the actual implementation.</strong> It calculated uptime as <em>`GetTime() — GetStartupTime()`</em>. Simple, elegant, correct.</li></ul><p>And I was about to break it.</p><h4>3. The Technical Solution</h4><h4>3.1 Understanding the Implementation Chain</h4><p>The code flow looked like this:</p><p>1. <strong>Test Layer</strong> (`test/functional/rpc_uptime.py`): Python test calls `self.nodes[0].uptime()`</p><p>2. <strong>RPC Interface</strong> (JSON-RPC over HTTP): Routes the call to the handler</p><p>3. <strong>RPC Handler</strong> (`src/rpc/server.cpp:189–191`): Lambda function that calculates uptime</p><p>4. <strong>Time Functions</strong> (`src/util/time.cpp`, `src/common/system.cpp`): `GetTime()` and `GetStartupTime()`</p><p>To break the test surgically, I needed to intervene at the RPC handler level. Modifying `GetTime()` or `GetStartupTime()` would be too broad — those functions were used everywhere.</p><h4>3.2 The Modification</h4><p><strong>File:</strong> <em>`src/rpc/server.cpp`</em></p><p><strong>Lines:</strong> 189–191</p><p><strong>Original code:</strong></p><pre>cpp</pre><pre>[&amp;](const RPCHelpMan&amp; self, const JSONRPCRequest&amp; request) -&gt; UniValue</pre><pre>{</pre><pre>return GetTime() — GetStartupTime();</pre><pre>}</pre><p><strong>Modified code:</strong></p><pre>cpp</pre><pre>[&amp;](const RPCHelpMan&amp; self, const JSONRPCRequest&amp; request) -&gt; UniValue</pre><pre>{</pre><pre>// return GetTime() — GetStartupTime();</pre><pre>return 0;</pre><pre>}</pre><p>That’s it. Two lines. Comment out the correct calculation, return 0 instead.</p><h4>3.3 Why This Works</h4><p>The test expects: `uptime() &gt;= 10` (at least 10 seconds)</p><p>My modified code returns: `0`</p><p>The assertion fails: `0 &gt;= 10` is false</p><p><strong>Why only this test fails:</strong></p><p>- The `uptime` RPC command is only tested in `rpc_uptime.py`</p><p>- No other tests depend on the actual uptime value</p><p>- The change is isolated to this single RPC endpoint</p><h4>3.4 The Rebuild and Verification</h4><p>I modified the code, took a breath, and rebuilt:</p><pre>bash</pre><pre>cmake — build build -j$(sysctl -n hw.ncpu)</pre><p>Only took 3 minutes this time — incremental builds are beautiful.</p><p>Then the moment of truth:</p><pre>bash</pre><pre>build/test/functional/test_runner.py rpc_uptime.py</pre><p>FAILED: rpc_uptime.py</p><p><em>Success! (The weird kind where failure is success.)</em></p><p>Now for the real test — did I break ONLY that one test?</p><pre>bash</pre><pre>build/test/functional/test_runner.py</pre><p>I watched the test runner scroll through hundreds of tests. Green checkmarks. Green checkmarks. Then:</p><p><em>rpc_uptime.py ✗</em></p><p>And then… more green checkmarks.</p><p>I let out a breath I didn’t know I was holding.</p><p><strong>4. Results and Discussion</strong></p><h4>4.1 The Solution in Context</h4><p>My solution worked, but was it the <em>*best*</em> solution? I considered alternatives:</p><p><strong>Alternative 1:</strong> Return -1</p><p>- <strong>Pro:</strong> Also fails the test</p><p>- <strong>Con:</strong> Negative uptime is logically weird</p><p><strong>Alternative 2:</strong> Return `wait_time — 1` (9 seconds)</p><p>- <strong>Pro:</strong> Closer to correct, still fails</p><p>- <strong>Con:</strong> Too clever; harder to understand why it’s wrong</p><p><strong>Alternative 3:</strong> Return a very large number</p><p>- <strong>Pro:</strong> Obviously wrong</p><p>- <strong>Con:</strong> Fails the test in a confusing way</p><p><strong>My choice (return 0):</strong></p><p>- <strong>Pro:</strong> Dead simple; obviously incorrect; clear intent</p><p>- <strong>Con:</strong> None</p><p>I chose the simplest solution. In the past, I might have chosen something more “clever” to prove I was smart enough. But I’ve learned that simplicity is a feature, not a bug. The best code is code that the next person (or future you) can understand at 2.22am.</p><h4>4.2 What I Learned About Bitcoin Core</h4><p><strong>Architecture insights:</strong></p><p><em>- Bitcoin Core uses the `RPCHelpMan` pattern for defining RPC commands</em></p><p><em>- RPC handlers are lambda functions that receive `JSONRPCRequest` and return `UniValue`</em></p><p><em>- Time functions are mockable for deterministic testing (`setmocktime`)</em></p><p><em>- The codebase has clear separation between layers (RPC, implementation, tests)</em></p><p><strong>Testing philosophy:</strong></p><p><em>- Each test is independent and isolated</em></p><p><em>- Tests use real `bitcoind` instances (not mocks)</em></p><p><em>- The framework supports hundreds of tests running in parallel</em></p><p><em>- Tests are written in Python for accessibility</em></p><h4>4.3 What I Learned About Myself</h4><p><strong>On perfectionism:</strong> I wasted hours second-guessing simple solutions. The pressure to be “impressive” almost led me to over-complicate the problem. Learning to trust the simple answer is an ongoing process.</p><p><strong>On asking for help:</strong> I didn’t ask for help on this assignment — I wanted to prove I could do it alone. In retrospect, discussing approaches with peers would have been faster and more educational.</p><p><strong>On confidence with large codebases:</strong> The intimidation factor of 500k+ lines of code is real, but it’s also… a lie? Once I stopped trying to understand <em>*everything*</em> and focused on tracing <em>*one path*</em>, the problem became manageable. I don’t need to know the entire Bitcoin protocol to modify one RPC handler.</p><p><strong>On breaking things:</strong> There was a moment when I hesitated before changing the code. “What if I break something important?” But that’s exactly the point — in a controlled environment with tests, breaking things is how you learn. The fear of making mistakes is learned behavior, and it can be unlearned.</p><h4>4.4 Broader Implications for Learning</h4><p>This exercise exemplifies what I call <strong>”intentional destruction as pedagogy.”</strong> Instead of building something new (where you might cargo-cult patterns without understanding them), breaking something forces you to:</p><p>1. <strong>Understand what something does</strong> (read the test)</p><p>2. <strong>Trace the implementation</strong> (find the code)</p><p>3. <strong>Understand dependencies</strong> (why won’t this break other things?)</p><p>4. <strong>Verify your mental model</strong> (did it break in the way you expected?)</p><p>It’s a form of reverse engineering that’s deeply educational.</p><h4>5. Conclusion</h4><p>When I started this assignment, I thought success would mean finding the right line of code to change. But the real success was learning to navigate complexity without fear.</p><blockquote>To the women developers reading this: the impostor syndrome never fully goes away, but you can learn to recognize it for what it is — a liar that wants to keep you small. That voice that says “you’re not good enough” is wrong. You are good enough to read complex code. You are good enough to break things and fix them. You are good enough to contribute to systems you don’t fully understand yet.</blockquote><p>The key insights from this exercise:</p><p>1. <strong>You don’t need to understand everything.</strong> Find one thread and pull.</p><p>2. <strong>Simple solutions are valid.</strong> Don’t over-engineer to prove yourself.</p><p>3. <strong>Breaking things is learning.</strong> Give yourself permission to fail in controlled environments.</p><p>4. <strong>Build time is thinking time.</strong> Don’t guilt yourself about “waiting.”</p><p>5. <strong>The intimidation is learned.</strong> Large codebases are just many small pieces.</p><h4>5.1 Final Thoughts</h4><p>I made a two-line change that broke one test out of hundreds. On the surface, that seems trivial. But the journey to those two lines taught me more about Bitcoin Core, test-driven development, and my own capabilities than any tutorial could have.</p><p>The assignment was about breaking a test. The real lesson was about breaking through self-doubt.</p><p>If you’re facing a large codebase that feels overwhelming, remember: someone else felt that way too. The developers who built Bitcoin Core didn’t have perfect knowledge when they started. They pulled threads, made mistakes, asked questions, and learned.</p><p>You can too.</p><h4>Acknowledgments</h4><p>Thank you to the Bitcoin Core developers for creating such a well-structured codebase with comprehensive tests. The clarity of the RPC layer made this exercise possible.</p><p>Thank you to the women developers who’ve shared their own stories of impostor syndrome and persistence. Seeing your journeys gave me permission to share mine.</p><h4>References</h4><p>1. Bitcoin Core repository: <a href="https://github.com/bitcoin/bitcoin">https://github.com/bitcoin/bitcoin</a></p><p>2. Bitcoin Core functional test framework documentation</p><p>3. Bitcoin Core RPC documentation</p><p>4. My commit: `c9e9d2f` — “make rpc_uptime.py fail”</p><h4>Appendix A: The Commit</h4><pre>commit c9e9d2fee433f6055fb510792eea91a449aeb6a2</pre><pre>Author: Elizabeth Wandia Mugo &lt;wwandia173@gmail.com&gt;</pre><pre>Date: Tue Dec 30 16:25:52 2025 +0300</pre><pre>make rpc_uptime.py fail</pre><h4>Appendix B: For Future Learners</h4><p>If you’re attempting this exercise, here are some tips:</p><p>1. <strong>Start with simple tests.</strong> Look for short test files with clear names.</p><p>2. <strong>Use grep liberally.</strong> Don’t be afraid to search the entire codebase.</p><p>3. <strong>Read the test first.</strong> Understand what it’s checking before hunting for code.</p><p>4. <strong>Trace backwards.</strong> Test → RPC call → RPC handler → Implementation.</p><p>5. <strong>Make minimal changes.</strong> The smaller the change, the less likely you’ll break other things.</p><p>6. <strong>Rebuild incrementally.</strong> You don’t need a full rebuild for small changes.</p><p>7. <strong>Run the specific test first.</strong> Verify it fails before running all tests.</p><p>8. <strong>Document your process.</strong> Future you will thank present you.</p><p>And most importantly: <strong>Give yourself permission to not know.</strong> Not knowing is the starting point of learning, not a character flaw.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81b430e528cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>