<?xml version="1.0"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
	<id>https://en.bitcoin.it/w/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Mrbandrews</id>
	<title>Bitcoin Wiki - User contributions [en]</title>
	<link rel="self" type="application/atom+xml" href="https://en.bitcoin.it/w/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Mrbandrews"/>
	<link rel="alternate" type="text/html" href="https://en.bitcoin.it/wiki/Special:Contributions/Mrbandrews"/>
	<updated>2026-04-07T08:28:57Z</updated>
	<subtitle>User contributions</subtitle>
	<generator>MediaWiki 1.43.8</generator>
	<entry>
		<id>https://en.bitcoin.it/w/index.php?title=Bitcoin_Core_0.11_(ch_5):_Initial_Block_Download&amp;diff=60027</id>
		<title>Bitcoin Core 0.11 (ch 5): Initial Block Download</title>
		<link rel="alternate" type="text/html" href="https://en.bitcoin.it/w/index.php?title=Bitcoin_Core_0.11_(ch_5):_Initial_Block_Download&amp;diff=60027"/>
		<updated>2016-01-21T20:32:44Z</updated>

		<summary type="html">&lt;p&gt;Mrbandrews: edit footer&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
This page explains how Bitcoin Core downloads the blockchain when your node first joins the network.  &lt;br /&gt;
&lt;br /&gt;
==Background==&lt;br /&gt;
&lt;br /&gt;
Once a new node joins the network, its first order of business is to download and validate the entire blockchain.   This is an integral step to the distributed nature of bitcoin because only by doing this can a node claim that it has independently validated all transactions.  &lt;br /&gt;
&lt;br /&gt;
As the blockchain grows in size, the time required for IBD increases unless optimizations are made to the code.  Various optimizations have been made since Satoshi&#039;s original client was released, but as of 2014, with increasing transaction volume, initial download on laptop hardware with an average connection could still take up to 24 hours.  Developers agreed that this was unacceptable and a new approach was developed called &amp;quot;headers first&amp;quot; mode.  This approach resulted in a substantial speedup.&lt;br /&gt;
&lt;br /&gt;
==&amp;quot;Headers First&amp;quot; mode==&lt;br /&gt;
&lt;br /&gt;
With &amp;quot;headers-first&amp;quot; mode, a new node downloads all of the block headers first, which are very small (about 80 bytes, whereas a block can be up to 1MB).  Once the node has all of the headers, from the genesis block up to the current tip of the blockchain (380,000 as of October 2015), only then does it begins downloading the full blocks.&lt;br /&gt;
&lt;br /&gt;
Now that it has the headers, the node downloads blocks in parallel from multiple peers.  (It downloads headers from only one peer, but that&#039;s no big deal since headers are small.)  The node will download from up to 8 peers at once and will disconnect any peer that stalls for more 2 seconds, attempting to connect to a faster peer. &lt;br /&gt;
&lt;br /&gt;
Headers-first IBD was merged in 2014 in:  [https://github.com/bitcoin/bitcoin/pull/4468 Pull Request 4468].&lt;br /&gt;
&lt;br /&gt;
As summarized in the PR comment, some of its main features are [comment is edited slightly here]:&lt;br /&gt;
&lt;br /&gt;
* Do not use &#039;getblocks&#039;, but &#039;getheaders&#039;, and use it to build a headers tree.&lt;br /&gt;
* Blocks are fetched in parallel from all available outbound peers, using a limited moving window. When one peer stalls the movement of the window, it is disconnected.&lt;br /&gt;
* No more orphan blocks. At all. We only ever request a block for which we have verified the headers, and store it to disk immediately. This means that a disk-fill attack would require Proof of Work.&lt;br /&gt;
* We sync from everyone we can, though limited to 1 during initial headers sync.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Checkpoints==&lt;br /&gt;
&lt;br /&gt;
The Bitcoin Core initial block download code makes sure that the block headers you are downloading (from a single peer) passes certain, hard-coded &amp;quot;checkpoints.&amp;quot; &lt;br /&gt;
&lt;br /&gt;
Checkpoints are block hashes corresponding to a long-ago block that everyone (where &amp;quot;everyone&amp;quot; means the network participants as recognized by the Bitcoin Core commit-access developers) recognizes as being on the longest chain.  The checkpoints are set far enough in the so as to be non-controversial. &lt;br /&gt;
&lt;br /&gt;
The IBD checkpoints check is at &amp;lt;u&amp;gt;main.cpp:2784&amp;lt;/u&amp;gt; (version 0.11).&lt;br /&gt;
&lt;br /&gt;
The hardcoded figures are in &amp;lt;u&amp;gt;chainparams.cpp&amp;lt;/u&amp;gt;.  (As of 0.11, there were 13 checkpoints, the first at block 11,111, the last at block 295,000.)&lt;br /&gt;
&lt;br /&gt;
From chainparams.cpp: &lt;br /&gt;
&lt;br /&gt;
:: /**&lt;br /&gt;
:: * What makes a good checkpoint block?&lt;br /&gt;
:: *   Is surrounded by blocks with reasonable timestamps (no blocks before with a timestamp after, none after with timestamp before)&lt;br /&gt;
:: *   Contains no strange transactions&lt;br /&gt;
:: */&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Purpose of Checkpoints&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The purpose of checkpoints is primarily DoS protection. As Greg Maxwell explained on [https://bitcointalk.org/index.php?topic=194078.0 bitcointalk in 2013]: &lt;br /&gt;
&lt;br /&gt;
: User: They [checkpoints] are there so some quantum computing farm (doesn&#039;t exist, but...) can&#039;t come out of nowhere and roll back blocks by mining a long chain from far in the past.&lt;br /&gt;
&lt;br /&gt;
: gmaxwell: That&#039;s not really what they&#039;re for— though they have that effect too. Most of their usefulness is that they prevent a dos attacker from filling up bitcoin node&#039;s disk space with long runs of low difficulty blocks forked off low in the chain.  e.g. you start off with difficulty 1 blocks at block 0, now mine-able by the millions by a single asic— _MAYBE_ a chain that starts off that way could eventually turn out to be the longest so absent the checkpoints a node would happily follow an endlessly long chain of them.  They also make is so that an attacker who has complete control of your network (and thus can prevent you from hearing the longest chain from the honest bitcoin network) from putting you on a fake (low difficulty) isolated chain unless they can also trick you into running replaced software. With the checkpoints such an attacker hast to have a ton of mining power in order to continue the chain.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Origin of Checkpoints&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
According to Gavin Andresen, checkpoints were originally introduced in response to the &amp;quot;overflow&amp;quot; bug which would permit anyone to spend anyone&#039;s bitcoins. [https://bitcointalk.org/index.php?topic=1647.40 see here, page 3]&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;More info on Checkpoints:&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
: First checkpoint introduced by Satoshi in July 2010 (v0.3.2): [https://bitcointalk.org/index.php?topic=437 here]&lt;br /&gt;
: Bitcoin talk thread on checkpoints (Nov 2010):  [https://bitcointalk.org/index.php?topic=1647 here] &lt;br /&gt;
: Bitcoin talk thread (2013): [https://bitcointalk.org/index.php?topic=194078.0 here]&lt;br /&gt;
&lt;br /&gt;
==Bitcoin Core code implementing IBD==&lt;br /&gt;
&lt;br /&gt;
Most of the code is in &amp;lt;u&amp;gt;main.h/cpp&amp;lt;/u&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Block Status&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The concept of block status is important (see chapter 2 and/or &amp;lt;u&amp;gt;chain.cpp&amp;lt;/u&amp;gt;).  Your node assigns a newly received block a status and updates that status as it learns more about the block.  (The block status could also change in the future, for example if there is a re-organization and the block is no longer on the longest blockchain.)  &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Downloading Block Headers&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The code starts by downloading headers from a single peer.  &lt;br /&gt;
&lt;br /&gt;
The download begins in SendMessages (&amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt;), which is called periodically by the message-handling thread.  &lt;br /&gt;
&lt;br /&gt;
If the code sees that we  are not caught up and we haven&#039;t started syncing from anyone:&lt;br /&gt;
&lt;br /&gt;
* We send: &amp;quot;getheaders&amp;quot;&lt;br /&gt;
* Peer replies: &amp;quot;headers&amp;quot; (a chunk of 2000 headers)&lt;br /&gt;
* We send: &amp;quot;getheaders&amp;quot;&lt;br /&gt;
* Peer replies: &amp;quot;headers&amp;quot; (a chunk of 2000 headers)&lt;br /&gt;
* &amp;lt;continue...&amp;gt;&lt;br /&gt;
* Peer replies: &amp;quot;headers&amp;quot; (a chunk of LESS THAN 2000 headers)&lt;br /&gt;
&lt;br /&gt;
When the peer sends less than 2000 headers, we conclude that we reached the tip of the peer&#039;s blockchain.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Block Locators&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
A Block Locator is used to find a fork point between two nodes, which is where the nodes should start exchanging block headers. &lt;br /&gt;
&lt;br /&gt;
Here is the definition (in &amp;lt;u&amp;gt;primitives/block.h&amp;lt;/u&amp;gt;): &lt;br /&gt;
&lt;br /&gt;
  /* Describes a place in the block chain to another node such that if the&lt;br /&gt;
  * other node doesn&#039;t have the same branch, it can find a recent common trunk.&lt;br /&gt;
  * The further back it is, the further before the fork it may be.&lt;br /&gt;
  */&lt;br /&gt;
  struct CBlockLocator&lt;br /&gt;
  {&lt;br /&gt;
  std::vector&amp;lt;uint256&amp;gt; vHave;&lt;br /&gt;
   ...&lt;br /&gt;
  (a few basic constructor &amp;amp; serialization methods)&lt;br /&gt;
  ...&lt;br /&gt;
  };&lt;br /&gt;
&lt;br /&gt;
So, a Locator is basically a vector of block hashes.  The vector is populated with 32 hashes which are chosen to maximize the likelihood of quickly finding a common block with a peer.  &lt;br /&gt;
&lt;br /&gt;
In normal operation, we would generally expect to be within a few blocks of our peers.  Thus, the vector starts with the 10 last block hashes before &amp;quot;jumping back&amp;quot; exponentially.  Thus the comment &amp;quot;the futher back it is, the futher before the fork it might be:&amp;quot;  what is meant is that firstly, if you and your peer are within 10 blocks of one another, the fork point will be included in the list of hashes.  If you and your peer are 15 blocks away from one another, you&#039;ll surely find a common block that&#039;s within a few blocks of the fork point and only one further iteration of Locator will be reuqired to find the fork point.  However, if you and your peer diverge by 10,000 blocks, the Locator may only find a common trunk that&#039;s a few hundred (or more) blocks before the fork point, so another two or three Locator objects will need to be exchanged to zero in on the fork point.  &lt;br /&gt;
&lt;br /&gt;
See CChain::GetLocator and CBlockIndex::GetAncestor [both in &amp;lt;u&amp;gt;chain.cpp&amp;lt;/u&amp;gt;].&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Block Skiplist Pointer&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Every block index contains the following attribute: &lt;br /&gt;
&lt;br /&gt;
  // pointer to the index of some further predecessor of this block&lt;br /&gt;
  CBlockIndex* pskip;&lt;br /&gt;
&lt;br /&gt;
The algorithm for choosing a given block&#039;s &amp;quot;skip pointer&amp;quot; is in &amp;lt;u&amp;gt;chain.cpp&amp;lt;/u&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
  // Determine which height to jump back to. Any number strictly lower than height is acceptable,&lt;br /&gt;
  // but the following expression seems to perform well in simulations (max 110 steps to go back&lt;br /&gt;
  // up to 2**18 blocks).&lt;br /&gt;
  return (height &amp;amp; 1) ? InvertLowestOne(InvertLowestOne(height - 1)) + 1 : InvertLowestOne(height)&lt;br /&gt;
  InvertLowestOne(int n) { return n &amp;amp; (n - 1); }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The skip pointer is used to move through the blockchain in O(log n) rather than walking the chain in O(n).&lt;br /&gt;
&lt;br /&gt;
The idea behind a &amp;quot;skip list&amp;quot; is described here: [https://en.wikipedia.org/wiki/Skip_list Wikipedia page for skiplist]&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Processing the Block Headers&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Code path: &lt;br /&gt;
ProcessMessage (entry point) &lt;br /&gt;
AcceptBlockHeader&lt;br /&gt;
CheckBlockHeader (non-contextual validation checks)&lt;br /&gt;
ContextualCheckBlockHeader  (blockchain-aware validation checks) &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;u&amp;gt;Non-Contextual Checks&amp;lt;/u&amp;gt;&lt;br /&gt;
&lt;br /&gt;
These checks are &amp;quot;non-contextual&amp;quot; because they do not require any knowledge of the state of our blockchain. &lt;br /&gt;
&lt;br /&gt;
1) Proof-of-Work Meets Claimed Requirement:  Here, the code checks that the block has the POW that the miner claims was necessary when constructing the block.  Later, we&#039;ll re-check it against our blockchain.  An honest miner should always pass both checks.  Only a miner who lies about the required POW (block.nBits) would pass this check but fail the contextual check. &lt;br /&gt;
&lt;br /&gt;
2) Timestamp not-too-late:  The code checks that the timestamp is less than 2 days in the future.  This is context-independent because the code just compares the block&#039;s timestamp against the system time. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;u&amp;gt; Contextual Checks &amp;lt;/u&amp;gt;&lt;br /&gt;
&lt;br /&gt;
These checks require some knowledge of our node&#039;s blockchain. &lt;br /&gt;
&lt;br /&gt;
1) Re-check Proof of Work:  Here, we re-check the POW based on our own knowledge of the difficulty target (rather than trusting the difficulty the miner placed in the block&#039;s nBits). &lt;br /&gt;
&lt;br /&gt;
2) Checkpoints (if enabled):  If this block&#039;s height is a checkpoint, the block hash matches the hash stored in the checkpoint map.  (see checkpoint.cpp).&lt;br /&gt;
&lt;br /&gt;
3) Timestamp not-too-early:  Here, we check that the block&#039;s timestamp is not prior to the previous block&#039;s median time (of the previous 11 blocks).  This guarantees that the median time continues to advance from block to block.  Obviously, this check is context-dependent because it requires knowledge of prior blocks in the active chain, which is obtained by retrieving the block from mapBlockIndex.  For more info, see [BIP 113].&lt;br /&gt;
&lt;br /&gt;
4) Version number&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;u&amp;gt;Add the Block&amp;lt;/u&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Finally, add the block to mapBlockIndex and update pIndexBestHeader (see AddToBlockIndex()).  &lt;br /&gt;
&lt;br /&gt;
At this point, the block indexes are VALID_TREE, since we know they are on the main chain, but we haven&#039;t yet received the transactions.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Downloading Blocks&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Your node will start downloading blocks from the peer that it is downloading headers from right away.  &lt;br /&gt;
&lt;br /&gt;
This is so because: &lt;br /&gt;
* The headers-peer is surely a preferred-download peer, set when you received its &amp;quot;version&amp;quot; message (&amp;lt;u&amp;gt;main.cpp:4056&amp;lt;/u&amp;gt;).&lt;br /&gt;
* Thus, your node will call FindNextBlocksToDownload for your headers-peer (&amp;lt;u&amp;gt;main.cpp:5143&amp;lt;/u&amp;gt;). &lt;br /&gt;
* Your headers-peer will have a valid pIndexBestKnownBlock (&amp;lt;u&amp;gt;main.cpp:421&amp;lt;/u&amp;gt;), since that was set in UpdateBlockAvailability() when you received the peer&#039;s headers (&amp;lt;u&amp;gt;main.cpp:4532&amp;lt;/u&amp;gt;).&lt;br /&gt;
* FindNextBlocksToDownload will return a vector of block hashes, which you&#039;ll then request (see &amp;lt;u&amp;gt;main.cpp:5145&amp;lt;/u&amp;gt; [add block to the request vector] and &amp;lt;u&amp;gt;main.cpp:5178&amp;lt;/u&amp;gt; [send getdata msg to your headers-peer]).&lt;br /&gt;
&lt;br /&gt;
However, you will not start downloading blocks from the other peers until IBD is complete.  &lt;br /&gt;
&lt;br /&gt;
This is so because: &lt;br /&gt;
* Your other peers are probably also preferred-download peers, so you&#039;ll call FindNextBlockToDownload just like with your headers-peer. &lt;br /&gt;
* However, that function call will return immediately because it won&#039;t be able to find any available blocks. &lt;br /&gt;
* When IBD concludes (see discussion below), you&#039;ll start exchanging headers with the other peers. &lt;br /&gt;
* Once you&#039;ve exchanged headers with your other peers, you&#039;ll start requesting blocks. &lt;br /&gt;
&lt;br /&gt;
Blocks are downloaded in chunks of 16 blocks at a time from each peer.  With a block size of 1MB, if blocks are full we are talking about 16MB chunks.  (See main.h - &amp;quot;MAX_BLOCKS_IN_TRANSIT_PER_PEER&amp;quot;.)  &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Moving Window&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The download code uses a &amp;quot;moving window&amp;quot; of 1024 blocks.  The idea is that although you are downloading different chunks from multiple peers, at any given time the blocks you are downloading are fairly close together.  The main purpose of this is so that blocks that are near one another on the blockchain are most likely contained in the same .dat file (where the raw block data is stored on disk).  One advantage of having a correlation between blockchain location and block file location is that if the node chooses to &amp;quot;prune&amp;quot; block data at a later date, it&#039;s easier to delete older block files.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Disconnecting a peer&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The code disconnects slow peers in order to keep the download moving.  The peer can be disconnect under two scenarios.  &lt;br /&gt;
&lt;br /&gt;
First, any block requested from the peer must be delivered within a certain timeframe. &lt;br /&gt;
&lt;br /&gt;
Usually, this timeframe is 20 minutes.&lt;br /&gt;
&lt;br /&gt;
The following code is in &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt;: &lt;br /&gt;
     GetBlockTimeout(...) { return nTime + 500000 * consensusParams.nPowTargetSpacing * (4 + nValidatedQueuedBefore);}&lt;br /&gt;
&lt;br /&gt;
nValidatedQueuedBefore are the number of blocks that are in flight to us and which we have validated.  Let&#039;s call that N. &lt;br /&gt;
&lt;br /&gt;
If N = 0, this code evaluates as: &lt;br /&gt;
: = 500,000 microseconds (1/2 second) * 600 seconds (the target block interval) * 4 &lt;br /&gt;
: = 0.5 seconds * 600 seconds * 4 &lt;br /&gt;
: = 1,200 seconds&lt;br /&gt;
: = 20 minutes&lt;br /&gt;
&lt;br /&gt;
The formula can be simplified as: &lt;br /&gt;
: = 0.5 * (4 + N) * block_interval&lt;br /&gt;
: = (2 + 0.5 * N) * block_interval&lt;br /&gt;
&lt;br /&gt;
Thus: &lt;br /&gt;
: N=0, timeout = 2 * block_interval = 20 minutes.&lt;br /&gt;
: N=10, timeout = 7 * block_interval = 70 minutes. &lt;br /&gt;
: N=30, timeout = 17 * block_interval = 170 minutes.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The second circumstance where we will disconnect a peer is where the peer manages to stall your entire download by preventing the moving window from progressing.  Imagine your moving window is blocks 1000 to 2024 and you&#039;ve downloaded everything from 1016 to 2024, but are waiting for Alice to serve up 1000 to 1016, which you may have requsted a few minutes earlier.  In this siutation, if Alice continues to stall the moving window for 2 seconds, you will drop Alice and replace her with a more reliable peer. In the mantime, your node will request blocks 1000 to 1016 from one of your other peers so your moving window can start moving again.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Requesting Blocks&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Requesting blocks is handled by sending out a &amp;quot;getdata&amp;quot; message (see main.cpp:5137 in v0.11).  A &amp;quot;getdata&amp;quot; message is used to pack a vector of &amp;quot;inv&amp;quot; messages and send as a group.  Thus, we can request 16 blocks from the peer with one network message, as opposed to sending 16 separate &amp;quot;inv&amp;quot; messages.&lt;br /&gt;
&lt;br /&gt;
What blocks do we request?  The code to figure that out is in FindNextBlocksToDownload; it uses a &#039;&#039;&#039;block locator&#039;&#039;&#039; to figure out the last block we have in common with this peer, and starts from there.  A block locator is a homemade algorithm that efficiently finds the fork point between our node and a given peer.  The locator will pack a list of 32 blocks, starting with the last 10 (since in steady-state we are usually within 10 blocks of our peers), and then jumping back exponentially.  (&amp;lt;u&amp;gt;chain.cpp:25&amp;lt;/u&amp;gt;). &lt;br /&gt;
&lt;br /&gt;
This algorithm has proven to be effective at locating the fork point. &lt;br /&gt;
 &lt;br /&gt;
Once we&#039;ve prepared the &amp;quot;getdata&amp;quot; message, we mark the blocks that we&#039;ve requested as being &amp;quot;in flight&amp;quot; - with MarkBlocksAsInFlight (main.cpp).&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Receiving Blocks&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The entry point for receiving blocks is in ProcessMessage, when our node receives a &amp;quot;block&amp;quot; message from a peer.  &lt;br /&gt;
&lt;br /&gt;
The block is processed with ProcessNewBlock (main.cpp):&lt;br /&gt;
&lt;br /&gt;
: 1) Checks on the block&lt;br /&gt;
:: a)  Basic, context-independent checks on the block (merkle root, block size, etc)&lt;br /&gt;
:: b)  Basic, context-independent on transactions within the block  (transaction size, etc.)&lt;br /&gt;
:: c)  Check that we requested this block (if unrequested, this may be a DOS attack - though not necessarily) &lt;br /&gt;
:: d)  Context-dependent checks on the block&lt;br /&gt;
&lt;br /&gt;
: 2)  Store the block to disk &lt;br /&gt;
&lt;br /&gt;
: 3)  General check on the integrity of our blockchain (this may sound expensive, but is very fast)&lt;br /&gt;
&lt;br /&gt;
: 4)  Connect the block to the blockchain - if appropriate (see ActivateBestChain)&lt;br /&gt;
&lt;br /&gt;
Note that the block&#039;s transactions are not validated (checked for a double-spend, etc.) until the last step, when the block is connected as the new tip of the blockchain.  For more info, see below &amp;quot;Connecting a Block&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
==Monitoring the Download==&lt;br /&gt;
&lt;br /&gt;
You can monitor the download with the RPC call getpeerinfo, which shows (for each peer that you&#039;re connected to):&lt;br /&gt;
&lt;br /&gt;
* &amp;quot;synced_headers&amp;quot;: The last header we have in common with this peer&lt;br /&gt;
* &amp;quot;synced blocks&amp;quot;: The last block in commen with this peer&lt;br /&gt;
* &amp;quot;inflight&amp;quot;: The heights of blocks we&#039;re currently requesting from this peer&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==See also==&lt;br /&gt;
[https://en.bitcoin.it/wiki/Bitcoin_Core_0.11_(ch_1):_Overview Bitcoin Core 0.11 (Ch 1): Overview]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[https://en.bitcoin.it/wiki/Bitcoin_Core_0.11_(ch_2):_Data_Storage Bitcoin Core 0.11 (Ch 2): Data Storage]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[https://en.bitcoin.it/wiki/Bitcoin_Core_0.11_(ch_3):_Initialization_and_Startup Bitcoin Core 0.11 (Ch 3): Initialization and Startup]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[https://en.bitcoin.it/wiki/Bitcoin_Core_0.11_(ch_4):_P2P_Network Bitcoin Core 0.11 (Ch 4): P2P Network]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[https://en.bitcoin.it/wiki/Bitcoin_Core_0.11_(ch_6):_The_Blockchain Bitcoin Core 0.11 (Ch 6): The Blockchain]&lt;br /&gt;
&lt;br /&gt;
[[Category:Technical]]&lt;br /&gt;
[[Category:Developer]]&lt;/div&gt;</summary>
		<author><name>Mrbandrews</name></author>
	</entry>
	<entry>
		<id>https://en.bitcoin.it/w/index.php?title=Bitcoin_Core_0.11_(ch_3):_Initialization_and_Startup&amp;diff=60026</id>
		<title>Bitcoin Core 0.11 (ch 3): Initialization and Startup</title>
		<link rel="alternate" type="text/html" href="https://en.bitcoin.it/w/index.php?title=Bitcoin_Core_0.11_(ch_3):_Initialization_and_Startup&amp;diff=60026"/>
		<updated>2016-01-21T20:32:03Z</updated>

		<summary type="html">&lt;p&gt;Mrbandrews: edit footer&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
This page describes the Bitcoin Core code that manages startup and initialization. &lt;br /&gt;
&lt;br /&gt;
==Program entry point== &lt;br /&gt;
&lt;br /&gt;
The program&#039;s entry point can be found in &amp;lt;u&amp;gt;bitcoind.cpp&amp;lt;/u&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
main() is three lines of code:&lt;br /&gt;
* SetupEnvironment() (all this does is set the program&#039;s locale)&lt;br /&gt;
* Connect signal handlers&lt;br /&gt;
* AppInit() (this function loops for the life of the program)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
AppInit:  this is located nearby in &amp;lt;u&amp;gt;bitcoind.cpp&amp;lt;/u&amp;gt;: &lt;br /&gt;
* Parses the command line&lt;br /&gt;
* Opens the data directory&lt;br /&gt;
* Reads the config file&lt;br /&gt;
* Forks a process (if running as a daemon)&lt;br /&gt;
* Passes control to AppInit2(), found in &amp;lt;u&amp;gt;init.cpp&amp;lt;/u&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Initialization steps (&amp;lt;u&amp;gt;init.cpp&amp;lt;/u&amp;gt;)==&lt;br /&gt;
&lt;br /&gt;
AppInit2() initializes the bitcoin system.  &lt;br /&gt;
&lt;br /&gt;
It contains about 800 lines of code, which are broken into 12 steps.  &lt;br /&gt;
&lt;br /&gt;
Where each step begins is documented in the code. &amp;lt;u&amp;gt;Init.cpp&amp;lt;/u&amp;gt; has a few functions at the top of the file, but for the most part it consists of AppInit2(). &lt;br /&gt;
&lt;br /&gt;
The following table summarizes the steps: &lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! Initialization&amp;lt;br&amp;gt;Step !! Short Description !! Longer Description&lt;br /&gt;
|-&lt;br /&gt;
| 1 || OS-specific setup tasks || These tasks are not particularly interesting.&amp;lt;br&amp;gt;For more info, see the code.  &lt;br /&gt;
|-&lt;br /&gt;
| 2 || Parameter Interactions || Certain command-line options require other options to be set in a certain way.&amp;lt;br&amp;gt;For example, -zapwallettxes implies a -rescan, thus the code will set the -rescan flag=true if it isn&#039;t already.  &lt;br /&gt;
|-&lt;br /&gt;
| 3 || Internal flags / &amp;lt;br&amp;gt;Parameter sanity-check || Sets global variables for certain parameters.&amp;lt;br&amp;gt;For the wallet, it sanity-checks transaction fee levels (makes sure your fee is high enough to qualify for relay [error]; but not absurdly high [warning]).  &lt;br /&gt;
|-&lt;br /&gt;
| 4 || Application init. / RPC Server || &lt;br /&gt;
Locks the data directory.  (If unable, print error and quit.)&amp;lt;br&amp;gt;&lt;br /&gt;
Spawn X threads for the Script-checking engine. (Default=0, meaning use all available processors; boost::thread::hardware_concurrency).&amp;lt;br&amp;gt;&lt;br /&gt;
Start RPC server in &amp;quot;warmup&amp;quot; mode. &lt;br /&gt;
|-&lt;br /&gt;
| 5 || Verify wallet database integrity || If wallet is enabled, try to open it.&amp;lt;br&amp;gt;&lt;br /&gt;
If the user knows that the wallet has been corrupted (-salvagewallet), try to recover the private keys.  &lt;br /&gt;
|-&lt;br /&gt;
| 6 || Network Initialization || &lt;br /&gt;
The node registers for certain signals.&amp;lt;br&amp;gt;&lt;br /&gt;
Checks whether the user wants to interact only with peers on a certain network (ip4, ip6, tor).&amp;lt;br&amp;gt;&lt;br /&gt;
Checks whether to use onion routing (tor).&amp;lt;br&amp;gt;&lt;br /&gt;
Checks whether the user wants to whitelist any specific peers.&amp;lt;br&amp;gt;&lt;br /&gt;
Attempts to listen on the bitcoin port (exits on failure).&amp;lt;br&amp;gt;&lt;br /&gt;
If user specified a certain peer to seed connections, attempt to connect.  &lt;br /&gt;
|-&lt;br /&gt;
| 7 || Load the block chain. || &lt;br /&gt;
Load the blockchain into memory and initialize the UTXO caches.&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;u&amp;gt;Calculate cache sizes.&amp;lt;/u&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
There is a total cache size, which is divided amongst three specific caches.&amp;lt;br&amp;gt; &lt;br /&gt;
Default total cache size = 100MB (Max: 4 GB, min: 4 MB).&amp;lt;br&amp;gt;  &lt;br /&gt;
1) Blockchain cache:  1/8 of the total cache, but shouldn&#039;t be larger than 2MB.&amp;lt;br&amp;gt;&lt;br /&gt;
2) UTXO database cache : 25-50% of the remaining cache space.  This is the LevelDB cache.&amp;lt;br&amp;gt;&lt;br /&gt;
This stores uncompressed blocks of LevelDB data and is managed by LevelDB, as described in [http://leveldb.googlecode.com/git-history/1.17/doc/index.html the LevelDB documentation.]&amp;lt;br&amp;gt;&lt;br /&gt;
3) UTXO in-memory cache: Half of the remaining cache space.&amp;lt;br&amp;gt;&lt;br /&gt;
This cache size defines the size of the cacheCoins object (a protected member of CoinsViewCache).&amp;lt;br&amp;gt;&lt;br /&gt;
TODO: verify that this statement is correct... &amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;u&amp;gt;Load the blockchain into mapBlockIndex.&amp;lt;/u&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
By &amp;quot;blockchain&amp;quot; this means the entire block tree (all known blocks, not just those in the active chain.)&amp;lt;br&amp;gt;&lt;br /&gt;
What is loaded into memory are the CBlockIndex objects, which contain metadata about the block. &amp;lt;br&amp;gt;&lt;br /&gt;
Verifies the last 288 blocks (VerifyDB).&amp;lt;br&amp;gt;&lt;br /&gt;
Note: The program takes less than 1 second from startup until this point;  this step takes about 10-20 seconds.&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;u&amp;gt;The UTXO set.&amp;lt;/u&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
The UTXO set is not loaded into memory; instead, the cache will be filled as coins are accessed from the database.&amp;lt;br&amp;gt;&lt;br /&gt;
Note that as of May 2015, storing the entire UTXO set in memory would require about 3.6 GB.&amp;lt;br&amp;gt;&lt;br /&gt;
As of Jan. 2016, the compressed data on disk is about 1.2 GB. &lt;br /&gt;
|-&lt;br /&gt;
| 8 || Load the wallet.  || If this is the first time the program has been run, it creates a wallet and gives you an initial key (address).&lt;br /&gt;
|-&lt;br /&gt;
| 9 || Datadir maintenance || If the user is block-pruning, unset NODE_NETWORK and call the pruning function.&lt;br /&gt;
|-&lt;br /&gt;
| 10 || Import blocks || Scan for better chains in the block chain database, that are not yet connected as the active best chain.&lt;br /&gt;
|-&lt;br /&gt;
| 11 || Start node /&amp;lt;br&amp;gt;RPC server || &lt;br /&gt;
Calls StartNode in net.cpp.&amp;lt;br&amp;gt;&lt;br /&gt;
This starts up the networking thread group, including ThreadProcessMessage, which is the program&#039;s main thread (see below). &amp;lt;br&amp;gt;&lt;br /&gt;
Transition RPC server from &amp;quot;warmup&amp;quot; mode to normal mode.&lt;br /&gt;
|-&lt;br /&gt;
| 12 || Finished&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
When AppInit2 finishes, control returns to AppInit() in &amp;lt;u&amp;gt;bitcoind.cpp&amp;lt;/u&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
There, the code&#039;s top-level thread loops indefinitely in a function called WaitForShutdown().  It sleeps for 2 seconds and checks to see if the user pressed ctrl-C.  If so, it calls Shutdown() back in &amp;lt;u&amp;gt;init.cpp&amp;lt;/u&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Shutdown() shuts down the RPC server, stops the node, unregisters the signal handlers, etc., and then the program completes.&lt;br /&gt;
&lt;br /&gt;
==Cache Sizes==&lt;br /&gt;
&lt;br /&gt;
Step 7 initialized the cache sizes.  There are 3 caches contemplated in step 7.  Two are LevelDB database caches and the other is the coins cache, whose size is managed by the flushing code in &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt;. &lt;br /&gt;
&lt;br /&gt;
The user can allocate a total cache size with -dbcache.  The user cannot pick and choose how much space to allocate to each specific cache. The default total cache size = 100MB (Max: 4 GB, min: 4 MB).  &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;1) Block index cache&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
This cache stores uncompressed chunks of the /blocks/index LevelDB data and is managed by LevelDB, as described in [http://leveldb.googlecode.com/git-history/1.17/doc/index.html the LevelDB documentation.]&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the user enables a full transaction index (-txindex=1) it can be up to 1/8 of the total cache size.  If -txindex is not enabled then only 2 MiB is needed. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;2) UTXO database cache&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
This is the LevelDB cache for the /chainstate database. &lt;br /&gt;
&lt;br /&gt;
This cache is allocated 25-50% of the remaining cache space, depending on the total cache size. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;3)  UTXO in-memory cache&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
This is the coins cache that is managed by the &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt; code. (see FlushStateToDisk and related functions) &lt;br /&gt;
&lt;br /&gt;
The variable (nCoinsCache) is declared as extern in &amp;lt;u&amp;gt;main.h&amp;lt;/u&amp;gt;.  In &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt;, it is hard-coded to 5000 * 300 (in-memory coins are about 300 bytes, so this means 5000 coins), however it should be re-initialized in Step 7. &lt;br /&gt;
&lt;br /&gt;
This cache is given all of the remaining cache space. &lt;br /&gt;
&lt;br /&gt;
This cache is not loaded during initialization, rather it is filled as coins are accessed.  (This can be verified by the CCoinsViewCache constructor, which sets cachedCoinsUsage=0.)&lt;br /&gt;
&lt;br /&gt;
==Thread Startup==&lt;br /&gt;
&lt;br /&gt;
The code uses boost::thread_groups to manage the various threads.&lt;br /&gt;
&lt;br /&gt;
It should be noted that although Bitcoin Core is a multi-threaded program, &amp;quot;the reference Satoshi client is largely single-threaded.&amp;quot; [https://github.com/bitcoin/bips/blob/master/bip-0031.mediawiki Comment by Mike Hearn in BIP 31 (2012)]&lt;br /&gt;
&lt;br /&gt;
What is meant is that the vast majority of the program&#039;s activity takes place in the messaging thread (ThreadMessageHandler - see below.)  &lt;br /&gt;
&lt;br /&gt;
Almost all of the threads are part of a single, master thread group that is created on the stack at program startup (see &amp;lt;u&amp;gt;bitcoind.cpp&amp;lt;/u&amp;gt;).  This thread group is passed to &amp;lt;u&amp;gt;init.cpp&amp;lt;/u&amp;gt; which creates a few child threads (including a number of script-checking threads, but these are all part of the master thread group, not a separate group.)&lt;br /&gt;
&lt;br /&gt;
The thread group is passed to &amp;lt;u&amp;gt;net.cpp&amp;lt;/u&amp;gt;, which creates the networking threads, including the message-processing thread. &lt;br /&gt;
&lt;br /&gt;
The two other thread groups are task-specific: &lt;br /&gt;
* rpc server thread group (see &amp;lt;u&amp;gt;rpcserver.h/cpp&amp;lt;/u&amp;gt;)&lt;br /&gt;
* miner thread group&lt;br /&gt;
&lt;br /&gt;
Naturally, the node will only create the RPC server thread group if the RPC server is activated, and will only create the miner thread group if it is mining.  If both are disabled, then Bitcoin Core only has a single thread group. &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Child Threads&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The parent thread (meaning the thread in which the program begins operating) delegates almost all of the program&#039;s work to child threads.  After spawning threads in &amp;lt;u&amp;gt;init.cpp&amp;lt;/u&amp;gt; and &amp;lt;u&amp;gt;net.cpp&amp;lt;/u&amp;gt;, the parent thread simply listens for a shutdown command, at which time the parent thread needs only to interrupt the threads in its thread group and proceed with shutdown. &lt;br /&gt;
&lt;br /&gt;
The child threads are summarized in this table, listed in the order in which they are created: &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! Thread !! When / Where Created !! Description&lt;br /&gt;
|-&lt;br /&gt;
| Script-checking || Step 4&amp;lt;br&amp;gt;init.cpp || This is a set of threads - 4 by default.&amp;lt;br&amp;gt;Script-checking (including signature checking) is expensive so is handled in separate threads.&lt;br /&gt;
|-&lt;br /&gt;
| Scheduler || Step 4&amp;lt;br&amp;gt;init.cpp ||  Scheduler thread.&amp;lt;br&amp;gt; (TODO: describe)&lt;br /&gt;
|-&lt;br /&gt;
| RPC Threads || Step 4&amp;lt;br&amp;gt;rpcserver.cpp ||  If RPC server enabled, start a group of threads to handle RPC calls. &lt;br /&gt;
|-&lt;br /&gt;
| Import || Step 10&amp;lt;br&amp;gt;init.cpp ||   Imports blocks. Three scenarios:&amp;lt;br&amp;gt;1) Reindex (rescan all known blocks from blk???.dat files).&amp;lt;br&amp;gt;2) Bootstrap (use bootstrap.dat as an alternative to full IBD from the network.)&amp;lt;br&amp;gt;3) -loadblock (scan a specific blk???.dat file)&amp;lt;br&amp;gt;If none of those apply, this thread does nothing.&lt;br /&gt;
|-&lt;br /&gt;
| DNSAddressSeed || Step 11&amp;lt;br&amp;gt;net.cpp || Attempts to build a vector of IP addresses based on the dns seeds, stores the vector and the thread exits.&amp;lt;br&amp;gt;In a test in June 2014, this took about 4 seconds and found 158 addresses. &lt;br /&gt;
|-&lt;br /&gt;
| Plug &amp;amp; Play || Step 11&amp;lt;br&amp;gt;net.cpp ||  UPNP (Universal Plug &amp;amp; Play) &amp;lt;br&amp;gt;Deals with port mapping for UPNP.&lt;br /&gt;
|-&lt;br /&gt;
| SocketHandler || Step 11&amp;lt;br&amp;gt;net.cpp || &amp;lt;u&amp;gt;This thread services the sockets:&amp;lt;/u&amp;gt;&amp;lt;br&amp;gt;Waits for I/O on all the relevant sockets with a 50ms timeout.&amp;lt;br&amp;gt;Processes new incoming connections on listening socket and creates a CNode for the new peer.&amp;lt;br&amp;gt;Receives and sends data streams.&amp;lt;br&amp;gt;Sets sockets that have not done anything to a disconnected state.&lt;br /&gt;
|-&lt;br /&gt;
| OpenAddedConnections || Step 11&amp;lt;br&amp;gt;net.cpp || Initiates outbound connections specified by the user with the –addnode parameter.&amp;lt;br&amp;gt;If can&#039;t connect, sleeps for 2 minutes each cycle.&lt;br /&gt;
|-&lt;br /&gt;
| OpenConnections || Step 11&amp;lt;br&amp;gt;net.cpp || Initiates other outbound connections from DNS seeds (if that fails, find nodes based on fixed seeds)&amp;lt;br&amp;gt;If can&#039;t connect, sleeps for 500 milliseconds each cycle.&lt;br /&gt;
|-&lt;br /&gt;
| MessageHandler || Step 11&amp;lt;br&amp;gt;net.cpp || &amp;lt;u&amp;gt;This is the program&#039;s main thread.&amp;lt;/u&amp;gt; &amp;lt;br&amp;gt; This thread runs a while(true) loop, receiving and sending messages.  (See &amp;lt;u&amp;gt;net.cpp&amp;lt;/u&amp;gt;:1049) &amp;lt;br&amp;gt;The code uses boost::signals2 to call the ProcessMessages and SendMessages functions in main.cpp.&amp;lt;br&amp;gt;(The code introducing signals is in PR 2154 - see the next-to-last commit in that pull.)&amp;lt;br&amp;gt;ProcessMessage and SendMessage run in this thread.&amp;lt;br&amp;gt;So, most of the code in &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt; runs in this thread.&lt;br /&gt;
|-&lt;br /&gt;
| Wallet Flusher || Step 12&amp;lt;br&amp;gt;init.cpp || If wallet is enabled, this thread flushes the wallet periodically.&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==See also==&lt;br /&gt;
[https://en.bitcoin.it/wiki/Bitcoin_Core_0.11_(ch_1):_Overview Bitcoin Core 0.11 (Ch 1): Overview]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[https://en.bitcoin.it/wiki/Bitcoin_Core_0.11_(ch_2):_Data_Storage Bitcoin Core 0.11 (Ch 2): Data Storage]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[https://en.bitcoin.it/wiki/Bitcoin_Core_0.11_(ch_4):_P2P_Network Bitcoin Core 0.11 (Ch 4): P2P Network]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[https://en.bitcoin.it/wiki/Bitcoin_Core_0.11_(ch_5):_Initial_Block_Download Bitcoin Core 0.11 (Ch 5): Initial Block Download]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[https://en.bitcoin.it/wiki/Bitcoin_Core_0.11_(ch_6):_The_Blockchain Bitcoin Core 0.11 (Ch 6): The Blockchain]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Technical]]&lt;br /&gt;
[[Category:Developer]]&lt;/div&gt;</summary>
		<author><name>Mrbandrews</name></author>
	</entry>
	<entry>
		<id>https://en.bitcoin.it/w/index.php?title=Bitcoin_Core_0.11_(ch_1):_Overview&amp;diff=60025</id>
		<title>Bitcoin Core 0.11 (ch 1): Overview</title>
		<link rel="alternate" type="text/html" href="https://en.bitcoin.it/w/index.php?title=Bitcoin_Core_0.11_(ch_1):_Overview&amp;diff=60025"/>
		<updated>2016-01-21T20:31:32Z</updated>

		<summary type="html">&lt;p&gt;Mrbandrews: edit footer&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
==Organization &amp;amp; Maintenance of these Pages==&lt;br /&gt;
&lt;br /&gt;
The purpose of this set of Wiki pages is to document the Bitcoin Core C++ source code, in a way that is helpful to the programmer who wants to learn how the program is designed and what the code does. &lt;br /&gt;
&lt;br /&gt;
Ideally, the accuracy of the information on these pages would be checked by developers who are getting up to speed on the Bitcoin Core code base.  Additionally, each new release of Bitcoin Core (0.12, 0.13, etc) could have a new set of pages that are modified to match that version.&lt;br /&gt;
&lt;br /&gt;
These pages are loosely based on the set of pages called &amp;quot;Satoshi Client: xxx&amp;quot; (on this Wiki) which were written in 2011 and based on version 0.3. &lt;br /&gt;
&lt;br /&gt;
This set of Wiki pages includes: &lt;br /&gt;
&lt;br /&gt;
* Ch 1: Intro &amp;amp; Overview (this page) &lt;br /&gt;
* Ch 2: Data Storage&lt;br /&gt;
* Ch 3: Initialization &amp;amp; Startup&lt;br /&gt;
* Ch 4: P2P Network&lt;br /&gt;
* Ch 5: Initial Block Download (IBD)&lt;br /&gt;
* Ch 6: Blockchain&lt;br /&gt;
* Ch 7: Transactions &amp;amp; the Memory Pool&lt;br /&gt;
* Ch 8: RPC Server&lt;br /&gt;
&lt;br /&gt;
These pages document the &amp;quot;relay node&amp;quot; aspect of Bitcoin Core, meaning a node which validates blocks and transactions and relays them to other nodes. The node has fully validated the blockchain, although it may not necessarily maintain a full copy of it on disk. &lt;br /&gt;
&lt;br /&gt;
These pages do NOT cover: &lt;br /&gt;
* Wallet&lt;br /&gt;
* GUI (Qt)&lt;br /&gt;
* Mining&lt;br /&gt;
&lt;br /&gt;
==Definitions==&lt;br /&gt;
&lt;br /&gt;
A few definitions at the outset:  &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Consensus code&#039;&#039;&#039; &lt;br /&gt;
&lt;br /&gt;
Code that validates blocks and transactions.  &lt;br /&gt;
&lt;br /&gt;
Consensus code must have bug-for-bug compatibility across versions and implementations (meaning, 0.12 must have the same consensus behaviour as 0.11, even if it is buggy;  otherwise, a network fork may result.) &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Policy code&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Code that implements a particular node&#039;s policy (as opposed to consensus).  A node&#039;s algorithm for which transactions to store in its transaction pool is an example of policy.  For example, a node could refuse to relay or store any transaction that is larger than 200KB.  What is important is that if such a transaction is transmitted to the node as part of a newly mined block, the node does not reject the block.   &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;P2P code&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Code relating to communications with other nodes (peers) over the P2P network.  Communication includes discovering and connecting to other nodes; exchanging various P2P messages (e.g., messages containing blocks and transactions); occasionally, banning misbehaving peers. The bitcoin network uses a custom set of P2P messages.  Most of the P2P code can be found in &amp;lt;u&amp;gt;net.h/net.cpp&amp;lt;/u&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Mempool (&amp;quot;memory pool&amp;quot; or &amp;quot;transaction pool&amp;quot;)&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
A set of transactions which the node knows about and chooses to store in memory and relay to other nodes, and which have not yet been included in a block.  In many cases, this may be the full set of transactions that the node has received and validated.  If the node has received transactions that violate its policy, however, the mempool will be a subset.  In any event, when the node receives and validates a block, it deletes any transactions in the block from its mempool.  &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Full Node&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
A full node is one that validates blocks and transactions and relays them to other nodes.  A full node has validated the blockchain from scratch (although with block file pruning, it may have discarded older parts of the chain to clear up disk space.) The key characteristic of a full node is that it has validated the blockchain and continues to fully validate and relay incoming blocks and transactions.  A full node can be differentiated from an SPV node, which trusts another node (or set of nodes) to validate. &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;&amp;quot;Basic Full Node&amp;quot;&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
A &amp;quot;basic full node&amp;quot; is what is documented in these pages.  By &amp;quot;basic full node,&amp;quot; what is meant is a node that validates and relays blocks and transactions, but does not mine new blocks or perform other optional tasks (RPC server, wallet).  Extending these pages to include documentation of these optional aspects of a node is a future project.&lt;br /&gt;
&lt;br /&gt;
==Architecture of a Bitcoin Node==&lt;br /&gt;
&lt;br /&gt;
One developer described the architecture of a basic full node as follows: &lt;br /&gt;
&lt;br /&gt;
: --------------------&lt;br /&gt;
&lt;br /&gt;
: The basic architecture of a bitcoin node is as follows:&lt;br /&gt;
&lt;br /&gt;
: At the core there exist fundamental bitcoin message structures, along with the code necessary for serialization/deserialization. These structures belong in their own source files with minimal dependencies so they can be reused for applications that needn&#039;t perform verification and relay - for instance, filtering and notification agents. Unfortunately, these core structures currently reside for the most part in main.h/main.cpp...&lt;br /&gt;
&lt;br /&gt;
: On top of these core structures sits a network component that manages sockets, does peer discovery, and handles queueing and dispatching of messages. This component is clearly dependent on the core message structures but does not depend on the specific logic used to verify blocks and transactions nor to identify misbehaving peers nor sign transactions nor maintain a block chain database.&lt;br /&gt;
&lt;br /&gt;
: Then we have a scripting engine, signature verification component, and a signing component. Historical database applications do not need signature verification/signing functionality at all. Filtering messages and sending alerts generally does not even require a scripting engine and does fine with basic pattern matching.&lt;br /&gt;
&lt;br /&gt;
: The most critical high-level operations needed by a verification/relay node such as the satoshi client are transaction verification; block chain and memory pool management; and detection/management of misbehaving peers. These things are currently primarily implemented in main.h/main.cpp. These are indeed the main operations of the satoshi client - but the core low-level structures should not depend at all on this logic.&lt;br /&gt;
&lt;br /&gt;
: ---------------------&lt;br /&gt;
&lt;br /&gt;
See here: [https://github.com/bitcoin/bitcoin/pull/2154 PR 2154]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In the form of a (crude) picture: &lt;br /&gt;
 &lt;br /&gt;
   Validating transactions; Managing blockchain, mempool, and peers.&lt;br /&gt;
                    | &lt;br /&gt;
       Scripting engine / Signatures&lt;br /&gt;
                    | &lt;br /&gt;
              Network layer&lt;br /&gt;
                    | &lt;br /&gt;
              P2P Messages&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
And here is the same picture, augmented with the definitions above: &lt;br /&gt;
 &lt;br /&gt;
   Validating transactions; Managing blockchain, mempool, peers  (Consensus and Policy code)&lt;br /&gt;
                    | &lt;br /&gt;
       Scripting engine / Signatures (Consensus code)&lt;br /&gt;
                    | &lt;br /&gt;
              Network layer  (P2P code) &lt;br /&gt;
                    | &lt;br /&gt;
              P2P Messages&lt;br /&gt;
&lt;br /&gt;
==Code Modularization / Organization==&lt;br /&gt;
&lt;br /&gt;
As of 0.11, modularization of the Bitcoin Core code is somewhat limited.   &lt;br /&gt;
&lt;br /&gt;
Ideally, Bitcoin Core would be modularized so that the consensus code would be separated and made into a library which could be distributed to other implementations.  In this way, fears of accidentally forking the network would be mitigated.  As of 2016, this is work in progress (see, e.g., various &amp;quot;libconsensus&amp;quot; pull requests on GitHub.) &lt;br /&gt;
&lt;br /&gt;
In December 2013, a proposal was made for modularizing the code base:  [https://github.com/bitcoin/bitcoin/issues/3440 Post-0.9 modularization of Bitcoin Core]&lt;br /&gt;
&lt;br /&gt;
Examples of optional modules would be: &lt;br /&gt;
* Miner&lt;br /&gt;
* Wallet&lt;br /&gt;
* Notifications&lt;br /&gt;
&lt;br /&gt;
As of 0.11, the steps taken toward modularization were primarily separating certain classes into subdirectories, described below.&lt;br /&gt;
&lt;br /&gt;
==Source Code Files==&lt;br /&gt;
&lt;br /&gt;
The C++ code is in the src/ directory of the repository.  &lt;br /&gt;
&lt;br /&gt;
Most of the code resides in the top-level directory, although there has been some effort to modularize the code base with subdirectories (wallet, consensus, primitives, etc.)  Also, certain components (QT, LevelDB, etc) live in subdirectories.&lt;br /&gt;
&lt;br /&gt;
Key files in the src/ directory include:  (file.* means the header file [file.h] and the source file [file.cpp])&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! File !! Description / Purpose&lt;br /&gt;
|-&lt;br /&gt;
| net.* ||  Manages the network (peer connections, etc.).&amp;lt;br&amp;gt;The while(true) loop in ThreadMessageHandler controls the program&#039;s flow, signalling &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt; when there is work to do. &amp;lt;br&amp;gt;Key dependencies:  None. &lt;br /&gt;
|-&lt;br /&gt;
| init.cpp ||  Initializes the node, calling functions in &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt; as necessary.&amp;lt;br&amp;gt;Key dependencies: main.h&lt;br /&gt;
|-&lt;br /&gt;
| main.* || main.h declares some key global variables (mapBlockIndex, chainActive, mempool, etc), constants, and functions. &amp;lt;br&amp;gt;&amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt; is the program&#039;s longest source file (5,237 lines).&amp;lt;br&amp;gt;main.cpp has most of the key functions for managing the blockchain, such as connecting, disconnecting, validating and storing blocks; identifying a certain block as the tip of the longest chain; and so forth.&amp;lt;br&amp;gt;The &amp;quot;entry point&amp;quot; for most of the code is ProcessMessages (which listens for a signal from the message-handling thread.).&amp;lt;br&amp;gt;Some of the code is run during initialization, called directly from init.cpp. &amp;lt;br&amp;gt;Key dependencies: net.h&lt;br /&gt;
|-&lt;br /&gt;
| chain.* || The header file (chain.h) is the more notable of the two, as it declares the type definitions for the metadata about the block (CBlockIndex) and the longest blockchain (CChain). &amp;lt;br&amp;gt;chain.cpp contains a few handy functions for managing the blockchain (e.g., locating blocks and finding a fork point between two chains.)&lt;br /&gt;
|-&lt;br /&gt;
| coins.* ||  The header file declares a CCoin, which is, conceptually, &amp;quot;a bitcoin.&amp;quot;&amp;lt;br&amp;gt;The source file contains methods for manipulating coins (retrieving, spending, etc.)&lt;br /&gt;
|-&lt;br /&gt;
| miner.* ||  Contains the mining code, including block creation and generating new bitcoins. &lt;br /&gt;
|-&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Subdirectories:&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The subdirectories fall into three categories: &lt;br /&gt;
* Well-defined components (in some cases third-party) &lt;br /&gt;
* Modularization of code&lt;br /&gt;
* Other (unit tests, build files, etc.)&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Subdirectories - Components:&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! Directory !! Description / Purpose&lt;br /&gt;
|-&lt;br /&gt;
| leveldb || C++ source code, docs, etc. for the LevelDB build.&lt;br /&gt;
|-&lt;br /&gt;
|  qt || The GUI code (QT).&amp;lt;br&amp;gt;QT is a C++ open-source project for GUI code, first released in 1995.&lt;br /&gt;
|-&lt;br /&gt;
|  secp256k1 || Library implementing ECDSA cryptography.&amp;lt;br&amp;gt;Purpose: This proprietary C library eliminates reliance on SSL for signature checking.&amp;lt;br&amp;gt;This is important because SSL was susceptible to introducing consensus bugs, because newly released versions do not guarantee bug-for-bug compatibility.&amp;lt;br&amp;gt;This library was written/released in early 2015. &lt;br /&gt;
|-&lt;br /&gt;
|  zmq || From the ZMQ wiki:&amp;lt;br&amp;gt;ZMQ (or ZeroMQ or 0MQ) is a high-performance asynchronous messaging library.&amp;lt;br&amp;gt;It provides a message queue, but unlike message-oriented middleware, a ZMQ system can run without a dedicated message broker. &amp;lt;br&amp;gt;The library is designed to have a familiar socket-style API.&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Subdirectories - Modularization:&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! Directory !! Key Files !! Description / Purpose&lt;br /&gt;
|-&lt;br /&gt;
| consensus || consensus.*&amp;lt;br&amp;gt;merkle.*&amp;lt;br&amp;gt;params.*&amp;lt;br&amp;gt;validation.*  || Code implementing (or defining, as the case may be) the block &amp;amp; transaction validation rules.&amp;lt;br&amp;gt;Purpose: Moving this code into a subdirectory is a step towards modularizing the consensus code.&amp;lt;br&amp;gt;The idea is that in a future version of bitcoin, the consensus code should be packaged as a library, so that alternative implementations of the protocol could simply include this library and guarantee validation compatibility.  &amp;quot;...[T]he goal is not reimplementing the consensus rules but rather extract them from Bitcoin Core so that nobody needs to re-implement them again. It is not only exposing it but also separating it from Bitcoin Core so that they can be changed without having to also change/take into account non-consensus Bitcoin Core specific things.&amp;quot; -- Jorge Timon, on bitcoin-development mailing list, 20 Aug 2015.&amp;lt;br&amp;gt;Discussion on github: [https://github.com/bitcoin/bitcoin/issues/6714 PR6714] &lt;br /&gt;
|-&lt;br /&gt;
| crypto || ripemd.*&amp;lt;br&amp;gt;sha256.*  || Cryptographic hash functions.&amp;lt;br&amp;gt;Both RIPEMD and SHA-256 are used in transforming a bitcoin address to Base-58 encoding.&lt;br /&gt;
|-&lt;br /&gt;
| policy || policy.*&amp;lt;br&amp;gt;fees.* ||  Move validation code that is a matter of &#039;&#039;policy&#039;&#039; (as opposed to consensus) into a separate directory.&lt;br /&gt;
|-&lt;br /&gt;
| primitives  || block.*&amp;lt;br&amp;gt;transaction.*  || Definitions of certain basic data types (blocks, transactions, etc.)&lt;br /&gt;
|-&lt;br /&gt;
|  script || interpreter.*&amp;lt;br&amp;gt;script.*&amp;lt;br&amp;gt;standard.* || The script engine.&amp;lt;br&amp;gt;Defines the op_codes (script.h).&amp;lt;br&amp;gt;Parses and evaluates the validation script. (interpreter.cpp:EvalScript())&amp;lt;br&amp;gt;Defines what is a &amp;quot;standard&amp;quot; transaction (standard.h).&amp;lt;br&amp;gt;Purpose: the Script engine validates basic transactions but also makes contracts possible.  It could be said that in large part, what a platform like Ethereum does is provide a more robust script engine (and language in which to express script) - so in a sense, deploying such as system consists of replacing this sub-directory with something more powerful. &lt;br /&gt;
|-&lt;br /&gt;
|  wallet || wallet.*  || Wallet code. &lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Subdirectories - Other:&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! Directory !! Description / Purpose&lt;br /&gt;
|-&lt;br /&gt;
| compat || A few minor, low-level files dealing with compatibility details. &lt;br /&gt;
|-&lt;br /&gt;
| config&amp;lt;br&amp;gt;obj&amp;lt;br&amp;gt;obj-test || These directories relate to the build process.&lt;br /&gt;
|-&lt;br /&gt;
|  test || Unit tests.&amp;lt;br&amp;gt;Uses the Boost unit test framework.&amp;lt;br&amp;gt;A good introduction to the Boost user test framework is here:  [http://www.alittlemadness.com/2009/03/31/c-unit-testing-with-boosttest/]&lt;br /&gt;
|-&lt;br /&gt;
|  univalue || Per the README:&amp;lt;br&amp;gt;&amp;quot;A universal value object, with JSON encoding (output) and decoding (input).&amp;lt;br&amp;gt;Built as a single dynamic RAII C++ object class, and no templates.&amp;quot;&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
==Design Patterns==&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Object-Oriented Design&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Naturally, being a C++ program, the code employs object-oriented design.&lt;br /&gt;
&lt;br /&gt;
However, the code&#039;s use of object-oriented design is by not universal.  In 0.11, objects are used mainly for defining the data structures which main.cpp uses to manage the blockchain and the UTXO set (the bitcoins). Main.h declares many functions and global variables but almost no classes; &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt; is over 5000 lines but does not include any class methods.  &lt;br /&gt;
&lt;br /&gt;
The code has a relatively flat class structure, with most classes being &amp;quot;stand-alone&amp;quot;.  &lt;br /&gt;
&lt;br /&gt;
Where inheritance is used, it often is a linear hierarchy (i.e.:  A &amp;lt;-- B &amp;lt;--C &amp;lt;-- D)&lt;br /&gt;
&lt;br /&gt;
For example: &lt;br /&gt;
 CBlockHeader &amp;lt;-- CBlock&lt;br /&gt;
 CTransaction &amp;lt;-- CMerkleTx &amp;lt;-- CWalletTx&lt;br /&gt;
&lt;br /&gt;
There are only a few examples of base classes that have more than one descendant class, and multiple inheritance is only used once in the code (CWallet inherits from 2 classes.) &lt;br /&gt;
&lt;br /&gt;
The program&#039;s best example of an elegant class hierarchy relates to the coins caches.  It uses an abstract class that is inherited by a few subclasses that demonstrate encapsulation and polymorphism.  Chapter 3 has a class diagram as well as a diagram and explanation of how the classes are instantiated and relate to one another.  &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Multithreading&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The code uses Boost thread groups to implement multithreading.  The vast majority of the action takes place in the message-processing thread, and to a lesser extent the socket thread. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Observer (Signals and slots)&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The &amp;quot;observer&amp;quot; pattern uses &amp;quot;signals and slots&amp;quot; to decouple two or more areas of code. Bitcoin Core 0.11 uses the observer pattern in a limited way.  Namely, it uses signals to decouple the message-gathering loop from the &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt; code.  In 0.10 and earlier a normal function call was used.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
==See also==&lt;br /&gt;
[https://en.bitcoin.it/wiki/Bitcoin_Core_0.11_(ch_2):_Data_Storage Bitcoin Core 0.11 (Ch 2): Data Storage]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[https://en.bitcoin.it/wiki/Bitcoin_Core_0.11_(ch_3):_Initialization_and_Startup Bitcoin Core 0.11 (Ch 3): Initialization and Startup]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[https://en.bitcoin.it/wiki/Bitcoin_Core_0.11_(ch_4):_P2P_Network Bitcoin Core 0.11 (Ch 4): P2P Network]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[https://en.bitcoin.it/wiki/Bitcoin_Core_0.11_(ch_5):_Initial_Block_Download Bitcoin Core 0.11 (Ch 5): Initial Block Download]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[https://en.bitcoin.it/wiki/Bitcoin_Core_0.11_(ch_6):_The_Blockchain Bitcoin Core 0.11 (Ch 6): The Blockchain]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Technical]]&lt;br /&gt;
[[Category:Developer]]&lt;/div&gt;</summary>
		<author><name>Mrbandrews</name></author>
	</entry>
	<entry>
		<id>https://en.bitcoin.it/w/index.php?title=Bitcoin_Core_0.11_(ch_2):_Data_Storage&amp;diff=60024</id>
		<title>Bitcoin Core 0.11 (ch 2): Data Storage</title>
		<link rel="alternate" type="text/html" href="https://en.bitcoin.it/w/index.php?title=Bitcoin_Core_0.11_(ch_2):_Data_Storage&amp;diff=60024"/>
		<updated>2016-01-21T20:30:42Z</updated>

		<summary type="html">&lt;p&gt;Mrbandrews: edit footer&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
This page describes how &amp;amp; where Bitcoin Core stores blockchain data. &lt;br /&gt;
&lt;br /&gt;
==Overview==&lt;br /&gt;
&lt;br /&gt;
There are basically four pieces of data that are maintained:&lt;br /&gt;
&lt;br /&gt;
: &#039;&#039;&#039;blocks/blk*.dat:&#039;&#039;&#039; the actual Bitcoin blocks, in network format, dumped in raw on disk. They are only needed for rescanning missing transactions in a wallet, reorganizing to a different part of the chain, and serving the block data to other nodes that are synchronizing.&lt;br /&gt;
&lt;br /&gt;
: &#039;&#039;&#039;blocks/index/*:&#039;&#039;&#039; this is a LevelDB database that contains metadata about all known blocks, and where to find them on disk. Without this, finding a block would be very slow.&lt;br /&gt;
&lt;br /&gt;
: &#039;&#039;&#039;chainstate/*:&#039;&#039;&#039; this is a LevelDB database with a compact representation of all currently unspent transaction outputs and some metadata about the transactions they are from. The data here is necessary for validating new incoming blocks and transactions. It can theoretically be rebuilt from the block data (see the -reindex command line option), but this takes a rather long time. Without it, you could still theoretically do validation indeed, but it would mean a full scan through the blocks (7 GB as of may 2013) for every output being spent.&lt;br /&gt;
&lt;br /&gt;
: &#039;&#039;&#039;blocks/rev*.dat:&#039;&#039;&#039; these contain &amp;quot;undo&amp;quot; data. You can see blocks as &#039;patches&#039; to the chain state (they consume some unspent outputs, and produce new ones), and see the undo data as reverse patches. They are necessary for rolling back the chainstate, which is necessary in case of reorganisations.&lt;br /&gt;
&lt;br /&gt;
Note that the LevelDB&#039;s are redundant in the sense that they can be rebuilt from the block data. But validation and other operations would become intolerably slow without them.&lt;br /&gt;
&lt;br /&gt;
See here:  [http://bitcoin.stackexchange.com/questions/11104/what-is-the-database-for?rq=1 StackExchange post by Pieter Wuille (2013)]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Raw Block data (blk*.dat)==&lt;br /&gt;
&lt;br /&gt;
Block files store the raw blocks as they were received over the network.  &lt;br /&gt;
&lt;br /&gt;
Block files are about 128 MB, allocated in 16 MB chunks to prevent excessive fragmentation.  As of October 2015, the block chain is stored in about 365 block files, for a total of about 45 GB. &lt;br /&gt;
&lt;br /&gt;
Each block file (blk1234.dat) has a corresponding undo file (rev1234.dat) which contains the data necessary to remove blocks from the blockchain in the event of a reorganization (fork). &lt;br /&gt;
&lt;br /&gt;
Info about the block files is stored in the block index (the LevelDB) in two places: &lt;br /&gt;
* General info about the files themselves is held in the &amp;quot;f&amp;quot; records in the block index LevelDB (meaning keys &amp;quot;fxxxx&amp;quot;, where &amp;quot;xxxx&amp;quot; is the 4 digit file number), including: &lt;br /&gt;
** Number of blocks stored in the file&lt;br /&gt;
** File size (and the corresponding undo file size) &lt;br /&gt;
** Lowest and highest block in the file&lt;br /&gt;
** Timestamps - earlier and latest blocks in the file&lt;br /&gt;
&lt;br /&gt;
* Info about where to find a particular block on disk is in the &amp;quot;b&amp;quot; (&amp;quot;b&amp;quot; = block) record: &lt;br /&gt;
** Each block contains a pointer to the block is on disk (a file number and an offset)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Accessing the block data files from the code&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The block files are accessed through: &lt;br /&gt;
&lt;br /&gt;
1) DiskBlockPos: a struct that is simply a pointer to a block&#039;s location on disk (a file number and an offset.) &lt;br /&gt;
&lt;br /&gt;
2) &#039;&#039;vInfoBlockFiles&#039;&#039;: a vector of BlockFileInfo objects.  This variable is used to perform such tasks as:  &lt;br /&gt;
* Determine whether new blocks can fit into the current file or a new file needs to be created&lt;br /&gt;
* Calculate the total disk usage by block &amp;amp; undo files &lt;br /&gt;
* Iterate through the block files and find ones that can be pruned&lt;br /&gt;
&lt;br /&gt;
Blocks are written to disk as soon as they are received, in AcceptBlock.  (The actual disk write operation is in WriteBlockToDisk [&amp;lt;u&amp;gt;main.cpp:1164&amp;lt;/u&amp;gt;]).  Note that there is some overlap of the code that accesses block files with the code that accesses and writes to the coins database (/chainstate).  There is a complex system of when to flush state to disk.  None of this code affects block files, which are simply written to disk when received.  Once they have been received and stored, the block files are only needed for serving blocks to other nodes. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;More info about block files&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
See here: [https://github.com/sipa/bitcoin/commit/5382bcf8cd23c36a435c29080770a79b5e28af42 the commit that puts multiple blocks in a block file (2012)]&lt;br /&gt;
&lt;br /&gt;
==Block index (leveldb)==&lt;br /&gt;
&lt;br /&gt;
The block index holds metadata about all known blocks, including where the block is stored on disk.  &lt;br /&gt;
&lt;br /&gt;
Note that the set of &amp;quot;known blocks&amp;quot; is a superset of the longest chain, because it includes blocks that were received and processed but are not part of the active chain - for example, orphaned blocks that were detached from the active chain in a small reorganization.   &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Terminology&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The terminology can be a little confusing here, because while people normally think of the &amp;quot;blockchain&amp;quot; as being synonymous with the active chain (an uninterrupted, linear chain of X blocks starting with the genesis block and continuing to the current tip), there are some places in the code where &amp;quot;blockchain&amp;quot; refers to the active chain plus the numerous, mostly short forks off the chain that our node happens to know about.  &lt;br /&gt;
&lt;br /&gt;
a) Block Tree&lt;br /&gt;
&lt;br /&gt;
A better term for the set of known blocks stored on disk is &amp;quot;block tree,&amp;quot; as this term contemplates a tree structure with numerous branches (albeit small ones) from the main chain.  Indeed, the block index LevelDB is accessed through the &amp;quot;CBlockTreeDB&amp;quot; wrapper class, defined in &amp;lt;u&amp;gt;src/txdb.h&amp;lt;/u&amp;gt;.  Note that it&#039;s perfectly fine, indeed it is expected, that different nodes would have slightly different block trees;  what matters is that they agree on the active chain.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Key-value pairs&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Inside the actual LevelDB, the used key/value pairs are:&lt;br /&gt;
&lt;br /&gt;
    &#039;b&#039; + 32-byte block hash -&amp;gt; block index record. Each record stores:&lt;br /&gt;
        * The block header&lt;br /&gt;
        * The height.&lt;br /&gt;
        * The number of transactions.&lt;br /&gt;
        * To what extent this block is validated.&lt;br /&gt;
        * In which file, and where in that file, the block data is stored.&lt;br /&gt;
        * In which file, and where in that file, the undo data is stored.&lt;br /&gt;
&lt;br /&gt;
   &#039;f&#039; + 4-byte file number -&amp;gt; file information record. Each record stores:&lt;br /&gt;
        * The number of blocks stored in the block file with that number.&lt;br /&gt;
        * The size of the block file with that number ($DATADIR/blocks/blkNNNNN.dat).&lt;br /&gt;
        * The size of the undo file with that number ($DATADIR/blocks/revNNNNN.dat).&lt;br /&gt;
        * The lowest and highest height of blocks stored in the block file with that number.&lt;br /&gt;
        * The lowest and highest timestamp of blocks stored in the block file with that number.&lt;br /&gt;
&lt;br /&gt;
    &#039;l&#039; -&amp;gt; 4-byte file number: the last block file number used.&lt;br /&gt;
&lt;br /&gt;
    &#039;R&#039; -&amp;gt; 1-byte boolean (&#039;1&#039; if true): whether we&#039;re in the process of reindexing.&lt;br /&gt;
&lt;br /&gt;
    &#039;F&#039; + 1-byte flag name length + flag name string -&amp;gt; 1 byte boolean (&#039;1&#039; if true, &#039;0&#039; if false): various flags that can be on or off. Currently defined flags include:&lt;br /&gt;
         * &#039;txindex&#039;: Whether the transaction index is enabled.&lt;br /&gt;
&lt;br /&gt;
    &#039;t&#039; + 32-byte transaction hash -&amp;gt; transaction index record. These are optional and only exist if &#039;txindex&#039; is enabled (see above). Each record stores:&lt;br /&gt;
        * Which block file number the transaction is stored in.&lt;br /&gt;
        * Which offset into that file the block the transaction is part of is stored at.&lt;br /&gt;
        * The offset from the start of that block to the position where that transaction itself is stored.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
See here: [http://bitcoin.stackexchange.com/questions/28168/what-are-the-keys-used-in-the-blockchain-leveldb-ie-what-are-the-keyvalue-pair StackExchange post by Pieter Wuille (2014)]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Data Access Layer&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The database is accessed through CBlockTreeDB wrapper class.  See &amp;lt;u&amp;gt;txdb.h&amp;lt;/u&amp;gt;.  &lt;br /&gt;
&lt;br /&gt;
The wrapper is instantiated in a global variable called pblocktree, defined in &amp;lt;u&amp;gt;main.cpp.&amp;lt;/u&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;CBlockIndex&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Blocks stored in the database are represented in memory as CBlockIndex objects.  An object of this type is first created after the &#039;&#039;header&#039;&#039; is received;  the code does not wait to receive the full block.  When headers are received over the network, they are streamed into a vector of CBlockHeaders, which are then checked. Each header that checks out causes a new CBlockIndex to be created, which is stored to the database. &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;CBlock / CBlockHeader&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Note that these objects have little to do with the /blocks LevelDB.  A CBlock holds the full set of transactions in the block, the data for which is stored in two places - in full, in raw format, in the blk???.dat files, and in pruned format in the UTXO database.  The block index database cares not for such details, since it holds only the metadata for the block. &lt;br /&gt;
 &lt;br /&gt;
&#039;&#039;Loading the block database into memory&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The entire database is loaded into memory on startup.  See LoadBlockIndexGuts (&amp;lt;u&amp;gt;txdb.cpp&amp;lt;/u&amp;gt;).  This only takes a few seconds. &lt;br /&gt;
&lt;br /&gt;
The blocks (&#039;b&#039; keys) are loaded into the global &amp;quot;mapBlockIndex&amp;quot; variable.  &amp;quot;mapBlockIndex&amp;quot; is an unordered_map that holds CBlockIndex for each block in the entire block tree; not just the active chain.  &lt;br /&gt;
&lt;br /&gt;
mapBlockIndex is described in more detail in Chapter 6 - The Blockchain. &lt;br /&gt;
&lt;br /&gt;
The block file metadata (&#039;f&#039; keys) is loaded into vInfoBlockFiles.&lt;br /&gt;
&lt;br /&gt;
==The UTXO set (chainstate leveldb)==&lt;br /&gt;
&lt;br /&gt;
The UTXO database was introduced in 2012 in [https://github.com/bitcoin/bitcoin/pull/1677 pull request #1677 - &amp;quot;Ultraprune.&amp;quot;]&lt;br /&gt;
&lt;br /&gt;
The idea behind &amp;quot;Ultraprune&amp;quot; is to reduce the size of (prune) the set of past transactions, keeping only those parts of past transactions that are necessary to validate later transactions.  &lt;br /&gt;
&lt;br /&gt;
Say you have a transaction T1 which takes two inputs and sends to 3 outputs: O1,O2,O3.  Two of those outputs (O1, O2) have been used as inputs in a later transaction, T2.   Once T2 has been mined, T1 only has one item of interest (O3).  There&#039;s no reason to keep T1 around in its entirety.  Instead, a slimmed-down version of T1 will suffice, consisting only of O3 (locking script and amount) and certain basic information about T1 (height, whether it is a coinbase, etc.)&lt;br /&gt;
&lt;br /&gt;
The description of ultraprune is on the specific &amp;quot;ultraprune&amp;quot; commit within the pull: &lt;br /&gt;
&lt;br /&gt;
: -------------&lt;br /&gt;
&lt;br /&gt;
: This switches bitcoin&#039;s transaction/block verification logic to use a &amp;quot;coin database&amp;quot;, which contains all unredeemed transaction output scripts, amounts and heights.&lt;br /&gt;
&lt;br /&gt;
: The name ultraprune comes from the fact that instead of a full transaction index, we only (need to) keep an index with unspent outputs. For now, the blocks themselves are kept as usual, although they are only necessary for serving, rescanning and reorganizing.&lt;br /&gt;
&lt;br /&gt;
: The basic data structures are CCoins (representing the coins of a single transaction), and CCoinsView (representing a state of the coins database).  There are several implementations for CCoinsView. A dummy, one backed by the coins database (coins.dat), one backed by the memory pool, and one that adds a cache on top of it. FetchInputs, ConnectInputs, ConnectBlock, DisconnectBlock, ... now operate on a generic CCoinsView.&lt;br /&gt;
&lt;br /&gt;
: The block switching logic now builds a single cached CCoinsView with changes to be committed to the database before any changes are made. This means no uncommitted changes are ever read from the database, and should ease the transition to another database layer which does not support transactions (but does support atomic writes), like LevelDB.&lt;br /&gt;
&lt;br /&gt;
: For the getrawtransaction() RPC call, access to a txid-to-disk index would be preferable. As this index is not necessary or even useful for any other part of the implementation, it is not provided. Instead, getrawtransaction() uses the coin database to find the block height, and then scans that block to find the requested transaction. This is slow, but should suffice for debug purposes.&lt;br /&gt;
&lt;br /&gt;
: -----------------&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
See:  [https://github.com/sipa/bitcoin/commit/450cbb0944cd20a06ce806e6679a1f4c83c50db2 Ultraprune - July 2012]&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Terminology&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
&amp;quot;UTXO (Unspent Transaction Out):&amp;quot;  An output from a transaction.  This is colloquially referred to as a &amp;quot;coin.&amp;quot;  For this reason, the UTXO db is sometimes referred to as the &amp;quot;coins database.&amp;quot;&lt;br /&gt;
&lt;br /&gt;
&amp;quot;UTXO set / coins database / chainstate database:&amp;quot;  These terms are more or less synonymous and are used interchangeably.  &lt;br /&gt;
&lt;br /&gt;
&amp;quot;Provably Unspendable:&amp;quot;  A coin is provably unspendable if its scriptPubKey cannot be satisfied - for example, an OP_RETURN.  A provably unspendable coin can be eliminated from the utxo database regardless of its amount. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Key-value pairs&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The records in the chainstate levelDB are: &lt;br /&gt;
&lt;br /&gt;
    &#039;c&#039; + 32-byte transaction hash -&amp;gt; unspent transaction output record for that transaction. These records are only present for transactions that have at least one unspent output left. Each record stores:&lt;br /&gt;
        * The version of the transaction.&lt;br /&gt;
        * Whether the transaction was a coinbase or not.&lt;br /&gt;
        * Which height block contains the transaction.&lt;br /&gt;
        * Which outputs of that transaction are unspent.&lt;br /&gt;
        * The scriptPubKey and amount for those unspent outputs.&amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
    &#039;B&#039; -&amp;gt; 32-byte block hash: the block hash up to which the database represents the unspent transaction outputs.&lt;br /&gt;
&lt;br /&gt;
See here: [http://bitcoin.stackexchange.com/questions/28168/what-are-the-keys-used-in-the-blockchain-leveldb-ie-what-are-the-keyvalue-pair StackExchange post by Pieter Wuille (2014)]&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Data Access Layer and Caching&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Access to the UTXO database is considerably more complex than the block index.   This is because its performance is critical to the overall performance of the Bitcoin system.  The block index is not so critical to performance because there are only a few hundred thousand blocks and a node running on decent hardware can retrieve and scroll through them in a few seconds (and does not need to do so very often.)  On the other hand, there are millions of coins in the UTXO database and they must be checked and modified for each input of each transaction going into the mempool or included in a block. &lt;br /&gt;
&lt;br /&gt;
As sipa said in the ultraprune commit: &lt;br /&gt;
: The basic data structures are CCoins (representing the coins of a single transaction), and CCoinsView (representing a state of the coins database).  There are several implementations for CCoinsView. A dummy, one backed by the coins database (coins.dat), one backed by the memory pool, and one that adds a cache on top of it.&lt;br /&gt;
&lt;br /&gt;
This is not stated as clearly as it might have been, however; at least, not for the current state of the code.  &lt;br /&gt;
&lt;br /&gt;
In 0.11, the instantiations of the CoinsView are:  &lt;br /&gt;
* dummy&lt;br /&gt;
* database&lt;br /&gt;
* pCoinsTip (a cache backed by the database)&lt;br /&gt;
* &amp;quot;validation cache&amp;quot; (used when  backed by pCoinsTip, in use when connecting a block)  &lt;br /&gt;
&lt;br /&gt;
Separate from that chain of caches is the memory pool&#039;s CoinsView, which is backed by the database. &lt;br /&gt;
&lt;br /&gt;
    &lt;br /&gt;
The &amp;lt;i&amp;gt;class diagram&amp;lt;/i&amp;gt; (data types) for the views is: &lt;br /&gt;
&lt;br /&gt;
       CCoinsView (abstract class)&lt;br /&gt;
              /            \&lt;br /&gt;
          ViewDB          ViewBacked &lt;br /&gt;
       (database)          /      \&lt;br /&gt;
                    ViewMempool   ViewCache&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Each class has one key characteristic: &lt;br /&gt;
* View is the base class, declaring methods for verifying that coins exist (HaveCoins), retrieving coins (GetCoins), etc. &lt;br /&gt;
* ViewDB has code to interact with the LevelDB. &lt;br /&gt;
* ViewBacked has a pointer to another View;  thus it is &amp;quot;backed&amp;quot; by another view (version) of the UTXO set. &lt;br /&gt;
* ViewCache has a cache (a map of CCoins). &lt;br /&gt;
* ViewMempool associates a mempool with a view. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Those are the defined classes; whereas the &amp;lt;i&amp;gt;object diagram&amp;lt;/i&amp;gt; is: &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
             Database       &lt;br /&gt;
            /       \&lt;br /&gt;
        MemPool     Blockchain cache (pcoinsTip) &lt;br /&gt;
      View/Cache            \&lt;br /&gt;
                          Validation cache&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here is a table summarizing the instantiations of Views: &lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! Object !! Type !! Backed By? !! Description / Purpose&lt;br /&gt;
|-&lt;br /&gt;
| DB view || ViewDB || n/a || Represents the UTXO set according to the /chainstate LevelDB.  Retrieves coins and flushes changes to the LevelDB.&amp;lt;br&amp;gt;Creation in code (instantiation):  see &amp;lt;u&amp;gt;init.cpp:1131&amp;lt;/u&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| pCoinsTip&amp;lt;br&amp;gt;(blockchain cache) || ViewCache || DB view || Holds the UTXO set corresponding to the active chain&#039;s tip.  Retrieves/flushes to the database view.&amp;lt;br&amp;gt;Creation in code:  see &amp;lt;u&amp;gt;init.cpp:1133&amp;lt;/u&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| Validation cache || ViewCache || pCoinsTip || This cache&#039;s lifetime is within ConnectTip (or DisconnectTip).&amp;lt;br&amp;gt;Its purpose is to keep track of modifications to the UTXO set while processing a block.&amp;lt;br&amp;gt;If the block validates, the cache is flushed to pcoinsTip.&amp;lt;br&amp;gt;If the block fails, the cache is discarded. &amp;lt;br&amp;gt;Creation in code:  see &amp;lt;u&amp;gt;main.cpp:2231&amp;lt;/u&amp;gt;:  CCoinsViewCache view(pcoinsTip);&lt;br /&gt;
|-&lt;br /&gt;
| Mempool view || ViewMemPool || pCoinsTip || This object brings the mempool into view, meaning it can see both a UTXO set and the mempool.&amp;lt;br&amp;gt;Its purpose is to enable validation of chains of transactions, a.k.a. &amp;quot;zero-confirmation&amp;quot; transactions.  (If chains of transactions weren&#039;t permitted, the mempool could simply validate against pcoinsTip.)&amp;lt;br&amp;gt;Thus, when queried, it can check if a given input can be found either in the mempool (i.e., &amp;quot;zero-conf&amp;quot;) or in the blockchain&#039;s utxo set (&amp;quot;confirmed.&amp;quot;)&amp;lt;br&amp;gt;Note that this object is not a cache; rather, it is a view that is used by the object below, which does contain a cache.  &amp;lt;br&amp;gt;Creation in code: Its lifetime is that of AcceptToMemoryPool in &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt;.&lt;br /&gt;
|-&lt;br /&gt;
| Mempool cache || ViewCache || Mempool view || The cache for the mempool.  It contains a cache and sets its backend to be the mempool view.&amp;lt;br&amp;gt;Creation in code: Its lifetime is also that of AcceptToMemoryPool in &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt;. &lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Loading the UTXO set&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Access to the coins database is initialized in &amp;lt;u&amp;gt;init.cpp&amp;lt;/u&amp;gt;: 1131-1133: &lt;br /&gt;
&lt;br /&gt;
 pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex);&lt;br /&gt;
 pcoinscatcher = new CCoinsViewErrorCatcher(pcoinsdbview);&lt;br /&gt;
 pcoinsTip = new CCoinsViewCache(pcoinscatcher);&lt;br /&gt;
&lt;br /&gt;
The code starts by initializing a CoinsViewDB, which is equipped with methods to load coins from the LevelDB. &amp;lt;br&amp;gt;&lt;br /&gt;
The error catcher is a little hack that can be ignored. &amp;lt;br&amp;gt;&lt;br /&gt;
Next, the code initalizes pCoinsTip, which is the cache representing the state of the active chain, and is backed by the database view. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Cache vs. Database&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The FetchCoins function in coins.cpp demonstrates how the code uses the cache vs. the database: &lt;br /&gt;
 1   CCoinsMap::iterator it = cacheCoins.find(txid);&lt;br /&gt;
 2   if (it != cacheCoins.end())&lt;br /&gt;
 3     return it;&lt;br /&gt;
 4   CCoins tmp;&lt;br /&gt;
 5   if (!base-&amp;gt;GetCoins(txid, tmp))&lt;br /&gt;
 6     return cacheCoins.end();&lt;br /&gt;
 7   CCoinsMap::iterator ret = cacheCoins.insert(std::make_pair(txid, CCoinsCacheEntry())).first;&lt;br /&gt;
&lt;br /&gt;
First, the code searches the cache for the coins for a given transaction id. (line 1)&amp;lt;br&amp;gt;&lt;br /&gt;
If found, it returns the &amp;quot;fetched&amp;quot; coins. (lines 2-3) &amp;lt;br&amp;gt;&lt;br /&gt;
If not, it searches the database. (line 5) &amp;lt;br&amp;gt;&lt;br /&gt;
If found in the database, it updates the cache. (line 7) &amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
Note:  if the cache&#039;s backend is another cache, then the term &amp;quot;database&amp;quot; really means &amp;quot;parent cache.&amp;quot; &lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Flushing the Validation Cache to the Blockchain Cache&#039;&#039;  &lt;br /&gt;
&lt;br /&gt;
The validation cache is flushed to the blockchain cache after connecting a block, just before it goes out of scope.  The scope is captured in ConnectTip, and specifically, in the code block &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt;:2231-2243.  In that code block, there is a call to ConnectBlock, during which the code stores the new coins in the validation cache.  (Specifically, see UpdateCoins() in &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt;.)  At the end of the code block, the validation cache is flushed.  Since its &amp;quot;parent view&amp;quot; is also a cache (pcoinsTip, the &amp;quot;blockchain cache&amp;quot;) the code will call the parent&#039;s ViewCache::BatchWrite, which swaps the updated coin entries into its own cache.  (Polymorphism in action: Later, when the the blockchain cache flushes to the database view, the code will run CoinsViewDB::BatchWrite, the last line of which writes to the LevelDB.) &lt;br /&gt;
&lt;br /&gt;
In summary, usage of the validation cache is straightforward: it is instantiated, used, flushed, and goes out of scope in the aforementioned code block. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Flushing the Blockchain Cache to the Database&#039;&#039;  &lt;br /&gt;
&lt;br /&gt;
Flushing the validate cache was simple because the code only shuffled items between two caches in memory (of which no one is aware outside of the caching code.)  Flushing the blockchain cache to the database is a bit more complicated.  At the lowest level, the mechanics of flushing the blockchain cache (pcoinsTip) is the same as the validation cache:  the Flush() method calls BatchWrite on its backend (the &amp;quot;base&amp;quot; pointer), and in this case that means BatchWrite on the database view.  Up a level, Flush() is called from FlushStateToDisk (FSTD) - &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt;:2098.  FlushStateToDisk is invoked at a few different points, with a given &#039;&#039;mode&#039;&#039;: &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! Flush Mode !! Description !! When called&lt;br /&gt;
|-&lt;br /&gt;
| IF_NEEDED || Flush only if the cache is over its size limit. || Right after connecting (or disconnecting) a block and flushing the validation cache.&amp;lt;br&amp;gt;See ConnectTip / DisconnectTip.&lt;br /&gt;
|-&lt;br /&gt;
| ALWAYS || Flush cache. || During initialization only. &lt;br /&gt;
|-&lt;br /&gt;
| PERIODIC || Here, the code considers other data points to decide whether to flush.&amp;lt;br&amp;gt;Is the code &#039;&#039;almost&#039;&#039; over its size limit?&amp;lt;br&amp;gt;Has it been a long time since the cache was flushed?&amp;lt;br&amp;gt;If so, then proceed.|| At end of ActivateBestChain()&amp;lt;br&amp;gt;(Code comment: &amp;quot;write changes periodically to disk, after relay&amp;quot;). &lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The idea is to flush the block cache frequently (to avoid having to download a large number of blocks if the program crashes), but the coins cache infrequently (in order to maximize the benefit from the coins cache.) &lt;br /&gt;
&lt;br /&gt;
Specifically, the block cache is guaranteed to be flushed once an hour, whereas the coins cache once per day.  (See here:  [https://github.com/bitcoin/bitcoin/pull/6102#issuecomment-98847663 Sipa comment on PR 6102])&lt;br /&gt;
&lt;br /&gt;
The FlushStateToDisk code is well-commented so for more info, the curious reader can check &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
==Raw undo data (rev*.dat)==&lt;br /&gt;
&lt;br /&gt;
The undo data contains the information that is necessary to disconnect or &amp;quot;roll back&amp;quot; a block: specifically, the coins that were spent by the block in question.&lt;br /&gt;
&lt;br /&gt;
So, the data being written is essentially a set of CTxOut objects.  (A CTxOut is simply an amount and a script - see &amp;lt;u&amp;gt;primitives/transaction.h&amp;lt;/u&amp;gt;:107-108).&lt;br /&gt;
&lt;br /&gt;
The matter is complicated slightly by the fact that if the coin is the last one being spent by its transaction, the undo data needs to store the transaction&#039;s metadata (the txn&#039;s block height, whether it&#039;s a coinbase, and its version.) So, if you have a transaction T with outputs O1,O2,O3 spent in that order, for O1 and O2 all that will be written to the undo file is the amount and the script.  For 03, the undo file will have the amount, the script, plus T&#039;s height and version, and whether T is a coinbase.&lt;br /&gt;
&lt;br /&gt;
The undo data is written to the raw file with the following code: &lt;br /&gt;
 fileout &amp;lt;&amp;lt; blockundo; (main.cpp:1567 [UndoWriteToDisk])&lt;br /&gt;
&lt;br /&gt;
This line of code calls the serialization function on the CBlockUndo - which is basically just a vector of coins (CTxOuts.)  Finally, a checksum is written to the undo file. The checksum  is used during initialization to verify that any undo data being checked is intact.  See [https://github.com/bitcoin/bitcoin/pull/2145 Pull 2145]&lt;br /&gt;
&lt;br /&gt;
The undo data is used when disconnecting a block.  The DisconnectBlock() code is discussed further down this wiki page in The Blockchain: Reorganizations.&lt;br /&gt;
&lt;br /&gt;
==Use of LevelDB==&lt;br /&gt;
&lt;br /&gt;
LevelDB is a key-value store that was introduced to store the block index and UTXO set (chainstate) in 2012 as part of the complex &amp;quot;Ultraprune&amp;quot; pull (PR 1677).  See here: [https://github.com/bitcoin/bitcoin/pull/1677/commits the 27 commits on Ultraprune]. &lt;br /&gt;
&lt;br /&gt;
On the subject of why LevelDB is used, core developer Greg Maxwell stated the following to the [http://bitcoin-development.narkive.com/XAPoxKZU/patch-switching-bitcoin-core-to-sqlite-db bitcoin-dev mailing list in October 2015]: &lt;br /&gt;
&lt;br /&gt;
:: I think people are falling into a trap of thinking &amp;quot;It&#039;s a &amp;lt;database&amp;gt;, I know a &amp;lt;black box&amp;gt; for that!&amp;quot;; but the application and needs are very specialized here. . . It just so happens that on the back of the very bitcoin specific cryptographic consensus algorithim there was a slot where a pre-existing high performance key-value store fit; and so we&#039;re using one and saving ourselves some effort... &lt;br /&gt;
&lt;br /&gt;
One might ask whether different nodes could use different databases - as long as they retrieve the same data, what&#039;s the difference? The issue here is &amp;quot;bug-for-bug compatibility&amp;quot; - if one database has a bug that causes records to not be returned under certain circumstances, then all other nodes bst have the same bug, else the network could fork as a result.  &lt;br /&gt;
&lt;br /&gt;
Greg Maxwell stated the following in [http://bitcoin-development.narkive.com/XAPoxKZU/patch-switching-bitcoin-core-to-sqlite-db the same thread referenced above (in response to a proposal to switch to using sqlite)]: &lt;br /&gt;
&lt;br /&gt;
:: ...[D]atabases sometimes have errors which cause them to fail to return records, or to return stale data. And if those exist consistency must be maintained; and &amp;quot;fixing&amp;quot; the bug can cause a divergence in consensus state that could open users up to theft.&lt;br /&gt;
&lt;br /&gt;
:: Case in point, prior to leveldb&#039;s use in Bitcoin Core it had a bug that, under rare conditions, could cause it to consistently return not found on records that were really there. . . Leveldb fixed this serious bug in a minor update.  But deploying a fix like this in an uncontrolled manner in the bitcoin network would potentially cause a fork in the consensus state; so any such fix would need to be rolled out in an orderly manner.&lt;br /&gt;
&lt;br /&gt;
==See also==&lt;br /&gt;
[https://en.bitcoin.it/wiki/Bitcoin_Core_0.11_(ch_1):_Overview Bitcoin Core 0.11 (Ch 1): Overview]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[https://en.bitcoin.it/wiki/Bitcoin_Core_0.11_(ch_3):_Initialization_and_Startup Bitcoin Core 0.11 (Ch 3): Initialization and Startup]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[https://en.bitcoin.it/wiki/Bitcoin_Core_0.11_(ch_4):_P2P_Network Bitcoin Core 0.11 (Ch 4): P2P Network]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[https://en.bitcoin.it/wiki/Bitcoin_Core_0.11_(ch_5):_Initial_Block_Download Bitcoin Core 0.11 (Ch 5): Initial Block Download]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[https://en.bitcoin.it/wiki/Bitcoin_Core_0.11_(ch_6):_The_Blockchain Bitcoin Core 0.11 (Ch 6): The Blockchain]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Technical]]&lt;br /&gt;
[[Category:Developer]]&lt;/div&gt;</summary>
		<author><name>Mrbandrews</name></author>
	</entry>
	<entry>
		<id>https://en.bitcoin.it/w/index.php?title=Bitcoin_Core_0.11_(ch_4):_P2P_Network&amp;diff=60023</id>
		<title>Bitcoin Core 0.11 (ch 4): P2P Network</title>
		<link rel="alternate" type="text/html" href="https://en.bitcoin.it/w/index.php?title=Bitcoin_Core_0.11_(ch_4):_P2P_Network&amp;diff=60023"/>
		<updated>2016-01-21T20:29:18Z</updated>

		<summary type="html">&lt;p&gt;Mrbandrews: edit footer&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
Bitcoin is a peer-to-peer network, so Bitcoin Core has code to discover peers and manage those connections. &lt;br /&gt;
&lt;br /&gt;
Most of the network-handling code is in &amp;lt;u&amp;gt;net.h/cpp&amp;lt;/u&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
==Data structures to manage peers==&lt;br /&gt;
&lt;br /&gt;
At any given time, the node is connected with a set of other nodes, i.e. peers.  By default the code connects to 8 outbound peers (nodes that our node goes out and finds) and allows up to 125 inbound peers (nodes that find us through the network). &lt;br /&gt;
&lt;br /&gt;
The global variable vNodes (&amp;lt;u&amp;gt;net.h&amp;lt;/u&amp;gt;) holds the set of peers.  The variable is protected by cs_vNodes. &lt;br /&gt;
&lt;br /&gt;
Each peer is represented by a CNode.&lt;br /&gt;
&lt;br /&gt;
The CNode contains dozens of attributes, most of which have to do with low-level plumbing (sockets, byte streams, etc.) &lt;br /&gt;
&lt;br /&gt;
Some of the key attributes of a CNode include: &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;CNode&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! Attribute !! Description&lt;br /&gt;
|-&lt;br /&gt;
| nServices || Commonly referred to as &amp;quot;the service bits.&amp;quot;&amp;lt;br&amp;gt;This is a bitmap of what services the peer provides.&amp;lt;br&amp;gt;As of 0.11 this is still just binary:  either the node is NODE_NETWORK (it is a full node and does everything) or not (it is SPV).&amp;lt;br&amp;gt;In future versions, these bits will convey more precise information about what the node can and can&#039;t do. For example, with Block Pruning a node may be able to serve recent blocks (say, the last week or two worth of blocks), but not the entire blockchain. &lt;br /&gt;
|-&lt;br /&gt;
| fClient || Whether this peer is a SPV node.  (Here, the term &amp;quot;client&amp;quot; means &amp;quot;merely SPV, not a full node.&amp;quot;)&lt;br /&gt;
|-&lt;br /&gt;
| fOneShot || &lt;br /&gt;
|-&lt;br /&gt;
| fInbound ||  Whether this node is &amp;quot;inbound&amp;quot; or &amp;quot;outbound.&amp;quot; Common sense suggests that a node that we discovered through the network (an outbound node) is less likely to attack us than a node that found us.&amp;lt;br&amp;gt;So, for example, when the code looks for a peer to request historical blocks from, it prefers an outbound node, if possible. &lt;br /&gt;
|-&lt;br /&gt;
| fWhiteListed || A whitelisted node is not subject to being banned for bad behaviour. &lt;br /&gt;
|-&lt;br /&gt;
| setInventoryKnown || &lt;br /&gt;
|-&lt;br /&gt;
| vSendMsg || Messages that we&#039;ve queued up to send to the peer.&amp;lt;br&amp;gt;This is type &amp;lt;CSerializeData&amp;gt; since we are going to send it over the network. &lt;br /&gt;
|-&lt;br /&gt;
| vRecvMsg || Messages that we&#039;ve received from the peer.&amp;lt;br&amp;gt;This is type &amp;lt;CNetMessage&amp;gt; because as soon as the data is received, it is deserialized and packed into a more useful format (an object).&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
==Peer discovery &amp;amp; connectivity==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Address manager===&lt;br /&gt;
&lt;br /&gt;
IP addresses of the node&#039;s peers are managed by the address manager (see &amp;lt;u&amp;gt;addrman.h&amp;lt;/u&amp;gt;). &lt;br /&gt;
&lt;br /&gt;
The code comment explains the address manager (edited here for conciseness):&lt;br /&gt;
&lt;br /&gt;
 Design goals:&lt;br /&gt;
   * Keep the address tables in-memory, and asynchronously dump the entire table to peers.dat.&lt;br /&gt;
   * Make sure no (localized) attacker can fill the entire table with his nodes/addresses.&amp;lt;br&amp;gt;&amp;lt;br&amp;gt;To that end: &lt;br /&gt;
   * Addresses are organized into buckets.&lt;br /&gt;
     * Addresses that have not yet been tried go into 1024 &amp;quot;new&amp;quot; buckets.&lt;br /&gt;
     * Addresses of nodes that are known to be accessible go into 256 &amp;quot;tried&amp;quot; buckets.&lt;br /&gt;
     * Bucket selection is based on cryptographic hashing, using a randomly-generated 256-bit key, which should not be observable by adversaries.&lt;br /&gt;
     * Several indexes are kept for high performance. Defining DEBUG_ADDRMAN will introduce frequent (and expensive) consistency checks for the entire data structure.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Timestamps&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The address manager also keeps track of when each peer was last heard from.  Timestamps are only updated on an address and saved to the database when the timestamp is over 20 minutes old.  By understanding the role of timestamps, it will become more clear why timestamps are kept the way they are for each of the different ways an address is discovered.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Peer discovery===&lt;br /&gt;
&lt;br /&gt;
The program discovers the IP address and port of nodes in several different ways: &lt;br /&gt;
* Address database (peers.dat)&lt;br /&gt;
* User-specified (-addnode and -connect)&lt;br /&gt;
* DNS seeding&lt;br /&gt;
* Hard-coded seeds&lt;br /&gt;
* From other peers (&amp;quot;getaddr&amp;quot; and &amp;quot;addr&amp;quot; messages)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;1) Address database (peers.dat)&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Nodes store addresses in a database (peers.dat) which is read on startup, and loaded into the address manager.  &lt;br /&gt;
&lt;br /&gt;
This method does not work the first time the program is run, since it does not already know about any other nodes on the bitcoin network.&lt;br /&gt;
&lt;br /&gt;
For details on when/how the code stores to the database, see the section above on the address manager. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;2) User-specified on the command line&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The user can specify nodes to connect to on the command line with -addnode &amp;lt;ip&amp;gt; or -connect &amp;lt;ip&amp;gt;. &lt;br /&gt;
&lt;br /&gt;
Notes on user-specified IP addresses: &lt;br /&gt;
* Multiple nodes may be specified.&lt;br /&gt;
* Addresses are initially given a zero timestamp, therefore they are not advertised in response to a &amp;quot;getaddr&amp;quot; request.&lt;br /&gt;
* With -connect, the IP addresses will not be added to peers.dat and only the provided addresses will be used. &lt;br /&gt;
* With -addnode, the provided addresses will be used as a starting point, but the node will soon learn other peers.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;3) DNS seeding&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
DNS seeding is only used if the peers.dat database is empty (as it would be when initiallly running the program) and the user has not specified any nodes with -addnode or -connect. &lt;br /&gt;
&lt;br /&gt;
In this case, the node can issue DNS requests to discover IP addresses of other peers.&lt;br /&gt;
&lt;br /&gt;
As of 0.11, there are six DNS servers hard-coded into the program -  see chainparams.cpp. &lt;br /&gt;
&lt;br /&gt;
A DNS reply can contain multiple IP addresses for a requested name.&lt;br /&gt;
&lt;br /&gt;
Addresses discovered via DNS are initially given a zero timestamp, to avoid being advertised in response to a &amp;quot;getaddr&amp;quot; request.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;4) Hard-coded nodes (last resort)&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
If DNS seeding fails, the client contains hard coded IP addresses that represent bitcoin nodes.  See:  &amp;lt;u&amp;gt;chainparamsseeds.h&amp;lt;/u&amp;gt;&lt;br /&gt;
&lt;br /&gt;
These addresses are only used as a last resort, and a log message will be printed:  &amp;quot;Adding fixed seed nodes as DNS doesn&#039;t seem to be available.&amp;quot;   (&amp;lt;u&amp;gt;net.cpp&amp;lt;/u&amp;gt;)&lt;br /&gt;
&lt;br /&gt;
The idea is to move away from seed nodes as soon as possible, to avoid overloading those nodes. &lt;br /&gt;
&lt;br /&gt;
Once the local node has enough addresses (presumably learned from the seed nodes), the connection thread will close any seed node connections.&lt;br /&gt;
&lt;br /&gt;
Like the DNS seed addresses, the hard-coded seed addresses are also given a zero timestamp to avoid being advertised in response to a &amp;quot;getaddr&amp;quot; request.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;5) From other nodes (&amp;quot;getaddr&amp;quot; and &amp;quot;addr&amp;quot; messages)&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Nodes exchange IP addresses with other nodes via the &amp;quot;getaddr&amp;quot; and &amp;quot;addr&amp;quot; messages.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Usually, an addr&amp;quot; message is sent in response to a &amp;quot;getaddr&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
However, the &amp;quot;addr&amp;quot; message may also arrive unsolicited, because nodes advertise addresses gratuitously when they: &lt;br /&gt;
* Relay addresses (see below)&lt;br /&gt;
* Advertise their own address periodically.  (Every 24 hours, the node advertises its own address to all connected nodes.)&lt;br /&gt;
* When a connection is made (in response to an initial &amp;quot;version&amp;quot; message) &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
When does a node send a &amp;quot;getaddr&amp;quot; message? &lt;br /&gt;
* In response to a &amp;quot;version&amp;quot; message from an outbound node, if we don&#039;t yet have 1000 addresses. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Receiving an &amp;quot;addr&amp;quot; message: &lt;br /&gt;
* If the sending node is an old version and we have 1000 addresses already, it is ignored. &lt;br /&gt;
* If the sending node is a current version and is attempting to send us more than 1000 addresses, the peer is punished for misbehaving. &lt;br /&gt;
* If the address has been seen in the last 24 hours and the timestamp is currently over 60 minutes old, then it is updated to 60 minutes ago.&lt;br /&gt;
* If the address has NOT been seen in the last 24 hours, and the timestamp is currently over 24 hours old, then it is updated to 24 hours ago.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Responding to a &amp;quot;getaddr&amp;quot; message:&lt;br /&gt;
* The node figures out how many addresses it has that have a timestamp in the last 3 hours. &lt;br /&gt;
* It sends those addresses, but if there are more than 2500 addresses, it randomly selects 2500.&lt;br /&gt;
* It clears the list of the addresses we think the remote node has, which will trigger a refresh of sends to nodes. See SendMessages. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Address Relay&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Once added, the newly received IP addresses may be relayed to other nodes if the following conditions are met:&lt;br /&gt;
* The address timestamp is recent (within 10 minutes of the current time)&lt;br /&gt;
* The &amp;quot;addr&amp;quot; message contained 10 addresses or less&lt;br /&gt;
* fGetAddr=false for the sending peer. (See the code for details.)&lt;br /&gt;
* The address must be routable.&lt;br /&gt;
* Code: &lt;br /&gt;
 if (addr.nTime &amp;gt; nSince &amp;amp;&amp;amp; !pfrom-&amp;gt;fGetAddr &amp;amp;&amp;amp; vAddr.size() &amp;lt;= 10 &amp;amp;&amp;amp; addr.IsRoutable())&lt;br /&gt;
* If this test is passed, then the code&#039;s next step is (see main.cpp for details): &lt;br /&gt;
 // Use deterministic randomness to send to the same nodes for 24 hours at a time so the addrKnowns of the chosen nodes prevent repeats.&lt;br /&gt;
&lt;br /&gt;
===Peer connectivity===&lt;br /&gt;
&lt;br /&gt;
The connection thread (ThreadOpenConnections) chooses among the available addresses and makes connections, and disconnects nodes when appropriate. &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Use of CSemaphore for outbound connections&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The code uses a semaphore to manage the number of outbound connections (usually 8). &lt;br /&gt;
&lt;br /&gt;
Most of the code dealing with the semaphore is in &amp;lt;u&amp;gt;net.cpp&amp;lt;/u&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
When a connection is opened, the semaphore grant is passed to the CNode data structure.  This allows the socket thread to release the semaphore when the time comes, with: &lt;br /&gt;
 pnode-&amp;gt;grantOutbound.Release()  // see net.cpp&lt;br /&gt;
&lt;br /&gt;
The code CSemaphore grant(*semOutbound) will wait until there is a connection available. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Inbound connections: accepting and disconnecting&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Inbound connections can be up to 125 total.  &lt;br /&gt;
&lt;br /&gt;
ThreadSocketHandler has the code that accepts inbound connections. &lt;br /&gt;
&lt;br /&gt;
The socket thread loop: &lt;br /&gt;
* 1) Disconnects sockets that have the fDisconnect flag set on them (and have empty buffers)&lt;br /&gt;
* 2) Prepares all sockets for &amp;quot;select&amp;quot;&lt;br /&gt;
* 3) Calls &amp;quot;select&amp;quot;, which is a system call which waits for activity on a set of sockets. &lt;br /&gt;
&lt;br /&gt;
When the select() call returns, the node accepts any new connections, receives and sends on any ready sockets, and marks any inactive sockets to be disconnected (whether inbound or outbound).&lt;br /&gt;
&lt;br /&gt;
Sockets are disconnected if: &lt;br /&gt;
 * they are 60 seconds old and have not sent or received data.&lt;br /&gt;
 * they have not sent or received data in the last 20 minutes (TIMEOUT_INTERVAL = 20*60) (or 90 minutes if peer is an old version)&lt;br /&gt;
 * the socket overfills the buffer (see CNode::ReceiveMsgBytes- &amp;quot;Oversized message from peer=%i, disconnecting\n&amp;quot; in &amp;lt;u&amp;gt;net.cpp&amp;lt;/u&amp;gt;)&lt;br /&gt;
&lt;br /&gt;
==Sockets &amp;amp; Messages==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Socket Thread&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The socket thread operates at the TCP layer.  &lt;br /&gt;
&lt;br /&gt;
It goes through an endless loop, reading and writing the sockets. (see &amp;lt;u&amp;gt;net.cpp&amp;lt;/u&amp;gt;).&lt;br /&gt;
&lt;br /&gt;
Its loop involves three basic activities: &lt;br /&gt;
&lt;br /&gt;
1) Administrative work:  disconnecting unused sockets, checking which sockets have data, adding sockets for new connections.&lt;br /&gt;
&lt;br /&gt;
2) Receiving data:  It reads the sockets that have data using the recv() system call and places that data into the peer&#039;s queue of CNetMessages.  A CNetMessage organizes the data into two data streams - the message header and the message data (vRecv).  The socket thread reads the buffer until it has processed all the messages from this particular peer. &lt;br /&gt;
&lt;br /&gt;
3) Sending data:  The message thread queued up messages-to-be-sent as vSendMsg objects, so the socket thread deserializes these objects and sends them using send(). (send() is a syscall and any incompatibilities across different operating systems are handled in the &amp;lt;u&amp;gt;compat.h&amp;lt;/u&amp;gt; file.)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Message Thread&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
This is the program&#039;s main thread. &lt;br /&gt;
&lt;br /&gt;
It operates primarily at the &amp;quot;business logic&amp;quot; level - validating transactions, managing the blockchain, etc. &lt;br /&gt;
&lt;br /&gt;
In a sense, all of the node&#039;s activities take the form of processing an inbound message or preparing an outbound message.  &lt;br /&gt;
&lt;br /&gt;
Like the socket thread, this thread consists of a while(true) loop, processing inbound messages and queuing up outbound messages.  Once the program&#039;s initialization is complete, this loop (see &amp;lt;u&amp;gt;net.cpp&amp;lt;/u&amp;gt;:ThreadMessageHandler) is the program&#039;s high-level point of control. &lt;br /&gt;
&lt;br /&gt;
The loop uses signals to notify &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt; that there are messages waiting to be processed.  The signal is picked up by ProcessMessages().&lt;br /&gt;
&lt;br /&gt;
The use of signals has nothing to do with multi-threading;  the signal is sent and picked up in the same thread.  The use of signals was introduced in version 0.9 for the purpose of decoupling &amp;lt;u&amp;gt;net.cpp&amp;lt;/u&amp;gt; from &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt;.   In version 0.8, the loop simply called the ProcessMessages() function.  By changing to signals, the &amp;lt;u&amp;gt;net.cpp&amp;lt;/u&amp;gt; code no longer needs to be aware of the processing code.  Removing that dependency allows the code to avoid circular includes (since &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt; requires knowledge of &amp;lt;u&amp;gt;net.h&amp;lt;/u&amp;gt;. &lt;br /&gt;
&lt;br /&gt;
The pull request introducing signals is [https://github.com/bitcoin/bitcoin/pull/2154 PR 2154.]&lt;br /&gt;
&lt;br /&gt;
The commit removing the &amp;quot;main.h&amp;quot; dependency is [https://github.com/CodeShark/bitcoin/commit/6e68524e95da2bedc21b1d95c4a206b902ab7c22 here].&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;ProcessMessages (&amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt;)&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
ProcessMessages() is the entry point in &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt; for almost all of the code that processes and validates transactions and blocks, etc. &lt;br /&gt;
&lt;br /&gt;
It attempts to find a message start signature in the vRecv stream. If it finds a message start, it deletes everything prior to the start. Then it reads the header, extracts the message type, and calls ProcessMessage on the message.&lt;br /&gt;
&lt;br /&gt;
ProcessMessage() is basically a large &amp;quot;switch&amp;quot; which takes action based on what type of message it is dealing with.  &lt;br /&gt;
&lt;br /&gt;
Often, in the course of processing a message, the code will push messages to the outbound queue.  For example, when processing an incoming &amp;quot;getdata&amp;quot; message, the node pushes the outbound data into the queue.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;SendMessages (&amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt;)&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
SendMessages() creates messages and queues them up in the peer&#039;s vSendMsg queue (a double-ended queue, or &amp;quot;deque&amp;quot; in C++).  The vSendMsg objects are basically just serialized data. &lt;br /&gt;
&lt;br /&gt;
SendMessages goes through various data structures looking for work to do.  When it produces a message it calls the CNode-&amp;gt;PushMessage, which queues the outbound data.  (Note that there are many other places in the code that produce messages and call CNode-&amp;gt;PushMessage;  SendMessages() doesn&#039;t have any kind of exclusive license on placing messages in the outbound queue.)&lt;br /&gt;
&lt;br /&gt;
Once the data is queued up by PushMessage, it sits and waits for the socket thread to come along. &lt;br /&gt;
&lt;br /&gt;
The socket thread and the message thread use a peer-specific lock (node-&amp;gt;cs_vSend) to coordinate access to the socket.&lt;br /&gt;
&lt;br /&gt;
==Locks==&lt;br /&gt;
&lt;br /&gt;
The main locks associated with the P2P aspect of the code are: &lt;br /&gt;
* cs_vNodes controls access to the CNode objects.&lt;br /&gt;
* cs_vSend controls access to the node&#039;s send buffer. &lt;br /&gt;
* cs_vRecvMsg controls access to the node&#039;s receiving buffer. &lt;br /&gt;
* cs_inventory &lt;br /&gt;
&lt;br /&gt;
==Denial-of-Service Prevention==&lt;br /&gt;
&lt;br /&gt;
DoS prevention is implemented by keeping track of misbehaving peers, and if they misbehave, banning them.&lt;br /&gt;
&lt;br /&gt;
The DoS prevention framework was introduced in 2011, in Pull 517.&lt;br /&gt;
&lt;br /&gt;
As summarized there: &lt;br /&gt;
&lt;br /&gt;
&amp;lt;blockquote&amp;gt;&lt;br /&gt;
-----&lt;br /&gt;
The big idea: if a peer is sending you obviously wrong information, punish it by maybe dropping your connection to it, and ban it&#039;s IP address so it cannot immediately re-connect.&lt;br /&gt;
&amp;lt;br&amp;gt;&amp;lt;br&amp;gt;The probability of dropping the connection, and the length of the ban, depend on how wrong, and how potentially wasteful/damaging, the peer is. So sending an extra &#039;version&#039; message is a minor transgression that is usually tolerated, sending an more than MAX_BLOCK_SIZE block is a major transgression.&lt;br /&gt;
&amp;lt;br&amp;gt;&amp;lt;br&amp;gt;Detailed how-it-works, using &amp;quot;I got a version message I wasn&#039;t expecting&amp;quot; as the specific example:&lt;br /&gt;
&amp;lt;br&amp;gt;&amp;lt;br&amp;gt;Getting a version message from a peer increases that peer&#039;s &#039;misbehaving&#039; score by 10, and (assuming that is the peer&#039;s first bad behavior) gives it a 10% of being disconnected. If it is disconnected, then that peer&#039;s IP address is banned from connecting for a couple of hours. If it is not disconnected, then nothing happens unless the peer misbehaves again; if it does, then its chances of being disconnected go up, and the length of time it will be banned increases.&lt;br /&gt;
&amp;lt;br&amp;gt;&amp;lt;br&amp;gt;Misbehavior/ban information is stored only in memory, and information about misbehaving peers is never broadcast. Also, peers that are disconnected/banned are just dropped, there is no warning or reason sent. &lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
     --Gavin Andresen&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
-----&lt;br /&gt;
&amp;lt;/blockquote&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Source:  https://github.com/bitcoin/bitcoin/pull/517&amp;lt;/blockquote&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Banned nodes&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The set of banned nodes is in setBanned in &amp;lt;u&amp;gt;net.cpp&amp;lt;/u&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
By default, a node is banned for 24 hours, though this can be configured with -bantime option.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==See also==&lt;br /&gt;
[https://en.bitcoin.it/wiki/Bitcoin_Core_0.11_(ch_1):_Overview Bitcoin Core 0.11 (Ch 1): Overview]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[https://en.bitcoin.it/wiki/Bitcoin_Core_0.11_(ch_2):_Data_Storage Bitcoin Core 0.11 (Ch 2): Data Storage]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[https://en.bitcoin.it/wiki/Bitcoin_Core_0.11_(ch_3):_Initialization_and_Startup Bitcoin Core 0.11 (Ch 3): Initialization and Startup]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[https://en.bitcoin.it/wiki/Bitcoin_Core_0.11_(ch_5):_Initial_Block_Download Bitcoin Core 0.11 (Ch 5): Initial Block Download]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[https://en.bitcoin.it/wiki/Bitcoin_Core_0.11_(ch_6):_The_Blockchain Bitcoin Core 0.11 (Ch 6): The Blockchain]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Technical]]&lt;br /&gt;
[[Category:Developer]]&lt;/div&gt;</summary>
		<author><name>Mrbandrews</name></author>
	</entry>
	<entry>
		<id>https://en.bitcoin.it/w/index.php?title=Bitcoin_Core_0.11_(ch_6):_The_Blockchain&amp;diff=60022</id>
		<title>Bitcoin Core 0.11 (ch 6): The Blockchain</title>
		<link rel="alternate" type="text/html" href="https://en.bitcoin.it/w/index.php?title=Bitcoin_Core_0.11_(ch_6):_The_Blockchain&amp;diff=60022"/>
		<updated>2016-01-21T20:27:20Z</updated>

		<summary type="html">&lt;p&gt;Mrbandrews: Created page with &amp;quot;  This page describes the code that manages the blockchain.     ==Block Index and Block Status==  The block index database gets loaded into memory when the node starts.  This...&amp;quot;&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
&lt;br /&gt;
This page describes the code that manages the blockchain. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Block Index and Block Status==&lt;br /&gt;
&lt;br /&gt;
The block index database gets loaded into memory when the node starts.  This means the entire block tree, not just the active chain.  See LoadBlockIndexGuts() in &amp;lt;u&amp;gt;src/txdb.cpp&amp;lt;/u&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
The block index (block metadata) is well commented in the code:  see &amp;lt;u&amp;gt;src/chain.h&amp;lt;/u&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
One of the key traits of a block is its &amp;quot;verification status.&amp;quot; &lt;br /&gt;
&lt;br /&gt;
Verification status captures the degree to which the code has validated this block, as well as its ancestor blocks. &lt;br /&gt;
&lt;br /&gt;
The block&#039;s status is one of the following: &lt;br /&gt;
&lt;br /&gt;
* VALID_HEADER = 1&lt;br /&gt;
* VALID_TREE = 2&lt;br /&gt;
* VALID_TRANSACTIONS = 3&lt;br /&gt;
* VALID_CHAIN = 4&lt;br /&gt;
* VALID_SCRIPTS = 5&lt;br /&gt;
&lt;br /&gt;
The precise meaning of each status code is documented in &amp;lt;u&amp;gt;chain.h&amp;lt;/u&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Also stored in the block index are two variables worth mentioning: &lt;br /&gt;
&lt;br /&gt;
: &#039;&#039;&#039;nTx:&#039;&#039;&#039;  Number of transactions in this block.  &lt;br /&gt;
: nTx &amp;gt; 0 means that the block has a status of at least VALID_TRANSACTIONS.  &lt;br /&gt;
&lt;br /&gt;
: &#039;&#039;&#039;nChainTx:&#039;&#039;&#039;  Number of transactions in this block&#039;s chain, up to and including this block.  &lt;br /&gt;
: This value will be set if and only if transactions for this block &#039;&#039;and all its parents&#039;&#039; are available.  &lt;br /&gt;
: Thus, nChainTx &amp;gt; 0 is shorthand for a chain that is VALID_TRANSACTIONS.  This is notable because this information is not available via the block-status enum.  Namely, VALID_TRANSACTIONS only implies that its parents are TREE, while VALID_CHAIN implies that its parents are also CHAIN.  In a sense, then, the expression (nChainTx !=0) is shorthand for a status that might be said to be &amp;quot;VALID_nChainTx = 3.5&amp;quot; - because it&#039;s more than VALID_TRANSACTIONS but less than VALID_CHAIN. &lt;br /&gt;
: Note: nChainTx is only stored in memory;  there is no corresponding entry in the database.&lt;br /&gt;
&lt;br /&gt;
==Key Variables==&lt;br /&gt;
&lt;br /&gt;
First, a quick C++ reminder: &lt;br /&gt;
* map:  an unordered &amp;lt;key,value&amp;gt; container (think of it as a hashtable) &lt;br /&gt;
* set:  an ordered &amp;lt;key&amp;gt; container (think of it as a sorted linked list) &lt;br /&gt;
* multimap:  an ordered map &amp;lt;key,value&amp;gt; where duplicate keys are allowed (thus, can hold elements &amp;lt;a,1&amp;gt;,&amp;lt;b,2&amp;gt;,&amp;lt;b,3&amp;gt;)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;mapBlockIndex (map&amp;lt;block_hash, CBlockIndex*&amp;gt;)&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
This map contains all known blocks (where &amp;quot;block&amp;quot; means &amp;quot;block index&amp;quot;).  Since a block index is created and stored in the LevelDB when a header is received, it&#039;s possible to have block indexes in the block map without having received the full block yet, let alone having stored it to disk.&lt;br /&gt;
&lt;br /&gt;
mapBlockIndex is not sorted.  Just think of it as your blocks/ LevelDB in memory, with the key being the block hash. &lt;br /&gt;
&lt;br /&gt;
It is technically of type BlockMap, which is for readability.  BlockMap is an unordered_map&amp;lt;block hash, block index*, comparator_function&amp;gt;. &lt;br /&gt;
&lt;br /&gt;
mapBlockIndex is initialized from the database in LoadBlockIndexGuts, which is run at Step 7 of startup.  Thereafter, it&#039;s updated whenever new blocks are received over the network. &lt;br /&gt;
&lt;br /&gt;
mapBlockIndex only grows, it never shrinks.  (Try searching main.cpp for mapBlockIndex.erase.)  Observe also that the block index&#039;s LevelDB wrapper does not contain functionality for erasing blocks from the database - it&#039;s writing function (WriteBatchSync) only writes to the database. By comparison, the chainstate wrapper&#039;s writing function (BatchWrite) both writes and erases.  (see &amp;lt;u&amp;gt;txdb.cpp&amp;lt;/u&amp;gt;).  &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;mapBlocksUnlinked&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Multimap containing &amp;quot;all pairs A-&amp;gt;B, where A (or one if its ancestors) misses transactions, but B has transactions.&amp;quot; (comment at &amp;lt;u&amp;gt;main.cpp:125&amp;lt;/u&amp;gt;).&lt;br /&gt;
&lt;br /&gt;
The purpose of mapBlocksUnlinked is to quickly attach blocks we&#039;ve already received to the blockchain when we receive a missing, intermediate block. &lt;br /&gt;
&lt;br /&gt;
The alternative would be to search the entire mapBlockIndex;  however, it is more efficient to keep track of unlinked blocks in a separate data structure.  &lt;br /&gt;
&lt;br /&gt;
  Example 1: &lt;br /&gt;
  Let A be our tip.&lt;br /&gt;
  We receive block &#039;&#039;headers&#039;&#039; for B, C.&lt;br /&gt;
  We receive the full block for C.&lt;br /&gt;
  mapBlocksUnlinked = &amp;lt;B,C&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Upon receiving block B, we can connect C.   &lt;br /&gt;
&lt;br /&gt;
  Example 2: &lt;br /&gt;
  Let A be our tip.&lt;br /&gt;
  We receive block &#039;&#039;headers&#039;&#039; for B, C, D.&lt;br /&gt;
  We receive the full block for D.&lt;br /&gt;
  mapBlocksUnlinked = &amp;lt;B,C&amp;gt;, &amp;lt;B,D&amp;gt;, &amp;lt;C,D&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Upon receiving block B, we can connect B as our tip and delete its entries in mapBlocksUnlinked, which would now consist of only one item: &amp;lt;C,D&amp;gt;. &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;setBlockIndexCandidates&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Set of block indexes that have more total work than our current tip.  (In the normal case where the block extends our current tip, it is easy enough to see that it has more total work than our tip.)  Thus, they are &amp;quot;candidates&amp;quot; for extending our current blockchain (or re-organizing from our current chain to the chain that the candidate is on.)  We call them &amp;quot;candidates&amp;quot; because we verify the block&#039;s proof-of-work when we receive the header, but before we receive the block.  Thus, the &#039;&#039;header&#039;&#039; is a candidate for extending our chain, but we can&#039;t say for sure until we receive the full block (and if the candidate is more than one block away from our current tip, we also need to receive and verify any intermediate blocks.)&lt;br /&gt;
&lt;br /&gt;
   Example 1: Let A be our tip; we then receive, in order, B, C, D, such that: &lt;br /&gt;
    A -- B&lt;br /&gt;
      \&lt;br /&gt;
       C -- D&lt;br /&gt;
&lt;br /&gt;
We verify headers for B, C, D and they all look good. At this point setBlockIndexCandidates contains &amp;lt;B,C,D&amp;gt;.  Assume B has more work than C but less work than D. &lt;br /&gt;
&lt;br /&gt;
Now we receive the full block for B and it checks out.  At this point, we extend chainActive with B as the new tip, and remove B from setBlockIndexCandidates.  We also remove C because it has less work than B.  But D still is. &lt;br /&gt;
&lt;br /&gt;
Now we receive C and D.  C is valid, but D has a bad transaction (double-spend, invalid signature, etc.): &lt;br /&gt;
* Store C to disk and keep it in mapBlocksIndex - it&#039;s a known block&lt;br /&gt;
* Discard D (do not store to disk) and delete it from mapBlocksIndex - it&#039;s a bad block&lt;br /&gt;
* Remove D from setBlockIndexCandidates&lt;br /&gt;
&lt;br /&gt;
Now our chainActive is Genesis - - - - - - - A--B, and setBlockIndexCandidates is &amp;lt;empty&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;pindexBestHeader&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
This variable holds the best (most work) header that your node has validated. &lt;br /&gt;
&lt;br /&gt;
It&#039;s set initially when loading the block index, and updated when adding a header to the mapBlockIndex which has more work than the current pIndexBestHeader. &lt;br /&gt;
&lt;br /&gt;
A header is added to mapBlockIndex once it has passed the context-dependent and context-indendent checks.  &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;chainActive (vector&amp;lt;CBlockIndex*&amp;gt;&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
chainActive is the holy blockchain.  It is a linear set of blocks, consisting only of those blocks that comprise the longest chain, beginning with the Genesis block and culminating with the tip. &lt;br /&gt;
&lt;br /&gt;
chainActive is a CChain, which is a vector of block indexes bundled with a few useful methods (see &amp;lt;u&amp;gt;chain.h&amp;lt;/u&amp;gt;). &lt;br /&gt;
&lt;br /&gt;
On startup, the chain is initialized in Step 10 (&amp;lt;u&amp;gt;init.cpp&amp;lt;/u&amp;gt;), which calls ActivateBestChain (&amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt;).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Difference between pindexBestHeader and chainActive.Tip&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
It&#039;s important to note that pindexBestHeader and chainActive.Tip are NOT necessarily the same thing.  &lt;br /&gt;
&lt;br /&gt;
pindexBestHeader is a pointer to the most-work header our node has received, before having received its transactions.  By comparison, chainActive.Tip is only set after we&#039;ve received and validated the entire block.&lt;br /&gt;
&lt;br /&gt;
==Connecting a block==&lt;br /&gt;
&lt;br /&gt;
When the node receives and accepts a block that has more proof-of-work than the tip of its active blockchain, the node will attempt to make this block the new tip.&lt;br /&gt;
&lt;br /&gt;
In &amp;quot;steady-state&amp;quot;, where our node&#039;s active chain tip is a block B1, the typical course of events is that every 10 minutes or so, the node receives and accepts a new block B2 which was built on top of B1 (meaning B2&#039;s &amp;quot;prev_block&amp;quot; is B1&#039;s hash), notices that B2 has more work than B1, and connects B2 to B1, thereby extending the active chain.&lt;br /&gt;
&lt;br /&gt;
ConnectBlock() is the key moment when a &amp;quot;double-spend&amp;quot; would be discovered.  The block&#039;s transactions are validated against the current UTXO set (the coins database).  Specifically, the code in ConnectBlock loops through each transaction, ensuring that all of the transaction&#039;s inputs can indeed be found in the coins database.  (If a coin had been spent in a prior block, it would not be in the current UTXO set; it would have been in a different, earlier view of the UTXO set, but no longer.)  The ConnectBlock code also contains some DoS protection code:  for example, it ensures that the transactions do not contain an excessive number of signature operations (which are expensive). &lt;br /&gt;
&lt;br /&gt;
ConnectBlock() is the last step in ProcessNewBlock.  Thus, it takes place only after the block has been accepted and stored to disk.  The idea is that a block can be valid in the abstract but whether its transactions are valid is dependent upon the UTXO set at the particular point where the block is being added to the chain.  This may not be known until a later point in time, even in steady-state.  Presume that our current tip is B1, which is then extended by B2 and B3 in rapid succession. For whatever reason, we receive B3 before B2 (perhaps B2 was created by a miner across the globe to whom we are poorly connected, whereas B3 was mined by our next-door neighbor who has a better link to the miner who created B2).  At the moment we receive B3, it may (and probably does) contain transactions whose inputs do not exist in our coin database, because they are only created in B2.  In any event, no effort is made to validate B3 beyond the basic checks.  Later, when we receive B2, we connect it and update the UTXO set, then notice that B3 extends B2.  Now B3&#039;s transactions can be validated and assuming it checks out, it becomes the new tip of the active chain. &lt;br /&gt;
&lt;br /&gt;
If the entire block checks out, then the block is connected, and the undo data is created and stored to disk.&lt;br /&gt;
&lt;br /&gt;
If there&#039;s a problem with one of the block&#039;s transactions, the block is not connected, and the code punishes the peer that sent us the bad block. (See InvalidBlockFound.)&lt;br /&gt;
&lt;br /&gt;
==Disconnecting a block (reorganizations)==&lt;br /&gt;
&lt;br /&gt;
A reorganization (re-org) occurs when your node realizes there is a longer chain that does not derive from chainActive.Tip.  &lt;br /&gt;
&lt;br /&gt;
Most reorganizations are only one-block reorganizations.  This is likely to happen whenever competing miners find new blocks (call them A and B) at about the same time.  Some of the network will receive A first, others B.  Eventually a new block C will be mined on top of either A or B; which one depends on whether the miner who produced C worked on the A or B chain.  Assuming C is mined on top of A, then any node which accepted B as the tip of their blockchain will need to detach B and instead attach A and C. &lt;br /&gt;
&lt;br /&gt;
Here is how a reorg happens in the code: &lt;br /&gt;
* When we receive a new block, if it has more work than our chain&#039;s tip, we add it to the setBlockIndexCandidates (see main.cpp:ReceivedBlockTransactions)&lt;br /&gt;
* After the block is processed, ActivateBestChain checks to see if there&#039;s a block (such as the one we just processed) that has more work than the current chain&#039;s tip.&lt;br /&gt;
* ActivateBestChainStep disconnects blocks as necessary to reach the new tip.  Obviously, in the usual case it is not necessary to disconnect any blocks.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;DisconnectTip() does the following:&#039;&#039;&#039;&lt;br /&gt;
* Returns the utxo&#039;s that were consumed by this block back to the utxo set (DisconnectBlock).&lt;br /&gt;
* Returns the block&#039;s transactions to the mempool.  (Now they need to be mined by some other block; quite likely in one of the blocks we are about to connect, in which case we&#039;ll remove them again!) &lt;br /&gt;
* Moves chainActive.Tip back one block. &lt;br /&gt;
* Updates the wallet. &lt;br /&gt;
&lt;br /&gt;
Once the code has disconnected blocks back to the fork point, it connects blocks from the fork point to the new tip.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;DisconnectBlock (returning utxo&#039;s to the utxo set)&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
This code uses the undo.dat file to &amp;quot;un-spend&amp;quot; the coins that were spent in the block now being disconnected: &lt;br /&gt;
* Reads the undo file from disk.&lt;br /&gt;
* Processes transactions in reverse order (must be reverse order because CreateNewBlock creates zero-conf transactions &amp;quot;in order&amp;quot;, meaning that if a block contains T1 and T2 and T2 spends a T1 coin, then T1 must come before T2 in its transaction vector;  therefore, when un-spending the coins, T2 must be un-spent before T1). &lt;br /&gt;
* Looks up the spent coins&lt;br /&gt;
* Un-spends the coins in a helper function, ApplyTxInUndo:  coins-&amp;gt;vout[out.n] = undo.txout;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==See also==&lt;br /&gt;
[https://en.bitcoin.it/wiki/Bitcoin_Core_0.11_(ch_1):_Overview Bitcoin Core 0.11 (Ch 1): Overview]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[https://en.bitcoin.it/wiki/Bitcoin_Core_0.11_(ch_2):_Data_Storage Bitcoin Core 0.11 (Ch 2): Data Storage]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[https://en.bitcoin.it/wiki/Bitcoin_Core_0.11_(ch_3):_Initialization_and_Startup Bitcoin Core 0.11 (Ch 3): Initialization and Startup]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[https://en.bitcoin.it/wiki/Bitcoin_Core_0.11_(ch_4):_P2P_Network Bitcoin Core 0.11 (Ch 4): P2P Network]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[https://en.bitcoin.it/wiki/Bitcoin_Core_0.11_(ch_5):_Initial_Block_Download Bitcoin Core 0.11 (Ch 5): Initial Block Download]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Technical]]&lt;br /&gt;
[[Category:Developer]]&lt;/div&gt;</summary>
		<author><name>Mrbandrews</name></author>
	</entry>
	<entry>
		<id>https://en.bitcoin.it/w/index.php?title=Bitcoin_Core_0.11_(ch_5):_Initial_Block_Download&amp;diff=60021</id>
		<title>Bitcoin Core 0.11 (ch 5): Initial Block Download</title>
		<link rel="alternate" type="text/html" href="https://en.bitcoin.it/w/index.php?title=Bitcoin_Core_0.11_(ch_5):_Initial_Block_Download&amp;diff=60021"/>
		<updated>2016-01-21T20:08:48Z</updated>

		<summary type="html">&lt;p&gt;Mrbandrews: Created page with &amp;quot; This page explains how Bitcoin Core downloads the blockchain when your node first joins the network.    ==Background==  Once a new node joins the network, its first order of...&amp;quot;&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
This page explains how Bitcoin Core downloads the blockchain when your node first joins the network.  &lt;br /&gt;
&lt;br /&gt;
==Background==&lt;br /&gt;
&lt;br /&gt;
Once a new node joins the network, its first order of business is to download and validate the entire blockchain.   This is an integral step to the distributed nature of bitcoin because only by doing this can a node claim that it has independently validated all transactions.  &lt;br /&gt;
&lt;br /&gt;
As the blockchain grows in size, the time required for IBD increases unless optimizations are made to the code.  Various optimizations have been made since Satoshi&#039;s original client was released, but as of 2014, with increasing transaction volume, initial download on laptop hardware with an average connection could still take up to 24 hours.  Developers agreed that this was unacceptable and a new approach was developed called &amp;quot;headers first&amp;quot; mode.  This approach resulted in a substantial speedup.&lt;br /&gt;
&lt;br /&gt;
==&amp;quot;Headers First&amp;quot; mode==&lt;br /&gt;
&lt;br /&gt;
With &amp;quot;headers-first&amp;quot; mode, a new node downloads all of the block headers first, which are very small (about 80 bytes, whereas a block can be up to 1MB).  Once the node has all of the headers, from the genesis block up to the current tip of the blockchain (380,000 as of October 2015), only then does it begins downloading the full blocks.&lt;br /&gt;
&lt;br /&gt;
Now that it has the headers, the node downloads blocks in parallel from multiple peers.  (It downloads headers from only one peer, but that&#039;s no big deal since headers are small.)  The node will download from up to 8 peers at once and will disconnect any peer that stalls for more 2 seconds, attempting to connect to a faster peer. &lt;br /&gt;
&lt;br /&gt;
Headers-first IBD was merged in 2014 in:  [https://github.com/bitcoin/bitcoin/pull/4468 Pull Request 4468].&lt;br /&gt;
&lt;br /&gt;
As summarized in the PR comment, some of its main features are [comment is edited slightly here]:&lt;br /&gt;
&lt;br /&gt;
* Do not use &#039;getblocks&#039;, but &#039;getheaders&#039;, and use it to build a headers tree.&lt;br /&gt;
* Blocks are fetched in parallel from all available outbound peers, using a limited moving window. When one peer stalls the movement of the window, it is disconnected.&lt;br /&gt;
* No more orphan blocks. At all. We only ever request a block for which we have verified the headers, and store it to disk immediately. This means that a disk-fill attack would require Proof of Work.&lt;br /&gt;
* We sync from everyone we can, though limited to 1 during initial headers sync.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Checkpoints==&lt;br /&gt;
&lt;br /&gt;
The Bitcoin Core initial block download code makes sure that the block headers you are downloading (from a single peer) passes certain, hard-coded &amp;quot;checkpoints.&amp;quot; &lt;br /&gt;
&lt;br /&gt;
Checkpoints are block hashes corresponding to a long-ago block that everyone (where &amp;quot;everyone&amp;quot; means the network participants as recognized by the Bitcoin Core commit-access developers) recognizes as being on the longest chain.  The checkpoints are set far enough in the so as to be non-controversial. &lt;br /&gt;
&lt;br /&gt;
The IBD checkpoints check is at &amp;lt;u&amp;gt;main.cpp:2784&amp;lt;/u&amp;gt; (version 0.11).&lt;br /&gt;
&lt;br /&gt;
The hardcoded figures are in &amp;lt;u&amp;gt;chainparams.cpp&amp;lt;/u&amp;gt;.  (As of 0.11, there were 13 checkpoints, the first at block 11,111, the last at block 295,000.)&lt;br /&gt;
&lt;br /&gt;
From chainparams.cpp: &lt;br /&gt;
&lt;br /&gt;
:: /**&lt;br /&gt;
:: * What makes a good checkpoint block?&lt;br /&gt;
:: *   Is surrounded by blocks with reasonable timestamps (no blocks before with a timestamp after, none after with timestamp before)&lt;br /&gt;
:: *   Contains no strange transactions&lt;br /&gt;
:: */&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Purpose of Checkpoints&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The purpose of checkpoints is primarily DoS protection. As Greg Maxwell explained on [https://bitcointalk.org/index.php?topic=194078.0 bitcointalk in 2013]: &lt;br /&gt;
&lt;br /&gt;
: User: They [checkpoints] are there so some quantum computing farm (doesn&#039;t exist, but...) can&#039;t come out of nowhere and roll back blocks by mining a long chain from far in the past.&lt;br /&gt;
&lt;br /&gt;
: gmaxwell: That&#039;s not really what they&#039;re for— though they have that effect too. Most of their usefulness is that they prevent a dos attacker from filling up bitcoin node&#039;s disk space with long runs of low difficulty blocks forked off low in the chain.  e.g. you start off with difficulty 1 blocks at block 0, now mine-able by the millions by a single asic— _MAYBE_ a chain that starts off that way could eventually turn out to be the longest so absent the checkpoints a node would happily follow an endlessly long chain of them.  They also make is so that an attacker who has complete control of your network (and thus can prevent you from hearing the longest chain from the honest bitcoin network) from putting you on a fake (low difficulty) isolated chain unless they can also trick you into running replaced software. With the checkpoints such an attacker hast to have a ton of mining power in order to continue the chain.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Origin of Checkpoints&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
According to Gavin Andresen, checkpoints were originally introduced in response to the &amp;quot;overflow&amp;quot; bug which would permit anyone to spend anyone&#039;s bitcoins. [https://bitcointalk.org/index.php?topic=1647.40 see here, page 3]&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;More info on Checkpoints:&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
: First checkpoint introduced by Satoshi in July 2010 (v0.3.2): [https://bitcointalk.org/index.php?topic=437 here]&lt;br /&gt;
: Bitcoin talk thread on checkpoints (Nov 2010):  [https://bitcointalk.org/index.php?topic=1647 here] &lt;br /&gt;
: Bitcoin talk thread (2013): [https://bitcointalk.org/index.php?topic=194078.0 here]&lt;br /&gt;
&lt;br /&gt;
==Bitcoin Core code implementing IBD==&lt;br /&gt;
&lt;br /&gt;
Most of the code is in &amp;lt;u&amp;gt;main.h/cpp&amp;lt;/u&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Block Status&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The concept of block status is important (see chapter 2 and/or &amp;lt;u&amp;gt;chain.cpp&amp;lt;/u&amp;gt;).  Your node assigns a newly received block a status and updates that status as it learns more about the block.  (The block status could also change in the future, for example if there is a re-organization and the block is no longer on the longest blockchain.)  &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Downloading Block Headers&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The code starts by downloading headers from a single peer.  &lt;br /&gt;
&lt;br /&gt;
The download begins in SendMessages (&amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt;), which is called periodically by the message-handling thread.  &lt;br /&gt;
&lt;br /&gt;
If the code sees that we  are not caught up and we haven&#039;t started syncing from anyone:&lt;br /&gt;
&lt;br /&gt;
* We send: &amp;quot;getheaders&amp;quot;&lt;br /&gt;
* Peer replies: &amp;quot;headers&amp;quot; (a chunk of 2000 headers)&lt;br /&gt;
* We send: &amp;quot;getheaders&amp;quot;&lt;br /&gt;
* Peer replies: &amp;quot;headers&amp;quot; (a chunk of 2000 headers)&lt;br /&gt;
* &amp;lt;continue...&amp;gt;&lt;br /&gt;
* Peer replies: &amp;quot;headers&amp;quot; (a chunk of LESS THAN 2000 headers)&lt;br /&gt;
&lt;br /&gt;
When the peer sends less than 2000 headers, we conclude that we reached the tip of the peer&#039;s blockchain.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Block Locators&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
A Block Locator is used to find a fork point between two nodes, which is where the nodes should start exchanging block headers. &lt;br /&gt;
&lt;br /&gt;
Here is the definition (in &amp;lt;u&amp;gt;primitives/block.h&amp;lt;/u&amp;gt;): &lt;br /&gt;
&lt;br /&gt;
  /* Describes a place in the block chain to another node such that if the&lt;br /&gt;
  * other node doesn&#039;t have the same branch, it can find a recent common trunk.&lt;br /&gt;
  * The further back it is, the further before the fork it may be.&lt;br /&gt;
  */&lt;br /&gt;
  struct CBlockLocator&lt;br /&gt;
  {&lt;br /&gt;
  std::vector&amp;lt;uint256&amp;gt; vHave;&lt;br /&gt;
   ...&lt;br /&gt;
  (a few basic constructor &amp;amp; serialization methods)&lt;br /&gt;
  ...&lt;br /&gt;
  };&lt;br /&gt;
&lt;br /&gt;
So, a Locator is basically a vector of block hashes.  The vector is populated with 32 hashes which are chosen to maximize the likelihood of quickly finding a common block with a peer.  &lt;br /&gt;
&lt;br /&gt;
In normal operation, we would generally expect to be within a few blocks of our peers.  Thus, the vector starts with the 10 last block hashes before &amp;quot;jumping back&amp;quot; exponentially.  Thus the comment &amp;quot;the futher back it is, the futher before the fork it might be:&amp;quot;  what is meant is that firstly, if you and your peer are within 10 blocks of one another, the fork point will be included in the list of hashes.  If you and your peer are 15 blocks away from one another, you&#039;ll surely find a common block that&#039;s within a few blocks of the fork point and only one further iteration of Locator will be reuqired to find the fork point.  However, if you and your peer diverge by 10,000 blocks, the Locator may only find a common trunk that&#039;s a few hundred (or more) blocks before the fork point, so another two or three Locator objects will need to be exchanged to zero in on the fork point.  &lt;br /&gt;
&lt;br /&gt;
See CChain::GetLocator and CBlockIndex::GetAncestor [both in &amp;lt;u&amp;gt;chain.cpp&amp;lt;/u&amp;gt;].&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Block Skiplist Pointer&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Every block index contains the following attribute: &lt;br /&gt;
&lt;br /&gt;
  // pointer to the index of some further predecessor of this block&lt;br /&gt;
  CBlockIndex* pskip;&lt;br /&gt;
&lt;br /&gt;
The algorithm for choosing a given block&#039;s &amp;quot;skip pointer&amp;quot; is in &amp;lt;u&amp;gt;chain.cpp&amp;lt;/u&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
  // Determine which height to jump back to. Any number strictly lower than height is acceptable,&lt;br /&gt;
  // but the following expression seems to perform well in simulations (max 110 steps to go back&lt;br /&gt;
  // up to 2**18 blocks).&lt;br /&gt;
  return (height &amp;amp; 1) ? InvertLowestOne(InvertLowestOne(height - 1)) + 1 : InvertLowestOne(height)&lt;br /&gt;
  InvertLowestOne(int n) { return n &amp;amp; (n - 1); }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The skip pointer is used to move through the blockchain in O(log n) rather than walking the chain in O(n).&lt;br /&gt;
&lt;br /&gt;
The idea behind a &amp;quot;skip list&amp;quot; is described here: [https://en.wikipedia.org/wiki/Skip_list Wikipedia page for skiplist]&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Processing the Block Headers&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Code path: &lt;br /&gt;
ProcessMessage (entry point) &lt;br /&gt;
AcceptBlockHeader&lt;br /&gt;
CheckBlockHeader (non-contextual validation checks)&lt;br /&gt;
ContextualCheckBlockHeader  (blockchain-aware validation checks) &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;u&amp;gt;Non-Contextual Checks&amp;lt;/u&amp;gt;&lt;br /&gt;
&lt;br /&gt;
These checks are &amp;quot;non-contextual&amp;quot; because they do not require any knowledge of the state of our blockchain. &lt;br /&gt;
&lt;br /&gt;
1) Proof-of-Work Meets Claimed Requirement:  Here, the code checks that the block has the POW that the miner claims was necessary when constructing the block.  Later, we&#039;ll re-check it against our blockchain.  An honest miner should always pass both checks.  Only a miner who lies about the required POW (block.nBits) would pass this check but fail the contextual check. &lt;br /&gt;
&lt;br /&gt;
2) Timestamp not-too-late:  The code checks that the timestamp is less than 2 days in the future.  This is context-independent because the code just compares the block&#039;s timestamp against the system time. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;u&amp;gt; Contextual Checks &amp;lt;/u&amp;gt;&lt;br /&gt;
&lt;br /&gt;
These checks require some knowledge of our node&#039;s blockchain. &lt;br /&gt;
&lt;br /&gt;
1) Re-check Proof of Work:  Here, we re-check the POW based on our own knowledge of the difficulty target (rather than trusting the difficulty the miner placed in the block&#039;s nBits). &lt;br /&gt;
&lt;br /&gt;
2) Checkpoints (if enabled):  If this block&#039;s height is a checkpoint, the block hash matches the hash stored in the checkpoint map.  (see checkpoint.cpp).&lt;br /&gt;
&lt;br /&gt;
3) Timestamp not-too-early:  Here, we check that the block&#039;s timestamp is not prior to the previous block&#039;s median time (of the previous 11 blocks).  This guarantees that the median time continues to advance from block to block.  Obviously, this check is context-dependent because it requires knowledge of prior blocks in the active chain, which is obtained by retrieving the block from mapBlockIndex.  For more info, see [BIP 113].&lt;br /&gt;
&lt;br /&gt;
4) Version number&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;u&amp;gt;Add the Block&amp;lt;/u&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Finally, add the block to mapBlockIndex and update pIndexBestHeader (see AddToBlockIndex()).  &lt;br /&gt;
&lt;br /&gt;
At this point, the block indexes are VALID_TREE, since we know they are on the main chain, but we haven&#039;t yet received the transactions.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Downloading Blocks&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Your node will start downloading blocks from the peer that it is downloading headers from right away.  &lt;br /&gt;
&lt;br /&gt;
This is so because: &lt;br /&gt;
* The headers-peer is surely a preferred-download peer, set when you received its &amp;quot;version&amp;quot; message (&amp;lt;u&amp;gt;main.cpp:4056&amp;lt;/u&amp;gt;).&lt;br /&gt;
* Thus, your node will call FindNextBlocksToDownload for your headers-peer (&amp;lt;u&amp;gt;main.cpp:5143&amp;lt;/u&amp;gt;). &lt;br /&gt;
* Your headers-peer will have a valid pIndexBestKnownBlock (&amp;lt;u&amp;gt;main.cpp:421&amp;lt;/u&amp;gt;), since that was set in UpdateBlockAvailability() when you received the peer&#039;s headers (&amp;lt;u&amp;gt;main.cpp:4532&amp;lt;/u&amp;gt;).&lt;br /&gt;
* FindNextBlocksToDownload will return a vector of block hashes, which you&#039;ll then request (see &amp;lt;u&amp;gt;main.cpp:5145&amp;lt;/u&amp;gt; [add block to the request vector] and &amp;lt;u&amp;gt;main.cpp:5178&amp;lt;/u&amp;gt; [send getdata msg to your headers-peer]).&lt;br /&gt;
&lt;br /&gt;
However, you will not start downloading blocks from the other peers until IBD is complete.  &lt;br /&gt;
&lt;br /&gt;
This is so because: &lt;br /&gt;
* Your other peers are probably also preferred-download peers, so you&#039;ll call FindNextBlockToDownload just like with your headers-peer. &lt;br /&gt;
* However, that function call will return immediately because it won&#039;t be able to find any available blocks. &lt;br /&gt;
* When IBD concludes (see discussion below), you&#039;ll start exchanging headers with the other peers. &lt;br /&gt;
* Once you&#039;ve exchanged headers with your other peers, you&#039;ll start requesting blocks. &lt;br /&gt;
&lt;br /&gt;
Blocks are downloaded in chunks of 16 blocks at a time from each peer.  With a block size of 1MB, if blocks are full we are talking about 16MB chunks.  (See main.h - &amp;quot;MAX_BLOCKS_IN_TRANSIT_PER_PEER&amp;quot;.)  &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Moving Window&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The download code uses a &amp;quot;moving window&amp;quot; of 1024 blocks.  The idea is that although you are downloading different chunks from multiple peers, at any given time the blocks you are downloading are fairly close together.  The main purpose of this is so that blocks that are near one another on the blockchain are most likely contained in the same .dat file (where the raw block data is stored on disk).  One advantage of having a correlation between blockchain location and block file location is that if the node chooses to &amp;quot;prune&amp;quot; block data at a later date, it&#039;s easier to delete older block files.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Disconnecting a peer&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The code disconnects slow peers in order to keep the download moving.  The peer can be disconnect under two scenarios.  &lt;br /&gt;
&lt;br /&gt;
First, any block requested from the peer must be delivered within a certain timeframe. &lt;br /&gt;
&lt;br /&gt;
Usually, this timeframe is 20 minutes.&lt;br /&gt;
&lt;br /&gt;
The following code is in &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt;: &lt;br /&gt;
     GetBlockTimeout(...) { return nTime + 500000 * consensusParams.nPowTargetSpacing * (4 + nValidatedQueuedBefore);}&lt;br /&gt;
&lt;br /&gt;
nValidatedQueuedBefore are the number of blocks that are in flight to us and which we have validated.  Let&#039;s call that N. &lt;br /&gt;
&lt;br /&gt;
If N = 0, this code evaluates as: &lt;br /&gt;
: = 500,000 microseconds (1/2 second) * 600 seconds (the target block interval) * 4 &lt;br /&gt;
: = 0.5 seconds * 600 seconds * 4 &lt;br /&gt;
: = 1,200 seconds&lt;br /&gt;
: = 20 minutes&lt;br /&gt;
&lt;br /&gt;
The formula can be simplified as: &lt;br /&gt;
: = 0.5 * (4 + N) * block_interval&lt;br /&gt;
: = (2 + 0.5 * N) * block_interval&lt;br /&gt;
&lt;br /&gt;
Thus: &lt;br /&gt;
: N=0, timeout = 2 * block_interval = 20 minutes.&lt;br /&gt;
: N=10, timeout = 7 * block_interval = 70 minutes. &lt;br /&gt;
: N=30, timeout = 17 * block_interval = 170 minutes.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The second circumstance where we will disconnect a peer is where the peer manages to stall your entire download by preventing the moving window from progressing.  Imagine your moving window is blocks 1000 to 2024 and you&#039;ve downloaded everything from 1016 to 2024, but are waiting for Alice to serve up 1000 to 1016, which you may have requsted a few minutes earlier.  In this siutation, if Alice continues to stall the moving window for 2 seconds, you will drop Alice and replace her with a more reliable peer. In the mantime, your node will request blocks 1000 to 1016 from one of your other peers so your moving window can start moving again.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Requesting Blocks&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Requesting blocks is handled by sending out a &amp;quot;getdata&amp;quot; message (see main.cpp:5137 in v0.11).  A &amp;quot;getdata&amp;quot; message is used to pack a vector of &amp;quot;inv&amp;quot; messages and send as a group.  Thus, we can request 16 blocks from the peer with one network message, as opposed to sending 16 separate &amp;quot;inv&amp;quot; messages.&lt;br /&gt;
&lt;br /&gt;
What blocks do we request?  The code to figure that out is in FindNextBlocksToDownload; it uses a &#039;&#039;&#039;block locator&#039;&#039;&#039; to figure out the last block we have in common with this peer, and starts from there.  A block locator is a homemade algorithm that efficiently finds the fork point between our node and a given peer.  The locator will pack a list of 32 blocks, starting with the last 10 (since in steady-state we are usually within 10 blocks of our peers), and then jumping back exponentially.  (&amp;lt;u&amp;gt;chain.cpp:25&amp;lt;/u&amp;gt;). &lt;br /&gt;
&lt;br /&gt;
This algorithm has proven to be effective at locating the fork point. &lt;br /&gt;
 &lt;br /&gt;
Once we&#039;ve prepared the &amp;quot;getdata&amp;quot; message, we mark the blocks that we&#039;ve requested as being &amp;quot;in flight&amp;quot; - with MarkBlocksAsInFlight (main.cpp).&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Receiving Blocks&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The entry point for receiving blocks is in ProcessMessage, when our node receives a &amp;quot;block&amp;quot; message from a peer.  &lt;br /&gt;
&lt;br /&gt;
The block is processed with ProcessNewBlock (main.cpp):&lt;br /&gt;
&lt;br /&gt;
: 1) Checks on the block&lt;br /&gt;
:: a)  Basic, context-independent checks on the block (merkle root, block size, etc)&lt;br /&gt;
:: b)  Basic, context-independent on transactions within the block  (transaction size, etc.)&lt;br /&gt;
:: c)  Check that we requested this block (if unrequested, this may be a DOS attack - though not necessarily) &lt;br /&gt;
:: d)  Context-dependent checks on the block&lt;br /&gt;
&lt;br /&gt;
: 2)  Store the block to disk &lt;br /&gt;
&lt;br /&gt;
: 3)  General check on the integrity of our blockchain (this may sound expensive, but is very fast)&lt;br /&gt;
&lt;br /&gt;
: 4)  Connect the block to the blockchain - if appropriate (see ActivateBestChain)&lt;br /&gt;
&lt;br /&gt;
Note that the block&#039;s transactions are not validated (checked for a double-spend, etc.) until the last step, when the block is connected as the new tip of the blockchain.  For more info, see below &amp;quot;Connecting a Block&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
==Monitoring the Download==&lt;br /&gt;
&lt;br /&gt;
You can monitor the download with the RPC call getpeerinfo, which shows (for each peer that you&#039;re connected to):&lt;br /&gt;
&lt;br /&gt;
* &amp;quot;synced_headers&amp;quot;: The last header we have in common with this peer&lt;br /&gt;
* &amp;quot;synced blocks&amp;quot;: The last block in commen with this peer&lt;br /&gt;
* &amp;quot;inflight&amp;quot;: The heights of blocks we&#039;re currently requesting from this peer&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==See also==&lt;br /&gt;
[https://en.bitcoin.it/wiki/Bitcoin_Core_0.11_(ch_1):_Overview Bitcoin Core 0.11 (Ch 1): Overview]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[https://en.bitcoin.it/wiki/Bitcoin_Core_0.11_(ch_2):_Data_Storage Bitcoin Core 0.11 (Ch 2): Data Storage]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[https://en.bitcoin.it/wiki/Bitcoin_Core_0.11_(ch_3):_Initialization_and_Startup Bitcoin Core 0.11 (Ch 3): Initialization and Startup]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[https://en.bitcoin.it/wiki/Bitcoin_Core_0.11_(ch_4):_P2P_Network Bitcoin Core 0.11 (Ch 4): P2P Network]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Technical]]&lt;br /&gt;
[[Category:Developer]]&lt;/div&gt;</summary>
		<author><name>Mrbandrews</name></author>
	</entry>
	<entry>
		<id>https://en.bitcoin.it/w/index.php?title=Bitcoin_Core_0.11_(ch_4):_P2P_Network&amp;diff=60020</id>
		<title>Bitcoin Core 0.11 (ch 4): P2P Network</title>
		<link rel="alternate" type="text/html" href="https://en.bitcoin.it/w/index.php?title=Bitcoin_Core_0.11_(ch_4):_P2P_Network&amp;diff=60020"/>
		<updated>2016-01-21T19:59:10Z</updated>

		<summary type="html">&lt;p&gt;Mrbandrews: Created page with &amp;quot; Bitcoin is a peer-to-peer network, so Bitcoin Core has code to discover peers and manage those connections.   Most of the network-handling code is in &amp;lt;u&amp;gt;net.h/cpp&amp;lt;/u&amp;gt;.      =...&amp;quot;&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
Bitcoin is a peer-to-peer network, so Bitcoin Core has code to discover peers and manage those connections. &lt;br /&gt;
&lt;br /&gt;
Most of the network-handling code is in &amp;lt;u&amp;gt;net.h/cpp&amp;lt;/u&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
==Data structures to manage peers==&lt;br /&gt;
&lt;br /&gt;
At any given time, the node is connected with a set of other nodes, i.e. peers.  By default the code connects to 8 outbound peers (nodes that our node goes out and finds) and allows up to 125 inbound peers (nodes that find us through the network). &lt;br /&gt;
&lt;br /&gt;
The global variable vNodes (&amp;lt;u&amp;gt;net.h&amp;lt;/u&amp;gt;) holds the set of peers.  The variable is protected by cs_vNodes. &lt;br /&gt;
&lt;br /&gt;
Each peer is represented by a CNode.&lt;br /&gt;
&lt;br /&gt;
The CNode contains dozens of attributes, most of which have to do with low-level plumbing (sockets, byte streams, etc.) &lt;br /&gt;
&lt;br /&gt;
Some of the key attributes of a CNode include: &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;CNode&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! Attribute !! Description&lt;br /&gt;
|-&lt;br /&gt;
| nServices || Commonly referred to as &amp;quot;the service bits.&amp;quot;&amp;lt;br&amp;gt;This is a bitmap of what services the peer provides.&amp;lt;br&amp;gt;As of 0.11 this is still just binary:  either the node is NODE_NETWORK (it is a full node and does everything) or not (it is SPV).&amp;lt;br&amp;gt;In future versions, these bits will convey more precise information about what the node can and can&#039;t do. For example, with Block Pruning a node may be able to serve recent blocks (say, the last week or two worth of blocks), but not the entire blockchain. &lt;br /&gt;
|-&lt;br /&gt;
| fClient || Whether this peer is a SPV node.  (Here, the term &amp;quot;client&amp;quot; means &amp;quot;merely SPV, not a full node.&amp;quot;)&lt;br /&gt;
|-&lt;br /&gt;
| fOneShot || &lt;br /&gt;
|-&lt;br /&gt;
| fInbound ||  Whether this node is &amp;quot;inbound&amp;quot; or &amp;quot;outbound.&amp;quot; Common sense suggests that a node that we discovered through the network (an outbound node) is less likely to attack us than a node that found us.&amp;lt;br&amp;gt;So, for example, when the code looks for a peer to request historical blocks from, it prefers an outbound node, if possible. &lt;br /&gt;
|-&lt;br /&gt;
| fWhiteListed || A whitelisted node is not subject to being banned for bad behaviour. &lt;br /&gt;
|-&lt;br /&gt;
| setInventoryKnown || &lt;br /&gt;
|-&lt;br /&gt;
| vSendMsg || Messages that we&#039;ve queued up to send to the peer.&amp;lt;br&amp;gt;This is type &amp;lt;CSerializeData&amp;gt; since we are going to send it over the network. &lt;br /&gt;
|-&lt;br /&gt;
| vRecvMsg || Messages that we&#039;ve received from the peer.&amp;lt;br&amp;gt;This is type &amp;lt;CNetMessage&amp;gt; because as soon as the data is received, it is deserialized and packed into a more useful format (an object).&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
==Peer discovery &amp;amp; connectivity==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Address manager===&lt;br /&gt;
&lt;br /&gt;
IP addresses of the node&#039;s peers are managed by the address manager (see &amp;lt;u&amp;gt;addrman.h&amp;lt;/u&amp;gt;). &lt;br /&gt;
&lt;br /&gt;
The code comment explains the address manager (edited here for conciseness):&lt;br /&gt;
&lt;br /&gt;
 Design goals:&lt;br /&gt;
   * Keep the address tables in-memory, and asynchronously dump the entire table to peers.dat.&lt;br /&gt;
   * Make sure no (localized) attacker can fill the entire table with his nodes/addresses.&amp;lt;br&amp;gt;&amp;lt;br&amp;gt;To that end: &lt;br /&gt;
   * Addresses are organized into buckets.&lt;br /&gt;
     * Addresses that have not yet been tried go into 1024 &amp;quot;new&amp;quot; buckets.&lt;br /&gt;
     * Addresses of nodes that are known to be accessible go into 256 &amp;quot;tried&amp;quot; buckets.&lt;br /&gt;
     * Bucket selection is based on cryptographic hashing, using a randomly-generated 256-bit key, which should not be observable by adversaries.&lt;br /&gt;
     * Several indexes are kept for high performance. Defining DEBUG_ADDRMAN will introduce frequent (and expensive) consistency checks for the entire data structure.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Timestamps&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The address manager also keeps track of when each peer was last heard from.  Timestamps are only updated on an address and saved to the database when the timestamp is over 20 minutes old.  By understanding the role of timestamps, it will become more clear why timestamps are kept the way they are for each of the different ways an address is discovered.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Peer discovery===&lt;br /&gt;
&lt;br /&gt;
The program discovers the IP address and port of nodes in several different ways: &lt;br /&gt;
* Address database (peers.dat)&lt;br /&gt;
* User-specified (-addnode and -connect)&lt;br /&gt;
* DNS seeding&lt;br /&gt;
* Hard-coded seeds&lt;br /&gt;
* From other peers (&amp;quot;getaddr&amp;quot; and &amp;quot;addr&amp;quot; messages)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;1) Address database (peers.dat)&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Nodes store addresses in a database (peers.dat) which is read on startup, and loaded into the address manager.  &lt;br /&gt;
&lt;br /&gt;
This method does not work the first time the program is run, since it does not already know about any other nodes on the bitcoin network.&lt;br /&gt;
&lt;br /&gt;
For details on when/how the code stores to the database, see the section above on the address manager. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;2) User-specified on the command line&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The user can specify nodes to connect to on the command line with -addnode &amp;lt;ip&amp;gt; or -connect &amp;lt;ip&amp;gt;. &lt;br /&gt;
&lt;br /&gt;
Notes on user-specified IP addresses: &lt;br /&gt;
* Multiple nodes may be specified.&lt;br /&gt;
* Addresses are initially given a zero timestamp, therefore they are not advertised in response to a &amp;quot;getaddr&amp;quot; request.&lt;br /&gt;
* With -connect, the IP addresses will not be added to peers.dat and only the provided addresses will be used. &lt;br /&gt;
* With -addnode, the provided addresses will be used as a starting point, but the node will soon learn other peers.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;3) DNS seeding&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
DNS seeding is only used if the peers.dat database is empty (as it would be when initiallly running the program) and the user has not specified any nodes with -addnode or -connect. &lt;br /&gt;
&lt;br /&gt;
In this case, the node can issue DNS requests to discover IP addresses of other peers.&lt;br /&gt;
&lt;br /&gt;
As of 0.11, there are six DNS servers hard-coded into the program -  see chainparams.cpp. &lt;br /&gt;
&lt;br /&gt;
A DNS reply can contain multiple IP addresses for a requested name.&lt;br /&gt;
&lt;br /&gt;
Addresses discovered via DNS are initially given a zero timestamp, to avoid being advertised in response to a &amp;quot;getaddr&amp;quot; request.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;4) Hard-coded nodes (last resort)&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
If DNS seeding fails, the client contains hard coded IP addresses that represent bitcoin nodes.  See:  &amp;lt;u&amp;gt;chainparamsseeds.h&amp;lt;/u&amp;gt;&lt;br /&gt;
&lt;br /&gt;
These addresses are only used as a last resort, and a log message will be printed:  &amp;quot;Adding fixed seed nodes as DNS doesn&#039;t seem to be available.&amp;quot;   (&amp;lt;u&amp;gt;net.cpp&amp;lt;/u&amp;gt;)&lt;br /&gt;
&lt;br /&gt;
The idea is to move away from seed nodes as soon as possible, to avoid overloading those nodes. &lt;br /&gt;
&lt;br /&gt;
Once the local node has enough addresses (presumably learned from the seed nodes), the connection thread will close any seed node connections.&lt;br /&gt;
&lt;br /&gt;
Like the DNS seed addresses, the hard-coded seed addresses are also given a zero timestamp to avoid being advertised in response to a &amp;quot;getaddr&amp;quot; request.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;5) From other nodes (&amp;quot;getaddr&amp;quot; and &amp;quot;addr&amp;quot; messages)&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Nodes exchange IP addresses with other nodes via the &amp;quot;getaddr&amp;quot; and &amp;quot;addr&amp;quot; messages.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Usually, an addr&amp;quot; message is sent in response to a &amp;quot;getaddr&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
However, the &amp;quot;addr&amp;quot; message may also arrive unsolicited, because nodes advertise addresses gratuitously when they: &lt;br /&gt;
* Relay addresses (see below)&lt;br /&gt;
* Advertise their own address periodically.  (Every 24 hours, the node advertises its own address to all connected nodes.)&lt;br /&gt;
* When a connection is made (in response to an initial &amp;quot;version&amp;quot; message) &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
When does a node send a &amp;quot;getaddr&amp;quot; message? &lt;br /&gt;
* In response to a &amp;quot;version&amp;quot; message from an outbound node, if we don&#039;t yet have 1000 addresses. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Receiving an &amp;quot;addr&amp;quot; message: &lt;br /&gt;
* If the sending node is an old version and we have 1000 addresses already, it is ignored. &lt;br /&gt;
* If the sending node is a current version and is attempting to send us more than 1000 addresses, the peer is punished for misbehaving. &lt;br /&gt;
* If the address has been seen in the last 24 hours and the timestamp is currently over 60 minutes old, then it is updated to 60 minutes ago.&lt;br /&gt;
* If the address has NOT been seen in the last 24 hours, and the timestamp is currently over 24 hours old, then it is updated to 24 hours ago.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Responding to a &amp;quot;getaddr&amp;quot; message:&lt;br /&gt;
* The node figures out how many addresses it has that have a timestamp in the last 3 hours. &lt;br /&gt;
* It sends those addresses, but if there are more than 2500 addresses, it randomly selects 2500.&lt;br /&gt;
* It clears the list of the addresses we think the remote node has, which will trigger a refresh of sends to nodes. See SendMessages. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Address Relay&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Once added, the newly received IP addresses may be relayed to other nodes if the following conditions are met:&lt;br /&gt;
* The address timestamp is recent (within 10 minutes of the current time)&lt;br /&gt;
* The &amp;quot;addr&amp;quot; message contained 10 addresses or less&lt;br /&gt;
* fGetAddr=false for the sending peer. (See the code for details.)&lt;br /&gt;
* The address must be routable.&lt;br /&gt;
* Code: &lt;br /&gt;
 if (addr.nTime &amp;gt; nSince &amp;amp;&amp;amp; !pfrom-&amp;gt;fGetAddr &amp;amp;&amp;amp; vAddr.size() &amp;lt;= 10 &amp;amp;&amp;amp; addr.IsRoutable())&lt;br /&gt;
* If this test is passed, then the code&#039;s next step is (see main.cpp for details): &lt;br /&gt;
 // Use deterministic randomness to send to the same nodes for 24 hours at a time so the addrKnowns of the chosen nodes prevent repeats.&lt;br /&gt;
&lt;br /&gt;
===Peer connectivity===&lt;br /&gt;
&lt;br /&gt;
The connection thread (ThreadOpenConnections) chooses among the available addresses and makes connections, and disconnects nodes when appropriate. &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Use of CSemaphore for outbound connections&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The code uses a semaphore to manage the number of outbound connections (usually 8). &lt;br /&gt;
&lt;br /&gt;
Most of the code dealing with the semaphore is in &amp;lt;u&amp;gt;net.cpp&amp;lt;/u&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
When a connection is opened, the semaphore grant is passed to the CNode data structure.  This allows the socket thread to release the semaphore when the time comes, with: &lt;br /&gt;
 pnode-&amp;gt;grantOutbound.Release()  // see net.cpp&lt;br /&gt;
&lt;br /&gt;
The code CSemaphore grant(*semOutbound) will wait until there is a connection available. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Inbound connections: accepting and disconnecting&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Inbound connections can be up to 125 total.  &lt;br /&gt;
&lt;br /&gt;
ThreadSocketHandler has the code that accepts inbound connections. &lt;br /&gt;
&lt;br /&gt;
The socket thread loop: &lt;br /&gt;
* 1) Disconnects sockets that have the fDisconnect flag set on them (and have empty buffers)&lt;br /&gt;
* 2) Prepares all sockets for &amp;quot;select&amp;quot;&lt;br /&gt;
* 3) Calls &amp;quot;select&amp;quot;, which is a system call which waits for activity on a set of sockets. &lt;br /&gt;
&lt;br /&gt;
When the select() call returns, the node accepts any new connections, receives and sends on any ready sockets, and marks any inactive sockets to be disconnected (whether inbound or outbound).&lt;br /&gt;
&lt;br /&gt;
Sockets are disconnected if: &lt;br /&gt;
 * they are 60 seconds old and have not sent or received data.&lt;br /&gt;
 * they have not sent or received data in the last 20 minutes (TIMEOUT_INTERVAL = 20*60) (or 90 minutes if peer is an old version)&lt;br /&gt;
 * the socket overfills the buffer (see CNode::ReceiveMsgBytes- &amp;quot;Oversized message from peer=%i, disconnecting\n&amp;quot; in &amp;lt;u&amp;gt;net.cpp&amp;lt;/u&amp;gt;)&lt;br /&gt;
&lt;br /&gt;
==Sockets &amp;amp; Messages==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Socket Thread&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The socket thread operates at the TCP layer.  &lt;br /&gt;
&lt;br /&gt;
It goes through an endless loop, reading and writing the sockets. (see &amp;lt;u&amp;gt;net.cpp&amp;lt;/u&amp;gt;).&lt;br /&gt;
&lt;br /&gt;
Its loop involves three basic activities: &lt;br /&gt;
&lt;br /&gt;
1) Administrative work:  disconnecting unused sockets, checking which sockets have data, adding sockets for new connections.&lt;br /&gt;
&lt;br /&gt;
2) Receiving data:  It reads the sockets that have data using the recv() system call and places that data into the peer&#039;s queue of CNetMessages.  A CNetMessage organizes the data into two data streams - the message header and the message data (vRecv).  The socket thread reads the buffer until it has processed all the messages from this particular peer. &lt;br /&gt;
&lt;br /&gt;
3) Sending data:  The message thread queued up messages-to-be-sent as vSendMsg objects, so the socket thread deserializes these objects and sends them using send(). (send() is a syscall and any incompatibilities across different operating systems are handled in the &amp;lt;u&amp;gt;compat.h&amp;lt;/u&amp;gt; file.)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Message Thread&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
This is the program&#039;s main thread. &lt;br /&gt;
&lt;br /&gt;
It operates primarily at the &amp;quot;business logic&amp;quot; level - validating transactions, managing the blockchain, etc. &lt;br /&gt;
&lt;br /&gt;
In a sense, all of the node&#039;s activities take the form of processing an inbound message or preparing an outbound message.  &lt;br /&gt;
&lt;br /&gt;
Like the socket thread, this thread consists of a while(true) loop, processing inbound messages and queuing up outbound messages.  Once the program&#039;s initialization is complete, this loop (see &amp;lt;u&amp;gt;net.cpp&amp;lt;/u&amp;gt;:ThreadMessageHandler) is the program&#039;s high-level point of control. &lt;br /&gt;
&lt;br /&gt;
The loop uses signals to notify &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt; that there are messages waiting to be processed.  The signal is picked up by ProcessMessages().&lt;br /&gt;
&lt;br /&gt;
The use of signals has nothing to do with multi-threading;  the signal is sent and picked up in the same thread.  The use of signals was introduced in version 0.9 for the purpose of decoupling &amp;lt;u&amp;gt;net.cpp&amp;lt;/u&amp;gt; from &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt;.   In version 0.8, the loop simply called the ProcessMessages() function.  By changing to signals, the &amp;lt;u&amp;gt;net.cpp&amp;lt;/u&amp;gt; code no longer needs to be aware of the processing code.  Removing that dependency allows the code to avoid circular includes (since &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt; requires knowledge of &amp;lt;u&amp;gt;net.h&amp;lt;/u&amp;gt;. &lt;br /&gt;
&lt;br /&gt;
The pull request introducing signals is [https://github.com/bitcoin/bitcoin/pull/2154 PR 2154.]&lt;br /&gt;
&lt;br /&gt;
The commit removing the &amp;quot;main.h&amp;quot; dependency is [https://github.com/CodeShark/bitcoin/commit/6e68524e95da2bedc21b1d95c4a206b902ab7c22 here].&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;ProcessMessages (&amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt;)&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
ProcessMessages() is the entry point in &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt; for almost all of the code that processes and validates transactions and blocks, etc. &lt;br /&gt;
&lt;br /&gt;
It attempts to find a message start signature in the vRecv stream. If it finds a message start, it deletes everything prior to the start. Then it reads the header, extracts the message type, and calls ProcessMessage on the message.&lt;br /&gt;
&lt;br /&gt;
ProcessMessage() is basically a large &amp;quot;switch&amp;quot; which takes action based on what type of message it is dealing with.  &lt;br /&gt;
&lt;br /&gt;
Often, in the course of processing a message, the code will push messages to the outbound queue.  For example, when processing an incoming &amp;quot;getdata&amp;quot; message, the node pushes the outbound data into the queue.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;SendMessages (&amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt;)&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
SendMessages() creates messages and queues them up in the peer&#039;s vSendMsg queue (a double-ended queue, or &amp;quot;deque&amp;quot; in C++).  The vSendMsg objects are basically just serialized data. &lt;br /&gt;
&lt;br /&gt;
SendMessages goes through various data structures looking for work to do.  When it produces a message it calls the CNode-&amp;gt;PushMessage, which queues the outbound data.  (Note that there are many other places in the code that produce messages and call CNode-&amp;gt;PushMessage;  SendMessages() doesn&#039;t have any kind of exclusive license on placing messages in the outbound queue.)&lt;br /&gt;
&lt;br /&gt;
Once the data is queued up by PushMessage, it sits and waits for the socket thread to come along. &lt;br /&gt;
&lt;br /&gt;
The socket thread and the message thread use a peer-specific lock (node-&amp;gt;cs_vSend) to coordinate access to the socket.&lt;br /&gt;
&lt;br /&gt;
==Locks==&lt;br /&gt;
&lt;br /&gt;
The main locks associated with the P2P aspect of the code are: &lt;br /&gt;
* cs_vNodes controls access to the CNode objects.&lt;br /&gt;
* cs_vSend controls access to the node&#039;s send buffer. &lt;br /&gt;
* cs_vRecvMsg controls access to the node&#039;s receiving buffer. &lt;br /&gt;
* cs_inventory &lt;br /&gt;
&lt;br /&gt;
==Denial-of-Service Prevention==&lt;br /&gt;
&lt;br /&gt;
DoS prevention is implemented by keeping track of misbehaving peers, and if they misbehave, banning them.&lt;br /&gt;
&lt;br /&gt;
The DoS prevention framework was introduced in 2011, in Pull 517.&lt;br /&gt;
&lt;br /&gt;
As summarized there: &lt;br /&gt;
&lt;br /&gt;
&amp;lt;blockquote&amp;gt;&lt;br /&gt;
-----&lt;br /&gt;
The big idea: if a peer is sending you obviously wrong information, punish it by maybe dropping your connection to it, and ban it&#039;s IP address so it cannot immediately re-connect.&lt;br /&gt;
&amp;lt;br&amp;gt;&amp;lt;br&amp;gt;The probability of dropping the connection, and the length of the ban, depend on how wrong, and how potentially wasteful/damaging, the peer is. So sending an extra &#039;version&#039; message is a minor transgression that is usually tolerated, sending an more than MAX_BLOCK_SIZE block is a major transgression.&lt;br /&gt;
&amp;lt;br&amp;gt;&amp;lt;br&amp;gt;Detailed how-it-works, using &amp;quot;I got a version message I wasn&#039;t expecting&amp;quot; as the specific example:&lt;br /&gt;
&amp;lt;br&amp;gt;&amp;lt;br&amp;gt;Getting a version message from a peer increases that peer&#039;s &#039;misbehaving&#039; score by 10, and (assuming that is the peer&#039;s first bad behavior) gives it a 10% of being disconnected. If it is disconnected, then that peer&#039;s IP address is banned from connecting for a couple of hours. If it is not disconnected, then nothing happens unless the peer misbehaves again; if it does, then its chances of being disconnected go up, and the length of time it will be banned increases.&lt;br /&gt;
&amp;lt;br&amp;gt;&amp;lt;br&amp;gt;Misbehavior/ban information is stored only in memory, and information about misbehaving peers is never broadcast. Also, peers that are disconnected/banned are just dropped, there is no warning or reason sent. &lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
     --Gavin Andresen&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
-----&lt;br /&gt;
&amp;lt;/blockquote&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Source:  https://github.com/bitcoin/bitcoin/pull/517&amp;lt;/blockquote&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Banned nodes&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The set of banned nodes is in setBanned in &amp;lt;u&amp;gt;net.cpp&amp;lt;/u&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
By default, a node is banned for 24 hours, though this can be configured with -bantime option.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==See also==&lt;br /&gt;
[https://en.bitcoin.it/wiki/Bitcoin_Core_0.11_(ch_1):_Overview Bitcoin Core 0.11 (Ch 1): Overview]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[https://en.bitcoin.it/wiki/Bitcoin_Core_0.11_(ch_2):_Data_Storage Bitcoin Core 0.11 (Ch 2): Data Storage]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[https://en.bitcoin.it/wiki/Bitcoin_Core_0.11_(ch_3):_Initialization_and_Startup Bitcoin Core 0.11 (Ch 3): Initialization and Startup]&lt;/div&gt;</summary>
		<author><name>Mrbandrews</name></author>
	</entry>
	<entry>
		<id>https://en.bitcoin.it/w/index.php?title=Bitcoin_Core_0.11_(ch_1):_Overview&amp;diff=60015</id>
		<title>Bitcoin Core 0.11 (ch 1): Overview</title>
		<link rel="alternate" type="text/html" href="https://en.bitcoin.it/w/index.php?title=Bitcoin_Core_0.11_(ch_1):_Overview&amp;diff=60015"/>
		<updated>2016-01-21T18:50:44Z</updated>

		<summary type="html">&lt;p&gt;Mrbandrews: /* Design Patterns */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
==Organization &amp;amp; Maintenance of these Pages==&lt;br /&gt;
&lt;br /&gt;
The purpose of this set of Wiki pages is to document the Bitcoin Core C++ source code, in a way that is helpful to the programmer who wants to learn how the program is designed and what the code does. &lt;br /&gt;
&lt;br /&gt;
Ideally, the accuracy of the information on these pages would be checked by developers who are getting up to speed on the Bitcoin Core code base.  Additionally, each new release of Bitcoin Core (0.12, 0.13, etc) could have a new set of pages that are modified to match that version.&lt;br /&gt;
&lt;br /&gt;
These pages are loosely based on the set of pages called &amp;quot;Satoshi Client: xxx&amp;quot; (on this Wiki) which were written in 2011 and based on version 0.3. &lt;br /&gt;
&lt;br /&gt;
This set of Wiki pages includes: &lt;br /&gt;
&lt;br /&gt;
* Ch 1: Intro &amp;amp; Overview (this page) &lt;br /&gt;
* Ch 2: Data Storage&lt;br /&gt;
* Ch 3: Initialization &amp;amp; Startup&lt;br /&gt;
* Ch 4: P2P Network&lt;br /&gt;
* Ch 5: Initial Block Download (IBD)&lt;br /&gt;
* Ch 6: Blockchain&lt;br /&gt;
* Ch 7: Transactions &amp;amp; the Memory Pool&lt;br /&gt;
* Ch 8: RPC Server&lt;br /&gt;
&lt;br /&gt;
These pages document the &amp;quot;relay node&amp;quot; aspect of Bitcoin Core, meaning a node which validates blocks and transactions and relays them to other nodes. The node has fully validated the blockchain, although it may not necessarily maintain a full copy of it on disk. &lt;br /&gt;
&lt;br /&gt;
These pages do NOT cover: &lt;br /&gt;
* Wallet&lt;br /&gt;
* GUI (Qt)&lt;br /&gt;
* Mining&lt;br /&gt;
&lt;br /&gt;
==Definitions==&lt;br /&gt;
&lt;br /&gt;
A few definitions at the outset:  &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Consensus code&#039;&#039;&#039; &lt;br /&gt;
&lt;br /&gt;
Code that validates blocks and transactions.  &lt;br /&gt;
&lt;br /&gt;
Consensus code must have bug-for-bug compatibility across versions and implementations (meaning, 0.12 must have the same consensus behaviour as 0.11, even if it is buggy;  otherwise, a network fork may result.) &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Policy code&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Code that implements a particular node&#039;s policy (as opposed to consensus).  A node&#039;s algorithm for which transactions to store in its transaction pool is an example of policy.  For example, a node could refuse to relay or store any transaction that is larger than 200KB.  What is important is that if such a transaction is transmitted to the node as part of a newly mined block, the node does not reject the block.   &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;P2P code&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Code relating to communications with other nodes (peers) over the P2P network.  Communication includes discovering and connecting to other nodes; exchanging various P2P messages (e.g., messages containing blocks and transactions); occasionally, banning misbehaving peers. The bitcoin network uses a custom set of P2P messages.  Most of the P2P code can be found in &amp;lt;u&amp;gt;net.h/net.cpp&amp;lt;/u&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Mempool (&amp;quot;memory pool&amp;quot; or &amp;quot;transaction pool&amp;quot;)&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
A set of transactions which the node knows about and chooses to store in memory and relay to other nodes, and which have not yet been included in a block.  In many cases, this may be the full set of transactions that the node has received and validated.  If the node has received transactions that violate its policy, however, the mempool will be a subset.  In any event, when the node receives and validates a block, it deletes any transactions in the block from its mempool.  &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Full Node&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
A full node is one that validates blocks and transactions and relays them to other nodes.  A full node has validated the blockchain from scratch (although with block file pruning, it may have discarded older parts of the chain to clear up disk space.) The key characteristic of a full node is that it has validated the blockchain and continues to fully validate and relay incoming blocks and transactions.  A full node can be differentiated from an SPV node, which trusts another node (or set of nodes) to validate. &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;&amp;quot;Basic Full Node&amp;quot;&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
A &amp;quot;basic full node&amp;quot; is what is documented in these pages.  By &amp;quot;basic full node,&amp;quot; what is meant is a node that validates and relays blocks and transactions, but does not mine new blocks or perform other optional tasks (RPC server, wallet).  Extending these pages to include documentation of these optional aspects of a node is a future project.&lt;br /&gt;
&lt;br /&gt;
==Architecture of a Bitcoin Node==&lt;br /&gt;
&lt;br /&gt;
One developer described the architecture of a basic full node as follows: &lt;br /&gt;
&lt;br /&gt;
: --------------------&lt;br /&gt;
&lt;br /&gt;
: The basic architecture of a bitcoin node is as follows:&lt;br /&gt;
&lt;br /&gt;
: At the core there exist fundamental bitcoin message structures, along with the code necessary for serialization/deserialization. These structures belong in their own source files with minimal dependencies so they can be reused for applications that needn&#039;t perform verification and relay - for instance, filtering and notification agents. Unfortunately, these core structures currently reside for the most part in main.h/main.cpp...&lt;br /&gt;
&lt;br /&gt;
: On top of these core structures sits a network component that manages sockets, does peer discovery, and handles queueing and dispatching of messages. This component is clearly dependent on the core message structures but does not depend on the specific logic used to verify blocks and transactions nor to identify misbehaving peers nor sign transactions nor maintain a block chain database.&lt;br /&gt;
&lt;br /&gt;
: Then we have a scripting engine, signature verification component, and a signing component. Historical database applications do not need signature verification/signing functionality at all. Filtering messages and sending alerts generally does not even require a scripting engine and does fine with basic pattern matching.&lt;br /&gt;
&lt;br /&gt;
: The most critical high-level operations needed by a verification/relay node such as the satoshi client are transaction verification; block chain and memory pool management; and detection/management of misbehaving peers. These things are currently primarily implemented in main.h/main.cpp. These are indeed the main operations of the satoshi client - but the core low-level structures should not depend at all on this logic.&lt;br /&gt;
&lt;br /&gt;
: ---------------------&lt;br /&gt;
&lt;br /&gt;
See here: [https://github.com/bitcoin/bitcoin/pull/2154 PR 2154]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In the form of a (crude) picture: &lt;br /&gt;
 &lt;br /&gt;
   Validating transactions; Managing blockchain, mempool, and peers.&lt;br /&gt;
                    | &lt;br /&gt;
       Scripting engine / Signatures&lt;br /&gt;
                    | &lt;br /&gt;
              Network layer&lt;br /&gt;
                    | &lt;br /&gt;
              P2P Messages&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
And here is the same picture, augmented with the definitions above: &lt;br /&gt;
 &lt;br /&gt;
   Validating transactions; Managing blockchain, mempool, peers  (Consensus and Policy code)&lt;br /&gt;
                    | &lt;br /&gt;
       Scripting engine / Signatures (Consensus code)&lt;br /&gt;
                    | &lt;br /&gt;
              Network layer  (P2P code) &lt;br /&gt;
                    | &lt;br /&gt;
              P2P Messages&lt;br /&gt;
&lt;br /&gt;
==Code Modularization / Organization==&lt;br /&gt;
&lt;br /&gt;
As of 0.11, modularization of the Bitcoin Core code is somewhat limited.   &lt;br /&gt;
&lt;br /&gt;
Ideally, Bitcoin Core would be modularized so that the consensus code would be separated and made into a library which could be distributed to other implementations.  In this way, fears of accidentally forking the network would be mitigated.  As of 2016, this is work in progress (see, e.g., various &amp;quot;libconsensus&amp;quot; pull requests on GitHub.) &lt;br /&gt;
&lt;br /&gt;
In December 2013, a proposal was made for modularizing the code base:  [https://github.com/bitcoin/bitcoin/issues/3440 Post-0.9 modularization of Bitcoin Core]&lt;br /&gt;
&lt;br /&gt;
Examples of optional modules would be: &lt;br /&gt;
* Miner&lt;br /&gt;
* Wallet&lt;br /&gt;
* Notifications&lt;br /&gt;
&lt;br /&gt;
As of 0.11, the steps taken toward modularization were primarily separating certain classes into subdirectories, described below.&lt;br /&gt;
&lt;br /&gt;
==Source Code Files==&lt;br /&gt;
&lt;br /&gt;
The C++ code is in the src/ directory of the repository.  &lt;br /&gt;
&lt;br /&gt;
Most of the code resides in the top-level directory, although there has been some effort to modularize the code base with subdirectories (wallet, consensus, primitives, etc.)  Also, certain components (QT, LevelDB, etc) live in subdirectories.&lt;br /&gt;
&lt;br /&gt;
Key files in the src/ directory include:  (file.* means the header file [file.h] and the source file [file.cpp])&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! File !! Description / Purpose&lt;br /&gt;
|-&lt;br /&gt;
| net.* ||  Manages the network (peer connections, etc.).&amp;lt;br&amp;gt;The while(true) loop in ThreadMessageHandler controls the program&#039;s flow, signalling &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt; when there is work to do. &amp;lt;br&amp;gt;Key dependencies:  None. &lt;br /&gt;
|-&lt;br /&gt;
| init.cpp ||  Initializes the node, calling functions in &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt; as necessary.&amp;lt;br&amp;gt;Key dependencies: main.h&lt;br /&gt;
|-&lt;br /&gt;
| main.* || main.h declares some key global variables (mapBlockIndex, chainActive, mempool, etc), constants, and functions. &amp;lt;br&amp;gt;&amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt; is the program&#039;s longest source file (5,237 lines).&amp;lt;br&amp;gt;main.cpp has most of the key functions for managing the blockchain, such as connecting, disconnecting, validating and storing blocks; identifying a certain block as the tip of the longest chain; and so forth.&amp;lt;br&amp;gt;The &amp;quot;entry point&amp;quot; for most of the code is ProcessMessages (which listens for a signal from the message-handling thread.).&amp;lt;br&amp;gt;Some of the code is run during initialization, called directly from init.cpp. &amp;lt;br&amp;gt;Key dependencies: net.h&lt;br /&gt;
|-&lt;br /&gt;
| chain.* || The header file (chain.h) is the more notable of the two, as it declares the type definitions for the metadata about the block (CBlockIndex) and the longest blockchain (CChain). &amp;lt;br&amp;gt;chain.cpp contains a few handy functions for managing the blockchain (e.g., locating blocks and finding a fork point between two chains.)&lt;br /&gt;
|-&lt;br /&gt;
| coins.* ||  The header file declares a CCoin, which is, conceptually, &amp;quot;a bitcoin.&amp;quot;&amp;lt;br&amp;gt;The source file contains methods for manipulating coins (retrieving, spending, etc.)&lt;br /&gt;
|-&lt;br /&gt;
| miner.* ||  Contains the mining code, including block creation and generating new bitcoins. &lt;br /&gt;
|-&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Subdirectories:&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The subdirectories fall into three categories: &lt;br /&gt;
* Well-defined components (in some cases third-party) &lt;br /&gt;
* Modularization of code&lt;br /&gt;
* Other (unit tests, build files, etc.)&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Subdirectories - Components:&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! Directory !! Description / Purpose&lt;br /&gt;
|-&lt;br /&gt;
| leveldb || C++ source code, docs, etc. for the LevelDB build.&lt;br /&gt;
|-&lt;br /&gt;
|  qt || The GUI code (QT).&amp;lt;br&amp;gt;QT is a C++ open-source project for GUI code, first released in 1995.&lt;br /&gt;
|-&lt;br /&gt;
|  secp256k1 || Library implementing ECDSA cryptography.&amp;lt;br&amp;gt;Purpose: This proprietary C library eliminates reliance on SSL for signature checking.&amp;lt;br&amp;gt;This is important because SSL was susceptible to introducing consensus bugs, because newly released versions do not guarantee bug-for-bug compatibility.&amp;lt;br&amp;gt;This library was written/released in early 2015. &lt;br /&gt;
|-&lt;br /&gt;
|  zmq || From the ZMQ wiki:&amp;lt;br&amp;gt;ZMQ (or ZeroMQ or 0MQ) is a high-performance asynchronous messaging library.&amp;lt;br&amp;gt;It provides a message queue, but unlike message-oriented middleware, a ZMQ system can run without a dedicated message broker. &amp;lt;br&amp;gt;The library is designed to have a familiar socket-style API.&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Subdirectories - Modularization:&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! Directory !! Key Files !! Description / Purpose&lt;br /&gt;
|-&lt;br /&gt;
| consensus || consensus.*&amp;lt;br&amp;gt;merkle.*&amp;lt;br&amp;gt;params.*&amp;lt;br&amp;gt;validation.*  || Code implementing (or defining, as the case may be) the block &amp;amp; transaction validation rules.&amp;lt;br&amp;gt;Purpose: Moving this code into a subdirectory is a step towards modularizing the consensus code.&amp;lt;br&amp;gt;The idea is that in a future version of bitcoin, the consensus code should be packaged as a library, so that alternative implementations of the protocol could simply include this library and guarantee validation compatibility.  &amp;quot;...[T]he goal is not reimplementing the consensus rules but rather extract them from Bitcoin Core so that nobody needs to re-implement them again. It is not only exposing it but also separating it from Bitcoin Core so that they can be changed without having to also change/take into account non-consensus Bitcoin Core specific things.&amp;quot; -- Jorge Timon, on bitcoin-development mailing list, 20 Aug 2015.&amp;lt;br&amp;gt;Discussion on github: [https://github.com/bitcoin/bitcoin/issues/6714 PR6714] &lt;br /&gt;
|-&lt;br /&gt;
| crypto || ripemd.*&amp;lt;br&amp;gt;sha256.*  || Cryptographic hash functions.&amp;lt;br&amp;gt;Both RIPEMD and SHA-256 are used in transforming a bitcoin address to Base-58 encoding.&lt;br /&gt;
|-&lt;br /&gt;
| policy || policy.*&amp;lt;br&amp;gt;fees.* ||  Move validation code that is a matter of &#039;&#039;policy&#039;&#039; (as opposed to consensus) into a separate directory.&lt;br /&gt;
|-&lt;br /&gt;
| primitives  || block.*&amp;lt;br&amp;gt;transaction.*  || Definitions of certain basic data types (blocks, transactions, etc.)&lt;br /&gt;
|-&lt;br /&gt;
|  script || interpreter.*&amp;lt;br&amp;gt;script.*&amp;lt;br&amp;gt;standard.* || The script engine.&amp;lt;br&amp;gt;Defines the op_codes (script.h).&amp;lt;br&amp;gt;Parses and evaluates the validation script. (interpreter.cpp:EvalScript())&amp;lt;br&amp;gt;Defines what is a &amp;quot;standard&amp;quot; transaction (standard.h).&amp;lt;br&amp;gt;Purpose: the Script engine validates basic transactions but also makes contracts possible.  It could be said that in large part, what a platform like Ethereum does is provide a more robust script engine (and language in which to express script) - so in a sense, deploying such as system consists of replacing this sub-directory with something more powerful. &lt;br /&gt;
|-&lt;br /&gt;
|  wallet || wallet.*  || Wallet code. &lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Subdirectories - Other:&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! Directory !! Description / Purpose&lt;br /&gt;
|-&lt;br /&gt;
| compat || A few minor, low-level files dealing with compatibility details. &lt;br /&gt;
|-&lt;br /&gt;
| config&amp;lt;br&amp;gt;obj&amp;lt;br&amp;gt;obj-test || These directories relate to the build process.&lt;br /&gt;
|-&lt;br /&gt;
|  test || Unit tests.&amp;lt;br&amp;gt;Uses the Boost unit test framework.&amp;lt;br&amp;gt;A good introduction to the Boost user test framework is here:  [http://www.alittlemadness.com/2009/03/31/c-unit-testing-with-boosttest/]&lt;br /&gt;
|-&lt;br /&gt;
|  univalue || Per the README:&amp;lt;br&amp;gt;&amp;quot;A universal value object, with JSON encoding (output) and decoding (input).&amp;lt;br&amp;gt;Built as a single dynamic RAII C++ object class, and no templates.&amp;quot;&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
==Design Patterns==&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Object-Oriented Design&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Naturally, being a C++ program, the code employs object-oriented design.&lt;br /&gt;
&lt;br /&gt;
However, the code&#039;s use of object-oriented design is by not universal.  In 0.11, objects are used mainly for defining the data structures which main.cpp uses to manage the blockchain and the UTXO set (the bitcoins). Main.h declares many functions and global variables but almost no classes; &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt; is over 5000 lines but does not include any class methods.  &lt;br /&gt;
&lt;br /&gt;
The code has a relatively flat class structure, with most classes being &amp;quot;stand-alone&amp;quot;.  &lt;br /&gt;
&lt;br /&gt;
Where inheritance is used, it often is a linear hierarchy (i.e.:  A &amp;lt;-- B &amp;lt;--C &amp;lt;-- D)&lt;br /&gt;
&lt;br /&gt;
For example: &lt;br /&gt;
 CBlockHeader &amp;lt;-- CBlock&lt;br /&gt;
 CTransaction &amp;lt;-- CMerkleTx &amp;lt;-- CWalletTx&lt;br /&gt;
&lt;br /&gt;
There are only a few examples of base classes that have more than one descendant class, and multiple inheritance is only used once in the code (CWallet inherits from 2 classes.) &lt;br /&gt;
&lt;br /&gt;
The program&#039;s best example of an elegant class hierarchy relates to the coins caches.  It uses an abstract class that is inherited by a few subclasses that demonstrate encapsulation and polymorphism.  Chapter 3 has a class diagram as well as a diagram and explanation of how the classes are instantiated and relate to one another.  &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Multithreading&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The code uses Boost thread groups to implement multithreading.  The vast majority of the action takes place in the message-processing thread, and to a lesser extent the socket thread. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Observer (Signals and slots)&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The &amp;quot;observer&amp;quot; pattern uses &amp;quot;signals and slots&amp;quot; to decouple two or more areas of code. Bitcoin Core 0.11 uses the observer pattern in a limited way.  Namely, it uses signals to decouple the message-gathering loop from the &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt; code.  In 0.10 and earlier a normal function call was used.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[Category:Technical]]&lt;br /&gt;
[[Category:Developer]]&lt;/div&gt;</summary>
		<author><name>Mrbandrews</name></author>
	</entry>
	<entry>
		<id>https://en.bitcoin.it/w/index.php?title=Bitcoin_Core_0.11_(ch_2):_Data_Storage&amp;diff=59981</id>
		<title>Bitcoin Core 0.11 (ch 2): Data Storage</title>
		<link rel="alternate" type="text/html" href="https://en.bitcoin.it/w/index.php?title=Bitcoin_Core_0.11_(ch_2):_Data_Storage&amp;diff=59981"/>
		<updated>2016-01-13T21:48:41Z</updated>

		<summary type="html">&lt;p&gt;Mrbandrews: /* The UTXO set (chainstate leveldb) */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
This page describes how &amp;amp; where Bitcoin Core stores blockchain data. &lt;br /&gt;
&lt;br /&gt;
==Overview==&lt;br /&gt;
&lt;br /&gt;
There are basically four pieces of data that are maintained:&lt;br /&gt;
&lt;br /&gt;
: &#039;&#039;&#039;blocks/blk*.dat:&#039;&#039;&#039; the actual Bitcoin blocks, in network format, dumped in raw on disk. They are only needed for rescanning missing transactions in a wallet, reorganizing to a different part of the chain, and serving the block data to other nodes that are synchronizing.&lt;br /&gt;
&lt;br /&gt;
: &#039;&#039;&#039;blocks/index/*:&#039;&#039;&#039; this is a LevelDB database that contains metadata about all known blocks, and where to find them on disk. Without this, finding a block would be very slow.&lt;br /&gt;
&lt;br /&gt;
: &#039;&#039;&#039;chainstate/*:&#039;&#039;&#039; this is a LevelDB database with a compact representation of all currently unspent transaction outputs and some metadata about the transactions they are from. The data here is necessary for validating new incoming blocks and transactions. It can theoretically be rebuilt from the block data (see the -reindex command line option), but this takes a rather long time. Without it, you could still theoretically do validation indeed, but it would mean a full scan through the blocks (7 GB as of may 2013) for every output being spent.&lt;br /&gt;
&lt;br /&gt;
: &#039;&#039;&#039;blocks/rev*.dat:&#039;&#039;&#039; these contain &amp;quot;undo&amp;quot; data. You can see blocks as &#039;patches&#039; to the chain state (they consume some unspent outputs, and produce new ones), and see the undo data as reverse patches. They are necessary for rolling back the chainstate, which is necessary in case of reorganisations.&lt;br /&gt;
&lt;br /&gt;
Note that the LevelDB&#039;s are redundant in the sense that they can be rebuilt from the block data. But validation and other operations would become intolerably slow without them.&lt;br /&gt;
&lt;br /&gt;
See here:  [http://bitcoin.stackexchange.com/questions/11104/what-is-the-database-for?rq=1 StackExchange post by Pieter Wuille (2013)]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Raw Block data (blk*.dat)==&lt;br /&gt;
&lt;br /&gt;
Block files store the raw blocks as they were received over the network.  &lt;br /&gt;
&lt;br /&gt;
Block files are about 128 MB, allocated in 16 MB chunks to prevent excessive fragmentation.  As of October 2015, the block chain is stored in about 365 block files, for a total of about 45 GB. &lt;br /&gt;
&lt;br /&gt;
Each block file (blk1234.dat) has a corresponding undo file (rev1234.dat) which contains the data necessary to remove blocks from the blockchain in the event of a reorganization (fork). &lt;br /&gt;
&lt;br /&gt;
Info about the block files is stored in the block index (the LevelDB) in two places: &lt;br /&gt;
* General info about the files themselves is held in the &amp;quot;f&amp;quot; records in the block index LevelDB (meaning keys &amp;quot;fxxxx&amp;quot;, where &amp;quot;xxxx&amp;quot; is the 4 digit file number), including: &lt;br /&gt;
** Number of blocks stored in the file&lt;br /&gt;
** File size (and the corresponding undo file size) &lt;br /&gt;
** Lowest and highest block in the file&lt;br /&gt;
** Timestamps - earlier and latest blocks in the file&lt;br /&gt;
&lt;br /&gt;
* Info about where to find a particular block on disk is in the &amp;quot;b&amp;quot; (&amp;quot;b&amp;quot; = block) record: &lt;br /&gt;
** Each block contains a pointer to the block is on disk (a file number and an offset)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Accessing the block data files from the code&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The block files are accessed through: &lt;br /&gt;
&lt;br /&gt;
1) DiskBlockPos: a struct that is simply a pointer to a block&#039;s location on disk (a file number and an offset.) &lt;br /&gt;
&lt;br /&gt;
2) &#039;&#039;vInfoBlockFiles&#039;&#039;: a vector of BlockFileInfo objects.  This variable is used to perform such tasks as:  &lt;br /&gt;
* Determine whether new blocks can fit into the current file or a new file needs to be created&lt;br /&gt;
* Calculate the total disk usage by block &amp;amp; undo files &lt;br /&gt;
* Iterate through the block files and find ones that can be pruned&lt;br /&gt;
&lt;br /&gt;
Blocks are written to disk as soon as they are received, in AcceptBlock.  (The actual disk write operation is in WriteBlockToDisk [&amp;lt;u&amp;gt;main.cpp:1164&amp;lt;/u&amp;gt;]).  Note that there is some overlap of the code that accesses block files with the code that accesses and writes to the coins database (/chainstate).  There is a complex system of when to flush state to disk.  None of this code affects block files, which are simply written to disk when received.  Once they have been received and stored, the block files are only needed for serving blocks to other nodes. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;More info about block files&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
See here: [https://github.com/sipa/bitcoin/commit/5382bcf8cd23c36a435c29080770a79b5e28af42 the commit that puts multiple blocks in a block file (2012)]&lt;br /&gt;
&lt;br /&gt;
==Block index (leveldb)==&lt;br /&gt;
&lt;br /&gt;
The block index holds metadata about all known blocks, including where the block is stored on disk.  &lt;br /&gt;
&lt;br /&gt;
Note that the set of &amp;quot;known blocks&amp;quot; is a superset of the longest chain, because it includes blocks that were received and processed but are not part of the active chain - for example, orphaned blocks that were detached from the active chain in a small reorganization.   &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Terminology&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The terminology can be a little confusing here, because while people normally think of the &amp;quot;blockchain&amp;quot; as being synonymous with the active chain (an uninterrupted, linear chain of X blocks starting with the genesis block and continuing to the current tip), there are some places in the code where &amp;quot;blockchain&amp;quot; refers to the active chain plus the numerous, mostly short forks off the chain that our node happens to know about.  &lt;br /&gt;
&lt;br /&gt;
a) Block Tree&lt;br /&gt;
&lt;br /&gt;
A better term for the set of known blocks stored on disk is &amp;quot;block tree,&amp;quot; as this term contemplates a tree structure with numerous branches (albeit small ones) from the main chain.  Indeed, the block index LevelDB is accessed through the &amp;quot;CBlockTreeDB&amp;quot; wrapper class, defined in &amp;lt;u&amp;gt;src/txdb.h&amp;lt;/u&amp;gt;.  Note that it&#039;s perfectly fine, indeed it is expected, that different nodes would have slightly different block trees;  what matters is that they agree on the active chain.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Key-value pairs&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Inside the actual LevelDB, the used key/value pairs are:&lt;br /&gt;
&lt;br /&gt;
    &#039;b&#039; + 32-byte block hash -&amp;gt; block index record. Each record stores:&lt;br /&gt;
        * The block header&lt;br /&gt;
        * The height.&lt;br /&gt;
        * The number of transactions.&lt;br /&gt;
        * To what extent this block is validated.&lt;br /&gt;
        * In which file, and where in that file, the block data is stored.&lt;br /&gt;
        * In which file, and where in that file, the undo data is stored.&lt;br /&gt;
&lt;br /&gt;
   &#039;f&#039; + 4-byte file number -&amp;gt; file information record. Each record stores:&lt;br /&gt;
        * The number of blocks stored in the block file with that number.&lt;br /&gt;
        * The size of the block file with that number ($DATADIR/blocks/blkNNNNN.dat).&lt;br /&gt;
        * The size of the undo file with that number ($DATADIR/blocks/revNNNNN.dat).&lt;br /&gt;
        * The lowest and highest height of blocks stored in the block file with that number.&lt;br /&gt;
        * The lowest and highest timestamp of blocks stored in the block file with that number.&lt;br /&gt;
&lt;br /&gt;
    &#039;l&#039; -&amp;gt; 4-byte file number: the last block file number used.&lt;br /&gt;
&lt;br /&gt;
    &#039;R&#039; -&amp;gt; 1-byte boolean (&#039;1&#039; if true): whether we&#039;re in the process of reindexing.&lt;br /&gt;
&lt;br /&gt;
    &#039;F&#039; + 1-byte flag name length + flag name string -&amp;gt; 1 byte boolean (&#039;1&#039; if true, &#039;0&#039; if false): various flags that can be on or off. Currently defined flags include:&lt;br /&gt;
         * &#039;txindex&#039;: Whether the transaction index is enabled.&lt;br /&gt;
&lt;br /&gt;
    &#039;t&#039; + 32-byte transaction hash -&amp;gt; transaction index record. These are optional and only exist if &#039;txindex&#039; is enabled (see above). Each record stores:&lt;br /&gt;
        * Which block file number the transaction is stored in.&lt;br /&gt;
        * Which offset into that file the block the transaction is part of is stored at.&lt;br /&gt;
        * The offset from the start of that block to the position where that transaction itself is stored.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
See here: [http://bitcoin.stackexchange.com/questions/28168/what-are-the-keys-used-in-the-blockchain-leveldb-ie-what-are-the-keyvalue-pair StackExchange post by Pieter Wuille (2014)]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Data Access Layer&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The database is accessed through CBlockTreeDB wrapper class.  See &amp;lt;u&amp;gt;txdb.h&amp;lt;/u&amp;gt;.  &lt;br /&gt;
&lt;br /&gt;
The wrapper is instantiated in a global variable called pblocktree, defined in &amp;lt;u&amp;gt;main.cpp.&amp;lt;/u&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;CBlockIndex&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Blocks stored in the database are represented in memory as CBlockIndex objects.  An object of this type is first created after the &#039;&#039;header&#039;&#039; is received;  the code does not wait to receive the full block.  When headers are received over the network, they are streamed into a vector of CBlockHeaders, which are then checked. Each header that checks out causes a new CBlockIndex to be created, which is stored to the database. &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;CBlock / CBlockHeader&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Note that these objects have little to do with the /blocks LevelDB.  A CBlock holds the full set of transactions in the block, the data for which is stored in two places - in full, in raw format, in the blk???.dat files, and in pruned format in the UTXO database.  The block index database cares not for such details, since it holds only the metadata for the block. &lt;br /&gt;
 &lt;br /&gt;
&#039;&#039;Loading the block database into memory&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The entire database is loaded into memory on startup.  See LoadBlockIndexGuts (&amp;lt;u&amp;gt;txdb.cpp&amp;lt;/u&amp;gt;).  This only takes a few seconds. &lt;br /&gt;
&lt;br /&gt;
The blocks (&#039;b&#039; keys) are loaded into the global &amp;quot;mapBlockIndex&amp;quot; variable.  &amp;quot;mapBlockIndex&amp;quot; is an unordered_map that holds CBlockIndex for each block in the entire block tree; not just the active chain.  &lt;br /&gt;
&lt;br /&gt;
mapBlockIndex is described in more detail in Chapter 6 - The Blockchain. &lt;br /&gt;
&lt;br /&gt;
The block file metadata (&#039;f&#039; keys) is loaded into vInfoBlockFiles.&lt;br /&gt;
&lt;br /&gt;
==The UTXO set (chainstate leveldb)==&lt;br /&gt;
&lt;br /&gt;
The UTXO database was introduced in 2012 in [https://github.com/bitcoin/bitcoin/pull/1677 pull request #1677 - &amp;quot;Ultraprune.&amp;quot;]&lt;br /&gt;
&lt;br /&gt;
The idea behind &amp;quot;Ultraprune&amp;quot; is to reduce the size of (prune) the set of past transactions, keeping only those parts of past transactions that are necessary to validate later transactions.  &lt;br /&gt;
&lt;br /&gt;
Say you have a transaction T1 which takes two inputs and sends to 3 outputs: O1,O2,O3.  Two of those outputs (O1, O2) have been used as inputs in a later transaction, T2.   Once T2 has been mined, T1 only has one item of interest (O3).  There&#039;s no reason to keep T1 around in its entirety.  Instead, a slimmed-down version of T1 will suffice, consisting only of O3 (locking script and amount) and certain basic information about T1 (height, whether it is a coinbase, etc.)&lt;br /&gt;
&lt;br /&gt;
The description of ultraprune is on the specific &amp;quot;ultraprune&amp;quot; commit within the pull: &lt;br /&gt;
&lt;br /&gt;
: -------------&lt;br /&gt;
&lt;br /&gt;
: This switches bitcoin&#039;s transaction/block verification logic to use a &amp;quot;coin database&amp;quot;, which contains all unredeemed transaction output scripts, amounts and heights.&lt;br /&gt;
&lt;br /&gt;
: The name ultraprune comes from the fact that instead of a full transaction index, we only (need to) keep an index with unspent outputs. For now, the blocks themselves are kept as usual, although they are only necessary for serving, rescanning and reorganizing.&lt;br /&gt;
&lt;br /&gt;
: The basic data structures are CCoins (representing the coins of a single transaction), and CCoinsView (representing a state of the coins database).  There are several implementations for CCoinsView. A dummy, one backed by the coins database (coins.dat), one backed by the memory pool, and one that adds a cache on top of it. FetchInputs, ConnectInputs, ConnectBlock, DisconnectBlock, ... now operate on a generic CCoinsView.&lt;br /&gt;
&lt;br /&gt;
: The block switching logic now builds a single cached CCoinsView with changes to be committed to the database before any changes are made. This means no uncommitted changes are ever read from the database, and should ease the transition to another database layer which does not support transactions (but does support atomic writes), like LevelDB.&lt;br /&gt;
&lt;br /&gt;
: For the getrawtransaction() RPC call, access to a txid-to-disk index would be preferable. As this index is not necessary or even useful for any other part of the implementation, it is not provided. Instead, getrawtransaction() uses the coin database to find the block height, and then scans that block to find the requested transaction. This is slow, but should suffice for debug purposes.&lt;br /&gt;
&lt;br /&gt;
: -----------------&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
See:  [https://github.com/sipa/bitcoin/commit/450cbb0944cd20a06ce806e6679a1f4c83c50db2 Ultraprune - July 2012]&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Terminology&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
&amp;quot;UTXO (Unspent Transaction Out):&amp;quot;  An output from a transaction.  This is colloquially referred to as a &amp;quot;coin.&amp;quot;  For this reason, the UTXO db is sometimes referred to as the &amp;quot;coins database.&amp;quot;&lt;br /&gt;
&lt;br /&gt;
&amp;quot;UTXO set / coins database / chainstate database:&amp;quot;  These terms are more or less synonymous and are used interchangeably.  &lt;br /&gt;
&lt;br /&gt;
&amp;quot;Provably Unspendable:&amp;quot;  A coin is provably unspendable if its scriptPubKey cannot be satisfied - for example, an OP_RETURN.  A provably unspendable coin can be eliminated from the utxo database regardless of its amount. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Key-value pairs&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The records in the chainstate levelDB are: &lt;br /&gt;
&lt;br /&gt;
    &#039;c&#039; + 32-byte transaction hash -&amp;gt; unspent transaction output record for that transaction. These records are only present for transactions that have at least one unspent output left. Each record stores:&lt;br /&gt;
        * The version of the transaction.&lt;br /&gt;
        * Whether the transaction was a coinbase or not.&lt;br /&gt;
        * Which height block contains the transaction.&lt;br /&gt;
        * Which outputs of that transaction are unspent.&lt;br /&gt;
        * The scriptPubKey and amount for those unspent outputs.&amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
    &#039;B&#039; -&amp;gt; 32-byte block hash: the block hash up to which the database represents the unspent transaction outputs.&lt;br /&gt;
&lt;br /&gt;
See here: [http://bitcoin.stackexchange.com/questions/28168/what-are-the-keys-used-in-the-blockchain-leveldb-ie-what-are-the-keyvalue-pair StackExchange post by Pieter Wuille (2014)]&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Data Access Layer and Caching&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Access to the UTXO database is considerably more complex than the block index.   This is because its performance is critical to the overall performance of the Bitcoin system.  The block index is not so critical to performance because there are only a few hundred thousand blocks and a node running on decent hardware can retrieve and scroll through them in a few seconds (and does not need to do so very often.)  On the other hand, there are millions of coins in the UTXO database and they must be checked and modified for each input of each transaction going into the mempool or included in a block. &lt;br /&gt;
&lt;br /&gt;
As sipa said in the ultraprune commit: &lt;br /&gt;
: The basic data structures are CCoins (representing the coins of a single transaction), and CCoinsView (representing a state of the coins database).  There are several implementations for CCoinsView. A dummy, one backed by the coins database (coins.dat), one backed by the memory pool, and one that adds a cache on top of it.&lt;br /&gt;
&lt;br /&gt;
This is not stated as clearly as it might have been, however; at least, not for the current state of the code.  &lt;br /&gt;
&lt;br /&gt;
In 0.11, the instantiations of the CoinsView are:  &lt;br /&gt;
* dummy&lt;br /&gt;
* database&lt;br /&gt;
* pCoinsTip (a cache backed by the database)&lt;br /&gt;
* &amp;quot;validation cache&amp;quot; (used when  backed by pCoinsTip, in use when connecting a block)  &lt;br /&gt;
&lt;br /&gt;
Separate from that chain of caches is the memory pool&#039;s CoinsView, which is backed by the database. &lt;br /&gt;
&lt;br /&gt;
    &lt;br /&gt;
The &amp;lt;i&amp;gt;class diagram&amp;lt;/i&amp;gt; (data types) for the views is: &lt;br /&gt;
&lt;br /&gt;
       CCoinsView (abstract class)&lt;br /&gt;
              /            \&lt;br /&gt;
          ViewDB          ViewBacked &lt;br /&gt;
       (database)          /      \&lt;br /&gt;
                    ViewMempool   ViewCache&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Each class has one key characteristic: &lt;br /&gt;
* View is the base class, declaring methods for verifying that coins exist (HaveCoins), retrieving coins (GetCoins), etc. &lt;br /&gt;
* ViewDB has code to interact with the LevelDB. &lt;br /&gt;
* ViewBacked has a pointer to another View;  thus it is &amp;quot;backed&amp;quot; by another view (version) of the UTXO set. &lt;br /&gt;
* ViewCache has a cache (a map of CCoins). &lt;br /&gt;
* ViewMempool associates a mempool with a view. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Those are the defined classes; whereas the &amp;lt;i&amp;gt;object diagram&amp;lt;/i&amp;gt; is: &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
             Database       &lt;br /&gt;
            /       \&lt;br /&gt;
        MemPool     Blockchain cache (pcoinsTip) &lt;br /&gt;
      View/Cache            \&lt;br /&gt;
                          Validation cache&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here is a table summarizing the instantiations of Views: &lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! Object !! Type !! Backed By? !! Description / Purpose&lt;br /&gt;
|-&lt;br /&gt;
| DB view || ViewDB || n/a || Represents the UTXO set according to the /chainstate LevelDB.  Retrieves coins and flushes changes to the LevelDB.&amp;lt;br&amp;gt;Creation in code (instantiation):  see &amp;lt;u&amp;gt;init.cpp:1131&amp;lt;/u&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| pCoinsTip&amp;lt;br&amp;gt;(blockchain cache) || ViewCache || DB view || Holds the UTXO set corresponding to the active chain&#039;s tip.  Retrieves/flushes to the database view.&amp;lt;br&amp;gt;Creation in code:  see &amp;lt;u&amp;gt;init.cpp:1133&amp;lt;/u&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| Validation cache || ViewCache || pCoinsTip || This cache&#039;s lifetime is within ConnectTip (or DisconnectTip).&amp;lt;br&amp;gt;Its purpose is to keep track of modifications to the UTXO set while processing a block.&amp;lt;br&amp;gt;If the block validates, the cache is flushed to pcoinsTip.&amp;lt;br&amp;gt;If the block fails, the cache is discarded. &amp;lt;br&amp;gt;Creation in code:  see &amp;lt;u&amp;gt;main.cpp:2231&amp;lt;/u&amp;gt;:  CCoinsViewCache view(pcoinsTip);&lt;br /&gt;
|-&lt;br /&gt;
| Mempool view || ViewMemPool || pCoinsTip || This object brings the mempool into view, meaning it can see both a UTXO set and the mempool.&amp;lt;br&amp;gt;Its purpose is to enable validation of chains of transactions, a.k.a. &amp;quot;zero-confirmation&amp;quot; transactions.  (If chains of transactions weren&#039;t permitted, the mempool could simply validate against pcoinsTip.)&amp;lt;br&amp;gt;Thus, when queried, it can check if a given input can be found either in the mempool (i.e., &amp;quot;zero-conf&amp;quot;) or in the blockchain&#039;s utxo set (&amp;quot;confirmed.&amp;quot;)&amp;lt;br&amp;gt;Note that this object is not a cache; rather, it is a view that is used by the object below, which does contain a cache.  &amp;lt;br&amp;gt;Creation in code: Its lifetime is that of AcceptToMemoryPool in &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt;.&lt;br /&gt;
|-&lt;br /&gt;
| Mempool cache || ViewCache || Mempool view || The cache for the mempool.  It contains a cache and sets its backend to be the mempool view.&amp;lt;br&amp;gt;Creation in code: Its lifetime is also that of AcceptToMemoryPool in &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt;. &lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Loading the UTXO set&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Access to the coins database is initialized in &amp;lt;u&amp;gt;init.cpp&amp;lt;/u&amp;gt;: 1131-1133: &lt;br /&gt;
&lt;br /&gt;
 pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex);&lt;br /&gt;
 pcoinscatcher = new CCoinsViewErrorCatcher(pcoinsdbview);&lt;br /&gt;
 pcoinsTip = new CCoinsViewCache(pcoinscatcher);&lt;br /&gt;
&lt;br /&gt;
The code starts by initializing a CoinsViewDB, which is equipped with methods to load coins from the LevelDB. &amp;lt;br&amp;gt;&lt;br /&gt;
The error catcher is a little hack that can be ignored. &amp;lt;br&amp;gt;&lt;br /&gt;
Next, the code initalizes pCoinsTip, which is the cache representing the state of the active chain, and is backed by the database view. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Cache vs. Database&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The FetchCoins function in coins.cpp demonstrates how the code uses the cache vs. the database: &lt;br /&gt;
 1   CCoinsMap::iterator it = cacheCoins.find(txid);&lt;br /&gt;
 2   if (it != cacheCoins.end())&lt;br /&gt;
 3     return it;&lt;br /&gt;
 4   CCoins tmp;&lt;br /&gt;
 5   if (!base-&amp;gt;GetCoins(txid, tmp))&lt;br /&gt;
 6     return cacheCoins.end();&lt;br /&gt;
 7   CCoinsMap::iterator ret = cacheCoins.insert(std::make_pair(txid, CCoinsCacheEntry())).first;&lt;br /&gt;
&lt;br /&gt;
First, the code searches the cache for the coins for a given transaction id. (line 1)&amp;lt;br&amp;gt;&lt;br /&gt;
If found, it returns the &amp;quot;fetched&amp;quot; coins. (lines 2-3) &amp;lt;br&amp;gt;&lt;br /&gt;
If not, it searches the database. (line 5) &amp;lt;br&amp;gt;&lt;br /&gt;
If found in the database, it updates the cache. (line 7) &amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
Note:  if the cache&#039;s backend is another cache, then the term &amp;quot;database&amp;quot; really means &amp;quot;parent cache.&amp;quot; &lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Flushing the Validation Cache to the Blockchain Cache&#039;&#039;  &lt;br /&gt;
&lt;br /&gt;
The validation cache is flushed to the blockchain cache after connecting a block, just before it goes out of scope.  The scope is captured in ConnectTip, and specifically, in the code block &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt;:2231-2243.  In that code block, there is a call to ConnectBlock, during which the code stores the new coins in the validation cache.  (Specifically, see UpdateCoins() in &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt;.)  At the end of the code block, the validation cache is flushed.  Since its &amp;quot;parent view&amp;quot; is also a cache (pcoinsTip, the &amp;quot;blockchain cache&amp;quot;) the code will call the parent&#039;s ViewCache::BatchWrite, which swaps the updated coin entries into its own cache.  (Polymorphism in action: Later, when the the blockchain cache flushes to the database view, the code will run CoinsViewDB::BatchWrite, the last line of which writes to the LevelDB.) &lt;br /&gt;
&lt;br /&gt;
In summary, usage of the validation cache is straightforward: it is instantiated, used, flushed, and goes out of scope in the aforementioned code block. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Flushing the Blockchain Cache to the Database&#039;&#039;  &lt;br /&gt;
&lt;br /&gt;
Flushing the validate cache was simple because the code only shuffled items between two caches in memory (of which no one is aware outside of the caching code.)  Flushing the blockchain cache to the database is a bit more complicated.  At the lowest level, the mechanics of flushing the blockchain cache (pcoinsTip) is the same as the validation cache:  the Flush() method calls BatchWrite on its backend (the &amp;quot;base&amp;quot; pointer), and in this case that means BatchWrite on the database view.  Up a level, Flush() is called from FlushStateToDisk (FSTD) - &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt;:2098.  FlushStateToDisk is invoked at a few different points, with a given &#039;&#039;mode&#039;&#039;: &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! Flush Mode !! Description !! When called&lt;br /&gt;
|-&lt;br /&gt;
| IF_NEEDED || Flush only if the cache is over its size limit. || Right after connecting (or disconnecting) a block and flushing the validation cache.&amp;lt;br&amp;gt;See ConnectTip / DisconnectTip.&lt;br /&gt;
|-&lt;br /&gt;
| ALWAYS || Flush cache. || During initialization only. &lt;br /&gt;
|-&lt;br /&gt;
| PERIODIC || Here, the code considers other data points to decide whether to flush.&amp;lt;br&amp;gt;Is the code &#039;&#039;almost&#039;&#039; over its size limit?&amp;lt;br&amp;gt;Has it been a long time since the cache was flushed?&amp;lt;br&amp;gt;If so, then proceed.|| At end of ActivateBestChain()&amp;lt;br&amp;gt;(Code comment: &amp;quot;write changes periodically to disk, after relay&amp;quot;). &lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The idea is to flush the block cache frequently (to avoid having to download a large number of blocks if the program crashes), but the coins cache infrequently (in order to maximize the benefit from the coins cache.) &lt;br /&gt;
&lt;br /&gt;
Specifically, the block cache is guaranteed to be flushed once an hour, whereas the coins cache once per day.  (See here:  [https://github.com/bitcoin/bitcoin/pull/6102#issuecomment-98847663 Sipa comment on PR 6102])&lt;br /&gt;
&lt;br /&gt;
The FlushStateToDisk code is well-commented so for more info, the curious reader can check &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
==Raw undo data (rev*.dat)==&lt;br /&gt;
&lt;br /&gt;
The undo data contains the information that is necessary to disconnect or &amp;quot;roll back&amp;quot; a block: specifically, the coins that were spent by the block in question.&lt;br /&gt;
&lt;br /&gt;
So, the data being written is essentially a set of CTxOut objects.  (A CTxOut is simply an amount and a script - see &amp;lt;u&amp;gt;primitives/transaction.h&amp;lt;/u&amp;gt;:107-108).&lt;br /&gt;
&lt;br /&gt;
The matter is complicated slightly by the fact that if the coin is the last one being spent by its transaction, the undo data needs to store the transaction&#039;s metadata (the txn&#039;s block height, whether it&#039;s a coinbase, and its version.) So, if you have a transaction T with outputs O1,O2,O3 spent in that order, for O1 and O2 all that will be written to the undo file is the amount and the script.  For 03, the undo file will have the amount, the script, plus T&#039;s height and version, and whether T is a coinbase.&lt;br /&gt;
&lt;br /&gt;
The undo data is written to the raw file with the following code: &lt;br /&gt;
 fileout &amp;lt;&amp;lt; blockundo; (main.cpp:1567 [UndoWriteToDisk])&lt;br /&gt;
&lt;br /&gt;
This line of code calls the serialization function on the CBlockUndo - which is basically just a vector of coins (CTxOuts.)  Finally, a checksum is written to the undo file. The checksum  is used during initialization to verify that any undo data being checked is intact.  See [https://github.com/bitcoin/bitcoin/pull/2145 Pull 2145]&lt;br /&gt;
&lt;br /&gt;
The undo data is used when disconnecting a block.  The DisconnectBlock() code is discussed further down this wiki page in The Blockchain: Reorganizations.&lt;br /&gt;
&lt;br /&gt;
==Use of LevelDB==&lt;br /&gt;
&lt;br /&gt;
LevelDB is a key-value store that was introduced to store the block index and UTXO set (chainstate) in 2012 as part of the complex &amp;quot;Ultraprune&amp;quot; pull (PR 1677).  See here: [https://github.com/bitcoin/bitcoin/pull/1677/commits the 27 commits on Ultraprune]. &lt;br /&gt;
&lt;br /&gt;
On the subject of why LevelDB is used, core developer Greg Maxwell stated the following to the [http://bitcoin-development.narkive.com/XAPoxKZU/patch-switching-bitcoin-core-to-sqlite-db bitcoin-dev mailing list in October 2015]: &lt;br /&gt;
&lt;br /&gt;
:: I think people are falling into a trap of thinking &amp;quot;It&#039;s a &amp;lt;database&amp;gt;, I know a &amp;lt;black box&amp;gt; for that!&amp;quot;; but the application and needs are very specialized here. . . It just so happens that on the back of the very bitcoin specific cryptographic consensus algorithim there was a slot where a pre-existing high performance key-value store fit; and so we&#039;re using one and saving ourselves some effort... &lt;br /&gt;
&lt;br /&gt;
One might ask whether different nodes could use different databases - as long as they retrieve the same data, what&#039;s the difference? The issue here is &amp;quot;bug-for-bug compatibility&amp;quot; - if one database has a bug that causes records to not be returned under certain circumstances, then all other nodes bst have the same bug, else the network could fork as a result.  &lt;br /&gt;
&lt;br /&gt;
Greg Maxwell stated the following in [http://bitcoin-development.narkive.com/XAPoxKZU/patch-switching-bitcoin-core-to-sqlite-db the same thread referenced above (in response to a proposal to switch to using sqlite)]: &lt;br /&gt;
&lt;br /&gt;
:: ...[D]atabases sometimes have errors which cause them to fail to return records, or to return stale data. And if those exist consistency must be maintained; and &amp;quot;fixing&amp;quot; the bug can cause a divergence in consensus state that could open users up to theft.&lt;br /&gt;
&lt;br /&gt;
:: Case in point, prior to leveldb&#039;s use in Bitcoin Core it had a bug that, under rare conditions, could cause it to consistently return not found on records that were really there. . . Leveldb fixed this serious bug in a minor update.  But deploying a fix like this in an uncontrolled manner in the bitcoin network would potentially cause a fork in the consensus state; so any such fix would need to be rolled out in an orderly manner.&lt;br /&gt;
&lt;br /&gt;
[[Category:Technical]]&lt;br /&gt;
[[Category:Developer]]&lt;/div&gt;</summary>
		<author><name>Mrbandrews</name></author>
	</entry>
	<entry>
		<id>https://en.bitcoin.it/w/index.php?title=Bitcoin_Core_0.11_(ch_2):_Data_Storage&amp;diff=59980</id>
		<title>Bitcoin Core 0.11 (ch 2): Data Storage</title>
		<link rel="alternate" type="text/html" href="https://en.bitcoin.it/w/index.php?title=Bitcoin_Core_0.11_(ch_2):_Data_Storage&amp;diff=59980"/>
		<updated>2016-01-13T21:27:08Z</updated>

		<summary type="html">&lt;p&gt;Mrbandrews: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
This page describes how &amp;amp; where Bitcoin Core stores blockchain data. &lt;br /&gt;
&lt;br /&gt;
==Overview==&lt;br /&gt;
&lt;br /&gt;
There are basically four pieces of data that are maintained:&lt;br /&gt;
&lt;br /&gt;
: &#039;&#039;&#039;blocks/blk*.dat:&#039;&#039;&#039; the actual Bitcoin blocks, in network format, dumped in raw on disk. They are only needed for rescanning missing transactions in a wallet, reorganizing to a different part of the chain, and serving the block data to other nodes that are synchronizing.&lt;br /&gt;
&lt;br /&gt;
: &#039;&#039;&#039;blocks/index/*:&#039;&#039;&#039; this is a LevelDB database that contains metadata about all known blocks, and where to find them on disk. Without this, finding a block would be very slow.&lt;br /&gt;
&lt;br /&gt;
: &#039;&#039;&#039;chainstate/*:&#039;&#039;&#039; this is a LevelDB database with a compact representation of all currently unspent transaction outputs and some metadata about the transactions they are from. The data here is necessary for validating new incoming blocks and transactions. It can theoretically be rebuilt from the block data (see the -reindex command line option), but this takes a rather long time. Without it, you could still theoretically do validation indeed, but it would mean a full scan through the blocks (7 GB as of may 2013) for every output being spent.&lt;br /&gt;
&lt;br /&gt;
: &#039;&#039;&#039;blocks/rev*.dat:&#039;&#039;&#039; these contain &amp;quot;undo&amp;quot; data. You can see blocks as &#039;patches&#039; to the chain state (they consume some unspent outputs, and produce new ones), and see the undo data as reverse patches. They are necessary for rolling back the chainstate, which is necessary in case of reorganisations.&lt;br /&gt;
&lt;br /&gt;
Note that the LevelDB&#039;s are redundant in the sense that they can be rebuilt from the block data. But validation and other operations would become intolerably slow without them.&lt;br /&gt;
&lt;br /&gt;
See here:  [http://bitcoin.stackexchange.com/questions/11104/what-is-the-database-for?rq=1 StackExchange post by Pieter Wuille (2013)]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Raw Block data (blk*.dat)==&lt;br /&gt;
&lt;br /&gt;
Block files store the raw blocks as they were received over the network.  &lt;br /&gt;
&lt;br /&gt;
Block files are about 128 MB, allocated in 16 MB chunks to prevent excessive fragmentation.  As of October 2015, the block chain is stored in about 365 block files, for a total of about 45 GB. &lt;br /&gt;
&lt;br /&gt;
Each block file (blk1234.dat) has a corresponding undo file (rev1234.dat) which contains the data necessary to remove blocks from the blockchain in the event of a reorganization (fork). &lt;br /&gt;
&lt;br /&gt;
Info about the block files is stored in the block index (the LevelDB) in two places: &lt;br /&gt;
* General info about the files themselves is held in the &amp;quot;f&amp;quot; records in the block index LevelDB (meaning keys &amp;quot;fxxxx&amp;quot;, where &amp;quot;xxxx&amp;quot; is the 4 digit file number), including: &lt;br /&gt;
** Number of blocks stored in the file&lt;br /&gt;
** File size (and the corresponding undo file size) &lt;br /&gt;
** Lowest and highest block in the file&lt;br /&gt;
** Timestamps - earlier and latest blocks in the file&lt;br /&gt;
&lt;br /&gt;
* Info about where to find a particular block on disk is in the &amp;quot;b&amp;quot; (&amp;quot;b&amp;quot; = block) record: &lt;br /&gt;
** Each block contains a pointer to the block is on disk (a file number and an offset)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Accessing the block data files from the code&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The block files are accessed through: &lt;br /&gt;
&lt;br /&gt;
1) DiskBlockPos: a struct that is simply a pointer to a block&#039;s location on disk (a file number and an offset.) &lt;br /&gt;
&lt;br /&gt;
2) &#039;&#039;vInfoBlockFiles&#039;&#039;: a vector of BlockFileInfo objects.  This variable is used to perform such tasks as:  &lt;br /&gt;
* Determine whether new blocks can fit into the current file or a new file needs to be created&lt;br /&gt;
* Calculate the total disk usage by block &amp;amp; undo files &lt;br /&gt;
* Iterate through the block files and find ones that can be pruned&lt;br /&gt;
&lt;br /&gt;
Blocks are written to disk as soon as they are received, in AcceptBlock.  (The actual disk write operation is in WriteBlockToDisk [&amp;lt;u&amp;gt;main.cpp:1164&amp;lt;/u&amp;gt;]).  Note that there is some overlap of the code that accesses block files with the code that accesses and writes to the coins database (/chainstate).  There is a complex system of when to flush state to disk.  None of this code affects block files, which are simply written to disk when received.  Once they have been received and stored, the block files are only needed for serving blocks to other nodes. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;More info about block files&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
See here: [https://github.com/sipa/bitcoin/commit/5382bcf8cd23c36a435c29080770a79b5e28af42 the commit that puts multiple blocks in a block file (2012)]&lt;br /&gt;
&lt;br /&gt;
==Block index (leveldb)==&lt;br /&gt;
&lt;br /&gt;
The block index holds metadata about all known blocks, including where the block is stored on disk.  &lt;br /&gt;
&lt;br /&gt;
Note that the set of &amp;quot;known blocks&amp;quot; is a superset of the longest chain, because it includes blocks that were received and processed but are not part of the active chain - for example, orphaned blocks that were detached from the active chain in a small reorganization.   &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Terminology&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The terminology can be a little confusing here, because while people normally think of the &amp;quot;blockchain&amp;quot; as being synonymous with the active chain (an uninterrupted, linear chain of X blocks starting with the genesis block and continuing to the current tip), there are some places in the code where &amp;quot;blockchain&amp;quot; refers to the active chain plus the numerous, mostly short forks off the chain that our node happens to know about.  &lt;br /&gt;
&lt;br /&gt;
a) Block Tree&lt;br /&gt;
&lt;br /&gt;
A better term for the set of known blocks stored on disk is &amp;quot;block tree,&amp;quot; as this term contemplates a tree structure with numerous branches (albeit small ones) from the main chain.  Indeed, the block index LevelDB is accessed through the &amp;quot;CBlockTreeDB&amp;quot; wrapper class, defined in &amp;lt;u&amp;gt;src/txdb.h&amp;lt;/u&amp;gt;.  Note that it&#039;s perfectly fine, indeed it is expected, that different nodes would have slightly different block trees;  what matters is that they agree on the active chain.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Key-value pairs&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Inside the actual LevelDB, the used key/value pairs are:&lt;br /&gt;
&lt;br /&gt;
    &#039;b&#039; + 32-byte block hash -&amp;gt; block index record. Each record stores:&lt;br /&gt;
        * The block header&lt;br /&gt;
        * The height.&lt;br /&gt;
        * The number of transactions.&lt;br /&gt;
        * To what extent this block is validated.&lt;br /&gt;
        * In which file, and where in that file, the block data is stored.&lt;br /&gt;
        * In which file, and where in that file, the undo data is stored.&lt;br /&gt;
&lt;br /&gt;
   &#039;f&#039; + 4-byte file number -&amp;gt; file information record. Each record stores:&lt;br /&gt;
        * The number of blocks stored in the block file with that number.&lt;br /&gt;
        * The size of the block file with that number ($DATADIR/blocks/blkNNNNN.dat).&lt;br /&gt;
        * The size of the undo file with that number ($DATADIR/blocks/revNNNNN.dat).&lt;br /&gt;
        * The lowest and highest height of blocks stored in the block file with that number.&lt;br /&gt;
        * The lowest and highest timestamp of blocks stored in the block file with that number.&lt;br /&gt;
&lt;br /&gt;
    &#039;l&#039; -&amp;gt; 4-byte file number: the last block file number used.&lt;br /&gt;
&lt;br /&gt;
    &#039;R&#039; -&amp;gt; 1-byte boolean (&#039;1&#039; if true): whether we&#039;re in the process of reindexing.&lt;br /&gt;
&lt;br /&gt;
    &#039;F&#039; + 1-byte flag name length + flag name string -&amp;gt; 1 byte boolean (&#039;1&#039; if true, &#039;0&#039; if false): various flags that can be on or off. Currently defined flags include:&lt;br /&gt;
         * &#039;txindex&#039;: Whether the transaction index is enabled.&lt;br /&gt;
&lt;br /&gt;
    &#039;t&#039; + 32-byte transaction hash -&amp;gt; transaction index record. These are optional and only exist if &#039;txindex&#039; is enabled (see above). Each record stores:&lt;br /&gt;
        * Which block file number the transaction is stored in.&lt;br /&gt;
        * Which offset into that file the block the transaction is part of is stored at.&lt;br /&gt;
        * The offset from the start of that block to the position where that transaction itself is stored.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
See here: [http://bitcoin.stackexchange.com/questions/28168/what-are-the-keys-used-in-the-blockchain-leveldb-ie-what-are-the-keyvalue-pair StackExchange post by Pieter Wuille (2014)]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Data Access Layer&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The database is accessed through CBlockTreeDB wrapper class.  See &amp;lt;u&amp;gt;txdb.h&amp;lt;/u&amp;gt;.  &lt;br /&gt;
&lt;br /&gt;
The wrapper is instantiated in a global variable called pblocktree, defined in &amp;lt;u&amp;gt;main.cpp.&amp;lt;/u&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;CBlockIndex&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Blocks stored in the database are represented in memory as CBlockIndex objects.  An object of this type is first created after the &#039;&#039;header&#039;&#039; is received;  the code does not wait to receive the full block.  When headers are received over the network, they are streamed into a vector of CBlockHeaders, which are then checked. Each header that checks out causes a new CBlockIndex to be created, which is stored to the database. &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;CBlock / CBlockHeader&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Note that these objects have little to do with the /blocks LevelDB.  A CBlock holds the full set of transactions in the block, the data for which is stored in two places - in full, in raw format, in the blk???.dat files, and in pruned format in the UTXO database.  The block index database cares not for such details, since it holds only the metadata for the block. &lt;br /&gt;
 &lt;br /&gt;
&#039;&#039;Loading the block database into memory&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The entire database is loaded into memory on startup.  See LoadBlockIndexGuts (&amp;lt;u&amp;gt;txdb.cpp&amp;lt;/u&amp;gt;).  This only takes a few seconds. &lt;br /&gt;
&lt;br /&gt;
The blocks (&#039;b&#039; keys) are loaded into the global &amp;quot;mapBlockIndex&amp;quot; variable.  &amp;quot;mapBlockIndex&amp;quot; is an unordered_map that holds CBlockIndex for each block in the entire block tree; not just the active chain.  &lt;br /&gt;
&lt;br /&gt;
mapBlockIndex is described in more detail in Chapter 6 - The Blockchain. &lt;br /&gt;
&lt;br /&gt;
The block file metadata (&#039;f&#039; keys) is loaded into vInfoBlockFiles.&lt;br /&gt;
&lt;br /&gt;
==The UTXO set (chainstate leveldb)==&lt;br /&gt;
&lt;br /&gt;
The UTXO database was introduced in 2012 in [https://github.com/bitcoin/bitcoin/pull/1677 pull request #1677 - &amp;quot;Ultraprune.&amp;quot;]&lt;br /&gt;
&lt;br /&gt;
The idea behind &amp;quot;Ultraprune&amp;quot; is to reduce the size of (prune) the set of past transactions, keeping only those parts of past transactions that are necessary to validate later transactions.  &lt;br /&gt;
&lt;br /&gt;
Say you have a transaction T1 which takes two inputs and sends to 3 outputs: O1,O2,O3.  Two of those outputs (O1, O2) have been used as inputs in a later transaction, T2.   Once T2 has been mined, T1 only has one item of interest (O3).  There&#039;s no reason to keep T1 around in its entirety.  Instead, a slimmed-down version of T1 will suffice, consisting only of O3 (locking script and amount) and certain basic information about T1 (height, whether it is a coinbase, etc.)&lt;br /&gt;
&lt;br /&gt;
The description of ultraprune is on the specific &amp;quot;ultraprune&amp;quot; commit within the pull: &lt;br /&gt;
&lt;br /&gt;
: -------------&lt;br /&gt;
&lt;br /&gt;
: This switches bitcoin&#039;s transaction/block verification logic to use a &amp;quot;coin database&amp;quot;, which contains all unredeemed transaction output scripts, amounts and heights.&lt;br /&gt;
&lt;br /&gt;
: The name ultraprune comes from the fact that instead of a full transaction index, we only (need to) keep an index with unspent outputs. For now, the blocks themselves are kept as usual, although they are only necessary for serving, rescanning and reorganizing.&lt;br /&gt;
&lt;br /&gt;
: The basic data structures are CCoins (representing the coins of a single transaction), and CCoinsView (representing a state of the coins database).  There are several implementations for CCoinsView. A dummy, one backed by the coins database (coins.dat), one backed by the memory pool, and one that adds a cache on top of it. FetchInputs, ConnectInputs, ConnectBlock, DisconnectBlock, ... now operate on a generic CCoinsView.&amp;lt;br&amp;gt;&amp;lt;br&amp;gt;The block switching logic now builds a single cached CCoinsView with changes to be committed to the database before any changes are made. This means no uncommitted changes are ever read from the database, and should ease the transition to another database layer which does not support transactions (but does support atomic writes), like LevelDB.&lt;br /&gt;
&lt;br /&gt;
: For the getrawtransaction() RPC call, access to a txid-to-disk index would be preferable. As this index is not necessary or even useful for any other part of the implementation, it is not provided. Instead, getrawtransaction() uses the coin database to find the block height, and then scans that block to find the requested transaction. This is slow, but should suffice for debug purposes.&lt;br /&gt;
&lt;br /&gt;
: -----------------&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
See:  [https://github.com/sipa/bitcoin/commit/450cbb0944cd20a06ce806e6679a1f4c83c50db2 Ultraprune - July 2012]&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Terminology&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
&amp;quot;UTXO (Unspent Transaction Out):&amp;quot;  An output from a transaction.  This is colloquially referred to as a &amp;quot;coin.&amp;quot;  For this reason, the UTXO db is sometimes referred to as the &amp;quot;coins database.&amp;quot;&lt;br /&gt;
&lt;br /&gt;
&amp;quot;UTXO set / coins database / chainstate database:&amp;quot;  These terms are more or less synonymous and are used interchangeably.  &lt;br /&gt;
&lt;br /&gt;
&amp;quot;Provably Unspendable:&amp;quot;  A coin is provably unspendable if its scriptPubKey cannot be satisfied - for example, an OP_RETURN.  A provably unspendable coin can be eliminated from the utxo database regardless of its amount. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Key-value pairs&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The records in the chainstate levelDB are: &lt;br /&gt;
&lt;br /&gt;
    &#039;c&#039; + 32-byte transaction hash -&amp;gt; unspent transaction output record for that transaction. These records are only present for transactions that have at least one unspent output left. Each record stores:&lt;br /&gt;
        * The version of the transaction.&lt;br /&gt;
        * Whether the transaction was a coinbase or not.&lt;br /&gt;
        * Which height block contains the transaction.&lt;br /&gt;
        * Which outputs of that transaction are unspent.&lt;br /&gt;
        * The scriptPubKey and amount for those unspent outputs.&amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
    &#039;B&#039; -&amp;gt; 32-byte block hash: the block hash up to which the database represents the unspent transaction outputs.&lt;br /&gt;
&lt;br /&gt;
See here: [http://bitcoin.stackexchange.com/questions/28168/what-are-the-keys-used-in-the-blockchain-leveldb-ie-what-are-the-keyvalue-pair StackExchange post by Pieter Wuille (2014)]&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Data Access Layer and Caching&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Access to the UTXO database is considerably more complex than the block index.   This is because its performance is critical to the overall performance of the Bitcoin system.  The block index is not so critical to performance because there are only a few hundred thousand blocks and a node running on decent hardware can retrieve and scroll through them in a few seconds (and does not need to do so very often.)  On the other hand, there are millions of coins in the UTXO database and they must be checked and modified for each input of each transaction going into the mempool or included in a block. &lt;br /&gt;
&lt;br /&gt;
As sipa said in the ultraprune commit: &lt;br /&gt;
: The basic data structures are CCoins (representing the coins of a single transaction), and CCoinsView (representing a state of the coins database).  There are several implementations for CCoinsView. A dummy, one backed by the coins database (coins.dat), one backed by the memory pool, and one that adds a cache on top of it.&lt;br /&gt;
&lt;br /&gt;
This is not stated as clearly as it might have been, however; at least, not for the current state of the code.  &lt;br /&gt;
&lt;br /&gt;
In 0.11, the instantiations of the CoinsView are:  &lt;br /&gt;
* dummy&lt;br /&gt;
* database&lt;br /&gt;
* pCoinsTip (a cache backed by the database)&lt;br /&gt;
* &amp;quot;validation cache&amp;quot; (used when  backed by pCoinsTip, in use when connecting a block)  &lt;br /&gt;
&lt;br /&gt;
Separate from that chain of caches is the memory pool&#039;s CoinsView, which is backed by the database. &lt;br /&gt;
&lt;br /&gt;
    &lt;br /&gt;
The &amp;lt;i&amp;gt;class diagram&amp;lt;/i&amp;gt; (data types) for the views is: &lt;br /&gt;
&lt;br /&gt;
       CCoinsView (abstract class)&lt;br /&gt;
              /            \&lt;br /&gt;
          ViewDB          ViewBacked &lt;br /&gt;
       (database)          /      \&lt;br /&gt;
                    ViewMempool   ViewCache&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Each class has one key characteristic: &lt;br /&gt;
* View is the base class, declaring methods for verifying that coins exist (HaveCoins), retrieving coins (GetCoins), etc. &lt;br /&gt;
* ViewDB has code to interact with the LevelDB. &lt;br /&gt;
* ViewBacked has a pointer to another View;  thus it is &amp;quot;backed&amp;quot; by another view (version) of the UTXO set. &lt;br /&gt;
* ViewCache has a cache (a map of CCoins). &lt;br /&gt;
* ViewMempool associates a mempool with a view. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Those are the defined classes; whereas the &amp;lt;i&amp;gt;object diagram&amp;lt;/i&amp;gt; is: &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
             Database       &lt;br /&gt;
            /       \&lt;br /&gt;
        MemPool     Blockchain cache (pcoinsTip) &lt;br /&gt;
      View/Cache            \&lt;br /&gt;
                          Validation cache&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here is a table summarizing the instantiations of Views: &lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! Object !! Type !! Backed By? !! Description / Purpose&lt;br /&gt;
|-&lt;br /&gt;
| DB view || ViewDB || n/a || Represents the UTXO set according to the /chainstate LevelDB.  Retrieves coins and flushes changes to the LevelDB.&amp;lt;br&amp;gt;Creation in code (instantiation):  see &amp;lt;u&amp;gt;init.cpp:1131&amp;lt;/u&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| pCoinsTip&amp;lt;br&amp;gt;(blockchain cache) || ViewCache || DB view || Holds the UTXO set corresponding to the active chain&#039;s tip.  Retrieves/flushes to the database view.&amp;lt;br&amp;gt;Creation in code:  see &amp;lt;u&amp;gt;init.cpp:1133&amp;lt;/u&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| Validation cache || ViewCache || pCoinsTip || This cache&#039;s lifetime is within ConnectTip (or DisconnectTip).&amp;lt;br&amp;gt;Its purpose is to keep track of modifications to the UTXO set while processing a block.&amp;lt;br&amp;gt;If the block validates, the cache is flushed to pcoinsTip.&amp;lt;br&amp;gt;If the block fails, the cache is discarded. &amp;lt;br&amp;gt;Creation in code:  see &amp;lt;u&amp;gt;main.cpp:2231&amp;lt;/u&amp;gt;:  CCoinsViewCache view(pcoinsTip);&lt;br /&gt;
|-&lt;br /&gt;
| Mempool view || ViewMemPool || pCoinsTip || This object brings the mempool into view, meaning it can see both a UTXO set and the mempool.&amp;lt;br&amp;gt;Its purpose is to enable validation of chains of transactions, a.k.a. &amp;quot;zero-confirmation&amp;quot; transactions.  (If chains of transactions weren&#039;t permitted, the mempool could simply validate against pcoinsTip.)&amp;lt;br&amp;gt;Thus, when queried, it can check if a given input can be found either in the mempool (i.e., &amp;quot;zero-conf&amp;quot;) or in the blockchain&#039;s utxo set (&amp;quot;confirmed.&amp;quot;)&amp;lt;br&amp;gt;Note that this object is not a cache; rather, it is a view that is used by the object below, which does contain a cache.  &amp;lt;br&amp;gt;Creation in code: Its lifetime is that of AcceptToMemoryPool in &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt;.&lt;br /&gt;
|-&lt;br /&gt;
| Mempool cache || ViewCache || Mempool view || The cache for the mempool.  It contains a cache and sets its backend to be the mempool view.&amp;lt;br&amp;gt;Creation in code: Its lifetime is also that of AcceptToMemoryPool in &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt;. &lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Loading the UTXO set&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Access to the coins database is initialized in &amp;lt;u&amp;gt;init.cpp&amp;lt;/u&amp;gt;: 1131-1133: &lt;br /&gt;
&lt;br /&gt;
 pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex);&lt;br /&gt;
 pcoinscatcher = new CCoinsViewErrorCatcher(pcoinsdbview);&lt;br /&gt;
 pcoinsTip = new CCoinsViewCache(pcoinscatcher);&lt;br /&gt;
&lt;br /&gt;
The code starts by initializing a CoinsViewDB, which is equipped with methods to load coins from the LevelDB. &amp;lt;br&amp;gt;&lt;br /&gt;
The error catcher is a little hack that can be ignored. &amp;lt;br&amp;gt;&lt;br /&gt;
Next, the code initalizes pCoinsTip, which is the cache representing the state of the active chain, and is backed by the database view. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Cache vs. Database&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The FetchCoins function in coins.cpp demonstrates how the code uses the cache vs. the database: &lt;br /&gt;
 1   CCoinsMap::iterator it = cacheCoins.find(txid);&lt;br /&gt;
 2   if (it != cacheCoins.end())&lt;br /&gt;
 3     return it;&lt;br /&gt;
 4   CCoins tmp;&lt;br /&gt;
 5   if (!base-&amp;gt;GetCoins(txid, tmp))&lt;br /&gt;
 6     return cacheCoins.end();&lt;br /&gt;
 7   CCoinsMap::iterator ret = cacheCoins.insert(std::make_pair(txid, CCoinsCacheEntry())).first;&lt;br /&gt;
&lt;br /&gt;
First, the code searches the cache for the coins for a given transaction id. (line 1)&amp;lt;br&amp;gt;&lt;br /&gt;
If found, it returns the &amp;quot;fetched&amp;quot; coins. (lines 2-3) &amp;lt;br&amp;gt;&lt;br /&gt;
If not, it searches the database. (line 5) &amp;lt;br&amp;gt;&lt;br /&gt;
If found in the database, it updates the cache. (line 7) &amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
Note:  if the cache&#039;s backend is another cache, then the term &amp;quot;database&amp;quot; really means &amp;quot;parent cache.&amp;quot; &lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Flushing the Validation Cache to the Blockchain Cache&#039;&#039;  &lt;br /&gt;
&lt;br /&gt;
The validation cache is flushed to the blockchain cache after connecting a block, just before it goes out of scope.  The scope is captured in ConnectTip, and specifically, in the code block &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt;:2231-2243.  In that code block, there is a call to ConnectBlock, during which the code stores the new coins in the validation cache.  (Specifically, see UpdateCoins() in &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt;.)  At the end of the code block, the validation cache is flushed.  Since its &amp;quot;parent view&amp;quot; is also a cache (pcoinsTip, the &amp;quot;blockchain cache&amp;quot;) the code will call the parent&#039;s ViewCache::BatchWrite, which swaps the updated coin entries into its own cache.  (Polymorphism in action: Later, when the the blockchain cache flushes to the database view, the code will run CoinsViewDB::BatchWrite, the last line of which writes to the LevelDB.) &lt;br /&gt;
&lt;br /&gt;
In summary, usage of the validation cache is straightforward: it is instantiated, used, flushed, and goes out of scope in the aforementioned code block. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Flushing the Blockchain Cache to the Database&#039;&#039;  &lt;br /&gt;
&lt;br /&gt;
Flushing the validate cache was simple because the code only shuffled items between two caches in memory (of which no one is aware outside of the caching code.)  Flushing the blockchain cache to the database is a bit more complicated.  At the lowest level, the mechanics of flushing the blockchain cache (pcoinsTip) is the same as the validation cache:  the Flush() method calls BatchWrite on its backend (the &amp;quot;base&amp;quot; pointer), and in this case that means BatchWrite on the database view.  Up a level, Flush() is called from FlushStateToDisk (FSTD) - &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt;:2098.  FlushStateToDisk is invoked at a few different points, with a given &#039;&#039;mode&#039;&#039;: &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! Flush Mode !! Description !! When called&lt;br /&gt;
|-&lt;br /&gt;
| IF_NEEDED || Flush only if the cache is over its size limit. || Right after connecting (or disconnecting) a block and flushing the validation cache.&amp;lt;br&amp;gt;See ConnectTip / DisconnectTip.&lt;br /&gt;
|-&lt;br /&gt;
| ALWAYS || Flush cache. || During initialization only. &lt;br /&gt;
|-&lt;br /&gt;
| PERIODIC || Here, the code considers other data points to decide whether to flush.&amp;lt;br&amp;gt;Is the code &#039;&#039;almost&#039;&#039; over its size limit?&amp;lt;br&amp;gt;Has it been a long time since the cache was flushed?&amp;lt;br&amp;gt;If so, then proceed.|| At end of ActivateBestChain()&amp;lt;br&amp;gt;(Code comment: &amp;quot;write changes periodically to disk, after relay&amp;quot;). &lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The idea is to flush the block cache frequently (to avoid having to download a large number of blocks if the program crashes), but the coins cache infrequently (in order to maximize the benefit from the coins cache.) &lt;br /&gt;
&lt;br /&gt;
Specifically, the block cache is guaranteed to be flushed once an hour, whereas the coins cache once per day.  (See here:  [https://github.com/bitcoin/bitcoin/pull/6102#issuecomment-98847663 Sipa comment on PR 6102])&lt;br /&gt;
&lt;br /&gt;
The FlushStateToDisk code is well-commented so for more info, the curious reader can check &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
==Raw undo data (rev*.dat)==&lt;br /&gt;
&lt;br /&gt;
The undo data contains the information that is necessary to disconnect or &amp;quot;roll back&amp;quot; a block: specifically, the coins that were spent by the block in question.&lt;br /&gt;
&lt;br /&gt;
So, the data being written is essentially a set of CTxOut objects.  (A CTxOut is simply an amount and a script - see &amp;lt;u&amp;gt;primitives/transaction.h&amp;lt;/u&amp;gt;:107-108).&lt;br /&gt;
&lt;br /&gt;
The matter is complicated slightly by the fact that if the coin is the last one being spent by its transaction, the undo data needs to store the transaction&#039;s metadata (the txn&#039;s block height, whether it&#039;s a coinbase, and its version.) So, if you have a transaction T with outputs O1,O2,O3 spent in that order, for O1 and O2 all that will be written to the undo file is the amount and the script.  For 03, the undo file will have the amount, the script, plus T&#039;s height and version, and whether T is a coinbase.&lt;br /&gt;
&lt;br /&gt;
The undo data is written to the raw file with the following code: &lt;br /&gt;
 fileout &amp;lt;&amp;lt; blockundo; (main.cpp:1567 [UndoWriteToDisk])&lt;br /&gt;
&lt;br /&gt;
This line of code calls the serialization function on the CBlockUndo - which is basically just a vector of coins (CTxOuts.)  Finally, a checksum is written to the undo file. The checksum  is used during initialization to verify that any undo data being checked is intact.  See [https://github.com/bitcoin/bitcoin/pull/2145 Pull 2145]&lt;br /&gt;
&lt;br /&gt;
The undo data is used when disconnecting a block.  The DisconnectBlock() code is discussed further down this wiki page in The Blockchain: Reorganizations.&lt;br /&gt;
&lt;br /&gt;
==Use of LevelDB==&lt;br /&gt;
&lt;br /&gt;
LevelDB is a key-value store that was introduced to store the block index and UTXO set (chainstate) in 2012 as part of the complex &amp;quot;Ultraprune&amp;quot; pull (PR 1677).  See here: [https://github.com/bitcoin/bitcoin/pull/1677/commits the 27 commits on Ultraprune]. &lt;br /&gt;
&lt;br /&gt;
On the subject of why LevelDB is used, core developer Greg Maxwell stated the following to the [http://bitcoin-development.narkive.com/XAPoxKZU/patch-switching-bitcoin-core-to-sqlite-db bitcoin-dev mailing list in October 2015]: &lt;br /&gt;
&lt;br /&gt;
:: I think people are falling into a trap of thinking &amp;quot;It&#039;s a &amp;lt;database&amp;gt;, I know a &amp;lt;black box&amp;gt; for that!&amp;quot;; but the application and needs are very specialized here. . . It just so happens that on the back of the very bitcoin specific cryptographic consensus algorithim there was a slot where a pre-existing high performance key-value store fit; and so we&#039;re using one and saving ourselves some effort... &lt;br /&gt;
&lt;br /&gt;
One might ask whether different nodes could use different databases - as long as they retrieve the same data, what&#039;s the difference? The issue here is &amp;quot;bug-for-bug compatibility&amp;quot; - if one database has a bug that causes records to not be returned under certain circumstances, then all other nodes bst have the same bug, else the network could fork as a result.  &lt;br /&gt;
&lt;br /&gt;
Greg Maxwell stated the following in [http://bitcoin-development.narkive.com/XAPoxKZU/patch-switching-bitcoin-core-to-sqlite-db the same thread referenced above (in response to a proposal to switch to using sqlite)]: &lt;br /&gt;
&lt;br /&gt;
:: ...[D]atabases sometimes have errors which cause them to fail to return records, or to return stale data. And if those exist consistency must be maintained; and &amp;quot;fixing&amp;quot; the bug can cause a divergence in consensus state that could open users up to theft.&lt;br /&gt;
&lt;br /&gt;
:: Case in point, prior to leveldb&#039;s use in Bitcoin Core it had a bug that, under rare conditions, could cause it to consistently return not found on records that were really there. . . Leveldb fixed this serious bug in a minor update.  But deploying a fix like this in an uncontrolled manner in the bitcoin network would potentially cause a fork in the consensus state; so any such fix would need to be rolled out in an orderly manner.&lt;br /&gt;
&lt;br /&gt;
[[Category:Technical]]&lt;br /&gt;
[[Category:Developer]]&lt;/div&gt;</summary>
		<author><name>Mrbandrews</name></author>
	</entry>
	<entry>
		<id>https://en.bitcoin.it/w/index.php?title=Bitcoin_Core_0.11_(ch_2):_Data_Storage&amp;diff=59979</id>
		<title>Bitcoin Core 0.11 (ch 2): Data Storage</title>
		<link rel="alternate" type="text/html" href="https://en.bitcoin.it/w/index.php?title=Bitcoin_Core_0.11_(ch_2):_Data_Storage&amp;diff=59979"/>
		<updated>2016-01-13T21:25:08Z</updated>

		<summary type="html">&lt;p&gt;Mrbandrews: added categories&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
This page describes how &amp;amp; where Bitcoin stores blockchain data. &lt;br /&gt;
&lt;br /&gt;
==Overview==&lt;br /&gt;
&lt;br /&gt;
There are basically four pieces of data that are maintained:&lt;br /&gt;
&lt;br /&gt;
: &#039;&#039;&#039;blocks/blk*.dat:&#039;&#039;&#039; the actual Bitcoin blocks, in network format, dumped in raw on disk. They are only needed for rescanning missing transactions in a wallet, reorganizing to a different part of the chain, and serving the block data to other nodes that are synchronizing.&lt;br /&gt;
&lt;br /&gt;
: &#039;&#039;&#039;blocks/index/*:&#039;&#039;&#039; this is a LevelDB database that contains metadata about all known blocks, and where to find them on disk. Without this, finding a block would be very slow.&lt;br /&gt;
&lt;br /&gt;
: &#039;&#039;&#039;chainstate/*:&#039;&#039;&#039; this is a LevelDB database with a compact representation of all currently unspent transaction outputs and some metadata about the transactions they are from. The data here is necessary for validating new incoming blocks and transactions. It can theoretically be rebuilt from the block data (see the -reindex command line option), but this takes a rather long time. Without it, you could still theoretically do validation indeed, but it would mean a full scan through the blocks (7 GB as of may 2013) for every output being spent.&lt;br /&gt;
&lt;br /&gt;
: &#039;&#039;&#039;blocks/rev*.dat:&#039;&#039;&#039; these contain &amp;quot;undo&amp;quot; data. You can see blocks as &#039;patches&#039; to the chain state (they consume some unspent outputs, and produce new ones), and see the undo data as reverse patches. They are necessary for rolling back the chainstate, which is necessary in case of reorganisations.&lt;br /&gt;
&lt;br /&gt;
Note that the LevelDB&#039;s are redundant in the sense that they can be rebuilt from the block data. But validation and other operations would become intolerably slow without them.&lt;br /&gt;
&lt;br /&gt;
See here:  [http://bitcoin.stackexchange.com/questions/11104/what-is-the-database-for?rq=1 StackExchange post by Pieter Wuille (2013)]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Raw Block data (blk*.dat)==&lt;br /&gt;
&lt;br /&gt;
Block files store the raw blocks as they were received over the network.  &lt;br /&gt;
&lt;br /&gt;
Block files are about 128 MB, allocated in 16 MB chunks to prevent excessive fragmentation.  As of October 2015, the block chain is stored in about 365 block files, for a total of about 45 GB. &lt;br /&gt;
&lt;br /&gt;
Each block file (blk1234.dat) has a corresponding undo file (rev1234.dat) which contains the data necessary to remove blocks from the blockchain in the event of a reorganization (fork). &lt;br /&gt;
&lt;br /&gt;
Info about the block files is stored in the block index (the LevelDB) in two places: &lt;br /&gt;
* General info about the files themselves is held in the &amp;quot;f&amp;quot; records in the block index LevelDB (meaning keys &amp;quot;fxxxx&amp;quot;, where &amp;quot;xxxx&amp;quot; is the 4 digit file number), including: &lt;br /&gt;
** Number of blocks stored in the file&lt;br /&gt;
** File size (and the corresponding undo file size) &lt;br /&gt;
** Lowest and highest block in the file&lt;br /&gt;
** Timestamps - earlier and latest blocks in the file&lt;br /&gt;
&lt;br /&gt;
* Info about where to find a particular block on disk is in the &amp;quot;b&amp;quot; (&amp;quot;b&amp;quot; = block) record: &lt;br /&gt;
** Each block contains a pointer to the block is on disk (a file number and an offset)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Accessing the block data files from the code&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The block files are accessed through: &lt;br /&gt;
&lt;br /&gt;
1) DiskBlockPos: a struct that is simply a pointer to a block&#039;s location on disk (a file number and an offset.) &lt;br /&gt;
&lt;br /&gt;
2) &#039;&#039;vInfoBlockFiles&#039;&#039;: a vector of BlockFileInfo objects.  This variable is used to perform such tasks as:  &lt;br /&gt;
* Determine whether new blocks can fit into the current file or a new file needs to be created&lt;br /&gt;
* Calculate the total disk usage by block &amp;amp; undo files &lt;br /&gt;
* Iterate through the block files and find ones that can be pruned&lt;br /&gt;
&lt;br /&gt;
Blocks are written to disk as soon as they are received, in AcceptBlock.  (The actual disk write operation is in WriteBlockToDisk [&amp;lt;u&amp;gt;main.cpp:1164&amp;lt;/u&amp;gt;]).  Note that there is some overlap of the code that accesses block files with the code that accesses and writes to the coins database (/chainstate).  There is a complex system of when to flush state to disk.  None of this code affects block files, which are simply written to disk when received.  Once they have been received and stored, the block files are only needed for serving blocks to other nodes. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;More info about block files&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
See here: [https://github.com/sipa/bitcoin/commit/5382bcf8cd23c36a435c29080770a79b5e28af42 the commit that puts multiple blocks in a block file (2012)]&lt;br /&gt;
&lt;br /&gt;
==Block index (leveldb)==&lt;br /&gt;
&lt;br /&gt;
The block index holds metadata about all known blocks, including where the block is stored on disk.  &lt;br /&gt;
&lt;br /&gt;
Note that the set of &amp;quot;known blocks&amp;quot; is a superset of the longest chain, because it includes blocks that were received and processed but are not part of the active chain - for example, orphaned blocks that were detached from the active chain in a small reorganization.   &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Terminology&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The terminology can be a little confusing here, because while people normally think of the &amp;quot;blockchain&amp;quot; as being synonymous with the active chain (an uninterrupted, linear chain of X blocks starting with the genesis block and continuing to the current tip), there are some places in the code where &amp;quot;blockchain&amp;quot; refers to the active chain plus the numerous, mostly short forks off the chain that our node happens to know about.  &lt;br /&gt;
&lt;br /&gt;
a) Block Tree&lt;br /&gt;
&lt;br /&gt;
A better term for the set of known blocks stored on disk is &amp;quot;block tree,&amp;quot; as this term contemplates a tree structure with numerous branches (albeit small ones) from the main chain.  Indeed, the block index LevelDB is accessed through the &amp;quot;CBlockTreeDB&amp;quot; wrapper class, defined in &amp;lt;u&amp;gt;src/txdb.h&amp;lt;/u&amp;gt;.  Note that it&#039;s perfectly fine, indeed it is expected, that different nodes would have slightly different block trees;  what matters is that they agree on the active chain.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Key-value pairs&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Inside the actual LevelDB, the used key/value pairs are:&lt;br /&gt;
&lt;br /&gt;
    &#039;b&#039; + 32-byte block hash -&amp;gt; block index record. Each record stores:&lt;br /&gt;
        * The block header&lt;br /&gt;
        * The height.&lt;br /&gt;
        * The number of transactions.&lt;br /&gt;
        * To what extent this block is validated.&lt;br /&gt;
        * In which file, and where in that file, the block data is stored.&lt;br /&gt;
        * In which file, and where in that file, the undo data is stored.&lt;br /&gt;
&lt;br /&gt;
   &#039;f&#039; + 4-byte file number -&amp;gt; file information record. Each record stores:&lt;br /&gt;
        * The number of blocks stored in the block file with that number.&lt;br /&gt;
        * The size of the block file with that number ($DATADIR/blocks/blkNNNNN.dat).&lt;br /&gt;
        * The size of the undo file with that number ($DATADIR/blocks/revNNNNN.dat).&lt;br /&gt;
        * The lowest and highest height of blocks stored in the block file with that number.&lt;br /&gt;
        * The lowest and highest timestamp of blocks stored in the block file with that number.&lt;br /&gt;
&lt;br /&gt;
    &#039;l&#039; -&amp;gt; 4-byte file number: the last block file number used.&lt;br /&gt;
&lt;br /&gt;
    &#039;R&#039; -&amp;gt; 1-byte boolean (&#039;1&#039; if true): whether we&#039;re in the process of reindexing.&lt;br /&gt;
&lt;br /&gt;
    &#039;F&#039; + 1-byte flag name length + flag name string -&amp;gt; 1 byte boolean (&#039;1&#039; if true, &#039;0&#039; if false): various flags that can be on or off. Currently defined flags include:&lt;br /&gt;
         * &#039;txindex&#039;: Whether the transaction index is enabled.&lt;br /&gt;
&lt;br /&gt;
    &#039;t&#039; + 32-byte transaction hash -&amp;gt; transaction index record. These are optional and only exist if &#039;txindex&#039; is enabled (see above). Each record stores:&lt;br /&gt;
        * Which block file number the transaction is stored in.&lt;br /&gt;
        * Which offset into that file the block the transaction is part of is stored at.&lt;br /&gt;
        * The offset from the start of that block to the position where that transaction itself is stored.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
See here: [http://bitcoin.stackexchange.com/questions/28168/what-are-the-keys-used-in-the-blockchain-leveldb-ie-what-are-the-keyvalue-pair StackExchange post by Pieter Wuille (2014)]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Data Access Layer&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The database is accessed through CBlockTreeDB wrapper class.  See &amp;lt;u&amp;gt;txdb.h&amp;lt;/u&amp;gt;.  &lt;br /&gt;
&lt;br /&gt;
The wrapper is instantiated in a global variable called pblocktree, defined in &amp;lt;u&amp;gt;main.cpp.&amp;lt;/u&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;CBlockIndex&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Blocks stored in the database are represented in memory as CBlockIndex objects.  An object of this type is first created after the &#039;&#039;header&#039;&#039; is received;  the code does not wait to receive the full block.  When headers are received over the network, they are streamed into a vector of CBlockHeaders, which are then checked. Each header that checks out causes a new CBlockIndex to be created, which is stored to the database. &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;CBlock / CBlockHeader&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Note that these objects have little to do with the /blocks LevelDB.  A CBlock holds the full set of transactions in the block, the data for which is stored in two places - in full, in raw format, in the blk???.dat files, and in pruned format in the UTXO database.  The block index database cares not for such details, since it holds only the metadata for the block. &lt;br /&gt;
 &lt;br /&gt;
&#039;&#039;Loading the block database into memory&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The entire database is loaded into memory on startup.  See LoadBlockIndexGuts (&amp;lt;u&amp;gt;txdb.cpp&amp;lt;/u&amp;gt;).  This only takes a few seconds. &lt;br /&gt;
&lt;br /&gt;
The blocks (&#039;b&#039; keys) are loaded into the global &amp;quot;mapBlockIndex&amp;quot; variable.  &amp;quot;mapBlockIndex&amp;quot; is an unordered_map that holds CBlockIndex for each block in the entire block tree; not just the active chain.  &lt;br /&gt;
&lt;br /&gt;
mapBlockIndex is described in more detail in Chapter 6 - The Blockchain. &lt;br /&gt;
&lt;br /&gt;
The block file metadata (&#039;f&#039; keys) is loaded into vInfoBlockFiles.&lt;br /&gt;
&lt;br /&gt;
==The UTXO set (chainstate leveldb)==&lt;br /&gt;
&lt;br /&gt;
The UTXO database was introduced in 2012 in [https://github.com/bitcoin/bitcoin/pull/1677 pull request #1677 - &amp;quot;Ultraprune.&amp;quot;]&lt;br /&gt;
&lt;br /&gt;
The idea behind &amp;quot;Ultraprune&amp;quot; is to reduce the size of (prune) the set of past transactions, keeping only those parts of past transactions that are necessary to validate later transactions.  &lt;br /&gt;
&lt;br /&gt;
Say you have a transaction T1 which takes two inputs and sends to 3 outputs: O1,O2,O3.  Two of those outputs (O1, O2) have been used as inputs in a later transaction, T2.   Once T2 has been mined, T1 only has one item of interest (O3).  There&#039;s no reason to keep T1 around in its entirety.  Instead, a slimmed-down version of T1 will suffice, consisting only of O3 (locking script and amount) and certain basic information about T1 (height, whether it is a coinbase, etc.)&lt;br /&gt;
&lt;br /&gt;
The description of ultraprune is on the specific &amp;quot;ultraprune&amp;quot; commit within the pull: &lt;br /&gt;
&lt;br /&gt;
: -------------&lt;br /&gt;
&lt;br /&gt;
: This switches bitcoin&#039;s transaction/block verification logic to use a &amp;quot;coin database&amp;quot;, which contains all unredeemed transaction output scripts, amounts and heights.&lt;br /&gt;
&lt;br /&gt;
: The name ultraprune comes from the fact that instead of a full transaction index, we only (need to) keep an index with unspent outputs. For now, the blocks themselves are kept as usual, although they are only necessary for serving, rescanning and reorganizing.&lt;br /&gt;
&lt;br /&gt;
: The basic data structures are CCoins (representing the coins of a single transaction), and CCoinsView (representing a state of the coins database).  There are several implementations for CCoinsView. A dummy, one backed by the coins database (coins.dat), one backed by the memory pool, and one that adds a cache on top of it. FetchInputs, ConnectInputs, ConnectBlock, DisconnectBlock, ... now operate on a generic CCoinsView.&amp;lt;br&amp;gt;&amp;lt;br&amp;gt;The block switching logic now builds a single cached CCoinsView with changes to be committed to the database before any changes are made. This means no uncommitted changes are ever read from the database, and should ease the transition to another database layer which does not support transactions (but does support atomic writes), like LevelDB.&lt;br /&gt;
&lt;br /&gt;
: For the getrawtransaction() RPC call, access to a txid-to-disk index would be preferable. As this index is not necessary or even useful for any other part of the implementation, it is not provided. Instead, getrawtransaction() uses the coin database to find the block height, and then scans that block to find the requested transaction. This is slow, but should suffice for debug purposes.&lt;br /&gt;
&lt;br /&gt;
: -----------------&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
See:  [https://github.com/sipa/bitcoin/commit/450cbb0944cd20a06ce806e6679a1f4c83c50db2 Ultraprune - July 2012]&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Terminology&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
&amp;quot;UTXO (Unspent Transaction Out):&amp;quot;  An output from a transaction.  This is colloquially referred to as a &amp;quot;coin.&amp;quot;  For this reason, the UTXO db is sometimes referred to as the &amp;quot;coins database.&amp;quot;&lt;br /&gt;
&lt;br /&gt;
&amp;quot;UTXO set / coins database / chainstate database:&amp;quot;  These terms are more or less synonymous and are used interchangeably.  &lt;br /&gt;
&lt;br /&gt;
&amp;quot;Provably Unspendable:&amp;quot;  A coin is provably unspendable if its scriptPubKey cannot be satisfied - for example, an OP_RETURN.  A provably unspendable coin can be eliminated from the utxo database regardless of its amount. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Key-value pairs&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The records in the chainstate levelDB are: &lt;br /&gt;
&lt;br /&gt;
    &#039;c&#039; + 32-byte transaction hash -&amp;gt; unspent transaction output record for that transaction. These records are only present for transactions that have at least one unspent output left. Each record stores:&lt;br /&gt;
        * The version of the transaction.&lt;br /&gt;
        * Whether the transaction was a coinbase or not.&lt;br /&gt;
        * Which height block contains the transaction.&lt;br /&gt;
        * Which outputs of that transaction are unspent.&lt;br /&gt;
        * The scriptPubKey and amount for those unspent outputs.&amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
    &#039;B&#039; -&amp;gt; 32-byte block hash: the block hash up to which the database represents the unspent transaction outputs.&lt;br /&gt;
&lt;br /&gt;
See here: [http://bitcoin.stackexchange.com/questions/28168/what-are-the-keys-used-in-the-blockchain-leveldb-ie-what-are-the-keyvalue-pair StackExchange post by Pieter Wuille (2014)]&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Data Access Layer and Caching&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Access to the UTXO database is considerably more complex than the block index.   This is because its performance is critical to the overall performance of the Bitcoin system.  The block index is not so critical to performance because there are only a few hundred thousand blocks and a node running on decent hardware can retrieve and scroll through them in a few seconds (and does not need to do so very often.)  On the other hand, there are millions of coins in the UTXO database and they must be checked and modified for each input of each transaction going into the mempool or included in a block. &lt;br /&gt;
&lt;br /&gt;
As sipa said in the ultraprune commit: &lt;br /&gt;
: The basic data structures are CCoins (representing the coins of a single transaction), and CCoinsView (representing a state of the coins database).  There are several implementations for CCoinsView. A dummy, one backed by the coins database (coins.dat), one backed by the memory pool, and one that adds a cache on top of it.&lt;br /&gt;
&lt;br /&gt;
This is not stated as clearly as it might have been, however; at least, not for the current state of the code.  &lt;br /&gt;
&lt;br /&gt;
In 0.11, the instantiations of the CoinsView are:  &lt;br /&gt;
* dummy&lt;br /&gt;
* database&lt;br /&gt;
* pCoinsTip (a cache backed by the database)&lt;br /&gt;
* &amp;quot;validation cache&amp;quot; (used when  backed by pCoinsTip, in use when connecting a block)  &lt;br /&gt;
&lt;br /&gt;
Separate from that chain of caches is the memory pool&#039;s CoinsView, which is backed by the database. &lt;br /&gt;
&lt;br /&gt;
    &lt;br /&gt;
The &amp;lt;i&amp;gt;class diagram&amp;lt;/i&amp;gt; (data types) for the views is: &lt;br /&gt;
&lt;br /&gt;
       CCoinsView (abstract class)&lt;br /&gt;
              /            \&lt;br /&gt;
          ViewDB          ViewBacked &lt;br /&gt;
       (database)          /      \&lt;br /&gt;
                    ViewMempool   ViewCache&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Each class has one key characteristic: &lt;br /&gt;
* View is the base class, declaring methods for verifying that coins exist (HaveCoins), retrieving coins (GetCoins), etc. &lt;br /&gt;
* ViewDB has code to interact with the LevelDB. &lt;br /&gt;
* ViewBacked has a pointer to another View;  thus it is &amp;quot;backed&amp;quot; by another view (version) of the UTXO set. &lt;br /&gt;
* ViewCache has a cache (a map of CCoins). &lt;br /&gt;
* ViewMempool associates a mempool with a view. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Those are the defined classes; whereas the &amp;lt;i&amp;gt;object diagram&amp;lt;/i&amp;gt; is: &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
             Database       &lt;br /&gt;
            /       \&lt;br /&gt;
        MemPool     Blockchain cache (pcoinsTip) &lt;br /&gt;
      View/Cache            \&lt;br /&gt;
                          Validation cache&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here is a table summarizing the instantiations of Views: &lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! Object !! Type !! Backed By? !! Description / Purpose&lt;br /&gt;
|-&lt;br /&gt;
| DB view || ViewDB || n/a || Represents the UTXO set according to the /chainstate LevelDB.  Retrieves coins and flushes changes to the LevelDB.&amp;lt;br&amp;gt;Creation in code (instantiation):  see &amp;lt;u&amp;gt;init.cpp:1131&amp;lt;/u&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| pCoinsTip&amp;lt;br&amp;gt;(blockchain cache) || ViewCache || DB view || Holds the UTXO set corresponding to the active chain&#039;s tip.  Retrieves/flushes to the database view.&amp;lt;br&amp;gt;Creation in code:  see &amp;lt;u&amp;gt;init.cpp:1133&amp;lt;/u&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| Validation cache || ViewCache || pCoinsTip || This cache&#039;s lifetime is within ConnectTip (or DisconnectTip).&amp;lt;br&amp;gt;Its purpose is to keep track of modifications to the UTXO set while processing a block.&amp;lt;br&amp;gt;If the block validates, the cache is flushed to pcoinsTip.&amp;lt;br&amp;gt;If the block fails, the cache is discarded. &amp;lt;br&amp;gt;Creation in code:  see &amp;lt;u&amp;gt;main.cpp:2231&amp;lt;/u&amp;gt;:  CCoinsViewCache view(pcoinsTip);&lt;br /&gt;
|-&lt;br /&gt;
| Mempool view || ViewMemPool || pCoinsTip || This object brings the mempool into view, meaning it can see both a UTXO set and the mempool.&amp;lt;br&amp;gt;Its purpose is to enable validation of chains of transactions, a.k.a. &amp;quot;zero-confirmation&amp;quot; transactions.  (If chains of transactions weren&#039;t permitted, the mempool could simply validate against pcoinsTip.)&amp;lt;br&amp;gt;Thus, when queried, it can check if a given input can be found either in the mempool (i.e., &amp;quot;zero-conf&amp;quot;) or in the blockchain&#039;s utxo set (&amp;quot;confirmed.&amp;quot;)&amp;lt;br&amp;gt;Note that this object is not a cache; rather, it is a view that is used by the object below, which does contain a cache.  &amp;lt;br&amp;gt;Creation in code: Its lifetime is that of AcceptToMemoryPool in &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt;.&lt;br /&gt;
|-&lt;br /&gt;
| Mempool cache || ViewCache || Mempool view || The cache for the mempool.  It contains a cache and sets its backend to be the mempool view.&amp;lt;br&amp;gt;Creation in code: Its lifetime is also that of AcceptToMemoryPool in &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt;. &lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Loading the UTXO set&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Access to the coins database is initialized in &amp;lt;u&amp;gt;init.cpp&amp;lt;/u&amp;gt;: 1131-1133: &lt;br /&gt;
&lt;br /&gt;
 pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex);&lt;br /&gt;
 pcoinscatcher = new CCoinsViewErrorCatcher(pcoinsdbview);&lt;br /&gt;
 pcoinsTip = new CCoinsViewCache(pcoinscatcher);&lt;br /&gt;
&lt;br /&gt;
The code starts by initializing a CoinsViewDB, which is equipped with methods to load coins from the LevelDB. &amp;lt;br&amp;gt;&lt;br /&gt;
The error catcher is a little hack that can be ignored. &amp;lt;br&amp;gt;&lt;br /&gt;
Next, the code initalizes pCoinsTip, which is the cache representing the state of the active chain, and is backed by the database view. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Cache vs. Database&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The FetchCoins function in coins.cpp demonstrates how the code uses the cache vs. the database: &lt;br /&gt;
 1   CCoinsMap::iterator it = cacheCoins.find(txid);&lt;br /&gt;
 2   if (it != cacheCoins.end())&lt;br /&gt;
 3     return it;&lt;br /&gt;
 4   CCoins tmp;&lt;br /&gt;
 5   if (!base-&amp;gt;GetCoins(txid, tmp))&lt;br /&gt;
 6     return cacheCoins.end();&lt;br /&gt;
 7   CCoinsMap::iterator ret = cacheCoins.insert(std::make_pair(txid, CCoinsCacheEntry())).first;&lt;br /&gt;
&lt;br /&gt;
First, the code searches the cache for the coins for a given transaction id. (line 1)&amp;lt;br&amp;gt;&lt;br /&gt;
If found, it returns the &amp;quot;fetched&amp;quot; coins. (lines 2-3) &amp;lt;br&amp;gt;&lt;br /&gt;
If not, it searches the database. (line 5) &amp;lt;br&amp;gt;&lt;br /&gt;
If found in the database, it updates the cache. (line 7) &amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
Note:  if the cache&#039;s backend is another cache, then the term &amp;quot;database&amp;quot; really means &amp;quot;parent cache.&amp;quot; &lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Flushing the Validation Cache to the Blockchain Cache&#039;&#039;  &lt;br /&gt;
&lt;br /&gt;
The validation cache is flushed to the blockchain cache after connecting a block, just before it goes out of scope.  The scope is captured in ConnectTip, and specifically, in the code block &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt;:2231-2243.  In that code block, there is a call to ConnectBlock, during which the code stores the new coins in the validation cache.  (Specifically, see UpdateCoins() in &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt;.)  At the end of the code block, the validation cache is flushed.  Since its &amp;quot;parent view&amp;quot; is also a cache (pcoinsTip, the &amp;quot;blockchain cache&amp;quot;) the code will call the parent&#039;s ViewCache::BatchWrite, which swaps the updated coin entries into its own cache.  (Polymorphism in action: Later, when the the blockchain cache flushes to the database view, the code will run CoinsViewDB::BatchWrite, the last line of which writes to the LevelDB.) &lt;br /&gt;
&lt;br /&gt;
In summary, usage of the validation cache is straightforward: it is instantiated, used, flushed, and goes out of scope in the aforementioned code block. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Flushing the Blockchain Cache to the Database&#039;&#039;  &lt;br /&gt;
&lt;br /&gt;
Flushing the validate cache was simple because the code only shuffled items between two caches in memory (of which no one is aware outside of the caching code.)  Flushing the blockchain cache to the database is a bit more complicated.  At the lowest level, the mechanics of flushing the blockchain cache (pcoinsTip) is the same as the validation cache:  the Flush() method calls BatchWrite on its backend (the &amp;quot;base&amp;quot; pointer), and in this case that means BatchWrite on the database view.  Up a level, Flush() is called from FlushStateToDisk (FSTD) - &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt;:2098.  FlushStateToDisk is invoked at a few different points, with a given &#039;&#039;mode&#039;&#039;: &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! Flush Mode !! Description !! When called&lt;br /&gt;
|-&lt;br /&gt;
| IF_NEEDED || Flush only if the cache is over its size limit. || Right after connecting (or disconnecting) a block and flushing the validation cache.&amp;lt;br&amp;gt;See ConnectTip / DisconnectTip.&lt;br /&gt;
|-&lt;br /&gt;
| ALWAYS || Flush cache. || During initialization only. &lt;br /&gt;
|-&lt;br /&gt;
| PERIODIC || Here, the code considers other data points to decide whether to flush.&amp;lt;br&amp;gt;Is the code &#039;&#039;almost&#039;&#039; over its size limit?&amp;lt;br&amp;gt;Has it been a long time since the cache was flushed?&amp;lt;br&amp;gt;If so, then proceed.|| At end of ActivateBestChain()&amp;lt;br&amp;gt;(Code comment: &amp;quot;write changes periodically to disk, after relay&amp;quot;). &lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The idea is to flush the block cache frequently (to avoid having to download a large number of blocks if the program crashes), but the coins cache infrequently (in order to maximize the benefit from the coins cache.) &lt;br /&gt;
&lt;br /&gt;
Specifically, the block cache is guaranteed to be flushed once an hour, whereas the coins cache once per day.  (See here:  [https://github.com/bitcoin/bitcoin/pull/6102#issuecomment-98847663 Sipa comment on PR 6102])&lt;br /&gt;
&lt;br /&gt;
The FlushStateToDisk code is well-commented so for more info, the curious reader can check &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
==Raw undo data (rev*.dat)==&lt;br /&gt;
&lt;br /&gt;
The undo data contains the information that is necessary to disconnect or &amp;quot;roll back&amp;quot; a block: specifically, the coins that were spent by the block in question.&lt;br /&gt;
&lt;br /&gt;
So, the data being written is essentially a set of CTxOut objects.  (A CTxOut is simply an amount and a script - see &amp;lt;u&amp;gt;primitives/transaction.h&amp;lt;/u&amp;gt;:107-108).&lt;br /&gt;
&lt;br /&gt;
The matter is complicated slightly by the fact that if the coin is the last one being spent by its transaction, the undo data needs to store the transaction&#039;s metadata (the txn&#039;s block height, whether it&#039;s a coinbase, and its version.) So, if you have a transaction T with outputs O1,O2,O3 spent in that order, for O1 and O2 all that will be written to the undo file is the amount and the script.  For 03, the undo file will have the amount, the script, plus T&#039;s height and version, and whether T is a coinbase.&lt;br /&gt;
&lt;br /&gt;
The undo data is written to the raw file with the following code: &lt;br /&gt;
 fileout &amp;lt;&amp;lt; blockundo; (main.cpp:1567 [UndoWriteToDisk])&lt;br /&gt;
&lt;br /&gt;
This line of code calls the serialization function on the CBlockUndo - which is basically just a vector of coins (CTxOuts.)  Finally, a checksum is written to the undo file. The checksum  is used during initialization to verify that any undo data being checked is intact.  See [https://github.com/bitcoin/bitcoin/pull/2145 Pull 2145]&lt;br /&gt;
&lt;br /&gt;
The undo data is used when disconnecting a block.  The DisconnectBlock() code is discussed further down this wiki page in The Blockchain: Reorganizations.&lt;br /&gt;
&lt;br /&gt;
==Use of LevelDB==&lt;br /&gt;
&lt;br /&gt;
LevelDB is a key-value store that was introduced to store the block index and UTXO set (chainstate) in 2012 as part of the complex &amp;quot;Ultraprune&amp;quot; pull (PR 1677).  See here: [https://github.com/bitcoin/bitcoin/pull/1677/commits the 27 commits on Ultraprune]. &lt;br /&gt;
&lt;br /&gt;
On the subject of why LevelDB is used, core developer Greg Maxwell stated the following to the [http://bitcoin-development.narkive.com/XAPoxKZU/patch-switching-bitcoin-core-to-sqlite-db bitcoin-dev mailing list in October 2015]: &lt;br /&gt;
&lt;br /&gt;
:: I think people are falling into a trap of thinking &amp;quot;It&#039;s a &amp;lt;database&amp;gt;, I know a &amp;lt;black box&amp;gt; for that!&amp;quot;; but the application and needs are very specialized here. . . It just so happens that on the back of the very bitcoin specific cryptographic consensus algorithim there was a slot where a pre-existing high performance key-value store fit; and so we&#039;re using one and saving ourselves some effort... &lt;br /&gt;
&lt;br /&gt;
One might ask whether different nodes could use different databases - as long as they retrieve the same data, what&#039;s the difference? The issue here is &amp;quot;bug-for-bug compatibility&amp;quot; - if one database has a bug that causes records to not be returned under certain circumstances, then all other nodes bst have the same bug, else the network could fork as a result.  &lt;br /&gt;
&lt;br /&gt;
Greg Maxwell stated the following in [http://bitcoin-development.narkive.com/XAPoxKZU/patch-switching-bitcoin-core-to-sqlite-db the same thread referenced above (in response to a proposal to switch to using sqlite)]: &lt;br /&gt;
&lt;br /&gt;
:: ...[D]atabases sometimes have errors which cause them to fail to return records, or to return stale data. And if those exist consistency must be maintained; and &amp;quot;fixing&amp;quot; the bug can cause a divergence in consensus state that could open users up to theft.&lt;br /&gt;
&lt;br /&gt;
:: Case in point, prior to leveldb&#039;s use in Bitcoin Core it had a bug that, under rare conditions, could cause it to consistently return not found on records that were really there. . . Leveldb fixed this serious bug in a minor update.  But deploying a fix like this in an uncontrolled manner in the bitcoin network would potentially cause a fork in the consensus state; so any such fix would need to be rolled out in an orderly manner.&lt;br /&gt;
&lt;br /&gt;
[[Category:Technical]]&lt;br /&gt;
[[Category:Developer]]&lt;/div&gt;</summary>
		<author><name>Mrbandrews</name></author>
	</entry>
	<entry>
		<id>https://en.bitcoin.it/w/index.php?title=Bitcoin_Core_0.11_(ch_3):_Initialization_and_Startup&amp;diff=59978</id>
		<title>Bitcoin Core 0.11 (ch 3): Initialization and Startup</title>
		<link rel="alternate" type="text/html" href="https://en.bitcoin.it/w/index.php?title=Bitcoin_Core_0.11_(ch_3):_Initialization_and_Startup&amp;diff=59978"/>
		<updated>2016-01-13T21:09:10Z</updated>

		<summary type="html">&lt;p&gt;Mrbandrews: Created page with &amp;quot; This page describes the Bitcoin Core code that manages startup and initialization.   ==Program entry point==   The program&amp;#039;s entry point can be found in &amp;lt;u&amp;gt;bitcoind.cpp&amp;lt;/u&amp;gt;....&amp;quot;&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
This page describes the Bitcoin Core code that manages startup and initialization. &lt;br /&gt;
&lt;br /&gt;
==Program entry point== &lt;br /&gt;
&lt;br /&gt;
The program&#039;s entry point can be found in &amp;lt;u&amp;gt;bitcoind.cpp&amp;lt;/u&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
main() is three lines of code:&lt;br /&gt;
* SetupEnvironment() (all this does is set the program&#039;s locale)&lt;br /&gt;
* Connect signal handlers&lt;br /&gt;
* AppInit() (this function loops for the life of the program)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
AppInit:  this is located nearby in &amp;lt;u&amp;gt;bitcoind.cpp&amp;lt;/u&amp;gt;: &lt;br /&gt;
* Parses the command line&lt;br /&gt;
* Opens the data directory&lt;br /&gt;
* Reads the config file&lt;br /&gt;
* Forks a process (if running as a daemon)&lt;br /&gt;
* Passes control to AppInit2(), found in &amp;lt;u&amp;gt;init.cpp&amp;lt;/u&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Initialization steps (&amp;lt;u&amp;gt;init.cpp&amp;lt;/u&amp;gt;)==&lt;br /&gt;
&lt;br /&gt;
AppInit2() initializes the bitcoin system.  &lt;br /&gt;
&lt;br /&gt;
It contains about 800 lines of code, which are broken into 12 steps.  &lt;br /&gt;
&lt;br /&gt;
Where each step begins is documented in the code. &amp;lt;u&amp;gt;Init.cpp&amp;lt;/u&amp;gt; has a few functions at the top of the file, but for the most part it consists of AppInit2(). &lt;br /&gt;
&lt;br /&gt;
The following table summarizes the steps: &lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! Initialization&amp;lt;br&amp;gt;Step !! Short Description !! Longer Description&lt;br /&gt;
|-&lt;br /&gt;
| 1 || OS-specific setup tasks || These tasks are not particularly interesting.&amp;lt;br&amp;gt;For more info, see the code.  &lt;br /&gt;
|-&lt;br /&gt;
| 2 || Parameter Interactions || Certain command-line options require other options to be set in a certain way.&amp;lt;br&amp;gt;For example, -zapwallettxes implies a -rescan, thus the code will set the -rescan flag=true if it isn&#039;t already.  &lt;br /&gt;
|-&lt;br /&gt;
| 3 || Internal flags / &amp;lt;br&amp;gt;Parameter sanity-check || Sets global variables for certain parameters.&amp;lt;br&amp;gt;For the wallet, it sanity-checks transaction fee levels (makes sure your fee is high enough to qualify for relay [error]; but not absurdly high [warning]).  &lt;br /&gt;
|-&lt;br /&gt;
| 4 || Application init. / RPC Server || &lt;br /&gt;
Locks the data directory.  (If unable, print error and quit.)&amp;lt;br&amp;gt;&lt;br /&gt;
Spawn X threads for the Script-checking engine. (Default=0, meaning use all available processors; boost::thread::hardware_concurrency).&amp;lt;br&amp;gt;&lt;br /&gt;
Start RPC server in &amp;quot;warmup&amp;quot; mode. &lt;br /&gt;
|-&lt;br /&gt;
| 5 || Verify wallet database integrity || If wallet is enabled, try to open it.&amp;lt;br&amp;gt;&lt;br /&gt;
If the user knows that the wallet has been corrupted (-salvagewallet), try to recover the private keys.  &lt;br /&gt;
|-&lt;br /&gt;
| 6 || Network Initialization || &lt;br /&gt;
The node registers for certain signals.&amp;lt;br&amp;gt;&lt;br /&gt;
Checks whether the user wants to interact only with peers on a certain network (ip4, ip6, tor).&amp;lt;br&amp;gt;&lt;br /&gt;
Checks whether to use onion routing (tor).&amp;lt;br&amp;gt;&lt;br /&gt;
Checks whether the user wants to whitelist any specific peers.&amp;lt;br&amp;gt;&lt;br /&gt;
Attempts to listen on the bitcoin port (exits on failure).&amp;lt;br&amp;gt;&lt;br /&gt;
If user specified a certain peer to seed connections, attempt to connect.  &lt;br /&gt;
|-&lt;br /&gt;
| 7 || Load the block chain. || &lt;br /&gt;
Load the blockchain into memory and initialize the UTXO caches.&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;u&amp;gt;Calculate cache sizes.&amp;lt;/u&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
There is a total cache size, which is divided amongst three specific caches.&amp;lt;br&amp;gt; &lt;br /&gt;
Default total cache size = 100MB (Max: 4 GB, min: 4 MB).&amp;lt;br&amp;gt;  &lt;br /&gt;
1) Blockchain cache:  1/8 of the total cache, but shouldn&#039;t be larger than 2MB.&amp;lt;br&amp;gt;&lt;br /&gt;
2) UTXO database cache : 25-50% of the remaining cache space.  This is the LevelDB cache.&amp;lt;br&amp;gt;&lt;br /&gt;
This stores uncompressed blocks of LevelDB data and is managed by LevelDB, as described in [http://leveldb.googlecode.com/git-history/1.17/doc/index.html the LevelDB documentation.]&amp;lt;br&amp;gt;&lt;br /&gt;
3) UTXO in-memory cache: Half of the remaining cache space.&amp;lt;br&amp;gt;&lt;br /&gt;
This cache size defines the size of the cacheCoins object (a protected member of CoinsViewCache).&amp;lt;br&amp;gt;&lt;br /&gt;
TODO: verify that this statement is correct... &amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;u&amp;gt;Load the blockchain into mapBlockIndex.&amp;lt;/u&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
By &amp;quot;blockchain&amp;quot; this means the entire block tree (all known blocks, not just those in the active chain.)&amp;lt;br&amp;gt;&lt;br /&gt;
What is loaded into memory are the CBlockIndex objects, which contain metadata about the block. &amp;lt;br&amp;gt;&lt;br /&gt;
Verifies the last 288 blocks (VerifyDB).&amp;lt;br&amp;gt;&lt;br /&gt;
Note: The program takes less than 1 second from startup until this point;  this step takes about 10-20 seconds.&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;u&amp;gt;The UTXO set.&amp;lt;/u&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
The UTXO set is not loaded into memory; instead, the cache will be filled as coins are accessed from the database.&amp;lt;br&amp;gt;&lt;br /&gt;
Note that as of May 2015, storing the entire UTXO set in memory would require about 3.6 GB.&amp;lt;br&amp;gt;&lt;br /&gt;
As of Jan. 2016, the compressed data on disk is about 1.2 GB. &lt;br /&gt;
|-&lt;br /&gt;
| 8 || Load the wallet.  || If this is the first time the program has been run, it creates a wallet and gives you an initial key (address).&lt;br /&gt;
|-&lt;br /&gt;
| 9 || Datadir maintenance || If the user is block-pruning, unset NODE_NETWORK and call the pruning function.&lt;br /&gt;
|-&lt;br /&gt;
| 10 || Import blocks || Scan for better chains in the block chain database, that are not yet connected as the active best chain.&lt;br /&gt;
|-&lt;br /&gt;
| 11 || Start node /&amp;lt;br&amp;gt;RPC server || &lt;br /&gt;
Calls StartNode in net.cpp.&amp;lt;br&amp;gt;&lt;br /&gt;
This starts up the networking thread group, including ThreadProcessMessage, which is the program&#039;s main thread (see below). &amp;lt;br&amp;gt;&lt;br /&gt;
Transition RPC server from &amp;quot;warmup&amp;quot; mode to normal mode.&lt;br /&gt;
|-&lt;br /&gt;
| 12 || Finished&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
When AppInit2 finishes, control returns to AppInit() in &amp;lt;u&amp;gt;bitcoind.cpp&amp;lt;/u&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
There, the code&#039;s top-level thread loops indefinitely in a function called WaitForShutdown().  It sleeps for 2 seconds and checks to see if the user pressed ctrl-C.  If so, it calls Shutdown() back in &amp;lt;u&amp;gt;init.cpp&amp;lt;/u&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Shutdown() shuts down the RPC server, stops the node, unregisters the signal handlers, etc., and then the program completes.&lt;br /&gt;
&lt;br /&gt;
==Cache Sizes==&lt;br /&gt;
&lt;br /&gt;
Step 7 initialized the cache sizes.  There are 3 caches contemplated in step 7.  Two are LevelDB database caches and the other is the coins cache, whose size is managed by the flushing code in &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt;. &lt;br /&gt;
&lt;br /&gt;
The user can allocate a total cache size with -dbcache.  The user cannot pick and choose how much space to allocate to each specific cache. The default total cache size = 100MB (Max: 4 GB, min: 4 MB).  &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;1) Block index cache&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
This cache stores uncompressed chunks of the /blocks/index LevelDB data and is managed by LevelDB, as described in [http://leveldb.googlecode.com/git-history/1.17/doc/index.html the LevelDB documentation.]&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the user enables a full transaction index (-txindex=1) it can be up to 1/8 of the total cache size.  If -txindex is not enabled then only 2 MiB is needed. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;2) UTXO database cache&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
This is the LevelDB cache for the /chainstate database. &lt;br /&gt;
&lt;br /&gt;
This cache is allocated 25-50% of the remaining cache space, depending on the total cache size. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;3)  UTXO in-memory cache&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
This is the coins cache that is managed by the &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt; code. (see FlushStateToDisk and related functions) &lt;br /&gt;
&lt;br /&gt;
The variable (nCoinsCache) is declared as extern in &amp;lt;u&amp;gt;main.h&amp;lt;/u&amp;gt;.  In &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt;, it is hard-coded to 5000 * 300 (in-memory coins are about 300 bytes, so this means 5000 coins), however it should be re-initialized in Step 7. &lt;br /&gt;
&lt;br /&gt;
This cache is given all of the remaining cache space. &lt;br /&gt;
&lt;br /&gt;
This cache is not loaded during initialization, rather it is filled as coins are accessed.  (This can be verified by the CCoinsViewCache constructor, which sets cachedCoinsUsage=0.)&lt;br /&gt;
&lt;br /&gt;
==Thread Startup==&lt;br /&gt;
&lt;br /&gt;
The code uses boost::thread_groups to manage the various threads.&lt;br /&gt;
&lt;br /&gt;
It should be noted that although Bitcoin Core is a multi-threaded program, &amp;quot;the reference Satoshi client is largely single-threaded.&amp;quot; [https://github.com/bitcoin/bips/blob/master/bip-0031.mediawiki Comment by Mike Hearn in BIP 31 (2012)]&lt;br /&gt;
&lt;br /&gt;
What is meant is that the vast majority of the program&#039;s activity takes place in the messaging thread (ThreadMessageHandler - see below.)  &lt;br /&gt;
&lt;br /&gt;
Almost all of the threads are part of a single, master thread group that is created on the stack at program startup (see &amp;lt;u&amp;gt;bitcoind.cpp&amp;lt;/u&amp;gt;).  This thread group is passed to &amp;lt;u&amp;gt;init.cpp&amp;lt;/u&amp;gt; which creates a few child threads (including a number of script-checking threads, but these are all part of the master thread group, not a separate group.)&lt;br /&gt;
&lt;br /&gt;
The thread group is passed to &amp;lt;u&amp;gt;net.cpp&amp;lt;/u&amp;gt;, which creates the networking threads, including the message-processing thread. &lt;br /&gt;
&lt;br /&gt;
The two other thread groups are task-specific: &lt;br /&gt;
* rpc server thread group (see &amp;lt;u&amp;gt;rpcserver.h/cpp&amp;lt;/u&amp;gt;)&lt;br /&gt;
* miner thread group&lt;br /&gt;
&lt;br /&gt;
Naturally, the node will only create the RPC server thread group if the RPC server is activated, and will only create the miner thread group if it is mining.  If both are disabled, then Bitcoin Core only has a single thread group. &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Child Threads&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The parent thread (meaning the thread in which the program begins operating) delegates almost all of the program&#039;s work to child threads.  After spawning threads in &amp;lt;u&amp;gt;init.cpp&amp;lt;/u&amp;gt; and &amp;lt;u&amp;gt;net.cpp&amp;lt;/u&amp;gt;, the parent thread simply listens for a shutdown command, at which time the parent thread needs only to interrupt the threads in its thread group and proceed with shutdown. &lt;br /&gt;
&lt;br /&gt;
The child threads are summarized in this table, listed in the order in which they are created: &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! Thread !! When / Where Created !! Description&lt;br /&gt;
|-&lt;br /&gt;
| Script-checking || Step 4&amp;lt;br&amp;gt;init.cpp || This is a set of threads - 4 by default.&amp;lt;br&amp;gt;Script-checking (including signature checking) is expensive so is handled in separate threads.&lt;br /&gt;
|-&lt;br /&gt;
| Scheduler || Step 4&amp;lt;br&amp;gt;init.cpp ||  Scheduler thread.&amp;lt;br&amp;gt; (TODO: describe)&lt;br /&gt;
|-&lt;br /&gt;
| RPC Threads || Step 4&amp;lt;br&amp;gt;rpcserver.cpp ||  If RPC server enabled, start a group of threads to handle RPC calls. &lt;br /&gt;
|-&lt;br /&gt;
| Import || Step 10&amp;lt;br&amp;gt;init.cpp ||   Imports blocks. Three scenarios:&amp;lt;br&amp;gt;1) Reindex (rescan all known blocks from blk???.dat files).&amp;lt;br&amp;gt;2) Bootstrap (use bootstrap.dat as an alternative to full IBD from the network.)&amp;lt;br&amp;gt;3) -loadblock (scan a specific blk???.dat file)&amp;lt;br&amp;gt;If none of those apply, this thread does nothing.&lt;br /&gt;
|-&lt;br /&gt;
| DNSAddressSeed || Step 11&amp;lt;br&amp;gt;net.cpp || Attempts to build a vector of IP addresses based on the dns seeds, stores the vector and the thread exits.&amp;lt;br&amp;gt;In a test in June 2014, this took about 4 seconds and found 158 addresses. &lt;br /&gt;
|-&lt;br /&gt;
| Plug &amp;amp; Play || Step 11&amp;lt;br&amp;gt;net.cpp ||  UPNP (Universal Plug &amp;amp; Play) &amp;lt;br&amp;gt;Deals with port mapping for UPNP.&lt;br /&gt;
|-&lt;br /&gt;
| SocketHandler || Step 11&amp;lt;br&amp;gt;net.cpp || &amp;lt;u&amp;gt;This thread services the sockets:&amp;lt;/u&amp;gt;&amp;lt;br&amp;gt;Waits for I/O on all the relevant sockets with a 50ms timeout.&amp;lt;br&amp;gt;Processes new incoming connections on listening socket and creates a CNode for the new peer.&amp;lt;br&amp;gt;Receives and sends data streams.&amp;lt;br&amp;gt;Sets sockets that have not done anything to a disconnected state.&lt;br /&gt;
|-&lt;br /&gt;
| OpenAddedConnections || Step 11&amp;lt;br&amp;gt;net.cpp || Initiates outbound connections specified by the user with the –addnode parameter.&amp;lt;br&amp;gt;If can&#039;t connect, sleeps for 2 minutes each cycle.&lt;br /&gt;
|-&lt;br /&gt;
| OpenConnections || Step 11&amp;lt;br&amp;gt;net.cpp || Initiates other outbound connections from DNS seeds (if that fails, find nodes based on fixed seeds)&amp;lt;br&amp;gt;If can&#039;t connect, sleeps for 500 milliseconds each cycle.&lt;br /&gt;
|-&lt;br /&gt;
| MessageHandler || Step 11&amp;lt;br&amp;gt;net.cpp || &amp;lt;u&amp;gt;This is the program&#039;s main thread.&amp;lt;/u&amp;gt; &amp;lt;br&amp;gt; This thread runs a while(true) loop, receiving and sending messages.  (See &amp;lt;u&amp;gt;net.cpp&amp;lt;/u&amp;gt;:1049) &amp;lt;br&amp;gt;The code uses boost::signals2 to call the ProcessMessages and SendMessages functions in main.cpp.&amp;lt;br&amp;gt;(The code introducing signals is in PR 2154 - see the next-to-last commit in that pull.)&amp;lt;br&amp;gt;ProcessMessage and SendMessage run in this thread.&amp;lt;br&amp;gt;So, most of the code in &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt; runs in this thread.&lt;br /&gt;
|-&lt;br /&gt;
| Wallet Flusher || Step 12&amp;lt;br&amp;gt;init.cpp || If wallet is enabled, this thread flushes the wallet periodically.&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Technical]]&lt;br /&gt;
[[Category:Developer]]&lt;/div&gt;</summary>
		<author><name>Mrbandrews</name></author>
	</entry>
	<entry>
		<id>https://en.bitcoin.it/w/index.php?title=Bitcoin_Core_0.11_(ch_1):_Overview&amp;diff=59976</id>
		<title>Bitcoin Core 0.11 (ch 1): Overview</title>
		<link rel="alternate" type="text/html" href="https://en.bitcoin.it/w/index.php?title=Bitcoin_Core_0.11_(ch_1):_Overview&amp;diff=59976"/>
		<updated>2016-01-13T21:02:50Z</updated>

		<summary type="html">&lt;p&gt;Mrbandrews: page creation&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
==Organization &amp;amp; Maintenance of these Pages==&lt;br /&gt;
&lt;br /&gt;
The purpose of this set of Wiki pages is to document the Bitcoin Core C++ source code, in a way that is helpful to the programmer who wants to learn how the program is designed and what the code does. &lt;br /&gt;
&lt;br /&gt;
Ideally, the accuracy of the information on these pages would be checked by developers who are getting up to speed on the Bitcoin Core code base.  Additionally, each new release of Bitcoin Core (0.12, 0.13, etc) could have a new set of pages that are modified to match that version.&lt;br /&gt;
&lt;br /&gt;
These pages are loosely based on the set of pages called &amp;quot;Satoshi Client: xxx&amp;quot; (on this Wiki) which were written in 2011 and based on version 0.3. &lt;br /&gt;
&lt;br /&gt;
This set of Wiki pages includes: &lt;br /&gt;
&lt;br /&gt;
* Ch 1: Intro &amp;amp; Overview (this page) &lt;br /&gt;
* Ch 2: Data Storage&lt;br /&gt;
* Ch 3: Initialization &amp;amp; Startup&lt;br /&gt;
* Ch 4: P2P Network&lt;br /&gt;
* Ch 5: Initial Block Download (IBD)&lt;br /&gt;
* Ch 6: Blockchain&lt;br /&gt;
* Ch 7: Transactions &amp;amp; the Memory Pool&lt;br /&gt;
* Ch 8: RPC Server&lt;br /&gt;
&lt;br /&gt;
These pages document the &amp;quot;relay node&amp;quot; aspect of Bitcoin Core, meaning a node which validates blocks and transactions and relays them to other nodes. The node has fully validated the blockchain, although it may not necessarily maintain a full copy of it on disk. &lt;br /&gt;
&lt;br /&gt;
These pages do NOT cover: &lt;br /&gt;
* Wallet&lt;br /&gt;
* GUI (Qt)&lt;br /&gt;
* Mining&lt;br /&gt;
&lt;br /&gt;
==Definitions==&lt;br /&gt;
&lt;br /&gt;
A few definitions at the outset:  &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Consensus code&#039;&#039;&#039; &lt;br /&gt;
&lt;br /&gt;
Code that validates blocks and transactions.  &lt;br /&gt;
&lt;br /&gt;
Consensus code must have bug-for-bug compatibility across versions and implementations (meaning, 0.12 must have the same consensus behaviour as 0.11, even if it is buggy;  otherwise, a network fork may result.) &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Policy code&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Code that implements a particular node&#039;s policy (as opposed to consensus).  A node&#039;s algorithm for which transactions to store in its transaction pool is an example of policy.  For example, a node could refuse to relay or store any transaction that is larger than 200KB.  What is important is that if such a transaction is transmitted to the node as part of a newly mined block, the node does not reject the block.   &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;P2P code&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Code relating to communications with other nodes (peers) over the P2P network.  Communication includes discovering and connecting to other nodes; exchanging various P2P messages (e.g., messages containing blocks and transactions); occasionally, banning misbehaving peers. The bitcoin network uses a custom set of P2P messages.  Most of the P2P code can be found in &amp;lt;u&amp;gt;net.h/net.cpp&amp;lt;/u&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Mempool (&amp;quot;memory pool&amp;quot; or &amp;quot;transaction pool&amp;quot;)&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
A set of transactions which the node knows about and chooses to store in memory and relay to other nodes, and which have not yet been included in a block.  In many cases, this may be the full set of transactions that the node has received and validated.  If the node has received transactions that violate its policy, however, the mempool will be a subset.  In any event, when the node receives and validates a block, it deletes any transactions in the block from its mempool.  &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Full Node&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
A full node is one that validates blocks and transactions and relays them to other nodes.  A full node has validated the blockchain from scratch (although with block file pruning, it may have discarded older parts of the chain to clear up disk space.) The key characteristic of a full node is that it has validated the blockchain and continues to fully validate and relay incoming blocks and transactions.  A full node can be differentiated from an SPV node, which trusts another node (or set of nodes) to validate. &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;&amp;quot;Basic Full Node&amp;quot;&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
A &amp;quot;basic full node&amp;quot; is what is documented in these pages.  By &amp;quot;basic full node,&amp;quot; what is meant is a node that validates and relays blocks and transactions, but does not mine new blocks or perform other optional tasks (RPC server, wallet).  Extending these pages to include documentation of these optional aspects of a node is a future project.&lt;br /&gt;
&lt;br /&gt;
==Architecture of a Bitcoin Node==&lt;br /&gt;
&lt;br /&gt;
One developer described the architecture of a basic full node as follows: &lt;br /&gt;
&lt;br /&gt;
: --------------------&lt;br /&gt;
&lt;br /&gt;
: The basic architecture of a bitcoin node is as follows:&lt;br /&gt;
&lt;br /&gt;
: At the core there exist fundamental bitcoin message structures, along with the code necessary for serialization/deserialization. These structures belong in their own source files with minimal dependencies so they can be reused for applications that needn&#039;t perform verification and relay - for instance, filtering and notification agents. Unfortunately, these core structures currently reside for the most part in main.h/main.cpp...&lt;br /&gt;
&lt;br /&gt;
: On top of these core structures sits a network component that manages sockets, does peer discovery, and handles queueing and dispatching of messages. This component is clearly dependent on the core message structures but does not depend on the specific logic used to verify blocks and transactions nor to identify misbehaving peers nor sign transactions nor maintain a block chain database.&lt;br /&gt;
&lt;br /&gt;
: Then we have a scripting engine, signature verification component, and a signing component. Historical database applications do not need signature verification/signing functionality at all. Filtering messages and sending alerts generally does not even require a scripting engine and does fine with basic pattern matching.&lt;br /&gt;
&lt;br /&gt;
: The most critical high-level operations needed by a verification/relay node such as the satoshi client are transaction verification; block chain and memory pool management; and detection/management of misbehaving peers. These things are currently primarily implemented in main.h/main.cpp. These are indeed the main operations of the satoshi client - but the core low-level structures should not depend at all on this logic.&lt;br /&gt;
&lt;br /&gt;
: ---------------------&lt;br /&gt;
&lt;br /&gt;
See here: [https://github.com/bitcoin/bitcoin/pull/2154 PR 2154]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In the form of a (crude) picture: &lt;br /&gt;
 &lt;br /&gt;
   Validating transactions; Managing blockchain, mempool, and peers.&lt;br /&gt;
                    | &lt;br /&gt;
       Scripting engine / Signatures&lt;br /&gt;
                    | &lt;br /&gt;
              Network layer&lt;br /&gt;
                    | &lt;br /&gt;
              P2P Messages&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
And here is the same picture, augmented with the definitions above: &lt;br /&gt;
 &lt;br /&gt;
   Validating transactions; Managing blockchain, mempool, peers  (Consensus and Policy code)&lt;br /&gt;
                    | &lt;br /&gt;
       Scripting engine / Signatures (Consensus code)&lt;br /&gt;
                    | &lt;br /&gt;
              Network layer  (P2P code) &lt;br /&gt;
                    | &lt;br /&gt;
              P2P Messages&lt;br /&gt;
&lt;br /&gt;
==Code Modularization / Organization==&lt;br /&gt;
&lt;br /&gt;
As of 0.11, modularization of the Bitcoin Core code is somewhat limited.   &lt;br /&gt;
&lt;br /&gt;
Ideally, Bitcoin Core would be modularized so that the consensus code would be separated and made into a library which could be distributed to other implementations.  In this way, fears of accidentally forking the network would be mitigated.  As of 2016, this is work in progress (see, e.g., various &amp;quot;libconsensus&amp;quot; pull requests on GitHub.) &lt;br /&gt;
&lt;br /&gt;
In December 2013, a proposal was made for modularizing the code base:  [https://github.com/bitcoin/bitcoin/issues/3440 Post-0.9 modularization of Bitcoin Core]&lt;br /&gt;
&lt;br /&gt;
Examples of optional modules would be: &lt;br /&gt;
* Miner&lt;br /&gt;
* Wallet&lt;br /&gt;
* Notifications&lt;br /&gt;
&lt;br /&gt;
As of 0.11, the steps taken toward modularization were primarily separating certain classes into subdirectories, described below.&lt;br /&gt;
&lt;br /&gt;
==Source Code Files==&lt;br /&gt;
&lt;br /&gt;
The C++ code is in the src/ directory of the repository.  &lt;br /&gt;
&lt;br /&gt;
Most of the code resides in the top-level directory, although there has been some effort to modularize the code base with subdirectories (wallet, consensus, primitives, etc.)  Also, certain components (QT, LevelDB, etc) live in subdirectories.&lt;br /&gt;
&lt;br /&gt;
Key files in the src/ directory include:  (file.* means the header file [file.h] and the source file [file.cpp])&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! File !! Description / Purpose&lt;br /&gt;
|-&lt;br /&gt;
| net.* ||  Manages the network (peer connections, etc.).&amp;lt;br&amp;gt;The while(true) loop in ThreadMessageHandler controls the program&#039;s flow, signalling &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt; when there is work to do. &amp;lt;br&amp;gt;Key dependencies:  None. &lt;br /&gt;
|-&lt;br /&gt;
| init.cpp ||  Initializes the node, calling functions in &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt; as necessary.&amp;lt;br&amp;gt;Key dependencies: main.h&lt;br /&gt;
|-&lt;br /&gt;
| main.* || main.h declares some key global variables (mapBlockIndex, chainActive, mempool, etc), constants, and functions. &amp;lt;br&amp;gt;&amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt; is the program&#039;s longest source file (5,237 lines).&amp;lt;br&amp;gt;main.cpp has most of the key functions for managing the blockchain, such as connecting, disconnecting, validating and storing blocks; identifying a certain block as the tip of the longest chain; and so forth.&amp;lt;br&amp;gt;The &amp;quot;entry point&amp;quot; for most of the code is ProcessMessages (which listens for a signal from the message-handling thread.).&amp;lt;br&amp;gt;Some of the code is run during initialization, called directly from init.cpp. &amp;lt;br&amp;gt;Key dependencies: net.h&lt;br /&gt;
|-&lt;br /&gt;
| chain.* || The header file (chain.h) is the more notable of the two, as it declares the type definitions for the metadata about the block (CBlockIndex) and the longest blockchain (CChain). &amp;lt;br&amp;gt;chain.cpp contains a few handy functions for managing the blockchain (e.g., locating blocks and finding a fork point between two chains.)&lt;br /&gt;
|-&lt;br /&gt;
| coins.* ||  The header file declares a CCoin, which is, conceptually, &amp;quot;a bitcoin.&amp;quot;&amp;lt;br&amp;gt;The source file contains methods for manipulating coins (retrieving, spending, etc.)&lt;br /&gt;
|-&lt;br /&gt;
| miner.* ||  Contains the mining code, including block creation and generating new bitcoins. &lt;br /&gt;
|-&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Subdirectories:&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The subdirectories fall into three categories: &lt;br /&gt;
* Well-defined components (in some cases third-party) &lt;br /&gt;
* Modularization of code&lt;br /&gt;
* Other (unit tests, build files, etc.)&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Subdirectories - Components:&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! Directory !! Description / Purpose&lt;br /&gt;
|-&lt;br /&gt;
| leveldb || C++ source code, docs, etc. for the LevelDB build.&lt;br /&gt;
|-&lt;br /&gt;
|  qt || The GUI code (QT).&amp;lt;br&amp;gt;QT is a C++ open-source project for GUI code, first released in 1995.&lt;br /&gt;
|-&lt;br /&gt;
|  secp256k1 || Library implementing ECDSA cryptography.&amp;lt;br&amp;gt;Purpose: This proprietary C library eliminates reliance on SSL for signature checking.&amp;lt;br&amp;gt;This is important because SSL was susceptible to introducing consensus bugs, because newly released versions do not guarantee bug-for-bug compatibility.&amp;lt;br&amp;gt;This library was written/released in early 2015. &lt;br /&gt;
|-&lt;br /&gt;
|  zmq || From the ZMQ wiki:&amp;lt;br&amp;gt;ZMQ (or ZeroMQ or 0MQ) is a high-performance asynchronous messaging library.&amp;lt;br&amp;gt;It provides a message queue, but unlike message-oriented middleware, a ZMQ system can run without a dedicated message broker. &amp;lt;br&amp;gt;The library is designed to have a familiar socket-style API.&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Subdirectories - Modularization:&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! Directory !! Key Files !! Description / Purpose&lt;br /&gt;
|-&lt;br /&gt;
| consensus || consensus.*&amp;lt;br&amp;gt;merkle.*&amp;lt;br&amp;gt;params.*&amp;lt;br&amp;gt;validation.*  || Code implementing (or defining, as the case may be) the block &amp;amp; transaction validation rules.&amp;lt;br&amp;gt;Purpose: Moving this code into a subdirectory is a step towards modularizing the consensus code.&amp;lt;br&amp;gt;The idea is that in a future version of bitcoin, the consensus code should be packaged as a library, so that alternative implementations of the protocol could simply include this library and guarantee validation compatibility.  &amp;quot;...[T]he goal is not reimplementing the consensus rules but rather extract them from Bitcoin Core so that nobody needs to re-implement them again. It is not only exposing it but also separating it from Bitcoin Core so that they can be changed without having to also change/take into account non-consensus Bitcoin Core specific things.&amp;quot; -- Jorge Timon, on bitcoin-development mailing list, 20 Aug 2015.&amp;lt;br&amp;gt;Discussion on github: [https://github.com/bitcoin/bitcoin/issues/6714 PR6714] &lt;br /&gt;
|-&lt;br /&gt;
| crypto || ripemd.*&amp;lt;br&amp;gt;sha256.*  || Cryptographic hash functions.&amp;lt;br&amp;gt;Both RIPEMD and SHA-256 are used in transforming a bitcoin address to Base-58 encoding.&lt;br /&gt;
|-&lt;br /&gt;
| policy || policy.*&amp;lt;br&amp;gt;fees.* ||  Move validation code that is a matter of &#039;&#039;policy&#039;&#039; (as opposed to consensus) into a separate directory.&lt;br /&gt;
|-&lt;br /&gt;
| primitives  || block.*&amp;lt;br&amp;gt;transaction.*  || Definitions of certain basic data types (blocks, transactions, etc.)&lt;br /&gt;
|-&lt;br /&gt;
|  script || interpreter.*&amp;lt;br&amp;gt;script.*&amp;lt;br&amp;gt;standard.* || The script engine.&amp;lt;br&amp;gt;Defines the op_codes (script.h).&amp;lt;br&amp;gt;Parses and evaluates the validation script. (interpreter.cpp:EvalScript())&amp;lt;br&amp;gt;Defines what is a &amp;quot;standard&amp;quot; transaction (standard.h).&amp;lt;br&amp;gt;Purpose: the Script engine validates basic transactions but also makes contracts possible.  It could be said that in large part, what a platform like Ethereum does is provide a more robust script engine (and language in which to express script) - so in a sense, deploying such as system consists of replacing this sub-directory with something more powerful. &lt;br /&gt;
|-&lt;br /&gt;
|  wallet || wallet.*  || Wallet code. &lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Subdirectories - Other:&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! Directory !! Description / Purpose&lt;br /&gt;
|-&lt;br /&gt;
| compat || A few minor, low-level files dealing with compatibility details. &lt;br /&gt;
|-&lt;br /&gt;
| config&amp;lt;br&amp;gt;obj&amp;lt;br&amp;gt;obj-test || These directories relate to the build process.&lt;br /&gt;
|-&lt;br /&gt;
|  test || Unit tests.&amp;lt;br&amp;gt;Uses the Boost unit test framework.&amp;lt;br&amp;gt;A good introduction to the Boost user test framework is here:  [http://www.alittlemadness.com/2009/03/31/c-unit-testing-with-boosttest/]&lt;br /&gt;
|-&lt;br /&gt;
|  univalue || Per the README:&amp;lt;br&amp;gt;&amp;quot;A universal value object, with JSON encoding (output) and decoding (input).&amp;lt;br&amp;gt;Built as a single dynamic RAII C++ object class, and no templates.&amp;quot;&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
==Design Patterns==&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Object-Oriented Design&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Naturally, being a C++ program, the code employs object-oriented design.&lt;br /&gt;
&lt;br /&gt;
However, the code&#039;s use of object-oriented design is by not universal.  In 0.11, objects are used mainly for defining the data structures which main.cpp uses to manage the blockchain and the UTXO set (the bitcoins). Main.h declares many functions and global variables but almost no classes; &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt; is over 5000 lines but does not include any class methods.  &lt;br /&gt;
&lt;br /&gt;
The code has a relatively flat class structure, with most classes being &amp;quot;stand-alone&amp;quot;.  &lt;br /&gt;
&lt;br /&gt;
Where inheritance is used, it often is a linear hierarchy (i.e.:  A &amp;lt;-- B &amp;lt;--C &amp;lt;-- D)&lt;br /&gt;
&lt;br /&gt;
For example: &lt;br /&gt;
 CBlockHeader &amp;lt;-- CBlock&lt;br /&gt;
 CTransaction &amp;lt;-- CMerkleTx &amp;lt;-- CWalletTx&lt;br /&gt;
&lt;br /&gt;
There are only a few examples of base classes that have more than one descendant class, and multiple inheritance is only used once in the code (CWallet inherits from 2 classes.) &lt;br /&gt;
&lt;br /&gt;
The program&#039;s best example of an elegant class hierarchy relates to the coins caches.  It uses an abstract class that is inherited by a few subclasses that demonstrate encapsulation and polymorphism.  Chapter 3 has a class diagram as well as a diagram and explanation of how the classes are instantiated and relate to one another.  &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Multithreading&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The code uses Boost thread groups to implement multithreading.  The vast majority of the action takes place in the message-processing thread, and to a lesser extent the socket thread. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Observer (Signals and slots)&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The &amp;quot;observer&amp;quot; pattern uses &amp;quot;signals and slots&amp;quot; to decouple two or more areas of code. Bitcoin Core 0.11 uses the observer pattern in a limited way.  Namely, it uses signals to decouple the message-gathering loop from the &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt; code.  In 0.10 and earlier a normal function call was used.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Technical]]&lt;br /&gt;
[[Category:Developer]]&lt;/div&gt;</summary>
		<author><name>Mrbandrews</name></author>
	</entry>
	<entry>
		<id>https://en.bitcoin.it/w/index.php?title=Bitcoin_Core_0.11_(ch_2):_Data_Storage&amp;diff=59975</id>
		<title>Bitcoin Core 0.11 (ch 2): Data Storage</title>
		<link rel="alternate" type="text/html" href="https://en.bitcoin.it/w/index.php?title=Bitcoin_Core_0.11_(ch_2):_Data_Storage&amp;diff=59975"/>
		<updated>2016-01-13T21:00:20Z</updated>

		<summary type="html">&lt;p&gt;Mrbandrews: page creation&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
This page describes how &amp;amp; where Bitcoin stores blockchain data. &lt;br /&gt;
&lt;br /&gt;
==Overview==&lt;br /&gt;
&lt;br /&gt;
There are basically four pieces of data that are maintained:&lt;br /&gt;
&lt;br /&gt;
: &#039;&#039;&#039;blocks/blk*.dat:&#039;&#039;&#039; the actual Bitcoin blocks, in network format, dumped in raw on disk. They are only needed for rescanning missing transactions in a wallet, reorganizing to a different part of the chain, and serving the block data to other nodes that are synchronizing.&lt;br /&gt;
&lt;br /&gt;
: &#039;&#039;&#039;blocks/index/*:&#039;&#039;&#039; this is a LevelDB database that contains metadata about all known blocks, and where to find them on disk. Without this, finding a block would be very slow.&lt;br /&gt;
&lt;br /&gt;
: &#039;&#039;&#039;chainstate/*:&#039;&#039;&#039; this is a LevelDB database with a compact representation of all currently unspent transaction outputs and some metadata about the transactions they are from. The data here is necessary for validating new incoming blocks and transactions. It can theoretically be rebuilt from the block data (see the -reindex command line option), but this takes a rather long time. Without it, you could still theoretically do validation indeed, but it would mean a full scan through the blocks (7 GB as of may 2013) for every output being spent.&lt;br /&gt;
&lt;br /&gt;
: &#039;&#039;&#039;blocks/rev*.dat:&#039;&#039;&#039; these contain &amp;quot;undo&amp;quot; data. You can see blocks as &#039;patches&#039; to the chain state (they consume some unspent outputs, and produce new ones), and see the undo data as reverse patches. They are necessary for rolling back the chainstate, which is necessary in case of reorganisations.&lt;br /&gt;
&lt;br /&gt;
Note that the LevelDB&#039;s are redundant in the sense that they can be rebuilt from the block data. But validation and other operations would become intolerably slow without them.&lt;br /&gt;
&lt;br /&gt;
See here:  [http://bitcoin.stackexchange.com/questions/11104/what-is-the-database-for?rq=1 StackExchange post by Pieter Wuille (2013)]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Raw Block data (blk*.dat)==&lt;br /&gt;
&lt;br /&gt;
Block files store the raw blocks as they were received over the network.  &lt;br /&gt;
&lt;br /&gt;
Block files are about 128 MB, allocated in 16 MB chunks to prevent excessive fragmentation.  As of October 2015, the block chain is stored in about 365 block files, for a total of about 45 GB. &lt;br /&gt;
&lt;br /&gt;
Each block file (blk1234.dat) has a corresponding undo file (rev1234.dat) which contains the data necessary to remove blocks from the blockchain in the event of a reorganization (fork). &lt;br /&gt;
&lt;br /&gt;
Info about the block files is stored in the block index (the LevelDB) in two places: &lt;br /&gt;
* General info about the files themselves is held in the &amp;quot;f&amp;quot; records in the block index LevelDB (meaning keys &amp;quot;fxxxx&amp;quot;, where &amp;quot;xxxx&amp;quot; is the 4 digit file number), including: &lt;br /&gt;
** Number of blocks stored in the file&lt;br /&gt;
** File size (and the corresponding undo file size) &lt;br /&gt;
** Lowest and highest block in the file&lt;br /&gt;
** Timestamps - earlier and latest blocks in the file&lt;br /&gt;
&lt;br /&gt;
* Info about where to find a particular block on disk is in the &amp;quot;b&amp;quot; (&amp;quot;b&amp;quot; = block) record: &lt;br /&gt;
** Each block contains a pointer to the block is on disk (a file number and an offset)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Accessing the block data files from the code&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The block files are accessed through: &lt;br /&gt;
&lt;br /&gt;
1) DiskBlockPos: a struct that is simply a pointer to a block&#039;s location on disk (a file number and an offset.) &lt;br /&gt;
&lt;br /&gt;
2) &#039;&#039;vInfoBlockFiles&#039;&#039;: a vector of BlockFileInfo objects.  This variable is used to perform such tasks as:  &lt;br /&gt;
* Determine whether new blocks can fit into the current file or a new file needs to be created&lt;br /&gt;
* Calculate the total disk usage by block &amp;amp; undo files &lt;br /&gt;
* Iterate through the block files and find ones that can be pruned&lt;br /&gt;
&lt;br /&gt;
Blocks are written to disk as soon as they are received, in AcceptBlock.  (The actual disk write operation is in WriteBlockToDisk [&amp;lt;u&amp;gt;main.cpp:1164&amp;lt;/u&amp;gt;]).  Note that there is some overlap of the code that accesses block files with the code that accesses and writes to the coins database (/chainstate).  There is a complex system of when to flush state to disk.  None of this code affects block files, which are simply written to disk when received.  Once they have been received and stored, the block files are only needed for serving blocks to other nodes. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;More info about block files&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
See here: [https://github.com/sipa/bitcoin/commit/5382bcf8cd23c36a435c29080770a79b5e28af42 the commit that puts multiple blocks in a block file (2012)]&lt;br /&gt;
&lt;br /&gt;
==Block index (leveldb)==&lt;br /&gt;
&lt;br /&gt;
The block index holds metadata about all known blocks, including where the block is stored on disk.  &lt;br /&gt;
&lt;br /&gt;
Note that the set of &amp;quot;known blocks&amp;quot; is a superset of the longest chain, because it includes blocks that were received and processed but are not part of the active chain - for example, orphaned blocks that were detached from the active chain in a small reorganization.   &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Terminology&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The terminology can be a little confusing here, because while people normally think of the &amp;quot;blockchain&amp;quot; as being synonymous with the active chain (an uninterrupted, linear chain of X blocks starting with the genesis block and continuing to the current tip), there are some places in the code where &amp;quot;blockchain&amp;quot; refers to the active chain plus the numerous, mostly short forks off the chain that our node happens to know about.  &lt;br /&gt;
&lt;br /&gt;
a) Block Tree&lt;br /&gt;
&lt;br /&gt;
A better term for the set of known blocks stored on disk is &amp;quot;block tree,&amp;quot; as this term contemplates a tree structure with numerous branches (albeit small ones) from the main chain.  Indeed, the block index LevelDB is accessed through the &amp;quot;CBlockTreeDB&amp;quot; wrapper class, defined in &amp;lt;u&amp;gt;src/txdb.h&amp;lt;/u&amp;gt;.  Note that it&#039;s perfectly fine, indeed it is expected, that different nodes would have slightly different block trees;  what matters is that they agree on the active chain.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Key-value pairs&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Inside the actual LevelDB, the used key/value pairs are:&lt;br /&gt;
&lt;br /&gt;
    &#039;b&#039; + 32-byte block hash -&amp;gt; block index record. Each record stores:&lt;br /&gt;
        * The block header&lt;br /&gt;
        * The height.&lt;br /&gt;
        * The number of transactions.&lt;br /&gt;
        * To what extent this block is validated.&lt;br /&gt;
        * In which file, and where in that file, the block data is stored.&lt;br /&gt;
        * In which file, and where in that file, the undo data is stored.&lt;br /&gt;
&lt;br /&gt;
   &#039;f&#039; + 4-byte file number -&amp;gt; file information record. Each record stores:&lt;br /&gt;
        * The number of blocks stored in the block file with that number.&lt;br /&gt;
        * The size of the block file with that number ($DATADIR/blocks/blkNNNNN.dat).&lt;br /&gt;
        * The size of the undo file with that number ($DATADIR/blocks/revNNNNN.dat).&lt;br /&gt;
        * The lowest and highest height of blocks stored in the block file with that number.&lt;br /&gt;
        * The lowest and highest timestamp of blocks stored in the block file with that number.&lt;br /&gt;
&lt;br /&gt;
    &#039;l&#039; -&amp;gt; 4-byte file number: the last block file number used.&lt;br /&gt;
&lt;br /&gt;
    &#039;R&#039; -&amp;gt; 1-byte boolean (&#039;1&#039; if true): whether we&#039;re in the process of reindexing.&lt;br /&gt;
&lt;br /&gt;
    &#039;F&#039; + 1-byte flag name length + flag name string -&amp;gt; 1 byte boolean (&#039;1&#039; if true, &#039;0&#039; if false): various flags that can be on or off. Currently defined flags include:&lt;br /&gt;
         * &#039;txindex&#039;: Whether the transaction index is enabled.&lt;br /&gt;
&lt;br /&gt;
    &#039;t&#039; + 32-byte transaction hash -&amp;gt; transaction index record. These are optional and only exist if &#039;txindex&#039; is enabled (see above). Each record stores:&lt;br /&gt;
        * Which block file number the transaction is stored in.&lt;br /&gt;
        * Which offset into that file the block the transaction is part of is stored at.&lt;br /&gt;
        * The offset from the start of that block to the position where that transaction itself is stored.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
See here: [http://bitcoin.stackexchange.com/questions/28168/what-are-the-keys-used-in-the-blockchain-leveldb-ie-what-are-the-keyvalue-pair StackExchange post by Pieter Wuille (2014)]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Data Access Layer&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The database is accessed through CBlockTreeDB wrapper class.  See &amp;lt;u&amp;gt;txdb.h&amp;lt;/u&amp;gt;.  &lt;br /&gt;
&lt;br /&gt;
The wrapper is instantiated in a global variable called pblocktree, defined in &amp;lt;u&amp;gt;main.cpp.&amp;lt;/u&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;CBlockIndex&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Blocks stored in the database are represented in memory as CBlockIndex objects.  An object of this type is first created after the &#039;&#039;header&#039;&#039; is received;  the code does not wait to receive the full block.  When headers are received over the network, they are streamed into a vector of CBlockHeaders, which are then checked. Each header that checks out causes a new CBlockIndex to be created, which is stored to the database. &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;CBlock / CBlockHeader&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Note that these objects have little to do with the /blocks LevelDB.  A CBlock holds the full set of transactions in the block, the data for which is stored in two places - in full, in raw format, in the blk???.dat files, and in pruned format in the UTXO database.  The block index database cares not for such details, since it holds only the metadata for the block. &lt;br /&gt;
 &lt;br /&gt;
&#039;&#039;Loading the block database into memory&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The entire database is loaded into memory on startup.  See LoadBlockIndexGuts (&amp;lt;u&amp;gt;txdb.cpp&amp;lt;/u&amp;gt;).  This only takes a few seconds. &lt;br /&gt;
&lt;br /&gt;
The blocks (&#039;b&#039; keys) are loaded into the global &amp;quot;mapBlockIndex&amp;quot; variable.  &amp;quot;mapBlockIndex&amp;quot; is an unordered_map that holds CBlockIndex for each block in the entire block tree; not just the active chain.  &lt;br /&gt;
&lt;br /&gt;
mapBlockIndex is described in more detail in Chapter 6 - The Blockchain. &lt;br /&gt;
&lt;br /&gt;
The block file metadata (&#039;f&#039; keys) is loaded into vInfoBlockFiles.&lt;br /&gt;
&lt;br /&gt;
==The UTXO set (chainstate leveldb)==&lt;br /&gt;
&lt;br /&gt;
The UTXO database was introduced in 2012 in [https://github.com/bitcoin/bitcoin/pull/1677 pull request #1677 - &amp;quot;Ultraprune.&amp;quot;]&lt;br /&gt;
&lt;br /&gt;
The idea behind &amp;quot;Ultraprune&amp;quot; is to reduce the size of (prune) the set of past transactions, keeping only those parts of past transactions that are necessary to validate later transactions.  &lt;br /&gt;
&lt;br /&gt;
Say you have a transaction T1 which takes two inputs and sends to 3 outputs: O1,O2,O3.  Two of those outputs (O1, O2) have been used as inputs in a later transaction, T2.   Once T2 has been mined, T1 only has one item of interest (O3).  There&#039;s no reason to keep T1 around in its entirety.  Instead, a slimmed-down version of T1 will suffice, consisting only of O3 (locking script and amount) and certain basic information about T1 (height, whether it is a coinbase, etc.)&lt;br /&gt;
&lt;br /&gt;
The description of ultraprune is on the specific &amp;quot;ultraprune&amp;quot; commit within the pull: &lt;br /&gt;
&lt;br /&gt;
: -------------&lt;br /&gt;
&lt;br /&gt;
: This switches bitcoin&#039;s transaction/block verification logic to use a &amp;quot;coin database&amp;quot;, which contains all unredeemed transaction output scripts, amounts and heights.&lt;br /&gt;
&lt;br /&gt;
: The name ultraprune comes from the fact that instead of a full transaction index, we only (need to) keep an index with unspent outputs. For now, the blocks themselves are kept as usual, although they are only necessary for serving, rescanning and reorganizing.&lt;br /&gt;
&lt;br /&gt;
: The basic data structures are CCoins (representing the coins of a single transaction), and CCoinsView (representing a state of the coins database).  There are several implementations for CCoinsView. A dummy, one backed by the coins database (coins.dat), one backed by the memory pool, and one that adds a cache on top of it. FetchInputs, ConnectInputs, ConnectBlock, DisconnectBlock, ... now operate on a generic CCoinsView.&amp;lt;br&amp;gt;&amp;lt;br&amp;gt;The block switching logic now builds a single cached CCoinsView with changes to be committed to the database before any changes are made. This means no uncommitted changes are ever read from the database, and should ease the transition to another database layer which does not support transactions (but does support atomic writes), like LevelDB.&lt;br /&gt;
&lt;br /&gt;
: For the getrawtransaction() RPC call, access to a txid-to-disk index would be preferable. As this index is not necessary or even useful for any other part of the implementation, it is not provided. Instead, getrawtransaction() uses the coin database to find the block height, and then scans that block to find the requested transaction. This is slow, but should suffice for debug purposes.&lt;br /&gt;
&lt;br /&gt;
: -----------------&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
See:  [https://github.com/sipa/bitcoin/commit/450cbb0944cd20a06ce806e6679a1f4c83c50db2 Ultraprune - July 2012]&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Terminology&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
&amp;quot;UTXO (Unspent Transaction Out):&amp;quot;  An output from a transaction.  This is colloquially referred to as a &amp;quot;coin.&amp;quot;  For this reason, the UTXO db is sometimes referred to as the &amp;quot;coins database.&amp;quot;&lt;br /&gt;
&lt;br /&gt;
&amp;quot;UTXO set / coins database / chainstate database:&amp;quot;  These terms are more or less synonymous and are used interchangeably.  &lt;br /&gt;
&lt;br /&gt;
&amp;quot;Provably Unspendable:&amp;quot;  A coin is provably unspendable if its scriptPubKey cannot be satisfied - for example, an OP_RETURN.  A provably unspendable coin can be eliminated from the utxo database regardless of its amount. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Key-value pairs&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The records in the chainstate levelDB are: &lt;br /&gt;
&lt;br /&gt;
    &#039;c&#039; + 32-byte transaction hash -&amp;gt; unspent transaction output record for that transaction. These records are only present for transactions that have at least one unspent output left. Each record stores:&lt;br /&gt;
        * The version of the transaction.&lt;br /&gt;
        * Whether the transaction was a coinbase or not.&lt;br /&gt;
        * Which height block contains the transaction.&lt;br /&gt;
        * Which outputs of that transaction are unspent.&lt;br /&gt;
        * The scriptPubKey and amount for those unspent outputs.&amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
    &#039;B&#039; -&amp;gt; 32-byte block hash: the block hash up to which the database represents the unspent transaction outputs.&lt;br /&gt;
&lt;br /&gt;
See here: [http://bitcoin.stackexchange.com/questions/28168/what-are-the-keys-used-in-the-blockchain-leveldb-ie-what-are-the-keyvalue-pair StackExchange post by Pieter Wuille (2014)]&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Data Access Layer and Caching&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Access to the UTXO database is considerably more complex than the block index.   This is because its performance is critical to the overall performance of the Bitcoin system.  The block index is not so critical to performance because there are only a few hundred thousand blocks and a node running on decent hardware can retrieve and scroll through them in a few seconds (and does not need to do so very often.)  On the other hand, there are millions of coins in the UTXO database and they must be checked and modified for each input of each transaction going into the mempool or included in a block. &lt;br /&gt;
&lt;br /&gt;
As sipa said in the ultraprune commit: &lt;br /&gt;
: The basic data structures are CCoins (representing the coins of a single transaction), and CCoinsView (representing a state of the coins database).  There are several implementations for CCoinsView. A dummy, one backed by the coins database (coins.dat), one backed by the memory pool, and one that adds a cache on top of it.&lt;br /&gt;
&lt;br /&gt;
This is not stated as clearly as it might have been, however; at least, not for the current state of the code.  &lt;br /&gt;
&lt;br /&gt;
In 0.11, the instantiations of the CoinsView are:  &lt;br /&gt;
* dummy&lt;br /&gt;
* database&lt;br /&gt;
* pCoinsTip (a cache backed by the database)&lt;br /&gt;
* &amp;quot;validation cache&amp;quot; (used when  backed by pCoinsTip, in use when connecting a block)  &lt;br /&gt;
&lt;br /&gt;
Separate from that chain of caches is the memory pool&#039;s CoinsView, which is backed by the database. &lt;br /&gt;
&lt;br /&gt;
    &lt;br /&gt;
The &amp;lt;i&amp;gt;class diagram&amp;lt;/i&amp;gt; (data types) for the views is: &lt;br /&gt;
&lt;br /&gt;
       CCoinsView (abstract class)&lt;br /&gt;
              /            \&lt;br /&gt;
          ViewDB          ViewBacked &lt;br /&gt;
       (database)          /      \&lt;br /&gt;
                    ViewMempool   ViewCache&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Each class has one key characteristic: &lt;br /&gt;
* View is the base class, declaring methods for verifying that coins exist (HaveCoins), retrieving coins (GetCoins), etc. &lt;br /&gt;
* ViewDB has code to interact with the LevelDB. &lt;br /&gt;
* ViewBacked has a pointer to another View;  thus it is &amp;quot;backed&amp;quot; by another view (version) of the UTXO set. &lt;br /&gt;
* ViewCache has a cache (a map of CCoins). &lt;br /&gt;
* ViewMempool associates a mempool with a view. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Those are the defined classes; whereas the &amp;lt;i&amp;gt;object diagram&amp;lt;/i&amp;gt; is: &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
             Database       &lt;br /&gt;
            /       \&lt;br /&gt;
        MemPool     Blockchain cache (pcoinsTip) &lt;br /&gt;
      View/Cache            \&lt;br /&gt;
                          Validation cache&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here is a table summarizing the instantiations of Views: &lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! Object !! Type !! Backed By? !! Description / Purpose&lt;br /&gt;
|-&lt;br /&gt;
| DB view || ViewDB || n/a || Represents the UTXO set according to the /chainstate LevelDB.  Retrieves coins and flushes changes to the LevelDB.&amp;lt;br&amp;gt;Creation in code (instantiation):  see &amp;lt;u&amp;gt;init.cpp:1131&amp;lt;/u&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| pCoinsTip&amp;lt;br&amp;gt;(blockchain cache) || ViewCache || DB view || Holds the UTXO set corresponding to the active chain&#039;s tip.  Retrieves/flushes to the database view.&amp;lt;br&amp;gt;Creation in code:  see &amp;lt;u&amp;gt;init.cpp:1133&amp;lt;/u&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| Validation cache || ViewCache || pCoinsTip || This cache&#039;s lifetime is within ConnectTip (or DisconnectTip).&amp;lt;br&amp;gt;Its purpose is to keep track of modifications to the UTXO set while processing a block.&amp;lt;br&amp;gt;If the block validates, the cache is flushed to pcoinsTip.&amp;lt;br&amp;gt;If the block fails, the cache is discarded. &amp;lt;br&amp;gt;Creation in code:  see &amp;lt;u&amp;gt;main.cpp:2231&amp;lt;/u&amp;gt;:  CCoinsViewCache view(pcoinsTip);&lt;br /&gt;
|-&lt;br /&gt;
| Mempool view || ViewMemPool || pCoinsTip || This object brings the mempool into view, meaning it can see both a UTXO set and the mempool.&amp;lt;br&amp;gt;Its purpose is to enable validation of chains of transactions, a.k.a. &amp;quot;zero-confirmation&amp;quot; transactions.  (If chains of transactions weren&#039;t permitted, the mempool could simply validate against pcoinsTip.)&amp;lt;br&amp;gt;Thus, when queried, it can check if a given input can be found either in the mempool (i.e., &amp;quot;zero-conf&amp;quot;) or in the blockchain&#039;s utxo set (&amp;quot;confirmed.&amp;quot;)&amp;lt;br&amp;gt;Note that this object is not a cache; rather, it is a view that is used by the object below, which does contain a cache.  &amp;lt;br&amp;gt;Creation in code: Its lifetime is that of AcceptToMemoryPool in &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt;.&lt;br /&gt;
|-&lt;br /&gt;
| Mempool cache || ViewCache || Mempool view || The cache for the mempool.  It contains a cache and sets its backend to be the mempool view.&amp;lt;br&amp;gt;Creation in code: Its lifetime is also that of AcceptToMemoryPool in &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt;. &lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Loading the UTXO set&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Access to the coins database is initialized in &amp;lt;u&amp;gt;init.cpp&amp;lt;/u&amp;gt;: 1131-1133: &lt;br /&gt;
&lt;br /&gt;
 pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex);&lt;br /&gt;
 pcoinscatcher = new CCoinsViewErrorCatcher(pcoinsdbview);&lt;br /&gt;
 pcoinsTip = new CCoinsViewCache(pcoinscatcher);&lt;br /&gt;
&lt;br /&gt;
The code starts by initializing a CoinsViewDB, which is equipped with methods to load coins from the LevelDB. &amp;lt;br&amp;gt;&lt;br /&gt;
The error catcher is a little hack that can be ignored. &amp;lt;br&amp;gt;&lt;br /&gt;
Next, the code initalizes pCoinsTip, which is the cache representing the state of the active chain, and is backed by the database view. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Cache vs. Database&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
The FetchCoins function in coins.cpp demonstrates how the code uses the cache vs. the database: &lt;br /&gt;
 1   CCoinsMap::iterator it = cacheCoins.find(txid);&lt;br /&gt;
 2   if (it != cacheCoins.end())&lt;br /&gt;
 3     return it;&lt;br /&gt;
 4   CCoins tmp;&lt;br /&gt;
 5   if (!base-&amp;gt;GetCoins(txid, tmp))&lt;br /&gt;
 6     return cacheCoins.end();&lt;br /&gt;
 7   CCoinsMap::iterator ret = cacheCoins.insert(std::make_pair(txid, CCoinsCacheEntry())).first;&lt;br /&gt;
&lt;br /&gt;
First, the code searches the cache for the coins for a given transaction id. (line 1)&amp;lt;br&amp;gt;&lt;br /&gt;
If found, it returns the &amp;quot;fetched&amp;quot; coins. (lines 2-3) &amp;lt;br&amp;gt;&lt;br /&gt;
If not, it searches the database. (line 5) &amp;lt;br&amp;gt;&lt;br /&gt;
If found in the database, it updates the cache. (line 7) &amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
Note:  if the cache&#039;s backend is another cache, then the term &amp;quot;database&amp;quot; really means &amp;quot;parent cache.&amp;quot; &lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Flushing the Validation Cache to the Blockchain Cache&#039;&#039;  &lt;br /&gt;
&lt;br /&gt;
The validation cache is flushed to the blockchain cache after connecting a block, just before it goes out of scope.  The scope is captured in ConnectTip, and specifically, in the code block &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt;:2231-2243.  In that code block, there is a call to ConnectBlock, during which the code stores the new coins in the validation cache.  (Specifically, see UpdateCoins() in &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt;.)  At the end of the code block, the validation cache is flushed.  Since its &amp;quot;parent view&amp;quot; is also a cache (pcoinsTip, the &amp;quot;blockchain cache&amp;quot;) the code will call the parent&#039;s ViewCache::BatchWrite, which swaps the updated coin entries into its own cache.  (Polymorphism in action: Later, when the the blockchain cache flushes to the database view, the code will run CoinsViewDB::BatchWrite, the last line of which writes to the LevelDB.) &lt;br /&gt;
&lt;br /&gt;
In summary, usage of the validation cache is straightforward: it is instantiated, used, flushed, and goes out of scope in the aforementioned code block. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Flushing the Blockchain Cache to the Database&#039;&#039;  &lt;br /&gt;
&lt;br /&gt;
Flushing the validate cache was simple because the code only shuffled items between two caches in memory (of which no one is aware outside of the caching code.)  Flushing the blockchain cache to the database is a bit more complicated.  At the lowest level, the mechanics of flushing the blockchain cache (pcoinsTip) is the same as the validation cache:  the Flush() method calls BatchWrite on its backend (the &amp;quot;base&amp;quot; pointer), and in this case that means BatchWrite on the database view.  Up a level, Flush() is called from FlushStateToDisk (FSTD) - &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt;:2098.  FlushStateToDisk is invoked at a few different points, with a given &#039;&#039;mode&#039;&#039;: &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! Flush Mode !! Description !! When called&lt;br /&gt;
|-&lt;br /&gt;
| IF_NEEDED || Flush only if the cache is over its size limit. || Right after connecting (or disconnecting) a block and flushing the validation cache.&amp;lt;br&amp;gt;See ConnectTip / DisconnectTip.&lt;br /&gt;
|-&lt;br /&gt;
| ALWAYS || Flush cache. || During initialization only. &lt;br /&gt;
|-&lt;br /&gt;
| PERIODIC || Here, the code considers other data points to decide whether to flush.&amp;lt;br&amp;gt;Is the code &#039;&#039;almost&#039;&#039; over its size limit?&amp;lt;br&amp;gt;Has it been a long time since the cache was flushed?&amp;lt;br&amp;gt;If so, then proceed.|| At end of ActivateBestChain()&amp;lt;br&amp;gt;(Code comment: &amp;quot;write changes periodically to disk, after relay&amp;quot;). &lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The idea is to flush the block cache frequently (to avoid having to download a large number of blocks if the program crashes), but the coins cache infrequently (in order to maximize the benefit from the coins cache.) &lt;br /&gt;
&lt;br /&gt;
Specifically, the block cache is guaranteed to be flushed once an hour, whereas the coins cache once per day.  (See here:  [https://github.com/bitcoin/bitcoin/pull/6102#issuecomment-98847663 Sipa comment on PR 6102])&lt;br /&gt;
&lt;br /&gt;
The FlushStateToDisk code is well-commented so for more info, the curious reader can check &amp;lt;u&amp;gt;main.cpp&amp;lt;/u&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
==Raw undo data (rev*.dat)==&lt;br /&gt;
&lt;br /&gt;
The undo data contains the information that is necessary to disconnect or &amp;quot;roll back&amp;quot; a block: specifically, the coins that were spent by the block in question.&lt;br /&gt;
&lt;br /&gt;
So, the data being written is essentially a set of CTxOut objects.  (A CTxOut is simply an amount and a script - see &amp;lt;u&amp;gt;primitives/transaction.h&amp;lt;/u&amp;gt;:107-108).&lt;br /&gt;
&lt;br /&gt;
The matter is complicated slightly by the fact that if the coin is the last one being spent by its transaction, the undo data needs to store the transaction&#039;s metadata (the txn&#039;s block height, whether it&#039;s a coinbase, and its version.) So, if you have a transaction T with outputs O1,O2,O3 spent in that order, for O1 and O2 all that will be written to the undo file is the amount and the script.  For 03, the undo file will have the amount, the script, plus T&#039;s height and version, and whether T is a coinbase.&lt;br /&gt;
&lt;br /&gt;
The undo data is written to the raw file with the following code: &lt;br /&gt;
 fileout &amp;lt;&amp;lt; blockundo; (main.cpp:1567 [UndoWriteToDisk])&lt;br /&gt;
&lt;br /&gt;
This line of code calls the serialization function on the CBlockUndo - which is basically just a vector of coins (CTxOuts.)  Finally, a checksum is written to the undo file. The checksum  is used during initialization to verify that any undo data being checked is intact.  See [https://github.com/bitcoin/bitcoin/pull/2145 Pull 2145]&lt;br /&gt;
&lt;br /&gt;
The undo data is used when disconnecting a block.  The DisconnectBlock() code is discussed further down this wiki page in The Blockchain: Reorganizations.&lt;br /&gt;
&lt;br /&gt;
==Use of LevelDB==&lt;br /&gt;
&lt;br /&gt;
LevelDB is a key-value store that was introduced to store the block index and UTXO set (chainstate) in 2012 as part of the complex &amp;quot;Ultraprune&amp;quot; pull (PR 1677).  See here: [https://github.com/bitcoin/bitcoin/pull/1677/commits the 27 commits on Ultraprune]. &lt;br /&gt;
&lt;br /&gt;
On the subject of why LevelDB is used, core developer Greg Maxwell stated the following to the [http://bitcoin-development.narkive.com/XAPoxKZU/patch-switching-bitcoin-core-to-sqlite-db bitcoin-dev mailing list in October 2015]: &lt;br /&gt;
&lt;br /&gt;
:: I think people are falling into a trap of thinking &amp;quot;It&#039;s a &amp;lt;database&amp;gt;, I know a &amp;lt;black box&amp;gt; for that!&amp;quot;; but the application and needs are very specialized here. . . It just so happens that on the back of the very bitcoin specific cryptographic consensus algorithim there was a slot where a pre-existing high performance key-value store fit; and so we&#039;re using one and saving ourselves some effort... &lt;br /&gt;
&lt;br /&gt;
One might ask whether different nodes could use different databases - as long as they retrieve the same data, what&#039;s the difference? The issue here is &amp;quot;bug-for-bug compatibility&amp;quot; - if one database has a bug that causes records to not be returned under certain circumstances, then all other nodes bst have the same bug, else the network could fork as a result.  &lt;br /&gt;
&lt;br /&gt;
Greg Maxwell stated the following in [http://bitcoin-development.narkive.com/XAPoxKZU/patch-switching-bitcoin-core-to-sqlite-db the same thread referenced above (in response to a proposal to switch to using sqlite)]: &lt;br /&gt;
&lt;br /&gt;
:: ...[D]atabases sometimes have errors which cause them to fail to return records, or to return stale data. And if those exist consistency must be maintained; and &amp;quot;fixing&amp;quot; the bug can cause a divergence in consensus state that could open users up to theft.&lt;br /&gt;
&lt;br /&gt;
:: Case in point, prior to leveldb&#039;s use in Bitcoin Core it had a bug that, under rare conditions, could cause it to consistently return not found on records that were really there. . . Leveldb fixed this serious bug in a minor update.  But deploying a fix like this in an uncontrolled manner in the bitcoin network would potentially cause a fork in the consensus state; so any such fix would need to be rolled out in an orderly manner.&lt;/div&gt;</summary>
		<author><name>Mrbandrews</name></author>
	</entry>
</feed>