net.bither.bitherj.exception.ScriptException Java Examples

The following examples show how to use net.bither.bitherj.exception.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: DialogAddressFullForHD.java    From bither-android with Apache License 2.0 6 votes vote down vote up
public DialogAddressFullForHD(Activity context, Tx tx, HDAccount account) {
    super(context);
    activity = context;
    List<String> inAddresses = tx.getInAddresses();
    List<String> outAddresses = tx.getOutAddressList();
    ownAddresses = account.getRelatedAddressesForTx(tx, inAddresses);
    Collections.sort(ownAddresses, new Comparator<HDAccount.HDAccountAddress>() {
        @Override
        public int compare(HDAccount.HDAccountAddress lhs, HDAccount.HDAccountAddress rhs) {
            if (lhs.getPathType() != rhs.getPathType()) {
                return lhs.getPathType().getValue() - rhs.getPathType().getValue();
            }
            return lhs.getIndex() - rhs.getIndex();
        }
    });
    boolean isIncoming = true;
    try {
        isIncoming = tx.deltaAmountFrom(account) >= 0;
    } catch (ScriptException e) {
        e.printStackTrace();
    }
    List<String> foreign = foreignAddresses(isIncoming ? inAddresses : outAddresses);
    initForeignAddresses(isIncoming, tx, foreign);
    initView();
}
 
Example #2
Source File: WalletUtils.java    From bither-desktop-java with Apache License 2.0 6 votes vote down vote up
public static boolean isInternal(@Nonnull final Tx tx) {
    if (tx.isCoinBase()) {
        return false;
    }

    final List<Out> outputs = tx.getOuts();
    if (outputs.size() != 1) {
        return false;
    }

    try {
        final Out output = outputs.get(0);
        final Script scriptPubKey = output.getScriptPubKey();
        if (!scriptPubKey.isSentToRawPubKey()) {
            return false;
        }

        return true;
    } catch (final ScriptException x) {
        return false;
    }
}
 
Example #3
Source File: Tx.java    From bitherj with Apache License 2.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 net.bither.bitherj.exception.ScriptException if the scriptPubKey is not a pay to address or pay to pubkey script.
 */
public In addSignedInput(Out prevOut, Script scriptPubKey, ECKey sigKey,
                         TransactionSignature.SigHash sigHash, boolean anyoneCanPay) throws
        ScriptException {
    In input = new In(this, new byte[]{}, prevOut);
    addInput(input);
    byte[] hash = hashForSignature(ins.size() - 1, scriptPubKey, sigHash, anyoneCanPay);
    ECKey.ECDSASignature ecSig = sigKey.sign(hash);
    TransactionSignature txSig = new TransactionSignature(ecSig, sigHash, anyoneCanPay);
    if (scriptPubKey.isSentToRawPubKey()) {
        input.setInSignature(ScriptBuilder.createInputScript(txSig).getProgram());
    } else if (scriptPubKey.isSentToAddress()) {
        input.setInSignature(ScriptBuilder.createInputScript(txSig, sigKey).getProgram());
    } else {
        throw new ScriptException("Don't know how to sign for this kind of scriptPubKey: " +
                scriptPubKey);
    }
    return input;
}
 
Example #4
Source File: Script.java    From bitherj with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the count of P2SH Sig Ops in the Script scriptSig
 */
public static long getP2SHSigOpCount(byte[] scriptSig) throws ScriptException {
    Script script = new Script();
    try {
        script.parse(scriptSig);
    } catch (ScriptException e) {
        // Ignore errors and count up to the parse-able length
    }
    for (int i = script.chunks.size() - 1; i >= 0; i--)
        if (!script.chunks.get(i).isOpCode()) {
            Script subScript = new Script();
            subScript.parse(script.chunks.get(i).data);
            return getSigOpCount(subScript.chunks, true);
        }
    return 0;
}
 
Example #5
Source File: Script.java    From bitherj with Apache License 2.0 6 votes vote down vote up
private static int getSigOpCount(List<ScriptChunk> chunks, boolean accurate) throws ScriptException {
    int sigOps = 0;
    int lastOpCode = OP_INVALIDOPCODE;
    for (ScriptChunk chunk : chunks) {
        if (chunk.isOpCode()) {
            switch (chunk.opcode) {
                case OP_CHECKSIG:
                case OP_CHECKSIGVERIFY:
                    sigOps++;
                    break;
                case OP_CHECKMULTISIG:
                case OP_CHECKMULTISIGVERIFY:
                    if (accurate && lastOpCode >= OP_1 && lastOpCode <= OP_16)
                        sigOps += decodeFromOpN(lastOpCode);
                    else
                        sigOps += 20;
                    break;
                default:
                    break;
            }
            lastOpCode = chunk.opcode;
        }
    }
    return sigOps;
}
 
Example #6
Source File: Script.java    From bitherj with Apache License 2.0 6 votes vote down vote up
public String getFromAddress() throws ScriptException {
    if (this.chunks.size() == 2
            && this.chunks.get(0).data != null && this.chunks.get(0).data.length > 2
            && this.chunks.get(1).data != null && this.chunks.get(1).data.length > 2) {
        return Utils.toAddress(Utils.sha256hash160(this.chunks.get(1).data));
    } else if (this.chunks.size() >= 3 && this.chunks.get(0).opcode == OP_0) {
        boolean isPay2SHScript = true;
        for (int i = 1; i < this.chunks.size(); i++) {
            isPay2SHScript &= (this.chunks.get(i).data != null && this.chunks.get(i).data.length > 2);
        }
        if (isPay2SHScript) {
            return Utils.toP2SHAddress(Utils.sha256hash160(this.chunks.get(this.chunks.size() - 1).data));
        }
    }
    return null;
}
 
Example #7
Source File: Script.java    From bitherj with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the public key in this script. If a script contains two constants and nothing else, it is assumed to
 * be a scriptSig (input) for a pay-to-address output and the second constant is returned (the first is the
 * signature). If a script contains a constant and an OP_CHECKSIG opcode, the constant is returned as it is
 * assumed to be a direct pay-to-key scriptPubKey (output) and the first constant is the public key.
 *
 * @throws ScriptException if the script is none of the named forms.
 */
public byte[] getPubKey() throws ScriptException {
    if (chunks.size() != 2) {
        throw new ScriptException("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("Script did not match expected form: " + toString());
    }
}
 
Example #8
Source File: Script.java    From bitherj with Apache License 2.0 6 votes vote down vote up
public boolean isSendFromMultiSig() {
    boolean result = this.chunks.get(0).opcode == OP_0;
    for (int i = 1; i < this.chunks.size(); i++) {

        result &= this.chunks.get(i).data != null && this.chunks.get(i).data.length > 2;
    }
    if (result) {
        try {
            Script multiSigRedeem = new Script(this.chunks.get(this.chunks.size() - 1).data);
            result &= multiSigRedeem.isMultiSigRedeem();
        } catch (ScriptException ex) {
            result = false;
        }
    }
    return result;
}
 
Example #9
Source File: WalletUtils.java    From bither-desktop-java with Apache License 2.0 6 votes vote down vote up
public static boolean isInternal(@Nonnull final Tx tx) {
    if (tx.isCoinBase()) {
        return false;
    }

    final List<Out> outputs = tx.getOuts();
    if (outputs.size() != 1) {
        return false;
    }

    try {
        final Out output = outputs.get(0);
        final Script scriptPubKey = output.getScriptPubKey();
        if (!scriptPubKey.isSentToRawPubKey()) {
            return false;
        }

        return true;
    } catch (final ScriptException x) {
        return false;
    }
}
 
Example #10
Source File: WalletUtils.java    From bither-android with Apache License 2.0 6 votes vote down vote up
public static boolean isInternal(@Nonnull final Tx tx) {
    if (tx.isCoinBase()) {
        return false;
    }

    final List<Out> outputs = tx.getOuts();
    if (outputs.size() != 1) {
        return false;
    }

    try {
        final Out output = outputs.get(0);
        final Script scriptPubKey = output.getScriptPubKey();
        if (!scriptPubKey.isSentToRawPubKey()) {
            return false;
        }

        return true;
    } catch (final ScriptException x) {
        return false;
    }
}
 
Example #11
Source File: Script.java    From bitherj with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the destination address from this script, if it's in the required form (see getPubKey).
 */
public String getToAddress() throws ScriptException {
    if (isSentToAddress())
        return Utils.toAddress(getPubKeyHash());
    else if (isSentToP2SH())
        return Utils.toP2SHAddress(this.getPubKeyHash());
    else
        throw new ScriptException("Cannot cast this script to a pay-to-address type");
}
 
Example #12
Source File: Script.java    From bitherj with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the count of regular SigOps in the script program (counting multisig ops as 20)
 */
public static int getSigOpCount(byte[] program) throws ScriptException {
    Script script = new Script();
    try {
        script.parse(program);
    } catch (ScriptException e) {
        // Ignore errors and count up to the parse-able length
    }
    return getSigOpCount(script.chunks, false);
}
 
Example #13
Source File: Script.java    From bitherj with Apache License 2.0 5 votes vote down vote up
private static void executeCheckSig(Tx txContainingThis, int index, Script script, LinkedList<byte[]> stack,
                                    int lastCodeSepLocation, int opcode) throws ScriptException {
    if (stack.size() < 2)
        throw new ScriptException("Attempted OP_CHECKSIG(VERIFY) on a stack with size < 2");
    byte[] pubKey = stack.pollLast();
    byte[] sigBytes = stack.pollLast();

    byte[] prog = script.getProgram();
    byte[] connectedScript = Arrays.copyOfRange(prog, lastCodeSepLocation, prog.length);

    UnsafeByteArrayOutputStream outStream = new UnsafeByteArrayOutputStream(sigBytes.length + 1);
    try {
        writeBytes(outStream, sigBytes);
    } catch (IOException e) {
        throw new RuntimeException(e); // Cannot happen
    }
    connectedScript = removeAllInstancesOf(connectedScript, outStream.toByteArray());

    // TODO: Use int for indexes everywhere, we can't have that many inputs/outputs
    boolean sigValid = false;
    try {
        TransactionSignature sig = TransactionSignature.decodeFromBitcoin(sigBytes, false);
        byte[] hash = txContainingThis.hashForSignature(index, connectedScript, (byte) sig.sighashFlags);
        sigValid = ECKey.verify(hash, sig, pubKey);
    } catch (Exception e1) {
        // There is (at least) one exception that could be hit here (EOFException, if the sig is too short)
        // Because I can't verify there aren't more, we use a very generic Exception catch
        log.warn(e1.toString());
    }

    if (opcode == OP_CHECKSIG)
        stack.add(sigValid ? new byte[]{1} : new byte[]{0});
    else if (opcode == OP_CHECKSIGVERIFY)
        if (!sigValid)
            throw new ScriptException("Script failed OP_CHECKSIGVERIFY");
}
 
Example #14
Source File: TransactionsUtil.java    From bitherj with Apache License 2.0 5 votes vote down vote up
public static boolean signTransaction(Tx tx, String qrCodeContent)
        throws ScriptException {
    String[] stringArray = QRCodeUtil.splitString(qrCodeContent);
    List<byte[]> hashList = new ArrayList<byte[]>();
    for (String str : stringArray) {
        if (!Utils.isEmpty(str)) {
            hashList.add(Utils.hexStringToByteArray(str));
        }
    }
    tx.signWithSignatures(hashList);
    return tx.verifySignatures();
}
 
Example #15
Source File: Out.java    From bitherj with Apache License 2.0 5 votes vote down vote up
public String getOutAddress() {
        if (outAddress == null) {
            try {
                Script pubKeyScript = new Script(this.getOutScript());
                outAddress = pubKeyScript.getToAddress();
            } catch (ScriptException e) {
//                if (this.getOutScript() != null) {
//                    log.warn("out script : " + Utils.bytesToHexString(this.getOutScript()));
//                }
            }
        }
        return outAddress;
    }
 
Example #16
Source File: Script.java    From bitherj with Apache License 2.0 5 votes vote down vote up
@Deprecated
public byte[] getSig() throws ScriptException {
    if (chunks.size() == 1 && chunks.get(0).isPushData()) {
        return chunks.get(0).data;
    } else if (chunks.size() == 2 && chunks.get(0).isPushData()
            && chunks.get(1).isPushData()
            && chunks.get(0).data != null
            && chunks.get(0).data.length > 2
            && chunks.get(1).data != null
            && chunks.get(1).data.length > 2) {
        return chunks.get(0).data;
    } else {
        throw new ScriptException("Script did not match expected form: " + toString());
    }
}
 
Example #17
Source File: Tx.java    From bitherj with Apache License 2.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 (In input : ins)
        sigOps += Script.getSigOpCount(input.getInSignature());
    for (Out output : outs)
        sigOps += Script.getSigOpCount(output.getOutScript());
    return sigOps;
}
 
Example #18
Source File: ScriptTest.java    From bitherj with Apache License 2.0 5 votes vote down vote up
@Test
    public void testDataDrivenValidScripts() throws Exception {
        BufferedReader in = new BufferedReader(new InputStreamReader(
                getClass().getResourceAsStream("script_valid.json"), Charset.forName("UTF-8")));
//        NetworkParameters params = TestNet3Params.get();

        // Poor man's JSON parser (because pulling in a lib for this is overkill)
        String script = "";
        while (in.ready()) {
            String line = in.readLine();
            if (line == null || line.equals("")) continue;
            script += line;
            if (line.equals("]") && script.equals("]") && !in.ready())
                break; // ignore last ]
            if (line.trim().endsWith("],") || line.trim().endsWith("]")) {
                String[] scripts = script.split(",");

                scripts[0] = scripts[0].replaceAll("[\"\\[\\]]", "").trim();
                scripts[1] = scripts[1].replaceAll("[\"\\[\\]]", "").trim();
                Script scriptSig = parseScriptString(scripts[0]);
                Script scriptPubKey = parseScriptString(scripts[1]);

                try {
                    scriptSig.correctlySpends(new Tx(), 0, scriptPubKey, true);
                } catch (ScriptException e) {
                    System.err.println("scriptSig: " + scripts[0]);
                    System.err.println("scriptPubKey: " + scripts[1]);
                    System.err.flush();
                    throw e;
                }
                script = "";
            }
        }
        in.close();
    }
 
Example #19
Source File: Script.java    From bitherj with Apache License 2.0 5 votes vote down vote up
/**
 * If a program matches the standard template DUP HASH160 <pubkey hash> EQUALVERIFY CHECKSIG
 * then this function retrieves the third element, otherwise it throws a ScriptException.<p>
 * <p/>
 * This is useful for fetching the destination address of a transaction.
 */
public byte[] getPubKeyHash() throws ScriptException {
    if (isSentToAddress())
        return chunks.get(2).data;
    else if (isPayToScriptHash())
        return chunks.get(1).data;
    else
        throw new ScriptException("Script not in the standard scriptPubKey form");
}
 
Example #20
Source File: Script.java    From bitherj with Apache License 2.0 4 votes vote down vote up
/**
 * <p>To run a script, first we parse it which breaks it up into chunks representing pushes of data or logical
 * opcodes. Then we can run the parsed chunks.</p>
 * <p/>
 * <p>The reason for this split, instead of just interpreting directly, is to make it easier
 * to reach into a programs structure and pull out bits of data without having to run it.
 * This is necessary to render the to/from addresses of transactions in a user interface.
 * The official client does something similar.</p>
 */
private void parse(byte[] program) throws ScriptException {
    chunks = new ArrayList<ScriptChunk>(5);   // Common size.
    ByteArrayInputStream bis = new ByteArrayInputStream(program);
    int initialSize = bis.available();
    while (bis.available() > 0) {
        int startLocationInProgram = initialSize - bis.available();
        int opcode = bis.read();

        long dataToRead = -1;
        if (opcode >= 0 && opcode < OP_PUSHDATA1) {
            // Read some bytes of data, where how many is the opcode value itself.
            dataToRead = opcode;
        } else if (opcode == OP_PUSHDATA1) {
            if (bis.available() < 1) throw new ScriptException("Unexpected end of script");
            dataToRead = bis.read();
        } else if (opcode == OP_PUSHDATA2) {
            // Read a short, then read that many bytes of data.
            if (bis.available() < 2) throw new ScriptException("Unexpected end of script");
            dataToRead = bis.read() | (bis.read() << 8);
        } else if (opcode == OP_PUSHDATA4) {
            // Read a uint32, then read that many bytes of data.
            // Though this is allowed, because its value cannot be > 520, it should never actually be used
            if (bis.available() < 4) throw new ScriptException("Unexpected end of script");
            dataToRead = ((long) bis.read()) | (((long) bis.read()) << 8) | (((long) bis.read()) << 16) | (((long) bis.read()) << 24);
        }

        ScriptChunk chunk;
        if (dataToRead == -1) {
            chunk = new ScriptChunk(opcode, null, startLocationInProgram);
        } else {
            if (dataToRead > bis.available())
                throw new ScriptException("Push of data element that is larger than remaining data");
            byte[] data = new byte[(int) dataToRead];
            checkState(dataToRead == 0 || bis.read(data, 0, (int) dataToRead) == dataToRead);
            chunk = new ScriptChunk(opcode, data, startLocationInProgram);
        }
        // Save some memory by eliminating redundant copies of the same chunk objects.
        for (ScriptChunk c : STANDARD_TRANSACTION_SCRIPT_CHUNKS) {
            if (c.equals(chunk)) chunk = c;
        }
        chunks.add(chunk);
    }
}
 
Example #21
Source File: Script.java    From bitherj with Apache License 2.0 4 votes vote down vote up
public Script(byte[] programBytes, long creationTimeSeconds) throws ScriptException {
    program = programBytes;
    parse(programBytes);
    this.creationTimeSeconds = creationTimeSeconds;
}
 
Example #22
Source File: Script.java    From bitherj with Apache License 2.0 4 votes vote down vote up
public List<byte[]> getP2SHPubKeys(Tx tx, int index) {
    if (!this.isSendFromMultiSig()) {
        throw new ScriptException("[Script Error] is not send from multisig");
    }

    Script scriptPubKey = new Script(this.chunks.get(this.chunks.size() - 1).data);
    int sigCount = scriptPubKey.chunks.get(0).opcode - 80;
    int pubKeyCount = scriptPubKey.chunks.get(scriptPubKey.chunks.size() - 2).opcode - 80;
    if (pubKeyCount < 0 || pubKeyCount > 20) {
        throw new ScriptException("[Script Error] OP_CHECKMULTISIG(VERIFY) with pubkey count out of range");
    }

    List<byte[]> pubKeys = new ArrayList<byte[]>();

    for (int i = 0; i < pubKeyCount; i++) {
        pubKeys.add(scriptPubKey.chunks.get(i + 1).data);
    }

    if (sigCount < 0 || sigCount > pubKeyCount) {
        throw new ScriptException("[Script Error] OP_CHECKMULTISIG(VERIFY) with sig count out of range");
    }

    List<byte[]> sigs = new ArrayList<byte[]>();
    for (int i = 1; i < sigCount + 1; i++) {
        sigs.add(this.chunks.get(i).data);
    }

    List<byte[]> result = new ArrayList<byte[]>();
    while (sigs.size() > 0) {
        byte[] pubKey = pubKeys.get(pubKeys.size() - 1);
        pubKeys.remove(pubKeys.size() - 1);

        byte[] sigBytes = sigs.get(sigs.size() - 1);

        if (sigBytes.length > 0) {
            TransactionSignature sig = TransactionSignature.decodeFromBitcoin(sigBytes, false);
            byte[] hash = tx.hashForSignature(index, scriptPubKey.getProgram(), (byte) sig.sighashFlags);
            boolean sigValid = ECKey.verify(hash, sig, pubKey);

            if (sigValid) {
                result.add(pubKey);
                sigs.remove(sigs.size() - 1);
            }
        }
        if (sigs.size() > pubKeys.size()) {
            break;
        }
    }

    return result;
}
 
Example #23
Source File: Script.java    From bitherj with Apache License 2.0 4 votes vote down vote up
private static BigInteger castToBigInteger(byte[] chunk) throws ScriptException {
    if (chunk.length > 4)
        throw new ScriptException("Script attempted to use an integer larger than 4 bytes");
    return Utils.decodeMPI(Utils.reverseBytes(chunk), false);
}
 
Example #24
Source File: Tx.java    From bitherj with Apache License 2.0 4 votes vote down vote up
/**
 * Same as {@link #addSignedInput(net.bither.bitherj.core.Out, net.bither.bitherj.script.Script, net.bither.bitherj.crypto.ECKey, net.bither.bitherj.crypto.TransactionSignature.SigHash, boolean)}
 * but defaults to {@link net.bither.bitherj.crypto.TransactionSignature.SigHash#ALL} and
 * "false" for the anyoneCanPay flag. This is normally what you want.
 */
public In addSignedInput(Out prevOut, Script scriptPubKey,
                         ECKey sigKey) throws ScriptException {
    return addSignedInput(prevOut, scriptPubKey, sigKey, TransactionSignature.SigHash.ALL,
            false);
}
 
Example #25
Source File: Script.java    From bitherj with Apache License 2.0 2 votes vote down vote up
/**
 * Construct a Script that copies and wraps the programBytes array. The array is parsed and checked for syntactic
 * validity.
 *
 * @param programBytes Array of program bytes from a transaction.
 */
public Script(byte[] programBytes) throws ScriptException {
    program = programBytes;
    parse(programBytes);
    creationTimeSeconds = Utils.currentTimeSeconds();
}
 
Example #26
Source File: Tx.java    From bitherj with Apache License 2.0 2 votes vote down vote up
/**
 * Once a transaction has some inputs and outputs added, the signatures in the inputs can be
 * calculated. The
 * signature is over the transaction itself, to prove the redeemer actually created that
 * transaction,
 * so we have to do this step last.<p>
 * <p/>
 * This method is similar to SignatureHash in script.cpp
 *
 * @param hashType This should always be set to SigHash.ALL currently. Other types are unused.
 * @param address  A wallet is required to fetch the keys needed for signing.
 */
public synchronized void signInputs(TransactionSignature.SigHash hashType,
                                    Address address) throws ScriptException {
    signInputs(hashType, address, null);
}