3
0
mirror of https://github.com/Qortal/altcoinj.git synced 2025-02-12 18:25:51 +00:00

Consequently use constants for network params in test cases.

This commit is contained in:
Andreas Schildbach 2018-02-28 00:51:43 +01:00
parent 1d15d95d97
commit 2aec06a281
46 changed files with 890 additions and 873 deletions

View File

@ -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)

View File

@ -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");

View File

@ -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

View File

@ -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<Sha256Hash, Block> preloadedBlocks = new HashMap<>();
final Iterator<Block> blocks = new BlockFileLoader(params, Arrays.asList(blockFile));
final Iterator<Block> 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<Sha256Hash> 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++;

View File

@ -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));

View File

@ -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());

View File

@ -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());

View File

@ -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);
}

View File

@ -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 {

View File

@ -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()));

File diff suppressed because one or more lines are too long

View File

@ -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 {

View File

@ -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));

View File

@ -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()));
}

View File

@ -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<List<Peer>> 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<List<Peer>> 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);

View File

@ -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<ClientType[]> 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<Sha256Hash> 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<Sha256Hash> 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<Sha256Hash> 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<UTXOsMessage> future1 = peer.getUTXOs(ImmutableList.of(op1));
ListenableFuture<UTXOsMessage> 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.

View File

@ -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);
}
}

View File

@ -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<Transaction> 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);

View File

@ -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));

View File

@ -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<ECKey> 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());
}
}

View File

@ -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<Transaction> 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);

View File

@ -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());

View File

@ -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);

View File

@ -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)));
}
}

View File

@ -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)

View File

@ -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);
}

View File

@ -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));
}
}

View File

@ -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.

View File

@ -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<PaymentChannelServerState> 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

View File

@ -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<Transaction> 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<Transaction> parsedTransactions = PaymentProtocol.parseTransactionsFromPaymentMessage(PARAMS,
List<Transaction> parsedTransactions = PaymentProtocol.parseTransactionsFromPaymentMessage(UNITTEST,
parsedPayment);
assertEquals(transactions, parsedTransactions);
assertEquals(1, parsedPayment.getRefundToCount());

View File

@ -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<Transaction> 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<Transaction> 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<Transaction> 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());
}

View File

@ -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<ECKey> 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)

View File

@ -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<byte[]> 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<TransactionOutPoint, Script> 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<VerifyFlag> 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<TransactionOutPoint, Script> 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<VerifyFlag> 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);
}
}

View File

@ -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);

View File

@ -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.

View File

@ -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<Transaction> 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());
}
}

View File

@ -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() {
}

View File

@ -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")) {

View File

@ -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

View File

@ -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());

View File

@ -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());
}
}

View File

@ -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<TransactionOutput> 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);

View File

@ -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());

View File

@ -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());

View File

@ -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<Protos.Key> 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<Protos.Key> 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<Protos.Key> 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<Protos.Key> 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();

File diff suppressed because it is too large Load Diff