Java Code Examples for org.bitcoinj.core.LegacyAddress#fromKey()

The following examples show how to use org.bitcoinj.core.LegacyAddress#fromKey() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SPVBlockStoreTest.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void twoStores_sequentially_grow() throws Exception {
    Address to = LegacyAddress.fromKey(UNITTEST, new ECKey());
    SPVBlockStore store = new SPVBlockStore(UNITTEST, blockStoreFile, 10, true);
    final StoredBlock block0 = store.getChainHead();
    final StoredBlock block1 = block0.build(block0.getHeader().createNextBlock(to).cloneAsHeader());
    store.put(block1);
    final StoredBlock block2 = block1.build(block1.getHeader().createNextBlock(to).cloneAsHeader());
    store.put(block2);
    store.setChainHead(block2);
    store.close();

    store = new SPVBlockStore(UNITTEST, blockStoreFile, 20, true);
    final StoredBlock read2 = store.getChainHead();
    assertEquals(block2, read2);
    final StoredBlock read1 = read2.getPrev(store);
    assertEquals(block1, read1);
    final StoredBlock read0 = read1.getPrev(store);
    assertEquals(block0, read0);
    store.close();
    assertEquals(SPVBlockStore.getFileSize(20), blockStoreFile.length());
}
 
Example 2
Source File: PaymentProtocolTest.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testPaymentMessage() throws Exception {
    // Create
    List<Transaction> transactions = new LinkedList<>();
    transactions.add(FakeTxBuilder.createFakeTx(UNITTEST, AMOUNT, TO_ADDRESS));
    Coin refundAmount = Coin.SATOSHI;
    Address refundAddress = LegacyAddress.fromKey(UNITTEST, new ECKey());
    Payment payment = PaymentProtocol.createPaymentMessage(transactions, refundAmount, refundAddress, MEMO,
            MERCHANT_DATA);
    byte[] paymentBytes = payment.toByteArray();

    // Parse
    Payment parsedPayment = Payment.parseFrom(paymentBytes);
    List<Transaction> parsedTransactions = PaymentProtocol.parseTransactionsFromPaymentMessage(UNITTEST,
            parsedPayment);
    assertEquals(transactions, parsedTransactions);
    assertEquals(1, parsedPayment.getRefundToCount());
    assertEquals(MEMO, parsedPayment.getMemo());
    assertArrayEquals(MERCHANT_DATA, parsedPayment.getMerchantData().toByteArray());
}
 
Example 3
Source File: SPVBlockStoreTest.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void basics() throws Exception {
    SPVBlockStore store = new SPVBlockStore(UNITTEST, blockStoreFile);

    Address to = LegacyAddress.fromKey(UNITTEST, new ECKey());
    // Check the first block in a new store is the genesis block.
    StoredBlock genesis = store.getChainHead();
    assertEquals(UNITTEST.getGenesisBlock(), genesis.getHeader());
    assertEquals(0, genesis.getHeight());

    // Build a new block.
    StoredBlock b1 = genesis.build(genesis.getHeader().createNextBlock(to).cloneAsHeader());
    store.put(b1);
    store.setChainHead(b1);
    store.close();

    // Check we can get it back out again if we rebuild the store object.
    store = new SPVBlockStore(UNITTEST, blockStoreFile);
    StoredBlock b2 = store.get(b1.getHeader().getHash());
    assertEquals(b1, b2);
    // Check the chain head was stored correctly also.
    StoredBlock chainHead = store.getChainHead();
    assertEquals(b1, chainHead);
}
 
Example 4
Source File: WalletTest.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void removeScriptsBloomFilter() throws Exception {
    List<Address> addressesForRemoval = new ArrayList<>();
    for (int i = 0; i < 10; i++) {
        Address watchedAddress = LegacyAddress.fromKey(UNITTEST, new ECKey());
        addressesForRemoval.add(watchedAddress);
        wallet.addWatchedAddress(watchedAddress);
    }

    wallet.removeWatchedAddresses(addressesForRemoval);

    for (Address addr : addressesForRemoval) {
        Transaction t1 = createFakeTx(UNITTEST, CENT, addr);
        TransactionOutPoint outPoint = new TransactionOutPoint(UNITTEST, 0, t1);

        // Note that this has a 1e-12 chance of failing this unit test due to a false positive
        assertFalse(wallet.getBloomFilter(1e-12).contains(outPoint.unsafeBitcoinSerialize()));

        sendMoneyToWallet(BlockChain.NewBlockType.BEST_CHAIN, t1);
        assertFalse(wallet.getBloomFilter(1e-12).contains(outPoint.unsafeBitcoinSerialize()));
    }
}
 
Example 5
Source File: WalletTest.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void watchingScriptsBloomFilter() throws Exception {
    assertFalse(wallet.isRequiringUpdateAllBloomFilter());

    Address watchedAddress = LegacyAddress.fromKey(UNITTEST, new ECKey());
    Transaction t1 = createFakeTx(UNITTEST, CENT, watchedAddress);
    TransactionOutPoint outPoint = new TransactionOutPoint(UNITTEST, 0, t1);
    wallet.addWatchedAddress(watchedAddress);

    assertTrue(wallet.isRequiringUpdateAllBloomFilter());
    // Note that this has a 1e-12 chance of failing this unit test due to a false positive
    assertFalse(wallet.getBloomFilter(1e-12).contains(outPoint.unsafeBitcoinSerialize()));

    sendMoneyToWallet(BlockChain.NewBlockType.BEST_CHAIN, t1);
    assertTrue(wallet.getBloomFilter(1e-12).contains(outPoint.unsafeBitcoinSerialize()));
}
 
Example 6
Source File: WalletTest.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void getWatchedAddresses() throws Exception {
    Address watchedAddress = LegacyAddress.fromKey(UNITTEST, new ECKey());
    wallet.addWatchedAddress(watchedAddress);
    List<Address> watchedAddresses = wallet.getWatchedAddresses();
    assertEquals(1, watchedAddresses.size());
    assertEquals(watchedAddress, watchedAddresses.get(0));
}
 
Example 7
Source File: FakeTxBuilder.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Creates two transactions that spend the same (fake) output. t1 spends to "to". t2 spends somewhere else.
 * The fake output goes to the same address as t2.
 */
public static DoubleSpends createFakeDoubleSpendTxns(NetworkParameters params, Address to) {
    DoubleSpends doubleSpends = new DoubleSpends();
    Coin value = COIN;
    Address someBadGuy = LegacyAddress.fromKey(params, new ECKey());

    doubleSpends.prevTx = new Transaction(params);
    TransactionOutput prevOut = new TransactionOutput(params, doubleSpends.prevTx, value, someBadGuy);
    doubleSpends.prevTx.addOutput(prevOut);

    doubleSpends.t1 = new Transaction(params);
    TransactionOutput o1 = new TransactionOutput(params, doubleSpends.t1, value, to);
    doubleSpends.t1.addOutput(o1);
    doubleSpends.t1.addInput(prevOut);

    doubleSpends.t2 = new Transaction(params);
    doubleSpends.t2.addInput(prevOut);
    TransactionOutput o2 = new TransactionOutput(params, doubleSpends.t2, value, someBadGuy);
    doubleSpends.t2.addOutput(o2);

    try {
        doubleSpends.t1 = params.getDefaultSerializer().makeTransaction(doubleSpends.t1.bitcoinSerialize());
        doubleSpends.t2 = params.getDefaultSerializer().makeTransaction(doubleSpends.t2.bitcoinSerialize());
    } catch (ProtocolException e) {
        throw new RuntimeException(e);
    }
    return doubleSpends;
}
 
Example 8
Source File: FakeTxBuilder.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Transaction[0] is a feeder transaction, supplying BTC to Transaction[1]
 */
public static Transaction[] createFakeTx(NetworkParameters params, Coin value,
                                         Address to, Address from) {
    // Create fake TXes of sufficient realism to exercise the unit tests. This transaction send BTC from the
    // from address, to the to address with to one to somewhere else to simulate change.
    Transaction t = new Transaction(params);
    TransactionOutput outputToMe = new TransactionOutput(params, t, value, to);
    t.addOutput(outputToMe);
    TransactionOutput change = new TransactionOutput(params, t, valueOf(1, 11), LegacyAddress.fromKey(params, new ECKey()));
    t.addOutput(change);
    // Make a feeder tx that sends to the from address specified. This feeder tx is not really valid but it doesn't
    // matter for our purposes.
    Transaction feederTx = new Transaction(params);
    TransactionOutput feederOut = new TransactionOutput(params, feederTx, value, from);
    feederTx.addOutput(feederOut);

    // make a previous tx that sends from the feeder to the from address
    Transaction prevTx = new Transaction(params);
    TransactionOutput prevOut = new TransactionOutput(params, prevTx, value, to);
    prevTx.addOutput(prevOut);

    // Connect up the txes
    prevTx.addInput(feederOut);
    t.addInput(prevOut);

    // roundtrip the tx so that they are just like they would be from the wire
    return new Transaction[]{roundTripTransaction(params, prevTx), roundTripTransaction(params, t)};
}
 
Example 9
Source File: FakeTxBuilder.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Create a fake coinbase transaction.
 */
public static Transaction createFakeCoinbaseTx(final NetworkParameters params) {
    TransactionOutPoint outpoint = new TransactionOutPoint(params, -1, Sha256Hash.ZERO_HASH);
    TransactionInput input = new TransactionInput(params, null, new byte[0], outpoint);
    Transaction tx = new Transaction(params);
    tx.addInput(input);
    TransactionOutput outputToMe = new TransactionOutput(params, tx, Coin.FIFTY_COINS,
            LegacyAddress.fromKey(params, new ECKey()));
    tx.addOutput(outputToMe);

    checkState(tx.isCoinBase());
    return tx;
}
 
Example 10
Source File: WalletTest.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void spendOutputFromPendingTransaction() throws Exception {
    // We'll set up a wallet that receives a coin, then sends a coin of lesser value and keeps the change.
    Coin v1 = COIN;
    sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, v1);
    // First create our current transaction
    ECKey k2 = wallet.freshReceiveKey();
    Coin v2 = valueOf(0, 50);
    Transaction t2 = new Transaction(UNITTEST);
    TransactionOutput o2 = new TransactionOutput(UNITTEST, t2, v2, LegacyAddress.fromKey(UNITTEST, k2));
    t2.addOutput(o2);
    SendRequest req = SendRequest.forTx(t2);
    wallet.completeTx(req);

    // Commit t2, so it is placed in the pending pool
    wallet.commitTx(t2);
    assertEquals(0, wallet.getPoolSize(WalletTransaction.Pool.UNSPENT));
    assertEquals(1, wallet.getPoolSize(WalletTransaction.Pool.PENDING));
    assertEquals(2, wallet.getTransactions(true).size());

    // Now try to the spend the output.
    ECKey k3 = new ECKey();
    Coin v3 = valueOf(0, 25);
    Transaction t3 = new Transaction(UNITTEST);
    t3.addOutput(v3, LegacyAddress.fromKey(UNITTEST, k3));
    t3.addInput(o2);
    wallet.signTransaction(SendRequest.forTx(t3));

    // Commit t3, so the coins from the pending t2 are spent
    wallet.commitTx(t3);
    assertEquals(0, wallet.getPoolSize(WalletTransaction.Pool.UNSPENT));
    assertEquals(2, wallet.getPoolSize(WalletTransaction.Pool.PENDING));
    assertEquals(3, wallet.getTransactions(true).size());

    // Now the output of t2 must not be available for spending
    assertFalse(o2.isAvailableForSpending());
}
 
Example 11
Source File: WalletTest.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void removeWatchedAddress() {
    Address watchedAddress = LegacyAddress.fromKey(UNITTEST, new ECKey());
    wallet.addWatchedAddress(watchedAddress);
    wallet.removeWatchedAddress(watchedAddress);
    assertFalse(wallet.isAddressWatched(watchedAddress));
    assertFalse(wallet.isRequiringUpdateAllBloomFilter());
}
 
Example 12
Source File: WalletTest.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void removeWatchedAddresses() {
    List<Address> addressesForRemoval = new ArrayList<>();
    for (int i = 0; i < 10; i++) {
        Address watchedAddress = LegacyAddress.fromKey(UNITTEST, new ECKey());
        addressesForRemoval.add(watchedAddress);
        wallet.addWatchedAddress(watchedAddress);
    }

    wallet.removeWatchedAddresses(addressesForRemoval);
    for (Address addr : addressesForRemoval)
        assertFalse(wallet.isAddressWatched(addr));

    assertFalse(wallet.isRequiringUpdateAllBloomFilter());
}
 
Example 13
Source File: KeyChainGroup.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns address for a {@link #currentKey(KeyChain.KeyPurpose)}
 */
public Address currentAddress(KeyChain.KeyPurpose purpose) {
    DeterministicKeyChain chain = getActiveKeyChain();
    if (chain.isMarried()) {
        Address current = currentAddresses.get(purpose);
        if (current == null) {
            current = freshAddress(purpose);
            currentAddresses.put(purpose, current);
        }
        return current;
    } else {
        return LegacyAddress.fromKey(params, currentKey(purpose));
    }
}
 
Example 14
Source File: WalletTest.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Test(expected = InsufficientMoneyException.class)
public void watchingScriptsConfirmed() throws Exception {
    Address watchedAddress = LegacyAddress.fromKey(UNITTEST, new ECKey());
    wallet.addWatchedAddress(watchedAddress);
    sendMoneyToWallet(BlockChain.NewBlockType.BEST_CHAIN, CENT, watchedAddress);
    assertEquals(CENT, wallet.getBalance());

    // We can't spend watched balances
    wallet.createSend(OTHER_ADDRESS, CENT);
}
 
Example 15
Source File: WalletTest.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void watchingScripts() throws Exception {
    // Verify that pending transactions to watched addresses are relevant
    Address watchedAddress = LegacyAddress.fromKey(UNITTEST, new ECKey());
    wallet.addWatchedAddress(watchedAddress);
    Coin value = valueOf(5, 0);
    Transaction t1 = createFakeTx(UNITTEST, value, watchedAddress);
    assertTrue(t1.getWalletOutputs(wallet).size() >= 1);
    assertTrue(wallet.isPendingTransactionRelevant(t1));
}
 
Example 16
Source File: WalletProtobufSerializerTest.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testKeys() throws Exception {
    for (int i = 0; i < 20; i++) {
        myKey = new ECKey();
        myAddress = LegacyAddress.fromKey(UNITTEST, myKey);
        myWallet = new Wallet(UNITTEST);
        myWallet.importKey(myKey);
        Wallet wallet1 = roundTrip(myWallet);
        assertArrayEquals(myKey.getPubKey(), wallet1.findKeyFromPubHash(myKey.getPubKeyHash()).getPubKey());
        assertArrayEquals(myKey.getPrivKeyBytes(), wallet1.findKeyFromPubHash(myKey.getPubKeyHash()).getPrivKeyBytes());
    }
}
 
Example 17
Source File: PaymentSessionTest.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Test(expected = PaymentProtocolException.InvalidNetwork.class)
public void testWrongNetwork() throws Exception {
    // Create a PaymentRequest and make sure the correct values are parsed by the PaymentSession.
    MockPaymentSession paymentSession = new MockPaymentSession(newSimplePaymentRequest("main"));
    assertEquals(MAINNET, paymentSession.getNetworkParameters());

    // Send the payment and verify that the correct information is sent.
    // Add a dummy input to tx so it is considered valid.
    tx.addInput(new TransactionInput(TESTNET, tx, outputToMe.getScriptBytes()));
    ArrayList<Transaction> txns = new ArrayList<>();
    txns.add(tx);
    Address refundAddr = LegacyAddress.fromKey(TESTNET, serverKey);
    paymentSession.sendPayment(txns, refundAddr, paymentMemo);
    assertEquals(1, paymentSession.getPaymentLog().size());
}
 
Example 18
Source File: PaymentSessionTest.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testSimplePayment() throws Exception {
    // Create a PaymentRequest and make sure the correct values are parsed by the PaymentSession.
    MockPaymentSession paymentSession = new MockPaymentSession(newSimplePaymentRequest("test"));
    assertEquals(paymentRequestMemo, paymentSession.getMemo());
    assertEquals(coin, paymentSession.getValue());
    assertEquals(simplePaymentUrl, paymentSession.getPaymentUrl());
    assertTrue(new Date(time * 1000L).equals(paymentSession.getDate()));
    assertTrue(paymentSession.getSendRequest().tx.equals(tx));
    assertFalse(paymentSession.isExpired());

    // Send the payment and verify that the correct information is sent.
    // Add a dummy input to tx so it is considered valid.
    tx.addInput(new TransactionInput(TESTNET, tx, outputToMe.getScriptBytes()));
    ArrayList<Transaction> txns = new ArrayList<>();
    txns.add(tx);
    Address refundAddr = LegacyAddress.fromKey(TESTNET, serverKey);
    paymentSession.sendPayment(txns, refundAddr, paymentMemo);
    assertEquals(1, paymentSession.getPaymentLog().size());
    assertEquals(simplePaymentUrl, paymentSession.getPaymentLog().get(0).getUrl().toString());
    Protos.Payment payment = paymentSession.getPaymentLog().get(0).getPayment();
    assertEquals(paymentMemo, payment.getMemo());
    assertEquals(merchantData, payment.getMerchantData());
    assertEquals(1, payment.getRefundToCount());
    assertEquals(coin.value, payment.getRefundTo(0).getAmount());
    TransactionOutput refundOutput = new TransactionOutput(TESTNET, null, coin, refundAddr);
    ByteString refundScript = ByteString.copyFrom(refundOutput.getScriptBytes());
    assertTrue(refundScript.equals(payment.getRefundTo(0).getScript()));
}
 
Example 19
Source File: Address.java    From balzac with Apache License 2.0 4 votes vote down vote up
public static Address fresh(NetworkType params) {
    LegacyAddress addr = LegacyAddress.fromKey(params.toNetworkParameters(), new ECKey());
    return new AddressImpl(addr.getHash(), params);
}
 
Example 20
Source File: Address.java    From balzac with Apache License 2.0 4 votes vote down vote up
public static Address fromPubkey(byte[] pubkey, NetworkType params) {
    LegacyAddress addr = LegacyAddress.fromKey(params.toNetworkParameters(), ECKey.fromPublicOnly(pubkey));
    return new AddressImpl(addr.getHash(), params);
}