[英]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));
output:
{
"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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.