Java Code Examples for org.bitcoinj.core.ECKey#toAddress()

The following examples show how to use org.bitcoinj.core.ECKey#toAddress() . 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: WalletTest.java    From green_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(PARAMS);
    TransactionOutput o2 = new TransactionOutput(PARAMS, t2, v2, k2.toAddress(PARAMS));
    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(PARAMS);
    t3.addOutput(v3, k3.toAddress(PARAMS));
    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 2
Source File: WalletTest.java    From green_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 = key.toAddress(PARAMS);
    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 3
Source File: WalletTest.java    From GreenBits 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(PARAMS);
    TransactionOutput o2 = new TransactionOutput(PARAMS, t2, v2, k2.toAddress(PARAMS));
    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(PARAMS);
    t3.addOutput(v3, k3.toAddress(PARAMS));
    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 4
Source File: WalletTest.java    From GreenBits 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 = key.toAddress(PARAMS);
    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 5
Source File: GenerateLowSTests.java    From green_android with GNU General Public License v3.0 4 votes vote down vote up
public static void main(final String[] argv) throws NoSuchAlgorithmException, IOException {
    final NetworkParameters params = new MainNetParams();
    final LocalTransactionSigner signer = new LocalTransactionSigner();
    final SecureRandom secureRandom = SecureRandom.getInstanceStrong();
    final ECKey key = new ECKey(secureRandom);
    final KeyBag bag = new KeyBag() {
        @Override
        public ECKey findKeyFromPubHash(byte[] pubkeyHash) {
            return key;
        }

        @Override
        public ECKey findKeyFromPubKey(byte[] pubkey) {
            return key;
        }

        @Override
        public RedeemData findRedeemDataFromScriptHash(byte[] scriptHash) {
            return null;
        }

    };

    // Generate a fictional output transaction we take values from, and
    // an input transaction for the test case

    final Transaction outputTransaction = new Transaction(params);
    final Transaction inputTransaction = new Transaction(params);
    final TransactionOutput output = new TransactionOutput(params, inputTransaction, Coin.ZERO, key.toAddress(params));

    inputTransaction.addOutput(output);
    outputTransaction.addInput(output);
    outputTransaction.addOutput(Coin.ZERO, new ECKey(secureRandom).toAddress(params));

    addOutputs(outputTransaction, bag);

    // Sign the transaction
    final ProposedTransaction proposedTransaction = new ProposedTransaction(outputTransaction);
    signer.signInputs(proposedTransaction, bag);
    final TransactionInput input = proposedTransaction.partialTx.getInput(0);

    input.verify(output);
    input.getScriptSig().correctlySpends(outputTransaction, 0, output.getScriptPubKey(),
        EnumSet.of(Script.VerifyFlag.DERSIG, Script.VerifyFlag.P2SH));

    final Script scriptSig = input.getScriptSig();
    final TransactionSignature signature = TransactionSignature.decodeFromBitcoin(scriptSig.getChunks().get(0).data, true, false);

    // First output a conventional low-S transaction with the LOW_S flag, for the tx_valid.json set
    System.out.println("[\"A transaction with a low-S signature.\"],");
    System.out.println("[[[\""
        + inputTransaction.getHashAsString() + "\", "
        + output.getIndex() + ", \""
        + scriptToString(output.getScriptPubKey()) + "\"]],\n"
        + "\"" + Utils.HEX.encode(proposedTransaction.partialTx.unsafeBitcoinSerialize()) + "\", \""
        + Script.VerifyFlag.P2SH.name() + "," + Script.VerifyFlag.LOW_S.name() + "\"],");

    final BigInteger highS = HIGH_S_DIFFERENCE.subtract(signature.s);
    final TransactionSignature highSig = new TransactionSignature(signature.r, highS);
    input.setScriptSig(new ScriptBuilder().data(highSig.encodeToBitcoin()).data(scriptSig.getChunks().get(1).data).build());
    input.getScriptSig().correctlySpends(outputTransaction, 0, output.getScriptPubKey(),
        EnumSet.of(Script.VerifyFlag.P2SH));

    // A high-S transaction without the LOW_S flag, for the tx_valid.json set
    System.out.println("[\"A transaction with a high-S signature.\"],");
    System.out.println("[[[\""
        + inputTransaction.getHashAsString() + "\", "
        + output.getIndex() + ", \""
        + scriptToString(output.getScriptPubKey()) + "\"]],\n"
        + "\"" + Utils.HEX.encode(proposedTransaction.partialTx.unsafeBitcoinSerialize()) + "\", \""
        + Script.VerifyFlag.P2SH.name() + "\"],");

    // Lastly a conventional high-S transaction with the LOW_S flag, for the tx_invalid.json set
    System.out.println("[\"A transaction with a high-S signature.\"],");
    System.out.println("[[[\""
        + inputTransaction.getHashAsString() + "\", "
        + output.getIndex() + ", \""
        + scriptToString(output.getScriptPubKey()) + "\"]],\n"
        + "\"" + Utils.HEX.encode(proposedTransaction.partialTx.unsafeBitcoinSerialize()) + "\", \""
        + Script.VerifyFlag.P2SH.name() + "," + Script.VerifyFlag.LOW_S.name() + "\"],");
}
 
Example 6
Source File: GenerateLowSTests.java    From GreenBits with GNU General Public License v3.0 4 votes vote down vote up
public static void main(final String[] argv) throws NoSuchAlgorithmException, IOException {
    final NetworkParameters params = new MainNetParams();
    final LocalTransactionSigner signer = new LocalTransactionSigner();
    final SecureRandom secureRandom = SecureRandom.getInstanceStrong();
    final ECKey key = new ECKey(secureRandom);
    final KeyBag bag = new KeyBag() {
        @Override
        public ECKey findKeyFromPubHash(byte[] pubkeyHash) {
            return key;
        }

        @Override
        public ECKey findKeyFromPubKey(byte[] pubkey) {
            return key;
        }

        @Override
        public RedeemData findRedeemDataFromScriptHash(byte[] scriptHash) {
            return null;
        }

    };

    // Generate a fictional output transaction we take values from, and
    // an input transaction for the test case

    final Transaction outputTransaction = new Transaction(params);
    final Transaction inputTransaction = new Transaction(params);
    final TransactionOutput output = new TransactionOutput(params, inputTransaction, Coin.ZERO, key.toAddress(params));

    inputTransaction.addOutput(output);
    outputTransaction.addInput(output);
    outputTransaction.addOutput(Coin.ZERO, new ECKey(secureRandom).toAddress(params));

    addOutputs(outputTransaction, bag);

    // Sign the transaction
    final ProposedTransaction proposedTransaction = new ProposedTransaction(outputTransaction);
    signer.signInputs(proposedTransaction, bag);
    final TransactionInput input = proposedTransaction.partialTx.getInput(0);

    input.verify(output);
    input.getScriptSig().correctlySpends(outputTransaction, 0, output.getScriptPubKey(),
        EnumSet.of(Script.VerifyFlag.DERSIG, Script.VerifyFlag.P2SH));

    final Script scriptSig = input.getScriptSig();
    final TransactionSignature signature = TransactionSignature.decodeFromBitcoin(scriptSig.getChunks().get(0).data, true, false);

    // First output a conventional low-S transaction with the LOW_S flag, for the tx_valid.json set
    System.out.println("[\"A transaction with a low-S signature.\"],");
    System.out.println("[[[\""
        + inputTransaction.getHashAsString() + "\", "
        + output.getIndex() + ", \""
        + scriptToString(output.getScriptPubKey()) + "\"]],\n"
        + "\"" + Utils.HEX.encode(proposedTransaction.partialTx.unsafeBitcoinSerialize()) + "\", \""
        + Script.VerifyFlag.P2SH.name() + "," + Script.VerifyFlag.LOW_S.name() + "\"],");

    final BigInteger highS = HIGH_S_DIFFERENCE.subtract(signature.s);
    final TransactionSignature highSig = new TransactionSignature(signature.r, highS);
    input.setScriptSig(new ScriptBuilder().data(highSig.encodeToBitcoin()).data(scriptSig.getChunks().get(1).data).build());
    input.getScriptSig().correctlySpends(outputTransaction, 0, output.getScriptPubKey(),
        EnumSet.of(Script.VerifyFlag.P2SH));

    // A high-S transaction without the LOW_S flag, for the tx_valid.json set
    System.out.println("[\"A transaction with a high-S signature.\"],");
    System.out.println("[[[\""
        + inputTransaction.getHashAsString() + "\", "
        + output.getIndex() + ", \""
        + scriptToString(output.getScriptPubKey()) + "\"]],\n"
        + "\"" + Utils.HEX.encode(proposedTransaction.partialTx.unsafeBitcoinSerialize()) + "\", \""
        + Script.VerifyFlag.P2SH.name() + "\"],");

    // Lastly a conventional high-S transaction with the LOW_S flag, for the tx_invalid.json set
    System.out.println("[\"A transaction with a high-S signature.\"],");
    System.out.println("[[[\""
        + inputTransaction.getHashAsString() + "\", "
        + output.getIndex() + ", \""
        + scriptToString(output.getScriptPubKey()) + "\"]],\n"
        + "\"" + Utils.HEX.encode(proposedTransaction.partialTx.unsafeBitcoinSerialize()) + "\", \""
        + Script.VerifyFlag.P2SH.name() + "," + Script.VerifyFlag.LOW_S.name() + "\"],");
}