-
Notifications
You must be signed in to change notification settings - Fork 0
/
Block.js
59 lines (45 loc) · 1.58 KB
/
Block.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
const {GENESIS_Data} = require('./config')
const cryptoHash = require("./crypto-hash");
const hexToBinary = require("hex-to-binary");
class Block {
constructor({timestamp,data,prevHash,hash,nonce,difficulty}){
this.timestamp = timestamp;
this.data = data;
this.prevHash = prevHash;
this.hash = hash;
this.nonce = nonce;
this.difficulty = difficulty;
}
//we dont want that whenever we create a new object our genesis block will be create
static genesis(){
return new this(GENESIS_Data);
}
static mineBlock({prevBlock,data}){
let hash,timestamp;
const prevHash = prevBlock.hash;
const{difficulty}=prevBlock;
let nonce=0;
do{
nonce++;
timestamp=Date.now(); //abcdef ,00 ,00cdef
hash = cryptoHash(timestamp,data,prevHash,nonce,difficulty)
}while(hexToBinary(hash).substring(0,difficulty)!=='0'.repeat(difficulty));
// const timestamp = Date.now();
// const prevHash = prevBlock.hash;
return new this({
timestamp,
data,
prevHash,
hash,
nonce,
difficulty
})
}
}
// const block1 = new Block({hash:"0xab",timestamp:"24/02/2002",prevHash:"0xaaaa",data:"helloooooo"});
// const genesisBlock = Block.genesis();
// console.log(genesisBlock);
// console.log(block1);
// const result = Block.mineBlock({prevBlock:block1, data: "block2"})
// console.log(result)
module.exports = Block;