This repository has been archived by the owner on Nov 10, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBlockchain.js
72 lines (56 loc) · 1.69 KB
/
Blockchain.js
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
'use strict';
const Block = require('./Block.js')
class Blockchain {
constructor() {
// Genesis block hardcoded, the hash is created at construction time.
const genesisBlock = new Block(0, null, (new Date()).valueOf(), "Welcome to the Blockchain!");
this.blockchain = [];
this.blockchain.push(genesisBlock);
}
getLatestBlock() {
return this.blockchain[this.blockchain.length - 1];
}
addData(blockData) {
const latestBlock = this.getLatestBlock();
const newBlock = new Block(latestBlock.index + 1, latestBlock.hash, (new Date()).valueOf(), blockData);
if (newBlock.isValid(latestBlock)) {
this.blockchain.push(newBlock);
}
return newBlock;
}
isValid() {
let previousBlock, isValid = true;
for (let i = 0; i < this.blockchain.length; i++) {
const currentBlock = this.blockchain[i];
const validBlock = (currentBlock.index === i) && currentBlock.isValid(previousBlock) && (currentBlock.calculateHash() === currentBlock.hash);
if (!validBlock) {
isValid = false;
break;
}
previousBlock = currentBlock;
}
return isValid;
}
conciliate(otherBlockchain) {
if (this.isValid()) {
if (otherBlockchain.isValid()) {
if (otherBlockchain.blockchain.length > this.blockchain.length) {
this.blockchain = otherBlockchain.blockchain;
}
}
} else {
if (otherBlockchain.isValid()) {
this.blockchain = otherBlockchain.blockchain;
}
}
}
show(logger) {
if (!logger) {
logger = console.log;
}
for (let i = 0; i < this.blockchain.length; i++) {
logger(`${this.blockchain[i]}`);
}
}
}
module.exports = Blockchain