@Test
  public void oneTx() throws Exception {
    // Check basic tx serialization.
    Coin v1 = COIN;
    Transaction t1 = createFakeTx(params, v1, myAddress);
    t1.getConfidence().markBroadcastBy(new PeerAddress(InetAddress.getByName("1.2.3.4")));
    t1.getConfidence().markBroadcastBy(new PeerAddress(InetAddress.getByName("5.6.7.8")));
    t1.getConfidence().setSource(TransactionConfidence.Source.NETWORK);
    myWallet.receivePending(t1, null);
    Wallet wallet1 = roundTrip(myWallet);
    assertEquals(1, wallet1.getTransactions(true).size());
    assertEquals(v1, wallet1.getBalance(Wallet.BalanceType.ESTIMATED));
    Transaction t1copy = wallet1.getTransaction(t1.getHash());
    assertArrayEquals(t1.bitcoinSerialize(), t1copy.bitcoinSerialize());
    assertEquals(2, t1copy.getConfidence().numBroadcastPeers());
    assertEquals(TransactionConfidence.Source.NETWORK, t1copy.getConfidence().getSource());

    Protos.Wallet walletProto = new WalletProtobufSerializer().walletToProto(myWallet);
    assertEquals(Protos.Key.Type.ORIGINAL, walletProto.getKey(0).getType());
    assertEquals(0, walletProto.getExtensionCount());
    assertEquals(1, walletProto.getTransactionCount());
    assertEquals(6, walletProto.getKeyCount());

    Protos.Transaction t1p = walletProto.getTransaction(0);
    assertEquals(0, t1p.getBlockHashCount());
    assertArrayEquals(t1.getHash().getBytes(), t1p.getHash().toByteArray());
    assertEquals(Protos.Transaction.Pool.PENDING, t1p.getPool());
    assertFalse(t1p.hasLockTime());
    assertFalse(t1p.getTransactionInput(0).hasSequence());
    assertArrayEquals(
        t1.getInputs().get(0).getOutpoint().getHash().getBytes(),
        t1p.getTransactionInput(0).getTransactionOutPointHash().toByteArray());
    assertEquals(0, t1p.getTransactionInput(0).getTransactionOutPointIndex());
    assertEquals(t1p.getTransactionOutput(0).getValue(), v1.value);
  }
Exemple #2
0
  @Test
  public void testReceiveCoinbaseTransaction() throws Exception {
    // Block 169482 (hash 0000000000000756935f1ee9d5987857b604046f846d3df56d024cdb5f368665)
    // contains coinbase transactions that are mining pool shares.
    // The private key MINERS_KEY is used to check transactions are received by a wallet correctly.

    // The address for this private key is 1GqtGtn4fctXuKxsVzRPSLmYWN1YioLi9y.
    final String MINING_PRIVATE_KEY = "5JDxPrBRghF1EvSBjDigywqfmAjpHPmTJxYtQTYJxJRHLLQA4mG";

    final long BLOCK_NONCE = 3973947400L;
    final Coin BALANCE_AFTER_BLOCK = Coin.valueOf(22223642);
    final NetworkParameters PARAMS = MainNetParams.get();

    Block block169482 =
        PARAMS
            .getDefaultSerializer()
            .makeBlock(ByteStreams.toByteArray(getClass().getResourceAsStream("block169482.dat")));

    // Check block.
    assertNotNull(block169482);
    block169482.verify(169482, EnumSet.noneOf(Block.VerifyFlag.class));
    assertEquals(BLOCK_NONCE, block169482.getNonce());

    StoredBlock storedBlock =
        new StoredBlock(block169482, BigInteger.ONE, 169482); // Nonsense work - not used in test.

    // Create a wallet contain the miner's key that receives a spend from a coinbase.
    ECKey miningKey = DumpedPrivateKey.fromBase58(PARAMS, MINING_PRIVATE_KEY).getKey();
    assertNotNull(miningKey);
    Context context = new Context(PARAMS);
    Wallet wallet = new Wallet(context);
    wallet.importKey(miningKey);

    // Initial balance should be zero by construction.
    assertEquals(Coin.ZERO, wallet.getBalance());

    // Give the wallet the first transaction in the block - this is the coinbase tx.
    List<Transaction> transactions = block169482.getTransactions();
    assertNotNull(transactions);
    wallet.receiveFromBlock(transactions.get(0), storedBlock, NewBlockType.BEST_CHAIN, 0);

    // Coinbase transaction should have been received successfully but be unavailable to spend (too
    // young).
    assertEquals(BALANCE_AFTER_BLOCK, wallet.getBalance(BalanceType.ESTIMATED));
    assertEquals(Coin.ZERO, wallet.getBalance(BalanceType.AVAILABLE));
  }
 @Test
 public void testRoundTripNormalWallet() throws Exception {
   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());
 }
  @Test
  public void doubleSpend() throws Exception {
    // Check that we can serialize double spends correctly, as this is a slightly tricky case.
    FakeTxBuilder.DoubleSpends doubleSpends =
        FakeTxBuilder.createFakeDoubleSpendTxns(params, myAddress);
    // t1 spends to our wallet.
    myWallet.receivePending(doubleSpends.t1, null);
    // t2 rolls back t1 and spends somewhere else.
    myWallet.receiveFromBlock(doubleSpends.t2, null, BlockChain.NewBlockType.BEST_CHAIN, 0);
    Wallet wallet1 = roundTrip(myWallet);
    assertEquals(1, wallet1.getTransactions(true).size());
    Transaction t1 = wallet1.getTransaction(doubleSpends.t1.getHash());
    assertEquals(ConfidenceType.DEAD, t1.getConfidence().getConfidenceType());
    assertEquals(Coin.ZERO, wallet1.getBalance());

    // TODO: Wallet should store overriding transactions even if they are not wallet-relevant.
    // assertEquals(doubleSpends.t2, t1.getConfidence().getOverridingTransaction());
  }
 @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(myWatchedKey.toAddress(params)),
       wallet1.getWatchedScripts().get(0));
   assertEquals(WALLET_DESCRIPTION, wallet1.getDescription());
 }
  @Test
  public void testRoundTripMarriedWallet() throws Exception {
    // create 2-of-2 married wallet
    myWallet = new Wallet(params);
    final DeterministicKeyChain partnerChain = new DeterministicKeyChain(new SecureRandom());
    DeterministicKey partnerKey =
        DeterministicKey.deserializeB58(
            null, partnerChain.getWatchingKey().serializePubB58(params), params);
    MarriedKeyChain chain =
        MarriedKeyChain.builder()
            .random(new SecureRandom())
            .followingKeys(partnerKey)
            .threshold(2)
            .build();
    myWallet.addAndActivateHDChain(chain);

    myAddress = myWallet.currentAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS);

    Wallet wallet1 = roundTrip(myWallet);
    assertEquals(0, wallet1.getTransactions(true).size());
    assertEquals(Coin.ZERO, wallet1.getBalance());
    assertEquals(2, wallet1.getActiveKeyChain().getSigsRequiredToSpend());
    assertEquals(myAddress, wallet1.currentAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS));
  }
  @Test
  public void testUTXOProviderWithWallet() throws Exception {
    final int UNDOABLE_BLOCKS_STORED = 10;
    store = createStore(params, UNDOABLE_BLOCKS_STORED);
    chain = new FullPrunedBlockChain(params, store);

    // Check that we aren't accidentally leaving any references
    // to the full StoredUndoableBlock's lying around (ie memory leaks)
    ECKey outKey = new ECKey();
    int height = 1;

    // Build some blocks on genesis block to create a spendable output.
    Block rollingBlock =
        params
            .getGenesisBlock()
            .createNextBlockWithCoinbase(Block.BLOCK_VERSION_GENESIS, outKey.getPubKey(), height++);
    chain.add(rollingBlock);
    Transaction transaction = rollingBlock.getTransactions().get(0);
    TransactionOutPoint spendableOutput = new TransactionOutPoint(params, 0, transaction.getHash());
    byte[] spendableOutputScriptPubKey = transaction.getOutputs().get(0).getScriptBytes();
    for (int i = 1; i < params.getSpendableCoinbaseDepth(); i++) {
      rollingBlock =
          rollingBlock.createNextBlockWithCoinbase(
              Block.BLOCK_VERSION_GENESIS, outKey.getPubKey(), height++);
      chain.add(rollingBlock);
    }
    rollingBlock = rollingBlock.createNextBlock(null);

    // Create 1 BTC spend to a key in this wallet (to ourselves).
    Wallet wallet = new Wallet(params);
    assertEquals(
        "Available balance is incorrect",
        Coin.ZERO,
        wallet.getBalance(Wallet.BalanceType.AVAILABLE));
    assertEquals(
        "Estimated balance is incorrect",
        Coin.ZERO,
        wallet.getBalance(Wallet.BalanceType.ESTIMATED));

    wallet.setUTXOProvider(store);
    ECKey toKey = wallet.freshReceiveKey();
    Coin amount = Coin.valueOf(100000000);

    Transaction t = new Transaction(params);
    t.addOutput(new TransactionOutput(params, t, amount, toKey));
    t.addSignedInput(spendableOutput, new Script(spendableOutputScriptPubKey), outKey);
    rollingBlock.addTransaction(t);
    rollingBlock.solve();
    chain.add(rollingBlock);

    // Create another spend of 1/2 the value of BTC we have available using the wallet (store coin
    // selector).
    ECKey toKey2 = new ECKey();
    Coin amount2 = amount.divide(2);
    Address address2 = new Address(params, toKey2.getPubKeyHash());
    Wallet.SendRequest req = Wallet.SendRequest.to(address2, amount2);
    wallet.completeTx(req);
    wallet.commitTx(req.tx);
    Coin fee = req.fee;

    // There should be one pending tx (our spend).
    assertEquals(
        "Wrong number of PENDING.4", 1, wallet.getPoolSize(WalletTransaction.Pool.PENDING));
    Coin totalPendingTxAmount = Coin.ZERO;
    for (Transaction tx : wallet.getPendingTransactions()) {
      totalPendingTxAmount = totalPendingTxAmount.add(tx.getValueSentToMe(wallet));
    }

    // The availbale balance should be the 0 (as we spent the 1 BTC that's pending) and estimated
    // should be 1/2 - fee BTC
    assertEquals(
        "Available balance is incorrect",
        Coin.ZERO,
        wallet.getBalance(Wallet.BalanceType.AVAILABLE));
    assertEquals(
        "Estimated balance is incorrect",
        amount2.subtract(fee),
        wallet.getBalance(Wallet.BalanceType.ESTIMATED));
    assertEquals("Pending tx amount is incorrect", amount2.subtract(fee), totalPendingTxAmount);
    try {
      store.close();
    } catch (Exception e) {
    }
  }