MCPcopy Create free account
hub / github.com/Savjee/SavjeeCoin / Blockchain

Class Blockchain

src/blockchain.js:141–330  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

139}
140
141class Blockchain {
142 constructor() {
143 this.chain = [this.createGenesisBlock()];
144 this.difficulty = 2;
145 this.pendingTransactions = [];
146 this.miningReward = 100;
147 }
148
149 /**
150 * @returns {Block}
151 */
152 createGenesisBlock() {
153 return new Block(Date.parse('2017-01-01'), [], '0');
154 }
155
156 /**
157 * Returns the latest block on our chain. Useful when you want to create a
158 * new Block and you need the hash of the previous Block.
159 *
160 * @returns {Block[]}
161 */
162 getLatestBlock() {
163 return this.chain[this.chain.length - 1];
164 }
165
166 /**
167 * Takes all the pending transactions, puts them in a Block and starts the
168 * mining process. It also adds a transaction to send the mining reward to
169 * the given address.
170 *
171 * @param {string} miningRewardAddress
172 */
173 minePendingTransactions(miningRewardAddress) {
174 const rewardTx = new Transaction(
175 null,
176 miningRewardAddress,
177 this.miningReward
178 );
179 this.pendingTransactions.push(rewardTx);
180
181 const block = new Block(
182 Date.now(),
183 this.pendingTransactions,
184 this.getLatestBlock().hash
185 );
186 block.mineBlock(this.difficulty);
187
188 debug('Block successfully mined!');
189 this.chain.push(block);
190
191 this.pendingTransactions = [];
192 }
193
194 /**
195 * Add a new transaction to the list of pending transactions (to be added
196 * next time the mining process starts). This verifies that the given
197 * transaction is properly signed.
198 *

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected