List of usage examples for java.math BigInteger subtract
public BigInteger subtract(BigInteger val)
From source file:piuk.blockchain.android.ui.AbstractWalletActivity.java
private void handleScanPrivateKeyPair(final ECKey key) throws Exception { final AlertDialog.Builder b = new AlertDialog.Builder(this); b.setPositiveButton(R.string.sweep_text, null); b.setNeutralButton(R.string.import_text, null); b.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() { @Override//w w w . j av a2 s. c om public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); b.setTitle("Scan Private Key"); b.setMessage("Fetching Balance. Please Wait"); final AlertDialog dialog = b.show(); dialog.getButton(Dialog.BUTTON1).setEnabled(false); new Thread() { public void run() { try { final String address; if (key.isCompressed()) { address = key.toAddressCompressed(MainNetParams.get()).toString(); } else { address = key.toAddressUnCompressed(MainNetParams.get()).toString(); } System.out.println("Scanned PK Address " + address); BigInteger balance = MyRemoteWallet.getAddressBalance(address); final BigInteger finalBalance = balance; handler.post(new Runnable() { @Override public void run() { final MyRemoteWallet remoteWallet = application.getRemoteWallet(); if (remoteWallet == null) return; dialog.getButton(Dialog.BUTTON3).setEnabled(true); if (finalBalance.longValue() == 0) { dialog.setMessage("The Balance of address " + address + " is zero."); } else { dialog.getButton(Dialog.BUTTON1).setEnabled(true); dialog.setMessage( "The Balance of " + address + " is " + WalletUtils.formatValue(finalBalance) + " BTC. Would you like to sweep it?"); } dialog.getButton(Dialog.BUTTON3).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (remoteWallet.isDoubleEncrypted() == false) { reallyAddKey(dialog, key); } else { if (remoteWallet.temporySecondPassword == null) { RequestPasswordDialog.show(getSupportFragmentManager(), new SuccessCallback() { public void onSuccess() { reallyAddKey(dialog, key); } public void onFail() { } }, RequestPasswordDialog.PasswordTypeSecond); } else { reallyAddKey(dialog, key); } } } }); dialog.getButton(Dialog.BUTTON1).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { try { MyRemoteWallet wallet = new MyRemoteWallet(); wallet.addKey(key, address, null); Address to = application.determineSelectedAddress(); if (to == null) { handler.post(new Runnable() { public void run() { dialog.dismiss(); } }); return; } BigInteger baseFee = wallet.getBaseFee(); wallet.simpleSendCoinsAsync(to.toString(), finalBalance.subtract(baseFee), MyRemoteWallet.FeePolicy.FeeForce, baseFee, new SendProgress() { @Override public boolean onReady(Transaction tx, BigInteger fee, MyRemoteWallet.FeePolicy feePolicy, long priority) { return true; } @Override public void onSend(Transaction tx, String message) { handler.post(new Runnable() { public void run() { dialog.dismiss(); longToast("Private Key Successfully Swept"); } }); } @Override public ECKey onPrivateKeyMissing(String address) { return null; } @Override public void onError(final String message) { handler.post(new Runnable() { public void run() { dialog.dismiss(); longToast(message); } }); } @Override public void onProgress(String message) { } @Override public void onStart() { } }); } catch (final Exception e) { e.getLocalizedMessage(); handler.post(new Runnable() { public void run() { dialog.dismiss(); longToast(e.getLocalizedMessage()); } }); } } }); } }); } catch (final Exception e) { e.printStackTrace(); handler.post(new Runnable() { public void run() { dialog.dismiss(); longToast(e.getLocalizedMessage()); } }); } } }.start(); }
From source file:com.google.bitcoin.core.Wallet.java
private void receive(Transaction tx, StoredBlock block, BlockChain.NewBlockType blockType, int relativityOffset) throws VerificationException { // Runs in a peer thread. checkState(lock.isHeldByCurrentThread()); BigInteger prevBalance = getBalance(); Sha256Hash txHash = tx.getHash();/* w w w. j a va 2 s . co m*/ boolean bestChain = blockType == BlockChain.NewBlockType.BEST_CHAIN; boolean sideChain = blockType == BlockChain.NewBlockType.SIDE_CHAIN; BigInteger valueSentFromMe = tx.getValueSentFromMe(this); BigInteger valueSentToMe = tx.getValueSentToMe(this); BigInteger valueDifference = valueSentToMe.subtract(valueSentFromMe); log.info("!!!! receive START " + tx.getHashAsString()); log.info("Received tx{} for {} BTC: {} [{}] in block {}", sideChain ? " on a side chain" : "", bitcoinValueToFriendlyString(valueDifference), tx.getHashAsString(), relativityOffset, block != null ? block.getHeader().getHash() : "(unit test)"); /* CSPK-mike START */ // Looking for CoinSpark assets in the transaction if (bestChain) { int blockHeight = 0; if (block != null) { blockHeight = block.getHeight(); CS.log.info("New tx " + tx.getHash().toString() + " in block " + blockHeight); } log.info("!!!! receive HIT!!! " + tx.getHashAsString()); CSTransactionAssets txAssets = new CSTransactionAssets(tx); txAssets.updateAssetBalances(this, blockHeight, CS.getInputAssetBalances(tx)); /* Look for payment reference and post CSEvent if found */ final int FBHCHAIN_START_BLOCK = 312500; // July 26th 2014 // optimise, only check from period when assets were first being created if (blockHeight > FBHCHAIN_START_BLOCK) { log.info("!!!! Extracting CoinSpark payment reference from a transaction..."); byte[] txnMetaData = null; //int metadataOutput=0; //int count=0; for (TransactionOutput output : tx.getOutputs()) { // TRANSACTION_PAYMENT_REFERENCE_DETECTED byte[] scriptBytes = output.getScriptBytes(); if (!CoinSparkBase.scriptIsRegular(scriptBytes)) { txnMetaData = CoinSparkBase.scriptToMetadata(scriptBytes); break; } } if (txnMetaData != null) { CoinSparkPaymentRef paymentRef = new CoinSparkPaymentRef(); if (paymentRef.decode(txnMetaData)) { log.info("!!!! Found Payment Ref: " + paymentRef.toString()); HashMap<String, Long> map = new HashMap<String, Long>(); map.put(tx.getHashAsString(), paymentRef.getRef()); CSEventBus.INSTANCE.postAsyncEvent(CSEventType.TRANSACTION_PAYMENT_REFERENCE_RECEIVED, map); } } } } /* CSPK-mike END */ // If the transaction is being replayed no need to add it to the wallet again. Transaction diagnosticTx = tx; if (spent.containsKey(txHash)) { diagnosticTx = spent.get(txHash); } if (unspent.containsKey(txHash)) { diagnosticTx = unspent.get(txHash); } if (dead.containsKey(txHash)) { diagnosticTx = dead.get(txHash); } boolean isReplay = ((spent.containsKey(txHash) || unspent.containsKey(txHash) || dead.containsKey(txHash)) && bestChain) && diagnosticTx.getConfidence().getConfidenceType() == ConfidenceType.BUILDING && (diagnosticTx.getConfidence().getAppearedAtChainHeight() > lastBlockSeenHeight); if (isReplay) { log.debug("Replay diagnostic for tx = " + txHash); log.debug(" spent.containsKey(txHash) = " + spent.containsKey(txHash)); log.debug(" unspent.containsKey(txHash) = " + unspent.containsKey(txHash)); log.debug(" dead.containsKey(txHash) = " + dead.containsKey(txHash)); log.debug(" diagnosticTx.getConfidence().getConfidenceType() = " + diagnosticTx.getConfidence().getConfidenceType()); if (diagnosticTx.getConfidence().getConfidenceType() == ConfidenceType.BUILDING) { log.debug(" diagnosticTx.getConfidence().getAppearedAtChainHeight() = " + diagnosticTx.getConfidence().getAppearedAtChainHeight()); } log.debug(" lastBlockSeenHeight = " + lastBlockSeenHeight); log.debug(" bestChain = " + bestChain); // We know the tx appears in the chain in the future (compared to // now) and it is not a reorg so can ignore it. // This happens on replay. log.debug("Received a tx '" + txHash.toString() + "' which is a replay so ignoring."); return; } onWalletChangedSuppressions++; // If this transaction is already in the wallet we may need to move it into a different pool. At the very // least we need to ensure we're manipulating the canonical object rather than a duplicate. { Transaction tmp = transactions.get(tx.getHash()); if (tmp != null) tx = tmp; } boolean wasPending = pending.remove(txHash) != null; if (wasPending) log.info(" <-pending"); if (bestChain) { if (wasPending) { // Was pending and is now confirmed. Disconnect the outputs in case we spent any already: they will be // re-connected by processTxFromBestChain below. for (TransactionOutput output : tx.getOutputs()) { final TransactionInput spentBy = output.getSpentBy(); if (spentBy != null) spentBy.disconnect(); } } processTxFromBestChain(tx, wasPending); } else { checkState(sideChain); // Transactions that appear in a side chain will have that appearance recorded below - we assume that // some miners are also trying to include the transaction into the current best chain too, so let's treat // it as pending, except we don't need to do any risk analysis on it. if (wasPending) { // Just put it back in without touching the connections or confidence. addWalletTransaction(Pool.PENDING, tx); log.info(" ->pending"); } else { // Ignore the case where a tx appears on a side chain at the same time as the best chain (this is // quite normal and expected). Sha256Hash hash = tx.getHash(); if (!unspent.containsKey(hash) && !spent.containsKey(hash)) { // Otherwise put it (possibly back) into pending. // Committing it updates the spent flags and inserts into the pool as well. commitTx(tx); } } } if (block != null) { // Mark the tx as appearing in this block so we can find it later after a re-org. This also tells the tx // confidence object about the block and sets its work done/depth appropriately. tx.setBlockAppearance(block, bestChain, relativityOffset); if (bestChain) { // Don't notify this tx of work done in notifyNewBestBlock which will be called immediately after // this method has been called by BlockChain for all relevant transactions. Otherwise we'd double // count. ignoreNextNewBlock.add(txHash); } } onWalletChangedSuppressions--; // Side chains don't affect confidence. if (bestChain) { // notifyNewBestBlock will be invoked next and will then call maybeQueueOnWalletChanged for us. confidenceChanged.put(tx, TransactionConfidence.Listener.ChangeReason.TYPE); } else { maybeQueueOnWalletChanged(); } // Inform anyone interested that we have received or sent coins but only if: // - This is not due to a re-org. // - The coins appeared on the best chain. // - We did in fact receive some new money. // - We have not already informed the user about the coins when we received the tx broadcast, or for our // own spends. If users want to know when a broadcast tx becomes confirmed, they need to use tx confidence // listeners. if (!insideReorg && bestChain) { BigInteger newBalance = getBalance(); // This is slow. log.info("Balance is now: " + bitcoinValueToFriendlyString(newBalance)); if (!wasPending) { int diff = valueDifference.compareTo(BigInteger.ZERO); // We pick one callback based on the value difference, though a tx can of course both send and receive // coins from the wallet. if (diff > 0) { queueOnCoinsReceived(tx, prevBalance, newBalance); } else if (diff < 0) { queueOnCoinsSent(tx, prevBalance, newBalance); } } checkBalanceFuturesLocked(newBalance); } informConfidenceListenersIfNotReorganizing(); checkState(isConsistent()); //saveNow(); }
From source file:com.peterbochs.PeterBochsDebugger.java
private void disasmFromEIPMinus100MenuItemActionPerformed(ActionEvent evt) { String str;// w ww.j av a 2 s . c o m if (Global.clickedWhichInstructionPanel == 0) { str = (String) instructionTable.getValueAt(instructionTable.getSelectedRow(), 1); } else { str = (String) sourceLevelDebugger.instructionTable .getValueAt(sourceLevelDebugger.instructionTable.getSelectedRow(), 1); } BigInteger address; if (str.startsWith("cCode")) { long l = CommonLib.string2long(str.split(":")[1]); address = BigInteger.valueOf(l); } else { long l = CommonLib.string2long(str.split(":")[0]); address = BigInteger.valueOf(l); } updateInstruction(address.subtract(BigInteger.valueOf(0x100))); }
From source file:com.google.bitcoin.core.Wallet.java
/** * Given a spend request containing an incomplete transaction, makes it valid by adding outputs and signed inputs * according to the instructions in the request. The transaction in the request is modified by this method, as is * the fee parameter./*from ww w.jav a 2 s . com*/ * * @param req a SendRequest that contains the incomplete transaction and details for how to make it valid. * @throws InsufficientMoneyException if the request could not be completed due to not enough balance. * @throws IllegalArgumentException if you try and complete the same SendRequest twice, or if the given send request * cannot be completed without violating the protocol rules. */ public void completeTx(SendRequest req, boolean sign) throws InsufficientMoneyException, CSExceptions.CannotEncode { lock.lock(); try { checkArgument(!req.completed, "Given SendRequest has already been completed."); // Calculate the amount of value we need to import. BigInteger value = BigInteger.ZERO; for (TransactionOutput output : req.tx.getOutputs()) { value = value.add(output.getValue()); } BigInteger totalOutput = value; log.info("Completing send tx with {} outputs totalling {} satoshis (not including fees)", req.tx.getOutputs().size(), value); // If any inputs have already been added, we don't need to get their value from wallet BigInteger totalInput = BigInteger.ZERO; /* CSPK-mike START */ /* Code commented out, input value is calculated after asset inputs were added for (TransactionInput input : req.tx.getInputs()) if (input.getConnectedOutput() != null) totalInput = totalInput.add(input.getConnectedOutput().getValue()); else log.warn("SendRequest transaction already has inputs but we don't know how much they are worth - they will be added to fee."); value = value.subtract(totalInput); */ /* CSPK-mike START */ List<TransactionInput> originalInputs = new ArrayList<TransactionInput>(req.tx.getInputs()); // We need to know if we need to add an additional fee because one of our values are smaller than 0.01 BTC boolean needAtLeastReferenceFee = false; if (req.ensureMinRequiredFee && !req.emptyWallet) { // min fee checking is handled later for emptyWallet for (TransactionOutput output : req.tx.getOutputs()) if (output.getValue().compareTo(Utils.CENT) < 0) { if (output.getValue().compareTo(output.getMinNonDustValue()) < 0) throw new IllegalArgumentException( "Tried to send dust with ensureMinRequiredFee set - no way to complete this"); needAtLeastReferenceFee = true; break; } } // Calculate a list of ALL potential candidates for spending and then ask a coin selector to provide us // with the actual outputs that'll be used to gather the required amount of value. In this way, users // can customize coin selection policies. // // Note that this code is poorly optimized: the spend candidates only alter when transactions in the wallet // change - it could be pre-calculated and held in RAM, and this is probably an optimization worth doing. // Note that output.isMine(this) needs to test the keychain which is currently an array, so it's // O(candidate outputs ^ keychain.size())! There's lots of low hanging fruit here. LinkedList<TransactionOutput> candidates = calculateAllSpendCandidates(true); CoinSelection bestCoinSelection; TransactionOutput bestChangeOutput = null; if (!req.emptyWallet) { // This can throw InsufficientMoneyException. FeeCalculation feeCalculation; /* CSPK-mike START */ // feeCalculation = new FeeCalculation(req, value, originalInputs, needAtLeastReferenceFee, candidates); // Fee and inputs calculation /* CoinSparkMessagePart [] MessageParts=new CoinSparkMessagePart[1]; MessageParts[0]=new CoinSparkMessagePart(); MessageParts[0].mimeType="text/plain"; MessageParts[0].fileName=null; MessageParts[0].content="Hello World!".getBytes(); String [] DeliveryServers=new String [] {"assets1.coinspark.org/","assets1.coinspark.org/abc"};//,"144.76.175.228/" }; req.setMessage(MessageParts, DeliveryServers); CoinSparkPaymentRef paymentRef=new CoinSparkPaymentRef(125); req.setPaymentRef(paymentRef); */ if (CS.createAssetTransfers(req, originalInputs, candidates)) { totalInput = BigInteger.ZERO; for (TransactionInput input : req.tx.getInputs()) { if (input.getConnectedOutput() != null) { totalInput = totalInput.add(input.getConnectedOutput().getValue()); } else { log.warn( "SendRequest transaction already has inputs but we don't know how much they are worth - they will be added to fee."); } } value = totalOutput; value = value.subtract(totalInput); originalInputs = new ArrayList<TransactionInput>(req.tx.getInputs()); // Coinspark transaction has to have change output even if there are no explicit transfers. feeCalculation = new FeeCalculation(req, value, originalInputs, needAtLeastReferenceFee, candidates, Transaction.MIN_NONDUST_OUTPUT); } else { throw new InsufficientMoneyException.CouldNotAdjustDownwards(); } /* CSPK-mike END */ bestCoinSelection = feeCalculation.bestCoinSelection; bestChangeOutput = feeCalculation.bestChangeOutput; } else { // We're being asked to empty the wallet. What this means is ensuring "tx" has only a single output // of the total value we can currently spend as determined by the selector, and then subtracting the fee. checkState(req.tx.getOutputs().size() == 1, "Empty wallet TX must have a single output only."); CoinSelector selector = req.coinSelector == null ? coinSelector : req.coinSelector; bestCoinSelection = selector.select(NetworkParameters.MAX_MONEY, candidates); req.tx.getOutput(0).setValue(bestCoinSelection.valueGathered); totalOutput = bestCoinSelection.valueGathered; } for (TransactionOutput output : bestCoinSelection.gathered) req.tx.addInput(output); /* CSPK-mike START */ if (!CS.preparePaymentRef(req)) { throw new CSExceptions.CannotEncode("Cannot prepare payment reference"); } if (!CS.prepareMessage(req)) { throw new CSExceptions.CannotEncode("Cannot prepare message"); } /* CSPK-mike END */ if (req.ensureMinRequiredFee && req.emptyWallet) { final BigInteger baseFee = req.fee == null ? BigInteger.ZERO : req.fee; final BigInteger feePerKb = req.feePerKb == null ? BigInteger.ZERO : req.feePerKb; Transaction tx = req.tx; if (!adjustOutputDownwardsForFee(tx, bestCoinSelection, baseFee, feePerKb)) throw new InsufficientMoneyException.CouldNotAdjustDownwards(); } /* CSPK-mike START */ // Input calculation for "Empty wallet" request if (req.emptyWallet) { Transaction tx = req.tx; TransactionOutput output = tx.getOutput(0); if (CS.createAssetTransfersForEmptyWallet(req, output.getValue().subtract(output.getMinNonDustValue()))) { if (req.ensureMinRequiredFee) { final BigInteger baseFee = req.fee == null ? BigInteger.ZERO : req.fee; final BigInteger feePerKb = req.feePerKb == null ? BigInteger.ZERO : req.feePerKb; totalOutput = bestCoinSelection.valueGathered; output.setValue(totalOutput); if (!adjustOutputDownwardsForFee(tx, bestCoinSelection, baseFee, feePerKb, req.assetFee)) { CS.log.warning("Empty wallet: not enough bitcoins to transfer assets."); tx.getOutputs().clear(); output.setValue(totalOutput); tx.addOutput(output); req.assetsEncoded = null; req.assetFee = BigInteger.ZERO; if (!adjustOutputDownwardsForFee(tx, bestCoinSelection, baseFee, feePerKb)) { throw new InsufficientMoneyException.CouldNotAdjustDownwards(); } } totalOutput = output.getValue(); bestChangeOutput = null; } } totalOutput = output.getValue(); bestChangeOutput = null; } /* CSPK-mike END */ totalInput = totalInput.add(bestCoinSelection.valueGathered); if (bestChangeOutput != null) { req.tx.addOutput(bestChangeOutput); totalOutput = totalOutput.add(bestChangeOutput.getValue()); log.info(" with {} coins change", bitcoinValueToFriendlyString(bestChangeOutput.getValue())); } final BigInteger calculatedFee = totalInput.subtract(totalOutput); if (calculatedFee.compareTo(BigInteger.ZERO) > 0) { log.info(" with a fee of {}", bitcoinValueToFriendlyString(calculatedFee)); } // Now sign the inputs, thus proving that we are entitled to redeem the connected outputs. if (sign) { sign(req); } // Check size. int size = req.tx.bitcoinSerialize().length; if (size > Transaction.MAX_STANDARD_TX_SIZE) { throw new IllegalArgumentException( String.format("Transaction could not be created without exceeding max size: %d vs %d", size, Transaction.MAX_STANDARD_TX_SIZE)); } // Label the transaction as being self created. We can use this later to spend its change output even before // the transaction is confirmed. We deliberately won't bother notifying listeners here as there's not much // point - the user isn't interested in a confidence transition they made themselves. req.tx.getConfidence().setSource(TransactionConfidence.Source.SELF); // Keep a track of the date the tx was created (used in MultiBitService // to work out the block it appears in). req.tx.setUpdateTime(new Date()); // Label the transaction as being a user requested payment. This can be used to render GUI wallet // transaction lists more appropriately, especially when the wallet starts to generate transactions itself // for internal purposes. req.tx.setPurpose(Transaction.Purpose.USER_PAYMENT); req.completed = true; req.fee = calculatedFee; log.info(" completed: {}", req.tx); } finally { lock.unlock(); } }