org.bitcoinj.core.LegacyAddress Java Examples

The following examples show how to use org.bitcoinj.core.LegacyAddress. 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: DeterministicKeyChainTest.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void deriveAccountOne() throws Exception {
    long secs = 1389353062L;
    DeterministicKeyChain chain1 = new AccountOneChain(ENTROPY, "", secs);
    ECKey key1 = chain1.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
    ECKey key2 = chain1.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);

    final Address address = LegacyAddress.fromBase58(UNITTEST, "n2nHHRHs7TiZScTuVhZUkzZfTfVgGYwy6X");
    assertEquals(address, LegacyAddress.fromKey(UNITTEST, key1));
    assertEquals("mnp2j9za5zMuz44vNxrJCXXhZsCdh89QXn", LegacyAddress.fromKey(UNITTEST, key2).toString());
    assertEquals(key1, chain1.findKeyFromPubHash(address.getHash()));
    assertEquals(key2, chain1.findKeyFromPubKey(key2.getPubKey()));

    key1.sign(Sha256Hash.ZERO_HASH);

    ECKey key3 = chain1.getKey(KeyChain.KeyPurpose.CHANGE);
    assertEquals("mpjRhk13rvV7vmnszcUQVYVQzy4HLTPTQU", LegacyAddress.fromKey(UNITTEST, key3).toString());
    key3.sign(Sha256Hash.ZERO_HASH);
}
 
Example #2
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 #3
Source File: ScriptPattern.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns true if this script is of the form {@code DUP HASH160 <pubkey hash> EQUALVERIFY CHECKSIG}, ie, payment to an
 * address like {@code 1VayNert3x1KzbpzMGt2qdqrAThiRovi8}. This form was originally intended for the case where you wish
 * to send somebody money with a written code because their node is offline, but over time has become the standard
 * way to make payments due to the short and recognizable base58 form addresses come in.
 */
public static boolean isPayToPubKeyHash(Script script) {
    List<ScriptChunk> chunks = script.chunks;
    if (chunks.size() != 5)
        return false;
    if (!chunks.get(0).equalsOpCode(OP_DUP))
        return false;
    if (!chunks.get(1).equalsOpCode(OP_HASH160))
        return false;
    byte[] chunk2data = chunks.get(2).data;
    if (chunk2data == null)
        return false;
    if (chunk2data.length != LegacyAddress.LENGTH)
        return false;
    if (!chunks.get(3).equalsOpCode(OP_EQUALVERIFY))
        return false;
    if (!chunks.get(4).equalsOpCode(OP_CHECKSIG))
        return false;
    return true;
}
 
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 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 #5
Source File: WalletTest.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void watchingScriptsSentFrom() throws Exception {
    int baseElements = wallet.getBloomFilterElementCount();

    Address watchedAddress = LegacyAddress.fromKey(UNITTEST, new ECKey());
    wallet.addWatchedAddress(watchedAddress);
    assertEquals(baseElements + 1, wallet.getBloomFilterElementCount());

    Transaction t1 = createFakeTx(UNITTEST, CENT, watchedAddress);
    Transaction t2 = createFakeTx(UNITTEST, COIN, OTHER_ADDRESS);
    sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, t1);
    assertEquals(baseElements + 2, wallet.getBloomFilterElementCount());
    Transaction st2 = new Transaction(UNITTEST);
    st2.addOutput(CENT, OTHER_ADDRESS);
    st2.addOutput(COIN, OTHER_ADDRESS);
    st2.addInput(t1.getOutput(0));
    st2.addInput(t2.getOutput(0));
    sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, st2);
    assertEquals(baseElements + 2, wallet.getBloomFilterElementCount());
    assertEquals(CENT, st2.getValueSentFromMe(wallet));
}
 
Example #6
Source File: WalletTest.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void keyRotationHD() throws Exception {
    // Test that if we rotate an HD chain, a new one is created and all arrivals on the old keys are moved.
    Utils.setMockClock();
    wallet = new Wallet(UNITTEST);
    ECKey key1 = wallet.freshReceiveKey();
    ECKey key2 = wallet.freshReceiveKey();
    sendMoneyToWallet(wallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, LegacyAddress.fromKey(UNITTEST, key1));
    sendMoneyToWallet(wallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, LegacyAddress.fromKey(UNITTEST, key2));
    DeterministicKey watchKey1 = wallet.getWatchingKey();

    // A day later, we get compromised.
    Utils.rollMockClock(86400);
    wallet.setKeyRotationTime(Utils.currentTimeSeconds());

    List<Transaction> txns = wallet.doMaintenance(null, false).get();
    assertEquals(1, txns.size());
    DeterministicKey watchKey2 = wallet.getWatchingKey();
    assertNotEquals(watchKey1, watchKey2);
}
 
Example #7
Source File: WalletTest.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void doubleSpendUnspendsOtherInputs() throws Exception {
    // Test another Finney attack, but this time the killed transaction was also spending some other outputs in
    // our wallet which were not themselves double spent. This test ensures the death of the pending transaction
    // frees up the other outputs and makes them spendable again.

    // Receive 1 coin and then 2 coins in separate transactions.
    sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, COIN);
    sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, valueOf(2, 0));
    // Create a send to a merchant of all our coins.
    Transaction send1 = wallet.createSend(OTHER_ADDRESS, valueOf(2, 90));
    // Create a double spend of just the first one.
    Address BAD_GUY = LegacyAddress.fromKey(UNITTEST, new ECKey());
    Transaction send2 = wallet.createSend(BAD_GUY, COIN);
    send2 = UNITTEST.getDefaultSerializer().makeTransaction(send2.bitcoinSerialize());
    // Broadcast send1, it's now pending.
    wallet.commitTx(send1);
    assertEquals(ZERO, wallet.getBalance()); // change of 10 cents is not yet mined so not included in the balance.
    // Receive a block that overrides the send1 using send2.
    sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, send2);
    // send1 got rolled back and replaced with a smaller send that only used one of our received coins, thus ...
    assertEquals(valueOf(2, 0), wallet.getBalance());
    assertTrue(wallet.isConsistent());
}
 
Example #8
Source File: DeterministicKeyChainTest.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void derive() throws Exception {
    ECKey key1 = chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
    assertFalse(key1.isPubKeyOnly());
    ECKey key2 = chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
    assertFalse(key2.isPubKeyOnly());

    final Address address = LegacyAddress.fromBase58(UNITTEST, "n1bQNoEx8uhmCzzA5JPG6sFdtsUQhwiQJV");
    assertEquals(address, LegacyAddress.fromKey(UNITTEST, key1));
    assertEquals("mnHUcqUVvrfi5kAaXJDQzBb9HsWs78b42R", LegacyAddress.fromKey(UNITTEST, key2).toString());
    assertEquals(key1, chain.findKeyFromPubHash(address.getHash()));
    assertEquals(key2, chain.findKeyFromPubKey(key2.getPubKey()));

    key1.sign(Sha256Hash.ZERO_HASH);
    assertFalse(key1.isPubKeyOnly());

    ECKey key3 = chain.getKey(KeyChain.KeyPurpose.CHANGE);
    assertFalse(key3.isPubKeyOnly());
    assertEquals("mqumHgVDqNzuXNrszBmi7A2UpmwaPMx4HQ", LegacyAddress.fromKey(UNITTEST, key3).toString());
    key3.sign(Sha256Hash.ZERO_HASH);
    assertFalse(key3.isPubKeyOnly());
}
 
Example #9
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 #10
Source File: ScriptPattern.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * <p>
 * Whether or not this is a scriptPubKey representing a P2SH output. In such outputs, the logic that
 * controls reclamation is not actually in the output at all. Instead there's just a hash, and it's up to the
 * spending input to provide a program matching that hash.
 * </p>
 * <p>
 * P2SH is described by <a href="https://github.com/bitcoin/bips/blob/master/bip-0016.mediawiki">BIP16</a>.
 * </p>
 */
public static boolean isPayToScriptHash(Script script) {
    List<ScriptChunk> chunks = script.chunks;
    // We check for the effective serialized form because BIP16 defines a P2SH output using an exact byte
    // template, not the logical program structure. Thus you can have two programs that look identical when
    // printed out but one is a P2SH script and the other isn't! :(
    // We explicitly test that the op code used to load the 20 bytes is 0x14 and not something logically
    // equivalent like {@code OP_HASH160 OP_PUSHDATA1 0x14 <20 bytes of script hash> OP_EQUAL}
    if (chunks.size() != 3)
        return false;
    if (!chunks.get(0).equalsOpCode(OP_HASH160))
        return false;
    ScriptChunk chunk1 = chunks.get(1);
    if (chunk1.opcode != 0x14)
        return false;
    byte[] chunk1data = chunk1.data;
    if (chunk1data == null)
        return false;
    if (chunk1data.length != LegacyAddress.LENGTH)
        return false;
    if (!chunks.get(2).equalsOpCode(OP_EQUAL))
        return false;
    return true;
}
 
Example #11
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 #12
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 #13
Source File: WalletProtobufSerializerTest.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void empty() throws Exception {
    // Check the base case of a wallet with one key and no transactions.
    Wallet wallet1 = roundTrip(myWallet);
    assertEquals(0, wallet1.getTransactions(true).size());
    assertEquals(Coin.ZERO, wallet1.getBalance());
    assertArrayEquals(myKey.getPubKey(),
            wallet1.findKeyFromPubHash(myKey.getPubKeyHash()).getPubKey());
    assertArrayEquals(myKey.getPrivKeyBytes(),
            wallet1.findKeyFromPubHash(myKey.getPubKeyHash()).getPrivKeyBytes());
    assertEquals(myKey.getCreationTimeSeconds(),
            wallet1.findKeyFromPubHash(myKey.getPubKeyHash()).getCreationTimeSeconds());
    assertEquals(mScriptCreationTime,
            wallet1.getWatchedScripts().get(0).getCreationTimeSeconds());
    assertEquals(1, wallet1.getWatchedScripts().size());
    assertEquals(ScriptBuilder.createOutputScript(LegacyAddress.fromKey(UNITTEST, myWatchedKey)),
            wallet1.getWatchedScripts().get(0));
    assertEquals(WALLET_DESCRIPTION, wallet1.getDescription());
}
 
Example #14
Source File: LevelDBBlockStoreTest.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void basics() throws Exception {
    File f = File.createTempFile("leveldbblockstore", null);
    f.delete();

    Context context = new Context(UNITTEST);
    LevelDBBlockStore store = new LevelDBBlockStore(context, f);
    store.reset();

    // 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.
    Address to = LegacyAddress.fromBase58(UNITTEST, "mrj2K6txjo2QBcSmuAzHj4nD1oXSEJE1Qo");
    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 LevelDBBlockStore(context, f);
    try {
        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);
    } finally {
        store.close();
        store.destroy();
    }
}
 
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 importAndEncrypt() throws InsufficientMoneyException {
    Wallet encryptedWallet = new Wallet(UNITTEST);
    encryptedWallet.encrypt(PASSWORD1);

    final ECKey key = new ECKey();
    encryptedWallet.importKeysAndEncrypt(ImmutableList.of(key), PASSWORD1);
    assertEquals(1, encryptedWallet.getImportedKeys().size());
    assertEquals(key.getPubKeyPoint(), encryptedWallet.getImportedKeys().get(0).getPubKeyPoint());
    sendMoneyToWallet(encryptedWallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, Coin.COIN, LegacyAddress.fromKey(UNITTEST, key));
    assertEquals(Coin.COIN, encryptedWallet.getBalance());
    SendRequest req = SendRequest.emptyWallet(OTHER_ADDRESS);
    req.aesKey = checkNotNull(encryptedWallet.getKeyCrypter()).deriveKey(PASSWORD1);
    encryptedWallet.sendCoinsOffline(req);
}
 
Example #16
Source File: WalletTest.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Test(expected = Wallet.ExceededMaxTransactionSize.class)
public void respectMaxStandardSize() throws Exception {
    // Check that we won't create txns > 100kb. Average tx size is ~220 bytes so this would have to be enormous.
    sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, valueOf(100, 0));
    Transaction tx = new Transaction(UNITTEST);
    byte[] bits = new byte[20];
    new Random().nextBytes(bits);
    Coin v = CENT;
    // 3100 outputs to a random address.
    for (int i = 0; i < 3100; i++) {
        tx.addOutput(v, LegacyAddress.fromPubKeyHash(UNITTEST, bits));
    }
    SendRequest req = SendRequest.forTx(tx);
    wallet.completeTx(req);
}
 
Example #17
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 #18
Source File: WalletTest.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
public void fragmentedReKeying() throws Exception {
    // Send lots of small coins and check the fee is correct.
    ECKey key = wallet.freshReceiveKey();
    Address address = LegacyAddress.fromKey(UNITTEST, key);
    Utils.setMockClock();
    Utils.rollMockClock(86400);
    for (int i = 0; i < 800; i++) {
        sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, address);
    }

    MockTransactionBroadcaster broadcaster = new MockTransactionBroadcaster(wallet);

    Date compromise = Utils.now();
    Utils.rollMockClock(86400);
    wallet.freshReceiveKey();
    wallet.setKeyRotationTime(compromise);
    wallet.doMaintenance(null, true);

    Transaction tx = broadcaster.waitForTransactionAndSucceed();
    final Coin valueSentToMe = tx.getValueSentToMe(wallet);
    Coin fee = tx.getValueSentFromMe(wallet).subtract(valueSentToMe);
    assertEquals(Coin.valueOf(900000), fee);
    assertEquals(KeyTimeCoinSelector.MAX_SIMULTANEOUS_INPUTS, tx.getInputs().size());
    assertEquals(Coin.valueOf(599100000), valueSentToMe);

    tx = broadcaster.waitForTransaction();
    assertNotNull(tx);
    assertEquals(200, tx.getInputs().size());
}
 
Example #19
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 #20
Source File: WalletTest.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("ConstantConditions")
public void completeTxPartiallySigned(Wallet.MissingSigsMode missSigMode, byte[] expectedSig) throws Exception {
    // Check the wallet will write dummy scriptSigs for inputs that we have only pubkeys for without the privkey.
    ECKey priv = new ECKey();
    ECKey pub = ECKey.fromPublicOnly(priv.getPubKeyPoint());
    wallet.importKey(pub);
    ECKey priv2 = wallet.freshReceiveKey();
    // Send three transactions, with one being an address type and the other being a raw CHECKSIG type pubkey only,
    // and the final one being a key we do have. We expect the first two inputs to be dummy values and the last
    // to be signed correctly.
    Transaction t1 = sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, LegacyAddress.fromKey(UNITTEST, pub));
    Transaction t2 = sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, pub);
    Transaction t3 = sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, priv2);

    SendRequest req = SendRequest.emptyWallet(OTHER_ADDRESS);
    req.missingSigsMode = missSigMode;
    wallet.completeTx(req);
    byte[] dummySig = TransactionSignature.dummy().encodeToBitcoin();
    // Selected inputs can be in any order.
    for (int i = 0; i < req.tx.getInputs().size(); i++) {
        TransactionInput input = req.tx.getInput(i);
        if (input.getConnectedOutput().getParentTransaction().equals(t1)) {
            assertArrayEquals(expectedSig, input.getScriptSig().getChunks().get(0).data);
        } else if (input.getConnectedOutput().getParentTransaction().equals(t2)) {
            assertArrayEquals(expectedSig, input.getScriptSig().getChunks().get(0).data);
        } else if (input.getConnectedOutput().getParentTransaction().equals(t3)) {
            input.getScriptSig().correctlySpends(req.tx, i, t3.getOutput(0).getScriptPubKey());
        }
    }
    assertTrue(TransactionSignature.isEncodingCanonical(dummySig));
}
 
Example #21
Source File: FakeTxBuilder.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Create a fake transaction, without change.
 */
public static Transaction createFakeTxWithoutChange(final NetworkParameters params, final TransactionOutput output) {
    Transaction prevTx = FakeTxBuilder.createFakeTx(params, Coin.COIN, LegacyAddress.fromKey(params, new ECKey()));
    Transaction tx = new Transaction(params);
    tx.addOutput(output);
    tx.addInput(prevTx.getOutput(0));
    return tx;
}
 
Example #22
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 #23
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 #24
Source File: TestWithWallet.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
public void setUp() throws Exception {
    BriefLogFormatter.init();
    Context.propagate(new Context(UNITTEST, 100, Coin.ZERO, false));
    wallet = new Wallet(UNITTEST);
    myKey = wallet.currentReceiveKey();
    myAddress = LegacyAddress.fromKey(UNITTEST, myKey);
    blockStore = new MemoryBlockStore(UNITTEST);
    chain = new BlockChain(UNITTEST, wallet, blockStore);
}
 
Example #25
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 #26
Source File: FakeTxBuilder.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
public static Block makeSolvedTestBlock(Block prev, Transaction... transactions) throws BlockStoreException {
    Address to = LegacyAddress.fromKey(prev.getParams(), new ECKey());
    Block b = prev.createNextBlock(to);
    // Coinbase tx already exists.
    for (Transaction tx : transactions) {
        b.addTransaction(tx);
    }
    b.solve();
    return b;
}
 
Example #27
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 #28
Source File: ScriptBuilder.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Creates a scriptPubKey that encodes payment to the given address.
 */
public static Script createOutputScript(Address to) {
    ScriptBuilder builder = new ScriptBuilder();
    if (to instanceof LegacyAddress) {
        ScriptType scriptType = to.getOutputScriptType();
        if (scriptType == ScriptType.P2PKH) {
            // OP_DUP OP_HASH160 <pubKeyHash> OP_EQUALVERIFY OP_CHECKSIG
            builder.op(OP_DUP);
            builder.op(OP_HASH160);
            builder.data(to.getHash());
            builder.op(OP_EQUALVERIFY);
            builder.op(OP_CHECKSIG);
        } else if (scriptType == ScriptType.P2SH) {
            // OP_HASH160 <scriptHash> OP_EQUAL
            builder.op(OP_HASH160);
            builder.data(to.getHash());
            builder.op(OP_EQUAL);
        } else {
            throw new IllegalStateException("Cannot handle " + scriptType);
        }
    } else if (to instanceof SegwitAddress) {
        // OP_0 <pubKeyHash|scriptHash>
        SegwitAddress toSegwit = (SegwitAddress) to;
        builder.smallNum(toSegwit.getWitnessVersion());
        builder.data(toSegwit.getWitnessProgram());
    } else {
        throw new IllegalStateException("Cannot handle " + to);
    }
    return builder.build();
}
 
Example #29
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 #30
Source File: KeyChainGroup.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
public void markP2SHAddressAsUsed(LegacyAddress address) {
    checkArgument(address.getOutputScriptType() == ScriptType.P2SH);
    RedeemData data = findRedeemDataFromScriptHash(address.getHash());
    if (data == null)
        return;   // Not our P2SH address.
    for (ECKey key : data.keys) {
        for (DeterministicKeyChain chain : chains) {
            DeterministicKey k = chain.findKeyFromPubKey(key.getPubKey());
            if (k == null)
                continue;
            chain.markKeyAsUsed(k);
            maybeMarkCurrentAddressAsUsed(address);
        }
    }
}