Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot read properties of undefined (reading ('hash')

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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];
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading