Java Code Examples for net.bither.bitherj.utils.Utils

The following examples show how to use net.bither.bitherj.utils.Utils. These examples are extracted from open source projects. 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 Project: bither-desktop-java   Source File: SelectQRCodePanel.java    License: Apache License 2.0 6 votes vote down vote up
protected void fromFile() {
    clearMessage();
    startFileChooser(new IFileChooser() {
        @Override
        public void selectFile(final File file) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    if (file != null) {
                        String str = QRCodeEncoderDecoder.decode(file);
                        if (Utils.isEmpty(str)) {
                            setMsg(LocaliserUtils.getString("no_format_qr_code"));
                        } else {
                            scanQRCode.handleResult(str, SelectQRCodePanel.this);
                        }

                    }
                }
            });


        }
    });

}
 
Example 2
@Override
protected void validateValues() {
    boolean isValidAmounts = false;
        btcAmount = getAmount(AbstractDb.hdAccountAddressProvider.getUnspentOutputByBlockNo(splitCoin.getForkBlockHeight(),
                AddressManager.getInstance().getHDAccountHot().getHdSeedId()));
    if (btcAmount > 0) {
        isValidAmounts = true;
    }
    toAddress = etAddress.getText().toString().trim();
    boolean isValidAddress = Utils.validSplitBitCoinAddress(toAddress,splitCoin);
    boolean isValidPassword = true;
    if (etPassword.getVisibility() == View.VISIBLE) {
        SecureCharSequence password = new SecureCharSequence(etPassword.getText());
        isValidPassword = Utils.validPassword(password) && password.length() >= 6 &&
                password.length() <= getResources().getInteger(R.integer.password_length_max);
        password.wipe();
    }
    btnSend.setEnabled(isValidAddress && isValidAmounts && isValidPassword);
}
 
Example 3
public void handleResult(String result) {

        if (Utils.isEmpty(result)) {
            setMessage("No QR code");
        } else {
            if (resultValid(result)) {
                QRCodeTransportPage page = QRCodeTransportPage
                        .formatQrCodeTransport(result);
                pages.add(page);
                totalPage = page.getSumPage();
                if (page.getCurrentPage() < totalPage - 1) {
                    String str = String.format(LocaliserUtils.getString("scan_qr_transport_page_label"),
                            pages.size() + 1, totalPage);
                    setMessage(str);
                    //        startScan();
                } else {
                    complete();
                }
            } else {
                shake();
            }

        }

    }
 
Example 4
Source Project: bither-desktop-java   Source File: BackupUtil.java    License: Apache License 2.0 6 votes vote down vote up
private static ECKey getEckeyFormBackupHot(String address, CharSequence password) {
    File file = FileUtil.getBackupFile();
    String str = Utils.readFile(file);
    if (str.contains(address)) {
        String[] backupStrArray = str.split(PrivateKeyUtil.BACKUP_KEY_SPLIT_MUTILKEY_STRING);
        for (String backupStr : backupStrArray) {
            if (backupStr.contains(address)) {
                String[] strArray = QRCodeUtil.splitString(backupStr);
                if (strArray.length > 3) {
                    String keyString = backupStr.substring(strArray[0]
                            .length() + 1);
                    return PrivateKeyUtil.getECKeyFromSingleString(
                            keyString, password);
                }
            }
        }
    }
    return null;
}
 
Example 5
Source Project: bither-desktop-java   Source File: SelectQRCodePanel.java    License: Apache License 2.0 6 votes vote down vote up
protected void fromFile() {
    clearMessage();
    startFileChooser(new IFileChooser() {
        @Override
        public void selectFile(final File file) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    if (file != null) {
                        String str = QRCodeEncoderDecoder.decode(file);
                        if (Utils.isEmpty(str)) {
                            setMsg(LocaliserUtils.getString("no_format_qr_code"));
                        } else {
                            scanQRCode.handleResult(str, SelectQRCodePanel.this);
                        }

                    }
                }
            });


        }
    });

}
 
Example 6
Source Project: bither-desktop-java   Source File: VerifyMessagePanel.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Verify the message text against the address specified and update UI
 */
private void verifyMessage() {
    String addressText = WhitespaceTrimmer.trim(verifyingAddress.getText().trim());
    String messageText = messageTextArea.getText().trim();
    String signatureText = signatureTextArea.getText().trim();
    if (Utils.isEmpty(addressText) || Utils.isEmpty(messageText) || Utils.isEmpty(signatureText)) {
        new MessageDialog(LocaliserUtils.getString("verify_message_signature_verify_failed")).showMsg();
    } else {
        boolean isVerify = PrivateKeyUtil.verifyMessage(addressText, messageText, signatureText);
        if (isVerify) {
            new MessageDialog(LocaliserUtils.getString("verify_message_signature_verify_success")).showMsg();
        } else {
            new MessageDialog(LocaliserUtils.getString("verify_message_signature_verify_failed")).showMsg();
        }
    }
}
 
Example 7
public void handleResult(String result) {

        if (Utils.isEmpty(result)) {
            setMessage("No QR code");
        } else {
            if (resultValid(result)) {
                QRCodeTransportPage page = QRCodeTransportPage
                        .formatQrCodeTransport(result);
                pages.add(page);
                totalPage = page.getSumPage();
                if (page.getCurrentPage() < totalPage - 1) {
                    String str = String.format(LocaliserUtils.getString("scan_qr_transport_page_label"),
                            pages.size() + 1, totalPage);
                    setMessage(str);
                    //        startScan();
                } else {
                    complete();
                }
            } else {
                shake();
            }

        }

    }
 
Example 8
Source Project: bither-android   Source File: DialogImportPrivateKeyText.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void onClick(View v) {
    clickedId = v.getId();
    if (v.getId() == R.id.btn_ok) {
        String s = et.getText().toString();
        tvError.setText(R.string.import_private_key_text_format_error);
        if (Utils.isEmpty(s)) {
            tvError.setVisibility(View.VISIBLE);
            shake();
            return;
        } else if (!Utils.validBitcoinPrivateKey(s)) {
            tvError.setVisibility(View.VISIBLE);
            shake();
            return;
        }

        privateKeyString = et.getText().toString();
        dismiss();

    } else {
        dismiss();
    }
}
 
Example 9
Source Project: bitherj   Source File: ECKeyTest.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public synchronized void nextBytes(byte[] bytes) {
    for (int i = 0; i < bytes.length; i++) {
        bytes[i] = 0;
    }
    if (index == 0) {
        System.out.println("call nextBytes: " + Utils.bytesToHexString(bytes));
    } else {
        SecureRandom secureRandom = new SecureRandom();
        secureRandom.nextBytes(bytes);

        assertTrue("use new bytes: " + Utils.bytesToHexString(bytes), index > 0);
    }
    index++;


}
 
Example 10
Source Project: bither-android   Source File: PeerListFragment.java    License: Apache License 2.0 6 votes vote down vote up
private void refreshPeer() {
    if (peerCacheList != null) {
        Collections.sort(peerCacheList, new Comparator<Peer>() {
            @Override
            public int compare(Peer lhs, Peer rhs) {
                if (lhs.getClientVersion() == 0 && rhs.getClientVersion() > 0) {
                    return 1;
                }
                if (rhs.getClientVersion() == 0 && lhs.getClientVersion() > 0) {
                    return -1;
                }
                return -1 * Long.valueOf(Utils.parseLongFromAddress(
                        lhs.getPeerAddress())).compareTo(
                        Long.valueOf(Utils.parseLongFromAddress(rhs.getPeerAddress())));

            }
        });
        for (final Peer peer : peerCacheList) {
            adapter.add(peer);
        }
    }
}
 
Example 11
@Override
protected void validateValues() {
    boolean isValidAmounts = false;
    btcAmount = getAmount(outs);
    if (btcAmount > 0) {
        isValidAmounts = true;
    }
    toAddress = etAddress.getText().toString().trim();
    boolean isValidAddress = Utils.validBicoinAddress(toAddress);
    boolean isValidPassword = true;
    if (etPassword.getVisibility() == View.VISIBLE) {
        SecureCharSequence password = new SecureCharSequence(etPassword.getText());
        isValidPassword = Utils.validPassword(password) && password.length() >= 6 &&
                password.length() <= getResources().getInteger(R.integer.password_length_max);
        password.wipe();
    }
    btnSend.setEnabled(isValidAddress && isValidAmounts && isValidPassword);
}
 
Example 12
Source Project: bither-desktop-java   Source File: SendBitcoinPanel.java    License: Apache License 2.0 6 votes vote down vote up
protected void onSend() {
    bitcoinAddress = tfAddress.getText().trim();
    if (Utils.validBicoinAddress(bitcoinAddress)) {
        if (Utils.compareString(bitcoinAddress, changeAddress)) {
            new MessageDialog(LocaliserUtils.getString("select_change_address_change_to_same_warn")).showMsg();
            return;
        }
        String amtString = tfAmt.getText().trim();
        long btc = GenericUtils.toNanoCoins(amtString, 0).longValue();
        try {
            SecureCharSequence secureCharSequence = new SecureCharSequence(currentPassword.getPassword());
            CompleteTransactionRunnable completeTransactionRunnable = new CompleteTransactionRunnable(
                    Bither.getActionAddress(), btc, bitcoinAddress, changeAddress, secureCharSequence);
            completeTransactionRunnable.setRunnableListener(completeTransactionListener);
            new Thread(completeTransactionRunnable).start();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
 
Example 13
@Override
protected void sendClicked() {
    final long btc = amountCalculatorLink.getAmount();
    if (btc > 0) {
        btcAmount = btc;
        tx = null;
        String address = etAddress.getText().toString().trim();
        if (Utils.validBicoinAddress(address)) {
            toAddress = address;
            if (!dp.isShowing()) {
                dp.show();
            }
            new Thread() {
                @Override
                public void run() {
                    send();
                }
            }.start();
        } else {
            DropdownMessage.showDropdownMessage(HDAccountMonitoredSendActivity.this, R.string
                    .send_failed);
        }
    }
}
 
Example 14
Source Project: bitherj   Source File: PeerAddress.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void bitcoinSerializeToStream(OutputStream stream) throws IOException {
    if (protocolVersion >= 31402) {
        //TODO this appears to be dynamic because the client only ever sends out it's own address
        //so assumes itself to be up.  For a fuller implementation this needs to be dynamic only if
        //the address refers to this client.
        int secs = (int) (Utils.currentTimeMillis() / 1000);
        uint32ToByteStreamLE(secs, stream);
    }
    uint64ToByteStreamLE(services, stream);  // nServices.
    // Java does not provide any utility to map an IPv4 address into IPv6 space, so we have to do it by hand.
    byte[] ipBytes = addr.getAddress();
    if (ipBytes.length == 4) {
        byte[] v6addr = new byte[16];
        System.arraycopy(ipBytes, 0, v6addr, 12, 4);
        v6addr[10] = (byte) 0xFF;
        v6addr[11] = (byte) 0xFF;
        ipBytes = v6addr;
    }
    stream.write(ipBytes);
    // And write out the port. Unlike the rest of the protocol, address and port is in big endian byte order.
    stream.write((byte) (0xFF & port >> 8));
    stream.write((byte) (0xFF & port));
}
 
Example 15
@Override
public boolean resultValid(String result) {
       boolean repeated = true;
	if (!Utils.compareString(result, lastResult)) {
           repeated = false;
		shake();
	}
	lastResult = result;
	QRCodeTransportPage page = QRCodeTransportPage
			.formatQrCodeTransport(result);
	if (page == null) {
           if (!repeated && Utils.validBicoinAddress(result) && Utils.compareString(tvTitle.getText()
                   .toString(), getString(R.string.scan_for_all_addresses_in_bither_cold_title))) {
               DropdownMessage.showDropdownMessage(this,
                       R.string.add_address_watch_only_scanned_address_warning);
           }
           return false;
       }
       if (page.getCurrentPage() == pages.size()) {
           return true;
       }
	return false;
}
 
Example 16
Source Project: bitherj   Source File: AbstractAddressProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public int addEnterpriseHDKey(String encryptedMnemonicSeed, String encryptHdSeed, String firstAddress, boolean isXrandom, String addressOfPS) {
    IDb writeDb = this.getWriteDb();
    writeDb.beginTransaction();
    int seedId = this.insertEnterpriseHDKeyToDb(writeDb, encryptedMnemonicSeed, encryptHdSeed, firstAddress, isXrandom);
    if (!hasPasswordSeed(writeDb) && !Utils.isEmpty(addressOfPS)) {
        addPasswordSeed(writeDb, new PasswordSeed(addressOfPS, encryptedMnemonicSeed));
    }
    writeDb.endTransaction();
    return seedId;
}
 
Example 17
Source Project: bither-desktop-java   Source File: SendHDMBitcoinPanel.java    License: 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 18
public CompleteTransactionRunnable(Address a, long amount, String toAddress,
                                   String changeAddress, SecureCharSequence password,
                                   HDMAddress.HDMFetchOtherSignatureDelegate
                                           otherSigFetcher1,
                                   HDMAddress.HDMFetchOtherSignatureDelegate
                                           otherSigFetcher2) throws Exception {
    boolean isHDM = otherSigFetcher1 != null || otherSigFetcher2 != null;
    this.amount = amount;
    this.toAddress = toAddress;
    this.password = password;
    sigFetcher1 = otherSigFetcher1;
    sigFetcher2 = otherSigFetcher2;
    if (isHDM) {
        wallet = a;
        toSign = true;
    } else if (password == null || password.length() == 0) {
        wallet = a;
        toSign = false;
    } else {
        if (a.hasPrivKey()) {
            wallet = a;
        } else {
            throw new Exception("address not with private key");
        }
        toSign = true;
    }
    if (!Utils.isEmpty(changeAddress)) {
        this.changeAddress = changeAddress;
    } else {
        this.changeAddress = wallet.getAddress();
    }
}
 
Example 19
Source Project: bither-desktop-java   Source File: SendHDMBitcoinPanel.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onCommitTransactionSuccess(Tx tx) {
    closePanel();
    if (Utils.isEmpty(doateAddress)) {
        new MessageDialog(LocaliserUtils.getString("send_success")).showMsg();
    } else {
        new MessageDialog(LocaliserUtils.getString("donate_thanks")).showMsg();
    }
}
 
Example 20
Source Project: bither-desktop-java   Source File: BackupUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static String[] getBackupKeyStrList(File file) {
    String keyStrs = Utils.readFile(file);
    String[] result = null;
    if (!Utils.isEmpty(keyStrs)) {
        result = keyStrs.split(PrivateKeyUtil.BACKUP_KEY_SPLIT_MUTILKEY_STRING);
    }
    return result;
}
 
Example 21
Source Project: bitherj   Source File: HDMKeychain.java    License: Apache License 2.0 5 votes vote down vote up
public static boolean checkPassword(String keysString, CharSequence password) throws
        MnemonicException.MnemonicLengthException {
    String[] passwordSeeds = QRCodeUtil.splitOfPasswordSeed(keysString);
    String address = Base58.hexToBase58WithAddress(passwordSeeds[0]);
    String encreyptString = Utils.joinString(new String[]{passwordSeeds[1], passwordSeeds[2],
            passwordSeeds[3]}, QRCodeUtil.QR_CODE_SPLIT);
    byte[] seed = new EncryptedData(encreyptString).decrypt(password);
    MnemonicCode mnemonic = MnemonicCode.instance();

    byte[] s = mnemonic.toSeed(mnemonic.toMnemonic(seed), "");

    DeterministicKey master = HDKeyDerivation.createMasterPrivateKey(s);

    DeterministicKey purpose = master.deriveHardened(44);

    DeterministicKey coinType = purpose.deriveHardened(0);

    DeterministicKey account = coinType.deriveHardened(0);

    DeterministicKey external = account.deriveSoftened(0);

    external.clearPrivateKey();

    DeterministicKey key = external.deriveSoftened(0);
    boolean result = Utils.compareString(address, Utils.toAddress(key.getPubKeyHash()));
    key.wipe();

    return result;
}
 
Example 22
Source Project: bither-android   Source File: BCCAssetsDetectHDActivity.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void sendClicked() {
    if (!dp.isShowing()) {
        dp.show();
    }
    BaseRunnable baseRunnable = new BaseRunnable() {
        @Override
        public void run() {
            BccHasAddressApi bccHasAddressApi = new BccHasAddressApi(toAddress, SplitCoin.BCC);
            try {
                bccHasAddressApi.handleHttpGet();
                JSONObject jsonObject = new JSONObject(bccHasAddressApi
                        .getResult());
                boolean result = jsonObject.getInt("result") == 1 ? true : false;
                if (result) {
                    send();
                } else {
                    DropdownMessage.showDropdownMessage(BCCAssetsDetectHDActivity.this,
                            Utils.format(getString(R.string.not_bitpie_split_coin_address), SplitCoin.BCC.getName()));

                    if (dp.isShowing()) {
                        dp.dismiss();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    new Thread(baseRunnable).start();
}
 
Example 23
Source Project: bither-android   Source File: Check.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean equals(Object o) {
	if (o instanceof Check) {
		Check check = (Check) o;
		return Utils.compareString(getTitle(), check.getTitle());
	}
	return false;
}
 
Example 24
Source Project: bither-desktop-java   Source File: UserPreference.java    License: Apache License 2.0 5 votes vote down vote up
private int getLong(String key, int defaultValue) {
    String result = userPreferences.getProperty(key);
    if (Utils.isEmpty(result)) {
        return defaultValue;
    } else {
        if (Utils.isInteger(result)) {
            return Integer.valueOf(result);
        } else {
            return defaultValue;
        }
    }
}
 
Example 25
Source Project: bither-android   Source File: BCCAssetsDetectHotActivity.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void afterTextChanged(Editable s) {
    SecureCharSequence p = new SecureCharSequence(etPassword.getText());
    if (p.length() > 0) {
        if (!Utils.validPassword(p)) {
            etPassword.setText(password);
        }
    }
    p.wipe();
    validateValues();
    password.wipe();
}
 
Example 26
Source Project: bither-android   Source File: SignMessageActivity.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onClick(View v) {
    final String input = etInput.getText().toString().trim();
    if (Utils.isEmpty(input)) {
        return;
    }
    new DialogPassword(SignMessageActivity.this, SignMessageActivity.this).show();
}
 
Example 27
Source Project: bither-desktop-java   Source File: WalletUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static Address findPrivateKey(String address) {
    for (Address bitherAddressWithPrivateKey : AddressManager.getInstance().getPrivKeyAddresses()) {

        if (Utils.compareString(address,
                bitherAddressWithPrivateKey.getAddress())) {
            return bitherAddressWithPrivateKey;
        }
    }
    return null;
}
 
Example 28
Source Project: bither-android   Source File: SendActivity.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void afterTextChanged(Editable s) {
    SecureCharSequence p = new SecureCharSequence(etPassword.getText());
    if (p.length() > 0) {
        if (!Utils.validPassword(p)) {
            etPassword.setText(password);
        }
    }
    p.wipe();
    validateValues();
    password.wipe();
}
 
Example 29
@Override
public void onAddressInfoChanged(String address) {
    if (this.address != null) {
        if (Utils.compareString(address, this.address.getAddress(AppSharedPreference.getInstance().isSegwitAddressType())) || (this.address
                .isHDAccount() && this.address.hasPrivKey() && Utils.compareString(address,
                HDAccount.HDAccountPlaceHolder)) || (this.address.isHDAccount() && !this
                .address.hasPrivKey() && Utils.compareString(address, HDAccount
                .HDAccountMonitoredPlaceHolder))) {
            showAddressInfo();
        }
    }
}
 
Example 30
@Override
protected void sendClicked() {
    if (!dp.isShowing()) {
        dp.show();
    }
    BaseRunnable baseRunnable = new BaseRunnable() {
        @Override
        public void run() {
            BccHasAddressApi bccHasAddressApi = new BccHasAddressApi(toAddress, SplitCoin.BCC);
            try {
                bccHasAddressApi.handleHttpGet();
                JSONObject jsonObject = new JSONObject(bccHasAddressApi
                        .getResult());
                boolean result = jsonObject.getInt("result") == 1 ? true : false;
                if (result) {
                    if (!dp.isShowing()) {
                        dp.show();
                    }
                    send();
                } else {
                    DropdownMessage.showDropdownMessage(BCCAssetsHDAccountMonitoredActivity.this,
                            Utils.format(getString(R.string.not_bitpie_split_coin_address), SplitCoin.BCC.getName()));
                    if (dp.isShowing()) {
                        dp.dismiss();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    new Thread(baseRunnable).start();
}