method2testcases
stringlengths
118
6.63k
### Question: FamilyUtils { public static List<BlockHeader> getUnclesHeaders(BlockStore store, Block block, int levels) { return getUnclesHeaders(store, block.getNumber(), block.getParentHash(), levels); } static Set<Keccak256> getAncestors(BlockStore blockStore, Block block, int limitNum); static Set<Keccak256> getAncestors(BlockStore blockStore, long blockNumber, Keccak256 parentHash, int limitNum); static Set<Keccak256> getUsedUncles(BlockStore blockStore, Block block, int limitNum); static Set<Keccak256> getUsedUncles(BlockStore blockStore, long blockNumber, Keccak256 parentHash, int limitNum); static List<BlockHeader> getUnclesHeaders(BlockStore store, Block block, int levels); static List<BlockHeader> getUnclesHeaders(@Nonnull BlockStore store, long blockNumber, Keccak256 parentHash, int levels); static Set<Keccak256> getUncles(BlockStore store, Block block, int levels); static Set<Keccak256> getUncles(BlockStore store, long blockNumber, Keccak256 parentHash, int levels); static Set<Keccak256> getFamily(BlockStore store, Block block, int levels); static Set<Keccak256> getFamily(BlockStore store, long blockNumber, Keccak256 parentHash, int levels); }### Answer: @Test public void getUnclesHeaders() { BlockStore store = createBlockStore(); BlockGenerator blockGenerator = new BlockGenerator(); Block genesis = blockGenerator.getGenesisBlock(); Block block1 = blockGenerator.createChildBlock(genesis); Block uncle11 = blockGenerator.createChildBlock(genesis); Block uncle111 = blockGenerator.createChildBlock(uncle11); Block uncle12 = blockGenerator.createChildBlock(genesis); Block uncle121 = blockGenerator.createChildBlock(uncle12); Block block2 = blockGenerator.createChildBlock(block1); Block uncle21 = blockGenerator.createChildBlock(block1); Block uncle22 = blockGenerator.createChildBlock(block1); Block block3 = blockGenerator.createChildBlock(block2); Block uncle31 = blockGenerator.createChildBlock(block2); Block uncle32 = blockGenerator.createChildBlock(block2); store.saveBlock(genesis, TEST_DIFFICULTY, true); store.saveBlock(block1, TEST_DIFFICULTY, true); store.saveBlock(uncle11, TEST_DIFFICULTY, false); store.saveBlock(uncle12, TEST_DIFFICULTY, false); store.saveBlock(uncle111, TEST_DIFFICULTY, false); store.saveBlock(uncle121, TEST_DIFFICULTY, false); store.saveBlock(block2, TEST_DIFFICULTY, true); store.saveBlock(uncle21, TEST_DIFFICULTY, false); store.saveBlock(uncle22, TEST_DIFFICULTY, false); store.saveBlock(block3, TEST_DIFFICULTY, true); store.saveBlock(uncle31, TEST_DIFFICULTY, false); store.saveBlock(uncle32, TEST_DIFFICULTY, false); List<BlockHeader> list = FamilyUtils.getUnclesHeaders(store, block3, 3); Assert.assertNotNull(list); Assert.assertFalse(list.isEmpty()); Assert.assertEquals(4, list.size()); Assert.assertTrue(containsHash(uncle11.getHash(), list)); Assert.assertTrue(containsHash(uncle12.getHash(), list)); Assert.assertTrue(containsHash(uncle21.getHash(), list)); Assert.assertTrue(containsHash(uncle22.getHash(), list)); }
### Question: FamilyUtils { public static Set<Keccak256> getUncles(BlockStore store, Block block, int levels) { return getUncles(store, block.getNumber(), block.getParentHash(), levels); } static Set<Keccak256> getAncestors(BlockStore blockStore, Block block, int limitNum); static Set<Keccak256> getAncestors(BlockStore blockStore, long blockNumber, Keccak256 parentHash, int limitNum); static Set<Keccak256> getUsedUncles(BlockStore blockStore, Block block, int limitNum); static Set<Keccak256> getUsedUncles(BlockStore blockStore, long blockNumber, Keccak256 parentHash, int limitNum); static List<BlockHeader> getUnclesHeaders(BlockStore store, Block block, int levels); static List<BlockHeader> getUnclesHeaders(@Nonnull BlockStore store, long blockNumber, Keccak256 parentHash, int levels); static Set<Keccak256> getUncles(BlockStore store, Block block, int levels); static Set<Keccak256> getUncles(BlockStore store, long blockNumber, Keccak256 parentHash, int levels); static Set<Keccak256> getFamily(BlockStore store, Block block, int levels); static Set<Keccak256> getFamily(BlockStore store, long blockNumber, Keccak256 parentHash, int levels); }### Answer: @Test public void getUncles() { BlockStore store = createBlockStore(); BlockGenerator blockGenerator = new BlockGenerator(); Block genesis = blockGenerator.getGenesisBlock(); Block block1 = blockGenerator.createChildBlock(genesis); Block uncle11 = blockGenerator.createChildBlock(genesis); Block uncle12 = blockGenerator.createChildBlock(genesis); Block block2 = blockGenerator.createChildBlock(block1); Block uncle21 = blockGenerator.createChildBlock(block1); Block uncle22 = blockGenerator.createChildBlock(block1); Block block3 = blockGenerator.createChildBlock(block2); Block uncle31 = blockGenerator.createChildBlock(block2); Block uncle32 = blockGenerator.createChildBlock(block2); store.saveBlock(genesis, TEST_DIFFICULTY, true); store.saveBlock(block1, TEST_DIFFICULTY, true); store.saveBlock(uncle11, TEST_DIFFICULTY, false); store.saveBlock(uncle12, TEST_DIFFICULTY, false); store.saveBlock(block2, TEST_DIFFICULTY, true); store.saveBlock(uncle21, TEST_DIFFICULTY, false); store.saveBlock(uncle22, TEST_DIFFICULTY, false); store.saveBlock(block3, TEST_DIFFICULTY, true); store.saveBlock(uncle31, TEST_DIFFICULTY, false); store.saveBlock(uncle32, TEST_DIFFICULTY, false); Set<Keccak256> family = FamilyUtils.getUncles(store, block3, 3); Assert.assertNotNull(family); Assert.assertFalse(family.isEmpty()); Assert.assertEquals(4, family.size()); Assert.assertFalse(family.contains(genesis.getHash())); Assert.assertFalse(family.contains(block1.getHash())); Assert.assertTrue(family.contains(uncle11.getHash())); Assert.assertTrue(family.contains(uncle12.getHash())); Assert.assertFalse(family.contains(block2.getHash())); Assert.assertTrue(family.contains(uncle21.getHash())); Assert.assertTrue(family.contains(uncle22.getHash())); Assert.assertFalse(family.contains(block3.getHash())); Assert.assertFalse(family.contains(uncle31.getHash())); Assert.assertFalse(family.contains(uncle32.getHash())); }
### Question: GarbageCollector implements InternalService { private void collect(long untilBlock) { BlockHeader untilHeader = blockStore.getChainBlockByNumber(untilBlock).getHeader(); multiTrieStore.collect(repositoryLocator.snapshotAt(untilHeader).getRoot()); } GarbageCollector(CompositeEthereumListener emitter, int blocksPerEpoch, int numberOfEpochs, MultiTrieStore multiTrieStore, BlockStore blockStore, RepositoryLocator repositoryLocator); @Override void start(); @Override void stop(); }### Answer: @Test public void collectsOnBlocksPerEpochModulo() { for (int i = 100; i < 105; i++) { Block block = block(i); listener.onBestBlock(block, null); } verify(multiTrieStore, never()).collect(any()); byte[] stateRoot = new byte[] {0x42, 0x43, 0x02}; withSnapshotStateRootAtBlockNumber(85, stateRoot); Block block = block(105); listener.onBestBlock(block, null); verify(multiTrieStore).collect(stateRoot); } @Test public void collectsOnBlocksPerEpochModuloAndMinimumOfStatesToKeep() { for (int i = 0; i < 21; i++) { Block block = block(i); listener.onBestBlock(block, null); } verify(multiTrieStore, never()).collect(any()); byte[] stateRoot = new byte[] {0x42, 0x43, 0x02}; withSnapshotStateRootAtBlockNumber(1, stateRoot); Block block = block(21); listener.onBestBlock(block, null); verify(multiTrieStore).collect(stateRoot); }
### Question: RLP { public static byte[] encodeLength(int length, int offset) { if (length < SIZE_THRESHOLD) { byte firstByte = (byte) (length + offset); return new byte[]{firstByte}; } else if (length < MAX_ITEM_LENGTH) { byte[] binaryLength; if (length > 0xFF) { binaryLength = intToBytesNoLeadZeroes(length); } else { binaryLength = new byte[]{(byte) length}; } byte firstByte = (byte) (binaryLength.length + offset + SIZE_THRESHOLD - 1); return concatenate(new byte[]{firstByte}, binaryLength); } else { throw new RuntimeException("Input too long"); } } static int decodeInt(byte[] data, int index); static BigInteger decodeBigInteger(byte[] data, int index); static byte[] decodeIP4Bytes(byte[] data, int index); static int getFirstListElement(byte[] payload, int pos); static int getNextElementIndex(byte[] payload, int pos); static void fullTraverse(byte[] msgData, int level, int startPos, int endPos, int levelToIndex, Queue<Integer> index); @Nonnull static ArrayList<RLPElement> decode2(@CheckForNull byte[] msgData); static RLPElement decodeFirstElement(@CheckForNull byte[] msgData, int position); static RLPList decodeList(byte[] msgData); @Nullable static RLPElement decode2OneItem(@CheckForNull byte[] msgData, int startPos); @Nonnull static RskAddress parseRskAddress(@Nullable byte[] bytes); @Nonnull static Coin parseCoin(@Nullable byte[] bytes); @Nullable static Coin parseCoinNonNullZero(byte[] bytes); @Nullable static Coin parseSignedCoinNonNullZero(byte[] bytes); static Coin parseCoinNullZero(@Nullable byte[] bytes); @Nullable static BlockDifficulty parseBlockDifficulty(@Nullable byte[] bytes); static byte[] encode(Object input); static byte[] encodeLength(int length, int offset); static byte[] encodeByte(byte singleByte); static byte[] encodeShort(short singleShort); static byte[] encodeInt(int singleInt); static byte[] encodeString(String srcString); static byte[] encodeBigInteger(BigInteger srcBigInteger); static byte[] encodeRskAddress(RskAddress addr); static byte[] encodeCoin(@Nullable Coin coin); static byte[] encodeCoinNonNullZero(@CheckForNull Coin coin); static byte[] encodeSignedCoinNonNullZero(@CheckForNull Coin coin); static byte[] encodeCoinNullZero(Coin coin); static byte[] encodeBlockDifficulty(BlockDifficulty difficulty); static byte[] encodeElement(@Nullable byte[] srcData); static byte[] encodeListHeader(int size); static byte[] encodeSet(Set<ByteArrayWrapper> data); static byte[] encodeList(byte[]... elements); static byte[] encodedEmptyList(); static byte[] encodedEmptyByteArray(); }### Answer: @Test public void testEncodeLength() { int length = 1; int offset = 128; byte[] encodedLength = encodeLength(length, offset); String expected = "81"; assertEquals(expected, ByteUtil.toHexString(encodedLength)); length = 56; offset = 192; encodedLength = encodeLength(length, offset); expected = "f838"; assertEquals(expected, ByteUtil.toHexString(encodedLength)); } @Test @Ignore public void unsupportedLength() { int length = 56; int offset = 192; byte[] encodedLength; double maxLength = Math.pow(256, 8); try { encodedLength = encodeLength((int) maxLength, offset); System.out.println("length: " + length + ", offset: " + offset + ", encoded: " + Arrays.toString(encodedLength)); fail("Expecting RuntimeException: 'Input too long'"); } catch (RuntimeException e) { } }
### Question: BlockExecutor { @VisibleForTesting public BlockResult execute(Block block, BlockHeader parent, boolean discardInvalidTxs) { return execute(block, parent, discardInvalidTxs, false); } BlockExecutor( ActivationConfig activationConfig, RepositoryLocator repositoryLocator, StateRootHandler stateRootHandler, TransactionExecutorFactory transactionExecutorFactory); BlockResult executeAndFill(Block block, BlockHeader parent); @VisibleForTesting void executeAndFillAll(Block block, BlockHeader parent); @VisibleForTesting void executeAndFillReal(Block block, BlockHeader parent); @VisibleForTesting boolean executeAndValidate(Block block, BlockHeader parent); boolean validate(Block block, BlockResult result); @VisibleForTesting BlockResult execute(Block block, BlockHeader parent, boolean discardInvalidTxs); BlockResult execute(Block block, BlockHeader parent, boolean discardInvalidTxs, boolean ignoreReadyToExecute); void traceBlock( ProgramTraceProcessor programTraceProcessor, int vmTraceOptions, Block block, BlockHeader parent, boolean discardInvalidTxs, boolean ignoreReadyToExecute); static void maintainPrecompiledContractStorageRoots(Repository track, ActivationConfig.ForBlock activations); @VisibleForTesting static byte[] calculateLogsBloom(List<TransactionReceipt> receipts); }### Answer: @Test public void executeBlockWithoutTransaction() { Block parent = blockchain.getBestBlock(); Block block = new BlockGenerator().createChildBlock(parent); BlockResult result = executor.execute(block, parent.getHeader(), false); Assert.assertNotNull(result); Assert.assertNotNull(result.getTransactionReceipts()); Assert.assertTrue(result.getTransactionReceipts().isEmpty()); Assert.assertArrayEquals(repository.getRoot(), parent.getStateRoot()); Assert.assertArrayEquals(repository.getRoot(), result.getFinalState().getHash().getBytes()); } @Test public void executeBlockWithTxThatMakesBlockInvalidSenderHasNoBalance() { TrieStore trieStore = new TrieStoreImpl(new HashMapDB()); Repository repository = new MutableRepository(new MutableTrieImpl(trieStore, new Trie(trieStore))); Repository track = repository.startTracking(); Account account = createAccount("acctest1", track, Coin.valueOf(30000)); Account account2 = createAccount("acctest2", track, Coin.valueOf(10L)); Account account3 = createAccount("acctest3", track, Coin.ZERO); track.commit(); Assert.assertFalse(Arrays.equals(EMPTY_TRIE_HASH, repository.getRoot())); BlockExecutor executor = buildBlockExecutor(trieStore); Transaction tx = createTransaction( account, account2, BigInteger.TEN, repository.getNonce(account.getAddress()) ); Transaction tx2 = createTransaction( account3, account2, BigInteger.TEN, repository.getNonce(account3.getAddress()) ); List<Transaction> txs = new ArrayList<>(); txs.add(tx); txs.add(tx2); List<BlockHeader> uncles = new ArrayList<>(); BlockGenerator blockGenerator = new BlockGenerator(); Block genesis = blockGenerator.getGenesisBlock(); genesis.setStateRoot(repository.getRoot()); Block block = blockGenerator.createChildBlock(genesis, txs, uncles, 1, null); BlockResult result = executor.execute(block, genesis.getHeader(), false); Assert.assertSame(BlockResult.INTERRUPTED_EXECUTION_BLOCK_RESULT, result); }
### Question: BlockExecutor { public BlockResult executeAndFill(Block block, BlockHeader parent) { BlockResult result = execute(block, parent, true, false); fill(block, result); return result; } BlockExecutor( ActivationConfig activationConfig, RepositoryLocator repositoryLocator, StateRootHandler stateRootHandler, TransactionExecutorFactory transactionExecutorFactory); BlockResult executeAndFill(Block block, BlockHeader parent); @VisibleForTesting void executeAndFillAll(Block block, BlockHeader parent); @VisibleForTesting void executeAndFillReal(Block block, BlockHeader parent); @VisibleForTesting boolean executeAndValidate(Block block, BlockHeader parent); boolean validate(Block block, BlockResult result); @VisibleForTesting BlockResult execute(Block block, BlockHeader parent, boolean discardInvalidTxs); BlockResult execute(Block block, BlockHeader parent, boolean discardInvalidTxs, boolean ignoreReadyToExecute); void traceBlock( ProgramTraceProcessor programTraceProcessor, int vmTraceOptions, Block block, BlockHeader parent, boolean discardInvalidTxs, boolean ignoreReadyToExecute); static void maintainPrecompiledContractStorageRoots(Repository track, ActivationConfig.ForBlock activations); @VisibleForTesting static byte[] calculateLogsBloom(List<TransactionReceipt> receipts); }### Answer: @Test public void executeAndFillBlockWithTxToExcludeBecauseSenderHasNoBalance() { TrieStore trieStore = new TrieStoreImpl(new HashMapDB()); Repository repository = new MutableRepository(new MutableTrieImpl(trieStore, new Trie(trieStore))); Repository track = repository.startTracking(); Account account = createAccount("acctest1", track, Coin.valueOf(30000)); Account account2 = createAccount("acctest2", track, Coin.valueOf(10L)); Account account3 = createAccount("acctest3", track, Coin.ZERO); track.commit(); Assert.assertFalse(Arrays.equals(EMPTY_TRIE_HASH, repository.getRoot())); BlockExecutor executor = buildBlockExecutor(trieStore); Transaction tx = createTransaction( account, account2, BigInteger.TEN, repository.getNonce(account.getAddress()) ); Transaction tx2 = createTransaction( account3, account2, BigInteger.TEN, repository.getNonce(account3.getAddress()) ); List<Transaction> txs = new ArrayList<>(); txs.add(tx); txs.add(tx2); List<BlockHeader> uncles = new ArrayList<>(); BlockGenerator blockGenerator = new BlockGenerator(); Block genesis = blockGenerator.getGenesisBlock(); genesis.setStateRoot(repository.getRoot()); Block block = blockGenerator.createChildBlock(genesis, txs, uncles, 1, null); executor.executeAndFill(block, genesis.getHeader()); Assert.assertEquals(1, block.getTransactionsList().size()); Assert.assertEquals(tx, block.getTransactionsList().get(0)); Assert.assertArrayEquals( calculateTxTrieRoot(Collections.singletonList(tx), block.getNumber()), block.getTxTrieRoot() ); Assert.assertEquals(3141592, new BigInteger(1, block.getGasLimit()).longValue()); }
### Question: BlockExecutor { @VisibleForTesting public boolean executeAndValidate(Block block, BlockHeader parent) { BlockResult result = execute(block, parent, false, false); return this.validate(block, result); } BlockExecutor( ActivationConfig activationConfig, RepositoryLocator repositoryLocator, StateRootHandler stateRootHandler, TransactionExecutorFactory transactionExecutorFactory); BlockResult executeAndFill(Block block, BlockHeader parent); @VisibleForTesting void executeAndFillAll(Block block, BlockHeader parent); @VisibleForTesting void executeAndFillReal(Block block, BlockHeader parent); @VisibleForTesting boolean executeAndValidate(Block block, BlockHeader parent); boolean validate(Block block, BlockResult result); @VisibleForTesting BlockResult execute(Block block, BlockHeader parent, boolean discardInvalidTxs); BlockResult execute(Block block, BlockHeader parent, boolean discardInvalidTxs, boolean ignoreReadyToExecute); void traceBlock( ProgramTraceProcessor programTraceProcessor, int vmTraceOptions, Block block, BlockHeader parent, boolean discardInvalidTxs, boolean ignoreReadyToExecute); static void maintainPrecompiledContractStorageRoots(Repository track, ActivationConfig.ForBlock activations); @VisibleForTesting static byte[] calculateLogsBloom(List<TransactionReceipt> receipts); }### Answer: @Test public void validateBlock() { TestObjects objects = generateBlockWithOneTransaction(); Block parent = objects.getParent(); Block block = objects.getBlock(); BlockExecutor executor = buildBlockExecutor(objects.getTrieStore()); Assert.assertTrue(executor.executeAndValidate(block, parent.getHeader())); } @Test public void invalidBlockBadStateRoot() { TestObjects objects = generateBlockWithOneTransaction(); Block parent = objects.getParent(); Block block = objects.getBlock(); BlockExecutor executor = buildBlockExecutor(objects.getTrieStore()); byte[] stateRoot = block.getStateRoot(); stateRoot[0] = (byte) ((stateRoot[0] + 1) % 256); Assert.assertFalse(executor.executeAndValidate(block, parent.getHeader())); } @Test public void invalidBlockBadReceiptsRoot() { TestObjects objects = generateBlockWithOneTransaction(); Block parent = objects.getParent(); Block block = objects.getBlock(); BlockExecutor executor = buildBlockExecutor(objects.getTrieStore()); byte[] receiptsRoot = block.getReceiptsRoot(); receiptsRoot[0] = (byte) ((receiptsRoot[0] + 1) % 256); Assert.assertFalse(executor.executeAndValidate(block, parent.getHeader())); } @Test public void invalidBlockBadGasUsed() { TestObjects objects = generateBlockWithOneTransaction(); Block parent = objects.getParent(); Block block = objects.getBlock(); BlockExecutor executor = buildBlockExecutor(objects.getTrieStore()); block.getHeader().setGasUsed(0); Assert.assertFalse(executor.executeAndValidate(block, parent.getHeader())); } @Test public void invalidBlockBadPaidFees() { TestObjects objects = generateBlockWithOneTransaction(); Block parent = objects.getParent(); Block block = objects.getBlock(); BlockExecutor executor = buildBlockExecutor(objects.getTrieStore()); block.getHeader().setPaidFees(Coin.ZERO); Assert.assertFalse(executor.executeAndValidate(block, parent.getHeader())); } @Test public void invalidBlockBadLogsBloom() { TestObjects objects = generateBlockWithOneTransaction(); Block parent = objects.getParent(); Block block = objects.getBlock(); BlockExecutor executor = buildBlockExecutor(objects.getTrieStore()); byte[] logBloom = block.getLogBloom(); logBloom[0] = (byte) ((logBloom[0] + 1) % 256); Assert.assertFalse(executor.executeAndValidate(block, parent.getHeader())); }
### Question: BlockChainImpl implements Blockchain { private void onBestBlock(Block block, BlockResult result) { if (result != null && listener != null){ listener.onBestBlock(block, result.getTransactionReceipts()); } } BlockChainImpl(BlockStore blockStore, ReceiptStore receiptStore, TransactionPool transactionPool, EthereumListener listener, BlockValidator blockValidator, BlockExecutor blockExecutor, StateRootHandler stateRootHandler); @VisibleForTesting void setBlockValidator(BlockValidator validator); @Override long getSize(); @Override ImportResult tryToConnect(Block block); @Override BlockChainStatus getStatus(); @Override void setStatus(Block block, BlockDifficulty totalDifficulty); @Override Block getBlockByHash(byte[] hash); @Override List<Block> getBlocksByNumber(long number); @Override List<BlockInformation> getBlocksInformationByNumber(long number); @Override boolean hasBlockInSomeBlockchain(@Nonnull final byte[] hash); @Override void removeBlocksByNumber(long number); @Override Block getBlockByNumber(long number); @Override Block getBestBlock(); void setNoValidation(boolean noValidation); @Override TransactionInfo getTransactionInfo(byte[] hash); @Override BlockDifficulty getTotalDifficulty(); @Override @VisibleForTesting byte[] getBestBlockHash(); }### Answer: @Test public void onBestBlockTest() { Block genesis = blockChain.getBestBlock(); BlockGenerator blockGenerator = new BlockGenerator(); Block block1 = blockGenerator.createChildBlock(genesis,0,2l); Block block1b = blockGenerator.createChildBlock(genesis,0,1l); Assert.assertEquals(ImportResult.IMPORTED_BEST, blockChain.tryToConnect(block1)); Assert.assertEquals(block1.getHash(), listener.getBestBlock().getHash()); Assert.assertEquals(listener.getBestBlock().getHash(), listener.getLatestBlock().getHash()); Assert.assertEquals(ImportResult.IMPORTED_NOT_BEST, blockChain.tryToConnect(block1b)); Assert.assertNotEquals(listener.getBestBlock().getHash(), listener.getLatestBlock().getHash()); Assert.assertEquals(block1.getHash(), listener.getBestBlock().getHash()); Assert.assertEquals(block1b.getHash(), listener.getLatestBlock().getHash()); }
### Question: BlockChainImpl implements Blockchain { @Override public ImportResult tryToConnect(Block block) { this.lock.readLock().lock(); try { if (block == null) { return ImportResult.INVALID_BLOCK; } if (!block.isSealed()) { panicProcessor.panic("unsealedblock", String.format("Unsealed block %s %s", block.getNumber(), block.getHash())); block.seal(); } try { org.slf4j.MDC.put("blockHash", block.getHash().toHexString()); org.slf4j.MDC.put("blockHeight", Long.toString(block.getNumber())); logger.trace("Try connect block hash: {}, number: {}", block.getPrintableHash(), block.getNumber()); synchronized (connectLock) { logger.trace("Start try connect"); long saveTime = System.nanoTime(); ImportResult result = internalTryToConnect(block); long totalTime = System.nanoTime() - saveTime; String timeInSeconds = FormatUtils.formatNanosecondsToSeconds(totalTime); if (BlockUtils.tooMuchProcessTime(totalTime)) { logger.warn("block: num: [{}] hash: [{}], processed after: [{}]seconds, result {}", block.getNumber(), block.getPrintableHash(), timeInSeconds, result); } else { logger.info("block: num: [{}] hash: [{}], processed after: [{}]seconds, result {}", block.getNumber(), block.getPrintableHash(), timeInSeconds, result); } return result; } } catch (Throwable t) { logger.error("Unexpected error: ", t); return ImportResult.INVALID_BLOCK; } finally { org.slf4j.MDC.remove("blockHash"); org.slf4j.MDC.remove("blockHeight"); } } finally { this.lock.readLock().unlock(); } } BlockChainImpl(BlockStore blockStore, ReceiptStore receiptStore, TransactionPool transactionPool, EthereumListener listener, BlockValidator blockValidator, BlockExecutor blockExecutor, StateRootHandler stateRootHandler); @VisibleForTesting void setBlockValidator(BlockValidator validator); @Override long getSize(); @Override ImportResult tryToConnect(Block block); @Override BlockChainStatus getStatus(); @Override void setStatus(Block block, BlockDifficulty totalDifficulty); @Override Block getBlockByHash(byte[] hash); @Override List<Block> getBlocksByNumber(long number); @Override List<BlockInformation> getBlocksInformationByNumber(long number); @Override boolean hasBlockInSomeBlockchain(@Nonnull final byte[] hash); @Override void removeBlocksByNumber(long number); @Override Block getBlockByNumber(long number); @Override Block getBestBlock(); void setNoValidation(boolean noValidation); @Override TransactionInfo getTransactionInfo(byte[] hash); @Override BlockDifficulty getTotalDifficulty(); @Override @VisibleForTesting byte[] getBestBlockHash(); }### Answer: @Test public void nullBlockAsInvalidBlock() { Assert.assertEquals(ImportResult.INVALID_BLOCK, blockChain.tryToConnect(null)); }
### Question: BlockChainImpl implements Blockchain { @Override public List<Block> getBlocksByNumber(long number) { return blockStore.getChainBlocksByNumber(number); } BlockChainImpl(BlockStore blockStore, ReceiptStore receiptStore, TransactionPool transactionPool, EthereumListener listener, BlockValidator blockValidator, BlockExecutor blockExecutor, StateRootHandler stateRootHandler); @VisibleForTesting void setBlockValidator(BlockValidator validator); @Override long getSize(); @Override ImportResult tryToConnect(Block block); @Override BlockChainStatus getStatus(); @Override void setStatus(Block block, BlockDifficulty totalDifficulty); @Override Block getBlockByHash(byte[] hash); @Override List<Block> getBlocksByNumber(long number); @Override List<BlockInformation> getBlocksInformationByNumber(long number); @Override boolean hasBlockInSomeBlockchain(@Nonnull final byte[] hash); @Override void removeBlocksByNumber(long number); @Override Block getBlockByNumber(long number); @Override Block getBestBlock(); void setNoValidation(boolean noValidation); @Override TransactionInfo getTransactionInfo(byte[] hash); @Override BlockDifficulty getTotalDifficulty(); @Override @VisibleForTesting byte[] getBestBlockHash(); }### Answer: @Test public void getBlocksByNumber() { Block genesis = blockChain.getBestBlock(); BlockGenerator blockGenerator = new BlockGenerator(); Block block1 = blockGenerator.createChildBlock(genesis,0,2); Block block1b = blockGenerator.createChildBlock(genesis,0,1); Assert.assertEquals(ImportResult.IMPORTED_BEST, blockChain.tryToConnect(block1)); Assert.assertEquals(ImportResult.IMPORTED_NOT_BEST, blockChain.tryToConnect(block1b)); List<Block> blocks = blockChain.getBlocksByNumber(1); Assert.assertNotNull(blocks); Assert.assertFalse(blocks.isEmpty()); Assert.assertEquals(2, blocks.size()); Assert.assertEquals(blocks.get(0).getHash(), block1.getHash()); Assert.assertEquals(blocks.get(1).getHash(), block1b.getHash()); blocks = blockChain.getBlocksByNumber(42); Assert.assertNotNull(blocks); Assert.assertTrue(blocks.isEmpty()); }
### Question: BlockChainImpl implements Blockchain { @Override public Block getBlockByNumber(long number) { return blockStore.getChainBlockByNumber(number); } BlockChainImpl(BlockStore blockStore, ReceiptStore receiptStore, TransactionPool transactionPool, EthereumListener listener, BlockValidator blockValidator, BlockExecutor blockExecutor, StateRootHandler stateRootHandler); @VisibleForTesting void setBlockValidator(BlockValidator validator); @Override long getSize(); @Override ImportResult tryToConnect(Block block); @Override BlockChainStatus getStatus(); @Override void setStatus(Block block, BlockDifficulty totalDifficulty); @Override Block getBlockByHash(byte[] hash); @Override List<Block> getBlocksByNumber(long number); @Override List<BlockInformation> getBlocksInformationByNumber(long number); @Override boolean hasBlockInSomeBlockchain(@Nonnull final byte[] hash); @Override void removeBlocksByNumber(long number); @Override Block getBlockByNumber(long number); @Override Block getBestBlock(); void setNoValidation(boolean noValidation); @Override TransactionInfo getTransactionInfo(byte[] hash); @Override BlockDifficulty getTotalDifficulty(); @Override @VisibleForTesting byte[] getBestBlockHash(); }### Answer: @Test public void getBlockByNumber() { Block genesis = blockChain.getBestBlock(); BlockGenerator blockGenerator = new BlockGenerator(); Block block1 = blockGenerator.createChildBlock(genesis); Block block2 = blockGenerator.createChildBlock(block1); Block block3 = blockGenerator.createChildBlock(block2); Assert.assertEquals(ImportResult.IMPORTED_BEST, blockChain.tryToConnect(block1)); Assert.assertEquals(ImportResult.IMPORTED_BEST, blockChain.tryToConnect(block2)); Assert.assertEquals(ImportResult.IMPORTED_BEST, blockChain.tryToConnect(block3)); Block block = blockChain.getBlockByNumber(0); Assert.assertNotNull(block); Assert.assertEquals(0, block.getNumber()); Assert.assertEquals(genesis.getHash(), block.getHash()); block = blockChain.getBlockByNumber(1); Assert.assertNotNull(block); Assert.assertEquals(1, block.getNumber()); Assert.assertEquals(block1.getHash(), block.getHash()); block = blockChain.getBlockByNumber(2); Assert.assertNotNull(block); Assert.assertEquals(2, block.getNumber()); Assert.assertEquals(block2.getHash(), block.getHash()); block = blockChain.getBlockByNumber(3); Assert.assertNotNull(block); Assert.assertEquals(3, block.getNumber()); Assert.assertEquals(block3.getHash(), block.getHash()); block = blockChain.getBlockByNumber(4); Assert.assertNull(block); }
### Question: BlockChainImpl implements Blockchain { @Override public Block getBestBlock() { return this.status.getBestBlock(); } BlockChainImpl(BlockStore blockStore, ReceiptStore receiptStore, TransactionPool transactionPool, EthereumListener listener, BlockValidator blockValidator, BlockExecutor blockExecutor, StateRootHandler stateRootHandler); @VisibleForTesting void setBlockValidator(BlockValidator validator); @Override long getSize(); @Override ImportResult tryToConnect(Block block); @Override BlockChainStatus getStatus(); @Override void setStatus(Block block, BlockDifficulty totalDifficulty); @Override Block getBlockByHash(byte[] hash); @Override List<Block> getBlocksByNumber(long number); @Override List<BlockInformation> getBlocksInformationByNumber(long number); @Override boolean hasBlockInSomeBlockchain(@Nonnull final byte[] hash); @Override void removeBlocksByNumber(long number); @Override Block getBlockByNumber(long number); @Override Block getBestBlock(); void setNoValidation(boolean noValidation); @Override TransactionInfo getTransactionInfo(byte[] hash); @Override BlockDifficulty getTotalDifficulty(); @Override @VisibleForTesting byte[] getBestBlockHash(); }### Answer: @Test public void switchToOtherChainInvalidBadBlockBadReceiptsRoot() { Block genesis = blockChain.getBestBlock(); BlockGenerator blockGenerator = new BlockGenerator(); Block block1 = blockGenerator.createChildBlock(genesis); Block block1b = blockGenerator.createChildBlock(genesis); if (FastByteComparisons.compareTo(block1.getHash().getBytes(), 0, 32, block1b.getHash().getBytes(), 0, 32) < 0) { switchToOtherChainInvalidBadBlockBadReceiptsRootHelper(blockChain, genesis, block1, block1b); } else { switchToOtherChainInvalidBadBlockBadReceiptsRootHelper(blockChain, genesis, block1b, block1); } } @Test public void validateMinedBlockOne() { Block genesis = blockChain.getBestBlock(); Block block = new BlockGenerator().createChildBlock(genesis); Assert.assertTrue(blockExecutor.executeAndValidate(block, genesis.getHeader())); } @Test public void validateMinedBlockSeven() { Block genesis = blockChain.getBestBlock(); BlockGenerator blockGenerator = new BlockGenerator(); Block block1 = blockGenerator.createChildBlock(genesis); Block block2 = blockGenerator.createChildBlock(block1); Block block3 = blockGenerator.createChildBlock(block2); Block block4 = blockGenerator.createChildBlock(block3); Block block5 = blockGenerator.createChildBlock(block4); Block block6 = blockGenerator.createChildBlock(block5); Block block7 = blockGenerator.createChildBlock(block6); Assert.assertTrue(blockExecutor.executeAndValidate(block1, genesis.getHeader())); Assert.assertTrue(blockExecutor.executeAndValidate(block2, block1.getHeader())); Assert.assertTrue(blockExecutor.executeAndValidate(block3, block2.getHeader())); Assert.assertTrue(blockExecutor.executeAndValidate(block4, block3.getHeader())); Assert.assertTrue(blockExecutor.executeAndValidate(block5, block4.getHeader())); Assert.assertTrue(blockExecutor.executeAndValidate(block6, block5.getHeader())); Assert.assertTrue(blockExecutor.executeAndValidate(block7, block6.getHeader())); }
### Question: BlockChainImpl implements Blockchain { @Override public Block getBlockByHash(byte[] hash) { return blockStore.getBlockByHash(hash); } BlockChainImpl(BlockStore blockStore, ReceiptStore receiptStore, TransactionPool transactionPool, EthereumListener listener, BlockValidator blockValidator, BlockExecutor blockExecutor, StateRootHandler stateRootHandler); @VisibleForTesting void setBlockValidator(BlockValidator validator); @Override long getSize(); @Override ImportResult tryToConnect(Block block); @Override BlockChainStatus getStatus(); @Override void setStatus(Block block, BlockDifficulty totalDifficulty); @Override Block getBlockByHash(byte[] hash); @Override List<Block> getBlocksByNumber(long number); @Override List<BlockInformation> getBlocksInformationByNumber(long number); @Override boolean hasBlockInSomeBlockchain(@Nonnull final byte[] hash); @Override void removeBlocksByNumber(long number); @Override Block getBlockByNumber(long number); @Override Block getBestBlock(); void setNoValidation(boolean noValidation); @Override TransactionInfo getTransactionInfo(byte[] hash); @Override BlockDifficulty getTotalDifficulty(); @Override @VisibleForTesting byte[] getBestBlockHash(); }### Answer: @Test public void getUnknownBlockByHash() { Assert.assertNull(blockChain.getBlockByHash(new BlockGenerator().getBlock(1).getHash().getBytes())); }
### Question: BlockChainImpl implements Blockchain { @Override public TransactionInfo getTransactionInfo(byte[] hash) { TransactionInfo txInfo = receiptStore.get(hash); if (txInfo == null) { return null; } Transaction tx = this.getBlockByHash(txInfo.getBlockHash()).getTransactionsList().get(txInfo.getIndex()); txInfo.setTransaction(tx); return txInfo; } BlockChainImpl(BlockStore blockStore, ReceiptStore receiptStore, TransactionPool transactionPool, EthereumListener listener, BlockValidator blockValidator, BlockExecutor blockExecutor, StateRootHandler stateRootHandler); @VisibleForTesting void setBlockValidator(BlockValidator validator); @Override long getSize(); @Override ImportResult tryToConnect(Block block); @Override BlockChainStatus getStatus(); @Override void setStatus(Block block, BlockDifficulty totalDifficulty); @Override Block getBlockByHash(byte[] hash); @Override List<Block> getBlocksByNumber(long number); @Override List<BlockInformation> getBlocksInformationByNumber(long number); @Override boolean hasBlockInSomeBlockchain(@Nonnull final byte[] hash); @Override void removeBlocksByNumber(long number); @Override Block getBlockByNumber(long number); @Override Block getBestBlock(); void setNoValidation(boolean noValidation); @Override TransactionInfo getTransactionInfo(byte[] hash); @Override BlockDifficulty getTotalDifficulty(); @Override @VisibleForTesting byte[] getBestBlockHash(); }### Answer: @Test public void getUnknownTransactionInfoAsNull() { Assert.assertNull(blockChain.getTransactionInfo(new byte[] { 0x01 })); } @Test public void getTransactionInfo() { Block block = getBlockWithOneTransaction(); Assert.assertEquals(ImportResult.IMPORTED_BEST, blockChain.tryToConnect(block)); Transaction tx = block.getTransactionsList().get(0); Assert.assertNotNull(blockChain.getTransactionInfo(tx.getHash().getBytes())); }
### Question: BlockUtils { public static boolean blockInSomeBlockChain(Block block, Blockchain blockChain) { return blockInSomeBlockChain(block.getHash(), block.getNumber(), blockChain); } private BlockUtils(); static boolean tooMuchProcessTime(long nanoseconds); static boolean blockInSomeBlockChain(Block block, Blockchain blockChain); static Set<Keccak256> unknownDirectAncestorsHashes(Block block, Blockchain blockChain, NetBlockStore store); static Set<Keccak256> unknownAncestorsHashes(Keccak256 blockHash, Blockchain blockChain, NetBlockStore store); static Set<Keccak256> unknownAncestorsHashes(Set<Keccak256> hashesToProcess, Blockchain blockChain, NetBlockStore store, boolean withUncles); static void addBlockToList(List<Block> blocks, Block block); static List<Block> sortBlocksByNumber(List<Block> blocks); }### Answer: @Test public void blockInSomeBlockChain() { BlockChainBuilder blockChainBuilder = new BlockChainBuilder(); BlockChainImpl blockChain = blockChainBuilder.build(); org.ethereum.db.BlockStore blockStore = blockChainBuilder.getBlockStore(); Block genesis = blockChain.getBestBlock(); Block block1 = new BlockBuilder(null, null, null).parent(genesis).build(); Block block1b = new BlockBuilder(null, null, null).parent(genesis).build(); Block block2 = new BlockBuilder(null, null, null).parent(block1).build(); Block block3 = new BlockBuilder(null, null, null).parent(block2).build(); blockStore.saveBlock(block3, new BlockDifficulty(BigInteger.ONE), false); blockChain.tryToConnect(block1); blockChain.tryToConnect(block1b); Assert.assertTrue(BlockUtils.blockInSomeBlockChain(genesis, blockChain)); Assert.assertTrue(BlockUtils.blockInSomeBlockChain(block1, blockChain)); Assert.assertTrue(BlockUtils.blockInSomeBlockChain(block1b, blockChain)); Assert.assertFalse(BlockUtils.blockInSomeBlockChain(block2, blockChain)); Assert.assertTrue(BlockUtils.blockInSomeBlockChain(block3, blockChain)); }
### Question: BlockUtils { public static boolean tooMuchProcessTime(long nanoseconds) { return nanoseconds > MAX_BLOCK_PROCESS_TIME_NANOSECONDS; } private BlockUtils(); static boolean tooMuchProcessTime(long nanoseconds); static boolean blockInSomeBlockChain(Block block, Blockchain blockChain); static Set<Keccak256> unknownDirectAncestorsHashes(Block block, Blockchain blockChain, NetBlockStore store); static Set<Keccak256> unknownAncestorsHashes(Keccak256 blockHash, Blockchain blockChain, NetBlockStore store); static Set<Keccak256> unknownAncestorsHashes(Set<Keccak256> hashesToProcess, Blockchain blockChain, NetBlockStore store, boolean withUncles); static void addBlockToList(List<Block> blocks, Block block); static List<Block> sortBlocksByNumber(List<Block> blocks); }### Answer: @Test public void tooMuchProcessTime() { Assert.assertFalse(BlockUtils.tooMuchProcessTime(0)); Assert.assertFalse(BlockUtils.tooMuchProcessTime(1000)); Assert.assertFalse(BlockUtils.tooMuchProcessTime(1_000_000L)); Assert.assertFalse(BlockUtils.tooMuchProcessTime(1_000_000_000L)); Assert.assertFalse(BlockUtils.tooMuchProcessTime(60_000_000_000L)); Assert.assertTrue(BlockUtils.tooMuchProcessTime(60_000_000_001L)); Assert.assertTrue(BlockUtils.tooMuchProcessTime(1_000_000_000_000L)); }
### Question: TransactionPoolImpl implements TransactionPool { @Override public PendingState getPendingState() { return getPendingState(getCurrentRepository()); } TransactionPoolImpl( RskSystemProperties config, RepositoryLocator repositoryLocator, BlockStore blockStore, BlockFactory blockFactory, EthereumListener listener, TransactionExecutorFactory transactionExecutorFactory, SignatureCache signatureCache, int outdatedThreshold, int outdatedTimeout); @Override void start(); @Override void stop(); boolean hasCleanerFuture(); void cleanUp(); int getOutdatedThreshold(); int getOutdatedTimeout(); Block getBestBlock(); @Override PendingState getPendingState(); @Override synchronized List<Transaction> addTransactions(final List<Transaction> txs); @Override synchronized TransactionPoolAddResult addTransaction(final Transaction tx); @Override synchronized void processBest(Block newBlock); @VisibleForTesting void acceptBlock(Block block); @VisibleForTesting void retractBlock(Block block); @VisibleForTesting void removeObsoleteTransactions(long currentBlock, int depth, int timeout); @VisibleForTesting synchronized void removeObsoleteTransactions(long timeSeconds); @Override synchronized void removeTransactions(List<Transaction> txs); @Override synchronized List<Transaction> getPendingTransactions(); @Override synchronized List<Transaction> getQueuedTransactions(); }### Answer: @Test public void usingAccountsWithInitialBalance() { createTestAccounts(2, Coin.valueOf(10L)); PendingState pendingState = transactionPool.getPendingState(); Assert.assertNotNull(pendingState); Account account1 = createAccount(1); Account account2 = createAccount(2); Assert.assertEquals(BigInteger.TEN, pendingState.getBalance(account1.getAddress()).asBigInteger()); Assert.assertEquals(BigInteger.TEN, pendingState.getBalance(account2.getAddress()).asBigInteger()); }
### Question: TransactionPoolImpl implements TransactionPool { @Override public synchronized List<Transaction> getPendingTransactions() { removeObsoleteTransactions(this.outdatedThreshold, this.outdatedTimeout); return Collections.unmodifiableList(pendingTransactions.getTransactions()); } TransactionPoolImpl( RskSystemProperties config, RepositoryLocator repositoryLocator, BlockStore blockStore, BlockFactory blockFactory, EthereumListener listener, TransactionExecutorFactory transactionExecutorFactory, SignatureCache signatureCache, int outdatedThreshold, int outdatedTimeout); @Override void start(); @Override void stop(); boolean hasCleanerFuture(); void cleanUp(); int getOutdatedThreshold(); int getOutdatedTimeout(); Block getBestBlock(); @Override PendingState getPendingState(); @Override synchronized List<Transaction> addTransactions(final List<Transaction> txs); @Override synchronized TransactionPoolAddResult addTransaction(final Transaction tx); @Override synchronized void processBest(Block newBlock); @VisibleForTesting void acceptBlock(Block block); @VisibleForTesting void retractBlock(Block block); @VisibleForTesting void removeObsoleteTransactions(long currentBlock, int depth, int timeout); @VisibleForTesting synchronized void removeObsoleteTransactions(long timeSeconds); @Override synchronized void removeTransactions(List<Transaction> txs); @Override synchronized List<Transaction> getPendingTransactions(); @Override synchronized List<Transaction> getQueuedTransactions(); }### Answer: @Test public void getEmptyPendingTransactionList() { List<Transaction> transactions = transactionPool.getPendingTransactions(); Assert.assertNotNull(transactions); Assert.assertTrue(transactions.isEmpty()); } @Test public void getEmptyTransactionList() { List<Transaction> transactions = transactionPool.getPendingTransactions(); Assert.assertNotNull(transactions); Assert.assertTrue(transactions.isEmpty()); }
### Question: SelectionRule { public static boolean isThisBlockHashSmaller(byte[] thisBlockHash, byte[] compareBlockHash) { return FastByteComparisons.compareTo( thisBlockHash, BYTE_ARRAY_OFFSET, BYTE_ARRAY_LENGTH, compareBlockHash, BYTE_ARRAY_OFFSET, BYTE_ARRAY_LENGTH) < 0; } static boolean shouldWeAddThisBlock( BlockDifficulty blockDifficulty, BlockDifficulty currentDifficulty, Block block, Block currentBlock); static boolean isBrokenSelectionRule( BlockHeader processingBlockHeader, List<Sibling> siblings); static boolean isThisBlockHashSmaller(byte[] thisBlockHash, byte[] compareBlockHash); }### Answer: @Test public void smallerBlockHashTest() { byte[] lowerHash = new byte[]{0}; byte[] biggerHash = new byte[]{1}; assertTrue(SelectionRule.isThisBlockHashSmaller(lowerHash, biggerHash)); assertFalse(SelectionRule.isThisBlockHashSmaller(biggerHash, lowerHash)); }
### Question: SelectionRule { public static boolean shouldWeAddThisBlock( BlockDifficulty blockDifficulty, BlockDifficulty currentDifficulty, Block block, Block currentBlock) { int compareDifficulties = blockDifficulty.compareTo(currentDifficulty); if (compareDifficulties > 0) { return true; } if (compareDifficulties < 0) { return false; } Coin pfm = currentBlock.getHeader().getPaidFees().multiply(PAID_FEES_MULTIPLIER_CRITERIA); if (block.getHeader().getPaidFees().compareTo(pfm) > 0) { return true; } Coin blockFeesCriteria = block.getHeader().getPaidFees().multiply(PAID_FEES_MULTIPLIER_CRITERIA); return currentBlock.getHeader().getPaidFees().compareTo(blockFeesCriteria) < 0 && isThisBlockHashSmaller(block.getHash().getBytes(), currentBlock.getHash().getBytes()); } static boolean shouldWeAddThisBlock( BlockDifficulty blockDifficulty, BlockDifficulty currentDifficulty, Block block, Block currentBlock); static boolean isBrokenSelectionRule( BlockHeader processingBlockHeader, List<Sibling> siblings); static boolean isThisBlockHashSmaller(byte[] thisBlockHash, byte[] compareBlockHash); }### Answer: @Test public void addBlockTest() { Blockchain blockchain = createBlockchain(); BlockGenerator blockGenerator = new BlockGenerator(); Block lowDifficultyBlock = blockGenerator.createChildBlock(blockchain.getBestBlock(), 0, 1); Block highDifficultyBlock = blockGenerator.createChildBlock(lowDifficultyBlock, 0, 5); Block highDifficultyBlockWithMoreFees = blockGenerator.createChildBlock(lowDifficultyBlock, 10L, new ArrayList<>(), highDifficultyBlock.getDifficulty().getBytes()); assertFalse(SelectionRule.shouldWeAddThisBlock(lowDifficultyBlock.getDifficulty(), highDifficultyBlock.getDifficulty(), lowDifficultyBlock, highDifficultyBlock)); assertTrue(SelectionRule.shouldWeAddThisBlock(highDifficultyBlock.getDifficulty(), lowDifficultyBlock.getDifficulty(), highDifficultyBlock, lowDifficultyBlock)); assertTrue(SelectionRule.shouldWeAddThisBlock(highDifficultyBlockWithMoreFees.getDifficulty(), highDifficultyBlock.getDifficulty(), highDifficultyBlockWithMoreFees, highDifficultyBlock)); }
### Question: BlockChainFlusher implements InternalService { private void flush() { if (nFlush == 0) { flushAll(); } nFlush++; nFlush = nFlush % flushNumberOfBlocks; } BlockChainFlusher( int flushNumberOfBlocks, CompositeEthereumListener emitter, TrieStore trieStore, BlockStore blockStore, ReceiptStore receiptStore); @Override void start(); @Override void stop(); }### Answer: @Test public void flushesAfterNInvocations() { for (int i = 0; i < 6; i++) { listener.onBestBlock(null, null); } verify(trieStore, never()).flush(); verify(blockStore, never()).flush(); verify(receiptStore, never()).flush(); listener.onBestBlock(null, null); verify(trieStore).flush(); verify(blockStore).flush(); verify(receiptStore).flush(); }
### Question: MiningMainchainViewImpl implements MiningMainchainView { @Override public List<BlockHeader> get() { synchronized (internalBlockStoreReadWriteLock) { return Collections.unmodifiableList(mainchain); } } MiningMainchainViewImpl(BlockStore blockStore, int height); void addBest(BlockHeader bestHeader); @Override List<BlockHeader> get(); }### Answer: @Test public void creationIsCorrect() { BlockStore blockStore = createBlockStore(3); MiningMainchainViewImpl testBlockchain = new MiningMainchainViewImpl( blockStore, 448); List<BlockHeader> result = testBlockchain.get(); assertNotNull(result); Block bestBlock = blockStore.getBestBlock(); assertThat(result.get(0).getNumber(), is(2L)); assertThat(result.get(0).getHash(), is(bestBlock.getHash())); Block bestBlockParent = blockStore.getBlockByHash(bestBlock.getParentHash().getBytes()); assertThat(result.get(1).getNumber(), is(1L)); assertThat(result.get(1).getHash(), is(bestBlockParent.getHash())); Block genesisBlock = blockStore.getBlockByHash(bestBlockParent.getParentHash().getBytes()); assertThat(result.get(2).getNumber(), is(0L)); assertThat(result.get(2).getHash(), is(genesisBlock.getHash())); } @Test public void createWithLessBlocksThanMaxHeight() { MiningMainchainViewImpl testBlockchain = new MiningMainchainViewImpl( createBlockStore(10), 11); List<BlockHeader> result = testBlockchain.get(); assertNotNull(result); assertThat(result.size(), is(10)); } @Test public void createWithBlocksEqualToMaxHeight() { MiningMainchainViewImpl testBlockchain = new MiningMainchainViewImpl( createBlockStore(4), 4); List<BlockHeader> result = testBlockchain.get(); assertNotNull(result); assertThat(result.size(), is(4)); } @Test public void createWithMoreBlocksThanMaxHeight() { MiningMainchainViewImpl testBlockchain = new MiningMainchainViewImpl( createBlockStore(8), 6); List<BlockHeader> result = testBlockchain.get(); assertNotNull(result); assertThat(result.size(), is(6)); } @Test public void createWithOnlyGenesisAndHeightOne() { BlockStore blockStore = createBlockStore(1); Block genesis = blockStore.getChainBlockByNumber(0L); when(blockStore.getBestBlock()).thenReturn(genesis); MiningMainchainViewImpl testBlockchain = new MiningMainchainViewImpl( blockStore, 1); List<BlockHeader> result = testBlockchain.get(); assertNotNull(result); assertThat(result.size(), is(1)); assertThat(result.get(0).isGenesis(), is(true)); } @Test public void createWithOnlyGenesisAndHeightGreaterThanOne() { BlockStore blockStore = createBlockStore(1); Block genesis = blockStore.getChainBlockByNumber(0L); when(blockStore.getBestBlock()).thenReturn(genesis); MiningMainchainViewImpl testBlockchain = new MiningMainchainViewImpl( blockStore, 10); List<BlockHeader> result = testBlockchain.get(); assertNotNull(result); assertThat(result.size(), is(1)); assertThat(result.get(0).isGenesis(), is(true)); }
### Question: RLP { public static byte[] encodeListHeader(int size) { if (size == 0) { return new byte[]{(byte) OFFSET_SHORT_LIST}; } int totalLength = size; byte[] header; if (totalLength < SIZE_THRESHOLD) { header = new byte[1]; header[0] = (byte) (OFFSET_SHORT_LIST + totalLength); } else { int tmpLength = totalLength; byte byteNum = 0; while (tmpLength != 0) { ++byteNum; tmpLength = tmpLength >> 8; } tmpLength = totalLength; byte[] lenBytes = new byte[byteNum]; for (int i = 0; i < byteNum; ++i) { lenBytes[byteNum - 1 - i] = (byte) ((tmpLength >> (8 * i)) & 0xFF); } header = new byte[1 + lenBytes.length]; header[0] = (byte) (OFFSET_LONG_LIST + byteNum); System.arraycopy(lenBytes, 0, header, 1, lenBytes.length); } return header; } static int decodeInt(byte[] data, int index); static BigInteger decodeBigInteger(byte[] data, int index); static byte[] decodeIP4Bytes(byte[] data, int index); static int getFirstListElement(byte[] payload, int pos); static int getNextElementIndex(byte[] payload, int pos); static void fullTraverse(byte[] msgData, int level, int startPos, int endPos, int levelToIndex, Queue<Integer> index); @Nonnull static ArrayList<RLPElement> decode2(@CheckForNull byte[] msgData); static RLPElement decodeFirstElement(@CheckForNull byte[] msgData, int position); static RLPList decodeList(byte[] msgData); @Nullable static RLPElement decode2OneItem(@CheckForNull byte[] msgData, int startPos); @Nonnull static RskAddress parseRskAddress(@Nullable byte[] bytes); @Nonnull static Coin parseCoin(@Nullable byte[] bytes); @Nullable static Coin parseCoinNonNullZero(byte[] bytes); @Nullable static Coin parseSignedCoinNonNullZero(byte[] bytes); static Coin parseCoinNullZero(@Nullable byte[] bytes); @Nullable static BlockDifficulty parseBlockDifficulty(@Nullable byte[] bytes); static byte[] encode(Object input); static byte[] encodeLength(int length, int offset); static byte[] encodeByte(byte singleByte); static byte[] encodeShort(short singleShort); static byte[] encodeInt(int singleInt); static byte[] encodeString(String srcString); static byte[] encodeBigInteger(BigInteger srcBigInteger); static byte[] encodeRskAddress(RskAddress addr); static byte[] encodeCoin(@Nullable Coin coin); static byte[] encodeCoinNonNullZero(@CheckForNull Coin coin); static byte[] encodeSignedCoinNonNullZero(@CheckForNull Coin coin); static byte[] encodeCoinNullZero(Coin coin); static byte[] encodeBlockDifficulty(BlockDifficulty difficulty); static byte[] encodeElement(@Nullable byte[] srcData); static byte[] encodeListHeader(int size); static byte[] encodeSet(Set<ByteArrayWrapper> data); static byte[] encodeList(byte[]... elements); static byte[] encodedEmptyList(); static byte[] encodedEmptyByteArray(); }### Answer: @Test public void testEncodeListHeader(){ byte[] header = encodeListHeader(10); String expected_1 = "ca"; assertEquals(expected_1, ByteUtil.toHexString(header)); header = encodeListHeader(1000); String expected_2 = "f903e8"; assertEquals(expected_2, ByteUtil.toHexString(header)); header = encodeListHeader(1000000000); String expected_3 = "fb3b9aca00"; assertEquals(expected_3, ByteUtil.toHexString(header)); }
### Question: Uint24 implements Comparable<Uint24> { public int intValue() { return intValue; } Uint24(int intValue); byte[] encode(); int intValue(); @Override boolean equals(Object o); @Override int hashCode(); @Override int compareTo(Uint24 o); @Override String toString(); static Uint24 decode(byte[] bytes, int offset); static final int SIZE; static final int BYTES; static final Uint24 ZERO; static final Uint24 MAX_VALUE; }### Answer: @Test(expected = IllegalArgumentException.class) public void instantiateMaxPlusOne() { new Uint24(Uint24.MAX_VALUE.intValue() + 1); }
### Question: Uint24 implements Comparable<Uint24> { public static Uint24 decode(byte[] bytes, int offset) { int intValue = (bytes[offset + 2] & 0xFF) + ((bytes[offset + 1] & 0xFF) << 8) + ((bytes[offset ] & 0xFF) << 16); return new Uint24(intValue); } Uint24(int intValue); byte[] encode(); int intValue(); @Override boolean equals(Object o); @Override int hashCode(); @Override int compareTo(Uint24 o); @Override String toString(); static Uint24 decode(byte[] bytes, int offset); static final int SIZE; static final int BYTES; static final Uint24 ZERO; static final Uint24 MAX_VALUE; }### Answer: @Test public void decodeOffsettedValue() { byte[] bytes = new byte[] {0x21, 0x53, (byte) 0xf2, (byte) 0xf4, 0x04, 0x55}; Uint24 decoded = Uint24.decode(bytes, 2); assertThat(decoded, is(new Uint24(15922180))); } @Test(expected = ArrayIndexOutOfBoundsException.class) public void decodeSmallArray() { byte[] bytes = new byte[] {0x21, 0x53, (byte) 0xf2}; Uint24.decode(bytes, 2); }
### Question: Uint8 { public byte asByte() { return (byte) intValue; } Uint8(int intValue); byte asByte(); byte[] encode(); int intValue(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); static Uint8 decode(byte[] bytes, int offset); static final int BYTES; static final Uint8 MAX_VALUE; }### Answer: @Test public void asByteReturnsByteValue() { Uint8 fortyTwo = new Uint8(42); assertThat(fortyTwo.asByte(), is((byte)42)); }
### Question: Uint8 { public int intValue() { return intValue; } Uint8(int intValue); byte asByte(); byte[] encode(); int intValue(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); static Uint8 decode(byte[] bytes, int offset); static final int BYTES; static final Uint8 MAX_VALUE; }### Answer: @Test(expected = IllegalArgumentException.class) public void instantiateMaxPlusOne() { new Uint8((Uint8.MAX_VALUE.intValue() + 1)); }
### Question: RLP { public static byte[] encodeSet(Set<ByteArrayWrapper> data) { int dataLength = 0; Set<byte[]> encodedElements = new HashSet<>(); for (ByteArrayWrapper element : data) { byte[] encodedElement = RLP.encodeElement(element.getData()); dataLength += encodedElement.length; encodedElements.add(encodedElement); } byte[] listHeader = encodeListHeader(dataLength); byte[] output = new byte[listHeader.length + dataLength]; System.arraycopy(listHeader, 0, output, 0, listHeader.length); int cummStart = listHeader.length; for (byte[] element : encodedElements) { System.arraycopy(element, 0, output, cummStart, element.length); cummStart += element.length; } return output; } static int decodeInt(byte[] data, int index); static BigInteger decodeBigInteger(byte[] data, int index); static byte[] decodeIP4Bytes(byte[] data, int index); static int getFirstListElement(byte[] payload, int pos); static int getNextElementIndex(byte[] payload, int pos); static void fullTraverse(byte[] msgData, int level, int startPos, int endPos, int levelToIndex, Queue<Integer> index); @Nonnull static ArrayList<RLPElement> decode2(@CheckForNull byte[] msgData); static RLPElement decodeFirstElement(@CheckForNull byte[] msgData, int position); static RLPList decodeList(byte[] msgData); @Nullable static RLPElement decode2OneItem(@CheckForNull byte[] msgData, int startPos); @Nonnull static RskAddress parseRskAddress(@Nullable byte[] bytes); @Nonnull static Coin parseCoin(@Nullable byte[] bytes); @Nullable static Coin parseCoinNonNullZero(byte[] bytes); @Nullable static Coin parseSignedCoinNonNullZero(byte[] bytes); static Coin parseCoinNullZero(@Nullable byte[] bytes); @Nullable static BlockDifficulty parseBlockDifficulty(@Nullable byte[] bytes); static byte[] encode(Object input); static byte[] encodeLength(int length, int offset); static byte[] encodeByte(byte singleByte); static byte[] encodeShort(short singleShort); static byte[] encodeInt(int singleInt); static byte[] encodeString(String srcString); static byte[] encodeBigInteger(BigInteger srcBigInteger); static byte[] encodeRskAddress(RskAddress addr); static byte[] encodeCoin(@Nullable Coin coin); static byte[] encodeCoinNonNullZero(@CheckForNull Coin coin); static byte[] encodeSignedCoinNonNullZero(@CheckForNull Coin coin); static byte[] encodeCoinNullZero(Coin coin); static byte[] encodeBlockDifficulty(BlockDifficulty difficulty); static byte[] encodeElement(@Nullable byte[] srcData); static byte[] encodeListHeader(int size); static byte[] encodeSet(Set<ByteArrayWrapper> data); static byte[] encodeList(byte[]... elements); static byte[] encodedEmptyList(); static byte[] encodedEmptyByteArray(); }### Answer: @Test public void testEncodeSet_2(){ Set<ByteArrayWrapper> data = new HashSet<>(); byte[] setEncoded = encodeSet(data); assertEquals("c0", ByteUtil.toHexString(setEncoded)); }
### Question: Uint8 { public static Uint8 decode(byte[] bytes, int offset) { int intValue = bytes[offset] & 0xFF; return new Uint8(intValue); } Uint8(int intValue); byte asByte(); byte[] encode(); int intValue(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); static Uint8 decode(byte[] bytes, int offset); static final int BYTES; static final Uint8 MAX_VALUE; }### Answer: @Test public void decodeOffsettedValue() { byte[] bytes = new byte[] {0x21, 0x53, (byte) 0xf3, (byte) 0xf4, 0x04, 0x55}; Uint8 decoded = Uint8.decode(bytes, 2); assertThat(decoded, is(new Uint8(243))); } @Test(expected = ArrayIndexOutOfBoundsException.class) public void decodeSmallArray() { byte[] bytes = new byte[] {0x21, 0x53, (byte) 0xf2}; Uint8.decode(bytes, 3); }
### Question: RskAddress { @Override public boolean equals(Object other) { if (this == other) { return true; } if (other == null || this.getClass() != other.getClass()) { return false; } RskAddress otherSender = (RskAddress) other; return Arrays.equals(bytes, otherSender.bytes); } RskAddress(DataWord address); RskAddress(String address); RskAddress(byte[] bytes); private RskAddress(); static RskAddress nullAddress(); byte[] getBytes(); String toHexString(); @Override boolean equals(Object other); @Override int hashCode(); @Override String toString(); String toJsonString(); static final int LENGTH_IN_BYTES; static final Comparator<RskAddress> LEXICOGRAPHICAL_COMPARATOR; }### Answer: @Test public void testEquals() { RskAddress senderA = new RskAddress("0000000000000000000000000000000001000006"); RskAddress senderB = new RskAddress("0000000000000000000000000000000001000006"); RskAddress senderC = new RskAddress("0000000000000000000000000000000001000008"); RskAddress senderD = RskAddress.nullAddress(); RskAddress senderE = new RskAddress("0x00002000f000000a000000330000000001000006"); Assert.assertEquals(senderA, senderB); Assert.assertNotEquals(senderA, senderC); Assert.assertNotEquals(senderA, senderD); Assert.assertNotEquals(senderA, senderE); }
### Question: RskAddress { public static RskAddress nullAddress() { return NULL_ADDRESS; } RskAddress(DataWord address); RskAddress(String address); RskAddress(byte[] bytes); private RskAddress(); static RskAddress nullAddress(); byte[] getBytes(); String toHexString(); @Override boolean equals(Object other); @Override int hashCode(); @Override String toString(); String toJsonString(); static final int LENGTH_IN_BYTES; static final Comparator<RskAddress> LEXICOGRAPHICAL_COMPARATOR; }### Answer: @Test public void zeroAddress() { RskAddress senderA = new RskAddress("0000000000000000000000000000000000000000"); RskAddress senderB = new RskAddress("0x0000000000000000000000000000000000000000"); RskAddress senderC = new RskAddress(new byte[20]); Assert.assertEquals(senderA, senderB); Assert.assertEquals(senderB, senderC); Assert.assertNotEquals(RskAddress.nullAddress(), senderC); } @Test public void nullAddress() { Assert.assertArrayEquals(RskAddress.nullAddress().getBytes(), new byte[0]); }
### Question: RskAddress { public String toJsonString() { if (NULL_ADDRESS.equals(this)) { return null; } return TypeConverter.toUnformattedJsonHex(this.getBytes()); } RskAddress(DataWord address); RskAddress(String address); RskAddress(byte[] bytes); private RskAddress(); static RskAddress nullAddress(); byte[] getBytes(); String toHexString(); @Override boolean equals(Object other); @Override int hashCode(); @Override String toString(); String toJsonString(); static final int LENGTH_IN_BYTES; static final Comparator<RskAddress> LEXICOGRAPHICAL_COMPARATOR; }### Answer: @Test public void jsonString_otherAddress() { String address = "0x0000000000000000000000000000000000000001"; RskAddress rskAddress = new RskAddress(address); Assert.assertEquals(address, rskAddress.toJsonString()); }
### Question: Coin implements Comparable<Coin> { public byte[] getBytes() { return value.toByteArray(); } Coin(byte[] value); Coin(BigInteger value); byte[] getBytes(); BigInteger asBigInteger(); Coin negate(); Coin add(Coin val); Coin subtract(Coin val); Coin multiply(BigInteger val); Coin divide(BigInteger val); Coin[] divideAndRemainder(BigInteger val); co.rsk.bitcoinj.core.Coin toBitcoin(); @Override boolean equals(Object other); @Override int hashCode(); @Override int compareTo(@Nonnull Coin other); @Override String toString(); static Coin valueOf(long val); static Coin fromBitcoin(co.rsk.bitcoinj.core.Coin val); static final Coin ZERO; }### Answer: @Test public void zeroGetBytes() { assertThat(Coin.ZERO.getBytes(), is(new byte[]{0})); }
### Question: TrieKeySlice { public TrieKeySlice leftPad(int paddingLength) { if (paddingLength == 0) { return this; } int currentLength = length(); byte[] paddedExpandedKey = new byte[currentLength + paddingLength]; System.arraycopy(expandedKey, offset, paddedExpandedKey, paddingLength, currentLength); return new TrieKeySlice(paddedExpandedKey, 0, paddedExpandedKey.length); } private TrieKeySlice(byte[] expandedKey, int offset, int limit); int length(); byte get(int i); byte[] encode(); TrieKeySlice slice(int from, int to); TrieKeySlice commonPath(TrieKeySlice other); TrieKeySlice rebuildSharedPath(byte implicitByte, TrieKeySlice childSharedPath); TrieKeySlice leftPad(int paddingLength); static TrieKeySlice fromKey(byte[] key); static TrieKeySlice fromEncoded(byte[] src, int offset, int keyLength, int encodedLength); static TrieKeySlice empty(); }### Answer: @Test public void leftPad() { int paddedLength = 8; TrieKeySlice initialKey = TrieKeySlice.fromKey(new byte[]{(byte) 0xff}); TrieKeySlice leftPaddedKey = initialKey.leftPad(paddedLength); Assert.assertThat(leftPaddedKey.length(), is(initialKey.length() + paddedLength)); Assert.assertArrayEquals( PathEncoder.encode(new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 }), leftPaddedKey.encode() ); }
### Question: TrieStoreImpl implements TrieStore { @Override public Optional<Trie> retrieve(byte[] hash) { byte[] message = this.store.get(hash); if (message == null) { return Optional.empty(); } Trie trie = Trie.fromMessage(message, this); savedTries.add(trie); return Optional.of(trie); } TrieStoreImpl(KeyValueDataSource store); @Override void save(Trie trie); @Override void flush(); @Override Optional<Trie> retrieve(byte[] hash); @Override byte[] retrieveValue(byte[] hash); @Override void dispose(); }### Answer: @Test public void retrieveTrieNotFound() { Assert.assertFalse(store.retrieve(new byte[] { 0x01, 0x02, 0x03, 0x04 }).isPresent()); }
### Question: TrieConverter { public byte[] getOrchidAccountTrieRoot(Trie src) { Metric metric = profiler.start(Profiler.PROFILING_TYPE.TRIE_CONVERTER_GET_ACCOUNT_ROOT); byte[] trieRoot = cacheHashes.computeIfAbsent(src.getHash(), k -> { Trie trie = getOrchidAccountTrieRoot(src.getSharedPath(), src, true); return trie == null ? HashUtil.EMPTY_TRIE_HASH : trie.getHashOrchid(true).getBytes(); }); profiler.stop(metric); return trieRoot; } TrieConverter(); byte[] getOrchidAccountTrieRoot(Trie src); }### Answer: @Test public void getOrchidAccountTrieRootWithCompressedStorageKeys() { TrieStore trieStore = new TrieStoreImpl(new HashMapDB()); Repository repository = new MutableRepository(new MutableTrieImpl(trieStore, new Trie(trieStore))); Repository track = repository.startTracking(); TestUtils.getRandom().setSeed(0); int maxAccounts = 10; int maxStorageRows = 5; for (int i = 0; i < maxAccounts; i++) { RskAddress addr = TestUtils.randomAddress(); track.createAccount(addr); AccountState a = track.getAccountState(addr); a.setNonce(TestUtils.randomBigInteger(4)); a.addToBalance(TestUtils.randomCoin(18, 1000)); track.updateAccountState(addr, a); if (i >= maxAccounts / 2) { track.setupContract(addr); for (int s = 0; s < maxStorageRows / 2; s++) { track.addStorageBytes(addr, TestUtils.randomDataWord(), TestUtils.randomBytes(TestUtils.getRandom().nextInt(40) + 1)); } for (int s = 0; s < maxStorageRows / 2; s++) { track.addStorageBytes(addr, DataWord.valueOf(TestUtils.randomBytes(20)), TestUtils.randomBytes(TestUtils.getRandom().nextInt(40) + 1)); } track.saveCode(addr, randomCode(60)); } } track.commit(); TrieConverter tc = new TrieConverter(); byte[] oldRoot = tc.getOrchidAccountTrieRoot(repository.getTrie()); Trie atrie = deserialize(SERIALIZED_ORCHID_TRIESTORE_WITH_LEADING_ZEROES_STORAGE_KEYS); Assert.assertThat(ByteUtil.toHexString(oldRoot), is(atrie.getHashOrchid(true).toHexString())); } @Test public void test1Simple() { TrieStore trieStore = new TrieStoreImpl(new HashMapDB()); Repository repository = new MutableRepository(new MutableTrieImpl(trieStore, new Trie(trieStore))); Repository track = repository.startTracking(); TestUtils.getRandom().setSeed(0); int maxAccounts = 10; int maxStorageRows = 5; for (int i = 0; i < maxAccounts; i++) { RskAddress addr = TestUtils.randomAddress(); track.createAccount(addr); AccountState a = track.getAccountState(addr); a.setNonce(TestUtils.randomBigInteger(4)); a.addToBalance(TestUtils.randomCoin(18, 1000)); track.updateAccountState(addr, a); if (i >= maxAccounts / 2) { track.setupContract(addr); for (int s = 0; s < maxStorageRows; s++) { track.addStorageBytes(addr, TestUtils.randomDataWord(), TestUtils.randomBytes(TestUtils.getRandom().nextInt(40) + 1)); } track.saveCode(addr, randomCode(60)); } } track.commit(); TrieConverter tc = new TrieConverter(); byte[] oldRoot = tc.getOrchidAccountTrieRoot(repository.getTrie()); Trie atrie = deserialize(SERIALIZED_ORCHID_TRIESTORE_SIMPLE); Assert.assertThat(ByteUtil.toHexString(oldRoot), is(atrie.getHashOrchid(true).toHexString())); }
### Question: PathEncoder { @Nonnull public static byte[] encode(byte[] path) { if (path == null) { throw new IllegalArgumentException("path"); } return encodeBinaryPath(path); } private PathEncoder(); @Nonnull static byte[] encode(byte[] path); @Nonnull static byte[] decode(byte[] encoded, int length); static int calculateEncodedLength(int keyLength); }### Answer: @Test public void encodeNullBinaryPath() { try { PathEncoder.encode(null); Assert.fail(); } catch (Exception ex) { Assert.assertTrue(ex instanceof IllegalArgumentException); } } @Test public void encodeBinaryPathOneByte() { byte[] path = new byte[] { 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01 }; byte[] encoded = PathEncoder.encode(path); Assert.assertNotNull(encoded); Assert.assertArrayEquals(new byte[] { 0x6d }, encoded); } @Test public void encodeBinaryPathNineBits() { byte[] path = new byte[] { 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01 }; byte[] encoded = PathEncoder.encode(path); Assert.assertNotNull(encoded); Assert.assertArrayEquals(new byte[] { 0x6d, (byte)0x80 }, encoded); } @Test public void encodeBinaryPathOneAndHalfByte() { byte[] path = new byte[] { 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01 }; byte[] encoded = PathEncoder.encode(path); Assert.assertNotNull(encoded); Assert.assertArrayEquals(new byte[] { 0x6d, 0x50 }, encoded); }
### Question: PathEncoder { @Nonnull private static byte[] encodeBinaryPath(byte[] path) { int lpath = path.length; int lencoded = calculateEncodedLength(lpath); byte[] encoded = new byte[lencoded]; int nbyte = 0; for (int k = 0; k < lpath; k++) { int offset = k % 8; if (k > 0 && offset == 0) { nbyte++; } if (path[k] == 0) { continue; } encoded[nbyte] |= 0x80 >> offset; } return encoded; } private PathEncoder(); @Nonnull static byte[] encode(byte[] path); @Nonnull static byte[] decode(byte[] encoded, int length); static int calculateEncodedLength(int keyLength); }### Answer: @Test public void encodeBinaryPath() { byte[] path = new byte[] { 0x00, 0x01, 0x01 }; byte[] encoded = PathEncoder.encode(path); Assert.assertNotNull(encoded); Assert.assertArrayEquals(new byte[] { 0x60 }, encoded); }
### Question: PathEncoder { @Nonnull public static byte[] decode(byte[] encoded, int length) { if (encoded == null) { throw new IllegalArgumentException("encoded"); } return decodeBinaryPath(encoded, length); } private PathEncoder(); @Nonnull static byte[] encode(byte[] path); @Nonnull static byte[] decode(byte[] encoded, int length); static int calculateEncodedLength(int keyLength); }### Answer: @Test public void decodeNullBinaryPath() { try { PathEncoder.decode(null, 0); Assert.fail(); } catch (Exception ex) { Assert.assertTrue(ex instanceof IllegalArgumentException); } } @Test public void decodeBinaryPathOneByte() { byte[] encoded = new byte[] { 0x6d }; byte[] path = PathEncoder.decode(encoded, 8); Assert.assertNotNull(path); Assert.assertArrayEquals(new byte[] { 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01 }, path); } @Test public void decodeBinaryPathNineBits() { byte[] encoded = new byte[] { 0x6d, (byte)0x80 }; byte[] path = PathEncoder.decode(encoded, 9); Assert.assertNotNull(path); Assert.assertArrayEquals(new byte[] { 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01 }, path); } @Test public void decodeBinaryPathOneAndHalfByte() { byte[] encoded = new byte[] { 0x6d, 0x50 }; byte[] path = PathEncoder.decode(encoded, 12); Assert.assertNotNull(path); Assert.assertArrayEquals(new byte[] { 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01 }, path); }
### Question: PathEncoder { @Nonnull private static byte[] decodeBinaryPath(byte[] encoded, int bitlength) { byte[] path = new byte[bitlength]; for (int k = 0; k < bitlength; k++) { int nbyte = k / 8; int offset = k % 8; if (((encoded[nbyte] >> (7 - offset)) & 0x01) != 0) { path[k] = 1; } } return path; } private PathEncoder(); @Nonnull static byte[] encode(byte[] path); @Nonnull static byte[] decode(byte[] encoded, int length); static int calculateEncodedLength(int keyLength); }### Answer: @Test public void decodeBinaryPath() { byte[] encoded = new byte[] { 0x60 }; byte[] path = PathEncoder.decode(encoded, 3); Assert.assertNotNull(path); Assert.assertArrayEquals(new byte[] { 0x00, 0x01, 0x01 }, path); }
### Question: MultiTrieStore implements TrieStore { @Override public void save(Trie trie) { getCurrentStore().save(trie); } MultiTrieStore(int currentEpoch, int liveEpochs, TrieStoreFactory trieStoreFactory, OnEpochDispose disposer); @Override void save(Trie trie); @Override void flush(); @Override Optional<Trie> retrieve(byte[] rootHash); @Override byte[] retrieveValue(byte[] hash); @Override void dispose(); void collect(byte[] oldestTrieHashToKeep); }### Answer: @Test public void callsSaveOnlyOnNewestStore() { TrieStore store1 = mock(TrieStore.class); TrieStore store2 = mock(TrieStore.class); TrieStore store3 = mock(TrieStore.class); TrieStoreFactory storeFactory = mock(TrieStoreFactory.class); when(storeFactory.newInstance("46")).thenReturn(store1); when(storeFactory.newInstance("47")).thenReturn(store2); when(storeFactory.newInstance("48")).thenReturn(store3); MultiTrieStore store = new MultiTrieStore(49, 3, storeFactory, null); Trie trie = mock(Trie.class); store.save(trie); verify(store1, never()).save(trie); verify(store2, never()).save(trie); verify(store3).save(trie); }
### Question: MultiTrieStore implements TrieStore { @Override public void flush() { epochs.forEach(TrieStore::flush); } MultiTrieStore(int currentEpoch, int liveEpochs, TrieStoreFactory trieStoreFactory, OnEpochDispose disposer); @Override void save(Trie trie); @Override void flush(); @Override Optional<Trie> retrieve(byte[] rootHash); @Override byte[] retrieveValue(byte[] hash); @Override void dispose(); void collect(byte[] oldestTrieHashToKeep); }### Answer: @Test public void callsFlushOnAllStores() { TrieStore store1 = mock(TrieStore.class); TrieStore store2 = mock(TrieStore.class); TrieStore store3 = mock(TrieStore.class); TrieStoreFactory storeFactory = mock(TrieStoreFactory.class); when(storeFactory.newInstance("46")).thenReturn(store1); when(storeFactory.newInstance("47")).thenReturn(store2); when(storeFactory.newInstance("48")).thenReturn(store3); MultiTrieStore store = new MultiTrieStore(49, 3, storeFactory, null); store.flush(); verify(store1).flush(); verify(store2).flush(); verify(store3).flush(); }
### Question: MultiTrieStore implements TrieStore { @Override public void dispose() { epochs.forEach(TrieStore::dispose); } MultiTrieStore(int currentEpoch, int liveEpochs, TrieStoreFactory trieStoreFactory, OnEpochDispose disposer); @Override void save(Trie trie); @Override void flush(); @Override Optional<Trie> retrieve(byte[] rootHash); @Override byte[] retrieveValue(byte[] hash); @Override void dispose(); void collect(byte[] oldestTrieHashToKeep); }### Answer: @Test public void callsDisposeOnAllStores() { TrieStore store1 = mock(TrieStore.class); TrieStore store2 = mock(TrieStore.class); TrieStore store3 = mock(TrieStore.class); TrieStoreFactory storeFactory = mock(TrieStoreFactory.class); when(storeFactory.newInstance("46")).thenReturn(store1); when(storeFactory.newInstance("47")).thenReturn(store2); when(storeFactory.newInstance("48")).thenReturn(store3); MultiTrieStore store = new MultiTrieStore(49, 3, storeFactory, null); store.dispose(); verify(store1).dispose(); verify(store2).dispose(); verify(store3).dispose(); }
### Question: MultiTrieStore implements TrieStore { @Override public byte[] retrieveValue(byte[] hash) { for (TrieStore epochTrieStore : epochs) { byte[] value = epochTrieStore.retrieveValue(hash); if (value != null) { return value; } } return null; } MultiTrieStore(int currentEpoch, int liveEpochs, TrieStoreFactory trieStoreFactory, OnEpochDispose disposer); @Override void save(Trie trie); @Override void flush(); @Override Optional<Trie> retrieve(byte[] rootHash); @Override byte[] retrieveValue(byte[] hash); @Override void dispose(); void collect(byte[] oldestTrieHashToKeep); }### Answer: @Test public void retrievesValueFromNewestStoreWithValue() { TrieStore store1 = mock(TrieStore.class); TrieStore store2 = mock(TrieStore.class); TrieStore store3 = mock(TrieStore.class); TrieStoreFactory storeFactory = mock(TrieStoreFactory.class); when(storeFactory.newInstance("46")).thenReturn(store1); when(storeFactory.newInstance("47")).thenReturn(store2); when(storeFactory.newInstance("48")).thenReturn(store3); MultiTrieStore store = new MultiTrieStore(49, 3, storeFactory, null); byte[] testValue = new byte[] {0x32, 0x42}; byte[] hashToRetrieve = new byte[] {0x2, 0x4}; when(store2.retrieveValue(hashToRetrieve)).thenReturn(testValue); byte[] retrievedValue = store.retrieveValue(hashToRetrieve); assertArrayEquals(testValue, retrievedValue); verify(store1, never()).retrieveValue(hashToRetrieve); verify(store2).retrieveValue(hashToRetrieve); verify(store3).retrieveValue(hashToRetrieve); }
### Question: BitSet { public boolean get(int position) { if (position < 0 || position >= this.size) { throw new IndexOutOfBoundsException(String.format("Index: %s, Size: %s", position, this.size)); } int offset = position / 8; int bitoffset = position % 8; return (this.bytes[offset] & 0xff & (1 << bitoffset)) != 0; } BitSet(int size); void set(int position); boolean get(int position); int size(); }### Answer: @Test public void exceptionIfGetWithNegativePosition() { BitSet set = new BitSet(17); try { set.get(-1); Assert.fail(); } catch (IndexOutOfBoundsException ex) { Assert.assertEquals("Index: -1, Size: 17", ex.getMessage()); } } @Test public void exceptionIfGetWithOutOfBoundPosition() { BitSet set = new BitSet(17); try { set.get(17); Assert.fail(); } catch (IndexOutOfBoundsException ex) { Assert.assertEquals("Index: 17, Size: 17", ex.getMessage()); } }
### Question: BitSet { public void set(int position) { if (position < 0 || position >= this.size) { throw new IndexOutOfBoundsException(String.format("Index: %s, Size: %s", position, this.size)); } int offset = position / 8; int bitoffset = position % 8; this.bytes[offset] |= 1 << bitoffset; } BitSet(int size); void set(int position); boolean get(int position); int size(); }### Answer: @Test public void exceptionIfSetWithNegativePosition() { BitSet set = new BitSet(17); try { set.set(-1); Assert.fail(); } catch (IndexOutOfBoundsException ex) { Assert.assertEquals("Index: -1, Size: 17", ex.getMessage()); } } @Test public void exceptionIfSetWithOutOfBoundPosition() { BitSet set = new BitSet(17); try { set.set(17); Assert.fail(); } catch (IndexOutOfBoundsException ex) { Assert.assertEquals("Index: 17, Size: 17", ex.getMessage()); } }
### Question: ExtractPublicKeyFromExtendedPublicKey extends NativeMethod { @Override public CallTransaction.Function getFunction() { return function; } ExtractPublicKeyFromExtendedPublicKey(ExecutionEnvironment executionEnvironment, HDWalletUtilsHelper helper); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override boolean isEnabled(); @Override boolean onlyAllowsLocalCalls(); @Override long getGas(Object[] parsedArguments, byte[] originalData); }### Answer: @Test public void functionSignatureOk() { CallTransaction.Function fn = method.getFunction(); Assert.assertEquals("extractPublicKeyFromExtendedPublicKey", fn.name); Assert.assertEquals(1, fn.inputs.length); Assert.assertEquals(SolidityType.getType("string").getName(), fn.inputs[0].type.getName()); Assert.assertEquals(1, fn.outputs.length); Assert.assertEquals(SolidityType.getType("bytes").getName(), fn.outputs[0].type.getName()); }
### Question: ExtractPublicKeyFromExtendedPublicKey extends NativeMethod { @Override public boolean isEnabled() { return true; } ExtractPublicKeyFromExtendedPublicKey(ExecutionEnvironment executionEnvironment, HDWalletUtilsHelper helper); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override boolean isEnabled(); @Override boolean onlyAllowsLocalCalls(); @Override long getGas(Object[] parsedArguments, byte[] originalData); }### Answer: @Test public void shouldBeEnabled() { Assert.assertTrue(method.isEnabled()); }
### Question: ExtractPublicKeyFromExtendedPublicKey extends NativeMethod { @Override public boolean onlyAllowsLocalCalls() { return false; } ExtractPublicKeyFromExtendedPublicKey(ExecutionEnvironment executionEnvironment, HDWalletUtilsHelper helper); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override boolean isEnabled(); @Override boolean onlyAllowsLocalCalls(); @Override long getGas(Object[] parsedArguments, byte[] originalData); }### Answer: @Test public void shouldAllowAnyTypeOfCall() { Assert.assertFalse(method.onlyAllowsLocalCalls()); }
### Question: ExtractPublicKeyFromExtendedPublicKey extends NativeMethod { @Override public Object execute(Object[] arguments) { if (arguments == null) { throw new NativeContractIllegalArgumentException(String.format(INVALID_EXTENDED_PUBLIC_KEY, null)); } String xpub = (String) arguments[0]; NetworkParameters params = helper.validateAndExtractNetworkFromExtendedPublicKey(xpub); DeterministicKey key; try { key = DeterministicKey.deserializeB58(xpub, params); } catch (IllegalArgumentException e) { throw new NativeContractIllegalArgumentException(String.format(INVALID_EXTENDED_PUBLIC_KEY, xpub), e); } return key.getPubKeyPoint().getEncoded(true); } ExtractPublicKeyFromExtendedPublicKey(ExecutionEnvironment executionEnvironment, HDWalletUtilsHelper helper); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override boolean isEnabled(); @Override boolean onlyAllowsLocalCalls(); @Override long getGas(Object[] parsedArguments, byte[] originalData); }### Answer: @Test public void executes() { Assert.assertEquals( "02be517550b9e3be7fe42c80932d51e88e698663b4926e598b269d050e87e34d8c", ByteUtil.toHexString((byte[]) method.execute(new Object[]{ "xpub661MyMwAqRbcFMGNG2YcHvj3x63bAZN9U5cKikaiQ4zu2D1cvpnZYyXNR9nH62sGp4RR39Ui7SVQSq1PY4JbPuEuu5prVJJC3d5Pogft712", }))); } @Test public void validatesExtendedPublicKeyFormat() { try { method.execute(new Object[]{ "this-is-not-an-xpub", }); Assert.fail(); } catch (NativeContractIllegalArgumentException e) { Assert.assertTrue(e.getMessage().contains("Invalid extended public key")); } } @Test public void failsUponInvalidPublicKey() { try { method.execute(new Object[]{ "tpubD6NzVbkrYhZ4YHQqwWz3Tm1ESZ9AidobeyLG4mEezB6hN8gFFWrcjczyF77Lw3HEs6Rjd2R11BEJ8Y9ptfxx9DFknkdujp58mFMx9H5dc1s", }); Assert.fail(); } catch (NativeContractIllegalArgumentException e) { Assert.assertTrue(e.getMessage().contains("Invalid extended public key")); } } @Test public void failsUponNull() { try { method.execute(null); Assert.fail(); } catch (NativeContractIllegalArgumentException e) { Assert.assertTrue(e.getMessage().contains("Invalid extended public key")); } }
### Question: RLP { @Nullable public static RLPElement decode2OneItem(@CheckForNull byte[] msgData, int startPos) { if (msgData == null) { return null; } return RLP.decodeFirstElement(msgData, startPos); } static int decodeInt(byte[] data, int index); static BigInteger decodeBigInteger(byte[] data, int index); static byte[] decodeIP4Bytes(byte[] data, int index); static int getFirstListElement(byte[] payload, int pos); static int getNextElementIndex(byte[] payload, int pos); static void fullTraverse(byte[] msgData, int level, int startPos, int endPos, int levelToIndex, Queue<Integer> index); @Nonnull static ArrayList<RLPElement> decode2(@CheckForNull byte[] msgData); static RLPElement decodeFirstElement(@CheckForNull byte[] msgData, int position); static RLPList decodeList(byte[] msgData); @Nullable static RLPElement decode2OneItem(@CheckForNull byte[] msgData, int startPos); @Nonnull static RskAddress parseRskAddress(@Nullable byte[] bytes); @Nonnull static Coin parseCoin(@Nullable byte[] bytes); @Nullable static Coin parseCoinNonNullZero(byte[] bytes); @Nullable static Coin parseSignedCoinNonNullZero(byte[] bytes); static Coin parseCoinNullZero(@Nullable byte[] bytes); @Nullable static BlockDifficulty parseBlockDifficulty(@Nullable byte[] bytes); static byte[] encode(Object input); static byte[] encodeLength(int length, int offset); static byte[] encodeByte(byte singleByte); static byte[] encodeShort(short singleShort); static byte[] encodeInt(int singleInt); static byte[] encodeString(String srcString); static byte[] encodeBigInteger(BigInteger srcBigInteger); static byte[] encodeRskAddress(RskAddress addr); static byte[] encodeCoin(@Nullable Coin coin); static byte[] encodeCoinNonNullZero(@CheckForNull Coin coin); static byte[] encodeSignedCoinNonNullZero(@CheckForNull Coin coin); static byte[] encodeCoinNullZero(Coin coin); static byte[] encodeBlockDifficulty(BlockDifficulty difficulty); static byte[] encodeElement(@Nullable byte[] srcData); static byte[] encodeListHeader(int size); static byte[] encodeSet(Set<ByteArrayWrapper> data); static byte[] encodeList(byte[]... elements); static byte[] encodedEmptyList(); static byte[] encodedEmptyByteArray(); }### Answer: @Test public void partialDataParseTest() { String hex = "000080c180000000000000000000000042699b1104e93abf0008be55f912c2ff"; RLPList el = (RLPList) decode2OneItem(Hex.decode(hex), 3); assertEquals(1, el.size()); }
### Question: ExtractPublicKeyFromExtendedPublicKey extends NativeMethod { @Override public long getGas(Object[] parsedArguments, byte[] originalData) { return 11_300L; } ExtractPublicKeyFromExtendedPublicKey(ExecutionEnvironment executionEnvironment, HDWalletUtilsHelper helper); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override boolean isEnabled(); @Override boolean onlyAllowsLocalCalls(); @Override long getGas(Object[] parsedArguments, byte[] originalData); }### Answer: @Test public void gasIsCorrect() { Assert.assertEquals(11_300, method.getGas(new Object[]{ "xpub661MyMwAqRbcFMGNG2YcHvj3x63bAZN9U5cKikaiQ4zu2D1cvpnZYyXNR9nH62sGp4RR39Ui7SVQSq1PY4JbPuEuu5prVJJC3d5Pogft712" }, new byte[]{})); }
### Question: GetMultisigScriptHash extends NativeMethod { @Override public CallTransaction.Function getFunction() { return function; } GetMultisigScriptHash(ExecutionEnvironment executionEnvironment); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override long getGas(Object[] parsedArguments, byte[] originalData); @Override boolean isEnabled(); @Override boolean onlyAllowsLocalCalls(); }### Answer: @Test public void functionSignatureOk() { CallTransaction.Function fn = method.getFunction(); Assert.assertEquals("getMultisigScriptHash", fn.name); Assert.assertEquals(2, fn.inputs.length); Assert.assertEquals(SolidityType.getType("int256").getName(), fn.inputs[0].type.getName()); Assert.assertEquals(SolidityType.getType("bytes[]").getName(), fn.inputs[1].type.getName()); Assert.assertEquals(1, fn.outputs.length); Assert.assertEquals(SolidityType.getType("bytes").getName(), fn.outputs[0].type.getName()); }
### Question: GetMultisigScriptHash extends NativeMethod { @Override public boolean isEnabled() { return true; } GetMultisigScriptHash(ExecutionEnvironment executionEnvironment); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override long getGas(Object[] parsedArguments, byte[] originalData); @Override boolean isEnabled(); @Override boolean onlyAllowsLocalCalls(); }### Answer: @Test public void shouldBeEnabled() { Assert.assertTrue(method.isEnabled()); }
### Question: GetMultisigScriptHash extends NativeMethod { @Override public boolean onlyAllowsLocalCalls() { return false; } GetMultisigScriptHash(ExecutionEnvironment executionEnvironment); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override long getGas(Object[] parsedArguments, byte[] originalData); @Override boolean isEnabled(); @Override boolean onlyAllowsLocalCalls(); }### Answer: @Test public void shouldAllowAnyTypeOfCall() { Assert.assertFalse(method.onlyAllowsLocalCalls()); }
### Question: ByteUtil { public static byte[] appendByte(byte[] bytes, byte b) { byte[] result = Arrays.copyOf(bytes, bytes.length + 1); result[result.length - 1] = b; return result; } private ByteUtil(); static byte[] appendByte(byte[] bytes, byte b); static byte[] cloneBytes(byte[] bytes); static byte[] bigIntegerToBytes(BigInteger b, int numBytes); static byte[] bigIntegerToBytes(BigInteger value); static byte[] parseBytes(byte[] input, int offset, int len); static byte[] parseWord(byte[] input, int idx); static byte[] parseWord(byte[] input, int offset, int idx); static int matchingNibbleLength(byte[] a, byte[] b); static byte[] longToBytes(long val); static byte[] longToBytesNoLeadZeroes(long val); static byte[] intToBytes(int val); static byte[] intToBytesNoLeadZeroes(int val); @Nonnull static String toHexStringOrEmpty(@Nullable byte[] data); @Nonnull static String toHexString(@Nonnull byte[] data); @Nonnull static String toHexString(@Nonnull byte[] data, int off, int length); static byte[] calcPacketLength(byte[] msg); static int byteArrayToInt(byte[] b); static long byteArrayToLong(byte[] b); static String nibblesToPrettyString(byte[] nibbles); static String oneByteToHexString(byte value); static int numBytes(String val); static int firstNonZeroByte(byte[] data); static byte[] stripLeadingZeroes(byte[] data); static byte[] stripLeadingZeroes(byte[] data, byte[] valueForZero); static boolean increment(byte[] bytes); static byte[] copyToArray(BigInteger value); static ByteArrayWrapper wrap(byte[] data); static byte[] setBit(byte[] data, int pos, int val); static int getBit(byte[] data, int pos); static byte[] and(byte[] b1, byte[] b2); static byte[] or(byte[] b1, byte[] b2); @java.lang.SuppressWarnings("squid:S3034") static byte[] shiftLeft(byte[] byteArray, int shiftBitCount); @java.lang.SuppressWarnings("squid:S3034") static byte[] shiftRight(byte[] byteArray, int shiftBitCount); static byte[] merge(byte[]... arrays); static boolean isSingleZero(byte[] array); static boolean isAllZeroes(byte[] array); static Set<T> difference(Set<T> setA, Set<T> setB); static int length(byte[]... bytes); static short bigEndianToShort(byte[] bs); static short bigEndianToShort(byte[] bs, int off); static byte[] shortToBytes(short n); static int numberOfLeadingZeros(byte[] bytes); static byte[] leftPadBytes(@Nonnull byte[] original, int newLength); static boolean fastEquals(byte[] left, byte[] right); static final byte[] EMPTY_BYTE_ARRAY; }### Answer: @Test public void testAppendByte() { byte[] bytes = "tes".getBytes(); byte b = 0x74; Assert.assertArrayEquals("test".getBytes(), ByteUtil.appendByte(bytes, b)); }
### Question: GetMultisigScriptHash extends NativeMethod { @Override public long getGas(Object[] parsedArguments, byte[] originalData) { Object[] keys = ((Object[]) parsedArguments[1]); if (keys == null || keys.length < 2) { return BASE_COST; } return BASE_COST + (keys.length - 2) * COST_PER_EXTRA_KEY; } GetMultisigScriptHash(ExecutionEnvironment executionEnvironment); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override long getGas(Object[] parsedArguments, byte[] originalData); @Override boolean isEnabled(); @Override boolean onlyAllowsLocalCalls(); }### Answer: @Test public void gasIsBaseIfLessThanOrEqualstoTwoKeysPassed() { Assert.assertEquals(20_000L, method.getGas(new Object[]{ BigInteger.valueOf(1L), null }, new byte[]{})); Assert.assertEquals(20_000L, method.getGas(new Object[]{ BigInteger.valueOf(1L), new Object[]{ } }, new byte[]{})); Assert.assertEquals(20_000L, method.getGas(new Object[]{ BigInteger.valueOf(1L), new Object[]{ Hex.decode("02566d5ded7c7db1aa7ee4ef6f76989fb42527fcfdcddcd447d6793b7d869e46f7") } }, new byte[]{})); Assert.assertEquals(20_000L, method.getGas(new Object[]{ BigInteger.valueOf(1L), new Object[]{ Hex.decode("02566d5ded7c7db1aa7ee4ef6f76989fb42527fcfdcddcd447d6793b7d869e46f7"), Hex.decode("aabbcc") } }, new byte[]{})); }
### Question: DeriveExtendedPublicKey extends NativeMethod { @Override public CallTransaction.Function getFunction() { return function; } DeriveExtendedPublicKey(ExecutionEnvironment executionEnvironment, HDWalletUtilsHelper helper); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override boolean isEnabled(); @Override boolean onlyAllowsLocalCalls(); @Override long getGas(Object[] parsedArguments, byte[] originalData); }### Answer: @Test public void functionSignatureOk() { CallTransaction.Function fn = method.getFunction(); Assert.assertEquals("deriveExtendedPublicKey", fn.name); Assert.assertEquals(2, fn.inputs.length); Assert.assertEquals(SolidityType.getType("string").getName(), fn.inputs[0].type.getName()); Assert.assertEquals(SolidityType.getType("string").getName(), fn.inputs[1].type.getName()); Assert.assertEquals(1, fn.outputs.length); Assert.assertEquals(SolidityType.getType("string").getName(), fn.outputs[0].type.getName()); }
### Question: DeriveExtendedPublicKey extends NativeMethod { @Override public boolean isEnabled() { return true; } DeriveExtendedPublicKey(ExecutionEnvironment executionEnvironment, HDWalletUtilsHelper helper); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override boolean isEnabled(); @Override boolean onlyAllowsLocalCalls(); @Override long getGas(Object[] parsedArguments, byte[] originalData); }### Answer: @Test public void shouldBeEnabled() { Assert.assertTrue(method.isEnabled()); }
### Question: DeriveExtendedPublicKey extends NativeMethod { @Override public boolean onlyAllowsLocalCalls() { return false; } DeriveExtendedPublicKey(ExecutionEnvironment executionEnvironment, HDWalletUtilsHelper helper); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override boolean isEnabled(); @Override boolean onlyAllowsLocalCalls(); @Override long getGas(Object[] parsedArguments, byte[] originalData); }### Answer: @Test public void shouldAllowAnyTypeOfCall() { Assert.assertFalse(method.onlyAllowsLocalCalls()); }
### Question: ByteUtil { public static byte[] bigIntegerToBytes(BigInteger b, int numBytes) { if (b == null) { return EMPTY_BYTE_ARRAY; } byte[] bytes = new byte[numBytes]; byte[] biBytes = b.toByteArray(); int start = (biBytes.length == numBytes + 1) ? 1 : 0; int length = Math.min(biBytes.length, numBytes); System.arraycopy(biBytes, start, bytes, numBytes - length, length); return bytes; } private ByteUtil(); static byte[] appendByte(byte[] bytes, byte b); static byte[] cloneBytes(byte[] bytes); static byte[] bigIntegerToBytes(BigInteger b, int numBytes); static byte[] bigIntegerToBytes(BigInteger value); static byte[] parseBytes(byte[] input, int offset, int len); static byte[] parseWord(byte[] input, int idx); static byte[] parseWord(byte[] input, int offset, int idx); static int matchingNibbleLength(byte[] a, byte[] b); static byte[] longToBytes(long val); static byte[] longToBytesNoLeadZeroes(long val); static byte[] intToBytes(int val); static byte[] intToBytesNoLeadZeroes(int val); @Nonnull static String toHexStringOrEmpty(@Nullable byte[] data); @Nonnull static String toHexString(@Nonnull byte[] data); @Nonnull static String toHexString(@Nonnull byte[] data, int off, int length); static byte[] calcPacketLength(byte[] msg); static int byteArrayToInt(byte[] b); static long byteArrayToLong(byte[] b); static String nibblesToPrettyString(byte[] nibbles); static String oneByteToHexString(byte value); static int numBytes(String val); static int firstNonZeroByte(byte[] data); static byte[] stripLeadingZeroes(byte[] data); static byte[] stripLeadingZeroes(byte[] data, byte[] valueForZero); static boolean increment(byte[] bytes); static byte[] copyToArray(BigInteger value); static ByteArrayWrapper wrap(byte[] data); static byte[] setBit(byte[] data, int pos, int val); static int getBit(byte[] data, int pos); static byte[] and(byte[] b1, byte[] b2); static byte[] or(byte[] b1, byte[] b2); @java.lang.SuppressWarnings("squid:S3034") static byte[] shiftLeft(byte[] byteArray, int shiftBitCount); @java.lang.SuppressWarnings("squid:S3034") static byte[] shiftRight(byte[] byteArray, int shiftBitCount); static byte[] merge(byte[]... arrays); static boolean isSingleZero(byte[] array); static boolean isAllZeroes(byte[] array); static Set<T> difference(Set<T> setA, Set<T> setB); static int length(byte[]... bytes); static short bigEndianToShort(byte[] bs); static short bigEndianToShort(byte[] bs, int off); static byte[] shortToBytes(short n); static int numberOfLeadingZeros(byte[] bytes); static byte[] leftPadBytes(@Nonnull byte[] original, int newLength); static boolean fastEquals(byte[] left, byte[] right); static final byte[] EMPTY_BYTE_ARRAY; }### Answer: @Test public void testBigIntegerToBytes() { byte[] expecteds = new byte[]{(byte) 0xff, (byte) 0xec, 0x78}; BigInteger b = BigInteger.valueOf(16772216); byte[] actuals = ByteUtil.bigIntegerToBytes(b); assertArrayEquals(expecteds, actuals); } @Test public void testBigIntegerToBytesNegative() { byte[] expecteds = new byte[]{(byte) 0xff, 0x0, 0x13, (byte) 0x88}; BigInteger b = BigInteger.valueOf(-16772216); byte[] actuals = ByteUtil.bigIntegerToBytes(b); assertArrayEquals(expecteds, actuals); } @Test public void testBigIntegerToBytesZero() { byte[] expecteds = new byte[]{0x00}; BigInteger b = BigInteger.ZERO; byte[] actuals = ByteUtil.bigIntegerToBytes(b); assertArrayEquals(expecteds, actuals); }
### Question: DeriveExtendedPublicKey extends NativeMethod { @Override public long getGas(Object[] parsedArguments, byte[] originalData) { return 107_000L; } DeriveExtendedPublicKey(ExecutionEnvironment executionEnvironment, HDWalletUtilsHelper helper); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override boolean isEnabled(); @Override boolean onlyAllowsLocalCalls(); @Override long getGas(Object[] parsedArguments, byte[] originalData); }### Answer: @Test public void gasIsCorrect() { Assert.assertEquals(107_000, method.getGas(new Object[]{ "tpubD6NzVbkrYhZ4YHQqwWz3Tm1ESZ9AidobeyLG4mEezB6hN8gFFWrcjczyF77Lw3HEs6Rjd2R11BEJ8Y9ptfxx9DFknkdujp58mFMx9H5dc1r", "2/3/4" }, new byte[]{})); }
### Question: HDWalletUtilsHelper { public NetworkParameters validateAndExtractNetworkFromExtendedPublicKey(String xpub) { if (xpub == null) { throw new NativeContractIllegalArgumentException(String.format("Invalid extended public key '%s'", xpub)); } if (xpub.startsWith("xpub")) { return NetworkParameters.fromID(NetworkParameters.ID_MAINNET); } else if (xpub.startsWith("tpub")) { return NetworkParameters.fromID(NetworkParameters.ID_TESTNET); } else { throw new NativeContractIllegalArgumentException(String.format("Invalid extended public key '%s'", xpub)); } } NetworkParameters validateAndExtractNetworkFromExtendedPublicKey(String xpub); }### Answer: @Test public void validateAndExtractNetworkFromExtendedPublicKeyMainnet() { Assert.assertEquals( NetworkParameters.fromID(NetworkParameters.ID_MAINNET), helper.validateAndExtractNetworkFromExtendedPublicKey("xpubSomethingSomething") ); } @Test public void validateAndExtractNetworkFromExtendedPublicKeyTestnet() { Assert.assertEquals( NetworkParameters.fromID(NetworkParameters.ID_TESTNET), helper.validateAndExtractNetworkFromExtendedPublicKey("tpubSomethingSomething") ); } @Test(expected = NativeContractIllegalArgumentException.class) public void validateAndExtractNetworkFromExtendedPublicKeyInvalid() { helper.validateAndExtractNetworkFromExtendedPublicKey("completelyInvalidStuff"); }
### Question: ToBase58Check extends NativeMethod { @Override public CallTransaction.Function getFunction() { return function; } ToBase58Check(ExecutionEnvironment executionEnvironment); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override boolean isEnabled(); @Override boolean onlyAllowsLocalCalls(); @Override long getGas(Object[] parsedArguments, byte[] originalData); }### Answer: @Test public void functionSignatureOk() { CallTransaction.Function fn = method.getFunction(); Assert.assertEquals("toBase58Check", fn.name); Assert.assertEquals(2, fn.inputs.length); Assert.assertEquals(SolidityType.getType("bytes").getName(), fn.inputs[0].type.getName()); Assert.assertEquals(SolidityType.getType("int256").getName(), fn.inputs[1].type.getName()); Assert.assertEquals(1, fn.outputs.length); Assert.assertEquals(SolidityType.getType("string").getName(), fn.outputs[0].type.getName()); }
### Question: ToBase58Check extends NativeMethod { @Override public boolean isEnabled() { return true; } ToBase58Check(ExecutionEnvironment executionEnvironment); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override boolean isEnabled(); @Override boolean onlyAllowsLocalCalls(); @Override long getGas(Object[] parsedArguments, byte[] originalData); }### Answer: @Test public void shouldBeEnabled() { Assert.assertTrue(method.isEnabled()); }
### Question: ToBase58Check extends NativeMethod { @Override public boolean onlyAllowsLocalCalls() { return false; } ToBase58Check(ExecutionEnvironment executionEnvironment); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override boolean isEnabled(); @Override boolean onlyAllowsLocalCalls(); @Override long getGas(Object[] parsedArguments, byte[] originalData); }### Answer: @Test public void shouldAllowAnyTypeOfCall() { Assert.assertFalse(method.onlyAllowsLocalCalls()); }
### Question: ToBase58Check extends NativeMethod { @Override public Object execute(Object[] arguments) { if (arguments == null) { throw new NativeContractIllegalArgumentException(HASH_NOT_PRESENT); } byte[] hash = (byte[]) arguments[0]; if (hash == null) { throw new NativeContractIllegalArgumentException(HASH_NOT_PRESENT); } if (hash.length != 20) { throw new NativeContractIllegalArgumentException(String.format( HASH_INVALID, ByteUtil.toHexString(hash), hash.length )); } int version = ((BigInteger) arguments[1]).intValueExact(); if (version < 0 || version >= 256) { throw new NativeContractIllegalArgumentException(INVALID_VERSION); } return new ExtendedVersionedChecksummedBytes(version, hash).toBase58(); } ToBase58Check(ExecutionEnvironment executionEnvironment); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override boolean isEnabled(); @Override boolean onlyAllowsLocalCalls(); @Override long getGas(Object[] parsedArguments, byte[] originalData); }### Answer: @Test public void executes() { Assert.assertEquals( "mgivuh9jErcGdRr81cJ3A7YfgbJV7WNyZV", method.execute(new Object[]{ Hex.decode("0d3bf5f30dda7584645546079318e97f0e1d044f"), BigInteger.valueOf(111L) })); } @Test public void validatesHashPresence() { try { method.execute(new Object[]{ Hex.decode("aabbcc"), BigInteger.valueOf(111L) }); Assert.fail(); } catch (NativeContractIllegalArgumentException e) { Assert.assertTrue(e.getMessage().contains("Invalid hash160")); } } @Test public void validatesHashLength() { try { method.execute(new Object[]{ Hex.decode("aabbcc"), BigInteger.valueOf(111L) }); Assert.fail(); } catch (NativeContractIllegalArgumentException e) { Assert.assertTrue(e.getMessage().contains("Invalid hash160")); } } @Test public void validatesVersion() { try { method.execute(new Object[]{ Hex.decode("0d3bf5f30dda7584645546079318e97f0e1d044f"), BigInteger.valueOf(-1L) }); Assert.fail(); } catch (NativeContractIllegalArgumentException e) { Assert.assertTrue(e.getMessage().contains("version must be a numeric value between 0 and 255")); } try { method.execute(new Object[]{ Hex.decode("0d3bf5f30dda7584645546079318e97f0e1d044f"), BigInteger.valueOf(256L) }); Assert.fail(); } catch (NativeContractIllegalArgumentException e) { Assert.assertTrue(e.getMessage().contains("version must be a numeric value between 0 and 255")); } }
### Question: ToBase58Check extends NativeMethod { @Override public long getGas(Object[] parsedArguments, byte[] originalData) { return 13_000L; } ToBase58Check(ExecutionEnvironment executionEnvironment); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override boolean isEnabled(); @Override boolean onlyAllowsLocalCalls(); @Override long getGas(Object[] parsedArguments, byte[] originalData); }### Answer: @Test public void gasIsCorrect() { Assert.assertEquals(13_000, method.getGas(new Object[]{ Hex.decode("0d3bf5f30dda7584645546079318e97f0e1d044f"), BigInteger.valueOf(111L) }, new byte[]{})); }
### Question: HDWalletUtils extends NativeContract { @Override public Optional<NativeMethod> getDefaultMethod() { return Optional.empty(); } HDWalletUtils(ActivationConfig config, RskAddress contractAddress); @Override List<NativeMethod> getMethods(); @Override Optional<NativeMethod> getDefaultMethod(); }### Answer: @Test public void hasNoDefaultMethod() { Assert.assertFalse(contract.getDefaultMethod().isPresent()); }
### Question: HDWalletUtils extends NativeContract { @Override public List<NativeMethod> getMethods() { return Arrays.asList( new ToBase58Check(getExecutionEnvironment()), new DeriveExtendedPublicKey(getExecutionEnvironment(), helper), new ExtractPublicKeyFromExtendedPublicKey(getExecutionEnvironment(), helper), new GetMultisigScriptHash(getExecutionEnvironment()) ); } HDWalletUtils(ActivationConfig config, RskAddress contractAddress); @Override List<NativeMethod> getMethods(); @Override Optional<NativeMethod> getDefaultMethod(); }### Answer: @Test public void hasFourMethods() { Assert.assertEquals(4, contract.getMethods().size()); }
### Question: BlockAccessor { public Optional<Block> getBlock(short blockDepth, ExecutionEnvironment environment) { if (blockDepth < 0) { throw new NativeContractIllegalArgumentException(String.format( "Invalid block depth '%d' (should be a non-negative value)", blockDepth )); } if (blockDepth >= maximumBlockDepth) { return Optional.empty(); } Block block = environment.getBlockStore().getBlockAtDepthStartingAt(blockDepth, environment.getBlock().getParentHash().getBytes()); if (block == null) { return Optional.empty(); } return Optional.of(block); } BlockAccessor(short maximumBlockDepth); Optional<Block> getBlock(short blockDepth, ExecutionEnvironment environment); }### Answer: @Test public void getBlockBeyondMaximumBlockDepth() { executionEnvironment = mock(ExecutionEnvironment.class); Assert.assertFalse(blockAccessor.getBlock(MAXIMUM_BLOCK_DEPTH, executionEnvironment).isPresent()); Assert.assertFalse(blockAccessor.getBlock((short) (MAXIMUM_BLOCK_DEPTH + 1), executionEnvironment).isPresent()); } @Test(expected = NativeContractIllegalArgumentException.class) public void getBlockWithNegativeDepth() { executionEnvironment = mock(ExecutionEnvironment.class); blockAccessor.getBlock(NEGATIVE_BLOCK_DEPTH, executionEnvironment); } @Test public void getGenesisBlock() { ExecutionEnvironment executionEnvironment = EnvironmentUtils.getEnvironmentWithBlockchainOfLength(1); Optional<Block> genesis = blockAccessor.getBlock(ZERO_BLOCK_DEPTH, executionEnvironment); Optional<Block> firstBlock = blockAccessor.getBlock(ONE_BLOCK_DEPTH, executionEnvironment); Assert.assertTrue(genesis.isPresent()); Assert.assertFalse(firstBlock.isPresent()); Assert.assertEquals(0, genesis.get().getNumber()); } @Test public void getTenBlocksFromTheTip() { ExecutionEnvironment executionEnvironment = EnvironmentUtils.getEnvironmentWithBlockchainOfLength(100); for(short i = 0; i < 10; i++) { Optional<Block> block = blockAccessor.getBlock(i, executionEnvironment); Assert.assertTrue(block.isPresent()); Assert.assertEquals(99 - i, block.get().getNumber()); } }
### Question: ByteUtil { @Nonnull public static String toHexString(@Nonnull byte[] data) { return Hex.toHexString(Objects.requireNonNull(data)); } private ByteUtil(); static byte[] appendByte(byte[] bytes, byte b); static byte[] cloneBytes(byte[] bytes); static byte[] bigIntegerToBytes(BigInteger b, int numBytes); static byte[] bigIntegerToBytes(BigInteger value); static byte[] parseBytes(byte[] input, int offset, int len); static byte[] parseWord(byte[] input, int idx); static byte[] parseWord(byte[] input, int offset, int idx); static int matchingNibbleLength(byte[] a, byte[] b); static byte[] longToBytes(long val); static byte[] longToBytesNoLeadZeroes(long val); static byte[] intToBytes(int val); static byte[] intToBytesNoLeadZeroes(int val); @Nonnull static String toHexStringOrEmpty(@Nullable byte[] data); @Nonnull static String toHexString(@Nonnull byte[] data); @Nonnull static String toHexString(@Nonnull byte[] data, int off, int length); static byte[] calcPacketLength(byte[] msg); static int byteArrayToInt(byte[] b); static long byteArrayToLong(byte[] b); static String nibblesToPrettyString(byte[] nibbles); static String oneByteToHexString(byte value); static int numBytes(String val); static int firstNonZeroByte(byte[] data); static byte[] stripLeadingZeroes(byte[] data); static byte[] stripLeadingZeroes(byte[] data, byte[] valueForZero); static boolean increment(byte[] bytes); static byte[] copyToArray(BigInteger value); static ByteArrayWrapper wrap(byte[] data); static byte[] setBit(byte[] data, int pos, int val); static int getBit(byte[] data, int pos); static byte[] and(byte[] b1, byte[] b2); static byte[] or(byte[] b1, byte[] b2); @java.lang.SuppressWarnings("squid:S3034") static byte[] shiftLeft(byte[] byteArray, int shiftBitCount); @java.lang.SuppressWarnings("squid:S3034") static byte[] shiftRight(byte[] byteArray, int shiftBitCount); static byte[] merge(byte[]... arrays); static boolean isSingleZero(byte[] array); static boolean isAllZeroes(byte[] array); static Set<T> difference(Set<T> setA, Set<T> setB); static int length(byte[]... bytes); static short bigEndianToShort(byte[] bs); static short bigEndianToShort(byte[] bs, int off); static byte[] shortToBytes(short n); static int numberOfLeadingZeros(byte[] bytes); static byte[] leftPadBytes(@Nonnull byte[] original, int newLength); static boolean fastEquals(byte[] left, byte[] right); static final byte[] EMPTY_BYTE_ARRAY; }### Answer: @Test public void testToHexString_ProducedHex() { byte[] data = new byte[] {(byte) 0xff, 0x0, 0x13, (byte) 0x88}; assertEquals(Hex.toHexString(data), ByteUtil.toHexString(data)); } @Test(expected = NullPointerException.class) public void testToHexString_NullPointerExceptionForNull() { assertEquals("", ByteUtil.toHexString(null)); }
### Question: BlockHeaderContract extends NativeContract { @Override public Optional<NativeMethod> getDefaultMethod() { return Optional.empty(); } BlockHeaderContract(ActivationConfig activationConfig, RskAddress contractAddress); @Override List<NativeMethod> getMethods(); @Override Optional<NativeMethod> getDefaultMethod(); }### Answer: @Test public void hasNoDefaultMethod() { Assert.assertFalse(contract.getDefaultMethod().isPresent()); }
### Question: BlockHeaderContract extends NativeContract { @Override public List<NativeMethod> getMethods() { return Arrays.asList( new GetCoinbaseAddress(getExecutionEnvironment(), this.blockAccessor), new GetBlockHash(getExecutionEnvironment(), this.blockAccessor), new GetMergedMiningTags(getExecutionEnvironment(), this.blockAccessor), new GetMinimumGasPrice(getExecutionEnvironment(), this.blockAccessor), new GetGasLimit(getExecutionEnvironment(), this.blockAccessor), new GetGasUsed(getExecutionEnvironment(), this.blockAccessor), new GetDifficulty(getExecutionEnvironment(), this.blockAccessor), new GetBitcoinHeader(getExecutionEnvironment(), this.blockAccessor), new GetUncleCoinbaseAddress(getExecutionEnvironment(), this.blockAccessor) ); } BlockHeaderContract(ActivationConfig activationConfig, RskAddress contractAddress); @Override List<NativeMethod> getMethods(); @Override Optional<NativeMethod> getDefaultMethod(); }### Answer: @Test public void hasNineMethods() { Assert.assertEquals(9, contract.getMethods().size()); }
### Question: NativeMethod { public ExecutionEnvironment getExecutionEnvironment() { return executionEnvironment; } NativeMethod(ExecutionEnvironment executionEnvironment); ExecutionEnvironment getExecutionEnvironment(); abstract CallTransaction.Function getFunction(); abstract Object execute(Object[] arguments); long getGas(Object[] parsedArguments, byte[] originalData); abstract boolean isEnabled(); abstract boolean onlyAllowsLocalCalls(); String getName(); }### Answer: @Test public void executionEnvironmentGetter() { Assert.assertEquals(executionEnvironment, method.getExecutionEnvironment()); }
### Question: NativeMethod { public long getGas(Object[] parsedArguments, byte[] originalData) { return originalData == null ? 0 : originalData.length * 2; } NativeMethod(ExecutionEnvironment executionEnvironment); ExecutionEnvironment getExecutionEnvironment(); abstract CallTransaction.Function getFunction(); abstract Object execute(Object[] arguments); long getGas(Object[] parsedArguments, byte[] originalData); abstract boolean isEnabled(); abstract boolean onlyAllowsLocalCalls(); String getName(); }### Answer: @Test public void getGasWithNullData() { Assert.assertEquals(0L, method.getGas(null, null)); } @Test public void getGasWithNonNullData() { Assert.assertEquals(6L, method.getGas(null, Hex.decode("aabbcc"))); Assert.assertEquals(10L, method.getGas(null, Hex.decode("aabbccddee"))); } @Test public void withArgumentsGetsGas() { Assert.assertEquals(6L, withArguments.getGas()); }
### Question: NativeMethod { public String getName() { return getFunction().name; } NativeMethod(ExecutionEnvironment executionEnvironment); ExecutionEnvironment getExecutionEnvironment(); abstract CallTransaction.Function getFunction(); abstract Object execute(Object[] arguments); long getGas(Object[] parsedArguments, byte[] originalData); abstract boolean isEnabled(); abstract boolean onlyAllowsLocalCalls(); String getName(); }### Answer: @Test public void getName() { function.name = "a-method-name"; Assert.assertEquals("a-method-name", method.getName()); }
### Question: NativeMethod { public abstract Object execute(Object[] arguments); NativeMethod(ExecutionEnvironment executionEnvironment); ExecutionEnvironment getExecutionEnvironment(); abstract CallTransaction.Function getFunction(); abstract Object execute(Object[] arguments); long getGas(Object[] parsedArguments, byte[] originalData); abstract boolean isEnabled(); abstract boolean onlyAllowsLocalCalls(); String getName(); }### Answer: @Test public void withArgumentsExecutesMethod() { Assert.assertEquals("execution-result", withArguments.execute()); }
### Question: NativeContract extends PrecompiledContracts.PrecompiledContract { public ExecutionEnvironment getExecutionEnvironment() { return executionEnvironment; } NativeContract(ActivationConfig activationConfig, RskAddress contractAddress); ExecutionEnvironment getExecutionEnvironment(); abstract List<NativeMethod> getMethods(); abstract Optional<NativeMethod> getDefaultMethod(); void before(); void after(); @Override void init(Transaction tx, Block executionBlock, Repository repository, BlockStore blockStore, ReceiptStore receiptStore, List<LogInfo> logs); @Override long getGasForData(byte[] data); @Override byte[] execute(byte[] data); }### Answer: @Test public void createsExecutionEnvironmentUponInit() { Assert.assertNull(contract.getExecutionEnvironment()); doInit(); ExecutionEnvironment executionEnvironment = contract.getExecutionEnvironment(); Assert.assertNotNull(executionEnvironment); Assert.assertEquals(tx, executionEnvironment.getTransaction()); Assert.assertEquals(block, executionEnvironment.getBlock()); Assert.assertEquals(repository, executionEnvironment.getRepository()); Assert.assertEquals(blockStore, executionEnvironment.getBlockStore()); Assert.assertEquals(receiptStore, executionEnvironment.getReceiptStore()); Assert.assertEquals(logs, executionEnvironment.getLogs()); }
### Question: NativeContract extends PrecompiledContracts.PrecompiledContract { @Override public long getGasForData(byte[] data) { if (executionEnvironment == null) { throw new RuntimeException("Execution environment is null"); } Optional<NativeMethod.WithArguments> methodWithArguments = parseData(data); if (!methodWithArguments.isPresent()) { return 0L; } return methodWithArguments.get().getGas(); } NativeContract(ActivationConfig activationConfig, RskAddress contractAddress); ExecutionEnvironment getExecutionEnvironment(); abstract List<NativeMethod> getMethods(); abstract Optional<NativeMethod> getDefaultMethod(); void before(); void after(); @Override void init(Transaction tx, Block executionBlock, Repository repository, BlockStore blockStore, ReceiptStore receiptStore, List<LogInfo> logs); @Override long getGasForData(byte[] data); @Override byte[] execute(byte[] data); }### Answer: @Test public void getGasForDataFailsWhenNoInit() { assertFails(() -> contract.getGasForData(Hex.decode("aabb"))); } @Test public void getGasForDataZeroWhenNullData() { doInit(); Assert.assertEquals(0L, contract.getGasForData(null)); } @Test public void getGasForDataZeroWhenEmptyData() { doInit(); Assert.assertEquals(0L, contract.getGasForData(null)); } @Test public void getGasForNullDataAndDefaultMethod() { NativeMethod method = mock(NativeMethod.class); when(method.getGas(any(), any())).thenReturn(10L); contract = new EmptyNativeContract(activationConfig) { @Override public Optional<NativeMethod> getDefaultMethod() { return Optional.of(method); } }; doInit(); Assert.assertEquals(10L, contract.getGasForData(null)); } @Test public void getGasForEmptyDataAndDefaultMethod() { NativeMethod method = mock(NativeMethod.class); when(method.getGas(any(), any())).thenReturn(10L); contract = new EmptyNativeContract(activationConfig) { @Override public Optional<NativeMethod> getDefaultMethod() { return Optional.of(method); } }; doInit(); Assert.assertEquals(10L, contract.getGasForData(new byte[]{})); } @Test public void getGasForDataZeroWhenInvalidSignature() { doInit(); Assert.assertEquals(0L, contract.getGasForData(Hex.decode("aabb"))); } @Test public void getGasForDataZeroWhenNoMappedMethod() { doInit(); Assert.assertEquals(0L, contract.getGasForData(Hex.decode("aabbccdd"))); }
### Question: Migrator { public String migrateConfiguration() throws IOException { return migrateConfiguration( Files.newBufferedReader(configuration.getSourceConfiguration(), StandardCharsets.UTF_8), configuration.getMigrationConfiguration() ); } Migrator(MigratorConfiguration configuration); String migrateConfiguration(); static String migrateConfiguration(Reader sourceReader, Properties migrationConfiguration); }### Answer: @Test public void migrateConfiguration() { Reader initialConfiguration = new StringReader("inline.config.name=\"value\"\n" + "nested {\n" + " nested = {\n" + " #test comment\n" + " config = 13\n" + " }\n" + "}\n" + "flat.config = \"0.0.0.0\"\n" + "another.config=\"don't change\""); Properties migrationProperties = new Properties(); migrationProperties.put("inline.config.name", "inline.config.new.name"); migrationProperties.put("flat.config", "flat_config"); migrationProperties.put("nested.nested.config", "nested.nested.new.config"); migrationProperties.put("unknown.config", "none"); migrationProperties.put("[new]new.key", "new value"); migrationProperties.put("[new] other.new.key", "12"); String migratedConfiguration = Migrator.migrateConfiguration(initialConfiguration, migrationProperties); Config config = ConfigFactory.parseString(migratedConfiguration); assertThat(config.hasPath("inline.config.name"), is(false)); assertThat(config.getString("inline.config.new.name"), is("value")); assertThat(config.hasPath("flat.config"), is(false)); assertThat(config.hasPath("flat_config"), is(true)); assertThat(config.getString("flat_config"), is("0.0.0.0")); assertThat(config.hasPath("nested.nested.config"), is(false)); assertThat(config.getInt("nested.nested.new.config"), is(13)); assertThat(config.hasPath("unknown.config"), is(false)); assertThat(config.getString("another.config"), is("don't change")); assertThat(config.getString("new.key"), is("new value")); assertThat(config.getInt("other.new.key"), is(12)); }
### Question: PeerScoringManager { public boolean hasGoodReputation(NodeID id) { synchronized (accessLock) { return this.getPeerScoring(id).hasGoodReputation(); } } PeerScoringManager( PeerScoring.Factory peerScoringFactory, int nodePeersSize, PunishmentParameters nodeParameters, PunishmentParameters ipParameters); void recordEvent(NodeID id, InetAddress address, EventType event); boolean hasGoodReputation(NodeID id); boolean hasGoodReputation(InetAddress address); void banAddress(InetAddress address); void banAddress(String address); void unbanAddress(InetAddress address); void unbanAddress(String address); void banAddressBlock(InetAddressBlock addressBlock); void unbanAddressBlock(InetAddressBlock addressBlock); List<PeerScoringInformation> getPeersInformation(); List<String> getBannedAddresses(); @VisibleForTesting boolean isEmpty(); @VisibleForTesting PeerScoring getPeerScoring(NodeID id); @VisibleForTesting PeerScoring getPeerScoring(InetAddress address); }### Answer: @Test public void newNodeHasGoodReputation() { NodeID id = generateNodeID(); PeerScoringManager manager = createPeerScoringManager(); Assert.assertTrue(manager.hasGoodReputation(id)); } @Test public void newAddressHasGoodReputation() throws UnknownHostException { InetAddress address = generateIPAddressV4(); PeerScoringManager manager = createPeerScoringManager(); Assert.assertTrue(manager.hasGoodReputation(address)); }
### Question: ByteUtil { @Nonnull public static String toHexStringOrEmpty(@Nullable byte[] data) { return data == null ? "" : toHexString(data); } private ByteUtil(); static byte[] appendByte(byte[] bytes, byte b); static byte[] cloneBytes(byte[] bytes); static byte[] bigIntegerToBytes(BigInteger b, int numBytes); static byte[] bigIntegerToBytes(BigInteger value); static byte[] parseBytes(byte[] input, int offset, int len); static byte[] parseWord(byte[] input, int idx); static byte[] parseWord(byte[] input, int offset, int idx); static int matchingNibbleLength(byte[] a, byte[] b); static byte[] longToBytes(long val); static byte[] longToBytesNoLeadZeroes(long val); static byte[] intToBytes(int val); static byte[] intToBytesNoLeadZeroes(int val); @Nonnull static String toHexStringOrEmpty(@Nullable byte[] data); @Nonnull static String toHexString(@Nonnull byte[] data); @Nonnull static String toHexString(@Nonnull byte[] data, int off, int length); static byte[] calcPacketLength(byte[] msg); static int byteArrayToInt(byte[] b); static long byteArrayToLong(byte[] b); static String nibblesToPrettyString(byte[] nibbles); static String oneByteToHexString(byte value); static int numBytes(String val); static int firstNonZeroByte(byte[] data); static byte[] stripLeadingZeroes(byte[] data); static byte[] stripLeadingZeroes(byte[] data, byte[] valueForZero); static boolean increment(byte[] bytes); static byte[] copyToArray(BigInteger value); static ByteArrayWrapper wrap(byte[] data); static byte[] setBit(byte[] data, int pos, int val); static int getBit(byte[] data, int pos); static byte[] and(byte[] b1, byte[] b2); static byte[] or(byte[] b1, byte[] b2); @java.lang.SuppressWarnings("squid:S3034") static byte[] shiftLeft(byte[] byteArray, int shiftBitCount); @java.lang.SuppressWarnings("squid:S3034") static byte[] shiftRight(byte[] byteArray, int shiftBitCount); static byte[] merge(byte[]... arrays); static boolean isSingleZero(byte[] array); static boolean isAllZeroes(byte[] array); static Set<T> difference(Set<T> setA, Set<T> setB); static int length(byte[]... bytes); static short bigEndianToShort(byte[] bs); static short bigEndianToShort(byte[] bs, int off); static byte[] shortToBytes(short n); static int numberOfLeadingZeros(byte[] bytes); static byte[] leftPadBytes(@Nonnull byte[] original, int newLength); static boolean fastEquals(byte[] left, byte[] right); static final byte[] EMPTY_BYTE_ARRAY; }### Answer: @Test public void testToHexStringOrEmpty_EmptyStringForNull() { assertEquals("", ByteUtil.toHexStringOrEmpty(null)); }
### Question: PunishmentCalculator { public long calculate(int punishmentCounter, int score) { long result = this.parameters.getDuration(); long rate = 100L + this.parameters.getIncrementRate(); int counter = punishmentCounter; long maxDuration = this.parameters.getMaximumDuration(); while (counter-- > 0) { result = multiplyExact(result, rate) / 100; if (maxDuration > 0 && result > maxDuration) { return maxDuration; } } if (score < 0) { result *= -score; } return maxDuration > 0 ? Math.min(maxDuration, result) : result; } PunishmentCalculator(PunishmentParameters parameters); long calculate(int punishmentCounter, int score); }### Answer: @Test public void calculatePunishmentTime() { PunishmentCalculator calculator = new PunishmentCalculator(new PunishmentParameters(100, 10, 1000)); Assert.assertEquals(100, calculator.calculate(0, 0)); } @Test public void calculatePunishmentTimeWithNegativeScore() { PunishmentCalculator calculator = new PunishmentCalculator(new PunishmentParameters(100, 10, 1000)); Assert.assertEquals(200, calculator.calculate(0, -2)); } @Test public void calculateSecondPunishmentTime() { PunishmentCalculator calculator = new PunishmentCalculator(new PunishmentParameters(100, 10, 1000)); Assert.assertEquals(110, calculator.calculate(1, 0)); } @Test public void calculateThirdPunishmentTime() { PunishmentCalculator calculator = new PunishmentCalculator(new PunishmentParameters(100, 10, 1000)); Assert.assertEquals(121, calculator.calculate(2, 0)); } @Test public void calculateThirdPunishmentTimeAndNegativeScore() { PunishmentCalculator calculator = new PunishmentCalculator(new PunishmentParameters(100, 10, 1000)); Assert.assertEquals(242, calculator.calculate(2, -2)); } @Test public void calculateUsingMaxPunishmentTime() { PunishmentCalculator calculator = new PunishmentCalculator(new PunishmentParameters(100, 10, 120)); Assert.assertEquals(120, calculator.calculate(2, 0)); } @Test public void calculateUsingNoMaxPunishmentTime() { PunishmentCalculator calculator = new PunishmentCalculator(new PunishmentParameters(100, 10, 0)); Assert.assertEquals(121, calculator.calculate(2, 0)); }
### Question: PeerScoring { public boolean hasGoodReputation() { try { rwlock.writeLock().lock(); if (this.goodReputation) { return true; } if (this.punishmentTime > 0 && this.timeLostGoodReputation > 0 && this.punishmentTime + this.timeLostGoodReputation <= System.currentTimeMillis()) { this.endPunishment(); } return this.goodReputation; } finally { rwlock.writeLock().unlock(); } } PeerScoring(); PeerScoring(boolean punishmentEnabled); void recordEvent(EventType evt); int getScore(); int getEventCounter(EventType evt); int getTotalEventCounter(); boolean isEmpty(); boolean hasGoodReputation(); @VisibleForTesting void startPunishment(long expirationTime); @VisibleForTesting long getPunishmentTime(); int getPunishmentCounter(); @VisibleForTesting long getTimeLostGoodReputation(); }### Answer: @Test public void newStatusHasGoodReputation() { PeerScoring scoring = new PeerScoring(); Assert.assertTrue(scoring.hasGoodReputation()); }
### Question: PeerScoring { public int getScore() { try { rwlock.readLock().lock(); return score; } finally { rwlock.readLock().unlock(); } } PeerScoring(); PeerScoring(boolean punishmentEnabled); void recordEvent(EventType evt); int getScore(); int getEventCounter(EventType evt); int getTotalEventCounter(); boolean isEmpty(); boolean hasGoodReputation(); @VisibleForTesting void startPunishment(long expirationTime); @VisibleForTesting long getPunishmentTime(); int getPunishmentCounter(); @VisibleForTesting long getTimeLostGoodReputation(); }### Answer: @Test public void getInformationFromNewScoring() { PeerScoring scoring = new PeerScoring(); PeerScoringInformation info = new PeerScoringInformation(scoring, "nodeid", "node"); Assert.assertTrue(info.getGoodReputation()); Assert.assertEquals(0, info.getValidBlocks()); Assert.assertEquals(0, info.getInvalidBlocks()); Assert.assertEquals(0, info.getValidTransactions()); Assert.assertEquals(0, info.getInvalidTransactions()); Assert.assertEquals(0, info.getScore()); Assert.assertEquals(0, info.getSuccessfulHandshakes()); Assert.assertEquals(0, info.getFailedHandshakes()); Assert.assertEquals(0, info.getRepeatedMessages()); Assert.assertEquals(0, info.getInvalidNetworks()); Assert.assertEquals("nodeid", info.getId()); Assert.assertEquals("node", info.getType()); } @Test public void getZeroScoreWhenEmpty() { PeerScoring scoring = new PeerScoring(); Assert.assertEquals(0, scoring.getScore()); }
### Question: PeerScoring { @VisibleForTesting public long getTimeLostGoodReputation() { return this.timeLostGoodReputation; } PeerScoring(); PeerScoring(boolean punishmentEnabled); void recordEvent(EventType evt); int getScore(); int getEventCounter(EventType evt); int getTotalEventCounter(); boolean isEmpty(); boolean hasGoodReputation(); @VisibleForTesting void startPunishment(long expirationTime); @VisibleForTesting long getPunishmentTime(); int getPunishmentCounter(); @VisibleForTesting long getTimeLostGoodReputation(); }### Answer: @Test public void newStatusHasNoTimeLostGoodReputation() { PeerScoring scoring = new PeerScoring(); Assert.assertEquals(0, scoring.getTimeLostGoodReputation()); }
### Question: ByteUtil { public static byte[] calcPacketLength(byte[] msg) { int msgLen = msg.length; return new byte[]{ (byte) ((msgLen >> 24) & 0xFF), (byte) ((msgLen >> 16) & 0xFF), (byte) ((msgLen >> 8) & 0xFF), (byte) ((msgLen) & 0xFF)}; } private ByteUtil(); static byte[] appendByte(byte[] bytes, byte b); static byte[] cloneBytes(byte[] bytes); static byte[] bigIntegerToBytes(BigInteger b, int numBytes); static byte[] bigIntegerToBytes(BigInteger value); static byte[] parseBytes(byte[] input, int offset, int len); static byte[] parseWord(byte[] input, int idx); static byte[] parseWord(byte[] input, int offset, int idx); static int matchingNibbleLength(byte[] a, byte[] b); static byte[] longToBytes(long val); static byte[] longToBytesNoLeadZeroes(long val); static byte[] intToBytes(int val); static byte[] intToBytesNoLeadZeroes(int val); @Nonnull static String toHexStringOrEmpty(@Nullable byte[] data); @Nonnull static String toHexString(@Nonnull byte[] data); @Nonnull static String toHexString(@Nonnull byte[] data, int off, int length); static byte[] calcPacketLength(byte[] msg); static int byteArrayToInt(byte[] b); static long byteArrayToLong(byte[] b); static String nibblesToPrettyString(byte[] nibbles); static String oneByteToHexString(byte value); static int numBytes(String val); static int firstNonZeroByte(byte[] data); static byte[] stripLeadingZeroes(byte[] data); static byte[] stripLeadingZeroes(byte[] data, byte[] valueForZero); static boolean increment(byte[] bytes); static byte[] copyToArray(BigInteger value); static ByteArrayWrapper wrap(byte[] data); static byte[] setBit(byte[] data, int pos, int val); static int getBit(byte[] data, int pos); static byte[] and(byte[] b1, byte[] b2); static byte[] or(byte[] b1, byte[] b2); @java.lang.SuppressWarnings("squid:S3034") static byte[] shiftLeft(byte[] byteArray, int shiftBitCount); @java.lang.SuppressWarnings("squid:S3034") static byte[] shiftRight(byte[] byteArray, int shiftBitCount); static byte[] merge(byte[]... arrays); static boolean isSingleZero(byte[] array); static boolean isAllZeroes(byte[] array); static Set<T> difference(Set<T> setA, Set<T> setB); static int length(byte[]... bytes); static short bigEndianToShort(byte[] bs); static short bigEndianToShort(byte[] bs, int off); static byte[] shortToBytes(short n); static int numberOfLeadingZeros(byte[] bytes); static byte[] leftPadBytes(@Nonnull byte[] original, int newLength); static boolean fastEquals(byte[] left, byte[] right); static final byte[] EMPTY_BYTE_ARRAY; }### Answer: @Test public void testCalcPacketLength() { byte[] test = new byte[]{0x0f, 0x10, 0x43}; byte[] expected = new byte[]{0x00, 0x00, 0x00, 0x03}; assertArrayEquals(expected, ByteUtil.calcPacketLength(test)); }
### Question: PeerScoring { public void recordEvent(EventType evt) { try { rwlock.writeLock().lock(); counters[evt.ordinal()]++; switch (evt) { case INVALID_NETWORK: case INVALID_BLOCK: case INVALID_TRANSACTION: case INVALID_MESSAGE: case INVALID_HEADER: if (score > 0) { score = 0; } score--; break; case UNEXPECTED_MESSAGE: case FAILED_HANDSHAKE: case SUCCESSFUL_HANDSHAKE: case REPEATED_MESSAGE: break; default: if (score >= 0) { score++; } break; } } finally { rwlock.writeLock().unlock(); } } PeerScoring(); PeerScoring(boolean punishmentEnabled); void recordEvent(EventType evt); int getScore(); int getEventCounter(EventType evt); int getTotalEventCounter(); boolean isEmpty(); boolean hasGoodReputation(); @VisibleForTesting void startPunishment(long expirationTime); @VisibleForTesting long getPunishmentTime(); int getPunishmentCounter(); @VisibleForTesting long getTimeLostGoodReputation(); }### Answer: @Test public void recordEvent() { PeerScoring scoring = new PeerScoring(); scoring.recordEvent(EventType.INVALID_BLOCK); Assert.assertEquals(1, scoring.getEventCounter(EventType.INVALID_BLOCK)); Assert.assertEquals(0, scoring.getEventCounter(EventType.INVALID_TRANSACTION)); Assert.assertEquals(1, scoring.getTotalEventCounter()); }
### Question: PeerScoring { @VisibleForTesting public void startPunishment(long expirationTime) { if (!punishmentEnabled) { return; } try { rwlock.writeLock().lock(); this.goodReputation = false; this.punishmentTime = expirationTime; this.punishmentCounter++; this.timeLostGoodReputation = System.currentTimeMillis(); } finally { rwlock.writeLock().unlock(); } } PeerScoring(); PeerScoring(boolean punishmentEnabled); void recordEvent(EventType evt); int getScore(); int getEventCounter(EventType evt); int getTotalEventCounter(); boolean isEmpty(); boolean hasGoodReputation(); @VisibleForTesting void startPunishment(long expirationTime); @VisibleForTesting long getPunishmentTime(); int getPunishmentCounter(); @VisibleForTesting long getTimeLostGoodReputation(); }### Answer: @Test public void startPunishment() throws InterruptedException { PeerScoring scoring = new PeerScoring(); Assert.assertEquals(0, scoring.getPunishmentTime()); Assert.assertEquals(0, scoring.getPunishmentCounter()); scoring.startPunishment(1000); Assert.assertEquals(1, scoring.getPunishmentCounter()); Assert.assertFalse(scoring.hasGoodReputation()); Assert.assertEquals(1000, scoring.getPunishmentTime()); TimeUnit.MILLISECONDS.sleep(10); Assert.assertFalse(scoring.hasGoodReputation()); TimeUnit.MILLISECONDS.sleep(2000); Assert.assertTrue(scoring.hasGoodReputation()); Assert.assertEquals(1, scoring.getPunishmentCounter()); }
### Question: ByteUtil { public static long byteArrayToLong(byte[] b) { if (b == null || b.length == 0) { return 0; } if (b.length > 8) { throw new IllegalArgumentException("byte array can't have more than 8 bytes if it is to be cast to long"); } long result = 0; for (int i = 0; i < b.length; i++) { result <<= 8; result |= (b[i] & 0xFF); } return result; } private ByteUtil(); static byte[] appendByte(byte[] bytes, byte b); static byte[] cloneBytes(byte[] bytes); static byte[] bigIntegerToBytes(BigInteger b, int numBytes); static byte[] bigIntegerToBytes(BigInteger value); static byte[] parseBytes(byte[] input, int offset, int len); static byte[] parseWord(byte[] input, int idx); static byte[] parseWord(byte[] input, int offset, int idx); static int matchingNibbleLength(byte[] a, byte[] b); static byte[] longToBytes(long val); static byte[] longToBytesNoLeadZeroes(long val); static byte[] intToBytes(int val); static byte[] intToBytesNoLeadZeroes(int val); @Nonnull static String toHexStringOrEmpty(@Nullable byte[] data); @Nonnull static String toHexString(@Nonnull byte[] data); @Nonnull static String toHexString(@Nonnull byte[] data, int off, int length); static byte[] calcPacketLength(byte[] msg); static int byteArrayToInt(byte[] b); static long byteArrayToLong(byte[] b); static String nibblesToPrettyString(byte[] nibbles); static String oneByteToHexString(byte value); static int numBytes(String val); static int firstNonZeroByte(byte[] data); static byte[] stripLeadingZeroes(byte[] data); static byte[] stripLeadingZeroes(byte[] data, byte[] valueForZero); static boolean increment(byte[] bytes); static byte[] copyToArray(BigInteger value); static ByteArrayWrapper wrap(byte[] data); static byte[] setBit(byte[] data, int pos, int val); static int getBit(byte[] data, int pos); static byte[] and(byte[] b1, byte[] b2); static byte[] or(byte[] b1, byte[] b2); @java.lang.SuppressWarnings("squid:S3034") static byte[] shiftLeft(byte[] byteArray, int shiftBitCount); @java.lang.SuppressWarnings("squid:S3034") static byte[] shiftRight(byte[] byteArray, int shiftBitCount); static byte[] merge(byte[]... arrays); static boolean isSingleZero(byte[] array); static boolean isAllZeroes(byte[] array); static Set<T> difference(Set<T> setA, Set<T> setB); static int length(byte[]... bytes); static short bigEndianToShort(byte[] bs); static short bigEndianToShort(byte[] bs, int off); static byte[] shortToBytes(short n); static int numberOfLeadingZeros(byte[] bytes); static byte[] leftPadBytes(@Nonnull byte[] original, int newLength); static boolean fastEquals(byte[] left, byte[] right); static final byte[] EMPTY_BYTE_ARRAY; }### Answer: @Test public void testByteArrayToLong() { assertEquals(Long.MAX_VALUE, ByteUtil.byteArrayToLong(new byte[]{ (byte)127, (byte)255, (byte)255, (byte)255, (byte)255, (byte)255, (byte)255, (byte)255, } )); assertEquals(0, ByteUtil.byteArrayToLong(new byte[]{ } )); } @Test(expected = IllegalArgumentException.class) public void testByteArrayToLongThrowsWhenOverflow() { assertEquals(Long.MAX_VALUE, ByteUtil.byteArrayToLong(new byte[]{ (byte)255, (byte)255, (byte)255, (byte)255, (byte)255, (byte)255, (byte)255, (byte)255, (byte)123, } )); }
### Question: InetAddressBlock { @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (!(obj instanceof InetAddressBlock)) { return false; } InetAddressBlock block = (InetAddressBlock)obj; return block.mask == this.mask && Arrays.equals(block.bytes, this.bytes); } InetAddressBlock(InetAddress address, int bits); boolean contains(InetAddress address); String getDescription(); @Override int hashCode(); @Override boolean equals(Object obj); @VisibleForTesting byte[] getBytes(); @VisibleForTesting byte getMask(); }### Answer: @Test public void equals() throws UnknownHostException { InetAddress address1 = generateIPAddressV4(); InetAddress address2 = alterByte(address1, 0); InetAddress address3 = generateIPAddressV6(); InetAddressBlock block1 = new InetAddressBlock(address1, 8); InetAddressBlock block2 = new InetAddressBlock(address2, 9); InetAddressBlock block3 = new InetAddressBlock(address1, 1); InetAddressBlock block4 = new InetAddressBlock(address1, 8); InetAddressBlock block5 = new InetAddressBlock(address3, 8); Assert.assertTrue(block1.equals(block1)); Assert.assertTrue(block2.equals(block2)); Assert.assertTrue(block3.equals(block3)); Assert.assertTrue(block4.equals(block4)); Assert.assertTrue(block5.equals(block5)); Assert.assertTrue(block1.equals(block4)); Assert.assertTrue(block4.equals(block1)); Assert.assertFalse(block1.equals(block2)); Assert.assertFalse(block1.equals(block3)); Assert.assertFalse(block1.equals(block5)); Assert.assertFalse(block1.equals(null)); Assert.assertFalse(block1.equals("block")); Assert.assertEquals(block1.hashCode(), block4.hashCode()); }
### Question: InetAddressTable { public boolean contains(InetAddress address) { if (this.addresses.contains(address)) { return true; } if (this.blocks.isEmpty()) { return false; } InetAddressBlock[] bs = this.blocks.toArray(new InetAddressBlock[0]); for (InetAddressBlock mask : bs) { if (mask.contains(address)) { return true; } } return false; } void addAddress(InetAddress address); void removeAddress(InetAddress address); void addAddressBlock(InetAddressBlock addressBlock); void removeAddressBlock(InetAddressBlock addressBlock); boolean contains(InetAddress address); List<InetAddress> getAddressList(); List<InetAddressBlock> getAddressBlockList(); }### Answer: @Test public void doesNotContainsNewIPV4Address() throws UnknownHostException { InetAddressTable table = new InetAddressTable(); Assert.assertFalse(table.contains(generateIPAddressV4())); } @Test public void doesNotContainsNewIPV6Address() throws UnknownHostException { InetAddressTable table = new InetAddressTable(); Assert.assertFalse(table.contains(generateIPAddressV6())); }
### Question: InetAddressUtils { public static boolean hasMask(String text) { if (text == null) { return false; } String[] parts = text.split("/"); return parts.length == 2 && parts[0].length() != 0 && parts[1].length() != 0; } private InetAddressUtils(); static boolean hasMask(String text); static InetAddress getAddressForBan(@CheckForNull String hostname); static InetAddressBlock parse(String text); }### Answer: @Test public void hasMask() { Assert.assertFalse(InetAddressUtils.hasMask(null)); Assert.assertFalse(InetAddressUtils.hasMask("/")); Assert.assertFalse(InetAddressUtils.hasMask("1234/")); Assert.assertFalse(InetAddressUtils.hasMask("/1234")); Assert.assertFalse(InetAddressUtils.hasMask("1234/1234/1234")); Assert.assertFalse(InetAddressUtils.hasMask("1234 Assert.assertTrue(InetAddressUtils.hasMask("1234/1234")); }
### Question: InetAddressUtils { public static InetAddress getAddressForBan(@CheckForNull String hostname) throws InvalidInetAddressException { if (hostname == null) { throw new InvalidInetAddressException("null address", null); } String name = hostname.trim(); if (name.length() == 0) { throw new InvalidInetAddressException("empty address", null); } try { InetAddress address = InetAddress.getByName(name); if (address.isLoopbackAddress() || address.isAnyLocalAddress()) { throw new InvalidInetAddressException("local address: '" + name + "'", null); } return address; } catch (UnknownHostException ex) { throw new InvalidInetAddressException("unknown host: '" + name + "'", ex); } } private InetAddressUtils(); static boolean hasMask(String text); static InetAddress getAddressForBan(@CheckForNull String hostname); static InetAddressBlock parse(String text); }### Answer: @Test public void getAddressFromIPV4() throws InvalidInetAddressException { InetAddress address = InetAddressUtils.getAddressForBan("192.168.56.1"); Assert.assertNotNull(address); byte[] bytes = address.getAddress(); Assert.assertNotNull(bytes); Assert.assertEquals(4, bytes.length); Assert.assertArrayEquals(new byte[] { (byte)192, (byte)168, (byte)56, (byte)1}, bytes); } @Test public void getAddressFromIPV6() throws InvalidInetAddressException, UnknownHostException { InetAddress address = InetAddressUtils.getAddressForBan("fe80::498a:7f0e:e63d:6b98"); InetAddress expected = InetAddress.getByName("fe80::498a:7f0e:e63d:6b98"); Assert.assertNotNull(address); byte[] bytes = address.getAddress(); Assert.assertNotNull(bytes); Assert.assertEquals(16, bytes.length); Assert.assertArrayEquals(expected.getAddress(), bytes); } @Test public void getAddressFromNull() { try { InetAddressUtils.getAddressForBan(null); Assert.fail(); } catch (InvalidInetAddressException ex) { Assert.assertEquals("null address", ex.getMessage()); } } @Test public void getAddressFromEmptyString() { try { InetAddressUtils.getAddressForBan(""); Assert.fail(); } catch (InvalidInetAddressException ex) { Assert.assertEquals("empty address", ex.getMessage()); } } @Test public void getAddressFromBlankString() { try { InetAddressUtils.getAddressForBan(" "); Assert.fail(); } catch (InvalidInetAddressException ex) { Assert.assertEquals("empty address", ex.getMessage()); } } @Test public void getLocalAddress() { try { InetAddressUtils.getAddressForBan("127.0.0.1"); Assert.fail(); } catch (InvalidInetAddressException ex) { Assert.assertEquals("local address: '127.0.0.1'", ex.getMessage()); } } @Test public void getLocalHost() { try { InetAddressUtils.getAddressForBan("localhost"); Assert.fail(); } catch (InvalidInetAddressException ex) { Assert.assertEquals("local address: 'localhost'", ex.getMessage()); } } @Test public void getAnyLocalAddress() { try { InetAddressUtils.getAddressForBan("0.0.0.0"); Assert.fail(); } catch (InvalidInetAddressException ex) { Assert.assertEquals("local address: '0.0.0.0'", ex.getMessage()); } }
### Question: InetAddressUtils { public static InetAddressBlock parse(String text) throws InvalidInetAddressException { String[] parts = text.split("/"); InetAddress address; address = InetAddressUtils.getAddressForBan(parts[0]); int nbits; try { nbits = Integer.parseInt(parts[1]); } catch (NumberFormatException ex) { throw new InvalidInetAddressBlockException("Invalid mask", ex); } if (nbits <= 0 || nbits > address.getAddress().length * 8) { throw new InvalidInetAddressBlockException("Invalid mask", null); } return new InetAddressBlock(address, nbits); } private InetAddressUtils(); static boolean hasMask(String text); static InetAddress getAddressForBan(@CheckForNull String hostname); static InetAddressBlock parse(String text); }### Answer: @Test public void parseAddressBlock() throws InvalidInetAddressException, InvalidInetAddressBlockException, UnknownHostException { InetAddressBlock result = InetAddressUtils.parse("192.162.12.0/8"); Assert.assertNotNull(result); Assert.assertArrayEquals(InetAddress.getByName("192.162.12.0").getAddress(), result.getBytes()); Assert.assertEquals((byte)0xff, result.getMask()); } @Test public void parseAddressBlockWithNonNumericBits() throws InvalidInetAddressException { try { InetAddressUtils.parse("192.162.12.0/a"); Assert.fail(); } catch (InvalidInetAddressBlockException ex) { Assert.assertEquals("Invalid mask", ex.getMessage()); } } @Test public void parseAddressBlockWithNegativeNumberOfBits() throws UnknownHostException, InvalidInetAddressException { try { InetAddressUtils.parse("192.162.12.0/-10"); Assert.fail(); } catch (InvalidInetAddressBlockException ex) { Assert.assertEquals("Invalid mask", ex.getMessage()); } } @Test public void parseAddressBlockWithZeroBits() throws InvalidInetAddressException { try { InetAddressUtils.parse("192.162.12.0/0"); Assert.fail(); } catch (InvalidInetAddressBlockException ex) { Assert.assertEquals("Invalid mask", ex.getMessage()); } } @Test public void parseAddressBlockWithTooBigNumberOfBits() throws InvalidInetAddressException { try { InetAddressUtils.parse("192.162.12.0/1000"); Assert.fail(); } catch (InvalidInetAddressBlockException ex) { Assert.assertEquals("Invalid mask", ex.getMessage()); } }
### Question: ByteUtil { public static int byteArrayToInt(byte[] b) { if (b == null || b.length == 0) { return 0; } return new BigInteger(1, b).intValue(); } private ByteUtil(); static byte[] appendByte(byte[] bytes, byte b); static byte[] cloneBytes(byte[] bytes); static byte[] bigIntegerToBytes(BigInteger b, int numBytes); static byte[] bigIntegerToBytes(BigInteger value); static byte[] parseBytes(byte[] input, int offset, int len); static byte[] parseWord(byte[] input, int idx); static byte[] parseWord(byte[] input, int offset, int idx); static int matchingNibbleLength(byte[] a, byte[] b); static byte[] longToBytes(long val); static byte[] longToBytesNoLeadZeroes(long val); static byte[] intToBytes(int val); static byte[] intToBytesNoLeadZeroes(int val); @Nonnull static String toHexStringOrEmpty(@Nullable byte[] data); @Nonnull static String toHexString(@Nonnull byte[] data); @Nonnull static String toHexString(@Nonnull byte[] data, int off, int length); static byte[] calcPacketLength(byte[] msg); static int byteArrayToInt(byte[] b); static long byteArrayToLong(byte[] b); static String nibblesToPrettyString(byte[] nibbles); static String oneByteToHexString(byte value); static int numBytes(String val); static int firstNonZeroByte(byte[] data); static byte[] stripLeadingZeroes(byte[] data); static byte[] stripLeadingZeroes(byte[] data, byte[] valueForZero); static boolean increment(byte[] bytes); static byte[] copyToArray(BigInteger value); static ByteArrayWrapper wrap(byte[] data); static byte[] setBit(byte[] data, int pos, int val); static int getBit(byte[] data, int pos); static byte[] and(byte[] b1, byte[] b2); static byte[] or(byte[] b1, byte[] b2); @java.lang.SuppressWarnings("squid:S3034") static byte[] shiftLeft(byte[] byteArray, int shiftBitCount); @java.lang.SuppressWarnings("squid:S3034") static byte[] shiftRight(byte[] byteArray, int shiftBitCount); static byte[] merge(byte[]... arrays); static boolean isSingleZero(byte[] array); static boolean isAllZeroes(byte[] array); static Set<T> difference(Set<T> setA, Set<T> setB); static int length(byte[]... bytes); static short bigEndianToShort(byte[] bs); static short bigEndianToShort(byte[] bs, int off); static byte[] shortToBytes(short n); static int numberOfLeadingZeros(byte[] bytes); static byte[] leftPadBytes(@Nonnull byte[] original, int newLength); static boolean fastEquals(byte[] left, byte[] right); static final byte[] EMPTY_BYTE_ARRAY; }### Answer: @Test public void testByteArrayToInt() { assertEquals(0, ByteUtil.byteArrayToInt(null)); assertEquals(0, ByteUtil.byteArrayToInt(new byte[0])); }
### Question: ScoringCalculator { public boolean hasGoodReputation(PeerScoring scoring) { return scoring.getEventCounter(EventType.INVALID_BLOCK) < 1 && scoring.getEventCounter(EventType.INVALID_MESSAGE) < 1 && scoring.getEventCounter(EventType.INVALID_HEADER) < 1; } boolean hasGoodReputation(PeerScoring scoring); }### Answer: @Test public void emptyScoringHasGoodReputation() { ScoringCalculator calculator = new ScoringCalculator(); PeerScoring scoring = new PeerScoring(); Assert.assertTrue(calculator.hasGoodReputation(scoring)); } @Test public void scoringWithOneValidBlockHasGoodReputation() { ScoringCalculator calculator = new ScoringCalculator(); PeerScoring scoring = new PeerScoring(); scoring.recordEvent(EventType.VALID_BLOCK); Assert.assertTrue(calculator.hasGoodReputation(scoring)); } @Test public void scoringWithOneValidTransactionHasGoodReputation() { ScoringCalculator calculator = new ScoringCalculator(); PeerScoring scoring = new PeerScoring(); scoring.recordEvent(EventType.VALID_TRANSACTION); Assert.assertTrue(calculator.hasGoodReputation(scoring)); } @Test public void scoringWithOneInvalidBlockHasBadReputation() { ScoringCalculator calculator = new ScoringCalculator(); PeerScoring scoring = new PeerScoring(); scoring.recordEvent(EventType.INVALID_BLOCK); Assert.assertFalse(calculator.hasGoodReputation(scoring)); } @Test public void scoringWithOneInvalidTransactionHasNoBadReputation() { ScoringCalculator calculator = new ScoringCalculator(); PeerScoring scoring = new PeerScoring(); scoring.recordEvent(EventType.INVALID_TRANSACTION); Assert.assertTrue(calculator.hasGoodReputation(scoring)); }
### Question: ByteUtil { public static int numBytes(String val) { return new BigInteger(val).bitLength() / 8 + 1; } private ByteUtil(); static byte[] appendByte(byte[] bytes, byte b); static byte[] cloneBytes(byte[] bytes); static byte[] bigIntegerToBytes(BigInteger b, int numBytes); static byte[] bigIntegerToBytes(BigInteger value); static byte[] parseBytes(byte[] input, int offset, int len); static byte[] parseWord(byte[] input, int idx); static byte[] parseWord(byte[] input, int offset, int idx); static int matchingNibbleLength(byte[] a, byte[] b); static byte[] longToBytes(long val); static byte[] longToBytesNoLeadZeroes(long val); static byte[] intToBytes(int val); static byte[] intToBytesNoLeadZeroes(int val); @Nonnull static String toHexStringOrEmpty(@Nullable byte[] data); @Nonnull static String toHexString(@Nonnull byte[] data); @Nonnull static String toHexString(@Nonnull byte[] data, int off, int length); static byte[] calcPacketLength(byte[] msg); static int byteArrayToInt(byte[] b); static long byteArrayToLong(byte[] b); static String nibblesToPrettyString(byte[] nibbles); static String oneByteToHexString(byte value); static int numBytes(String val); static int firstNonZeroByte(byte[] data); static byte[] stripLeadingZeroes(byte[] data); static byte[] stripLeadingZeroes(byte[] data, byte[] valueForZero); static boolean increment(byte[] bytes); static byte[] copyToArray(BigInteger value); static ByteArrayWrapper wrap(byte[] data); static byte[] setBit(byte[] data, int pos, int val); static int getBit(byte[] data, int pos); static byte[] and(byte[] b1, byte[] b2); static byte[] or(byte[] b1, byte[] b2); @java.lang.SuppressWarnings("squid:S3034") static byte[] shiftLeft(byte[] byteArray, int shiftBitCount); @java.lang.SuppressWarnings("squid:S3034") static byte[] shiftRight(byte[] byteArray, int shiftBitCount); static byte[] merge(byte[]... arrays); static boolean isSingleZero(byte[] array); static boolean isAllZeroes(byte[] array); static Set<T> difference(Set<T> setA, Set<T> setB); static int length(byte[]... bytes); static short bigEndianToShort(byte[] bs); static short bigEndianToShort(byte[] bs, int off); static byte[] shortToBytes(short n); static int numberOfLeadingZeros(byte[] bytes); static byte[] leftPadBytes(@Nonnull byte[] original, int newLength); static boolean fastEquals(byte[] left, byte[] right); static final byte[] EMPTY_BYTE_ARRAY; }### Answer: @Test public void testNumBytes() { String test1 = "0"; String test2 = "1"; String test3 = "1000000000"; int expected1 = 1; int expected2 = 1; int expected3 = 4; assertEquals(expected1, ByteUtil.numBytes(test1)); assertEquals(expected2, ByteUtil.numBytes(test2)); assertEquals(expected3, ByteUtil.numBytes(test3)); }
### Question: ByteUtil { public static byte[] stripLeadingZeroes(byte[] data) { return stripLeadingZeroes(data, ZERO_BYTE_ARRAY); } private ByteUtil(); static byte[] appendByte(byte[] bytes, byte b); static byte[] cloneBytes(byte[] bytes); static byte[] bigIntegerToBytes(BigInteger b, int numBytes); static byte[] bigIntegerToBytes(BigInteger value); static byte[] parseBytes(byte[] input, int offset, int len); static byte[] parseWord(byte[] input, int idx); static byte[] parseWord(byte[] input, int offset, int idx); static int matchingNibbleLength(byte[] a, byte[] b); static byte[] longToBytes(long val); static byte[] longToBytesNoLeadZeroes(long val); static byte[] intToBytes(int val); static byte[] intToBytesNoLeadZeroes(int val); @Nonnull static String toHexStringOrEmpty(@Nullable byte[] data); @Nonnull static String toHexString(@Nonnull byte[] data); @Nonnull static String toHexString(@Nonnull byte[] data, int off, int length); static byte[] calcPacketLength(byte[] msg); static int byteArrayToInt(byte[] b); static long byteArrayToLong(byte[] b); static String nibblesToPrettyString(byte[] nibbles); static String oneByteToHexString(byte value); static int numBytes(String val); static int firstNonZeroByte(byte[] data); static byte[] stripLeadingZeroes(byte[] data); static byte[] stripLeadingZeroes(byte[] data, byte[] valueForZero); static boolean increment(byte[] bytes); static byte[] copyToArray(BigInteger value); static ByteArrayWrapper wrap(byte[] data); static byte[] setBit(byte[] data, int pos, int val); static int getBit(byte[] data, int pos); static byte[] and(byte[] b1, byte[] b2); static byte[] or(byte[] b1, byte[] b2); @java.lang.SuppressWarnings("squid:S3034") static byte[] shiftLeft(byte[] byteArray, int shiftBitCount); @java.lang.SuppressWarnings("squid:S3034") static byte[] shiftRight(byte[] byteArray, int shiftBitCount); static byte[] merge(byte[]... arrays); static boolean isSingleZero(byte[] array); static boolean isAllZeroes(byte[] array); static Set<T> difference(Set<T> setA, Set<T> setB); static int length(byte[]... bytes); static short bigEndianToShort(byte[] bs); static short bigEndianToShort(byte[] bs, int off); static byte[] shortToBytes(short n); static int numberOfLeadingZeros(byte[] bytes); static byte[] leftPadBytes(@Nonnull byte[] original, int newLength); static boolean fastEquals(byte[] left, byte[] right); static final byte[] EMPTY_BYTE_ARRAY; }### Answer: @Test public void testStripLeadingZeroes() { byte[] test1 = null; byte[] test2 = new byte[]{}; byte[] test3 = new byte[]{0x00}; byte[] test4 = new byte[]{0x00, 0x01}; byte[] test5 = new byte[]{0x00, 0x00, 0x01}; byte[] expected1 = null; byte[] expected2 = new byte[]{0}; byte[] expected3 = new byte[]{0}; byte[] expected4 = new byte[]{0x01}; byte[] expected5 = new byte[]{0x01}; assertArrayEquals(expected1, ByteUtil.stripLeadingZeroes(test1)); assertArrayEquals(expected2, ByteUtil.stripLeadingZeroes(test2)); assertArrayEquals(expected3, ByteUtil.stripLeadingZeroes(test3)); assertArrayEquals(expected4, ByteUtil.stripLeadingZeroes(test4)); assertArrayEquals(expected5, ByteUtil.stripLeadingZeroes(test5)); }