Java Code Examples for org.bitcoinj.core.Transaction#bitcoinSerialize()

The following examples show how to use org.bitcoinj.core.Transaction#bitcoinSerialize() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DisputeManager.java    From bisq-core with GNU Affero General Public License v3.0 5 votes vote down vote up
private void sendPeerPublishedPayoutTxMessage(Transaction transaction, Dispute dispute, Contract contract) {
    PubKeyRing peersPubKeyRing = dispute.isDisputeOpenerIsBuyer() ? contract.getSellerPubKeyRing() : contract.getBuyerPubKeyRing();
    NodeAddress peersNodeAddress = dispute.isDisputeOpenerIsBuyer() ? contract.getSellerNodeAddress() : contract.getBuyerNodeAddress();
    log.trace("sendPeerPublishedPayoutTxMessage to peerAddress " + peersNodeAddress);
    final PeerPublishedDisputePayoutTxMessage message = new PeerPublishedDisputePayoutTxMessage(transaction.bitcoinSerialize(),
            dispute.getTradeId(),
            p2PService.getAddress(),
            UUID.randomUUID().toString());
    log.info("Send {} to peer {}. tradeId={}, uid={}",
            message.getClass().getSimpleName(), peersNodeAddress, message.getTradeId(), message.getUid());
    p2PService.sendEncryptedMailboxMessage(peersNodeAddress,
            peersPubKeyRing,
            message,
            new SendMailboxMessageListener() {
                @Override
                public void onArrived() {
                    log.info("{} arrived at peer {}. tradeId={}, uid={}",
                            message.getClass().getSimpleName(), peersNodeAddress, message.getTradeId(), message.getUid());
                }

                @Override
                public void onStoredInMailbox() {
                    log.info("{} stored in mailbox for peer {}. tradeId={}, uid={}",
                            message.getClass().getSimpleName(), peersNodeAddress, message.getTradeId(), message.getUid());
                }

                @Override
                public void onFault(String errorMessage) {
                    log.error("{} failed: Peer {}. tradeId={}, uid={}, errorMessage={}",
                            message.getClass().getSimpleName(), peersNodeAddress, message.getTradeId(), message.getUid(), errorMessage);
                }
            }
    );
}
 
Example 2
Source File: SellerSendPayoutTxPublishedMessage.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
protected TradeMessage getMessage(String id) {
    Transaction payoutTx = checkNotNull(trade.getPayoutTx(), "trade.getPayoutTx() must not be null");
    return new PayoutTxPublishedMessage(
            id,
            payoutTx.bitcoinSerialize(),
            processModel.getMyNodeAddress(),
            UUID.randomUUID().toString()
    );
}
 
Example 3
Source File: SendMediatedPayoutTxPublishedMessage.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
protected TradeMessage getMessage(String id) {
    Transaction payoutTx = checkNotNull(trade.getPayoutTx(), "trade.getPayoutTx() must not be null");
    return new MediatedPayoutTxPublishedMessage(
            id,
            payoutTx.bitcoinSerialize(),
            processModel.getMyNodeAddress(),
            UUID.randomUUID().toString()
    );
}
 
Example 4
Source File: DumpTxList.java    From jelectrum with MIT License 5 votes vote down vote up
public static String hasHeaderData(Transaction tx)
{
  if (funHeader == null) buildHeaders();

  byte[] serial = tx.bitcoinSerialize();
  String hex = Hex.encodeHexString(serial);

  for(String c : funHeader)
  {
    if (hex.contains(c)) return c;
  }

  return null;

}
 
Example 5
Source File: LNEstablishAMessage.java    From thunder with GNU Affero General Public License v3.0 5 votes vote down vote up
public LNEstablishAMessage (ECKey channelKeyServer, Transaction anchor, RevocationHash revocationHash, long clientAmount, long
        serverAmount, int minConfirmationAnchor, Address address, int feePerByte, long csvDelay) {
    this.channelKeyServer = channelKeyServer.getPubKey();
    this.minConfirmationAnchor = minConfirmationAnchor;
    this.anchorTransaction = anchor.bitcoinSerialize();
    this.revocationHash = revocationHash;
    this.amountClient = clientAmount;
    this.amountServer = serverAmount;
    this.addressBytes = address.getHash160();
    this.feePerByte = feePerByte;
    this.csvDelay = csvDelay;
}
 
Example 6
Source File: TradeWalletService.java    From bisq-core with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * @param transaction The transaction to be added to the wallet
 * @return The transaction we added to the wallet, which is different as the one we passed as argument!
 * @throws VerificationException
 */
public Transaction addTxToWallet(Transaction transaction) throws VerificationException {
    Log.traceCall("transaction " + transaction.toString());

    // We need to recreate the transaction otherwise we get a null pointer...
    Transaction result = new Transaction(params, transaction.bitcoinSerialize());
    result.getConfidence(Context.get()).setSource(TransactionConfidence.Source.SELF);

    if (wallet != null)
        wallet.receivePending(result, null, true);
    return result;
}
 
Example 7
Source File: MyBlindVoteListService.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
public Tuple2<Coin, Integer> getMiningFeeAndTxSize(Coin stake)
        throws InsufficientMoneyException, WalletException, TransactionVerificationException {
    // We set dummy opReturn data
    Coin blindVoteFee = BlindVoteConsensus.getFee(daoStateService, daoStateService.getChainHeight());
    Transaction dummyTx = getBlindVoteTx(stake, blindVoteFee, new byte[22]);
    Coin miningFee = dummyTx.getFee();
    int txSize = dummyTx.bitcoinSerialize().length;
    return new Tuple2<>(miningFee, txSize);
}
 
Example 8
Source File: UnlockTxService.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
public Tuple2<Coin, Integer> getMiningFeeAndTxSize(String lockupTxId)
        throws InsufficientMoneyException, WalletException, TransactionVerificationException {
    Transaction tx = getUnlockTx(lockupTxId);
    Coin miningFee = tx.getFee();
    int txSize = tx.bitcoinSerialize().length;
    return new Tuple2<>(miningFee, txSize);
}
 
Example 9
Source File: LockupTxService.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
public Tuple2<Coin, Integer> getMiningFeeAndTxSize(Coin lockupAmount, int lockTime, LockupReason lockupReason, byte[] hash)
        throws InsufficientMoneyException, WalletException, TransactionVerificationException, IOException {
    Transaction tx = getLockupTx(lockupAmount, lockTime, lockupReason, hash);
    Coin miningFee = tx.getFee();
    int txSize = tx.bitcoinSerialize().length;
    return new Tuple2<>(miningFee, txSize);
}
 
Example 10
Source File: SerializedTransaction.java    From jelectrum with MIT License 4 votes vote down vote up
public static Transaction scrubTransaction(NetworkParameters params, Transaction trans)
{
    return new Transaction(params, trans.bitcoinSerialize());
}
 
Example 11
Source File: TradeWalletService.java    From bisq-core with GNU Affero General Public License v3.0 4 votes vote down vote up
public Transaction getClonedTransaction(Transaction tx) {
    return new Transaction(params, tx.bitcoinSerialize());
}
 
Example 12
Source File: WalletTest.java    From green_android with GNU General Public License v3.0 4 votes vote down vote up
@Test
public void doubleSpends() throws Exception {
    // Test the case where two semantically identical but bitwise different transactions double spend each other.
    // We call the second transaction a "mutant" of the first.
    //
    // This can (and has!) happened when a wallet is cloned between devices, and both devices decide to make the
    // same spend simultaneously - for example due a re-keying operation. It can also happen if there are malicious
    // nodes in the P2P network that are mutating transactions on the fly as occurred during Feb 2014.
    final Coin value = COIN;
    final Coin value2 = valueOf(2, 0);
    // Give us three coins and make sure we have some change.
    sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, value.add(value2));
    Transaction send1 = checkNotNull(wallet.createSend(OTHER_ADDRESS, value2));
    Transaction send2 = checkNotNull(wallet.createSend(OTHER_ADDRESS, value2));
    byte[] buf = send1.bitcoinSerialize();
    buf[43] = 0;  // Break the signature: bitcoinj won't check in SPV mode and this is easier than other mutations.
    send1 = PARAMS.getDefaultSerializer().makeTransaction(buf);
    wallet.commitTx(send2);
    wallet.allowSpendingUnconfirmedTransactions();
    assertEquals(value, wallet.getBalance(Wallet.BalanceType.ESTIMATED));
    // Now spend the change. This transaction should die permanently when the mutant appears in the chain.
    Transaction send3 = checkNotNull(wallet.createSend(OTHER_ADDRESS, value));
    wallet.commitTx(send3);
    assertEquals(ZERO, wallet.getBalance());
    final LinkedList<TransactionConfidence> dead = new LinkedList<>();
    final TransactionConfidence.Listener listener = new TransactionConfidence.Listener() {
        @Override
        public void onConfidenceChanged(TransactionConfidence confidence, ChangeReason reason) {
            final TransactionConfidence.ConfidenceType type = confidence.getConfidenceType();
            if (reason == ChangeReason.TYPE && type == TransactionConfidence.ConfidenceType.DEAD)
                dead.add(confidence);
        }
    };
    send2.getConfidence().addEventListener(Threading.SAME_THREAD, listener);
    send3.getConfidence().addEventListener(Threading.SAME_THREAD, listener);
    // Double spend!
    sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, send1);
    // Back to having one coin.
    assertEquals(value, wallet.getBalance());
    assertEquals(send2.getHash(), dead.poll().getTransactionHash());
    assertEquals(send3.getHash(), dead.poll().getTransactionHash());
}
 
Example 13
Source File: BtcWalletService.java    From bisq-core with GNU Affero General Public License v3.0 4 votes vote down vote up
public Transaction completePreparedCompensationRequestTx(Coin issuanceAmount, Address issuanceAddress, Transaction feeTx, byte[] opReturnData) throws
        TransactionVerificationException, WalletException, InsufficientMoneyException {

    // (BsqFee)tx has following structure:
    // inputs [1-n] BSQ inputs (fee)
    // outputs [0-1] BSQ request fee change output (>= 546 Satoshi)

    // preparedCompensationRequestTx has following structure:
    // inputs [1-n] BSQ inputs for request fee
    // inputs [1-n] BTC inputs for BSQ issuance and miner fee
    // outputs [1] Mandatory BSQ request fee change output (>= 546 Satoshi)
    // outputs [1] Potentially BSQ issuance output (>= 546 Satoshi)
    // outputs [0-1] BTC change output from issuance and miner fee inputs (>= 546 Satoshi)
    // outputs [1] OP_RETURN with opReturnData and amount 0
    // mining fee: BTC mining fee + burned BSQ fee

    Transaction preparedTx = new Transaction(params);
    // Copy inputs from BSQ fee tx
    feeTx.getInputs().forEach(preparedTx::addInput);
    int indexOfBtcFirstInput = feeTx.getInputs().size();

    // Need to be first because issuance is not guaranteed to be valid and would otherwise burn change output!
    // BSQ change outputs from BSQ fee inputs.
    feeTx.getOutputs().forEach(preparedTx::addOutput);

    // BSQ issuance output
    preparedTx.addOutput(issuanceAmount, issuanceAddress);


    // safety check counter to avoid endless loops
    int counter = 0;
    // estimated size of input sig
    final int sigSizePerInput = 106;
    // typical size for a tx with 3 inputs
    int txSizeWithUnsignedInputs = 300;
    final Coin txFeePerByte = feeService.getTxFeePerByte();

    Address changeAddress = getFreshAddressEntry().getAddress();
    checkNotNull(changeAddress, "changeAddress must not be null");

    final BtcCoinSelector coinSelector = new BtcCoinSelector(walletsSetup.getAddressesByContext(AddressEntry.Context.AVAILABLE));
    final List<TransactionInput> preparedBsqTxInputs = preparedTx.getInputs();
    final List<TransactionOutput> preparedBsqTxOutputs = preparedTx.getOutputs();
    int numInputs = preparedBsqTxInputs.size();
    Transaction resultTx = null;
    boolean isFeeOutsideTolerance;
    do {
        counter++;
        if (counter >= 10) {
            checkNotNull(resultTx, "resultTx must not be null");
            log.error("Could not calculate the fee. Tx=" + resultTx);
            break;
        }

        Transaction tx = new Transaction(params);
        preparedBsqTxInputs.stream().forEach(tx::addInput);
        preparedBsqTxOutputs.stream().forEach(tx::addOutput);

        SendRequest sendRequest = SendRequest.forTx(tx);
        sendRequest.shuffleOutputs = false;
        sendRequest.aesKey = aesKey;
        // signInputs needs to be false as it would try to sign all inputs (BSQ inputs are not in this wallet)
        sendRequest.signInputs = false;

        sendRequest.fee = txFeePerByte.multiply(txSizeWithUnsignedInputs + sigSizePerInput * numInputs);
        sendRequest.feePerKb = Coin.ZERO;
        sendRequest.ensureMinRequiredFee = false;

        sendRequest.coinSelector = coinSelector;
        sendRequest.changeAddress = changeAddress;
        wallet.completeTx(sendRequest);

        resultTx = sendRequest.tx;

        // add OP_RETURN output
        resultTx.addOutput(new TransactionOutput(params, resultTx, Coin.ZERO, ScriptBuilder.createOpReturnScript(opReturnData).getProgram()));

        numInputs = resultTx.getInputs().size();
        txSizeWithUnsignedInputs = resultTx.bitcoinSerialize().length;
        final long estimatedFeeAsLong = txFeePerByte.multiply(txSizeWithUnsignedInputs + sigSizePerInput * numInputs).value;
        // calculated fee must be inside of a tolerance range with tx fee
        isFeeOutsideTolerance = Math.abs(resultTx.getFee().value - estimatedFeeAsLong) > 1000;
    }
    while (isFeeOutsideTolerance);

    // Sign all BTC inputs
    signAllBtcInputs(indexOfBtcFirstInput, resultTx);

    checkWalletConsistency(wallet);
    verifyTransaction(resultTx);

    // printTx("BTC wallet: Signed tx", resultTx);
    return resultTx;
}
 
Example 14
Source File: Trade.java    From bisq with GNU Affero General Public License v3.0 4 votes vote down vote up
public void applyDelayedPayoutTx(Transaction delayedPayoutTx) {
    this.delayedPayoutTx = delayedPayoutTx;
    this.delayedPayoutTxBytes = delayedPayoutTx.bitcoinSerialize();
    persist();
}
 
Example 15
Source File: WalletService.java    From bisq-core with GNU Affero General Public License v3.0 4 votes vote down vote up
public Transaction getClonedTransaction(Transaction tx) {
    return new Transaction(params, tx.bitcoinSerialize());
}
 
Example 16
Source File: SellerSendsDepositTxAndDelayedPayoutTxMessage.java    From bisq with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
protected void run() {
    try {
        runInterceptHook();
        if (trade.getDepositTx() != null) {
            Transaction delayedPayoutTx = checkNotNull(trade.getDelayedPayoutTx());
            Transaction depositTx = checkNotNull(trade.getDepositTx());
            DepositTxAndDelayedPayoutTxMessage message = new DepositTxAndDelayedPayoutTxMessage(UUID.randomUUID().toString(),
                    processModel.getOfferId(),
                    processModel.getMyNodeAddress(),
                    depositTx.bitcoinSerialize(),
                    delayedPayoutTx.bitcoinSerialize());
            trade.setState(Trade.State.SELLER_SENT_DEPOSIT_TX_PUBLISHED_MSG);

            NodeAddress peersNodeAddress = trade.getTradingPeerNodeAddress();
            log.info("Send {} to peer {}. tradeId={}, uid={}",
                    message.getClass().getSimpleName(), peersNodeAddress, message.getTradeId(), message.getUid());
            processModel.getP2PService().sendEncryptedMailboxMessage(
                    peersNodeAddress,
                    processModel.getTradingPeer().getPubKeyRing(),
                    message,
                    new SendMailboxMessageListener() {
                        @Override
                        public void onArrived() {
                            log.info("{} arrived at peer {}. tradeId={}, uid={}",
                                    message.getClass().getSimpleName(), peersNodeAddress, message.getTradeId(), message.getUid());
                            trade.setState(Trade.State.SELLER_SAW_ARRIVED_DEPOSIT_TX_PUBLISHED_MSG);
                            complete();
                        }

                        @Override
                        public void onStoredInMailbox() {
                            log.info("{} stored in mailbox for peer {}. tradeId={}, uid={}",
                                    message.getClass().getSimpleName(), peersNodeAddress, message.getTradeId(), message.getUid());

                            trade.setState(Trade.State.SELLER_STORED_IN_MAILBOX_DEPOSIT_TX_PUBLISHED_MSG);
                            complete();
                        }

                        @Override
                        public void onFault(String errorMessage) {
                            log.error("{} failed: Peer {}. tradeId={}, uid={}, errorMessage={}",
                                    message.getClass().getSimpleName(), peersNodeAddress, message.getTradeId(), message.getUid(), errorMessage);
                            trade.setState(Trade.State.SELLER_SEND_FAILED_DEPOSIT_TX_PUBLISHED_MSG);
                            appendToErrorMessage("Sending message failed: message=" + message + "\nerrorMessage=" + errorMessage);
                            failed();
                        }
                    }
            );
        } else {
            log.error("trade.getDepositTx() = " + trade.getDepositTx());
            failed("DepositTx is null");
        }
    } catch (Throwable t) {
        failed(t);
    }
}
 
Example 17
Source File: BtcWalletService.java    From bisq with GNU Affero General Public License v3.0 4 votes vote down vote up
private Transaction addInputsForMinerFee(Transaction preparedTx, byte[] opReturnData) throws InsufficientMoneyException {
    // safety check counter to avoid endless loops
    int counter = 0;
    // estimated size of input sig
    int sigSizePerInput = 106;
    // typical size for a tx with 3 inputs
    int txSizeWithUnsignedInputs = 300;
    Coin txFeePerByte = feeService.getTxFeePerByte();

    Address changeAddress = getFreshAddressEntry().getAddress();
    checkNotNull(changeAddress, "changeAddress must not be null");

    BtcCoinSelector coinSelector = new BtcCoinSelector(walletsSetup.getAddressesByContext(AddressEntry.Context.AVAILABLE),
            preferences.getIgnoreDustThreshold());
    List<TransactionInput> preparedBsqTxInputs = preparedTx.getInputs();
    List<TransactionOutput> preparedBsqTxOutputs = preparedTx.getOutputs();
    int numInputs = preparedBsqTxInputs.size();
    Transaction resultTx = null;
    boolean isFeeOutsideTolerance;
    do {
        counter++;
        if (counter >= 10) {
            checkNotNull(resultTx, "resultTx must not be null");
            log.error("Could not calculate the fee. Tx=" + resultTx);
            break;
        }

        Transaction tx = new Transaction(params);
        preparedBsqTxInputs.forEach(tx::addInput);
        preparedBsqTxOutputs.forEach(tx::addOutput);

        SendRequest sendRequest = SendRequest.forTx(tx);
        sendRequest.shuffleOutputs = false;
        sendRequest.aesKey = aesKey;
        // signInputs needs to be false as it would try to sign all inputs (BSQ inputs are not in this wallet)
        sendRequest.signInputs = false;

        sendRequest.fee = txFeePerByte.multiply(txSizeWithUnsignedInputs + sigSizePerInput * numInputs);
        sendRequest.feePerKb = Coin.ZERO;
        sendRequest.ensureMinRequiredFee = false;

        sendRequest.coinSelector = coinSelector;
        sendRequest.changeAddress = changeAddress;
        wallet.completeTx(sendRequest);

        resultTx = sendRequest.tx;

        // add OP_RETURN output
        resultTx.addOutput(new TransactionOutput(params, resultTx, Coin.ZERO, ScriptBuilder.createOpReturnScript(opReturnData).getProgram()));

        numInputs = resultTx.getInputs().size();
        txSizeWithUnsignedInputs = resultTx.bitcoinSerialize().length;
        final long estimatedFeeAsLong = txFeePerByte.multiply(txSizeWithUnsignedInputs + sigSizePerInput * numInputs).value;
        // calculated fee must be inside of a tolerance range with tx fee
        isFeeOutsideTolerance = Math.abs(resultTx.getFee().value - estimatedFeeAsLong) > 1000;
    }
    while (isFeeOutsideTolerance);
    return resultTx;
}
 
Example 18
Source File: WalletService.java    From bisq with GNU Affero General Public License v3.0 4 votes vote down vote up
public Transaction getClonedTransaction(Transaction tx) {
    return new Transaction(params, tx.bitcoinSerialize());
}
 
Example 19
Source File: SellerSendDelayedPayoutTxSignatureRequest.java    From bisq with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
protected void run() {
    try {
        runInterceptHook();

        Transaction preparedDelayedPayoutTx = checkNotNull(processModel.getPreparedDelayedPayoutTx(),
                "processModel.getPreparedDelayedPayoutTx() must not be null");
        DelayedPayoutTxSignatureRequest message = new DelayedPayoutTxSignatureRequest(UUID.randomUUID().toString(),
                processModel.getOfferId(),
                processModel.getMyNodeAddress(),
                preparedDelayedPayoutTx.bitcoinSerialize());

        // todo trade.setState

        NodeAddress peersNodeAddress = trade.getTradingPeerNodeAddress();
        log.info("Send {} to peer {}. tradeId={}, uid={}",
                message.getClass().getSimpleName(), peersNodeAddress, message.getTradeId(), message.getUid());
        processModel.getP2PService().sendEncryptedDirectMessage(
                peersNodeAddress,
                processModel.getTradingPeer().getPubKeyRing(),
                message,
                new SendDirectMessageListener() {
                    @Override
                    public void onArrived() {
                        log.info("{} arrived at peer {}. tradeId={}, uid={}",
                                message.getClass().getSimpleName(), peersNodeAddress, message.getTradeId(), message.getUid());
                        // todo trade.setState
                        complete();
                    }

                    @Override
                    public void onFault(String errorMessage) {
                        log.error("{} failed: Peer {}. tradeId={}, uid={}, errorMessage={}",
                                message.getClass().getSimpleName(), peersNodeAddress, message.getTradeId(), message.getUid(), errorMessage);
                        // todo trade.setState
                        appendToErrorMessage("Sending message failed: message=" + message + "\nerrorMessage=" + errorMessage);
                        failed();
                    }
                }
        );
    } catch (Throwable t) {
        failed(t);
    }
}
 
Example 20
Source File: TransactionWrapper.java    From thundernetwork with GNU Affero General Public License v3.0 3 votes vote down vote up
/**
 * Instantiates a new transaction wrapper.
 *
 * @param t         the t
 * @param channelId the channel id
 * @param id        the id
 */
public TransactionWrapper (Transaction t, int channelId, int id) {
    this.hash = t.getHashAsString();
    this.channelId = channelId;
    this.data = t.bitcoinSerialize();
    this.id = id;
}