Skip to content

blockchain.ex

Alex Dovzhanyn edited this page Feb 19, 2018 · 1 revision

This module stores functions related to the actual blockchain and its separate parts. Unlike most other modules in the codebase, this one does not contain a struct. Our actual chain of blocks is stored in a List.

Functions

initialize/0

This function is called whenever the miner starts up. We first check to see if LevelDB is empty, and if it is, we generate a genesis block and store it into LevelDB. If the datastore is not empty, we just retrieve the full existing chain from the datastore.

add_block/2

Takes in the existing chain and a new, freshly mined block. The block is prepended to the chain, and also stored in LevelDB. This function should only be called after a block has been validated, as it has no validation protection itself. The transactions within the block are enumerated upon and the UTXOs spent as inputs are removed from the .utxo/ datastore, while the new UTXOs from the outputs are added to the store.

recalculate_difficulty/1

Using the chain, calculate the necessary block difficulty. We want to maintain a 2 minute average block time (that is, 1 new block mined every 2 minutes). This function is called after every 10,080 blocks (roughly every 2 weeks). By taking the timestamp of the block at index 0, and subtracting the timestamp of block at index 10,080, we will have the totall amount (in seconds) that it took to mine all 10,080 blocks. Dividing this number by 10,080 will give the average time spent to mine each block (in seconds). We then compare the average with our target average of 120 seconds/block, and find the ratio at which hashing is happening based on what we want. So if the average time per block is 60 seconds, we divide 120 / 60 and get 2. Therefore, the network is hashing at 2x the speed of what it would take to hit a 2 minute blocktime. To scale proportionally, we find the base16 logarithm of the speed ratio, which will give a number (either positive or negative) by which we should increase / decrease the difficulty.