Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class BlockChain {
- constructor() {
- this.chain = [this.createGenesisBlock()];
- this.difficulty = 2;
- this.pendingTransactions = [];
- this.miningReward = 100;
- }
- createGenesisBlock() {
- return new Block("2018-06-29", "Genesis Block", "0");
- }
- getLatestBlock() {
- return this.chain[this.chain.length - 1];
- }
- minePendingTransactions(miningRewardAdress) {
- const block = new Block(Date.now(), this.pendingTransactions);
- block.mineBlock(this.difficulty);
- console.log("Block mined!");
- this.chain.push(block);
- this.pendingTransactions = [
- new Transaction(null, miningRewardAdress, this.miningReward),
- ];
- }
- createTransaction(transaction) {
- this.pendingTransactions.push(transaction);
- }
- getBalanceOfAddres(address) {
- let balance = 0;
- for(const block of this.chain) {
- for(const transaction of block.transactions) {
- if(transaction.fromAddress === address)
- balance -= transaction.amount;
- if(transaction.toAddress === address)
- balance += transaction.amount;
- }
- }
- return balance;
- }
- isChainValid() {
- for(let i = 1; i < this.chain.length; i++) {
- const currentBlock = this.chain[i];
- const prevBlock = this.chain[i - 1];
- if(currentBlock.hash !== currentBlock.calculateHash())
- return false;
- if(currentBlock.prevHash !== prevBlock.hash)
- return false;
- }
- return true;
- }
- }
- export default BlockChain;
Add Comment
Please, Sign In to add comment