Bitcoin's blockchain is the global public ledger (list) of all transactions, which everyone in the bitcoin network accepts as the authoritative record of ownership.
But how can everyone in the network agree on a single universal "truth" about who owns what, without having to trust anyone? All traditional payment systems depend on a trust model that has a central authority providing a clearinghouse service, basically verifying and clearing all transactions. Bitcoin has no central authority, yet somehow every node has a complete copy of a public ledger that it can trust as the authoritative record. The blockchain is not created by a central authority, but is assembled independently by every node in the network. Somehow, every node in the network, acting on information transmitted across insecure network connections can arrive at the same conclusion and assemble a copy of the same public ledger as everyone else. This chapter examines the process by which the bitcoin network achieves global consensus without central authority.
Satoshi Nakamoto's main invention is the decentralized mechanism for emergent consensus. All the properties of bitcoin, including currency, transactions, payments and the security model that does not depend central authority or trust derive from this invention.
* Independent aggregation of those transactions into new blocks by mining nodes, coupled with demonstrated computation through a Proof-of-Work algorithm
* Independent assembly of the new blocks by every full node into a chain and selection of the chain with the most cumulative computation demonstrated through Proof-of-Work
In the next few sections we will examine these processes and how they interact to create the emergent property of network-wide consensus that allows any bitcoin node to assemble its own copy of the authoritative, trusted, public, global ledger.
Each of these processes also aggregates smaller bitcoin units into larger data structures. First, unspent transaction outputs (UTXO) are aggregated into transactions. Next, many transactions are aggregated into a block. Finally, blocks are added to a chain of blocks, the blockchain. In the previous chapter we looked at transactions as a data structure. In this chapter we will also look at the larger data structures: blocks and the blockchain.
In the previous chapter we saw how wallet software creates transactions by collecting UTXO, providing the appropriate unlocking scripts and then constructing new outputs assigned to a new owner. The resulting transaction is then sent to the neighboring nodes in the bitcoin network so that it may be propagated across the entire bitcoin network.
Every bitcoin node that receives a transaction will first verify the transaction before forwarding it to its neighbors. This ensures that only valid transactions are propagated across the network, while invalid transactions are discarded at the first node that encounters them.
* Check none of the inputs have hash=0, N=-1 (coinbase transactions should not be relayed)
* Check that nLockTime is less than or equal to INT_MAX
* Check that the transaction size in bytes is greater than or equal to 100
* Check the number of signature operations contained in the transaction is less than the signature operation limit
* Reject "nonstandard" transactions: unlocking script (scriptSig) doing anything other than pushing numbers on the stack, or the locking script (scriptPubkey) not matching isStandard forms
* For each input, look in the main branch and the transaction pool to find the referenced output transaction. If the output transaction is missing for any input, this will be an orphan transaction. Add to the orphan transactions, if a matching transaction is not already in the pool.
* For each input, if the referenced output transaction is a coinbase output, it must have at least COINBASE_MATURITY (100) confirmations; else reject this transaction
* For each input, if the referenced output does not exist (e.g. never existed or has already been spent), reject this transaction
* Using the referenced output transactions to get input values, check that each input value, as well as the sum, are in the allowed range of values (less than 21m coins, more than 0)
* Verify the unlocking scripts for each input against the corresponding output locking scripts
These conditions can be seen in detail in the functions AcceptToMemoryPool, CheckTransaction and CheckInputs in the bitcoin reference client. Note that the conditions change over time, to address new types of Denial-of-Service attacks or sometimes to relax the rules so as to include more types of transactions.
By independently verifying each transaction as it is received and before propagating it, every node builds a pool of valid new transactions (the transaction pool), roughly in the same order.
Almost every node on the bitcoin network maintains a temporary list of unconfirmed transactions called the memory pool or transaction pool. Once a transaction is verified using the detailed checklist introduced in the section above, it is added to the transaction pool. Nodes use this pool to keep track of transactions that are known to the network but are not yet included in the blockchain. For example, a node that holds a users wallet will use the transaction pool to track incoming payments to the users wallet that have been received on the network but are not yet confirmed. Every node also maintains a separate pool of orphaned transactions as detailed in <<orphan_transactions>>. If a transactions inputs refer to a transaction that is not yet known, a missing parent, then it will be stored temporarily in the orphan pool until the parent transaction arrives. Both the transaction pool and orphan pool are stored in local memory and are not saved on persistent storage, rather they are dynamically populated from incoming network messages. When a node starts, both pools are empty and are gradually populated with new transactions received on the network.
As transactions are received and verified using the criteria in the previous section, they are added to the transaction pool and relayed to the neighboring nodes to propagate on the network.
When a transaction is added to the transaction pool, the orphan pool is checked for any orphans that reference this transaction's outputs (its children). Any orphans found are pulled from the orphan pool and validated using the above checklist. If valid, they are also added to the transaction pool, completing the chain that started with the parent transaction. In light of the newly added transaction which is no longer an orphan, the process is repeated recursively looking for any further descendants, until no more descendants are found. Through this process, the arrival of a parent transaction triggers a cascade reconstruction of an entire chain of interdependent transactions by re-uniting the orphans with their parents all the way down the chain.
Some implementations of the bitcoin client also maintain a UTXO pool which is the set of all unspent outputs on the blockchain. This may be housed in local memory or as an indexed database table on persistent storage. Unlike the transaction and orphan pools, the UTXO pool is not initialized empty but instead contains millions of entries of unspent transaction outputs including some dating back to 2009. Whereas the transaction and orphan pools represent a nodes local perspective and may vary significantly from node to node depending upon when the node was started or restarted, the UTXO pool represents the emergent consensus of the network and therefore will vary little between nodes. Furthermore the transaction and orphan pools only contain unconfirmed transactions, while the UTXO pool only contains confirmed outputs.
Some of the nodes on the bitcoin network are specialized nodes called _miners_. A miner will collect, validate and relay new transactions just like any other node. Unlike other nodes, a miner will then aggregate these transactions into a _block_. The block of transactions constructed by a miner is a candidate block and becomes valid only if the miner succeeds in winning the mining competition. Each miner competes by trying billions of possible solutions to an equation based on a cryptographic hash. If they find a solution, they broadcast the candidate block for everyone to record on the blockchain. The competition difficulty is calibrated to ensure that a new block solution is found by someone every 10 minutes on average. We will look at the mining process itself in more detail in <<mining>>. For now, let's look at how miners aggregate transactions into blocks.
In Chapter 1 we introduced Jing, a computer engineering student in Shanghai China, who is a bitcoin miner. Jing earns bitcoin by running a "mining rig" which is a specialized computer-hardware system designed to mine bitcoins. Jing started mining for bitcoin in 2010, when mining was not as competitive as it is today. At that time, Jing could mine bitcoin using a desktop computer. Today, he uses a much more powerful mining system based on Application Specific Integrated Circuits (ASICs), which are specialized silicon chips designed exclusively for one application - bitcoin mining. Over time, the way Jing participates in the mining process has changed slightly, but the fundamentals remain the same. We will start by looking at how Jing mined in 2010, when things were simpler and then look at how he mines today, as bitcoin mining has become a more complex and competitive activity.
In 2010, Jing mined on a desktop computer. At the time, he would run a full bitcoin node, connected to the bitcoin network. A full bitcoin node keeps a full copy of the blockchain, the list of all transactions since the first ever transaction in 2009. Jing's bitcoin node receives transactions propagated by other nodes, just like any other node on the bitcoin network. After validating those transactions, the bitcoin software adds them to the _memory pool_, or _transaction pool_, where transactions would await until they could be included (mined) into a block.
Jing's bitcoin node is also listening for new blocks, propagated on the bitcoin network. Let's follow the blocks that were created during the time Alice bought a cup of coffee from Bob's Cafe (see <<cup_of_coffee>>). Alice's transaction was included in block 277316. For the purpose of demonstrating the concepts in this chapter let's assume that block was mined by Jing's mining system and follow Alice's transaction as it becomes part of this new block.
Jing's mining node maintains a local copy of the blockchain, the list of all blocks created since the beginning of the bitcoin system in 2009. By the time Alice buys the cup of coffee, Jing's node has assembled a chain of 277,314 blocks of transactions. Jing's node is listening for transactions, trying to mine a new block and also listening for blocks discovered by other nodes. Jing's node receives an incoming block, propagated by the bitcoin network, which fits into the existing blockchain at height 277,315.
As soon a Jing's bitcoin node receives a valid new block, it immediately starts the next round of competition. Receiving a new block signifies that someone else has won the previous round, meaning that Jing's system did not win that round and should abandon its current efforts and shift its resources to try and win the next round. During the previous 10 minutes, while Jing's node was searching for a solution, it was also collecting transactions. By now it has collected a few hundred transactions in the memory pool. After removing any transactions that appear in the new block recently received, Jing's memory pool is left containing unconfirmed transactions that are waiting to be recorded in a new block.
A block is a container data structure that aggregates transactions for inclusion in the public ledger, the blockchain. The block is made of a header, containing metadata, followed by a long list of transactions that make up the bulk of it's size.
[[block_structure]]
.The structure of a block
[options="header"]
|=======
|Size| Field | Description
| 4 bytes | Magic Number | A constant (0xD9B4BEF9) used to easily recognize bitcoin blocks
| 4 bytes | Block Size | The size of the block, in bytes, following this field
| 80 bytes | Block Header | Several fields form the block header (see below)
| 1-9 bytes (VarInt) | Transaction Counter | How many transactions follow
| Variable | Transactions | The transactions recorded in this block
|=======
Jing's mining node creates a candidate block by building an empty data structure and then filling it with transactions and the appropriate metadata. We'll ignore the header for now, as it is the last thing filled in by a node and concentrate instead on the transactions and how they are added to the block. Jing's node uses a selection algorithm to pick transactions from the memory pool (and the orphan pool if the parent has arrived) and adds them after the block header. The selection algorithm is detailed in the next section.
=== Adding Transactions to a Candidate Block
To construct the candidate block Jing's bitcoin node selects transactions from the memory pool, by applying a priority metric to each transaction and adding the highest priority transactions first. Transactions are prioritized based on the "age" of the UTXO that is being spent in their inputs, allowing for old and high-value inputs to be prioritized over newer and smaller inputs. Prioritized transactions can be sent without any fees, if there is enough space in the block.
In the equation above, the value of an input is measured in the base unit, satoshis (1/100m of a bitcoin). The age of a UTXO is the number of blocks that have elapsed since the UTXO was recorded on the blockchain, measuring how many blocks "deep" into the blockchain it is. The size of the transaction is measured in bytes.
For a transaction to be considered "high priority" its priority must be greater than 57,600,000, which corresponds to one bitcoin (100m satoshis), aged one day (144 blocks) in a transaction of 250 bytes total size.
The first 50 kilobytes of transaction space in a block are set aside for high priority transactions. Jing's node will fill the first 50 kilobytes, prioritizing the highest priority transactions first, regardless of fee. This allows high-priority transactions to be processed even if they carry zero fees.
Jing's mining node then fills the rest of the block up to the maximum block size (MAX_BLOCK_SIZE in the code), with transactions that carry at least the minimum fee, prioritizing those with the highest fee per kilobyte of transaction.
If there is any space remaining in the block, Jing's mining node may choose to fill it with no-fee transactions. Some miners choose to mine transactions without fees on a best-effort basis. Other miners may choose to ignore transactions without fees.
Any transactions left in the memory pool after the block is filled will remain in the pool for inclusion in the next block. As transactions remain in the memory pool, their inputs "age", as the UTXO they spend get deeper into the blockchain with new blocks added on top. Since a transactions priority depends on the age of its inputs, transactions remaining in the pool will age and therefore increase in priority. Eventually a transaction without fees may reach a high enough priority to be included in the block for free.
Bitcoin transactions do not have an expiration time-out. A transaction that is valid now will be valid in perpetuity. However, if a transaction is only propagated across the network once it will persist only as long as it is held in a mining node memory pool. When a mining node is restarted, its memory pool is wiped clear, as it is a transient non-persistent form of storage. While a valid transaction may have been propagated across the network, if it is not executed it may eventually not reside in the memory pool of any miner. Wallet software is expected to retransmit such transactions or reconstruct them with higher fees if they are not successfully executed within a reasonable amount of time.
The block header consists of three sets of block metadata. First, there is a reference to a previous block hash, which connects this block to the previous block in the blockchain. We will examine this in more detail in <<blockchain>>. The second set of metadata, namely the difficulty, timestamp and nonce, relate to the mining competition, as detailed in <<mining>>. The third piece of metadata is the Merkle Tree root, a data structure used to efficiently summarize all the transactions in the block.
The primary identifier of a block is its cryptographic hash, a digital fingerprint, made by hashing the block header twice through the SHA256 algorithm. The resulting 32-byte hash, is called the _block hash_, but is more accurately the _block *header* hash_, as only the block header is used to compute it. For example, the block hash of the first bitcoin block ever created is +000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f+. The block hash identifies a block uniquely and unambiguously and can be independently derived by any node by simply hashing the block header.
Note that the block hash is not actually included inside the block's data structure, neither when the block is transmitted on the network, nor when it is stored on a node's persistence storage as part of the blockchain. Instead, the block's hash is computed by each node as the block is received from the network. On full nodes, the block hash may be stored in a separate database table as part of the block's metadata, to facilitate indexing and faster retrieval of block from disk.
A second way to identify a block is by its position in the blockchain, called the _block height_. The first block ever created is at block height 0 (zero), and is the same block that was referenced by the block hash +000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f+ above. A block can thus be identified two ways, either by referencing the block hash, or by referencing the block height. Each subsequent block added "on top" of that first block is one position "higher" in the blockchain, like boxes stacked one on top of the other. The block height on January 1st 2014 was approximately 278,000, meaning there were 278,000 blocks stacked on top of the first block created in January 2009.
Unlike the block hash, the block height is not a unique identifier. While a single block will always have a specific and invariant block height, the reverse is not true - the block height does not always identify a single block. Two or more blocks may have the same block height, competing for the same position in the blockchain. This scenario is discussed in detail in the section on <<forks>>. The block height is also not a part of the block's data structure, it is not stored within the block. Each node dynamically identifies a block's position (height) in the blockchain when it is received from the bitcoin network. The block height may also be stored as metadata in an indexed database table for faster retrieval.
[TIP]
====
A block's _block hash_ always identifies a single block uniquely. A block also always has a specific _block height_. However, it is not always the case that a specific block height can identify a single block, rather more than one blocks can compete for a single position in the blockchain.
Now that the Jing's node has built a candidate block and populated the transactions and merkle root, this block must be linked to the other blocks in the blockchain {must be ready to link to other blocks (if he wins the competition)}. In this section we will look at the blockchain data structure in more detail and see how Jing will extend this chain with the new block.
The blockchain data structure is an ordered linked list of blocks of transactions. The blockchain can be stored as a flat file, or in a simple database. The bitcoin core client stores the blockchain metadata using Google's LevelDB database.
Each block within the blockchain is identified by a hash, generated using the SHA256 cryptographic hash algorithm on the header of the block. Each block also references a previous block, known as the _parent_ block, through the "previous block hash" field in the block header. In other words, each block contains the hash of its parent inside its own header. The sequence of hashes linking each block to its parent, creates a chain going back all the way to the first block ever created, known as the _genesis block_. A block can have multiple children, each of which refers to it as its parent and contains the same hash in the "previous block hash" field. However, since a block only hash one single "previous block hash", that means each block can only have one parent. {one of which will win out while the others die...}
The hash of the parent is also part of the data (the block header) that creates the hash of the child, making the ancestry of each block an immutable part of its identity. The chain of hashes guarantees that a block cannot be modified retrospectively without forcing the re-computation of all following blocks (children), because a retrospective change in any block would change its hash, thereby changing the reference in any children whose hash also changes, and so on. As new blocks are added to the chain, they strengthen the immutability of the ledger by effectively incorporating all previous blocks by reference in their cryptographic hash.
The first block in the blockchain is called the _genesis block_ and was created in 2009. It is the "common ancestor" of all the blocks in the blockchain, meaning that if you start at any block and follow the chain backwards in time you will eventually arrive at the _genesis block_.
The genesis block has the identifier hash +000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f+. You can search for that block hash in any block explorer website, such as blockchain.info, and you will find a page describing the contents of this block, with a URL containing that hash:
Jing's node maintains a complete copy of the blockchain, starting at the genesis block. The local copy of the blockchain is constantly updated as new blocks are found and used to extend the chain. As Jing's node receives incoming blocks from the network, it will validate these blocks and then link them to the existing blockchain. To establish a link, Jing's node will examine the incoming block header and look for the "previous block hash".
Let's assume for example that Jing's node has 277,314 blocks in the local copy of the blockchain. The last block Jing's node knows about is block 277314, with a block header hash of +00000000000000027e7ba6fe7bad39faf3b5a83daed765f05f7d1b71a1632249+.
Jing's node then receives a new block from the network, which it parses as follows:
Looking at this new block, Jing's node sees the "previousblockhash" field contains the hash of its parent block. It is a hash known to Jing's node, that of the last block on the chain at height 277314. Therefore, this new block is a child of the last block on the chain and extends the existing blockchain. Jing's node adds this new block to the end of the chain, making its heigh 277315.
The moment Jing's node received this block (height 277315), this event signified that another node on the network had won this round of the mining competition. Jing's mining node then created the candidate block for the new round of the competition. After filling the candidate block with transactions, Jing's node needs to populate the header of the candidate block and therefore link it to the rest of the blockchain. The existing block at height 277315 will be the parent of Jing's new candidate block. Jing's node will therefore populate the "previous block hash" field in the candidate block with the hash of the block at height 277315.
As part of populating the block header, a mining node will create a summary of all the transactions added to the block. This summary is created by computing the _root_ of the Merkle Tree, which is a binary hash tree data structure. The merkle root is a 32-byte hash that provides a shortcut to identify individual transactions contained within that block.
A _Merkle Tree_, also known as a _Binary Hash Tree_ is a data structure created by Ralph Merkle used for efficiently summarizing and verifying the integrity of large sets of data. Merkle Trees are binary trees containing cryptographic hashes. When N data elements are hashed and summarized in a Merkle Tree, you can check to see if any one data element is included in the tree with at most +2*log~2~(N)+ calculations, making this a very efficient data structure. The term "tree" is used in computer science to describe a branching data structure, but these trees are usually displayed upside down with the "root" at the top and the "leaves" at the bottom of a diagram, as you will see in the examples that follow.
Merkle trees are used in bitcoin to summarize all the transactions in a block, producing an overall digital fingerprint of the entire set of transactions, which can be used to prove that a transaction is included in the set. A merkle tree is constructed by recursively hashing pairs of nodes until there is only one hash, called the _root_, or _merkle root_. The cryptographic hash algorithm used in bitcoin's merkle trees is SHA256 applied twice, also known as double-SHA256.
The merkle tree is constructed bottom-up. In the example below, we start with four transactions A, B, C and D, which form the _leaves_ of the Merkle Tree, shown in the diagram at the bottom. The transactions are not stored in the merkle tree, rather their data is hashed and the resulting hash is stored in each leaf node as H~A~, H~B~, H~C~ and H~D~:
+H~A~ = SHA256(SHA256(Transaction A))+
Consecutive pairs of leaf nodes are then summarized in a parent node, by concatenating the two hashes and hashing them together. For example, to construct the parent node H~AB~, the two 32-byte hashes of the children are concatenated to create a 64-byte string. That string is then double-hashed to produce the parent node's hash:
+H~AB~ = SHA256(SHA256(H~A~ + H~B~))+
The process continues until there is only one node at the top, the node known as the Merkle Root. That 32-byte hash is stored in the block header and summarizes all the data in all four transactions.
[[simple_merkle]]
.Calculating the nodes in a Merkle Tree
image::images/MerkleTree.png["merkle_tree"]
Since the merkle tree is a binary tree, it needs an even number of leaf nodes. If there is an odd number of transactions to summarize, the last transaction hash is duplicated to create an even number of leaf nodes, also known as a _balanced tree_. This is shown in the example below, where transaction C is duplicated:
[[merkle_tree_odd]]
.An even number of data elements, by duplicating one data element
The same method for constructing a tree from four transactions can be generalized to construct trees of any size. In bitcoin it is common to have several hundred to more than a thousand transactions in a single block, which are summarized in exactly the same way producing just 32-bytes of data from a single merkle root. In the diagram below, you will see a tree built from 16 transactions:
To prove that a specific transaction is included in a block, a node need only produce +log~2~(N)+ 32-byte hashes, constituting an _authentication path_ or _merkle path_ connecting the specific transaction to the root of the tree. This is especially important as the number of transactions increases, because the base-2 logarithm of the number of transactions increases much more slowly. This allows bitcoin nodes to efficiently produce paths of ten or twelve hashes (320-384 bytes) which can provide proof of a single transaction out of more than a thousand transactions in a megabyte sized block. In the example below, a node can prove that a transaction K is included in the block by producing a merkle path that is only four 32-byte hashes long (128 bytes total). The path consists of the four hashes H~L~, H~IJ~, H~MNOP~ and H~ABCDEFGH~. With those four hashes provided as an authentication path, any node can prove that H~K~ is included in the merkle root by computing four additional pair-wise hashes H~KL~, H~IJKL~ and H~IJKLMNOP~ that lead to the merkle root.
[[merkle_tree_path]]
.A Merkle Path used to prove inclusion of a data element
As you can see from the table above, while the block size increases rapidly, from 4KB with 16 transactions to a block size of 16 MB to fit 65,535 transactions, the merkle path required to prove the inclusion of a transaction increases much more slowly, from 128 bytes to only 512 bytes. With merkle trees, a node can download just the block headers (80 bytes per block) and still be able to identify a transaction's inclusion in a block by retrieving a small merkle path from a full node, without storing or transmitting the vast majority of the blockchain which may be several gigabytes in size. Nodes which do not maintain a full blockchain, called Simple Payment Verification or SPV nodes use merkle paths to verify transactions without downloading full blocks.
Mining is the process by which new bitcoin is added to the money supply. Mining also serves to secure the bitcoin system against fraudulent transactions or transactions spending the same amount of bitcoin more than once, known as a double-spend. Miners act as a decentralized clearinghouse, validating new transactions and recording them on the global ledger. A new block, containing transactions which occurred since the last block, is "mined" every 10 minutes thereby adding those transactions to the blockchain. Transactions that become part of a block and added to the blockchain are considered "confirmed", which allows the new owners of bitcoin to spend the bitcoin they received in those transactions. Miners receive two types of reward for mining: new coins created with each new block and transaction fees from all the transactions included in the block. To earn this reward, the miners compete to solve a difficult mathematical problem based on a cryptographic hash algorithm. The solution to the problem, called the Proof-of-Work, is included in the new block and acts as proof that the miner expended significant computing effort. The competition to solve the Proof-of-Work algorithm to earn reward and the right to record transactions on the blockchain is the basis for bitcoin's security model.
Bitcoin's security is underpinned by computation. New blocks are added to the blockchain through a consensus mechanism called the _Proof-of-Work_ (PoW) that requires a predictable computational effort, one that takes approximately 10 minutes to solve on average. Specialized bitcoin nodes called _miners_ validate transactions and collect them into blocks, then attempt to find the solution that satisfies the Proof-of-Work algorithm. The first miner to find such a solution, propagates the newly created block across the network. All other nodes on the network verify that the new block contains valid transactions and satisfies the Proof-of-Work algorithm, then they add it to the blockchain, thereby extending it by one block. The miners add a special coin generation transaction into the blocks they build, which creates new bitcoin from nothing and is payable to the miner's own bitcoin address. Once the block is accepted as valid by the entire network, that transaction is also recorded on the blockchain, thereby rewarding the miner for the computational effort it took to satisfy the Proof-of-Work. This de-centralized consensus mechanism, based on a global competition and requiring computation to create new blocks, is the basis for the security of the bitcoin transaction ledger and also for the issuance of new bitcoin. {move the last sentence to the beginning of the paragraph - to explain more about security} The equilibrium between the incentive of bitcoin reward and the immense computing effort required to win it force the participants to behave honestly, without the need for a centralized clearinghouse or currency issuer. The bitcoin consensus mechanism is a dynamic, self-regulating and completely decentralized security model that operates at very large scale.
The process of new coin generation is called mining, because the reward is designed to simulate diminishing returns, just like mining for precious metals. Bitcoin's money supply is created through mining, just like a central bank issues new money by printing bank notes. The amount of newly created bitcoin a miner can add to a block decreases approximately every four years (or precisely every 210,000 blocks). It started at 50 bitcoin per block in January of 2009 and halved to 25 bitcoin per block in November of 2012. It will halve again to 12.5 bitcoin per block sometime in 2016. Based on this formula, bitcoin mining rewards decrease exponentially until approximately the year 2140 when all 21 million bitcoin have been issued.
Bitcoin miners also earn fees from transactions. Every transaction may include a transaction fee, in the form of a surplus of bitcoin between the transaction's inputs and outputs. The bitcoin miner gets to "keep the change" on the transactions.
Today the fees represent 1% or less of a bitcoin miner's income, the vast majority coming from the newly minted bitcoins. However, as the reward decreases over time and the number of transactions per block increases, a greater proportion of bitcoin mining earnings will come from fees. After 2140 all bitcoin miner earnings will be in the form of transaction fees.
With SHA-256, the output is always 256 bits long, regardless of the size of the input. In the example below, we will use the Python interpreter to calculate the SHA256 hash of the phrase "I am Satoshi Nakamoto".
The example shows that if we calculate the hash of the phrase +"I am Satoshi Nakamoto"+, it will produce +5d7c7ba21cbbcd75d14800b100252d5b428e5b1213d27c385bc141ca6b47989e+. This 256-bit number is the _hash_ or _digest_ of the phrase and depends on every part of the phrase. Adding a single letter, punctuation mark or any character will produce a different hash.
Now, if we vary the phrase, we will expect to see completely different hashes. Let's try that by adding a number to the end of our phrase, using this simple Python script
[[sha256_example_generator]]
.SHA256 A script for generating many hashes by iterating on a nonce
====
[source, python]
----
include::code/hash_example.py[]
----
====
Running this will produce the hashes of several phrases, made different by adding a unique number, called a _nonce_ at the end of the text. By incrementing the nonce, we can get different hashes.
((("nonce")))
[[sha256_example_generator_output]]
.SHA256 Output of a script for generating many hashes by iterating on a nonce
Each phrase produces a completely different hash result. They seem completely random, but you can re-produce the exact results in this example on any computer with Python and see the same exact hashes.
To make a challenge out of this algorithm, let's set an arbitrary target: find a phrase starting with "I am Satoshi Nakamoto" which produces a hash that starts with a zero. In numerical terms, that means finding a hash value that is less than +0x1000000000000000000000000000000000000000000000000000000000000000+. Fortunately, this isn't so difficult! If you notice above, we can see that the phrase "I am Satoshi Nakamoto13" produces the hash 0ebc56d59a34f5082aaef3d66b37a661696c2b618e62432727216ba9531041a5, which fits our criteria. It only took 13 attempts to find it.
Bitcoin's proof-of-work is very similar to the problem above. First, a miner will generate a new block, containing:
((("block")))
* Transactions waiting to be included in a block
* The hash from the previous block
* A _nonce_
The only part a miner can modify is the nonce. Now, the miner will calculate the hash of this block's header and see if it is smaller than the current _target difficulty_. The miner will likely have to try many nonces before finding one that results in a low enough hash.
A very simplified proof-of-work algorithm is implemented in Python here:
((("proof of work")))
[[pow_example1]]
.Simplified Proof-Of-Work Implementation
====
[source, python]
----
include::code/proof-of-work-example.py[]
----
====
Running the code above, you can set the desired difficulty (in bits, how many of the leading bits must be zero) and see how long it takes for your computer to find a solution. In the following examples, you can see how it works on an average laptop:
[[pow_example_outputs]]
.Running the proof-of-work example for various difficulties
As you can see, increasing the difficulty by 1 bit causes an exponential increase in the time it takes to find a solution. If you think of the entire 256-bit number space, each time you constrain one more bit to zero, you decrease the search space by half. In the example above, it takes 84 million hash attempts to find a nonce that produces a hash with 26 leading bits as zero. Even at a speed of more than 120 thousand hashes per second, it still requires ten minutes on a consumer laptop to find this solution.
At the time of writing this, the network is attempting to find a block whose header hash is less than +000000000000004c296e6376db3a241271f43fd3f5de7ba18986e517a243baa7+. As you can see, there are a lot of zeroes at the beginning of that hash, meaning that the acceptable range of hashes is much smaller, hence more difficult to find a valid hash. It will take on average more 150 quadrillion hash calculations per second for the network to discover the next block. That seems like an impossible task, but fortunately the network is bringing 500 TH/sec of processing power to bear, which will be able to find a block in about 10 minutes on average.
Bitcoin is tuned to generate blocks approximately every 10 minutes. This is achieved by automatically adjusting the target difficulty to account for increases and decreases in the available computing power on the network. This process occurs automatically and on every full node independently. Each node recalculates the expected difficulty every 2106 blocks, based on the time it took to hash the previous 2106 blocks. In simple terms: If the network is finding blocks faster than every 10 minutes, the difficulty increases. If block discovery is slower than expected, the difficulty will decrease.
{miners that are on mining pools get the difficulty (do not calculate difficulty independently) they are given the difficulty from the mining pool so they don't have to calculate the difficulty themselves and they are actually given a lower difficulty target. There are essentially two classifications of miners today - pool miners and solo miners. Solo miners run a full node and compete on their own. Whereas pool miners collaborate with one another and compete against the network as a team, while sharing the reward. The reason miners join pools - solo miners need an enormous amount of hashing power in order to have even the slimmest chance of finding a solution to a block which will make their earnings erratic. By participating in a pool, miners get smaller shares but a more regular share of rewards, reducing uncertainty. Solo mining is becoming obsolete, as the difficulty increases the likelihood of a solo miner finding a solution is more like winning the lottery.}
{ASIC miners do not run full nodes. Full nodes independently calculate the difficulty using the same equation on the same block, arriving at the same result for the new difficulty. Retargeting the difficulty at block heights that are multiples of 2106 from the genesis block. The equation for retargeting difficulty measures the time it took to find the last 2106 blocks, compares that to the expected time of 21,060 minutes (based upon a desired 10 minute block time), the difference is calculated as a percentage and a corresponding percentage adjustment is made to the difficulty. To avoid extreme volatility in the difficulty, the retargeting adjustment cannot exceed {X%} per retargeting. The difficulty will only be retargeted up or down by maximum of {X%} per cycle. If the required difficulty adjustment is greater than the maximum it will be reflected in the next retargeting adjustment as the imbalance will persist through the next 2106 blocks. Large discrepancies between hashing power and difficulty may take several cycles to even out. This leads to a potential problem which has been observed in alt coins, where very large changes in difficulty can cause hashing power to collapse leading to excessively long block times. If the aggregate network hashing power collapses due to the departure of many miners simultaneously, the remaining hashing power may be insufficient to meet the difficulty target leading to excessively long block intervals. Since retargeting is not a function of time but rather block number, a large hashing deficit can mean the next cycle is very far in the future. Usually this is caused for two reasons - scenario one - entry for a brief period of a lot of hashing which temporarily increases the difficulty, followed by the departure of that hashing, resulting in a collapse of block solutions. Essentially a hashing pump and dump. Usually a deliberate attack. This is not a concern in bitcoin because new hashing power introduced into the network will not effect the average enough to cause a major change in difficulty. The other scenario in which hashing power can collapse is a crash in bitcoin price, making mining unprofitable. (If the miner cannot pay their electricity bill, the miner will leave the network.) This is a weakness of the protocol, as an insurmountable hashing deficit could occur with a precipitous collapse in price and corresponding reduction in available hashing power. The network would be unable to recover because ... }
The difficulty of finding a bitcoin block is approximately '10 minutes of processing' for the entire network, based on the time it took to find the previous 2106 blocks, adjusted every 2106 blocks.
====
Note that the target difficulty is independent of the number of transactions or the value of transactions. This means that the amount of hashing power and therefore electricity expended to secure bitcoin is also entirely independent of the number of transactions. Bitcoin can scale up, achieve broader adoption and remain secure without any increase in hashing power from today's level. The increase in hashing power represents market forces as new miners enter the market to compete for the reward. As long as enough hashing power is under the control of miners acting honestly in pursuit of the reward, it is enough to prevent "takeover" attacks and therefore it is enough to secure bitcoin.
The target difficulty is closely related to the cost of electricity and the exchange rate of bitcoin vis-a-vis the currency used to pay for electricity. High performance mining systems are about as efficient as possible with the current generation of silicon fabrication, converting electricity into hashing computation at the highest rate possible. The primary influence on the mining market is the price of one kilowatt-hour in bitcoin, as that determines the profitability of mining and therefore the incentives to enter or exit the mining market.
Bitcoins are "minted" during the creation of each block at a fixed and diminishing rate. Each block, generated on average every 10 minutes, contains a _reward_ that consists of entirely new bitcoins. The reward was 50BTC for the first four years of operation of the network. Every four years the reward is decreased by 50%, resulting in a diminishing rate of issuance over time. In 2012, the reward was decreased to 25BTC and it will decrease again to 12.5BTC in 2016. By approximately 2140, the last fragments of a bitcoin will be mined, for a total of 21 million bitcoins. {Clarify coinbase transaction as first - includes the reward and transactions. Discuss how the coinbase transaction will change in 2140}
The finite and diminishing issuance creates a fixed monetary supply that resists inflation. Unlike a fiat currency which can be printed in infinite numbers by a central bank, bitcoin can never be inflated by printing.
===== Monetary supply
Bitcoin's monetary supply is defined as the number of coins in circulation (minted). Like any other currency, this measure of monetary supply is called M0, which represents the narrowest measure of the money supply. Just like any other currency, bitcoin can also have a _fractional reserve banking_ which means that an organization can trade bitcoins "off blockchain" which are not part of the M0 monetary measure, but of the broader monetary supply measures M1-M3. {have you explained M1-M3?}{also, i think you should explain fractional reserve banking a bit here}
While the total bitcoins in circulation will not exceed 21m, that monetary base can support a much broader economy through fractional reserve banking and expansion of the available credit.
===== Deflationary Money
The most important and debated consequence of a fixed and diminishing monetary issuance is that the currency will tend to be inherently _deflationary_. Deflation is the phenomenon of appreciation of value due to a mismatch in supply and demand that drives up the value (and exchange rate) of a currency. The opposite of inflation, price deflation means that your money has more purchasing power over time.
Many economists argue that a deflationary economy is a disaster that should be avoided at all costs. That is because in a period of rapid deflation, the incentives for regular people are to hoard the money and not spend it, hoping that prices will fall. Such a phenomenon unfolded during Japan's "Lost Decade", when a complete collapse of demand pushed the currency into a deflationary spiral.
Bitcoin experts argue that deflation is not bad *per se*. Rather, we associate deflation with a collapse in demand because that is the only example of deflation we have to study. In a fiat currency with the possibility of unlimited printing, it is very difficult to enter a deflationary spiral unless there is a complete collapse in demand and an unwillingness to print money. Deflation in bitcoin is not caused by a collapse in demand, but by predictably constrained supply.
In practice, it has become evident that the hoarding instinct caused by a deflationary currency can be overcome by discounting from vendors, until the discount overcomes the hoarding instinct of the buyer. Since the seller is also motivated to hoard, the discount becomes the equilibrium price at which the two hoarding instincts are matched. With discounts of 30% on the bitcoin price, most bitcoin retailers are not experiencing difficulty overcoming the hoarding instinct and generating revenue. It remains to be seen whether the deflationary aspect of the currency is really a problem when it is not driven by rapid economic retraction.
{Discuss chain selection: As new blocks are found they are added to the chain. Each full node constructs a chain and calculates the cumulative difficulty of that chain. As blocks are constructed and propagated across the network,}
{create a graphic showing propagating transaction}
{Because the blockchain is a decentralized data structure, different copies of it are not always consistent. Blocks may arrive at different nodes at different times, causing them to have a different perspective o ft the blockchain. To resolve this, each node always selects and attempts to extend the chain of blocks that represents the most Proof-of-Work, also known as the longest chain or greatest cumulative difficulty chain, by adding the difficulty recorded in each block for a chain a node can calculate the total amount of PoW that has been expended to create that chain. As long as all nodes select the longest, i.e. the longest cumulative difficulty chain, the global bitcoin network eventually converges to a consistent state. Forks occur as temporary inconsistencies between versions of the blockchain, which are resolved by the eventual reconvergence.}
{Bitcoin's _consensus mechanism_, which creates the is comprised of the independent validation of transactions by every node, the cumulative work of the miners, and the network convergence upon the greatest difficulty chain. The interplay of these three processes manifests the emergent property of consensus that allows for a global decentralized public ledger without a central authority. which creates one global public ledger, emerges as a property of (1) the selection of the greatest difficulty chain. This chapter is about the emergent property of consensus. This consensus is created by the interplay of three processes - (1) ,2,3. The emergent property of network-wide consensus is what establishes a trusted decentralized global public ledger. Satohsi's invention was not proof of work, elliptic curve cryptography. Satoshi's invention was how the interplay of these processes creates emergent consensus in a decentralized network without the need for a centralized trusted authority.}
A "fork" occurs whenever there are two candidate blocks competing to form the longest blockchain. This occurs under normal conditions whenever two miners solve the Proof-of-Work algorithm within a short period of time from each other. As both miners discover a solution for their respective candidate blocks, they immediately broadcast their own "winning" block to their immediate neighbors who begin propagating the block across the network. Each node that receives a valid block will incorporate it into their blockchain, extending the blockchain by one block. If that node later sees another candidate block extending the same parent, they ignore the second candidate. As a result, some nodes will "see" one candidate block first, while other nodes will see the other candidate block and two competing versions of the blockchain will emerge.
{create a graphic with the globe, two miners each - bitcoin topology map}
.Visualization of a blockchain fork event - Two blocks found simultaneously
image::images/GlobalFork2.png["globalfork2"]
Let's assume for example that a miner in Canada finds a proof-of-work solution for block "A" that extends the blockchain from height 315000 to height 315001, building on top of parent block "P". Almost simultaneously, an Australian miner who was also extending block "P", finds a solution for block "B", their candidate block. Now, there are two possible candidates for block height 315001, one we call "A", originating in Canada and one we call "B", originating in Australia. Both blocks are valid, both blocks contain a valid solution to the proof of work, both blocks extend the same parent. Both blocks likely contain most of the same transactions, with only perhaps a few differences in the order of transactions.
[[fork2]]
.Visualization of a blockchain fork event - Two blocks propagate, splitting the network
image::images/GlobalFork3.png["globalfork3"]
From that moment, the bitcoin network nodes closest (topologically, not geographically) to the Canadian node will hear about block "A" first and will create a new greatest-cumulative-difficulty blockchain with height 315001 and "A" as the last block in the chain (e.g. P-A), ignoring the candidate block "B" that arrives a bit later. Meanwhile, nodes closer to the Australian node will take that block as the winner and extend the blockchain to height 315001 with "B" as the last block (e.g. P-B), ignoring "A" when it arrives a few seconds later. Any miners that saw "A" first will immediately build candidate blocks that reference "A" as the parent and start trying to solve the PoW for these candidate blocks. The miners that accepted "B" instead, will start extending that chain.
.Visualization of a blockchain fork event - A new block extends one fork
image::images/GlobalFork4.png["globalfork4"]
Forks are almost always resolved within one block. As part of the network's hashing power is dedicated to building on top of "A" as the parent, another part of the hashing power is focused on building on top of "B". Even if the hashing power is almost evenly split, it is likely that one set of miners will find a solution and propagate it before the other set of miners have found any solutions. Let's say for example that the miners building on top of "B" find a new block "X" that extends the chain to height 315002 (e.g. P-B-X). They immediately propagate this new block and the entire network sees it as a valid solution.
All nodes that had chosen "B" as the winner in the previous round will simply extend the chain one more block. The nodes that chose "A" as the winner, however, will now see a block extending an even longer chain (greater-cumulative difficulty), that does not include "A" in it. Any miners working on extending the chain P-A will now stop that work because their candidate block is an "orphan", as its parent "A" is no longer on the longest chain. The block "A" is removed from the blockchain by any nodes that had accepted it and any transactions within it are queued up again for processing in the next block. The entire network re-converges on a single blockchain P-B-X, with "X" as the last block in the chain. All miners immediately start working on candidate blocks that reference "X" as their parent to extend the P-B-X chain.
It is theoretically possible for a fork to extend to two blocks, if two blocks are found almost simultaneously by miners on opposite "sides" of a previous fork. However, the chance of that happening is very low. Whereas a one-block fork may occur every week, a two-block fork is exceedingly rare.
----
Block "X" extends the chain: P-B-X
Old chain is now "shorter": P-A
----
[TIP]
====
As of version 0.9, Bitcoin Core's +alertnotify+ option will send alerts whenever a 6-block or longer fork occurs