Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

259
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda