-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathbc.js
85 lines (75 loc) · 2.64 KB
/
bc.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
73
74
75
76
77
78
79
80
81
82
83
84
85
const SHA256 = require("crypto-js/sha256");
// const senderId = document.getElementById("senderid");
// const recepientId = document.getElementById("recepientid");
class CryptoBlock {
constructor( timestamp, data, prevHash = " "){
// this.index = index; // assign the value of index to index key and value as the input in the empty obj{}
this.timestamp = timestamp;
this.data = data;
this.previousHash = prevHash;
this.hash = this.createHash();
this.nonce = 0;
} // 'this' here is refering to the empty object that will be created.
createHash() { // returns created hash of the given data
return SHA256 (
this.prevHash + this.timestamp + JSON.stringify(this.data) + this.nonce
).toString();
}
pow(difficulty) {
while(
this.hash.substring(0,difficulty) !== Array(difficulty + 1).join("0") //array.join returns array as string with parameter as the connector
)
{
this.nonce++;
this.hash = this.createHash();
}
}
}
class CryptoBlockchain {
constructor() {
this.blockchain = [this.startGenesisBlock()]; //first block or starting point for a particular blockchain
this.difficulty = 4;
}
startGenesisBlock() {
return new CryptoBlock("17/01/2024","intial block of the chain", "0");
}
obtainLatestBlock() {
return this.blockchain[this.blockchain.length-1];
}
addNewBlock(newBlock) {
newBlock.previousHash = this.obtainLatestBlock().hash;
// newBlock.hash = newBlock.createHash();
newBlock.pow(this.difficulty);
this.blockchain.push(newBlock);
// console.log(this.obtainLatestBlock());
}
checkChainValidity() {
for (let i=0;i<this.blockchain.length;i++){
const currentBlock = this.blockchain[i];
const precedingBlock = this.blockchain[i-1];
if(currentBlock.hash !== currentBlock.createHash()){
return false;
}
if(currentBlock.previousHash !== precedingBlock.hash) {return false;}
}
return true;
}
}
// const obj = new CryptoBlockchain();
// // console.log("the blockchain mining in process");
// obj.addNewBlock(
// new CryptoBlock("17/01/2024",{
// sender : `krishan`,
// recepient : `shivam`,
// amount : 200,
// })
// )
// obj.addNewBlock(
// new CryptoBlock("17/01/2024",{
// sender : `krishan`,
// recepient : `shivam`,
// amount : 100,
// })
// )
module.exports = { CryptoBlockchain , CryptoBlock };
// console.log(JSON.stringify(obj, null , 4));