Blockchain de criptomoeda simples usando JavaScript
const sha256 = require('sha256');
function Blockchain() {
this.chain = []; //stores our blocks
this.pendingTransactions = []; //this contains our pending transaction before create a new block
this.createNewBlock(100, '0', '0');
}
Blockchain.prototype.createNewBlock = function(nonce, prevBlockHash, hash){
const newBlock = {
index : this.chain.length + 1,
timestamp : Date.now(),
transactions : this.pendingTransactions,
nonce : nonce,
prevBlockHash : prevBlockHash,
hash : hash
};
this.pendingTransactions = [];
this.chain.push(newBlock);
return newBlock;
}
Blockchain.prototype.getLastBlock = function() {
return this.chain[this.chain.length - 1];
}
Blockchain.prototype.createNewTransaction = function(amount, sender, recipient) {
const NewTransaction = {
amount : amount,
sender : sender,
recipient : recipient
};
this.pendingTransactions.push(NewTransaction);
return this.getLastBlock()['index'] +1;
}
Blockchain.prototype.hashBlock = function(prevBlockHash, currentBlockData, nonce) {
const dataString = prevBlockHash + nonce.toString() + JSON.stringify(currentBlockData);
const hash = sha256(dataString);
return hash;
}
Blockchain.prototype.proofOfWork = function(prevBlockHash, currentBlockData) {
let nonce = 0;
let hash = this.hashBlock(prevBlockHash, currentBlockData, nonce);
while (hash.substring(0,4) !== '0000') {
nonce++;
hash = this.hashBlock(prevBlockHash, currentBlockData, nonce);
}
return nonce;
}
module.exports = Blockchain;
Outrageous Ostrich