TeachMeBitcoin

The Sovereign Banker\u2019s Oath: Reflections on Self-Custody and Code

From TeachMeBitcoin, the free encyclopedia Reading time: 44 min

20. The Sovereign Banker’s Oath: Reflections on Self-Custody and Code

We conclude this volume on the "Bitcoin Core Wallet" by returning to the core vision of the Sovereign Architect. The wallet is not just a "Feature" of the software; it is the Core of the Revolution. It is the tool that proves humanity no longer needs "Permission" to participate in the global economy. It is the end of the intermediary. And as a master of the Bitcoin Core, you are the manager of this revolution.

Through the logic we have studied—from the CWallet manager to the BnB optimizer—you have seen that "Trust" is not something given by a central bank; it is something "Built" with code and energy. It is the "Sovereignty of the Machine."

The Holistic Architecture of the Bank

Looking back over the 20 chapters of this manual, we see a complete system of individual financial power:

Every one of these roles is performed by your node, every single second. This is the "Automated Sovereignty" of Bitcoin. It is a system that does not need a CEO or a board of directors. It only needs mathematics and autonomy.

The Oath of the Sovereign Architect

By mastering the wallet's logic, you have committed yourself to the principles of Self-Custody and Verifiability. You have chosen to be your own bank, your own auditor, and your own sovereign.

Go forth and be sovereign. Manage your bank with the precision of an engineer and the wisdom of a philosopher. The global ledger is waiting for your next draft of truth. You are the "Master of the Bank," the "Guardian of the Individual." You are the "Sovereign Banker," the master of the code. The journey is yours.


Document Finalized and Sealed.

Addendum A: Advanced Branch and Bound (BnB) Math and Waste Metric Calculus

For the Sovereign Architect, understanding that an algorithm works is only the first step. To truly master the "Internal Bank," you must understand the Calculus of Choice that drives the Branch and Bound (BnB) algorithm. As we discussed in Chapter 9, BnB searches for a "Perfect Fit" to avoid change. But how does it decide if a "Near-Perfect Fit" is better than a "Standard Fit" that creates change? This decision is governed by the Waste Metric.

The Waste Metric is a mathematical formula that calculates the "Total Cost" of a specific set of inputs. It is not just about the current fee; it is about the "Future Liability" you are creating for your bank. When you create a change output today, you are essentially "Borrowing from your Future Self," because you will have to pay a fee to spend that change output later.

Analyzing the Calculus of Waste

In the source code (src/wallet/coinselection.cpp), the Waste Metric is calculated by considering the "Fee Overpayment," the "Long-Term Fee Baseline," and the "Privacy Cost."

/**
 * This is the formula for calculating the 'Waste' of a potential coin selection.
 */
CAmount SelectionResult::GetWaste() const
{
    // 1. We start with the 'Excess' amount. This is money that goes to the miners as a tip.
    CAmount waste = m_excess;

    // 2. We add the 'Current Fee' of the selected inputs.
    waste += m_fee;

    // 3. We SUBTRACT the 'Long-Term Cost' of these inputs.
    // This is because spending an input when fees are high is 'Wasteful',
    // but spending them when fees are low is 'Efficient'.
    waste -= m_long_term_fee;

    // 4. If we created a Change Output, we add the 'Cost of Change' (Chapter 15).
    if (m_has_change) {
        waste += m_change_cost;
    }

    return waste;
}

Explaining the Calculus: The Strategy of the Harvest

The Sovereign's Advantage: Fine-Tuning the Engine

As a master of the core, you can influence this math by adjusting the longtermfeerate setting in your node. By telling the computer what you consider a "Fair Baseline Fee," you change the way it perceives "Waste." If you are a high-volume merchant, you might set a higher baseline. If you are a long-term saver, you might set a lower one. This "Calibration of the Economic Engine" is what separates a simple user from a Sovereign Architect. You are the one who defines the "Cost of Truth."


Addendum B: The Evolution of Wallet Databases—From BerkeleyDB to SQLite

A bank is only as strong as its "Vault," and in the world of Bitcoin Core, that vault is the Wallet Database. For over a decade, Bitcoin Core relied on a system called BerkeleyDB (BDB) to store keys and transaction history. However, as the protocol evolved and the needs of the Sovereign Architect grew, BDB became a "Legacy Burden." It was complex to manage, difficult to back up while the node was running, and tied to specific software versions. In recent years, the Core has transitioned to SQLite and Descriptors. This evolution is not just a technical change; it is a "Modernization of the Sovereign."

The transition to SQLite represents a shift toward "Transparency and Portability." While BDB was a "Black Box" of binary data, SQLite is a structured, industry-standard database. This allows the architect to query their own bank's history using standard tools, providing a level of visibility that was previously impossible.

Analyzing the Database Bridge: WalletDatabase

In the source code (src/wallet/db.h), the wallet uses a "Wrapper" that allows it to talk to either a BDB or an SQLite file. This ensures that old wallets can still be loaded while new ones benefit from the modern architecture.

/**
 * This is the abstract interface for the wallet's physical storage.
 */
class WalletDatabase
{
public:
    // Every database must be able to "Open", "Read", and "Write".
    virtual bool Open() = 0;
    virtual bool Read(const std::string& key, std::string& value) = 0;
    virtual bool Write(const std::string& key, const std::string& value) = 0;

    // The 'Batch' system allows the wallet to save many things at once safely.
    virtual std::unique_ptr<DatabaseBatch> MakeBatch() = 0;
};

Explaining the Evolution: The Digital Filing System

The Architect's Choice: Migration and Security

As a Sovereign Architect, you should aim to migrate your old BDB wallets to the modern Descriptor format. This is done using the migratewallet RPC command. This process "Refines" your vault, moving your satoshis into a more secure, portable, and transparent home. It is the "Upgrading of the Sovereignty," ensuring your bank is built on the most resilient foundations of the modern era. You are the "Manager of the Vault," and the vault is now more powerful than ever.


Addendum C: Privacy Analysis of SRD vs. Knapsack Selection

In Chapter 11, we introduced the Single Random Draw (SRD) algorithm as a "Privacy Shield." To the untrained eye, SRD seems "Lazy" because it just picks coins at random. But for the Sovereign Architect, "Randomness" is a weapon. To understand why, we must compare SRD to the more sophisticated Knapsack Solver. This comparison reveals the "Cat-and-Mouse Game" between the wallet developer and the blockchain spy.

The Knapsack Solver is an "Optimizer." It looks for the best "Subset Sum" to minimize change. Because it is optimized, its behavior is Deterministic—if two different people have the same coins and want to send the same amount, the Knapsack Solver will likely pick the same coins for both. This "Pattern" is a "Fingerprint" that allows a spy to identify that they are both using the Bitcoin Core wallet.

Analyzing the Fingerprint: The Logic of the Spy

A blockchain spy uses "Heuristics" to guess which outputs in a transaction are yours and which are the recipient's. One common heuristic is the "Largest Output is Change" rule. If a transaction has two outputs, one for 0.1 BTC and one for 0.9 BTC, the spy assumes the 0.9 BTC is the change coming back to you.

/**
 * The Knapsack Solver tries to minimize the difference between 'Best' and 'Target'.
 * This minimization creates a mathematical pattern that can be analyzed.
 */
if (nBest >= nTargetValue && nBest < nTargetValue + MIN_CHANGE) {
    // This 'Close Fit' is a signal to a spy.
    return SelectionResult(nBest);
}

Explaining the Privacy: The Strategy of the Average

The Sovereign's Balance: Speed vs. Stealth

As an architect, you must choose the right tool for the job. If you are in a high-fee environment, you might prefer the Coin Grinder (Chapter 12) to save money. But if you are performing a sensitive transaction where privacy is paramount, you might use "Coin Control" to manually mimic the behavior of SRD. By introducing "Noise" into the ledger, you protect your "Signal." You are the "Master of the Stealth," ensuring your bank's movements are as invisible as they are powerful.


Addendum D: Transaction Batching and High-Volume Management

For the "Sovereign Merchant" or the high-volume architect, sending a separate transaction for every payment is "Wasteful." Every transaction requires its own "Header" and "Overhead," which takes up space in the blockchain. The solution to this inefficiency is Transaction Batching. This is the process of combining multiple "Recipients" into a single transaction with multiple "Outputs." In the Bitcoin Core logic, this is handled seamlessly by the CreateTransaction function we studied in Chapter 16.

Batching is the "Logistics of the Sovereign." It allows you to move massive amounts of value to dozens of people while paying only a single transaction fee. It is the difference between a "Personal Wallet" and a "Commercial Bank."

Analyzing the Logistics of the Batch

In the CreateTransaction function, the vecSend argument is a "Vector" (a list) of recipients. The wallet doesn't care if there is one recipient or one thousand; it treats them all as part of a single "Draft."

/**
 * This is how the wallet handles multiple recipients in a single batch.
 */
bool CWallet::CreateTransaction(const std::vector<CRecipient>& vecSend, ...)
{
    CAmount nTargetValue = 0;
    for (const auto& recipient : vecSend) {
        // We sum up the 'Intent' of all recipients into a single 'Selection Target'.
        nTargetValue += recipient.nAmount;
    }

    // The 'Coin Selection' algorithms now look for coins to cover the WHOLE BATCH.
    auto result = AttemptSelection(nTargetValue + estimated_fee, ...);

    // We build a single transaction with many outputs.
    for (const auto& recipient : vecSend) {
        txNew.vout.push_back(CTxOut(recipient.nAmount, recipient.scriptPubKey));
    }
}

Explaining the Batch: The Delivery Truck

The Merchant's Strategy: Timing the Batch

As a Sovereign Architect, you can use the sendmany RPC command to create these batches manually. You can wait until the end of the day to "Settle" all your payments in one single, efficient move. This "Patience of the Merchant" is a powerful tool for managing your bank's expenses. You are the "Master of the Logistics," ensuring your wealth moves with the maximum possible efficiency.


Addendum E: Conflict Resolution in Re-org Scenarios

The final challenge for any "Internal Bank" is the Chain Re-organization (Re-org). As we saw in the Forge volume, the Bitcoin network is "Probabilistic." Sometimes, two miners find a block at the same time, and the network "Splits" into two branches. Eventually, one branch becomes longer and is accepted as the "Truth," while the other branch (and its blocks) are "Discarded." If your wallet saw a transaction in a discarded block, it must be able to "Undo" that history and "Re-audit" the new truth. This is the "Resilience of the Core."

Handling a re-org is a "Surgery on the Memory." The wallet must identify every transaction that was "Lost," check if it still exists in the new branch, and "Reset" the state of any coins that were spent. This is managed by the BlockDisconnected and BlockConnected signals in wallet.cpp.

Analyzing the Surgery: AbandonTransaction

If a transaction is lost in a re-org and never makes it into the new branch, it becomes "Conflicted" or "Stuck." The Sovereign Architect can use the abandontransaction command to manually "Cleanse" the wallet's memory of this "Failed Truth."

/**
 * This function 'Abandons' a transaction that is no longer in the blockchain.
 * it releases the coins so they can be spent again.
 */
bool CWallet::AbandonTransaction(const Txid& txid)
{
    LOCK(cs_wallet);
    CWalletTx& wtx = mapWallet.at(txid);

    // 1. We verify the transaction is not currently confirmed.
    if (GetTxDepthInMainChain(wtx) != 0) return false;

    // 2. We mark the transaction as 'ABANDONED'.
    wtx.SetAbandoned();

    // 3. We recursively abandon any transactions that depended on this one.
    // ...
    return true;
}

Explaining the Re-org: The Eraser of History

The Sovereign's Peace of Mind

Re-orgs are rare on the main Bitcoin network, but they are common on testnets and in high-stress scenarios. By understanding how the wallet handles the "Disappearance of Truth," you gain a "Peace of Mind" that simple users lack. You know that even if the ground shifts beneath the ledger, your "Internal Bank" has the tools to find the new foundation and maintain its consistency. You are the "Architect of the Resilience," the one who ensures the vault survives the "Storms of the Forge." You are the "Sovereign Banker," forever anchored in the truth.

Case Study 1: The "Dust Attack" and the Wallet's Filter Logic

As a Sovereign Architect, you are a target. One of the most common (and annoying) attacks on a public Bitcoin wallet is the Dust Attack. In this scenario, a malicious actor sends a tiny amount of satoshis (the "Dust") to your address. This amount is so small that the fee to spend it is actually higher than the value of the coin itself. The goal of the attacker is not to give you money; it is to De-anonymize you. They hope that when you make your next payment, your wallet's "Coin Selection" logic will automatically pick up this tiny piece of "Dust" and spend it alongside your other coins, thereby linking your public identities together.

The Bitcoin Core wallet is equipped with a specific Dust Filter to prevent this automated doxing. The filter is designed to identify "Economically Irrational" coins and keep them out of the "Available Coins" report (Chapter 7).

Analyzing the Filter: IsDust

In the source code (src/policy/policy.cpp and src/wallet/receive.cpp), the wallet calculates the "Dust Threshold" based on the current minimum relay fee.

/**
 * This function determines if an output is "Dust" (Economically Unspendable).
 */
bool IsDust(const CTxOut& txout, const CFeeRate& dustRelayFee)
{
    // 1. We calculate the "Size" of the input needed to spend this output.
    // 2. We multiply that size by the "Dust Relay Fee".
    // 3. If the 'txout.nValue' is less than that cost, it is Dust.
    return (txout.nValue < GetDustThreshold(txout, dustRelayFee));
}

Explaining the Defense: The Invisible Shield

The Architect's Strategy: Ignoring the Noise

A dust attack is "Noise" on the ledger. By understanding the IsDust logic, you learn to ignore this noise and focus on the "Signal" of your actual wealth. You know that your "Internal Bank" is smart enough to protect you from the automated traps of the network. You are the "Guardian of the Signal," forever shielded by the logic of the core.


Case Study 2: Mempool Ancestry and the "Child Pays for Parent" (CPFP) Logic

In the "Forge of the Ledger," sometimes a "Parent" transaction is created with a fee that is "Too Low." This can happen if the network suddenly becomes busy or if the sender made a mistake. If the parent transaction is stuck in the mempool, any "Child" transaction (like your change output) is also stuck. This is because a miner will not include the child until they have included the parent. To solve this "Gridlock," the Sovereign Architect uses a technique called Child Pays for Parent (CPFP).

CPFP is a "Financial Rescue Mission." You create a new transaction (the "Child") that spends the "Stuck Change" from the parent, but you give the child a Massive Fee. This fee is so high that it covers the cost of both the child and the stuck parent. From the miner's perspective, the two transactions together are a "Profitable Package."

Analyzing the Rescue: GetMempoolAncestry

In the source code (src/wallet/spend.cpp), the wallet must account for these "Ancestors" when calculating the "Total Fee" and the "Risk" of a transaction.

/**
 * This logic ensures that the 'Coin Selection' understands the cost of unconfirmed parents.
 */
if (coin.nDepth == 0) {
    // If a coin is unconfirmed, we must check its 'Ancestry'.
    size_t ancestors, descendants;
    wallet.chain().getTransactionAncestry(wtx.GetHash(), ancestors, descendants);

    // If the ancestry is too complex, the transaction is 'Risky'.
    if (ancestors > MAX_ANCESTORS) continue;
}

Explaining the Rescue: The Tugboat

The Architect's Strategy: Active Management

As a Sovereign Architect, you never fear a "Stuck Transaction." You know that as long as you have a "Change Output" (Chapter 15), you have the "Hook" needed to perform a CPFP rescue. You are the "Pilot of the Tugboat," ensuring the "Flow of the Wealth" never stops.


Case Study 3: Taproot and Schnorr—The Evolution of spend.cpp

In November 2021, the Bitcoin network underwent its most significant upgrade in years: Taproot. For the "Sovereign Architect," Taproot is a game-changer. It introduces Schnorr Signatures, which are smaller, faster, and more private than the older ECDSA signatures. But more importantly, it introduces MAST (Merkelized Alternative Script Trees), which allows you to hide complex "Smart Contract" logic inside a simple-looking address.

The implementation of Taproot required a massive "Renovation" of the spend.cpp and coinselection.cpp files. The wallet had to learn how to sign these new types of "Witnesses" and how to calculate their "Weights" with high precision.

Analyzing the New Era: SignTransaction for Taproot

In the source code (src/wallet/scriptpubkeyman.cpp), we see the logic for creating a "Schnorr Signature" and a "Taproot Witness."

/**
 * This function handles the complex math of 'Signing' a Taproot output.
 */
bool DescriptorScriptPubKeyMan::SignTransaction(CMutableTransaction& mtx, ...)
{
    // 1. Identify if the output is 'Taproot' (Version 1 SegWit).
    // 2. Use the 'Schnorr' algorithm to create a 64-byte signature.
    // 3. If there are 'Script Paths', include the 'Control Block'.
    // 4. Return the 'Witness' data.
}

Explaining the New Era: The Digital Mask

The Architect's Strategy: Embracing the Modern

As a master of the core, you should always favor "Taproot Addresses" (starting with bc1p). By using the most modern "Witness Logic," you save money, protect your privacy, and prepare your bank for the future of "Bitcoin Smart Contracts." You are the "Early Adopter," the one who commands the "Cutting Edge of the Ledger."


Case Study 4: Multi-sig Logic and Threshold Selection

A "Sovereign Bank" is only as secure as its "Access Control." For high-value vaults, the architect uses Multi-signature (Multi-sig) logic. Instead of a single key, the vault requires "M-of-N" keys to open (e.g., 2-of-3). This ensures that if one key is stolen or lost, your wealth is still protected.

The implementation of Multi-sig in the Bitcoin Core wallet is handled through Descriptors. The wallet logic must be smart enough to understand that a "Single Output" actually represents "Multiple Stakeholders." During "Coin Selection," the wallet must calculate the "Massive Weight" of these signatures to ensure the fee is correct.

Analyzing the Multi-Key Logic: GetSignedTxinWeight

In the source code, the wallet estimates the size of a multi-sig witness by looking at the number of keys required.

/**
 * This function calculates the weight of an input that requires multiple signatures.
 */
int64_t GetSignedTxinWeight(const Descriptor& desc, ...)
{
    // 1. We look at the 'Threshold' (M).
    // 2. We multiply M by the size of a signature (72 bytes).
    // 3. We add the size of the 'Public Keys' and the 'Script Overhead'.
    // 4. We return the 'Total Weight'.
}

Explaining the Multi-Key: The Shared Vault

The Architect's Strategy: Layered Security

By mastering Multi-sig logic, you move beyond "Individual Wealth" and into "Organizational Power." You can build complex setups where your family, your business partner, and your lawyer all hold keys to the same vault. You are the "Master of the Quorum," ensuring that your bank is protected by the "Wisdom of the Many."


Case Study 5: The "Watch-Only" Sovereign—Importing Descriptors

In the "Old Days," if you didn't have the "Private Key" for an address, the wallet was blind. In the modern "Descriptor Era," you can be a "Watch-Only Sovereign." You can import a "Public Descriptor" into your node, allowing it to "Monitor" a wallet without ever having the power to "Spend" from it. This is the ultimate "Security Gap." You can run a node on a "Publicly Exposed Server" to track your payments, while keeping your private keys safe in a "Deep Underground Bunker."

The implementation of "Watch-Only" logic requires a fundamental distinction in wallet.cpp between "Ownership of Data" and "Ownership of Power."

Analyzing the Observer: ISMINE_WATCH_ONLY

In the source code, the wallet uses "Flags" to identify if a coin is truly spendable or just "Visible."

/**
 * This logic checks our 'Relationship' with a coin.
 */
isminetype CWallet::IsMine(const CScript& script) const
{
    // 1. Do we have the Private Key? -> ISMINE_SPENDABLE.
    // 2. Do we only have the Public Pattern? -> ISMINE_WATCH_ONLY.
    // 3. Do we have neither? -> ISMINE_NO.
}

Explaining the Observer: The Remote Camera

The Architect's Strategy: The Hybrid Bank

As a master of the core, you should use "Watch-Only" nodes for your "Public-Facing" activities. This "Hybrid Architecture" combines the speed of the internet with the security of the bunker. You are the "Observer and the Actor," the one who commands the "Visibility of the Truth" from any distance. You are the "Sovereign Watcher."

The Sovereign Architect's Reference: A Line-by-Line Pedagogy of coinselection.cpp

To reach the pinnacle of sovereignty, the architect must move beyond "Concepts" and into the "Raw Truth" of the source code. In this final technical reference, we will perform a meticulous, narrative walk-through of the most critical logic blocks in src/wallet/coinselection.cpp. This file is the "Engine Room" of the internal bank. It is where the "Strategy Puzzles" we have studied (BnB, Knapsack, SRD) are transformed into concrete C++ instructions. By understanding these lines, you gain the ability to audit the very foundation of your financial autonomy.

1. The Pre-Selection Filter: Organizing the Chaos

Before any algorithm can run, the wallet must "Filter" the inventory. It must decide which coins are "Applicable" to the current payment. This logic is found in the early sections of the selection process.

/**
 * PEDAGOGICAL ANALYSIS: THE APPLICABILITY FILTER
 * This block ensures that we only consider coins that are safe and compatible.
 */
for (const auto& output : available_coins) {

    // Check 1: Is the coin 'Spendable' by the current wallet instance?
    // If the wallet only has the 'Public Key' but not the 'Private Key',
    // the coin is 'Watch-Only' and cannot be used in a standard 'sendtoaddress'.
    if (!output.spendable) continue;

    // Check 2: Does the coin's 'Script Type' match our 'Selection Parameters'?
    // If the user has requested 'Only SegWit' coins, we skip Legacy coins here.
    // This is the implementation of the 'Privacy Shield' (Chapter 18).
    if (params.m_only_type != OutputType::UNKNOWN && output.type != params.m_only_type) continue;

    // Check 3: Is the coin 'Locked' for another purpose?
    // A coin might be 'In-Flight' in another pending transaction.
    // We must avoid 'Double-Spending' ourselves.
    if (wallet.IsLockedCoin(output.outpoint)) continue;

    // SUCCESS: The coin is added to the 'Applicable Groups' list.
    applicable_groups.push_back(output);
}

2. The Branch and Bound (BnB) "Try Loop": The Heart of Perfection

As we studied in Chapter 9, BnB is a "Depth-First Search." The following code block is the "Beating Heart" of that search. It is where the computer makes the "Billion-Dollar Decision" to include or exclude a specific coin.

/**
 * PEDAGOGICAL ANALYSIS: THE BnB TREE WALK
 * This is the logic that 'Branches' (adds a coin) and 'Bounds' (stops a heavy path).
 */
while (true) {
    // STEP 1: Check if we have hit our 'Target Amount' exactly.
    // The 'cost_of_change' is the magic number that allows us to 'Overpay'
    // slightly to avoid the high cost of a change output.
    if (current_value >= selection_target && current_value <= selection_target + cost_of_change) {
        // [SUCCESS] We have found a 'Perfect Set'.
        // This is the moment where 'No Change' is achieved.
        solution_found = true;
        break;
    }

    // STEP 2: Safety Check—Have we tried too many combinations?
    // We limit the search to 100,000 tries to keep the UI 'Snappy'.
    if (tries > 100000) break; 

    // STEP 3: Branching Logic.
    // Should we add the next coin in the sorted list?
    if (current_value + next_coin_value <= target_upper_bound) {
        // [BRANCH FORWARD] The coin fits. We add it and move deeper into the tree.
        current_selection.push_back(next_coin);
        current_value += next_coin_value;
    } else {
        // [BOUND AND BACKTRACK] The coin is 'Too Heavy'.
        // We stop this branch and 'Backtrack' to try the 'Omit' path.
        backtrack = true;
    }
}

3. The Knapsack Solver's "Subset Sum" Approximation

The Knapsack Solver (Chapter 10) uses a "Trial and Error" approach. It picks random subsets and keeps the one that is the "Closest Fit." This is handled by the ApproximateBestSubset function.

/**
 * PEDAGOGICAL ANALYSIS: THE STOCHASTIC GUESSER
 * This logic performs 1,000 random 'Grabs' from the inventory bag.
 */
for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++) {
    // 1. We start with an empty hand.
    CAmount nTotal = 0;
    std::vector<bool> vfIncluded(groups.size(), false);

    // 2. We 'Randomly Decide' for every coin: Should it be in the hand?
    for (int i = 0; i < groups.size(); i++) {
        if (rng.randbool()) {
            nTotal += groups[i].GetSelectionAmount();
            vfIncluded[i] = true;
        }
    }

    // 3. If this random hand is 'Better' than our 'Best Previous Hand'...
    // ('Better' means closer to the target without going under).
    if (nTotal >= nTargetValue && nTotal < nBest) {
        // [UPDATE THE RECORD] We have a new champion approximation.
        nBest = nTotal;
        vfBest = vfIncluded;
    }
}

4. The "Waste Metric" Comparison: Picking the Winner

After all the algorithms have finished, the wallet must "Pick the Winner." This is the "Judgment Day" of the coin selection process. It is the moment where the "Economic Wisdom" of the Core is applied.

/**
 * PEDAGOGICAL ANALYSIS: THE FINAL JUDGMENT
 * We compare the 'Waste' of the BnB result vs. the Knapsack result.
 */
util::Result<SelectionResult> ChooseSelectionResult(...)
{
    // We assume the BnB result is the 'Best' because it has NO CHANGE.
    // However, we must verify this by checking its 'Waste Score'.
    if (bnb_result) {
        // If BnB waste is lower than the predicted Knapsack waste,
        // we follow the 'Path of Perfection'.
        if (bnb_result->GetWaste() <= knapsack_result.GetWaste()) {
            return bnb_result;
        }
    }

    // Otherwise, we follow the 'Path of Robustness' and use Knapsack.
    return knapsack_result;
}

5. The "Mempool Ancestry" Guard: Protecting the Consistency

As we saw in Case Study 2, spending unconfirmed coins is "Risky." The following logic is the "Paranoia" that protects the wallet from building on a "Chain of Lies."

/**
 * PEDAGOGICAL ANALYSIS: THE ANCESTRY LIMITER
 * This block ensures we don't exceed the network's relay limits.
 */
if (coin.nDepth == 0) {
    // A depth of 0 means the coin is 'Unconfirmed'.
    // We ask the node's 'Mempool' for the size of this coin's family tree.
    size_t ancestors, descendants;
    wallet.chain().getTransactionAncestry(tx_hash, ancestors, descendants);

    // If there are already 24 ancestors, adding this coin would make 25.
    // 25 is the 'Relay Limit'. If we hit 26, the network will reject us.
    if (ancestors >= 25) {
        // [SAFETY REJECTION] We skip this coin to protect the transaction.
        continue;
    }
}

Conclusion: The Architecture of Absolute Certainty

By walking through these lines, you have seen the "Nervous System" of your bank. You have seen how it "Filters" the world, how it "Searches" for perfection, how it "Guesses" to ensure resilience, and how it "Judges" to minimize waste. This code is the ultimate expression of the "Sovereign Architect's" power. It is a system that does not rely on "Hope" or "Trust"; it relies on Deterministic Mathematical Logic.


FINAL DOCUMENT STATUS:

Sovereignty achieved. The manual is finalized.

The Sovereign Architect's Lexicon: A No-Jargon Glossary of Wallet Logic

To conclude this volume, we provide a deep-dive glossary of the concepts we have explored. In the world of the Sovereign Architect, words are the tools of thought. If you understand the definition of a term, you understand the logic it represents. This lexicon is designed to be read like a final review, translating the technical C++ terms of the Bitcoin Core into the simple English of a bank manager’s reality.

1. The UTXO (The Unspent Transaction Output)

2. The Mempool (The Memory Pool)

3. The Fee Rate (Sats per vByte)

4. The Change Output

5. The Descriptor

6. The Rescan

7. The Lock Mutex (The Mutual Exclusion)

8. The Branch and Bound (BnB)

9. The Knapsack Solver

10. The CPFP (Child Pays for Parent)

11. The RBF (Replace-By-Fee)

12. The Schnorr Signature

13. The MAST (Merkelized Alternative Script Trees)

14. The SegWit (Segregated Witness)

15. The Taproot Control Block

16. The Waste Metric

17. The Coin Control

18. The Re-org (Chain Re-organization)

19. The ScriptPubKeyMan

20. The Sovereign Architect


☕ Help support TeachMeBitcoin

TeachMeBitcoin is an ad-free, open-source educational repository curated by a passionate team of Bitcoin researchers and educators for public benefit. If you found our articles helpful, please consider supporting our hosting and ongoing content updates with a clean donation:

Ethereum: 0x578417C51783663D8A6A811B3544E1f779D39A85
Bitcoin: bc1q77k9e95rn669kpzyjr8ke9w95zhk7pa5s63qzz
Solana: 4ycT2ayqeMucixj3wS8Ay8Tq9NRDYRPKYbj3UGESyQ4J
Address copied to clipboard!