Java Code Examples for org.bitcoinj.core.TransactionInput#getScriptSig()

The following examples show how to use org.bitcoinj.core.TransactionInput#getScriptSig() . 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: 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 2
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 3
Source File: MissingSigResolutionSigner.java    From bcm-android with GNU General Public License v3.0 4 votes vote down vote up
@Override
public boolean signInputs(ProposedTransaction propTx, KeyBag keyBag) {
    if (missingSigsMode == Wallet.MissingSigsMode.USE_OP_ZERO)
        return true;

    int numInputs = propTx.partialTx.getInputs().size();
    byte[] dummySig = TransactionSignature.dummy().encodeToBitcoin();
    for (int i = 0; i < numInputs; i++) {
        TransactionInput txIn = propTx.partialTx.getInput(i);
        if (txIn.getConnectedOutput() == null) {
            log.warn("Missing connected output, assuming input {} is already signed.", i);
            continue;
        }

        Script scriptPubKey = txIn.getConnectedOutput().getScriptPubKey();
        Script inputScript = txIn.getScriptSig();
        if (ScriptPattern.isPayToScriptHash(scriptPubKey) || ScriptPattern.isSentToMultisig(scriptPubKey)) {
            int sigSuffixCount = ScriptPattern.isPayToScriptHash(scriptPubKey) ? 1 : 0;
            // all chunks except the first one (OP_0) and the last (redeem script) are signatures
            for (int j = 1; j < inputScript.getChunks().size() - sigSuffixCount; j++) {
                ScriptChunk scriptChunk = inputScript.getChunks().get(j);
                if (scriptChunk.equalsOpCode(0)) {
                    if (missingSigsMode == Wallet.MissingSigsMode.THROW) {
                        throw new MissingSignatureException();
                    } else if (missingSigsMode == Wallet.MissingSigsMode.USE_DUMMY_SIG) {
                        txIn.setScriptSig(scriptPubKey.getScriptSigWithSignature(inputScript, dummySig, j - 1));
                    }
                }
            }
        } else {
            if (inputScript.getChunks().get(0).equalsOpCode(0)) {
                if (missingSigsMode == Wallet.MissingSigsMode.THROW) {
                    throw new ECKey.MissingPrivateKeyException();
                } else if (missingSigsMode == Wallet.MissingSigsMode.USE_DUMMY_SIG) {
                    txIn.setScriptSig(scriptPubKey.getScriptSigWithSignature(inputScript, dummySig, 0));
                }
            }
        }
        // TODO handle non-P2SH multisig
    }
    return true;
}
 
Example 4
Source File: GenerateLowSTests.java    From green_android with GNU General Public License v3.0 4 votes vote down vote up
public static void main(final String[] argv) throws NoSuchAlgorithmException, IOException {
    final NetworkParameters params = new MainNetParams();
    final LocalTransactionSigner signer = new LocalTransactionSigner();
    final SecureRandom secureRandom = SecureRandom.getInstanceStrong();
    final ECKey key = new ECKey(secureRandom);
    final KeyBag bag = new KeyBag() {
        @Override
        public ECKey findKeyFromPubHash(byte[] pubkeyHash) {
            return key;
        }

        @Override
        public ECKey findKeyFromPubKey(byte[] pubkey) {
            return key;
        }

        @Override
        public RedeemData findRedeemDataFromScriptHash(byte[] scriptHash) {
            return null;
        }

    };

    // Generate a fictional output transaction we take values from, and
    // an input transaction for the test case

    final Transaction outputTransaction = new Transaction(params);
    final Transaction inputTransaction = new Transaction(params);
    final TransactionOutput output = new TransactionOutput(params, inputTransaction, Coin.ZERO, key.toAddress(params));

    inputTransaction.addOutput(output);
    outputTransaction.addInput(output);
    outputTransaction.addOutput(Coin.ZERO, new ECKey(secureRandom).toAddress(params));

    addOutputs(outputTransaction, bag);

    // Sign the transaction
    final ProposedTransaction proposedTransaction = new ProposedTransaction(outputTransaction);
    signer.signInputs(proposedTransaction, bag);
    final TransactionInput input = proposedTransaction.partialTx.getInput(0);

    input.verify(output);
    input.getScriptSig().correctlySpends(outputTransaction, 0, output.getScriptPubKey(),
        EnumSet.of(Script.VerifyFlag.DERSIG, Script.VerifyFlag.P2SH));

    final Script scriptSig = input.getScriptSig();
    final TransactionSignature signature = TransactionSignature.decodeFromBitcoin(scriptSig.getChunks().get(0).data, true, false);

    // First output a conventional low-S transaction with the LOW_S flag, for the tx_valid.json set
    System.out.println("[\"A transaction with a low-S signature.\"],");
    System.out.println("[[[\""
        + inputTransaction.getHashAsString() + "\", "
        + output.getIndex() + ", \""
        + scriptToString(output.getScriptPubKey()) + "\"]],\n"
        + "\"" + Utils.HEX.encode(proposedTransaction.partialTx.unsafeBitcoinSerialize()) + "\", \""
        + Script.VerifyFlag.P2SH.name() + "," + Script.VerifyFlag.LOW_S.name() + "\"],");

    final BigInteger highS = HIGH_S_DIFFERENCE.subtract(signature.s);
    final TransactionSignature highSig = new TransactionSignature(signature.r, highS);
    input.setScriptSig(new ScriptBuilder().data(highSig.encodeToBitcoin()).data(scriptSig.getChunks().get(1).data).build());
    input.getScriptSig().correctlySpends(outputTransaction, 0, output.getScriptPubKey(),
        EnumSet.of(Script.VerifyFlag.P2SH));

    // A high-S transaction without the LOW_S flag, for the tx_valid.json set
    System.out.println("[\"A transaction with a high-S signature.\"],");
    System.out.println("[[[\""
        + inputTransaction.getHashAsString() + "\", "
        + output.getIndex() + ", \""
        + scriptToString(output.getScriptPubKey()) + "\"]],\n"
        + "\"" + Utils.HEX.encode(proposedTransaction.partialTx.unsafeBitcoinSerialize()) + "\", \""
        + Script.VerifyFlag.P2SH.name() + "\"],");

    // Lastly a conventional high-S transaction with the LOW_S flag, for the tx_invalid.json set
    System.out.println("[\"A transaction with a high-S signature.\"],");
    System.out.println("[[[\""
        + inputTransaction.getHashAsString() + "\", "
        + output.getIndex() + ", \""
        + scriptToString(output.getScriptPubKey()) + "\"]],\n"
        + "\"" + Utils.HEX.encode(proposedTransaction.partialTx.unsafeBitcoinSerialize()) + "\", \""
        + Script.VerifyFlag.P2SH.name() + "," + Script.VerifyFlag.LOW_S.name() + "\"],");
}
 
Example 5
Source File: MissingSigResolutionSigner.java    From green_android with GNU General Public License v3.0 4 votes vote down vote up
@Override
public boolean signInputs(ProposedTransaction propTx, KeyBag keyBag) {
    if (missingSigsMode == Wallet.MissingSigsMode.USE_OP_ZERO)
        return true;

    int numInputs = propTx.partialTx.getInputs().size();
    byte[] dummySig = TransactionSignature.dummy().encodeToBitcoin();
    for (int i = 0; i < numInputs; i++) {
        TransactionInput txIn = propTx.partialTx.getInput(i);
        if (txIn.getConnectedOutput() == null) {
            log.warn("Missing connected output, assuming input {} is already signed.", i);
            continue;
        }

        Script scriptPubKey = txIn.getConnectedOutput().getScriptPubKey();
        Script inputScript = txIn.getScriptSig();
        if (scriptPubKey.isPayToScriptHash() || scriptPubKey.isSentToMultiSig()) {
            int sigSuffixCount = scriptPubKey.isPayToScriptHash() ? 1 : 0;
            // all chunks except the first one (OP_0) and the last (redeem script) are signatures
            for (int j = 1; j < inputScript.getChunks().size() - sigSuffixCount; j++) {
                ScriptChunk scriptChunk = inputScript.getChunks().get(j);
                if (scriptChunk.equalsOpCode(0)) {
                    if (missingSigsMode == Wallet.MissingSigsMode.THROW) {
                        throw new MissingSignatureException();
                    } else if (missingSigsMode == Wallet.MissingSigsMode.USE_DUMMY_SIG) {
                        txIn.setScriptSig(scriptPubKey.getScriptSigWithSignature(inputScript, dummySig, j - 1));
                    }
                }
            }
        } else {
            if (inputScript.getChunks().get(0).equalsOpCode(0)) {
                if (missingSigsMode == Wallet.MissingSigsMode.THROW) {
                    throw new ECKey.MissingPrivateKeyException();
                } else if (missingSigsMode == Wallet.MissingSigsMode.USE_DUMMY_SIG) {
                    txIn.setScriptSig(scriptPubKey.getScriptSigWithSignature(inputScript, dummySig, 0));
                }
            }
        }
        // TODO handle non-P2SH multisig
    }
    return true;
}
 
Example 6
Source File: GenerateLowSTests.java    From GreenBits with GNU General Public License v3.0 4 votes vote down vote up
public static void main(final String[] argv) throws NoSuchAlgorithmException, IOException {
    final NetworkParameters params = new MainNetParams();
    final LocalTransactionSigner signer = new LocalTransactionSigner();
    final SecureRandom secureRandom = SecureRandom.getInstanceStrong();
    final ECKey key = new ECKey(secureRandom);
    final KeyBag bag = new KeyBag() {
        @Override
        public ECKey findKeyFromPubHash(byte[] pubkeyHash) {
            return key;
        }

        @Override
        public ECKey findKeyFromPubKey(byte[] pubkey) {
            return key;
        }

        @Override
        public RedeemData findRedeemDataFromScriptHash(byte[] scriptHash) {
            return null;
        }

    };

    // Generate a fictional output transaction we take values from, and
    // an input transaction for the test case

    final Transaction outputTransaction = new Transaction(params);
    final Transaction inputTransaction = new Transaction(params);
    final TransactionOutput output = new TransactionOutput(params, inputTransaction, Coin.ZERO, key.toAddress(params));

    inputTransaction.addOutput(output);
    outputTransaction.addInput(output);
    outputTransaction.addOutput(Coin.ZERO, new ECKey(secureRandom).toAddress(params));

    addOutputs(outputTransaction, bag);

    // Sign the transaction
    final ProposedTransaction proposedTransaction = new ProposedTransaction(outputTransaction);
    signer.signInputs(proposedTransaction, bag);
    final TransactionInput input = proposedTransaction.partialTx.getInput(0);

    input.verify(output);
    input.getScriptSig().correctlySpends(outputTransaction, 0, output.getScriptPubKey(),
        EnumSet.of(Script.VerifyFlag.DERSIG, Script.VerifyFlag.P2SH));

    final Script scriptSig = input.getScriptSig();
    final TransactionSignature signature = TransactionSignature.decodeFromBitcoin(scriptSig.getChunks().get(0).data, true, false);

    // First output a conventional low-S transaction with the LOW_S flag, for the tx_valid.json set
    System.out.println("[\"A transaction with a low-S signature.\"],");
    System.out.println("[[[\""
        + inputTransaction.getHashAsString() + "\", "
        + output.getIndex() + ", \""
        + scriptToString(output.getScriptPubKey()) + "\"]],\n"
        + "\"" + Utils.HEX.encode(proposedTransaction.partialTx.unsafeBitcoinSerialize()) + "\", \""
        + Script.VerifyFlag.P2SH.name() + "," + Script.VerifyFlag.LOW_S.name() + "\"],");

    final BigInteger highS = HIGH_S_DIFFERENCE.subtract(signature.s);
    final TransactionSignature highSig = new TransactionSignature(signature.r, highS);
    input.setScriptSig(new ScriptBuilder().data(highSig.encodeToBitcoin()).data(scriptSig.getChunks().get(1).data).build());
    input.getScriptSig().correctlySpends(outputTransaction, 0, output.getScriptPubKey(),
        EnumSet.of(Script.VerifyFlag.P2SH));

    // A high-S transaction without the LOW_S flag, for the tx_valid.json set
    System.out.println("[\"A transaction with a high-S signature.\"],");
    System.out.println("[[[\""
        + inputTransaction.getHashAsString() + "\", "
        + output.getIndex() + ", \""
        + scriptToString(output.getScriptPubKey()) + "\"]],\n"
        + "\"" + Utils.HEX.encode(proposedTransaction.partialTx.unsafeBitcoinSerialize()) + "\", \""
        + Script.VerifyFlag.P2SH.name() + "\"],");

    // Lastly a conventional high-S transaction with the LOW_S flag, for the tx_invalid.json set
    System.out.println("[\"A transaction with a high-S signature.\"],");
    System.out.println("[[[\""
        + inputTransaction.getHashAsString() + "\", "
        + output.getIndex() + ", \""
        + scriptToString(output.getScriptPubKey()) + "\"]],\n"
        + "\"" + Utils.HEX.encode(proposedTransaction.partialTx.unsafeBitcoinSerialize()) + "\", \""
        + Script.VerifyFlag.P2SH.name() + "," + Script.VerifyFlag.LOW_S.name() + "\"],");
}
 
Example 7
Source File: MissingSigResolutionSigner.java    From GreenBits with GNU General Public License v3.0 4 votes vote down vote up
@Override
public boolean signInputs(ProposedTransaction propTx, KeyBag keyBag) {
    if (missingSigsMode == Wallet.MissingSigsMode.USE_OP_ZERO)
        return true;

    int numInputs = propTx.partialTx.getInputs().size();
    byte[] dummySig = TransactionSignature.dummy().encodeToBitcoin();
    for (int i = 0; i < numInputs; i++) {
        TransactionInput txIn = propTx.partialTx.getInput(i);
        if (txIn.getConnectedOutput() == null) {
            log.warn("Missing connected output, assuming input {} is already signed.", i);
            continue;
        }

        Script scriptPubKey = txIn.getConnectedOutput().getScriptPubKey();
        Script inputScript = txIn.getScriptSig();
        if (scriptPubKey.isPayToScriptHash() || scriptPubKey.isSentToMultiSig()) {
            int sigSuffixCount = scriptPubKey.isPayToScriptHash() ? 1 : 0;
            // all chunks except the first one (OP_0) and the last (redeem script) are signatures
            for (int j = 1; j < inputScript.getChunks().size() - sigSuffixCount; j++) {
                ScriptChunk scriptChunk = inputScript.getChunks().get(j);
                if (scriptChunk.equalsOpCode(0)) {
                    if (missingSigsMode == Wallet.MissingSigsMode.THROW) {
                        throw new MissingSignatureException();
                    } else if (missingSigsMode == Wallet.MissingSigsMode.USE_DUMMY_SIG) {
                        txIn.setScriptSig(scriptPubKey.getScriptSigWithSignature(inputScript, dummySig, j - 1));
                    }
                }
            }
        } else {
            if (inputScript.getChunks().get(0).equalsOpCode(0)) {
                if (missingSigsMode == Wallet.MissingSigsMode.THROW) {
                    throw new ECKey.MissingPrivateKeyException();
                } else if (missingSigsMode == Wallet.MissingSigsMode.USE_DUMMY_SIG) {
                    txIn.setScriptSig(scriptPubKey.getScriptSigWithSignature(inputScript, dummySig, 0));
                }
            }
        }
        // TODO handle non-P2SH multisig
    }
    return true;
}