Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

261
Visualizações
TypeError: Cannot read properties of undefined (reading 'length') - Blockchain JS

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));
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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:

  1. Allowing to set initial data, using defaults
  2. Move the current hash inside the block, I don't like it very much that each block should contain (and maintain) the previous hash (and half the required memory this way).
  3. Make members private so they can be written only on Block creation
  4. Add getters to read values after creation
  5. Reuse addBlock to create the initial block
  6. Don't pass the date as string, but use timestamp
  7. Save the current timestamp at creation (prevents possible frauds)
  8. Avoid the data object, because it's too arbitrary. Use another class if you need more data, in the meantime I only saved the amount as number.
  9. Concat params differently with a separator (this could be avoided, but it was good for my eyes 😂)
  10. Don't set properties from outside (like hash) after the block constructor is called. Everything (as said before) is set on creation and should be immutable!

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...

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda