I keep getting an error stating that it cannot read the return in getLatestBlock. I literally followed a YouTube video step - by - step. It worked for him I don't understand what i'm doing wrong?
The video was released in 2017 - have there been changes to JS that i'm unaware of? Thanks all.
const SHA256 = require("crypto-js/sha256");
class Block {
constructor(index, timestamp, data, previousHash = "") {
this.index = index;
this.timestamp = timestamp;
this.data = data;
this.previousHash = previousHash;
this.hash = this.calculateHash();
}
// Hash identifies the block
calculateHash() {
return SHA256(
this.index +
this.previousHash +
this.timestamp +
JSON.stringify(this.data)
).toString();
}
}
class Blockchain {
contstructor() {
this.chain = [this.createGenesisBlock()];
}
createGenesisBlock() {
return new Block(0, "01/01/2017", "Genesis block", "0");
}
getLatestBlock() {
this.chain[this.chain.length - 1];
}
addBlock(newBlock) {
newBlock.previousHash = this.getLatestBlock().hash;
newBlock.hash = newBlock.calculateHash();
this.chain.push(newBlock);
}
}
let savejeeCoin = new Blockchain();
savejeeCoin.addBlock(new Block(1, "10/07/2017", { amount: 4 }));
savejeeCoin.addBlock(new Block(2, "12/07/2017", { amount: 10 }));
console.log(JSON.stringify(savejeeCoin, null, 4));
First of all, there's a typo in your Blockchain class:
contstructor should be constructor. That's why you don't get your stuff initialized and get the error.
I would refactor the thing a bit:
Hope this helps...It looks more OOP to me.
Cheers
const SHA256 = require("crypto-js/sha256");
class Block {
get amount() {
return this._amount;
}
get hash() {
return this._hash;
}
get index() {
return this._index;
}
get timestamp() {
return this._timestamp;
}
constructor(index, amount, prevHash = '') {
// make all props private so they can be written only once
this._index = index;
this._timestamp = +new Date();
this._amount = amount;
this._hash = SHA256(
`${this.index}-${prevHash}-${this.timestamp}-${this.amount}`
).toString();
}
}
class BlockChain {
get chain() {
return this._chain;
}
constructor() {
this._chain = [];
this.addBlock(0, 'Genesis block');
}
getCurrentHash() {
this.chain[this.chain.length - 1].hash;
}
addBlock(amount, prevHash = this.getCurrentHash()) {
this.chain.push(new Block(this.chain.length - 1, amount, prevHash));
}
}
let savejeeCoin = new Blockchain();
savejeeCoin.addBlock(4);
savejeeCoin.addBlock(10);
console.log(JSON.stringify(savejeeCoin, null, 4));
Blitz here where I implemented private members (#) and a build fn to print single blocks and the chain...