如何使用node.js打印区块链中的当前区块?

How to print the current block in the blockchain using node.js?

我有一个简单的区块链来生成区块。我只想打印当前块。

我的代码:

class Block {
    constructor(index, data) {
       this.index = index;
       this.timestamp = Date.now();
       this.data = data;
       this.id = uuidv4();
    }   
    static genesis(){
        return new this(0, 'data gensis');
    }
}

class BlockChain {
    constructor() {
       this.chain = [Block.genesis()];
    }
    addBlock(data) {
       let index = this.chain.length;
       let block = new Block(index, data);
       this.chain.push(block);

    }
}

打印链:

let BChain = new BlockChain();
BChain.addBlock(jsMsgData.msg)
console.log(JSON.stringify(BChain, null, 4));

输出:

{
    "chain": [
        {
            "index": 0,
            "timestamp": 1615484160580,
            "data": "data gensis",
            "id": "5326f3e4-67d9-48b7-b2db-9b8daf16b405"
        },
        {
            "index": 1,
            "timestamp": 1615484160581,
            "data": [
                {
                    "parent": "1",
                    "child": "2"
                },
                {
                    "parent": "3",
                    "child": "4"
                }
            ],
            "id": "71ac1cf4-621b-4631-b81e-cfeaca7ca5f5"
        }
    ]
}

我收到这样的数据:

client.on('message', function (topic, message) {
   const jsArray = JSON.parse(message);
        jsArray.forEach(jsMsgData => {
              BChain.addBlock(jsMsgData.msg)
         });
}

我想打印当前块(例如索引 1)。

请问怎么做到的?

提前致谢。

要获取当前区块(基本上是链上的最后一个区块),您可以在区块链 class 上添加一个 getCurrentBlock 方法,就像这样

class BlockChain {
  constructor() {
     this.chain = [Block.genesis()];
  }
  addBlock(data) {
     let index = this.chain.length;
     let block = new Block(index, data);
     this.chain.push(block);

  }

  getCurrentBlock() {
    return this.chain[this.chain.length - 1];
  }
}

let BChain = new BlockChain();
BChain.addBlock(jsMsgData.msg)

BChain.getCurrentBlock() // should  return the current  block  here