| 73 | } |
| 74 | |
| 75 | class Block { |
| 76 | /** |
| 77 | * @param {number} timestamp |
| 78 | * @param {Transaction[]} transactions |
| 79 | * @param {string} previousHash |
| 80 | */ |
| 81 | constructor(timestamp, transactions, previousHash = '') { |
| 82 | this.previousHash = previousHash; |
| 83 | this.timestamp = timestamp; |
| 84 | this.transactions = transactions; |
| 85 | this.nonce = 0; |
| 86 | this.hash = this.calculateHash(); |
| 87 | } |
| 88 | |
| 89 | /** |
| 90 | * Returns the SHA256 of this block (by processing all the data stored |
| 91 | * inside this block) |
| 92 | * |
| 93 | * @returns {string} |
| 94 | */ |
| 95 | calculateHash() { |
| 96 | return crypto |
| 97 | .createHash('sha256') |
| 98 | .update( |
| 99 | this.previousHash + |
| 100 | this.timestamp + |
| 101 | JSON.stringify(this.transactions) + |
| 102 | this.nonce |
| 103 | ) |
| 104 | .digest('hex'); |
| 105 | } |
| 106 | |
| 107 | /** |
| 108 | * Starts the mining process on the block. It changes the 'nonce' until the hash |
| 109 | * of the block starts with enough zeros (= difficulty) |
| 110 | * |
| 111 | * @param {number} difficulty |
| 112 | */ |
| 113 | mineBlock(difficulty) { |
| 114 | while ( |
| 115 | this.hash.substring(0, difficulty) !== Array(difficulty + 1).join('0') |
| 116 | ) { |
| 117 | this.nonce++; |
| 118 | this.hash = this.calculateHash(); |
| 119 | } |
| 120 | |
| 121 | debug(`Block mined: ${this.hash}`); |
| 122 | } |
| 123 | |
| 124 | /** |
| 125 | * Validates all the transactions inside this block (signature + hash) and |
| 126 | * returns true if everything checks out. False if the block is invalid. |
| 127 | * |
| 128 | * @returns {boolean} |
| 129 | */ |
| 130 | hasValidTransactions() { |
| 131 | for (const tx of this.transactions) { |
| 132 | if (!tx.isValid()) { |
nothing calls this directly
no outgoing calls
no test coverage detected