by capableweb · 3y ago · 0 comments
const crypto = require('crypto');
function Block(index, data, prevHash) {
this.index = index;
this.data = data;
this.prevHash = prevHash;
this.hash = crypto.createHash('sha256').update(`${this.index}${this.data}${this.prevHash}`).digest('hex');
}
function Blockchain() {
this.chain = [new Block(0, 'Genesis', '0')];
}
Blockchain.prototype.add = function(data) {
const prevBlock = this.chain[this.chain.length - 1];
this.chain.push(new Block(prevBlock.index + 1, data, prevBlock.hash));
};
Any ways we can make it even shorter? const crypto = require('crypto')
const Block = (index, data, prevHash) => ({
index,
data,
prevHash,
hash: crypto.createHash('sha256').update(index + data + prevHash).digest('hex'),
})
const Blockchain = () => ({
chain: [Block(0, 'Genesis', '0')],
add(data) {
return this.chain.push(
Block(this.chain.at(-1).index + 1, data, this.chain.at(-1).hash)
)
},
})