/** * */ @Override public String getBalanceFriendlyStr() { //send test coins back to : mwCwTceJvYV27KXBc3NJZys6CjsgsoeHmf Coin balance = _coin.getWalletManager().wallet().getBalance(Wallet.BalanceType.ESTIMATED); String balanceStatus = "Friendly balance : " + balance.toFriendlyString() + " Estimated : " + _coin.getWalletManager().wallet().getBalance(Wallet.BalanceType.ESTIMATED) + " Available : " + _coin.getWalletManager().wallet().getBalance(Wallet.BalanceType.AVAILABLE) + " Available Spendable : " + _coin.getWalletManager().wallet().getBalance(Wallet.BalanceType.AVAILABLE_SPENDABLE) + " Estimated Spendable : " + _coin.getWalletManager().wallet().getBalance(Wallet.BalanceType.ESTIMATED_SPENDABLE); return balance.toPlainString(); }
@Nullable public Coin getAmount() { if (exchangeDirection) { return (Coin) btcAmountView.getAmount(); } else if (exchangeRate != null) { final Fiat localAmount = (Fiat) localAmountView.getAmount(); if (localAmount == null) return null; try { final Coin btcAmount = exchangeRate.fiatToCoin(localAmount); if (((Coin) btcAmount).isGreaterThan(Constants.NETWORK_PARAMETERS.getMaxMoney())) throw new ArithmeticException(); return btcAmount; } catch (ArithmeticException x) { return null; } } else { return null; } }
/** * <p>Returns a future that will complete when the balance of the given type has becom equal or larger to the given * value. If the wallet already has a large enough balance the future is returned in a pre-completed state. Note * that this method is not blocking, if you want to actually wait immediately, you have to call .get() on * the result.</p> * * <p>Also note that by the time the future completes, the wallet may have changed yet again if something else * is going on in parallel, so you should treat the returned balance as advisory and be prepared for sending * money to fail! Finally please be aware that any listeners on the future will run either on the calling thread * if it completes immediately, or eventually on a background thread if the balance is not yet at the right * level. If you do something that means you know the balance should be sufficient to trigger the future, * you can use {@link org.bitcoinj.utils.Threading#waitForUserCode()} to block until the future had a * chance to be updated.</p> */ public ListenableFuture<Coin> getBalanceFuture(final Coin value, final BalanceType type) { lock.lock(); try { final SettableFuture<Coin> future = SettableFuture.create(); final Coin current = getBalance(type); if (current.compareTo(value) >= 0) { // Already have enough. future.set(current); } else { // Will be checked later in checkBalanceFutures. We don't just add an event listener for ourselves // here so that running getBalanceFuture().get() in the user code thread works - generally we must // avoid giving the user back futures that require the user code thread to be free. BalanceFutureRequest req = new BalanceFutureRequest(); req.future = future; req.value = value; req.type = type; balanceFutureRequests.add(req); } return future; } finally { lock.unlock(); } }
@SuppressWarnings("FieldAccessNotGuarded") private void checkBalanceFuturesLocked(@Nullable Coin avail) { checkState(lock.isHeldByCurrentThread()); final ListIterator<BalanceFutureRequest> it = balanceFutureRequests.listIterator(); while (it.hasNext()) { final BalanceFutureRequest req = it.next(); Coin val = getBalance(req.type); // This could be slow for lots of futures. if (val.compareTo(req.value) < 0) continue; // Found one that's finished. it.remove(); final Coin v = val; // Don't run any user-provided future listeners with our lock held. Threading.USER_THREAD.execute(new Runnable() { @Override public void run() { req.future.set(v); } }); } }
/** * Returns the amount of bitcoin ever received via output. <b>This is not the balance!</b> If an output spends from a * transaction whose inputs are also to our wallet, the input amounts are deducted from the outputs contribution, with a minimum of zero * contribution. The idea behind this is we avoid double counting money sent to us. * @return the total amount of satoshis received, regardless of whether it was spent or not. */ public Coin getTotalReceived() { Coin total = Coin.ZERO; // Include outputs to us if they were not just change outputs, ie the inputs to us summed to less // than the outputs to us. for (Transaction tx: transactions.values()) { Coin txTotal = Coin.ZERO; for (TransactionOutput output : tx.getOutputs()) { if (output.isMine(this)) { txTotal = txTotal.add(output.getValue()); } } for (TransactionInput in : tx.getInputs()) { TransactionOutput prevOut = in.getConnectedOutput(); if (prevOut != null && prevOut.isMine(this)) { txTotal = txTotal.subtract(prevOut.getValue()); } } if (txTotal.isPositive()) { total = total.add(txTotal); } } return total; }
@Override public CoinSelection select(Coin target, List<TransactionOutput> candidates) { ArrayList<TransactionOutput> selected = new ArrayList<>(); // Sort the inputs by age*value so we get the highest "coindays" spent. // TODO: Consider changing the wallets internal format to track just outputs and keep them ordered. ArrayList<TransactionOutput> sortedOutputs = new ArrayList<>(candidates); // When calculating the wallet balance, we may be asked to select all possible coins, if so, avoid sorting // them in order to improve performance. // TODO: Take in network parameters when instanatiated, and then test against the current network. Or just have a boolean parameter for "give me everything" if (!target.equals(NetworkParameters.MAX_MONEY)) { sortOutputs(sortedOutputs); } // Now iterate over the sorted outputs until we have got as close to the target as possible or a little // bit over (excessive value will be change). long total = 0; for (TransactionOutput output : sortedOutputs) { if (total >= target.value) break; // Only pick chain-included transactions, or transactions that are ours and pending. if (!shouldSelect(output.getParentTransaction())) continue; selected.add(output); total += output.getValue().value; } // Total may be lower than target here, if the given candidates were insufficient to create to requested // transaction. return new CoinSelection(Coin.valueOf(total), selected); }
@VisibleForTesting static void sortOutputs(ArrayList<TransactionOutput> outputs) { Collections.sort(outputs, new Comparator<TransactionOutput>() { @Override public int compare(TransactionOutput a, TransactionOutput b) { int depth1 = a.getParentTransactionDepthInBlocks(); int depth2 = b.getParentTransactionDepthInBlocks(); Coin aValue = a.getValue(); Coin bValue = b.getValue(); BigInteger aCoinDepth = BigInteger.valueOf(aValue.value).multiply(BigInteger.valueOf(depth1)); BigInteger bCoinDepth = BigInteger.valueOf(bValue.value).multiply(BigInteger.valueOf(depth2)); int c1 = bCoinDepth.compareTo(aCoinDepth); if (c1 != 0) return c1; // The "coin*days" destroyed are equal, sort by value alone to get the lowest transaction size. int c2 = bValue.compareTo(aValue); if (c2 != 0) return c2; // They are entirely equivalent (possibly pending) so sort by hash to ensure a total ordering. BigInteger aHash = a.getParentTransactionHash().toBigInteger(); BigInteger bHash = b.getParentTransactionHash().toBigInteger(); return aHash.compareTo(bHash); } }); }
public static void updateWidgets(final Context context, final Wallet wallet) { final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context); final ComponentName providerName = new ComponentName(context, WalletBalanceWidgetProvider.class); try { final int[] appWidgetIds = appWidgetManager.getAppWidgetIds(providerName); if (appWidgetIds.length > 0) { final Coin balance = wallet.getBalance(BalanceType.ESTIMATED); WalletBalanceWidgetProvider.updateWidgets(context, appWidgetManager, appWidgetIds, balance); } } catch (final RuntimeException x) // system server dead? { log.warn("cannot update app widgets", x); } }
/** Updates the BTC and USD balance. * @param availableBalance Available balance to show. */ public void updateBalance(Coin availableBalance) { ConversionRate.update(); // Get most recent exchange rate. lblCurrentBalanceAmount.setText(availableBalance.toFriendlyString()); lblBitcoinValueAmount.setText("$" + ConversionRate.convert(availableBalance).setScale(2, RoundingMode.HALF_UP) + (Utils.isTestNetwork() ? " (TESTNET)" : "")); }
private void handleEmpty() { final Coin available = wallet.getBalance(BalanceType.AVAILABLE); amountCalculatorLink.setBtcAmount(available); updateView(); handler.post(dryrunRunnable); }
/** Sends Bitcoin to the specified bitcoin address. * @author Francis Fasola * @param address String representation of the public address. * @param amount The amount of Bitcoin to send. * @throws InsufficientMoneyException Not enough money. * @throws ExecutionException Error during execution. * @throws InterruptedException Error during execution. */ @SuppressWarnings("deprecation") public void sendBitcoin(String address, String amount) throws InsufficientMoneyException, ExecutionException, InterruptedException { Address destinationAddress = Address.fromBase58(params, address); SendRequest request = SendRequest.to(destinationAddress, Coin.parseCoin(amount)); SendResult result = wallet.sendCoins(request); result.broadcastComplete.addListener(() -> { System.out.println("Coins were sent. Transaction hash: " + result.tx.getHashAsString()); }, MoreExecutors.sameThreadExecutor()); }
/** When coins are received this will report information; used as an event listener. * @author Francis Fasola * @param wallet The wallet receiving the coins. * @param tx The transaction sending the coins. * @param prevBalance The previous balance of the wallet. * @param newBalance The new balance of the wallet. */ private void coinsRecevied(Wallet wallet, Transaction tx, Coin prevBalance, Coin newBalance) { Coin value = tx.getValueSentToMe(wallet); JOptionPane.showMessageDialog(null, "Coins receive.\nHASH: " + tx.getHashAsString() + "\nRECEIVED: " + tx.getValue(wallet) + "\nPREVIOUS BALANCE: " + prevBalance.value + " NEW BALANCE: " + newBalance.value + "VERSION: " + tx.getVersion() + "Received transaction for " + value.toFriendlyString() + ": " + tx); }
@Override public CoinSelection select(Coin coin, List<TransactionOutput> list) { ArrayList<TransactionOutput> selected = new ArrayList<>(); long total = 0; for (TransactionOutput txOut : list) { if (TransactionConfidence.ConfidenceType.BUILDING == txOut.getParentTransaction().getConfidence().getConfidenceType()) { total += txOut.getValue().value; selected.add(txOut); } } return new CoinSelection(Coin.valueOf(total), selected); }
/** * * @param valueMessage * @return */ @Override public SpentValueMessage applyTxFee(SpentValueMessage valueMessage) { Coin amountCoin = Coin.parseCoin(valueMessage.getAmount()); Address addr = Address.fromBase58(_coin.getWalletManager().wallet().getParams(), valueMessage.getAddress()); SendRequest sendRequest = SendRequest.to(addr, amountCoin); Coin txValue = CalculateFeeTxSizeBytes(sendRequest.tx, sendRequest.feePerKb.getValue()); valueMessage.setTxFee(txValue.toPlainString()); String amountStr = amountCoin.toPlainString(); valueMessage.setAmount(amountStr); return valueMessage; }
/** * * @see { https://bitcoin.stackexchange.com/questions/1195/how-to-calculate-transaction-size-before-sending } * * @param tx * @return */ public static Coin CalculateFeeTxSizeBytes(Transaction tx, long feePerKb) { int nrInputs = tx.getInputs().size(); int nrOutputs = tx.getOutputs().size(); long txSizeKb = nrInputs * 148 + nrOutputs * 34 + 10 +- nrInputs; float feeV = feePerKb / (float) txSizeKb; Coin txValue = Coin.valueOf((long) (feeV * 10)); return txValue; }
/** * */ @Override public List<CoinTransaction> getTransactionList() { List<CoinTransaction> transactions = new ArrayList<>(); Set<Transaction> txs = _coin.getWalletManager().wallet().getTransactions(true); for (Transaction tx : txs) { Coin amount = tx.getValue(_coin.getWalletManager().wallet()); String hash = tx.getHash().toString(); String amountStr = amount.toPlainString(); String fee = ""; String confirmationStr = "CONFIRMED"; if (tx.getFee() != null) { fee = tx.getFee().toPlainString(); } TransactionConfidence confidence = tx.getConfidence(); if (confidence.getDepthInBlocks() < 6) { confirmationStr = confidence.getDepthInBlocks() + " CONFIRMATIONS"; } TransactionConfidence.ConfidenceType cType = confidence.getConfidenceType(); CoinTransaction coinTransaction = new CoinTransaction(fee, hash, amountStr, confirmationStr, tx.getUpdateTime()); transactions.add(coinTransaction); } return transactions; }
/** * * @param callbacks */ @Override public void execute(final CoinActionCallback<CurrencyCoin>... callbacks) { this._callbacks = callbacks; this._bitcoin.getWalletManager().wallet().addCoinsSentEventListener(this); Coin balance = _bitcoin.getWalletManager().wallet().getBalance(); Coin amountCoin = Coin.parseCoin(_amount); Address addr = Address.fromBase58(_bitcoin.getWalletManager().wallet().getParams(), _address); SendRequest sendRequest = SendRequest.to(addr, amountCoin); Coin feeCoin = BitcoinManager.CalculateFeeTxSizeBytes(sendRequest.tx, sendRequest.feePerKb.getValue()); long balValue = balance.getValue(); long amountValue = amountCoin.getValue(); long txFeeValue = feeCoin.getValue(); if (amountValue + txFeeValue > balValue) { amountCoin = Coin.valueOf(balValue - txFeeValue); sendRequest = SendRequest.to(addr, amountCoin); } try { _bitcoin.getWalletManager().wallet().sendCoins(sendRequest); } catch (InsufficientMoneyException e) { for (CoinActionCallback<CurrencyCoin> callback : _callbacks) { callback.onError(_bitcoin); } e.printStackTrace(); } }
public void sendBroadcastAnnouncement(BroadcastAnnouncement ba, File f, ProofMessage pm, int lockTime) throws InsufficientMoneyException { //build transaction Transaction tx = new Transaction(params); Script s = ba.buildScript(); System.out.println("Script size is " + s.SIG_SIZE); //System.out.println(s.getScriptType()); ECKey psnymKey = new ECKey(); long unixTime = System.currentTimeMillis() / 1000L; //TODO use bitcoin nets median time tx.setLockTime(CLTVScriptPair.currentBitcoinBIP113Time(bc)-1); CLTVScriptPair sp = new CLTVScriptPair(psnymKey, CLTVScriptPair.currentBitcoinBIP113Time(bc)+lockTime); w.importKey(psnymKey); tx.addOutput(new TransactionOutput(params, tx, pm.getLastTransactionOutput().getValue().subtract(estimateBroadcastFee()), sp.getPubKeyScript().getProgram())); tx.addOutput(Coin.ZERO, s); tx.addInput(pm.getLastTransactionOutput()); tx.getInput(0).setSequenceNumber(3); //the concrete value doesn't matter, this is just for cltv tx.getInput(0).setScriptSig(pm.getScriptPair().calculateSigScript(tx, 0, w)); try { w.commitTx(tx); w.saveToFile(f); } catch (IOException e1) { e1.printStackTrace(); } TransactionBroadcast broadcast = pg.broadcastTransaction(tx); pm.addTransaction(tx, 0, sp); pm.writeToFile(); System.out.println("save broadcast announcement to file"); }
private Coin computeValueOfNewPsyNyms(Coin ownValue, Coin mixpartnerVal, Coin feePerKb) { assert(ownValue != null && mixpartnerVal != null && feePerKb != null); //statically computed, is ok as we know the size of the mixTx approximately //estimated by the following formula in*180 + out*34 + 10 + in, where in and out are the number of inputs and outputs double sizeInKBytes = ((double) (2*180+2*34 + 10 + 2))/1000.0; Coin fee = Coin.valueOf((int) (feePerKb.getValue() * sizeInKBytes)); return ((ownValue.add(mixpartnerVal)).minus(fee)).div(2); }
public void setBtcAmount(final Coin amount) { final Listener listener = this.listener; this.listener = null; btcAmountView.setAmount(amount, true); this.listener = listener; }
/** Construct exchange rate. This amount of coin is worth that amount of fiat. */ public ExchangeRate(Coin coin, Fiat fiat) { checkArgument(coin.isPositive()); checkArgument(fiat.isPositive()); checkArgument(fiat.currencyCode != null, "currency code required"); this.coin = coin; this.fiat = fiat; }
@Override public void onLoadFinished(final Loader<Coin> loader, final Coin balance) { WalletBalanceFragment.this.balance = balance; activity.invalidateOptionsMenu(); updateView(); }
protected void queueOnCoinsReceived(final Transaction tx, final Coin balance, final Coin newBalance) { checkState(lock.isHeldByCurrentThread()); for (final ListenerRegistration<WalletCoinsReceivedEventListener> registration : coinsReceivedListeners) { registration.executor.execute(new Runnable() { @Override public void run() { registration.listener.onCoinsReceived(Wallet.this, tx, balance, newBalance); } }); } }
private byte[] determinePaymentRequest(final boolean includeBluetoothMac) { final Coin amount = amountCalculatorLink.getAmount(); final String paymentUrl = includeBluetoothMac && bluetoothMac != null ? "bt:" + bluetoothMac : null; return PaymentProtocol.createPaymentRequest(Constants.NETWORK_PARAMETERS, amount, address, config.getOwnName(), paymentUrl, null).build().toByteArray(); }
/** * Returns the balance that would be considered spendable by the given coin selector, including watched outputs * (i.e. balance includes outputs we don't have the private keys for). Just asks it to select as many coins as * possible and returns the total. */ public Coin getBalance(CoinSelector selector) { lock.lock(); try { checkNotNull(selector); List<TransactionOutput> candidates = calculateAllSpendCandidates(true, false); CoinSelection selection = selector.select(params.getMaxMoney(), candidates); return selection.valueGathered; } finally { lock.unlock(); } }
/** * Returns the amount of bitcoin ever sent via output. If an output is sent to our own wallet, because of change or * rotating keys or whatever, we do not count it. If the wallet was * involved in a shared transaction, i.e. there is some input to the transaction that we don't have the key for, then * we multiply the sum of the output values by the proportion of satoshi coming in to our inputs. Essentially we treat * inputs as pooling into the transaction, becoming fungible and being equally distributed to all outputs. * @return the total amount of satoshis sent by us */ public Coin getTotalSent() { Coin total = Coin.ZERO; for (Transaction tx: transactions.values()) { // Count spent outputs to only if they were not to us. This means we don't count change outputs. Coin txOutputTotal = Coin.ZERO; for (TransactionOutput out : tx.getOutputs()) { if (out.isMine(this) == false) { txOutputTotal = txOutputTotal.add(out.getValue()); } } // Count the input values to us Coin txOwnedInputsTotal = Coin.ZERO; for (TransactionInput in : tx.getInputs()) { TransactionOutput prevOut = in.getConnectedOutput(); if (prevOut != null && prevOut.isMine(this)) { txOwnedInputsTotal = txOwnedInputsTotal.add(prevOut.getValue()); } } // If there is an input that isn't from us, i.e. this is a shared transaction Coin txInputsTotal = tx.getInputSum(); if (txOwnedInputsTotal != txInputsTotal) { // multiply our output total by the appropriate proportion to account for the inputs that we don't own BigInteger txOutputTotalNum = new BigInteger(txOutputTotal.toString()); txOutputTotalNum = txOutputTotalNum.multiply(new BigInteger(txOwnedInputsTotal.toString())); txOutputTotalNum = txOutputTotalNum.divide(new BigInteger(txInputsTotal.toString())); txOutputTotal = Coin.valueOf(txOutputTotalNum.longValue()); } total = total.add(txOutputTotal); } return total; }
/** Reduce the value of the first output of a transaction to pay the given feePerKb as appropriate for its size. */ private boolean adjustOutputDownwardsForFee(Transaction tx, CoinSelection coinSelection, Coin feePerKb, boolean ensureMinRequiredFee) { final int size = tx.unsafeBitcoinSerialize().length + estimateBytesForSigning(coinSelection); Coin fee = feePerKb.multiply(size).divide(1000); if (ensureMinRequiredFee && fee.compareTo(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE) < 0) fee = Transaction.REFERENCE_DEFAULT_MIN_TX_FEE; TransactionOutput output = tx.getOutput(0); output.setValue(output.getValue().subtract(fee)); return !output.isDust(); }
/** * <p>Creates a new SendRequest to the given address for the given value.</p> * * <p>Be very careful when value is smaller than {@link Transaction#MIN_NONDUST_OUTPUT} as the transaction will * likely be rejected by the network in this case.</p> */ public static SendRequest to(Address destination, Coin value) { SendRequest req = new SendRequest(); final NetworkParameters parameters = destination.getParameters(); checkNotNull(parameters, "Address is for an unknown network"); req.tx = new Transaction(parameters); req.tx.addOutput(value, destination); return req; }
public static SendRequest emptyWallet(Address destination) { SendRequest req = new SendRequest(); final NetworkParameters parameters = destination.getParameters(); checkNotNull(parameters, "Address is for an unknown network"); req.tx = new Transaction(parameters); req.tx.addOutput(Coin.ZERO, destination); req.emptyWallet = true; return req; }
private static @Nullable TransactionOutput findSpendableOutput(final Wallet wallet, final Transaction transaction, final Coin minimumOutputValue) { for (final TransactionOutput output : transaction.getOutputs()) { if (output.isMine(wallet) && output.isAvailableForSpending() && output.getValue().isGreaterThan(minimumOutputValue)) return output; } return null; }
private TransactionCacheEntry(final Coin value, final boolean sent, final boolean self, final boolean showFee, final @Nullable Address address, final @Nullable String addressLabel) { this.value = value; this.sent = sent; this.self = self; this.showFee = showFee; this.address = address; this.addressLabel = addressLabel; }
public Coin getBtcBase() { final int shift = getBtcShift(); if (shift == 0) return Coin.COIN; else if (shift == 3) return Coin.MILLICOIN; else if (shift == 6) return Coin.MICROCOIN; else throw new IllegalStateException("cannot handle shift: " + shift); }
public ExchangeRate getCachedExchangeRate() { if (prefs.contains(PREFS_KEY_CACHED_EXCHANGE_CURRENCY) && prefs.contains(PREFS_KEY_CACHED_EXCHANGE_RATE_COIN) && prefs.contains(PREFS_KEY_CACHED_EXCHANGE_RATE_FIAT)) { final String cachedExchangeCurrency = prefs.getString(PREFS_KEY_CACHED_EXCHANGE_CURRENCY, null); final Coin cachedExchangeRateCoin = Coin.valueOf(prefs.getLong(PREFS_KEY_CACHED_EXCHANGE_RATE_COIN, 0)); final Fiat cachedExchangeRateFiat = Fiat.valueOf(cachedExchangeCurrency, prefs.getLong(PREFS_KEY_CACHED_EXCHANGE_RATE_FIAT, 0)); return new ExchangeRate(new org.bitcoinj.utils.ExchangeRate(cachedExchangeRateCoin, cachedExchangeRateFiat), null); } else { return null; } }
public static ExchangeRate getExchangeRate(final Cursor cursor) { final String currencyCode = cursor .getString(cursor.getColumnIndexOrThrow(ExchangeRatesProvider.KEY_CURRENCY_CODE)); final Coin rateCoin = Coin .valueOf(cursor.getLong(cursor.getColumnIndexOrThrow(ExchangeRatesProvider.KEY_RATE_COIN))); final Fiat rateFiat = Fiat.valueOf(currencyCode, cursor.getLong(cursor.getColumnIndexOrThrow(ExchangeRatesProvider.KEY_RATE_FIAT))); final String source = cursor.getString(cursor.getColumnIndexOrThrow(ExchangeRatesProvider.KEY_SOURCE)); return new ExchangeRate(new org.bitcoinj.utils.ExchangeRate(rateCoin, rateFiat), source); }
private Output(final Parcel in) { amount = (Coin) in.readSerializable(); final int programLength = in.readInt(); final byte[] program = new byte[programLength]; in.readByteArray(program); script = new Script(program); }
public Coin getAmount() { Coin amount = Coin.ZERO; if (hasOutputs()) for (final Output output : outputs) if (output.hasAmount()) amount = amount.add(output.amount); if (amount.signum() != 0) return amount; else return null; }
@Override public int onStartCommand(final Intent intent, final int flags, final int startId) { if (intent != null) { log.info("service start command: " + intent + (intent.hasExtra(Intent.EXTRA_ALARM_COUNT) ? " (alarm count: " + intent.getIntExtra(Intent.EXTRA_ALARM_COUNT, 0) + ")" : "")); final String action = intent.getAction(); if (BlockchainService.ACTION_CANCEL_COINS_RECEIVED.equals(action)) { notificationCount = 0; notificationAccumulatedAmount = Coin.ZERO; notificationAddresses.clear(); nm.cancel(Constants.NOTIFICATION_ID_COINS_RECEIVED); } else if (BlockchainService.ACTION_RESET_BLOCKCHAIN.equals(action)) { log.info("will remove blockchain on service shutdown"); resetBlockchainOnShutdown = true; stopSelf(); } else if (BlockchainService.ACTION_BROADCAST_TRANSACTION.equals(action)) { final Sha256Hash hash = Sha256Hash .wrap(intent.getByteArrayExtra(BlockchainService.ACTION_BROADCAST_TRANSACTION_HASH)); final Transaction tx = application.getWallet().getTransaction(hash); if (peerGroup != null) { log.info("broadcasting transaction " + tx.getHashAsString()); peerGroup.broadcastTransaction(tx); } else { log.info("peergroup not available, not broadcasting transaction " + tx.getHashAsString()); } } } else { log.warn("service restart, although it was started as non-sticky"); } return START_NOT_STICKY; }
private void handleDonate() { final Coin balance = wallet.getBalance(BalanceType.AVAILABLE_SPENDABLE); SendCoinsActivity.startDonate(this, balance, FeeCategory.ECONOMIC, Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); nm.cancel(Constants.NOTIFICATION_ID_INACTIVITY); sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)); }
@Override public void onUpdate(final Context context, final AppWidgetManager appWidgetManager, final int[] appWidgetIds) { final WalletApplication application = (WalletApplication) context.getApplicationContext(); final Coin balance = application.getWallet().getBalance(BalanceType.ESTIMATED); updateWidgets(context, appWidgetManager, appWidgetIds, balance); }
@Override public void onAppWidgetOptionsChanged(final Context context, final AppWidgetManager appWidgetManager, final int appWidgetId, final Bundle newOptions) { if (newOptions != null) log.info("app widget {} options changed: minWidth={}", appWidgetId, newOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH)); final WalletApplication application = (WalletApplication) context.getApplicationContext(); final Coin balance = application.getWallet().getBalance(BalanceType.ESTIMATED); updateWidget(context, appWidgetManager, appWidgetId, newOptions, balance); }