【问题标题】:How to print the current block in the blockchain using node.js?如何使用 node.js 打印区块链中的当前块?
【发布时间】:2021-03-12 02:06:15
【问题描述】:

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

我的代码:

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)。

请问,怎么可能?

提前致谢。

【问题讨论】:

  • 你怎么知道当前块是哪个?
  • 我是从MQTT协议实时接收的。
  • 您是如何收到的。是吗?
  • console.log(JSON.stringify(BChain.chain[BChain.chain.length - 1], null, 4));
  • @fortunee 我已经更新了我的问题,请检查一下?

标签: javascript node.js blockchain


【解决方案1】:

要获取当前块(基本上是链上的最后一个块),您可以像这样在 Blockchain 类上添加 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

【讨论】:

    猜你喜欢
    • 2019-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-18
    • 2016-02-08
    • 1970-01-01
    • 1970-01-01
    • 2021-10-25
    相关资源
    最近更新 更多