org.bitcoinj.core.Transaction类的使用及代码示例

x33g5p2x  于2022-01-30 转载在 其他  
字(9.8k)|赞(0)|评价(0)|浏览(169)

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

Transaction介绍

[英]A transaction represents the movement of coins from some addresses to some other addresses. It can also represent the minting of new coins. A Transaction object corresponds to the equivalent in the Bitcoin C++ implementation.

Transactions are the fundamental atoms of Bitcoin and have many powerful features. Read "Working with transactions" in the documentation to learn more about how to use this class.

All Bitcoin transactions are at risk of being reversed, though the risk is much less than with traditional payment systems. Transactions have confidence levels, which help you decide whether to trust a transaction or not. Whether to trust a transaction is something that needs to be decided on a case by case basis - a rule that makes sense for selling MP3s might not make sense for selling cars, or accepting payments from a family member. If you are building a wallet, how to present confidence to your users is something to consider carefully.

Instances of this class are not safe for use by multiple threads.
[中]

代码示例

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

/**
 * Returns whether this transaction will opt into the
 * <a href="https://github.com/bitcoin/bips/blob/master/bip-0125.mediawiki">full replace-by-fee </a> semantics.
 */
public boolean isOptInFullRBF() {
  for (TransactionInput input : getInputs())
    if (input.isOptInFullRBF())
      return true;
  return false;
}

代码示例来源:origin: Coinomi/coinomi-android

public boolean isOutputAvailable(int index) {
  checkIndex(index);
  if (trimmedOutputs == null) {
    return index < super.getOutputs().size();
  } else {
    return trimmedOutputs.containsKey(index);
  }
}

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

@Override
public String toString() {
  if (!analyzed)
    return "Pending risk analysis for " + tx.getHashAsString();
  else if (nonFinal != null)
    return "Risky due to non-finality of " + nonFinal.getHashAsString();
  else if (nonStandard != null)
    return "Risky due to non-standard tx " + nonStandard.getHashAsString();
  else
    return "Non-risky";
}

代码示例来源:origin: Coinomi/coinomi-android

private static void resetTxInputs(Transaction tx, List<TransactionInput> originalInputs) {
    tx.clearInputs();
    for (TransactionInput input : originalInputs)
      tx.addInput(input);
  }
}

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

@Override
  public synchronized void onCoinsReceived(Wallet w, Transaction tx, Coin prevBalance, Coin newBalance) {
    System.out.println("\nReceived tx " + tx.getHashAsString());
    System.out.println(tx.toString());
  }
});

代码示例来源:origin: Multibit-Legacy/multibit-hd

/**
 * Calculate the size of the transaction
 *
 * @param transaction The transaction to calculate the size of
 *
 * @return size of the transaction
 */
private int calculateSizeWithSignatures(Transaction transaction) throws IOException {
 ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
 transaction.bitcoinSerialize(byteOutputStream);
 int unsignedSize = byteOutputStream.size();
 // Add on size of signatures
 return unsignedSize + SIZE_OF_SIGNATURE * transaction.getInputs().size();
}

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

private synchronized Transaction makeUnsignedChannelContract(Coin valueToMe) throws ValueOutOfRangeException {
  Transaction tx = new Transaction(wallet.getParams());
  tx.addInput(getContractInternal().getOutput(0));
  // Our output always comes first.
  // TODO: We should drop myKey in favor of output key + multisig key separation
  // (as its always obvious who the client is based on T2 output order)
  tx.addOutput(valueToMe, myKey.toAddress(wallet.getParams()));
  return tx;
}

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

@Test
public void testOptimalEncodingMessageSize() {
  Transaction tx = new Transaction(PARAMS);
  int length = tx.length;
  // add basic transaction input, check the length
  tx.addOutput(new TransactionOutput(PARAMS, null, Coin.COIN, ADDRESS));
  length += getCombinedLength(tx.getOutputs());
  // add basic output, check the length
  length += getCombinedLength(tx.getInputs());
  // optimal encoding size should equal the length we just calculated
  assertEquals(tx.getOptimalEncodingMessageSize(), length);
}

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

/**
 * Returns true if the tx is a valid settlement transaction.
 */
public synchronized boolean isSettlementTransaction(Transaction tx) {
  try {
    tx.verify();
    tx.getInput(0).verify(getContractInternal().getOutput(0));
    return true;
  } catch (VerificationException e) {
    return false;
  }
}

代码示例来源:origin: blockchain/thunder

public void addAnchorOutputToAnchor () {
  List<TransactionOutput> outputList = new ArrayList<>();
  outputList.add(new TransactionOutput(
      Constants.getNetwork(),
      null,
      Coin.valueOf(channelStatus.amountClient + channelStatus.amountServer),
      getAnchorScript().getProgram()));
  outputList.addAll(anchorTx.getOutputs());
  Transaction tx = new Transaction(Constants.getNetwork());
  anchorTx.getInputs().stream().forEach(tx::addInput);
  outputList.stream().forEach(tx::addOutput);
  this.anchorTx = tx;
}

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

public static SendRequest emptyWallet(Address destination) {
  SendRequest req = new SendRequest();
  final NetworkParameters parameters = destination.getParameters();
  checkNotNull(parameters, "Address is for an unknown network");
  req.tx = new Transaction(parameters);
  req.tx.addOutput(Coin.ZERO, destination);
  req.emptyWallet = true;
  return req;
}

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

@Test
public void roundtripVersionTwoTransaction() throws Exception {
  Transaction tx = new Transaction(PARAMS, Utils.HEX.decode(
      "0200000001d7902864af9310420c6e606b814c8f89f7902d40c130594e85df2e757a7cc301070000006b483045022100ca1757afa1af85c2bb014382d9ce411e1628d2b3d478df9d5d3e9e93cb25dcdd02206c5d272b31a23baf64e82793ee5c816e2bbef251e733a638b630ff2331fc83ba0121026ac2316508287761befbd0f7495ea794b396dbc5b556bf276639f56c0bd08911feffffff0274730700000000001976a91456da2d038a098c42390c77ef163e1cc23aedf24088ac91062300000000001976a9148ebf3467b9a8d7ae7b290da719e61142793392c188ac22e00600"));
  assertEquals(tx.getVersion(), 2);
  assertEquals(tx.getHashAsString(), "0321b1413ed9048199815bd6bc2650cab1a9e8d543f109a42c769b1f18df4174");
  myWallet.addWalletTransaction(new WalletTransaction(Pool.UNSPENT, tx));
  Wallet wallet1 = roundTrip(myWallet);
  Transaction tx2 = wallet1.getTransaction(tx.getHash());
  assertEquals(checkNotNull(tx2).getVersion(), 2);
}

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

/** Create a fake coinbase transaction. */
public static Transaction createFakeCoinbaseTx(final NetworkParameters params) {
  TransactionOutPoint outpoint = new TransactionOutPoint(params, -1, Sha256Hash.ZERO_HASH);
  TransactionInput input = new TransactionInput(params, null, new byte[0], outpoint);
  Transaction tx = new Transaction(params);
  tx.addInput(input);
  TransactionOutput outputToMe = new TransactionOutput(params, tx, Coin.FIFTY_COINS,
      new ECKey().toAddress(params));
  tx.addOutput(outputToMe);
  checkState(tx.isCoinBase());
  return tx;
}

代码示例来源:origin: blockchain/thunder

public void fillAnchorTransactionWithoutSignatures (WalletHelper walletHelper) {
  long totalAmount = channelStatus.amountServer + channelStatus.amountClient;
  if (anchorTx == null) {
    Script anchorScriptServer = getAnchorScriptOutput();
    Script anchorScriptServerP2SH = ScriptBuilder.createP2SHOutputScript(anchorScriptServer);
    anchorTx = new Transaction(Constants.getNetwork());
    anchorTx.addOutput(Coin.valueOf(totalAmount), anchorScriptServerP2SH);
  }
  anchorTx = walletHelper.addInputs(anchorTx, channelStatus.amountServer, channelStatus.feePerByte);
  anchorTxHash = anchorTx.getHash();
}

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

private void basicSanityChecks(Wallet wallet, Transaction t, Address destination) throws VerificationException {
  assertEquals("Wrong number of tx inputs", 1, t.getInputs().size());
  assertEquals("Wrong number of tx outputs",2, t.getOutputs().size());
  assertEquals(destination, t.getOutput(0).getScriptPubKey().getToAddress(PARAMS));
  assertEquals(wallet.currentChangeAddress(), t.getOutputs().get(1).getScriptPubKey().getToAddress(PARAMS));
  assertEquals(valueOf(0, 50), t.getOutputs().get(1).getValue());
  // Check the script runs and signatures verify.
  t.getInputs().get(0).verify();
}

代码示例来源:origin: blockchain/thunder

public Transaction getClosingTransaction (ChannelStatus channelStatus, float feePerByte) {
  //For the sake of privacy (and simplicity) we use lexicographically ordering here, as defined in BIP69
  Transaction transaction = new Transaction(Constants.getNetwork());
  transaction.addInput(channel.anchorTxHash, 0, Tools.getDummyScript());
  //TODO deduct the transaction fee correctly from both amounts
  //TODO would be better to have another address on file that we can use here..
  long feePerParty = (Tools.getTransactionFees(2, 2, feePerByte) / 2);
  transaction.addOutput(Coin.valueOf(channelStatus.amountClient - feePerParty), channel.channelStatus.addressClient);
  transaction.addOutput(Coin.valueOf(channelStatus.amountServer - feePerParty), channel.channelStatus.addressServer);
  return Tools.applyBIP69(transaction);
}

代码示例来源:origin: Multibit-Legacy/multibit-hardware

@Override
public Optional<MessageEvent> signTx(Transaction tx) {
 return sendMessage(
  TrezorMessage.SignTx
   .newBuilder()
   .setCoinName("Bitcoin")
   .setInputsCount(tx.getInputs().size())
   .setOutputsCount(tx.getOutputs().size())
   .build()
 );
}

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

@Test
public void getAddressTests() throws Exception {
  Transaction tx = new Transaction(MainNetParams.get());
  tx.addOutput(Coin.CENT, ScriptBuilder.createOpReturnScript("hello world!".getBytes()));
  assertNull(tx.getOutput(0).getAddressFromP2SH(PARAMS));
  assertNull(tx.getOutput(0).getAddressFromP2PKHScript(PARAMS));
}

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

/** Finds whether txA spends txB */
boolean spends(Transaction txA, Transaction txB) {
  for (TransactionInput txInput : txA.getInputs()) {
    if (txInput.getOutpoint().getHash().equals(txB.getHash())) {
      return true;
    }
  }
  return false;
}

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

private void signMultisigInput(Transaction tx, Transaction.SigHash hashType,
                boolean anyoneCanPay, @Nullable KeyParameter userKey) {
  TransactionSignature signature = tx.calculateSignature(0, serverKey, userKey, getContractScript(), hashType, anyoneCanPay);
  byte[] mySig = signature.encodeToBitcoin();
  Script scriptSig = ScriptBuilder.createMultiSigInputScriptBytes(ImmutableList.of(bestValueSignature, mySig));
  tx.getInput(0).setScriptSig(scriptSig);
}

相关文章

微信公众号

最新文章

更多

Transaction类方法