-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathblockchain.js
53 lines (44 loc) · 1.19 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
class Blockchain {
constructor() {
this.chain = [];
this.currentTransactions = [];
this.newBlock(100, "1"); // Genesis block
}
newBlock(proof, previousHash) {
const block = {
index: this.chain.length + 1,
timestamp: Date.now(),
transactions: this.currentTransactions,
proof: proof,
previous_hash:
previousHash || this.hash(this.chain[this.chain.length - 1]),
};
this.currentTransactions = [];
this.chain.push(block);
return block;
}
newTransaction(sender, recipient, amount) {
this.currentTransactions.push({ sender, recipient, amount });
return this.lastBlock().index + 1;
}
hash(block) {
const blockString = JSON.stringify(block);
return CryptoJS.SHA256(blockString).toString();
}
proofOfWork(lastProof) {
let proof = 0;
while (!this.validProof(lastProof, proof)) {
proof++;
}
return proof;
}
validProof(lastProof, proof) {
const guess = `${lastProof}${proof}`;
const guessHash = CryptoJS.SHA256(guess).toString();
return guessHash.startsWith("0000");
}
lastBlock() {
return this.chain[this.chain.length - 1];
}
}
const blockchain = new Blockchain();