/** * Generates a simple MultipleAlignment: 3 structures with the same Atoms but incorreclty aligned * with gaps. * * @return MultipleAlignment gapped MSTA * @throws StructureException */ private MultipleAlignment gappedMSTA() throws StructureException { // Generate three identical Atom arrays List<Atom[]> atomArrays = new ArrayList<Atom[]>(30); for (int i = 0; i < 3; i++) atomArrays.add(makeDummyCA(30)); // Generate alignment with nulls and some missalignments List<List<Integer>> alnRes = new ArrayList<List<Integer>>(3); List<Integer> chain1 = Arrays.asList(1, 2, 3, 5, 8, 10, 12, 15, 17, 19, 22, null, 24, 27); List<Integer> chain2 = Arrays.asList(1, null, 3, 6, 9, 11, 12, 15, null, 18, 22, 24, 26, 28); List<Integer> chain3 = Arrays.asList(1, 2, 4, 7, 9, 10, null, 15, null, 17, 22, 24, 26, 28); alnRes.add(chain1); alnRes.add(chain2); alnRes.add(chain3); // MultipleAlignment generation MultipleAlignment msa = new MultipleAlignmentImpl(); msa.getEnsemble().setAtomArrays(atomArrays); BlockSet bs = new BlockSetImpl(msa); Block b = new BlockImpl(bs); b.setAlignRes(alnRes); // We want the identity transfromations to mantain the missalignments Matrix4d ident = new Matrix4d(); ident.setIdentity(); msa.setTransformations(Arrays.asList(ident, ident, ident)); return msa; }
/** * Generates a simple MultipleAlignment: 3 structures with the same Atoms but incorreclty aligned * (offset of 1 position) without gaps. * * @return MultipleAlignment simple MSTA * @throws StructureException */ private MultipleAlignment simpleMSTA() throws StructureException { // Generate three identical Atom arrays List<Atom[]> atomArrays = new ArrayList<Atom[]>(52); for (int i = 0; i < 3; i++) atomArrays.add(makeDummyCA(52)); // Generate the incorrect alignment (0-1-2,1-2-3,etc) List<List<Integer>> alnRes = new ArrayList<List<Integer>>(3); for (int str = 0; str < 3; str++) { List<Integer> chain = new ArrayList<Integer>(50); for (int res = 0; res < 50; res++) chain.add(res + str); alnRes.add(chain); } // MultipleAlignment generation MultipleAlignment msa = new MultipleAlignmentImpl(); msa.getEnsemble().setAtomArrays(atomArrays); BlockSet bs = new BlockSetImpl(msa); Block b = new BlockImpl(bs); b.setAlignRes(alnRes); // We want the identity transfromations to maintain the missalignment Matrix4d ident = new Matrix4d(); ident.setIdentity(); msa.setTransformations(Arrays.asList(ident, ident, ident)); return msa; }
@Test public void testEquals() { final Block block = new Block(program), block2 = new Block(program); assertTrue(block.equals(block2)); assertTrue(block2.equals(block2)); assertFalse(block.equals(new Block())); }
/** * Generates an identity MultipleAlignment: 3 structures with the same Atoms and perfectly * aligned, so that TM-score = 1 and RMSD = 0. * * @return MultipleAlignment identity * @throws StructureException */ private MultipleAlignment identityMSTA() throws StructureException { // Generate the identical Atom arrays List<Atom[]> atomArrays = new ArrayList<Atom[]>(20); for (int i = 0; i < 3; i++) atomArrays.add(makeDummyCA(20)); // Generate the identity alignment (1-1-1,2-2-2,etc) List<List<Integer>> alnRes = new ArrayList<List<Integer>>(3); for (int str = 0; str < 3; str++) { List<Integer> chain = new ArrayList<Integer>(20); for (int res = 0; res < 20; res++) chain.add(res); alnRes.add(chain); } // MultipleAlignment generation MultipleAlignment msa = new MultipleAlignmentImpl(); msa.getEnsemble().setAtomArrays(atomArrays); BlockSet bs = new BlockSetImpl(msa); Block b = new BlockImpl(bs); b.setAlignRes(alnRes); // Superimpose the alignment (which should give the identity matrices) ReferenceSuperimposer imposer = new ReferenceSuperimposer(); imposer.superimpose(msa); return msa; }
@Test public void testAssignReturn() { mainBlock.addSimpleAssign("it", 5); mainBlock.addReturnVar("it"); int result = runMain(); assertEquals(5, result); }
@Test public void testProofOfWork() throws Exception { // This params accepts any difficulty target. NetworkParameters params = UnitTestParams.get(); Block block = params.getDefaultSerializer().makeBlock(blockBytes); block.setNonce(12346); try { block.verify(Block.BLOCK_HEIGHT_GENESIS, EnumSet.noneOf(Block.VerifyFlag.class)); fail(); } catch (VerificationException e) { // Expected. } // Blocks contain their own difficulty target. The BlockChain verification mechanism is what // stops real blocks // from containing artificially weak difficulties. block.setDifficultyTarget(Block.EASIEST_DIFFICULTY_TARGET); // Now it should pass. block.verify(Block.BLOCK_HEIGHT_GENESIS, EnumSet.noneOf(Block.VerifyFlag.class)); // Break the nonce again at the lower difficulty level so we can try solving for it. block.setNonce(1); try { block.verify(Block.BLOCK_HEIGHT_GENESIS, EnumSet.noneOf(Block.VerifyFlag.class)); fail(); } catch (VerificationException e) { // Expected to fail as the nonce is no longer correct. } // Should find an acceptable nonce. block.solve(); block.verify(Block.BLOCK_HEIGHT_GENESIS, EnumSet.noneOf(Block.VerifyFlag.class)); assertEquals(block.getNonce(), 2); }
@Test public void testLastBlockSeenHash() throws Exception { // Test the lastBlockSeenHash field works. // LastBlockSeenHash should be empty if never set. Wallet wallet = new Wallet(params); Protos.Wallet walletProto = new WalletProtobufSerializer().walletToProto(wallet); ByteString lastSeenBlockHash = walletProto.getLastSeenBlockHash(); assertTrue(lastSeenBlockHash.isEmpty()); // Create a block. Block block = params.getDefaultSerializer().makeBlock(BlockTest.blockBytes); Sha256Hash blockHash = block.getHash(); wallet.setLastBlockSeenHash(blockHash); wallet.setLastBlockSeenHeight(1); // Roundtrip the wallet and check it has stored the blockHash. Wallet wallet1 = roundTrip(wallet); assertEquals(blockHash, wallet1.getLastBlockSeenHash()); assertEquals(1, wallet1.getLastBlockSeenHeight()); // Test the Satoshi genesis block (hash of all zeroes) is roundtripped ok. Block genesisBlock = MainNetParams.get().getGenesisBlock(); wallet.setLastBlockSeenHash(genesisBlock.getHash()); Wallet wallet2 = roundTrip(wallet); assertEquals(genesisBlock.getHash(), wallet2.getLastBlockSeenHash()); }
@Test public void testHeaderParse() throws Exception { Block block = params.getDefaultSerializer().makeBlock(blockBytes); Block header = block.cloneAsHeader(); Block reparsed = params.getDefaultSerializer().makeBlock(header.bitcoinSerialize()); assertEquals(reparsed, header); }
@Test public void testCoinbaseHeightTestnet() throws Exception { // Testnet block 21066 (hash 0000000004053156021d8e42459d284220a7f6e087bf78f30179c3703ca4eefa) // 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( ByteStreams.toByteArray(getClass().getResourceAsStream("block_testnet21066.dat"))); // Check block. assertEquals( "0000000004053156021d8e42459d284220a7f6e087bf78f30179c3703ca4eefa", block.getHashAsString()); block.verify(21066, EnumSet.of(Block.VerifyFlag.HEIGHT_IN_COINBASE)); // Testnet block 32768 (hash 000000007590ba495b58338a5806c2b6f10af921a70dbd814e0da3c6957c0c03) // contains a coinbase transaction whose height is three bytes, but could // fit in two bytes. This test primarily ensures script encoding checks // are applied correctly. block = TestNet3Params.get() .getDefaultSerializer() .makeBlock( ByteStreams.toByteArray(getClass().getResourceAsStream("block_testnet32768.dat"))); // Check block. assertEquals( "000000007590ba495b58338a5806c2b6f10af921a70dbd814e0da3c6957c0c03", block.getHashAsString()); block.verify(32768, EnumSet.of(Block.VerifyFlag.HEIGHT_IN_COINBASE)); }
// Check that it starts downloading the block chain correctly on request. @Test public void startBlockChainDownload() throws Exception { Block b1 = createFakeBlock(blockStore).block; blockChain.add(b1); Block b2 = makeSolvedTestBlock(b1); blockChain.add(b2); connect(); fail.set(true); peer.addEventListener( new AbstractPeerEventListener() { @Override public void onChainDownloadStarted(Peer p, int blocksLeft) { if (p == peer && blocksLeft == 108) fail.set(false); } }, Threading.SAME_THREAD); peer.startBlockChainDownload(); List<Sha256Hash> expectedLocator = new ArrayList<Sha256Hash>(); expectedLocator.add(b2.getHash()); expectedLocator.add(b1.getHash()); expectedLocator.add(unitTestParams.getGenesisBlock().getHash()); GetBlocksMessage message = (GetBlocksMessage) outbound(writeTarget); assertEquals(message.getLocator(), expectedLocator); assertEquals(Sha256Hash.ZERO_HASH, message.getStopHash()); }
@Test public void testBlockVerification() throws Exception { Block block = params.getDefaultSerializer().makeBlock(blockBytes); block.verify(Block.BLOCK_HEIGHT_GENESIS, EnumSet.noneOf(Block.VerifyFlag.class)); assertEquals( "00000000a6e5eb79dcec11897af55e90cd571a4335383a3ccfbc12ec81085935", block.getHashAsString()); }
// Check that inventory message containing blocks we want is processed correctly. @Test public void newBlock() throws Exception { Block b1 = createFakeBlock(blockStore).block; blockChain.add(b1); final Block b2 = makeSolvedTestBlock(b1); // Receive notification of a new block. final InventoryMessage inv = new InventoryMessage(unitTestParams); InventoryItem item = new InventoryItem(InventoryItem.Type.Block, b2.getHash()); inv.addItem(item); final AtomicInteger newBlockMessagesReceived = new AtomicInteger(0); connect(); // Round-trip a ping so that we never see the response verack if we attach too quick pingAndWait(writeTarget); peer.addEventListener( new AbstractPeerEventListener() { @Override public synchronized Message onPreMessageReceived(Peer p, Message m) { if (p != peer) fail.set(true); if (m instanceof Pong) return m; int newValue = newBlockMessagesReceived.incrementAndGet(); if (newValue == 1 && !inv.equals(m)) fail.set(true); else if (newValue == 2 && !b2.equals(m)) fail.set(true); else if (newValue > 3) fail.set(true); return m; } @Override public synchronized void onBlocksDownloaded(Peer p, Block block, int blocksLeft) { int newValue = newBlockMessagesReceived.incrementAndGet(); if (newValue != 3 || p != peer || !block.equals(b2) || blocksLeft != OTHER_PEER_CHAIN_HEIGHT - 2) fail.set(true); } }, Threading.SAME_THREAD); long height = peer.getBestHeight(); inbound(writeTarget, inv); pingAndWait(writeTarget); assertEquals(height + 1, peer.getBestHeight()); // Response to the getdata message. inbound(writeTarget, b2); pingAndWait(writeTarget); Threading.waitForUserCode(); pingAndWait(writeTarget); assertEquals(3, newBlockMessagesReceived.get()); GetDataMessage getdata = (GetDataMessage) outbound(writeTarget); List<InventoryItem> items = getdata.getItems(); assertEquals(1, items.size()); assertEquals(b2.getHash(), items.get(0).hash); assertEquals(InventoryItem.Type.Block, items.get(0).type); }
/** Test that if the block height is missing from coinbase of a version 2 block, it's rejected. */ @Test public void missingHeightFromCoinbase() throws Exception { final int UNDOABLE_BLOCKS_STORED = params.getMajorityEnforceBlockUpgrade() + 1; store = createStore(params, UNDOABLE_BLOCKS_STORED); try { chain = new FullPrunedBlockChain(params, store); ECKey outKey = new ECKey(); int height = 1; Block chainHead = params.getGenesisBlock(); // Build some blocks on genesis block to create a spendable output. // Put in just enough v1 blocks to stop the v2 blocks from forming a majority for (height = 1; height <= (params.getMajorityWindow() - params.getMajorityEnforceBlockUpgrade()); height++) { chainHead = chainHead.createNextBlockWithCoinbase( Block.BLOCK_VERSION_GENESIS, outKey.getPubKey(), height); chain.add(chainHead); } // Fill the rest of the window in with v2 blocks for (; height < params.getMajorityWindow(); height++) { chainHead = chainHead.createNextBlockWithCoinbase( Block.BLOCK_VERSION_BIP34, outKey.getPubKey(), height); chain.add(chainHead); } // Throw a broken v2 block in before we have a supermajority to enable // enforcement, which should validate as-is chainHead = chainHead.createNextBlockWithCoinbase( Block.BLOCK_VERSION_BIP34, outKey.getPubKey(), height * 2); chain.add(chainHead); height++; // Trying to add a broken v2 block should now result in rejection as // we have a v2 supermajority thrown.expect(VerificationException.CoinbaseHeightMismatch.class); chainHead = chainHead.createNextBlockWithCoinbase( Block.BLOCK_VERSION_BIP34, outKey.getPubKey(), height * 2); chain.add(chainHead); } catch (final VerificationException ex) { throw (Exception) ex.getCause(); } finally { try { store.close(); } catch (Exception e) { // Catch and drop any exception so a break mid-test doesn't result // in a new exception being thrown and the original lost } } }
@Test public void testBitcoinSerialization() throws Exception { // We have to be able to reserialize everything exactly as we found it for hashing to work. This // test also // 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); assertTrue(Arrays.equals(blockBytes, block.bitcoinSerialize())); }
@Test public void testSimpleCall() { Block other = new Block(); other.addReturnValue(5); addFunc("other", other); mainBlock.addStatement(new ReturnStatement(new FuncExpr("other", new ArrayList<IntOrVar>()))); int result = runMain(); assertEquals(5, result); }
@Before public void setUp() throws Exception { unitTestParams = UnitTestParams.get(); wallet = new Wallet(unitTestParams); wallet.addKey(new ECKey()); resetBlockStore(); Transaction tx1 = createFakeTx( unitTestParams, Utils.toNanoCoins(2, 0), wallet.getKeys().get(0).toAddress(unitTestParams)); // add a second input so can test granularity of byte cache. Transaction prevTx = new Transaction(unitTestParams); TransactionOutput prevOut = new TransactionOutput( unitTestParams, prevTx, Utils.toNanoCoins(1, 0), wallet.getKeys().get(0).toAddress(unitTestParams)); prevTx.addOutput(prevOut); // Connect it. tx1.addInput(prevOut); Transaction tx2 = createFakeTx( unitTestParams, Utils.toNanoCoins(1, 0), new ECKey().toAddress(unitTestParams)); Block b1 = createFakeBlock(blockStore, tx1, tx2).block; BitcoinSerializer bs = new BitcoinSerializer(unitTestParams); ByteArrayOutputStream bos = new ByteArrayOutputStream(); bs.serialize(tx1, bos); tx1BytesWithHeader = bos.toByteArray(); tx1Bytes = tx1.bitcoinSerialize(); bos.reset(); bs.serialize(tx2, bos); tx2BytesWithHeader = bos.toByteArray(); tx2Bytes = tx2.bitcoinSerialize(); bos.reset(); bs.serialize(b1, bos); b1BytesWithHeader = bos.toByteArray(); b1Bytes = b1.bitcoinSerialize(); }
@Test public void testBadTransactions() throws Exception { Block block = params.getDefaultSerializer().makeBlock(blockBytes); // Re-arrange so the coinbase transaction is not first. Transaction tx1 = block.transactions.get(0); Transaction tx2 = block.transactions.get(1); block.transactions.set(0, tx2); block.transactions.set(1, tx1); try { block.verify(Block.BLOCK_HEIGHT_GENESIS, EnumSet.noneOf(Block.VerifyFlag.class)); fail(); } catch (VerificationException e) { // We should get here. } }
@Test public void testIfFalse() { // if it == 0 return 1 args.set("it", 2); Expr expr = new MathExpr(MathExpr.Operation.EQ, ValueExpr.createVar("it"), ValueExpr.createValue(0)); Block block = new Block(); block.addReturnValue(1); mainBlock.addStatement(new IfStatement(expr, block)); mainBlock.addReturnValue(0); int result = runMain(); assertEquals(0, result); }
@Test public void testReturnArg() { args.set("it", 9); mainBlock.addReturnVar("it"); int result = runMain(); assertEquals(9, result); }
@Test public void testReceiveCoinbaseTransaction() throws Exception { // Block 169482 (hash 0000000000000756935f1ee9d5987857b604046f846d3df56d024cdb5f368665) // contains coinbase transactions that are mining pool shares. // The private key MINERS_KEY is used to check transactions are received by a wallet correctly. // The address for this private key is 1GqtGtn4fctXuKxsVzRPSLmYWN1YioLi9y. final String MINING_PRIVATE_KEY = "5JDxPrBRghF1EvSBjDigywqfmAjpHPmTJxYtQTYJxJRHLLQA4mG"; final long BLOCK_NONCE = 3973947400L; final Coin BALANCE_AFTER_BLOCK = Coin.valueOf(22223642); final NetworkParameters PARAMS = MainNetParams.get(); Block block169482 = PARAMS .getDefaultSerializer() .makeBlock(ByteStreams.toByteArray(getClass().getResourceAsStream("block169482.dat"))); // Check block. assertNotNull(block169482); block169482.verify(169482, EnumSet.noneOf(Block.VerifyFlag.class)); assertEquals(BLOCK_NONCE, block169482.getNonce()); StoredBlock storedBlock = new StoredBlock(block169482, BigInteger.ONE, 169482); // Nonsense work - not used in test. // Create a wallet contain the miner's key that receives a spend from a coinbase. ECKey miningKey = DumpedPrivateKey.fromBase58(PARAMS, MINING_PRIVATE_KEY).getKey(); assertNotNull(miningKey); Context context = new Context(PARAMS); Wallet wallet = new Wallet(context); wallet.importKey(miningKey); // Initial balance should be zero by construction. assertEquals(Coin.ZERO, wallet.getBalance()); // Give the wallet the first transaction in the block - this is the coinbase tx. List<Transaction> transactions = block169482.getTransactions(); assertNotNull(transactions); wallet.receiveFromBlock(transactions.get(0), storedBlock, NewBlockType.BEST_CHAIN, 0); // Coinbase transaction should have been received successfully but be unavailable to spend (too // young). assertEquals(BALANCE_AFTER_BLOCK, wallet.getBalance(BalanceType.ESTIMATED)); assertEquals(Coin.ZERO, wallet.getBalance(BalanceType.AVAILABLE)); }
@Test public void testUpdateLength() { NetworkParameters params = UnitTestParams.get(); Block block = params .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); // 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})))); int origTxLength = 8 + 2 + 8 + 1 + 10 + 40 + 1 + 1; assertEquals(tx.bitcoinSerialize().length, tx.length); assertEquals(origTxLength, tx.length); block.addTransaction(tx); assertEquals(block.bitcoinSerialize().length, block.length); assertEquals(origBlockLen + tx.length, block.length); block .getTransactions() .get(1) .getInputs() .get(0) .setScriptBytes(new byte[] {(byte) ScriptOpCodes.OP_FALSE, (byte) ScriptOpCodes.OP_FALSE}); assertEquals(block.length, origBlockLen + tx.length); assertEquals(tx.length, origTxLength + 1); block.getTransactions().get(1).getInputs().get(0).setScriptBytes(new byte[] {}); assertEquals(block.length, block.bitcoinSerialize().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})))); assertEquals(block.length, origBlockLen + tx.length); assertEquals(tx.length, origTxLength + 41); // - 1 + 40 + 1 + 1 }
@Test public void testSimpleMath() { Expr four = ValueExpr.createValue(4); Expr five = ValueExpr.createValue(5); Expr expr = new MathExpr(MathExpr.Operation.ADD, four, five); mainBlock.addStatement(new ReturnStatement(expr)); int result = runMain(); assertEquals(9, result); }
// Check that an inv to a peer that is not set to download missing blocks does nothing. @Test public void invNoDownload() throws Exception { // Don't download missing blocks. peer.setDownloadData(false); connect(); // Make a missing block that we receive. Block b1 = createFakeBlock(blockStore).block; blockChain.add(b1); Block b2 = makeSolvedTestBlock(b1); // Receive an inv. InventoryMessage inv = new InventoryMessage(unitTestParams); InventoryItem item = new InventoryItem(InventoryItem.Type.Block, b2.getHash()); inv.addItem(item); inbound(writeTarget, inv); // Peer does nothing with it. assertNull(outbound(writeTarget)); }
@Test public void getBlock() throws Exception { connect(); Block b1 = createFakeBlock(blockStore).block; blockChain.add(b1); Block b2 = makeSolvedTestBlock(b1); Block b3 = makeSolvedTestBlock(b2); // Request the block. Future<Block> resultFuture = peer.getBlock(b3.getHash()); assertFalse(resultFuture.isDone()); // Peer asks for it. GetDataMessage message = (GetDataMessage) outbound(writeTarget); assertEquals(message.getItems().get(0).hash, b3.getHash()); assertFalse(resultFuture.isDone()); // Peer receives it. inbound(writeTarget, b3); Block b = resultFuture.get(); assertEquals(b, b3); }
@Test public void testWhile() { // if it == 0 return 1 args.set("it", 5); Expr expr = new MathExpr(MathExpr.Operation.GT, ValueExpr.createVar("it"), ValueExpr.createValue(0)); mainBlock.addSimpleAssign("total", 0); Block block = new Block(); // subtract 1 from it MathExpr decrementIt = new MathExpr(MathExpr.Operation.SUB, ValueExpr.createVar("it"), ValueExpr.createValue(1)); block.addStatement(new Assignment("it", decrementIt)); // add 2 to total MathExpr addTwoToTotal = new MathExpr( MathExpr.Operation.ADD, ValueExpr.createVar("total"), ValueExpr.createValue(2)); block.addStatement(new Assignment("total", addTwoToTotal)); mainBlock.addStatement(new WhileStatement(expr, block)); mainBlock.addReturnVar("total"); int result = runMain(); assertEquals(10, result); }
@Test public void getLargeBlock() throws Exception { connect(); Block b1 = createFakeBlock(blockStore).block; blockChain.add(b1); Block b2 = makeSolvedTestBlock(b1); Transaction t = new Transaction(unitTestParams); t.addInput(b1.getTransactions().get(0).getOutput(0)); t.addOutput( new TransactionOutput( unitTestParams, t, BigInteger.ZERO, new byte[Block.MAX_BLOCK_SIZE - 1000])); b2.addTransaction(t); // Request the block. Future<Block> resultFuture = peer.getBlock(b2.getHash()); assertFalse(resultFuture.isDone()); // Peer asks for it. GetDataMessage message = (GetDataMessage) outbound(writeTarget); assertEquals(message.getItems().get(0).hash, b2.getHash()); assertFalse(resultFuture.isDone()); // Peer receives it. inbound(writeTarget, b2); Block b = resultFuture.get(); assertEquals(b, b2); }
@Test public void testSimpleMath2() { // 2 * 3 * 2 Expr two = ValueExpr.createValue(2); Expr three = ValueExpr.createValue(3); Expr multExpr = new MathExpr(MathExpr.Operation.MULT, two, three); Expr expr = new MathExpr(MathExpr.Operation.MULT, multExpr, two); mainBlock.addStatement(new ReturnStatement(expr)); int result = runMain(); assertEquals(12, result); }
@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); Transaction coinbase = b.getTransactions().get(0); assertTrue(coinbase.isCoinBase()); BlockChain chain = new BlockChain(params, myWallet, new MemoryBlockStore(params)); assertTrue(chain.add(b)); // Wallet now has a coinbase tx in it. assertEquals(1, myWallet.getTransactions(true).size()); assertTrue(myWallet.getTransaction(coinbase.getHash()).isCoinBase()); Wallet wallet2 = roundTrip(myWallet); assertEquals(1, wallet2.getTransactions(true).size()); assertTrue(wallet2.getTransaction(coinbase.getHash()).isCoinBase()); }
// Check that an inventory tickle is processed correctly when downloading missing blocks is // active. @Test public void invTickle() throws Exception { connect(); Block b1 = createFakeBlock(blockStore).block; blockChain.add(b1); // Make a missing block. Block b2 = makeSolvedTestBlock(b1); Block b3 = makeSolvedTestBlock(b2); inbound(writeTarget, b3); InventoryMessage inv = new InventoryMessage(unitTestParams); InventoryItem item = new InventoryItem(InventoryItem.Type.Block, b3.getHash()); inv.addItem(item); inbound(writeTarget, inv); GetBlocksMessage getblocks = (GetBlocksMessage) outbound(writeTarget); List<Sha256Hash> expectedLocator = new ArrayList<Sha256Hash>(); expectedLocator.add(b1.getHash()); expectedLocator.add(unitTestParams.getGenesisBlock().getHash()); assertEquals(getblocks.getLocator(), expectedLocator); assertEquals(getblocks.getStopHash(), b3.getHash()); assertNull(outbound(writeTarget)); }
@Test public void testGetOpenTransactionOutputs() throws Exception { final int UNDOABLE_BLOCKS_STORED = 10; store = createStore(params, UNDOABLE_BLOCKS_STORED); chain = new FullPrunedBlockChain(params, store); // Check that we aren't accidentally leaving any references // to the full StoredUndoableBlock's lying around (ie memory leaks) ECKey outKey = new ECKey(); int height = 1; // Build some blocks on genesis block to create a spendable output Block rollingBlock = params .getGenesisBlock() .createNextBlockWithCoinbase(Block.BLOCK_VERSION_GENESIS, outKey.getPubKey(), height++); chain.add(rollingBlock); Transaction transaction = rollingBlock.getTransactions().get(0); TransactionOutPoint spendableOutput = new TransactionOutPoint(params, 0, transaction.getHash()); byte[] spendableOutputScriptPubKey = transaction.getOutputs().get(0).getScriptBytes(); for (int i = 1; i < params.getSpendableCoinbaseDepth(); i++) { rollingBlock = rollingBlock.createNextBlockWithCoinbase( Block.BLOCK_VERSION_GENESIS, outKey.getPubKey(), height++); chain.add(rollingBlock); } rollingBlock = rollingBlock.createNextBlock(null); // Create bitcoin spend of 1 BTC. ECKey toKey = new ECKey(); Coin amount = Coin.valueOf(100000000); Address address = new Address(params, toKey.getPubKeyHash()); Coin totalAmount = Coin.ZERO; Transaction t = new Transaction(params); t.addOutput(new TransactionOutput(params, t, amount, toKey)); t.addSignedInput(spendableOutput, new Script(spendableOutputScriptPubKey), outKey); rollingBlock.addTransaction(t); rollingBlock.solve(); chain.add(rollingBlock); totalAmount = totalAmount.add(amount); List<UTXO> outputs = store.getOpenTransactionOutputs(Lists.newArrayList(address)); assertNotNull(outputs); assertEquals("Wrong Number of Outputs", 1, outputs.size()); UTXO output = outputs.get(0); assertEquals("The address is not equal", address.toString(), output.getAddress()); assertEquals("The amount is not equal", totalAmount, output.getValue()); outputs = null; output = null; try { store.close(); } catch (Exception e) { } }