private void prepareRestoreWalletDialog(final Dialog dialog) { final AlertDialog alertDialog = (AlertDialog) dialog; final View replaceWarningView = alertDialog.findViewById(R.id.restore_wallet_from_content_dialog_replace_warning); final boolean hasCoins = wallet.getBalance(BalanceType.ESTIMATED).signum() > 0; replaceWarningView.setVisibility(hasCoins ? View.VISIBLE : View.GONE); final EditText passwordView = (EditText) alertDialog.findViewById(R.id.import_keys_from_content_dialog_password); passwordView.setText(null); final ImportDialogButtonEnablerListener dialogButtonEnabler = new ImportDialogButtonEnablerListener(passwordView, alertDialog) { @Override protected boolean hasFile() { return true; } }; passwordView.addTextChangedListener(dialogButtonEnabler); final CheckBox showView = (CheckBox) alertDialog.findViewById(R.id.import_keys_from_content_dialog_show); showView.setOnCheckedChangeListener(new ShowPasswordCheckListener(passwordView)); }
private void listenForCoinsAndRetry(final Coin value, final Address toAddress){ // Wait until the we have enough balance and display a notice. ListenableFuture<Coin> balanceFuture = SPECIEBOX.wallet().getBalanceFuture(value, BalanceType.AVAILABLE); FutureCallback<Coin> retry = new FutureCallback<Coin>() { public void onSuccess(Coin balance) { System.out.println("coins arrived and the wallet now has enough balance"); try { Wallet.SendResult result = SPECIEBOX.wallet().sendCoins(SPECIEBOX.peerGroup(), toAddress, value); System.out.println("Info: COINS RESENT. Transaction hash: " + result.tx.getHashAsString()); } catch (InsufficientMoneyException e) { e.printStackTrace(); System.out.println("Still not enough coins in your wallet, missing " + e.missing.getValue() + " satoshis."); } } public void onFailure(Throwable t) { System.out.println("something went wrong"); } }; Futures.addCallback(balanceFuture, retry); }
private void handleEmpty() { final Coin available = wallet.getBalance(BalanceType.AVAILABLE); btcAmountView.setAmount(available, true); updateView(); handler.post(dryrunRunnable); }
private Wallet saveCentralWallet(final Wallet wallet, final org.bitcoinj.core.Wallet blockchainWallet) throws IOException { if (wallet == null) { return null; } final DeterministicKey freshKey = blockchainWallet.freshReceiveKey(); final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); blockchainWallet.saveToFileStream(outputStream); final String walletHash = freshKey.toAddress(this.params).toString(); final String privatekey = freshKey.getPrivateKeyEncoded(this.params) .toString(); final String content = DatatypeConverter .printBase64Binary(outputStream.toByteArray()); final BigDecimal balance = new BigDecimal( blockchainWallet.getBalance(BalanceType.ESTIMATED).value) .divide(Constants.MILLI_TO_SATOSHI); final BigDecimal availableBalance = new BigDecimal( blockchainWallet.getBalance(BalanceType.AVAILABLE).value) .divide(Constants.MILLI_TO_SATOSHI); ; final Wallet central = wallet.toBuilder().content(content) .walletHash(walletHash).privateKey(privatekey) .type(Wallet.Type.EXTERNAL).status(Wallet.Status.ACTIVE) .name(this.settings.getWalletName()) .description(FilenameUtils.concat(this.settings.getWalletFolder(), this.settings.getWalletName())) .balance(balance).availableBalance(availableBalance).build(); this.saveToFile(blockchainWallet); return this.walletService.create(central); }
@Test public void testReceiveCoinbaseTransaction() throws Exception { // Block 169482 (hash 0000000000000756935f1ee9d5987857b604046f846d3df56d024cdb5f368665) // contains coinbase transactions that are mining pool shares. // The private key MINERS_KEY is used to check transactions are received by a wallet correctly. byte[] blockAsBytes = getBytes(getClass().getResourceAsStream("block169482.dat")); // Create block 169482. Block block = new Block(params, blockAsBytes); // Check block. assertNotNull(block); block.verify(); assertEquals(BLOCK_NONCE, block.getNonce()); StoredBlock storedBlock = new StoredBlock(block, BigInteger.ONE, BLOCK_OF_INTEREST); // Nonsense work - not used in test. // Create a wallet contain the miner's key that receives a spend from a coinbase. ECKey miningKey = (new DumpedPrivateKey(params, MINING_PRIVATE_KEY)).getKey(); assertNotNull(miningKey); Wallet wallet = new Wallet(params); wallet.importKey(miningKey); // Initial balance should be zero by construction. assertEquals(Coin.ZERO, wallet.getBalance()); // Give the wallet the first transaction in the block - this is the coinbase tx. List<Transaction> transactions = block.getTransactions(); assertNotNull(transactions); wallet.receiveFromBlock(transactions.get(0), storedBlock, NewBlockType.BEST_CHAIN, 0); // Coinbase transaction should have been received successfully but be unavailable to spend (too young). assertEquals(BALANCE_AFTER_BLOCK, wallet.getBalance(BalanceType.ESTIMATED)); assertEquals(Coin.ZERO, wallet.getBalance(BalanceType.AVAILABLE)); }
private void prepareRestoreWalletDialog(final Dialog dialog) { final AlertDialog alertDialog = (AlertDialog) dialog; final List<File> files = new LinkedList<File>(); // external storage if (Constants.Files.EXTERNAL_WALLET_BACKUP_DIR.exists() && Constants.Files.EXTERNAL_WALLET_BACKUP_DIR.isDirectory()) for (final File file : Constants.Files.EXTERNAL_WALLET_BACKUP_DIR.listFiles()) if (Crypto.OPENSSL_FILE_FILTER.accept(file)) files.add(file); // internal storage for (final String filename : fileList()) if (filename.startsWith(Constants.Files.WALLET_KEY_BACKUP_PROTOBUF + '.')) files.add(new File(getFilesDir(), filename)); // sort Collections.sort(files, new Comparator<File>() { @Override public int compare(final File lhs, final File rhs) { return lhs.getName().compareToIgnoreCase(rhs.getName()); } }); final View replaceWarningView = alertDialog.findViewById(R.id.restore_wallet_from_storage_dialog_replace_warning); final boolean hasCoins = wallet.getBalance(BalanceType.ESTIMATED).signum() > 0; replaceWarningView.setVisibility(hasCoins ? View.VISIBLE : View.GONE); final Spinner fileView = (Spinner) alertDialog.findViewById(R.id.import_keys_from_storage_file); final FileAdapter adapter = (FileAdapter) fileView.getAdapter(); adapter.setFiles(files); fileView.setEnabled(!adapter.isEmpty()); final EditText passwordView = (EditText) alertDialog.findViewById(R.id.import_keys_from_storage_password); passwordView.setText(null); final ImportDialogButtonEnablerListener dialogButtonEnabler = new ImportDialogButtonEnablerListener(passwordView, alertDialog) { @Override protected boolean hasFile() { return fileView.getSelectedItem() != null; } @Override protected boolean needsPassword() { final File selectedFile = (File) fileView.getSelectedItem(); return selectedFile != null ? Crypto.OPENSSL_FILE_FILTER.accept(selectedFile) : false; } }; passwordView.addTextChangedListener(dialogButtonEnabler); fileView.setOnItemSelectedListener(dialogButtonEnabler); final CheckBox showView = (CheckBox) alertDialog.findViewById(R.id.import_keys_from_storage_show); showView.setOnCheckedChangeListener(new ShowPasswordCheckListener(passwordView)); }
@Override public Coin loadInBackground() { return wallet.getBalance(BalanceType.ESTIMATED); }
public static void main(String[] args) throws Exception { // We use the WalletAppKit that handles all the boilerplate for us. Have a look at the Kit.java example for more details. NetworkParameters params = TestNet3Params.get(); WalletAppKit kit = new WalletAppKit(params, new File("."), "sendrequest-example"); kit.startAsync(); kit.awaitRunning(); System.out.println("Send money to: " + kit.wallet().currentReceiveAddress().toString()); // How much coins do we want to send? // The Coin class represents a monetary Bitcoin value. // We use the parseCoin function to simply get a Coin instance from a simple String. Coin value = Coin.parseCoin("0.09"); // To which address you want to send the coins? // The Address class represents a Bitcoin address. Address to = new Address(params, "mupBAFeT63hXfeeT4rnAUcpKHDkz1n4fdw"); // There are different ways to create and publish a SendRequest. This is probably the easiest one. // Have a look at the code of the SendRequest class to see what's happening and what other options you have: https://bitcoinj.github.io/javadoc/0.11/com/google/bitcoin/core/Wallet.SendRequest.html // // Please note that this might raise a InsufficientMoneyException if your wallet has not enough coins to spend. // When using the testnet you can use a faucet (like the http://faucet.xeno-genesis.com/) to get testnet coins. // In this example we catch the InsufficientMoneyException and register a BalanceFuture callback that runs once the wallet has enough balance. try { Wallet.SendResult result = kit.wallet().sendCoins(kit.peerGroup(), to, value); System.out.println("coins sent. transaction hash: " + result.tx.getHashAsString()); // you can use a block explorer like https://www.biteasy.com/ to inspect the transaction with the printed transaction hash. } catch (InsufficientMoneyException e) { System.out.println("Not enough coins in your wallet. Missing " + e.missing.getValue() + " satoshis are missing (including fees)"); System.out.println("Send money to: " + kit.wallet().currentReceiveAddress().toString()); // Bitcoinj allows you to define a BalanceFuture to execute a callback once your wallet has a certain balance. // Here we wait until the we have enough balance and display a notice. // Bitcoinj is using the ListenableFutures of the Guava library. Have a look here for more information: https://code.google.com/p/guava-libraries/wiki/ListenableFutureExplained ListenableFuture<Coin> balanceFuture = kit.wallet().getBalanceFuture(value, BalanceType.AVAILABLE); FutureCallback<Coin> callback = new FutureCallback<Coin>() { public void onSuccess(Coin balance) { System.out.println("coins arrived and the wallet now has enough balance"); } public void onFailure(Throwable t) { System.out.println("something went wrong"); } }; Futures.addCallback(balanceFuture, callback); } // shutting down //kit.stopAsync(); //kit.awaitTerminated(); }