org.bitcoinj.core.Block.getTransactions()方法的使用及代码示例

x33g5p2x  于2022-01-17 转载在 其他  
字(16.0k)|赞(0)|评价(0)|浏览(136)

本文整理了Java中org.bitcoinj.core.Block.getTransactions()方法的一些代码示例,展示了Block.getTransactions()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Block.getTransactions()方法的具体详情如下:
包路径:org.bitcoinj.core.Block
类名称:Block
方法名:getTransactions

Block.getTransactions介绍

[英]Returns an immutable list of transactions held in this block, or null if this object represents just a header.
[中]返回此块中保存的事务的不可变列表,如果此对象仅表示头,则返回null。

代码示例

代码示例来源:origin: greenaddress/GreenBits

@Override
public synchronized void onBlocksDownloaded(Peer peer, Block block, @Nullable FilteredBlock filteredBlock, int blocksLeft) {
  blocksInLastSecond++;
  bytesInLastSecond += Block.HEADER_SIZE;
  List<Transaction> blockTransactions = block.getTransactions();
  // This whole area of the type hierarchy is a mess.
  int txCount = (blockTransactions != null ? countAndMeasureSize(blockTransactions) : 0) +
         (filteredBlock != null ? countAndMeasureSize(filteredBlock.getAssociatedTransactions().values()) : 0);
  txnsInLastSecond = txnsInLastSecond + txCount;
  if (filteredBlock != null)
    origTxnsInLastSecond += filteredBlock.getTransactionCount();
}

代码示例来源:origin: fr.acinq/bitcoinj-core

@Override
public synchronized void onBlocksDownloaded(Peer peer, Block block, @Nullable FilteredBlock filteredBlock, int blocksLeft) {
  blocksInLastSecond++;
  bytesInLastSecond += Block.HEADER_SIZE;
  List<Transaction> blockTransactions = block.getTransactions();
  // This whole area of the type hierarchy is a mess.
  int txCount = (blockTransactions != null ? countAndMeasureSize(blockTransactions) : 0) +
         (filteredBlock != null ? countAndMeasureSize(filteredBlock.getAssociatedTransactions().values()) : 0);
  txnsInLastSecond = txnsInLastSecond + txCount;
  if (filteredBlock != null)
    origTxnsInLastSecond += filteredBlock.getTransactionCount();
}

代码示例来源:origin: cash.bitcoinj/bitcoinj-core

@Override
public synchronized void onBlocksDownloaded(Peer peer, Block block, @Nullable FilteredBlock filteredBlock, int blocksLeft) {
  blocksInLastSecond++;
  bytesInLastSecond += Block.HEADER_SIZE;
  List<Transaction> blockTransactions = block.getTransactions();
  // This whole area of the type hierarchy is a mess.
  int txCount = (blockTransactions != null ? countAndMeasureSize(blockTransactions) : 0) +
         (filteredBlock != null ? countAndMeasureSize(filteredBlock.getAssociatedTransactions().values()) : 0);
  txnsInLastSecond = txnsInLastSecond + txCount;
  if (filteredBlock != null)
    origTxnsInLastSecond += filteredBlock.getTransactionCount();
}

代码示例来源:origin: HashEngineering/dashj

@Override
public synchronized void onBlocksDownloaded(Peer peer, Block block, @Nullable FilteredBlock filteredBlock, int blocksLeft) {
  blocksInLastSecond++;
  bytesInLastSecond += Block.HEADER_SIZE;
  List<Transaction> blockTransactions = block.getTransactions();
  // This whole area of the type hierarchy is a mess.
  int txCount = (blockTransactions != null ? countAndMeasureSize(blockTransactions) : 0) +
         (filteredBlock != null ? countAndMeasureSize(filteredBlock.getAssociatedTransactions().values()) : 0);
  txnsInLastSecond = txnsInLastSecond + txCount;
  if (filteredBlock != null)
    origTxnsInLastSecond += filteredBlock.getTransactionCount();
}

代码示例来源:origin: greenaddress/GreenBits

public TransactionOutPointWithValue getCoinbaseOutput() {
  return new TransactionOutPointWithValue(block.getTransactions().get(0), 0);
}

代码示例来源:origin: HashEngineering/dashj

/**
 * Creates a new FilteredBlock from the given Block, using this filter to select transactions. Matches can cause the
 * filter to be updated with the matched element, this ensures that when a filter is applied to a block, spends of
 * matched transactions are also matched. However it means this filter can be mutated by the operation. The returned
 * filtered block already has the matched transactions associated with it.
 */
public synchronized FilteredBlock applyAndUpdate(Block block) {
  List<Transaction> txns = block.getTransactions();
  List<Sha256Hash> txHashes = new ArrayList<Sha256Hash>(txns.size());
  List<Transaction> matched = Lists.newArrayList();
  byte[] bits = new byte[(int) Math.ceil(txns.size() / 8.0)];
  for (int i = 0; i < txns.size(); i++) {
    Transaction tx = txns.get(i);
    txHashes.add(tx.getHash());
    if (applyAndUpdate(tx)) {
      Utils.setBitLE(bits, i);
      matched.add(tx);
    }
  }
  PartialMerkleTree pmt = PartialMerkleTree.buildFromLeaves(block.getParams(), bits, txHashes);
  FilteredBlock filteredBlock = new FilteredBlock(block.getParams(), block.cloneAsHeader(), pmt);
  for (Transaction transaction : matched)
    filteredBlock.provideTransaction(transaction);
  return filteredBlock;
}

代码示例来源:origin: greenaddress/GreenBits

/**
 * Creates a new FilteredBlock from the given Block, using this filter to select transactions. Matches can cause the
 * filter to be updated with the matched element, this ensures that when a filter is applied to a block, spends of
 * matched transactions are also matched. However it means this filter can be mutated by the operation. The returned
 * filtered block already has the matched transactions associated with it.
 */
public synchronized FilteredBlock applyAndUpdate(Block block) {
  List<Transaction> txns = block.getTransactions();
  List<Sha256Hash> txHashes = new ArrayList<>(txns.size());
  List<Transaction> matched = Lists.newArrayList();
  byte[] bits = new byte[(int) Math.ceil(txns.size() / 8.0)];
  for (int i = 0; i < txns.size(); i++) {
    Transaction tx = txns.get(i);
    txHashes.add(tx.getHash());
    if (applyAndUpdate(tx)) {
      Utils.setBitLE(bits, i);
      matched.add(tx);
    }
  }
  PartialMerkleTree pmt = PartialMerkleTree.buildFromLeaves(block.getParams(), bits, txHashes);
  FilteredBlock filteredBlock = new FilteredBlock(block.getParams(), block.cloneAsHeader(), pmt);
  for (Transaction transaction : matched)
    filteredBlock.provideTransaction(transaction);
  return filteredBlock;
}

代码示例来源:origin: cash.bitcoinj/bitcoinj-core

/**
 * Creates a new FilteredBlock from the given Block, using this filter to select transactions. Matches can cause the
 * filter to be updated with the matched element, this ensures that when a filter is applied to a block, spends of
 * matched transactions are also matched. However it means this filter can be mutated by the operation. The returned
 * filtered block already has the matched transactions associated with it.
 */
public synchronized FilteredBlock applyAndUpdate(Block block) {
  List<Transaction> txns = block.getTransactions();
  List<Sha256Hash> txHashes = new ArrayList<Sha256Hash>(txns.size());
  List<Transaction> matched = Lists.newArrayList();
  byte[] bits = new byte[(int) Math.ceil(txns.size() / 8.0)];
  for (int i = 0; i < txns.size(); i++) {
    Transaction tx = txns.get(i);
    txHashes.add(tx.getHash());
    if (applyAndUpdate(tx)) {
      Utils.setBitLE(bits, i);
      matched.add(tx);
    }
  }
  PartialMerkleTree pmt = PartialMerkleTree.buildFromLeaves(block.getParams(), bits, txHashes);
  FilteredBlock filteredBlock = new FilteredBlock(block.getParams(), block.cloneAsHeader(), pmt);
  for (Transaction transaction : matched)
    filteredBlock.provideTransaction(transaction);
  return filteredBlock;
}

代码示例来源:origin: fr.acinq/bitcoinj-core

/**
 * Creates a new FilteredBlock from the given Block, using this filter to select transactions. Matches can cause the
 * filter to be updated with the matched element, this ensures that when a filter is applied to a block, spends of
 * matched transactions are also matched. However it means this filter can be mutated by the operation. The returned
 * filtered block already has the matched transactions associated with it.
 */
public synchronized FilteredBlock applyAndUpdate(Block block) {
  List<Transaction> txns = block.getTransactions();
  List<Sha256Hash> txHashes = new ArrayList<>(txns.size());
  List<Transaction> matched = Lists.newArrayList();
  byte[] bits = new byte[(int) Math.ceil(txns.size() / 8.0)];
  for (int i = 0; i < txns.size(); i++) {
    Transaction tx = txns.get(i);
    txHashes.add(tx.getHash());
    if (applyAndUpdate(tx)) {
      Utils.setBitLE(bits, i);
      matched.add(tx);
    }
  }
  PartialMerkleTree pmt = PartialMerkleTree.buildFromLeaves(block.getParams(), bits, txHashes);
  FilteredBlock filteredBlock = new FilteredBlock(block.getParams(), block.cloneAsHeader(), pmt);
  for (Transaction transaction : matched)
    filteredBlock.provideTransaction(transaction);
  return filteredBlock;
}

代码示例来源:origin: greenaddress/GreenBits

public BlockAndValidity(NewBlock block, boolean connects, boolean throwsException, Sha256Hash hashChainTipAfterBlock, int heightAfterBlock, String blockName) {
  this(block.block, connects, throwsException, hashChainTipAfterBlock, heightAfterBlock, blockName);
  coinbaseBlockMap.put(block.getCoinbaseOutput().outpoint.getHash(), block.getHash());
  Integer blockHeight = blockToHeightMap.get(block.block.getPrevBlockHash());
  if (blockHeight != null) {
    blockHeight++;
    for (Transaction t : block.block.getTransactions())
      for (TransactionInput in : t.getInputs()) {
        Sha256Hash blockSpendingHash = coinbaseBlockMap.get(in.getOutpoint().getHash());
        checkState(blockSpendingHash == null || blockToHeightMap.get(blockSpendingHash) == null ||
            blockToHeightMap.get(blockSpendingHash) == blockHeight - params.getSpendableCoinbaseDepth());
      }
  }
}

代码示例来源:origin: greenaddress/GreenBits

@Test
public void nonStandardDust() {
  Transaction standardTx = new Transaction(PARAMS);
  standardTx.addInput(PARAMS.getGenesisBlock().getTransactions().get(0).getOutput(0));
  standardTx.addOutput(COIN, key1);
  assertEquals(RiskAnalysis.Result.OK, DefaultRiskAnalysis.FACTORY.create(wallet, standardTx, NO_DEPS).analyze());
  Transaction dustTx = new Transaction(PARAMS);
  dustTx.addInput(PARAMS.getGenesisBlock().getTransactions().get(0).getOutput(0));
  dustTx.addOutput(Coin.SATOSHI, key1); // 1 Satoshi
  assertEquals(RiskAnalysis.Result.NON_STANDARD, DefaultRiskAnalysis.FACTORY.create(wallet, dustTx, NO_DEPS).analyze());
  Transaction edgeCaseTx = new Transaction(PARAMS);
  edgeCaseTx.addInput(PARAMS.getGenesisBlock().getTransactions().get(0).getOutput(0));
  edgeCaseTx.addOutput(DefaultRiskAnalysis.MIN_ANALYSIS_NONDUST_OUTPUT, key1); // Dust threshold
  assertEquals(RiskAnalysis.Result.OK, DefaultRiskAnalysis.FACTORY.create(wallet, edgeCaseTx, NO_DEPS).analyze());
}

代码示例来源:origin: greenaddress/GreenBits

/**
 * Ensure that hashForSignature() doesn't modify a transaction's data, which could wreak multithreading havoc.
 */
@Test
public void testHashForSignatureThreadSafety() {
  Block genesis = UnitTestParams.get().getGenesisBlock();
  Block block1 = genesis.createNextBlock(new ECKey().toAddress(UnitTestParams.get()),
        genesis.getTransactions().get(0).getOutput(0).getOutPointFor());
  final Transaction tx = block1.getTransactions().get(1);
  final String txHash = tx.getHashAsString();
  final String txNormalizedHash = tx.hashForSignature(0, new byte[0], Transaction.SigHash.ALL.byteValue()).toString();
  for (int i = 0; i < 100; i++) {
    // ensure the transaction object itself was not modified; if it was, the hash will change
    assertEquals(txHash, tx.getHashAsString());
    new Thread(){
      public void run() {
        assertEquals(txNormalizedHash, tx.hashForSignature(0, new byte[0], Transaction.SigHash.ALL.byteValue()).toString());
      }
    };
  }
}

代码示例来源:origin: greenaddress/GreenBits

@Test
public void getLargeBlock() throws Exception {
  connect();
  Block b1 = createFakeBlock(blockStore, Block.BLOCK_HEIGHT_GENESIS).block;
  blockChain.add(b1);
  Block b2 = makeSolvedTestBlock(b1);
  Transaction t = new Transaction(PARAMS);
  t.addInput(b1.getTransactions().get(0).getOutput(0));
  t.addOutput(new TransactionOutput(PARAMS, t, Coin.ZERO, new byte[Block.MAX_BLOCK_SIZE - 1000]));
  b2.addTransaction(t);
  // Request the block.
  Future<Block> resultFuture = peer.getBlock(b2.getHash());
  assertFalse(resultFuture.isDone());
  // Peer asks for it.
  GetDataMessage message = (GetDataMessage) outbound(writeTarget);
  assertEquals(message.getItems().get(0).hash, b2.getHash());
  assertFalse(resultFuture.isDone());
  // Peer receives it.
  inbound(writeTarget, b2);
  Block b = resultFuture.get();
  assertEquals(b, b2);
}

代码示例来源:origin: greenaddress/GreenBits

@Test
public void nonFinalDependency() {
  // Final tx has a dependency that is non-final.
  Transaction tx1 = new Transaction(PARAMS);
  tx1.addInput(PARAMS.getGenesisBlock().getTransactions().get(0).getOutput(0)).setSequenceNumber(1);
  TransactionOutput output = tx1.addOutput(COIN, key1);
  tx1.setLockTime(TIMESTAMP + 86400);
  Transaction tx2 = new Transaction(PARAMS);
  tx2.addInput(output);
  tx2.addOutput(COIN, new ECKey());
  DefaultRiskAnalysis analysis = DefaultRiskAnalysis.FACTORY.create(wallet, tx2, ImmutableList.of(tx1));
  assertEquals(RiskAnalysis.Result.NON_FINAL, analysis.analyze());
  assertEquals(tx1, analysis.getNonFinal());
}

代码示例来源:origin: greenaddress/GreenBits

assertEquals(block.unsafeBitcoinSerialize().length, block.length);
assertEquals(origBlockLen + tx.length, block.length);
block.getTransactions().get(1).getInputs().get(0).setScriptBytes(new byte[] {(byte) ScriptOpCodes.OP_FALSE, (byte) ScriptOpCodes.OP_FALSE});
assertEquals(block.length, origBlockLen + tx.length);
assertEquals(tx.length, origTxLength + 1);
block.getTransactions().get(1).getInputs().get(0).clearScriptBytes();
assertEquals(block.length, block.unsafeBitcoinSerialize().length);
assertEquals(block.length, origBlockLen + tx.length);
assertEquals(tx.length, origTxLength - 1);
block.getTransactions().get(1).addInput(new TransactionInput(params, null, new byte[] {(byte) ScriptOpCodes.OP_FALSE},
    new TransactionOutPoint(params, 0, Sha256Hash.of(new byte[] { 1 }))));
assertEquals(block.length, origBlockLen + tx.length);

代码示例来源:origin: greenaddress/GreenBits

@Test
public void coinbaseTxns() throws Exception {
  // Covers issue 420 where the outpoint index of a coinbase tx input was being mis-serialized.
  Block b = PARAMS.getGenesisBlock().createNextBlockWithCoinbase(Block.BLOCK_VERSION_GENESIS, myKey.getPubKey(), FIFTY_COINS, Block.BLOCK_HEIGHT_GENESIS);
  Transaction coinbase = b.getTransactions().get(0);
  assertTrue(coinbase.isCoinBase());
  BlockChain chain = new BlockChain(PARAMS, myWallet, new MemoryBlockStore(PARAMS));
  assertTrue(chain.add(b));
  // Wallet now has a coinbase tx in it.
  assertEquals(1, myWallet.getTransactions(true).size());
  assertTrue(myWallet.getTransaction(coinbase.getHash()).isCoinBase());
  Wallet wallet2 = roundTrip(myWallet);
  assertEquals(1, wallet2.getTransactions(true).size());
  assertTrue(wallet2.getTransaction(coinbase.getHash()).isCoinBase());
}

代码示例来源:origin: greenaddress/GreenBits

List<Transaction> transactions = block169482.getTransactions();
assertNotNull(transactions);
wallet.receiveFromBlock(transactions.get(0), storedBlock, NewBlockType.BEST_CHAIN, 0);

代码示例来源:origin: greenaddress/GreenBits

@Test
public void standardOutputs() throws Exception {
  Transaction tx = new Transaction(PARAMS);
  tx.addInput(PARAMS.getGenesisBlock().getTransactions().get(0).getOutput(0));
  // A pay to address output
  tx.addOutput(Coin.CENT, ScriptBuilder.createOutputScript(key1.toAddress(PARAMS)));
  // A pay to pubkey output
  tx.addOutput(Coin.CENT, ScriptBuilder.createOutputScript(key1));
  tx.addOutput(Coin.CENT, ScriptBuilder.createOutputScript(key1));
  // 1-of-2 multisig output.
  ImmutableList<ECKey> keys = ImmutableList.of(key1, new ECKey());
  tx.addOutput(Coin.CENT, ScriptBuilder.createMultiSigOutputScript(1, keys));
  // 2-of-2 multisig output.
  tx.addOutput(Coin.CENT, ScriptBuilder.createMultiSigOutputScript(2, keys));
  // P2SH
  tx.addOutput(Coin.CENT, ScriptBuilder.createP2SHOutputScript(1, keys));
  // OP_RETURN
  tx.addOutput(Coin.CENT, ScriptBuilder.createOpReturnScript("hi there".getBytes()));
  assertEquals(RiskAnalysis.Result.OK, DefaultRiskAnalysis.FACTORY.create(wallet, tx, NO_DEPS).analyze());
}

代码示例来源:origin: greenaddress/GreenBits

@Test
public void selfCreatedAreNotRisky() {
  Transaction tx = new Transaction(PARAMS);
  tx.addInput(PARAMS.getGenesisBlock().getTransactions().get(0).getOutput(0)).setSequenceNumber(1);
  tx.addOutput(COIN, key1);
  tx.setLockTime(TIMESTAMP + 86400);
  {
    // Is risky ...
    DefaultRiskAnalysis analysis = DefaultRiskAnalysis.FACTORY.create(wallet, tx, NO_DEPS);
    assertEquals(RiskAnalysis.Result.NON_FINAL, analysis.analyze());
  }
  tx.getConfidence().setSource(TransactionConfidence.Source.SELF);
  {
    // Is no longer risky.
    DefaultRiskAnalysis analysis = DefaultRiskAnalysis.FACTORY.create(wallet, tx, NO_DEPS);
    assertEquals(RiskAnalysis.Result.OK, analysis.analyze());
  }
}

代码示例来源:origin: greenaddress/GreenBits

@Test
public void nonFinal() throws Exception {
  // Verify that just having a lock time in the future is not enough to be considered risky (it's still final).
  Transaction tx = new Transaction(PARAMS);
  TransactionInput input = tx.addInput(PARAMS.getGenesisBlock().getTransactions().get(0).getOutput(0));
  tx.addOutput(COIN, key1);
  tx.setLockTime(TIMESTAMP + 86400);
  DefaultRiskAnalysis analysis = DefaultRiskAnalysis.FACTORY.create(wallet, tx, NO_DEPS);
  assertEquals(RiskAnalysis.Result.OK, analysis.analyze());
  assertNull(analysis.getNonFinal());
  // Set a sequence number on the input to make it genuinely non-final. Verify it's risky.
  input.setSequenceNumber(TransactionInput.NO_SEQUENCE - 1);
  analysis = DefaultRiskAnalysis.FACTORY.create(wallet, tx, NO_DEPS);
  assertEquals(RiskAnalysis.Result.NON_FINAL, analysis.analyze());
  assertEquals(tx, analysis.getNonFinal());
  // If the lock time is the current block, it's about to become final and we consider it non-risky.
  tx.setLockTime(1000);
  analysis = DefaultRiskAnalysis.FACTORY.create(wallet, tx, NO_DEPS);
  assertEquals(RiskAnalysis.Result.OK, analysis.analyze());
}

相关文章