Skip to content

BlockChain101

Unleashing the power of blockchain technology

  • Home
  • 2023
  • March
  • 7
  • Bitcoin Source Code (3): Core Code

Bitcoin Source Code (3): Core Code

Posted on March 7, 2023March 7, 2023 By admin No Comments on Bitcoin Source Code (3): Core Code
Blockchain

The Core Code section of the Bitcoin source code is responsible for implementing the core logic of the blockchain. It includes the consensus rules that determine how transactions are validated and how new blocks are added to the chain. The code is organized into several modules, each of which handles a specific aspect of the blockchain’s functionality. Here are some of the main modules in the Core Code section of the Bitcoin source code:

  1. Validation: This module is responsible for validating new transactions and blocks. It includes functions for checking that a transaction is correctly formatted, that it does not double-spend previously spent outputs, and that it satisfies all of the conditions specified in its transaction script.

Here is a sample code for validating a new transaction:

bool CTransaction::CheckTransaction() const {
    // Check that the transaction is well-formed
    if (vin.empty() || vout.empty())
        return false;
        
    // Check that inputs and outputs are not too large
    if (GetTotalSize() > MAX_BLOCK_SERIALIZED_SIZE || ::GetSerializeSize(this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SERIALIZED_SIZE)
        return false;
    
    // Check that all input transactions are valid
    for (const CTxIn& txin : vin) {
        if (!txin.IsFinal())
            return false;
        if (!txin.prevout.IsNull() && !txin.prevout.GetNValue() < prevout.size() && prevout[txin.prevout.GetNValue()].IsNull())
            return false;
    }
    
    // Check that all output transactions are valid
    for (const CTxOut& txout : vout) {
        if (txout.nValue <= 0 || txout.nValue > MAX_MONEY)
            return false;
        if (!IsValidDestination(txout.scriptPubKey))
            return false;
    }
    
    // Check that the transaction fee is sufficient
    if (GetMinRelayFee() > CFeeRate(GetTransactionFee()))
        return false;
        
    return true;
}
  1. Consensus: This module is responsible for implementing the consensus rules that determine how new blocks are added to the blockchain. It includes functions for checking that a block satisfies the proof-of-work requirement, that it contains a valid Merkle root, and that it does not contain any invalid transactions.

Here is a sample code for checking that a block satisfies the proof-of-work requirement:

bool CheckProofOfWork(const uint256& hash, unsigned int nBits, const Consensus::Params& consensusParams) {
    // Get the target hash
    uint256 target = GetBlockProof(GetBlockHeader(hash), consensusParams);
    
    // Check that the hash is less than the target
    if (hash > target)
        return false;
        
    return true;
}
  1. Block Chain: This module is responsible for managing the blockchain. It includes functions for adding new blocks to the chain, reorganizing the chain in response to forks, and validating the integrity of the chain.
bool CBlockIndex::AddBlock(const CBlock& block, CValidationState& state) {
    // Check that the block has not already been added to the chain
    if (phashBlock != nullptr)
        return true;
        
    // Check that the previous block in the chain exists
    if (pprev == nullptr) {
        state.DoS(100, false, REJECT_INVALID, "previous block not found");
        return false;
    }
    
    // Check that the new block is valid
    if (!CheckBlock(block, state))
        return false;
    
    // Calculate the new block's hash and height
    uint256 hash = block.GetHash();
    int nHeight = pprev->nHeight + 1;
    
    // Add the block to the chain index
    if (!setBlockIndex.count(hash)) {
        pnext = nullptr;
        pprev->pnext = this;
        setBlockIndex.insert(std::make_pair(hash, this));
        nChainTx = pprev->nChainTx + block.vtx.size();
        nChainSize = pprev->nChainSize + ::GetSerializeSize(&block, SER_DISK, CLIENT_VERSION);
        nHeight = pprev->nHeight + 1;
        nFile = -1;
        nDataPos = 0;
    }
    
    return true;
}
  1. Mining Code: This module is responsible for the mining process, which involves finding new blocks and adding them to the blockchain. It includes the implementation of the Proof of Work algorithm, which is used to validate new blocks.

Here are some of the main modules in the Mining Code section of the Bitcoin source code:

  • Miner: This module is responsible for finding new blocks and adding them to the blockchain. It includes functions for generating new block templates, verifying that a new block meets the proof-of-work requirement, and submitting new blocks to the network.

Here is a sample code for generating a new block template:

bool CreateNewBlock(const CScript& scriptPubKey, CBlock& block, CMutableTransaction& coinbaseTx, const CChainParams& chainparams) {
    // Get the latest block header
    CBlockIndex* pindexPrev = chainActive.Tip();
    uint32_t nHeight = pindexPrev->nHeight + 1;
    
    // Create a new coinbase transaction
    coinbaseTx.vin.resize(1);
    coinbaseTx.vin[0].scriptSig = CScript() << nHeight << CScriptNum(0) << OP_FALSE;
    coinbaseTx.vout.resize(1);
    coinbaseTx.vout[0].nValue = GetBlockSubsidy(nHeight, chainparams.GetConsensus());
    coinbaseTx.vout[0].scriptPubKey = scriptPubKey;
    
    // Create a new block template
    block.vtx.clear();
    block.vtx.push_back(MakeTransactionRef(std::move(coinbaseTx)));
    block.hashPrevBlock = pindexPrev->GetBlockHash();
    block.nTime = std::max(GetAdjustedTime(), pindexPrev->GetMedianTimePast() + 1);
    block.nBits = GetNextWorkRequired(pindexPrev, &block, chainparams.GetConsensus());
    
    return true;
}
  1. Scripting Code: This module is responsible for implementing the scripting language used by Bitcoin transactions. It allows for the creation of complex transaction scripts that can specify conditions for spending funds, such as requiring multiple signatures or time-based conditions.

Here are some of the main modules in the Scripting Code section of the Bitcoin source code:

  • Script: This module is responsible for parsing and executing Bitcoin transaction scripts. It includes functions for checking that a script is correctly formatted, for executing a script against a transaction, and for verifying that a script satisfies all of the specified conditions.

Here is a sample code for executing a Bitcoin transaction script:

bool EvalScript(const CScript& script, CScript::const_iterator& pc, const CTransaction& txTo, unsigned int nIn, int flags, CScriptNum* pnRet) {
    // Initialize the script evaluation stack
    std::vector<std::vector<unsigned char>> stack;
    std::vector<unsigned char> altstack;
    
    try {
        while (pc < script.end()) {
            // Get the current opcode
            opcodetype opcode = script.GetOp(pc);
            
            // Handle the opcode
            if (opcode <= OP_PUSHDATA4) {
                // Push the data onto the stack
                stack.push_back(script.GetData(pc));
            } else if (opcode == OP_IF) {
                // Execute the if branch if the top stack element is not zero
                ...
  1. User Interface Code: This module handles the graphical user interface (GUI) for Bitcoin wallets and other applications built on the Bitcoin network. It includes functions for displaying transaction histories, managing settings, and displaying network status.

Here are some of the main modules in the

User Interface Code section of the Bitcoin source code:

  • Qt: This module provides the user interface components for Bitcoin Core, the reference implementation of the Bitcoin protocol. It includes functions for displaying the main application window, managing menus and toolbars, and displaying user notifications.

Here is a sample code for displaying a notification to the user:

void CBitcoinGUI::InitMessage(const QString& message) {
    // Show a message box with the specified message
    QMessageBox::information(this, tr("Bitcoin Core"), message);
}
  • RPC: This module provides a remote procedure call (RPC) interface for interacting with Bitcoin Core. It includes functions for making RPC calls to the Bitcoin Core daemon, managing authentication and authorization, and handling error conditions.

Here is a sample code for making an RPC call to the Bitcoin Core daemon:

QString BitcoinRPC::call(const QString &strMethod, const QList<QVariant> &params) const {
    // Build the RPC request JSON object
    QJsonObject request;
    request.insert("method", strMethod);
    request.insert("id", 1);
    request.insert("jsonrpc", "2.0");
    
    QJsonArray arrParams;
    for (const QVariant& param : params) {
        arrParams.append(QJsonValue::fromVariant(param));
    }
    request.insert("params", arrParams);
    
    // Send the RPC request and wait for a response
    QNetworkRequest req(QUrl(QString("http://%1:%2").arg(m_strHost).arg(m_nPort)));
    req.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    req.setRawHeader("Authorization", QString("Basic %1").arg(QString(m_strUser + ":" + m_strPassword).toLatin1().toBase64()));
    QNetworkReply* reply = m_qnam.post(req, QJsonDocument(request).toJson(QJsonDocument::Compact));
    while (!reply->isFinished()) {
        QApplication::processEvents();
    }
    
    // Process the RPC response
    QByteArray response = reply->readAll();
    QJsonDocument doc = QJsonDocument::fromJson(response);
    if (doc.isNull()) {
        throw RPCError(RPC_MISC_ERROR, "Failed to parse RPC response: " + response);
    }
    
    QJsonObject obj = doc.object();
    if (obj.contains("error")) {
        QJsonObject error = obj.value("error").toObject();
        throw RPCError(error.value("code").toInt(), error.value("message").toString());
    }
    
    return obj.value("result").toVariant().toString();
}
Tags: Bitcoin source code

Post navigation

❮ Previous Post: Bitcoin Source Code (2): The Structure
Next Post: Bitcoin Source Code (4): Update Core Code ❯

You may also like

Blockchain
Bitcoin Source Code (1): Understanding the Technical Aspects
March 7, 2023
Blockchain
Bitcoin Source Code (6): Adding Support for Multi-Party Transactions to the Bitcoin Protocol: A Guide to Modifying the Core Code
March 7, 2023
Blockchain
Bitcoin Source Code (2): The Structure
March 7, 2023
Blockchain
Bitcoin Source Code (7): Optimizing performance
March 7, 2023

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Copyright © 2025 BlockChain101.

Theme: Oceanly News Dark by ScriptsTown