3 ms·
Here is a correct (OPs is slightly but importantly wrong) and shorter one in JavaScript: const crypto = require('crypto'); function Block(index, data,
by capableweb 4y ago
Here is a correct (OPs is slightly but importantly wrong) and shorter one in JavaScript:
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?
- jonahx 4y agoconst 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) ) }, })