-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBlock.js
53 lines (45 loc) · 1.53 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
'use strict';
import calcHash from 'crypto-js/sha256';
export default class Block {
constructor(miner, initialTransaction = '', previousHash = '') {
this.miner = miner;
this.transactions = {
'initialTransaction': initialTransaction,
'participants': [],
'gameStartPolls': [],
'cardDispenseHistory': [],
'bettingHistory': [],
};
this.timestamp = new Date();
this.previousBlockHash = previousHash;
this.nonce = 0;
this.blockHash = this.calculateBlockHash();
}
getNumParticipants = () => {
return this.transactions.cardDispense.length;
};
addTransaction = (type, data) => {
this.transactions[type].push(data);
};
replaceTransaction = (newTransactions) => {
this.transactions = newTransactions;
};
calculateBlockHash = () => {
return calcHash(this.timestamp + JSON.stringify(this.transaction) + this.previousBlockHash + this.nonce).toString();
};
mine = (difficulty) => {
let zeros = "";
for (let i = 0; i < difficulty; i++) zeros += "0";
while(true) {
const hash = this.calculateBlockHash();
if (hash.substring(0, difficulty) === zeros) {
this.blockHash = hash;
break;
}
this.nonce++;
}
console.log("Mining completed!");
console.log("New block\'s nonce: " + this.nonce);
console.log("New block\'s blockHash: " + this.blockHash);
};
}