/** * Restore watch-only account deterministic public key from XPUB. * * @return DeterministicKey * */ private DeterministicKey createMasterPubKeyFromXPub(String xpubstr) throws AddressFormatException { byte[] xpubBytes = Base58.decodeChecked(xpubstr); ByteBuffer bb = ByteBuffer.wrap(xpubBytes); if(bb.getInt() != 0x0488B21E) { throw new AddressFormatException("invalid xpub version"); } byte[] chain = new byte[32]; byte[] pub = new byte[33]; // depth: bb.get(); // parent fingerprint: bb.getInt(); // child no. bb.getInt(); bb.get(chain); bb.get(pub); return HDKeyDerivation.createMasterPubKeyFromBytes(pub, chain); }
@Test public void testConstructors() throws AddressFormatException { // BTC assertEquals(BTC_P2PKH_ADDR, new BitAddress(BTC, HASH160).toString()); assertEquals(BTC_P2PKH_ADDR, new BitAddress(BTC, BTC.getAddressHeader(), HASH160).toString()); assertEquals(BTC_P2PKH_ADDR, new BitAddress(BTC, BTC_P2PKH_ADDR).toString()); assertEquals(BTC_P2SH_ADDR, new BitAddress(BTC, BTC.getP2SHHeader(), HASH160).toString()); assertEquals(BTC_P2SH_ADDR, new BitAddress(BTC, BTC_P2SH_ADDR).toString()); // LTC assertEquals(LTC_P2PKH_ADDR, new BitAddress(LTC, HASH160).toString()); assertEquals(LTC_P2PKH_ADDR, new BitAddress(LTC, LTC.getAddressHeader(), HASH160).toString()); assertEquals(LTC_P2PKH_ADDR, new BitAddress(LTC, LTC_P2PKH_ADDR).toString()); assertEquals(LTC_P2SH_ADDR, new BitAddress(LTC, LTC.getP2SHHeader(), HASH160).toString()); assertEquals(LTC_P2SH_ADDR, new BitAddress(LTC, LTC_P2SH_ADDR).toString()); }
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); } } catch (final AddressFormatException x) { // swallow } }
void checkDoubleSpending(Transaction t) throws InterruptedException, IOException, FormatException, TimeoutException, Matrix, CoinNetworkException, AddressFormatException { // Check for double spending. Message doubleSpend = messages.make(); for (VerificationKey key : players.values()) { Transaction o = coin.getConflictingTransaction(t, key.address(), amount); if (o != null) { doubleSpend = doubleSpend.attach(Blame.DoubleSpend(key, o)); } } if (!doubleSpend.isEmpty()) { phase.set(Phase.Blame); mailbox.broadcast(doubleSpend, phase.get()); throw fillBlameMatrix(); } }
public String sendOffline(String destinationAddress, long amountSatoshis) throws InsufficientMoneyException { Address addressj; try { addressj = new Address(params, destinationAddress); } catch (AddressFormatException e) { e.printStackTrace(); throw new RuntimeException(e); } Coin amount = Coin.valueOf(amountSatoshis); // create a SendRequest of amount to destinationAddress Wallet.SendRequest sendRequest = Wallet.SendRequest.to(addressj, amount); // set dynamic fee sendRequest.feePerKb = getRecommendedFee(); // complete & sign tx kit.wallet().completeTx(sendRequest); kit.wallet().signTransaction(sendRequest); // return tx bytes as hex encoded String return Hex.encodeHexString(sendRequest.tx.bitcoinSerialize()); }
private void testVector(int testCase) throws AddressFormatException { log.info("======= Test vector {}", testCase); HDWTestVector tv = tvs[testCase]; DeterministicKey masterPrivateKey = HDKeyDerivation.createMasterPrivateKey(HEX.decode(tv.seed)); assertEquals(testEncode(tv.priv), testEncode(masterPrivateKey.serializePrivB58())); assertEquals(testEncode(tv.pub), testEncode(masterPrivateKey.serializePubB58())); DeterministicHierarchy dh = new DeterministicHierarchy(masterPrivateKey); for (int i = 0; i < tv.derived.size(); i++) { HDWTestVector.DerivedTestCase tc = tv.derived.get(i); log.info("{}", tc.name); assertEquals(tc.name, String.format("Test%d %s", testCase + 1, tc.getPathDescription())); int depth = tc.path.length - 1; DeterministicKey ehkey = dh.deriveChild(Arrays.asList(tc.path).subList(0, depth), false, true, tc.path[depth]); assertEquals(testEncode(tc.priv), testEncode(ehkey.serializePrivB58())); assertEquals(testEncode(tc.pub), testEncode(ehkey.serializePubB58())); } }
private void testVector(int testCase) throws AddressFormatException { log.info("======= Test vector {}", testCase); HDWTestVector tv = tvs[testCase]; NetworkParameters params = MainNetParams.get(); DeterministicKey masterPrivateKey = HDKeyDerivation.createMasterPrivateKey(HEX.decode(tv.seed)); assertEquals(testEncode(tv.priv), testEncode(masterPrivateKey.serializePrivB58(params))); assertEquals(testEncode(tv.pub), testEncode(masterPrivateKey.serializePubB58(params))); DeterministicHierarchy dh = new DeterministicHierarchy(masterPrivateKey); for (int i = 0; i < tv.derived.size(); i++) { HDWTestVector.DerivedTestCase tc = tv.derived.get(i); log.info("{}", tc.name); assertEquals(tc.name, String.format("Test%d %s", testCase + 1, tc.getPathDescription())); int depth = tc.path.length - 1; DeterministicKey ehkey = dh.deriveChild(Arrays.asList(tc.path).subList(0, depth), false, true, tc.path[depth]); assertEquals(testEncode(tc.priv), testEncode(ehkey.serializePrivB58(params))); assertEquals(testEncode(tc.pub), testEncode(ehkey.serializePubB58(params))); } }
/** * * @param accountIndex * @param type * @param addressKey * @param iKnowAddressFromKeyIsNotWatched * @return * @throws AddressNotWatchedByWalletException * @throws CannotGetHDKeyException */ public DeterministicKey getPubKeyFromAccount(int accountIndex, HierarchyAddressTypes type, int addressKey, boolean iKnowAddressFromKeyIsNotWatched) throws AddressNotWatchedByWalletException, CannotGetHDKeyException, AddressFormatException{ try { ATAccount acc = this.getAccount(accountIndex); ATAccountAddressHierarchy H = type == HierarchyAddressTypes.External? acc.getAccountExternalHierarchy():acc.getAccountInternalHierarchy(); DeterministicKey ret = authenticatorWalletHierarchy.getPubKeyFromAccount(accountIndex, type, addressKey, H); if(!iKnowAddressFromKeyIsNotWatched && !isWatchingAddress(ret.toAddress(getNetworkParams()))) throw new AddressNotWatchedByWalletException("You are trying to get an unwatched address"); return ret; } catch(KeyIndexOutOfRangeException | AccountWasNotFoundException e) { throw new CannotGetHDKeyException(e.toString()); } }
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; } }
private boolean testAddr(String text) { try { new Address(params, text); return true; } catch (AddressFormatException e) { return false; } }
/** * Constructor for watch-only wallet initialized from submitted XPUB(s). * * @param NetworkParameters params * @param String[] xpub array of XPUB strings * */ public Wallet(NetworkParameters params, String[] xpub) throws AddressFormatException { this.params = params; accounts = new ArrayList<Account>(); for(int i = 0; i < xpub.length; i++) { accounts.add(new Account(params, xpub[i], i)); } }
/** * Return instance for a watch only wallet. No seed, no private keys. * * @param Context ctx app context * @param String[] xpub restore these accounts only * * @return WalletFactory * */ public static WalletFactory getInstance(String[] xpub) throws AddressFormatException { if(instance == null) { locale = new Locale("en", "US"); wallets = new ArrayList<Wallet>(); instance = new WalletFactory(); } if(watch_only_wallet == null) { watch_only_wallet = new Wallet(MainNetParams.get(), xpub); } return instance; }
@Test public void newWalletTest() throws AddressFormatException, MnemonicLengthException, MnemonicWordException, MnemonicChecksumException, IOException, DecoderException { String MNEMONIC_STRING = "sword acquire little despair wave swear during expect target science banana eyebrow"; String passphrase = ""; org.matthiaszimmermann.bitcoin.pwg.Wallet hdWallet = WalletFactory.getInstance().restoreWallet(MNEMONIC_STRING, passphrase); System.out.println(hdWallet.toJSON().toString(4)); }
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); } }
@Override public void onItemClick(final AdapterView<?> parent, final View view, final int position, final long id) { final Cursor cursor = receivingAddressViewAdapter.getCursor(); cursor.moveToPosition(position); final String address = cursor.getString(cursor.getColumnIndexOrThrow(AddressBookProvider.KEY_ADDRESS)); final String label = cursor.getString(cursor.getColumnIndexOrThrow(AddressBookProvider.KEY_LABEL)); try { validatedAddress = new AddressAndLabel(Constants.NETWORK_PARAMETERS, address, label); receivingAddressView.setText(null); log.info("Picked valid address from suggestions: {}", validatedAddress); } catch (final AddressFormatException x) { // swallow } }
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 } }
public byte[] getIncomingMask(Wallet wallet, byte[] pubkey, byte[] outPoint) throws AddressFormatException, Exception { Address notifAddress = getNotificationAddress(wallet); DumpedPrivateKey dpk = new DumpedPrivateKey(MainNetParams.get(), notifAddress.getPrivateKeyString()); ECKey inputKey = dpk.getKey(); byte[] privkey = inputKey.getPrivKeyBytes(); byte[] mask = PaymentCode.getMask(new SecretPoint(privkey, pubkey).ECDHSecretAsBytes(), outPoint); return mask; }
private BigInteger secretPoint() throws AddressFormatException, InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException, NotSecp256k1Exception { // // convert hash to value 's' // BigInteger s = new BigInteger(1, hashSharedSecret()); // // check that 's' is on the secp256k1 curve // if(!isSecp256k1(s)) { throw new NotSecp256k1Exception("secret point not on Secp256k1 curve"); } return s; }
private boolean testAddr(String text) { try { Address.fromBase58(params, text); return true; } catch (AddressFormatException e) { return false; } }
private boolean testAddr (String text) { try { new Address(params, text); return true; } catch (AddressFormatException e) { return false; } }
private byte[] parseBase58(String key) throws KeyFormatException { byte[] versionAndDataBytes; try { versionAndDataBytes = Base58.decodeChecked(key); } catch (AddressFormatException e) { throw new KeyFormatException(e); } version = versionAndDataBytes[0] & 0xFF; byte[] payload = new byte[versionAndDataBytes.length - 1]; System.arraycopy(versionAndDataBytes, 1, payload, 0, versionAndDataBytes.length - 1); clearData(versionAndDataBytes); return payload; }
public static BitAddress from(CoinType type, String address) throws AddressMalformedException { try { return new BitAddress(type, address); } catch (AddressFormatException e) { throw new AddressMalformedException(e); } }
public static BitAddress from(AbstractAddress address) throws AddressMalformedException { try { if (address instanceof BitAddress) { return (BitAddress) address; } else if (address instanceof Address) { return new BitAddress((Address) address); } else { return new BitAddress(address.getType(), address.toString()); } } catch (AddressFormatException e) { throw new AddressMalformedException(e); } }
private void handleSend(final String address) { try { SendCoinsActivity.start(activity, PaymentIntent.fromAddress(address, null)); } catch (final AddressFormatException x) { // cannot happen, address was picked from address book throw new RuntimeException(x); } }
public static void edit(final FragmentManager fm, final String address) { try { edit(fm, new Address(Constants.NETWORK_PARAMETERS, address), null); } catch (final AddressFormatException x) { throw new IllegalArgumentException(x); } }
public static Address newAddressOrThrow(final NetworkParameters params, final String base58) throws IllegalArgumentException { try { return new Address(params, base58); } catch (AddressFormatException x) { throw new IllegalArgumentException(x); } }
private void blameInsufficientFunds() throws CoinNetworkException, TimeoutException, Matrix, IOException, InterruptedException, FormatException, AddressFormatException { List<VerificationKey> offenders = new LinkedList<>(); // Check that each participant has the required amounts. for (VerificationKey player : players.values()) { if (!coin.sufficientFunds(player.address(), amount + fee)) { // Enter the blame phase. offenders.add(player); } } // If they do, return. if (offenders.isEmpty()) return; // If not, enter blame phase and find offending transactions. phase.set(Phase.Blame); Message blameMessage = messages.make(); for (VerificationKey offender : offenders) { blameMessage = blameMessage.attach(Blame.InsufficientFunds(offender)); } // Broadcast offending transactions. mailbox.broadcast(blameMessage, phase.get()); // Get all subsequent blame messages. throw fillBlameMatrix(); }
public static boolean isValidAddress(String address, NetworkParameters params) { try { new Address(params, address); return true; } catch (AddressFormatException e) { return false; } }
public SigningKeyImpl(@Nonnull String s) throws AddressFormatException { Bytestring stripped = new Bytestring(Base58.decodeChecked(s)); boolean compressed; switch (stripped.bytes.length) { case (34) : { if (stripped.bytes[33] != 1) { throw new AddressFormatException("Wrong compressed byte"); } stripped = stripped.drop(-1); compressed = true; break; } case (33) : { compressed = false; break; } default : { throw new AddressFormatException("Invalid length."); } } switch (stripped.bytes[0]) { case (-128) : { params = NetworkParameters.fromID(NetworkParameters.ID_MAINNET); break; } case (-17) : { params = NetworkParameters.fromID(NetworkParameters.ID_TESTNET); break; } default: { throw new AddressFormatException("Invalid net byte."); } } stripped = stripped.drop(1); signingKey = ECKey.fromPrivate(stripped.bytes, compressed); vk = new VerificationKeyImpl(signingKey.getPubKey(), params); }
public AddressImpl(String address) throws FormatException { try { this.address = new org.bitcoinj.core.Address( org.bitcoinj.core.Address.getParametersFromAddress(address), address); } catch (AddressFormatException e) { throw new FormatException("Could not parse address " + address); } }
/** * * The valueHeld method takes in an Address variable and returns the balance held using * satoshis as the unit. * */ @Override public long valueHeld(Address addr) throws CoinNetworkException, AddressFormatException { try { return getAddressBalance(addr.toString()); } catch (IOException e) { throw new CoinNetworkException("Could not look up balance: " + e.getMessage()); } }
/** * * The sumUnspentTxOutputs takes in a list of transactions, sums the UTXOs pertaining to address, * and returns a long value. This long value represents the balance of a Bitcoin address in Satoshis. * */ protected synchronized long getAddressBalance(String address) throws IOException, CoinNetworkException, AddressFormatException { List<Bitcoin.Transaction> txList = getAddressTransactions(address); long sum = 0; for (Bitcoin.Transaction tx : txList) { org.bitcoinj.core.Transaction tx2 = tx.bitcoinj; String txhash = tx.hash; boolean usedInput = false; // check that txhash hasn't been used as input in any transactions, if it has, we discard. outerloop: for (Bitcoin.Transaction checkTx : txList) { org.bitcoinj.core.Transaction tempTx = checkTx.bitcoinj; for (TransactionInput input : tempTx.getInputs()) { if (input.getOutpoint().getHash().toString().equals(txhash)) { usedInput = true; break outerloop; } } } // else, we find the specific output in the transaction pertaining to our address, and add the value to sum. if (!usedInput) { for (TransactionOutput output : tx2.getOutputs()) { String addressP2pkh = output.getAddressFromP2PKHScript(netParams).toString(); if (address.equals(addressP2pkh)) { sum += output.getValue().getValue(); break; } } } } return sum; }
@Override public final boolean sufficientFunds(Address addr, long amount) throws CoinNetworkException, AddressFormatException, IOException { String address = addr.toString(); List<Bitcoin.Transaction> transactions = getAddressTransactions(address); if (transactions.size() == 1) { Bitcoin.Transaction tx = transactions.get(0); if (!tx.confirmed) { return false; } long txAmount = 0; if (tx.bitcoinj == null) { try { tx.bitcoinj = getTransaction(tx.hash); } catch (IOException e) { return false; } } for (TransactionOutput output : tx.bitcoinj.getOutputs()) { /** * Every address in the outputs should be of type pay to public key hash, not pay to script hash */ String addressP2pkh = output.getAddressFromP2PKHScript(netParams).toString(); if (address.equals(addressP2pkh)) { txAmount += output.getValue().value; } } return txAmount >= amount; } else { return false; } }
@Test public void testToString() throws AddressFormatException { String ks = ecKey.getPrivateKeyAsWiF(testnet); assertEquals(ks, signingKey.toString()); assertEquals(signingKey.VerificationKey(), new VerificationKeyImpl(signingKey.VerificationKey().toString(), testnet)); assertEquals(signingKey, new SigningKeyImpl(signingKey.toString())); }
@Test public void testSigning() throws AddressFormatException { Bytestring b = new Bytestring(new byte[]{ 10, 38, 67, 111, 105, 110, 83, 104, 117, 102, 102, 108, 101, 32, 83, 104, 117, 102, 102, 108, 101, 112, 117, 102, 102, 32, 116, 101, 115, 116, 32, 116, 101, 115, 116, 110, 101, 116, 48, 48, 26, 68, 10, 66, 48, 50, 99, 51, 57, 100, 52, 49, 98, 102, 51, 51, 53, 101, 98, 56, 53, 97, 52, 51, 53, 52, 48, 57, 55, 100, 51, 51, 102, 102, 100, 54, 52, 57, 102, 100, 55, 99, 53, 52, 49, 50, 49, 56, 49, 100, 50, 102, 56, 55, 97, 99, 50, 48, 51, 56, 48, 54, 102, 102, 54, 100, 50, 55, 99, 55, 34, 68, 10, 66, 48, 50, 99, 51, 57, 100, 52, 49, 98, 102, 51, 51, 53, 101, 98, 56, 53, 97, 52, 51, 53, 52, 48, 57, 55, 100, 51, 51, 102, 102, 100, 54, 52, 57, 102, 100, 55, 99, 53, 52, 49, 50, 49, 56, 49, 100, 50, 102, 56, 55, 97, 99, 50, 48, 51, 56, 48, 54, 102, 102, 54, 100, 50, 55, 99, 55, 40, 7, 50, -13, 2, 50, 70, 18, 68, 10, 66, 48, 50, 99, 51, 57, 100, 52, 49, 98, 102, 51, 51, 53, 101, 98, 56, 53, 97, 52, 51, 53, 52, 48, 57, 55, 100, 51, 51, 102, 102, 100, 54, 52, 57, 102, 100, 55, 99, 53, 52, 49, 50, 49, 56, 49, 100, 50, 102, 56, 55, 97, 99, 50, 48, 51, 56, 48, 54, 102, 102, 54, 100, 50, 55, 99, 55, 58, -88, 2, 50, 70, 18, 68, 10, 66, 48, 51, 99, 54, 54, 51, 98, 50, 50, 100, 98, 98, 97, 100, 48, 101, 53, 55, 55, 52, 98, 50, 100, 57, 49, 99, 54, 51, 57, 56, 56, 100, 98, 99, 99, 100, 49, 56, 102, 53, 100, 54, 48, 50, 52, 48, 49, 97, 101, 99, 98, 55, 53, 52, 54, 102, 57, 98, 55, 100, 100, 49, 99, 50, 53, 50, 58, -35, 1, 50, 70, 18, 68, 10, 66, 48, 50, 48, 50, 97, 56, 99, 54, 97, 55, 100, 102, 48, 53, 55, 99, 99, 101, 55, 54, 50, 99, 53, 101, 56, 100, 48, 100, 55, 50, 55, 54, 56, 98, 56, 101, 100, 99, 50, 98, 52, 49, 56, 101, 102, 98, 51, 98, 53, 51, 48, 54, 99, 99, 98, 100, 50, 53, 100, 57, 56, 48, 100, 49, 101, 50, 58, -110, 1, 50, 70, 18, 68, 10, 66, 48, 50, 98, 51, 100, 97, 56, 99, 48, 51, 100, 97, 99, 49, 97, 48, 57, 57, 98, 48, 101, 55, 51, 56, 50, 98, 99, 56, 99, 100, 101, 51, 51, 54, 51, 57, 48, 100, 52, 50, 97, 102, 99, 48, 57, 52, 55, 50, 54, 48, 97, 97, 52, 54, 57, 102, 99, 49, 97, 97, 48, 51, 48, 48, 56, 102, 58, 72, 50, 70, 18, 68, 10, 66, 48, 50, 56, 97, 50, 97, 57, 53, 50, 55, 54, 49, 51, 51, 101, 50, 98, 54, 97, 52, 99, 54, 100, 50, 56, 50, 54, 98, 52, 57, 97, 52, 99, 49, 52, 102, 101, 51, 49, 55, 102, 99, 101, 50, 50, 56, 53, 100, 101, 98, 53, 49, 98, 53, 52, 57, 52, 50, 53, 98, 98, 97, 49, 97, 53, 50}); SigningKey key = new SigningKeyImpl( "cRT6Vk7qHrJicYtL1cdTkR71A8YDnftjLdhV4r9tAgYqeG7ZPhYk"); key.sign(b); }
public void testGetWalletTransactions() throws IOException, BlockStoreException, AddressFormatException, CoinNetworkException { List<Bitcoin.Transaction> listOfTx = testCase.getAddressTransactions(testAddress); Transaction testTx = listOfTx.get(0).bitcoinj(); Transaction testTx2 = listOfTx.get(1).bitcoinj(); List<Transaction> testTxList = new LinkedList<>(Arrays.asList(testTx, testTx2)); Assert.assertEquals(txList, testTxList); }