-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
79 lines (69 loc) · 1.86 KB
/
main.js
File metadata and controls
79 lines (69 loc) · 1.86 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
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
73
74
75
76
77
78
79
const crypto = require("crypto");
class Block {
constructor(index, data, prevHash) {
this.index = index;
this.timestamp = Math.floor(Date.now() / 1000);
this.data = data;
this.prevHash = prevHash;
this.hash = this.getHash();
}
getHash() {
var encript =
JSON.stringify(this.data) + this.prevHash + this.index + this.timestamp;
var hash = crypto
.createHmac("sha256", "secret")
.update(encript)
.digest("hex");
return hash;
}
}
class BlockChain {
constructor() {
this.chain = [];
}
addBlock(data) {
let index = this.chain.length;
let prevHash =
this.chain.length !== 0 ? this.chain[this.chain.length - 1].hash : 0;
let block = new Block(index, data, prevHash);
this.chain.push(block);
}
chainIsValid() {
for (var i = 0; i < this.chain.length; i++) {
if (this.chain[i].hash !== this.chain[i].getHash()) return false;
if (i > 0 && this.chain[i].prevHash !== this.chain[i - 1].hash)
return false;
}
return true;
}
}
const blockChain = new BlockChain();
blockChain.addBlock({
sender: " San Engineer",
receiver: "Frodo",
ammount: 100000,
});
blockChain.addBlock({
sender: "San Developer",
receiver: "Bagins",
ammount: 40000,
});
blockChain.addBlock({
sender: "San Mac",
receiver: "Rings",
ammount: 8,
});
// check receiver true or false
blockChain.chain[0].data.receiver = "Frodo";
// display console on terminal
console.log(
"\n\n----------------------------------------------------------------------------------"
);
console.dir(blockChain, { depth: null });
console.log(
"-----------------------------------------------------------------------------------"
);
console.log("Validity of this blockchain:", blockChain.chainIsValid());
console.log(
"-----------------------------------------------------------------------------------\n\n"
);