-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
38 lines (29 loc) · 1.06 KB
/
Copy pathindex.js
File metadata and controls
38 lines (29 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// This index.js is based off this Tutorial:
//https://medium.com/coinmonks/understanding-and-building-your-own-tiny-blockchain-in-javascript-a16f2137cfec
const sha256 = require('js-sha256');
class Block {
constructor(index, timestamp, data, prevHash) {
this.index = index;
this.timestamp = timestamp;
this.data = data;
this.prevHash = prevHash;
this.thisHash = sha256(
this.index + this.timestamp + this.data + this.prevHash
);
}
}
const createGenesisBlock = () => new Block(0, Date.now(), 'Genesis Block', '0');
const nextBlock = (lastBlock, data) =>
new Block(lastBlock.index + 1, Date.now(), data, lastBlock.thisHash);
const createBlockchain = num => {
const blockchain = [createGenesisBlock()];
let previousBlock = blockchain[0];
for (let i = 1; i < num; i += 1) {
const blockToAdd = nextBlock(previousBlock, `This is block #${i}`);
blockchain.push(blockToAdd);
previousBlock = blockToAdd;
}
console.log(blockchain);
};
const lengthToCreate = 20;
createBlockchain(lengthToCreate);