-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblockchain.js
64 lines (56 loc) · 1.54 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
const SHA256 = require('sha256');
class Blockchain {
constructor() {
this.chain = [this.createGenesisBlock()];
this.pendingTransactions = [];
}
createGenesisBlock() {
return new Block(0, "0", "Genesis Block");
}
}
Blockchain.prototype.createGenesisBlock = function() {
return {
index: 1,
timestamp: Date.now(),
transactions: [],
nonce: 0,
hash: "genesisHash",
previousBlockHash: "genesisPreviousBlockHash",
};
}
Blockchain.prototype.getLastBlock = function() {
if (this.chain.length > 0) {
return this.chain[this.chain.length - 1];
} else {
throw new Error("Blockchain is empty, there are no blocks to retrieve.");
}
}
Blockchain.prototype.generateHash = function(data) {
return SHA256(data).toString();
};
Blockchain.prototype.createNewTransaction = function(amount, sender, recipient){
if (!this.pendingTransactions) {
this.pendingTransactions = [];
}
const newTransaction = {
amount,
sender,
recipient,
};
this.pendingTransactions.push(newTransaction);
}
Blockchain.prototype.createNewBlock = function(){
const newBlock = {
index: this.chain.length + 1,
timestamp: Date.now(),
transactions: this.pendingTransactions,
nonce: String(Math.random()),
hash: String(Math.random()),
previousBlockHash: this.getLastBlock().hash,
};
newBlock.hash = this.generateHash(JSON.stringify(newBlock));
this.pendingTransactions = [];
this.chain.push(newBlock);
return newBlock;
}
module.exports = Blockchain;