I built a little blockchain-in-a-browser in ClojureScript to help understand the underlying algorithms.
You can simulate a network of peers by opening multiple browser tabs. Each peer can mine blocks and make transactions independently and the resulting blockchain will resolve conflicts correctly across all tabs.
A blockchain works by laying down a chain of blocks of transaction data.
Each block in the chain contains a cryptographic hash with two important properties:
- It proves a link to the previous block.
- It proves that difficult computational work has been done.
The proof-of-work is accomplished by iteratively updating a nonce until a low-probability hash is discovered.
These two properties mean a blockchain is digital amber.
If somebody wants to modify a transaction deep inside the amber it would be very difficult because they would have to re-create every layer of the blockchain by doing as much work as the original process required.
In my browser blockchain the hashing is implemented like this:
(hash-object [timestamp transactions previous-hash nonce])
As you can see the previous block's hash is included in the current block.
The hashing is performed iteratively in a loop until a hash with at least one byte of leading zeroes is found:
(loop [c 0]
(let [candidate-block (make-block (now) transactions previous-hash new-index (make-nonce))]
(if (not= (aget (candidate-block :hash) 0) 0)
(recur (inc c))