Repository navigation
Expand file tree
/
Copy pathblock.js
More file actions
50 lines (42 loc) · 1.39 KB
/
Copy pathblock.js
File metadata and controls
50 lines (42 loc) · 1.39 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
// const CryptoUtil = require("./util/crypto");
// const Proofofwork = require("./proofofwork")
import Proofofwork from './proofofwork.js'
import {CryptoUtil} from './util/crypto.js';
import {Transaction} from "./transaction.js";
class Block{
constructor(index, timeStamp, txs, preBlockHash){
this.index = index;
this.timeStamp = timeStamp;
this.transactions = txs;
this.preBlockHash = preBlockHash;
this.hash = this.calculateHash()
this.nonce = 0;
}
calculateHash() {
return CryptoUtil.hash(this.preBlockHash + JSON.stringify(this.transactions) + this.timeStamp)
}
static newGenesisBlock(coinbase) {
return this.newBlock(0, 1508270000000, [coinbase], "");
}
static newBlock(index, timeStamp, txs, preBlockHash) {
let block = new Block(index, timeStamp, txs, preBlockHash);
let pow = new Proofofwork(block);
let ret = pow.run();
block.hash = ret[0];
block.nonce = ret[1];
return block;
}
static fromJson(data) {
let block = new Block();
let obj = JSON.parse(data);
Object.entries(obj).forEach(([key, value]) => {
if (key === "transactions") {
block[key] = Transaction.fromJSON(value);
} else {
block[key] = value;
}
});
return block;
}
}
export default Block