Codementor Events

Blockchain, where code creates trust. (Bitcoin)

Published Feb 15, 2019
Blockchain, where code creates trust. (Bitcoin)

Blockchain Technology has taken over the world by a storm. In this post, I am going to talk about blockchain, bitcoin and how bitcon network creates trust without a third party or a central authority. This post hopes to guide and encourage readers to actually go through the code of Bitcoin(Or any of their favourite blockchain project) and increase the adoption rate of crypto currencies.
We will visit some parts of the actual bitcoin blockchain code just to open up and spread our wings of knowledge.

Content

  • What is Blockchain?
  • What is Bitcoin?
  • How is Bitcoin created?
  • What is Consensus Algorithm and how is it used?
  • What is that "Puzzle" and where is all of this written?
  • References
  • Conclusion

What is Blockchain?

A blockchain, is a distributed digital ledger(a growing list of records), called blocks, which are linked using cryptography. Once recorded/verified, the data stored in the blocks can never be changed/modified. more
A public blockchain is borderless, open, neutral, global and censorship resistant.

What is Bitcoin?

A purely peer-to-peer version of electronic cash would allow online payments to be sent directly from one party to another without going through a financial institution.

Bitcoin's whitepaper: https://bitcoin.org/bitcoin.pdf

Bitcoin is a decentralized digital currency that enables instant payments to anyone, anywhere in the world. Transaction validation, security and money issuance are carried out collectively by the network(miners) in exchange of a small transaction fee.

Bitcoin's code is open sourced(with MIT license) which means anyone can use it with or without modification. It is available on GitHub.

In Bitcoin, each block contains a cryptographic hash of the previous block, a timestamp, and transaction data. Having a look the code of block.h verifies this statement.

/** Nodes collect new transactions into a block, hash them into a hash tree,
 * and scan through nonce values to make the block's hash satisfy proof-of-work
 * requirements.  When they solve the proof-of-work, they broadcast the block
 * to everyone and the block is added to the block chain.  The first transaction
 * in the block is a special one that creates a new coin owned by the creator
 * of the block.
 */
class CBlockHeader
{
public:
    // header
    int32_t nVersion;
    uint256 hashPrevBlock;
    uint256 hashMerkleRoot;
    uint32_t nTime;
    uint32_t nBits;
    uint32_t nNonce;
  ...
   // Check out rest of the code on github.

How is Bitcoin created?

Bitcoin is created through a process called mining. Through mining, miners(Special kind of nodes in the bitcoin network) are rewarded a certain calculated amount of bitcoin(s) as an incentive(new bitcoins) and the transaction fee of each transaction within the block or since the last block for securing the network and validating the transactions.

This reward is pre calculated(halves in every 4 year or after 210,000 blocks) and added to the block as the first transaction by the mining node itself, this special transaction is called coinebase transaction.

Miners validate new transactions and record them on the global ledger(Blockchain). They use a special algorithm to create new block and add it to the blockchain. This special algorithm is called Consensus Algorithm.

What is Consensus Algorithm and how is it used?

Consensus(a general aggrement) algorithm creates trust in the blockchain network. PoW (Proof of Work) is the Consensus Algorithm underneath bitcoin.

Proof of Work: This algorithm is used to confirm transactions and create new blocks, In the network there are special kind of nodes(miners) they all compete against each other to add a new block to the chain by solving a difficult cryptographic puzzle, the first node to solve the puzzle gets the reward.

What is that "Puzzle" and where is all of this written?

There is not much informations(In form of blogs or articles) about the code that's actually being put into these blockchains(Bitcoin, in our case). Let's talk about this puzzle and see where is this written.

As already stated that Bitcoin is open sources and it's code is available on GitHub. Bitcoin is written in C++ programming language.

When you hear “solving a block” described as a puzzle or lottery system, it is because of the nonce(A nonce is a “number used once.”). The puzzle is solved and the lottery is won when the correct nonce is discovered. In order to find the correct nonce, miners repeatedly choose a nonce, include it in the contents of the block, hash the block and see if the hash falls below the target hash. If the hash of the block does not fall below the target hash, miners pick a new nonce until they find one that succeeds.

Looking at a blockchain explorer blockchain.com

Screen Shot 2019-02-15 at 12.31.02 PM.png

As you can see the nounce in this block was 89761782. The nounce is incremented in the mining.cpp of bitcoin code.
From the source code of mining.cpp

UniValue generateBlocks(std::shared_ptr<CReserveScript> coinbaseScript, int nGenerate, uint64_t nMaxTries, bool keepScript)
{
    static const int nInnerLoopCount = 0x10000;
    int nHeightEnd = 0;
    int nHeight = 0;

  	// Visit the link above to see the complete code.
        while (nMaxTries > 0 && pblock->nNonce < nInnerLoopCount && !CheckProofOfWork(pblock->GetHash(), pblock->nBits, Params().GetConsensus())) {
            ++pblock->nNonce;
            --nMaxTries;
        }
        if (nMaxTries == 0) {
            break;
        }
        if (pblock->nNonce == nInnerLoopCount) {
            continue;
        }
        // Visit the link above to see the complete code.

Bitcoin's codebase is HUGE so let's look at couple of files and see what's in there.

From the source code of pow.cpp (Proof of Work)

unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params)
{	
  // params defined in the chainparams.cpp
    assert(pindexLast != nullptr);
    unsigned int nProofOfWorkLimit = UintToArith256(params.powLimit).GetCompact();

    // Only change once per difficulty adjustment interval
    if ((pindexLast->nHeight+1) % params.DifficultyAdjustmentInterval() != 0)
    {
        if (params.fPowAllowMinDifficultyBlocks)
        {
            // Special difficulty rule for testnet:
            // If the new block's timestamp is more than 2* 10 minutes
            // then allow mining of a min-difficulty block.
            if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + params.nPowTargetSpacing*2)
                return nProofOfWorkLimit;
            else
            {
                // Return the last non-special-min-difficulty-rules-block
                const CBlockIndex* pindex = pindexLast;
                while (pindex->pprev && pindex->nHeight % params.DifficultyAdjustmentInterval() != 0 && pindex->nBits == nProofOfWorkLimit)
                    pindex = pindex->pprev;
                return pindex->nBits;
            }
        }
        return pindexLast->nBits;
    }

    // Go back by what we want to be 14 days worth of blocks
    int nHeightFirst = pindexLast->nHeight - (params.DifficultyAdjustmentInterval()-1);
    assert(nHeightFirst >= 0);
    const CBlockIndex* pindexFirst = pindexLast->GetAncestor(nHeightFirst);
    assert(pindexFirst);

    return CalculateNextWorkRequired(pindexLast, pindexFirst->GetBlockTime(), params);
}

What are the factors that affect Proof of Work algorithm in Bitcoin?
From the source code of params.h

struct Params {
  ...
 /** Proof of work parameters */
    uint256 powLimit;
    bool fPowAllowMinDifficultyBlocks;
    bool fPowNoRetargeting;
    int64_t nPowTargetSpacing;
    int64_t nPowTargetTimespan;
    int64_t DifficultyAdjustmentInterval() const { return nPowTargetTimespan / nPowTargetSpacing; }
    uint256 nMinimumChainWork;
  // ...
}

chainparams.h

consensus.powLimit = uint256S("00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
consensus.nPowTargetTimespan = 14 * 24 * 60 * 60; // two weeks
consensus.nPowTargetSpacing = 10 * 60;
consensus.fPowAllowMinDifficultyBlocks = false;
consensus.fPowNoRetargeting = false;
// ...
// The best chain should have at least this much work.
consensus.nMinimumChainWork = uint256S("0x0000000000000000000000000000000000000000028822fef1c230963535a90d");

Bitcoin's code lives in a GitHub public repository https://github.com/bitcoin/bitcoin. Anyone can see it, anyone can fork it and create a new blockchain of their own(Which many have done). Go ahead checkout the code, If you would like to contribute create Issues or comment on existing issues to share your opinion or send Pull Requests.

References

Conclusion

Blockchains like Bitcoin are truly changing the world as we know of, It is going to change the fundamental of how we treat money and assets and distrupt multiple sectors.

Thank you for reading this post — I hope it was helpful.
More posts:

About me

I am the Co-Founder of Oc2(Blockchain based bootstrap startup), I have been in the crypto space for an year. I have devoted my full time to explore the vast possibilities that blockchain has to offer to this world. Feel free to reach out.

You can find me on GitHub, LinkedIn and CodeMentor.

Discover and read more posts from Kuldeep
get started
post commentsBe the first to share your opinion
Show more replies