-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathblock.js
More file actions
50 lines (36 loc) · 1.37 KB
/
block.js
File metadata and controls
50 lines (36 loc) · 1.37 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 hexToBinary=require('hex-to-binary');
const {GENESIS_DATA,MINE_RATE}=require('./config');
const cryptoHash=require('./crypto-hash');
class Block{
constructor({timestamp,lastHash,data,hash,nonce, difficulty}){
this.timestamp=timestamp;
this.lastHash=lastHash;
this.data=data;
this.hash=hash;
this.nonce=nonce;
this.difficulty=difficulty;
}
static genesis(){
return new this(GENESIS_DATA);
}
static minedBlock({lastblock,data}){
const lastHash=lastblock.hash;
let difficulty=lastblock.difficulty;
let timestamp, hash;
let nonce=0;
do {
nonce++;
timestamp=Date.now();
difficulty=Block.adjustDifficulty({originalBlock:lastblock, timestamp})
hash=cryptoHash(timestamp,lastHash,data,nonce,difficulty);
} while (hexToBinary(hash).substring(0, difficulty) !== '0'.repeat(difficulty));
return new this({timestamp,lastHash,data,difficulty,nonce,hash});
}
static adjustDifficulty({originalBlock,timestamp}){
const {difficulty}= originalBlock;
if(difficulty<1) return 1;
if((timestamp-originalBlock.timestamp) >= MINE_RATE) return difficulty-1;
return difficulty+1;
}
}
module.exports=Block;