org.bitcoinj.core.TransactionInput Java Examples

The following examples show how to use org.bitcoinj.core.TransactionInput. 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: ToolsTest.java    From thunder with GNU Affero General Public License v3.0 6 votes vote down vote up
private static Transaction shuffleTransaction (Transaction transaction) {
    Transaction shuffledTransaction = new Transaction(Constants.getNetwork());

    List<TransactionInput> shuffledInputs = new ArrayList<>(transaction.getInputs());
    List<TransactionOutput> shuffledOutputs = new ArrayList<>(transaction.getOutputs());

    Collections.shuffle(shuffledInputs);
    Collections.shuffle(shuffledOutputs);
    for (TransactionInput input : shuffledInputs) {
        shuffledTransaction.addInput(input);
    }
    for (TransactionOutput output : shuffledOutputs) {
        shuffledTransaction.addOutput(output);
    }
    return shuffledTransaction;
}
 
Example #2
Source File: BisqRiskAnalysis.java    From bisq-core with GNU Affero General Public License v3.0 6 votes vote down vote up
/** Checks if the given input passes some of the AreInputsStandard checks. Not complete. */
public static RuleViolation isInputStandard(TransactionInput input) {
    for (ScriptChunk chunk : input.getScriptSig().getChunks()) {
        if (chunk.data != null && !chunk.isShortestPossiblePushData())
            return RuleViolation.SHORTEST_POSSIBLE_PUSHDATA;
        if (chunk.isPushData()) {
            ECDSASignature signature;
            try {
                signature = ECKey.ECDSASignature.decodeFromDER(chunk.data);
            } catch (RuntimeException x) {
                // Doesn't look like a signature.
                signature = null;
            }
            if (signature != null) {
                if (!TransactionSignature.isEncodingCanonical(chunk.data))
                    return RuleViolation.SIGNATURE_CANONICAL_ENCODING;
                if (!signature.isCanonical())
                    return RuleViolation.SIGNATURE_CANONICAL_ENCODING;
            }
        }
    }
    return RuleViolation.NONE;
}
 
Example #3
Source File: WalletTest.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
public void completeTxPartiallySignedMarried(Wallet.MissingSigsMode missSigMode, byte[] expectedSig) throws Exception {
    // create married wallet without signer
    createMarriedWallet(2, 2, false);
    myAddress = wallet.currentAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS);
    sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, COIN, myAddress);

    SendRequest req = SendRequest.emptyWallet(OTHER_ADDRESS);
    req.missingSigsMode = missSigMode;
    wallet.completeTx(req);
    TransactionInput input = req.tx.getInput(0);

    boolean firstSigIsMissing = Arrays.equals(expectedSig, input.getScriptSig().getChunks().get(1).data);
    boolean secondSigIsMissing = Arrays.equals(expectedSig, input.getScriptSig().getChunks().get(2).data);

    assertTrue("Only one of the signatures should be missing/dummy", firstSigIsMissing ^ secondSigIsMissing);
    int localSigIndex = firstSigIsMissing ? 2 : 1;
    int length = input.getScriptSig().getChunks().get(localSigIndex).data.length;
    assertTrue("Local sig should be present: " + length, length >= 70);
}
 
Example #4
Source File: Trezor.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
private TxInputType.Builder createInput(final TxRequestDetailsType txRequest) {
    final int index = txRequest.getRequestIndex();

    final TransactionInput in;
    in = (txRequest.hasTxHash() ? getPreviousTx(txRequest) : mTx.mDecoded).getInput(index);

    TxInputType.Builder txin;
    txin = TxInputType.newBuilder()
                      .setPrevHash(ByteString.copyFrom(in.getOutpoint().getHash().getBytes()))
                      .setPrevIndex((int) in.getOutpoint().getIndex())
                      .setSequence((int) in.getSequenceNumber());

    if (txRequest.hasTxHash())
        return txin.setScriptSig(ByteString.copyFrom(in.getScriptBytes()));

    final Output prevout = mTx.mPrevOutputs.get(index);
    txin.clearAddressN().addAllAddressN(makePath(prevout.pointer))
                        .setMultisig(makeRedeemScript(prevout.pointer));

    if (prevout.scriptType.equals(GATx.P2SH_P2WSH_FORTIFIED_OUT))
        return txin.setScriptType(InputScriptType.SPENDP2SHWITNESS)
                   .setAmount(prevout.value);
    return txin.setScriptType(InputScriptType.SPENDMULTISIG);
}
 
Example #5
Source File: RawTransactionInfo.java    From consensusj with Apache License 2.0 6 votes vote down vote up
/**
 * Construct from a bitcoinj transaction
 * @param transaction A bitcoinj confirmed or unconfirmed transaction
 */
public RawTransactionInfo(Transaction transaction) {
    this.hex = HexUtil.bytesToHexString(transaction.bitcoinSerialize());
    this.txid = transaction.getTxId();
    this.version = transaction.getVersion();
    this.locktime = transaction.getLockTime();
    this.blockhash = null;  // For now
    this.confirmations = transaction.getConfidence().getDepthInBlocks();
    this.time = 0; // TODO: block header time of block including transaction
    this.blocktime = this.time; // same as time (see API doc)
    vin = new VinList();
    for (TransactionInput input : transaction.getInputs()) {
        vin.add(new Vin(txid,
                        input.getOutpoint().getIndex(),
                        input.getScriptSig().toString(),
                        input.getSequenceNumber()));
    }
    vout = new VoutList();
    for (TransactionOutput output : transaction.getOutputs()) {
        vout.add(new Vout(output.getValue(),
                            output.getIndex(),
                            output.getScriptPubKey().toString()));
    }
}
 
Example #6
Source File: SWWallet.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
@Override
public List<byte[]> signTransaction(final Transaction tx, final PreparedTransaction ptx, final List<Output> prevOuts) {
    final List<TransactionInput> txInputs = tx.getInputs();
    final List<byte[]> sigs = new ArrayList<>(txInputs.size());

    for (int i = 0; i < txInputs.size(); ++i) {
        final Output prevOut = prevOuts.get(i);

        final Script script = new Script(Wally.hex_to_bytes(prevOut.script));
        final Sha256Hash hash;
        if (prevOut.scriptType.equals(GATx.P2SH_P2WSH_FORTIFIED_OUT))
            hash = tx.hashForSignatureWitness(i, script.getProgram(), Coin.valueOf(prevOut.value), Transaction.SigHash.ALL, false);
        else
            hash = tx.hashForSignature(i, script.getProgram(), Transaction.SigHash.ALL, false);

        final SWWallet key = getMyKey(prevOut.subAccount).derive(prevOut.branch).derive(prevOut.pointer);
        final ECKey eckey = ECKey.fromPrivate(key.mRootKey.getPrivKey());
        sigs.add(getTxSignature(eckey.sign(Sha256Hash.wrap(hash.getBytes()))));
    }
    return sigs;
}
 
Example #7
Source File: TXUtil.java    From jelectrum with MIT License 6 votes vote down vote up
public static byte[] getPubKey(TransactionInput in) throws ScriptException
{
Script script = in.getScriptSig();
List<ScriptChunk> chunks = script.getChunks();

// Copied from Bitcoinj release 0.14 Script.java getPubKey
  // Should handle old style things fine.  Probably.

      if (chunks.size() != 2) {
          throw new ScriptException(ScriptError.SCRIPT_ERR_UNKNOWN_ERROR, "Script not of right size, expecting 2 but got " + chunks.size());
      }
      final ScriptChunk chunk0 = chunks.get(0);
      final byte[] chunk0data = chunk0.data;
      final ScriptChunk chunk1 = chunks.get(1);
      final byte[] chunk1data = chunk1.data;
      if (chunk0data != null && chunk0data.length > 2 && chunk1data != null && chunk1data.length > 2) {
          // If we have two large constants assume the input to a pay-to-address output.
          return chunk1data;
      } else if (chunk1.equalsOpCode(OP_CHECKSIG) && chunk0data != null && chunk0data.length > 2) {
          // A large constant followed by an OP_CHECKSIG is the key.
          return chunk0data;
      } else {
          throw new ScriptException(ScriptError.SCRIPT_ERR_UNKNOWN_ERROR, "Script did not match expected form: " + script);
      }
}
 
Example #8
Source File: TradeWalletService.java    From bisq-core with GNU Affero General Public License v3.0 6 votes vote down vote up
private void signInput(Transaction transaction, TransactionInput input, int inputIndex) throws SigningException {
    checkNotNull(input.getConnectedOutput(), "input.getConnectedOutput() must not be null");
    Script scriptPubKey = input.getConnectedOutput().getScriptPubKey();
    checkNotNull(wallet);
    ECKey sigKey = input.getOutpoint().getConnectedKey(wallet);
    checkNotNull(sigKey, "signInput: sigKey must not be null. input.getOutpoint()=" + input.getOutpoint().toString());
    if (sigKey.isEncrypted())
        checkNotNull(aesKey);
    Sha256Hash hash = transaction.hashForSignature(inputIndex, scriptPubKey, Transaction.SigHash.ALL, false);
    ECKey.ECDSASignature signature = sigKey.sign(hash, aesKey);
    TransactionSignature txSig = new TransactionSignature(signature, Transaction.SigHash.ALL, false);
    if (scriptPubKey.isSentToRawPubKey()) {
        input.setScriptSig(ScriptBuilder.createInputScript(txSig));
    } else if (scriptPubKey.isSentToAddress()) {
        input.setScriptSig(ScriptBuilder.createInputScript(txSig, sigKey));
    } else {
        throw new SigningException("Don't know how to sign for this kind of scriptPubKey: " + scriptPubKey);
    }
}
 
Example #9
Source File: WalletService.java    From bisq-core with GNU Affero General Public License v3.0 6 votes vote down vote up
protected List<TransactionOutput> getOutputsWithConnectedOutputs(Transaction tx) {
    List<TransactionOutput> transactionOutputs = tx.getOutputs();
    List<TransactionOutput> connectedOutputs = new ArrayList<>();

    // add all connected outputs from any inputs as well
    List<TransactionInput> transactionInputs = tx.getInputs();
    for (TransactionInput transactionInput : transactionInputs) {
        TransactionOutput transactionOutput = transactionInput.getConnectedOutput();
        if (transactionOutput != null) {
            connectedOutputs.add(transactionOutput);
        }
    }

    List<TransactionOutput> mergedOutputs = new ArrayList<>();
    mergedOutputs.addAll(transactionOutputs);
    mergedOutputs.addAll(connectedOutputs);
    return mergedOutputs;
}
 
Example #10
Source File: MemPooler.java    From jelectrum with MIT License 6 votes vote down vote up
public boolean areSomeInputsPending(Transaction tx)
{
  MemPoolInfo info = latest_info;
  if (info == null) return false; //Hard to say

  for(TransactionInput tx_in : tx.getInputs())
  {
    if (!tx_in.isCoinBase())
    {
      TransactionOutPoint tx_out = tx_in.getOutpoint();
      Sha256Hash parent_hash = tx_out.getHash();
      if (info.tx_set.contains(parent_hash)) return true;
    }
  }
  return false;
}
 
Example #11
Source File: WalletService.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
protected List<TransactionOutput> getOutputsWithConnectedOutputs(Transaction tx) {
    List<TransactionOutput> transactionOutputs = tx.getOutputs();
    List<TransactionOutput> connectedOutputs = new ArrayList<>();

    // add all connected outputs from any inputs as well
    List<TransactionInput> transactionInputs = tx.getInputs();
    for (TransactionInput transactionInput : transactionInputs) {
        TransactionOutput transactionOutput = transactionInput.getConnectedOutput();
        if (transactionOutput != null) {
            connectedOutputs.add(transactionOutput);
        }
    }

    List<TransactionOutput> mergedOutputs = new ArrayList<>();
    mergedOutputs.addAll(transactionOutputs);
    mergedOutputs.addAll(connectedOutputs);
    return mergedOutputs;
}
 
Example #12
Source File: BsqWalletService.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
public Transaction signTx(Transaction tx) throws WalletException, TransactionVerificationException {
    for (int i = 0; i < tx.getInputs().size(); i++) {
        TransactionInput txIn = tx.getInputs().get(i);
        TransactionOutput connectedOutput = txIn.getConnectedOutput();
        if (connectedOutput != null && connectedOutput.isMine(wallet)) {
            signTransactionInput(wallet, aesKey, tx, txIn, i);
            checkScriptSig(tx, txIn, i);
        }
    }

    for (TransactionOutput txo : tx.getOutputs()) {
        Coin value = txo.getValue();
        // OpReturn outputs have value 0
        if (value.isPositive()) {
            checkArgument(Restrictions.isAboveDust(txo.getValue()),
                    "An output value is below dust limit. Transaction=" + tx);
        }
    }

    checkWalletConsistency(wallet);
    verifyTransaction(tx);
    printTx("BSQ wallet: Signed Tx", tx);
    return tx;
}
 
Example #13
Source File: DefaultRiskAnalysis.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
/** Checks if the given input passes some of the AreInputsStandard checks. Not complete. */
public static RuleViolation isInputStandard(TransactionInput input) {
    for (ScriptChunk chunk : input.getScriptSig().getChunks()) {
        if (chunk.data != null && !chunk.isShortestPossiblePushData())
            return RuleViolation.SHORTEST_POSSIBLE_PUSHDATA;
        if (chunk.isPushData()) {
            ECDSASignature signature;
            try {
                signature = ECKey.ECDSASignature.decodeFromDER(chunk.data);
            } catch (RuntimeException x) {
                // Doesn't look like a signature.
                signature = null;
            }
            if (signature != null) {
                if (!TransactionSignature.isEncodingCanonical(chunk.data))
                    return RuleViolation.SIGNATURE_CANONICAL_ENCODING;
                if (!signature.isCanonical())
                    return RuleViolation.SIGNATURE_CANONICAL_ENCODING;
            }
        }
    }
    return RuleViolation.NONE;
}
 
Example #14
Source File: WalletTest.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
public void completeTxPartiallySignedMarried(Wallet.MissingSigsMode missSigMode, byte[] expectedSig) throws Exception {
    // create married wallet without signer
    createMarriedWallet(2, 2, false);
    myAddress = wallet.currentAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS);
    sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, COIN, myAddress);

    SendRequest req = SendRequest.emptyWallet(OTHER_ADDRESS);
    req.missingSigsMode = missSigMode;
    wallet.completeTx(req);
    TransactionInput input = req.tx.getInput(0);

    boolean firstSigIsMissing = Arrays.equals(expectedSig, input.getScriptSig().getChunks().get(1).data);
    boolean secondSigIsMissing = Arrays.equals(expectedSig, input.getScriptSig().getChunks().get(2).data);

    assertTrue("Only one of the signatures should be missing/dummy", firstSigIsMissing ^ secondSigIsMissing);
    int localSigIndex = firstSigIsMissing ? 2 : 1;
    int length = input.getScriptSig().getChunks().get(localSigIndex).data.length;
    assertTrue("Local sig should be present: " + length, length >= 70);
}
 
Example #15
Source File: BisqRiskAnalysis.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
/** Checks if the given input passes some of the AreInputsStandard checks. Not complete. */
public static RuleViolation isInputStandard(TransactionInput input) {
    for (ScriptChunk chunk : input.getScriptSig().getChunks()) {
        if (chunk.data != null && !chunk.isShortestPossiblePushData())
            return RuleViolation.SHORTEST_POSSIBLE_PUSHDATA;
        if (chunk.isPushData()) {
            ECDSASignature signature;
            try {
                signature = ECKey.ECDSASignature.decodeFromDER(chunk.data);
            } catch (RuntimeException x) {
                // Doesn't look like a signature.
                signature = null;
            }
            if (signature != null) {
                if (!TransactionSignature.isEncodingCanonical(chunk.data))
                    return RuleViolation.SIGNATURE_CANONICAL_ENCODING;
                if (!signature.isCanonical())
                    return RuleViolation.SIGNATURE_CANONICAL_ENCODING;
            }
        }
    }
    return RuleViolation.NONE;
}
 
Example #16
Source File: WalletTest.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
public void completeTxPartiallySignedMarried(Wallet.MissingSigsMode missSigMode, byte[] expectedSig) throws Exception {
    // create married wallet without signer
    createMarriedWallet(2, 2, false);
    myAddress = wallet.currentAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS);
    sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, COIN, myAddress);

    SendRequest req = SendRequest.emptyWallet(OTHER_ADDRESS);
    req.missingSigsMode = missSigMode;
    wallet.completeTx(req);
    TransactionInput input = req.tx.getInput(0);

    boolean firstSigIsMissing = Arrays.equals(expectedSig, input.getScriptSig().getChunks().get(1).data);
    boolean secondSigIsMissing = Arrays.equals(expectedSig, input.getScriptSig().getChunks().get(2).data);

    assertTrue("Only one of the signatures should be missing/dummy", firstSigIsMissing ^ secondSigIsMissing);
    int localSigIndex = firstSigIsMissing ? 2 : 1;
    int length = input.getScriptSig().getChunks().get(localSigIndex).data.length;
    assertTrue("Local sig should be present: " + length, length >= 70);
}
 
Example #17
Source File: TradeWalletService.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
public Transaction finalizeDelayedPayoutTx(Transaction delayedPayoutTx,
                                           byte[] buyerPubKey,
                                           byte[] sellerPubKey,
                                           byte[] buyerSignature,
                                           byte[] sellerSignature)
        throws AddressFormatException, TransactionVerificationException, WalletException {
    Script redeemScript = get2of2MultiSigRedeemScript(buyerPubKey, sellerPubKey);
    ECKey.ECDSASignature buyerECDSASignature = ECKey.ECDSASignature.decodeFromDER(buyerSignature);
    ECKey.ECDSASignature sellerECDSASignature = ECKey.ECDSASignature.decodeFromDER(sellerSignature);
    TransactionSignature buyerTxSig = new TransactionSignature(buyerECDSASignature, Transaction.SigHash.ALL, false);
    TransactionSignature sellerTxSig = new TransactionSignature(sellerECDSASignature, Transaction.SigHash.ALL, false);
    Script inputScript = ScriptBuilder.createP2SHMultiSigInputScript(ImmutableList.of(sellerTxSig, buyerTxSig), redeemScript);
    TransactionInput input = delayedPayoutTx.getInput(0);
    input.setScriptSig(inputScript);
    WalletService.printTx("finalizeDelayedPayoutTx", delayedPayoutTx);
    WalletService.verifyTransaction(delayedPayoutTx);
    WalletService.checkWalletConsistency(wallet);
    WalletService.checkScriptSig(delayedPayoutTx, input, 0);
    checkNotNull(input.getConnectedOutput(), "input.getConnectedOutput() must not be null");
    input.verify(input.getConnectedOutput());
    return delayedPayoutTx;
}
 
Example #18
Source File: Importer.java    From jelectrum with MIT License 6 votes vote down vote up
public void putTxOutSpents(Transaction tx)
{
  LinkedList<String> tx_outs = new LinkedList<String>();

    for(TransactionInput in : tx.getInputs())
    {
        if (!in.isCoinBase())
        {
            TransactionOutPoint out = in.getOutpoint();
            String key = out.getHash().toString() + ":" + out.getIndex();
            //file_db.addTxOutSpentByMap(key, tx.getHash());
            tx_outs.add(key);

        }
    }
}
 
Example #19
Source File: PaymentSessionTest.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testExpiredPaymentRequest() throws Exception {
    MockPaymentSession paymentSession = new MockPaymentSession(newExpiredPaymentRequest());
    assertTrue(paymentSession.isExpired());
    // Send the payment and verify that an exception is thrown.
    // Add a dummy input to tx so it is considered valid.
    tx.addInput(new TransactionInput(TESTNET, tx, outputToMe.getScriptBytes()));
    ArrayList<Transaction> txns = new ArrayList<>();
    txns.add(tx);
    try {
        paymentSession.sendPayment(txns, null, null);
    } catch (PaymentProtocolException.Expired e) {
        assertEquals(0, paymentSession.getPaymentLog().size());
        assertEquals(e.getMessage(), "PaymentRequest is expired");
        return;
    }
    fail("Expected exception due to expired PaymentRequest");
}
 
Example #20
Source File: TXUtil.java    From jelectrum with MIT License 6 votes vote down vote up
public static ByteString parseWitness(TransactionInput in)
{
  if (in.hasWitness())
  if (in.getWitness().getPushCount() == 2)
  if (in.getWitness().getPush(1).length == 33)
  {
    try (TimeRecordAuto tra = new TimeRecordAuto("txutil_parse_input_witness"))
    {
      ByteString h = ByteString.copyFrom( in.getWitness().getPush(1));
      h = Util.SHA256BIN(h);
      h = Util.RIPEMD160(h);
      ByteString prefix = HexUtil.hexStringToBytes("0014");

      ByteString out_script = prefix.concat(h);

      return Util.reverse(Util.SHA256BIN(out_script));
    }
 
  }


  return null;
}
 
Example #21
Source File: DefaultRiskAnalysis.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Checks if the given input passes some of the AreInputsStandard checks. Not complete.
 */
public static RuleViolation isInputStandard(TransactionInput input) {
    for (ScriptChunk chunk : input.getScriptSig().getChunks()) {
        if (chunk.data != null && !chunk.isShortestPossiblePushData())
            return RuleViolation.SHORTEST_POSSIBLE_PUSHDATA;
        if (chunk.isPushData()) {
            ECDSASignature signature;
            try {
                signature = ECKey.ECDSASignature.decodeFromDER(chunk.data);
            } catch (IllegalArgumentException x) {
                // Doesn't look like a signature.
                signature = null;
            }
            if (signature != null) {
                if (!TransactionSignature.isEncodingCanonical(chunk.data))
                    return RuleViolation.SIGNATURE_CANONICAL_ENCODING;
                if (!signature.isCanonical())
                    return RuleViolation.SIGNATURE_CANONICAL_ENCODING;
            }
        }
    }
    return RuleViolation.NONE;
}
 
Example #22
Source File: BsqWalletService.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
public Transaction getPreparedVoteRevealTx(TxOutput stakeTxOutput) {
    daoKillSwitch.assertDaoIsNotDisabled();
    Transaction tx = new Transaction(params);
    final Coin stake = Coin.valueOf(stakeTxOutput.getValue());
    Transaction blindVoteTx = getTransaction(stakeTxOutput.getTxId());
    checkNotNull(blindVoteTx, "blindVoteTx must not be null");
    TransactionOutPoint outPoint = new TransactionOutPoint(params, stakeTxOutput.getIndex(), blindVoteTx);
    // Input is not signed yet so we use new byte[]{}
    tx.addInput(new TransactionInput(params, tx, new byte[]{}, outPoint, stake));
    tx.addOutput(new TransactionOutput(params, tx, stake, getUnusedAddress()));
    // printTx("getPreparedVoteRevealTx", tx);
    return tx;
}
 
Example #23
Source File: TradeWalletService.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Seller creates and signs payout transaction and adds signature of buyer to complete the transaction.
 *
 * @param depositTx                 deposit transaction
 * @param buyerSignature            DER encoded canonical signature of buyer
 * @param buyerPayoutAmount         payout amount for buyer
 * @param sellerPayoutAmount        payout amount for seller
 * @param buyerPayoutAddressString  address for buyer
 * @param sellerPayoutAddressString address for seller
 * @param multiSigKeyPair           seller's key pair for MultiSig
 * @param buyerPubKey               the public key of the buyer
 * @param sellerPubKey              the public key of the seller
 * @return the payout transaction
 * @throws AddressFormatException if the buyer or seller base58 address doesn't parse or its checksum is invalid
 * @throws TransactionVerificationException if there was an unexpected problem with the payout tx or its signatures
 * @throws WalletException if the seller's wallet is null or structurally inconsistent
 */
public Transaction sellerSignsAndFinalizesPayoutTx(Transaction depositTx,
                                                   byte[] buyerSignature,
                                                   Coin buyerPayoutAmount,
                                                   Coin sellerPayoutAmount,
                                                   String buyerPayoutAddressString,
                                                   String sellerPayoutAddressString,
                                                   DeterministicKey multiSigKeyPair,
                                                   byte[] buyerPubKey,
                                                   byte[] sellerPubKey)
        throws AddressFormatException, TransactionVerificationException, WalletException {
    Transaction payoutTx = createPayoutTx(depositTx, buyerPayoutAmount, sellerPayoutAmount, buyerPayoutAddressString, sellerPayoutAddressString);
    // MS redeemScript
    Script redeemScript = get2of2MultiSigRedeemScript(buyerPubKey, sellerPubKey);
    // MS output from prev. tx is index 0
    Sha256Hash sigHash = payoutTx.hashForSignature(0, redeemScript, Transaction.SigHash.ALL, false);
    checkNotNull(multiSigKeyPair, "multiSigKeyPair must not be null");
    if (multiSigKeyPair.isEncrypted()) {
        checkNotNull(aesKey);
    }
    ECKey.ECDSASignature sellerSignature = multiSigKeyPair.sign(sigHash, aesKey).toCanonicalised();
    TransactionSignature buyerTxSig = new TransactionSignature(ECKey.ECDSASignature.decodeFromDER(buyerSignature),
            Transaction.SigHash.ALL, false);
    TransactionSignature sellerTxSig = new TransactionSignature(sellerSignature, Transaction.SigHash.ALL, false);
    // Take care of order of signatures. Need to be reversed here. See comment below at getMultiSigRedeemScript (seller, buyer)
    Script inputScript = ScriptBuilder.createP2SHMultiSigInputScript(ImmutableList.of(sellerTxSig, buyerTxSig),
            redeemScript);
    TransactionInput input = payoutTx.getInput(0);
    input.setScriptSig(inputScript);
    WalletService.printTx("payoutTx", payoutTx);
    WalletService.verifyTransaction(payoutTx);
    WalletService.checkWalletConsistency(wallet);
    WalletService.checkScriptSig(payoutTx, input, 0);
    checkNotNull(input.getConnectedOutput(), "input.getConnectedOutput() must not be null");
    input.verify(input.getConnectedOutput());
    return payoutTx;
}
 
Example #24
Source File: BsqWalletService.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
public Transaction getPreparedUnlockTx(TxOutput lockupTxOutput) throws AddressFormatException {
    daoKillSwitch.assertDaoIsNotDisabled();
    Transaction tx = new Transaction(params);
    // Unlocking means spending the full value of the locked txOutput to another txOutput with the same value
    Coin amountToUnlock = Coin.valueOf(lockupTxOutput.getValue());
    checkArgument(Restrictions.isAboveDust(amountToUnlock), "The amount is too low (dust limit).");
    Transaction lockupTx = getTransaction(lockupTxOutput.getTxId());
    checkNotNull(lockupTx, "lockupTx must not be null");
    TransactionOutPoint outPoint = new TransactionOutPoint(params, lockupTxOutput.getIndex(), lockupTx);
    // Input is not signed yet so we use new byte[]{}
    tx.addInput(new TransactionInput(params, tx, new byte[]{}, outPoint, amountToUnlock));
    tx.addOutput(new TransactionOutput(params, tx, amountToUnlock, getUnusedAddress()));
    printTx("prepareUnlockTx", tx);
    return tx;
}
 
Example #25
Source File: WalletService.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
public static void checkScriptSig(Transaction transaction,
                                  TransactionInput input,
                                  int inputIndex) throws TransactionVerificationException {
    try {
        checkNotNull(input.getConnectedOutput(), "input.getConnectedOutput() must not be null");
        input.getScriptSig().correctlySpends(transaction, inputIndex, input.getConnectedOutput().getScriptPubKey(), Script.ALL_VERIFY_FLAGS);
    } catch (Throwable t) {
        t.printStackTrace();
        log.error(t.getMessage());
        throw new TransactionVerificationException(t);
    }
}
 
Example #26
Source File: UnconfirmedBsqChangeOutputListService.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
private void removeConnectedOutputsOfInputsOfTx(Transaction tx) {
    tx.getInputs().stream()
            .map(TransactionInput::getConnectedOutput)
            .filter(Objects::nonNull)
            .map(UnconfirmedTxOutput::fromTransactionOutput)
            .filter(unconfirmedBsqChangeOutputList::containsTxOutput)
            .forEach(txOutput -> {
                unconfirmedBsqChangeOutputList.remove(txOutput);
                persist();
            });
}
 
Example #27
Source File: TradeWalletService.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
public void sellerAsMakerFinalizesDepositTx(Transaction myDepositTx,
                                            Transaction takersDepositTx,
                                            int numTakersInputs)
        throws TransactionVerificationException, AddressFormatException {

    // We add takers signature from his inputs and add it to out tx which was already signed earlier.
    for (int i = 0; i < numTakersInputs; i++) {
        TransactionInput input = takersDepositTx.getInput(i);
        Script scriptSig = input.getScriptSig();
        myDepositTx.getInput(i).setScriptSig(scriptSig);
    }

    WalletService.printTx("sellerAsMakerFinalizesDepositTx", myDepositTx);
    WalletService.verifyTransaction(myDepositTx);
}
 
Example #28
Source File: GenerateLowSTests.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
private static void addOutputs(final Transaction outputTransaction, final KeyBag bag) throws ScriptException {
    int numInputs = outputTransaction.getInputs().size();
    for (int i = 0; i < numInputs; i++) {
        TransactionInput txIn = outputTransaction.getInput(i);
        Script scriptPubKey = txIn.getConnectedOutput().getScriptPubKey();
        RedeemData redeemData = txIn.getConnectedRedeemData(bag);
        checkNotNull(redeemData, "Transaction exists in wallet that we cannot redeem: %s", txIn.getOutpoint().getHash());
        txIn.setScriptSig(scriptPubKey.createEmptyInputScript(redeemData.keys.get(0), redeemData.redeemScript));
    }
}
 
Example #29
Source File: WalletTest.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("ConstantConditions")
public void completeTxPartiallySigned(Wallet.MissingSigsMode missSigMode, byte[] expectedSig) throws Exception {
    // Check the wallet will write dummy scriptSigs for inputs that we have only pubkeys for without the privkey.
    ECKey priv = new ECKey();
    ECKey pub = ECKey.fromPublicOnly(priv.getPubKeyPoint());
    wallet.importKey(pub);
    ECKey priv2 = wallet.freshReceiveKey();
    // Send three transactions, with one being an address type and the other being a raw CHECKSIG type pubkey only,
    // and the final one being a key we do have. We expect the first two inputs to be dummy values and the last
    // to be signed correctly.
    Transaction t1 = sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, pub.toAddress(PARAMS));
    Transaction t2 = sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, pub);
    Transaction t3 = sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, priv2);

    SendRequest req = SendRequest.emptyWallet(OTHER_ADDRESS);
    req.missingSigsMode = missSigMode;
    wallet.completeTx(req);
    byte[] dummySig = TransactionSignature.dummy().encodeToBitcoin();
    // Selected inputs can be in any order.
    for (int i = 0; i < req.tx.getInputs().size(); i++) {
        TransactionInput input = req.tx.getInput(i);
        if (input.getConnectedOutput().getParentTransaction().equals(t1)) {
            assertArrayEquals(expectedSig, input.getScriptSig().getChunks().get(0).data);
        } else if (input.getConnectedOutput().getParentTransaction().equals(t2)) {
            assertArrayEquals(expectedSig, input.getScriptSig().getChunks().get(0).data);
        } else if (input.getConnectedOutput().getParentTransaction().equals(t3)) {
            input.getScriptSig().correctlySpends(req.tx, i, t3.getOutput(0).getScriptPubKey());
        }
    }
    assertTrue(TransactionSignature.isEncodingCanonical(dummySig));
}
 
Example #30
Source File: WalletTest.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@Test (expected = ECKey.MissingPrivateKeyException.class)
public void completeTxPartiallySignedThrows() throws Exception {
    sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, wallet.freshReceiveKey());
    SendRequest req = SendRequest.emptyWallet(OTHER_ADDRESS);
    wallet.completeTx(req);
    // Delete the sigs
    for (TransactionInput input : req.tx.getInputs())
        input.clearScriptBytes();
    Wallet watching = Wallet.fromWatchingKey(PARAMS, wallet.getWatchingKey().dropParent().dropPrivateBytes());
    watching.completeTx(SendRequest.forTx(req.tx));
}