net.bither.bitherj.crypto.TransactionSignature Java Examples

The following examples show how to use net.bither.bitherj.crypto.TransactionSignature. 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: 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 #2
Source File: Address.java    From bitherj with Apache License 2.0 6 votes vote down vote up
public List<byte[]> signHashes(List<byte[]> unsignedInHashes, CharSequence passphrase) throws
        PasswordException {
    ECKey key = PrivateKeyUtil.getECKeyFromSingleString(this.getFullEncryptPrivKey(), passphrase);
    if (key == null) {
        throw new PasswordException("do not decrypt eckey");
    }
    KeyParameter assKey = key.getKeyCrypter().deriveKey(passphrase);
    List<byte[]> result = new ArrayList<byte[]>();
    for (byte[] unsignedInHash : unsignedInHashes) {
        TransactionSignature signature = new TransactionSignature(key.sign(unsignedInHash,
                assKey), TransactionSignature.SigHash.ALL, false);
        result.add(ScriptBuilder.createInputScript(signature, key).getProgram());
    }
    key.clearPrivateKey();
    return result;
}
 
Example #3
Source File: DesktopHDMKeychain.java    From bitherj with Apache License 2.0 6 votes vote down vote up
public static List<byte[]> formatInScript(List<TransactionSignature> signs1,
                                          List<TransactionSignature> signs2,
                                          List<DesktopHDMAddress> addressList) {
    List<byte[]> result = new ArrayList<byte[]>();
    for (int i = 0;
         i < signs1.size();
         i++) {
        DesktopHDMAddress a = addressList.get(i);
        List<TransactionSignature> signs = new ArrayList<TransactionSignature>(2);
        signs.add(signs1.get(i));
        signs.add(signs2.get(i));
        result.add(ScriptBuilder.createP2SHMultiSigInputScript(signs,
                a.getPubKey()).getProgram());
    }
    return result;
}
 
Example #4
Source File: DesktopHDMKeychain.java    From bitherj with Apache License 2.0 6 votes vote down vote up
public ArrayList<TransactionSignature> signMyPart(List<byte[]> unsignedHashes,
                                                  CharSequence password,
                                                  List<PathTypeIndex> pathTypeIndexList) {


    ArrayList<TransactionSignature> sigs = new ArrayList<TransactionSignature>();
    for (int i = 0;
         i < unsignedHashes.size();
         i++) {
        PathTypeIndex pathTypeIndex = pathTypeIndexList.get(i);
        DeterministicKey key;
        if (pathTypeIndex.pathType == PathType.EXTERNAL_ROOT_PATH) {
            key = getExternalKey(pathTypeIndex.index, password);
        } else {
            key = getInternalKey(pathTypeIndex.index, password);
        }
        TransactionSignature transactionSignature = new TransactionSignature(key.sign
                (unsignedHashes.get(i)), TransactionSignature.SigHash.ALL, false);
        sigs.add(transactionSignature);
        key.wipe();
    }

    return sigs;
}
 
Example #5
Source File: HDMAddress.java    From bitherj with Apache License 2.0 6 votes vote down vote up
public ArrayList<TransactionSignature> signMyPart(List<byte[]> unsignedHashes,
                                                  CharSequence password) {
    if (isInRecovery()) {
        throw new AssertionError("recovery hdm address can not sign");
    }
    DeterministicKey key = keychain.getExternalKey(pubs.index, password);
    ArrayList<TransactionSignature> sigs = new ArrayList<TransactionSignature>();
    for (int i = 0;
         i < unsignedHashes.size();
         i++) {
        TransactionSignature transactionSignature = new TransactionSignature(key.sign
                (unsignedHashes.get(i)), TransactionSignature.SigHash.ALL, false);
        sigs.add(transactionSignature);
    }
    key.wipe();
    return sigs;
}
 
Example #6
Source File: SendHDMBitcoinPanel.java    From bither-desktop-java with Apache License 2.0 5 votes vote down vote up
public boolean setQrCodeResult(String qr) {

            if (!Utils.isEmpty(qr)) {
                try {
                    String[] stringArray = QRCodeUtil.splitString(qr);
                    sigs = new ArrayList<TransactionSignature>();
                    for (String str : stringArray) {
                        if (!Utils.isEmpty(str)) {
                            TransactionSignature transactionSignature = new
                                    TransactionSignature(ECKey.ECDSASignature.decodeFromDER
                                    (Utils.hexStringToByteArray(str)),
                                    TransactionSignature.SigHash.ALL, false);
                            sigs.add(transactionSignature);
                        }
                    }
                } catch (Exception e) {
                    sigs = null;
                    e.printStackTrace();
                    new MessageDialog(LocaliserUtils.getString("send_failed")).showMsg();
                }
            } else {
                sigs = null;
            }
            try {
                lock.lock();
                fetchedCondition.signal();
            } finally {
                lock.unlock();
            }
            return true;

        }
 
Example #7
Source File: SendHDMBitcoinPanel.java    From bither-desktop-java with Apache License 2.0 5 votes vote down vote up
public boolean setQrCodeResult(String qr) {

            if (!Utils.isEmpty(qr)) {
                try {
                    String[] stringArray = QRCodeUtil.splitString(qr);
                    sigs = new ArrayList<TransactionSignature>();
                    for (String str : stringArray) {
                        if (!Utils.isEmpty(str)) {
                            TransactionSignature transactionSignature = new
                                    TransactionSignature(ECKey.ECDSASignature.decodeFromDER
                                    (Utils.hexStringToByteArray(str)),
                                    TransactionSignature.SigHash.ALL, false);
                            sigs.add(transactionSignature);
                        }
                    }
                } catch (Exception e) {
                    sigs = null;
                    e.printStackTrace();
                    new MessageDialog(LocaliserUtils.getString("send_failed")).showMsg();
                }
            } else {
                sigs = null;
            }
            try {
                lock.lock();
                fetchedCondition.signal();
            } finally {
                lock.unlock();
            }
            return true;

        }
 
Example #8
Source File: SendHDMBitcoinPanel.java    From bither-desktop-java with Apache License 2.0 5 votes vote down vote up
@Override
public List<TransactionSignature> getOtherSignature(int addressIndex,
                                                    CharSequence password,
                                                    List<byte[]> unsignHash, final Tx tx) {
    signingIndex = addressIndex;
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            SendBitcoinConfirmPanel dialog = new SendBitcoinConfirmPanel(preConfirmListener,
                    bitcoinAddress, changeAddress, tx
            );
            dialog.showPanel();
        }
    });
    sigs = null;
    try {
        lock.lockInterruptibly();
        fetchedCondition.await();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        lock.unlock();
    }
    if (sigs == null) {
        throw new CompleteTransactionRunnable.HDMSignUserCancelExcetion();
    }
    signingIndex = -1;
    return sigs;
}
 
Example #9
Source File: Tx.java    From bitherj with Apache License 2.0 5 votes vote down vote up
public List<byte[]> getUnsignedInHashesForDesktpHDM(byte[] pubs, int index) {
    List<byte[]> result = new ArrayList<byte[]>();
    In in = this.getIns().get(index);
    byte sigHashType = (byte) TransactionSignature.calcSigHashValue(TransactionSignature
            .SigHash.ALL, false);
    result.add(this.hashForSignature(in.getInSn(), pubs, sigHashType));
    return result;
}
 
Example #10
Source File: Tx.java    From bitherj with Apache License 2.0 5 votes vote down vote up
public List<byte[]> getUnsignedInHashesForHDM(byte[] pubs) {
    List<byte[]> result = new ArrayList<byte[]>();
    for (In in : this.getIns()) {
        byte sigHashType = (byte) TransactionSignature.calcSigHashValue(TransactionSignature
                .SigHash.ALL, false);
        result.add(this.hashForSignature(in.getInSn(), pubs, sigHashType));
    }
    return result;
}
 
Example #11
Source File: Tx.java    From bitherj with Apache License 2.0 5 votes vote down vote up
public List<byte[]> getUnsignedInHashes() {
    List<byte[]> result = new ArrayList<byte[]>();
    for (In in : this.getIns()) {
        byte sigHashType = (byte) TransactionSignature.calcSigHashValue(TransactionSignature
                .SigHash.ALL, false);
        result.add(this.hashForSignature(in.getInSn(), in.getPrevOutScript(), sigHashType));
    }
    return result;
}
 
Example #12
Source File: EnterpriseHDMTxSignaturePool.java    From bitherj with Apache License 2.0 5 votes vote down vote up
public boolean addSignature(List<byte[]> sigs) {
    if (sigs.size() != tx.getIns().size()) {
        return false;
    }
    ArrayList<TransactionSignature> txSigs = new ArrayList<TransactionSignature>();
    int pubIndex = -1;
    for (int i = 0;
         i < tx.getIns().size();
         i++) {
        TransactionSignature txSig = new TransactionSignature(ECKey.ECDSASignature
                .decodeFromDER(sigs.get(i)), TransactionSignature.SigHash.ALL, false);
        if (i == 0) {
            byte[] pub = recoverPub(sigs.get(i), unsignedHashes().get(i));
            if (pub == null) {
                break;
            }
            pubIndex = pubs.indexOf(pub);
            if (pubIndex < 0) {
                break;
            }
        }
        txSigs.add(txSig);
    }
    if (pubIndex < 0) {
        return false;
    }
    signatures.put(Integer.valueOf(pubIndex), txSigs);
    return true;
}
 
Example #13
Source File: DesktopHDMAddress.java    From bitherj with Apache License 2.0 5 votes vote down vote up
public static List<byte[]> formatInScript(List<TransactionSignature> signs1,
                                          List<TransactionSignature> signs2,
                                          byte[] scriptPubKey) {
    List<byte[]> result = new ArrayList<byte[]>();
    for (int i = 0;
         i < signs1.size();
         i++) {
        List<TransactionSignature> signs = new ArrayList<TransactionSignature>(2);
        signs.add(signs1.get(i));
        signs.add(signs2.get(i));
        result.add(ScriptBuilder.createP2SHMultiSigInputScript(signs,
                scriptPubKey).getProgram());
    }
    return result;
}
 
Example #14
Source File: DesktopHDMAddress.java    From bitherj with Apache License 2.0 5 votes vote down vote up
public ArrayList<TransactionSignature> signMyPart(List<byte[]> unsignedHashes,
                                                  CharSequence password) {
    DeterministicKey key = keychain.getExternalKey(pubs.index, password);
    ArrayList<TransactionSignature> sigs = new ArrayList<TransactionSignature>();
    for (int i = 0;
         i < unsignedHashes.size();
         i++) {
        TransactionSignature transactionSignature = new TransactionSignature(key.sign
                (unsignedHashes.get(i)), TransactionSignature.SigHash.ALL, false);
        sigs.add(transactionSignature);
    }
    key.wipe();
    return sigs;
}
 
Example #15
Source File: HDMAddress.java    From bitherj with Apache License 2.0 5 votes vote down vote up
public static List<byte[]> formatInScript(List<TransactionSignature> signs1,
                                          List<TransactionSignature> signs2,
                                          byte[] scriptPubKey) {
    List<byte[]> result = new ArrayList<byte[]>();
    for (int i = 0;
         i < signs1.size();
         i++) {
        List<TransactionSignature> signs = new ArrayList<TransactionSignature>(2);
        signs.add(signs1.get(i));
        signs.add(signs2.get(i));
        result.add(ScriptBuilder.createP2SHMultiSigInputScript(signs,
                scriptPubKey).getProgram());
    }
    return result;
}
 
Example #16
Source File: ScriptBuilder.java    From bitherj with Apache License 2.0 5 votes vote down vote up
/**
 * Create a program that satisfies a pay-to-script hashed OP_CHECKMULTISIG program.
 */
public static Script createP2SHMultiSigInputScript(List<TransactionSignature> signatures,
                                                   byte[] multisigProgramBytes) {
    List<byte[]> sigs = new ArrayList<byte[]>(signatures.size());
    for (TransactionSignature signature : signatures)
        sigs.add(signature.encodeToBitcoin());
    return createMultiSigInputScriptBytes(sigs, multisigProgramBytes);
}
 
Example #17
Source File: SendHDMBitcoinPanel.java    From bither-desktop-java with Apache License 2.0 5 votes vote down vote up
@Override
public List<TransactionSignature> getOtherSignature(int addressIndex,
                                                    CharSequence password,
                                                    List<byte[]> unsignHash, final Tx tx) {
    signingIndex = addressIndex;
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            SendBitcoinConfirmPanel dialog = new SendBitcoinConfirmPanel(preConfirmListener,
                    bitcoinAddress, changeAddress, tx
            );
            dialog.showPanel();
        }
    });
    sigs = null;
    try {
        lock.lockInterruptibly();
        fetchedCondition.await();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        lock.unlock();
    }
    if (sigs == null) {
        throw new CompleteTransactionRunnable.HDMSignUserCancelExcetion();
    }
    signingIndex = -1;
    return sigs;
}
 
Example #18
Source File: HdmSendActivity.java    From bither-android with Apache License 2.0 5 votes vote down vote up
@Override
public List<TransactionSignature> getOtherSignature(int addressIndex,
                                                    CharSequence password,
                                                    List<byte[]> unsignHash, final Tx tx) {
    signingIndex = addressIndex;
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            DialogSendConfirm dialog = new DialogSendConfirm(HdmSendActivity.this, tx,
                    dialogSelectChangeAddress.getChangeAddress().equals(address) ? null :
                            dialogSelectChangeAddress.getChangeAddress().getAddress(),
                    preConfirmListener);
            dialog.show();
        }
    });
    sigs = null;
    try {
        lock.lockInterruptibly();
        fetchedCondition.await();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        lock.unlock();
    }
    if (sigs == null) {
        throw new CompleteTransactionRunnable.HDMSignUserCancelExcetion();
    }
    signingIndex = -1;
    return sigs;
}
 
Example #19
Source File: HdmSendActivity.java    From bither-android with Apache License 2.0 5 votes vote down vote up
public boolean onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == RequestCode) {
        if (resultCode == RESULT_OK) {
            final String qr = data.getStringExtra(ScanActivity.INTENT_EXTRA_RESULT);
            try {
                String[] stringArray = QRCodeUtil.splitString(qr);
                sigs = new ArrayList<TransactionSignature>();
                for (String str : stringArray) {
                    if (!Utils.isEmpty(str)) {
                        TransactionSignature transactionSignature = new
                                TransactionSignature(ECKey.ECDSASignature.decodeFromDER
                                (Utils.hexStringToByteArray(str)),
                                TransactionSignature.SigHash.ALL, false);
                        sigs.add(transactionSignature);
                    }
                }
            } catch (Exception e) {
                sigs = null;
                e.printStackTrace();
                DropdownMessage.showDropdownMessage(HdmSendActivity.this,
                        R.string.send_failed);
            }
        } else {
            sigs = null;
        }
        try {
            lock.lock();
            fetchedCondition.signal();
        } finally {
            lock.unlock();
        }
        return true;
    }
    return false;
}
 
Example #20
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 #21
Source File: DesktopHDMKeychain.java    From bitherj with Apache License 2.0 4 votes vote down vote up
List<TransactionSignature> getOtherSignature(Tx tx,
List<byte[]> unsignHash, List<PathTypeIndex> pathTypeIndexLsit);
 
Example #22
Source File: SendHDMBitcoinPanel.java    From bither-desktop-java with Apache License 2.0 4 votes vote down vote up
@Override
public List<TransactionSignature> getOtherSignature(int addressIndex,
                                                    CharSequence password,
                                                    List<byte[]> unsignHash, Tx tx) {
    List<TransactionSignature> transactionSignatureList = new
            ArrayList<TransactionSignature>();
    try {
        HDMBId hdmbId = HDMBId.getHDMBidFromDb();
        byte[] decryptedPassword = hdmbId.decryptHDMBIdPassword(password);
        SignatureHDMApi signatureHDMApi = new SignatureHDMApi(HDMBId.getHDMBidFromDb()
                .getAddress(), addressIndex, decryptedPassword, unsignHash);
        signatureHDMApi.handleHttpPost();
        List<byte[]> bytesList = signatureHDMApi.getResult();
        for (byte[] bytes : bytesList) {
            TransactionSignature transactionSignature = new TransactionSignature(ECKey
                    .ECDSASignature.decodeFromDER(bytes), TransactionSignature.SigHash
                    .ALL, false);
            transactionSignatureList.add(transactionSignature);
        }
    } catch (Exception e) {
        if (e instanceof Http400Exception) {
            if (((Http400Exception) e).getErrorCode() == HttpSetting.PasswordWrong) {
                toChangePassword = false;
                final ReentrantLock lock = new ReentrantLock();
                final Condition changePasswordCondition = lock.newCondition();
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        dp.dispose();
                        DialogConfirmTask dialogConfirmTask = new DialogConfirmTask(LocaliserUtils.getString("hdm_reset_server_password_password_wrong_confirm"),
                                new Runnable() {
                                    @Override
                                    public void run() {
                                        toChangePassword = true;
                                        try {
                                            lock.lock();
                                            changePasswordCondition.signal();
                                        } finally {
                                            lock.unlock();
                                        }
                                    }
                                }, new Runnable() {
                            @Override
                            public void run() {
                                toChangePassword = false;
                                try {
                                    lock.lock();
                                    changePasswordCondition.signal();
                                } finally {
                                    lock.unlock();
                                }
                            }
                        });
                        dialogConfirmTask.pack();
                        dialogConfirmTask.setVisible(true);
                    }
                });
                try {
                    lock.lock();
                    changePasswordCondition.awaitUninterruptibly();
                } finally {
                    lock.unlock();
                }
                if (!toChangePassword) {
                    throw new CompleteTransactionRunnable.HDMSignUserCancelExcetion();
                }
                resetServerPasswordUtil.setPassword(password);
                if (!resetServerPasswordUtil.changePassword()) {
                    throw new CompleteTransactionRunnable.HDMSignUserCancelExcetion();
                }
                return getOtherSignature(addressIndex, password, unsignHash, tx);
            } else {
                throw new CompleteTransactionRunnable.HDMServerSignException(LocaliserUtils.getString(
                        "hdm_address_sign_tx_server_error"));
            }
        } else if (e instanceof KeyCrypterException) {
            throw new PasswordException("hdm password decrypting error");
        } else {
            throw new RuntimeException(e);
        }
    }

    return transactionSignatureList;
}
 
Example #23
Source File: SendHDMBitcoinPanel.java    From bither-desktop-java with Apache License 2.0 4 votes vote down vote up
@Override
public List<TransactionSignature> getOtherSignature(int addressIndex,
                                                    CharSequence password,
                                                    List<byte[]> unsignHash, Tx tx) {
    List<TransactionSignature> transactionSignatureList = new
            ArrayList<TransactionSignature>();
    try {
        HDMBId hdmbId = HDMBId.getHDMBidFromDb();
        byte[] decryptedPassword = hdmbId.decryptHDMBIdPassword(password);
        SignatureHDMApi signatureHDMApi = new SignatureHDMApi(HDMBId.getHDMBidFromDb()
                .getAddress(), addressIndex, decryptedPassword, unsignHash);
        signatureHDMApi.handleHttpPost();
        List<byte[]> bytesList = signatureHDMApi.getResult();
        for (byte[] bytes : bytesList) {
            TransactionSignature transactionSignature = new TransactionSignature(ECKey
                    .ECDSASignature.decodeFromDER(bytes), TransactionSignature.SigHash
                    .ALL, false);
            transactionSignatureList.add(transactionSignature);
        }
    } catch (Exception e) {
        if (e instanceof Http400Exception) {
            if (((Http400Exception) e).getErrorCode() == HttpSetting.PasswordWrong) {
                toChangePassword = false;
                final ReentrantLock lock = new ReentrantLock();
                final Condition changePasswordCondition = lock.newCondition();
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        dp.dispose();
                        DialogConfirmTask dialogConfirmTask = new DialogConfirmTask(LocaliserUtils.getString("hdm_reset_server_password_password_wrong_confirm"),
                                new Runnable() {
                                    @Override
                                    public void run() {
                                        toChangePassword = true;
                                        try {
                                            lock.lock();
                                            changePasswordCondition.signal();
                                        } finally {
                                            lock.unlock();
                                        }
                                    }
                                }, new Runnable() {
                            @Override
                            public void run() {
                                toChangePassword = false;
                                try {
                                    lock.lock();
                                    changePasswordCondition.signal();
                                } finally {
                                    lock.unlock();
                                }
                            }
                        });
                        dialogConfirmTask.pack();
                        dialogConfirmTask.setVisible(true);
                    }
                });
                try {
                    lock.lock();
                    changePasswordCondition.awaitUninterruptibly();
                } finally {
                    lock.unlock();
                }
                if (!toChangePassword) {
                    throw new CompleteTransactionRunnable.HDMSignUserCancelExcetion();
                }
                resetServerPasswordUtil.setPassword(password);
                if (!resetServerPasswordUtil.changePassword()) {
                    throw new CompleteTransactionRunnable.HDMSignUserCancelExcetion();
                }
                return getOtherSignature(addressIndex, password, unsignHash, tx);
            } else {
                throw new CompleteTransactionRunnable.HDMServerSignException(LocaliserUtils.getString(
                        "hdm_address_sign_tx_server_error"));
            }
        } else if (e instanceof KeyCrypterException) {
            throw new PasswordException("hdm password decrypting error");
        } else {
            throw new RuntimeException(e);
        }
    }

    return transactionSignatureList;
}
 
Example #24
Source File: HdmSendActivity.java    From bither-android with Apache License 2.0 4 votes vote down vote up
@Override
public List<TransactionSignature> getOtherSignature(int addressIndex,
                                                    CharSequence password,
                                                    List<byte[]> unsignHash, Tx tx) {
    List<TransactionSignature> transactionSignatureList = new
            ArrayList<TransactionSignature>();
    try {
        HDMBId hdmbId = HDMBId.getHDMBidFromDb();
        byte[] decryptedPassword = hdmbId.decryptHDMBIdPassword(password);
        SignatureHDMApi signatureHDMApi = new SignatureHDMApi(HDMBId.getHDMBidFromDb()
                .getAddress(), addressIndex, decryptedPassword, unsignHash);
        signatureHDMApi.handleHttpPost();
        List<byte[]> bytesList = signatureHDMApi.getResult();
        for (byte[] bytes : bytesList) {
            TransactionSignature transactionSignature = new TransactionSignature(ECKey
                    .ECDSASignature.decodeFromDER(bytes), TransactionSignature.SigHash
                    .ALL, false);
            transactionSignatureList.add(transactionSignature);
        }
    } catch (Exception e) {
        if (e instanceof Http400Exception) {
            if (((Http400Exception) e).getErrorCode() == HttpSetting.PasswordWrong) {
                toChangePassword = false;
                final ReentrantLock lock = new ReentrantLock();
                final Condition changePasswordCondition = lock.newCondition();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (dp.isShowing()) {
                            dp.dismiss();
                        }
                        new DialogConfirmTask(HdmSendActivity.this, getString(R.string.hdm_reset_server_password_password_wrong_confirm),
                                new Runnable() {
                                    @Override
                                    public void run() {
                                        toChangePassword = true;
                                        try {
                                            lock.lock();
                                            changePasswordCondition.signal();
                                        } finally {
                                            lock.unlock();
                                        }
                                    }
                                }, new Runnable() {
                            @Override
                            public void run() {
                                toChangePassword = false;
                                try {
                                    lock.lock();
                                    changePasswordCondition.signal();
                                } finally {
                                    lock.unlock();
                                }
                            }
                        }).show();
                    }
                });
                try {
                    lock.lock();
                    changePasswordCondition.awaitUninterruptibly();
                } finally {
                    lock.unlock();
                }
                if (!toChangePassword) {
                    throw new CompleteTransactionRunnable.HDMSignUserCancelExcetion();
                }
                resetServerPasswordUtil.setPassword(password);
                if (!resetServerPasswordUtil.changePassword()) {
                    throw new CompleteTransactionRunnable.HDMSignUserCancelExcetion();
                }
                return getOtherSignature(addressIndex, password, unsignHash, tx);
            } else {
                throw new CompleteTransactionRunnable.HDMServerSignException(R.string
                        .hdm_address_sign_tx_server_error);
            }
        } else if (e instanceof KeyCrypterException) {
            throw new PasswordException("hdm password decrypting error");
        } else {
            throw new RuntimeException(e);
        }
    }

    return transactionSignatureList;
}
 
Example #25
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 #26
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 #27
Source File: ScriptBuilder.java    From bitherj with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a scriptSig that can redeem a pay-to-address output.
 */
public static Script createInputScript(TransactionSignature signature, ECKey pubKey) {
    byte[] pubkeyBytes = pubKey.getPubKey();
    return new ScriptBuilder().data(signature.encodeToBitcoin()).data(pubkeyBytes).build();
}
 
Example #28
Source File: ScriptBuilder.java    From bitherj with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a scriptSig that can redeem a pay-to-pubkey output.
 */
public static Script createInputScript(TransactionSignature signature) {
    return new ScriptBuilder().data(signature.encodeToBitcoin()).build();
}
 
Example #29
Source File: DesktopHDMAddress.java    From bitherj with Apache License 2.0 4 votes vote down vote up
List<TransactionSignature> getOtherSignature(int addressIndex, CharSequence password,
List<byte[]> unsignHash, Tx tx);
 
Example #30
Source File: ScriptBuilder.java    From bitherj with Apache License 2.0 4 votes vote down vote up
/**
 * Create a program that satisfies an OP_CHECKMULTISIG program.
 */
public static Script createMultiSigInputScript(List<TransactionSignature> signatures) {
    return createP2SHMultiSigInputScript(signatures, null);
}