請求帶有 bitcore-p2p 的 merkle 塊

在這個例子中,我們將向比特幣網路詢問 merkle 塊號 442603

為此,我們需要傳送 filterload 訊息 ,然後我們必須使用庫存型別 MSG_MERKLEBLOCK 傳送 getdata 訊息

對等體應回覆所請求塊的 merkleblock 訊息和所請求塊中與過濾器匹配的任何事務的 tx 訊息

bitcore-p2p 中, 我們需要為每個我們想要的資訊型別註冊一個事件。

let Pool = require('bitcore-p2p').Pool;
let BloomFilter = require('bitcore-p2p').BloomFilter;
let NetworksData = require('bitcore-lib').Networks;
let Messages = require('bitcore-p2p').Messages;

let network = 'livenet';  // Network can be livenet or testnet
let txs = []; // Here we store the transactions
let filteredBlocks = []; // Here we store the merkleblocks

// Date that we are loocking for
let data = {
  code: '88adcf0215d5fcbca5c6532aaecffb48128cf1a6',  // 1DTh7XPb42PgCFnuMHSitMPWxCfNNFej8n in hex fromat
  format: 'hex',
};

// Isatnciate and connect a node Pool
let pool = new Pool({network: NetworksData[network]});
pool.connect();

// Create a filter and a bitcoin message with the filter
let filter = BloomFilter.create(1000, 0.1).insert(new Buffer(data.code, data.format));
let filterLoad = new Messages({network: NetworksData[network]}).FilterLoad(filter);

// Create a bitcoin message for require a merkleblock
let blockHashRequested = '0000000000000000004f8325a66388e22c10e6de9f0f6e5809eaf1e0393efe02';
let getDataForFilteredBlock = new Messages({network: NetworksData[network]}).GetData.forFilteredBlock(blockHashRequested);

// Transactions and merkleblock are sent in different messages
pool.on('peertx', function(peer, message) {
  txs.push({
    peer: peer,
    message: message,
  });

  console.log('Recived from: ', peer.host);
  console.log('The transaction: ', message.transaction.hash);
});

pool.on('peermerkleblock', function(peer, message) {
  filteredBlocks.push({
    peer: peer,
    message: message,
  });

  console.log('Recived from: ', peer.host);
  console.log('The merkleBlock: ', message.merkleBlock.header.hash);
});

// Wait for pool to connect
setTimeout(function(){
  pool.sendMessage(filterLoad);
  pool.sendMessage(getDataForFilteredBlock);
}, 5000);

//Recived from:  138.68.111.63
//The merkleBlock:  0000000000000000004f8325a66388e22c10e6de9f0f6e5809eaf1e0393efe02
//Recived from:  138.68.111.63
//The transaction:  9aec6cc42ddcf5900d280f3fa598f5cdb101f00614785165f777a6856314f4d9
//Recived from:  103.3.61.48
//The merkleBlock:  0000000000000000004f8325a66388e22c10e6de9f0f6e5809eaf1e0393efe02
//Recived from:  103.3.61.48
//The transaction:  9aec6cc42ddcf5900d280f3fa598f5cdb101f00614785165f777a6856314f4d9