-1

我使用https://bitcoin.org下载了很多区块链数据,我拿了一些文件并尝试使用 bitcoinj 库对其进行分析。

我想从每笔交易中获取信息:-谁发送比特币,-多少,-谁接收比特币。

我用:

   <dependency>
      <groupId>org.bitcoinj</groupId>
      <artifactId>bitcoinj-core</artifactId>
      <version>0.15.10</version>
    </dependency>

我有一个代码:

NetworkParameters np = new MainNetParams();
Context.getOrCreate(MainNetParams.get());
BlockFileLoader loader = new BlockFileLoader(np,List.of(new File("test/resources/blk00450.dat")));

for (Block block : loader) {
  for (Transaction tx : block.getTransactions()) { 
    System.out.println("Transaction ID" + tx.getTxId().toString());
    for (TransactionInput ti : tx.getInputs()) {
      // how to get wallet addresses of inputs? 
    }

  
    // this code works for 99% of transactions but for some throws exceptions
    for (TransactionOutput to : tx.getOutputs()) {
      // sometimes this line throws: org.bitcoinj.script.ScriptException: Cannot cast this script to an address
      System.out.println("out address:" + to.getScriptPubKey().getToAddress(np));
      System.out.println("out value:" + to.getValue().toString());
    }
  }
}

你能分享一些适用于区块链中所有交易的片段吗?

4

1 回答 1

-1

至少有两种交易类型,P2PKHP2SH。您的代码适用于 P2PKH,但不适用于 P2SH。您可以从以下位置更改该行:

System.out.println("out address:" + to.getScriptPubKey().getToAddress(np));

至:

System.out.println("out address:" + to.getAddressFromP2PKHScript(np)!=null?to.getAddressFromP2PKHScript(np):to.getAddressFromP2SH(np));

比特币的 API 说方法getAddressFromP2PKHScript()getAddressFromP2SH()已被弃用,我还没有找到合适的方法。

然而,P2SH 的意思是“Pay to Script Hash”,这意味着它可以包含两个或多个公钥来支持多重签名。此外,getAddressFromP2SH() 只返回一个地址,也许这就是它被弃用的原因。

我还写了一个方便的方法来检查一个块的输入和输出:

private void printCoinValueInOut(Block block) {
    Coin blockInputSum = Coin.ZERO;
    Coin blockOutputSum = Coin.ZERO;

    System.out.println("--------------------Block["+block.getHashAsString()+"]------"+block.getPrevBlockHash()+"------------------------");
    for(Transaction tx : block.getTransactions()) {
        Coin txInputSum = tx.getOutputSum();
        Coin txOutputSum = tx.getOutputSum();   
        blockInputSum = blockInputSum.add(txInputSum);  
        blockOutputSum = blockOutputSum.add(txOutputSum);
        System.out.println("Tx["+tx.getTxId()+"]:\t" + txInputSum + "(satoshi) IN, " + txOutputSum +  "(satoshi) OUT.");
    }
    System.out.println("Block total:\t" + blockInputSum + "(satoshi) IN, " + blockOutputSum +  "(satoshi) OUT. \n");
}
于 2021-08-02T10:35:46.113 回答