Move ECKey.toAddress() to Address.fromKey().

This is a preparation for supporting native segwit addresses. Keys can't know what
type of address is wanted. In future, there will also be a SegwitAddress.fromKey().
This commit is contained in:
Andreas Schildbach 2018-02-24 11:59:57 +01:00
parent 1a1693bd8a
commit dedeb01dac
39 changed files with 149 additions and 145 deletions

View file

@ -64,6 +64,14 @@ public class Address extends VersionedChecksummedBytes {
this.params = params; this.params = params;
} }
/**
* Returns an {@link Address} that represents the public part of the given {@link ECKey}. Note that an address is
* derived from a hash of the public key and is not the public key itself (which is too large to be convenient).
*/
public static Address fromKey(NetworkParameters params, ECKey key) {
return new Address(params, key.getPubKeyHash());
}
/** Returns an Address that represents the given P2SH script hash. */ /** Returns an Address that represents the given P2SH script hash. */
public static Address fromP2SHHash(NetworkParameters params, byte[] hash160) { public static Address fromP2SHHash(NetworkParameters params, byte[] hash160) {
try { try {

View file

@ -507,14 +507,6 @@ public class ECKey implements EncryptableItem {
return pub.isCompressed(); return pub.isCompressed();
} }
/**
* Returns the address that corresponds to the public part of this ECKey. Note that an address is derived from
* the RIPEMD-160 hash of the public key and is not the public key itself (which is too large to be convenient).
*/
public Address toAddress(NetworkParameters params) {
return new Address(params, getPubKeyHash());
}
/** /**
* Groups the two components that make up a signature, and provides a way to encode to DER form, which is * Groups the two components that make up a signature, and provides a way to encode to DER form, which is
* how ECDSA signatures are represented when embedded in other data structures in the Bitcoin protocol. The raw * how ECDSA signatures are represented when embedded in other data structures in the Bitcoin protocol. The raw
@ -1276,7 +1268,7 @@ public class ECKey implements EncryptableItem {
public void formatKeyWithAddress(boolean includePrivateKeys, @Nullable KeyParameter aesKey, StringBuilder builder, public void formatKeyWithAddress(boolean includePrivateKeys, @Nullable KeyParameter aesKey, StringBuilder builder,
NetworkParameters params) { NetworkParameters params) {
final Address address = toAddress(params); final Address address = Address.fromKey(params, this);
builder.append(" addr:"); builder.append(" addr:");
builder.append(address.toString()); builder.append(address.toString());
builder.append(" hash160:"); builder.append(" hash160:");

View file

@ -107,7 +107,7 @@ public class BIP38PrivateKey extends VersionedChecksummedBytes {
public ECKey decrypt(String passphrase) throws BadPassphraseException { public ECKey decrypt(String passphrase) throws BadPassphraseException {
String normalizedPassphrase = Normalizer.normalize(passphrase, Normalizer.Form.NFC); String normalizedPassphrase = Normalizer.normalize(passphrase, Normalizer.Form.NFC);
ECKey key = ecMultiply ? decryptEC(normalizedPassphrase) : decryptNoEC(normalizedPassphrase); ECKey key = ecMultiply ? decryptEC(normalizedPassphrase) : decryptNoEC(normalizedPassphrase);
Sha256Hash hash = Sha256Hash.twiceOf(key.toAddress(params).toString().getBytes(Charsets.US_ASCII)); Sha256Hash hash = Sha256Hash.twiceOf(Address.fromKey(params, key).toString().getBytes(Charsets.US_ASCII));
byte[] actualAddressHash = Arrays.copyOfRange(hash.getBytes(), 0, 4); byte[] actualAddressHash = Arrays.copyOfRange(hash.getBytes(), 0, 4);
if (!Arrays.equals(actualAddressHash, addressHash)) if (!Arrays.equals(actualAddressHash, addressHash))
throw new BadPassphraseException(); throw new BadPassphraseException();

View file

@ -617,7 +617,7 @@ public class DeterministicKey extends ECKey {
@Override @Override
public void formatKeyWithAddress(boolean includePrivateKeys, @Nullable KeyParameter aesKey, StringBuilder builder, public void formatKeyWithAddress(boolean includePrivateKeys, @Nullable KeyParameter aesKey, StringBuilder builder,
NetworkParameters params) { NetworkParameters params) {
final Address address = toAddress(params); final Address address = Address.fromKey(params, this);
builder.append(" addr:").append(address); builder.append(" addr:").append(address);
builder.append(" hash160:").append(Utils.HEX.encode(getPubKeyHash())); builder.append(" hash160:").append(Utils.HEX.encode(getPubKeyHash()));
builder.append(" (").append(getPathAsString()).append(")\n"); builder.append(" (").append(getPathAsString()).append(")\n");

View file

@ -245,7 +245,7 @@ public abstract class PaymentChannelClientState {
// Our output always comes first. // Our output always comes first.
// TODO: We should drop myKey in favor of output key + multisig key separation // TODO: We should drop myKey in favor of output key + multisig key separation
// (as its always obvious who the client is based on T2 output order) // (as its always obvious who the client is based on T2 output order)
tx.addOutput(valueToMe, myKey.toAddress(wallet.getParams())); tx.addOutput(valueToMe, Address.fromKey(wallet.getParams(), myKey));
return tx; return tx;
} }

View file

@ -220,7 +220,7 @@ public abstract class PaymentChannelServerState {
protected synchronized SendRequest makeUnsignedChannelContract(Coin valueToMe) { protected synchronized SendRequest makeUnsignedChannelContract(Coin valueToMe) {
Transaction tx = new Transaction(wallet.getParams()); Transaction tx = new Transaction(wallet.getParams());
if (!getTotalValue().subtract(valueToMe).equals(Coin.ZERO)) { if (!getTotalValue().subtract(valueToMe).equals(Coin.ZERO)) {
tx.addOutput(getTotalValue().subtract(valueToMe), getClientKey().toAddress(wallet.getParams())); tx.addOutput(getTotalValue().subtract(valueToMe), Address.fromKey(wallet.getParams(), getClientKey()));
} }
tx.addInput(contract.getOutput(0)); tx.addInput(contract.getOutput(0));
return SendRequest.forTx(tx); return SendRequest.forTx(tx);

View file

@ -163,10 +163,10 @@ public class PaymentChannelV1ClientState extends PaymentChannelClientState {
final Coin valueAfterFee = totalValue.subtract(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE); final Coin valueAfterFee = totalValue.subtract(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE);
if (Transaction.MIN_NONDUST_OUTPUT.compareTo(valueAfterFee) > 0) if (Transaction.MIN_NONDUST_OUTPUT.compareTo(valueAfterFee) > 0)
throw new ValueOutOfRangeException("totalValue too small to use"); throw new ValueOutOfRangeException("totalValue too small to use");
refundTx.addOutput(valueAfterFee, myKey.toAddress(params)); refundTx.addOutput(valueAfterFee, Address.fromKey(params, myKey));
refundFees = multisigFee.add(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE); refundFees = multisigFee.add(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE);
} else { } else {
refundTx.addOutput(totalValue, myKey.toAddress(params)); refundTx.addOutput(totalValue, Address.fromKey(params, myKey));
refundFees = multisigFee; refundFees = multisigFee;
} }
refundTx.getConfidence().setSource(TransactionConfidence.Source.SELF); refundTx.getConfidence().setSource(TransactionConfidence.Source.SELF);

View file

@ -134,10 +134,10 @@ public class PaymentChannelV2ClientState extends PaymentChannelClientState {
final Coin valueAfterFee = totalValue.subtract(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE); final Coin valueAfterFee = totalValue.subtract(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE);
if (Transaction.MIN_NONDUST_OUTPUT.compareTo(valueAfterFee) > 0) if (Transaction.MIN_NONDUST_OUTPUT.compareTo(valueAfterFee) > 0)
throw new ValueOutOfRangeException("totalValue too small to use"); throw new ValueOutOfRangeException("totalValue too small to use");
refundTx.addOutput(valueAfterFee, myKey.toAddress(params)); refundTx.addOutput(valueAfterFee, Address.fromKey(params, myKey));
refundFees = multisigFee.add(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE); refundFees = multisigFee.add(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE);
} else { } else {
refundTx.addOutput(totalValue, myKey.toAddress(params)); refundTx.addOutput(totalValue, Address.fromKey(params, myKey));
refundFees = multisigFee; refundFees = multisigFee;
} }

View file

@ -345,7 +345,7 @@ public class Script {
else if (ScriptPattern.isPayToScriptHash(this)) else if (ScriptPattern.isPayToScriptHash(this))
return Address.fromP2SHScript(params, this); return Address.fromP2SHScript(params, this);
else if (forcePayToPubKey && ScriptPattern.isPayToPubKey(this)) else if (forcePayToPubKey && ScriptPattern.isPayToPubKey(this))
return ECKey.fromPublicOnly(getPubKey()).toAddress(params); return Address.fromKey(params, ECKey.fromPublicOnly(getPubKey()));
else else
throw new ScriptException(ScriptError.SCRIPT_ERR_UNKNOWN_ERROR, "Cannot cast this script to a pay-to-address type"); throw new ScriptException(ScriptError.SCRIPT_ERR_UNKNOWN_ERROR, "Cannot cast this script to a pay-to-address type");
} }

View file

@ -188,7 +188,7 @@ public class KeyChainGroup implements KeyBag {
} }
return current; return current;
} else { } else {
return currentKey(purpose).toAddress(params); return Address.fromKey(params, currentKey(purpose));
} }
} }
@ -242,7 +242,7 @@ public class KeyChainGroup implements KeyBag {
currentAddresses.put(purpose, freshAddress); currentAddresses.put(purpose, freshAddress);
return freshAddress; return freshAddress;
} else { } else {
return freshKey(purpose).toAddress(params); return Address.fromKey(params, freshKey(purpose));
} }
} }
@ -727,7 +727,7 @@ public class KeyChainGroup implements KeyBag {
} else { } else {
log.info("Wallet with existing HD chain is being re-upgraded due to change in key rotation time."); log.info("Wallet with existing HD chain is being re-upgraded due to change in key rotation time.");
} }
log.info("Instantiating new HD chain using oldest non-rotating private key (address: {})", keyToUse.toAddress(params)); log.info("Instantiating new HD chain using oldest non-rotating private key (address: {})", Address.fromKey(params, keyToUse));
byte[] entropy = checkNotNull(keyToUse.getSecretBytes()); byte[] entropy = checkNotNull(keyToUse.getSecretBytes());
// Private keys should be at least 128 bits long. // Private keys should be at least 128 bits long.
checkState(entropy.length >= DeterministicSeed.DEFAULT_SEED_ENTROPY_BITS / 8); checkState(entropy.length >= DeterministicSeed.DEFAULT_SEED_ENTROPY_BITS / 8);

View file

@ -545,7 +545,7 @@ public class Wallet extends BaseTaggableObject
final List<ECKey> keys = getIssuedReceiveKeys(); final List<ECKey> keys = getIssuedReceiveKeys();
List<Address> addresses = new ArrayList<>(keys.size()); List<Address> addresses = new ArrayList<>(keys.size());
for (ECKey key : keys) for (ECKey key : keys)
addresses.add(key.toAddress(getParams())); addresses.add(Address.fromKey(getParams(), key));
return addresses; return addresses;
} }

View file

@ -92,7 +92,7 @@ public class BlockChainTest {
resetBlockStore(); resetBlockStore();
chain = new BlockChain(PARAMS, wallet, blockStore); chain = new BlockChain(PARAMS, wallet, blockStore);
coinbaseTo = wallet.currentReceiveKey().toAddress(PARAMS); coinbaseTo = Address.fromKey(PARAMS, wallet.currentReceiveKey());
} }
@Test @Test
@ -128,7 +128,7 @@ public class BlockChainTest {
// Quick check that we can actually receive coins. // Quick check that we can actually receive coins.
Transaction tx1 = createFakeTx(PARAMS, Transaction tx1 = createFakeTx(PARAMS,
COIN, COIN,
wallet.currentReceiveKey().toAddress(PARAMS)); Address.fromKey(PARAMS, wallet.currentReceiveKey()));
Block b1 = createFakeBlock(blockStore, height, tx1).block; Block b1 = createFakeBlock(blockStore, height, tx1).block;
chain.add(b1); chain.add(b1);
assertTrue(wallet.getBalance().signum() > 0); assertTrue(wallet.getBalance().signum() > 0);
@ -291,10 +291,10 @@ public class BlockChainTest {
public void intraBlockDependencies() throws Exception { public void intraBlockDependencies() throws Exception {
// Covers issue 166 in which transactions that depend on each other inside a block were not always being // Covers issue 166 in which transactions that depend on each other inside a block were not always being
// considered relevant. // considered relevant.
Address somebodyElse = new ECKey().toAddress(PARAMS); Address somebodyElse = Address.fromKey(PARAMS, new ECKey());
Block b1 = PARAMS.getGenesisBlock().createNextBlock(somebodyElse); Block b1 = PARAMS.getGenesisBlock().createNextBlock(somebodyElse);
ECKey key = wallet.freshReceiveKey(); ECKey key = wallet.freshReceiveKey();
Address addr = key.toAddress(PARAMS); Address addr = Address.fromKey(PARAMS, key);
// Create a tx that gives us some coins, and another that spends it to someone else in the same block. // Create a tx that gives us some coins, and another that spends it to someone else in the same block.
Transaction t1 = FakeTxBuilder.createFakeTx(PARAMS, COIN, addr); Transaction t1 = FakeTxBuilder.createFakeTx(PARAMS, COIN, addr);
Transaction t2 = new Transaction(PARAMS); Transaction t2 = new Transaction(PARAMS);
@ -317,7 +317,7 @@ public class BlockChainTest {
int height = 1; int height = 1;
chain.addWallet(wallet2); chain.addWallet(wallet2);
Address addressToSendTo = receiveKey.toAddress(PARAMS); Address addressToSendTo = Address.fromKey(PARAMS, receiveKey);
// Create a block, sending the coinbase to the coinbaseTo address (which is in the wallet). // Create a block, sending the coinbase to the coinbaseTo address (which is in the wallet).
Block b1 = PARAMS.getGenesisBlock().createNextBlockWithCoinbase(Block.BLOCK_VERSION_GENESIS, wallet.currentReceiveKey().getPubKey(), height++); Block b1 = PARAMS.getGenesisBlock().createNextBlockWithCoinbase(Block.BLOCK_VERSION_GENESIS, wallet.currentReceiveKey().getPubKey(), height++);
@ -341,8 +341,7 @@ public class BlockChainTest {
// Check that the coinbase is unavailable to spend for the next spendableCoinbaseDepth - 2 blocks. // Check that the coinbase is unavailable to spend for the next spendableCoinbaseDepth - 2 blocks.
for (int i = 0; i < PARAMS.getSpendableCoinbaseDepth() - 2; i++) { for (int i = 0; i < PARAMS.getSpendableCoinbaseDepth() - 2; i++) {
// Non relevant tx - just for fake block creation. // Non relevant tx - just for fake block creation.
Transaction tx2 = createFakeTx(PARAMS, COIN, Transaction tx2 = createFakeTx(PARAMS, COIN, Address.fromKey(PARAMS, new ECKey()));
new ECKey().toAddress(PARAMS));
Block b2 = createFakeBlock(blockStore, height++, tx2).block; Block b2 = createFakeBlock(blockStore, height++, tx2).block;
chain.add(b2); chain.add(b2);
@ -363,7 +362,7 @@ public class BlockChainTest {
} }
// Give it one more block - should now be able to spend coinbase transaction. Non relevant tx. // Give it one more block - should now be able to spend coinbase transaction. Non relevant tx.
Transaction tx3 = createFakeTx(PARAMS, COIN, new ECKey().toAddress(PARAMS)); Transaction tx3 = createFakeTx(PARAMS, COIN, Address.fromKey(PARAMS, new ECKey()));
Block b3 = createFakeBlock(blockStore, height++, tx3).block; Block b3 = createFakeBlock(blockStore, height++, tx3).block;
chain.add(b3); chain.add(b3);

View file

@ -73,7 +73,7 @@ public class BloomFilterTest {
DumpedPrivateKey privKey = DumpedPrivateKey.fromBase58(params, "5Kg1gnAjaLfKiwhhPpGS3QfRg2m6awQvaj98JCZBZQ5SuS2F15C"); DumpedPrivateKey privKey = DumpedPrivateKey.fromBase58(params, "5Kg1gnAjaLfKiwhhPpGS3QfRg2m6awQvaj98JCZBZQ5SuS2F15C");
Address addr = privKey.getKey().toAddress(params); Address addr = Address.fromKey(params, privKey.getKey());
assertTrue(addr.toString().equals("17Wx1GQfyPTNWpQMHrTwRSMTCAonSiZx9e")); assertTrue(addr.toString().equals("17Wx1GQfyPTNWpQMHrTwRSMTCAonSiZx9e"));
KeyChainGroup group = new KeyChainGroup(params); KeyChainGroup group = new KeyChainGroup(params);

View file

@ -65,9 +65,9 @@ public class ChainSplitTest {
ECKey key1 = wallet.freshReceiveKey(); ECKey key1 = wallet.freshReceiveKey();
ECKey key2 = wallet.freshReceiveKey(); ECKey key2 = wallet.freshReceiveKey();
chain = new BlockChain(PARAMS, wallet, blockStore); chain = new BlockChain(PARAMS, wallet, blockStore);
coinsTo = key1.toAddress(PARAMS); coinsTo = Address.fromKey(PARAMS, key1);
coinsTo2 = key2.toAddress(PARAMS); coinsTo2 = Address.fromKey(PARAMS, key2);
someOtherGuy = new ECKey().toAddress(PARAMS); someOtherGuy = Address.fromKey(PARAMS, new ECKey());
} }
@Test @Test
@ -186,7 +186,7 @@ public class ChainSplitTest {
Block b1 = PARAMS.getGenesisBlock().createNextBlock(coinsTo); Block b1 = PARAMS.getGenesisBlock().createNextBlock(coinsTo);
chain.add(b1); chain.add(b1);
assertEquals(FIFTY_COINS, wallet.getBalance()); assertEquals(FIFTY_COINS, wallet.getBalance());
Address dest = new ECKey().toAddress(PARAMS); Address dest = Address.fromKey(PARAMS, new ECKey());
Transaction spend = wallet.createSend(dest, valueOf(10, 0)); Transaction spend = wallet.createSend(dest, valueOf(10, 0));
wallet.commitTx(spend); wallet.commitTx(spend);
// Waiting for confirmation ... make it eligible for selection. // Waiting for confirmation ... make it eligible for selection.
@ -220,7 +220,7 @@ public class ChainSplitTest {
Block b1 = PARAMS.getGenesisBlock().createNextBlock(coinsTo); Block b1 = PARAMS.getGenesisBlock().createNextBlock(coinsTo);
chain.add(b1); chain.add(b1);
assertEquals(FIFTY_COINS, wallet.getBalance()); assertEquals(FIFTY_COINS, wallet.getBalance());
Address dest = new ECKey().toAddress(PARAMS); Address dest = Address.fromKey(PARAMS, new ECKey());
Transaction spend = wallet.createSend(dest, FIFTY_COINS); Transaction spend = wallet.createSend(dest, FIFTY_COINS);
// We do NOT confirm the spend here. That means it's not considered to be pending because createSend is // We do NOT confirm the spend here. That means it's not considered to be pending because createSend is
// stateless. For our purposes it is as if some other program with our keys created the tx. // stateless. For our purposes it is as if some other program with our keys created the tx.
@ -311,21 +311,21 @@ public class ChainSplitTest {
chain.add(b1); chain.add(b1);
Transaction t1 = wallet.createSend(someOtherGuy, valueOf(10, 0)); Transaction t1 = wallet.createSend(someOtherGuy, valueOf(10, 0));
Address yetAnotherGuy = new ECKey().toAddress(PARAMS); Address yetAnotherGuy = Address.fromKey(PARAMS, new ECKey());
Transaction t2 = wallet.createSend(yetAnotherGuy, valueOf(20, 0)); Transaction t2 = wallet.createSend(yetAnotherGuy, valueOf(20, 0));
wallet.commitTx(t1); wallet.commitTx(t1);
// Receive t1 as confirmed by the network. // Receive t1 as confirmed by the network.
Block b2 = b1.createNextBlock(new ECKey().toAddress(PARAMS)); Block b2 = b1.createNextBlock(Address.fromKey(PARAMS, new ECKey()));
b2.addTransaction(t1); b2.addTransaction(t1);
b2.solve(); b2.solve();
chain.add(roundtrip(b2)); chain.add(roundtrip(b2));
// Now we make a double spend become active after a re-org. // Now we make a double spend become active after a re-org.
Block b3 = b1.createNextBlock(new ECKey().toAddress(PARAMS)); Block b3 = b1.createNextBlock(Address.fromKey(PARAMS, new ECKey()));
b3.addTransaction(t2); b3.addTransaction(t2);
b3.solve(); b3.solve();
chain.add(roundtrip(b3)); // Side chain. chain.add(roundtrip(b3)); // Side chain.
Block b4 = b3.createNextBlock(new ECKey().toAddress(PARAMS)); Block b4 = b3.createNextBlock(Address.fromKey(PARAMS, new ECKey()));
chain.add(b4); // New best chain. chain.add(b4); // New best chain.
Threading.waitForUserCode(); Threading.waitForUserCode();
// Should have seen a double spend. // Should have seen a double spend.
@ -354,11 +354,11 @@ public class ChainSplitTest {
chain.add(b1); chain.add(b1);
Transaction t1 = checkNotNull(wallet.createSend(someOtherGuy, valueOf(10, 0))); Transaction t1 = checkNotNull(wallet.createSend(someOtherGuy, valueOf(10, 0)));
Address yetAnotherGuy = new ECKey().toAddress(PARAMS); Address yetAnotherGuy = Address.fromKey(PARAMS, new ECKey());
Transaction t2 = checkNotNull(wallet.createSend(yetAnotherGuy, valueOf(20, 0))); Transaction t2 = checkNotNull(wallet.createSend(yetAnotherGuy, valueOf(20, 0)));
wallet.commitTx(t1); wallet.commitTx(t1);
// t1 is still pending ... // t1 is still pending ...
Block b2 = b1.createNextBlock(new ECKey().toAddress(PARAMS)); Block b2 = b1.createNextBlock(Address.fromKey(PARAMS, new ECKey()));
chain.add(b2); chain.add(b2);
assertEquals(ZERO, wallet.getBalance()); assertEquals(ZERO, wallet.getBalance());
assertEquals(valueOf(40, 0), wallet.getBalance(Wallet.BalanceType.ESTIMATED)); assertEquals(valueOf(40, 0), wallet.getBalance(Wallet.BalanceType.ESTIMATED));
@ -366,11 +366,11 @@ public class ChainSplitTest {
// Now we make a double spend become active after a re-org. // Now we make a double spend become active after a re-org.
// genesis -> b1 -> b2 [t1 pending] // genesis -> b1 -> b2 [t1 pending]
// \-> b3 (t2) -> b4 // \-> b3 (t2) -> b4
Block b3 = b1.createNextBlock(new ECKey().toAddress(PARAMS)); Block b3 = b1.createNextBlock(Address.fromKey(PARAMS, new ECKey()));
b3.addTransaction(t2); b3.addTransaction(t2);
b3.solve(); b3.solve();
chain.add(roundtrip(b3)); // Side chain. chain.add(roundtrip(b3)); // Side chain.
Block b4 = b3.createNextBlock(new ECKey().toAddress(PARAMS)); Block b4 = b3.createNextBlock(Address.fromKey(PARAMS, new ECKey()));
chain.add(b4); // New best chain. chain.add(b4); // New best chain.
Threading.waitForUserCode(); Threading.waitForUserCode();
// Should have seen a double spend against the pending pool. // Should have seen a double spend against the pending pool.
@ -381,9 +381,9 @@ public class ChainSplitTest {
assertEquals(valueOf(30, 0), wallet.getBalance()); assertEquals(valueOf(30, 0), wallet.getBalance());
// ... and back to our own parallel universe. // ... and back to our own parallel universe.
Block b5 = b2.createNextBlock(new ECKey().toAddress(PARAMS)); Block b5 = b2.createNextBlock(Address.fromKey(PARAMS, new ECKey()));
chain.add(b5); chain.add(b5);
Block b6 = b5.createNextBlock(new ECKey().toAddress(PARAMS)); Block b6 = b5.createNextBlock(Address.fromKey(PARAMS, new ECKey()));
chain.add(b6); chain.add(b6);
// genesis -> b1 -> b2 -> b5 -> b6 [t1 still dead] // genesis -> b1 -> b2 -> b5 -> b6 [t1 still dead]
// \-> b3 [t2 resurrected and now pending] -> b4 // \-> b3 [t2 resurrected and now pending] -> b4
@ -530,9 +530,9 @@ public class ChainSplitTest {
// Send a couple of payments one after the other (so the second depends on the change output of the first). // Send a couple of payments one after the other (so the second depends on the change output of the first).
wallet.allowSpendingUnconfirmedTransactions(); wallet.allowSpendingUnconfirmedTransactions();
Transaction t2 = checkNotNull(wallet.createSend(new ECKey().toAddress(PARAMS), CENT)); Transaction t2 = checkNotNull(wallet.createSend(Address.fromKey(PARAMS, new ECKey()), CENT));
wallet.commitTx(t2); wallet.commitTx(t2);
Transaction t3 = checkNotNull(wallet.createSend(new ECKey().toAddress(PARAMS), CENT)); Transaction t3 = checkNotNull(wallet.createSend(Address.fromKey(PARAMS, new ECKey()), CENT));
wallet.commitTx(t3); wallet.commitTx(t3);
chain.add(FakeTxBuilder.makeSolvedTestBlock(b1, t2, t3)); chain.add(FakeTxBuilder.makeSolvedTestBlock(b1, t2, t3));
@ -600,7 +600,7 @@ public class ChainSplitTest {
chain.add(firstTip); chain.add(firstTip);
} }
// ... and spend. // ... and spend.
Transaction fodder = wallet.createSend(new ECKey().toAddress(PARAMS), FIFTY_COINS); Transaction fodder = wallet.createSend(Address.fromKey(PARAMS, new ECKey()), FIFTY_COINS);
wallet.commitTx(fodder); wallet.commitTx(fodder);
final AtomicBoolean fodderIsDead = new AtomicBoolean(false); final AtomicBoolean fodderIsDead = new AtomicBoolean(false);
fodder.getConfidence().addEventListener(Threading.SAME_THREAD, new TransactionConfidence.Listener() { fodder.getConfidence().addEventListener(Threading.SAME_THREAD, new TransactionConfidence.Listener() {

View file

@ -186,7 +186,7 @@ public class ECKeyTest {
String privkey = "92shANodC6Y4evT5kFzjNFQAdjqTtHAnDTLzqBBq4BbKUPyx6CD"; String privkey = "92shANodC6Y4evT5kFzjNFQAdjqTtHAnDTLzqBBq4BbKUPyx6CD";
ECKey key = DumpedPrivateKey.fromBase58(TestNet3Params.get(), privkey).getKey(); ECKey key = DumpedPrivateKey.fromBase58(TestNet3Params.get(), privkey).getKey();
assertEquals(privkey, key.getPrivateKeyEncoded(TestNet3Params.get()).toString()); assertEquals(privkey, key.getPrivateKeyEncoded(TestNet3Params.get()).toString());
assertEquals(addr, key.toAddress(TestNet3Params.get()).toString()); assertEquals(addr, Address.fromKey(TestNet3Params.get(), key).toString());
} }
@Test @Test
@ -214,7 +214,7 @@ public class ECKeyTest {
ECKey key = new ECKey(); ECKey key = new ECKey();
String message = "聡中本"; String message = "聡中本";
String signatureBase64 = key.signMessage(message); String signatureBase64 = key.signMessage(message);
log.info("Message signed with " + key.toAddress(MainNetParams.get()) + ": " + signatureBase64); log.info("Message signed with " + Address.fromKey(MainNetParams.get(), key) + ": " + signatureBase64);
// Should verify correctly. // Should verify correctly.
key.verifyMessage(message, signatureBase64); key.verifyMessage(message, signatureBase64);
try { try {
@ -232,7 +232,7 @@ public class ECKeyTest {
String sigBase64 = "HxNZdo6ggZ41hd3mM3gfJRqOQPZYcO8z8qdX2BwmpbF11CaOQV+QiZGGQxaYOncKoNW61oRuSMMF8udfK54XqI8="; String sigBase64 = "HxNZdo6ggZ41hd3mM3gfJRqOQPZYcO8z8qdX2BwmpbF11CaOQV+QiZGGQxaYOncKoNW61oRuSMMF8udfK54XqI8=";
Address expectedAddress = Address.fromBase58(MainNetParams.get(), "14YPSNPi6NSXnUxtPAsyJSuw3pv7AU3Cag"); Address expectedAddress = Address.fromBase58(MainNetParams.get(), "14YPSNPi6NSXnUxtPAsyJSuw3pv7AU3Cag");
ECKey key = ECKey.signedMessageToKey(message, sigBase64); ECKey key = ECKey.signedMessageToKey(message, sigBase64);
Address gotAddress = key.toAddress(MainNetParams.get()); Address gotAddress = Address.fromKey(MainNetParams.get(), key);
assertEquals(expectedAddress, gotAddress); assertEquals(expectedAddress, gotAddress);
} }

View file

@ -92,7 +92,7 @@ public class FilteredBlockAndPartialMerkleTreeTests extends TestWithPeerGroup {
ECKey key1 = new ECKey(); ECKey key1 = new ECKey();
ECKey key2 = new ECKey(); ECKey key2 = new ECKey();
Transaction tx1 = FakeTxBuilder.createFakeTx(PARAMS, Coin.COIN, key1); Transaction tx1 = FakeTxBuilder.createFakeTx(PARAMS, Coin.COIN, key1);
Transaction tx2 = FakeTxBuilder.createFakeTx(PARAMS, Coin.FIFTY_COINS, key2.toAddress(PARAMS)); Transaction tx2 = FakeTxBuilder.createFakeTx(PARAMS, Coin.FIFTY_COINS, Address.fromKey(PARAMS, key2));
Block block = FakeTxBuilder.makeSolvedTestBlock(PARAMS.getGenesisBlock(), Address.fromBase58(PARAMS, "msg2t2V2sWNd85LccoddtWysBTR8oPnkzW"), tx1, tx2); Block block = FakeTxBuilder.makeSolvedTestBlock(PARAMS.getGenesisBlock(), Address.fromBase58(PARAMS, "msg2t2V2sWNd85LccoddtWysBTR8oPnkzW"), tx1, tx2);
BloomFilter filter = new BloomFilter(4, 0.1, 1); BloomFilter filter = new BloomFilter(4, 0.1, 1);
filter.insert(key1); filter.insert(key1);

View file

@ -90,17 +90,17 @@ public class ParseByteCacheTest {
Transaction tx1 = createFakeTx(PARAMS, Transaction tx1 = createFakeTx(PARAMS,
valueOf(2, 0), valueOf(2, 0),
wallet.currentReceiveKey().toAddress(PARAMS)); Address.fromKey(PARAMS, wallet.currentReceiveKey()));
// add a second input so can test granularity of byte cache. // add a second input so can test granularity of byte cache.
Transaction prevTx = new Transaction(PARAMS); Transaction prevTx = new Transaction(PARAMS);
TransactionOutput prevOut = new TransactionOutput(PARAMS, prevTx, COIN, wallet.currentReceiveKey().toAddress(PARAMS)); TransactionOutput prevOut = new TransactionOutput(PARAMS, prevTx, COIN, Address.fromKey(PARAMS, wallet.currentReceiveKey()));
prevTx.addOutput(prevOut); prevTx.addOutput(prevOut);
// Connect it. // Connect it.
tx1.addInput(prevOut); tx1.addInput(prevOut);
Transaction tx2 = createFakeTx(PARAMS, COIN, Transaction tx2 = createFakeTx(PARAMS, COIN,
new ECKey().toAddress(PARAMS)); Address.fromKey(PARAMS, new ECKey()));
Block b1 = createFakeBlock(blockStore, BLOCK_HEIGHT_GENESIS, tx1, tx2).block; Block b1 = createFakeBlock(blockStore, BLOCK_HEIGHT_GENESIS, tx1, tx2).block;

View file

@ -245,7 +245,7 @@ public class PeerGroupTest extends TestWithPeerGroup {
Wallet wallet2 = new Wallet(PARAMS); Wallet wallet2 = new Wallet(PARAMS);
ECKey key2 = wallet2.freshReceiveKey(); ECKey key2 = wallet2.freshReceiveKey();
Address address2 = key2.toAddress(PARAMS); Address address2 = Address.fromKey(PARAMS, key2);
peerGroup.addWallet(wallet2); peerGroup.addWallet(wallet2);
blockChain.addWallet(wallet2); blockChain.addWallet(wallet2);
@ -804,7 +804,7 @@ public class PeerGroupTest extends TestWithPeerGroup {
Coin expectedBalance = Coin.ZERO; Coin expectedBalance = Coin.ZERO;
Block prev = blockStore.getChainHead().getHeader(); Block prev = blockStore.getChainHead().getHeader();
for (ECKey key1 : keys) { for (ECKey key1 : keys) {
Address addr = key1.toAddress(PARAMS); Address addr = Address.fromKey(PARAMS, key1);
Block next = FakeTxBuilder.makeSolvedTestBlock(prev, FakeTxBuilder.createFakeTx(PARAMS, Coin.FIFTY_COINS, addr)); Block next = FakeTxBuilder.makeSolvedTestBlock(prev, FakeTxBuilder.createFakeTx(PARAMS, Coin.FIFTY_COINS, addr));
expectedBalance = expectedBalance.add(next.getTransactions().get(2).getOutput(0).getValue()); expectedBalance = expectedBalance.add(next.getTransactions().get(2).getOutput(0).getValue());
blocks.add(next); blocks.add(next);

View file

@ -870,7 +870,7 @@ public class PeerTest extends TestWithNetworkConnections {
connect(); connect();
Transaction t1 = new Transaction(PARAMS); Transaction t1 = new Transaction(PARAMS);
t1.addInput(new TransactionInput(PARAMS, t1, new byte[]{})); t1.addInput(new TransactionInput(PARAMS, t1, new byte[]{}));
t1.addOutput(COIN, new ECKey().toAddress(PARAMS)); t1.addOutput(COIN, Address.fromKey(PARAMS, new ECKey()));
Transaction t2 = new Transaction(PARAMS); Transaction t2 = new Transaction(PARAMS);
t2.addInput(t1.getOutput(0)); t2.addInput(t1.getOutput(0));
t2.addOutput(COIN, wallet.currentChangeAddress()); t2.addOutput(COIN, wallet.currentChangeAddress());

View file

@ -159,7 +159,7 @@ public class TransactionBroadcastTest extends TestWithPeerGroup {
assertEquals(FIFTY_COINS, wallet.getBalance()); assertEquals(FIFTY_COINS, wallet.getBalance());
// Now create a spend, and expect the announcement on p1. // Now create a spend, and expect the announcement on p1.
Address dest = new ECKey().toAddress(PARAMS); Address dest = Address.fromKey(PARAMS, new ECKey());
Wallet.SendResult sendResult = wallet.sendCoins(peerGroup, dest, COIN); Wallet.SendResult sendResult = wallet.sendCoins(peerGroup, dest, COIN);
assertFalse(sendResult.broadcastComplete.isDone()); assertFalse(sendResult.broadcastComplete.isDone());
Transaction t1; Transaction t1;
@ -208,7 +208,7 @@ public class TransactionBroadcastTest extends TestWithPeerGroup {
}); });
// Now create a spend, and expect the announcement on p1. // Now create a spend, and expect the announcement on p1.
Address dest = new ECKey().toAddress(PARAMS); Address dest = Address.fromKey(PARAMS, new ECKey());
Wallet.SendResult sendResult = wallet.sendCoins(peerGroup, dest, COIN); Wallet.SendResult sendResult = wallet.sendCoins(peerGroup, dest, COIN);
assertNotNull(sendResult.tx); assertNotNull(sendResult.tx);
Threading.waitForUserCode(); Threading.waitForUserCode();

View file

@ -40,7 +40,7 @@ import static org.junit.Assert.*;
*/ */
public class TransactionTest { public class TransactionTest {
private static final NetworkParameters PARAMS = UnitTestParams.get(); private static final NetworkParameters PARAMS = UnitTestParams.get();
private static final Address ADDRESS = new ECKey().toAddress(PARAMS); private static final Address ADDRESS = Address.fromKey(PARAMS, new ECKey());
private Transaction tx; private Transaction tx;
@ -344,7 +344,7 @@ public class TransactionTest {
@Test(expected = ScriptException.class) @Test(expected = ScriptException.class)
public void testAddSignedInputThrowsExceptionWhenScriptIsNotToRawPubKeyAndIsNotToAddress() { public void testAddSignedInputThrowsExceptionWhenScriptIsNotToRawPubKeyAndIsNotToAddress() {
ECKey key = new ECKey(); ECKey key = new ECKey();
Address addr = key.toAddress(PARAMS); Address addr = Address.fromKey(PARAMS, key);
Transaction fakeTx = FakeTxBuilder.createFakeTx(PARAMS, Coin.COIN, addr); Transaction fakeTx = FakeTxBuilder.createFakeTx(PARAMS, Coin.COIN, addr);
Transaction tx = new Transaction(PARAMS); Transaction tx = new Transaction(PARAMS);
@ -409,7 +409,7 @@ public class TransactionTest {
@Test @Test
public void testHashForSignatureThreadSafety() { public void testHashForSignatureThreadSafety() {
Block genesis = UnitTestParams.get().getGenesisBlock(); Block genesis = UnitTestParams.get().getGenesisBlock();
Block block1 = genesis.createNextBlock(new ECKey().toAddress(UnitTestParams.get()), Block block1 = genesis.createNextBlock(Address.fromKey(UnitTestParams.get(), new ECKey()),
genesis.getTransactions().get(0).getOutput(0).getOutPointFor()); genesis.getTransactions().get(0).getOutput(0).getOutPointFor());
final Transaction tx = block1.getTransactions().get(1); final Transaction tx = block1.getTransactions().get(1);

View file

@ -38,8 +38,8 @@ public class TxConfidenceTableTest {
Context context = new Context(PARAMS); Context context = new Context(PARAMS);
table = context.getConfidenceTable(); table = context.getConfidenceTable();
Address to = new ECKey().toAddress(PARAMS); Address to = Address.fromKey(PARAMS, new ECKey());
Address change = new ECKey().toAddress(PARAMS); Address change = Address.fromKey(PARAMS, new ECKey());
tx1 = FakeTxBuilder.createFakeTxWithChangeAddress(PARAMS, COIN, to, change); tx1 = FakeTxBuilder.createFakeTxWithChangeAddress(PARAMS, COIN, to, change);
tx2 = FakeTxBuilder.createFakeTxWithChangeAddress(PARAMS, COIN, to, change); tx2 = FakeTxBuilder.createFakeTxWithChangeAddress(PARAMS, COIN, to, change);

View file

@ -341,7 +341,7 @@ public class PaymentChannelStateTest extends TestWithWallet {
// we can broadcast the refund and get our balance back. // we can broadcast the refund and get our balance back.
// Spend the client wallet's one coin // Spend the client wallet's one coin
Transaction spendCoinTx = wallet.sendCoinsOffline(SendRequest.to(new ECKey().toAddress(PARAMS), COIN)); Transaction spendCoinTx = wallet.sendCoinsOffline(SendRequest.to(Address.fromKey(PARAMS, new ECKey()), COIN));
assertEquals(Coin.ZERO, wallet.getBalance()); assertEquals(Coin.ZERO, wallet.getBalance());
chain.add(makeSolvedTestBlock(blockStore.getChainHead().getHeader(), spendCoinTx, createFakeTx(PARAMS, CENT, myAddress))); chain.add(makeSolvedTestBlock(blockStore.getChainHead().getHeader(), spendCoinTx, createFakeTx(PARAMS, CENT, myAddress)));
assertEquals(CENT, wallet.getBalance()); assertEquals(CENT, wallet.getBalance());
@ -473,7 +473,7 @@ public class PaymentChannelStateTest extends TestWithWallet {
// Test refund transaction with any number of issues // Test refund transaction with any number of issues
byte[] refundTxBytes = clientV1State().getIncompleteRefundTransaction().bitcoinSerialize(); byte[] refundTxBytes = clientV1State().getIncompleteRefundTransaction().bitcoinSerialize();
Transaction refund = new Transaction(PARAMS, refundTxBytes); Transaction refund = new Transaction(PARAMS, refundTxBytes);
refund.addOutput(Coin.ZERO, new ECKey().toAddress(PARAMS)); refund.addOutput(Coin.ZERO, Address.fromKey(PARAMS, new ECKey()));
try { try {
serverV1State().provideRefundTransaction(refund, myKey.getPubKey()); serverV1State().provideRefundTransaction(refund, myKey.getPubKey());
fail(); fail();
@ -692,7 +692,7 @@ public class PaymentChannelStateTest extends TestWithWallet {
Context.propagate(new Context(PARAMS, 100, Coin.ZERO, true)); Context.propagate(new Context(PARAMS, 100, Coin.ZERO, true));
// Spend the client wallet's one coin // Spend the client wallet's one coin
final SendRequest request = SendRequest.to(new ECKey().toAddress(PARAMS), COIN); final SendRequest request = SendRequest.to(Address.fromKey(PARAMS, new ECKey()), COIN);
request.ensureMinRequiredFee = false; request.ensureMinRequiredFee = false;
wallet.sendCoinsOffline(request); wallet.sendCoinsOffline(request);
assertEquals(Coin.ZERO, wallet.getBalance()); assertEquals(Coin.ZERO, wallet.getBalance());
@ -892,7 +892,7 @@ public class PaymentChannelStateTest extends TestWithWallet {
} }
// Now give the server enough coins to pay the fee // Now give the server enough coins to pay the fee
sendMoneyToWallet(serverWallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, COIN, serverKey.toAddress(PARAMS)); sendMoneyToWallet(serverWallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, COIN, Address.fromKey(PARAMS, serverKey));
// The contract is still not worth redeeming - its worth less than we pay in fee // The contract is still not worth redeeming - its worth less than we pay in fee
try { try {
@ -998,7 +998,7 @@ public class PaymentChannelStateTest extends TestWithWallet {
doubleSpendContract.addOutput(HALF_COIN, myKey); doubleSpendContract.addOutput(HALF_COIN, myKey);
doubleSpendContract = new Transaction(PARAMS, doubleSpendContract.bitcoinSerialize()); doubleSpendContract = new Transaction(PARAMS, doubleSpendContract.bitcoinSerialize());
StoredBlock block = new StoredBlock(PARAMS.getGenesisBlock().createNextBlock(myKey.toAddress(PARAMS)), BigInteger.TEN, 1); StoredBlock block = new StoredBlock(PARAMS.getGenesisBlock().createNextBlock(Address.fromKey(PARAMS, myKey)), BigInteger.TEN, 1);
serverWallet.receiveFromBlock(doubleSpendContract, block, AbstractBlockChain.NewBlockType.BEST_CHAIN, 0); serverWallet.receiveFromBlock(doubleSpendContract, block, AbstractBlockChain.NewBlockType.BEST_CHAIN, 0);
// Now if we try to spend again the server will reject it since it saw a double-spend // Now if we try to spend again the server will reject it since it saw a double-spend

View file

@ -43,9 +43,9 @@ import static org.junit.Assert.*;
public class PaymentProtocolTest { public class PaymentProtocolTest {
// static test data // static test data
private static final NetworkParameters NETWORK_PARAMS = UnitTestParams.get(); private static final NetworkParameters PARAMS = UnitTestParams.get();
private static final Coin AMOUNT = Coin.SATOSHI; private static final Coin AMOUNT = Coin.SATOSHI;
private static final Address TO_ADDRESS = new ECKey().toAddress(NETWORK_PARAMS); private static final Address TO_ADDRESS = Address.fromKey(PARAMS, new ECKey());
private static final String MEMO = "memo"; private static final String MEMO = "memo";
private static final String PAYMENT_URL = "https://example.com"; private static final String PAYMENT_URL = "https://example.com";
private static final byte[] MERCHANT_DATA = { 0, 1, 2 }; private static final byte[] MERCHANT_DATA = { 0, 1, 2 };
@ -122,16 +122,16 @@ public class PaymentProtocolTest {
public void testPaymentMessage() throws Exception { public void testPaymentMessage() throws Exception {
// Create // Create
List<Transaction> transactions = new LinkedList<>(); List<Transaction> transactions = new LinkedList<>();
transactions.add(FakeTxBuilder.createFakeTx(NETWORK_PARAMS, AMOUNT, TO_ADDRESS)); transactions.add(FakeTxBuilder.createFakeTx(PARAMS, AMOUNT, TO_ADDRESS));
Coin refundAmount = Coin.SATOSHI; Coin refundAmount = Coin.SATOSHI;
Address refundAddress = new ECKey().toAddress(NETWORK_PARAMS); Address refundAddress = Address.fromKey(PARAMS, new ECKey());
Payment payment = PaymentProtocol.createPaymentMessage(transactions, refundAmount, refundAddress, MEMO, Payment payment = PaymentProtocol.createPaymentMessage(transactions, refundAmount, refundAddress, MEMO,
MERCHANT_DATA); MERCHANT_DATA);
byte[] paymentBytes = payment.toByteArray(); byte[] paymentBytes = payment.toByteArray();
// Parse // Parse
Payment parsedPayment = Payment.parseFrom(paymentBytes); Payment parsedPayment = Payment.parseFrom(paymentBytes);
List<Transaction> parsedTransactions = PaymentProtocol.parseTransactionsFromPaymentMessage(NETWORK_PARAMS, List<Transaction> parsedTransactions = PaymentProtocol.parseTransactionsFromPaymentMessage(PARAMS,
parsedPayment); parsedPayment);
assertEquals(transactions, parsedTransactions); assertEquals(transactions, parsedTransactions);
assertEquals(1, parsedPayment.getRefundToCount()); assertEquals(1, parsedPayment.getRefundToCount());

View file

@ -18,6 +18,8 @@
package org.bitcoinj.script; package org.bitcoinj.script;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import org.bitcoinj.core.Address;
import org.bitcoinj.core.ECKey; import org.bitcoinj.core.ECKey;
import org.bitcoinj.params.MainNetParams; import org.bitcoinj.params.MainNetParams;
import org.junit.Test; import org.junit.Test;
@ -33,7 +35,7 @@ public class ScriptPatternTest {
@Test @Test
public void testCommonScripts() { public void testCommonScripts() {
assertTrue(ScriptPattern.isPayToPubKeyHash( assertTrue(ScriptPattern.isPayToPubKeyHash(
ScriptBuilder.createOutputScript(keys.get(0).toAddress(MainNetParams.get())) ScriptBuilder.createOutputScript(Address.fromKey(MainNetParams.get(), keys.get(0)))
)); ));
assertTrue(ScriptPattern.isPayToScriptHash( assertTrue(ScriptPattern.isPayToScriptHash(
ScriptBuilder.createP2SHOutputScript(2, keys) ScriptBuilder.createP2SHOutputScript(2, keys)

View file

@ -439,7 +439,7 @@ public class ScriptTest {
public void getToAddress() throws Exception { public void getToAddress() throws Exception {
// pay to pubkey // pay to pubkey
ECKey toKey = new ECKey(); ECKey toKey = new ECKey();
Address toAddress = toKey.toAddress(PARAMS); Address toAddress = Address.fromKey(PARAMS, toKey);
assertEquals(toAddress, ScriptBuilder.createOutputScript(toKey).getToAddress(PARAMS, true)); assertEquals(toAddress, ScriptBuilder.createOutputScript(toKey).getToAddress(PARAMS, true));
// pay to pubkey hash // pay to pubkey hash
assertEquals(toAddress, ScriptBuilder.createOutputScript(toAddress).getToAddress(PARAMS, true)); assertEquals(toAddress, ScriptBuilder.createOutputScript(toAddress).getToAddress(PARAMS, true));

View file

@ -29,18 +29,19 @@ import static org.junit.Assert.assertEquals;
public class SPVBlockStoreTest { public class SPVBlockStoreTest {
private static final NetworkParameters PARAMS = UnitTestParams.get();
@Test @Test
public void basics() throws Exception { public void basics() throws Exception {
NetworkParameters params = UnitTestParams.get();
File f = File.createTempFile("spvblockstore", null); File f = File.createTempFile("spvblockstore", null);
f.delete(); f.delete();
f.deleteOnExit(); f.deleteOnExit();
SPVBlockStore store = new SPVBlockStore(params, f); SPVBlockStore store = new SPVBlockStore(PARAMS, f);
Address to = new ECKey().toAddress(params); Address to = Address.fromKey(PARAMS, new ECKey());
// Check the first block in a new store is the genesis block. // Check the first block in a new store is the genesis block.
StoredBlock genesis = store.getChainHead(); StoredBlock genesis = store.getChainHead();
assertEquals(params.getGenesisBlock(), genesis.getHeader()); assertEquals(PARAMS.getGenesisBlock(), genesis.getHeader());
assertEquals(0, genesis.getHeight()); assertEquals(0, genesis.getHeight());
@ -51,7 +52,7 @@ public class SPVBlockStoreTest {
store.close(); store.close();
// Check we can get it back out again if we rebuild the store object. // Check we can get it back out again if we rebuild the store object.
store = new SPVBlockStore(params, f); store = new SPVBlockStore(PARAMS, f);
StoredBlock b2 = store.get(b1.getHeader().getHash()); StoredBlock b2 = store.get(b1.getHeader().getHash());
assertEquals(b1, b2); assertEquals(b1, b2);
// Check the chain head was stored correctly also. // Check the chain head was stored correctly also.

View file

@ -78,11 +78,11 @@ public class WalletProtobufSerializerTest {
myKey = new ECKey(); myKey = new ECKey();
myKey.setCreationTimeSeconds(123456789L); myKey.setCreationTimeSeconds(123456789L);
myWallet.importKey(myKey); myWallet.importKey(myKey);
myAddress = myKey.toAddress(PARAMS); myAddress = Address.fromKey(PARAMS, myKey);
myWallet = new Wallet(PARAMS); myWallet = new Wallet(PARAMS);
myWallet.importKey(myKey); myWallet.importKey(myKey);
mScriptCreationTime = new Date().getTime() / 1000 - 1234; mScriptCreationTime = new Date().getTime() / 1000 - 1234;
myWallet.addWatchedAddress(myWatchedKey.toAddress(PARAMS), mScriptCreationTime); myWallet.addWatchedAddress(Address.fromKey(PARAMS, myWatchedKey), mScriptCreationTime);
myWallet.setDescription(WALLET_DESCRIPTION); myWallet.setDescription(WALLET_DESCRIPTION);
} }
@ -101,7 +101,7 @@ public class WalletProtobufSerializerTest {
assertEquals(mScriptCreationTime, assertEquals(mScriptCreationTime,
wallet1.getWatchedScripts().get(0).getCreationTimeSeconds()); wallet1.getWatchedScripts().get(0).getCreationTimeSeconds());
assertEquals(1, wallet1.getWatchedScripts().size()); assertEquals(1, wallet1.getWatchedScripts().size());
assertEquals(ScriptBuilder.createOutputScript(myWatchedKey.toAddress(PARAMS)), assertEquals(ScriptBuilder.createOutputScript(Address.fromKey(PARAMS, myWatchedKey)),
wallet1.getWatchedScripts().get(0)); wallet1.getWatchedScripts().get(0));
assertEquals(WALLET_DESCRIPTION, wallet1.getDescription()); assertEquals(WALLET_DESCRIPTION, wallet1.getDescription());
} }
@ -176,7 +176,7 @@ public class WalletProtobufSerializerTest {
public void testKeys() throws Exception { public void testKeys() throws Exception {
for (int i = 0 ; i < 20 ; i++) { for (int i = 0 ; i < 20 ; i++) {
myKey = new ECKey(); myKey = new ECKey();
myAddress = myKey.toAddress(PARAMS); myAddress = Address.fromKey(PARAMS, myKey);
myWallet = new Wallet(PARAMS); myWallet = new Wallet(PARAMS);
myWallet.importKey(myKey); myWallet.importKey(myKey);
Wallet wallet1 = roundTrip(myWallet); Wallet wallet1 = roundTrip(myWallet);

View file

@ -34,12 +34,12 @@ import static com.google.common.base.Preconditions.checkState;
public class FakeTxBuilder { public class FakeTxBuilder {
/** Create a fake transaction, without change. */ /** Create a fake transaction, without change. */
public static Transaction createFakeTx(final NetworkParameters params) { public static Transaction createFakeTx(final NetworkParameters params) {
return createFakeTxWithoutChangeAddress(params, Coin.COIN, new ECKey().toAddress(params)); return createFakeTxWithoutChangeAddress(params, Coin.COIN, Address.fromKey(params, new ECKey()));
} }
/** Create a fake transaction, without change. */ /** Create a fake transaction, without change. */
public static Transaction createFakeTxWithoutChange(final NetworkParameters params, final TransactionOutput output) { public static Transaction createFakeTxWithoutChange(final NetworkParameters params, final TransactionOutput output) {
Transaction prevTx = FakeTxBuilder.createFakeTx(params, Coin.COIN, new ECKey().toAddress(params)); Transaction prevTx = FakeTxBuilder.createFakeTx(params, Coin.COIN, Address.fromKey(params, new ECKey()));
Transaction tx = new Transaction(params); Transaction tx = new Transaction(params);
tx.addOutput(output); tx.addOutput(output);
tx.addInput(prevTx.getOutput(0)); tx.addInput(prevTx.getOutput(0));
@ -53,7 +53,7 @@ public class FakeTxBuilder {
Transaction tx = new Transaction(params); Transaction tx = new Transaction(params);
tx.addInput(input); tx.addInput(input);
TransactionOutput outputToMe = new TransactionOutput(params, tx, Coin.FIFTY_COINS, TransactionOutput outputToMe = new TransactionOutput(params, tx, Coin.FIFTY_COINS,
new ECKey().toAddress(params)); Address.fromKey(params, new ECKey()));
tx.addOutput(outputToMe); tx.addOutput(outputToMe);
checkState(tx.isCoinBase()); checkState(tx.isCoinBase());
@ -123,7 +123,7 @@ public class FakeTxBuilder {
* else to simulate change. There is one random input. * else to simulate change. There is one random input.
*/ */
public static Transaction createFakeTx(NetworkParameters params, Coin value, Address to) { public static Transaction createFakeTx(NetworkParameters params, Coin value, Address to) {
return createFakeTxWithChangeAddress(params, value, to, new ECKey().toAddress(params)); return createFakeTxWithChangeAddress(params, value, to, Address.fromKey(params, new ECKey()));
} }
/** /**
@ -157,7 +157,7 @@ public class FakeTxBuilder {
Transaction t = new Transaction(params); Transaction t = new Transaction(params);
TransactionOutput outputToMe = new TransactionOutput(params, t, value, to); TransactionOutput outputToMe = new TransactionOutput(params, t, value, to);
t.addOutput(outputToMe); t.addOutput(outputToMe);
TransactionOutput change = new TransactionOutput(params, t, valueOf(1, 11), new ECKey().toAddress(params)); TransactionOutput change = new TransactionOutput(params, t, valueOf(1, 11), Address.fromKey(params, new ECKey()));
t.addOutput(change); 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 // 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. // matter for our purposes.
@ -203,7 +203,7 @@ public class FakeTxBuilder {
public static DoubleSpends createFakeDoubleSpendTxns(NetworkParameters params, Address to) { public static DoubleSpends createFakeDoubleSpendTxns(NetworkParameters params, Address to) {
DoubleSpends doubleSpends = new DoubleSpends(); DoubleSpends doubleSpends = new DoubleSpends();
Coin value = COIN; Coin value = COIN;
Address someBadGuy = new ECKey().toAddress(params); Address someBadGuy = Address.fromKey(params, new ECKey());
doubleSpends.prevTx = new Transaction(params); doubleSpends.prevTx = new Transaction(params);
TransactionOutput prevOut = new TransactionOutput(params, doubleSpends.prevTx, value, someBadGuy); TransactionOutput prevOut = new TransactionOutput(params, doubleSpends.prevTx, value, someBadGuy);
@ -245,7 +245,7 @@ public class FakeTxBuilder {
Transaction... transactions) { Transaction... transactions) {
try { try {
Block previousBlock = previousStoredBlock.getHeader(); Block previousBlock = previousStoredBlock.getHeader();
Address to = new ECKey().toAddress(previousBlock.getParams()); Address to = Address.fromKey(previousBlock.getParams(), new ECKey());
Block b = previousBlock.createNextBlock(to, version, timeSeconds, height); Block b = previousBlock.createNextBlock(to, version, timeSeconds, height);
// Coinbase tx was already added. // Coinbase tx was already added.
for (Transaction tx : transactions) { for (Transaction tx : transactions) {
@ -297,7 +297,7 @@ public class FakeTxBuilder {
} }
public static Block makeSolvedTestBlock(Block prev, Transaction... transactions) throws BlockStoreException { public static Block makeSolvedTestBlock(Block prev, Transaction... transactions) throws BlockStoreException {
Address to = new ECKey().toAddress(prev.getParams()); Address to = Address.fromKey(prev.getParams(), new ECKey());
Block b = prev.createNextBlock(to); Block b = prev.createNextBlock(to);
// Coinbase tx already exists. // Coinbase tx already exists.
for (Transaction tx : transactions) { for (Transaction tx : transactions) {

View file

@ -90,7 +90,7 @@ public class TestWithNetworkConnections {
if (wallet == null) { if (wallet == null) {
wallet = new Wallet(PARAMS); wallet = new Wallet(PARAMS);
key = wallet.freshReceiveKey(); key = wallet.freshReceiveKey();
address = key.toAddress(PARAMS); address = Address.fromKey(PARAMS, key);
} }
blockChain = new BlockChain(PARAMS, wallet, blockStore); blockChain = new BlockChain(PARAMS, wallet, blockStore);

View file

@ -49,7 +49,7 @@ public class TestWithWallet {
Context.propagate(new Context(PARAMS, 100, Coin.ZERO, false)); Context.propagate(new Context(PARAMS, 100, Coin.ZERO, false));
wallet = new Wallet(PARAMS); wallet = new Wallet(PARAMS);
myKey = wallet.currentReceiveKey(); myKey = wallet.currentReceiveKey();
myAddress = myKey.toAddress(PARAMS); myAddress = Address.fromKey(PARAMS, myKey);
blockStore = new MemoryBlockStore(PARAMS); blockStore = new MemoryBlockStore(PARAMS);
chain = new BlockChain(PARAMS, wallet, blockStore); chain = new BlockChain(PARAMS, wallet, blockStore);
} }

View file

@ -208,7 +208,7 @@ public class DefaultRiskAnalysisTest {
Transaction tx = new Transaction(PARAMS); Transaction tx = new Transaction(PARAMS);
tx.addInput(PARAMS.getGenesisBlock().getTransactions().get(0).getOutput(0)); tx.addInput(PARAMS.getGenesisBlock().getTransactions().get(0).getOutput(0));
// A pay to address output // A pay to address output
tx.addOutput(Coin.CENT, ScriptBuilder.createOutputScript(key1.toAddress(PARAMS))); tx.addOutput(Coin.CENT, ScriptBuilder.createOutputScript(Address.fromKey(PARAMS, key1)));
// A pay to pubkey output // A pay to pubkey output
tx.addOutput(Coin.CENT, ScriptBuilder.createOutputScript(key1)); tx.addOutput(Coin.CENT, ScriptBuilder.createOutputScript(key1));
tx.addOutput(Coin.CENT, ScriptBuilder.createOutputScript(key1)); tx.addOutput(Coin.CENT, ScriptBuilder.createOutputScript(key1));

View file

@ -46,6 +46,7 @@ public class DeterministicKeyChainTest {
private DeterministicKeyChain chain; private DeterministicKeyChain chain;
private DeterministicKeyChain bip44chain; private DeterministicKeyChain bip44chain;
private final byte[] ENTROPY = Sha256Hash.hash("don't use a string seed like this in real life".getBytes()); private final byte[] ENTROPY = Sha256Hash.hash("don't use a string seed like this in real life".getBytes());
private static final NetworkParameters PARAMS = UnitTestParams.get();
@Before @Before
public void setup() { public void setup() {
@ -70,9 +71,9 @@ public class DeterministicKeyChainTest {
ECKey key2 = chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS); ECKey key2 = chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
assertFalse(key2.isPubKeyOnly()); assertFalse(key2.isPubKeyOnly());
final Address address = Address.fromBase58(UnitTestParams.get(), "n1bQNoEx8uhmCzzA5JPG6sFdtsUQhwiQJV"); final Address address = Address.fromBase58(PARAMS, "n1bQNoEx8uhmCzzA5JPG6sFdtsUQhwiQJV");
assertEquals(address, key1.toAddress(UnitTestParams.get())); assertEquals(address, Address.fromKey(PARAMS, key1));
assertEquals("mnHUcqUVvrfi5kAaXJDQzBb9HsWs78b42R", key2.toAddress(UnitTestParams.get()).toString()); assertEquals("mnHUcqUVvrfi5kAaXJDQzBb9HsWs78b42R", Address.fromKey(PARAMS, key2).toString());
assertEquals(key1, chain.findKeyFromPubHash(address.getHash160())); assertEquals(key1, chain.findKeyFromPubHash(address.getHash160()));
assertEquals(key2, chain.findKeyFromPubKey(key2.getPubKey())); assertEquals(key2, chain.findKeyFromPubKey(key2.getPubKey()));
@ -81,7 +82,7 @@ public class DeterministicKeyChainTest {
ECKey key3 = chain.getKey(KeyChain.KeyPurpose.CHANGE); ECKey key3 = chain.getKey(KeyChain.KeyPurpose.CHANGE);
assertFalse(key3.isPubKeyOnly()); assertFalse(key3.isPubKeyOnly());
assertEquals("mqumHgVDqNzuXNrszBmi7A2UpmwaPMx4HQ", key3.toAddress(UnitTestParams.get()).toString()); assertEquals("mqumHgVDqNzuXNrszBmi7A2UpmwaPMx4HQ", Address.fromKey(PARAMS, key3).toString());
key3.sign(Sha256Hash.ZERO_HASH); key3.sign(Sha256Hash.ZERO_HASH);
assertFalse(key3.isPubKeyOnly()); assertFalse(key3.isPubKeyOnly());
} }
@ -101,16 +102,16 @@ public class DeterministicKeyChainTest {
ECKey key1 = chain1.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS); ECKey key1 = chain1.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
ECKey key2 = chain1.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS); ECKey key2 = chain1.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
final Address address = Address.fromBase58(UnitTestParams.get(), "n2nHHRHs7TiZScTuVhZUkzZfTfVgGYwy6X"); final Address address = Address.fromBase58(PARAMS, "n2nHHRHs7TiZScTuVhZUkzZfTfVgGYwy6X");
assertEquals(address, key1.toAddress(UnitTestParams.get())); assertEquals(address, Address.fromKey(PARAMS, key1));
assertEquals("mnp2j9za5zMuz44vNxrJCXXhZsCdh89QXn", key2.toAddress(UnitTestParams.get()).toString()); assertEquals("mnp2j9za5zMuz44vNxrJCXXhZsCdh89QXn", Address.fromKey(PARAMS, key2).toString());
assertEquals(key1, chain1.findKeyFromPubHash(address.getHash160())); assertEquals(key1, chain1.findKeyFromPubHash(address.getHash160()));
assertEquals(key2, chain1.findKeyFromPubKey(key2.getPubKey())); assertEquals(key2, chain1.findKeyFromPubKey(key2.getPubKey()));
key1.sign(Sha256Hash.ZERO_HASH); key1.sign(Sha256Hash.ZERO_HASH);
ECKey key3 = chain1.getKey(KeyChain.KeyPurpose.CHANGE); ECKey key3 = chain1.getKey(KeyChain.KeyPurpose.CHANGE);
assertEquals("mpjRhk13rvV7vmnszcUQVYVQzy4HLTPTQU", key3.toAddress(UnitTestParams.get()).toString()); assertEquals("mpjRhk13rvV7vmnszcUQVYVQzy4HLTPTQU", Address.fromKey(PARAMS, key3).toString());
key3.sign(Sha256Hash.ZERO_HASH); key3.sign(Sha256Hash.ZERO_HASH);
} }
@ -135,8 +136,8 @@ public class DeterministicKeyChainTest {
DeterministicKeyChain chain1 = new AccountOneChain(ENTROPY, "", secs); DeterministicKeyChain chain1 = new AccountOneChain(ENTROPY, "", secs);
ECKey key1 = chain1.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS); ECKey key1 = chain1.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
final Address address = Address.fromBase58(UnitTestParams.get(), "n2nHHRHs7TiZScTuVhZUkzZfTfVgGYwy6X"); final Address address = Address.fromBase58(PARAMS, "n2nHHRHs7TiZScTuVhZUkzZfTfVgGYwy6X");
assertEquals(address, key1.toAddress(UnitTestParams.get())); assertEquals(address, Address.fromKey(PARAMS, key1));
DeterministicKey watching = chain1.getWatchingKey(); DeterministicKey watching = chain1.getWatchingKey();
@ -162,14 +163,14 @@ public class DeterministicKeyChainTest {
chain1 = DeterministicKeyChain.fromProtobuf(keys, null, factory).get(0); chain1 = DeterministicKeyChain.fromProtobuf(keys, null, factory).get(0);
ECKey key2 = chain1.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS); ECKey key2 = chain1.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
assertEquals("mnp2j9za5zMuz44vNxrJCXXhZsCdh89QXn", key2.toAddress(UnitTestParams.get()).toString()); assertEquals("mnp2j9za5zMuz44vNxrJCXXhZsCdh89QXn", Address.fromKey(PARAMS, key2).toString());
assertEquals(key1, chain1.findKeyFromPubHash(address.getHash160())); assertEquals(key1, chain1.findKeyFromPubHash(address.getHash160()));
assertEquals(key2, chain1.findKeyFromPubKey(key2.getPubKey())); assertEquals(key2, chain1.findKeyFromPubKey(key2.getPubKey()));
key1.sign(Sha256Hash.ZERO_HASH); key1.sign(Sha256Hash.ZERO_HASH);
ECKey key3 = chain1.getKey(KeyChain.KeyPurpose.CHANGE); ECKey key3 = chain1.getKey(KeyChain.KeyPurpose.CHANGE);
assertEquals("mpjRhk13rvV7vmnszcUQVYVQzy4HLTPTQU", key3.toAddress(UnitTestParams.get()).toString()); assertEquals("mpjRhk13rvV7vmnszcUQVYVQzy4HLTPTQU", Address.fromKey(PARAMS, key3).toString());
key3.sign(Sha256Hash.ZERO_HASH); key3.sign(Sha256Hash.ZERO_HASH);
assertEquals(watching, chain1.getWatchingKey()); assertEquals(watching, chain1.getWatchingKey());

View file

@ -93,7 +93,7 @@ public class WalletTest extends TestWithWallet {
private static final CharSequence PASSWORD1 = "my helicopter contains eels"; private static final CharSequence PASSWORD1 = "my helicopter contains eels";
private static final CharSequence WRONG_PASSWORD = "nothing noone nobody nowhere"; private static final CharSequence WRONG_PASSWORD = "nothing noone nobody nowhere";
private final Address OTHER_ADDRESS = new ECKey().toAddress(PARAMS); private final Address OTHER_ADDRESS = Address.fromKey(PARAMS, new ECKey());
@Before @Before
@Override @Override
@ -158,7 +158,7 @@ public class WalletTest extends TestWithWallet {
public void basicSpendingWithEncryptedWallet() throws Exception { public void basicSpendingWithEncryptedWallet() throws Exception {
Wallet encryptedWallet = new Wallet(PARAMS); Wallet encryptedWallet = new Wallet(PARAMS);
encryptedWallet.encrypt(PASSWORD1); encryptedWallet.encrypt(PASSWORD1);
Address myEncryptedAddress = encryptedWallet.freshReceiveKey().toAddress(PARAMS); Address myEncryptedAddress = Address.fromKey(PARAMS, encryptedWallet.freshReceiveKey());
basicSpendingCommon(encryptedWallet, myEncryptedAddress, OTHER_ADDRESS, encryptedWallet); basicSpendingCommon(encryptedWallet, myEncryptedAddress, OTHER_ADDRESS, encryptedWallet);
} }
@ -776,7 +776,7 @@ public class WalletTest extends TestWithWallet {
// Create a send to a merchant of all our coins. // Create a send to a merchant of all our coins.
Transaction send1 = wallet.createSend(OTHER_ADDRESS, valueOf(2, 90)); Transaction send1 = wallet.createSend(OTHER_ADDRESS, valueOf(2, 90));
// Create a double spend of just the first one. // Create a double spend of just the first one.
Address BAD_GUY = new ECKey().toAddress(PARAMS); Address BAD_GUY = Address.fromKey(PARAMS, new ECKey());
Transaction send2 = wallet.createSend(BAD_GUY, COIN); Transaction send2 = wallet.createSend(BAD_GUY, COIN);
send2 = PARAMS.getDefaultSerializer().makeTransaction(send2.bitcoinSerialize()); send2 = PARAMS.getDefaultSerializer().makeTransaction(send2.bitcoinSerialize());
// Broadcast send1, it's now pending. // Broadcast send1, it's now pending.
@ -870,7 +870,7 @@ public class WalletTest extends TestWithWallet {
// Create a send to a merchant. // Create a send to a merchant.
Transaction send1 = wallet.createSend(OTHER_ADDRESS, valueOf(0, 50)); Transaction send1 = wallet.createSend(OTHER_ADDRESS, valueOf(0, 50));
// Create a double spend. // Create a double spend.
Address BAD_GUY = new ECKey().toAddress(PARAMS); Address BAD_GUY = Address.fromKey(PARAMS, new ECKey());
Transaction send2 = wallet.createSend(BAD_GUY, valueOf(0, 50)); Transaction send2 = wallet.createSend(BAD_GUY, valueOf(0, 50));
send2 = PARAMS.getDefaultSerializer().makeTransaction(send2.bitcoinSerialize()); send2 = PARAMS.getDefaultSerializer().makeTransaction(send2.bitcoinSerialize());
// Broadcast send1. // Broadcast send1.
@ -1405,7 +1405,7 @@ public class WalletTest extends TestWithWallet {
Coin nanos = COIN; Coin nanos = COIN;
// Create two transactions that share the same input tx. // Create two transactions that share the same input tx.
Address badGuy = new ECKey().toAddress(PARAMS); Address badGuy = Address.fromKey(PARAMS, new ECKey());
Transaction doubleSpentTx = new Transaction(PARAMS); Transaction doubleSpentTx = new Transaction(PARAMS);
TransactionOutput doubleSpentOut = new TransactionOutput(PARAMS, doubleSpentTx, nanos, badGuy); TransactionOutput doubleSpentOut = new TransactionOutput(PARAMS, doubleSpentTx, nanos, badGuy);
doubleSpentTx.addOutput(doubleSpentOut); doubleSpentTx.addOutput(doubleSpentOut);
@ -1617,7 +1617,7 @@ public class WalletTest extends TestWithWallet {
// Expected // Expected
} }
receiveATransaction(watchingWallet, myKey.toAddress(PARAMS)); receiveATransaction(watchingWallet, Address.fromKey(PARAMS, myKey));
assertEquals(COIN, watchingWallet.getBalance()); assertEquals(COIN, watchingWallet.getBalance());
assertEquals(COIN, watchingWallet.getBalance(Wallet.BalanceType.AVAILABLE)); assertEquals(COIN, watchingWallet.getBalance(Wallet.BalanceType.AVAILABLE));
assertEquals(ZERO, watchingWallet.getBalance(Wallet.BalanceType.AVAILABLE_SPENDABLE)); assertEquals(ZERO, watchingWallet.getBalance(Wallet.BalanceType.AVAILABLE_SPENDABLE));
@ -1641,7 +1641,7 @@ public class WalletTest extends TestWithWallet {
@Test @Test
public void watchingScripts() throws Exception { public void watchingScripts() throws Exception {
// Verify that pending transactions to watched addresses are relevant // Verify that pending transactions to watched addresses are relevant
Address watchedAddress = new ECKey().toAddress(PARAMS); Address watchedAddress = Address.fromKey(PARAMS, new ECKey());
wallet.addWatchedAddress(watchedAddress); wallet.addWatchedAddress(watchedAddress);
Coin value = valueOf(5, 0); Coin value = valueOf(5, 0);
Transaction t1 = createFakeTx(PARAMS, value, watchedAddress); Transaction t1 = createFakeTx(PARAMS, value, watchedAddress);
@ -1651,7 +1651,7 @@ public class WalletTest extends TestWithWallet {
@Test(expected = InsufficientMoneyException.class) @Test(expected = InsufficientMoneyException.class)
public void watchingScriptsConfirmed() throws Exception { public void watchingScriptsConfirmed() throws Exception {
Address watchedAddress = new ECKey().toAddress(PARAMS); Address watchedAddress = Address.fromKey(PARAMS, new ECKey());
wallet.addWatchedAddress(watchedAddress); wallet.addWatchedAddress(watchedAddress);
sendMoneyToWallet(BlockChain.NewBlockType.BEST_CHAIN, CENT, watchedAddress); sendMoneyToWallet(BlockChain.NewBlockType.BEST_CHAIN, CENT, watchedAddress);
assertEquals(CENT, wallet.getBalance()); assertEquals(CENT, wallet.getBalance());
@ -1664,7 +1664,7 @@ public class WalletTest extends TestWithWallet {
public void watchingScriptsSentFrom() throws Exception { public void watchingScriptsSentFrom() throws Exception {
int baseElements = wallet.getBloomFilterElementCount(); int baseElements = wallet.getBloomFilterElementCount();
Address watchedAddress = new ECKey().toAddress(PARAMS); Address watchedAddress = Address.fromKey(PARAMS, new ECKey());
wallet.addWatchedAddress(watchedAddress); wallet.addWatchedAddress(watchedAddress);
assertEquals(baseElements + 1, wallet.getBloomFilterElementCount()); assertEquals(baseElements + 1, wallet.getBloomFilterElementCount());
@ -1686,7 +1686,7 @@ public class WalletTest extends TestWithWallet {
public void watchingScriptsBloomFilter() throws Exception { public void watchingScriptsBloomFilter() throws Exception {
assertFalse(wallet.isRequiringUpdateAllBloomFilter()); assertFalse(wallet.isRequiringUpdateAllBloomFilter());
Address watchedAddress = new ECKey().toAddress(PARAMS); Address watchedAddress = Address.fromKey(PARAMS, new ECKey());
Transaction t1 = createFakeTx(PARAMS, CENT, watchedAddress); Transaction t1 = createFakeTx(PARAMS, CENT, watchedAddress);
TransactionOutPoint outPoint = new TransactionOutPoint(PARAMS, 0, t1); TransactionOutPoint outPoint = new TransactionOutPoint(PARAMS, 0, t1);
wallet.addWatchedAddress(watchedAddress); wallet.addWatchedAddress(watchedAddress);
@ -1701,7 +1701,7 @@ public class WalletTest extends TestWithWallet {
@Test @Test
public void getWatchedAddresses() throws Exception { public void getWatchedAddresses() throws Exception {
Address watchedAddress = new ECKey().toAddress(PARAMS); Address watchedAddress = Address.fromKey(PARAMS, new ECKey());
wallet.addWatchedAddress(watchedAddress); wallet.addWatchedAddress(watchedAddress);
List<Address> watchedAddresses = wallet.getWatchedAddresses(); List<Address> watchedAddresses = wallet.getWatchedAddresses();
assertEquals(1, watchedAddresses.size()); assertEquals(1, watchedAddresses.size());
@ -1712,7 +1712,7 @@ public class WalletTest extends TestWithWallet {
public void removeWatchedAddresses() { public void removeWatchedAddresses() {
List<Address> addressesForRemoval = new ArrayList<>(); List<Address> addressesForRemoval = new ArrayList<>();
for (int i = 0; i < 10; i++) { for (int i = 0; i < 10; i++) {
Address watchedAddress = new ECKey().toAddress(PARAMS); Address watchedAddress = Address.fromKey(PARAMS, new ECKey());
addressesForRemoval.add(watchedAddress); addressesForRemoval.add(watchedAddress);
wallet.addWatchedAddress(watchedAddress); wallet.addWatchedAddress(watchedAddress);
} }
@ -1726,7 +1726,7 @@ public class WalletTest extends TestWithWallet {
@Test @Test
public void removeWatchedAddress() { public void removeWatchedAddress() {
Address watchedAddress = new ECKey().toAddress(PARAMS); Address watchedAddress = Address.fromKey(PARAMS, new ECKey());
wallet.addWatchedAddress(watchedAddress); wallet.addWatchedAddress(watchedAddress);
wallet.removeWatchedAddress(watchedAddress); wallet.removeWatchedAddress(watchedAddress);
assertFalse(wallet.isAddressWatched(watchedAddress)); assertFalse(wallet.isAddressWatched(watchedAddress));
@ -1737,7 +1737,7 @@ public class WalletTest extends TestWithWallet {
public void removeScriptsBloomFilter() throws Exception { public void removeScriptsBloomFilter() throws Exception {
List<Address> addressesForRemoval = new ArrayList<>(); List<Address> addressesForRemoval = new ArrayList<>();
for (int i = 0; i < 10; i++) { for (int i = 0; i < 10; i++) {
Address watchedAddress = new ECKey().toAddress(PARAMS); Address watchedAddress = Address.fromKey(PARAMS, new ECKey());
addressesForRemoval.add(watchedAddress); addressesForRemoval.add(watchedAddress);
wallet.addWatchedAddress(watchedAddress); wallet.addWatchedAddress(watchedAddress);
} }
@ -1866,7 +1866,7 @@ public class WalletTest extends TestWithWallet {
ECKey k2 = wallet.freshReceiveKey(); ECKey k2 = wallet.freshReceiveKey();
Coin v2 = valueOf(0, 50); Coin v2 = valueOf(0, 50);
Transaction t2 = new Transaction(PARAMS); Transaction t2 = new Transaction(PARAMS);
TransactionOutput o2 = new TransactionOutput(PARAMS, t2, v2, k2.toAddress(PARAMS)); TransactionOutput o2 = new TransactionOutput(PARAMS, t2, v2, Address.fromKey(PARAMS, k2));
t2.addOutput(o2); t2.addOutput(o2);
SendRequest req = SendRequest.forTx(t2); SendRequest req = SendRequest.forTx(t2);
wallet.completeTx(req); wallet.completeTx(req);
@ -1881,7 +1881,7 @@ public class WalletTest extends TestWithWallet {
ECKey k3 = new ECKey(); ECKey k3 = new ECKey();
Coin v3 = valueOf(0, 25); Coin v3 = valueOf(0, 25);
Transaction t3 = new Transaction(PARAMS); Transaction t3 = new Transaction(PARAMS);
t3.addOutput(v3, k3.toAddress(PARAMS)); t3.addOutput(v3, Address.fromKey(PARAMS, k3));
t3.addInput(o2); t3.addInput(o2);
wallet.signTransaction(SendRequest.forTx(t3)); wallet.signTransaction(SendRequest.forTx(t3));
@ -2109,7 +2109,7 @@ public class WalletTest extends TestWithWallet {
encryptedWallet.importKeysAndEncrypt(ImmutableList.of(key), PASSWORD1); encryptedWallet.importKeysAndEncrypt(ImmutableList.of(key), PASSWORD1);
assertEquals(1, encryptedWallet.getImportedKeys().size()); assertEquals(1, encryptedWallet.getImportedKeys().size());
assertEquals(key.getPubKeyPoint(), encryptedWallet.getImportedKeys().get(0).getPubKeyPoint()); assertEquals(key.getPubKeyPoint(), encryptedWallet.getImportedKeys().get(0).getPubKeyPoint());
sendMoneyToWallet(encryptedWallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, Coin.COIN, key.toAddress(PARAMS)); sendMoneyToWallet(encryptedWallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, Coin.COIN, Address.fromKey(PARAMS, key));
assertEquals(Coin.COIN, encryptedWallet.getBalance()); assertEquals(Coin.COIN, encryptedWallet.getBalance());
SendRequest req = SendRequest.emptyWallet(OTHER_ADDRESS); SendRequest req = SendRequest.emptyWallet(OTHER_ADDRESS);
req.aesKey = checkNotNull(encryptedWallet.getKeyCrypter()).deriveKey(PASSWORD1); req.aesKey = checkNotNull(encryptedWallet.getKeyCrypter()).deriveKey(PASSWORD1);
@ -2905,9 +2905,9 @@ public class WalletTest extends TestWithWallet {
key2.setCreationTimeSeconds(Utils.currentTimeSeconds() - 86400); key2.setCreationTimeSeconds(Utils.currentTimeSeconds() - 86400);
wallet.importKey(key1); wallet.importKey(key1);
wallet.importKey(key2); wallet.importKey(key2);
sendMoneyToWallet(wallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, key1.toAddress(PARAMS)); sendMoneyToWallet(wallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, Address.fromKey(PARAMS, key1));
sendMoneyToWallet(wallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, key2.toAddress(PARAMS)); sendMoneyToWallet(wallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, Address.fromKey(PARAMS, key2));
sendMoneyToWallet(wallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, key2.toAddress(PARAMS)); sendMoneyToWallet(wallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, Address.fromKey(PARAMS, key2));
Date compromiseTime = Utils.now(); Date compromiseTime = Utils.now();
assertEquals(0, broadcaster.size()); assertEquals(0, broadcaster.size());
assertFalse(wallet.isKeyRotating(key1)); assertFalse(wallet.isKeyRotating(key1));
@ -2938,7 +2938,7 @@ public class WalletTest extends TestWithWallet {
assertEquals(0, broadcaster.size()); assertEquals(0, broadcaster.size());
// Receive money via a new block on key1 and ensure it shows up as a maintenance task. // Receive money via a new block on key1 and ensure it shows up as a maintenance task.
sendMoneyToWallet(wallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, key1.toAddress(PARAMS)); sendMoneyToWallet(wallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, Address.fromKey(PARAMS, key1));
wallet.doMaintenance(null, true); wallet.doMaintenance(null, true);
tx = broadcaster.waitForTransactionAndSucceed(); tx = broadcaster.waitForTransactionAndSucceed();
assertNotNull(wallet.findKeyFromPubHash(tx.getOutput(0).getScriptPubKey().getPubKeyHash())); assertNotNull(wallet.findKeyFromPubHash(tx.getOutput(0).getScriptPubKey().getPubKeyHash()));
@ -2980,8 +2980,8 @@ public class WalletTest extends TestWithWallet {
wallet = new Wallet(PARAMS); wallet = new Wallet(PARAMS);
ECKey key1 = wallet.freshReceiveKey(); ECKey key1 = wallet.freshReceiveKey();
ECKey key2 = wallet.freshReceiveKey(); ECKey key2 = wallet.freshReceiveKey();
sendMoneyToWallet(wallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, key1.toAddress(PARAMS)); sendMoneyToWallet(wallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, Address.fromKey(PARAMS, key1));
sendMoneyToWallet(wallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, key2.toAddress(PARAMS)); sendMoneyToWallet(wallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, Address.fromKey(PARAMS, key2));
DeterministicKey watchKey1 = wallet.getWatchingKey(); DeterministicKey watchKey1 = wallet.getWatchingKey();
// A day later, we get compromised. // A day later, we get compromised.
@ -3025,7 +3025,7 @@ public class WalletTest extends TestWithWallet {
wallet.upgradeToDeterministic(null); wallet.upgradeToDeterministic(null);
DeterministicKey badWatchingKey = wallet.getWatchingKey(); DeterministicKey badWatchingKey = wallet.getWatchingKey();
assertEquals(badKey.getCreationTimeSeconds(), badWatchingKey.getCreationTimeSeconds()); assertEquals(badKey.getCreationTimeSeconds(), badWatchingKey.getCreationTimeSeconds());
sendMoneyToWallet(wallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, badWatchingKey.toAddress(PARAMS)); sendMoneyToWallet(wallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, Address.fromKey(PARAMS, badWatchingKey));
// Now we set the rotation time to the time we started making good keys. This should create a new HD chain. // Now we set the rotation time to the time we started making good keys. This should create a new HD chain.
wallet.setKeyRotationTime(goodKey.getCreationTimeSeconds()); wallet.setKeyRotationTime(goodKey.getCreationTimeSeconds());
@ -3035,7 +3035,7 @@ public class WalletTest extends TestWithWallet {
ECKey usedKey = wallet.findKeyFromPubHash(output.getHash160()); ECKey usedKey = wallet.findKeyFromPubHash(output.getHash160());
assertEquals(goodKey.getCreationTimeSeconds(), usedKey.getCreationTimeSeconds()); assertEquals(goodKey.getCreationTimeSeconds(), usedKey.getCreationTimeSeconds());
assertEquals(goodKey.getCreationTimeSeconds(), wallet.freshReceiveKey().getCreationTimeSeconds()); assertEquals(goodKey.getCreationTimeSeconds(), wallet.freshReceiveKey().getCreationTimeSeconds());
assertEquals("mrM3TpCnav5YQuVA1xLercCGJH4DXujMtv", usedKey.toAddress(PARAMS).toString()); assertEquals("mrM3TpCnav5YQuVA1xLercCGJH4DXujMtv", Address.fromKey(PARAMS, usedKey).toString());
DeterministicKeyChain c = fChains.get().get(1); DeterministicKeyChain c = fChains.get().get(1);
assertEquals(c.getEarliestKeyCreationTime(), goodKey.getCreationTimeSeconds()); assertEquals(c.getEarliestKeyCreationTime(), goodKey.getCreationTimeSeconds());
assertEquals(2, fChains.get().size()); assertEquals(2, fChains.get().size());
@ -3058,7 +3058,7 @@ public class WalletTest extends TestWithWallet {
public void fragmentedReKeying() throws Exception { public void fragmentedReKeying() throws Exception {
// Send lots of small coins and check the fee is correct. // Send lots of small coins and check the fee is correct.
ECKey key = wallet.freshReceiveKey(); ECKey key = wallet.freshReceiveKey();
Address address = key.toAddress(PARAMS); Address address = Address.fromKey(PARAMS, key);
Utils.setMockClock(); Utils.setMockClock();
Utils.rollMockClock(86400); Utils.rollMockClock(86400);
for (int i = 0; i < 800; i++) { for (int i = 0; i < 800; i++) {
@ -3167,7 +3167,7 @@ public class WalletTest extends TestWithWallet {
// Send three transactions, with one being an address type and the other being a raw CHECKSIG type pubkey only, // 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 // 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. // to be signed correctly.
Transaction t1 = sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, pub.toAddress(PARAMS)); Transaction t1 = sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, Address.fromKey(PARAMS, pub));
Transaction t2 = sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, pub); Transaction t2 = sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, pub);
Transaction t3 = sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, priv2); Transaction t3 = sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, priv2);

View file

@ -210,7 +210,7 @@ public class ExamplePaymentChannelClient {
ListenableFuture<Coin> balanceFuture = appKit.wallet().getBalanceFuture(amountPlusFee, Wallet.BalanceType.ESTIMATED); ListenableFuture<Coin> balanceFuture = appKit.wallet().getBalanceFuture(amountPlusFee, Wallet.BalanceType.ESTIMATED);
if (!balanceFuture.isDone()) { if (!balanceFuture.isDone()) {
System.out.println("Please send " + amountPlusFee.toFriendlyString() + System.out.println("Please send " + amountPlusFee.toFriendlyString() +
" to " + myKey.toAddress(params)); " to " + Address.fromKey(params, myKey));
Futures.getUnchecked(balanceFuture); Futures.getUnchecked(balanceFuture);
} }
} }

View file

@ -111,7 +111,7 @@ public class ForwardingService {
} }
}); });
Address sendToAddress = kit.wallet().currentReceiveKey().toAddress(params); Address sendToAddress = Address.fromKey(params, kit.wallet().currentReceiveKey());
System.out.println("Send coins to: " + sendToAddress); System.out.println("Send coins to: " + sendToAddress);
System.out.println("Waiting for coins to arrive. Press Ctrl-C to quit."); System.out.println("Waiting for coins to arrive. Press Ctrl-C to quit.");

View file

@ -24,6 +24,7 @@ import java.util.EnumSet;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import org.bitcoinj.core.Address;
import org.bitcoinj.core.Coin; import org.bitcoinj.core.Coin;
import org.bitcoinj.core.ECKey; import org.bitcoinj.core.ECKey;
import org.bitcoinj.core.NetworkParameters; import org.bitcoinj.core.NetworkParameters;
@ -81,11 +82,11 @@ public class GenerateLowSTests {
final Transaction outputTransaction = new Transaction(params); final Transaction outputTransaction = new Transaction(params);
final Transaction inputTransaction = new Transaction(params); final Transaction inputTransaction = new Transaction(params);
final TransactionOutput output = new TransactionOutput(params, inputTransaction, Coin.ZERO, key.toAddress(params)); final TransactionOutput output = new TransactionOutput(params, inputTransaction, Coin.ZERO, Address.fromKey(params, key));
inputTransaction.addOutput(output); inputTransaction.addOutput(output);
outputTransaction.addInput(output); outputTransaction.addInput(output);
outputTransaction.addOutput(Coin.ZERO, new ECKey(secureRandom).toAddress(params)); outputTransaction.addOutput(Coin.ZERO, Address.fromKey(params, new ECKey(secureRandom)));
addOutputs(outputTransaction, bag); addOutputs(outputTransaction, bag);

View file

@ -50,7 +50,7 @@ public class PrivateKeys {
BigInteger privKey = Base58.decodeToBigInteger(args[0]); BigInteger privKey = Base58.decodeToBigInteger(args[0]);
key = ECKey.fromPrivate(privKey); key = ECKey.fromPrivate(privKey);
} }
System.out.println("Address from private key is: " + key.toAddress(params).toString()); System.out.println("Address from private key is: " + Address.fromKey(params, key).toString());
// And the address ... // And the address ...
Address destination = Address.fromBase58(params, args[1]); Address destination = Address.fromBase58(params, args[1]);

View file

@ -1355,7 +1355,7 @@ public class WalletTool {
} }
key = wallet.freshReceiveKey(); key = wallet.freshReceiveKey();
} }
System.out.println(key.toAddress(params) + " " + key); System.out.println(Address.fromKey(params, key) + " " + key);
} }
} }
@ -1420,7 +1420,7 @@ public class WalletTool {
key = key.encrypt(checkNotNull(wallet.getKeyCrypter()), aesKey); key = key.encrypt(checkNotNull(wallet.getKeyCrypter()), aesKey);
} }
wallet.importKey(key); wallet.importKey(key);
System.out.println(key.toAddress(params) + " " + key); System.out.println(Address.fromKey(params, key) + " " + key);
} catch (KeyCrypterException kce) { } catch (KeyCrypterException kce) {
System.err.println("There was an encryption related error when adding the key. The error was '" + kce.getMessage() + "'."); System.err.println("There was an encryption related error when adding the key. The error was '" + kce.getMessage() + "'.");
} }
@ -1480,7 +1480,7 @@ public class WalletTool {
private static void currentReceiveAddr() { private static void currentReceiveAddr() {
ECKey key = wallet.currentReceiveKey(); ECKey key = wallet.currentReceiveKey();
System.out.println(key.toAddress(params) + " " + key); System.out.println(Address.fromKey(params, key) + " " + key);
} }
private static void dumpWallet() throws BlockStoreException { private static void dumpWallet() throws BlockStoreException {