A distributed database that maintains a continuously growing list of ordered records.
npm install vanillachain-core> A distributed database that maintains a continuously growing list of ordered records.
If we look for the definition of blockchain in Wikipedia) we will find something like:
> Blockchain is a distributed database that maintains a continuously-growing list of records called blocks secured from tampering and revision.
So we will work on this concept extracting the most important points that VanillaChain has to solve:
* Use HTTP interface in each node to add new blocks or find them.
* Use Websockets in order to communicate with the network of nodes.
* Find a way to add/remove nodes from the network.
* Super simple protocol in our P2P communication.
All data will be persisted in JSON* files.
* Use a basic implementation of Proof of work.
That is the reason why cryptocurrencies are based on blockchains. You don't want people changing their transactions after they've made them!
We will start by defining the block structure. Only the most essential properties are included at the block at this point.
* data: Any data that is included in the block.
* timestamp: A UTC timestamp using numeric format.
* nonce : A number of attempts to generate the correct hash.
* hash: A sha256 hash taken from the content of the block.
* previousHash: A reference to the hash of the previous block.
The code for the block structure looks like the following:
```
class Block {
constructor({
data = {}, previousHash, timestamp = new Date().getTime(),
} = {}) {
this.data = data;
this.nonce = 0;
this.previousHash = previousHash;
this.timestamp = timestamp;
}
}
We calculate the hash of the block using the following code:
`
import { SHA256 } from 'crypto-js';
export default ({
previousHash, timestamp, data = {}, nonce = 0,
} = {}) => SHA256(previousHash + timestamp + JSON.stringify(data) + nonce).toString();
`
To fix this problem, blockchains add a nonce value. This is a number that gets incremented until a good hash is found. And because you cannot predict the output of a hash function, you simply have to try a lot of combinations before you get a hash that satisfies the difficulty. Looking for a valid hash (to create a new block) is also called mining in the cryptoworld.
Adjusting the difficulty we can decide how long it would take to calculate a new block. Let's see the code of our mining function:
``
mine(difficulty = 0) {
this.hash = calculateHash(this);
while (this.hash.substring(0, difficulty) !== Array(difficulty + 1).join('0')) {
this.nonce += 1;
this.hash = calculateHash(this);
}
}
file in the root of the project. You just to choose the kind of instance and its port of running.`
const blockchain = new Blockchain();
const { hash: previousHash } = blockchain.latestBlock;const data = { hello: 'world' };
blockchain.addBlock(data, previousHash);
``