/** Creates a scriptPubKey that encodes payment to the given address. */ public static Script createOutputScript(Address to) { if (to.isP2SHAddress()) { // OP_HASH160 <scriptHash> OP_EQUAL return new ScriptBuilder() .op(OP_HASH160) .data(to.getHash160()) .op(OP_EQUAL) .build(); } else { // OP_DUP OP_HASH160 <pubKeyHash> OP_EQUALVERIFY OP_CHECKSIG return new ScriptBuilder() .op(OP_DUP) .op(OP_HASH160) .data(to.getHash160()) .op(OP_EQUALVERIFY) .op(OP_CHECKSIG) .build(); } }
public static Address getUserInternalAddress(final String pubKey, final NetworkParameters networkParameters, final long userIndex) { DeterministicKey deterministicKey = DeterministicKey.deserializeB58(pubKey, networkParameters); DeterministicHierarchy deterministicHierarchy = new DeterministicHierarchy(deterministicKey); List<ChildNumber> child = null; if (deterministicKey.getDepth() == 2) { /* M/44'/0' node tpub */ child = ImmutableList.of(new ChildNumber(0, false), new ChildNumber(1/*user*/, false), new ChildNumber(1/*internal*/, false), new ChildNumber((int)userIndex, false)); } else if (deterministicKey.getDepth() == 3) { /* M/44'/0'/X context tpub */ child = ImmutableList.of(new ChildNumber(1/*user*/, false), new ChildNumber(1/*internal*/, false), new ChildNumber((int)userIndex, false)); } DeterministicKey imprintingKey = deterministicHierarchy.get(child, true, true); return imprintingKey.toAddress(networkParameters); }
public static Address getProviderExternalAddress(final String pubKey, final NetworkParameters networkParameters, final long providerIndex) { DeterministicKey deterministicKey = DeterministicKey.deserializeB58(pubKey, networkParameters); DeterministicHierarchy deterministicHierarchy = new DeterministicHierarchy(deterministicKey); List<ChildNumber> child = null; if (deterministicKey.getDepth() == 2) { /* M/44'/0' node tpub */ child = ImmutableList.of(new ChildNumber(0, false), new ChildNumber(0/*provider*/, false), new ChildNumber(/*external*/0, false), new ChildNumber((int)providerIndex, false)); } else if (deterministicKey.getDepth() == 3) { /* M/44'/0'/X context tpub */ child = ImmutableList.of(new ChildNumber(0/*provider*/, false), new ChildNumber(/*external*/0, false), new ChildNumber((int)providerIndex, false)); } DeterministicKey imprintingKey = deterministicHierarchy.get(child, true, true); return imprintingKey.toAddress(networkParameters); }
public static Address getProviderInternalAddress(final String pubKey, final NetworkParameters networkParameters, final long providerIndex) { DeterministicKey deterministicKey = DeterministicKey.deserializeB58(pubKey, networkParameters); DeterministicHierarchy deterministicHierarchy = new DeterministicHierarchy(deterministicKey); List<ChildNumber> child = null; if (deterministicKey.getDepth() == 2) { /* M/44'/0' node tpub */ child = ImmutableList.of(new ChildNumber(0, false), new ChildNumber(0/*provider*/, false), new ChildNumber(1/*internal*/, false), new ChildNumber((int)providerIndex, false)); } else if (deterministicKey.getDepth() == 3) { /* M/44'/0'/X context tpub */ child = ImmutableList.of(new ChildNumber(0/*provider*/, false), new ChildNumber(1/*internal*/, false), new ChildNumber((int)providerIndex, false)); } DeterministicKey imprintingKey = deterministicHierarchy.get(child, true, true); return imprintingKey.toAddress(networkParameters); }
/** * Return true if the transaction in input is a valid imprinting transaction and contains the specified address in * one of its output, otherwise false. * @param tx the transaction to check if is valid imprinting * @param networkParameters the {@link NetworkParameters} * @param imprintingAddress the address to check for * @return true if it's an imprinting transaction otherwise false */ public static boolean isValidImprintingTransaction(Transaction tx, NetworkParameters networkParameters, Address imprintingAddress) { // Retrieve sender String sender = tx.getInput(0).getFromAddress().toBase58(); // Check output List<TransactionOutput> transactionOutputs = tx.getOutputs(); for (TransactionOutput to : transactionOutputs) { Address address = to.getAddressFromP2PKHScript(networkParameters); if (address != null && address.equals(imprintingAddress)) { return true; } } return false; }
/** * * @return */ @Override public Map<String, String> getAddressesKeys() { Map<String, String> addrKeysMap = new HashMap<>(); List<ECKey> allWalletKeys = _coin.getWalletManager().wallet().getImportedKeys(); allWalletKeys.addAll(_coin.getWalletManager().wallet().getIssuedReceiveKeys()); for (ECKey k : allWalletKeys) { Address addr = k.toAddress(Constants.NETWORK_PARAMETERS); String hash = WalletUtils.formatAddress(addr, Constants.ADDRESS_FORMAT_GROUP_SIZE, Constants.ADDRESS_FORMAT_LINE_SIZE).toString(); addrKeysMap.put(hash, k.getPrivateKeyAsHex()); } return addrKeysMap; }
/** * * @param wallet * @param tx * @param prevBalance * @param newBalance */ @Override public void onCoinsReceived(Wallet wallet, Transaction tx, Coin prevBalance, Coin newBalance) { final Address address = WalletUtils.getWalletAddressOfReceived(tx, wallet); final Coin amount = tx.getValue(wallet); //final TransactionConfidence.ConfidenceType confidenceType = tx.getConfidence().getConfidenceType(); // String addressStr = WalletUtils.formatAddress(address, Constants.ADDRESS_FORMAT_GROUP_SIZE, Constants.ADDRESS_FORMAT_LINE_SIZE).toString(); // long value = amount.getValue(); // for (CoinAction.CoinActionCallback<CurrencyCoin> callback : _callbacks) { // callback.onCoinsReceived(addressStr, value, _bitcoin); // } // meaning that we are receiving amount, not sending if (amount.isPositive()) { // wallet.freshReceiveAddress(); } }
@Nullable public static Address getWalletAddressOfReceived(final Transaction tx, final Wallet wallet) { for (final TransactionOutput output : tx.getOutputs()) { try { if (output.isMine(wallet)) { final Script script = output.getScriptPubKey(); return script.getToAddress(Constants.NETWORK_PARAMETERS, true); } } catch (final ScriptException x) { // swallow } } return null; }
/** * Marks all keys used in the transaction output as used in the wallet. * See {@link org.bitcoinj.wallet.DeterministicKeyChain#markKeyAsUsed(DeterministicKey)} for more info on this. */ private void markKeysAsUsed(Transaction tx) { keyChainGroupLock.lock(); try { for (TransactionOutput o : tx.getOutputs()) { try { Script script = o.getScriptPubKey(); if (script.isSentToRawPubKey()) { byte[] pubkey = script.getPubKey(); keyChainGroup.markPubKeyAsUsed(pubkey); } else if (script.isSentToAddress()) { byte[] pubkeyHash = script.getPubKeyHash(); keyChainGroup.markPubKeyHashAsUsed(pubkeyHash); } else if (script.isPayToScriptHash()) { Address a = Address.fromP2SHScript(tx.getParams(), script); keyChainGroup.markP2SHAddressAsUsed(a); } } catch (ScriptException e) { // Just means we didn't understand the output of this transaction: ignore it. log.warn("Could not parse tx output script: {}", e.toString()); } } } finally { keyChainGroupLock.unlock(); } }
public PaymentIntent mergeWithEditedValues(@Nullable final Coin editedAmount, @Nullable final Address editedAddress) { final Output[] outputs; if (hasOutputs()) { if (mayEditAmount()) { checkArgument(editedAmount != null); // put all coins on first output, skip the others outputs = new Output[] { new Output(editedAmount, this.outputs[0].script) }; } else { // exact copy of outputs outputs = this.outputs; } } else { checkArgument(editedAmount != null); checkArgument(editedAddress != null); // custom output outputs = buildSimplePayTo(editedAmount, editedAddress); } return new PaymentIntent(standard, payeeName, payeeVerifiedBy, outputs, memo, null, payeeData, null, null); }
@Override public void onCoinsReceived(final Wallet wallet, final Transaction tx, final Coin prevBalance, final Coin newBalance) { transactionsReceived.incrementAndGet(); final int bestChainHeight = blockChain.getBestChainHeight(); final Address address = WalletUtils.getWalletAddressOfReceived(tx, wallet); final Coin amount = tx.getValue(wallet); final ConfidenceType confidenceType = tx.getConfidence().getConfidenceType(); final Sha256Hash hash = tx.getHash(); handler.post(new Runnable() { @Override public void run() { final boolean isReceived = amount.signum() > 0; final boolean replaying = bestChainHeight < config.getBestChainHeightEver(); final boolean isReplayedTx = confidenceType == ConfidenceType.BUILDING && replaying; if (isReceived && !isReplayedTx) notifyCoinsReceived(address, amount, hash); } }); }
@Override public void onLoadFinished(final Loader<Address> loader, final Address currentAddress) { if (!currentAddress.equals(currentAddressQrAddress)) { currentAddressQrAddress = new AddressAndLabel(currentAddress, config.getOwnName()); final String addressStr = BitcoinURI.convertToBitcoinURI(currentAddressQrAddress.address, null, currentAddressQrAddress.label, null); currentAddressQrBitmap = new BitmapDrawable(getResources(), Qr.bitmap(addressStr)); currentAddressQrBitmap.setFilterBitmap(false); currentAddressUriRef.set(addressStr); updateView(); } }
public boolean isValidBitcoinAddress(String address) { try { Address.fromBase58(getBitcoinNetworkParameters(), address); return true; } catch(AddressFormatException e) { return false; } }
public boolean isValidAddress(String address) { try { Address.fromBase58(getNetworkParameters(), address); return true; } catch(AddressFormatException e) { return false; } }
public boolean isValidAddress(byte[] address) { try { Address.fromP2SHHash(TestNet3Params.get(), address); return true; } catch(AddressFormatException e) { return false; } }
/** * Gets the amount of voting tokens associated with the given public key. * @param pubKey - The Public Key read from the ID of the voter * @param mcAsset - The asset (election) that is chosen at app start-up. * @return - The amount of voting tokens available */ public int getVotingPassAmount(PublicKey pubKey, Asset mcAsset) { if(pubKey != null && mcAsset != null) { Address mcAddress = Address.fromBase58(params, MultiChainAddressGenerator.getPublicAddress(version, Long.toString(addressChecksum), pubKey)); return (int) kit.wallet().getAssetBalance(mcAsset, mcAddress).getBalance(); } else { return 0; } }
private boolean testAddr(String text) { try { new Address(params, text); return true; } catch (AddressFormatException e) { return false; } }
/** 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()); }
/** * * @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; }
/** * * @return */ @Override public List<String> getCurrentAddresses() { List<String> addrHash160List = new ArrayList<>(); List<Address> walletAddresses = _coin.getWalletManager().wallet().getIssuedReceiveAddresses(); for (Address aAddr : walletAddresses) { String hash = WalletUtils.formatAddress(aAddr, Constants.ADDRESS_FORMAT_GROUP_SIZE, Constants.ADDRESS_FORMAT_LINE_SIZE).toString(); addrHash160List.add(hash); } return addrHash160List; }
/** * * @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(); } }
@Nullable public static Address getToAddressOfSent(final Transaction tx, final Wallet wallet) { for (final TransactionOutput output : tx.getOutputs()) { try { if (!output.isMine(wallet)) { final Script script = output.getScriptPubKey(); return script.getToAddress(Constants.NETWORK_PARAMETERS, true); } } catch (final ScriptException x) { // swallow } } return null; }
private void handleRequest() { try { final String[] addresses = donationAddresses(); final NetworkParameters params = Address.getParametersFromAddress(addresses[0]); final Protos.Output.Builder output1 = Protos.Output.newBuilder(); output1.setAmount(AMOUNT); output1.setScript(ByteString .copyFrom(ScriptBuilder.createOutputScript(new Address(params, addresses[0])).getProgram())); final Protos.Output.Builder output2 = Protos.Output.newBuilder(); output2.setAmount(AMOUNT); output2.setScript(ByteString .copyFrom(ScriptBuilder.createOutputScript(new Address(params, addresses[1])).getProgram())); final Protos.PaymentDetails.Builder paymentDetails = Protos.PaymentDetails.newBuilder(); paymentDetails.setNetwork(params.getPaymentProtocolId()); paymentDetails.addOutputs(output1); paymentDetails.addOutputs(output2); paymentDetails.setMemo(MEMO); paymentDetails.setTime(System.currentTimeMillis()); final Protos.PaymentRequest.Builder paymentRequest = Protos.PaymentRequest.newBuilder(); paymentRequest.setSerializedPaymentDetails(paymentDetails.build().toByteString()); BitcoinIntegration.requestForResult(SampleActivity.this, REQUEST_CODE, paymentRequest.build().toByteArray()); } catch (final AddressFormatException x) { throw new RuntimeException(x); } }
/** * Returns address for a {@link #currentKey(org.bitcoinj.wallet.KeyChain.KeyPurpose)} */ public Address currentAddress(KeyChain.KeyPurpose purpose) { keyChainGroupLock.lock(); try { maybeUpgradeToHD(); return keyChainGroup.currentAddress(purpose); } finally { keyChainGroupLock.unlock(); } }
/** * Returns address for a {@link #freshKey(org.bitcoinj.wallet.KeyChain.KeyPurpose)} */ public Address freshAddress(KeyChain.KeyPurpose purpose) { Address key; keyChainGroupLock.lock(); try { key = keyChainGroup.freshAddress(purpose); } finally { keyChainGroupLock.unlock(); } saveNow(); return key; }
/** * Returns only the addresses that have been issued by {@link #freshReceiveKey()}, {@link #freshReceiveAddress()}, * {@link #currentReceiveKey()} or {@link #currentReceiveAddress()}. */ public List<Address> getIssuedReceiveAddresses() { final List<ECKey> keys = getIssuedReceiveKeys(); List<Address> addresses = new ArrayList<>(keys.size()); for (ECKey key : keys) addresses.add(key.toAddress(getParams())); return addresses; }
/** * Adds the given address to the wallet to be watched. Outputs can be retrieved * by {@link #getWatchedOutputs(boolean)}. * * @return how many addresses were added successfully */ public int addWatchedAddresses(final List<Address> addresses, long creationTime) { List<Script> scripts = Lists.newArrayList(); for (Address address : addresses) { Script script = ScriptBuilder.createOutputScript(address); script.setCreationTimeSeconds(creationTime); scripts.add(script); } return addWatchedScripts(scripts); }
/** * Removes the given output scripts from the wallet that were being watched. * * @return true if successful */ public boolean removeWatchedAddresses(final List<Address> addresses) { List<Script> scripts = Lists.newArrayList(); for (Address address : addresses) { Script script = ScriptBuilder.createOutputScript(address); scripts.add(script); } return removeWatchedScripts(scripts); }
/** * Returns all addresses watched by this wallet. */ public List<Address> getWatchedAddresses() { keyChainGroupLock.lock(); try { List<Address> addresses = new LinkedList<>(); for (Script script : watchedScripts) if (script.isSentToAddress()) addresses.add(script.getToAddress(params)); return addresses; } finally { keyChainGroupLock.unlock(); } }
/** * Get all the {@link UTXO}'s from the {@link UTXOProvider} based on keys that the * wallet contains. * @return The list of stored outputs. */ protected List<UTXO> getStoredOutputsFromUTXOProvider() throws UTXOProviderException { UTXOProvider utxoProvider = checkNotNull(vUTXOProvider, "No UTXO provider has been set"); List<UTXO> candidates = new ArrayList<>(); List<ECKey> keys = getImportedKeys(); keys.addAll(getActiveKeyChain().getLeafKeys()); List<Address> addresses = new ArrayList<>(); for (ECKey key : keys) { Address address = new Address(params, key.getPubKeyHash()); addresses.add(address); } candidates.addAll(utxoProvider.getOpenTransactionOutputs(addresses)); return candidates; }
/** * <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; }
public static PaymentIntent fromBitcoinUri(final BitcoinURI bitcoinUri) { final Address address = bitcoinUri.getAddress(); final Output[] outputs = address != null ? buildSimplePayTo(bitcoinUri.getAmount(), address) : null; final String bluetoothMac = (String) bitcoinUri.getParameterByName(Bluetooth.MAC_URI_PARAM); final String paymentRequestHashStr = (String) bitcoinUri.getParameterByName("h"); final byte[] paymentRequestHash = paymentRequestHashStr != null ? base64UrlDecode(paymentRequestHashStr) : null; return new PaymentIntent(PaymentIntent.Standard.BIP21, null, null, outputs, bitcoinUri.getLabel(), bluetoothMac != null ? "bt:" + bluetoothMac : null, null, bitcoinUri.getPaymentRequestUrl(), paymentRequestHash); }
public Address getAddress() { if (!hasAddress()) throw new IllegalStateException(); final Script script = outputs[0].script; return script.getToAddress(Constants.NETWORK_PARAMETERS, true); }
private void validateReceivingAddress() { try { final String addressStr = receivingAddressView.getText().toString().trim(); if (!addressStr.isEmpty() && Constants.NETWORK_PARAMETERS.equals(Address.getParametersFromAddress(addressStr))) { final String label = AddressBookProvider.resolveLabel(activity, addressStr); validatedAddress = new AddressAndLabel(Constants.NETWORK_PARAMETERS, addressStr, label); receivingAddressView.setText(null); log.info("Locked to valid address: {}", validatedAddress); } } catch (final AddressFormatException x) { // swallow } }
@Override public void onActivityResult(final int requestCode, final int resultCode, final Intent intent) { if (requestCode == REQUEST_CODE_SCAN && resultCode == Activity.RESULT_OK) { final String input = intent.getStringExtra(ScanActivity.INTENT_EXTRA_RESULT); new StringInputParser(input) { @Override protected void handlePaymentIntent(final PaymentIntent paymentIntent) { // workaround for "IllegalStateException: Can not perform this action after // onSaveInstanceState" handler.postDelayed(new Runnable() { @Override public void run() { if (paymentIntent.hasAddress()) { final Address address = paymentIntent.getAddress(); if (!wallet.isPubKeyHashMine(address.getHash160())) EditAddressBookEntryFragment.edit(getFragmentManager(), address); else dialog(activity, null, R.string.address_book_options_scan_title, R.string.address_book_options_scan_own_address); } else { dialog(activity, null, R.string.address_book_options_scan_title, R.string.address_book_options_scan_invalid); } } }, 500); } @Override protected void handleDirectTransaction(final Transaction transaction) throws VerificationException { cannotClassify(input); } @Override protected void error(final int messageResId, final Object... messageArgs) { dialog(activity, null, R.string.address_book_options_scan_title, messageResId, messageArgs); } }.parse(); } }
public void setWalletAddresses(@Nonnull final ArrayList<Address> addresses) { final StringBuilder builder = new StringBuilder(); for (final Address address : addresses) builder.append(address.toBase58()).append(","); if (addresses.size() > 0) builder.setLength(builder.length() - 1); walletAddressesSelection = builder.toString(); }