I am trying to write a simple blockchain in VSC on Windows 10. Running the node however results in an error that I cannot solve.
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();
}
calculateHash(){
return SHA256(this.index + this.previousHash + this.timestamp + JSON.stringify(this.data)).toString();
}
}
class Blockchain{
constructor(){
this.chain = [this.createGenesisBlock()];
}
createGenesisBlock(){
return new Block(0, "01/01/2022", "Genesis block", "0");
}
getLatestBlock(){
return this.chain[this.chain.lenght - 1];
}
addBlock(newBlock){
newBlock.previousHash = this.getLatestBlock().hash;
newBlock.hash = newBlock.calculateHash();
this.chain.push(newBlock);
}
}
let simCoin = new Blockchain();
simCoin.addBlock(new Block(1, "02/01/2022", {amount: 2 }));
simCoin.addBlock(new Block(2, "03/01/2022", {amount: 2 }));
console.log(JSON.stringify(simCoin, null, 4));
Yields this error:
C:\Users\simon\Desktop\Programmieren\Javascript\SimCoin\main.js:31
newBlock.previousHash = this.getLatestBlock().hash;
^
TypeError: Cannot read properties of undefined (reading 'hash')
at Blockchain.addBlock (C:\Users\simon\Desktop\Programmieren\Javascript\SimCoin\main.js:31:54)
at Object.<anonymous> (C:\Users\simon\Desktop\Programmieren\Javascript\SimCoin\main.js:38:9)
Where did I go wrong?
>Solution :
Apparently return this.chain[this.chain.lenght - 1]; is undefined.
Probably due to your typo, so re write:
return this.chain[this.chain.length - 1];