org.bitcoinj.script.ScriptException Java Examples

The following examples show how to use org.bitcoinj.script.ScriptException. 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: FullBlockTestGenerator.java    From bcm-android with GNU General Public License v3.0 7 votes vote down vote up
private void addOnlyInputToTransaction(Transaction t, TransactionOutPointWithValue prevOut, long sequence) throws ScriptException {
    TransactionInput input = new TransactionInput(params, t, new byte[]{}, prevOut.outpoint);
    input.setSequenceNumber(sequence);
    t.addInput(input);

    if (prevOut.scriptPubKey.getChunks().get(0).equalsOpCode(OP_TRUE)) {
        input.setScriptSig(new ScriptBuilder().op(OP_1).build());
    } else {
        // Sign input
        checkState(ScriptPattern.isPayToPubKey(prevOut.scriptPubKey));
        Sha256Hash hash = t.hashForSignature(0, prevOut.scriptPubKey, SigHash.ALL, false);
        input.setScriptSig(ScriptBuilder.createInputScript(
                new TransactionSignature(coinbaseOutKey.sign(hash), SigHash.ALL, false))
        );
    }
}
 
Example #2
Source File: Transaction.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Calculates the sum of the inputs that are spending coins with keys in the wallet. This requires the
 * transactions sending coins to those keys to be in the wallet. This method will not attempt to download the
 * blocks containing the input transactions if the key is in the wallet but the transactions are not.
 *
 * @return sum of the inputs that are spending coins with keys in the wallet
 */
public Coin getValueSentFromMe(TransactionBag wallet) throws ScriptException {
    // This is tested in WalletTest.
    Coin v = Coin.ZERO;
    for (TransactionInput input : inputs) {
        // This input is taking value from a transaction in our wallet. To discover the value,
        // we must find the connected transaction.
        TransactionOutput connected = input.getConnectedOutput(wallet.getTransactionPool(Pool.UNSPENT));
        if (connected == null)
            connected = input.getConnectedOutput(wallet.getTransactionPool(Pool.SPENT));
        if (connected == null)
            connected = input.getConnectedOutput(wallet.getTransactionPool(Pool.PENDING));
        if (connected == null)
            continue;
        // The connected output may be the change to the sender of a previous input sent to this wallet. In this
        // case we ignore it.
        if (!connected.isMineOrWatched(wallet))
            continue;
        v = v.add(connected.getValue());
    }
    return v;
}
 
Example #3
Source File: Transaction.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Adds a new and fully signed input for the given parameters. Note that this method is <b>not</b> thread safe
 * and requires external synchronization. Please refer to general documentation on Bitcoin scripting and contracts
 * to understand the values of sigHash and anyoneCanPay: otherwise you can use the other form of this method
 * that sets them to typical defaults.
 *
 * @throws ScriptException if the scriptPubKey is not a pay to address or pay to pubkey script.
 */
public TransactionInput addSignedInput(TransactionOutPoint prevOut, Script scriptPubKey, ECKey sigKey,
                                       SigHash sigHash, boolean anyoneCanPay) throws ScriptException {
    // Verify the API user didn't try to do operations out of order.
    checkState(!outputs.isEmpty(), "Attempting to sign tx without outputs.");
    TransactionInput input = new TransactionInput(params, this, new byte[]{}, prevOut);
    addInput(input);
    Sha256Hash hash = hashForSignature(inputs.size() - 1, scriptPubKey, sigHash, anyoneCanPay);
    ECKey.ECDSASignature ecSig = sigKey.sign(hash);
    TransactionSignature txSig = new TransactionSignature(ecSig, sigHash, anyoneCanPay);
    if (ScriptPattern.isPayToPubKey(scriptPubKey))
        input.setScriptSig(ScriptBuilder.createInputScript(txSig));
    else if (ScriptPattern.isPayToPubKeyHash(scriptPubKey))
        input.setScriptSig(ScriptBuilder.createInputScript(txSig, sigKey));
    else
        throw new ScriptException(ScriptError.SCRIPT_ERR_UNKNOWN_ERROR, "Don't know how to sign for this kind of scriptPubKey: " + scriptPubKey);
    return input;
}
 
Example #4
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 #5
Source File: TransactionInput.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns a human readable debug string.
 */
@Override
public String toString() {
    StringBuilder s = new StringBuilder("TxIn");
    try {
        if (isCoinBase()) {
            s.append(": COINBASE");
        } else {
            s.append(" for [").append(outpoint).append("]: ").append(getScriptSig());
            String flags = Joiner.on(", ").skipNulls().join(hasWitness() ? "witness" : null,
                    hasSequence() ? "sequence: " + Long.toHexString(sequence) : null,
                    isOptInFullRBF() ? "opts into full RBF" : null);
            if (!flags.isEmpty())
                s.append(" (").append(flags).append(')');
        }
        return s.toString();
    } catch (ScriptException e) {
        throw new RuntimeException(e);
    }
}
 
Example #6
Source File: FullBlockTestGenerator.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
private NewBlock createNextBlock(Block baseBlock, int nextBlockHeight, @Nullable TransactionOutPointWithValue prevOut,
                                 Coin additionalCoinbaseValue) throws ScriptException {
    Integer height = blockToHeightMap.get(baseBlock.getHash());
    if (height != null)
        checkState(height == nextBlockHeight - 1);
    Coin coinbaseValue = FIFTY_COINS.shiftRight(nextBlockHeight / params.getSubsidyDecreaseBlockCount())
            .add((prevOut != null ? prevOut.value.subtract(SATOSHI) : ZERO))
            .add(additionalCoinbaseValue == null ? ZERO : additionalCoinbaseValue);
    Block block = baseBlock.createNextBlockWithCoinbase(Block.BLOCK_VERSION_GENESIS, coinbaseOutKeyPubKey, coinbaseValue, nextBlockHeight);
    Transaction t = new Transaction(params);
    if (prevOut != null) {
        // Entirely invalid scriptPubKey to ensure we aren't pre-verifying too much
        t.addOutput(new TransactionOutput(params, t, ZERO, new byte[]{(byte) (new Random().nextInt() & 0xff), uniquenessCounter++}));
        // Spendable output
        t.addOutput(new TransactionOutput(params, t, SATOSHI, new byte[]{OP_1}));
        addOnlyInputToTransaction(t, prevOut);
        block.addTransaction(t);
        block.solve();
    }
    return new NewBlock(block, prevOut == null ? null : new TransactionOutPointWithValue(t, 1));
}
 
Example #7
Source File: PaymentChannelV1ClientState.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * <p>When the servers signature for the refund transaction is received, call this to verify it and sign the
 * complete refund ourselves.</p>
 * <p>
 * <p>If this does not throw an exception, we are secure against the loss of funds and can safely provide the server
 * with the multi-sig contract to lock in the agreement. In this case, both the multisig contract and the refund
 * transaction are automatically committed to wallet so that it can handle broadcasting the refund transaction at
 * the appropriate time if necessary.</p>
 */
public synchronized void provideRefundSignature(byte[] theirSignature, @Nullable KeyParameter userKey)
        throws VerificationException {
    checkNotNull(theirSignature);
    stateMachine.checkState(State.WAITING_FOR_SIGNED_REFUND);
    TransactionSignature theirSig = TransactionSignature.decodeFromBitcoin(theirSignature, true);
    if (theirSig.sigHashMode() != Transaction.SigHash.NONE || !theirSig.anyoneCanPay())
        throw new VerificationException("Refund signature was not SIGHASH_NONE|SIGHASH_ANYONECANPAY");
    // Sign the refund transaction ourselves.
    final TransactionOutput multisigContractOutput = multisigContract.getOutput(0);
    try {
        multisigScript = multisigContractOutput.getScriptPubKey();
    } catch (ScriptException e) {
        throw new RuntimeException(e);  // Cannot happen: we built this ourselves.
    }
    TransactionSignature ourSignature =
            refundTx.calculateSignature(0, myKey.maybeDecrypt(userKey),
                    multisigScript, Transaction.SigHash.ALL, false);
    // Insert the signatures.
    Script scriptSig = ScriptBuilder.createMultiSigInputScript(ourSignature, theirSig);
    log.info("Refund scriptSig: {}", scriptSig);
    log.info("Multi-sig contract scriptPubKey: {}", multisigScript);
    TransactionInput refundInput = refundTx.getInput(0);
    refundInput.setScriptSig(scriptSig);
    refundInput.verify(multisigContractOutput);
    stateMachine.transition(State.SAVE_STATE_IN_WALLET);
}
 
Example #8
Source File: KeyTimeCoinSelector.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public CoinSelection select(Coin target, List<TransactionOutput> candidates) {
    try {
        LinkedList<TransactionOutput> gathered = Lists.newLinkedList();
        Coin valueGathered = Coin.ZERO;
        for (TransactionOutput output : candidates) {
            if (ignorePending && !isConfirmed(output))
                continue;
            // Find the key that controls output, assuming it's a regular P2PK or P2PKH output.
            // We ignore any other kind of exotic output on the assumption we can't spend it ourselves.
            final Script scriptPubKey = output.getScriptPubKey();
            ECKey controllingKey;
            if (ScriptPattern.isPayToPubKey(scriptPubKey)) {
                controllingKey = wallet.findKeyFromPubKey(ScriptPattern.extractKeyFromPayToPubKey(scriptPubKey));
            } else if (ScriptPattern.isPayToPubKeyHash(scriptPubKey)) {
                controllingKey = wallet.findKeyFromPubHash(ScriptPattern.extractHashFromPayToPubKeyHash(scriptPubKey));
            } else {
                log.info("Skipping tx output {} because it's not of simple form.", output);
                continue;
            }
            checkNotNull(controllingKey, "Coin selector given output as candidate for which we lack the key");
            if (controllingKey.getCreationTimeSeconds() >= unixTimeSeconds)
                continue;
            // It's older than the cutoff time so select.
            valueGathered = valueGathered.add(output.getValue());
            gathered.push(output);
            if (gathered.size() >= MAX_SIMULTANEOUS_INPUTS) {
                log.warn("Reached {} inputs, going further would yield a tx that is too large, stopping here.", gathered.size());
                break;
            }
        }
        return new CoinSelection(valueGathered, gathered);
    } catch (ScriptException e) {
        throw new RuntimeException(e);  // We should never have problems understanding scripts in our wallet.
    }
}
 
Example #9
Source File: Transaction.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns the difference of {@link Transaction#getValueSentToMe(TransactionBag)} and {@link Transaction#getValueSentFromMe(TransactionBag)}.
 */
public Coin getValue(TransactionBag wallet) throws ScriptException {
    // FIXME: TEMP PERF HACK FOR ANDROID - this crap can go away once we have a real payments API.
    boolean isAndroid = Utils.isAndroidRuntime();
    if (isAndroid && cachedValue != null && cachedForBag == wallet)
        return cachedValue;
    Coin result = getValueSentToMe(wallet).subtract(getValueSentFromMe(wallet));
    if (isAndroid) {
        cachedValue = result;
        cachedForBag = wallet;
    }
    return result;
}
 
Example #10
Source File: Transaction.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Gets the count of regular SigOps in this transactions
 */
public int getSigOpCount() throws ScriptException {
    int sigOps = 0;
    for (TransactionInput input : inputs)
        sigOps += Script.getSigOpCount(input.getScriptBytes());
    for (TransactionOutput output : outputs)
        sigOps += Script.getSigOpCount(output.getScriptBytes());
    return sigOps;
}
 
Example #11
Source File: UtxoTrieMgr.java    From jelectrum with MIT License 5 votes vote down vote up
public static byte[] getPublicKeyForTxOut(TransactionOutput out, NetworkParameters params)
{
    byte[] public_key=null;
    Script script = null;
        try
        {  
            script = out.getScriptPubKey();
            if (script.isSentToRawPubKey())
            {  
                byte[] key = out.getScriptPubKey().getPubKey();
                byte[] address_bytes = org.bitcoinj.core.Utils.sha256hash160(key);

                public_key = address_bytes;
            }
            else
            {  
                Address a = script.getToAddress(params);
                public_key = a.getHash160();
            }
        }
        catch(ScriptException e)
        { 
          public_key = figureOutStrange(script, out, params);
       }

  return public_key; 
}
 
Example #12
Source File: TXUtil.java    From jelectrum with MIT License 4 votes vote down vote up
public Address getFromAddress(TransactionInput in) throws ScriptException {
     return new LegacyAddress(params, org.bitcoinj.core.Utils.sha256hash160(getPubKey(in)));
}
 
Example #13
Source File: UtxoTrieMgr.java    From jelectrum with MIT License 4 votes vote down vote up
public String getKeyForInput(TransactionInput in)
{
  if (in.isCoinBase()) return null;
  try
  {   
    byte[] public_key=null; 
    Address a = in.getFromAddress();
    public_key = a.getHash160();

    return getKey(public_key, in.getOutpoint().getHash(), (int)in.getOutpoint().getIndex());
  }
  catch(ScriptException e)
  {
    //Lets try this the other way
    try
    {   

      TransactionOutPoint out_p = in.getOutpoint();

      Transaction src_tx = tx_util.getTransaction(out_p.getHash());
      TransactionOutput out = src_tx.getOutput((int)out_p.getIndex());
      return getKeyForOutput(out, (int)out_p.getIndex());
    }
    catch(ScriptException e2)
    {   
      return null;
    }
  }

 
}
 
Example #14
Source File: FullBlockTestGenerator.java    From bcm-android with GNU General Public License v3.0 4 votes vote down vote up
private void addOnlyInputToTransaction(Transaction t, TransactionOutPointWithValue prevOut) throws ScriptException {
    addOnlyInputToTransaction(t, prevOut, TransactionInput.NO_SEQUENCE);
}
 
Example #15
Source File: FullBlockTestGenerator.java    From bcm-android with GNU General Public License v3.0 4 votes vote down vote up
private void addOnlyInputToTransaction(Transaction t, NewBlock block) throws ScriptException {
    addOnlyInputToTransaction(t, block.getSpendableOutput(), TransactionInput.NO_SEQUENCE);
}
 
Example #16
Source File: FullBlockTestGenerator.java    From bcm-android with GNU General Public License v3.0 4 votes vote down vote up
private NewBlock createNextBlock(NewBlock baseBlock, int nextBlockHeight, @Nullable TransactionOutPointWithValue prevOut,
                                 Coin additionalCoinbaseValue) throws ScriptException {
    return createNextBlock(baseBlock.block, nextBlockHeight, prevOut, additionalCoinbaseValue);
}
 
Example #17
Source File: CustomTransactionSigner.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) {
    Transaction tx = propTx.partialTx;
    int numInputs = tx.getInputs().size();
    for (int i = 0; i < numInputs; i++) {
        TransactionInput txIn = tx.getInput(i);
        TransactionOutput txOut = txIn.getConnectedOutput();
        if (txOut == null) {
            continue;
        }
        Script scriptPubKey = txOut.getScriptPubKey();
        if (!ScriptPattern.isPayToScriptHash(scriptPubKey)) {
            log.warn("CustomTransactionSigner works only with P2SH transactions");
            return false;
        }

        Script inputScript = checkNotNull(txIn.getScriptSig());

        try {
            // We assume if its already signed, its hopefully got a SIGHASH type that will not invalidate when
            // we sign missing pieces (to check this would require either assuming any signatures are signing
            // standard output types or a way to get processed signatures out of script execution)
            txIn.getScriptSig().correctlySpends(tx, i, txIn.getConnectedOutput().getScriptPubKey());
            log.warn("Input {} already correctly spends output, assuming SIGHASH type used will be safe and skipping signing.", i);
            continue;
        } catch (ScriptException e) {
            // Expected.
        }

        RedeemData redeemData = txIn.getConnectedRedeemData(keyBag);
        if (redeemData == null) {
            log.warn("No redeem data found for input {}", i);
            continue;
        }

        Sha256Hash sighash = tx.hashForSignature(i, redeemData.redeemScript, Transaction.SigHash.ALL, false);
        SignatureAndKey sigKey = getSignature(sighash, propTx.keyPaths.get(scriptPubKey));
        TransactionSignature txSig = new TransactionSignature(sigKey.sig, Transaction.SigHash.ALL, false);
        int sigIndex = inputScript.getSigInsertionIndex(sighash, sigKey.pubKey);
        inputScript = scriptPubKey.getScriptSigWithSignature(inputScript, txSig.encodeToBitcoin(), sigIndex);
        txIn.setScriptSig(inputScript);
    }
    return true;
}
 
Example #18
Source File: TransactionInput.java    From bcm-android with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Alias for getOutpoint().getConnectedRedeemData(keyBag)
 *
 * @see TransactionOutPoint#getConnectedRedeemData(KeyBag)
 */
@Nullable
public RedeemData getConnectedRedeemData(KeyBag keyBag) throws ScriptException {
    return getOutpoint().getConnectedRedeemData(keyBag);
}
 
Example #19
Source File: Transaction.java    From bcm-android with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Same as {@link #addSignedInput(TransactionOutPoint, Script, ECKey, Transaction.SigHash, boolean)}
 * but defaults to {@link SigHash#ALL} and "false" for the anyoneCanPay flag. This is normally what you want.
 */
public TransactionInput addSignedInput(TransactionOutPoint prevOut, Script scriptPubKey, ECKey sigKey) throws ScriptException {
    return addSignedInput(prevOut, scriptPubKey, sigKey, SigHash.ALL, false);
}