本文整理汇总了Java中org.bitcoinj.core.Coin类的典型用法代码示例。如果您正苦于以下问题:Java Coin类的具体用法?Java Coin怎么用?Java Coin使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
Coin类属于org.bitcoinj.core包,在下文中一共展示了Coin类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: getBalanceFriendlyStr
import org.bitcoinj.core.Coin; //导入依赖的package包/类
/**
*
*/
@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();
}
示例2: execute
import org.bitcoinj.core.Coin; //导入依赖的package包/类
/**
*
* @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();
}
}
示例3: getAmount
import org.bitcoinj.core.Coin; //导入依赖的package包/类
@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;
}
}
示例4: getBalanceFuture
import org.bitcoinj.core.Coin; //导入依赖的package包/类
/**
* <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();
}
}
示例5: checkBalanceFuturesLocked
import org.bitcoinj.core.Coin; //导入依赖的package包/类
@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);
}
});
}
}
示例6: getTotalReceived
import org.bitcoinj.core.Coin; //导入依赖的package包/类
/**
* 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;
}
示例7: select
import org.bitcoinj.core.Coin; //导入依赖的package包/类
@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);
}
示例8: sortOutputs
import org.bitcoinj.core.Coin; //导入依赖的package包/类
@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);
}
});
}
示例9: updateWidgets
import org.bitcoinj.core.Coin; //导入依赖的package包/类
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);
}
}
示例10: updateBalance
import org.bitcoinj.core.Coin; //导入依赖的package包/类
/** 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)" : ""));
}
示例11: handleEmpty
import org.bitcoinj.core.Coin; //导入依赖的package包/类
private void handleEmpty() {
final Coin available = wallet.getBalance(BalanceType.AVAILABLE);
amountCalculatorLink.setBtcAmount(available);
updateView();
handler.post(dryrunRunnable);
}
示例12: sendBitcoin
import org.bitcoinj.core.Coin; //导入依赖的package包/类
/** 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());
}
示例13: coinsRecevied
import org.bitcoinj.core.Coin; //导入依赖的package包/类
/** 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);
}
示例14: select
import org.bitcoinj.core.Coin; //导入依赖的package包/类
@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);
}
示例15: applyTxFee
import org.bitcoinj.core.Coin; //导入依赖的package包/类
/**
*
* @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;
}