From 2aec06a28142dbe21a7b7e90a0fe1eb4bb4b3db3 Mon Sep 17 00:00:00 2001 From: Andreas Schildbach Date: Wed, 28 Feb 2018 00:51:43 +0100 Subject: [PATCH] Consequently use constants for network params in test cases. --- .../AbstractFullPrunedBlockChainTest.java | 9 +- .../java/org/bitcoinj/core/AddressTest.java | 20 +- .../bitcoinj/core/BitcoinSerializerTest.java | 16 +- .../bitcoinj/core/BitcoindComparisonTool.java | 31 +- .../org/bitcoinj/core/BlockChainTest.java | 83 ++-- .../java/org/bitcoinj/core/BlockTest.java | 64 ++- .../org/bitcoinj/core/BloomFilterTest.java | 15 +- .../org/bitcoinj/core/ChainSplitTest.java | 84 ++-- .../bitcoinj/core/DumpedPrivateKeyTest.java | 5 +- .../java/org/bitcoinj/core/ECKeyTest.java | 30 +- ...ilteredBlockAndPartialMerkleTreeTests.java | 36 +- .../java/org/bitcoinj/core/MessageTest.java | 7 +- .../org/bitcoinj/core/ParseByteCacheTest.java | 38 +- .../org/bitcoinj/core/PeerAddressTest.java | 9 +- .../java/org/bitcoinj/core/PeerGroupTest.java | 62 +-- .../test/java/org/bitcoinj/core/PeerTest.java | 149 ++++--- .../bitcoinj/core/SendHeadersMessageTest.java | 5 +- .../core/TransactionBroadcastTest.java | 16 +- .../bitcoinj/core/TransactionInputTest.java | 15 +- .../bitcoinj/core/TransactionOutputTest.java | 16 +- .../org/bitcoinj/core/TransactionTest.java | 58 +-- .../bitcoinj/core/TxConfidenceTableTest.java | 20 +- .../org/bitcoinj/core/VersionMessageTest.java | 12 +- .../java/org/bitcoinj/crypto/BIP32Test.java | 10 +- .../bitcoinj/crypto/BIP38PrivateKeyTest.java | 18 +- .../crypto/ChildKeyDerivationTest.java | 35 +- .../bitcoinj/net/discovery/SeedPeersTest.java | 13 +- .../channels/ChannelConnectionTest.java | 10 +- .../channels/PaymentChannelStateTest.java | 74 ++-- .../payments/PaymentProtocolTest.java | 13 +- .../payments/PaymentSessionTest.java | 22 +- .../bitcoinj/script/ScriptPatternTest.java | 4 +- .../java/org/bitcoinj/script/ScriptTest.java | 55 +-- .../bitcoinj/store/LevelDBBlockStoreTest.java | 9 +- .../org/bitcoinj/store/SPVBlockStoreTest.java | 11 +- .../store/WalletProtobufSerializerTest.java | 72 ++-- .../testing/TestWithNetworkConnections.java | 14 +- .../bitcoinj/testing/TestWithPeerGroup.java | 6 +- .../org/bitcoinj/testing/TestWithWallet.java | 19 +- .../java/org/bitcoinj/uri/BitcoinURITest.java | 7 +- .../org/bitcoinj/utils/VersionTallyTest.java | 36 +- .../wallet/DefaultCoinSelectorTest.java | 23 +- .../wallet/DefaultRiskAnalysisTest.java | 60 +-- .../wallet/DeterministicKeyChainTest.java | 38 +- .../bitcoinj/wallet/KeyChainGroupTest.java | 48 +-- .../java/org/bitcoinj/wallet/WalletTest.java | 366 +++++++++--------- 46 files changed, 890 insertions(+), 873 deletions(-) diff --git a/core/src/test/java/org/bitcoinj/core/AbstractFullPrunedBlockChainTest.java b/core/src/test/java/org/bitcoinj/core/AbstractFullPrunedBlockChainTest.java index b5dbbaa1..9f095ff1 100644 --- a/core/src/test/java/org/bitcoinj/core/AbstractFullPrunedBlockChainTest.java +++ b/core/src/test/java/org/bitcoinj/core/AbstractFullPrunedBlockChainTest.java @@ -57,6 +57,8 @@ public abstract class AbstractFullPrunedBlockChainTest { return 10000; } }; + private static final NetworkParameters MAINNET = MainNetParams.get(); + protected FullPrunedBlockChain chain; protected FullPrunedBlockStore store; @@ -219,12 +221,11 @@ public abstract class AbstractFullPrunedBlockChainTest { @Test public void testFirst100KBlocks() throws Exception { - NetworkParameters params = MainNetParams.get(); - Context context = new Context(params); + Context context = new Context(MAINNET); File blockFile = new File(getClass().getResource("first-100k-blocks.dat").getFile()); - BlockFileLoader loader = new BlockFileLoader(params, Arrays.asList(blockFile)); + BlockFileLoader loader = new BlockFileLoader(MAINNET, Arrays.asList(blockFile)); - store = createStore(params, 10); + store = createStore(MAINNET, 10); resetStore(store); chain = new FullPrunedBlockChain(context, store); for (Block block : loader) diff --git a/core/src/test/java/org/bitcoinj/core/AddressTest.java b/core/src/test/java/org/bitcoinj/core/AddressTest.java index 4a186e0c..f3652f7f 100644 --- a/core/src/test/java/org/bitcoinj/core/AddressTest.java +++ b/core/src/test/java/org/bitcoinj/core/AddressTest.java @@ -104,7 +104,7 @@ public class AddressTest { fail(); } catch (WrongNetworkException e) { // Success. - assertEquals(e.verCode, MainNetParams.get().getAddressHeader()); + assertEquals(e.verCode, MAINNET.getAddressHeader()); } catch (AddressFormatException e) { fail(); } @@ -113,9 +113,9 @@ public class AddressTest { @Test public void getNetwork() throws Exception { NetworkParameters params = Address.getParametersFromAddress("17kzeh4N8g49GFvdDzSf8PjaPfyoD1MndL"); - assertEquals(MainNetParams.get().getId(), params.getId()); + assertEquals(MAINNET.getId(), params.getId()); params = Address.getParametersFromAddress("n4eA2nbYqErp7H6jebchxAN59DmNpksexv"); - assertEquals(TestNet3Params.get().getId(), params.getId()); + assertEquals(TESTNET.getId(), params.getId()); } @Test @@ -137,7 +137,7 @@ public class AddressTest { assertEquals(altNetwork.getId(), params.getId()); // Check if main network works as before params = Address.getParametersFromAddress("17kzeh4N8g49GFvdDzSf8PjaPfyoD1MndL"); - assertEquals(MainNetParams.get().getId(), params.getId()); + assertEquals(MAINNET.getId(), params.getId()); // Unregister network Networks.unregister(altNetwork); try { @@ -149,18 +149,18 @@ public class AddressTest { @Test public void p2shAddress() throws Exception { // Test that we can construct P2SH addresses - Address mainNetP2SHAddress = Address.fromBase58(MainNetParams.get(), "35b9vsyH1KoFT5a5KtrKusaCcPLkiSo1tU"); - assertEquals(mainNetP2SHAddress.version, MainNetParams.get().p2shHeader); + Address mainNetP2SHAddress = Address.fromBase58(MAINNET, "35b9vsyH1KoFT5a5KtrKusaCcPLkiSo1tU"); + assertEquals(mainNetP2SHAddress.version, MAINNET.p2shHeader); assertTrue(mainNetP2SHAddress.isP2SHAddress()); - Address testNetP2SHAddress = Address.fromBase58(TestNet3Params.get(), "2MuVSxtfivPKJe93EC1Tb9UhJtGhsoWEHCe"); - assertEquals(testNetP2SHAddress.version, TestNet3Params.get().p2shHeader); + Address testNetP2SHAddress = Address.fromBase58(TESTNET, "2MuVSxtfivPKJe93EC1Tb9UhJtGhsoWEHCe"); + assertEquals(testNetP2SHAddress.version, TESTNET.p2shHeader); assertTrue(testNetP2SHAddress.isP2SHAddress()); // Test that we can determine what network a P2SH address belongs to NetworkParameters mainNetParams = Address.getParametersFromAddress("35b9vsyH1KoFT5a5KtrKusaCcPLkiSo1tU"); - assertEquals(MainNetParams.get().getId(), mainNetParams.getId()); + assertEquals(MAINNET.getId(), mainNetParams.getId()); NetworkParameters testNetParams = Address.getParametersFromAddress("2MuVSxtfivPKJe93EC1Tb9UhJtGhsoWEHCe"); - assertEquals(TestNet3Params.get().getId(), testNetParams.getId()); + assertEquals(TESTNET.getId(), testNetParams.getId()); // Test that we can convert them from hashes byte[] hex = HEX.decode("2ac4b0b501117cc8119c5797b519538d4942e90e"); diff --git a/core/src/test/java/org/bitcoinj/core/BitcoinSerializerTest.java b/core/src/test/java/org/bitcoinj/core/BitcoinSerializerTest.java index c43cbac6..36be9714 100644 --- a/core/src/test/java/org/bitcoinj/core/BitcoinSerializerTest.java +++ b/core/src/test/java/org/bitcoinj/core/BitcoinSerializerTest.java @@ -30,6 +30,7 @@ import static org.bitcoinj.core.Utils.HEX; import static org.junit.Assert.*; public class BitcoinSerializerTest { + private static final NetworkParameters MAINNET = MainNetParams.get(); private static final byte[] ADDRESS_MESSAGE_BYTES = HEX.decode("f9beb4d96164647200000000000000001f000000" + "ed52399b01e215104d010000000000000000000000000000000000ffff0a000001208d"); @@ -55,8 +56,7 @@ public class BitcoinSerializerTest { @Test public void testAddr() throws Exception { - final NetworkParameters params = MainNetParams.get(); - MessageSerializer serializer = params.getDefaultSerializer(); + MessageSerializer serializer = MAINNET.getDefaultSerializer(); // the actual data from https://en.bitcoin.it/wiki/Protocol_specification#addr AddressMessage addressMessage = (AddressMessage) serializer.deserialize(ByteBuffer.wrap(ADDRESS_MESSAGE_BYTES)); assertEquals(1, addressMessage.getAddresses().size()); @@ -67,7 +67,7 @@ public class BitcoinSerializerTest { serializer.serialize(addressMessage, bos); assertEquals(31, addressMessage.getMessageSize()); - addressMessage.addAddress(new PeerAddress(params, InetAddress.getLocalHost())); + addressMessage.addAddress(new PeerAddress(MAINNET, InetAddress.getLocalHost())); assertEquals(61, addressMessage.getMessageSize()); addressMessage.removeAddress(0); assertEquals(31, addressMessage.getMessageSize()); @@ -78,7 +78,7 @@ public class BitcoinSerializerTest { @Test public void testCachedParsing() throws Exception { - MessageSerializer serializer = MainNetParams.get().getSerializer(true); + MessageSerializer serializer = MAINNET.getSerializer(true); // first try writing to a fields to ensure uncaching and children are not affected Transaction transaction = (Transaction) serializer.deserialize(ByteBuffer.wrap(TRANSACTION_MESSAGE_BYTES)); @@ -135,7 +135,7 @@ public class BitcoinSerializerTest { */ @Test public void testHeaders1() throws Exception { - MessageSerializer serializer = MainNetParams.get().getDefaultSerializer(); + MessageSerializer serializer = MAINNET.getDefaultSerializer(); byte[] headersMessageBytes = HEX.decode("f9beb4d9686561" + "646572730000000000520000005d4fab8101010000006fe28c0ab6f1b372c1a6a246ae6" + @@ -161,7 +161,7 @@ public class BitcoinSerializerTest { */ @Test public void testHeaders2() throws Exception { - MessageSerializer serializer = MainNetParams.get().getDefaultSerializer(); + MessageSerializer serializer = MAINNET.getDefaultSerializer(); byte[] headersMessageBytes = HEX.decode("f9beb4d96865616465" + "72730000000000e701000085acd4ea06010000006fe28c0ab6f1b372c1a6a246ae63f74f931e" + @@ -217,7 +217,7 @@ public class BitcoinSerializerTest { public void testSeekPastMagicBytes() { // Fail in another way, there is data in the stream but no magic bytes. byte[] brokenMessage = HEX.decode("000000"); - MainNetParams.get().getDefaultSerializer().seekPastMagicBytes(ByteBuffer.wrap(brokenMessage)); + MAINNET.getDefaultSerializer().seekPastMagicBytes(ByteBuffer.wrap(brokenMessage)); } /** @@ -225,7 +225,7 @@ public class BitcoinSerializerTest { */ @Test(expected = Error.class) public void testSerializeUnknownMessage() throws Exception { - MessageSerializer serializer = MainNetParams.get().getDefaultSerializer(); + MessageSerializer serializer = MAINNET.getDefaultSerializer(); Message unknownMessage = new Message() { @Override diff --git a/core/src/test/java/org/bitcoinj/core/BitcoindComparisonTool.java b/core/src/test/java/org/bitcoinj/core/BitcoindComparisonTool.java index 6eb5e10c..00218922 100644 --- a/core/src/test/java/org/bitcoinj/core/BitcoindComparisonTool.java +++ b/core/src/test/java/org/bitcoinj/core/BitcoindComparisonTool.java @@ -40,7 +40,7 @@ import java.util.concurrent.atomic.*; public class BitcoindComparisonTool { private static final Logger log = LoggerFactory.getLogger(BitcoindComparisonTool.class); - private static NetworkParameters params; + private static final NetworkParameters PARAMS = RegTestParams.get(); private static FullPrunedBlockChain chain; private static Sha256Hash bitcoindChainHead; private static volatile InventoryMessage mostRecentInv = null; @@ -54,31 +54,30 @@ public class BitcoindComparisonTool { System.out.println("USAGE: bitcoinjBlockStoreLocation runExpensiveTests(1/0) [port=18444]"); boolean runExpensiveTests = args.length > 1 && Integer.parseInt(args[1]) == 1; - params = RegTestParams.get(); - Context ctx = new Context(params); + Context ctx = new Context(PARAMS); File blockFile = File.createTempFile("testBlocks", ".dat"); blockFile.deleteOnExit(); - FullBlockTestGenerator generator = new FullBlockTestGenerator(params); + FullBlockTestGenerator generator = new FullBlockTestGenerator(PARAMS); final RuleList blockList = generator.getBlocksToTest(false, runExpensiveTests, blockFile); final Map preloadedBlocks = new HashMap<>(); - final Iterator blocks = new BlockFileLoader(params, Arrays.asList(blockFile)); + final Iterator blocks = new BlockFileLoader(PARAMS, Arrays.asList(blockFile)); try { - H2FullPrunedBlockStore store = new H2FullPrunedBlockStore(params, args.length > 0 ? args[0] : "BitcoindComparisonTool", blockList.maximumReorgBlockCount); + H2FullPrunedBlockStore store = new H2FullPrunedBlockStore(PARAMS, args.length > 0 ? args[0] : "BitcoindComparisonTool", blockList.maximumReorgBlockCount); store.resetStore(); //store = new MemoryFullPrunedBlockStore(params, blockList.maximumReorgBlockCount); - chain = new FullPrunedBlockChain(params, store); + chain = new FullPrunedBlockChain(PARAMS, store); } catch (BlockStoreException e) { e.printStackTrace(); System.exit(1); } - VersionMessage ver = new VersionMessage(params, 42); + VersionMessage ver = new VersionMessage(PARAMS, 42); ver.appendToSubVer("BlockAcceptanceComparisonTool", "1.1", null); ver.localServices = VersionMessage.NODE_NETWORK; - final Peer bitcoind = new Peer(params, ver, new BlockChain(params, new MemoryBlockStore(params)), new PeerAddress(params, InetAddress.getLocalHost())); + final Peer bitcoind = new Peer(PARAMS, ver, new BlockChain(PARAMS, new MemoryBlockStore(PARAMS)), new PeerAddress(PARAMS, InetAddress.getLocalHost())); Preconditions.checkState(bitcoind.getVersionMessage().hasBlockChain()); final BlockWrapper currentBlock = new BlockWrapper(); @@ -180,8 +179,8 @@ public class BitcoindComparisonTool { } if (!found) sendHeaders = headers; - bitcoind.sendMessage(new HeadersMessage(params, sendHeaders)); - InventoryMessage i = new InventoryMessage(params); + bitcoind.sendMessage(new HeadersMessage(PARAMS, sendHeaders)); + InventoryMessage i = new InventoryMessage(PARAMS); for (Block b : sendHeaders) i.addBlock(b); bitcoind.sendMessage(i); @@ -200,15 +199,15 @@ public class BitcoindComparisonTool { } }); - bitcoindChainHead = params.getGenesisBlock().getHash(); + bitcoindChainHead = PARAMS.getGenesisBlock().getHash(); // bitcoind MUST be on localhost or we will get banned as a DoSer - new NioClient(new InetSocketAddress(InetAddress.getByName("127.0.0.1"), args.length > 2 ? Integer.parseInt(args[2]) : params.getPort()), bitcoind, 1000); + new NioClient(new InetSocketAddress(InetAddress.getByName("127.0.0.1"), args.length > 2 ? Integer.parseInt(args[2]) : PARAMS.getPort()), bitcoind, 1000); connectedFuture.get(); ArrayList locator = new ArrayList<>(1); - locator.add(params.getGenesisBlock().getHash()); + locator.add(PARAMS.getGenesisBlock().getHash()); Sha256Hash hashTo = Sha256Hash.wrap("0000000000000000000000000000000000000000000000000000000000000000"); int rulesSinceFirstFail = 0; @@ -266,7 +265,7 @@ public class BitcoindComparisonTool { boolean shouldntRequest = blocksRequested.contains(nextBlock.getHash()); if (shouldntRequest) blocksRequested.remove(nextBlock.getHash()); - InventoryMessage message = new InventoryMessage(params); + InventoryMessage message = new InventoryMessage(PARAMS); message.addBlock(nextBlock); bitcoind.sendMessage(message); log.info("Sent inv with block " + nextBlock.getHashAsString()); @@ -298,7 +297,7 @@ public class BitcoindComparisonTool { //bitcoind.sendMessage(nextBlock); locator.clear(); locator.add(bitcoindChainHead); - bitcoind.sendMessage(new GetHeadersMessage(params, locator, hashTo)); + bitcoind.sendMessage(new GetHeadersMessage(PARAMS, locator, hashTo)); bitcoind.ping().get(); if (!chain.getChainHead().getHeader().getHash().equals(bitcoindChainHead)) { rulesSinceFirstFail++; diff --git a/core/src/test/java/org/bitcoinj/core/BlockChainTest.java b/core/src/test/java/org/bitcoinj/core/BlockChainTest.java index 14f2296f..df84c2b1 100644 --- a/core/src/test/java/org/bitcoinj/core/BlockChainTest.java +++ b/core/src/test/java/org/bitcoinj/core/BlockChainTest.java @@ -55,7 +55,7 @@ public class BlockChainTest { private BlockChain chain; private BlockStore blockStore; private Address coinbaseTo; - private static final NetworkParameters PARAMS = UnitTestParams.get(); + private final StoredBlock[] block = new StoredBlock[1]; private Transaction coinbaseTransaction; @@ -64,19 +64,21 @@ public class BlockChainTest { maxTarget = limit; } } - private static final TweakableTestNet2Params testNet = new TweakableTestNet2Params(); + private static final TweakableTestNet2Params TESTNET = new TweakableTestNet2Params(); + private static final NetworkParameters UNITTEST = UnitTestParams.get(); + private static final NetworkParameters MAINNET = MainNetParams.get(); private void resetBlockStore() { - blockStore = new MemoryBlockStore(PARAMS); + blockStore = new MemoryBlockStore(UNITTEST); } @Before public void setUp() throws Exception { BriefLogFormatter.initVerbose(); - Context.propagate(new Context(testNet, 100, Coin.ZERO, false)); - testNetChain = new BlockChain(testNet, new Wallet(testNet), new MemoryBlockStore(testNet)); - Context.propagate(new Context(PARAMS, 100, Coin.ZERO, false)); - wallet = new Wallet(PARAMS) { + Context.propagate(new Context(TESTNET, 100, Coin.ZERO, false)); + testNetChain = new BlockChain(TESTNET, new Wallet(TESTNET), new MemoryBlockStore(TESTNET)); + Context.propagate(new Context(UNITTEST, 100, Coin.ZERO, false)); + wallet = new Wallet(UNITTEST) { @Override public void receiveFromBlock(Transaction tx, StoredBlock block, BlockChain.NewBlockType blockType, int relativityOffset) throws VerificationException { @@ -90,9 +92,9 @@ public class BlockChainTest { wallet.freshReceiveKey(); resetBlockStore(); - chain = new BlockChain(PARAMS, wallet, blockStore); + chain = new BlockChain(UNITTEST, wallet, blockStore); - coinbaseTo = Address.fromKey(PARAMS, wallet.currentReceiveKey()); + coinbaseTo = Address.fromKey(UNITTEST, wallet.currentReceiveKey()); } @Test @@ -126,9 +128,9 @@ public class BlockChainTest { public void receiveCoins() throws Exception { int height = 1; // Quick check that we can actually receive coins. - Transaction tx1 = createFakeTx(PARAMS, + Transaction tx1 = createFakeTx(UNITTEST, COIN, - Address.fromKey(PARAMS, wallet.currentReceiveKey())); + Address.fromKey(UNITTEST, wallet.currentReceiveKey())); Block b1 = createFakeBlock(blockStore, height, tx1).block; chain.add(b1); assertTrue(wallet.getBalance().signum() > 0); @@ -136,7 +138,7 @@ public class BlockChainTest { @Test public void unconnectedBlocks() throws Exception { - Block b1 = PARAMS.getGenesisBlock().createNextBlock(coinbaseTo); + Block b1 = UNITTEST.getGenesisBlock().createNextBlock(coinbaseTo); Block b2 = b1.createNextBlock(coinbaseTo); Block b3 = b2.createNextBlock(coinbaseTo); // Connected. @@ -153,9 +155,9 @@ public class BlockChainTest { public void difficultyTransitions() throws Exception { // Add a bunch of blocks in a loop until we reach a difficulty transition point. The unit test params have an // artificially shortened period. - Block prev = PARAMS.getGenesisBlock(); + Block prev = UNITTEST.getGenesisBlock(); Utils.setMockClock(System.currentTimeMillis()/1000); - for (int height = 0; height < PARAMS.getInterval() - 1; height++) { + for (int height = 0; height < UNITTEST.getInterval() - 1; height++) { Block newBlock = prev.createNextBlock(coinbaseTo, 1, Utils.currentTimeSeconds(), height); assertTrue(chain.add(newBlock)); prev = newBlock; @@ -164,13 +166,13 @@ public class BlockChainTest { } // Now add another block that has no difficulty adjustment, it should be rejected. try { - chain.add(prev.createNextBlock(coinbaseTo, 1, Utils.currentTimeSeconds(), PARAMS.getInterval())); + chain.add(prev.createNextBlock(coinbaseTo, 1, Utils.currentTimeSeconds(), UNITTEST.getInterval())); fail(); } catch (VerificationException e) { } // Create a new block with the right difficulty target given our blistering speed relative to the huge amount // of time it's supposed to take (set in the unit test network parameters). - Block b = prev.createNextBlock(coinbaseTo, 1, Utils.currentTimeSeconds(), PARAMS.getInterval() + 1); + Block b = prev.createNextBlock(coinbaseTo, 1, Utils.currentTimeSeconds(), UNITTEST.getInterval() + 1); b.setDifficultyTarget(0x201fFFFFL); b.solve(); assertTrue(chain.add(b)); @@ -182,7 +184,7 @@ public class BlockChainTest { assertTrue(testNetChain.add(getBlock1())); Block b2 = getBlock2(); assertTrue(testNetChain.add(b2)); - Block bad = new Block(testNet, Block.BLOCK_VERSION_GENESIS); + Block bad = new Block(TESTNET, Block.BLOCK_VERSION_GENESIS); // Merkle root can be anything here, doesn't matter. bad.setMerkleRoot(Sha256Hash.wrap("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")); // Nonce was just some number that made the hash < difficulty limit set below, it can be anything. @@ -203,8 +205,8 @@ public class BlockChainTest { } // Accept any level of difficulty now. - BigInteger oldVal = testNet.getMaxTarget(); - testNet.setMaxTarget(new BigInteger("00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 16)); + BigInteger oldVal = TESTNET.getMaxTarget(); + TESTNET.setMaxTarget(new BigInteger("00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 16)); try { testNetChain.add(bad); // We should not get here as the difficulty target should not be changing at this point. @@ -212,7 +214,7 @@ public class BlockChainTest { } catch (VerificationException e) { assertTrue(e.getMessage(), e.getCause().getMessage().contains("Unexpected change in difficulty")); } - testNet.setMaxTarget(oldVal); + TESTNET.setMaxTarget(oldVal); // TODO: Test difficulty change is not out of range when a transition period becomes valid. } @@ -237,8 +239,8 @@ public class BlockChainTest { private void testDeprecatedBlockVersion(final long deprecatedVersion, final long newVersion) throws Exception { - final BlockStore versionBlockStore = new MemoryBlockStore(PARAMS); - final BlockChain versionChain = new BlockChain(PARAMS, versionBlockStore); + final BlockStore versionBlockStore = new MemoryBlockStore(UNITTEST); + final BlockChain versionChain = new BlockChain(UNITTEST, versionBlockStore); // Build a historical chain of version 3 blocks long timeSeconds = 1231006505; @@ -246,13 +248,13 @@ public class BlockChainTest { FakeTxBuilder.BlockPair chainHead = null; // Put in just enough v2 blocks to be a minority - for (height = 0; height < (PARAMS.getMajorityWindow() - PARAMS.getMajorityRejectBlockOutdated()); height++) { + for (height = 0; height < (UNITTEST.getMajorityWindow() - UNITTEST.getMajorityRejectBlockOutdated()); height++) { chainHead = FakeTxBuilder.createFakeBlock(versionBlockStore, deprecatedVersion, timeSeconds, height); versionChain.add(chainHead.block); timeSeconds += 60; } // Fill the rest of the window with v3 blocks - for (; height < PARAMS.getMajorityWindow(); height++) { + for (; height < UNITTEST.getMajorityWindow(); height++) { chainHead = FakeTxBuilder.createFakeBlock(versionBlockStore, newVersion, timeSeconds, height); versionChain.add(chainHead.block); timeSeconds += 60; @@ -271,7 +273,7 @@ public class BlockChainTest { @Test public void duplicates() throws Exception { // Adding a block twice should not have any effect, in particular it should not send the block to the wallet. - Block b1 = PARAMS.getGenesisBlock().createNextBlock(coinbaseTo); + Block b1 = UNITTEST.getGenesisBlock().createNextBlock(coinbaseTo); Block b2 = b1.createNextBlock(coinbaseTo); Block b3 = b2.createNextBlock(coinbaseTo); assertTrue(chain.add(b1)); @@ -291,13 +293,13 @@ public class BlockChainTest { public void intraBlockDependencies() throws Exception { // Covers issue 166 in which transactions that depend on each other inside a block were not always being // considered relevant. - Address somebodyElse = Address.fromKey(PARAMS, new ECKey()); - Block b1 = PARAMS.getGenesisBlock().createNextBlock(somebodyElse); + Address somebodyElse = Address.fromKey(UNITTEST, new ECKey()); + Block b1 = UNITTEST.getGenesisBlock().createNextBlock(somebodyElse); ECKey key = wallet.freshReceiveKey(); - Address addr = Address.fromKey(PARAMS, key); + Address addr = Address.fromKey(UNITTEST, key); // 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 t2 = new Transaction(PARAMS); + Transaction t1 = FakeTxBuilder.createFakeTx(UNITTEST, COIN, addr); + Transaction t2 = new Transaction(UNITTEST); t2.addInput(t1.getOutputs().get(0)); t2.addOutput(valueOf(2, 0), somebodyElse); b1.addTransaction(t1); @@ -312,15 +314,15 @@ public class BlockChainTest { // Check that a coinbase transaction is only available to spend after NetworkParameters.getSpendableCoinbaseDepth() blocks. // Create a second wallet to receive the coinbase spend. - Wallet wallet2 = new Wallet(PARAMS); + Wallet wallet2 = new Wallet(UNITTEST); ECKey receiveKey = wallet2.freshReceiveKey(); int height = 1; chain.addWallet(wallet2); - Address addressToSendTo = Address.fromKey(PARAMS, receiveKey); + Address addressToSendTo = Address.fromKey(UNITTEST, receiveKey); // 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 = UNITTEST.getGenesisBlock().createNextBlockWithCoinbase(Block.BLOCK_VERSION_GENESIS, wallet.currentReceiveKey().getPubKey(), height++); chain.add(b1); // Check a transaction has been received. @@ -339,9 +341,9 @@ public class BlockChainTest { } // 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 < UNITTEST.getSpendableCoinbaseDepth() - 2; i++) { // Non relevant tx - just for fake block creation. - Transaction tx2 = createFakeTx(PARAMS, COIN, Address.fromKey(PARAMS, new ECKey())); + Transaction tx2 = createFakeTx(UNITTEST, COIN, Address.fromKey(UNITTEST, new ECKey())); Block b2 = createFakeBlock(blockStore, height++, tx2).block; chain.add(b2); @@ -362,7 +364,7 @@ public class BlockChainTest { } // Give it one more block - should now be able to spend coinbase transaction. Non relevant tx. - Transaction tx3 = createFakeTx(PARAMS, COIN, Address.fromKey(PARAMS, new ECKey())); + Transaction tx3 = createFakeTx(UNITTEST, COIN, Address.fromKey(UNITTEST, new ECKey())); Block b3 = createFakeBlock(blockStore, height++, tx3).block; chain.add(b3); @@ -393,7 +395,7 @@ public class BlockChainTest { // Some blocks from the test net. private static Block getBlock2() throws Exception { - Block b2 = new Block(testNet, Block.BLOCK_VERSION_GENESIS); + Block b2 = new Block(TESTNET, Block.BLOCK_VERSION_GENESIS); b2.setMerkleRoot(Sha256Hash.wrap("addc858a17e21e68350f968ccd384d6439b64aafa6c193c8b9dd66320470838b")); b2.setNonce(2642058077L); b2.setTime(1296734343L); @@ -404,7 +406,7 @@ public class BlockChainTest { } private static Block getBlock1() throws Exception { - Block b1 = new Block(testNet, Block.BLOCK_VERSION_GENESIS); + Block b1 = new Block(TESTNET, Block.BLOCK_VERSION_GENESIS); b1.setMerkleRoot(Sha256Hash.wrap("0e8e58ecdacaa7b3c6304a35ae4ffff964816d2b80b62b58558866ce4e648c10")); b1.setNonce(236038445); b1.setTime(1296734340); @@ -416,8 +418,7 @@ public class BlockChainTest { @Test public void estimatedBlockTime() throws Exception { - NetworkParameters params = MainNetParams.get(); - BlockChain prod = new BlockChain(new Context(params), new MemoryBlockStore(params)); + BlockChain prod = new BlockChain(new Context(MAINNET), new MemoryBlockStore(MAINNET)); Date d = prod.estimateBlockTime(200000); // The actual date of block 200,000 was 2012-09-22 10:47:00 assertEquals(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.US).parse("2012-10-23T08:35:05.000-0700"), d); @@ -454,7 +455,7 @@ public class BlockChainTest { public void rollbackBlockStore() throws Exception { // This test simulates an issue on Android, that causes the VM to crash while receiving a block, so that the // block store is persisted but the wallet is not. - Block b1 = PARAMS.getGenesisBlock().createNextBlock(coinbaseTo); + Block b1 = UNITTEST.getGenesisBlock().createNextBlock(coinbaseTo); Block b2 = b1.createNextBlock(coinbaseTo); // Add block 1, no frills. assertTrue(chain.add(b1)); diff --git a/core/src/test/java/org/bitcoinj/core/BlockTest.java b/core/src/test/java/org/bitcoinj/core/BlockTest.java index 597a0db7..2c63758a 100644 --- a/core/src/test/java/org/bitcoinj/core/BlockTest.java +++ b/core/src/test/java/org/bitcoinj/core/BlockTest.java @@ -39,7 +39,10 @@ import static org.bitcoinj.core.Utils.HEX; import static org.junit.Assert.*; public class BlockTest { - private static final NetworkParameters PARAMS = TestNet2Params.get(); + private static final NetworkParameters TESTNET2 = TestNet2Params.get(); + private static final NetworkParameters TESTNET3 = TestNet3Params.get(); + private static final NetworkParameters UNITTEST = UnitTestParams.get(); + private static final NetworkParameters MAINNET = MainNetParams.get(); public static final byte[] blockBytes; @@ -51,12 +54,12 @@ public class BlockTest { @Before public void setUp() throws Exception { - Context context = new Context(PARAMS); + Context context = new Context(TESTNET2); } @Test public void testWork() throws Exception { - BigInteger work = PARAMS.getGenesisBlock().getWork(); + BigInteger work = TESTNET2.getGenesisBlock().getWork(); // This number is printed by Bitcoin Core at startup as the calculated value of chainWork on testnet: // // SetBestChain: new best=00000007199508e34a9f height=0 work=536879104 @@ -65,7 +68,7 @@ public class BlockTest { @Test public void testBlockVerification() throws Exception { - Block block = PARAMS.getDefaultSerializer().makeBlock(blockBytes); + Block block = TESTNET2.getDefaultSerializer().makeBlock(blockBytes); block.verify(Block.BLOCK_HEIGHT_GENESIS, EnumSet.noneOf(Block.VerifyFlag.class)); assertEquals("00000000a6e5eb79dcec11897af55e90cd571a4335383a3ccfbc12ec81085935", block.getHashAsString()); } @@ -73,15 +76,14 @@ public class BlockTest { @SuppressWarnings("deprecation") @Test public void testDate() throws Exception { - Block block = PARAMS.getDefaultSerializer().makeBlock(blockBytes); + Block block = TESTNET2.getDefaultSerializer().makeBlock(blockBytes); assertEquals("4 Nov 2010 16:06:04 GMT", block.getTime().toGMTString()); } @Test public void testProofOfWork() throws Exception { // This params accepts any difficulty target. - NetworkParameters params = UnitTestParams.get(); - Block block = params.getDefaultSerializer().makeBlock(blockBytes); + Block block = UNITTEST.getDefaultSerializer().makeBlock(blockBytes); block.setNonce(12346); try { block.verify(Block.BLOCK_HEIGHT_GENESIS, EnumSet.noneOf(Block.VerifyFlag.class)); @@ -110,7 +112,7 @@ public class BlockTest { @Test public void testBadTransactions() throws Exception { - Block block = PARAMS.getDefaultSerializer().makeBlock(blockBytes); + Block block = TESTNET2.getDefaultSerializer().makeBlock(blockBytes); // Re-arrange so the coinbase transaction is not first. Transaction tx1 = block.transactions.get(0); Transaction tx2 = block.transactions.get(1); @@ -126,9 +128,9 @@ public class BlockTest { @Test public void testHeaderParse() throws Exception { - Block block = PARAMS.getDefaultSerializer().makeBlock(blockBytes); + Block block = TESTNET2.getDefaultSerializer().makeBlock(blockBytes); Block header = block.cloneAsHeader(); - Block reparsed = PARAMS.getDefaultSerializer().makeBlock(header.bitcoinSerialize()); + Block reparsed = TESTNET2.getDefaultSerializer().makeBlock(header.bitcoinSerialize()); assertEquals(reparsed, header); } @@ -138,24 +140,23 @@ public class BlockTest { // proves that transaction serialization works, along with all its subobjects like scripts and in/outpoints. // // NB: This tests the bitcoin serialization protocol. - Block block = PARAMS.getDefaultSerializer().makeBlock(blockBytes); + Block block = TESTNET2.getDefaultSerializer().makeBlock(blockBytes); assertTrue(Arrays.equals(blockBytes, block.bitcoinSerialize())); } @Test public void testUpdateLength() { - NetworkParameters params = UnitTestParams.get(); - Block block = params.getGenesisBlock().createNextBlockWithCoinbase(Block.BLOCK_VERSION_GENESIS, new ECKey().getPubKey(), Block.BLOCK_HEIGHT_GENESIS); + Block block = UNITTEST.getGenesisBlock().createNextBlockWithCoinbase(Block.BLOCK_VERSION_GENESIS, new ECKey().getPubKey(), Block.BLOCK_HEIGHT_GENESIS); assertEquals(block.bitcoinSerialize().length, block.length); final int origBlockLen = block.length; - Transaction tx = new Transaction(params); + Transaction tx = new Transaction(UNITTEST); // this is broken until the transaction has > 1 input + output (which is required anyway...) //assertTrue(tx.length == tx.bitcoinSerialize().length && tx.length == 8); byte[] outputScript = new byte[10]; Arrays.fill(outputScript, (byte) ScriptOpCodes.OP_FALSE); - tx.addOutput(new TransactionOutput(params, null, Coin.SATOSHI, outputScript)); - tx.addInput(new TransactionInput(params, null, new byte[] {(byte) ScriptOpCodes.OP_FALSE}, - new TransactionOutPoint(params, 0, Sha256Hash.of(new byte[] { 1 })))); + tx.addOutput(new TransactionOutput(UNITTEST, null, Coin.SATOSHI, outputScript)); + tx.addInput(new TransactionInput(UNITTEST, null, new byte[] {(byte) ScriptOpCodes.OP_FALSE}, + new TransactionOutPoint(UNITTEST, 0, Sha256Hash.of(new byte[] { 1 })))); int origTxLength = 8 + 2 + 8 + 1 + 10 + 40 + 1 + 1; assertEquals(tx.unsafeBitcoinSerialize().length, tx.length); assertEquals(origTxLength, tx.length); @@ -169,8 +170,8 @@ public class BlockTest { assertEquals(block.length, block.unsafeBitcoinSerialize().length); assertEquals(block.length, origBlockLen + tx.length); assertEquals(tx.length, origTxLength - 1); - block.getTransactions().get(1).addInput(new TransactionInput(params, null, new byte[] {(byte) ScriptOpCodes.OP_FALSE}, - new TransactionOutPoint(params, 0, Sha256Hash.of(new byte[] { 1 })))); + block.getTransactions().get(1).addInput(new TransactionInput(UNITTEST, null, new byte[] {(byte) ScriptOpCodes.OP_FALSE}, + new TransactionOutPoint(UNITTEST, 0, Sha256Hash.of(new byte[] { 1 })))); assertEquals(block.length, origBlockLen + tx.length); assertEquals(tx.length, origTxLength + 41); // - 1 + 40 + 1 + 1 } @@ -181,7 +182,7 @@ public class BlockTest { // contains a coinbase transaction whose height is two bytes, which is // shorter than we see in most other cases. - Block block = TestNet3Params.get().getDefaultSerializer().makeBlock( + Block block = TESTNET3.getDefaultSerializer().makeBlock( ByteStreams.toByteArray(getClass().getResourceAsStream("block_testnet21066.dat"))); // Check block. @@ -193,7 +194,7 @@ public class BlockTest { // fit in two bytes. This test primarily ensures script encoding checks // are applied correctly. - block = TestNet3Params.get().getDefaultSerializer().makeBlock( + block = TESTNET3.getDefaultSerializer().makeBlock( ByteStreams.toByteArray(getClass().getResourceAsStream("block_testnet32768.dat"))); // Check block. @@ -212,9 +213,7 @@ public class BlockTest { final long BLOCK_NONCE = 3973947400L; final Coin BALANCE_AFTER_BLOCK = Coin.valueOf(22223642); - final NetworkParameters PARAMS = MainNetParams.get(); - - Block block169482 = PARAMS.getDefaultSerializer().makeBlock(ByteStreams.toByteArray(getClass().getResourceAsStream("block169482.dat"))); + Block block169482 = MAINNET.getDefaultSerializer().makeBlock(ByteStreams.toByteArray(getClass().getResourceAsStream("block169482.dat"))); // Check block. assertNotNull(block169482); @@ -224,9 +223,9 @@ public class BlockTest { StoredBlock storedBlock = new StoredBlock(block169482, BigInteger.ONE, 169482); // Nonsense work - not used in test. // Create a wallet contain the miner's key that receives a spend from a coinbase. - ECKey miningKey = DumpedPrivateKey.fromBase58(PARAMS, MINING_PRIVATE_KEY).getKey(); + ECKey miningKey = DumpedPrivateKey.fromBase58(MAINNET, MINING_PRIVATE_KEY).getKey(); assertNotNull(miningKey); - Context context = new Context(PARAMS); + Context context = new Context(MAINNET); Wallet wallet = new Wallet(context); wallet.importKey(miningKey); @@ -245,42 +244,41 @@ public class BlockTest { @Test public void isBIPs() throws Exception { - final MainNetParams mainnet = MainNetParams.get(); - final Block genesis = mainnet.getGenesisBlock(); + final Block genesis = MAINNET.getGenesisBlock(); assertFalse(genesis.isBIP34()); assertFalse(genesis.isBIP66()); assertFalse(genesis.isBIP65()); // 227835/00000000000001aa077d7aa84c532a4d69bdbff519609d1da0835261b7a74eb6: last version 1 block - final Block block227835 = mainnet.getDefaultSerializer() + final Block block227835 = MAINNET.getDefaultSerializer() .makeBlock(ByteStreams.toByteArray(getClass().getResourceAsStream("block227835.dat"))); assertFalse(block227835.isBIP34()); assertFalse(block227835.isBIP66()); assertFalse(block227835.isBIP65()); // 227836/00000000000000d0dfd4c9d588d325dce4f32c1b31b7c0064cba7025a9b9adcc: version 2 block - final Block block227836 = mainnet.getDefaultSerializer() + final Block block227836 = MAINNET.getDefaultSerializer() .makeBlock(ByteStreams.toByteArray(getClass().getResourceAsStream("block227836.dat"))); assertTrue(block227836.isBIP34()); assertFalse(block227836.isBIP66()); assertFalse(block227836.isBIP65()); // 363703/0000000000000000011b2a4cb91b63886ffe0d2263fd17ac5a9b902a219e0a14: version 3 block - final Block block363703 = mainnet.getDefaultSerializer() + final Block block363703 = MAINNET.getDefaultSerializer() .makeBlock(ByteStreams.toByteArray(getClass().getResourceAsStream("block363703.dat"))); assertTrue(block363703.isBIP34()); assertTrue(block363703.isBIP66()); assertFalse(block363703.isBIP65()); // 383616/00000000000000000aab6a2b34e979b09ca185584bd1aecf204f24d150ff55e9: version 4 block - final Block block383616 = mainnet.getDefaultSerializer() + final Block block383616 = MAINNET.getDefaultSerializer() .makeBlock(ByteStreams.toByteArray(getClass().getResourceAsStream("block383616.dat"))); assertTrue(block383616.isBIP34()); assertTrue(block383616.isBIP66()); assertTrue(block383616.isBIP65()); // 370661/00000000000000001416a613602d73bbe5c79170fd8f39d509896b829cf9021e: voted for BIP101 - final Block block370661 = mainnet.getDefaultSerializer() + final Block block370661 = MAINNET.getDefaultSerializer() .makeBlock(ByteStreams.toByteArray(getClass().getResourceAsStream("block370661.dat"))); assertTrue(block370661.isBIP34()); assertTrue(block370661.isBIP66()); diff --git a/core/src/test/java/org/bitcoinj/core/BloomFilterTest.java b/core/src/test/java/org/bitcoinj/core/BloomFilterTest.java index 04fae635..817874a2 100644 --- a/core/src/test/java/org/bitcoinj/core/BloomFilterTest.java +++ b/core/src/test/java/org/bitcoinj/core/BloomFilterTest.java @@ -28,6 +28,8 @@ import static org.bitcoinj.core.Utils.HEX; import static org.junit.Assert.*; public class BloomFilterTest { + private static final NetworkParameters MAINNET = MainNetParams.get(); + @Test public void insertSerializeTest() { BloomFilter filter = new BloomFilter(3, 0.01, 0, BloomFilter.BloomUpdate.UPDATE_ALL); @@ -68,19 +70,18 @@ public class BloomFilterTest { @Test public void walletTest() throws Exception { - NetworkParameters params = MainNetParams.get(); - Context.propagate(new Context(params)); + Context.propagate(new Context(MAINNET)); - DumpedPrivateKey privKey = DumpedPrivateKey.fromBase58(params, "5Kg1gnAjaLfKiwhhPpGS3QfRg2m6awQvaj98JCZBZQ5SuS2F15C"); + DumpedPrivateKey privKey = DumpedPrivateKey.fromBase58(MAINNET, "5Kg1gnAjaLfKiwhhPpGS3QfRg2m6awQvaj98JCZBZQ5SuS2F15C"); - Address addr = Address.fromKey(params, privKey.getKey()); + Address addr = Address.fromKey(MAINNET, privKey.getKey()); assertTrue(addr.toString().equals("17Wx1GQfyPTNWpQMHrTwRSMTCAonSiZx9e")); - KeyChainGroup group = new KeyChainGroup(params); + KeyChainGroup group = new KeyChainGroup(MAINNET); // Add a random key which happens to have been used in a recent generation group.importKeys(ECKey.fromPublicOnly(privKey.getKey().getPubKeyPoint()), ECKey.fromPublicOnly(HEX.decode("03cb219f69f1b49468bd563239a86667e74a06fcba69ac50a08a5cbc42a5808e99"))); - Wallet wallet = new Wallet(params, group); - wallet.commitTx(new Transaction(params, HEX.decode("01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff0d038754030114062f503253482fffffffff01c05e559500000000232103cb219f69f1b49468bd563239a86667e74a06fcba69ac50a08a5cbc42a5808e99ac00000000"))); + Wallet wallet = new Wallet(MAINNET, group); + wallet.commitTx(new Transaction(MAINNET, HEX.decode("01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff0d038754030114062f503253482fffffffff01c05e559500000000232103cb219f69f1b49468bd563239a86667e74a06fcba69ac50a08a5cbc42a5808e99ac00000000"))); // We should have 2 per pubkey, and one for the pay-2-pubkey output we have assertEquals(5, wallet.getBloomFilterElementCount()); diff --git a/core/src/test/java/org/bitcoinj/core/ChainSplitTest.java b/core/src/test/java/org/bitcoinj/core/ChainSplitTest.java index a018f4be..af4c0796 100644 --- a/core/src/test/java/org/bitcoinj/core/ChainSplitTest.java +++ b/core/src/test/java/org/bitcoinj/core/ChainSplitTest.java @@ -48,7 +48,7 @@ import static org.junit.Assert.*; public class ChainSplitTest { private static final Logger log = LoggerFactory.getLogger(ChainSplitTest.class); - private static final NetworkParameters PARAMS = UnitTestParams.get(); + private static final NetworkParameters UNITTEST = UnitTestParams.get(); private Wallet wallet; private BlockChain chain; private Address coinsTo; @@ -59,15 +59,15 @@ public class ChainSplitTest { public void setUp() throws Exception { BriefLogFormatter.init(); Utils.setMockClock(); // Use mock clock - Context.propagate(new Context(PARAMS, 100, Coin.ZERO, false)); - MemoryBlockStore blockStore = new MemoryBlockStore(PARAMS); - wallet = new Wallet(PARAMS); + Context.propagate(new Context(UNITTEST, 100, Coin.ZERO, false)); + MemoryBlockStore blockStore = new MemoryBlockStore(UNITTEST); + wallet = new Wallet(UNITTEST); ECKey key1 = wallet.freshReceiveKey(); ECKey key2 = wallet.freshReceiveKey(); - chain = new BlockChain(PARAMS, wallet, blockStore); - coinsTo = Address.fromKey(PARAMS, key1); - coinsTo2 = Address.fromKey(PARAMS, key2); - someOtherGuy = Address.fromKey(PARAMS, new ECKey()); + chain = new BlockChain(UNITTEST, wallet, blockStore); + coinsTo = Address.fromKey(UNITTEST, key1); + coinsTo2 = Address.fromKey(UNITTEST, key2); + someOtherGuy = Address.fromKey(UNITTEST, new ECKey()); } @Test @@ -91,7 +91,7 @@ public class ChainSplitTest { }); // Start by building a couple of blocks on top of the genesis block. - Block b1 = PARAMS.getGenesisBlock().createNextBlock(coinsTo); + Block b1 = UNITTEST.getGenesisBlock().createNextBlock(coinsTo); Block b2 = b1.createNextBlock(coinsTo); assertTrue(chain.add(b1)); assertTrue(chain.add(b2)); @@ -165,7 +165,7 @@ public class ChainSplitTest { public void testForking2() throws Exception { // Check that if the chain forks and new coins are received in the alternate chain our balance goes up // after the re-org takes place. - Block b1 = PARAMS.getGenesisBlock().createNextBlock(someOtherGuy); + Block b1 = UNITTEST.getGenesisBlock().createNextBlock(someOtherGuy); Block b2 = b1.createNextBlock(someOtherGuy); assertTrue(chain.add(b1)); assertTrue(chain.add(b2)); @@ -183,16 +183,16 @@ public class ChainSplitTest { @Test public void testForking3() throws Exception { // Check that we can handle our own spends being rolled back by a fork. - Block b1 = PARAMS.getGenesisBlock().createNextBlock(coinsTo); + Block b1 = UNITTEST.getGenesisBlock().createNextBlock(coinsTo); chain.add(b1); assertEquals(FIFTY_COINS, wallet.getBalance()); - Address dest = Address.fromKey(PARAMS, new ECKey()); + Address dest = Address.fromKey(UNITTEST, new ECKey()); Transaction spend = wallet.createSend(dest, valueOf(10, 0)); wallet.commitTx(spend); // Waiting for confirmation ... make it eligible for selection. assertEquals(Coin.ZERO, wallet.getBalance()); - spend.getConfidence().markBroadcastBy(new PeerAddress(PARAMS, InetAddress.getByAddress(new byte[]{1, 2, 3, 4}))); - spend.getConfidence().markBroadcastBy(new PeerAddress(PARAMS, InetAddress.getByAddress(new byte[]{5,6,7,8}))); + spend.getConfidence().markBroadcastBy(new PeerAddress(UNITTEST, InetAddress.getByAddress(new byte[]{1, 2, 3, 4}))); + spend.getConfidence().markBroadcastBy(new PeerAddress(UNITTEST, InetAddress.getByAddress(new byte[]{5,6,7,8}))); assertEquals(ConfidenceType.PENDING, spend.getConfidence().getConfidenceType()); assertEquals(valueOf(40, 0), wallet.getBalance()); Block b2 = b1.createNextBlock(someOtherGuy); @@ -217,10 +217,10 @@ public class ChainSplitTest { // Check that we can handle external spends on an inactive chain becoming active. An external spend is where // we see a transaction that spends our own coins but we did not broadcast it ourselves. This happens when // keys are being shared between wallets. - Block b1 = PARAMS.getGenesisBlock().createNextBlock(coinsTo); + Block b1 = UNITTEST.getGenesisBlock().createNextBlock(coinsTo); chain.add(b1); assertEquals(FIFTY_COINS, wallet.getBalance()); - Address dest = Address.fromKey(PARAMS, new ECKey()); + Address dest = Address.fromKey(UNITTEST, new ECKey()); 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 // stateless. For our purposes it is as if some other program with our keys created the tx. @@ -247,13 +247,13 @@ public class ChainSplitTest { @Test public void testForking5() throws Exception { // Test the standard case in which a block containing identical transactions appears on a side chain. - Block b1 = PARAMS.getGenesisBlock().createNextBlock(coinsTo); + Block b1 = UNITTEST.getGenesisBlock().createNextBlock(coinsTo); chain.add(b1); final Transaction t = b1.transactions.get(1); assertEquals(FIFTY_COINS, wallet.getBalance()); // genesis -> b1 // -> b2 - Block b2 = PARAMS.getGenesisBlock().createNextBlock(coinsTo); + Block b2 = UNITTEST.getGenesisBlock().createNextBlock(coinsTo); Transaction b2coinbase = b2.transactions.get(0); b2.transactions.clear(); b2.addTransaction(b2coinbase); @@ -271,17 +271,17 @@ public class ChainSplitTest { } private Block roundtrip(Block b2) throws ProtocolException { - return PARAMS.getDefaultSerializer().makeBlock(b2.bitcoinSerialize()); + return UNITTEST.getDefaultSerializer().makeBlock(b2.bitcoinSerialize()); } @Test public void testForking6() throws Exception { // Test the case in which a side chain block contains a tx, and then it appears in the main chain too. - Block b1 = PARAMS.getGenesisBlock().createNextBlock(someOtherGuy); + Block b1 = UNITTEST.getGenesisBlock().createNextBlock(someOtherGuy); chain.add(b1); // genesis -> b1 // -> b2 - Block b2 = PARAMS.getGenesisBlock().createNextBlock(coinsTo); + Block b2 = UNITTEST.getGenesisBlock().createNextBlock(coinsTo); chain.add(b2); assertEquals(Coin.ZERO, wallet.getBalance()); // genesis -> b1 -> b3 @@ -307,25 +307,25 @@ public class ChainSplitTest { } }); - Block b1 = PARAMS.getGenesisBlock().createNextBlock(coinsTo); + Block b1 = UNITTEST.getGenesisBlock().createNextBlock(coinsTo); chain.add(b1); Transaction t1 = wallet.createSend(someOtherGuy, valueOf(10, 0)); - Address yetAnotherGuy = Address.fromKey(PARAMS, new ECKey()); + Address yetAnotherGuy = Address.fromKey(UNITTEST, new ECKey()); Transaction t2 = wallet.createSend(yetAnotherGuy, valueOf(20, 0)); wallet.commitTx(t1); // Receive t1 as confirmed by the network. - Block b2 = b1.createNextBlock(Address.fromKey(PARAMS, new ECKey())); + Block b2 = b1.createNextBlock(Address.fromKey(UNITTEST, new ECKey())); b2.addTransaction(t1); b2.solve(); chain.add(roundtrip(b2)); // Now we make a double spend become active after a re-org. - Block b3 = b1.createNextBlock(Address.fromKey(PARAMS, new ECKey())); + Block b3 = b1.createNextBlock(Address.fromKey(UNITTEST, new ECKey())); b3.addTransaction(t2); b3.solve(); chain.add(roundtrip(b3)); // Side chain. - Block b4 = b3.createNextBlock(Address.fromKey(PARAMS, new ECKey())); + Block b4 = b3.createNextBlock(Address.fromKey(UNITTEST, new ECKey())); chain.add(b4); // New best chain. Threading.waitForUserCode(); // Should have seen a double spend. @@ -350,15 +350,15 @@ public class ChainSplitTest { }); // Start with 50 coins. - Block b1 = PARAMS.getGenesisBlock().createNextBlock(coinsTo); + Block b1 = UNITTEST.getGenesisBlock().createNextBlock(coinsTo); chain.add(b1); Transaction t1 = checkNotNull(wallet.createSend(someOtherGuy, valueOf(10, 0))); - Address yetAnotherGuy = Address.fromKey(PARAMS, new ECKey()); + Address yetAnotherGuy = Address.fromKey(UNITTEST, new ECKey()); Transaction t2 = checkNotNull(wallet.createSend(yetAnotherGuy, valueOf(20, 0))); wallet.commitTx(t1); // t1 is still pending ... - Block b2 = b1.createNextBlock(Address.fromKey(PARAMS, new ECKey())); + Block b2 = b1.createNextBlock(Address.fromKey(UNITTEST, new ECKey())); chain.add(b2); assertEquals(ZERO, wallet.getBalance()); 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. // genesis -> b1 -> b2 [t1 pending] // \-> b3 (t2) -> b4 - Block b3 = b1.createNextBlock(Address.fromKey(PARAMS, new ECKey())); + Block b3 = b1.createNextBlock(Address.fromKey(UNITTEST, new ECKey())); b3.addTransaction(t2); b3.solve(); chain.add(roundtrip(b3)); // Side chain. - Block b4 = b3.createNextBlock(Address.fromKey(PARAMS, new ECKey())); + Block b4 = b3.createNextBlock(Address.fromKey(UNITTEST, new ECKey())); chain.add(b4); // New best chain. Threading.waitForUserCode(); // Should have seen a double spend against the pending pool. @@ -381,9 +381,9 @@ public class ChainSplitTest { assertEquals(valueOf(30, 0), wallet.getBalance()); // ... and back to our own parallel universe. - Block b5 = b2.createNextBlock(Address.fromKey(PARAMS, new ECKey())); + Block b5 = b2.createNextBlock(Address.fromKey(UNITTEST, new ECKey())); chain.add(b5); - Block b6 = b5.createNextBlock(Address.fromKey(PARAMS, new ECKey())); + Block b6 = b5.createNextBlock(Address.fromKey(UNITTEST, new ECKey())); chain.add(b6); // genesis -> b1 -> b2 -> b5 -> b6 [t1 still dead] // \-> b3 [t2 resurrected and now pending] -> b4 @@ -409,7 +409,7 @@ public class ChainSplitTest { }); // Start by building three blocks on top of the genesis block. All send to us. - Block b1 = PARAMS.getGenesisBlock().createNextBlock(coinsTo); + Block b1 = UNITTEST.getGenesisBlock().createNextBlock(coinsTo); BigInteger work1 = b1.getWork(); Block b2 = b1.createNextBlock(coinsTo2); BigInteger work2 = b2.getWork(); @@ -524,15 +524,15 @@ public class ChainSplitTest { // This covers issue 468. // Receive some money to the wallet. - Transaction t1 = FakeTxBuilder.createFakeTx(PARAMS, COIN, coinsTo); - final Block b1 = FakeTxBuilder.makeSolvedTestBlock(PARAMS.genesisBlock, t1); + Transaction t1 = FakeTxBuilder.createFakeTx(UNITTEST, COIN, coinsTo); + final Block b1 = FakeTxBuilder.makeSolvedTestBlock(UNITTEST.genesisBlock, t1); chain.add(b1); // Send a couple of payments one after the other (so the second depends on the change output of the first). wallet.allowSpendingUnconfirmedTransactions(); - Transaction t2 = checkNotNull(wallet.createSend(Address.fromKey(PARAMS, new ECKey()), CENT)); + Transaction t2 = checkNotNull(wallet.createSend(Address.fromKey(UNITTEST, new ECKey()), CENT)); wallet.commitTx(t2); - Transaction t3 = checkNotNull(wallet.createSend(Address.fromKey(PARAMS, new ECKey()), CENT)); + Transaction t3 = checkNotNull(wallet.createSend(Address.fromKey(UNITTEST, new ECKey()), CENT)); wallet.commitTx(t3); chain.add(FakeTxBuilder.makeSolvedTestBlock(b1, t2, t3)); @@ -566,7 +566,7 @@ public class ChainSplitTest { } }); - Block b1 = PARAMS.getGenesisBlock().createNextBlock(someOtherGuy); + Block b1 = UNITTEST.getGenesisBlock().createNextBlock(someOtherGuy); final ECKey coinsTo2 = wallet.freshReceiveKey(); Block b2 = b1.createNextBlockWithCoinbase(Block.BLOCK_VERSION_GENESIS, coinsTo2.getPubKey(), 2); Block b3 = b2.createNextBlock(someOtherGuy); @@ -595,12 +595,12 @@ public class ChainSplitTest { // Add blocks to b3 until we can spend the coinbase. Block firstTip = b3; - for (int i = 0; i < PARAMS.getSpendableCoinbaseDepth() - 2; i++) { + for (int i = 0; i < UNITTEST.getSpendableCoinbaseDepth() - 2; i++) { firstTip = firstTip.createNextBlock(someOtherGuy); chain.add(firstTip); } // ... and spend. - Transaction fodder = wallet.createSend(Address.fromKey(PARAMS, new ECKey()), FIFTY_COINS); + Transaction fodder = wallet.createSend(Address.fromKey(UNITTEST, new ECKey()), FIFTY_COINS); wallet.commitTx(fodder); final AtomicBoolean fodderIsDead = new AtomicBoolean(false); fodder.getConfidence().addEventListener(Threading.SAME_THREAD, new TransactionConfidence.Listener() { @@ -628,7 +628,7 @@ public class ChainSplitTest { assertTrue(chain.add(b6)); Block secondTip = b6; - for (int i = 0; i < PARAMS.getSpendableCoinbaseDepth() - 2; i++) { + for (int i = 0; i < UNITTEST.getSpendableCoinbaseDepth() - 2; i++) { secondTip = secondTip.createNextBlock(someOtherGuy); chain.add(secondTip); } diff --git a/core/src/test/java/org/bitcoinj/core/DumpedPrivateKeyTest.java b/core/src/test/java/org/bitcoinj/core/DumpedPrivateKeyTest.java index 7cdf88bc..cc01f8dc 100644 --- a/core/src/test/java/org/bitcoinj/core/DumpedPrivateKeyTest.java +++ b/core/src/test/java/org/bitcoinj/core/DumpedPrivateKeyTest.java @@ -32,9 +32,8 @@ import org.bitcoinj.params.MainNetParams; import org.bitcoinj.params.TestNet3Params; public class DumpedPrivateKeyTest { - - private static final MainNetParams MAINNET = MainNetParams.get(); - private static final TestNet3Params TESTNET = TestNet3Params.get(); + private static final NetworkParameters MAINNET = MainNetParams.get(); + private static final NetworkParameters TESTNET = TestNet3Params.get(); @Test public void checkNetwork() throws Exception { diff --git a/core/src/test/java/org/bitcoinj/core/ECKeyTest.java b/core/src/test/java/org/bitcoinj/core/ECKeyTest.java index dbf4d990..243d05bc 100644 --- a/core/src/test/java/org/bitcoinj/core/ECKeyTest.java +++ b/core/src/test/java/org/bitcoinj/core/ECKeyTest.java @@ -61,6 +61,9 @@ public class ECKeyTest { private static CharSequence PASSWORD1 = "my hovercraft has eels"; private static CharSequence WRONG_PASSWORD = "it is a snowy day today"; + private static final NetworkParameters TESTNET = TestNet3Params.get(); + private static final NetworkParameters MAINNET = MainNetParams.get(); + private static final NetworkParameters UNITTEST = UnitTestParams.get(); @Before public void setUp() throws Exception { @@ -184,16 +187,16 @@ public class ECKeyTest { public void base58Encoding() throws Exception { String addr = "mqAJmaxMcG5pPHHc3H3NtyXzY7kGbJLuMF"; String privkey = "92shANodC6Y4evT5kFzjNFQAdjqTtHAnDTLzqBBq4BbKUPyx6CD"; - ECKey key = DumpedPrivateKey.fromBase58(TestNet3Params.get(), privkey).getKey(); - assertEquals(privkey, key.getPrivateKeyEncoded(TestNet3Params.get()).toString()); - assertEquals(addr, Address.fromKey(TestNet3Params.get(), key).toString()); + ECKey key = DumpedPrivateKey.fromBase58(TESTNET, privkey).getKey(); + assertEquals(privkey, key.getPrivateKeyEncoded(TESTNET).toString()); + assertEquals(addr, Address.fromKey(TESTNET, key).toString()); } @Test public void base58Encoding_leadingZero() throws Exception { String privkey = "91axuYLa8xK796DnBXXsMbjuc8pDYxYgJyQMvFzrZ6UfXaGYuqL"; - ECKey key = DumpedPrivateKey.fromBase58(TestNet3Params.get(), privkey).getKey(); - assertEquals(privkey, key.getPrivateKeyEncoded(TestNet3Params.get()).toString()); + ECKey key = DumpedPrivateKey.fromBase58(TESTNET, privkey).getKey(); + assertEquals(privkey, key.getPrivateKeyEncoded(TESTNET).toString()); assertEquals(0, key.getPrivKeyBytes()[0]); } @@ -202,8 +205,8 @@ public class ECKeyTest { // Replace the loop bound with 1000 to get some keys with leading zero byte for (int i = 0 ; i < 20 ; i++) { ECKey key = new ECKey(); - ECKey key1 = DumpedPrivateKey.fromBase58(TestNet3Params.get(), - key.getPrivateKeyEncoded(TestNet3Params.get()).toString()).getKey(); + ECKey key1 = DumpedPrivateKey.fromBase58(TESTNET, + key.getPrivateKeyEncoded(TESTNET).toString()).getKey(); assertEquals(Utils.HEX.encode(key.getPrivKeyBytes()), Utils.HEX.encode(key1.getPrivKeyBytes())); } @@ -214,7 +217,7 @@ public class ECKeyTest { ECKey key = new ECKey(); String message = "聡中本"; String signatureBase64 = key.signMessage(message); - log.info("Message signed with " + Address.fromKey(MainNetParams.get(), key) + ": " + signatureBase64); + log.info("Message signed with " + Address.fromKey(MAINNET, key) + ": " + signatureBase64); // Should verify correctly. key.verifyMessage(message, signatureBase64); try { @@ -230,9 +233,9 @@ public class ECKeyTest { // Test vector generated by Bitcoin-Qt. String message = "hello"; String sigBase64 = "HxNZdo6ggZ41hd3mM3gfJRqOQPZYcO8z8qdX2BwmpbF11CaOQV+QiZGGQxaYOncKoNW61oRuSMMF8udfK54XqI8="; - Address expectedAddress = Address.fromBase58(MainNetParams.get(), "14YPSNPi6NSXnUxtPAsyJSuw3pv7AU3Cag"); + Address expectedAddress = Address.fromBase58(MAINNET, "14YPSNPi6NSXnUxtPAsyJSuw3pv7AU3Cag"); ECKey key = ECKey.signedMessageToKey(message, sigBase64); - Address gotAddress = Address.fromKey(MainNetParams.get(), key); + Address gotAddress = Address.fromKey(MAINNET, key); assertEquals(expectedAddress, gotAddress); } @@ -315,7 +318,7 @@ public class ECKeyTest { @Test public void testToString() throws Exception { ECKey key = ECKey.fromPrivate(BigInteger.TEN).decompress(); // An example private key. - NetworkParameters params = MainNetParams.get(); + NetworkParameters params = MAINNET; assertEquals("ECKey{pub HEX=04a0434d9e47f3c86235477c7b1ae6ae5d3442d49b1943c2b752a68e2a47e247c7893aba425419bc27a3b6c7e693a24c696f794c2ed877a1593cbee53b037368d7, isEncrypted=false, isPubKeyOnly=false}", key.toString()); assertEquals("ECKey{pub HEX=04a0434d9e47f3c86235477c7b1ae6ae5d3442d49b1943c2b752a68e2a47e247c7893aba425419bc27a3b6c7e693a24c696f794c2ed877a1593cbee53b037368d7, priv HEX=000000000000000000000000000000000000000000000000000000000000000a, priv WIF=5HpHagT65TZzG1PH3CSu63k8DbpvD8s5ip4nEB3kEsreBoNWTw6, isEncrypted=false, isPubKeyOnly=false}", key.toStringWithPrivate(null, params)); } @@ -358,9 +361,8 @@ public class ECKeyTest { public void roundTripDumpedPrivKey() throws Exception { ECKey key = new ECKey(); assertTrue(key.isCompressed()); - NetworkParameters params = UnitTestParams.get(); - String base58 = key.getPrivateKeyEncoded(params).toString(); - ECKey key2 = DumpedPrivateKey.fromBase58(params, base58).getKey(); + String base58 = key.getPrivateKeyEncoded(UNITTEST).toString(); + ECKey key2 = DumpedPrivateKey.fromBase58(UNITTEST, base58).getKey(); assertTrue(key2.isCompressed()); assertTrue(Arrays.equals(key.getPrivKeyBytes(), key2.getPrivKeyBytes())); assertTrue(Arrays.equals(key.getPubKey(), key2.getPubKey())); diff --git a/core/src/test/java/org/bitcoinj/core/FilteredBlockAndPartialMerkleTreeTests.java b/core/src/test/java/org/bitcoinj/core/FilteredBlockAndPartialMerkleTreeTests.java index b672413b..ec0fbd90 100644 --- a/core/src/test/java/org/bitcoinj/core/FilteredBlockAndPartialMerkleTreeTests.java +++ b/core/src/test/java/org/bitcoinj/core/FilteredBlockAndPartialMerkleTreeTests.java @@ -46,20 +46,20 @@ public class FilteredBlockAndPartialMerkleTreeTests extends TestWithPeerGroup { @Before public void setUp() throws Exception { - context = new Context(PARAMS); - MemoryBlockStore store = new MemoryBlockStore(PARAMS); + context = new Context(UNITTEST); + MemoryBlockStore store = new MemoryBlockStore(UNITTEST); // Cheat and place the previous block (block 100000) at the head of the block store without supporting blocks - store.put(new StoredBlock(new Block(PARAMS, HEX.decode("0100000050120119172a610421a6c3011dd330d9df07b63616c2cc1f1cd00200000000006657a9252aacd5c0b2940996ecff952228c3067cc38d4885efb5a4ac4247e9f337221b4d4c86041b0f2b5710")), + store.put(new StoredBlock(new Block(UNITTEST, HEX.decode("0100000050120119172a610421a6c3011dd330d9df07b63616c2cc1f1cd00200000000006657a9252aacd5c0b2940996ecff952228c3067cc38d4885efb5a4ac4247e9f337221b4d4c86041b0f2b5710")), BigInteger.valueOf(1), 100000)); store.setChainHead(store.get(Sha256Hash.wrap("000000000003ba27aa200b1cecaad478d2b00432346c3f1f3986da1afd33e506"))); - KeyChainGroup group = new KeyChainGroup(PARAMS); + KeyChainGroup group = new KeyChainGroup(UNITTEST); group.importKeys(ECKey.fromPublicOnly(HEX.decode("04b27f7e9475ccf5d9a431cb86d665b8302c140144ec2397fce792f4a4e7765fecf8128534eaa71df04f93c74676ae8279195128a1506ebf7379d23dab8fca0f63")), ECKey.fromPublicOnly(HEX.decode("04732012cb962afa90d31b25d8fb0e32c94e513ab7a17805c14ca4c3423e18b4fb5d0e676841733cb83abaf975845c9f6f2a8097b7d04f4908b18368d6fc2d68ec")), ECKey.fromPublicOnly(HEX.decode("04cfb4113b3387637131ebec76871fd2760fc430dd16de0110f0eb07bb31ffac85e2607c189cb8582ea1ccaeb64ffd655409106589778f3000fdfe3263440b0350")), ECKey.fromPublicOnly(HEX.decode("04b2f30018908a59e829c1534bfa5010d7ef7f79994159bba0f534d863ef9e4e973af6a8de20dc41dbea50bc622263ec8a770b2c9406599d39e4c9afe61f8b1613"))); - wallet = new Wallet(PARAMS, group); + wallet = new Wallet(UNITTEST, group); super.setUp(store); } @@ -73,7 +73,7 @@ public class FilteredBlockAndPartialMerkleTreeTests extends TestWithPeerGroup { public void deserializeFilteredBlock() throws Exception { // Random real block (000000000000dab0130bbcc991d3d7ae6b81aa6f50a798888dfe62337458dc45) // With one tx - FilteredBlock block = new FilteredBlock(PARAMS, HEX.decode("0100000079cda856b143d9db2c1caff01d1aecc8630d30625d10e8b4b8b0000000000000b50cc069d6a3e33e3ff84a5c41d9d3febe7c770fdcc96b2c3ff60abe184f196367291b4d4c86041b8fa45d630100000001b50cc069d6a3e33e3ff84a5c41d9d3febe7c770fdcc96b2c3ff60abe184f19630101")); + FilteredBlock block = new FilteredBlock(UNITTEST, HEX.decode("0100000079cda856b143d9db2c1caff01d1aecc8630d30625d10e8b4b8b0000000000000b50cc069d6a3e33e3ff84a5c41d9d3febe7c770fdcc96b2c3ff60abe184f196367291b4d4c86041b8fa45d630100000001b50cc069d6a3e33e3ff84a5c41d9d3febe7c770fdcc96b2c3ff60abe184f19630101")); // Check that the header was properly deserialized assertTrue(block.getBlockHeader().getHash().equals(Sha256Hash.wrap("000000000000dab0130bbcc991d3d7ae6b81aa6f50a798888dfe62337458dc45"))); @@ -84,16 +84,16 @@ public class FilteredBlockAndPartialMerkleTreeTests extends TestWithPeerGroup { assertTrue(txesMatched.contains(Sha256Hash.wrap("63194f18be0af63f2c6bc9dc0f777cbefed3d9415c4af83f3ee3a3d669c00cb5"))); // Check round tripping. - assertEquals(block, new FilteredBlock(PARAMS, block.bitcoinSerialize())); + assertEquals(block, new FilteredBlock(UNITTEST, block.bitcoinSerialize())); } @Test public void createFilteredBlock() throws Exception { ECKey key1 = new ECKey(); ECKey key2 = new ECKey(); - Transaction tx1 = FakeTxBuilder.createFakeTx(PARAMS, Coin.COIN, key1); - Transaction tx2 = FakeTxBuilder.createFakeTx(PARAMS, Coin.FIFTY_COINS, Address.fromKey(PARAMS, key2)); - Block block = FakeTxBuilder.makeSolvedTestBlock(PARAMS.getGenesisBlock(), Address.fromBase58(PARAMS, "msg2t2V2sWNd85LccoddtWysBTR8oPnkzW"), tx1, tx2); + Transaction tx1 = FakeTxBuilder.createFakeTx(UNITTEST, Coin.COIN, key1); + Transaction tx2 = FakeTxBuilder.createFakeTx(UNITTEST, Coin.FIFTY_COINS, Address.fromKey(UNITTEST, key2)); + Block block = FakeTxBuilder.makeSolvedTestBlock(UNITTEST.getGenesisBlock(), Address.fromBase58(UNITTEST, "msg2t2V2sWNd85LccoddtWysBTR8oPnkzW"), tx1, tx2); BloomFilter filter = new BloomFilter(4, 0.1, 1); filter.insert(key1); filter.insert(key2); @@ -120,7 +120,7 @@ public class FilteredBlockAndPartialMerkleTreeTests extends TestWithPeerGroup { byte[] includeBits = new byte[2]; Utils.setBitLE(includeBits, 9); Utils.setBitLE(includeBits, 10); - PartialMerkleTree pmt = PartialMerkleTree.buildFromLeaves(PARAMS, includeBits, hashes); + PartialMerkleTree pmt = PartialMerkleTree.buildFromLeaves(UNITTEST, includeBits, hashes); List matchedHashes = Lists.newArrayList(); pmt.getTxnHashAndMerkleRoot(matchedHashes); } @@ -129,8 +129,8 @@ public class FilteredBlockAndPartialMerkleTreeTests extends TestWithPeerGroup { public void serializeDownloadBlockWithWallet() throws Exception { // First we create all the neccessary objects, including lots of serialization and double-checks // Note that all serialized forms here are generated by Bitcoin Core/pulled from block explorer - Block block = new Block(PARAMS, HEX.decode("0100000006e533fd1ada86391f3f6c343204b0d278d4aaec1c0b20aa27ba0300000000006abbb3eb3d733a9fe18967fd7d4c117e4ccbbac5bec4d910d900b3ae0793e77f54241b4d4c86041b4089cc9b0c01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff07044c86041b010dffffffff0100f2052a01000000434104b27f7e9475ccf5d9a431cb86d665b8302c140144ec2397fce792f4a4e7765fecf8128534eaa71df04f93c74676ae8279195128a1506ebf7379d23dab8fca0f63ac000000000100000001d992e5a888a86d4c7a6a69167a4728ee69497509740fc5f456a24528c340219a000000008b483045022100f0519bdc9282ff476da1323b8ef7ffe33f495c1a8d52cc522b437022d83f6a230220159b61d197fbae01b4a66622a23bc3f1def65d5fa24efd5c26fa872f3a246b8e014104839f9023296a1fabb133140128ca2709f6818c7d099491690bd8ac0fd55279def6a2ceb6ab7b5e4a71889b6e739f09509565eec789e86886f6f936fa42097adeffffffff02000fe208010000001976a914948c765a6914d43f2a7ac177da2c2f6b52de3d7c88ac00e32321000000001976a9140c34f4e29ab5a615d5ea28d4817f12b137d62ed588ac0000000001000000059daf0abe7a92618546a9dbcfd65869b6178c66ec21ccfda878c1175979cfd9ef000000004a493046022100c2f7f25be5de6ce88ac3c1a519514379e91f39b31ddff279a3db0b1a229b708b022100b29efbdbd9837cc6a6c7318aa4900ed7e4d65662c34d1622a2035a3a5534a99a01ffffffffd516330ebdf075948da56db13d22632a4fb941122df2884397dda45d451acefb0000000048473044022051243debe6d4f2b433bee0cee78c5c4073ead0e3bde54296dbed6176e128659c022044417bfe16f44eb7b6eb0cdf077b9ce972a332e15395c09ca5e4f602958d266101ffffffffe1f5aa33961227b3c344e57179417ce01b7ccd421117fe2336289b70489883f900000000484730440220593252bb992ce3c85baf28d6e3aa32065816271d2c822398fe7ee28a856bc943022066d429dd5025d3c86fd8fd8a58e183a844bd94aa312cefe00388f57c85b0ca3201ffffffffe207e83718129505e6a7484831442f668164ae659fddb82e9e5421a081fb90d50000000049483045022067cf27eb733e5bcae412a586b25a74417c237161a084167c2a0b439abfebdcb2022100efcc6baa6824b4c5205aa967e0b76d31abf89e738d4b6b014e788c9a8cccaf0c01ffffffffe23b8d9d80a9e9d977fab3c94dbe37befee63822443c3ec5ae5a713ede66c3940000000049483045022020f2eb35036666b1debe0d1d2e77a36d5d9c4e96c1dba23f5100f193dbf524790221008ce79bc1321fb4357c6daee818038d41544749127751726e46b2b320c8b565a201ffffffff0200ba1dd2050000001976a914366a27645806e817a6cd40bc869bdad92fe5509188ac40420f00000000001976a914ee8bd501094a7d5ca318da2506de35e1cb025ddc88ac0000000001000000010abad2dc0c9b4b1dbb023077da513f81e5a71788d8680fca98ef1c37356c459c000000004a493046022100a894e521c87b3dbe23007079db4ac2896e9e791f8b57317ba6c0d99a7becd27a022100bc40981393eafeb33e89079f857c728701a9af4523c3f857cd96a500f240780901ffffffff024026ee22010000001976a914d28f9cefb58c1f7a5f97aa6b79047585f58fbd4388acc0cb1707000000001976a9142229481696e417aa5f51ad751d8cd4c6a669e4fe88ac000000000100000001f66d89b3649e0b18d84db056930676cb81c0168042fc4324c3682e252ea9410d0000000048473044022038e0b55b37c9253bfeda59c76c0134530f91fb586d6eb21738a77a984f370a44022048d4d477aaf97ef9c8275bbc5cb19b9c8a0e9b1f9fdafdd39bc85bf6c2f04a4d01ffffffff024041a523010000001976a914955f70ac8792b48b7bd52b15413bd8500ecf32c888ac00f36f06000000001976a91486116d15f3dbb23a2b58346f36e6ec2d867eba2b88ac00000000010000000126c384984f63446a4f2be8dd6531ba9837bd5f2c3d37403c5f51fb9192ee754e010000008b48304502210083af8324456f052ff1b2597ff0e6a8cce8b006e379a410cf781be7874a2691c2022072259e2f7292960dea0ffc361bbad0b861f719beb8550476f22ce0f82c023449014104f3ed46a81cba02af0593e8572a9130adb0d348b538c829ccaaf8e6075b78439b2746a76891ce7ba71abbcbb7ca76e8a220782738a6789562827c1065b0ce911dffffffff02c0dd9107000000001976a91463d4dd1b29d95ed601512b487bfc1c49d84d057988ac00a0491a010000001976a91465746bef92511df7b34abf71c162efb7ae353de388ac0000000001000000011b56cf3aab3286d582c055a42af3a911ee08423f276da702bb67f1222ac1a5b6000000008c4930460221009e9fba682e162c9627b96b7df272006a727988680b956c61baff869f0907b8fb022100a9c19adc7c36144bafe526630783845e5cb9554d30d3edfb56f0740274d507f30141046e0efbfac7b1615ad553a6f097615bc63b7cdb3b8e1cb3263b619ba63740012f51c7c5b09390e3577e377b7537e61226e315f95f926444fc5e5f2978c112e448ffffffff02c0072b11010000001976a914b73e9e01933351ca076faf8e0d94dd58079d0b1f88ac80b63908000000001976a9141aca0bdf0d2cee63db19aa4a484f45a4e26a880c88ac000000000100000001251b187504ea873b2c3915fad401f7a7734cc13567e0417708e86294a29f4f68010000008b4830450221009bef423141ed1ae60d0a5bcaa57b1673fc96001f0d4e105535cca817ba5a7724022037c399bd30374f22481ffc81327cfca4951c7264b227f765fcd6a429f3d9d2080141044d0d1b4f194c31a73dbce41c42b4b3946849117c5bb320467e014bad3b1532f28a9a1568ba7108f188e7823b6e618e91d974306701379a27b9339e646e156e7bffffffff02c00fd103010000001976a914ef7f5d9e1bc6ed68cfe0b1db9d8f09cef0f3ba4a88ac004dd208000000001976a914c22420641cea028c9e06c4d9104c1646f8b1769088ac0000000001000000013486dd5f0a2f3efcc04f64cb03872c021f98ee39f514747ce5336b874bbe47a7010000008b48304502201cadddc2838598fee7dc35a12b340c6bde8b389f7bfd19a1252a17c4b5ed2d71022100c1a251bbecb14b058a8bd77f65de87e51c47e95904f4c0e9d52eddc21c1415ac014104fe7df86d58aafa9246ca6fd30c905714533c25f700e2329b8ecec8aa52083b844baa3a8acd5d6b9732dcb39079bb56ba2711a3580dec824955fce0596a460c11ffffffff02c011f6e1000000001976a91490fac83c9adde91d670dde8755f8b475ab9e427d88acc0f9df15000000001976a91437f691b3e8ee5dcb56c2e31af4c80caa2df3b09b88ac00000000010000000170016bd1274b795b262f32a53003a4714b22b62f9057adf5fbe6ed939003b5190100000089463043022061456499582170a94d6b54308f792e37dad28bf0ed7aa61021f0301d2774d378021f4224b33f707efd810a01dd34ea86d6069cd599cc435513a0eef8c83c137bf7014104a2c95d6b98e745448eb45ed0ba95cf24dd7c3b16386e1028e24a0358ee4afc33e2f0199139853edaf32845d8a42254c75f7dc8add3286c682c650fbd93f0a4a1ffffffff02001bd2b7000000001976a9141b11c6acaa5223013f3a3240fdb024ecd9f8135488ac8023ad18000000001976a914ada27ca87bbaa1ee6fb1cb61bb0a29baaf6da2c988ac000000000100000001c8ff91f031ec6a5aba4baee6549e61dd01f26f61b70e2f1574f24cd680f464ad000000008b48304502210082235e21a2300022738dabb8e1bbd9d19cfb1e7ab8c30a23b0afbb8d178abcf3022024bf68e256c534ddfaf966bf908deb944305596f7bdcc38d69acad7f9c868724014104174f9eef1157dc1ad5eac198250b70d1c3b04b2fca12ad1483f07358486f02909b088bbc83f4de55f767f6cdf9d424aa02b5eeaffa08394d39b717895fc08d0affffffff0200ea3b43000000001976a914fb32df708f0610901f6d1b6df8c9c368fe0d981c88ac800f1777000000001976a914462c501c70fb996d15ac0771e7fc8d3ca3f7201888ac000000000100000001c67323867de802402e780a70e0deba3c708c4d87497e17590afee9c321f1c680010000008a473044022042734b25f54845d662e6499b75ff8529ff47f42fd224498a9f752d212326dbfa0220523e4b7b570bbb1f3af02baa2c04ea8eb7b0fccb1522cced130b666ae9a9d014014104b5a23b922949877e9eaf7512897ed091958e2e8cf05b0d0eb9064e7976043fde6023b4e2c188b7e38ef94eec6845dc4933f5e8635f1f6a3702290956aa9e284bffffffff0280041838030000001976a91436e5884215f7d3044be5d37bdd8c987d9d942c8488ac404b4c00000000001976a91460085d6838f8a44a21a0de56ff963cfa6242a96188ac00000000")); - FilteredBlock filteredBlock = new FilteredBlock(PARAMS, HEX.decode("0100000006e533fd1ada86391f3f6c343204b0d278d4aaec1c0b20aa27ba0300000000006abbb3eb3d733a9fe18967fd7d4c117e4ccbbac5bec4d910d900b3ae0793e77f54241b4d4c86041b4089cc9b0c000000084c30b63cfcdc2d35e3329421b9805ef0c6565d35381ca857762ea0b3a5a128bbca5065ff9617cbcba45eb23726df6498a9b9cafed4f54cbab9d227b0035ddefbbb15ac1d57d0182aaee61c74743a9c4f785895e563909bafec45c9a2b0ff3181d77706be8b1dcc91112eada86d424e2d0a8907c3488b6e44fda5a74a25cbc7d6bb4fa04245f4ac8a1a571d5537eac24adca1454d65eda446055479af6c6d4dd3c9ab658448c10b6921b7a4ce3021eb22ed6bb6a7fde1e5bcc4b1db6615c6abc5ca042127bfaf9f44ebce29cb29c6df9d05b47f35b2edff4f0064b578ab741fa78276222651209fe1a2c4c0fa1c58510aec8b090dd1eb1f82f9d261b8273b525b02ff1a")); + Block block = new Block(UNITTEST, HEX.decode("0100000006e533fd1ada86391f3f6c343204b0d278d4aaec1c0b20aa27ba0300000000006abbb3eb3d733a9fe18967fd7d4c117e4ccbbac5bec4d910d900b3ae0793e77f54241b4d4c86041b4089cc9b0c01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff07044c86041b010dffffffff0100f2052a01000000434104b27f7e9475ccf5d9a431cb86d665b8302c140144ec2397fce792f4a4e7765fecf8128534eaa71df04f93c74676ae8279195128a1506ebf7379d23dab8fca0f63ac000000000100000001d992e5a888a86d4c7a6a69167a4728ee69497509740fc5f456a24528c340219a000000008b483045022100f0519bdc9282ff476da1323b8ef7ffe33f495c1a8d52cc522b437022d83f6a230220159b61d197fbae01b4a66622a23bc3f1def65d5fa24efd5c26fa872f3a246b8e014104839f9023296a1fabb133140128ca2709f6818c7d099491690bd8ac0fd55279def6a2ceb6ab7b5e4a71889b6e739f09509565eec789e86886f6f936fa42097adeffffffff02000fe208010000001976a914948c765a6914d43f2a7ac177da2c2f6b52de3d7c88ac00e32321000000001976a9140c34f4e29ab5a615d5ea28d4817f12b137d62ed588ac0000000001000000059daf0abe7a92618546a9dbcfd65869b6178c66ec21ccfda878c1175979cfd9ef000000004a493046022100c2f7f25be5de6ce88ac3c1a519514379e91f39b31ddff279a3db0b1a229b708b022100b29efbdbd9837cc6a6c7318aa4900ed7e4d65662c34d1622a2035a3a5534a99a01ffffffffd516330ebdf075948da56db13d22632a4fb941122df2884397dda45d451acefb0000000048473044022051243debe6d4f2b433bee0cee78c5c4073ead0e3bde54296dbed6176e128659c022044417bfe16f44eb7b6eb0cdf077b9ce972a332e15395c09ca5e4f602958d266101ffffffffe1f5aa33961227b3c344e57179417ce01b7ccd421117fe2336289b70489883f900000000484730440220593252bb992ce3c85baf28d6e3aa32065816271d2c822398fe7ee28a856bc943022066d429dd5025d3c86fd8fd8a58e183a844bd94aa312cefe00388f57c85b0ca3201ffffffffe207e83718129505e6a7484831442f668164ae659fddb82e9e5421a081fb90d50000000049483045022067cf27eb733e5bcae412a586b25a74417c237161a084167c2a0b439abfebdcb2022100efcc6baa6824b4c5205aa967e0b76d31abf89e738d4b6b014e788c9a8cccaf0c01ffffffffe23b8d9d80a9e9d977fab3c94dbe37befee63822443c3ec5ae5a713ede66c3940000000049483045022020f2eb35036666b1debe0d1d2e77a36d5d9c4e96c1dba23f5100f193dbf524790221008ce79bc1321fb4357c6daee818038d41544749127751726e46b2b320c8b565a201ffffffff0200ba1dd2050000001976a914366a27645806e817a6cd40bc869bdad92fe5509188ac40420f00000000001976a914ee8bd501094a7d5ca318da2506de35e1cb025ddc88ac0000000001000000010abad2dc0c9b4b1dbb023077da513f81e5a71788d8680fca98ef1c37356c459c000000004a493046022100a894e521c87b3dbe23007079db4ac2896e9e791f8b57317ba6c0d99a7becd27a022100bc40981393eafeb33e89079f857c728701a9af4523c3f857cd96a500f240780901ffffffff024026ee22010000001976a914d28f9cefb58c1f7a5f97aa6b79047585f58fbd4388acc0cb1707000000001976a9142229481696e417aa5f51ad751d8cd4c6a669e4fe88ac000000000100000001f66d89b3649e0b18d84db056930676cb81c0168042fc4324c3682e252ea9410d0000000048473044022038e0b55b37c9253bfeda59c76c0134530f91fb586d6eb21738a77a984f370a44022048d4d477aaf97ef9c8275bbc5cb19b9c8a0e9b1f9fdafdd39bc85bf6c2f04a4d01ffffffff024041a523010000001976a914955f70ac8792b48b7bd52b15413bd8500ecf32c888ac00f36f06000000001976a91486116d15f3dbb23a2b58346f36e6ec2d867eba2b88ac00000000010000000126c384984f63446a4f2be8dd6531ba9837bd5f2c3d37403c5f51fb9192ee754e010000008b48304502210083af8324456f052ff1b2597ff0e6a8cce8b006e379a410cf781be7874a2691c2022072259e2f7292960dea0ffc361bbad0b861f719beb8550476f22ce0f82c023449014104f3ed46a81cba02af0593e8572a9130adb0d348b538c829ccaaf8e6075b78439b2746a76891ce7ba71abbcbb7ca76e8a220782738a6789562827c1065b0ce911dffffffff02c0dd9107000000001976a91463d4dd1b29d95ed601512b487bfc1c49d84d057988ac00a0491a010000001976a91465746bef92511df7b34abf71c162efb7ae353de388ac0000000001000000011b56cf3aab3286d582c055a42af3a911ee08423f276da702bb67f1222ac1a5b6000000008c4930460221009e9fba682e162c9627b96b7df272006a727988680b956c61baff869f0907b8fb022100a9c19adc7c36144bafe526630783845e5cb9554d30d3edfb56f0740274d507f30141046e0efbfac7b1615ad553a6f097615bc63b7cdb3b8e1cb3263b619ba63740012f51c7c5b09390e3577e377b7537e61226e315f95f926444fc5e5f2978c112e448ffffffff02c0072b11010000001976a914b73e9e01933351ca076faf8e0d94dd58079d0b1f88ac80b63908000000001976a9141aca0bdf0d2cee63db19aa4a484f45a4e26a880c88ac000000000100000001251b187504ea873b2c3915fad401f7a7734cc13567e0417708e86294a29f4f68010000008b4830450221009bef423141ed1ae60d0a5bcaa57b1673fc96001f0d4e105535cca817ba5a7724022037c399bd30374f22481ffc81327cfca4951c7264b227f765fcd6a429f3d9d2080141044d0d1b4f194c31a73dbce41c42b4b3946849117c5bb320467e014bad3b1532f28a9a1568ba7108f188e7823b6e618e91d974306701379a27b9339e646e156e7bffffffff02c00fd103010000001976a914ef7f5d9e1bc6ed68cfe0b1db9d8f09cef0f3ba4a88ac004dd208000000001976a914c22420641cea028c9e06c4d9104c1646f8b1769088ac0000000001000000013486dd5f0a2f3efcc04f64cb03872c021f98ee39f514747ce5336b874bbe47a7010000008b48304502201cadddc2838598fee7dc35a12b340c6bde8b389f7bfd19a1252a17c4b5ed2d71022100c1a251bbecb14b058a8bd77f65de87e51c47e95904f4c0e9d52eddc21c1415ac014104fe7df86d58aafa9246ca6fd30c905714533c25f700e2329b8ecec8aa52083b844baa3a8acd5d6b9732dcb39079bb56ba2711a3580dec824955fce0596a460c11ffffffff02c011f6e1000000001976a91490fac83c9adde91d670dde8755f8b475ab9e427d88acc0f9df15000000001976a91437f691b3e8ee5dcb56c2e31af4c80caa2df3b09b88ac00000000010000000170016bd1274b795b262f32a53003a4714b22b62f9057adf5fbe6ed939003b5190100000089463043022061456499582170a94d6b54308f792e37dad28bf0ed7aa61021f0301d2774d378021f4224b33f707efd810a01dd34ea86d6069cd599cc435513a0eef8c83c137bf7014104a2c95d6b98e745448eb45ed0ba95cf24dd7c3b16386e1028e24a0358ee4afc33e2f0199139853edaf32845d8a42254c75f7dc8add3286c682c650fbd93f0a4a1ffffffff02001bd2b7000000001976a9141b11c6acaa5223013f3a3240fdb024ecd9f8135488ac8023ad18000000001976a914ada27ca87bbaa1ee6fb1cb61bb0a29baaf6da2c988ac000000000100000001c8ff91f031ec6a5aba4baee6549e61dd01f26f61b70e2f1574f24cd680f464ad000000008b48304502210082235e21a2300022738dabb8e1bbd9d19cfb1e7ab8c30a23b0afbb8d178abcf3022024bf68e256c534ddfaf966bf908deb944305596f7bdcc38d69acad7f9c868724014104174f9eef1157dc1ad5eac198250b70d1c3b04b2fca12ad1483f07358486f02909b088bbc83f4de55f767f6cdf9d424aa02b5eeaffa08394d39b717895fc08d0affffffff0200ea3b43000000001976a914fb32df708f0610901f6d1b6df8c9c368fe0d981c88ac800f1777000000001976a914462c501c70fb996d15ac0771e7fc8d3ca3f7201888ac000000000100000001c67323867de802402e780a70e0deba3c708c4d87497e17590afee9c321f1c680010000008a473044022042734b25f54845d662e6499b75ff8529ff47f42fd224498a9f752d212326dbfa0220523e4b7b570bbb1f3af02baa2c04ea8eb7b0fccb1522cced130b666ae9a9d014014104b5a23b922949877e9eaf7512897ed091958e2e8cf05b0d0eb9064e7976043fde6023b4e2c188b7e38ef94eec6845dc4933f5e8635f1f6a3702290956aa9e284bffffffff0280041838030000001976a91436e5884215f7d3044be5d37bdd8c987d9d942c8488ac404b4c00000000001976a91460085d6838f8a44a21a0de56ff963cfa6242a96188ac00000000")); + FilteredBlock filteredBlock = new FilteredBlock(UNITTEST, HEX.decode("0100000006e533fd1ada86391f3f6c343204b0d278d4aaec1c0b20aa27ba0300000000006abbb3eb3d733a9fe18967fd7d4c117e4ccbbac5bec4d910d900b3ae0793e77f54241b4d4c86041b4089cc9b0c000000084c30b63cfcdc2d35e3329421b9805ef0c6565d35381ca857762ea0b3a5a128bbca5065ff9617cbcba45eb23726df6498a9b9cafed4f54cbab9d227b0035ddefbbb15ac1d57d0182aaee61c74743a9c4f785895e563909bafec45c9a2b0ff3181d77706be8b1dcc91112eada86d424e2d0a8907c3488b6e44fda5a74a25cbc7d6bb4fa04245f4ac8a1a571d5537eac24adca1454d65eda446055479af6c6d4dd3c9ab658448c10b6921b7a4ce3021eb22ed6bb6a7fde1e5bcc4b1db6615c6abc5ca042127bfaf9f44ebce29cb29c6df9d05b47f35b2edff4f0064b578ab741fa78276222651209fe1a2c4c0fa1c58510aec8b090dd1eb1f82f9d261b8273b525b02ff1a")); // Block 100001 assertTrue(block.getHash().equals(Sha256Hash.wrap("00000000000080b66c911bd5ba14a74260057311eaeb1982802f7010f1a9f090"))); @@ -139,20 +139,20 @@ public class FilteredBlockAndPartialMerkleTreeTests extends TestWithPeerGroup { List txHashList = filteredBlock.getTransactionHashes(); assertTrue(txHashList.size() == 4); // Four transactions (0, 1, 2, 6) from block 100001 - Transaction tx0 = PARAMS.getDefaultSerializer().makeTransaction(HEX.decode("01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff07044c86041b010dffffffff0100f2052a01000000434104b27f7e9475ccf5d9a431cb86d665b8302c140144ec2397fce792f4a4e7765fecf8128534eaa71df04f93c74676ae8279195128a1506ebf7379d23dab8fca0f63ac00000000")); + Transaction tx0 = UNITTEST.getDefaultSerializer().makeTransaction(HEX.decode("01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff07044c86041b010dffffffff0100f2052a01000000434104b27f7e9475ccf5d9a431cb86d665b8302c140144ec2397fce792f4a4e7765fecf8128534eaa71df04f93c74676ae8279195128a1506ebf7379d23dab8fca0f63ac00000000")); assertTrue(tx0.getHash().equals(Sha256Hash.wrap("bb28a1a5b3a02e7657a81c38355d56c6f05e80b9219432e3352ddcfc3cb6304c"))); assertEquals(tx0.getHash(), txHashList.get(0)); - Transaction tx1 = PARAMS.getDefaultSerializer().makeTransaction(HEX.decode("0100000001d992e5a888a86d4c7a6a69167a4728ee69497509740fc5f456a24528c340219a000000008b483045022100f0519bdc9282ff476da1323b8ef7ffe33f495c1a8d52cc522b437022d83f6a230220159b61d197fbae01b4a66622a23bc3f1def65d5fa24efd5c26fa872f3a246b8e014104839f9023296a1fabb133140128ca2709f6818c7d099491690bd8ac0fd55279def6a2ceb6ab7b5e4a71889b6e739f09509565eec789e86886f6f936fa42097adeffffffff02000fe208010000001976a914948c765a6914d43f2a7ac177da2c2f6b52de3d7c88ac00e32321000000001976a9140c34f4e29ab5a615d5ea28d4817f12b137d62ed588ac00000000")); + Transaction tx1 = UNITTEST.getDefaultSerializer().makeTransaction(HEX.decode("0100000001d992e5a888a86d4c7a6a69167a4728ee69497509740fc5f456a24528c340219a000000008b483045022100f0519bdc9282ff476da1323b8ef7ffe33f495c1a8d52cc522b437022d83f6a230220159b61d197fbae01b4a66622a23bc3f1def65d5fa24efd5c26fa872f3a246b8e014104839f9023296a1fabb133140128ca2709f6818c7d099491690bd8ac0fd55279def6a2ceb6ab7b5e4a71889b6e739f09509565eec789e86886f6f936fa42097adeffffffff02000fe208010000001976a914948c765a6914d43f2a7ac177da2c2f6b52de3d7c88ac00e32321000000001976a9140c34f4e29ab5a615d5ea28d4817f12b137d62ed588ac00000000")); assertTrue(tx1.getHash().equals(Sha256Hash.wrap("fbde5d03b027d2b9ba4cf5d4fecab9a99864df2637b25ea4cbcb1796ff6550ca"))); assertEquals(tx1.getHash(), txHashList.get(1)); - Transaction tx2 = PARAMS.getDefaultSerializer().makeTransaction(HEX.decode("01000000059daf0abe7a92618546a9dbcfd65869b6178c66ec21ccfda878c1175979cfd9ef000000004a493046022100c2f7f25be5de6ce88ac3c1a519514379e91f39b31ddff279a3db0b1a229b708b022100b29efbdbd9837cc6a6c7318aa4900ed7e4d65662c34d1622a2035a3a5534a99a01ffffffffd516330ebdf075948da56db13d22632a4fb941122df2884397dda45d451acefb0000000048473044022051243debe6d4f2b433bee0cee78c5c4073ead0e3bde54296dbed6176e128659c022044417bfe16f44eb7b6eb0cdf077b9ce972a332e15395c09ca5e4f602958d266101ffffffffe1f5aa33961227b3c344e57179417ce01b7ccd421117fe2336289b70489883f900000000484730440220593252bb992ce3c85baf28d6e3aa32065816271d2c822398fe7ee28a856bc943022066d429dd5025d3c86fd8fd8a58e183a844bd94aa312cefe00388f57c85b0ca3201ffffffffe207e83718129505e6a7484831442f668164ae659fddb82e9e5421a081fb90d50000000049483045022067cf27eb733e5bcae412a586b25a74417c237161a084167c2a0b439abfebdcb2022100efcc6baa6824b4c5205aa967e0b76d31abf89e738d4b6b014e788c9a8cccaf0c01ffffffffe23b8d9d80a9e9d977fab3c94dbe37befee63822443c3ec5ae5a713ede66c3940000000049483045022020f2eb35036666b1debe0d1d2e77a36d5d9c4e96c1dba23f5100f193dbf524790221008ce79bc1321fb4357c6daee818038d41544749127751726e46b2b320c8b565a201ffffffff0200ba1dd2050000001976a914366a27645806e817a6cd40bc869bdad92fe5509188ac40420f00000000001976a914ee8bd501094a7d5ca318da2506de35e1cb025ddc88ac00000000")); + Transaction tx2 = UNITTEST.getDefaultSerializer().makeTransaction(HEX.decode("01000000059daf0abe7a92618546a9dbcfd65869b6178c66ec21ccfda878c1175979cfd9ef000000004a493046022100c2f7f25be5de6ce88ac3c1a519514379e91f39b31ddff279a3db0b1a229b708b022100b29efbdbd9837cc6a6c7318aa4900ed7e4d65662c34d1622a2035a3a5534a99a01ffffffffd516330ebdf075948da56db13d22632a4fb941122df2884397dda45d451acefb0000000048473044022051243debe6d4f2b433bee0cee78c5c4073ead0e3bde54296dbed6176e128659c022044417bfe16f44eb7b6eb0cdf077b9ce972a332e15395c09ca5e4f602958d266101ffffffffe1f5aa33961227b3c344e57179417ce01b7ccd421117fe2336289b70489883f900000000484730440220593252bb992ce3c85baf28d6e3aa32065816271d2c822398fe7ee28a856bc943022066d429dd5025d3c86fd8fd8a58e183a844bd94aa312cefe00388f57c85b0ca3201ffffffffe207e83718129505e6a7484831442f668164ae659fddb82e9e5421a081fb90d50000000049483045022067cf27eb733e5bcae412a586b25a74417c237161a084167c2a0b439abfebdcb2022100efcc6baa6824b4c5205aa967e0b76d31abf89e738d4b6b014e788c9a8cccaf0c01ffffffffe23b8d9d80a9e9d977fab3c94dbe37befee63822443c3ec5ae5a713ede66c3940000000049483045022020f2eb35036666b1debe0d1d2e77a36d5d9c4e96c1dba23f5100f193dbf524790221008ce79bc1321fb4357c6daee818038d41544749127751726e46b2b320c8b565a201ffffffff0200ba1dd2050000001976a914366a27645806e817a6cd40bc869bdad92fe5509188ac40420f00000000001976a914ee8bd501094a7d5ca318da2506de35e1cb025ddc88ac00000000")); assertTrue(tx2.getHash().equals(Sha256Hash.wrap("8131ffb0a2c945ecaf9b9063e59558784f9c3a74741ce6ae2a18d0571dac15bb"))); assertEquals(tx2.getHash(), txHashList.get(2)); - Transaction tx3 = PARAMS.getDefaultSerializer().makeTransaction(HEX.decode("01000000011b56cf3aab3286d582c055a42af3a911ee08423f276da702bb67f1222ac1a5b6000000008c4930460221009e9fba682e162c9627b96b7df272006a727988680b956c61baff869f0907b8fb022100a9c19adc7c36144bafe526630783845e5cb9554d30d3edfb56f0740274d507f30141046e0efbfac7b1615ad553a6f097615bc63b7cdb3b8e1cb3263b619ba63740012f51c7c5b09390e3577e377b7537e61226e315f95f926444fc5e5f2978c112e448ffffffff02c0072b11010000001976a914b73e9e01933351ca076faf8e0d94dd58079d0b1f88ac80b63908000000001976a9141aca0bdf0d2cee63db19aa4a484f45a4e26a880c88ac00000000")); + Transaction tx3 = UNITTEST.getDefaultSerializer().makeTransaction(HEX.decode("01000000011b56cf3aab3286d582c055a42af3a911ee08423f276da702bb67f1222ac1a5b6000000008c4930460221009e9fba682e162c9627b96b7df272006a727988680b956c61baff869f0907b8fb022100a9c19adc7c36144bafe526630783845e5cb9554d30d3edfb56f0740274d507f30141046e0efbfac7b1615ad553a6f097615bc63b7cdb3b8e1cb3263b619ba63740012f51c7c5b09390e3577e377b7537e61226e315f95f926444fc5e5f2978c112e448ffffffff02c0072b11010000001976a914b73e9e01933351ca076faf8e0d94dd58079d0b1f88ac80b63908000000001976a9141aca0bdf0d2cee63db19aa4a484f45a4e26a880c88ac00000000")); assertTrue(tx3.getHash().equals(Sha256Hash.wrap("c5abc61566dbb1c4bce5e1fda7b66bed22eb2130cea4b721690bc1488465abc9"))); assertEquals(tx3.getHash(),txHashList.get(3)); @@ -165,7 +165,7 @@ public class FilteredBlockAndPartialMerkleTreeTests extends TestWithPeerGroup { InboundMessageQueuer p1 = connectPeer(1); assertEquals(1, peerGroup.numConnectedPeers()); // Send an inv for block 100001 - InventoryMessage inv = new InventoryMessage(PARAMS); + InventoryMessage inv = new InventoryMessage(UNITTEST); inv.addBlock(block); inbound(p1, inv); diff --git a/core/src/test/java/org/bitcoinj/core/MessageTest.java b/core/src/test/java/org/bitcoinj/core/MessageTest.java index cb23b440..fa676824 100644 --- a/core/src/test/java/org/bitcoinj/core/MessageTest.java +++ b/core/src/test/java/org/bitcoinj/core/MessageTest.java @@ -21,14 +21,14 @@ import org.bitcoinj.params.UnitTestParams; import org.junit.Test; public class MessageTest { + private static final NetworkParameters UNITTEST = UnitTestParams.get(); // If readStr() is vulnerable this causes OutOfMemory @Test(expected = ProtocolException.class) public void readStrOfExtremeLength() throws Exception { - NetworkParameters params = UnitTestParams.get(); VarInt length = new VarInt(Integer.MAX_VALUE); byte[] payload = length.encode(); - new VarStrMessage(params, payload); + new VarStrMessage(UNITTEST, payload); } static class VarStrMessage extends Message { @@ -45,10 +45,9 @@ public class MessageTest { // If readBytes() is vulnerable this causes OutOfMemory @Test(expected = ProtocolException.class) public void readByteArrayOfExtremeLength() throws Exception { - NetworkParameters params = UnitTestParams.get(); VarInt length = new VarInt(Integer.MAX_VALUE); byte[] payload = length.encode(); - new VarBytesMessage(params, payload); + new VarBytesMessage(UNITTEST, payload); } static class VarBytesMessage extends Message { diff --git a/core/src/test/java/org/bitcoinj/core/ParseByteCacheTest.java b/core/src/test/java/org/bitcoinj/core/ParseByteCacheTest.java index 1e25ef4e..a6ff52b6 100644 --- a/core/src/test/java/org/bitcoinj/core/ParseByteCacheTest.java +++ b/core/src/test/java/org/bitcoinj/core/ParseByteCacheTest.java @@ -65,7 +65,6 @@ public class ParseByteCacheTest { "c7 36 7a 7a 25 3b c1 13 52 23 ad b9 a4 68 bb 3a"); private BlockStore blockStore; - private static final NetworkParameters PARAMS = UnitTestParams.get(); private byte[] b1Bytes; private byte[] b1BytesWithHeader; @@ -76,35 +75,38 @@ public class ParseByteCacheTest { private byte[] tx2Bytes; private byte[] tx2BytesWithHeader; + private static final NetworkParameters UNITTEST = UnitTestParams.get(); + private static final NetworkParameters MAINNET = MainNetParams.get(); + private void resetBlockStore() { - blockStore = new MemoryBlockStore(PARAMS); + blockStore = new MemoryBlockStore(UNITTEST); } @Before public void setUp() throws Exception { - Context context = new Context(PARAMS); + Context context = new Context(UNITTEST); Wallet wallet = new Wallet(context); wallet.freshReceiveKey(); resetBlockStore(); - Transaction tx1 = createFakeTx(PARAMS, + Transaction tx1 = createFakeTx(UNITTEST, valueOf(2, 0), - Address.fromKey(PARAMS, wallet.currentReceiveKey())); + Address.fromKey(UNITTEST, wallet.currentReceiveKey())); // add a second input so can test granularity of byte cache. - Transaction prevTx = new Transaction(PARAMS); - TransactionOutput prevOut = new TransactionOutput(PARAMS, prevTx, COIN, Address.fromKey(PARAMS, wallet.currentReceiveKey())); + Transaction prevTx = new Transaction(UNITTEST); + TransactionOutput prevOut = new TransactionOutput(UNITTEST, prevTx, COIN, Address.fromKey(UNITTEST, wallet.currentReceiveKey())); prevTx.addOutput(prevOut); // Connect it. tx1.addInput(prevOut); - Transaction tx2 = createFakeTx(PARAMS, COIN, - Address.fromKey(PARAMS, new ECKey())); + Transaction tx2 = createFakeTx(UNITTEST, COIN, + Address.fromKey(UNITTEST, new ECKey())); Block b1 = createFakeBlock(blockStore, BLOCK_HEIGHT_GENESIS, tx1, tx2).block; - MessageSerializer bs = PARAMS.getDefaultSerializer(); + MessageSerializer bs = UNITTEST.getDefaultSerializer(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); bs.serialize(tx1, bos); @@ -138,16 +140,16 @@ public class ParseByteCacheTest { @Test public void testTransactionsRetain() throws Exception { - testTransaction(MainNetParams.get(), txMessage, false, true); - testTransaction(PARAMS, tx1BytesWithHeader, false, true); - testTransaction(PARAMS, tx2BytesWithHeader, false, true); + testTransaction(MAINNET, txMessage, false, true); + testTransaction(UNITTEST, tx1BytesWithHeader, false, true); + testTransaction(UNITTEST, tx2BytesWithHeader, false, true); } @Test public void testTransactionsNoRetain() throws Exception { - testTransaction(MainNetParams.get(), txMessage, false, false); - testTransaction(PARAMS, tx1BytesWithHeader, false, false); - testTransaction(PARAMS, tx2BytesWithHeader, false, false); + testTransaction(MAINNET, txMessage, false, false); + testTransaction(UNITTEST, tx1BytesWithHeader, false, false); + testTransaction(UNITTEST, tx2BytesWithHeader, false, false); } @Test @@ -159,10 +161,10 @@ public class ParseByteCacheTest { public void testBlock(byte[] blockBytes, boolean isChild, boolean retain) throws Exception { // reference serializer to produce comparison serialization output after changes to // message structure. - MessageSerializer bsRef = PARAMS.getSerializer(false); + MessageSerializer bsRef = UNITTEST.getSerializer(false); ByteArrayOutputStream bos = new ByteArrayOutputStream(); - BitcoinSerializer bs = PARAMS.getSerializer(retain); + BitcoinSerializer bs = UNITTEST.getSerializer(retain); Block b1; Block bRef; b1 = (Block) bs.deserialize(ByteBuffer.wrap(blockBytes)); diff --git a/core/src/test/java/org/bitcoinj/core/PeerAddressTest.java b/core/src/test/java/org/bitcoinj/core/PeerAddressTest.java index 030af0f3..cf8b06de 100644 --- a/core/src/test/java/org/bitcoinj/core/PeerAddressTest.java +++ b/core/src/test/java/org/bitcoinj/core/PeerAddressTest.java @@ -26,13 +26,14 @@ import java.net.InetAddress; import static org.bitcoinj.core.Utils.HEX; import static org.junit.Assert.assertEquals; -public class PeerAddressTest -{ +public class PeerAddressTest { + private static final NetworkParameters MAINNET = MainNetParams.get(); + @Test public void testPeerAddressRoundtrip() throws Exception { // copied verbatim from https://en.bitcoin.it/wiki/Protocol_specification#Network_address String fromSpec = "010000000000000000000000000000000000ffff0a000001208d"; - PeerAddress pa = new PeerAddress(MainNetParams.get(), + PeerAddress pa = new PeerAddress(MAINNET, HEX.decode(fromSpec), 0, 0); String reserialized = Utils.HEX.encode(pa.unsafeBitcoinSerialize()); assertEquals(reserialized,fromSpec ); @@ -40,7 +41,7 @@ public class PeerAddressTest @Test public void testBitcoinSerialize() throws Exception { - PeerAddress pa = new PeerAddress(MainNetParams.get(), InetAddress.getByName(null), 8333, 0, BigInteger.ZERO); + PeerAddress pa = new PeerAddress(MAINNET, InetAddress.getByName(null), 8333, 0, BigInteger.ZERO); assertEquals("000000000000000000000000000000000000ffff7f000001208d", Utils.HEX.encode(pa.bitcoinSerialize())); } diff --git a/core/src/test/java/org/bitcoinj/core/PeerGroupTest.java b/core/src/test/java/org/bitcoinj/core/PeerGroupTest.java index 590a1ca4..9138a1a4 100644 --- a/core/src/test/java/org/bitcoinj/core/PeerGroupTest.java +++ b/core/src/test/java/org/bitcoinj/core/PeerGroupTest.java @@ -214,8 +214,8 @@ public class PeerGroupTest extends TestWithPeerGroup { assertEquals(tmp, expectedPeers); Coin value = COIN; - Transaction t1 = FakeTxBuilder.createFakeTx(PARAMS, value, address); - InventoryMessage inv = new InventoryMessage(PARAMS); + Transaction t1 = FakeTxBuilder.createFakeTx(UNITTEST, value, address); + InventoryMessage inv = new InventoryMessage(UNITTEST); inv.addTransaction(t1); // Note: we start with p2 here to verify that transactions are downloaded from whichever peer announces first @@ -229,7 +229,7 @@ public class PeerGroupTest extends TestWithPeerGroup { // Asks for dependency. GetDataMessage getdata = (GetDataMessage) outbound(p2); assertNotNull(getdata); - inbound(p2, new NotFoundMessage(PARAMS, getdata.getItems())); + inbound(p2, new NotFoundMessage(UNITTEST, getdata.getItems())); pingAndWait(p2); assertEquals(value, wallet.getBalance(Wallet.BalanceType.ESTIMATED)); } @@ -243,9 +243,9 @@ public class PeerGroupTest extends TestWithPeerGroup { // Create a peer. InboundMessageQueuer p1 = connectPeer(1); - Wallet wallet2 = new Wallet(PARAMS); + Wallet wallet2 = new Wallet(UNITTEST); ECKey key2 = wallet2.freshReceiveKey(); - Address address2 = Address.fromKey(PARAMS, key2); + Address address2 = Address.fromKey(UNITTEST, key2); peerGroup.addWallet(wallet2); blockChain.addWallet(wallet2); @@ -254,8 +254,8 @@ public class PeerGroupTest extends TestWithPeerGroup { assertEquals(MemoryPoolMessage.class, waitForOutbound(p1).getClass()); Coin value = COIN; - Transaction t1 = FakeTxBuilder.createFakeTx(PARAMS, value, address2); - InventoryMessage inv = new InventoryMessage(PARAMS); + Transaction t1 = FakeTxBuilder.createFakeTx(UNITTEST, value, address2); + InventoryMessage inv = new InventoryMessage(UNITTEST); inv.addTransaction(t1); inbound(p1, inv); @@ -264,7 +264,7 @@ public class PeerGroupTest extends TestWithPeerGroup { // Asks for dependency. GetDataMessage getdata = (GetDataMessage) outbound(p1); assertNotNull(getdata); - inbound(p1, new NotFoundMessage(PARAMS, getdata.getItems())); + inbound(p1, new NotFoundMessage(UNITTEST, getdata.getItems())); pingAndWait(p1); assertEquals(value, wallet2.getBalance(Wallet.BalanceType.ESTIMATED)); } @@ -287,7 +287,7 @@ public class PeerGroupTest extends TestWithPeerGroup { Block b3 = FakeTxBuilder.makeSolvedTestBlock(b2); // Peer 1 and 2 receives an inv advertising a newly solved block. - InventoryMessage inv = new InventoryMessage(PARAMS); + InventoryMessage inv = new InventoryMessage(UNITTEST); inv.addBlock(b3); // Only peer 1 tries to download it. inbound(p1, inv); @@ -331,7 +331,7 @@ public class PeerGroupTest extends TestWithPeerGroup { GetBlocksMessage getblocks = (GetBlocksMessage) outbound(p1); assertEquals(Sha256Hash.ZERO_HASH, getblocks.getStopHash()); // We give back an inv with some blocks in it. - InventoryMessage inv = new InventoryMessage(PARAMS); + InventoryMessage inv = new InventoryMessage(UNITTEST); inv.addBlock(b1); inv.addBlock(b2); inv.addBlock(b3); @@ -365,8 +365,8 @@ public class PeerGroupTest extends TestWithPeerGroup { InboundMessageQueuer p2 = connectPeer(2); InboundMessageQueuer p3 = connectPeer(3); - Transaction tx = FakeTxBuilder.createFakeTx(PARAMS, valueOf(20, 0), address); - InventoryMessage inv = new InventoryMessage(PARAMS); + Transaction tx = FakeTxBuilder.createFakeTx(UNITTEST, valueOf(20, 0), address); + InventoryMessage inv = new InventoryMessage(UNITTEST); inv.addTransaction(tx); assertEquals(0, tx.getConfidence().numBroadcastPeers()); @@ -419,7 +419,7 @@ public class PeerGroupTest extends TestWithPeerGroup { final long now = Utils.currentTimeSeconds(); peerGroup.start(); assertTrue(peerGroup.getFastCatchupTimeSecs() > now - WEEK - 10000); - Wallet w2 = new Wallet(PARAMS); + Wallet w2 = new Wallet(UNITTEST); ECKey key1 = new ECKey(); key1.setCreationTimeSeconds(now - 86400); // One day ago. w2.importKey(key1); @@ -439,7 +439,7 @@ public class PeerGroupTest extends TestWithPeerGroup { public void noPings() throws Exception { peerGroup.start(); peerGroup.setPingIntervalMsec(0); - VersionMessage versionMessage = new VersionMessage(PARAMS, 2); + VersionMessage versionMessage = new VersionMessage(UNITTEST, 2); versionMessage.clientVersion = NetworkParameters.ProtocolVersion.BLOOM_FILTER.getBitcoinProtocolVersion(); versionMessage.localServices = VersionMessage.NODE_NETWORK; connectPeer(1, versionMessage); @@ -451,7 +451,7 @@ public class PeerGroupTest extends TestWithPeerGroup { public void pings() throws Exception { peerGroup.start(); peerGroup.setPingIntervalMsec(100); - VersionMessage versionMessage = new VersionMessage(PARAMS, 2); + VersionMessage versionMessage = new VersionMessage(UNITTEST, 2); versionMessage.clientVersion = NetworkParameters.ProtocolVersion.BLOOM_FILTER.getBitcoinProtocolVersion(); versionMessage.localServices = VersionMessage.NODE_NETWORK; InboundMessageQueuer p1 = connectPeer(1, versionMessage); @@ -468,10 +468,10 @@ public class PeerGroupTest extends TestWithPeerGroup { @Test public void downloadPeerSelection() throws Exception { peerGroup.start(); - VersionMessage versionMessage2 = new VersionMessage(PARAMS, 2); + VersionMessage versionMessage2 = new VersionMessage(UNITTEST, 2); versionMessage2.clientVersion = NetworkParameters.ProtocolVersion.BLOOM_FILTER.getBitcoinProtocolVersion(); versionMessage2.localServices = VersionMessage.NODE_NETWORK; - VersionMessage versionMessage3 = new VersionMessage(PARAMS, 3); + VersionMessage versionMessage3 = new VersionMessage(UNITTEST, 3); versionMessage3.clientVersion = NetworkParameters.ProtocolVersion.BLOOM_FILTER.getBitcoinProtocolVersion(); versionMessage3.localServices = VersionMessage.NODE_NETWORK; assertNull(peerGroup.getDownloadPeer()); @@ -491,7 +491,7 @@ public class PeerGroupTest extends TestWithPeerGroup { // New peer with a higher protocol version but same chain height. // TODO: When PeerGroup.selectDownloadPeer.PREFERRED_VERSION is not equal to vMinRequiredProtocolVersion, // reenable this test - /*VersionMessage versionMessage4 = new VersionMessage(PARAMS, 3); + /*VersionMessage versionMessage4 = new VersionMessage(UNITTEST, 3); versionMessage4.clientVersion = 100000; versionMessage4.localServices = VersionMessage.NODE_NETWORK; InboundMessageQueuer d = connectPeer(5, versionMessage4); @@ -617,8 +617,8 @@ public class PeerGroupTest extends TestWithPeerGroup { InboundMessageQueuer p1 = connectPeer(1); InboundMessageQueuer p2 = connectPeer(2); // Create a pay to pubkey tx. - Transaction tx = FakeTxBuilder.createFakeTx(PARAMS, COIN, key); - Transaction tx2 = new Transaction(PARAMS); + Transaction tx = FakeTxBuilder.createFakeTx(UNITTEST, COIN, key); + Transaction tx2 = new Transaction(UNITTEST); tx2.addInput(tx.getOutput(0)); TransactionOutPoint outpoint = tx2.getInput(0).getOutpoint(); assertTrue(p1.lastReceivedFilter.contains(key.getPubKey())); @@ -628,7 +628,7 @@ public class PeerGroupTest extends TestWithPeerGroup { assertTrue(outbound(p1) instanceof GetDataMessage); final Sha256Hash dephash = tx.getInput(0).getOutpoint().getHash(); final InventoryItem inv = new InventoryItem(InventoryItem.Type.Transaction, dephash); - inbound(p1, new NotFoundMessage(PARAMS, ImmutableList.of(inv))); + inbound(p1, new NotFoundMessage(UNITTEST, ImmutableList.of(inv))); assertNull(outbound(p1)); assertNull(outbound(p2)); peerGroup.waitForJobQueue(); @@ -694,10 +694,10 @@ public class PeerGroupTest extends TestWithPeerGroup { ListenableFuture> future = peerGroup.waitForPeersOfVersion(2, newVer); - VersionMessage ver1 = new VersionMessage(PARAMS, 10); + VersionMessage ver1 = new VersionMessage(UNITTEST, 10); ver1.clientVersion = baseVer; ver1.localServices = VersionMessage.NODE_NETWORK; - VersionMessage ver2 = new VersionMessage(PARAMS, 10); + VersionMessage ver2 = new VersionMessage(UNITTEST, 10); ver2.clientVersion = newVer; ver2.localServices = VersionMessage.NODE_NETWORK; peerGroup.start(); @@ -716,10 +716,10 @@ public class PeerGroupTest extends TestWithPeerGroup { public void waitForPeersWithServiceFlags() throws Exception { ListenableFuture> future = peerGroup.waitForPeersWithServiceMask(2, 3); - VersionMessage ver1 = new VersionMessage(PARAMS, 10); + VersionMessage ver1 = new VersionMessage(UNITTEST, 10); ver1.clientVersion = 70000; ver1.localServices = VersionMessage.NODE_NETWORK; - VersionMessage ver2 = new VersionMessage(PARAMS, 10); + VersionMessage ver2 = new VersionMessage(UNITTEST, 10); ver2.clientVersion = 70000; ver2.localServices = VersionMessage.NODE_NETWORK | 2; peerGroup.start(); @@ -744,12 +744,12 @@ public class PeerGroupTest extends TestWithPeerGroup { // 1. Test are executed on the same machine that is running a full node // 2. Test are executed without any full node running locally // We have to avoid to connecting to real and external services in unit tests - // So we skip this test in case we have already something running on port PARAMS.getPort() + // So we skip this test in case we have already something running on port UNITTEST.getPort() // Check that if we have a localhost port 8333 or 18333 then it's used instead of the p2p network. ServerSocket local = null; try { - local = new ServerSocket(PARAMS.getPort(), 100, InetAddresses.forString("127.0.0.1")); + local = new ServerSocket(UNITTEST.getPort(), 100, InetAddresses.forString("127.0.0.1")); } catch(BindException e) { // Port already in use, skipping this test. return; @@ -762,7 +762,7 @@ public class PeerGroupTest extends TestWithPeerGroup { local.accept(); // Real connect // If we get here it used the local peer. Check no others are in use. assertEquals(1, peerGroup.getMaxConnections()); - assertEquals(PeerAddress.localhost(PARAMS), peerGroup.getPendingPeers().get(0).getAddress()); + assertEquals(PeerAddress.localhost(UNITTEST), peerGroup.getPendingPeers().get(0).getAddress()); } finally { local.close(); } @@ -804,8 +804,8 @@ public class PeerGroupTest extends TestWithPeerGroup { Coin expectedBalance = Coin.ZERO; Block prev = blockStore.getChainHead().getHeader(); for (ECKey key1 : keys) { - Address addr = Address.fromKey(PARAMS, key1); - Block next = FakeTxBuilder.makeSolvedTestBlock(prev, FakeTxBuilder.createFakeTx(PARAMS, Coin.FIFTY_COINS, addr)); + Address addr = Address.fromKey(UNITTEST, key1); + Block next = FakeTxBuilder.makeSolvedTestBlock(prev, FakeTxBuilder.createFakeTx(UNITTEST, Coin.FIFTY_COINS, addr)); expectedBalance = expectedBalance.add(next.getTransactions().get(2).getOutput(0).getValue()); blocks.add(next); prev = next; @@ -814,7 +814,7 @@ public class PeerGroupTest extends TestWithPeerGroup { // Send the chain that doesn't have all the transactions in it. The blocks after the exhaustion point should all // be ignored. int epoch = wallet.getKeyChainGroupCombinedKeyLookaheadEpochs(); - BloomFilter filter = new BloomFilter(PARAMS, p1.lastReceivedFilter.bitcoinSerialize()); + BloomFilter filter = new BloomFilter(UNITTEST, p1.lastReceivedFilter.bitcoinSerialize()); filterAndSend(p1, blocks, filter); Block exhaustionPoint = blocks.get(3); pingAndWait(p1); diff --git a/core/src/test/java/org/bitcoinj/core/PeerTest.java b/core/src/test/java/org/bitcoinj/core/PeerTest.java index e093e3c1..2d918ea3 100644 --- a/core/src/test/java/org/bitcoinj/core/PeerTest.java +++ b/core/src/test/java/org/bitcoinj/core/PeerTest.java @@ -62,7 +62,7 @@ public class PeerTest extends TestWithNetworkConnections { private InboundMessageQueuer writeTarget; private static final int OTHER_PEER_CHAIN_HEIGHT = 110; private final AtomicBoolean fail = new AtomicBoolean(false); - + private static final NetworkParameters TESTNET = TestNet3Params.get(); @Parameterized.Parameters public static Collection parameters() { @@ -80,9 +80,9 @@ public class PeerTest extends TestWithNetworkConnections { @Before public void setUp() throws Exception { super.setUp(); - VersionMessage ver = new VersionMessage(PARAMS, 100); + VersionMessage ver = new VersionMessage(UNITTEST, 100); InetSocketAddress address = new InetSocketAddress("127.0.0.1", 4000); - peer = new Peer(PARAMS, ver, new PeerAddress(PARAMS, address), blockChain); + peer = new Peer(UNITTEST, ver, new PeerAddress(UNITTEST, address), blockChain); peer.addWallet(wallet); } @@ -98,7 +98,7 @@ public class PeerTest extends TestWithNetworkConnections { } private void connectWithVersion(int version, int flags) throws Exception { - VersionMessage peerVersion = new VersionMessage(PARAMS, OTHER_PEER_CHAIN_HEIGHT); + VersionMessage peerVersion = new VersionMessage(UNITTEST, OTHER_PEER_CHAIN_HEIGHT); peerVersion.clientVersion = version; peerVersion.localServices = flags; writeTarget = connect(peer, peerVersion); @@ -150,7 +150,7 @@ public class PeerTest extends TestWithNetworkConnections { assertEquals(blockStore.getChainHead().getHeader().getHash(), getblocks.getLocator().get(0)); assertEquals(Sha256Hash.ZERO_HASH, getblocks.getStopHash()); // Remote peer sends us an inv with some blocks. - InventoryMessage inv = new InventoryMessage(PARAMS); + InventoryMessage inv = new InventoryMessage(UNITTEST); inv.addBlock(b2); inv.addBlock(b3); // We do a getdata on them. @@ -164,7 +164,7 @@ public class PeerTest extends TestWithNetworkConnections { inbound(writeTarget, b2); inbound(writeTarget, b3); - inv = new InventoryMessage(PARAMS); + inv = new InventoryMessage(UNITTEST); inv.addBlock(b5); // We request the head block. inbound(writeTarget, inv); @@ -183,7 +183,7 @@ public class PeerTest extends TestWithNetworkConnections { // because we walk backwards down the orphan chain and then discover we already asked for those blocks, so // nothing is done. Block b6 = makeSolvedTestBlock(b5); - inv = new InventoryMessage(PARAMS); + inv = new InventoryMessage(UNITTEST); inv.addBlock(b6); inbound(writeTarget, inv); getdata = (GetDataMessage)outbound(writeTarget); @@ -192,7 +192,7 @@ public class PeerTest extends TestWithNetworkConnections { inbound(writeTarget, b6); assertNull(outbound(writeTarget)); // Nothing is sent at this point. // We're still waiting for the response to the getblocks (b3,b5) sent above. - inv = new InventoryMessage(PARAMS); + inv = new InventoryMessage(UNITTEST); inv.addBlock(b4); inv.addBlock(b5); inbound(writeTarget, inv); @@ -218,7 +218,7 @@ public class PeerTest extends TestWithNetworkConnections { Block b2 = makeSolvedTestBlock(b1); Block b3 = makeSolvedTestBlock(b2); inbound(writeTarget, b3); - InventoryMessage inv = new InventoryMessage(PARAMS); + InventoryMessage inv = new InventoryMessage(UNITTEST); InventoryItem item = new InventoryItem(InventoryItem.Type.Block, b3.getHash()); inv.addItem(item); inbound(writeTarget, inv); @@ -226,7 +226,7 @@ public class PeerTest extends TestWithNetworkConnections { GetBlocksMessage getblocks = (GetBlocksMessage)outbound(writeTarget); List expectedLocator = new ArrayList<>(); expectedLocator.add(b1.getHash()); - expectedLocator.add(PARAMS.getGenesisBlock().getHash()); + expectedLocator.add(UNITTEST.getGenesisBlock().getHash()); assertEquals(getblocks.getLocator(), expectedLocator); assertEquals(getblocks.getStopHash(), b3.getHash()); @@ -247,7 +247,7 @@ public class PeerTest extends TestWithNetworkConnections { Block b2 = makeSolvedTestBlock(b1); // Receive an inv. - InventoryMessage inv = new InventoryMessage(PARAMS); + InventoryMessage inv = new InventoryMessage(UNITTEST); InventoryItem item = new InventoryItem(InventoryItem.Type.Block, b2.getHash()); inv.addItem(item); inbound(writeTarget, inv); @@ -263,8 +263,8 @@ public class PeerTest extends TestWithNetworkConnections { peer.setDownloadData(true); // Make a transaction and tell the peer we have it. Coin value = COIN; - Transaction tx = createFakeTx(PARAMS, value, address); - InventoryMessage inv = new InventoryMessage(PARAMS); + Transaction tx = createFakeTx(UNITTEST, value, address); + InventoryMessage inv = new InventoryMessage(UNITTEST); InventoryItem item = new InventoryItem(InventoryItem.Type.Transaction, tx.getHash()); inv.addItem(item); inbound(writeTarget, inv); @@ -275,7 +275,7 @@ public class PeerTest extends TestWithNetworkConnections { inbound(writeTarget, tx); // Ask for the dependency, it's not in the mempool (in chain). getdata = (GetDataMessage) outbound(writeTarget); - inbound(writeTarget, new NotFoundMessage(PARAMS, getdata.getItems())); + inbound(writeTarget, new NotFoundMessage(UNITTEST, getdata.getItems())); pingAndWait(writeTarget); assertEquals(value, wallet.getBalance(Wallet.BalanceType.ESTIMATED)); } @@ -283,11 +283,11 @@ public class PeerTest extends TestWithNetworkConnections { @Test public void invDownloadTxMultiPeer() throws Exception { // Check co-ordination of which peer to download via the memory pool. - VersionMessage ver = new VersionMessage(PARAMS, 100); + VersionMessage ver = new VersionMessage(UNITTEST, 100); InetSocketAddress address = new InetSocketAddress("127.0.0.1", 4242); - Peer peer2 = new Peer(PARAMS, ver, new PeerAddress(PARAMS, address), blockChain); + Peer peer2 = new Peer(UNITTEST, ver, new PeerAddress(UNITTEST, address), blockChain); peer2.addWallet(wallet); - VersionMessage peerVersion = new VersionMessage(PARAMS, OTHER_PEER_CHAIN_HEIGHT); + VersionMessage peerVersion = new VersionMessage(UNITTEST, OTHER_PEER_CHAIN_HEIGHT); peerVersion.clientVersion = 70001; peerVersion.localServices = VersionMessage.NODE_NETWORK; @@ -296,8 +296,8 @@ public class PeerTest extends TestWithNetworkConnections { // Make a tx and advertise it to one of the peers. Coin value = COIN; - Transaction tx = createFakeTx(PARAMS, value, this.address); - InventoryMessage inv = new InventoryMessage(PARAMS); + Transaction tx = createFakeTx(UNITTEST, value, this.address); + InventoryMessage inv = new InventoryMessage(UNITTEST); InventoryItem item = new InventoryItem(InventoryItem.Type.Transaction, tx.getHash()); inv.addItem(item); @@ -322,7 +322,7 @@ public class PeerTest extends TestWithNetworkConnections { blockChain.add(b1); final Block b2 = makeSolvedTestBlock(b1); // Receive notification of a new block. - final InventoryMessage inv = new InventoryMessage(PARAMS); + final InventoryMessage inv = new InventoryMessage(UNITTEST); InventoryItem item = new InventoryItem(InventoryItem.Type.Block, b2.getHash()); inv.addItem(item); @@ -398,7 +398,7 @@ public class PeerTest extends TestWithNetworkConnections { List expectedLocator = new ArrayList<>(); expectedLocator.add(b2.getHash()); expectedLocator.add(b1.getHash()); - expectedLocator.add(PARAMS.getGenesisBlock().getHash()); + expectedLocator.add(UNITTEST.getGenesisBlock().getHash()); GetBlocksMessage message = (GetBlocksMessage) outbound(writeTarget); assertEquals(message.getLocator(), expectedLocator); @@ -434,9 +434,9 @@ public class PeerTest extends TestWithNetworkConnections { Block b1 = createFakeBlock(blockStore, Block.BLOCK_HEIGHT_GENESIS).block; blockChain.add(b1); Block b2 = makeSolvedTestBlock(b1); - Transaction t = new Transaction(PARAMS); + Transaction t = new Transaction(UNITTEST); t.addInput(b1.getTransactions().get(0).getOutput(0)); - t.addOutput(new TransactionOutput(PARAMS, t, Coin.ZERO, new byte[Block.MAX_BLOCK_SIZE - 1000])); + t.addOutput(new TransactionOutput(UNITTEST, t, Coin.ZERO, new byte[Block.MAX_BLOCK_SIZE - 1000])); b2.addTransaction(t); // Request the block. @@ -479,23 +479,23 @@ public class PeerTest extends TestWithNetworkConnections { GetHeadersMessage getheaders = (GetHeadersMessage) outbound(writeTarget); List expectedLocator = new ArrayList<>(); expectedLocator.add(b1.getHash()); - expectedLocator.add(PARAMS.getGenesisBlock().getHash()); + expectedLocator.add(UNITTEST.getGenesisBlock().getHash()); assertEquals(getheaders.getLocator(), expectedLocator); assertEquals(getheaders.getStopHash(), Sha256Hash.ZERO_HASH); // Now send all the headers. - HeadersMessage headers = new HeadersMessage(PARAMS, b2.cloneAsHeader(), + HeadersMessage headers = new HeadersMessage(UNITTEST, b2.cloneAsHeader(), b3.cloneAsHeader(), b4.cloneAsHeader()); // We expect to be asked for b3 and b4 again, but this time, with a body. expectedLocator.clear(); expectedLocator.add(b2.getHash()); expectedLocator.add(b1.getHash()); - expectedLocator.add(PARAMS.getGenesisBlock().getHash()); + expectedLocator.add(UNITTEST.getGenesisBlock().getHash()); inbound(writeTarget, headers); GetBlocksMessage getblocks = (GetBlocksMessage) outbound(writeTarget); assertEquals(expectedLocator, getblocks.getLocator()); assertEquals(Sha256Hash.ZERO_HASH, getblocks.getStopHash()); // We're supposed to get an inv here. - InventoryMessage inv = new InventoryMessage(PARAMS); + InventoryMessage inv = new InventoryMessage(UNITTEST); inv.addItem(new InventoryItem(InventoryItem.Type.Block, b3.getHash())); inbound(writeTarget, inv); GetDataMessage getdata = (GetDataMessage) outbound(writeTarget); @@ -542,7 +542,7 @@ public class PeerTest extends TestWithNetworkConnections { peer.setDownloadTxDependencies(false); connect(); // Check that if we request dependency download to be disabled and receive a relevant tx, things work correctly. - Transaction tx = FakeTxBuilder.createFakeTx(PARAMS, COIN, address); + Transaction tx = FakeTxBuilder.createFakeTx(UNITTEST, COIN, address); final Transaction[] result = new Transaction[1]; wallet.addCoinsReceivedEventListener(new WalletCoinsReceivedEventListener() { @Override @@ -575,29 +575,29 @@ public class PeerTest extends TestWithNetworkConnections { // -> [t7] // -> [t8] // The ones in brackets are assumed to be in the chain and are represented only by hashes. - Transaction t2 = FakeTxBuilder.createFakeTx(PARAMS, COIN, to); + Transaction t2 = FakeTxBuilder.createFakeTx(UNITTEST, COIN, to); Sha256Hash t5hash = t2.getInput(0).getOutpoint().getHash(); - Transaction t4 = FakeTxBuilder.createFakeTx(PARAMS, COIN, new ECKey()); + Transaction t4 = FakeTxBuilder.createFakeTx(UNITTEST, COIN, new ECKey()); Sha256Hash t6hash = t4.getInput(0).getOutpoint().getHash(); t4.addOutput(COIN, new ECKey()); - Transaction t3 = new Transaction(PARAMS); + Transaction t3 = new Transaction(UNITTEST); t3.addInput(t4.getOutput(0)); t3.addOutput(COIN, new ECKey()); - Transaction t1 = new Transaction(PARAMS); + Transaction t1 = new Transaction(UNITTEST); t1.addInput(t2.getOutput(0)); t1.addInput(t3.getOutput(0)); Sha256Hash t7hash = Sha256Hash.wrap("2b801dd82f01d17bbde881687bf72bc62e2faa8ab8133d36fcb8c3abe7459da6"); - t1.addInput(new TransactionInput(PARAMS, t1, new byte[]{}, new TransactionOutPoint(PARAMS, 0, t7hash))); + t1.addInput(new TransactionInput(UNITTEST, t1, new byte[]{}, new TransactionOutPoint(UNITTEST, 0, t7hash))); Sha256Hash t8hash = Sha256Hash.wrap("3b801dd82f01d17bbde881687bf72bc62e2faa8ab8133d36fcb8c3abe7459da6"); - t1.addInput(new TransactionInput(PARAMS, t1, new byte[]{}, new TransactionOutPoint(PARAMS, 1, t8hash))); + t1.addInput(new TransactionInput(UNITTEST, t1, new byte[]{}, new TransactionOutPoint(UNITTEST, 1, t8hash))); t1.addOutput(COIN, to); - t1 = FakeTxBuilder.roundTripTransaction(PARAMS, t1); - t2 = FakeTxBuilder.roundTripTransaction(PARAMS, t2); - t3 = FakeTxBuilder.roundTripTransaction(PARAMS, t3); - t4 = FakeTxBuilder.roundTripTransaction(PARAMS, t4); + t1 = FakeTxBuilder.roundTripTransaction(UNITTEST, t1); + t2 = FakeTxBuilder.roundTripTransaction(UNITTEST, t2); + t3 = FakeTxBuilder.roundTripTransaction(UNITTEST, t3); + t4 = FakeTxBuilder.roundTripTransaction(UNITTEST, t4); // Announce the first one. Wait for it to be downloaded. - InventoryMessage inv = new InventoryMessage(PARAMS); + InventoryMessage inv = new InventoryMessage(UNITTEST); inv.addTransaction(t1); inbound(writeTarget, inv); GetDataMessage getdata = (GetDataMessage) outbound(writeTarget); @@ -619,7 +619,7 @@ public class PeerTest extends TestWithNetworkConnections { // Deliver the requested transactions. inbound(writeTarget, t2); inbound(writeTarget, t3); - NotFoundMessage notFound = new NotFoundMessage(PARAMS); + NotFoundMessage notFound = new NotFoundMessage(UNITTEST); notFound.addItem(new InventoryItem(InventoryItem.Type.Transaction, t7hash)); notFound.addItem(new InventoryItem(InventoryItem.Type.Transaction, t8hash)); inbound(writeTarget, notFound); @@ -628,7 +628,7 @@ public class PeerTest extends TestWithNetworkConnections { getdata = (GetDataMessage) outbound(writeTarget); assertEquals(getdata.getItems().get(0).hash, t2.getInput(0).getOutpoint().getHash()); // t5 isn't found and t4 is. - notFound = new NotFoundMessage(PARAMS); + notFound = new NotFoundMessage(UNITTEST); notFound.addItem(new InventoryItem(InventoryItem.Type.Transaction, t5hash)); inbound(writeTarget, notFound); assertFalse(futures.isDone()); @@ -639,7 +639,7 @@ public class PeerTest extends TestWithNetworkConnections { // Continue to explore the t4 branch and ask for t6, which is in the chain. getdata = (GetDataMessage) outbound(writeTarget); assertEquals(t6hash, getdata.getItems().get(0).hash); - notFound = new NotFoundMessage(PARAMS); + notFound = new NotFoundMessage(UNITTEST); notFound.addItem(new InventoryItem(InventoryItem.Type.Transaction, t6hash)); inbound(writeTarget, notFound); pingAndWait(writeTarget); @@ -661,21 +661,21 @@ public class PeerTest extends TestWithNetworkConnections { // t1 -> t2 -> t3 -> [t4] // The ones in brackets are assumed to be in the chain and are represented only by hashes. Sha256Hash t4hash = Sha256Hash.wrap("2b801dd82f01d17bbde881687bf72bc62e2faa8ab8133d36fcb8c3abe7459da6"); - Transaction t3 = new Transaction(PARAMS); - t3.addInput(new TransactionInput(PARAMS, t3, new byte[]{}, new TransactionOutPoint(PARAMS, 0, t4hash))); + Transaction t3 = new Transaction(UNITTEST); + t3.addInput(new TransactionInput(UNITTEST, t3, new byte[]{}, new TransactionOutPoint(UNITTEST, 0, t4hash))); t3.addOutput(COIN, new ECKey()); - t3 = FakeTxBuilder.roundTripTransaction(PARAMS, t3); - Transaction t2 = new Transaction(PARAMS); + t3 = FakeTxBuilder.roundTripTransaction(UNITTEST, t3); + Transaction t2 = new Transaction(UNITTEST); t2.addInput(t3.getOutput(0)); t2.addOutput(COIN, new ECKey()); - t2 = FakeTxBuilder.roundTripTransaction(PARAMS, t2); - Transaction t1 = new Transaction(PARAMS); + t2 = FakeTxBuilder.roundTripTransaction(UNITTEST, t2); + Transaction t1 = new Transaction(UNITTEST); t1.addInput(t2.getOutput(0)); t1.addOutput(COIN, new ECKey()); - t1 = FakeTxBuilder.roundTripTransaction(PARAMS, t1); + t1 = FakeTxBuilder.roundTripTransaction(UNITTEST, t1); // Announce the first one. Wait for it to be downloaded. - InventoryMessage inv = new InventoryMessage(PARAMS); + InventoryMessage inv = new InventoryMessage(UNITTEST); inv.addTransaction(t1); inbound(writeTarget, inv); GetDataMessage getdata = (GetDataMessage) outbound(writeTarget); @@ -708,7 +708,7 @@ public class PeerTest extends TestWithNetworkConnections { connectWithVersion(70001, VersionMessage.NODE_NETWORK); // Test that if we receive a relevant transaction that has a lock time, it doesn't result in a notification // until we explicitly opt in to seeing those. - Wallet wallet = new Wallet(PARAMS); + Wallet wallet = new Wallet(UNITTEST); ECKey key = wallet.freshReceiveKey(); peer.addWallet(wallet); final Transaction[] vtx = new Transaction[1]; @@ -719,16 +719,16 @@ public class PeerTest extends TestWithNetworkConnections { } }); // Send a normal relevant transaction, it's received correctly. - Transaction t1 = FakeTxBuilder.createFakeTx(PARAMS, COIN, key); + Transaction t1 = FakeTxBuilder.createFakeTx(UNITTEST, COIN, key); inbound(writeTarget, t1); GetDataMessage getdata = (GetDataMessage) outbound(writeTarget); - inbound(writeTarget, new NotFoundMessage(PARAMS, getdata.getItems())); + inbound(writeTarget, new NotFoundMessage(UNITTEST, getdata.getItems())); pingAndWait(writeTarget); Threading.waitForUserCode(); assertNotNull(vtx[0]); vtx[0] = null; // Send a timelocked transaction, nothing happens. - Transaction t2 = FakeTxBuilder.createFakeTx(PARAMS, valueOf(2, 0), key); + Transaction t2 = FakeTxBuilder.createFakeTx(UNITTEST, valueOf(2, 0), key); t2.setLockTime(999999); inbound(writeTarget, t2); Threading.waitForUserCode(); @@ -737,7 +737,7 @@ public class PeerTest extends TestWithNetworkConnections { wallet.setAcceptRiskyTransactions(true); inbound(writeTarget, t2); getdata = (GetDataMessage) outbound(writeTarget); - inbound(writeTarget, new NotFoundMessage(PARAMS, getdata.getItems())); + inbound(writeTarget, new NotFoundMessage(UNITTEST, getdata.getItems())); pingAndWait(writeTarget); Threading.waitForUserCode(); assertEquals(t2, vtx[0]); @@ -759,7 +759,7 @@ public class PeerTest extends TestWithNetworkConnections { private void checkTimeLockedDependency(boolean shouldAccept) throws Exception { // Initial setup. connectWithVersion(70001, VersionMessage.NODE_NETWORK); - Wallet wallet = new Wallet(PARAMS); + Wallet wallet = new Wallet(UNITTEST); ECKey key = wallet.freshReceiveKey(); wallet.setAcceptRiskyTransactions(shouldAccept); peer.addWallet(wallet); @@ -771,18 +771,18 @@ public class PeerTest extends TestWithNetworkConnections { } }); // t1 -> t2 [locked] -> t3 (not available) - Transaction t2 = new Transaction(PARAMS); + Transaction t2 = new Transaction(UNITTEST); t2.setLockTime(999999); // Add a fake input to t3 that goes nowhere. Sha256Hash t3 = Sha256Hash.of("abc".getBytes(Charsets.UTF_8)); - t2.addInput(new TransactionInput(PARAMS, t2, new byte[]{}, new TransactionOutPoint(PARAMS, 0, t3))); + t2.addInput(new TransactionInput(UNITTEST, t2, new byte[]{}, new TransactionOutPoint(UNITTEST, 0, t3))); t2.getInput(0).setSequenceNumber(0xDEADBEEF); t2.addOutput(COIN, new ECKey()); - Transaction t1 = new Transaction(PARAMS); + Transaction t1 = new Transaction(UNITTEST); t1.addInput(t2.getOutput(0)); t1.addOutput(COIN, key); // Make it relevant. // Announce t1. - InventoryMessage inv = new InventoryMessage(PARAMS); + InventoryMessage inv = new InventoryMessage(UNITTEST); inv.addTransaction(t1); inbound(writeTarget, inv); // Send it. @@ -799,7 +799,7 @@ public class PeerTest extends TestWithNetworkConnections { getdata = (GetDataMessage) outbound(writeTarget); assertEquals(t3, getdata.getItems().get(0).hash); // Can't find it: bottom of tree. - NotFoundMessage notFound = new NotFoundMessage(PARAMS); + NotFoundMessage notFound = new NotFoundMessage(UNITTEST); notFound.addItem(new InventoryItem(InventoryItem.Type.Transaction, t3)); inbound(writeTarget, notFound); pingAndWait(writeTarget); @@ -868,15 +868,15 @@ public class PeerTest extends TestWithNetworkConnections { } }); connect(); - Transaction t1 = new Transaction(PARAMS); - t1.addInput(new TransactionInput(PARAMS, t1, new byte[]{})); - t1.addOutput(COIN, Address.fromKey(PARAMS, new ECKey())); - Transaction t2 = new Transaction(PARAMS); + Transaction t1 = new Transaction(UNITTEST); + t1.addInput(new TransactionInput(UNITTEST, t1, new byte[]{})); + t1.addOutput(COIN, Address.fromKey(UNITTEST, new ECKey())); + Transaction t2 = new Transaction(UNITTEST); t2.addInput(t1.getOutput(0)); t2.addOutput(COIN, wallet.currentChangeAddress()); inbound(writeTarget, t2); final InventoryItem inventoryItem = new InventoryItem(InventoryItem.Type.Transaction, t2.getInput(0).getOutpoint().getHash()); - final NotFoundMessage nfm = new NotFoundMessage(PARAMS, Lists.newArrayList(inventoryItem)); + final NotFoundMessage nfm = new NotFoundMessage(UNITTEST, Lists.newArrayList(inventoryItem)); inbound(writeTarget, nfm); pingAndWait(writeTarget); Threading.waitForUserCode(); @@ -889,8 +889,8 @@ public class PeerTest extends TestWithNetworkConnections { // Basic test of support for BIP 64: getutxos support. The Lighthouse unit tests exercise this stuff more // thoroughly. connectWithVersion(GetUTXOsMessage.MIN_PROTOCOL_VERSION, VersionMessage.NODE_NETWORK | VersionMessage.NODE_GETUTXOS); - TransactionOutPoint op1 = new TransactionOutPoint(PARAMS, 1, Sha256Hash.of("foo".getBytes())); - TransactionOutPoint op2 = new TransactionOutPoint(PARAMS, 2, Sha256Hash.of("bar".getBytes())); + TransactionOutPoint op1 = new TransactionOutPoint(UNITTEST, 1, Sha256Hash.of("foo".getBytes())); + TransactionOutPoint op2 = new TransactionOutPoint(UNITTEST, 2, Sha256Hash.of("bar".getBytes())); ListenableFuture future1 = peer.getUTXOs(ImmutableList.of(op1)); ListenableFuture future2 = peer.getUTXOs(ImmutableList.of(op2)); @@ -905,13 +905,13 @@ public class PeerTest extends TestWithNetworkConnections { assertFalse(future1.isDone()); ECKey key = new ECKey(); - TransactionOutput out1 = new TransactionOutput(PARAMS, null, Coin.CENT, key); - UTXOsMessage response1 = new UTXOsMessage(PARAMS, ImmutableList.of(out1), new long[]{UTXOsMessage.MEMPOOL_HEIGHT}, Sha256Hash.ZERO_HASH, 1234); + TransactionOutput out1 = new TransactionOutput(UNITTEST, null, Coin.CENT, key); + UTXOsMessage response1 = new UTXOsMessage(UNITTEST, ImmutableList.of(out1), new long[]{UTXOsMessage.MEMPOOL_HEIGHT}, Sha256Hash.ZERO_HASH, 1234); inbound(writeTarget, response1); assertEquals(future1.get(), response1); - TransactionOutput out2 = new TransactionOutput(PARAMS, null, Coin.FIFTY_COINS, key); - UTXOsMessage response2 = new UTXOsMessage(PARAMS, ImmutableList.of(out2), new long[]{1000}, Sha256Hash.ZERO_HASH, 1234); + TransactionOutput out2 = new TransactionOutput(UNITTEST, null, Coin.FIFTY_COINS, key); + UTXOsMessage response2 = new UTXOsMessage(UNITTEST, ImmutableList.of(out2), new long[]{1000}, Sha256Hash.ZERO_HASH, 1234); inbound(writeTarget, response2); assertEquals(future2.get(), response2); } @@ -934,11 +934,10 @@ public class PeerTest extends TestWithNetworkConnections { peerDisconnected.set(null); } }); - final NetworkParameters params = TestNet3Params.get(); - MessageSerializer serializer = params.getDefaultSerializer(); + MessageSerializer serializer = TESTNET.getDefaultSerializer(); // Now write some bogus truncated message. ByteArrayOutputStream out = new ByteArrayOutputStream(); - serializer.serialize("inv", new InventoryMessage(PARAMS) { + serializer.serialize("inv", new InventoryMessage(UNITTEST) { @Override public void bitcoinSerializeToStream(OutputStream stream) throws IOException { // Add some hashes. diff --git a/core/src/test/java/org/bitcoinj/core/SendHeadersMessageTest.java b/core/src/test/java/org/bitcoinj/core/SendHeadersMessageTest.java index 641dce72..f52cb5da 100644 --- a/core/src/test/java/org/bitcoinj/core/SendHeadersMessageTest.java +++ b/core/src/test/java/org/bitcoinj/core/SendHeadersMessageTest.java @@ -25,6 +25,8 @@ import static org.bitcoinj.core.Utils.HEX; import static org.junit.Assert.assertTrue; public class SendHeadersMessageTest { + private static final NetworkParameters REGTEST = RegTestParams.get(); + @Test public void decodeAndEncode() throws Exception { byte[] message = HEX @@ -37,8 +39,7 @@ public class SendHeadersMessageTest { + "c96fe88d4a0f01ed9dedae2b6f9e00da94cad0fecaae66ecf689bf71b50000000000000000000000000000000000000000000000000"); ByteBuffer buffer = ByteBuffer.wrap(message); - RegTestParams params = org.bitcoinj.params.RegTestParams.get(); - BitcoinSerializer serializer = new BitcoinSerializer(params, false); + BitcoinSerializer serializer = new BitcoinSerializer(REGTEST, false); assertTrue(serializer.deserialize(buffer) instanceof org.bitcoinj.core.SendHeadersMessage); } } diff --git a/core/src/test/java/org/bitcoinj/core/TransactionBroadcastTest.java b/core/src/test/java/org/bitcoinj/core/TransactionBroadcastTest.java index 0e5ab263..1b2e6e5e 100644 --- a/core/src/test/java/org/bitcoinj/core/TransactionBroadcastTest.java +++ b/core/src/test/java/org/bitcoinj/core/TransactionBroadcastTest.java @@ -66,7 +66,7 @@ public class TransactionBroadcastTest extends TestWithPeerGroup { @Test public void fourPeers() throws Exception { InboundMessageQueuer[] channels = { connectPeer(1), connectPeer(2), connectPeer(3), connectPeer(4) }; - Transaction tx = new Transaction(PARAMS); + Transaction tx = new Transaction(UNITTEST); tx.getConfidence().setSource(TransactionConfidence.Source.SELF); TransactionBroadcast broadcast = new TransactionBroadcast(peerGroup, tx); final AtomicDouble lastProgress = new AtomicDouble(); @@ -109,7 +109,7 @@ public class TransactionBroadcastTest extends TestWithPeerGroup { // immediately with the latest state. This avoids API users writing accidentally racy code when they use // a convenience method like peerGroup.broadcastTransaction. InboundMessageQueuer[] channels = { connectPeer(1), connectPeer(2), connectPeer(3), connectPeer(4) }; - Transaction tx = FakeTxBuilder.createFakeTx(PARAMS, CENT, address); + Transaction tx = FakeTxBuilder.createFakeTx(UNITTEST, CENT, address); tx.getConfidence().setSource(TransactionConfidence.Source.SELF); TransactionBroadcast broadcast = peerGroup.broadcastTransaction(tx); inbound(channels[1], InventoryMessage.with(tx)); @@ -127,14 +127,14 @@ public class TransactionBroadcastTest extends TestWithPeerGroup { @Test public void rejectHandling() throws Exception { InboundMessageQueuer[] channels = { connectPeer(0), connectPeer(1), connectPeer(2), connectPeer(3), connectPeer(4) }; - Transaction tx = new Transaction(PARAMS); + Transaction tx = new Transaction(UNITTEST); TransactionBroadcast broadcast = new TransactionBroadcast(peerGroup, tx); ListenableFuture future = broadcast.broadcast(); // 0 and 3 are randomly selected to receive the broadcast. assertEquals(tx, outbound(channels[1])); assertEquals(tx, outbound(channels[2])); assertEquals(tx, outbound(channels[4])); - RejectMessage reject = new RejectMessage(PARAMS, RejectMessage.RejectCode.DUST, tx.getHash(), "tx", "dust"); + RejectMessage reject = new RejectMessage(UNITTEST, RejectMessage.RejectCode.DUST, tx.getHash(), "tx", "dust"); inbound(channels[1], reject); inbound(channels[4], reject); try { @@ -159,7 +159,7 @@ public class TransactionBroadcastTest extends TestWithPeerGroup { assertEquals(FIFTY_COINS, wallet.getBalance()); // Now create a spend, and expect the announcement on p1. - Address dest = Address.fromKey(PARAMS, new ECKey()); + Address dest = Address.fromKey(UNITTEST, new ECKey()); Wallet.SendResult sendResult = wallet.sendCoins(peerGroup, dest, COIN); assertFalse(sendResult.broadcastComplete.isDone()); Transaction t1; @@ -186,7 +186,7 @@ public class TransactionBroadcastTest extends TestWithPeerGroup { // Make sure we can create spends, and that they are announced. Then do the same with offline mode. // Set up connections and block chain. - VersionMessage ver = new VersionMessage(PARAMS, 2); + VersionMessage ver = new VersionMessage(UNITTEST, 2); ver.localServices = VersionMessage.NODE_NETWORK; InboundMessageQueuer p1 = connectPeer(1, ver); InboundMessageQueuer p2 = connectPeer(2); @@ -208,7 +208,7 @@ public class TransactionBroadcastTest extends TestWithPeerGroup { }); // Now create a spend, and expect the announcement on p1. - Address dest = Address.fromKey(PARAMS, new ECKey()); + Address dest = Address.fromKey(UNITTEST, new ECKey()); Wallet.SendResult sendResult = wallet.sendCoins(peerGroup, dest, COIN); assertNotNull(sendResult.tx); Threading.waitForUserCode(); @@ -229,7 +229,7 @@ public class TransactionBroadcastTest extends TestWithPeerGroup { // 49 BTC in change. assertEquals(valueOf(49, 0), t1.getValueSentToMe(wallet)); // The future won't complete until it's heard back from the network on p2. - InventoryMessage inv = new InventoryMessage(PARAMS); + InventoryMessage inv = new InventoryMessage(UNITTEST); inv.addTransaction(t1); inbound(p2, inv); pingAndWait(p2); diff --git a/core/src/test/java/org/bitcoinj/core/TransactionInputTest.java b/core/src/test/java/org/bitcoinj/core/TransactionInputTest.java index 73f98f76..db60ba42 100644 --- a/core/src/test/java/org/bitcoinj/core/TransactionInputTest.java +++ b/core/src/test/java/org/bitcoinj/core/TransactionInputTest.java @@ -32,16 +32,16 @@ import org.junit.Test; import com.google.common.collect.Lists; public class TransactionInputTest { + private static final NetworkParameters UNITTEST = UnitTestParams.get(); @Test public void testStandardWalletDisconnect() throws Exception { - NetworkParameters params = UnitTestParams.get(); - Wallet w = new Wallet(new Context(params)); + Wallet w = new Wallet(new Context(UNITTEST)); w.setCoinSelector(new AllowUnconfirmedCoinSelector()); Address a = w.currentReceiveAddress(); - Transaction tx1 = FakeTxBuilder.createFakeTxWithoutChangeAddress(params, Coin.COIN, a); + Transaction tx1 = FakeTxBuilder.createFakeTxWithoutChangeAddress(UNITTEST, Coin.COIN, a); w.receivePending(tx1, null); - Transaction tx2 = new Transaction(params); + Transaction tx2 = new Transaction(UNITTEST); tx2.addOutput(Coin.valueOf(99000000), new ECKey()); w.completeTx(SendRequest.forTx(tx2)); @@ -58,15 +58,14 @@ public class TransactionInputTest { @Test public void testUTXOWalletDisconnect() throws Exception { - final NetworkParameters params = UnitTestParams.get(); - Wallet w = new Wallet(new Context(params)); + Wallet w = new Wallet(new Context(UNITTEST)); Address a = w.currentReceiveAddress(); final UTXO utxo = new UTXO(Sha256Hash.of(new byte[] { 1, 2, 3 }), 1, Coin.COIN, 0, false, ScriptBuilder.createOutputScript(a)); w.setUTXOProvider(new UTXOProvider() { @Override public NetworkParameters getParams() { - return params; + return UNITTEST; } @Override @@ -80,7 +79,7 @@ public class TransactionInputTest { } }); - Transaction tx2 = new Transaction(params); + Transaction tx2 = new Transaction(UNITTEST); tx2.addOutput(Coin.valueOf(99000000), new ECKey()); w.completeTx(SendRequest.forTx(tx2)); diff --git a/core/src/test/java/org/bitcoinj/core/TransactionOutputTest.java b/core/src/test/java/org/bitcoinj/core/TransactionOutputTest.java index 4ef31140..ce4b7509 100644 --- a/core/src/test/java/org/bitcoinj/core/TransactionOutputTest.java +++ b/core/src/test/java/org/bitcoinj/core/TransactionOutputTest.java @@ -51,7 +51,7 @@ public class TransactionOutputTest extends TestWithWallet { ECKey otherKey = new ECKey(); // Create multi-sig transaction - Transaction multiSigTransaction = new Transaction(PARAMS); + Transaction multiSigTransaction = new Transaction(UNITTEST); ImmutableList keys = ImmutableList.of(myKey, otherKey); Script scriptPubKey = ScriptBuilder.createMultiSigOutputScript(2, keys); @@ -67,24 +67,24 @@ public class TransactionOutputTest extends TestWithWallet { @Test public void testP2SHOutputScript() throws Exception { String P2SHAddressString = "35b9vsyH1KoFT5a5KtrKusaCcPLkiSo1tU"; - Address P2SHAddress = Address.fromBase58(MainNetParams.get(), P2SHAddressString); + Address P2SHAddress = Address.fromBase58(MAINNET, P2SHAddressString); Script script = ScriptBuilder.createOutputScript(P2SHAddress); - Transaction tx = new Transaction(MainNetParams.get()); + Transaction tx = new Transaction(MAINNET); tx.addOutput(Coin.COIN, script); - assertEquals(P2SHAddressString, tx.getOutput(0).getAddressFromP2SH(MainNetParams.get()).toString()); + assertEquals(P2SHAddressString, tx.getOutput(0).getAddressFromP2SH(MAINNET).toString()); } @Test public void getAddressTests() throws Exception { - Transaction tx = new Transaction(MainNetParams.get()); + Transaction tx = new Transaction(MAINNET); tx.addOutput(Coin.CENT, ScriptBuilder.createOpReturnScript("hello world!".getBytes())); - assertNull(tx.getOutput(0).getAddressFromP2SH(PARAMS)); - assertNull(tx.getOutput(0).getAddressFromP2PKHScript(PARAMS)); + assertNull(tx.getOutput(0).getAddressFromP2SH(UNITTEST)); + assertNull(tx.getOutput(0).getAddressFromP2PKHScript(UNITTEST)); } @Test public void getMinNonDustValue() throws Exception { - TransactionOutput payToAddressOutput = new TransactionOutput(PARAMS, null, Coin.COIN, myAddress); + TransactionOutput payToAddressOutput = new TransactionOutput(UNITTEST, null, Coin.COIN, myAddress); assertEquals(Transaction.MIN_NONDUST_OUTPUT, payToAddressOutput.getMinNonDustValue()); } } diff --git a/core/src/test/java/org/bitcoinj/core/TransactionTest.java b/core/src/test/java/org/bitcoinj/core/TransactionTest.java index 6dbff90c..f20c1920 100644 --- a/core/src/test/java/org/bitcoinj/core/TransactionTest.java +++ b/core/src/test/java/org/bitcoinj/core/TransactionTest.java @@ -39,15 +39,15 @@ import static org.junit.Assert.*; * so we make sure to cover it here as well. */ public class TransactionTest { - private static final NetworkParameters PARAMS = UnitTestParams.get(); - private static final Address ADDRESS = Address.fromKey(PARAMS, new ECKey()); + private static final NetworkParameters UNITTEST = UnitTestParams.get(); + private static final Address ADDRESS = Address.fromKey(UNITTEST, new ECKey()); private Transaction tx; @Before public void setUp() throws Exception { - Context context = new Context(PARAMS); - tx = FakeTxBuilder.createFakeTx(PARAMS); + Context context = new Context(UNITTEST); + tx = FakeTxBuilder.createFakeTx(UNITTEST); } @Test(expected = VerificationException.EmptyInputsOrOutputs.class) @@ -84,7 +84,7 @@ public class TransactionTest { @Test(expected = VerificationException.ExcessiveValue.class) public void exceedsMaxMoney2() throws Exception { - Coin half = PARAMS.getMaxMoney().divide(2).add(Coin.SATOSHI); + Coin half = UNITTEST.getMaxMoney().divide(2).add(Coin.SATOSHI); tx.getOutput(0).setValue(half); tx.addOutput(half, ADDRESS); tx.verify(); @@ -119,7 +119,7 @@ public class TransactionTest { BlockChain mockBlockChain = createMock(BlockChain.class); EasyMock.expect(mockBlockChain.estimateBlockTime(TEST_LOCK_TIME)).andReturn(now); - Transaction tx = FakeTxBuilder.createFakeTx(PARAMS); + Transaction tx = FakeTxBuilder.createFakeTx(UNITTEST); tx.setLockTime(TEST_LOCK_TIME); // less than five hundred million replay(mockBlockChain); @@ -129,12 +129,12 @@ public class TransactionTest { @Test public void testOptimalEncodingMessageSize() { - Transaction tx = new Transaction(PARAMS); + Transaction tx = new Transaction(UNITTEST); int length = tx.length; // add basic transaction input, check the length - tx.addOutput(new TransactionOutput(PARAMS, null, Coin.COIN, ADDRESS)); + tx.addOutput(new TransactionOutput(UNITTEST, null, Coin.COIN, ADDRESS)); length += getCombinedLength(tx.getOutputs()); // add basic output, check the length @@ -152,7 +152,7 @@ public class TransactionTest { @Test public void testIsMatureReturnsFalseIfTransactionIsCoinbaseAndConfidenceTypeIsNotEqualToBuilding() { - Transaction tx = FakeTxBuilder.createFakeCoinbaseTx(PARAMS); + Transaction tx = FakeTxBuilder.createFakeCoinbaseTx(UNITTEST); tx.getConfidence().setConfidenceType(ConfidenceType.UNKNOWN); assertEquals(tx.isMature(), false); @@ -171,8 +171,8 @@ public class TransactionTest { ECKey from = new ECKey(), to = new ECKey(), incorrect = new ECKey(); Script outputScript = ScriptBuilder.createCLTVPaymentChannelOutput(time, from, to); - Transaction tx = new Transaction(PARAMS); - tx.addInput(new TransactionInput(PARAMS, tx, new byte[] {})); + Transaction tx = new Transaction(UNITTEST); + tx.addInput(new TransactionInput(UNITTEST, tx, new byte[] {})); tx.getInput(0).setSequenceNumber(0); tx.setLockTime(time.subtract(BigInteger.ONE).longValue()); TransactionSignature fromSig = @@ -233,8 +233,8 @@ public class TransactionTest { ECKey from = new ECKey(), to = new ECKey(), incorrect = new ECKey(); Script outputScript = ScriptBuilder.createCLTVPaymentChannelOutput(time, from, to); - Transaction tx = new Transaction(PARAMS); - tx.addInput(new TransactionInput(PARAMS, tx, new byte[] {})); + Transaction tx = new Transaction(UNITTEST); + tx.addInput(new TransactionInput(UNITTEST, tx, new byte[] {})); tx.getInput(0).setSequenceNumber(0); tx.setLockTime(time.add(BigInteger.ONE).longValue()); TransactionSignature fromSig = @@ -271,7 +271,7 @@ public class TransactionTest { @Test public void testToStringWhenLockTimeIsSpecifiedInBlockHeight() { - Transaction tx = FakeTxBuilder.createFakeTx(PARAMS); + Transaction tx = FakeTxBuilder.createFakeTx(UNITTEST); TransactionInput input = tx.getInput(0); input.setSequenceNumber(42); @@ -295,8 +295,8 @@ public class TransactionTest { @Test public void testToStringWhenIteratingOverAnInputCatchesAnException() { - Transaction tx = FakeTxBuilder.createFakeTx(PARAMS); - TransactionInput ti = new TransactionInput(PARAMS, tx, new byte[0]) { + Transaction tx = FakeTxBuilder.createFakeTx(UNITTEST); + TransactionInput ti = new TransactionInput(UNITTEST, tx, new byte[0]) { @Override public Script getScriptSig() throws ScriptException { throw new ScriptException(ScriptError.SCRIPT_ERR_UNKNOWN_ERROR, ""); @@ -309,19 +309,19 @@ public class TransactionTest { @Test public void testToStringWhenThereAreZeroInputs() { - Transaction tx = new Transaction(PARAMS); + Transaction tx = new Transaction(UNITTEST); assertEquals(tx.toString().contains("No inputs!"), true); } @Test public void testTheTXByHeightComparator() { - Transaction tx1 = FakeTxBuilder.createFakeTx(PARAMS); + Transaction tx1 = FakeTxBuilder.createFakeTx(UNITTEST); tx1.getConfidence().setAppearedAtChainHeight(1); - Transaction tx2 = FakeTxBuilder.createFakeTx(PARAMS); + Transaction tx2 = FakeTxBuilder.createFakeTx(UNITTEST); tx2.getConfidence().setAppearedAtChainHeight(2); - Transaction tx3 = FakeTxBuilder.createFakeTx(PARAMS); + Transaction tx3 = FakeTxBuilder.createFakeTx(UNITTEST); tx3.getConfidence().setAppearedAtChainHeight(3); SortedSet set = new TreeSet<>(Transaction.SORT_TX_BY_HEIGHT); @@ -344,10 +344,10 @@ public class TransactionTest { @Test(expected = ScriptException.class) public void testAddSignedInputThrowsExceptionWhenScriptIsNotToRawPubKeyAndIsNotToAddress() { ECKey key = new ECKey(); - Address addr = Address.fromKey(PARAMS, key); - Transaction fakeTx = FakeTxBuilder.createFakeTx(PARAMS, Coin.COIN, addr); + Address addr = Address.fromKey(UNITTEST, key); + Transaction fakeTx = FakeTxBuilder.createFakeTx(UNITTEST, Coin.COIN, addr); - Transaction tx = new Transaction(PARAMS); + Transaction tx = new Transaction(UNITTEST); tx.addOutput(fakeTx.getOutput(0)); Script script = ScriptBuilder.createOpReturnScript(new byte[0]); @@ -357,7 +357,7 @@ public class TransactionTest { @Test public void testPrioSizeCalc() throws Exception { - Transaction tx1 = FakeTxBuilder.createFakeTx(PARAMS, Coin.COIN, ADDRESS); + Transaction tx1 = FakeTxBuilder.createFakeTx(UNITTEST, Coin.COIN, ADDRESS); int size1 = tx1.getMessageSize(); int size2 = tx1.getMessageSizeForPriorityCalc(); assertEquals(113, size1 - size2); @@ -375,7 +375,7 @@ public class TransactionTest { final byte[] transactionBytes = HEX.decode( "01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff4803e09304062f503253482f0403c86d53087ceca141295a00002e522cfabe6d6d7561cf262313da1144026c8f7a43e3899c44f6145f39a36507d36679a8b7006104000000000000000000000001c8704095000000001976a91480ad90d403581fa3bf46086a91b2d9d4125db6c188ac00000000"); final int height = 300000; - final Transaction transaction = PARAMS.getDefaultSerializer().makeTransaction(transactionBytes); + final Transaction transaction = UNITTEST.getDefaultSerializer().makeTransaction(transactionBytes); transaction.checkCoinBaseHeight(height); } @@ -389,14 +389,14 @@ public class TransactionTest { final byte[] transactionBytes = HEX.decode( "01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff3b03ae6c0300044bd7031a0400000000522cfabe6d6d00000000000000b7b8bf0100000068692066726f6d20706f6f6c7365727665726aac1eeeed88ffffffff01e0587597000000001976a91421c0d001728b3feaf115515b7c135e779e9f442f88ac00000000"); final int height = 224430; - final Transaction transaction = PARAMS.getDefaultSerializer().makeTransaction(transactionBytes); + final Transaction transaction = UNITTEST.getDefaultSerializer().makeTransaction(transactionBytes); transaction.checkCoinBaseHeight(height); } @Test public void optInFullRBF() { // a standard transaction as wallets would create - Transaction tx = FakeTxBuilder.createFakeTx(PARAMS); + Transaction tx = FakeTxBuilder.createFakeTx(UNITTEST); assertFalse(tx.isOptInFullRBF()); tx.getInputs().get(0).setSequenceNumber(TransactionInput.NO_SEQUENCE - 2); @@ -408,8 +408,8 @@ public class TransactionTest { */ @Test public void testHashForSignatureThreadSafety() { - Block genesis = UnitTestParams.get().getGenesisBlock(); - Block block1 = genesis.createNextBlock(Address.fromKey(UnitTestParams.get(), new ECKey()), + Block genesis = UNITTEST.getGenesisBlock(); + Block block1 = genesis.createNextBlock(Address.fromKey(UNITTEST, new ECKey()), genesis.getTransactions().get(0).getOutput(0).getOutPointFor()); final Transaction tx = block1.getTransactions().get(1); diff --git a/core/src/test/java/org/bitcoinj/core/TxConfidenceTableTest.java b/core/src/test/java/org/bitcoinj/core/TxConfidenceTableTest.java index 14885ab7..e6103ad6 100644 --- a/core/src/test/java/org/bitcoinj/core/TxConfidenceTableTest.java +++ b/core/src/test/java/org/bitcoinj/core/TxConfidenceTableTest.java @@ -27,7 +27,7 @@ import static org.bitcoinj.core.Coin.*; import static org.junit.Assert.*; public class TxConfidenceTableTest { - private static final NetworkParameters PARAMS = UnitTestParams.get(); + private static final NetworkParameters UNITTEST = UnitTestParams.get(); private Transaction tx1, tx2; private PeerAddress address1, address2, address3; private TxConfidenceTable table; @@ -35,24 +35,24 @@ public class TxConfidenceTableTest { @Before public void setup() throws Exception { BriefLogFormatter.init(); - Context context = new Context(PARAMS); + Context context = new Context(UNITTEST); table = context.getConfidenceTable(); - Address to = Address.fromKey(PARAMS, new ECKey()); - Address change = Address.fromKey(PARAMS, new ECKey()); + Address to = Address.fromKey(UNITTEST, new ECKey()); + Address change = Address.fromKey(UNITTEST, new ECKey()); - tx1 = FakeTxBuilder.createFakeTxWithChangeAddress(PARAMS, COIN, to, change); - tx2 = FakeTxBuilder.createFakeTxWithChangeAddress(PARAMS, COIN, to, change); + tx1 = FakeTxBuilder.createFakeTxWithChangeAddress(UNITTEST, COIN, to, change); + tx2 = FakeTxBuilder.createFakeTxWithChangeAddress(UNITTEST, COIN, to, change); assertEquals(tx1.getHash(), tx2.getHash()); - address1 = new PeerAddress(PARAMS, InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 })); - address2 = new PeerAddress(PARAMS, InetAddress.getByAddress(new byte[] { 127, 0, 0, 2 })); - address3 = new PeerAddress(PARAMS, InetAddress.getByAddress(new byte[] { 127, 0, 0, 3 })); + address1 = new PeerAddress(UNITTEST, InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 })); + address2 = new PeerAddress(UNITTEST, InetAddress.getByAddress(new byte[] { 127, 0, 0, 2 })); + address3 = new PeerAddress(UNITTEST, InetAddress.getByAddress(new byte[] { 127, 0, 0, 3 })); } @Test public void pinHandlers() throws Exception { - Transaction tx = PARAMS.getDefaultSerializer().makeTransaction(tx1.bitcoinSerialize()); + Transaction tx = UNITTEST.getDefaultSerializer().makeTransaction(tx1.bitcoinSerialize()); Sha256Hash hash = tx.getHash(); table.seen(hash, address1); assertEquals(1, tx.getConfidence().numBroadcastPeers()); diff --git a/core/src/test/java/org/bitcoinj/core/VersionMessageTest.java b/core/src/test/java/org/bitcoinj/core/VersionMessageTest.java index 6a023e5b..fb62894b 100644 --- a/core/src/test/java/org/bitcoinj/core/VersionMessageTest.java +++ b/core/src/test/java/org/bitcoinj/core/VersionMessageTest.java @@ -26,27 +26,27 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class VersionMessageTest { + private static final NetworkParameters UNITTEST = UnitTestParams.get(); + @Test // Test that we can decode version messages which miss data which some old nodes may not include public void testDecode() throws Exception { - NetworkParameters params = UnitTestParams.get(); - - VersionMessage ver = new VersionMessage(params, HEX.decode("7111010000000000000000003334a85500000000000000000000000000000000000000000000ffff7f000001479d000000000000000000000000000000000000ffff7f000001479d00000000000000000f2f626974636f696e6a3a302e31332f0004000000")); + VersionMessage ver = new VersionMessage(UNITTEST, HEX.decode("7111010000000000000000003334a85500000000000000000000000000000000000000000000ffff7f000001479d000000000000000000000000000000000000ffff7f000001479d00000000000000000f2f626974636f696e6a3a302e31332f0004000000")); assertFalse(ver.relayTxesBeforeFilter); assertEquals(1024, ver.bestHeight); assertEquals("/bitcoinj:0.13/", ver.subVer); - ver = new VersionMessage(params, HEX.decode("711101000000000000000000a634a85500000000000000000000000000000000000000000000ffff7f000001479d000000000000000000000000000000000000ffff7f000001479d00000000000000000f2f626974636f696e6a3a302e31332f0004000001")); + ver = new VersionMessage(UNITTEST, HEX.decode("711101000000000000000000a634a85500000000000000000000000000000000000000000000ffff7f000001479d000000000000000000000000000000000000ffff7f000001479d00000000000000000f2f626974636f696e6a3a302e31332f0004000001")); assertTrue(ver.relayTxesBeforeFilter); assertEquals(1024, ver.bestHeight); assertEquals("/bitcoinj:0.13/", ver.subVer); - ver = new VersionMessage(params, HEX.decode("711101000000000000000000c334a85500000000000000000000000000000000000000000000ffff7f000001479d000000000000000000000000000000000000ffff7f000001479d00000000000000000f2f626974636f696e6a3a302e31332f0000000001")); + ver = new VersionMessage(UNITTEST, HEX.decode("711101000000000000000000c334a85500000000000000000000000000000000000000000000ffff7f000001479d000000000000000000000000000000000000ffff7f000001479d00000000000000000f2f626974636f696e6a3a302e31332f0000000001")); assertTrue(ver.relayTxesBeforeFilter); assertEquals(0, ver.bestHeight); assertEquals("/bitcoinj:0.13/", ver.subVer); - ver = new VersionMessage(params, HEX.decode("71110100000000000000000048e5e95000000000000000000000000000000000000000000000ffff7f000001479d000000000000000000000000000000000000ffff7f000001479d0000000000000000")); + ver = new VersionMessage(UNITTEST, HEX.decode("71110100000000000000000048e5e95000000000000000000000000000000000000000000000ffff7f000001479d000000000000000000000000000000000000ffff7f000001479d0000000000000000")); assertTrue(ver.relayTxesBeforeFilter); assertEquals(0, ver.bestHeight); assertEquals("", ver.subVer); diff --git a/core/src/test/java/org/bitcoinj/crypto/BIP32Test.java b/core/src/test/java/org/bitcoinj/crypto/BIP32Test.java index 0f57b533..51e3a4e8 100644 --- a/core/src/test/java/org/bitcoinj/crypto/BIP32Test.java +++ b/core/src/test/java/org/bitcoinj/crypto/BIP32Test.java @@ -39,6 +39,7 @@ import static org.junit.Assert.assertEquals; */ public class BIP32Test { private static final Logger log = LoggerFactory.getLogger(BIP32Test.class); + private static final NetworkParameters MAINNET = MainNetParams.get(); HDWTestVector[] tvs = { new HDWTestVector( @@ -148,10 +149,9 @@ public class BIP32Test { private void testVector(int testCase) { log.info("======= Test vector {}", testCase); HDWTestVector tv = tvs[testCase]; - NetworkParameters params = MainNetParams.get(); DeterministicKey masterPrivateKey = HDKeyDerivation.createMasterPrivateKey(HEX.decode(tv.seed)); - assertEquals(testEncode(tv.priv), testEncode(masterPrivateKey.serializePrivB58(params))); - assertEquals(testEncode(tv.pub), testEncode(masterPrivateKey.serializePubB58(params))); + assertEquals(testEncode(tv.priv), testEncode(masterPrivateKey.serializePrivB58(MAINNET))); + assertEquals(testEncode(tv.pub), testEncode(masterPrivateKey.serializePubB58(MAINNET))); DeterministicHierarchy dh = new DeterministicHierarchy(masterPrivateKey); for (int i = 0; i < tv.derived.size(); i++) { HDWTestVector.DerivedTestCase tc = tv.derived.get(i); @@ -159,8 +159,8 @@ public class BIP32Test { assertEquals(tc.name, String.format(Locale.US, "Test%d %s", testCase + 1, tc.getPathDescription())); int depth = tc.path.length - 1; DeterministicKey ehkey = dh.deriveChild(Arrays.asList(tc.path).subList(0, depth), false, true, tc.path[depth]); - assertEquals(testEncode(tc.priv), testEncode(ehkey.serializePrivB58(params))); - assertEquals(testEncode(tc.pub), testEncode(ehkey.serializePubB58(params))); + assertEquals(testEncode(tc.priv), testEncode(ehkey.serializePrivB58(MAINNET))); + assertEquals(testEncode(tc.pub), testEncode(ehkey.serializePubB58(MAINNET))); } } diff --git a/core/src/test/java/org/bitcoinj/crypto/BIP38PrivateKeyTest.java b/core/src/test/java/org/bitcoinj/crypto/BIP38PrivateKeyTest.java index 5cbbc30e..589b044c 100644 --- a/core/src/test/java/org/bitcoinj/crypto/BIP38PrivateKeyTest.java +++ b/core/src/test/java/org/bitcoinj/crypto/BIP38PrivateKeyTest.java @@ -17,6 +17,7 @@ package org.bitcoinj.crypto; import org.bitcoinj.core.ECKey; +import org.bitcoinj.core.NetworkParameters; import org.bitcoinj.crypto.BIP38PrivateKey.BadPassphraseException; import org.bitcoinj.params.MainNetParams; import org.bitcoinj.params.TestNet3Params; @@ -31,9 +32,8 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotSame; public class BIP38PrivateKeyTest { - - private static final MainNetParams MAINNET = MainNetParams.get(); - private static final TestNet3Params TESTNET = TestNet3Params.get(); + private static final NetworkParameters MAINNET = MainNetParams.get(); + private static final NetworkParameters TESTNET = TestNet3Params.get(); @Test public void bip38testvector_noCompression_noEcMultiply_test1() throws Exception { @@ -70,7 +70,7 @@ public class BIP38PrivateKeyTest { @Test public void bip38testvector_compression_noEcMultiply_test1() throws Exception { - BIP38PrivateKey encryptedKey = BIP38PrivateKey.fromBase58(MainNetParams.get(), + BIP38PrivateKey encryptedKey = BIP38PrivateKey.fromBase58(MAINNET, "6PYNKZ1EAgYgmQfmNVamxyXVWHzK5s6DGhwP4J5o44cvXdoY7sRzhtpUeo"); ECKey key = encryptedKey.decrypt("TestingOneTwoThree"); assertEquals("L44B5gGEpqEDRS9vVPz7QT35jcBG2r3CZwSwQ4fCewXAhAhqGVpP", key.getPrivateKeyEncoded(MAINNET) @@ -79,7 +79,7 @@ public class BIP38PrivateKeyTest { @Test public void bip38testvector_compression_noEcMultiply_test2() throws Exception { - BIP38PrivateKey encryptedKey = BIP38PrivateKey.fromBase58(MainNetParams.get(), + BIP38PrivateKey encryptedKey = BIP38PrivateKey.fromBase58(MAINNET, "6PYLtMnXvfG3oJde97zRyLYFZCYizPU5T3LwgdYJz1fRhh16bU7u6PPmY7"); ECKey key = encryptedKey.decrypt("Satoshi"); assertEquals("KwYgW8gcxj1JWJXhPSu4Fqwzfhp5Yfi42mdYmMa4XqK7NJxXUSK7", key.getPrivateKeyEncoded(MAINNET) @@ -88,7 +88,7 @@ public class BIP38PrivateKeyTest { @Test public void bip38testvector_ecMultiply_noCompression_noLotAndSequence_test1() throws Exception { - BIP38PrivateKey encryptedKey = BIP38PrivateKey.fromBase58(MainNetParams.get(), + BIP38PrivateKey encryptedKey = BIP38PrivateKey.fromBase58(MAINNET, "6PfQu77ygVyJLZjfvMLyhLMQbYnu5uguoJJ4kMCLqWwPEdfpwANVS76gTX"); ECKey key = encryptedKey.decrypt("TestingOneTwoThree"); assertEquals("5K4caxezwjGCGfnoPTZ8tMcJBLB7Jvyjv4xxeacadhq8nLisLR2", key.getPrivateKeyEncoded(MAINNET) @@ -97,7 +97,7 @@ public class BIP38PrivateKeyTest { @Test public void bip38testvector_ecMultiply_noCompression_noLotAndSequence_test2() throws Exception { - BIP38PrivateKey encryptedKey = BIP38PrivateKey.fromBase58(MainNetParams.get(), + BIP38PrivateKey encryptedKey = BIP38PrivateKey.fromBase58(MAINNET, "6PfLGnQs6VZnrNpmVKfjotbnQuaJK4KZoPFrAjx1JMJUa1Ft8gnf5WxfKd"); ECKey key = encryptedKey.decrypt("Satoshi"); assertEquals("5KJ51SgxWaAYR13zd9ReMhJpwrcX47xTJh2D3fGPG9CM8vkv5sH", key.getPrivateKeyEncoded(MAINNET) @@ -106,7 +106,7 @@ public class BIP38PrivateKeyTest { @Test public void bip38testvector_ecMultiply_noCompression_lotAndSequence_test1() throws Exception { - BIP38PrivateKey encryptedKey = BIP38PrivateKey.fromBase58(MainNetParams.get(), + BIP38PrivateKey encryptedKey = BIP38PrivateKey.fromBase58(MAINNET, "6PgNBNNzDkKdhkT6uJntUXwwzQV8Rr2tZcbkDcuC9DZRsS6AtHts4Ypo1j"); ECKey key = encryptedKey.decrypt("MOLON LABE"); assertEquals("5JLdxTtcTHcfYcmJsNVy1v2PMDx432JPoYcBTVVRHpPaxUrdtf8", key.getPrivateKeyEncoded(MAINNET) @@ -115,7 +115,7 @@ public class BIP38PrivateKeyTest { @Test public void bip38testvector_ecMultiply_noCompression_lotAndSequence_test2() throws Exception { - BIP38PrivateKey encryptedKey = BIP38PrivateKey.fromBase58(MainNetParams.get(), + BIP38PrivateKey encryptedKey = BIP38PrivateKey.fromBase58(MAINNET, "6PgGWtx25kUg8QWvwuJAgorN6k9FbE25rv5dMRwu5SKMnfpfVe5mar2ngH"); ECKey key = encryptedKey.decrypt("ΜΟΛΩΝ ΛΑΒΕ"); assertEquals("5KMKKuUmAkiNbA3DazMQiLfDq47qs8MAEThm4yL8R2PhV1ov33D", key.getPrivateKeyEncoded(MAINNET) diff --git a/core/src/test/java/org/bitcoinj/crypto/ChildKeyDerivationTest.java b/core/src/test/java/org/bitcoinj/crypto/ChildKeyDerivationTest.java index afcffb3e..7e6d4d3a 100644 --- a/core/src/test/java/org/bitcoinj/crypto/ChildKeyDerivationTest.java +++ b/core/src/test/java/org/bitcoinj/crypto/ChildKeyDerivationTest.java @@ -29,6 +29,10 @@ import static org.junit.Assert.*; * This test is adapted from Armory's BIP 32 tests. */ public class ChildKeyDerivationTest { + private static final NetworkParameters MAINNET = MainNetParams.get(); + private static final NetworkParameters TESTNET = TestNet3Params.get(); + private static final NetworkParameters UNITTEST = UnitTestParams.get(); + private static final int HDW_CHAIN_EXTERNAL = 0; private static final int HDW_CHAIN_INTERNAL = 1; @@ -188,14 +192,12 @@ public class ChildKeyDerivationTest { @Test public void testSerializationMainAndTestNetworks() { DeterministicKey key1 = HDKeyDerivation.createMasterPrivateKey("satoshi lives!".getBytes()); - NetworkParameters params = MainNetParams.get(); - String pub58 = key1.serializePubB58(params); - String priv58 = key1.serializePrivB58(params); + String pub58 = key1.serializePubB58(MAINNET); + String priv58 = key1.serializePrivB58(MAINNET); assertEquals("xpub661MyMwAqRbcF7mq7Aejj5xZNzFfgi3ABamE9FedDHVmViSzSxYTgAQGcATDo2J821q7Y9EAagjg5EP3L7uBZk11PxZU3hikL59dexfLkz3", pub58); assertEquals("xprv9s21ZrQH143K2dhN197jMx1ppxRBHFKJpMqdLsF1ewxncv7quRED8N5nksxphju3W7naj1arF56L5PUEWfuSk8h73Sb2uh7bSwyXNrjzhAZ", priv58); - params = TestNet3Params.get(); - pub58 = key1.serializePubB58(params); - priv58 = key1.serializePrivB58(params); + pub58 = key1.serializePubB58(TESTNET); + priv58 = key1.serializePrivB58(TESTNET); assertEquals("tpubD6NzVbkrYhZ4WuxgZMdpw1Hvi7MKg6YDjDMXVohmZCFfF17hXBPYpc56rCY1KXFMovN29ik37nZimQseiykRTBTJTZJmjENyv2k3R12BJ1M", pub58); assertEquals("tprv8ZgxMBicQKsPdSvtfhyEXbdp95qPWmMK9ukkDHfU8vTGQWrvtnZxe7TEg48Ui7HMsZKMj7CcQRg8YF1ydtFPZBxha5oLa3qeN3iwpYhHPVZ", priv58); } @@ -207,7 +209,7 @@ public class ChildKeyDerivationTest { // Creation time can't survive the xpub serialization format unfortunately. key1.setCreationTimeSeconds(0); - NetworkParameters params = MainNetParams.get(); + NetworkParameters params = MAINNET; { final String pub58 = key1.serializePubB58(params); @@ -241,15 +243,14 @@ public class ChildKeyDerivationTest { @Test public void parentlessDeserialization() { - NetworkParameters params = UnitTestParams.get(); DeterministicKey key1 = HDKeyDerivation.createMasterPrivateKey("satoshi lives!".getBytes()); DeterministicKey key2 = HDKeyDerivation.deriveChildKey(key1, ChildNumber.ZERO_HARDENED); DeterministicKey key3 = HDKeyDerivation.deriveChildKey(key2, ChildNumber.ZERO_HARDENED); DeterministicKey key4 = HDKeyDerivation.deriveChildKey(key3, ChildNumber.ZERO_HARDENED); assertEquals(key4.getPath().size(), 3); - assertEquals(DeterministicKey.deserialize(params, key4.serializePrivate(params), key3).getPath().size(), 3); - assertEquals(DeterministicKey.deserialize(params, key4.serializePrivate(params), null).getPath().size(), 1); - assertEquals(DeterministicKey.deserialize(params, key4.serializePrivate(params)).getPath().size(), 1); + assertEquals(DeterministicKey.deserialize(UNITTEST, key4.serializePrivate(UNITTEST), key3).getPath().size(), 3); + assertEquals(DeterministicKey.deserialize(UNITTEST, key4.serializePrivate(UNITTEST), null).getPath().size(), 1); + assertEquals(DeterministicKey.deserialize(UNITTEST, key4.serializePrivate(UNITTEST)).getPath().size(), 1); } /** Reserializing a deserialized key should yield the original input */ @@ -259,8 +260,8 @@ public class ChildKeyDerivationTest { // https://en.bitcoin.it/wiki/BIP_0032_TestVectors String encoded = "xpub6D4BDPcP2GT577Vvch3R8wDkScZWzQzMMUm3PWbmWvVJrZwQY4VUNgqFJPMM3No2dFDFGTsxxpG5uJh7n7epu4trkrX7x7DogT5Uv6fcLW5"; - DeterministicKey key = DeterministicKey.deserializeB58(encoded, MainNetParams.get()); - assertEquals("Reserialized parentless private HD key is wrong", key.serializePubB58(MainNetParams.get()), encoded); + DeterministicKey key = DeterministicKey.deserializeB58(encoded, MAINNET); + assertEquals("Reserialized parentless private HD key is wrong", key.serializePubB58(MAINNET), encoded); assertEquals("Depth of deserialized parentless public HD key is wrong", key.getDepth(), 3); assertEquals("Path size of deserialized parentless public HD key is wrong", key.getPath().size(), 1); assertEquals("Parent fingerprint of deserialized parentless public HD key is wrong", @@ -269,8 +270,8 @@ public class ChildKeyDerivationTest { // This encoding is the same key but including its private data: encoded = "xprv9z4pot5VBttmtdRTWfWQmoH1taj2axGVzFqSb8C9xaxKymcFzXBDptWmT7FwuEzG3ryjH4ktypQSAewRiNMjANTtpgP4mLTj34bhnZX7UiM"; - key = DeterministicKey.deserializeB58(encoded, MainNetParams.get()); - assertEquals("Reserialized parentless private HD key is wrong", key.serializePrivB58(MainNetParams.get()), encoded); + key = DeterministicKey.deserializeB58(encoded, MAINNET); + assertEquals("Reserialized parentless private HD key is wrong", key.serializePrivB58(MAINNET), encoded); assertEquals("Depth of deserialized parentless private HD key is wrong", key.getDepth(), 3); assertEquals("Path size of deserialized parentless private HD key is wrong", key.getPath().size(), 1); assertEquals("Parent fingerprint of deserialized parentless private HD key is wrong", @@ -278,10 +279,10 @@ public class ChildKeyDerivationTest { // These encodings are of the the root key of that hierarchy assertEquals("Parent fingerprint of root node public HD key should be zero", - DeterministicKey.deserializeB58("xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB", MainNetParams.get()).getParentFingerprint(), + DeterministicKey.deserializeB58("xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB", MAINNET).getParentFingerprint(), 0); assertEquals("Parent fingerprint of root node private HD key should be zero", - DeterministicKey.deserializeB58("xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U", MainNetParams.get()).getParentFingerprint(), + DeterministicKey.deserializeB58("xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U", MAINNET).getParentFingerprint(), 0); } diff --git a/core/src/test/java/org/bitcoinj/net/discovery/SeedPeersTest.java b/core/src/test/java/org/bitcoinj/net/discovery/SeedPeersTest.java index 626a3547..4ffba51a 100644 --- a/core/src/test/java/org/bitcoinj/net/discovery/SeedPeersTest.java +++ b/core/src/test/java/org/bitcoinj/net/discovery/SeedPeersTest.java @@ -17,6 +17,7 @@ package org.bitcoinj.net.discovery; +import org.bitcoinj.core.NetworkParameters; import org.bitcoinj.params.MainNetParams; import org.junit.Test; @@ -28,16 +29,18 @@ import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; public class SeedPeersTest { + private static final NetworkParameters MAINNET = MainNetParams.get(); + @Test public void getPeer_one() throws Exception{ - SeedPeers seedPeers = new SeedPeers(MainNetParams.get()); + SeedPeers seedPeers = new SeedPeers(MAINNET); assertThat(seedPeers.getPeer(), notNullValue()); } @Test public void getPeer_all() throws Exception{ - SeedPeers seedPeers = new SeedPeers(MainNetParams.get()); - for (int i = 0; i < MainNetParams.get().getAddrSeeds().length; ++i) { + SeedPeers seedPeers = new SeedPeers(MAINNET); + for (int i = 0; i < MAINNET.getAddrSeeds().length; ++i) { assertThat("Failed on index: "+i, seedPeers.getPeer(), notNullValue()); } assertThat(seedPeers.getPeer(), equalTo(null)); @@ -45,8 +48,8 @@ public class SeedPeersTest { @Test public void getPeers_length() throws Exception{ - SeedPeers seedPeers = new SeedPeers(MainNetParams.get()); + SeedPeers seedPeers = new SeedPeers(MAINNET); InetSocketAddress[] addresses = seedPeers.getPeers(0, 0, TimeUnit.SECONDS); - assertThat(addresses.length, equalTo(MainNetParams.get().getAddrSeeds().length)); + assertThat(addresses.length, equalTo(MAINNET.getAddrSeeds().length)); } } diff --git a/core/src/test/java/org/bitcoinj/protocols/channels/ChannelConnectionTest.java b/core/src/test/java/org/bitcoinj/protocols/channels/ChannelConnectionTest.java index 94a31335..ac9eb512 100644 --- a/core/src/test/java/org/bitcoinj/protocols/channels/ChannelConnectionTest.java +++ b/core/src/test/java/org/bitcoinj/protocols/channels/ChannelConnectionTest.java @@ -113,11 +113,11 @@ public class ChannelConnectionTest extends TestWithWallet { public void setUp() throws Exception { super.setUp(); Utils.setMockClock(); // Use mock clock - Context.propagate(new Context(PARAMS, 3, Coin.ZERO, false)); // Shorter event horizon for unit tests. + Context.propagate(new Context(UNITTEST, 3, Coin.ZERO, false)); // Shorter event horizon for unit tests. sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, COIN); sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, COIN); wallet.addExtension(new StoredPaymentChannelClientStates(wallet, failBroadcaster)); - serverWallet = new Wallet(PARAMS); + serverWallet = new Wallet(UNITTEST); serverWallet.addExtension(new StoredPaymentChannelServerStates(serverWallet, failBroadcaster)); serverWallet.freshReceiveKey(); // Use an atomic boolean to indicate failure because fail()/assert*() dont work in network threads @@ -678,7 +678,7 @@ public class ChannelConnectionTest extends TestWithWallet { .setType(MessageType.INITIATE).build()); if (useRefunds()) { final Protos.TwoWayChannelMessage provideRefund = pair.clientRecorder.checkNextMsg(MessageType.PROVIDE_REFUND); - Transaction refund = new Transaction(PARAMS, provideRefund.getProvideRefund().getTx().toByteArray()); + Transaction refund = new Transaction(UNITTEST, provideRefund.getProvideRefund().getTx().toByteArray()); assertEquals(myValue, refund.getOutput(0).getValue()); } else { assertEquals(2, client.state().getMajorVersion()); @@ -689,7 +689,7 @@ public class ChannelConnectionTest extends TestWithWallet { @Test public void testEmptyWallet() throws Exception { - Wallet emptyWallet = new Wallet(PARAMS); + Wallet emptyWallet = new Wallet(UNITTEST); emptyWallet.freshReceiveKey(); ChannelTestUtils.RecordingPair pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster); PaymentChannelServer server = pair.server; @@ -857,7 +857,7 @@ public class ChannelConnectionTest extends TestWithWallet { Transaction settlement1 = broadcasts.take(); // Server sends back the settle TX it just broadcast. final Protos.TwoWayChannelMessage closeMsg = pair.serverRecorder.checkNextMsg(MessageType.CLOSE); - final Transaction settlement2 = new Transaction(PARAMS, closeMsg.getSettlement().getTx().toByteArray()); + final Transaction settlement2 = new Transaction(UNITTEST, closeMsg.getSettlement().getTx().toByteArray()); assertEquals(settlement1, settlement2); client.receiveMessage(closeMsg); assertNotNull(wallet.getTransaction(settlement2.getHash())); // Close TX entered the wallet. diff --git a/core/src/test/java/org/bitcoinj/protocols/channels/PaymentChannelStateTest.java b/core/src/test/java/org/bitcoinj/protocols/channels/PaymentChannelStateTest.java index 177c5dae..8aede2c2 100644 --- a/core/src/test/java/org/bitcoinj/protocols/channels/PaymentChannelStateTest.java +++ b/core/src/test/java/org/bitcoinj/protocols/channels/PaymentChannelStateTest.java @@ -92,7 +92,7 @@ public class PaymentChannelStateTest extends TestWithWallet { public void setUp() throws Exception { Utils.setMockClock(); // Use mock clock super.setUp(); - Context.propagate(new Context(PARAMS, 100, Coin.ZERO, false)); + Context.propagate(new Context(UNITTEST, 100, Coin.ZERO, false)); wallet.addExtension(new StoredPaymentChannelClientStates(wallet, new TransactionBroadcaster() { @Override public TransactionBroadcast broadcastTransaction(Transaction tx) { @@ -101,8 +101,8 @@ public class PaymentChannelStateTest extends TestWithWallet { } })); sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, COIN); - chain = new BlockChain(PARAMS, wallet, blockStore); // Recreate chain as sendMoneyToWallet will confuse it - serverWallet = new Wallet(PARAMS); + chain = new BlockChain(UNITTEST, wallet, blockStore); // Recreate chain as sendMoneyToWallet will confuse it + serverWallet = new Wallet(UNITTEST); serverKey = serverWallet.freshReceiveKey(); chain.addWallet(serverWallet); @@ -238,7 +238,7 @@ public class PaymentChannelStateTest extends TestWithWallet { // Send the refund tx from client to server and get back the signature. Transaction refund; if (useRefunds()) { - refund = new Transaction(PARAMS, clientV1State().getIncompleteRefundTransaction().bitcoinSerialize()); + refund = new Transaction(UNITTEST, clientV1State().getIncompleteRefundTransaction().bitcoinSerialize()); byte[] refundSig = serverV1State().provideRefundTransaction(refund, myKey.getPubKey()); assertEquals(PaymentChannelServerState.State.WAITING_FOR_MULTISIG_CONTRACT, serverState.getState()); // This verifies that the refund can spend the multi-sig output when run. @@ -251,7 +251,7 @@ public class PaymentChannelStateTest extends TestWithWallet { assertEquals(PaymentChannelClientState.State.PROVIDE_MULTISIG_CONTRACT_TO_SERVER, clientState.getState()); // Validate the multisig contract looks right. - Transaction multisigContract = new Transaction(PARAMS, clientState.getContract().bitcoinSerialize()); + Transaction multisigContract = new Transaction(UNITTEST, clientState.getContract().bitcoinSerialize()); assertEquals(PaymentChannelClientState.State.READY, clientState.getState()); assertEquals(2, multisigContract.getOutputs().size()); // One multi-sig, one change. Script script = multisigContract.getOutput(0).getScriptPubKey(); @@ -309,7 +309,7 @@ public class PaymentChannelStateTest extends TestWithWallet { final TxFuturePair pair2 = broadcasts.take(); Transaction closeTx = pair2.tx; pair2.future.set(closeTx); - final Transaction reserializedCloseTx = new Transaction(PARAMS, closeTx.bitcoinSerialize()); + final Transaction reserializedCloseTx = new Transaction(UNITTEST, closeTx.bitcoinSerialize()); assertEquals(PaymentChannelServerState.State.CLOSED, serverState.getState()); // ... and on the client side. wallet.receivePending(reserializedCloseTx, null); @@ -341,9 +341,9 @@ public class PaymentChannelStateTest extends TestWithWallet { // we can broadcast the refund and get our balance back. // Spend the client wallet's one coin - Transaction spendCoinTx = wallet.sendCoinsOffline(SendRequest.to(Address.fromKey(PARAMS, new ECKey()), COIN)); + Transaction spendCoinTx = wallet.sendCoinsOffline(SendRequest.to(Address.fromKey(UNITTEST, new ECKey()), COIN)); assertEquals(Coin.ZERO, wallet.getBalance()); - chain.add(makeSolvedTestBlock(blockStore.getChainHead().getHeader(), spendCoinTx, createFakeTx(PARAMS, CENT, myAddress))); + chain.add(makeSolvedTestBlock(blockStore.getChainHead().getHeader(), spendCoinTx, createFakeTx(UNITTEST, CENT, myAddress))); assertEquals(CENT, wallet.getBalance()); // Set the wallet's stored states to use our real test PeerGroup @@ -365,7 +365,7 @@ public class PaymentChannelStateTest extends TestWithWallet { if (useRefunds()) { // Send the refund tx from client to server and get back the signature. - Transaction refund = new Transaction(PARAMS, clientV1State().getIncompleteRefundTransaction().bitcoinSerialize()); + Transaction refund = new Transaction(UNITTEST, clientV1State().getIncompleteRefundTransaction().bitcoinSerialize()); byte[] refundSig = serverV1State().provideRefundTransaction(refund, myKey.getPubKey()); assertEquals(PaymentChannelServerState.State.WAITING_FOR_MULTISIG_CONTRACT, serverState.getState()); // This verifies that the refund can spend the multi-sig output when run. @@ -376,7 +376,7 @@ public class PaymentChannelStateTest extends TestWithWallet { assertEquals(PaymentChannelClientState.State.PROVIDE_MULTISIG_CONTRACT_TO_SERVER, clientState.getState()); // Validate the multisig contract looks right. - Transaction multisigContract = new Transaction(PARAMS, clientState.getContract().bitcoinSerialize()); + Transaction multisigContract = new Transaction(UNITTEST, clientState.getContract().bitcoinSerialize()); assertEquals(PaymentChannelClientState.State.READY, clientState.getState()); assertEquals(2, multisigContract.getOutputs().size()); // One multi-sig, one change. Script script = multisigContract.getOutput(0).getScriptPubKey(); @@ -472,23 +472,23 @@ public class PaymentChannelStateTest extends TestWithWallet { if (useRefunds()) { // Test refund transaction with any number of issues byte[] refundTxBytes = clientV1State().getIncompleteRefundTransaction().bitcoinSerialize(); - Transaction refund = new Transaction(PARAMS, refundTxBytes); - refund.addOutput(Coin.ZERO, Address.fromKey(PARAMS, new ECKey())); + Transaction refund = new Transaction(UNITTEST, refundTxBytes); + refund.addOutput(Coin.ZERO, Address.fromKey(UNITTEST, new ECKey())); try { serverV1State().provideRefundTransaction(refund, myKey.getPubKey()); fail(); } catch (VerificationException e) { } - refund = new Transaction(PARAMS, refundTxBytes); - refund.addInput(new TransactionInput(PARAMS, refund, new byte[]{}, new TransactionOutPoint(PARAMS, 42, refund.getHash()))); + refund = new Transaction(UNITTEST, refundTxBytes); + refund.addInput(new TransactionInput(UNITTEST, refund, new byte[]{}, new TransactionOutPoint(UNITTEST, 42, refund.getHash()))); try { serverV1State().provideRefundTransaction(refund, myKey.getPubKey()); fail(); } catch (VerificationException e) { } - refund = new Transaction(PARAMS, refundTxBytes); + refund = new Transaction(UNITTEST, refundTxBytes); refund.setLockTime(0); try { serverV1State().provideRefundTransaction(refund, myKey.getPubKey()); @@ -496,7 +496,7 @@ public class PaymentChannelStateTest extends TestWithWallet { } catch (VerificationException e) { } - refund = new Transaction(PARAMS, refundTxBytes); + refund = new Transaction(UNITTEST, refundTxBytes); refund.getInput(0).setSequenceNumber(TransactionInput.NO_SEQUENCE); try { serverV1State().provideRefundTransaction(refund, myKey.getPubKey()); @@ -504,7 +504,7 @@ public class PaymentChannelStateTest extends TestWithWallet { } catch (VerificationException e) { } - refund = new Transaction(PARAMS, refundTxBytes); + refund = new Transaction(UNITTEST, refundTxBytes); byte[] refundSig = serverV1State().provideRefundTransaction(refund, myKey.getPubKey()); try { serverV1State().provideRefundTransaction(refund, myKey.getPubKey()); @@ -565,7 +565,7 @@ public class PaymentChannelStateTest extends TestWithWallet { byte[] multisigContractSerialized = clientState.getContract().bitcoinSerialize(); - Transaction multisigContract = new Transaction(PARAMS, multisigContractSerialized); + Transaction multisigContract = new Transaction(UNITTEST, multisigContractSerialized); multisigContract.clearOutputs(); // Swap order of client and server keys to check correct failure if (versionSelector == PaymentChannelClient.VersionSelector.VERSION_1) { @@ -582,7 +582,7 @@ public class PaymentChannelStateTest extends TestWithWallet { assertTrue(e.getMessage().contains("client and server in that order")); } - multisigContract = new Transaction(PARAMS, multisigContractSerialized); + multisigContract = new Transaction(UNITTEST, multisigContractSerialized); multisigContract.clearOutputs(); if (versionSelector == PaymentChannelClient.VersionSelector.VERSION_1) { multisigContract.addOutput(Coin.ZERO, ScriptBuilder.createMultiSigOutputScript(2, Lists.newArrayList(myKey, serverKey))); @@ -598,15 +598,15 @@ public class PaymentChannelStateTest extends TestWithWallet { assertTrue(e.getMessage().contains("zero value")); } - multisigContract = new Transaction(PARAMS, multisigContractSerialized); + multisigContract = new Transaction(UNITTEST, multisigContractSerialized); multisigContract.clearOutputs(); - multisigContract.addOutput(new TransactionOutput(PARAMS, multisigContract, HALF_COIN, new byte[] {0x01})); + multisigContract.addOutput(new TransactionOutput(UNITTEST, multisigContract, HALF_COIN, new byte[] {0x01})); try { serverState.provideContract(multisigContract); fail(); } catch (VerificationException e) {} - multisigContract = new Transaction(PARAMS, multisigContractSerialized); + multisigContract = new Transaction(UNITTEST, multisigContractSerialized); ListenableFuture multisigStateFuture = serverState.provideContract(multisigContract); try { serverState.provideContract(multisigContract); fail(); } catch (IllegalStateException e) {} assertEquals(PaymentChannelServerState.State.WAITING_FOR_MULTISIG_ACCEPTANCE, serverState.getState()); @@ -689,16 +689,16 @@ public class PaymentChannelStateTest extends TestWithWallet { @Test public void feesTest() throws Exception { // Test that transactions are getting the necessary fees - Context.propagate(new Context(PARAMS, 100, Coin.ZERO, true)); + Context.propagate(new Context(UNITTEST, 100, Coin.ZERO, true)); // Spend the client wallet's one coin - final SendRequest request = SendRequest.to(Address.fromKey(PARAMS, new ECKey()), COIN); + final SendRequest request = SendRequest.to(Address.fromKey(UNITTEST, new ECKey()), COIN); request.ensureMinRequiredFee = false; wallet.sendCoinsOffline(request); assertEquals(Coin.ZERO, wallet.getBalance()); chain.add(makeSolvedTestBlock(blockStore.getChainHead().getHeader(), - createFakeTx(PARAMS, CENT.add(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE), myAddress))); + createFakeTx(UNITTEST, CENT.add(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE), myAddress))); assertEquals(CENT.add(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE), wallet.getBalance()); Utils.setMockClock(); // Use mock clock @@ -746,7 +746,7 @@ public class PaymentChannelStateTest extends TestWithWallet { if (useRefunds()) { // Send the refund tx from client to server and get back the signature. - Transaction refund = new Transaction(PARAMS, clientV1State().getIncompleteRefundTransaction().bitcoinSerialize()); + Transaction refund = new Transaction(UNITTEST, clientV1State().getIncompleteRefundTransaction().bitcoinSerialize()); byte[] refundSig = serverV1State().provideRefundTransaction(refund, myKey.getPubKey()); assertEquals(PaymentChannelServerState.State.WAITING_FOR_MULTISIG_CONTRACT, serverState.getState()); // This verifies that the refund can spend the multi-sig output when run. @@ -757,7 +757,7 @@ public class PaymentChannelStateTest extends TestWithWallet { assertEquals(PaymentChannelClientState.State.PROVIDE_MULTISIG_CONTRACT_TO_SERVER, clientState.getState()); // Get the multisig contract - Transaction multisigContract = new Transaction(PARAMS, clientState.getContract().bitcoinSerialize()); + Transaction multisigContract = new Transaction(UNITTEST, clientState.getContract().bitcoinSerialize()); assertEquals(PaymentChannelClientState.State.READY, clientState.getState()); // Provide the server with the multisig contract and simulate successful propagation/acceptance. @@ -812,7 +812,7 @@ public class PaymentChannelStateTest extends TestWithWallet { @Test public void serverAddsFeeTest() throws Exception { // Test that the server properly adds the necessary fee at the end (or just drops the payment if its not worth it) - Context.propagate(new Context(PARAMS, 100, Coin.ZERO, true)); + Context.propagate(new Context(UNITTEST, 100, Coin.ZERO, true)); Utils.setMockClock(); // Use mock clock final long EXPIRE_TIME = Utils.currentTimeMillis()/1000 + 60*60*24; @@ -841,7 +841,7 @@ public class PaymentChannelStateTest extends TestWithWallet { if (useRefunds()) { // Send the refund tx from client to server and get back the signature. - Transaction refund = new Transaction(PARAMS, clientV1State().getIncompleteRefundTransaction().bitcoinSerialize()); + Transaction refund = new Transaction(UNITTEST, clientV1State().getIncompleteRefundTransaction().bitcoinSerialize()); byte[] refundSig = serverV1State().provideRefundTransaction(refund, myKey.getPubKey()); assertEquals(PaymentChannelServerState.State.WAITING_FOR_MULTISIG_CONTRACT, serverState.getState()); // This verifies that the refund can spend the multi-sig output when run. @@ -852,7 +852,7 @@ public class PaymentChannelStateTest extends TestWithWallet { assertEquals(PaymentChannelClientState.State.PROVIDE_MULTISIG_CONTRACT_TO_SERVER, clientState.getState()); // Validate the multisig contract looks right. - Transaction multisigContract = new Transaction(PARAMS, clientState.getContract().bitcoinSerialize()); + Transaction multisigContract = new Transaction(UNITTEST, clientState.getContract().bitcoinSerialize()); assertEquals(PaymentChannelV1ClientState.State.READY, clientState.getState()); assertEquals(2, multisigContract.getOutputs().size()); // One multi-sig, one change. Script script = multisigContract.getOutput(0).getScriptPubKey(); @@ -892,7 +892,7 @@ public class PaymentChannelStateTest extends TestWithWallet { } // Now give the server enough coins to pay the fee - sendMoneyToWallet(serverWallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, COIN, Address.fromKey(PARAMS, serverKey)); + sendMoneyToWallet(serverWallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, COIN, Address.fromKey(UNITTEST, serverKey)); // The contract is still not worth redeeming - its worth less than we pay in fee try { @@ -932,7 +932,7 @@ public class PaymentChannelStateTest extends TestWithWallet { Transaction refund; if (useRefunds()) { - refund = new Transaction(PARAMS, clientV1State().getIncompleteRefundTransaction().bitcoinSerialize()); + refund = new Transaction(UNITTEST, clientV1State().getIncompleteRefundTransaction().bitcoinSerialize()); // Send the refund tx from client to server and get back the signature. byte[] refundSig = serverV1State().provideRefundTransaction(refund, myKey.getPubKey()); assertEquals(PaymentChannelV1ServerState.State.WAITING_FOR_MULTISIG_CONTRACT, serverState.getState()); @@ -946,7 +946,7 @@ public class PaymentChannelStateTest extends TestWithWallet { assertEquals(PaymentChannelClientState.State.PROVIDE_MULTISIG_CONTRACT_TO_SERVER, clientState.getState()); // Validate the multisig contract looks right. - Transaction multisigContract = new Transaction(PARAMS, clientState.getContract().bitcoinSerialize()); + Transaction multisigContract = new Transaction(UNITTEST, clientState.getContract().bitcoinSerialize()); assertEquals(PaymentChannelClientState.State.READY, clientState.getState()); assertEquals(2, multisigContract.getOutputs().size()); // One multi-sig, one change. Script script = multisigContract.getOutput(0).getScriptPubKey(); @@ -992,13 +992,13 @@ public class PaymentChannelStateTest extends TestWithWallet { } // Now create a double-spend and send it to the server - Transaction doubleSpendContract = new Transaction(PARAMS); - doubleSpendContract.addInput(new TransactionInput(PARAMS, doubleSpendContract, new byte[0], + Transaction doubleSpendContract = new Transaction(UNITTEST); + doubleSpendContract.addInput(new TransactionInput(UNITTEST, doubleSpendContract, new byte[0], multisigContract.getInput(0).getOutpoint())); doubleSpendContract.addOutput(HALF_COIN, myKey); - doubleSpendContract = new Transaction(PARAMS, doubleSpendContract.bitcoinSerialize()); + doubleSpendContract = new Transaction(UNITTEST, doubleSpendContract.bitcoinSerialize()); - StoredBlock block = new StoredBlock(PARAMS.getGenesisBlock().createNextBlock(Address.fromKey(PARAMS, myKey)), BigInteger.TEN, 1); + StoredBlock block = new StoredBlock(UNITTEST.getGenesisBlock().createNextBlock(Address.fromKey(UNITTEST, myKey)), BigInteger.TEN, 1); 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 diff --git a/core/src/test/java/org/bitcoinj/protocols/payments/PaymentProtocolTest.java b/core/src/test/java/org/bitcoinj/protocols/payments/PaymentProtocolTest.java index c83741c3..7b8f305f 100644 --- a/core/src/test/java/org/bitcoinj/protocols/payments/PaymentProtocolTest.java +++ b/core/src/test/java/org/bitcoinj/protocols/payments/PaymentProtocolTest.java @@ -41,11 +41,12 @@ import java.util.List; import static org.junit.Assert.*; public class PaymentProtocolTest { + private static final NetworkParameters UNITTEST = UnitTestParams.get(); + private static final NetworkParameters TESTNET = TestNet3Params.get(); // static test data - private static final NetworkParameters PARAMS = UnitTestParams.get(); private static final Coin AMOUNT = Coin.SATOSHI; - private static final Address TO_ADDRESS = Address.fromKey(PARAMS, new ECKey()); + private static final Address TO_ADDRESS = Address.fromKey(UNITTEST, new ECKey()); private static final String MEMO = "memo"; private static final String PAYMENT_URL = "https://example.com"; private static final byte[] MERCHANT_DATA = { 0, 1, 2 }; @@ -102,7 +103,7 @@ public class PaymentProtocolTest { @Test public void testPaymentRequest() throws Exception { // Create - PaymentRequest paymentRequest = PaymentProtocol.createPaymentRequest(TestNet3Params.get(), AMOUNT, TO_ADDRESS, MEMO, + PaymentRequest paymentRequest = PaymentProtocol.createPaymentRequest(TESTNET, AMOUNT, TO_ADDRESS, MEMO, PAYMENT_URL, MERCHANT_DATA).build(); byte[] paymentRequestBytes = paymentRequest.toByteArray(); @@ -122,16 +123,16 @@ public class PaymentProtocolTest { public void testPaymentMessage() throws Exception { // Create List transactions = new LinkedList<>(); - transactions.add(FakeTxBuilder.createFakeTx(PARAMS, AMOUNT, TO_ADDRESS)); + transactions.add(FakeTxBuilder.createFakeTx(UNITTEST, AMOUNT, TO_ADDRESS)); Coin refundAmount = Coin.SATOSHI; - Address refundAddress = Address.fromKey(PARAMS, new ECKey()); + Address refundAddress = Address.fromKey(UNITTEST, new ECKey()); Payment payment = PaymentProtocol.createPaymentMessage(transactions, refundAmount, refundAddress, MEMO, MERCHANT_DATA); byte[] paymentBytes = payment.toByteArray(); // Parse Payment parsedPayment = Payment.parseFrom(paymentBytes); - List parsedTransactions = PaymentProtocol.parseTransactionsFromPaymentMessage(PARAMS, + List parsedTransactions = PaymentProtocol.parseTransactionsFromPaymentMessage(UNITTEST, parsedPayment); assertEquals(transactions, parsedTransactions); assertEquals(1, parsedPayment.getRefundToCount()); diff --git a/core/src/test/java/org/bitcoinj/protocols/payments/PaymentSessionTest.java b/core/src/test/java/org/bitcoinj/protocols/payments/PaymentSessionTest.java index 37e15198..d6353fe5 100644 --- a/core/src/test/java/org/bitcoinj/protocols/payments/PaymentSessionTest.java +++ b/core/src/test/java/org/bitcoinj/protocols/payments/PaymentSessionTest.java @@ -36,7 +36,9 @@ import static org.bitcoinj.core.Coin.COIN; import static org.junit.Assert.*; public class PaymentSessionTest { - private static final NetworkParameters PARAMS = TestNet3Params.get(); + private static final NetworkParameters TESTNET = TestNet3Params.get(); + private static final NetworkParameters MAINNET = MainNetParams.get(); + private static final String simplePaymentUrl = "http://a.simple.url.com/"; private static final String paymentRequestMemo = "send coinz noa plz kthx"; private static final String paymentMemo = "take ze coinz"; @@ -50,8 +52,8 @@ public class PaymentSessionTest { @Before public void setUp() throws Exception { serverKey = new ECKey(); - tx = new Transaction(PARAMS); - outputToMe = new TransactionOutput(PARAMS, tx, coin, serverKey); + tx = new Transaction(TESTNET); + outputToMe = new TransactionOutput(TESTNET, tx, coin, serverKey); tx.addOutput(outputToMe); } @@ -68,10 +70,10 @@ public class PaymentSessionTest { // Send the payment and verify that the correct information is sent. // Add a dummy input to tx so it is considered valid. - tx.addInput(new TransactionInput(PARAMS, tx, outputToMe.getScriptBytes())); + tx.addInput(new TransactionInput(TESTNET, tx, outputToMe.getScriptBytes())); ArrayList txns = new ArrayList<>(); txns.add(tx); - Address refundAddr = Address.fromKey(PARAMS, serverKey); + Address refundAddr = Address.fromKey(TESTNET, serverKey); paymentSession.sendPayment(txns, refundAddr, paymentMemo); assertEquals(1, paymentSession.getPaymentLog().size()); assertEquals(simplePaymentUrl, paymentSession.getPaymentLog().get(0).getUrl().toString()); @@ -80,7 +82,7 @@ public class PaymentSessionTest { assertEquals(merchantData, payment.getMerchantData()); assertEquals(1, payment.getRefundToCount()); assertEquals(coin.value, payment.getRefundTo(0).getAmount()); - TransactionOutput refundOutput = new TransactionOutput(PARAMS, null, coin, refundAddr); + TransactionOutput refundOutput = new TransactionOutput(TESTNET, null, coin, refundAddr); ByteString refundScript = ByteString.copyFrom(refundOutput.getScriptBytes()); assertTrue(refundScript.equals(payment.getRefundTo(0).getScript())); } @@ -108,7 +110,7 @@ public class PaymentSessionTest { assertTrue(paymentSession.isExpired()); // Send the payment and verify that an exception is thrown. // Add a dummy input to tx so it is considered valid. - tx.addInput(new TransactionInput(PARAMS, tx, outputToMe.getScriptBytes())); + tx.addInput(new TransactionInput(TESTNET, tx, outputToMe.getScriptBytes())); ArrayList txns = new ArrayList<>(); txns.add(tx); try { @@ -135,14 +137,14 @@ public class PaymentSessionTest { public void testWrongNetwork() throws Exception { // Create a PaymentRequest and make sure the correct values are parsed by the PaymentSession. MockPaymentSession paymentSession = new MockPaymentSession(newSimplePaymentRequest("main")); - assertEquals(MainNetParams.get(), paymentSession.getNetworkParameters()); + assertEquals(MAINNET, paymentSession.getNetworkParameters()); // Send the payment and verify that the correct information is sent. // Add a dummy input to tx so it is considered valid. - tx.addInput(new TransactionInput(PARAMS, tx, outputToMe.getScriptBytes())); + tx.addInput(new TransactionInput(TESTNET, tx, outputToMe.getScriptBytes())); ArrayList txns = new ArrayList<>(); txns.add(tx); - Address refundAddr = Address.fromKey(PARAMS, serverKey); + Address refundAddr = Address.fromKey(TESTNET, serverKey); paymentSession.sendPayment(txns, refundAddr, paymentMemo); assertEquals(1, paymentSession.getPaymentLog().size()); } diff --git a/core/src/test/java/org/bitcoinj/script/ScriptPatternTest.java b/core/src/test/java/org/bitcoinj/script/ScriptPatternTest.java index 591ef64c..cd2ee463 100644 --- a/core/src/test/java/org/bitcoinj/script/ScriptPatternTest.java +++ b/core/src/test/java/org/bitcoinj/script/ScriptPatternTest.java @@ -21,6 +21,7 @@ import com.google.common.collect.Lists; import org.bitcoinj.core.Address; import org.bitcoinj.core.ECKey; +import org.bitcoinj.core.NetworkParameters; import org.bitcoinj.params.MainNetParams; import org.junit.Test; @@ -31,11 +32,12 @@ import static org.junit.Assert.assertTrue; public class ScriptPatternTest { private List keys = Lists.newArrayList(new ECKey(), new ECKey(), new ECKey()); + private static final NetworkParameters MAINNET = MainNetParams.get(); @Test public void testCommonScripts() { assertTrue(ScriptPattern.isPayToPubKeyHash( - ScriptBuilder.createOutputScript(Address.fromKey(MainNetParams.get(), keys.get(0))) + ScriptBuilder.createOutputScript(Address.fromKey(MAINNET, keys.get(0))) )); assertTrue(ScriptPattern.isPayToScriptHash( ScriptBuilder.createP2SHOutputScript(2, keys) diff --git a/core/src/test/java/org/bitcoinj/script/ScriptTest.java b/core/src/test/java/org/bitcoinj/script/ScriptTest.java index 24012449..de91834c 100644 --- a/core/src/test/java/org/bitcoinj/script/ScriptTest.java +++ b/core/src/test/java/org/bitcoinj/script/ScriptTest.java @@ -55,13 +55,14 @@ public class ScriptTest { static final String pubkeyProg = "76a91433e81a941e64cda12c6a299ed322ddbdd03f8d0e88ac"; - private static final NetworkParameters PARAMS = TestNet3Params.get(); + private static final NetworkParameters TESTNET = TestNet3Params.get(); + private static final NetworkParameters MAINNET = MainNetParams.get(); private static final Logger log = LoggerFactory.getLogger(ScriptTest.class); @Before public void setUp() throws Exception { - Context context = new Context(PARAMS); + Context context = new Context(TESTNET); } @Test @@ -79,7 +80,7 @@ public class ScriptTest { byte[] pubkeyBytes = HEX.decode(pubkeyProg); Script pubkey = new Script(pubkeyBytes); assertEquals("DUP HASH160 PUSHDATA(20)[33e81a941e64cda12c6a299ed322ddbdd03f8d0e] EQUALVERIFY CHECKSIG", pubkey.toString()); - Address toAddr = Address.fromPubKeyHash(PARAMS, ScriptPattern.extractHashFromPayToPubKeyHash(pubkey)); + Address toAddr = Address.fromPubKeyHash(TESTNET, ScriptPattern.extractHashFromPayToPubKeyHash(pubkey)); assertEquals("mkFQohBpy2HDXrCwyMrYL5RtfrmeiuuPY2", toAddr.toString()); } @@ -111,7 +112,7 @@ public class ScriptTest { @Test public void testP2SHOutputScript() throws Exception { - Address p2shAddress = Address.fromBase58(MainNetParams.get(), "35b9vsyH1KoFT5a5KtrKusaCcPLkiSo1tU"); + Address p2shAddress = Address.fromBase58(MAINNET, "35b9vsyH1KoFT5a5KtrKusaCcPLkiSo1tU"); assertTrue(ScriptPattern.isPayToScriptHash(ScriptBuilder.createOutputScript(p2shAddress))); } @@ -125,15 +126,15 @@ public class ScriptTest { @Test public void testCreateMultiSigInputScript() { // Setup transaction and signatures - ECKey key1 = DumpedPrivateKey.fromBase58(PARAMS, "cVLwRLTvz3BxDAWkvS3yzT9pUcTCup7kQnfT2smRjvmmm1wAP6QT").getKey(); - ECKey key2 = DumpedPrivateKey.fromBase58(PARAMS, "cTine92s8GLpVqvebi8rYce3FrUYq78ZGQffBYCS1HmDPJdSTxUo").getKey(); - ECKey key3 = DumpedPrivateKey.fromBase58(PARAMS, "cVHwXSPRZmL9adctwBwmn4oTZdZMbaCsR5XF6VznqMgcvt1FDDxg").getKey(); + ECKey key1 = DumpedPrivateKey.fromBase58(TESTNET, "cVLwRLTvz3BxDAWkvS3yzT9pUcTCup7kQnfT2smRjvmmm1wAP6QT").getKey(); + ECKey key2 = DumpedPrivateKey.fromBase58(TESTNET, "cTine92s8GLpVqvebi8rYce3FrUYq78ZGQffBYCS1HmDPJdSTxUo").getKey(); + ECKey key3 = DumpedPrivateKey.fromBase58(TESTNET, "cVHwXSPRZmL9adctwBwmn4oTZdZMbaCsR5XF6VznqMgcvt1FDDxg").getKey(); Script multisigScript = ScriptBuilder.createMultiSigOutputScript(2, Arrays.asList(key1, key2, key3)); byte[] bytes = HEX.decode("01000000013df681ff83b43b6585fa32dd0e12b0b502e6481e04ee52ff0fdaf55a16a4ef61000000006b483045022100a84acca7906c13c5895a1314c165d33621cdcf8696145080895cbf301119b7cf0220730ff511106aa0e0a8570ff00ee57d7a6f24e30f592a10cae1deffac9e13b990012102b8d567bcd6328fd48a429f9cf4b315b859a58fd28c5088ef3cb1d98125fc4e8dffffffff02364f1c00000000001976a91439a02793b418de8ec748dd75382656453dc99bcb88ac40420f000000000017a9145780b80be32e117f675d6e0ada13ba799bf248e98700000000"); - Transaction transaction = PARAMS.getDefaultSerializer().makeTransaction(bytes); + Transaction transaction = TESTNET.getDefaultSerializer().makeTransaction(bytes); TransactionOutput output = transaction.getOutput(1); - Transaction spendTx = new Transaction(PARAMS); - Address address = Address.fromBase58(PARAMS, "n3CFiCmBXVt5d3HXKQ15EFZyhPz4yj5F3H"); + Transaction spendTx = new Transaction(TESTNET); + Address address = Address.fromBase58(TESTNET, "n3CFiCmBXVt5d3HXKQ15EFZyhPz4yj5F3H"); Script outputScript = ScriptBuilder.createOutputScript(address); spendTx.addOutput(output.getValue(), outputScript); spendTx.addInput(output); @@ -223,8 +224,8 @@ public class ScriptTest { @Test public void testOp0() { // Check that OP_0 doesn't NPE and pushes an empty stack frame. - Transaction tx = new Transaction(PARAMS); - tx.addInput(new TransactionInput(PARAMS, tx, new byte[] {})); + Transaction tx = new Transaction(TESTNET); + tx.addInput(new TransactionInput(TESTNET, tx, new byte[] {})); Script script = new ScriptBuilder().smallNum(0).build(); LinkedList stack = new LinkedList<>(); @@ -317,37 +318,37 @@ public class ScriptTest { int index = input.get(1).asInt(); String script = input.get(2).asText(); Sha256Hash sha256Hash = Sha256Hash.wrap(HEX.decode(hash)); - scriptPubKeys.put(new TransactionOutPoint(PARAMS, index, sha256Hash), parseScriptString(script)); + scriptPubKeys.put(new TransactionOutPoint(TESTNET, index, sha256Hash), parseScriptString(script)); } return scriptPubKeys; } private Transaction buildCreditingTransaction(Script scriptPubKey) { - Transaction tx = new Transaction(PARAMS); + Transaction tx = new Transaction(TESTNET); tx.setVersion(1); tx.setLockTime(0); - TransactionInput txInput = new TransactionInput(PARAMS, null, + TransactionInput txInput = new TransactionInput(TESTNET, null, new ScriptBuilder().number(0).number(0).build().getProgram()); txInput.setSequenceNumber(TransactionInput.NO_SEQUENCE); tx.addInput(txInput); - TransactionOutput txOutput = new TransactionOutput(PARAMS, tx, Coin.ZERO, scriptPubKey.getProgram()); + TransactionOutput txOutput = new TransactionOutput(TESTNET, tx, Coin.ZERO, scriptPubKey.getProgram()); tx.addOutput(txOutput); return tx; } private Transaction buildSpendingTransaction(Transaction creditingTransaction, Script scriptSig) { - Transaction tx = new Transaction(PARAMS); + Transaction tx = new Transaction(TESTNET); tx.setVersion(1); tx.setLockTime(0); - TransactionInput txInput = new TransactionInput(PARAMS, creditingTransaction, scriptSig.getProgram()); + TransactionInput txInput = new TransactionInput(TESTNET, creditingTransaction, scriptSig.getProgram()); txInput.setSequenceNumber(TransactionInput.NO_SEQUENCE); tx.addInput(txInput); - TransactionOutput txOutput = new TransactionOutput(PARAMS, tx, creditingTransaction.getOutput(0).getValue(), + TransactionOutput txOutput = new TransactionOutput(TESTNET, tx, creditingTransaction.getOutput(0).getValue(), new Script(new byte[] {}).getProgram()); tx.addOutput(txOutput); @@ -364,7 +365,7 @@ public class ScriptTest { Transaction transaction = null; try { Map scriptPubKeys = parseScriptPubKeys(test.get(0)); - transaction = PARAMS.getDefaultSerializer().makeTransaction(HEX.decode(test.get(1).asText().toLowerCase())); + transaction = TESTNET.getDefaultSerializer().makeTransaction(HEX.decode(test.get(1).asText().toLowerCase())); transaction.verify(); Set verifyFlags = parseVerifyFlags(test.get(2).asText()); @@ -393,7 +394,7 @@ public class ScriptTest { if (test.isArray() && test.size() == 1 && test.get(0).isTextual()) continue; // This is a comment. Map scriptPubKeys = parseScriptPubKeys(test.get(0)); - Transaction transaction = PARAMS.getDefaultSerializer().makeTransaction(HEX.decode(test.get(1).asText().toLowerCase())); + Transaction transaction = TESTNET.getDefaultSerializer().makeTransaction(HEX.decode(test.get(1).asText().toLowerCase())); Set verifyFlags = parseVerifyFlags(test.get(2).asText()); boolean valid = true; @@ -438,18 +439,18 @@ public class ScriptTest { public void getToAddress() throws Exception { // pay to pubkey ECKey toKey = new ECKey(); - Address toAddress = Address.fromKey(PARAMS, toKey); - assertEquals(toAddress, ScriptBuilder.createOutputScript(toKey).getToAddress(PARAMS, true)); + Address toAddress = Address.fromKey(TESTNET, toKey); + assertEquals(toAddress, ScriptBuilder.createOutputScript(toKey).getToAddress(TESTNET, true)); // pay to pubkey hash - assertEquals(toAddress, ScriptBuilder.createOutputScript(toAddress).getToAddress(PARAMS, true)); + assertEquals(toAddress, ScriptBuilder.createOutputScript(toAddress).getToAddress(TESTNET, true)); // pay to script hash Script p2shScript = ScriptBuilder.createP2SHOutputScript(new byte[20]); - Address scriptAddress = Address.fromP2SHScript(PARAMS, p2shScript); - assertEquals(scriptAddress, p2shScript.getToAddress(PARAMS, true)); + Address scriptAddress = Address.fromP2SHScript(TESTNET, p2shScript); + assertEquals(scriptAddress, p2shScript.getToAddress(TESTNET, true)); } @Test(expected = ScriptException.class) public void getToAddressNoPubKey() throws Exception { - ScriptBuilder.createOutputScript(new ECKey()).getToAddress(PARAMS, false); + ScriptBuilder.createOutputScript(new ECKey()).getToAddress(TESTNET, false); } } diff --git a/core/src/test/java/org/bitcoinj/store/LevelDBBlockStoreTest.java b/core/src/test/java/org/bitcoinj/store/LevelDBBlockStoreTest.java index 77374738..322c81da 100644 --- a/core/src/test/java/org/bitcoinj/store/LevelDBBlockStoreTest.java +++ b/core/src/test/java/org/bitcoinj/store/LevelDBBlockStoreTest.java @@ -25,23 +25,24 @@ import java.io.*; import static org.junit.Assert.assertEquals; public class LevelDBBlockStoreTest { + private static final NetworkParameters UNITTEST = UnitTestParams.get(); + @Test public void basics() throws Exception { File f = File.createTempFile("leveldbblockstore", null); f.delete(); - NetworkParameters params = UnitTestParams.get(); - Context context = new Context(params); + Context context = new Context(UNITTEST); LevelDBBlockStore store = new LevelDBBlockStore(context, f); store.reset(); // Check the first block in a new store is the genesis block. StoredBlock genesis = store.getChainHead(); - assertEquals(params.getGenesisBlock(), genesis.getHeader()); + assertEquals(UNITTEST.getGenesisBlock(), genesis.getHeader()); assertEquals(0, genesis.getHeight()); // Build a new block. - Address to = Address.fromBase58(params, "mrj2K6txjo2QBcSmuAzHj4nD1oXSEJE1Qo"); + Address to = Address.fromBase58(UNITTEST, "mrj2K6txjo2QBcSmuAzHj4nD1oXSEJE1Qo"); StoredBlock b1 = genesis.build(genesis.getHeader().createNextBlock(to).cloneAsHeader()); store.put(b1); store.setChainHead(b1); diff --git a/core/src/test/java/org/bitcoinj/store/SPVBlockStoreTest.java b/core/src/test/java/org/bitcoinj/store/SPVBlockStoreTest.java index ded79a9c..bdd7daae 100644 --- a/core/src/test/java/org/bitcoinj/store/SPVBlockStoreTest.java +++ b/core/src/test/java/org/bitcoinj/store/SPVBlockStoreTest.java @@ -28,20 +28,19 @@ import java.io.File; import static org.junit.Assert.assertEquals; public class SPVBlockStoreTest { - - private static final NetworkParameters PARAMS = UnitTestParams.get(); + private static final NetworkParameters UNITTEST = UnitTestParams.get(); @Test public void basics() throws Exception { File f = File.createTempFile("spvblockstore", null); f.delete(); f.deleteOnExit(); - SPVBlockStore store = new SPVBlockStore(PARAMS, f); + SPVBlockStore store = new SPVBlockStore(UNITTEST, f); - Address to = Address.fromKey(PARAMS, new ECKey()); + Address to = Address.fromKey(UNITTEST, new ECKey()); // Check the first block in a new store is the genesis block. StoredBlock genesis = store.getChainHead(); - assertEquals(PARAMS.getGenesisBlock(), genesis.getHeader()); + assertEquals(UNITTEST.getGenesisBlock(), genesis.getHeader()); assertEquals(0, genesis.getHeight()); @@ -52,7 +51,7 @@ public class SPVBlockStoreTest { store.close(); // Check we can get it back out again if we rebuild the store object. - store = new SPVBlockStore(PARAMS, f); + store = new SPVBlockStore(UNITTEST, f); StoredBlock b2 = store.get(b1.getHeader().getHash()); assertEquals(b1, b2); // Check the chain head was stored correctly also. diff --git a/core/src/test/java/org/bitcoinj/store/WalletProtobufSerializerTest.java b/core/src/test/java/org/bitcoinj/store/WalletProtobufSerializerTest.java index 1bd65608..f8641a4a 100644 --- a/core/src/test/java/org/bitcoinj/store/WalletProtobufSerializerTest.java +++ b/core/src/test/java/org/bitcoinj/store/WalletProtobufSerializerTest.java @@ -60,7 +60,9 @@ import static org.junit.Assert.*; import static com.google.common.base.Preconditions.checkNotNull; public class WalletProtobufSerializerTest { - private static final NetworkParameters PARAMS = UnitTestParams.get(); + private static final NetworkParameters UNITTEST = UnitTestParams.get(); + private static final NetworkParameters MAINNET = MainNetParams.get(); + private ECKey myKey; private ECKey myWatchedKey; private Address myAddress; @@ -72,17 +74,17 @@ public class WalletProtobufSerializerTest { @Before public void setUp() throws Exception { BriefLogFormatter.initVerbose(); - Context ctx = new Context(PARAMS); + Context ctx = new Context(UNITTEST); myWatchedKey = new ECKey(); - myWallet = new Wallet(PARAMS); + myWallet = new Wallet(UNITTEST); myKey = new ECKey(); myKey.setCreationTimeSeconds(123456789L); myWallet.importKey(myKey); - myAddress = Address.fromKey(PARAMS, myKey); - myWallet = new Wallet(PARAMS); + myAddress = Address.fromKey(UNITTEST, myKey); + myWallet = new Wallet(UNITTEST); myWallet.importKey(myKey); mScriptCreationTime = new Date().getTime() / 1000 - 1234; - myWallet.addWatchedAddress(Address.fromKey(PARAMS, myWatchedKey), mScriptCreationTime); + myWallet.addWatchedAddress(Address.fromKey(UNITTEST, myWatchedKey), mScriptCreationTime); myWallet.setDescription(WALLET_DESCRIPTION); } @@ -101,7 +103,7 @@ public class WalletProtobufSerializerTest { assertEquals(mScriptCreationTime, wallet1.getWatchedScripts().get(0).getCreationTimeSeconds()); assertEquals(1, wallet1.getWatchedScripts().size()); - assertEquals(ScriptBuilder.createOutputScript(Address.fromKey(PARAMS, myWatchedKey)), + assertEquals(ScriptBuilder.createOutputScript(Address.fromKey(UNITTEST, myWatchedKey)), wallet1.getWatchedScripts().get(0)); assertEquals(WALLET_DESCRIPTION, wallet1.getDescription()); } @@ -110,9 +112,9 @@ public class WalletProtobufSerializerTest { public void oneTx() throws Exception { // Check basic tx serialization. Coin v1 = COIN; - Transaction t1 = createFakeTx(PARAMS, v1, myAddress); - t1.getConfidence().markBroadcastBy(new PeerAddress(PARAMS, InetAddress.getByName("1.2.3.4"))); - t1.getConfidence().markBroadcastBy(new PeerAddress(PARAMS, InetAddress.getByName("5.6.7.8"))); + Transaction t1 = createFakeTx(UNITTEST, v1, myAddress); + t1.getConfidence().markBroadcastBy(new PeerAddress(UNITTEST, InetAddress.getByName("1.2.3.4"))); + t1.getConfidence().markBroadcastBy(new PeerAddress(UNITTEST, InetAddress.getByName("5.6.7.8"))); t1.getConfidence().setSource(TransactionConfidence.Source.NETWORK); myWallet.receivePending(t1, null); Wallet wallet1 = roundTrip(myWallet); @@ -146,7 +148,7 @@ public class WalletProtobufSerializerTest { public void raiseFeeTx() throws Exception { // Check basic tx serialization. Coin v1 = COIN; - Transaction t1 = createFakeTx(PARAMS, v1, myAddress); + Transaction t1 = createFakeTx(UNITTEST, v1, myAddress); t1.setPurpose(Purpose.RAISE_FEE); myWallet.receivePending(t1, null); Wallet wallet1 = roundTrip(myWallet); @@ -157,7 +159,7 @@ public class WalletProtobufSerializerTest { @Test public void doubleSpend() throws Exception { // Check that we can serialize double spends correctly, as this is a slightly tricky case. - FakeTxBuilder.DoubleSpends doubleSpends = FakeTxBuilder.createFakeDoubleSpendTxns(PARAMS, myAddress); + FakeTxBuilder.DoubleSpends doubleSpends = FakeTxBuilder.createFakeDoubleSpendTxns(UNITTEST, myAddress); // t1 spends to our wallet. myWallet.receivePending(doubleSpends.t1, null); // t2 rolls back t1 and spends somewhere else. @@ -176,8 +178,8 @@ public class WalletProtobufSerializerTest { public void testKeys() throws Exception { for (int i = 0 ; i < 20 ; i++) { myKey = new ECKey(); - myAddress = Address.fromKey(PARAMS, myKey); - myWallet = new Wallet(PARAMS); + myAddress = Address.fromKey(UNITTEST, myKey); + myWallet = new Wallet(UNITTEST); myWallet.importKey(myKey); Wallet wallet1 = roundTrip(myWallet); assertArrayEquals(myKey.getPubKey(), wallet1.findKeyFromPubHash(myKey.getPubKeyHash()).getPubKey()); @@ -190,13 +192,13 @@ public class WalletProtobufSerializerTest { // Test the lastBlockSeenHash field works. // LastBlockSeenHash should be empty if never set. - Wallet wallet = new Wallet(PARAMS); + Wallet wallet = new Wallet(UNITTEST); Protos.Wallet walletProto = new WalletProtobufSerializer().walletToProto(wallet); ByteString lastSeenBlockHash = walletProto.getLastSeenBlockHash(); assertTrue(lastSeenBlockHash.isEmpty()); // Create a block. - Block block = PARAMS.getDefaultSerializer().makeBlock(BlockTest.blockBytes); + Block block = UNITTEST.getDefaultSerializer().makeBlock(BlockTest.blockBytes); Sha256Hash blockHash = block.getHash(); wallet.setLastBlockSeenHash(blockHash); wallet.setLastBlockSeenHeight(1); @@ -207,7 +209,7 @@ public class WalletProtobufSerializerTest { assertEquals(1, wallet1.getLastBlockSeenHeight()); // Test the Satoshi genesis block (hash of all zeroes) is roundtripped ok. - Block genesisBlock = MainNetParams.get().getGenesisBlock(); + Block genesisBlock = MAINNET.getGenesisBlock(); wallet.setLastBlockSeenHash(genesisBlock.getHash()); Wallet wallet2 = roundTrip(wallet); assertEquals(genesisBlock.getHash(), wallet2.getLastBlockSeenHash()); @@ -215,11 +217,11 @@ public class WalletProtobufSerializerTest { @Test public void testSequenceNumber() throws Exception { - Wallet wallet = new Wallet(PARAMS); - Transaction tx1 = createFakeTx(PARAMS, Coin.COIN, wallet.currentReceiveAddress()); + Wallet wallet = new Wallet(UNITTEST); + Transaction tx1 = createFakeTx(UNITTEST, Coin.COIN, wallet.currentReceiveAddress()); tx1.getInput(0).setSequenceNumber(TransactionInput.NO_SEQUENCE); wallet.receivePending(tx1, null); - Transaction tx2 = createFakeTx(PARAMS, Coin.COIN, wallet.currentReceiveAddress()); + Transaction tx2 = createFakeTx(UNITTEST, Coin.COIN, wallet.currentReceiveAddress()); tx2.getInput(0).setSequenceNumber(TransactionInput.NO_SEQUENCE - 1); wallet.receivePending(tx2, null); Wallet walletCopy = roundTrip(wallet); @@ -233,7 +235,7 @@ public class WalletProtobufSerializerTest { public void testAppearedAtChainHeightDepthAndWorkDone() throws Exception { // Test the TransactionConfidence appearedAtChainHeight, depth and workDone field are stored. - BlockChain chain = new BlockChain(PARAMS, myWallet, new MemoryBlockStore(PARAMS)); + BlockChain chain = new BlockChain(UNITTEST, myWallet, new MemoryBlockStore(UNITTEST)); final ArrayList txns = new ArrayList<>(2); myWallet.addCoinsReceivedEventListener(new WalletCoinsReceivedEventListener() { @@ -244,7 +246,7 @@ public class WalletProtobufSerializerTest { }); // Start by building two blocks on top of the genesis block. - Block b1 = PARAMS.getGenesisBlock().createNextBlock(myAddress); + Block b1 = UNITTEST.getGenesisBlock().createNextBlock(myAddress); BigInteger work1 = b1.getWork(); assertTrue(work1.signum() > 0); @@ -327,10 +329,10 @@ public class WalletProtobufSerializerTest { public void testRoundTripWatchingWallet() throws Exception { final String xpub = "tpubD9LrDvFDrB6wYNhbR2XcRRaT4yCa37TjBR3YthBQvrtEwEq6CKeEXUs3TppQd38rfxmxD1qLkC99iP3vKcKwLESSSYdFAftbrpuhSnsw6XM"; final long creationTimeSeconds = 1457019819; - Wallet wallet = Wallet.fromWatchingKeyB58(PARAMS, xpub, creationTimeSeconds); + Wallet wallet = Wallet.fromWatchingKeyB58(UNITTEST, xpub, creationTimeSeconds); Wallet wallet2 = roundTrip(wallet); Wallet wallet3 = roundTrip(wallet2); - assertEquals(xpub, wallet.getWatchingKey().serializePubB58(PARAMS)); + assertEquals(xpub, wallet.getWatchingKey().serializePubB58(UNITTEST)); assertEquals(creationTimeSeconds, wallet.getWatchingKey().getCreationTimeSeconds()); assertEquals(creationTimeSeconds, wallet2.getWatchingKey().getCreationTimeSeconds()); assertEquals(creationTimeSeconds, wallet3.getWatchingKey().getCreationTimeSeconds()); @@ -342,9 +344,9 @@ public class WalletProtobufSerializerTest { @Test public void testRoundTripMarriedWallet() throws Exception { // create 2-of-2 married wallet - myWallet = new Wallet(PARAMS); + myWallet = new Wallet(UNITTEST); final DeterministicKeyChain partnerChain = new DeterministicKeyChain(new SecureRandom()); - DeterministicKey partnerKey = DeterministicKey.deserializeB58(null, partnerChain.getWatchingKey().serializePubB58(PARAMS), PARAMS); + DeterministicKey partnerKey = DeterministicKey.deserializeB58(null, partnerChain.getWatchingKey().serializePubB58(UNITTEST), UNITTEST); MarriedKeyChain chain = MarriedKeyChain.builder() .random(new SecureRandom()) .followingKeys(partnerKey) @@ -362,7 +364,7 @@ public class WalletProtobufSerializerTest { @Test public void roundtripVersionTwoTransaction() throws Exception { - Transaction tx = new Transaction(PARAMS, Utils.HEX.decode( + Transaction tx = new Transaction(UNITTEST, Utils.HEX.decode( "0200000001d7902864af9310420c6e606b814c8f89f7902d40c130594e85df2e757a7cc301070000006b483045022100ca1757afa1af85c2bb014382d9ce411e1628d2b3d478df9d5d3e9e93cb25dcdd02206c5d272b31a23baf64e82793ee5c816e2bbef251e733a638b630ff2331fc83ba0121026ac2316508287761befbd0f7495ea794b396dbc5b556bf276639f56c0bd08911feffffff0274730700000000001976a91456da2d038a098c42390c77ef163e1cc23aedf24088ac91062300000000001976a9148ebf3467b9a8d7ae7b290da719e61142793392c188ac22e00600")); assertEquals(tx.getVersion(), 2); assertEquals(tx.getHashAsString(), "0321b1413ed9048199815bd6bc2650cab1a9e8d543f109a42c769b1f18df4174"); @@ -375,10 +377,10 @@ public class WalletProtobufSerializerTest { @Test public void coinbaseTxns() throws Exception { // Covers issue 420 where the outpoint index of a coinbase tx input was being mis-serialized. - Block b = PARAMS.getGenesisBlock().createNextBlockWithCoinbase(Block.BLOCK_VERSION_GENESIS, myKey.getPubKey(), FIFTY_COINS, Block.BLOCK_HEIGHT_GENESIS); + Block b = UNITTEST.getGenesisBlock().createNextBlockWithCoinbase(Block.BLOCK_VERSION_GENESIS, myKey.getPubKey(), FIFTY_COINS, Block.BLOCK_HEIGHT_GENESIS); Transaction coinbase = b.getTransactions().get(0); assertTrue(coinbase.isCoinBase()); - BlockChain chain = new BlockChain(PARAMS, myWallet, new MemoryBlockStore(PARAMS)); + BlockChain chain = new BlockChain(UNITTEST, myWallet, new MemoryBlockStore(UNITTEST)); assertTrue(chain.add(b)); // Wallet now has a coinbase tx in it. assertEquals(1, myWallet.getTransactions(true).size()); @@ -402,21 +404,21 @@ public class WalletProtobufSerializerTest { Protos.Wallet proto = new WalletProtobufSerializer().walletToProto(myWallet); // Initial extension is mandatory: try to read it back into a wallet that doesn't know about it. try { - new WalletProtobufSerializer().readWallet(PARAMS, null, proto); + new WalletProtobufSerializer().readWallet(UNITTEST, null, proto); fail(); } catch (UnreadableWalletException e) { assertTrue(e.getMessage().contains("mandatory")); } - Wallet wallet = new WalletProtobufSerializer().readWallet(PARAMS, + Wallet wallet = new WalletProtobufSerializer().readWallet(UNITTEST, new WalletExtension[]{ new FooWalletExtension("com.whatever.required", true) }, proto); assertTrue(wallet.getExtensions().containsKey("com.whatever.required")); // Non-mandatory extensions are ignored if the wallet doesn't know how to read them. - Wallet wallet2 = new Wallet(PARAMS); + Wallet wallet2 = new Wallet(UNITTEST); wallet2.addExtension(new FooWalletExtension("com.whatever.optional", false)); Protos.Wallet proto2 = new WalletProtobufSerializer().walletToProto(wallet2); - Wallet wallet5 = new WalletProtobufSerializer().readWallet(PARAMS, null, proto2); + Wallet wallet5 = new WalletProtobufSerializer().readWallet(UNITTEST, null, proto2); assertEquals(0, wallet5.getExtensions().size()); } @@ -445,7 +447,7 @@ public class WalletProtobufSerializerTest { }; myWallet.addExtension(extension); Protos.Wallet proto = new WalletProtobufSerializer().walletToProto(myWallet); - Wallet wallet = new WalletProtobufSerializer().readWallet(PARAMS, new WalletExtension[]{extension}, proto); + Wallet wallet = new WalletProtobufSerializer().readWallet(UNITTEST, new WalletExtension[]{extension}, proto); assertEquals(0, wallet.getExtensions().size()); } @@ -453,6 +455,6 @@ public class WalletProtobufSerializerTest { public void versions() throws Exception { Protos.Wallet.Builder proto = Protos.Wallet.newBuilder(new WalletProtobufSerializer().walletToProto(myWallet)); proto.setVersion(2); - new WalletProtobufSerializer().readWallet(PARAMS, null, proto.build()); + new WalletProtobufSerializer().readWallet(UNITTEST, null, proto.build()); } } diff --git a/core/src/test/java/org/bitcoinj/testing/TestWithNetworkConnections.java b/core/src/test/java/org/bitcoinj/testing/TestWithNetworkConnections.java index a2518442..480fa273 100644 --- a/core/src/test/java/org/bitcoinj/testing/TestWithNetworkConnections.java +++ b/core/src/test/java/org/bitcoinj/testing/TestWithNetworkConnections.java @@ -48,7 +48,7 @@ import static com.google.common.base.Preconditions.checkState; */ public class TestWithNetworkConnections { public static final int PEER_SERVERS = 5; - protected static final NetworkParameters PARAMS = UnitTestParams.get(); + protected static final NetworkParameters UNITTEST = UnitTestParams.get(); protected Context context; protected BlockStore blockStore; protected BlockChain blockChain; @@ -79,20 +79,20 @@ public class TestWithNetworkConnections { } public void setUp() throws Exception { - setUp(new MemoryBlockStore(UnitTestParams.get())); + setUp(new MemoryBlockStore(UNITTEST)); } public void setUp(BlockStore blockStore) throws Exception { BriefLogFormatter.init(); - Context.propagate(new Context(PARAMS, 100, Coin.ZERO, false)); + Context.propagate(new Context(UNITTEST, 100, Coin.ZERO, false)); this.blockStore = blockStore; // Allow subclasses to override the wallet object with their own. if (wallet == null) { - wallet = new Wallet(PARAMS); + wallet = new Wallet(UNITTEST); key = wallet.freshReceiveKey(); - address = Address.fromKey(PARAMS, key); + address = Address.fromKey(UNITTEST, key); } - blockChain = new BlockChain(PARAMS, wallet, blockStore); + blockChain = new BlockChain(UNITTEST, wallet, blockStore); startPeerServers(); if (clientType == ClientType.NIO_CLIENT_MANAGER || clientType == ClientType.BLOCKING_CLIENT_MANAGER) { @@ -114,7 +114,7 @@ public class TestWithNetworkConnections { @Nullable @Override public StreamConnection getNewConnection(InetAddress inetAddress, int port) { - return new InboundMessageQueuer(PARAMS) { + return new InboundMessageQueuer(UNITTEST) { @Override public void connectionClosed() { } diff --git a/core/src/test/java/org/bitcoinj/testing/TestWithPeerGroup.java b/core/src/test/java/org/bitcoinj/testing/TestWithPeerGroup.java index f36e82e4..d8a1d14c 100644 --- a/core/src/test/java/org/bitcoinj/testing/TestWithPeerGroup.java +++ b/core/src/test/java/org/bitcoinj/testing/TestWithPeerGroup.java @@ -48,14 +48,14 @@ public class TestWithPeerGroup extends TestWithNetworkConnections { @Override public void setUp() throws Exception { - setUp(new MemoryBlockStore(PARAMS)); + setUp(new MemoryBlockStore(UNITTEST)); } @Override public void setUp(BlockStore blockStore) throws Exception { super.setUp(blockStore); - remoteVersionMessage = new VersionMessage(PARAMS, 1); + remoteVersionMessage = new VersionMessage(UNITTEST, 1); remoteVersionMessage.localServices = VersionMessage.NODE_NETWORK; remoteVersionMessage.clientVersion = NotFoundMessage.MIN_PROTOCOL_VERSION; blockJobs = false; @@ -89,7 +89,7 @@ public class TestWithPeerGroup extends TestWithNetworkConnections { protected final Semaphore jobBlocks = new Semaphore(0); private PeerGroup createPeerGroup(final ClientConnectionManager manager) { - return new PeerGroup(PARAMS, blockChain, manager) { + return new PeerGroup(UNITTEST, blockChain, manager) { @Override protected ListeningScheduledExecutorService createPrivateExecutor() { return MoreExecutors.listeningDecorator(new ScheduledThreadPoolExecutor(1, new ContextPropagatingThreadFactory("PeerGroup test thread")) { diff --git a/core/src/test/java/org/bitcoinj/testing/TestWithWallet.java b/core/src/test/java/org/bitcoinj/testing/TestWithWallet.java index 82f8f291..c78bf256 100644 --- a/core/src/test/java/org/bitcoinj/testing/TestWithWallet.java +++ b/core/src/test/java/org/bitcoinj/testing/TestWithWallet.java @@ -17,6 +17,7 @@ package org.bitcoinj.testing; import org.bitcoinj.core.*; +import org.bitcoinj.params.MainNetParams; import org.bitcoinj.params.UnitTestParams; import org.bitcoinj.store.BlockStore; import org.bitcoinj.store.MemoryBlockStore; @@ -37,7 +38,9 @@ import static org.bitcoinj.testing.FakeTxBuilder.createFakeTx; * fee per kilobyte to zero in setUp. */ public class TestWithWallet { - protected static final NetworkParameters PARAMS = UnitTestParams.get(); + protected static final NetworkParameters UNITTEST = UnitTestParams.get(); + protected static final NetworkParameters MAINNET = MainNetParams.get(); + protected ECKey myKey; protected Address myAddress; protected Wallet wallet; @@ -46,12 +49,12 @@ public class TestWithWallet { public void setUp() throws Exception { BriefLogFormatter.init(); - Context.propagate(new Context(PARAMS, 100, Coin.ZERO, false)); - wallet = new Wallet(PARAMS); + Context.propagate(new Context(UNITTEST, 100, Coin.ZERO, false)); + wallet = new Wallet(UNITTEST); myKey = wallet.currentReceiveKey(); - myAddress = Address.fromKey(PARAMS, myKey); - blockStore = new MemoryBlockStore(PARAMS); - chain = new BlockChain(PARAMS, wallet, blockStore); + myAddress = Address.fromKey(UNITTEST, myKey); + blockStore = new MemoryBlockStore(UNITTEST); + chain = new BlockChain(UNITTEST, wallet, blockStore); } public void tearDown() throws Exception { @@ -80,12 +83,12 @@ public class TestWithWallet { @Nullable protected Transaction sendMoneyToWallet(Wallet wallet, AbstractBlockChain.NewBlockType type, Coin value, Address toAddress) throws VerificationException { - return sendMoneyToWallet(wallet, type, createFakeTx(PARAMS, value, toAddress)); + return sendMoneyToWallet(wallet, type, createFakeTx(UNITTEST, value, toAddress)); } @Nullable protected Transaction sendMoneyToWallet(Wallet wallet, AbstractBlockChain.NewBlockType type, Coin value, ECKey toPubKey) throws VerificationException { - return sendMoneyToWallet(wallet, type, createFakeTx(PARAMS, value, toPubKey)); + return sendMoneyToWallet(wallet, type, createFakeTx(UNITTEST, value, toPubKey)); } @Nullable diff --git a/core/src/test/java/org/bitcoinj/uri/BitcoinURITest.java b/core/src/test/java/org/bitcoinj/uri/BitcoinURITest.java index bd1e31d8..57604f3e 100644 --- a/core/src/test/java/org/bitcoinj/uri/BitcoinURITest.java +++ b/core/src/test/java/org/bitcoinj/uri/BitcoinURITest.java @@ -30,6 +30,7 @@ public class BitcoinURITest { private BitcoinURI testObject = null; private static final NetworkParameters MAINNET = MainNetParams.get(); + private static final NetworkParameters TESTNET = TestNet3Params.get(); private static final String MAINNET_GOOD_ADDRESS = "1KzTSfqjF2iKCduwz59nv2uqh1W2JsTxZH"; private static final String BITCOIN_SCHEME = MAINNET.getUriScheme(); @@ -149,7 +150,7 @@ public class BitcoinURITest { @Test public void testBad_IncorrectAddressType() { try { - testObject = new BitcoinURI(TestNet3Params.get(), BITCOIN_SCHEME + ":" + MAINNET_GOOD_ADDRESS); + testObject = new BitcoinURI(TESTNET, BITCOIN_SCHEME + ":" + MAINNET_GOOD_ADDRESS); fail("Expecting BitcoinURIParseException"); } catch (BitcoinURIParseException e) { assertTrue(e.getMessage().contains("Bad address")); @@ -378,7 +379,7 @@ public class BitcoinURITest { @Test public void testPaymentProtocolReq() throws Exception { // Non-backwards compatible form ... - BitcoinURI uri = new BitcoinURI(TestNet3Params.get(), "bitcoin:?r=https%3A%2F%2Fbitcoincore.org%2F%7Egavin%2Ff.php%3Fh%3Db0f02e7cea67f168e25ec9b9f9d584f9"); + BitcoinURI uri = new BitcoinURI(TESTNET, "bitcoin:?r=https%3A%2F%2Fbitcoincore.org%2F%7Egavin%2Ff.php%3Fh%3Db0f02e7cea67f168e25ec9b9f9d584f9"); assertEquals("https://bitcoincore.org/~gavin/f.php?h=b0f02e7cea67f168e25ec9b9f9d584f9", uri.getPaymentRequestUrl()); assertEquals(ImmutableList.of("https://bitcoincore.org/~gavin/f.php?h=b0f02e7cea67f168e25ec9b9f9d584f9"), uri.getPaymentRequestUrls()); @@ -403,7 +404,7 @@ public class BitcoinURITest { @Test public void testUnescapedPaymentProtocolReq() throws Exception { - BitcoinURI uri = new BitcoinURI(TestNet3Params.get(), + BitcoinURI uri = new BitcoinURI(TESTNET, "bitcoin:?r=https://merchant.com/pay.php?h%3D2a8628fc2fbe"); assertEquals("https://merchant.com/pay.php?h=2a8628fc2fbe", uri.getPaymentRequestUrl()); assertEquals(ImmutableList.of("https://merchant.com/pay.php?h=2a8628fc2fbe"), uri.getPaymentRequestUrls()); diff --git a/core/src/test/java/org/bitcoinj/utils/VersionTallyTest.java b/core/src/test/java/org/bitcoinj/utils/VersionTallyTest.java index 45202210..c6e328eb 100644 --- a/core/src/test/java/org/bitcoinj/utils/VersionTallyTest.java +++ b/core/src/test/java/org/bitcoinj/utils/VersionTallyTest.java @@ -30,7 +30,7 @@ import static org.junit.Assert.*; import org.junit.Before; public class VersionTallyTest { - private static final NetworkParameters PARAMS = UnitTestParams.get(); + private static final NetworkParameters UNITTEST = UnitTestParams.get(); public VersionTallyTest() { } @@ -38,7 +38,7 @@ public class VersionTallyTest { @Before public void setUp() throws Exception { BriefLogFormatter.initVerbose(); - Context context = new Context(PARAMS); + Context context = new Context(UNITTEST); } /** @@ -46,12 +46,12 @@ public class VersionTallyTest { */ @Test public void testNullWhileEmpty() { - VersionTally instance = new VersionTally(PARAMS); - for (int i = 0; i < PARAMS.getMajorityWindow(); i++) { + VersionTally instance = new VersionTally(UNITTEST); + for (int i = 0; i < UNITTEST.getMajorityWindow(); i++) { assertNull(instance.getCountAtOrAbove(1)); instance.add(1); } - assertEquals(PARAMS.getMajorityWindow(), instance.getCountAtOrAbove(1).intValue()); + assertEquals(UNITTEST.getMajorityWindow(), instance.getCountAtOrAbove(1).intValue()); } /** @@ -59,8 +59,8 @@ public class VersionTallyTest { */ @Test public void testSize() { - VersionTally instance = new VersionTally(PARAMS); - assertEquals(PARAMS.getMajorityWindow(), instance.size()); + VersionTally instance = new VersionTally(UNITTEST); + assertEquals(UNITTEST.getMajorityWindow(), instance.size()); } /** @@ -68,46 +68,46 @@ public class VersionTallyTest { */ @Test public void testVersionCounts() { - VersionTally instance = new VersionTally(PARAMS); + VersionTally instance = new VersionTally(UNITTEST); // Fill the tally with 1s - for (int i = 0; i < PARAMS.getMajorityWindow(); i++) { + for (int i = 0; i < UNITTEST.getMajorityWindow(); i++) { assertNull(instance.getCountAtOrAbove(1)); instance.add(1); } - assertEquals(PARAMS.getMajorityWindow(), instance.getCountAtOrAbove(1).intValue()); + assertEquals(UNITTEST.getMajorityWindow(), instance.getCountAtOrAbove(1).intValue()); // Check the count updates as we replace with 2s - for (int i = 0; i < PARAMS.getMajorityWindow(); i++) { + for (int i = 0; i < UNITTEST.getMajorityWindow(); i++) { assertEquals(i, instance.getCountAtOrAbove(2).intValue()); instance.add(2); } // Inject a rogue 1 instance.add(1); - assertEquals(PARAMS.getMajorityWindow() - 1, instance.getCountAtOrAbove(2).intValue()); + assertEquals(UNITTEST.getMajorityWindow() - 1, instance.getCountAtOrAbove(2).intValue()); // Check we accept high values as well instance.add(10); - assertEquals(PARAMS.getMajorityWindow() - 1, instance.getCountAtOrAbove(2).intValue()); + assertEquals(UNITTEST.getMajorityWindow() - 1, instance.getCountAtOrAbove(2).intValue()); } @Test public void testInitialize() throws BlockStoreException { - final BlockStore blockStore = new MemoryBlockStore(PARAMS); - final BlockChain chain = new BlockChain(PARAMS, blockStore); + final BlockStore blockStore = new MemoryBlockStore(UNITTEST); + final BlockChain chain = new BlockChain(UNITTEST, blockStore); // Build a historical chain of version 2 blocks long timeSeconds = 1231006505; StoredBlock chainHead = null; - for (int height = 0; height < PARAMS.getMajorityWindow(); height++) { + for (int height = 0; height < UNITTEST.getMajorityWindow(); height++) { chainHead = FakeTxBuilder.createFakeBlock(blockStore, 2, timeSeconds, height).storedBlock; assertEquals(2, chainHead.getHeader().getVersion()); timeSeconds += 60; } - VersionTally instance = new VersionTally(PARAMS); + VersionTally instance = new VersionTally(UNITTEST); instance.initialize(blockStore, chainHead); - assertEquals(PARAMS.getMajorityWindow(), instance.getCountAtOrAbove(2).intValue()); + assertEquals(UNITTEST.getMajorityWindow(), instance.getCountAtOrAbove(2).intValue()); } } diff --git a/core/src/test/java/org/bitcoinj/wallet/DefaultCoinSelectorTest.java b/core/src/test/java/org/bitcoinj/wallet/DefaultCoinSelectorTest.java index afaa0598..a3718829 100644 --- a/core/src/test/java/org/bitcoinj/wallet/DefaultCoinSelectorTest.java +++ b/core/src/test/java/org/bitcoinj/wallet/DefaultCoinSelectorTest.java @@ -29,7 +29,8 @@ import static org.bitcoinj.core.Coin.*; import static org.junit.Assert.*; public class DefaultCoinSelectorTest extends TestWithWallet { - private static final NetworkParameters PARAMS = UnitTestParams.get(); + private static final NetworkParameters UNITTEST = UnitTestParams.get(); + private static final NetworkParameters REGTEST = RegTestParams.get(); @Before @Override @@ -47,19 +48,19 @@ public class DefaultCoinSelectorTest extends TestWithWallet { @Test public void selectable() throws Exception { Transaction t; - t = new Transaction(PARAMS); + t = new Transaction(UNITTEST); t.getConfidence().setConfidenceType(TransactionConfidence.ConfidenceType.PENDING); assertFalse(DefaultCoinSelector.isSelectable(t)); t.getConfidence().setSource(TransactionConfidence.Source.SELF); assertFalse(DefaultCoinSelector.isSelectable(t)); - t.getConfidence().markBroadcastBy(new PeerAddress(PARAMS, InetAddress.getByName("1.2.3.4"))); + t.getConfidence().markBroadcastBy(new PeerAddress(UNITTEST, InetAddress.getByName("1.2.3.4"))); assertFalse(DefaultCoinSelector.isSelectable(t)); - t.getConfidence().markBroadcastBy(new PeerAddress(PARAMS, InetAddress.getByName("5.6.7.8"))); + t.getConfidence().markBroadcastBy(new PeerAddress(UNITTEST, InetAddress.getByName("5.6.7.8"))); assertTrue(DefaultCoinSelector.isSelectable(t)); - t = new Transaction(PARAMS); + t = new Transaction(UNITTEST); t.getConfidence().setConfidenceType(TransactionConfidence.ConfidenceType.BUILDING); assertTrue(DefaultCoinSelector.isSelectable(t)); - t = new Transaction(RegTestParams.get()); + t = new Transaction(REGTEST); t.getConfidence().setConfidenceType(TransactionConfidence.ConfidenceType.PENDING); t.getConfidence().setSource(TransactionConfidence.Source.SELF); assertTrue(DefaultCoinSelector.isSelectable(t)); @@ -111,12 +112,12 @@ public class DefaultCoinSelectorTest extends TestWithWallet { @Test public void identicalInputs() throws Exception { // Add four outputs to a transaction with same value and destination. Select them all. - Transaction t = new Transaction(PARAMS); + Transaction t = new Transaction(UNITTEST); java.util.List outputs = Arrays.asList( - new TransactionOutput(PARAMS, t, Coin.valueOf(30302787), myAddress), - new TransactionOutput(PARAMS, t, Coin.valueOf(30302787), myAddress), - new TransactionOutput(PARAMS, t, Coin.valueOf(30302787), myAddress), - new TransactionOutput(PARAMS, t, Coin.valueOf(30302787), myAddress) + new TransactionOutput(UNITTEST, t, Coin.valueOf(30302787), myAddress), + new TransactionOutput(UNITTEST, t, Coin.valueOf(30302787), myAddress), + new TransactionOutput(UNITTEST, t, Coin.valueOf(30302787), myAddress), + new TransactionOutput(UNITTEST, t, Coin.valueOf(30302787), myAddress) ); t.getConfidence().setConfidenceType(TransactionConfidence.ConfidenceType.BUILDING); diff --git a/core/src/test/java/org/bitcoinj/wallet/DefaultRiskAnalysisTest.java b/core/src/test/java/org/bitcoinj/wallet/DefaultRiskAnalysisTest.java index e490ece4..6c2ff22d 100644 --- a/core/src/test/java/org/bitcoinj/wallet/DefaultRiskAnalysisTest.java +++ b/core/src/test/java/org/bitcoinj/wallet/DefaultRiskAnalysisTest.java @@ -35,7 +35,7 @@ import static org.junit.Assert.*; public class DefaultRiskAnalysisTest { // Uses mainnet because isStandard checks are disabled on testnet. - private static final NetworkParameters PARAMS = MainNetParams.get(); + private static final NetworkParameters MAINNET = MainNetParams.get(); private Wallet wallet; private final int TIMESTAMP = 1384190189; private static final ECKey key1 = new ECKey(); @@ -43,7 +43,7 @@ public class DefaultRiskAnalysisTest { @Before public void setup() { - wallet = new Wallet(new Context(PARAMS)) { + wallet = new Wallet(new Context(MAINNET)) { @Override public int getLastBlockSeenHeight() { return 1000; @@ -58,7 +58,7 @@ public class DefaultRiskAnalysisTest { @Test(expected = IllegalStateException.class) public void analysisCantBeUsedTwice() { - Transaction tx = new Transaction(PARAMS); + Transaction tx = new Transaction(MAINNET); DefaultRiskAnalysis analysis = DefaultRiskAnalysis.FACTORY.create(wallet, tx, NO_DEPS); assertEquals(RiskAnalysis.Result.OK, analysis.analyze()); assertNull(analysis.getNonFinal()); @@ -69,8 +69,8 @@ public class DefaultRiskAnalysisTest { @Test public void nonFinal() throws Exception { // Verify that just having a lock time in the future is not enough to be considered risky (it's still final). - Transaction tx = new Transaction(PARAMS); - TransactionInput input = tx.addInput(PARAMS.getGenesisBlock().getTransactions().get(0).getOutput(0)); + Transaction tx = new Transaction(MAINNET); + TransactionInput input = tx.addInput(MAINNET.getGenesisBlock().getTransactions().get(0).getOutput(0)); tx.addOutput(COIN, key1); tx.setLockTime(TIMESTAMP + 86400); DefaultRiskAnalysis analysis = DefaultRiskAnalysis.FACTORY.create(wallet, tx, NO_DEPS); @@ -91,8 +91,8 @@ public class DefaultRiskAnalysisTest { @Test public void selfCreatedAreNotRisky() { - Transaction tx = new Transaction(PARAMS); - tx.addInput(PARAMS.getGenesisBlock().getTransactions().get(0).getOutput(0)).setSequenceNumber(1); + Transaction tx = new Transaction(MAINNET); + tx.addInput(MAINNET.getGenesisBlock().getTransactions().get(0).getOutput(0)).setSequenceNumber(1); tx.addOutput(COIN, key1); tx.setLockTime(TIMESTAMP + 86400); @@ -112,11 +112,11 @@ public class DefaultRiskAnalysisTest { @Test public void nonFinalDependency() { // Final tx has a dependency that is non-final. - Transaction tx1 = new Transaction(PARAMS); - tx1.addInput(PARAMS.getGenesisBlock().getTransactions().get(0).getOutput(0)).setSequenceNumber(1); + Transaction tx1 = new Transaction(MAINNET); + tx1.addInput(MAINNET.getGenesisBlock().getTransactions().get(0).getOutput(0)).setSequenceNumber(1); TransactionOutput output = tx1.addOutput(COIN, key1); tx1.setLockTime(TIMESTAMP + 86400); - Transaction tx2 = new Transaction(PARAMS); + Transaction tx2 = new Transaction(MAINNET); tx2.addInput(output); tx2.addOutput(COIN, new ECKey()); @@ -127,18 +127,18 @@ public class DefaultRiskAnalysisTest { @Test public void nonStandardDust() { - Transaction standardTx = new Transaction(PARAMS); - standardTx.addInput(PARAMS.getGenesisBlock().getTransactions().get(0).getOutput(0)); + Transaction standardTx = new Transaction(MAINNET); + standardTx.addInput(MAINNET.getGenesisBlock().getTransactions().get(0).getOutput(0)); standardTx.addOutput(COIN, key1); assertEquals(RiskAnalysis.Result.OK, DefaultRiskAnalysis.FACTORY.create(wallet, standardTx, NO_DEPS).analyze()); - Transaction dustTx = new Transaction(PARAMS); - dustTx.addInput(PARAMS.getGenesisBlock().getTransactions().get(0).getOutput(0)); + Transaction dustTx = new Transaction(MAINNET); + dustTx.addInput(MAINNET.getGenesisBlock().getTransactions().get(0).getOutput(0)); dustTx.addOutput(Coin.SATOSHI, key1); // 1 Satoshi assertEquals(RiskAnalysis.Result.NON_STANDARD, DefaultRiskAnalysis.FACTORY.create(wallet, dustTx, NO_DEPS).analyze()); - Transaction edgeCaseTx = new Transaction(PARAMS); - edgeCaseTx.addInput(PARAMS.getGenesisBlock().getTransactions().get(0).getOutput(0)); + Transaction edgeCaseTx = new Transaction(MAINNET); + edgeCaseTx.addInput(MAINNET.getGenesisBlock().getTransactions().get(0).getOutput(0)); edgeCaseTx.addOutput(DefaultRiskAnalysis.MIN_ANALYSIS_NONDUST_OUTPUT, key1); // Dust threshold assertEquals(RiskAnalysis.Result.OK, DefaultRiskAnalysis.FACTORY.create(wallet, edgeCaseTx, NO_DEPS).analyze()); } @@ -148,14 +148,14 @@ public class DefaultRiskAnalysisTest { ScriptChunk nonStandardChunk = new ScriptChunk(OP_PUSHDATA1, new byte[75]); byte[] nonStandardScript = new ScriptBuilder().addChunk(nonStandardChunk).build().getProgram(); // Test non-standard script as an input. - Transaction tx = new Transaction(PARAMS); + Transaction tx = new Transaction(MAINNET); assertEquals(DefaultRiskAnalysis.RuleViolation.NONE, DefaultRiskAnalysis.isStandard(tx)); - tx.addInput(new TransactionInput(PARAMS, null, nonStandardScript)); + tx.addInput(new TransactionInput(MAINNET, null, nonStandardScript)); assertEquals(DefaultRiskAnalysis.RuleViolation.SHORTEST_POSSIBLE_PUSHDATA, DefaultRiskAnalysis.isStandard(tx)); // Test non-standard script as an output. tx.clearInputs(); assertEquals(DefaultRiskAnalysis.RuleViolation.NONE, DefaultRiskAnalysis.isStandard(tx)); - tx.addOutput(new TransactionOutput(PARAMS, null, COIN, nonStandardScript)); + tx.addOutput(new TransactionOutput(MAINNET, null, COIN, nonStandardScript)); assertEquals(DefaultRiskAnalysis.RuleViolation.SHORTEST_POSSIBLE_PUSHDATA, DefaultRiskAnalysis.isStandard(tx)); } @@ -164,14 +164,14 @@ public class DefaultRiskAnalysisTest { TransactionSignature sig = TransactionSignature.dummy(); Script scriptOk = ScriptBuilder.createInputScript(sig); assertEquals(RuleViolation.NONE, - DefaultRiskAnalysis.isInputStandard(new TransactionInput(PARAMS, null, scriptOk.getProgram()))); + DefaultRiskAnalysis.isInputStandard(new TransactionInput(MAINNET, null, scriptOk.getProgram()))); byte[] sigBytes = sig.encodeToBitcoin(); // Appending a zero byte makes the signature uncanonical without violating DER encoding. Script scriptUncanonicalEncoding = new ScriptBuilder().data(Arrays.copyOf(sigBytes, sigBytes.length + 1)) .build(); assertEquals(RuleViolation.SIGNATURE_CANONICAL_ENCODING, - DefaultRiskAnalysis.isInputStandard(new TransactionInput(PARAMS, null, scriptUncanonicalEncoding + DefaultRiskAnalysis.isInputStandard(new TransactionInput(MAINNET, null, scriptUncanonicalEncoding .getProgram()))); } @@ -182,10 +182,10 @@ public class DefaultRiskAnalysisTest { Script scriptHighS = ScriptBuilder .createInputScript(new TransactionSignature(sig.r, ECKey.CURVE.getN().subtract(sig.s))); assertEquals(RuleViolation.SIGNATURE_CANONICAL_ENCODING, - DefaultRiskAnalysis.isInputStandard(new TransactionInput(PARAMS, null, scriptHighS.getProgram()))); + DefaultRiskAnalysis.isInputStandard(new TransactionInput(MAINNET, null, scriptHighS.getProgram()))); // This is a real transaction. Its signatures S component is "low". - Transaction tx1 = new Transaction(PARAMS, Utils.HEX.decode( + Transaction tx1 = new Transaction(MAINNET, Utils.HEX.decode( "010000000200a2be4376b7f47250ad9ad3a83b6aa5eb6a6d139a1f50771704d77aeb8ce76c010000006a4730440220055723d363cd2d4fe4e887270ebdf5c4b99eaf233a5c09f9404f888ec8b839350220763c3794d310b384ce86decfb05787e5bfa5d31983db612a2dde5ffec7f396ae012102ef47e27e0c4bdd6dc83915f185d972d5eb8515c34d17bad584a9312e59f4e0bcffffffff52239451d37757eeacb86d32864ec1ee6b6e131d1e3fee6f1cff512703b71014030000006b483045022100ea266ac4f893d98a623a6fc0e6a961cd5a3f32696721e87e7570a68851917e75022056d75c3b767419f6f6cb8189a0ad78d45971523908dc4892f7594b75fd43a8d00121038bb455ca101ebbb0ecf7f5c01fa1dcb7d14fbf6b7d7ea52ee56f0148e72a736cffffffff0630b15a00000000001976a9146ae477b690cf85f21c2c01e2c8639a5c18dc884e88ac4f260d00000000001976a91498d08c02ab92a671590adb726dddb719695ee12e88ac65753b00000000001976a9140b2eb4ba6d364c82092f25775f56bc10cd92c8f188ac65753b00000000001976a914d1cb414e22081c6ba3a935635c0f1d837d3c5d9188ac65753b00000000001976a914df9d137a0d279471a2796291874c29759071340b88ac3d753b00000000001976a91459f5aa4815e3aa8e1720e8b82f4ac8e6e904e47d88ac00000000")); assertEquals("2a1c8569b2b01ebac647fb94444d1118d4d00e327456a3c518e40d47d72cd5fe", tx1.getHashAsString()); @@ -193,7 +193,7 @@ public class DefaultRiskAnalysisTest { // This tx is the same as the above, except for a "high" S component on the signature of input 1. // It was part of the Oct 2015 malleability attack. - Transaction tx2 = new Transaction(PARAMS, Utils.HEX.decode( + Transaction tx2 = new Transaction(MAINNET, Utils.HEX.decode( "010000000200a2be4376b7f47250ad9ad3a83b6aa5eb6a6d139a1f50771704d77aeb8ce76c010000006a4730440220055723d363cd2d4fe4e887270ebdf5c4b99eaf233a5c09f9404f888ec8b839350220763c3794d310b384ce86decfb05787e5bfa5d31983db612a2dde5ffec7f396ae012102ef47e27e0c4bdd6dc83915f185d972d5eb8515c34d17bad584a9312e59f4e0bcffffffff52239451d37757eeacb86d32864ec1ee6b6e131d1e3fee6f1cff512703b71014030000006c493046022100ea266ac4f893d98a623a6fc0e6a961cd5a3f32696721e87e7570a68851917e75022100a928a3c4898be60909347e765f52872a613d8aada66c57a8c8791316d2f298710121038bb455ca101ebbb0ecf7f5c01fa1dcb7d14fbf6b7d7ea52ee56f0148e72a736cffffffff0630b15a00000000001976a9146ae477b690cf85f21c2c01e2c8639a5c18dc884e88ac4f260d00000000001976a91498d08c02ab92a671590adb726dddb719695ee12e88ac65753b00000000001976a9140b2eb4ba6d364c82092f25775f56bc10cd92c8f188ac65753b00000000001976a914d1cb414e22081c6ba3a935635c0f1d837d3c5d9188ac65753b00000000001976a914df9d137a0d279471a2796291874c29759071340b88ac3d753b00000000001976a91459f5aa4815e3aa8e1720e8b82f4ac8e6e904e47d88ac00000000")); assertEquals("dbe4147cf89b89fd9fa6c8ce6a3e2adecb234db094ec88301ae09073ca17d61d", tx2.getHashAsString()); assertFalse(ECKey.ECDSASignature @@ -205,10 +205,10 @@ public class DefaultRiskAnalysisTest { @Test public void standardOutputs() throws Exception { - Transaction tx = new Transaction(PARAMS); - tx.addInput(PARAMS.getGenesisBlock().getTransactions().get(0).getOutput(0)); + Transaction tx = new Transaction(MAINNET); + tx.addInput(MAINNET.getGenesisBlock().getTransactions().get(0).getOutput(0)); // A pay to address output - tx.addOutput(Coin.CENT, ScriptBuilder.createOutputScript(Address.fromKey(PARAMS, key1))); + tx.addOutput(Coin.CENT, ScriptBuilder.createOutputScript(Address.fromKey(MAINNET, key1))); // A pay to pubkey output tx.addOutput(Coin.CENT, ScriptBuilder.createOutputScript(key1)); tx.addOutput(Coin.CENT, ScriptBuilder.createOutputScript(key1)); @@ -226,7 +226,7 @@ public class DefaultRiskAnalysisTest { @Test public void optInFullRBF() throws Exception { - Transaction tx = FakeTxBuilder.createFakeTx(PARAMS); + Transaction tx = FakeTxBuilder.createFakeTx(MAINNET); tx.getInput(0).setSequenceNumber(TransactionInput.NO_SEQUENCE - 2); DefaultRiskAnalysis analysis = DefaultRiskAnalysis.FACTORY.create(wallet, tx, NO_DEPS); assertEquals(RiskAnalysis.Result.NON_FINAL, analysis.analyze()); @@ -235,7 +235,7 @@ public class DefaultRiskAnalysisTest { @Test public void relativeLockTime() throws Exception { - Transaction tx = FakeTxBuilder.createFakeTx(PARAMS); + Transaction tx = FakeTxBuilder.createFakeTx(MAINNET); tx.setVersion(2); checkState(!tx.hasRelativeLockTime()); @@ -251,7 +251,7 @@ public class DefaultRiskAnalysisTest { @Test public void transactionVersions() throws Exception { - Transaction tx = FakeTxBuilder.createFakeTx(PARAMS); + Transaction tx = FakeTxBuilder.createFakeTx(MAINNET); tx.setVersion(1); DefaultRiskAnalysis analysis = DefaultRiskAnalysis.FACTORY.create(wallet, tx, NO_DEPS); assertEquals(RiskAnalysis.Result.OK, analysis.analyze()); diff --git a/core/src/test/java/org/bitcoinj/wallet/DeterministicKeyChainTest.java b/core/src/test/java/org/bitcoinj/wallet/DeterministicKeyChainTest.java index adfd83a9..a76e3328 100644 --- a/core/src/test/java/org/bitcoinj/wallet/DeterministicKeyChainTest.java +++ b/core/src/test/java/org/bitcoinj/wallet/DeterministicKeyChainTest.java @@ -46,7 +46,8 @@ public class DeterministicKeyChainTest { private DeterministicKeyChain chain; private DeterministicKeyChain bip44chain; 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(); + private static final NetworkParameters UNITTEST = UnitTestParams.get(); + private static final NetworkParameters MAINNET = MainNetParams.get(); @Before public void setup() { @@ -71,9 +72,9 @@ public class DeterministicKeyChainTest { ECKey key2 = chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS); assertFalse(key2.isPubKeyOnly()); - final Address address = Address.fromBase58(PARAMS, "n1bQNoEx8uhmCzzA5JPG6sFdtsUQhwiQJV"); - assertEquals(address, Address.fromKey(PARAMS, key1)); - assertEquals("mnHUcqUVvrfi5kAaXJDQzBb9HsWs78b42R", Address.fromKey(PARAMS, key2).toString()); + final Address address = Address.fromBase58(UNITTEST, "n1bQNoEx8uhmCzzA5JPG6sFdtsUQhwiQJV"); + assertEquals(address, Address.fromKey(UNITTEST, key1)); + assertEquals("mnHUcqUVvrfi5kAaXJDQzBb9HsWs78b42R", Address.fromKey(UNITTEST, key2).toString()); assertEquals(key1, chain.findKeyFromPubHash(address.getHash160())); assertEquals(key2, chain.findKeyFromPubKey(key2.getPubKey())); @@ -82,7 +83,7 @@ public class DeterministicKeyChainTest { ECKey key3 = chain.getKey(KeyChain.KeyPurpose.CHANGE); assertFalse(key3.isPubKeyOnly()); - assertEquals("mqumHgVDqNzuXNrszBmi7A2UpmwaPMx4HQ", Address.fromKey(PARAMS, key3).toString()); + assertEquals("mqumHgVDqNzuXNrszBmi7A2UpmwaPMx4HQ", Address.fromKey(UNITTEST, key3).toString()); key3.sign(Sha256Hash.ZERO_HASH); assertFalse(key3.isPubKeyOnly()); } @@ -102,16 +103,16 @@ public class DeterministicKeyChainTest { ECKey key1 = chain1.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS); ECKey key2 = chain1.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS); - final Address address = Address.fromBase58(PARAMS, "n2nHHRHs7TiZScTuVhZUkzZfTfVgGYwy6X"); - assertEquals(address, Address.fromKey(PARAMS, key1)); - assertEquals("mnp2j9za5zMuz44vNxrJCXXhZsCdh89QXn", Address.fromKey(PARAMS, key2).toString()); + final Address address = Address.fromBase58(UNITTEST, "n2nHHRHs7TiZScTuVhZUkzZfTfVgGYwy6X"); + assertEquals(address, Address.fromKey(UNITTEST, key1)); + assertEquals("mnp2j9za5zMuz44vNxrJCXXhZsCdh89QXn", Address.fromKey(UNITTEST, key2).toString()); assertEquals(key1, chain1.findKeyFromPubHash(address.getHash160())); assertEquals(key2, chain1.findKeyFromPubKey(key2.getPubKey())); key1.sign(Sha256Hash.ZERO_HASH); ECKey key3 = chain1.getKey(KeyChain.KeyPurpose.CHANGE); - assertEquals("mpjRhk13rvV7vmnszcUQVYVQzy4HLTPTQU", Address.fromKey(PARAMS, key3).toString()); + assertEquals("mpjRhk13rvV7vmnszcUQVYVQzy4HLTPTQU", Address.fromKey(UNITTEST, key3).toString()); key3.sign(Sha256Hash.ZERO_HASH); } @@ -136,8 +137,8 @@ public class DeterministicKeyChainTest { DeterministicKeyChain chain1 = new AccountOneChain(ENTROPY, "", secs); ECKey key1 = chain1.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS); - final Address address = Address.fromBase58(PARAMS, "n2nHHRHs7TiZScTuVhZUkzZfTfVgGYwy6X"); - assertEquals(address, Address.fromKey(PARAMS, key1)); + final Address address = Address.fromBase58(UNITTEST, "n2nHHRHs7TiZScTuVhZUkzZfTfVgGYwy6X"); + assertEquals(address, Address.fromKey(UNITTEST, key1)); DeterministicKey watching = chain1.getWatchingKey(); @@ -163,14 +164,14 @@ public class DeterministicKeyChainTest { chain1 = DeterministicKeyChain.fromProtobuf(keys, null, factory).get(0); ECKey key2 = chain1.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS); - assertEquals("mnp2j9za5zMuz44vNxrJCXXhZsCdh89QXn", Address.fromKey(PARAMS, key2).toString()); + assertEquals("mnp2j9za5zMuz44vNxrJCXXhZsCdh89QXn", Address.fromKey(UNITTEST, key2).toString()); assertEquals(key1, chain1.findKeyFromPubHash(address.getHash160())); assertEquals(key2, chain1.findKeyFromPubKey(key2.getPubKey())); key1.sign(Sha256Hash.ZERO_HASH); ECKey key3 = chain1.getKey(KeyChain.KeyPurpose.CHANGE); - assertEquals("mpjRhk13rvV7vmnszcUQVYVQzy4HLTPTQU", Address.fromKey(PARAMS, key3).toString()); + assertEquals("mpjRhk13rvV7vmnszcUQVYVQzy4HLTPTQU", Address.fromKey(UNITTEST, key3).toString()); key3.sign(Sha256Hash.ZERO_HASH); assertEquals(watching, chain1.getWatchingKey()); @@ -371,11 +372,10 @@ public class DeterministicKeyChainTest { DeterministicKey key3 = chain.getKey(KeyChain.KeyPurpose.CHANGE); DeterministicKey key4 = chain.getKey(KeyChain.KeyPurpose.CHANGE); - NetworkParameters params = MainNetParams.get(); DeterministicKey watchingKey = chain.getWatchingKey(); - final String pub58 = watchingKey.serializePubB58(params); + final String pub58 = watchingKey.serializePubB58(MAINNET); assertEquals("xpub69KR9epSNBM59KLuasxMU5CyKytMJjBP5HEZ5p8YoGUCpM6cM9hqxB9DDPCpUUtqmw5duTckvPfwpoWGQUFPmRLpxs5jYiTf2u6xRMcdhDf", pub58); - watchingKey = DeterministicKey.deserializeB58(null, pub58, params); + watchingKey = DeterministicKey.deserializeB58(null, pub58, MAINNET); watchingKey.setCreationTimeSeconds(100000); chain = DeterministicKeyChain.watch(watchingKey); assertEquals(100000, chain.getEarliestKeyCreationTime()); @@ -409,7 +409,6 @@ public class DeterministicKeyChainTest { DeterministicKey key3 = bip44chain.getKey(KeyChain.KeyPurpose.CHANGE); DeterministicKey key4 = bip44chain.getKey(KeyChain.KeyPurpose.CHANGE); - NetworkParameters params = MainNetParams.get(); DeterministicKey watchingKey = bip44chain.getWatchingKey(); watchingKey = watchingKey.dropPrivateBytes().dropParent(); watchingKey.setCreationTimeSeconds(100000); @@ -446,11 +445,10 @@ public class DeterministicKeyChainTest { DeterministicKey key3 = chain1.getKey(KeyChain.KeyPurpose.CHANGE); DeterministicKey key4 = chain1.getKey(KeyChain.KeyPurpose.CHANGE); - NetworkParameters params = MainNetParams.get(); DeterministicKey watchingKey = chain1.getWatchingKey(); - final String pub58 = watchingKey.serializePubB58(params); + final String pub58 = watchingKey.serializePubB58(MAINNET); assertEquals("xpub69KR9epJ2Wp6ywiv4Xu5WfBUpX4GLu6D5NUMd4oUkCFoZoRNyk3ZCxfKPDkkGvCPa16dPgEdY63qoyLqEa5TQQy1nmfSmgWcagRzimyV7uA", pub58); - watchingKey = DeterministicKey.deserializeB58(null, pub58, params); + watchingKey = DeterministicKey.deserializeB58(null, pub58, MAINNET); watchingKey.setCreationTimeSeconds(100000); chain = DeterministicKeyChain.watch(watchingKey); assertEquals(100000, chain.getEarliestKeyCreationTime()); diff --git a/core/src/test/java/org/bitcoinj/wallet/KeyChainGroupTest.java b/core/src/test/java/org/bitcoinj/wallet/KeyChainGroupTest.java index 20abe30b..d3533cd4 100644 --- a/core/src/test/java/org/bitcoinj/wallet/KeyChainGroupTest.java +++ b/core/src/test/java/org/bitcoinj/wallet/KeyChainGroupTest.java @@ -40,7 +40,7 @@ public class KeyChainGroupTest { // Number of initial keys in this tests HD wallet, including interior keys. private static final int INITIAL_KEYS = 4; private static final int LOOKAHEAD_SIZE = 5; - private static final NetworkParameters PARAMS = MainNetParams.get(); + private static final NetworkParameters MAINNET = MainNetParams.get(); private static final String XPUB = "xpub68KFnj3bqUx1s7mHejLDBPywCAKdJEu1b49uniEEn2WSbHmZ7xbLqFTjJbtx1LUcAt1DwhoqWHmo2s5WMJp6wi38CiF2hYD49qVViKVvAoi"; private KeyChainGroup group; private DeterministicKey watchingAccountKey; @@ -49,15 +49,15 @@ public class KeyChainGroupTest { public void setup() { BriefLogFormatter.init(); Utils.setMockClock(); - group = new KeyChainGroup(PARAMS); + group = new KeyChainGroup(MAINNET); group.setLookaheadSize(LOOKAHEAD_SIZE); // Don't want slow tests. group.getActiveKeyChain(); // Force create a chain. - watchingAccountKey = DeterministicKey.deserializeB58(null, XPUB, PARAMS); + watchingAccountKey = DeterministicKey.deserializeB58(null, XPUB, MAINNET); } private KeyChainGroup createMarriedKeyChainGroup() { - KeyChainGroup group = new KeyChainGroup(PARAMS); + KeyChainGroup group = new KeyChainGroup(MAINNET); DeterministicKeyChain chain = createMarriedKeyChain(); group.addAndActivateHDChain(chain); group.setLookaheadSize(LOOKAHEAD_SIZE); @@ -295,7 +295,7 @@ public class KeyChainGroupTest { @Test public void encryptionWhilstEmpty() throws Exception { - group = new KeyChainGroup(PARAMS); + group = new KeyChainGroup(MAINNET); group.setLookaheadSize(5); KeyCrypterScrypt scrypt = new KeyCrypterScrypt(2); final KeyParameter aesKey = scrypt.deriveKey("password"); @@ -412,7 +412,7 @@ public class KeyChainGroupTest { public void serialization() throws Exception { int initialKeys = INITIAL_KEYS + group.getActiveKeyChain().getAccountPath().size() - 1; assertEquals(initialKeys + 1 /* for the seed */, group.serializeToProtobuf().size()); - group = KeyChainGroup.fromProtobufUnencrypted(PARAMS, group.serializeToProtobuf()); + group = KeyChainGroup.fromProtobufUnencrypted(MAINNET, group.serializeToProtobuf()); group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS); DeterministicKey key1 = group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS); DeterministicKey key2 = group.freshKey(KeyChain.KeyPurpose.CHANGE); @@ -423,13 +423,13 @@ public class KeyChainGroupTest { List protoKeys2 = group.serializeToProtobuf(); assertEquals(initialKeys + ((LOOKAHEAD_SIZE + 1) * 2) + 1 /* for the seed */ + 2, protoKeys2.size()); - group = KeyChainGroup.fromProtobufUnencrypted(PARAMS, protoKeys1); + group = KeyChainGroup.fromProtobufUnencrypted(MAINNET, protoKeys1); assertEquals(initialKeys + ((LOOKAHEAD_SIZE + 1) * 2) + 1 /* for the seed */ + 1, protoKeys1.size()); assertTrue(group.hasKey(key1)); assertTrue(group.hasKey(key2)); assertEquals(key2, group.currentKey(KeyChain.KeyPurpose.CHANGE)); assertEquals(key1, group.currentKey(KeyChain.KeyPurpose.RECEIVE_FUNDS)); - group = KeyChainGroup.fromProtobufUnencrypted(PARAMS, protoKeys2); + group = KeyChainGroup.fromProtobufUnencrypted(MAINNET, protoKeys2); assertEquals(initialKeys + ((LOOKAHEAD_SIZE + 1) * 2) + 1 /* for the seed */ + 2, protoKeys2.size()); assertTrue(group.hasKey(key1)); assertTrue(group.hasKey(key2)); @@ -438,7 +438,7 @@ public class KeyChainGroupTest { final KeyParameter aesKey = scrypt.deriveKey("password"); group.encrypt(scrypt, aesKey); List protoKeys3 = group.serializeToProtobuf(); - group = KeyChainGroup.fromProtobufEncrypted(PARAMS, protoKeys3, scrypt); + group = KeyChainGroup.fromProtobufEncrypted(MAINNET, protoKeys3, scrypt); assertTrue(group.isEncrypted()); assertTrue(group.checkPassword("password")); group.decrypt(aesKey); @@ -448,14 +448,14 @@ public class KeyChainGroupTest { @Test public void serializeWatching() throws Exception { - group = new KeyChainGroup(PARAMS, watchingAccountKey); + group = new KeyChainGroup(MAINNET, watchingAccountKey); group.setLookaheadSize(LOOKAHEAD_SIZE); group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS); group.freshKey(KeyChain.KeyPurpose.CHANGE); group.getBloomFilterElementCount(); // Force lookahead. List protoKeys1 = group.serializeToProtobuf(); assertEquals(3 + (group.getLookaheadSize() + group.getLookaheadThreshold() + 1) * 2, protoKeys1.size()); - group = KeyChainGroup.fromProtobufUnencrypted(PARAMS, protoKeys1); + group = KeyChainGroup.fromProtobufUnencrypted(MAINNET, protoKeys1); assertEquals(3 + (group.getLookaheadSize() + group.getLookaheadThreshold() + 1) * 2, group.serializeToProtobuf().size()); } @@ -467,7 +467,7 @@ public class KeyChainGroupTest { assertEquals(2, group.getActiveKeyChain().getSigsRequiredToSpend()); List protoKeys = group.serializeToProtobuf(); - KeyChainGroup group2 = KeyChainGroup.fromProtobufUnencrypted(PARAMS, protoKeys); + KeyChainGroup group2 = KeyChainGroup.fromProtobufUnencrypted(MAINNET, protoKeys); assertTrue(group2.isMarried()); assertEquals(2, group.getActiveKeyChain().getSigsRequiredToSpend()); Address address2 = group2.currentAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS); @@ -485,7 +485,7 @@ public class KeyChainGroupTest { public void constructFromSeed() throws Exception { ECKey key1 = group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS); final DeterministicSeed seed = checkNotNull(group.getActiveKeyChain().getSeed()); - KeyChainGroup group2 = new KeyChainGroup(PARAMS, seed); + KeyChainGroup group2 = new KeyChainGroup(MAINNET, seed); group2.setLookaheadSize(5); ECKey key2 = group2.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS); assertEquals(key1, key2); @@ -494,7 +494,7 @@ public class KeyChainGroupTest { @Test(expected = DeterministicUpgradeRequiredException.class) public void deterministicUpgradeRequired() throws Exception { // Check that if we try to use HD features in a KCG that only has random keys, we get an exception. - group = new KeyChainGroup(PARAMS); + group = new KeyChainGroup(MAINNET); group.importKeys(new ECKey(), new ECKey()); assertTrue(group.isDeterministicUpgradeRequired()); group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS); // throws @@ -504,7 +504,7 @@ public class KeyChainGroupTest { public void deterministicUpgradeUnencrypted() throws Exception { // Check that a group that contains only random keys has its HD chain created using the private key bytes of // the oldest random key, so upgrading the same wallet twice gives the same outcome. - group = new KeyChainGroup(PARAMS); + group = new KeyChainGroup(MAINNET); group.setLookaheadSize(LOOKAHEAD_SIZE); // Don't want slow tests. ECKey key1 = new ECKey(); Utils.rollMockClock(86400); @@ -518,7 +518,7 @@ public class KeyChainGroupTest { DeterministicSeed seed1 = group.getActiveKeyChain().getSeed(); assertNotNull(seed1); - group = KeyChainGroup.fromProtobufUnencrypted(PARAMS, protobufs); + group = KeyChainGroup.fromProtobufUnencrypted(MAINNET, protobufs); group.upgradeToDeterministic(0, null); // Should give same result as last time. DeterministicKey dkey2 = group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS); DeterministicSeed seed2 = group.getActiveKeyChain().getSeed(); @@ -532,7 +532,7 @@ public class KeyChainGroupTest { @Test public void deterministicUpgradeRotating() throws Exception { - group = new KeyChainGroup(PARAMS); + group = new KeyChainGroup(MAINNET); group.setLookaheadSize(LOOKAHEAD_SIZE); // Don't want slow tests. long now = Utils.currentTimeSeconds(); ECKey key1 = new ECKey(); @@ -551,7 +551,7 @@ public class KeyChainGroupTest { @Test public void deterministicUpgradeEncrypted() throws Exception { - group = new KeyChainGroup(PARAMS); + group = new KeyChainGroup(MAINNET); final ECKey key = new ECKey(); group.importKeys(key); final KeyCrypterScrypt crypter = new KeyCrypterScrypt(); @@ -588,7 +588,7 @@ public class KeyChainGroupTest { @Test public void isNotWatching() { - group = new KeyChainGroup(PARAMS); + group = new KeyChainGroup(MAINNET); final ECKey key = ECKey.fromPrivate(BigInteger.TEN); group.importKeys(key); assertFalse(group.isWatching()); @@ -597,11 +597,11 @@ public class KeyChainGroupTest { @Test public void isWatching() { group = new KeyChainGroup( - PARAMS, + MAINNET, DeterministicKey .deserializeB58( "xpub69bjfJ91ikC5ghsqsVDHNq2dRGaV2HHVx7Y9LXi27LN9BWWAXPTQr4u8U3wAtap8bLdHdkqPpAcZmhMS5SnrMQC4ccaoBccFhh315P4UYzo", - PARAMS)); + MAINNET)); final ECKey watchingKey = ECKey.fromPublicOnly(new ECKey().getPubKeyPoint()); group.importKeys(watchingKey); assertTrue(group.isWatching()); @@ -609,18 +609,18 @@ public class KeyChainGroupTest { @Test(expected = IllegalStateException.class) public void isWatchingNoKeys() { - group = new KeyChainGroup(PARAMS); + group = new KeyChainGroup(MAINNET); group.isWatching(); } @Test(expected = IllegalStateException.class) public void isWatchingMixedKeys() { group = new KeyChainGroup( - PARAMS, + MAINNET, DeterministicKey .deserializeB58( "xpub69bjfJ91ikC5ghsqsVDHNq2dRGaV2HHVx7Y9LXi27LN9BWWAXPTQr4u8U3wAtap8bLdHdkqPpAcZmhMS5SnrMQC4ccaoBccFhh315P4UYzo", - PARAMS)); + MAINNET)); final ECKey key = ECKey.fromPrivate(BigInteger.TEN); group.importKeys(key); group.isWatching(); diff --git a/core/src/test/java/org/bitcoinj/wallet/WalletTest.java b/core/src/test/java/org/bitcoinj/wallet/WalletTest.java index 3d2b5460..f2756862 100644 --- a/core/src/test/java/org/bitcoinj/wallet/WalletTest.java +++ b/core/src/test/java/org/bitcoinj/wallet/WalletTest.java @@ -95,7 +95,7 @@ public class WalletTest extends TestWithWallet { private static final CharSequence PASSWORD1 = "my helicopter contains eels"; private static final CharSequence WRONG_PASSWORD = "nothing noone nobody nowhere"; - private final Address OTHER_ADDRESS = Address.fromKey(PARAMS, new ECKey()); + private final Address OTHER_ADDRESS = Address.fromKey(UNITTEST, new ECKey()); @Before @Override @@ -114,14 +114,14 @@ public class WalletTest extends TestWithWallet { } private void createMarriedWallet(int threshold, int numKeys, boolean addSigners) throws BlockStoreException { - wallet = new Wallet(PARAMS); - blockStore = new MemoryBlockStore(PARAMS); - chain = new BlockChain(PARAMS, wallet, blockStore); + wallet = new Wallet(UNITTEST); + blockStore = new MemoryBlockStore(UNITTEST); + chain = new BlockChain(UNITTEST, wallet, blockStore); List followingKeys = Lists.newArrayList(); for (int i = 0; i < numKeys - 1; i++) { final DeterministicKeyChain keyChain = new DeterministicKeyChain(new SecureRandom()); - DeterministicKey partnerKey = DeterministicKey.deserializeB58(null, keyChain.getWatchingKey().serializePubB58(PARAMS), PARAMS); + DeterministicKey partnerKey = DeterministicKey.deserializeB58(null, keyChain.getWatchingKey().serializePubB58(UNITTEST), UNITTEST); followingKeys.add(partnerKey); if (addSigners && i < threshold - 1) wallet.addTransactionSigner(new KeyChainTransactionSigner(keyChain)); @@ -152,15 +152,15 @@ public class WalletTest extends TestWithWallet { @Test public void basicSpendingToP2SH() throws Exception { - Address destination = Address.fromP2SHHash(PARAMS, HEX.decode("4a22c3c4cbb31e4d03b15550636762bda0baf85a")); + Address destination = Address.fromP2SHHash(UNITTEST, HEX.decode("4a22c3c4cbb31e4d03b15550636762bda0baf85a")); basicSpendingCommon(wallet, myAddress, destination, null); } @Test public void basicSpendingWithEncryptedWallet() throws Exception { - Wallet encryptedWallet = new Wallet(PARAMS); + Wallet encryptedWallet = new Wallet(UNITTEST); encryptedWallet.encrypt(PASSWORD1); - Address myEncryptedAddress = Address.fromKey(PARAMS, encryptedWallet.freshReceiveKey()); + Address myEncryptedAddress = Address.fromKey(UNITTEST, encryptedWallet.freshReceiveKey()); basicSpendingCommon(encryptedWallet, myEncryptedAddress, OTHER_ADDRESS, encryptedWallet); } @@ -413,8 +413,8 @@ public class WalletTest extends TestWithWallet { private void basicSanityChecks(Wallet wallet, Transaction t, Address destination) throws VerificationException { assertEquals("Wrong number of tx inputs", 1, t.getInputs().size()); assertEquals("Wrong number of tx outputs",2, t.getOutputs().size()); - assertEquals(destination, t.getOutput(0).getScriptPubKey().getToAddress(PARAMS)); - assertEquals(wallet.currentChangeAddress(), t.getOutputs().get(1).getScriptPubKey().getToAddress(PARAMS)); + assertEquals(destination, t.getOutput(0).getScriptPubKey().getToAddress(UNITTEST)); + assertEquals(wallet.currentChangeAddress(), t.getOutputs().get(1).getScriptPubKey().getToAddress(UNITTEST)); assertEquals(valueOf(0, 50), t.getOutputs().get(1).getValue()); // Check the script runs and signatures verify. t.getInputs().get(0).verify(); @@ -429,8 +429,8 @@ public class WalletTest extends TestWithWallet { } }); - t.getConfidence().markBroadcastBy(new PeerAddress(PARAMS, InetAddress.getByAddress(new byte[]{1,2,3,4}))); - t.getConfidence().markBroadcastBy(new PeerAddress(PARAMS, InetAddress.getByAddress(new byte[]{10,2,3,4}))); + t.getConfidence().markBroadcastBy(new PeerAddress(UNITTEST, InetAddress.getByAddress(new byte[]{1,2,3,4}))); + t.getConfidence().markBroadcastBy(new PeerAddress(UNITTEST, InetAddress.getByAddress(new byte[]{10,2,3,4}))); wallet.commitTx(t); Threading.waitForUserCode(); assertEquals(1, wallet.getPoolSize(WalletTransaction.Pool.PENDING)); @@ -450,8 +450,8 @@ public class WalletTest extends TestWithWallet { req.shuffleOutputs = false; wallet.completeTx(req); Transaction t3 = req.tx; - assertNotEquals(t2.getOutput(1).getScriptPubKey().getToAddress(PARAMS), - t3.getOutput(1).getScriptPubKey().getToAddress(PARAMS)); + assertNotEquals(t2.getOutput(1).getScriptPubKey().getToAddress(UNITTEST), + t3.getOutput(1).getScriptPubKey().getToAddress(UNITTEST)); assertNotNull(t3); wallet.commitTx(t3); assertTrue(wallet.isConsistent()); @@ -474,7 +474,7 @@ public class WalletTest extends TestWithWallet { Coin v3 = valueOf(0, 75); Coin v4 = valueOf(1, 25); - Transaction t2 = new Transaction(PARAMS); + Transaction t2 = new Transaction(UNITTEST); t2.addOutput(v2, OTHER_ADDRESS); t2.addOutput(v3, OTHER_ADDRESS); t2.addOutput(v4, OTHER_ADDRESS); @@ -486,7 +486,7 @@ public class WalletTest extends TestWithWallet { List scriptSigChunks = t2.getInput(0).getScriptSig().getChunks(); // check 'from address' -- in a unit test this is fine assertEquals(2, scriptSigChunks.size()); - assertEquals(myAddress, Address.fromPubKeyHash(PARAMS, Utils.sha256hash160(scriptSigChunks.get(1).data))); + assertEquals(myAddress, Address.fromPubKeyHash(UNITTEST, Utils.sha256hash160(scriptSigChunks.get(1).data))); assertEquals(TransactionConfidence.ConfidenceType.UNKNOWN, t2.getConfidence().getConfidenceType()); // We have NOT proven that the signature is correct! @@ -549,7 +549,7 @@ public class WalletTest extends TestWithWallet { @Test public void balanceWithIdenticalOutputs() { assertEquals(Coin.ZERO, wallet.getBalance(BalanceType.ESTIMATED)); - Transaction tx = new Transaction(PARAMS); + Transaction tx = new Transaction(UNITTEST); tx.addOutput(Coin.COIN, myAddress); tx.addOutput(Coin.COIN, myAddress); // identical to the above wallet.addWalletTransaction(new WalletTransaction(Pool.UNSPENT, tx)); @@ -641,7 +641,7 @@ public class WalletTest extends TestWithWallet { // Send 0.10 to somebody else. Transaction send1 = wallet.createSend(OTHER_ADDRESS, valueOf(0, 10)); // Reserialize. - Transaction send2 = PARAMS.getDefaultSerializer().makeTransaction(send1.bitcoinSerialize()); + Transaction send2 = UNITTEST.getDefaultSerializer().makeTransaction(send1.bitcoinSerialize()); assertEquals(nanos, send2.getValueSentFromMe(wallet)); assertEquals(ZERO.subtract(valueOf(0, 10)), send2.getValue(wallet)); } @@ -650,14 +650,14 @@ public class WalletTest extends TestWithWallet { public void isConsistent_duplicates() throws Exception { // This test ensures that isConsistent catches duplicate transactions, eg, because we submitted the same block // twice (this is not allowed). - Transaction tx = createFakeTx(PARAMS, COIN, myAddress); - TransactionOutput output = new TransactionOutput(PARAMS, tx, valueOf(0, 5), OTHER_ADDRESS); + Transaction tx = createFakeTx(UNITTEST, COIN, myAddress); + TransactionOutput output = new TransactionOutput(UNITTEST, tx, valueOf(0, 5), OTHER_ADDRESS); tx.addOutput(output); wallet.receiveFromBlock(tx, null, BlockChain.NewBlockType.BEST_CHAIN, 0); assertTrue(wallet.isConsistent()); - Transaction txClone = PARAMS.getDefaultSerializer().makeTransaction(tx.bitcoinSerialize()); + Transaction txClone = UNITTEST.getDefaultSerializer().makeTransaction(tx.bitcoinSerialize()); try { wallet.receiveFromBlock(txClone, null, BlockChain.NewBlockType.BEST_CHAIN, 0); fail("Illegal argument not thrown when it should have been."); @@ -669,8 +669,8 @@ public class WalletTest extends TestWithWallet { @Test public void isConsistent_pools() throws Exception { // This test ensures that isConsistent catches transactions that are in incompatible pools. - Transaction tx = createFakeTx(PARAMS, COIN, myAddress); - TransactionOutput output = new TransactionOutput(PARAMS, tx, valueOf(0, 5), OTHER_ADDRESS); + Transaction tx = createFakeTx(UNITTEST, COIN, myAddress); + TransactionOutput output = new TransactionOutput(UNITTEST, tx, valueOf(0, 5), OTHER_ADDRESS); tx.addOutput(output); wallet.receiveFromBlock(tx, null, BlockChain.NewBlockType.BEST_CHAIN, 0); @@ -684,8 +684,8 @@ public class WalletTest extends TestWithWallet { public void isConsistent_spent() throws Exception { // This test ensures that isConsistent catches transactions that are marked spent when // they aren't. - Transaction tx = createFakeTx(PARAMS, COIN, myAddress); - TransactionOutput output = new TransactionOutput(PARAMS, tx, valueOf(0, 5), OTHER_ADDRESS); + Transaction tx = createFakeTx(UNITTEST, COIN, myAddress); + TransactionOutput output = new TransactionOutput(UNITTEST, tx, valueOf(0, 5), OTHER_ADDRESS); tx.addOutput(output); assertTrue(wallet.isConsistent()); @@ -695,13 +695,13 @@ public class WalletTest extends TestWithWallet { @Test public void isTxConsistentReturnsFalseAsExpected() { - Wallet wallet = new Wallet(PARAMS); + Wallet wallet = new Wallet(UNITTEST); TransactionOutput to = createMock(TransactionOutput.class); EasyMock.expect(to.isAvailableForSpending()).andReturn(true); EasyMock.expect(to.isMineOrWatched(wallet)).andReturn(true); - EasyMock.expect(to.getSpentBy()).andReturn(new TransactionInput(PARAMS, null, new byte[0])); + EasyMock.expect(to.getSpentBy()).andReturn(new TransactionInput(UNITTEST, null, new byte[0])); - Transaction tx = FakeTxBuilder.createFakeTxWithoutChange(PARAMS, to); + Transaction tx = FakeTxBuilder.createFakeTxWithoutChange(UNITTEST, to); replay(to); @@ -711,12 +711,12 @@ public class WalletTest extends TestWithWallet { @Test public void isTxConsistentReturnsFalseAsExpected_WhenAvailableForSpendingEqualsFalse() { - Wallet wallet = new Wallet(PARAMS); + Wallet wallet = new Wallet(UNITTEST); TransactionOutput to = createMock(TransactionOutput.class); EasyMock.expect(to.isAvailableForSpending()).andReturn(false); EasyMock.expect(to.getSpentBy()).andReturn(null); - Transaction tx = FakeTxBuilder.createFakeTxWithoutChange(PARAMS, to); + Transaction tx = FakeTxBuilder.createFakeTxWithoutChange(UNITTEST, to); replay(to); @@ -727,18 +727,18 @@ public class WalletTest extends TestWithWallet { @Test public void transactions() throws Exception { // This test covers a bug in which Transaction.getValueSentFromMe was calculating incorrectly. - Transaction tx = createFakeTx(PARAMS, COIN, myAddress); + Transaction tx = createFakeTx(UNITTEST, COIN, myAddress); // Now add another output (ie, change) that goes to some other address. - TransactionOutput output = new TransactionOutput(PARAMS, tx, valueOf(0, 5), OTHER_ADDRESS); + TransactionOutput output = new TransactionOutput(UNITTEST, tx, valueOf(0, 5), OTHER_ADDRESS); tx.addOutput(output); // Note that tx is no longer valid: it spends more than it imports. However checking transactions balance // correctly isn't possible in SPV mode because value is a property of outputs not inputs. Without all // transactions you can't check they add up. sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, tx); // Now the other guy creates a transaction which spends that change. - Transaction tx2 = new Transaction(PARAMS); + Transaction tx2 = new Transaction(UNITTEST); tx2.addInput(output); - tx2.addOutput(new TransactionOutput(PARAMS, tx2, valueOf(0, 5), myAddress)); + tx2.addOutput(new TransactionOutput(UNITTEST, tx2, valueOf(0, 5), myAddress)); // tx2 doesn't send any coins from us, even though the output is in the wallet. assertEquals(ZERO, tx2.getValueSentFromMe(wallet)); } @@ -759,8 +759,8 @@ public class WalletTest extends TestWithWallet { sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, outbound1); assertTrue(outbound1.getWalletOutputs(wallet).size() <= 1); //the change address at most // That other guy gives us the coins right back. - Transaction inbound2 = new Transaction(PARAMS); - inbound2.addOutput(new TransactionOutput(PARAMS, inbound2, coinHalf, myAddress)); + Transaction inbound2 = new Transaction(UNITTEST); + inbound2.addOutput(new TransactionOutput(UNITTEST, inbound2, coinHalf, myAddress)); assertTrue(outbound1.getWalletOutputs(wallet).size() >= 1); inbound2.addInput(outbound1.getOutputs().get(0)); sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, inbound2); @@ -779,9 +779,9 @@ public class WalletTest extends TestWithWallet { // Create a send to a merchant of all our coins. Transaction send1 = wallet.createSend(OTHER_ADDRESS, valueOf(2, 90)); // Create a double spend of just the first one. - Address BAD_GUY = Address.fromKey(PARAMS, new ECKey()); + Address BAD_GUY = Address.fromKey(UNITTEST, new ECKey()); Transaction send2 = wallet.createSend(BAD_GUY, COIN); - send2 = PARAMS.getDefaultSerializer().makeTransaction(send2.bitcoinSerialize()); + send2 = UNITTEST.getDefaultSerializer().makeTransaction(send2.bitcoinSerialize()); // Broadcast send1, it's now pending. wallet.commitTx(send1); assertEquals(ZERO, wallet.getBalance()); // change of 10 cents is not yet mined so not included in the balance. @@ -808,7 +808,7 @@ public class WalletTest extends TestWithWallet { Transaction send2 = checkNotNull(wallet.createSend(OTHER_ADDRESS, value2)); byte[] buf = send1.bitcoinSerialize(); buf[43] = 0; // Break the signature: bitcoinj won't check in SPV mode and this is easier than other mutations. - send1 = PARAMS.getDefaultSerializer().makeTransaction(buf); + send1 = UNITTEST.getDefaultSerializer().makeTransaction(buf); wallet.commitTx(send2); wallet.allowSpendingUnconfirmedTransactions(); assertEquals(value, wallet.getBalance(Wallet.BalanceType.ESTIMATED)); @@ -873,9 +873,9 @@ public class WalletTest extends TestWithWallet { // Create a send to a merchant. Transaction send1 = wallet.createSend(OTHER_ADDRESS, valueOf(0, 50)); // Create a double spend. - Address BAD_GUY = Address.fromKey(PARAMS, new ECKey()); + Address BAD_GUY = Address.fromKey(UNITTEST, new ECKey()); Transaction send2 = wallet.createSend(BAD_GUY, valueOf(0, 50)); - send2 = PARAMS.getDefaultSerializer().makeTransaction(send2.bitcoinSerialize()); + send2 = UNITTEST.getDefaultSerializer().makeTransaction(send2.bitcoinSerialize()); // Broadcast send1. wallet.commitTx(send1); assertEquals(send1, received.getOutput(0).getSpentBy().getParentTransaction()); @@ -888,7 +888,7 @@ public class WalletTest extends TestWithWallet { send1.getConfidence().getConfidenceType()); assertEquals(send2, received.getOutput(0).getSpentBy().getParentTransaction()); - FakeTxBuilder.DoubleSpends doubleSpends = FakeTxBuilder.createFakeDoubleSpendTxns(PARAMS, myAddress); + FakeTxBuilder.DoubleSpends doubleSpends = FakeTxBuilder.createFakeDoubleSpendTxns(UNITTEST, myAddress); // t1 spends to our wallet. t2 double spends somewhere else. wallet.receivePending(doubleSpends.t1, null); assertEquals(TransactionConfidence.ConfidenceType.PENDING, @@ -1097,11 +1097,11 @@ public class WalletTest extends TestWithWallet { @Test public void doubleSpendWeReceive() throws Exception { - FakeTxBuilder.DoubleSpends doubleSpends = FakeTxBuilder.createFakeDoubleSpendTxns(PARAMS, myAddress); + FakeTxBuilder.DoubleSpends doubleSpends = FakeTxBuilder.createFakeDoubleSpendTxns(UNITTEST, myAddress); // doubleSpends.t1 spends to our wallet. doubleSpends.t2 double spends somewhere else. - Transaction t1b = new Transaction(PARAMS); - TransactionOutput t1bo = new TransactionOutput(PARAMS, t1b, valueOf(0, 50), OTHER_ADDRESS); + Transaction t1b = new Transaction(UNITTEST); + TransactionOutput t1bo = new TransactionOutput(UNITTEST, t1b, valueOf(0, 50), OTHER_ADDRESS); t1b.addOutput(t1bo); t1b.addInput(doubleSpends.t1.getOutput(0)); @@ -1297,7 +1297,7 @@ public class WalletTest extends TestWithWallet { public void pending1() throws Exception { // Check that if we receive a pending transaction that is then confirmed, we are notified as appropriate. final Coin nanos = COIN; - final Transaction t1 = createFakeTx(PARAMS, nanos, myAddress); + final Transaction t1 = createFakeTx(UNITTEST, nanos, myAddress); // First one is "called" second is "pending". final boolean[] flags = new boolean[2]; @@ -1351,7 +1351,7 @@ public class WalletTest extends TestWithWallet { sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN); Threading.waitForUserCode(); assertNull(reasons[0]); - final Transaction t1Copy = PARAMS.getDefaultSerializer().makeTransaction(t1.bitcoinSerialize()); + final Transaction t1Copy = UNITTEST.getDefaultSerializer().makeTransaction(t1.bitcoinSerialize()); sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, t1Copy); Threading.waitForUserCode(); assertFalse(flags[0]); @@ -1360,7 +1360,7 @@ public class WalletTest extends TestWithWallet { // Check we don't get notified about an irrelevant transaction. flags[0] = false; flags[1] = false; - Transaction irrelevant = createFakeTx(PARAMS, nanos, OTHER_ADDRESS); + Transaction irrelevant = createFakeTx(UNITTEST, nanos, OTHER_ADDRESS); if (wallet.isPendingTransactionRelevant(irrelevant)) wallet.receivePending(irrelevant, null); Threading.waitForUserCode(); @@ -1408,16 +1408,16 @@ public class WalletTest extends TestWithWallet { Coin nanos = COIN; // Create two transactions that share the same input tx. - Address badGuy = Address.fromKey(PARAMS, new ECKey()); - Transaction doubleSpentTx = new Transaction(PARAMS); - TransactionOutput doubleSpentOut = new TransactionOutput(PARAMS, doubleSpentTx, nanos, badGuy); + Address badGuy = Address.fromKey(UNITTEST, new ECKey()); + Transaction doubleSpentTx = new Transaction(UNITTEST); + TransactionOutput doubleSpentOut = new TransactionOutput(UNITTEST, doubleSpentTx, nanos, badGuy); doubleSpentTx.addOutput(doubleSpentOut); - Transaction t1 = new Transaction(PARAMS); - TransactionOutput o1 = new TransactionOutput(PARAMS, t1, nanos, myAddress); + Transaction t1 = new Transaction(UNITTEST); + TransactionOutput o1 = new TransactionOutput(UNITTEST, t1, nanos, myAddress); t1.addOutput(o1); t1.addInput(doubleSpentOut); - Transaction t2 = new Transaction(PARAMS); - TransactionOutput o2 = new TransactionOutput(PARAMS, t2, nanos, badGuy); + Transaction t2 = new Transaction(UNITTEST); + TransactionOutput o2 = new TransactionOutput(UNITTEST, t2, nanos, badGuy); t2.addOutput(o2); t2.addInput(doubleSpentOut); @@ -1497,7 +1497,7 @@ public class WalletTest extends TestWithWallet { public void keyCreationTime() throws Exception { Utils.setMockClock(); long now = Utils.currentTimeSeconds(); - wallet = new Wallet(PARAMS); + wallet = new Wallet(UNITTEST); assertEquals(now, wallet.getEarliestKeyCreationTime()); Utils.rollMockClock(60); wallet.freshReceiveKey(); @@ -1508,7 +1508,7 @@ public class WalletTest extends TestWithWallet { public void scriptCreationTime() throws Exception { Utils.setMockClock(); long now = Utils.currentTimeSeconds(); - wallet = new Wallet(PARAMS); + wallet = new Wallet(UNITTEST); assertEquals(now, wallet.getEarliestKeyCreationTime()); Utils.rollMockClock(-120); wallet.addWatchedAddress(OTHER_ADDRESS); @@ -1542,9 +1542,9 @@ public class WalletTest extends TestWithWallet { Coin v1 = valueOf(5, 0); Coin v2 = valueOf(0, 50); Coin v3 = valueOf(0, 25); - Transaction t1 = createFakeTx(PARAMS, v1, myAddress); - Transaction t2 = createFakeTx(PARAMS, v2, myAddress); - Transaction t3 = createFakeTx(PARAMS, v3, myAddress); + Transaction t1 = createFakeTx(UNITTEST, v1, myAddress); + Transaction t2 = createFakeTx(UNITTEST, v2, myAddress); + Transaction t3 = createFakeTx(UNITTEST, v3, myAddress); Block genesis = blockStore.getChainHead().getHeader(); Block b10 = makeSolvedTestBlock(genesis, t1); @@ -1573,7 +1573,7 @@ public class WalletTest extends TestWithWallet { // Verify that we support outputs like OP_PUBKEY and the corresponding inputs. ECKey key1 = wallet.freshReceiveKey(); Coin value = valueOf(5, 0); - Transaction t1 = createFakeTx(PARAMS, value, key1); + Transaction t1 = createFakeTx(UNITTEST, value, key1); if (wallet.isPendingTransactionRelevant(t1)) wallet.receivePending(t1, null); // TX should have been seen as relevant. @@ -1593,7 +1593,7 @@ public class WalletTest extends TestWithWallet { @Test public void isWatching() { assertFalse(wallet.isWatching()); - Wallet watchingWallet = Wallet.fromWatchingKey(PARAMS, wallet.getWatchingKey().dropPrivateBytes().dropParent()); + Wallet watchingWallet = Wallet.fromWatchingKey(UNITTEST, wallet.getWatchingKey().dropPrivateBytes().dropParent()); assertTrue(watchingWallet.isWatching()); wallet.encrypt(PASSWORD1); assertFalse(wallet.isWatching()); @@ -1602,10 +1602,10 @@ public class WalletTest extends TestWithWallet { @Test public void watchingWallet() throws Exception { DeterministicKey watchKey = wallet.getWatchingKey(); - String serialized = watchKey.serializePubB58(PARAMS); + String serialized = watchKey.serializePubB58(UNITTEST); // Construct watching wallet. - Wallet watchingWallet = Wallet.fromWatchingKey(PARAMS, DeterministicKey.deserializeB58(null, serialized, PARAMS)); + Wallet watchingWallet = Wallet.fromWatchingKey(UNITTEST, DeterministicKey.deserializeB58(null, serialized, UNITTEST)); DeterministicKey key2 = watchingWallet.freshReceiveKey(); assertEquals(myKey, key2); @@ -1620,7 +1620,7 @@ public class WalletTest extends TestWithWallet { // Expected } - receiveATransaction(watchingWallet, Address.fromKey(PARAMS, myKey)); + receiveATransaction(watchingWallet, Address.fromKey(UNITTEST, myKey)); assertEquals(COIN, watchingWallet.getBalance()); assertEquals(COIN, watchingWallet.getBalance(Wallet.BalanceType.AVAILABLE)); assertEquals(ZERO, watchingWallet.getBalance(Wallet.BalanceType.AVAILABLE_SPENDABLE)); @@ -1629,8 +1629,8 @@ public class WalletTest extends TestWithWallet { @Test(expected = ECKey.MissingPrivateKeyException.class) public void watchingWalletWithCreationTime() throws Exception { DeterministicKey watchKey = wallet.getWatchingKey(); - String serialized = watchKey.serializePubB58(PARAMS); - Wallet watchingWallet = Wallet.fromWatchingKeyB58(PARAMS, serialized, 1415282801); + String serialized = watchKey.serializePubB58(UNITTEST); + Wallet watchingWallet = Wallet.fromWatchingKeyB58(UNITTEST, serialized, 1415282801); DeterministicKey key2 = watchingWallet.freshReceiveKey(); assertEquals(myKey, key2); @@ -1644,17 +1644,17 @@ public class WalletTest extends TestWithWallet { @Test public void watchingScripts() throws Exception { // Verify that pending transactions to watched addresses are relevant - Address watchedAddress = Address.fromKey(PARAMS, new ECKey()); + Address watchedAddress = Address.fromKey(UNITTEST, new ECKey()); wallet.addWatchedAddress(watchedAddress); Coin value = valueOf(5, 0); - Transaction t1 = createFakeTx(PARAMS, value, watchedAddress); + Transaction t1 = createFakeTx(UNITTEST, value, watchedAddress); assertTrue(t1.getWalletOutputs(wallet).size() >= 1); assertTrue(wallet.isPendingTransactionRelevant(t1)); } @Test(expected = InsufficientMoneyException.class) public void watchingScriptsConfirmed() throws Exception { - Address watchedAddress = Address.fromKey(PARAMS, new ECKey()); + Address watchedAddress = Address.fromKey(UNITTEST, new ECKey()); wallet.addWatchedAddress(watchedAddress); sendMoneyToWallet(BlockChain.NewBlockType.BEST_CHAIN, CENT, watchedAddress); assertEquals(CENT, wallet.getBalance()); @@ -1667,15 +1667,15 @@ public class WalletTest extends TestWithWallet { public void watchingScriptsSentFrom() throws Exception { int baseElements = wallet.getBloomFilterElementCount(); - Address watchedAddress = Address.fromKey(PARAMS, new ECKey()); + Address watchedAddress = Address.fromKey(UNITTEST, new ECKey()); wallet.addWatchedAddress(watchedAddress); assertEquals(baseElements + 1, wallet.getBloomFilterElementCount()); - Transaction t1 = createFakeTx(PARAMS, CENT, watchedAddress); - Transaction t2 = createFakeTx(PARAMS, COIN, OTHER_ADDRESS); + Transaction t1 = createFakeTx(UNITTEST, CENT, watchedAddress); + Transaction t2 = createFakeTx(UNITTEST, COIN, OTHER_ADDRESS); sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, t1); assertEquals(baseElements + 2, wallet.getBloomFilterElementCount()); - Transaction st2 = new Transaction(PARAMS); + Transaction st2 = new Transaction(UNITTEST); st2.addOutput(CENT, OTHER_ADDRESS); st2.addOutput(COIN, OTHER_ADDRESS); st2.addInput(t1.getOutput(0)); @@ -1689,9 +1689,9 @@ public class WalletTest extends TestWithWallet { public void watchingScriptsBloomFilter() throws Exception { assertFalse(wallet.isRequiringUpdateAllBloomFilter()); - Address watchedAddress = Address.fromKey(PARAMS, new ECKey()); - Transaction t1 = createFakeTx(PARAMS, CENT, watchedAddress); - TransactionOutPoint outPoint = new TransactionOutPoint(PARAMS, 0, t1); + Address watchedAddress = Address.fromKey(UNITTEST, new ECKey()); + Transaction t1 = createFakeTx(UNITTEST, CENT, watchedAddress); + TransactionOutPoint outPoint = new TransactionOutPoint(UNITTEST, 0, t1); wallet.addWatchedAddress(watchedAddress); assertTrue(wallet.isRequiringUpdateAllBloomFilter()); @@ -1704,7 +1704,7 @@ public class WalletTest extends TestWithWallet { @Test public void getWatchedAddresses() throws Exception { - Address watchedAddress = Address.fromKey(PARAMS, new ECKey()); + Address watchedAddress = Address.fromKey(UNITTEST, new ECKey()); wallet.addWatchedAddress(watchedAddress); List
watchedAddresses = wallet.getWatchedAddresses(); assertEquals(1, watchedAddresses.size()); @@ -1715,7 +1715,7 @@ public class WalletTest extends TestWithWallet { public void removeWatchedAddresses() { List
addressesForRemoval = new ArrayList<>(); for (int i = 0; i < 10; i++) { - Address watchedAddress = Address.fromKey(PARAMS, new ECKey()); + Address watchedAddress = Address.fromKey(UNITTEST, new ECKey()); addressesForRemoval.add(watchedAddress); wallet.addWatchedAddress(watchedAddress); } @@ -1729,7 +1729,7 @@ public class WalletTest extends TestWithWallet { @Test public void removeWatchedAddress() { - Address watchedAddress = Address.fromKey(PARAMS, new ECKey()); + Address watchedAddress = Address.fromKey(UNITTEST, new ECKey()); wallet.addWatchedAddress(watchedAddress); wallet.removeWatchedAddress(watchedAddress); assertFalse(wallet.isAddressWatched(watchedAddress)); @@ -1740,7 +1740,7 @@ public class WalletTest extends TestWithWallet { public void removeScriptsBloomFilter() throws Exception { List
addressesForRemoval = new ArrayList<>(); for (int i = 0; i < 10; i++) { - Address watchedAddress = Address.fromKey(PARAMS, new ECKey()); + Address watchedAddress = Address.fromKey(UNITTEST, new ECKey()); addressesForRemoval.add(watchedAddress); wallet.addWatchedAddress(watchedAddress); } @@ -1748,8 +1748,8 @@ public class WalletTest extends TestWithWallet { wallet.removeWatchedAddresses(addressesForRemoval); for (Address addr : addressesForRemoval) { - Transaction t1 = createFakeTx(PARAMS, CENT, addr); - TransactionOutPoint outPoint = new TransactionOutPoint(PARAMS, 0, t1); + Transaction t1 = createFakeTx(UNITTEST, CENT, addr); + TransactionOutPoint outPoint = new TransactionOutPoint(UNITTEST, 0, t1); // Note that this has a 1e-12 chance of failing this unit test due to a false positive assertFalse(wallet.getBloomFilter(1e-12).contains(outPoint.unsafeBitcoinSerialize())); @@ -1766,8 +1766,8 @@ public class WalletTest extends TestWithWallet { assertTrue(wallet.getBloomFilter(0.001).contains(address.getHash160())); - Transaction t1 = createFakeTx(PARAMS, CENT, address); - TransactionOutPoint outPoint = new TransactionOutPoint(PARAMS, 0, t1); + Transaction t1 = createFakeTx(UNITTEST, CENT, address); + TransactionOutPoint outPoint = new TransactionOutPoint(UNITTEST, 0, t1); assertFalse(wallet.getBloomFilter(0.001).contains(outPoint.unsafeBitcoinSerialize())); @@ -1786,7 +1786,7 @@ public class WalletTest extends TestWithWallet { Sha256Hash hash2 = Sha256Hash.of(f); assertFalse("Wallet not saved after generating fresh key", hash1.equals(hash2)); // File has changed. - Transaction t1 = createFakeTx(PARAMS, valueOf(5, 0), key); + Transaction t1 = createFakeTx(UNITTEST, valueOf(5, 0), key); if (wallet.isPendingTransactionRelevant(t1)) wallet.receivePending(t1, null); Sha256Hash hash3 = Sha256Hash.of(f); @@ -1868,8 +1868,8 @@ public class WalletTest extends TestWithWallet { // 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, Address.fromKey(PARAMS, k2)); + Transaction t2 = new Transaction(UNITTEST); + TransactionOutput o2 = new TransactionOutput(UNITTEST, t2, v2, Address.fromKey(UNITTEST, k2)); t2.addOutput(o2); SendRequest req = SendRequest.forTx(t2); wallet.completeTx(req); @@ -1883,8 +1883,8 @@ public class WalletTest extends TestWithWallet { // Now try to the spend the output. ECKey k3 = new ECKey(); Coin v3 = valueOf(0, 25); - Transaction t3 = new Transaction(PARAMS); - t3.addOutput(v3, Address.fromKey(PARAMS, k3)); + Transaction t3 = new Transaction(UNITTEST); + t3.addOutput(v3, Address.fromKey(UNITTEST, k3)); t3.addInput(o2); wallet.signTransaction(SendRequest.forTx(t3)); @@ -1904,8 +1904,8 @@ public class WalletTest extends TestWithWallet { // See bug 345. This can happen if there is a pending transaction floating around and then you replay the // chain without emptying the memory pool (or refilling it from a peer). Coin value = COIN; - Transaction tx1 = createFakeTx(PARAMS, value, myAddress); - Transaction tx2 = new Transaction(PARAMS); + Transaction tx1 = createFakeTx(UNITTEST, value, myAddress); + Transaction tx2 = new Transaction(UNITTEST); tx2.addInput(tx1.getOutput(0)); tx2.addOutput(valueOf(0, 9), OTHER_ADDRESS); // Add a change address to ensure this tx is relevant. @@ -1924,14 +1924,14 @@ public class WalletTest extends TestWithWallet { // correctly. For instance, we are watching a wallet, someone pays us (A) and we then pay someone else (B) // with a change address but the network delivers the transactions to us in order B then A. Coin value = COIN; - Transaction a = createFakeTx(PARAMS, value, myAddress); - Transaction b = new Transaction(PARAMS); + Transaction a = createFakeTx(UNITTEST, value, myAddress); + Transaction b = new Transaction(UNITTEST); b.addInput(a.getOutput(0)); b.addOutput(CENT, OTHER_ADDRESS); Coin v = COIN.subtract(CENT); b.addOutput(v, wallet.currentChangeAddress()); - a = roundTripTransaction(PARAMS, a); - b = roundTripTransaction(PARAMS, b); + a = roundTripTransaction(UNITTEST, a); + b = roundTripTransaction(UNITTEST, b); wallet.receivePending(b, null); assertEquals(v, wallet.getBalance(Wallet.BalanceType.ESTIMATED)); wallet.receivePending(a, null); @@ -1940,7 +1940,7 @@ public class WalletTest extends TestWithWallet { @Test public void encryptionDecryptionAESBasic() throws Exception { - Wallet encryptedWallet = new Wallet(PARAMS); + Wallet encryptedWallet = new Wallet(UNITTEST); encryptedWallet.encrypt(PASSWORD1); KeyCrypter keyCrypter = encryptedWallet.getKeyCrypter(); KeyParameter aesKey = keyCrypter.deriveKey(PASSWORD1); @@ -1963,7 +1963,7 @@ public class WalletTest extends TestWithWallet { @Test public void encryptionDecryptionPasswordBasic() throws Exception { - Wallet encryptedWallet = new Wallet(PARAMS); + Wallet encryptedWallet = new Wallet(UNITTEST); encryptedWallet.encrypt(PASSWORD1); assertTrue(encryptedWallet.isEncrypted()); @@ -1981,7 +1981,7 @@ public class WalletTest extends TestWithWallet { @Test public void encryptionDecryptionBadPassword() throws Exception { - Wallet encryptedWallet = new Wallet(PARAMS); + Wallet encryptedWallet = new Wallet(UNITTEST); encryptedWallet.encrypt(PASSWORD1); KeyCrypter keyCrypter = encryptedWallet.getKeyCrypter(); KeyParameter wrongAesKey = keyCrypter.deriveKey(WRONG_PASSWORD); @@ -2001,7 +2001,7 @@ public class WalletTest extends TestWithWallet { @Test public void changePasswordTest() { - Wallet encryptedWallet = new Wallet(PARAMS); + Wallet encryptedWallet = new Wallet(UNITTEST); encryptedWallet.encrypt(PASSWORD1); CharSequence newPassword = "My name is Tom"; encryptedWallet.changeEncryptionPassword(PASSWORD1, newPassword); @@ -2011,7 +2011,7 @@ public class WalletTest extends TestWithWallet { @Test public void changeAesKeyTest() { - Wallet encryptedWallet = new Wallet(PARAMS); + Wallet encryptedWallet = new Wallet(UNITTEST); encryptedWallet.encrypt(PASSWORD1); KeyCrypter keyCrypter = encryptedWallet.getKeyCrypter(); @@ -2028,7 +2028,7 @@ public class WalletTest extends TestWithWallet { @Test public void encryptionDecryptionCheckExceptions() throws Exception { - Wallet encryptedWallet = new Wallet(PARAMS); + Wallet encryptedWallet = new Wallet(UNITTEST); encryptedWallet.encrypt(PASSWORD1); KeyCrypter keyCrypter = encryptedWallet.getKeyCrypter(); KeyParameter aesKey = keyCrypter.deriveKey(PASSWORD1); @@ -2067,7 +2067,7 @@ public class WalletTest extends TestWithWallet { @Test(expected = KeyCrypterException.class) public void addUnencryptedKeyToEncryptedWallet() throws Exception { - Wallet encryptedWallet = new Wallet(PARAMS); + Wallet encryptedWallet = new Wallet(UNITTEST); encryptedWallet.encrypt(PASSWORD1); ECKey key1 = new ECKey(); @@ -2076,7 +2076,7 @@ public class WalletTest extends TestWithWallet { @Test(expected = KeyCrypterException.class) public void addEncryptedKeyToUnencryptedWallet() throws Exception { - Wallet encryptedWallet = new Wallet(PARAMS); + Wallet encryptedWallet = new Wallet(UNITTEST); encryptedWallet.encrypt(PASSWORD1); KeyCrypter keyCrypter = encryptedWallet.getKeyCrypter(); @@ -2087,7 +2087,7 @@ public class WalletTest extends TestWithWallet { @Test(expected = KeyCrypterException.class) public void mismatchedCrypter() throws Exception { - Wallet encryptedWallet = new Wallet(PARAMS); + Wallet encryptedWallet = new Wallet(UNITTEST); encryptedWallet.encrypt(PASSWORD1); KeyCrypter keyCrypter = encryptedWallet.getKeyCrypter(); KeyParameter aesKey = keyCrypter.deriveKey(PASSWORD1); @@ -2105,14 +2105,14 @@ public class WalletTest extends TestWithWallet { @Test public void importAndEncrypt() throws InsufficientMoneyException { - Wallet encryptedWallet = new Wallet(PARAMS); + Wallet encryptedWallet = new Wallet(UNITTEST); encryptedWallet.encrypt(PASSWORD1); final ECKey key = new ECKey(); encryptedWallet.importKeysAndEncrypt(ImmutableList.of(key), PASSWORD1); assertEquals(1, encryptedWallet.getImportedKeys().size()); assertEquals(key.getPubKeyPoint(), encryptedWallet.getImportedKeys().get(0).getPubKeyPoint()); - sendMoneyToWallet(encryptedWallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, Coin.COIN, Address.fromKey(PARAMS, key)); + sendMoneyToWallet(encryptedWallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, Coin.COIN, Address.fromKey(UNITTEST, key)); assertEquals(Coin.COIN, encryptedWallet.getBalance()); SendRequest req = SendRequest.emptyWallet(OTHER_ADDRESS); req.aesKey = checkNotNull(encryptedWallet.getKeyCrypter()).deriveKey(PASSWORD1); @@ -2141,13 +2141,13 @@ public class WalletTest extends TestWithWallet { public void respectMaxStandardSize() throws Exception { // Check that we won't create txns > 100kb. Average tx size is ~220 bytes so this would have to be enormous. sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, valueOf(100, 0)); - Transaction tx = new Transaction(PARAMS); + Transaction tx = new Transaction(UNITTEST); byte[] bits = new byte[20]; new Random().nextBytes(bits); Coin v = CENT; // 3100 outputs to a random address. for (int i = 0; i < 3100; i++) { - tx.addOutput(v, Address.fromPubKeyHash(PARAMS, bits)); + tx.addOutput(v, Address.fromPubKeyHash(UNITTEST, bits)); } SendRequest req = SendRequest.forTx(tx); wallet.completeTx(req); @@ -2157,7 +2157,7 @@ public class WalletTest extends TestWithWallet { public void opReturnOneOutputTest() throws Exception { // Tests basic send of transaction with one output that doesn't transfer any value but just writes OP_RETURN. receiveATransaction(wallet, myAddress); - Transaction tx = new Transaction(PARAMS); + Transaction tx = new Transaction(UNITTEST); Coin messagePrice = Coin.ZERO; Script script = ScriptBuilder.createOpReturnScript("hello world!".getBytes()); tx.addOutput(messagePrice, script); @@ -2169,7 +2169,7 @@ public class WalletTest extends TestWithWallet { @Test public void opReturnMaxBytes() throws Exception { receiveATransaction(wallet, myAddress); - Transaction tx = new Transaction(PARAMS); + Transaction tx = new Transaction(UNITTEST); Script script = ScriptBuilder.createOpReturnScript(new byte[80]); tx.addOutput(Coin.ZERO, script); SendRequest request = SendRequest.forTx(tx); @@ -2181,7 +2181,7 @@ public class WalletTest extends TestWithWallet { public void opReturnOneOutputWithValueTest() throws Exception { // Tests basic send of transaction with one output that destroys coins and has an OP_RETURN. receiveATransaction(wallet, myAddress); - Transaction tx = new Transaction(PARAMS); + Transaction tx = new Transaction(UNITTEST); Coin messagePrice = CENT; Script script = ScriptBuilder.createOpReturnScript("hello world!".getBytes()); tx.addOutput(messagePrice, script); @@ -2193,7 +2193,7 @@ public class WalletTest extends TestWithWallet { public void opReturnTwoOutputsTest() throws Exception { // Tests sending transaction where one output transfers BTC, the other one writes OP_RETURN. receiveATransaction(wallet, myAddress); - Transaction tx = new Transaction(PARAMS); + Transaction tx = new Transaction(UNITTEST); Coin messagePrice = Coin.ZERO; Script script = ScriptBuilder.createOpReturnScript("hello world!".getBytes()); tx.addOutput(CENT, OTHER_ADDRESS); @@ -2206,7 +2206,7 @@ public class WalletTest extends TestWithWallet { public void twoOpReturnsPerTransactionTest() throws Exception { // Tests sending transaction where there are 2 attempts to write OP_RETURN scripts - this should fail and throw MultipleOpReturnRequested. receiveATransaction(wallet, myAddress); - Transaction tx = new Transaction(PARAMS); + Transaction tx = new Transaction(UNITTEST); Coin messagePrice = Coin.ZERO; Script script1 = ScriptBuilder.createOpReturnScript("hello world 1!".getBytes()); Script script2 = ScriptBuilder.createOpReturnScript("hello world 2!".getBytes()); @@ -2220,7 +2220,7 @@ public class WalletTest extends TestWithWallet { @Test(expected = Wallet.DustySendRequested.class) public void sendDustTest() throws InsufficientMoneyException { // Tests sending dust, should throw DustySendRequested. - Transaction tx = new Transaction(PARAMS); + Transaction tx = new Transaction(UNITTEST); tx.addOutput(Transaction.MIN_NONDUST_OUTPUT.subtract(SATOSHI), OTHER_ADDRESS); SendRequest request = SendRequest.forTx(tx); request.ensureMinRequiredFee = true; @@ -2230,7 +2230,7 @@ public class WalletTest extends TestWithWallet { @Test public void sendMultipleCentsTest() throws Exception { receiveATransactionAmount(wallet, myAddress, Coin.COIN); - Transaction tx = new Transaction(PARAMS); + Transaction tx = new Transaction(UNITTEST); Coin c = CENT.subtract(SATOSHI); tx.addOutput(c, OTHER_ADDRESS); tx.addOutput(c, OTHER_ADDRESS); @@ -2244,7 +2244,7 @@ public class WalletTest extends TestWithWallet { public void sendDustAndOpReturnWithoutValueTest() throws Exception { // Tests sending dust and OP_RETURN without value, should throw DustySendRequested because sending sending dust is not allowed in any case. receiveATransactionAmount(wallet, myAddress, Coin.COIN); - Transaction tx = new Transaction(PARAMS); + Transaction tx = new Transaction(UNITTEST); tx.addOutput(Coin.ZERO, ScriptBuilder.createOpReturnScript("hello world!".getBytes())); tx.addOutput(Coin.SATOSHI, OTHER_ADDRESS); SendRequest request = SendRequest.forTx(tx); @@ -2256,7 +2256,7 @@ public class WalletTest extends TestWithWallet { public void sendDustAndMessageWithValueTest() throws Exception { // Tests sending dust and OP_RETURN with value, should throw DustySendRequested receiveATransaction(wallet, myAddress); - Transaction tx = new Transaction(PARAMS); + Transaction tx = new Transaction(UNITTEST); tx.addOutput(Coin.CENT, ScriptBuilder.createOpReturnScript("hello world!".getBytes())); tx.addOutput(Transaction.MIN_NONDUST_OUTPUT.subtract(SATOSHI), OTHER_ADDRESS); SendRequest request = SendRequest.forTx(tx); @@ -2267,7 +2267,7 @@ public class WalletTest extends TestWithWallet { @Test public void sendRequestP2PKTest() { ECKey key = new ECKey(); - SendRequest req = SendRequest.to(PARAMS, key, SATOSHI.multiply(12)); + SendRequest req = SendRequest.to(UNITTEST, key, SATOSHI.multiply(12)); assertArrayEquals(key.getPubKey(), ScriptPattern.extractKeyFromPayToPubKey(req.tx.getOutputs().get(0).getScriptPubKey())); } @@ -2275,16 +2275,16 @@ public class WalletTest extends TestWithWallet { @Test public void sendRequestP2PKHTest() { SendRequest req = SendRequest.to(OTHER_ADDRESS, SATOSHI.multiply(12)); - assertEquals(OTHER_ADDRESS, req.tx.getOutputs().get(0).getScriptPubKey().getToAddress(PARAMS)); + assertEquals(OTHER_ADDRESS, req.tx.getOutputs().get(0).getScriptPubKey().getToAddress(UNITTEST)); } @Test public void feeSolverAndCoinSelectionTest_dustySendRequested() throws Exception { // Generate a few outputs to us that are far too small to spend reasonably - Transaction tx1 = createFakeTx(PARAMS, SATOSHI, myAddress); - Transaction tx2 = createFakeTx(PARAMS, SATOSHI, myAddress); + Transaction tx1 = createFakeTx(UNITTEST, SATOSHI, myAddress); + Transaction tx2 = createFakeTx(UNITTEST, SATOSHI, myAddress); assertNotEquals(tx1.getHash(), tx2.getHash()); - Transaction tx3 = createFakeTx(PARAMS, SATOSHI.multiply(10), myAddress); + Transaction tx3 = createFakeTx(UNITTEST, SATOSHI.multiply(10), myAddress); sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, tx1, tx2, tx3); // Not allowed to send dust. @@ -2396,7 +2396,7 @@ public class WalletTest extends TestWithWallet { SendRequest request17 = SendRequest.to(OTHER_ADDRESS, CENT); for (int i = 0; i < 22; i++) request17.tx.addOutput(CENT, OTHER_ADDRESS); - request17.tx.addOutput(new TransactionOutput(PARAMS, request17.tx, CENT, new byte[15])); + request17.tx.addOutput(new TransactionOutput(UNITTEST, request17.tx, CENT, new byte[15])); request17.feePerKb = Transaction.DEFAULT_TX_FEE; request17.ensureMinRequiredFee = true; wallet.completeTx(request17); @@ -2423,7 +2423,7 @@ public class WalletTest extends TestWithWallet { SendRequest request18 = SendRequest.to(OTHER_ADDRESS, CENT); for (int i = 0; i < 22; i++) request18.tx.addOutput(CENT, OTHER_ADDRESS); - request18.tx.addOutput(new TransactionOutput(PARAMS, request18.tx, CENT, new byte[17])); + request18.tx.addOutput(new TransactionOutput(UNITTEST, request18.tx, CENT, new byte[17])); request18.feePerKb = Transaction.DEFAULT_TX_FEE; request18.ensureMinRequiredFee = true; wallet.completeTx(request18); @@ -2526,7 +2526,7 @@ public class WalletTest extends TestWithWallet { assertEquals(CENT, request25.tx.getInput(1).getValue()); // Spend our CENT output. - Transaction spendTx5 = new Transaction(PARAMS); + Transaction spendTx5 = new Transaction(UNITTEST); spendTx5.addOutput(CENT, OTHER_ADDRESS); spendTx5.addInput(tx5.getOutput(0)); wallet.signTransaction(SendRequest.forTx(spendTx5)); @@ -2680,7 +2680,7 @@ public class WalletTest extends TestWithWallet { public void transactionGetFeeTest() throws Exception { // Prepare wallet to spend StoredBlock block = new StoredBlock(makeSolvedTestBlock(blockStore, OTHER_ADDRESS), BigInteger.ONE, 1); - Transaction tx = createFakeTx(PARAMS, COIN, myAddress); + Transaction tx = createFakeTx(UNITTEST, COIN, myAddress); wallet.receiveFromBlock(tx, block, AbstractBlockChain.NewBlockType.BEST_CHAIN, 0); // Create a transaction @@ -2735,12 +2735,12 @@ public class WalletTest extends TestWithWallet { // Generate a few outputs to us StoredBlock block = new StoredBlock(makeSolvedTestBlock(blockStore, OTHER_ADDRESS), BigInteger.ONE, 1); - Transaction tx1 = createFakeTx(PARAMS, COIN, myAddress); + Transaction tx1 = createFakeTx(UNITTEST, COIN, myAddress); wallet.receiveFromBlock(tx1, block, AbstractBlockChain.NewBlockType.BEST_CHAIN, 0); - Transaction tx2 = createFakeTx(PARAMS, COIN, myAddress); + Transaction tx2 = createFakeTx(UNITTEST, COIN, myAddress); assertNotEquals(tx1.getHash(), tx2.getHash()); wallet.receiveFromBlock(tx2, block, AbstractBlockChain.NewBlockType.BEST_CHAIN, 1); - Transaction tx3 = createFakeTx(PARAMS, CENT, myAddress); + Transaction tx3 = createFakeTx(UNITTEST, CENT, myAddress); wallet.receiveFromBlock(tx3, block, AbstractBlockChain.NewBlockType.BEST_CHAIN, 2); SendRequest request1 = SendRequest.to(OTHER_ADDRESS, CENT); @@ -2766,7 +2766,7 @@ public class WalletTest extends TestWithWallet { // However, if there is no connected output, we will grab a COIN output anyway and add the CENT to fee SendRequest request3 = SendRequest.to(OTHER_ADDRESS, CENT); - request3.tx.addInput(new TransactionInput(PARAMS, request3.tx, new byte[]{}, new TransactionOutPoint(PARAMS, 0, tx3.getHash()))); + request3.tx.addInput(new TransactionInput(UNITTEST, request3.tx, new byte[]{}, new TransactionOutPoint(UNITTEST, 0, tx3.getHash()))); // Now completeTx will result in two inputs, two outputs and a fee of a CENT // Note that it is simply assumed that the inputs are correctly signed, though in fact the first is not request3.shuffleOutputs = false; @@ -2824,7 +2824,7 @@ public class WalletTest extends TestWithWallet { StoredBlock block = new StoredBlock(makeSolvedTestBlock(blockStore, OTHER_ADDRESS), BigInteger.ONE, 1); Random rng = new Random(); for (int i = 0; i < rng.nextInt(100) + 1; i++) { - Transaction tx = createFakeTx(PARAMS, Coin.valueOf(rng.nextInt((int) COIN.value)), myAddress); + Transaction tx = createFakeTx(UNITTEST, Coin.valueOf(rng.nextInt((int) COIN.value)), myAddress); wallet.receiveFromBlock(tx, block, AbstractBlockChain.NewBlockType.BEST_CHAIN, i); } SendRequest request = SendRequest.emptyWallet(OTHER_ADDRESS); @@ -2837,7 +2837,7 @@ public class WalletTest extends TestWithWallet { public void testEmptyWallet() throws Exception { // Add exactly 0.01 StoredBlock block = new StoredBlock(makeSolvedTestBlock(blockStore, OTHER_ADDRESS), BigInteger.ONE, 1); - Transaction tx = createFakeTx(PARAMS, CENT, myAddress); + Transaction tx = createFakeTx(UNITTEST, CENT, myAddress); wallet.receiveFromBlock(tx, block, AbstractBlockChain.NewBlockType.BEST_CHAIN, 0); SendRequest request = SendRequest.emptyWallet(OTHER_ADDRESS); wallet.completeTx(request); @@ -2849,9 +2849,9 @@ public class WalletTest extends TestWithWallet { // Add 1 confirmed cent and 1 unconfirmed cent. Verify only one cent is emptied because of the coin selection // policies that are in use by default. block = new StoredBlock(makeSolvedTestBlock(blockStore, OTHER_ADDRESS), BigInteger.ONE, 2); - tx = createFakeTx(PARAMS, CENT, myAddress); + tx = createFakeTx(UNITTEST, CENT, myAddress); wallet.receiveFromBlock(tx, block, AbstractBlockChain.NewBlockType.BEST_CHAIN, 0); - tx = createFakeTx(PARAMS, CENT, myAddress); + tx = createFakeTx(UNITTEST, CENT, myAddress); wallet.receivePending(tx, null); request = SendRequest.emptyWallet(OTHER_ADDRESS); wallet.completeTx(request); @@ -2863,7 +2863,7 @@ public class WalletTest extends TestWithWallet { // Add an unsendable value block = new StoredBlock(block.getHeader().createNextBlock(OTHER_ADDRESS), BigInteger.ONE, 3); Coin outputValue = Transaction.MIN_NONDUST_OUTPUT.subtract(SATOSHI); - tx = createFakeTx(PARAMS, outputValue, myAddress); + tx = createFakeTx(UNITTEST, outputValue, myAddress); wallet.receiveFromBlock(tx, block, AbstractBlockChain.NewBlockType.BEST_CHAIN, 0); try { request = SendRequest.emptyWallet(OTHER_ADDRESS); @@ -2876,12 +2876,12 @@ public class WalletTest extends TestWithWallet { @Test public void childPaysForParent() throws Exception { // Receive confirmed balance to play with. - Transaction toMe = createFakeTxWithoutChangeAddress(PARAMS, COIN, myAddress); + Transaction toMe = createFakeTxWithoutChangeAddress(UNITTEST, COIN, myAddress); sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, toMe); assertEquals(Coin.COIN, wallet.getBalance(BalanceType.ESTIMATED_SPENDABLE)); assertEquals(Coin.COIN, wallet.getBalance(BalanceType.AVAILABLE_SPENDABLE)); // Receive unconfirmed coin without fee. - Transaction toMeWithoutFee = createFakeTxWithoutChangeAddress(PARAMS, COIN, myAddress); + Transaction toMeWithoutFee = createFakeTxWithoutChangeAddress(UNITTEST, COIN, myAddress); wallet.receivePending(toMeWithoutFee, null); assertEquals(Coin.COIN.multiply(2), wallet.getBalance(BalanceType.ESTIMATED_SPENDABLE)); assertEquals(Coin.COIN, wallet.getBalance(BalanceType.AVAILABLE_SPENDABLE)); @@ -2899,7 +2899,7 @@ public class WalletTest extends TestWithWallet { public void keyRotationRandom() throws Exception { Utils.setMockClock(); // Start with an empty wallet (no HD chain). - wallet = new Wallet(PARAMS); + wallet = new Wallet(UNITTEST); // Watch out for wallet-initiated broadcasts. MockTransactionBroadcaster broadcaster = new MockTransactionBroadcaster(wallet); // Send three cents to two different random keys, then add a key and mark the initial keys as compromised. @@ -2909,9 +2909,9 @@ public class WalletTest extends TestWithWallet { key2.setCreationTimeSeconds(Utils.currentTimeSeconds() - 86400); wallet.importKey(key1); wallet.importKey(key2); - sendMoneyToWallet(wallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, Address.fromKey(PARAMS, key1)); - sendMoneyToWallet(wallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, Address.fromKey(PARAMS, key2)); - sendMoneyToWallet(wallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, Address.fromKey(PARAMS, key2)); + sendMoneyToWallet(wallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, Address.fromKey(UNITTEST, key1)); + sendMoneyToWallet(wallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, Address.fromKey(UNITTEST, key2)); + sendMoneyToWallet(wallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, Address.fromKey(UNITTEST, key2)); Date compromiseTime = Utils.now(); assertEquals(0, broadcaster.size()); assertFalse(wallet.isKeyRotating(key1)); @@ -2928,7 +2928,7 @@ public class WalletTest extends TestWithWallet { assertEquals(THREE_CENTS, tx.getValueSentFromMe(wallet)); assertEquals(THREE_CENTS.subtract(tx.getFee()), tx.getValueSentToMe(wallet)); // TX sends to one of our addresses (for now we ignore married wallets). - final Address toAddress = tx.getOutput(0).getScriptPubKey().getToAddress(PARAMS); + final Address toAddress = tx.getOutput(0).getScriptPubKey().getToAddress(UNITTEST); final ECKey rotatingToKey = wallet.findKeyFromPubHash(toAddress.getHash160()); assertNotNull(rotatingToKey); assertFalse(wallet.isKeyRotating(rotatingToKey)); @@ -2942,7 +2942,7 @@ public class WalletTest extends TestWithWallet { assertEquals(0, broadcaster.size()); // Receive money via a new block on key1 and ensure it shows up as a maintenance task. - sendMoneyToWallet(wallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, Address.fromKey(PARAMS, key1)); + sendMoneyToWallet(wallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, Address.fromKey(UNITTEST, key1)); wallet.doMaintenance(null, true); tx = broadcaster.waitForTransactionAndSucceed(); assertNotNull(wallet.findKeyFromPubHash(tx.getOutput(0).getScriptPubKey().getPubKeyHash())); @@ -2974,18 +2974,18 @@ public class WalletTest extends TestWithWallet { private Wallet roundTrip(Wallet wallet) throws UnreadableWalletException { Protos.Wallet protos = new WalletProtobufSerializer().walletToProto(wallet); - return new WalletProtobufSerializer().readWallet(PARAMS, null, protos); + return new WalletProtobufSerializer().readWallet(UNITTEST, null, protos); } @Test public void keyRotationHD() throws Exception { // Test that if we rotate an HD chain, a new one is created and all arrivals on the old keys are moved. Utils.setMockClock(); - wallet = new Wallet(PARAMS); + wallet = new Wallet(UNITTEST); ECKey key1 = wallet.freshReceiveKey(); ECKey key2 = wallet.freshReceiveKey(); - sendMoneyToWallet(wallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, Address.fromKey(PARAMS, key1)); - sendMoneyToWallet(wallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, Address.fromKey(PARAMS, key2)); + sendMoneyToWallet(wallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, Address.fromKey(UNITTEST, key1)); + sendMoneyToWallet(wallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, Address.fromKey(UNITTEST, key2)); DeterministicKey watchKey1 = wallet.getWatchingKey(); // A day later, we get compromised. @@ -3016,7 +3016,7 @@ public class WalletTest extends TestWithWallet { // Do an upgrade based on the bad key. final AtomicReference> fChains = new AtomicReference<>(); - KeyChainGroup kcg = new KeyChainGroup(PARAMS) { + KeyChainGroup kcg = new KeyChainGroup(UNITTEST) { { fChains.set(chains); @@ -3024,22 +3024,22 @@ public class WalletTest extends TestWithWallet { }; kcg.importKeys(badKey, goodKey); Utils.rollMockClock(86400); - wallet = new Wallet(PARAMS, kcg); // This avoids the automatic HD initialisation + wallet = new Wallet(UNITTEST, kcg); // This avoids the automatic HD initialisation assertTrue(fChains.get().isEmpty()); wallet.upgradeToDeterministic(null); DeterministicKey badWatchingKey = wallet.getWatchingKey(); assertEquals(badKey.getCreationTimeSeconds(), badWatchingKey.getCreationTimeSeconds()); - sendMoneyToWallet(wallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, Address.fromKey(PARAMS, badWatchingKey)); + sendMoneyToWallet(wallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, Address.fromKey(UNITTEST, badWatchingKey)); // 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()); List txns = wallet.doMaintenance(null, false).get(); assertEquals(1, txns.size()); - Address output = txns.get(0).getOutput(0).getAddressFromP2PKHScript(PARAMS); + Address output = txns.get(0).getOutput(0).getAddressFromP2PKHScript(UNITTEST); ECKey usedKey = wallet.findKeyFromPubHash(output.getHash160()); assertEquals(goodKey.getCreationTimeSeconds(), usedKey.getCreationTimeSeconds()); assertEquals(goodKey.getCreationTimeSeconds(), wallet.freshReceiveKey().getCreationTimeSeconds()); - assertEquals("mrM3TpCnav5YQuVA1xLercCGJH4DXujMtv", Address.fromKey(PARAMS, usedKey).toString()); + assertEquals("mrM3TpCnav5YQuVA1xLercCGJH4DXujMtv", Address.fromKey(UNITTEST, usedKey).toString()); DeterministicKeyChain c = fChains.get().get(1); assertEquals(c.getEarliestKeyCreationTime(), goodKey.getCreationTimeSeconds()); assertEquals(2, fChains.get().size()); @@ -3062,7 +3062,7 @@ public class WalletTest extends TestWithWallet { public void fragmentedReKeying() throws Exception { // Send lots of small coins and check the fee is correct. ECKey key = wallet.freshReceiveKey(); - Address address = Address.fromKey(PARAMS, key); + Address address = Address.fromKey(UNITTEST, key); Utils.setMockClock(); Utils.rollMockClock(86400); for (int i = 0; i < 800; i++) { @@ -3110,7 +3110,7 @@ public class WalletTest extends TestWithWallet { // Delete the sigs for (TransactionInput input : req.tx.getInputs()) input.clearScriptBytes(); - Wallet watching = Wallet.fromWatchingKey(PARAMS, wallet.getWatchingKey().dropParent().dropPrivateBytes()); + Wallet watching = Wallet.fromWatchingKey(UNITTEST, wallet.getWatchingKey().dropParent().dropPrivateBytes()); watching.completeTx(SendRequest.forTx(req.tx)); } @@ -3171,7 +3171,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, // and the final one being a key we do have. We expect the first two inputs to be dummy values and the last // to be signed correctly. - Transaction t1 = sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, Address.fromKey(PARAMS, pub)); + Transaction t1 = sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, Address.fromKey(UNITTEST, pub)); Transaction t2 = sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, pub); Transaction t3 = sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, priv2); @@ -3196,7 +3196,7 @@ public class WalletTest extends TestWithWallet { @Test public void riskAnalysis() throws Exception { // Send a tx that is considered risky to the wallet, verify it doesn't show up in the balances. - final Transaction tx = createFakeTx(PARAMS, COIN, myAddress); + final Transaction tx = createFakeTx(UNITTEST, COIN, myAddress); final AtomicBoolean bool = new AtomicBoolean(); wallet.setRiskAnalyzer(new RiskAnalysis.Analyzer() { @Override @@ -3228,13 +3228,13 @@ public class WalletTest extends TestWithWallet { @Test public void transactionInBlockNotification() { - final Transaction tx = createFakeTx(PARAMS, COIN, myAddress); + final Transaction tx = createFakeTx(UNITTEST, COIN, myAddress); StoredBlock block = createFakeBlock(blockStore, Block.BLOCK_HEIGHT_GENESIS, tx).storedBlock; wallet.receivePending(tx, null); boolean notification = wallet.notifyTransactionIsInBlock(tx.getHash(), block, AbstractBlockChain.NewBlockType.BEST_CHAIN, 1); assertTrue(notification); - final Transaction tx2 = createFakeTx(PARAMS, COIN, OTHER_ADDRESS); + final Transaction tx2 = createFakeTx(UNITTEST, COIN, OTHER_ADDRESS); wallet.receivePending(tx2, null); StoredBlock block2 = createFakeBlock(blockStore, Block.BLOCK_HEIGHT_GENESIS + 1, tx2).storedBlock; boolean notification2 = wallet.notifyTransactionIsInBlock(tx2.getHash(), block2, AbstractBlockChain.NewBlockType.BEST_CHAIN, 1); @@ -3243,7 +3243,7 @@ public class WalletTest extends TestWithWallet { @Test public void duplicatedBlock() { - final Transaction tx = createFakeTx(PARAMS, COIN, myAddress); + final Transaction tx = createFakeTx(UNITTEST, COIN, myAddress); StoredBlock block = createFakeBlock(blockStore, Block.BLOCK_HEIGHT_GENESIS, tx).storedBlock; wallet.notifyNewBestBlock(block); wallet.notifyNewBestBlock(block); @@ -3252,7 +3252,7 @@ public class WalletTest extends TestWithWallet { @Test public void keyEvents() throws Exception { // Check that we can register an event listener, generate some keys and the callbacks are invoked properly. - wallet = new Wallet(PARAMS); + wallet = new Wallet(UNITTEST); final List keys = Lists.newLinkedList(); wallet.addKeyChainEventListener(Threading.SAME_THREAD, new KeyChainEventListener() { @Override @@ -3273,9 +3273,9 @@ public class WalletTest extends TestWithWallet { // much where it goes). Wallet on the other hand will try to auto-upgrade you when possible. // Create an old-style random wallet. - KeyChainGroup group = new KeyChainGroup(PARAMS); + KeyChainGroup group = new KeyChainGroup(UNITTEST); group.importKeys(new ECKey(), new ECKey()); - wallet = new Wallet(PARAMS, group); + wallet = new Wallet(UNITTEST, group); assertTrue(wallet.isDeterministicUpgradeRequired()); // Use an HD feature. wallet.freshReceiveKey(); @@ -3285,9 +3285,9 @@ public class WalletTest extends TestWithWallet { @Test public void upgradeToHDEncrypted() throws Exception { // Create an old-style random wallet. - KeyChainGroup group = new KeyChainGroup(PARAMS); + KeyChainGroup group = new KeyChainGroup(UNITTEST); group.importKeys(new ECKey(), new ECKey()); - wallet = new Wallet(PARAMS, group); + wallet = new Wallet(UNITTEST, group); assertTrue(wallet.isDeterministicUpgradeRequired()); KeyCrypter crypter = new KeyCrypterScrypt(); KeyParameter aesKey = crypter.deriveKey("abc"); @@ -3320,13 +3320,13 @@ public class WalletTest extends TestWithWallet { @Test public void watchingMarriedWallet() throws Exception { DeterministicKey watchKey = wallet.getWatchingKey(); - String serialized = watchKey.serializePubB58(PARAMS); - Wallet wallet = Wallet.fromWatchingKeyB58(PARAMS, serialized, 0); - blockStore = new MemoryBlockStore(PARAMS); - chain = new BlockChain(PARAMS, wallet, blockStore); + String serialized = watchKey.serializePubB58(UNITTEST); + Wallet wallet = Wallet.fromWatchingKeyB58(UNITTEST, serialized, 0); + blockStore = new MemoryBlockStore(UNITTEST); + chain = new BlockChain(UNITTEST, wallet, blockStore); final DeterministicKeyChain keyChain = new DeterministicKeyChain(new SecureRandom()); - DeterministicKey partnerKey = DeterministicKey.deserializeB58(null, keyChain.getWatchingKey().serializePubB58(PARAMS), PARAMS); + DeterministicKey partnerKey = DeterministicKey.deserializeB58(null, keyChain.getWatchingKey().serializePubB58(UNITTEST), UNITTEST); TransactionSigner signer = new StatelessTransactionSigner() { @Override @@ -3401,7 +3401,7 @@ public class WalletTest extends TestWithWallet { @Test public void fromKeys() { ECKey key = ECKey.fromPrivate(Utils.HEX.decode("00905b93f990267f4104f316261fc10f9f983551f9ef160854f40102eb71cffdcc")); - Wallet wallet = Wallet.fromKeys(PARAMS, Arrays.asList(key)); + Wallet wallet = Wallet.fromKeys(UNITTEST, Arrays.asList(key)); assertEquals(1, wallet.getImportedKeys().size()); assertEquals(key, wallet.getImportedKeys().get(0)); wallet.upgradeToDeterministic(null); @@ -3424,8 +3424,8 @@ public class WalletTest extends TestWithWallet { @Test public void totalReceivedSent() throws Exception { // Receive 4 BTC in 2 separate transactions - Transaction toMe1 = createFakeTxWithoutChangeAddress(PARAMS, COIN.multiply(2), myAddress); - Transaction toMe2 = createFakeTxWithoutChangeAddress(PARAMS, COIN.multiply(2), myAddress); + Transaction toMe1 = createFakeTxWithoutChangeAddress(UNITTEST, COIN.multiply(2), myAddress); + Transaction toMe2 = createFakeTxWithoutChangeAddress(UNITTEST, COIN.multiply(2), myAddress); sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, toMe1, toMe2); // Check we calculate the total received correctly @@ -3445,10 +3445,10 @@ public class WalletTest extends TestWithWallet { @Test public void testIrrelevantDoubleSpend() throws Exception { - Transaction tx0 = createFakeTx(PARAMS); - Transaction tx1 = createFakeTx(PARAMS); + Transaction tx0 = createFakeTx(UNITTEST); + Transaction tx1 = createFakeTx(UNITTEST); - Transaction tx2 = new Transaction(PARAMS); + Transaction tx2 = new Transaction(UNITTEST); tx2.addInput(tx0.getOutput(0)); tx2.addOutput(COIN, myAddress); tx2.addOutput(COIN, OTHER_ADDRESS); @@ -3456,14 +3456,14 @@ public class WalletTest extends TestWithWallet { sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, tx2, tx1, tx0); // tx3 and tx4 double spend each other - Transaction tx3 = new Transaction(PARAMS); + Transaction tx3 = new Transaction(UNITTEST); tx3.addInput(tx1.getOutput(0)); tx3.addOutput(COIN, myAddress); tx3.addOutput(COIN, OTHER_ADDRESS); wallet.receivePending(tx3, null); // tx4 also spends irrelevant output from tx2 - Transaction tx4 = new Transaction(PARAMS); + Transaction tx4 = new Transaction(UNITTEST); tx4.addInput(tx1.getOutput(0)); // spends same output tx4.addInput(tx2.getOutput(1)); tx4.addOutput(COIN, OTHER_ADDRESS); @@ -3479,9 +3479,9 @@ public class WalletTest extends TestWithWallet { @Test public void overridingDeadTxTest() throws Exception { - Transaction tx0 = createFakeTx(PARAMS); + Transaction tx0 = createFakeTx(UNITTEST); - Transaction tx1 = new Transaction(PARAMS); + Transaction tx1 = new Transaction(UNITTEST); tx1.addInput(tx0.getOutput(0)); tx1.addOutput(COIN, OTHER_ADDRESS); tx1.addOutput(COIN, OTHER_ADDRESS); @@ -3490,7 +3490,7 @@ public class WalletTest extends TestWithWallet { sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, tx0, tx1); // tx2, tx3 and tx4 double spend each other - Transaction tx2 = new Transaction(PARAMS); + Transaction tx2 = new Transaction(UNITTEST); tx2.addInput(tx1.getOutput(0)); tx2.addInput(tx1.getOutput(1)); tx2.addOutput(COIN, myAddress); @@ -3498,12 +3498,12 @@ public class WalletTest extends TestWithWallet { wallet.receivePending(tx2, null); // irrelevant to the wallet - Transaction tx3 = new Transaction(PARAMS); + Transaction tx3 = new Transaction(UNITTEST); tx3.addInput(tx1.getOutput(0)); // spends same output as tx2 tx3.addOutput(COIN, OTHER_ADDRESS); // irrelevant to the wallet - Transaction tx4 = new Transaction(PARAMS); + Transaction tx4 = new Transaction(UNITTEST); tx4.addInput(tx1.getOutput(1)); // spends different output, but also in tx2 tx4.addOutput(COIN, OTHER_ADDRESS);