method2testcases
stringlengths
118
6.63k
### Question: BlockUnclesValidationRule implements BlockValidationRule { @Override public boolean isValid(Block block) { if (!blockValidationRule.isValid(block)) { return false; } List<BlockHeader> uncles = block.getUncleList(); if (!uncles.isEmpty() && !validateUncleList(block.getNumber(), uncles, FamilyUtils.getAncestors(blockStore, block, uncleGenerationLimit), FamilyUtils.getUsedUncles(blockStore, block, uncleGenerationLimit))) { logger.warn("Uncles list validation failed"); return false; } return true; } BlockUnclesValidationRule( BlockStore blockStore, int uncleListLimit, int uncleGenerationLimit, BlockHeaderValidationRule validations, BlockHeaderParentDependantValidationRule parentValidations); @Override boolean isValid(Block block); boolean validateUncleList(long blockNumber, List<BlockHeader> uncles, Set<Keccak256> ancestors, Set<Keccak256> used); static final String INVALIDUNCLE; }### Answer: @Test public void rejectBlockWithSiblingUncle() { BlockGenerator blockGenerator = new BlockGenerator(); Block genesis = blockGenerator.getGenesisBlock(); Block block1 = blockGenerator.createChildBlock(genesis); Block uncle = blockGenerator.createChildBlock(block1); List<BlockHeader> uncles = new ArrayList<>(); uncles.add(uncle.getHeader()); Block block = blockGenerator.createChildBlock(block1, null, uncles, 1, null); BlockStore blockStore = new IndexedBlockStore(null, new HashMapDB(), new HashMapBlocksIndex()); blockStore.saveBlock(genesis, new BlockDifficulty(BigInteger.valueOf(1)), true); blockStore.saveBlock(block1, new BlockDifficulty(BigInteger.valueOf(2)), true); BlockUnclesValidationRule rule = new BlockUnclesValidationRule(blockStore,10, 10, new BlockHeaderCompositeRule(), new BlockHeaderParentCompositeRule()); Assert.assertFalse(rule.isValid(block)); } @Test public void rejectBlockWithUncleHavingHigherNumber() { BlockGenerator blockGenerator = new BlockGenerator(); Block genesis = blockGenerator.getGenesisBlock(); Block block1 = blockGenerator.createChildBlock(genesis); Block uncle1 = blockGenerator.createChildBlock(block1); Block uncle2 = blockGenerator.createChildBlock(uncle1); List<BlockHeader> uncles = new ArrayList<>(); uncles.add(uncle2.getHeader()); Block block = blockGenerator.createChildBlock(block1, null, uncles, 1, null); BlockStore blockStore = new IndexedBlockStore(null, new HashMapDB(), new HashMapBlocksIndex()); blockStore.saveBlock(genesis, new BlockDifficulty(BigInteger.valueOf(1)), true); blockStore.saveBlock(block1, new BlockDifficulty(BigInteger.valueOf(2)), true); BlockUnclesValidationRule rule = new BlockUnclesValidationRule(blockStore, 10, 10, new BlockHeaderCompositeRule(), new BlockHeaderParentCompositeRule()); Assert.assertFalse(rule.isValid(block)); }
### Question: BlockDifficultyRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule { @Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockDifficultyRule - block or parent are null"); return false; } BlockDifficulty calcDifficulty = difficultyCalculator.calcDifficulty(header, parent.getHeader()); BlockDifficulty difficulty = header.getDifficulty(); if (!difficulty.equals(calcDifficulty)) { logger.warn("#{}: difficulty != calcDifficulty", header.getNumber()); return false; } return true; } BlockDifficultyRule(DifficultyCalculator difficultyCalculator); @Override boolean isValid(BlockHeader header, Block parent); @Override boolean isValid(Block block, Block parent); }### Answer: @Test public void validWhenCalculatedDifficultyMatches() { whenCalculatedDifficulty(452); whenBlockDifficulty(452); Assert.assertTrue(rule.isValid(block, parent)); } @Test public void invalidWhenCalculatedDifficultyDoesntMatch() { whenCalculatedDifficulty(452); whenBlockDifficulty(999); Assert.assertFalse(rule.isValid(block, parent)); }
### Question: BlockTxsValidationRule implements BlockParentDependantValidationRule { @Override public boolean isValid(Block block, Block parent) { if(block == null || parent == null) { logger.warn("BlockTxsValidationRule - block or parent are null"); return false; } List<Transaction> txs = block.getTransactionsList(); if (txs.isEmpty()) { return true; } RepositorySnapshot parentRepo = repositoryLocator.snapshotAt(parent.getHeader()); Map<RskAddress, BigInteger> curNonce = new HashMap<>(); for (Transaction tx : txs) { try { tx.verify(); } catch (RuntimeException e) { logger.warn("Unable to verify transaction", e); return false; } RskAddress sender = tx.getSender(); BigInteger expectedNonce = curNonce.get(sender); if (expectedNonce == null) { expectedNonce = parentRepo.getNonce(sender); } curNonce.put(sender, expectedNonce.add(ONE)); BigInteger txNonce = new BigInteger(1, tx.getNonce()); if (!expectedNonce.equals(txNonce)) { logger.warn("Invalid transaction: Tx nonce {} != expected nonce {} (parent nonce: {}): {}", txNonce, expectedNonce, parentRepo.getNonce(sender), tx); panicProcessor.panic("invalidtransaction", String.format("Invalid transaction: Tx nonce %s != expected nonce %s (parent nonce: %s): %s", txNonce, expectedNonce, parentRepo.getNonce(sender), tx.getHash())); return false; } } return true; } BlockTxsValidationRule(RepositoryLocator repositoryLocator); @Override boolean isValid(Block block, Block parent); }### Answer: @Test public void validNonceSame() { RskAddress sender = TestUtils.randomAddress(); initialNonce(sender, 42); Block block = block(transaction(sender, 42)); Assert.assertTrue(rule.isValid(block, parent)); } @Test public void invalidNonceLower() { RskAddress sender = TestUtils.randomAddress(); initialNonce(sender, 42); Block block = block(transaction(sender, 41)); Assert.assertFalse(rule.isValid(block, parent)); } @Test public void invalidNonceHigher() { RskAddress sender = TestUtils.randomAddress(); initialNonce(sender, 42); Block block = block(transaction(sender, 43)); Assert.assertFalse(rule.isValid(block, parent)); } @Test public void validTransactionsWithSameNonceAndDifferentSenders() { RskAddress sender1 = TestUtils.randomAddress(); initialNonce(sender1, 64); RskAddress sender2 = TestUtils.randomAddress(); initialNonce(sender2, 64); Block block = block(transaction(sender1, 64), transaction(sender2, 64)); Assert.assertTrue(rule.isValid(block, parent)); } @Test public void validConsecutiveTransactionsFromSameSender() { RskAddress sender = TestUtils.randomAddress(); initialNonce(sender, 42); Block block = block(transaction(sender, 42), transaction(sender, 43)); Assert.assertTrue(rule.isValid(block, parent)); } @Test public void invalidTransactionsFromSameSenderWithSkippedNonce() { RskAddress sender = TestUtils.randomAddress(); initialNonce(sender, 42); Block block = block(transaction(sender, 42), transaction(sender, 44)); Assert.assertFalse(rule.isValid(block, parent)); } @Test public void invalidTransactionsWithSameNonceAndSameSender() { RskAddress sender = TestUtils.randomAddress(); initialNonce(sender, 42); Block block = block(transaction(sender, 42), transaction(sender, 42)); Assert.assertFalse(rule.isValid(block, parent)); }
### Question: AddressesTopicsFilter { boolean matchesContractAddress(RskAddress toAddr) { for (RskAddress address : addresses) { if (address.equals(toAddr)) { return true; } } return addresses.length == 0; } AddressesTopicsFilter(RskAddress[] addresses, Topic[][] topics); boolean matchBloom(Bloom blockBloom); boolean matchesExactly(LogInfo logInfo); }### Answer: @Test public void matchAddress() { Account account = new AccountBuilder().name("account").build(); RskAddress address = account.getAddress(); AddressesTopicsFilter filter = new AddressesTopicsFilter(new RskAddress[] { address }, null); Assert.assertTrue(filter.matchesContractAddress(address)); Assert.assertFalse(filter.matchesContractAddress(RskAddress.nullAddress())); }
### Question: BlockParentGasLimitRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule { @Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockParentGasLimitRule - block or parent are null"); return false; } BlockHeader parentHeader = parent.getHeader(); BigInteger headerGasLimit = new BigInteger(1, header.getGasLimit()); BigInteger parentGasLimit = new BigInteger(1, parentHeader.getGasLimit()); if (headerGasLimit.compareTo(parentGasLimit.multiply(BigInteger.valueOf(gasLimitBoundDivisor - 1L)).divide(BigInteger.valueOf(gasLimitBoundDivisor))) < 0 || headerGasLimit.compareTo(parentGasLimit.multiply(BigInteger.valueOf(gasLimitBoundDivisor + 1L)).divide(BigInteger.valueOf(gasLimitBoundDivisor))) > 0) { logger.warn(String.format("#%d: gas limit exceeds parentBlock.getGasLimit() (+-) GAS_LIMIT_BOUND_DIVISOR", header.getNumber())); return false; } return true; } BlockParentGasLimitRule(int gasLimitBoundDivisor); @Override boolean isValid(BlockHeader header, Block parent); @Override boolean isValid(Block block, Block parent); }### Answer: @Test public void validWhenGasIsTheSame() { whenGasLimitBoundDivisor(10); whenGasLimit(parentHeader, 1000); whenGasLimit(blockHeader, 1000); Assert.assertTrue(rule.isValid(block, parent)); } @Test public void validWhenGasIsOnLeftLimit() { whenGasLimitBoundDivisor(10); whenGasLimit(parentHeader, 1000); whenGasLimit(blockHeader, 900); Assert.assertTrue(rule.isValid(block, parent)); } @Test public void validWhenGasIsOnRightLimit() { whenGasLimitBoundDivisor(20); whenGasLimit(parentHeader, 1000); whenGasLimit(blockHeader, 1050); Assert.assertTrue(rule.isValid(block, parent)); } @Test public void invalidWhenGasIsOnLeftLimit() { whenGasLimitBoundDivisor(10); whenGasLimit(parentHeader, 1000); whenGasLimit(blockHeader, 899); Assert.assertFalse(rule.isValid(block, parent)); } @Test public void invalidWhenGasIsOnRightLimit() { whenGasLimitBoundDivisor(20); whenGasLimit(parentHeader, 1000); whenGasLimit(blockHeader, 1051); Assert.assertFalse(rule.isValid(block, parent)); }
### Question: AddressesTopicsFilter { public boolean matchBloom(Bloom blockBloom) { for (Bloom[] andBloom : filterBlooms) { boolean orMatches = false; for (Bloom orBloom : andBloom) { if (blockBloom.matches(orBloom)) { orMatches = true; break; } } if (!orMatches) { return false; } } return true; } AddressesTopicsFilter(RskAddress[] addresses, Topic[][] topics); boolean matchBloom(Bloom blockBloom); boolean matchesExactly(LogInfo logInfo); }### Answer: @Test public void matchEmptyBloomWithAllFilter() { AddressesTopicsFilter filter = new AddressesTopicsFilter(new RskAddress[0], null); Assert.assertTrue(filter.matchBloom(new Bloom())); } @Test public void noMatchEmptyBloomWithFilterWithAccount() { Account account = new AccountBuilder().name("account").build(); RskAddress address = account.getAddress(); AddressesTopicsFilter filter = new AddressesTopicsFilter(new RskAddress[] { address }, null); Assert.assertFalse(filter.matchBloom(new Bloom())); } @Test public void noMatchEmptyBloomWithFilterWithTopic() { Topic topic = createTopic(); AddressesTopicsFilter filter = new AddressesTopicsFilter(new RskAddress[0], new Topic[][] {{ topic }}); Assert.assertFalse(filter.matchBloom(new Bloom())); } @Test public void matchAllBloomWithFilterWithTopic() { Topic topic = createTopic(); AddressesTopicsFilter filter = new AddressesTopicsFilter(new RskAddress[0], new Topic[][] {{ topic }}); Assert.assertTrue(filter.matchBloom(getAllBloom())); } @Test public void matchAllBloomWithFilterWithAccount() { Account account = new AccountBuilder().name("account").build(); RskAddress address = account.getAddress(); AddressesTopicsFilter filter = new AddressesTopicsFilter(new RskAddress[] { address }, null); Assert.assertTrue(filter.matchBloom(getAllBloom())); }
### Question: BlockTimeStampValidationRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule, BlockValidationRule, BlockHeaderValidationRule { @Override public boolean isValid(Block block) { return isValid(block.getHeader()); } BlockTimeStampValidationRule(int validPeriodLength); @Override boolean isValid(Block block); @Override boolean isValid(BlockHeader header); @Override boolean isValid(BlockHeader header, Block parent); @Override boolean isValid(Block block, Block parent); }### Answer: @Test public void blockInThePast() { int validPeriod = 540; BlockTimeStampValidationRule validationRule = new BlockTimeStampValidationRule(validPeriod); BlockHeader header = Mockito.mock(BlockHeader.class); Block block = Mockito.mock(Block.class); Mockito.when(block.getHeader()).thenReturn(header); Mockito.when(header.getTimestamp()) .thenReturn((System.currentTimeMillis() / 1000) - 1000); Assert.assertTrue(validationRule.isValid(header)); } @Test public void blockInTheFutureLimit() { int validPeriod = 540; BlockTimeStampValidationRule validationRule = new BlockTimeStampValidationRule(validPeriod); BlockHeader header = Mockito.mock(BlockHeader.class); Block block = Mockito.mock(Block.class); Mockito.when(block.getHeader()).thenReturn(header); Mockito.when(header.getTimestamp()) .thenReturn((System.currentTimeMillis() / 1000) + validPeriod); Assert.assertTrue(validationRule.isValid(header)); } @Test public void blockInTheFuture() { int validPeriod = 540; BlockTimeStampValidationRule validationRule = new BlockTimeStampValidationRule(validPeriod); BlockHeader header = Mockito.mock(BlockHeader.class); Block block = Mockito.mock(Block.class); Mockito.when(block.getHeader()).thenReturn(header); Mockito.when(header.getTimestamp()) .thenReturn((System.currentTimeMillis() / 1000) + 2*validPeriod); Assert.assertFalse(validationRule.isValid(header)); } @Test public void blockTimeLowerThanParentTime() { int validPeriod = 540; BlockTimeStampValidationRule validationRule = new BlockTimeStampValidationRule(validPeriod); BlockHeader header = Mockito.mock(BlockHeader.class); Block block = Mockito.mock(Block.class); Mockito.when(block.getHeader()).thenReturn(header); Block parent = Mockito.mock(Block.class); Mockito.when(header.getTimestamp()) .thenReturn(System.currentTimeMillis() / 1000); Mockito.when(parent.getTimestamp()) .thenReturn((System.currentTimeMillis() / 1000) + 1000); Assert.assertFalse(validationRule.isValid(header, parent)); } @Test public void blockTimeGreaterThanParentTime() { int validPeriod = 540; BlockTimeStampValidationRule validationRule = new BlockTimeStampValidationRule(validPeriod); BlockHeader header = Mockito.mock(BlockHeader.class); Block block = Mockito.mock(Block.class); Mockito.when(block.getHeader()).thenReturn(header); Block parent = Mockito.mock(Block.class); Mockito.when(header.getTimestamp()) .thenReturn(System.currentTimeMillis() / 1000); Mockito.when(parent.getTimestamp()) .thenReturn((System.currentTimeMillis() / 1000) - 1000); Assert.assertTrue(validationRule.isValid(header, parent)); } @Test public void blockTimeEqualsParentTime() { int validPeriod = 540; BlockTimeStampValidationRule validationRule = new BlockTimeStampValidationRule(validPeriod); BlockHeader header = Mockito.mock(BlockHeader.class); Block block = Mockito.mock(Block.class); Mockito.when(block.getHeader()).thenReturn(header); Block parent = Mockito.mock(Block.class); Mockito.when(header.getTimestamp()) .thenReturn(System.currentTimeMillis() / 1000); Mockito.when(parent.getTimestamp()) .thenReturn(System.currentTimeMillis() / 1000); Assert.assertFalse(validationRule.isValid(header, parent)); }
### Question: RemascValidationRule implements BlockValidationRule { @Override public boolean isValid(Block block) { List<Transaction> txs = block.getTransactionsList(); boolean result = !txs.isEmpty() && (txs.get(txs.size()-1) instanceof RemascTransaction); if(!result) { logger.warn("Remasc tx not found in block"); panicProcessor.panic("invalidremasctx", "Remasc tx not found in block"); } return result; } @Override boolean isValid(Block block); }### Answer: @Test public void noTxInTheBlock() { Block b = Mockito.mock(Block.class); RemascValidationRule rule = new RemascValidationRule(); Assert.assertFalse(rule.isValid(b)); } @Test public void noRemascTxInTheBlock() { Block b = Mockito.mock(Block.class); List<Transaction> tx = new ArrayList<>(); tx.add(new Transaction("0000000000000000000000000000000000000001", BigInteger.ZERO, BigInteger.ZERO, BigInteger.ONE, BigInteger.TEN, Constants.REGTEST_CHAIN_ID)); Mockito.when(b.getTransactionsList()).thenReturn(tx); RemascValidationRule rule = new RemascValidationRule(); Assert.assertFalse(rule.isValid(b)); } @Test public void remascTxIsNotTheLastOne() { Block b = Mockito.mock(Block.class); List<Transaction> tx = new ArrayList<>(); tx.add(new RemascTransaction(1L)); tx.add(new Transaction("0000000000000000000000000000000000000001", BigInteger.ZERO, BigInteger.ZERO, BigInteger.ONE, BigInteger.TEN, Constants.REGTEST_CHAIN_ID)); Mockito.when(b.getTransactionsList()).thenReturn(tx); RemascValidationRule rule = new RemascValidationRule(); Assert.assertFalse(rule.isValid(b)); } @Test public void remascTxInBlock() { Block b = Mockito.mock(Block.class); List<Transaction> tx = new ArrayList<>(); tx.add(new Transaction("0000000000000000000000000000000000000001", BigInteger.ZERO, BigInteger.ZERO, BigInteger.ONE, BigInteger.TEN, Constants.REGTEST_CHAIN_ID)); tx.add(new RemascTransaction(1L)); Mockito.when(b.getTransactionsList()).thenReturn(tx); RemascValidationRule rule = new RemascValidationRule(); Assert.assertTrue(rule.isValid(b)); }
### Question: BlockParentNumberRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule { @Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockParentNumberRule - block or parent are null"); return false; } BlockHeader parentHeader = parent.getHeader(); if (header.getNumber() != (parentHeader.getNumber() + 1)) { logger.warn("#{}: block number is not parentBlock number + 1", header.getNumber()); return false; } return true; } @Override boolean isValid(BlockHeader header, Block parent); @Override boolean isValid(Block block, Block parent); }### Answer: @Test public void validWhenNumberIsOneMore() { whenBlockNumber(parentHeader, 451); whenBlockNumber(blockHeader, 452); Assert.assertTrue(rule.isValid(block, parent)); } @Test public void invalidWhenNumberIsTheSame() { whenBlockNumber(parentHeader, 451); whenBlockNumber(blockHeader, 451); Assert.assertFalse(rule.isValid(block, parent)); } @Test public void invalidWhenNumberIsLess() { whenBlockNumber(parentHeader, 451); whenBlockNumber(blockHeader, 450); Assert.assertFalse(rule.isValid(block, parent)); } @Test public void invalidWhenNumberIsMoreThanOne() { whenBlockNumber(parentHeader, 451); whenBlockNumber(blockHeader, 999); Assert.assertFalse(rule.isValid(block, parent)); }
### Question: RepositoryLocator { public RepositorySnapshot snapshotAt(BlockHeader header) { return mutableTrieSnapshotAt(header) .map(MutableRepository::new) .orElseThrow(() -> trieNotFoundException(header)); } RepositoryLocator(TrieStore store, StateRootHandler stateRootHandler); Optional<RepositorySnapshot> findSnapshotAt(BlockHeader header); RepositorySnapshot snapshotAt(BlockHeader header); Repository startTrackingAt(BlockHeader header); }### Answer: @Test public void getsSnapshotFromTranslatedStateRoot() { BlockHeader header = mock(BlockHeader.class); Keccak256 stateRoot = TestUtils.randomHash(); when(stateRootHandler.translate(header)).thenReturn(stateRoot); Trie underlyingTrie = mock(Trie.class); when(underlyingTrie.getHash()).thenReturn(TestUtils.randomHash()); when(trieStore.retrieve(stateRoot.getBytes())).thenReturn(Optional.of(underlyingTrie)); RepositorySnapshot actualRepository = target.snapshotAt(header); assertEquals(underlyingTrie.getHash(), new Keccak256(actualRepository.getRoot())); }
### Question: RepositoryLocator { public Optional<RepositorySnapshot> findSnapshotAt(BlockHeader header) { return mutableTrieSnapshotAt(header).map(MutableRepository::new); } RepositoryLocator(TrieStore store, StateRootHandler stateRootHandler); Optional<RepositorySnapshot> findSnapshotAt(BlockHeader header); RepositorySnapshot snapshotAt(BlockHeader header); Repository startTrackingAt(BlockHeader header); }### Answer: @Test public void findSnapshotAt_notFound() { BlockHeader header = mock(BlockHeader.class); Keccak256 stateRoot = TestUtils.randomHash(); when(stateRootHandler.translate(header)).thenReturn(stateRoot); Trie underlyingTrie = mock(Trie.class); when(underlyingTrie.getHash()).thenReturn(TestUtils.randomHash()); when(trieStore.retrieve(stateRoot.getBytes())).thenReturn(Optional.empty()); Optional<RepositorySnapshot> result = target.findSnapshotAt(header); assertFalse(result.isPresent()); } @Test public void findSnapshotAt_found() { BlockHeader header = mock(BlockHeader.class); Keccak256 stateRoot = TestUtils.randomHash(); when(stateRootHandler.translate(header)).thenReturn(stateRoot); Trie underlyingTrie = mock(Trie.class); when(underlyingTrie.getHash()).thenReturn(TestUtils.randomHash()); when(trieStore.retrieve(stateRoot.getBytes())).thenReturn(Optional.of(mock(Trie.class))); Optional<RepositorySnapshot> result = target.findSnapshotAt(header); assertTrue(result.isPresent()); }
### Question: MutableTrieCache implements MutableTrie { @Override public Uint24 getValueLength(byte[] key) { return internalGet(key, trie::getValueLength, cachedBytes -> new Uint24(cachedBytes.length)).orElse(Uint24.ZERO); } MutableTrieCache(MutableTrie parentTrie); @Override Trie getTrie(); @Override Keccak256 getHash(); @Override byte[] get(byte[] key); Iterator<DataWord> getStorageKeys(RskAddress addr); @Override void put(byte[] key, byte[] value); @Override void put(ByteArrayWrapper wrapper, byte[] value); @Override void put(String key, byte[] value); @Override void deleteRecursive(byte[] key); @Override void commit(); @Override void save(); @Override void rollback(); @Override Set<ByteArrayWrapper> collectKeys(int size); @Override Uint24 getValueLength(byte[] key); @Override Optional<Keccak256> getValueHash(byte[] key); }### Answer: @Test public void testGetValueNotStoredAndGetSize() { MutableTrieImpl baseMutableTrie = new MutableTrieImpl(null, new Trie()); byte[] wrongKey = toBytes("BOB"); Uint24 valueLength = baseMutableTrie.getValueLength(wrongKey); assertEquals(Uint24.ZERO, valueLength); MutableTrieCache mtCache = new MutableTrieCache(baseMutableTrie); Uint24 cacheValueLength = mtCache.getValueLength(wrongKey); assertEquals(Uint24.ZERO, cacheValueLength); }
### Question: MutableTrieCache implements MutableTrie { @Override public void put(byte[] key, byte[] value) { put(new ByteArrayWrapper(key), value); } MutableTrieCache(MutableTrie parentTrie); @Override Trie getTrie(); @Override Keccak256 getHash(); @Override byte[] get(byte[] key); Iterator<DataWord> getStorageKeys(RskAddress addr); @Override void put(byte[] key, byte[] value); @Override void put(ByteArrayWrapper wrapper, byte[] value); @Override void put(String key, byte[] value); @Override void deleteRecursive(byte[] key); @Override void commit(); @Override void save(); @Override void rollback(); @Override Set<ByteArrayWrapper> collectKeys(int size); @Override Uint24 getValueLength(byte[] key); @Override Optional<Keccak256> getValueHash(byte[] key); }### Answer: @Test public void testStoreValueOnTrieAndGetHash() { MutableTrieImpl baseMutableTrie = new MutableTrieImpl(null, new Trie()); MutableTrieCache mtCache = new MutableTrieCache(baseMutableTrie); byte[] value = toBytes("11111111112222222222333333333344"); byte[] key = toBytes("ALICE"); byte[] keyForCache = toBytes("ALICE2"); Keccak256 expectedHash = new Keccak256(Keccak256Helper.keccak256(value)); baseMutableTrie.put(key, value); mtCache.put(keyForCache, value); getValueHashAndAssert(baseMutableTrie, key, expectedHash); getValueHashAndAssert(mtCache, keyForCache, expectedHash); } @Test public void testStoreEmptyValueOnTrieAndGetHash() { MutableTrieImpl baseMutableTrie = new MutableTrieImpl(null, new Trie()); MutableTrieCache mtCache = new MutableTrieCache(baseMutableTrie); byte[] emptyValue = new byte[0]; byte[] key = toBytes("ALICE"); byte[] keyForCache = toBytes("ALICE2"); Keccak256 emptyHash = new Keccak256(Keccak256Helper.keccak256(emptyValue)); baseMutableTrie.put(key, emptyValue); mtCache.put(keyForCache, emptyValue); getValueHashAndAssert(baseMutableTrie, key, null); getValueHashAndAssert(mtCache, keyForCache, emptyHash); }
### Question: BootstrapDataProvider { public void retrieveData() { BootstrapIndexCandidateSelector.HeightCandidate heightCandidate = bootstrapIndexCandidateSelector.getHeightData(getIndices()); Map<String, BootstrapDataEntry> selectedEntries = heightCandidate.getEntries(); verify(heightCandidate); height = heightCandidate.getHeight(); bootstrapFileHandler.setTempDirectory(); bootstrapFileHandler.retrieveAndUnpack(selectedEntries); } BootstrapDataProvider( BootstrapDataVerifier bootstrapDataVerifier, BootstrapFileHandler bootstrapFileHandler, BootstrapIndexCandidateSelector bootstrapIndexCandidateSelector, BootstrapIndexRetriever bootstrapIndexRetriever, int minimumRequiredVerifications); void retrieveData(); byte[] getBootstrapData(); long getSelectedHeight(); }### Answer: @Test(expected = BootstrapImportException.class) public void retrieveDataInsufficientsSources() { BootstrapDataVerifier bootstrapDataVerifier = mock(BootstrapDataVerifier.class); when(bootstrapDataVerifier.verifyEntries(any())).thenReturn(1); BootstrapFileHandler bootstrapFileHandler = mock(BootstrapFileHandler.class); BootstrapIndexCandidateSelector bootstrapIndexCandidateSelector = mock(BootstrapIndexCandidateSelector.class); Map<String, BootstrapDataEntry> entries = new HashMap<>(); BootstrapIndexCandidateSelector.HeightCandidate mchd = new BootstrapIndexCandidateSelector.HeightCandidate(1L, entries); when(bootstrapIndexCandidateSelector.getHeightData(any())).thenReturn(mchd); BootstrapDataProvider bootstrapDataProvider = new BootstrapDataProvider( bootstrapDataVerifier, bootstrapFileHandler, bootstrapIndexCandidateSelector, mock(BootstrapIndexRetriever.class), 2 ); bootstrapDataProvider.retrieveData(); } @Test public void retrieveData() { BootstrapDataVerifier bootstrapDataVerifier = mock(BootstrapDataVerifier.class); when(bootstrapDataVerifier.verifyEntries(any())).thenReturn(2); BootstrapFileHandler bootstrapFileHandler = mock(BootstrapFileHandler.class); BootstrapIndexCandidateSelector bootstrapIndexCandidateSelector = mock(BootstrapIndexCandidateSelector.class); Map<String, BootstrapDataEntry> entries = new HashMap<>(); BootstrapIndexCandidateSelector.HeightCandidate mchd = new BootstrapIndexCandidateSelector.HeightCandidate(1L, entries); when(bootstrapIndexCandidateSelector.getHeightData(any())).thenReturn(mchd); BootstrapDataProvider bootstrapDataProvider = new BootstrapDataProvider( bootstrapDataVerifier, bootstrapFileHandler, bootstrapIndexCandidateSelector, mock(BootstrapIndexRetriever.class), 2 ); bootstrapDataProvider.retrieveData(); }
### Question: BootstrapIndexRetriever { public List<BootstrapDataIndex> retrieve() { List<BootstrapDataIndex> indices = new ArrayList<>(); for (String pk : publicKeys) { String indexSuffix = pk +"/" + INDEX_NAME; URL indexURL = bootstrapUrlProvider.getFullURL(indexSuffix); indices.add(readJson(indexURL)); } return indices; } BootstrapIndexRetriever( List<String> publicKeys, BootstrapURLProvider bootstrapUrlProvider, ObjectMapper objectMapper); List<BootstrapDataIndex> retrieve(); }### Answer: @Test public void retrieveEmpty() { BootstrapIndexRetriever bootstrapIndexRetriever = new BootstrapIndexRetriever( new ArrayList<>(), mock(BootstrapURLProvider.class), mock(ObjectMapper.class) ); List<BootstrapDataIndex> indices = bootstrapIndexRetriever.retrieve(); Assert.assertTrue(indices.isEmpty()); } @Test public void retrievePublicKey() throws IOException { ObjectMapper objectMapper = mock(ObjectMapper.class); BootstrapDataIndex bdi = new BootstrapDataIndex(Collections.singletonList( new BootstrapDataEntry(1, "", "db", "hash", new BootstrapDataSignature("r", "s")))); when(objectMapper.readValue(any(URL.class), eq(BootstrapDataIndex.class))).thenReturn(bdi); BootstrapURLProvider bootstrapUrlProvider = mock(BootstrapURLProvider.class); when(bootstrapUrlProvider.getFullURL(any())).thenReturn(new URL("http: BootstrapIndexRetriever bootstrapIndexRetriever = new BootstrapIndexRetriever( Collections.singletonList("key1"), bootstrapUrlProvider, objectMapper ); List<BootstrapDataIndex> indices = bootstrapIndexRetriever.retrieve(); Assert.assertTrue(indices.contains(bdi)); }
### Question: BootstrapImporter { public void importData() { bootstrapDataProvider.retrieveData(); updateDatabase(); } BootstrapImporter( BlockStore blockStore, TrieStore trieStore, BlockFactory blockFactory, BootstrapDataProvider bootstrapDataProvider); void importData(); }### Answer: @Test public void importData() throws IOException, URISyntaxException { BlockStore blockStore = mock(BlockStore.class); when(blockStore.getMaxNumber()).thenReturn(0L); when(blockStore.isEmpty()).thenReturn(false); BlockFactory blockFactory = mock(BlockFactory.class); TrieStore trieStore = mock(TrieStore.class); BootstrapDataProvider bootstrapDataProvider = mock(BootstrapDataProvider.class); Path path = Paths.get(getClass().getClassLoader().getResource("import/bootstrap-data.bin").toURI()); byte[] oneBlockAndState = Files.readAllBytes(path); when(bootstrapDataProvider.getBootstrapData()).thenReturn(oneBlockAndState); when(bootstrapDataProvider.getSelectedHeight()).thenReturn(1L); BootstrapImporter bootstrapImporter = new BootstrapImporter(blockStore, trieStore, blockFactory, bootstrapDataProvider ); bootstrapImporter.importData(); verify(blockFactory, atLeastOnce()).decodeBlock(any()); }
### Question: BootstrapURLProvider { public URL getFullURL(String uriSuffix) { try { return new URL(bootstrapBaseURL + uriSuffix); } catch (MalformedURLException e) { throw new BootstrapImportException(String.format( "The defined url for database.import.url %s is not valid", bootstrapBaseURL ), e); } } BootstrapURLProvider(String bootstrapBaseURL); URL getFullURL(String uriSuffix); }### Answer: @Test public void getFullURL() { String BASE_URL = "http: BootstrapURLProvider bootstrapURLProvider = new BootstrapURLProvider(BASE_URL); String suffix = "suffix"; URL fullURL = bootstrapURLProvider.getFullURL(suffix); try { URL expected = new URL(BASE_URL + suffix); assertEquals(expected, fullURL); } catch (MalformedURLException e) { e.printStackTrace(); } } @Test(expected=BootstrapImportException.class) public void getWrongFullURL() { String BASE_URL = "localhost/baseURL"; BootstrapURLProvider bootstrapURLProvider = new BootstrapURLProvider(BASE_URL); String suffix = "suffix"; bootstrapURLProvider.getFullURL(suffix); }
### Question: MapDBBlocksIndex implements BlocksIndex { @Override public long getMinNumber() { if (index.isEmpty()) { throw new IllegalStateException("Index is empty"); } return getMaxNumber() - index.size() + 1; } MapDBBlocksIndex(DB indexDB); @Override boolean isEmpty(); @Override long getMaxNumber(); @Override long getMinNumber(); @Override boolean contains(long blockNumber); @Override List<IndexedBlockStore.BlockInfo> getBlocksByNumber(long blockNumber); @Override void putBlocks(long blockNumber, List<IndexedBlockStore.BlockInfo> blocks); @Override List<IndexedBlockStore.BlockInfo> removeLast(); @Override void flush(); @Override void close(); }### Answer: @Test(expected = IllegalStateException.class) public void getMinNumber_emptyIndex() { target.getMinNumber(); } @Test public void getMinNumber_nonEmptyIndex() { metadata.put(MAX_BLOCK_NUMBER_KEY, ByteUtil.longToBytes(9)); index.put(9L, new ArrayList<>()); index.put(8L, new ArrayList<>()); assertEquals(8L, target.getMinNumber()); }
### Question: MapDBBlocksIndex implements BlocksIndex { @Override public long getMaxNumber() { if (index.isEmpty()) { throw new IllegalStateException("Index is empty"); } return ByteUtil.byteArrayToLong(metadata.get(MAX_BLOCK_NUMBER_KEY)); } MapDBBlocksIndex(DB indexDB); @Override boolean isEmpty(); @Override long getMaxNumber(); @Override long getMinNumber(); @Override boolean contains(long blockNumber); @Override List<IndexedBlockStore.BlockInfo> getBlocksByNumber(long blockNumber); @Override void putBlocks(long blockNumber, List<IndexedBlockStore.BlockInfo> blocks); @Override List<IndexedBlockStore.BlockInfo> removeLast(); @Override void flush(); @Override void close(); }### Answer: @Test(expected = IllegalStateException.class) public void getMaxNumber_emptyIndex() { metadata.put(MAX_BLOCK_NUMBER_KEY, ByteUtil.longToBytes(9)); target.getMaxNumber(); } @Test public void getMaxNumber() { metadata.put(MAX_BLOCK_NUMBER_KEY, ByteUtil.longToBytes(9)); index.put(9L, new ArrayList<>()); assertEquals(target.getMaxNumber(),9); }
### Question: MapDBBlocksIndex implements BlocksIndex { @Override public boolean contains(long blockNumber) { return index.containsKey(blockNumber); } MapDBBlocksIndex(DB indexDB); @Override boolean isEmpty(); @Override long getMaxNumber(); @Override long getMinNumber(); @Override boolean contains(long blockNumber); @Override List<IndexedBlockStore.BlockInfo> getBlocksByNumber(long blockNumber); @Override void putBlocks(long blockNumber, List<IndexedBlockStore.BlockInfo> blocks); @Override List<IndexedBlockStore.BlockInfo> removeLast(); @Override void flush(); @Override void close(); }### Answer: @Test public void contains_true() { long blockNumber = 12; index.put(blockNumber, new ArrayList<>()); assertTrue(target.contains(blockNumber)); } @Test public void contains_false() { long blockNumber = 12; assertFalse(target.contains(blockNumber)); }
### Question: MapDBBlocksIndex implements BlocksIndex { @Override public List<IndexedBlockStore.BlockInfo> getBlocksByNumber(long blockNumber) { return index.getOrDefault(blockNumber, new ArrayList<>()); } MapDBBlocksIndex(DB indexDB); @Override boolean isEmpty(); @Override long getMaxNumber(); @Override long getMinNumber(); @Override boolean contains(long blockNumber); @Override List<IndexedBlockStore.BlockInfo> getBlocksByNumber(long blockNumber); @Override void putBlocks(long blockNumber, List<IndexedBlockStore.BlockInfo> blocks); @Override List<IndexedBlockStore.BlockInfo> removeLast(); @Override void flush(); @Override void close(); }### Answer: @Test public void getBlocksByNumber_found() { long blockNumber = 20; List<IndexedBlockStore.BlockInfo> expectedResult = mock(List.class); index.put(blockNumber, expectedResult); List<IndexedBlockStore.BlockInfo> result = target.getBlocksByNumber(blockNumber); assertEquals(expectedResult, result); }
### Question: MapDBBlocksIndex implements BlocksIndex { @Override public void putBlocks(long blockNumber, List<IndexedBlockStore.BlockInfo> blocks) { if (blocks == null || blocks.isEmpty()) { throw new IllegalArgumentException("Block list cannot be empty nor null."); } long maxNumber = -1; if (index.size() > 0) { maxNumber = getMaxNumber(); } if (blockNumber > maxNumber) { metadata.put(MAX_BLOCK_NUMBER_KEY, ByteUtil.longToBytes(blockNumber)); } index.put(blockNumber, blocks); } MapDBBlocksIndex(DB indexDB); @Override boolean isEmpty(); @Override long getMaxNumber(); @Override long getMinNumber(); @Override boolean contains(long blockNumber); @Override List<IndexedBlockStore.BlockInfo> getBlocksByNumber(long blockNumber); @Override void putBlocks(long blockNumber, List<IndexedBlockStore.BlockInfo> blocks); @Override List<IndexedBlockStore.BlockInfo> removeLast(); @Override void flush(); @Override void close(); }### Answer: @Test(expected = IllegalArgumentException.class) public void putBlocks_nullList() { target.putBlocks(20L, null); }
### Question: MapDBBlocksIndex implements BlocksIndex { @Override public boolean isEmpty() { return index.isEmpty(); } MapDBBlocksIndex(DB indexDB); @Override boolean isEmpty(); @Override long getMaxNumber(); @Override long getMinNumber(); @Override boolean contains(long blockNumber); @Override List<IndexedBlockStore.BlockInfo> getBlocksByNumber(long blockNumber); @Override void putBlocks(long blockNumber, List<IndexedBlockStore.BlockInfo> blocks); @Override List<IndexedBlockStore.BlockInfo> removeLast(); @Override void flush(); @Override void close(); }### Answer: @Test public void isEmpty_empty() { assertTrue(target.isEmpty()); }
### Question: MapDBBlocksIndex implements BlocksIndex { @Override public void flush() { indexDB.commit(); } MapDBBlocksIndex(DB indexDB); @Override boolean isEmpty(); @Override long getMaxNumber(); @Override long getMinNumber(); @Override boolean contains(long blockNumber); @Override List<IndexedBlockStore.BlockInfo> getBlocksByNumber(long blockNumber); @Override void putBlocks(long blockNumber, List<IndexedBlockStore.BlockInfo> blocks); @Override List<IndexedBlockStore.BlockInfo> removeLast(); @Override void flush(); @Override void close(); }### Answer: @Test public void flush() { target.flush(); verify(indexDB, times(1)).commit(); }
### Question: HttpUtils { public static String getMimeType(String contentTypeValue) { if (contentTypeValue == null) { return null; } int indexOfSemicolon = contentTypeValue.indexOf(';'); if (indexOfSemicolon != -1) { return contentTypeValue.substring(0, indexOfSemicolon); } else { return contentTypeValue.length() > 0 ? contentTypeValue : null; } } static String getMimeType(String contentTypeValue); }### Answer: @Test public void mimeTest() { final String SIMPLE_CONTENT_TYPE = "text/html"; final String NORMAL_CONTENT_TYPE = "text/html; charset=utf-8"; HttpMessage message = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); HttpHeaders headers = message.headers(); String contentType = HttpHeaders.Names.CONTENT_TYPE; Assert.assertNull(HttpUtils.getMimeType(headers.get(contentType))); headers.set(contentType, ""); Assert.assertNull(HttpUtils.getMimeType(headers.get(contentType))); Assert.assertNull(HttpUtils.getMimeType("")); headers.set(contentType, SIMPLE_CONTENT_TYPE); Assert.assertEquals("text/html", HttpUtils.getMimeType(headers.get(contentType))); Assert.assertEquals("text/html", HttpUtils.getMimeType(SIMPLE_CONTENT_TYPE)); headers.set(contentType, NORMAL_CONTENT_TYPE); Assert.assertEquals("text/html", HttpUtils.getMimeType(headers.get(contentType))); Assert.assertEquals("text/html", HttpUtils.getMimeType(NORMAL_CONTENT_TYPE)); }
### Question: RskContext implements NodeBootstrapper { public CliArgs<NodeCliOptions, NodeCliFlags> getCliArgs() { return cliArgs; } RskContext(String[] args); private RskContext(CliArgs<NodeCliOptions, NodeCliFlags> cliArgs); BootstrapImporter getBootstrapImporter(); @Override NodeRunner getNodeRunner(); Blockchain getBlockchain(); MiningMainchainView getMiningMainchainView(); ConsensusValidationMainchainView getConsensusValidationMainchainView(); BlockFactory getBlockFactory(); TransactionPool getTransactionPool(); ReceivedTxSignatureCache getReceivedTxSignatureCache(); RepositoryLocator getRepositoryLocator(); StateRootHandler getStateRootHandler(); TrieConverter getTrieConverter(); ReceiptStore getReceiptStore(); TrieStore getTrieStore(); BlockExecutor getBlockExecutor(); PrecompiledContracts getPrecompiledContracts(); BridgeSupportFactory getBridgeSupportFactory(); BtcBlockStoreWithCache.Factory getBtcBlockStoreFactory(); org.ethereum.db.BlockStore getBlockStore(); Ethereum getRsk(); ReversibleTransactionExecutor getReversibleTransactionExecutor(); TransactionExecutorFactory getTransactionExecutorFactory(); NodeBlockProcessor getNodeBlockProcessor(); RskSystemProperties getRskSystemProperties(); PeerScoringManager getPeerScoringManager(); HashRateCalculator getHashRateCalculator(); EthModule getEthModule(); EvmModule getEvmModule(); PeerServer getPeerServer(); PersonalModule getPersonalModule(); CliArgs<NodeCliOptions, NodeCliFlags> getCliArgs(); BuildInfo getBuildInfo(); ChannelManager getChannelManager(); ConfigCapabilities getConfigCapabilities(); DebugModule getDebugModule(); TraceModule getTraceModule(); MnrModule getMnrModule(); TxPoolModule getTxPoolModule(); RskModule getRskModule(); NetworkStateExporter getNetworkStateExporter(); MinerClient getMinerClient(); MinerServer getMinerServer(); ProgramInvokeFactory getProgramInvokeFactory(); CompositeEthereumListener getCompositeEthereumListener(); BlocksBloomStore getBlocksBloomStore(); List<InternalService> buildInternalServices(); GenesisLoader getGenesisLoader(); Genesis getGenesis(); Wallet getWallet(); BlockValidationRule getBlockValidationRule(); BlockParentDependantValidationRule getBlockParentDependantValidationRule(); org.ethereum.db.BlockStore buildBlockStore(String databaseDir); }### Answer: @Test public void getCliArgsSmokeTest() { RskTestContext devnetContext = new RskTestContext(new String[] { "--devnet" }); assertThat(devnetContext.getCliArgs(), notNullValue()); assertThat(devnetContext.getCliArgs().getFlags(), contains(NodeCliFlags.NETWORK_DEVNET)); }
### Question: BlocksBloomStore { public void setBlocksBloom(BlocksBloom blocksBloom) { this.blocksBloom.put(blocksBloom.fromBlock(), blocksBloom); if (this.dataSource != null) { this.dataSource.put(longToKey(blocksBloom.fromBlock()), BlocksBloomEncoder.encode(blocksBloom)); } } BlocksBloomStore(int noBlocks, int noConfirmations, KeyValueDataSource dataSource); boolean hasBlockNumber(long blockNumber); BlocksBloom getBlocksBloomByNumber(long number); void setBlocksBloom(BlocksBloom blocksBloom); long firstNumberInRange(long number); long lastNumberInRange(long number); int getNoBlocks(); int getNoConfirmations(); static byte[] longToKey(long value); }### Answer: @Test public void setBlocksBloom() { BlocksBloom blocksBloom = new BlocksBloom(); byte[] bytes1 = new byte[Bloom.BLOOM_BYTES]; bytes1[0] = 0x01; byte[] bytes2 = new byte[Bloom.BLOOM_BYTES]; bytes2[1] = 0x10; Bloom bloom1 = new Bloom(bytes1); Bloom bloom2 = new Bloom(bytes2); BlocksBloomStore blocksBloomStore = new BlocksBloomStore(64, 0, null); blocksBloom.addBlockBloom(blocksBloomStore.getNoBlocks(), bloom1); blocksBloom.addBlockBloom(blocksBloomStore.getNoBlocks() + 1, bloom2); blocksBloomStore.setBlocksBloom(blocksBloom); Assert.assertSame(blocksBloom, blocksBloomStore.getBlocksBloomByNumber(blocksBloomStore.getNoBlocks())); }
### Question: BlocksBloom { public void addBlockBloom(long blockNumber, Bloom blockBloom) { if (this.empty) { this.fromBlock = blockNumber; this.toBlock = blockNumber; this.empty = false; } else if (blockNumber == toBlock + 1) { this.toBlock = blockNumber; } else { throw new UnsupportedOperationException("Block out of sequence"); } this.bloom.or(blockBloom); } BlocksBloom(); BlocksBloom(long fromBlock, long toBlock, Bloom bloom); Bloom getBloom(); long fromBlock(); long toBlock(); long size(); void addBlockBloom(long blockNumber, Bloom blockBloom); boolean matches(Bloom bloom); }### Answer: @Test public void addTwoNonConsecutiveBlocksToBlocksBloom() { BlocksBloom blocksBloom = new BlocksBloom(); byte[] bytes1 = new byte[Bloom.BLOOM_BYTES]; bytes1[0] = 0x01; byte[] bytes2 = new byte[Bloom.BLOOM_BYTES]; bytes2[1] = 0x10; Bloom bloom1 = new Bloom(bytes1); Bloom bloom2 = new Bloom(bytes2); exception.expect(UnsupportedOperationException.class); exception.expectMessage("Block out of sequence"); blocksBloom.addBlockBloom(1, bloom1); blocksBloom.addBlockBloom(3, bloom2); }
### Question: BlocksBloom { public boolean matches(Bloom bloom) { return this.bloom.matches(bloom); } BlocksBloom(); BlocksBloom(long fromBlock, long toBlock, Bloom bloom); Bloom getBloom(); long fromBlock(); long toBlock(); long size(); void addBlockBloom(long blockNumber, Bloom blockBloom); boolean matches(Bloom bloom); }### Answer: @Test public void doesNotMatchBloom() { BlocksBloom blocksBloom = new BlocksBloom(); byte[] bytes1 = new byte[Bloom.BLOOM_BYTES]; bytes1[0] = 0x01; byte[] bytes2 = new byte[Bloom.BLOOM_BYTES]; bytes2[1] = 0x10; Bloom bloom1 = new Bloom(bytes1); Bloom bloom2 = new Bloom(bytes2); Assert.assertFalse(blocksBloom.matches(bloom1)); Assert.assertFalse(blocksBloom.matches(bloom2)); bloom1.or(bloom2); Assert.assertFalse(blocksBloom.matches(bloom1)); }
### Question: NewBlockFilter extends Filter { @Override public void newBlockReceived(Block b) { add(new NewBlockFilterEvent(b)); } @Override void newBlockReceived(Block b); }### Answer: @Test public void oneBlockAndEvent() { NewBlockFilter filter = new NewBlockFilter(); Block block = new BlockGenerator().getBlock(1); filter.newBlockReceived(block); Object[] result = filter.getEvents(); Assert.assertNotNull(result); Assert.assertEquals(1, result.length); Assert.assertEquals("0x" + block.getHash(), result[0]); } @Test public void twoBlocksAndEvents() { NewBlockFilter filter = new NewBlockFilter(); Block block1 = new BlockGenerator().getBlock(1); Block block2 = new BlockGenerator().getBlock(2); filter.newBlockReceived(block1); filter.newBlockReceived(block2); Object[] result = filter.getEvents(); Assert.assertNotNull(result); Assert.assertEquals(2, result.length); Assert.assertEquals("0x" + block1.getHash(), result[0]); Assert.assertEquals("0x" + block2.getHash(), result[1]); }
### Question: NetBlockStore { public synchronized Block getBlockByHash(byte[] hash) { return this.blocks.get(new Keccak256(hash)); } synchronized void saveBlock(Block block); synchronized void removeBlock(Block block); synchronized Block getBlockByHash(byte[] hash); synchronized List<Block> getBlocksByNumber(long number); synchronized List<Block> getBlocksByParentHash(Keccak256 hash); List<Block> getChildrenOf(Set<Block> blocks); synchronized boolean hasBlock(Block block); synchronized boolean hasBlock(byte[] hash); synchronized int size(); synchronized long minimalHeight(); synchronized long maximumHeight(); synchronized void releaseRange(long from, long to); synchronized boolean hasHeader(Keccak256 hash); synchronized void saveHeader(@Nonnull final BlockHeader header); synchronized void removeHeader(@Nonnull final BlockHeader header); }### Answer: @Test public void getUnknownBlockAsNull() { NetBlockStore store = new NetBlockStore(); Assert.assertNull(store.getBlockByHash(TestUtils.randomBytes(32))); }
### Question: NetBlockStore { public synchronized void releaseRange(long from, long to) { for (long k = from; k <= to; k++) { for (Block b : this.getBlocksByNumber(k)) { this.removeBlock(b); } } } synchronized void saveBlock(Block block); synchronized void removeBlock(Block block); synchronized Block getBlockByHash(byte[] hash); synchronized List<Block> getBlocksByNumber(long number); synchronized List<Block> getBlocksByParentHash(Keccak256 hash); List<Block> getChildrenOf(Set<Block> blocks); synchronized boolean hasBlock(Block block); synchronized boolean hasBlock(byte[] hash); synchronized int size(); synchronized long minimalHeight(); synchronized long maximumHeight(); synchronized void releaseRange(long from, long to); synchronized boolean hasHeader(Keccak256 hash); synchronized void saveHeader(@Nonnull final BlockHeader header); synchronized void removeHeader(@Nonnull final BlockHeader header); }### Answer: @Test public void releaseRange() { NetBlockStore store = new NetBlockStore(); final BlockGenerator generator = new BlockGenerator(); Block genesis = generator.getGenesisBlock(); List<Block> blocks1 = generator.getBlockChain(genesis, 1000); List<Block> blocks2 = generator.getBlockChain(genesis, 1000); for (Block b : blocks1) store.saveBlock(b); for (Block b : blocks2) store.saveBlock(b); Assert.assertEquals(2000, store.size()); store.releaseRange(1, 1000); Assert.assertEquals(0, store.size()); }
### Question: NetBlockStore { public synchronized void saveHeader(@Nonnull final BlockHeader header) { this.headers.put(header.getHash(), header); } synchronized void saveBlock(Block block); synchronized void removeBlock(Block block); synchronized Block getBlockByHash(byte[] hash); synchronized List<Block> getBlocksByNumber(long number); synchronized List<Block> getBlocksByParentHash(Keccak256 hash); List<Block> getChildrenOf(Set<Block> blocks); synchronized boolean hasBlock(Block block); synchronized boolean hasBlock(byte[] hash); synchronized int size(); synchronized long minimalHeight(); synchronized long maximumHeight(); synchronized void releaseRange(long from, long to); synchronized boolean hasHeader(Keccak256 hash); synchronized void saveHeader(@Nonnull final BlockHeader header); synchronized void removeHeader(@Nonnull final BlockHeader header); }### Answer: @Test public void saveHeader() { NetBlockStore store = new NetBlockStore(); BlockHeader blockHeader = blockFactory.getBlockHeaderBuilder() .setParentHash(new byte[0]) .setCoinbase(TestUtils.randomAddress()) .setNumber(1) .setMinimumGasPrice(Coin.ZERO) .build(); store.saveHeader(blockHeader); Assert.assertTrue(store.hasHeader(blockHeader.getHash())); }
### Question: NetBlockStore { public synchronized void removeHeader(@Nonnull final BlockHeader header) { if (!this.hasHeader(header.getHash())) { return; } this.headers.remove(header.getHash()); } synchronized void saveBlock(Block block); synchronized void removeBlock(Block block); synchronized Block getBlockByHash(byte[] hash); synchronized List<Block> getBlocksByNumber(long number); synchronized List<Block> getBlocksByParentHash(Keccak256 hash); List<Block> getChildrenOf(Set<Block> blocks); synchronized boolean hasBlock(Block block); synchronized boolean hasBlock(byte[] hash); synchronized int size(); synchronized long minimalHeight(); synchronized long maximumHeight(); synchronized void releaseRange(long from, long to); synchronized boolean hasHeader(Keccak256 hash); synchronized void saveHeader(@Nonnull final BlockHeader header); synchronized void removeHeader(@Nonnull final BlockHeader header); }### Answer: @Test public void removeHeader() { NetBlockStore store = new NetBlockStore(); BlockHeader blockHeader = blockFactory.getBlockHeaderBuilder() .setParentHash(new byte[0]) .setCoinbase(TestUtils.randomAddress()) .setNumber(1) .setMinimumGasPrice(Coin.ZERO) .build(); store.saveHeader(blockHeader); store.removeHeader(blockHeader); Assert.assertFalse(store.hasHeader(blockHeader.getHash())); }
### Question: PacketDecoder extends MessageToMessageDecoder<DatagramPacket> { @Override public void decode(ChannelHandlerContext ctx, DatagramPacket packet, List<Object> out) throws Exception { ByteBuf buf = packet.content(); byte[] encoded = new byte[buf.readableBytes()]; buf.readBytes(encoded); out.add(this.decodeMessage(ctx, encoded, packet.sender())); } @Override void decode(ChannelHandlerContext ctx, DatagramPacket packet, List<Object> out); DiscoveryEvent decodeMessage(ChannelHandlerContext ctx, byte[] encoded, InetSocketAddress sender); }### Answer: @Test public void decode() throws Exception { ECKey key1 = ECKey.fromPrivate(Hex.decode(KEY_1)).decompress(); String check = UUID.randomUUID().toString(); ChannelHandlerContext ctx = Mockito.mock(ChannelHandlerContext.class); PacketDecoder decoder = new PacketDecoder(); PingPeerMessage nodeMessage = PingPeerMessage.create("localhost", 44035, check, key1, NETWORK_ID); InetSocketAddress sender = new InetSocketAddress("localhost", 44035); this.assertDecodedMessage(decoder.decodeMessage(ctx, nodeMessage.getPacket(), sender), sender, DiscoveryMessageType.PING); PongPeerMessage pongPeerMessage = PongPeerMessage.create("localhost", 44036, check, key1, NETWORK_ID); sender = new InetSocketAddress("localhost", 44036); this.assertDecodedMessage(decoder.decodeMessage(ctx, pongPeerMessage.getPacket(), sender), sender, DiscoveryMessageType.PONG); FindNodePeerMessage findNodePeerMessage = FindNodePeerMessage.create(key1.getNodeId(), check, key1, NETWORK_ID); sender = new InetSocketAddress("localhost", 44037); this.assertDecodedMessage(decoder.decodeMessage(ctx, findNodePeerMessage.getPacket(), sender), sender, DiscoveryMessageType.FIND_NODE); NeighborsPeerMessage neighborsPeerMessage = NeighborsPeerMessage.create(new ArrayList<>(), check, key1, NETWORK_ID); sender = new InetSocketAddress("localhost", 44038); this.assertDecodedMessage(decoder.decodeMessage(ctx, neighborsPeerMessage.getPacket(), sender), sender, DiscoveryMessageType.NEIGHBORS); }
### Question: NodeDistanceTable { public synchronized List<Node> getClosestNodes(NodeID nodeId) { return getAllNodes().stream() .sorted(new NodeDistanceComparator(nodeId, this.distanceCalculator)) .collect(Collectors.toList()); } NodeDistanceTable(int numberOfBuckets, int entriesPerBucket, Node localNode); synchronized OperationResult addNode(Node node); synchronized OperationResult removeNode(Node node); synchronized List<Node> getClosestNodes(NodeID nodeId); Set<Node> getAllNodes(); void updateEntry(Node node); }### Answer: @Test public void creation() { Node localNode = new Node(Hex.decode(NODE_ID_1), HOST, PORT_1); NodeDistanceTable table = new NodeDistanceTable(KademliaOptions.BINS, KademliaOptions.BUCKET_SIZE, localNode); Assert.assertTrue(table != null); Assert.assertEquals(0, table.getClosestNodes(EMPTY_NODE_ID).size()); }
### Question: SolidityType { public abstract Object decode(byte[] encoded, int offset); SolidityType(String name); String getName(); @JsonValue String getCanonicalName(); @JsonCreator static SolidityType getType(String typeName); abstract byte[] encode(Object value); abstract Object decode(byte[] encoded, int offset); Object decode(byte[] encoded); int getFixedSize(); boolean isDynamicType(); @Override String toString(); }### Answer: @Test public void TestDynamicArrayTypeWithInvalidDataSize() { SolidityType.DynamicArrayType dat = new SolidityType.DynamicArrayType("string[]"); byte[] input = new byte[32]; input[31] = 0x10; try { dat.decode(input, 0); Assert.fail(); } catch (IllegalArgumentException e) { } input = new byte[98]; input[31] = 0x01; input[63] = 0x20; input[95] = 0x10; input[96] = 0x68; input[97] = 0x69; try { dat.decode(input, 0); Assert.fail(); } catch (IllegalArgumentException e) { } input = new byte[164]; input[31] = 0x02; input[63] = 0x20; input[95] = 0x02; input[96] = 0x68; input[97] = 0x69; input[129] = 0x20; input[161] = 0x10; input[162] = 0x68; input[163] = 0x69; try { dat.decode(input, 0); Assert.fail(); } catch (IllegalArgumentException e) { } } @Test public void TestStaticArrayTypeWithInvalidSize() { try { SolidityType.StaticArrayType dat = new SolidityType.StaticArrayType("string[2]"); byte[] input = new byte[34]; input[31] = 0x02; input[32] = 0x68; input[33] = 0x69; dat.decode(input, 0); Assert.fail("should have failed"); } catch (IllegalArgumentException e) { } try { SolidityType.StaticArrayType dat = new SolidityType.StaticArrayType("string[1]"); byte[] input = new byte[34]; input[31] = 0x03; input[32] = 0x68; input[33] = 0x69; dat.decode(input, 0); Assert.fail("should have failed"); } catch (IllegalArgumentException e) { } }
### Question: NodeDistanceTable { public synchronized OperationResult addNode(Node node) { return getNodeBucket(node).addNode(node); } NodeDistanceTable(int numberOfBuckets, int entriesPerBucket, Node localNode); synchronized OperationResult addNode(Node node); synchronized OperationResult removeNode(Node node); synchronized List<Node> getClosestNodes(NodeID nodeId); Set<Node> getAllNodes(); void updateEntry(Node node); }### Answer: @Test public void addNode() { Node localNode = new Node(Hex.decode(NODE_ID_1), HOST, PORT_1); Node node2 = new Node(Hex.decode(NODE_ID_2), HOST, PORT_2); Node node3 = new Node(Hex.decode(NODE_ID_3), HOST, PORT_3); NodeDistanceTable table = new NodeDistanceTable(KademliaOptions.BINS, KademliaOptions.BUCKET_SIZE, localNode); OperationResult result = table.addNode(node3); Assert.assertTrue(result.isSuccess()); result = table.addNode(node2); Assert.assertTrue(result.isSuccess()); Assert.assertEquals(2, table.getClosestNodes(EMPTY_NODE_ID).size()); result = table.addNode(node2); Assert.assertTrue(result.isSuccess()); Assert.assertEquals(2, table.getClosestNodes(EMPTY_NODE_ID).size()); NodeDistanceTable smallerTable = new NodeDistanceTable(KademliaOptions.BINS, 1, localNode); result = smallerTable.addNode(node3); Assert.assertTrue(result.isSuccess()); Node sameDistanceNode = new Node(Hex.decode("00"), HOST, PORT_3); result = smallerTable.addNode(sameDistanceNode); Assert.assertFalse(result.isSuccess()); Assert.assertEquals(NODE_ID_3, result.getAffectedEntry().getNode().getHexId()); }
### Question: DistanceCalculator { public int calculateDistance(NodeID node1, NodeID node2) { byte[] nodeId1 = HashUtil.keccak256(HashUtil.keccak256(node1.getID())); byte[] nodeId2 = HashUtil.keccak256(HashUtil.keccak256(node2.getID())); byte[] result = new byte[nodeId1.length]; for (int i = 0; i < result.length; i++) { result[i] = (byte) (((int) nodeId1[i]) ^ ((int) nodeId2[i])); } return msbPosition(result); } DistanceCalculator(int maxDistance); int calculateDistance(NodeID node1, NodeID node2); }### Answer: @Test public void distance() { DistanceCalculator calculator = new DistanceCalculator(256); Node node1 = new Node(Hex.decode(NODE_ID_1), "190.0.0.128", 8080); Node node2 = new Node(Hex.decode(NODE_ID_2), "192.0.0.127", 8080); Assert.assertEquals(0, calculator.calculateDistance(node1.getId(), node1.getId())); Assert.assertEquals(calculator.calculateDistance(node1.getId(), node2.getId()), calculator.calculateDistance(node2.getId(), node1.getId())); }
### Question: UDPChannel extends SimpleChannelInboundHandler<DiscoveryEvent> { @Override public void channelRead0(ChannelHandlerContext ctx, DiscoveryEvent event) throws Exception { this.peerExplorer.handleMessage(event); } UDPChannel(Channel ch, PeerExplorer peerExplorer); @Override void channelRead0(ChannelHandlerContext ctx, DiscoveryEvent event); void write(DiscoveryEvent discoveryEvent); @Override void channelReadComplete(ChannelHandlerContext ctx); @Override void exceptionCaught(ChannelHandlerContext ctx, Throwable cause); @Override void channelActive(ChannelHandlerContext ctx); }### Answer: @Test public void channelRead0() throws Exception { Channel channel = Mockito.mock(Channel.class); PeerExplorer peerExplorer = Mockito.mock(PeerExplorer.class); UDPChannel udpChannel = new UDPChannel(channel, peerExplorer); DiscoveryEvent event = Mockito.mock(DiscoveryEvent.class); udpChannel.channelRead0(Mockito.mock(ChannelHandlerContext.class), event); Mockito.verify(peerExplorer, Mockito.times(1)).handleMessage(event); }
### Question: UDPChannel extends SimpleChannelInboundHandler<DiscoveryEvent> { public void write(DiscoveryEvent discoveryEvent) { InetSocketAddress address = discoveryEvent.getAddress(); sendPacket(discoveryEvent.getMessage().getPacket(), address); } UDPChannel(Channel ch, PeerExplorer peerExplorer); @Override void channelRead0(ChannelHandlerContext ctx, DiscoveryEvent event); void write(DiscoveryEvent discoveryEvent); @Override void channelReadComplete(ChannelHandlerContext ctx); @Override void exceptionCaught(ChannelHandlerContext ctx, Throwable cause); @Override void channelActive(ChannelHandlerContext ctx); }### Answer: @Test public void write() { String check = UUID.randomUUID().toString(); ECKey key = new ECKey(); PingPeerMessage nodeMessage = PingPeerMessage.create("localhost", 80, check, key, NETWORK_ID); Channel channel = Mockito.mock(Channel.class); PeerExplorer peerExplorer = Mockito.mock(PeerExplorer.class); UDPChannel udpChannel = new UDPChannel(channel, peerExplorer); udpChannel.write(new DiscoveryEvent(nodeMessage, new InetSocketAddress("localhost", 8080))); Mockito.verify(channel, Mockito.times(1)).write(Mockito.any()); Mockito.verify(channel, Mockito.times(1)).flush(); }
### Question: UDPChannel extends SimpleChannelInboundHandler<DiscoveryEvent> { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { peerExplorer.start(); } UDPChannel(Channel ch, PeerExplorer peerExplorer); @Override void channelRead0(ChannelHandlerContext ctx, DiscoveryEvent event); void write(DiscoveryEvent discoveryEvent); @Override void channelReadComplete(ChannelHandlerContext ctx); @Override void exceptionCaught(ChannelHandlerContext ctx, Throwable cause); @Override void channelActive(ChannelHandlerContext ctx); }### Answer: @Test public void channelActive() throws Exception { Channel channel = Mockito.mock(Channel.class); PeerExplorer peerExplorer = Mockito.mock(PeerExplorer.class); UDPChannel udpChannel = new UDPChannel(channel, peerExplorer); ChannelHandlerContext ctx = Mockito.mock(ChannelHandlerContext.class); udpChannel.channelActive(ctx); Mockito.verify(peerExplorer, Mockito.times(1)).start(); }
### Question: NodeChallengeManager { public NodeChallenge startChallenge(Node challengedNode, Node challenger, PeerExplorer explorer) { PingPeerMessage pingMessage = explorer.sendPing(challengedNode.getAddress(), 1, challengedNode); String messageId = pingMessage.getMessageId(); NodeChallenge challenge = new NodeChallenge(challengedNode, challenger, messageId); activeChallenges.put(messageId, challenge); return challenge; } NodeChallenge startChallenge(Node challengedNode, Node challenger, PeerExplorer explorer); NodeChallenge removeChallenge(String challengeId); @VisibleForTesting int activeChallengesCount(); }### Answer: @Test public void startChallenge() { ECKey key1 = ECKey.fromPrivate(Hex.decode(KEY_1)).decompress(); ECKey key2 = ECKey.fromPrivate(Hex.decode(KEY_2)).decompress(); ECKey key3 = ECKey.fromPrivate(Hex.decode(KEY_3)).decompress(); Node node1 = new Node(key1.getNodeId(), HOST_1, PORT_1); Node node2 = new Node(key2.getNodeId(), HOST_2, PORT_2); Node node3 = new Node(key3.getNodeId(), HOST_3, PORT_3); NodeDistanceTable distanceTable = new NodeDistanceTable(KademliaOptions.BINS, KademliaOptions.BUCKET_SIZE, node1); PeerExplorer peerExplorer = new PeerExplorer(new ArrayList<>(), node1, distanceTable, new ECKey(), TIMEOUT, UPDATE, CLEAN, NETWORK_ID); peerExplorer.setUDPChannel(Mockito.mock(UDPChannel.class)); NodeChallengeManager manager = new NodeChallengeManager(); NodeChallenge challenge = manager.startChallenge(node2, node3, peerExplorer); Assert.assertNotNull(challenge); Assert.assertEquals(challenge.getChallengedNode(), node2); Assert.assertEquals(challenge.getChallenger(), node3); NodeChallenge anotherChallenge = manager.removeChallenge(UUID.randomUUID().toString()); Assert.assertNull(anotherChallenge); anotherChallenge = manager.removeChallenge(challenge.getChallengeId()); Assert.assertEquals(challenge, anotherChallenge); }
### Question: UDPServer implements InternalService { @Override public void start() { if (port == 0) { logger.error("Discovery can't be started while listen port == 0"); } else { new Thread("UDPServer") { @Override public void run() { try { UDPServer.this.startUDPServer(); } catch (Exception e) { logger.error("Discovery can't be started. ", e); throw new PeerDiscoveryException("Discovery can't be started. ", e); } } }.start(); } } UDPServer(String address, int port, PeerExplorer peerExplorer); @Override void start(); void startUDPServer(); @Override void stop(); }### Answer: @Test public void port0DoesntCreateANewChannel() throws InterruptedException { UDPServer udpServer = new UDPServer(HOST, 0, null); Channel channel = Whitebox.getInternalState(udpServer, "channel"); udpServer.start(); TimeUnit.SECONDS.sleep(2); Assert.assertNull(channel); }
### Question: PeerDiscoveryRequest { public boolean validateMessageResponse(InetSocketAddress responseAddress, PeerDiscoveryMessage message) { return this.expectedResponse == message.getMessageType() && !this.hasExpired() && getAddress().equals(responseAddress); } PeerDiscoveryRequest(String messageId, PeerDiscoveryMessage message, InetSocketAddress address, DiscoveryMessageType expectedResponse, Long expirationPeriod, int attemptNumber, Node relatedNode); String getMessageId(); PeerDiscoveryMessage getMessage(); InetSocketAddress getAddress(); int getAttemptNumber(); Node getRelatedNode(); boolean validateMessageResponse(InetSocketAddress responseAddress, PeerDiscoveryMessage message); boolean hasExpired(); }### Answer: @Test public void create() { ECKey key = new ECKey(); String check = UUID.randomUUID().toString(); PingPeerMessage pingPeerMessage = PingPeerMessage.create("localhost", 80, check, key, NETWORK_ID); PongPeerMessage pongPeerMessage = PongPeerMessage.create("localhost", 80, check, key, NETWORK_ID); InetSocketAddress address = new InetSocketAddress("localhost", 8080); PeerDiscoveryRequest request = PeerDiscoveryRequestBuilder.builder().messageId(check) .message(pingPeerMessage).address(address).expectedResponse(DiscoveryMessageType.PONG) .expirationPeriod(1000).attemptNumber(1).build(); Assert.assertNotNull(request); Assert.assertTrue(request.validateMessageResponse(address, pongPeerMessage)); Assert.assertFalse(request.validateMessageResponse(address, pingPeerMessage)); }
### Question: StatusMessage extends Message { @Override public void accept(MessageVisitor v) { v.apply(this); } StatusMessage(Status status); @Override MessageType getMessageType(); @Override byte[] getEncodedMessage(); Status getStatus(); @Override void accept(MessageVisitor v); }### Answer: @Test public void accept() { StatusMessage message = new StatusMessage(mock(Status.class)); MessageVisitor visitor = mock(MessageVisitor.class); message.accept(visitor); verify(visitor, times(1)).apply(message); }
### Question: BlockResponseMessage extends MessageWithId { @Override public void accept(MessageVisitor v) { v.apply(this); } BlockResponseMessage(long id, Block block); long getId(); Block getBlock(); @Override MessageType getMessageType(); @Override byte[] getEncodedMessageWithoutId(); @Override void accept(MessageVisitor v); }### Answer: @Test public void accept() { Block block = new BlockGenerator().getBlock(1); BlockResponseMessage message = new BlockResponseMessage(100, block); MessageVisitor visitor = mock(MessageVisitor.class); message.accept(visitor); verify(visitor, times(1)).apply(message); }
### Question: BlockRequestMessage extends MessageWithId { @Override public void accept(MessageVisitor v) { v.apply(this); } BlockRequestMessage(long id, byte[] hash); long getId(); byte[] getBlockHash(); @Override MessageType getMessageType(); @Override MessageType getResponseMessageType(); @Override byte[] getEncodedMessageWithoutId(); @Override void accept(MessageVisitor v); }### Answer: @Test public void accept() { byte[] hash = new BlockGenerator().getGenesisBlock().getHash().getBytes(); BlockRequestMessage message = new BlockRequestMessage(100, hash); MessageVisitor visitor = mock(MessageVisitor.class); message.accept(visitor); verify(visitor, times(1)).apply(message); }
### Question: BodyRequestMessage extends MessageWithId { @Override public void accept(MessageVisitor v) { v.apply(this); } BodyRequestMessage(long id, byte[] hash); long getId(); byte[] getBlockHash(); @Override MessageType getMessageType(); @Override MessageType getResponseMessageType(); @Override byte[] getEncodedMessageWithoutId(); @Override void accept(MessageVisitor v); }### Answer: @Test public void accept() { byte[] hash = new byte[]{0x0F}; BodyRequestMessage message = new BodyRequestMessage(100, hash); MessageVisitor visitor = mock(MessageVisitor.class); message.accept(visitor); verify(visitor, times(1)).apply(message); }
### Question: BlockHashRequestMessage extends MessageWithId { @Override public void accept(MessageVisitor v) { v.apply(this); } BlockHashRequestMessage(long id, long height); @Override MessageType getMessageType(); @Override MessageType getResponseMessageType(); @Override byte[] getEncodedMessageWithoutId(); long getId(); long getHeight(); @Override void accept(MessageVisitor v); }### Answer: @Test public void accept() { long someId = 42; long someHeight = 99; BlockHashRequestMessage message = new BlockHashRequestMessage(someId, someHeight); MessageVisitor visitor = mock(MessageVisitor.class); message.accept(visitor); verify(visitor, times(1)).apply(message); }
### Question: BlockHeadersResponseMessage extends MessageWithId { @Override public void accept(MessageVisitor v) { v.apply(this); } BlockHeadersResponseMessage(long id, List<BlockHeader> headers); @Override long getId(); List<BlockHeader> getBlockHeaders(); @Override MessageType getMessageType(); @Override void accept(MessageVisitor v); }### Answer: @Test public void accept() { BlockHeader blockHeader = mock(BlockHeader.class); List<BlockHeader> headers = new LinkedList<>(); headers.add(blockHeader); BlockHeadersResponseMessage message = new BlockHeadersResponseMessage(1, headers); MessageVisitor visitor = mock(MessageVisitor.class); message.accept(visitor); verify(visitor, times(1)).apply(message); }
### Question: BlockHeadersRequestMessage extends MessageWithId { @Override public void accept(MessageVisitor v) { v.apply(this); } BlockHeadersRequestMessage(long id, byte[] hash, int count); long getId(); byte[] getHash(); int getCount(); @Override byte[] getEncodedMessageWithoutId(); @Override MessageType getMessageType(); @Override MessageType getResponseMessageType(); @Override void accept(MessageVisitor v); }### Answer: @Test public void accept() { byte[] hash = HashUtil.randomHash(); BlockHeadersRequestMessage message = new BlockHeadersRequestMessage(1, hash, 100); MessageVisitor visitor = mock(MessageVisitor.class); message.accept(visitor); verify(visitor, times(1)).apply(message); }
### Question: ECIESCoder { public static byte[] decrypt(BigInteger privKey, byte[] cipher) throws IOException, InvalidCipherTextException { return decrypt(privKey, cipher, null); } static byte[] decrypt(BigInteger privKey, byte[] cipher); static byte[] decrypt(BigInteger privKey, byte[] cipher, byte[] macData); static byte[] decrypt(ECPoint ephem, BigInteger prv, byte[] iv, byte[] cipher, byte[] macData); static byte[] decryptSimple(BigInteger privKey, byte[] cipher); static byte[] encrypt(ECPoint toPub, byte[] plaintext); static byte[] encrypt(ECPoint toPub, byte[] plaintext, byte[] macData); static int getOverhead(); static final int KEY_SIZE; }### Answer: @Test public void test1(){ BigInteger privKey = new BigInteger("5e173f6ac3c669587538e7727cf19b782a4f2fda07c1eaa662c593e5e85e3051", 16); byte[] cipher = Hex.decode("049934a7b2d7f9af8fd9db941d9da281ac9381b5740e1f64f7092f3588d4f87f5ce55191a6653e5e80c1c5dd538169aa123e70dc6ffc5af1827e546c0e958e42dad355bcc1fcb9cdf2cf47ff524d2ad98cbf275e661bf4cf00960e74b5956b799771334f426df007350b46049adb21a6e78ab1408d5e6ccde6fb5e69f0f4c92bb9c725c02f99fa72b9cdc8dd53cff089e0e73317f61cc5abf6152513cb7d833f09d2851603919bf0fbe44d79a09245c6e8338eb502083dc84b846f2fee1cc310d2cc8b1b9334728f97220bb799376233e113"); byte[] payload = new byte[0]; try { payload = ECIESCoder.decrypt(privKey, cipher); } catch (Throwable e) {e.printStackTrace();} Assert.assertEquals("802b052f8b066640bba94a4fc39d63815c377fced6fcb84d27f791c9921ddf3e9bf0108e298f490812847109cbd778fae393e80323fd643209841a3b7f110397f37ec61d84cea03dcc5e8385db93248584e8af4b4d1c832d8c7453c0089687a700", ByteUtil.toHexString(payload)); }
### Question: ECDSASignature { public boolean validateComponents() { return validateComponents(r, s, v); } ECDSASignature(BigInteger r, BigInteger s); ECDSASignature(BigInteger r, BigInteger s, byte v); static ECDSASignature fromComponentsWithRecoveryCalculation(byte[] r, byte[] s, byte[] hash, byte[] pub); static ECDSASignature fromSignature(ECKey.ECDSASignature sign); BigInteger getR(); BigInteger getS(); byte getV(); void setV(byte v); static ECDSASignature fromComponents(byte[] r, byte[] s); static ECDSASignature fromComponents(byte[] r, byte[] s, byte v); boolean validateComponents(); static boolean validateComponents(BigInteger r, BigInteger s, byte v); ECDSASignature toCanonicalised(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void testValidateComponents() { assertTrue(new ECDSASignature(BigInteger.ONE, BigInteger.ONE, (byte) 27).validateComponents()); assertTrue(new ECDSASignature(BigInteger.ONE, BigInteger.ONE, (byte) 28).validateComponents()); assertTrue(new ECDSASignature(SECP256K1N.subtract(BigInteger.ONE), BigInteger.ONE, (byte) 28).validateComponents()); assertTrue(new ECDSASignature(BigInteger.ONE, SECP256K1N.subtract(BigInteger.ONE), (byte) 28).validateComponents()); assertFalse(new ECDSASignature(BigInteger.ZERO, BigInteger.ONE, (byte) 27).validateComponents()); assertFalse(new ECDSASignature(SECP256K1N, BigInteger.ONE, (byte) 27).validateComponents()); assertFalse(new ECDSASignature(BigInteger.ONE, BigInteger.ZERO, (byte) 27).validateComponents()); assertFalse(new ECDSASignature(BigInteger.ONE, SECP256K1N, (byte) 27).validateComponents()); assertFalse(new ECDSASignature(BigInteger.ONE, BigInteger.ONE, (byte) 29).validateComponents()); assertFalse(new ECDSASignature(BigInteger.ONE, BigInteger.ONE, (byte) 26).validateComponents()); }
### Question: SkeletonResponseMessage extends MessageWithId { @Override public void accept(MessageVisitor v) { v.apply(this); } SkeletonResponseMessage(long id, List<BlockIdentifier> blockIdentifiers); @Override MessageType getMessageType(); @Override byte[] getEncodedMessageWithoutId(); long getId(); List<BlockIdentifier> getBlockIdentifiers(); @Override void accept(MessageVisitor v); }### Answer: @Test public void accept() { List<BlockIdentifier> blockIdentifiers = new LinkedList<>(); SkeletonResponseMessage message = new SkeletonResponseMessage(1, blockIdentifiers); MessageVisitor visitor = mock(MessageVisitor.class); message.accept(visitor); verify(visitor, times(1)).apply(message); }
### Question: BodyResponseMessage extends MessageWithId { @Override public void accept(MessageVisitor v) { v.apply(this); } BodyResponseMessage(long id, List<Transaction> transactions, List<BlockHeader> uncles); @Override long getId(); List<Transaction> getTransactions(); List<BlockHeader> getUncles(); @Override MessageType getMessageType(); @Override void accept(MessageVisitor v); }### Answer: @Test public void accept() { List<Transaction> transactions = new LinkedList<>(); List<BlockHeader> uncles = new LinkedList<>(); BodyResponseMessage message = new BodyResponseMessage(100, transactions, uncles); MessageVisitor visitor = mock(MessageVisitor.class); message.accept(visitor); verify(visitor, times(1)).apply(message); }
### Question: SkeletonRequestMessage extends MessageWithId { @Override public void accept(MessageVisitor v) { v.apply(this); } SkeletonRequestMessage(long id, long startNumber); @Override MessageType getMessageType(); @Override MessageType getResponseMessageType(); @Override byte[] getEncodedMessageWithoutId(); long getId(); long getStartNumber(); @Override void accept(MessageVisitor v); }### Answer: @Test public void accept() { SkeletonRequestMessage message = new SkeletonRequestMessage(1, 10); MessageVisitor visitor = mock(MessageVisitor.class); message.accept(visitor); verify(visitor, times(1)).apply(message); }
### Question: BlockHashResponseMessage extends MessageWithId { @Override public void accept(MessageVisitor v) { v.apply(this); } BlockHashResponseMessage(long id, byte[] hash); @Override MessageType getMessageType(); @Override byte[] getEncodedMessageWithoutId(); long getId(); byte[] getHash(); @Override void accept(MessageVisitor v); }### Answer: @Test public void accept() { long someId = 42; byte[] hash = new byte[32]; Random random = new Random(); random.nextBytes(hash); BlockHashResponseMessage message = new BlockHashResponseMessage(someId, hash); MessageVisitor visitor = mock(MessageVisitor.class); message.accept(visitor); verify(visitor, times(1)).apply(message); }
### Question: ECDSASignature { @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ECDSASignature signature = (ECDSASignature) o; if (!r.equals(signature.r)) { return false; } return s.equals(signature.s); } ECDSASignature(BigInteger r, BigInteger s); ECDSASignature(BigInteger r, BigInteger s, byte v); static ECDSASignature fromComponentsWithRecoveryCalculation(byte[] r, byte[] s, byte[] hash, byte[] pub); static ECDSASignature fromSignature(ECKey.ECDSASignature sign); BigInteger getR(); BigInteger getS(); byte getV(); void setV(byte v); static ECDSASignature fromComponents(byte[] r, byte[] s); static ECDSASignature fromComponents(byte[] r, byte[] s, byte v); boolean validateComponents(); static boolean validateComponents(BigInteger r, BigInteger s, byte v); ECDSASignature toCanonicalised(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void testEquals() { ECDSASignature expected = new ECDSASignature(BigInteger.ONE, BigInteger.ONE, (byte) 27); assertEquals(expected, expected); assertEquals(expected, new ECDSASignature(expected.getR(), expected.getS(), expected.getV())); assertEquals(expected, new ECDSASignature(expected.getR(), expected.getS(), (byte) 0)); assertNotEquals(expected, null); assertNotEquals(expected, BigInteger.ZERO); assertNotEquals(new ECDSASignature(BigInteger.ONE, BigInteger.ONE, (byte) 27), new ECDSASignature(BigInteger.TEN, BigInteger.ONE, (byte) 27)); assertNotEquals(new ECDSASignature(BigInteger.ONE, BigInteger.ONE, (byte) 27), new ECDSASignature(BigInteger.ONE, BigInteger.TEN, (byte) 27)); }
### Question: TransactionsMessage extends Message { @Override public MessageType getMessageType() { return MessageType.TRANSACTIONS; } TransactionsMessage(List<Transaction> transactions); List<Transaction> getTransactions(); @Override MessageType getMessageType(); @Override byte[] getEncodedMessage(); String getMessageContentInfo(); @Override void accept(MessageVisitor v); }### Answer: @Test public void getMessageType() { TransactionsMessage message = new TransactionsMessage(null); Assert.assertEquals(MessageType.TRANSACTIONS, message.getMessageType()); }
### Question: TransactionsMessage extends Message { public List<Transaction> getTransactions() { return this.transactions; } TransactionsMessage(List<Transaction> transactions); List<Transaction> getTransactions(); @Override MessageType getMessageType(); @Override byte[] getEncodedMessage(); String getMessageContentInfo(); @Override void accept(MessageVisitor v); }### Answer: @Test public void setAndGetTransactions() { List<Transaction> txs = TransactionUtils.getTransactions(10); TransactionsMessage message = new TransactionsMessage(txs); Assert.assertNotNull(message.getTransactions()); Assert.assertEquals(10, message.getTransactions().size()); Assert.assertSame(txs, message.getTransactions()); }
### Question: TransactionsMessage extends Message { @Override public void accept(MessageVisitor v) { v.apply(this); } TransactionsMessage(List<Transaction> transactions); List<Transaction> getTransactions(); @Override MessageType getMessageType(); @Override byte[] getEncodedMessage(); String getMessageContentInfo(); @Override void accept(MessageVisitor v); }### Answer: @Test public void accept() { List<Transaction> txs = new LinkedList<>(); TransactionsMessage message = new TransactionsMessage(txs); MessageVisitor visitor = mock(MessageVisitor.class); message.accept(visitor); verify(visitor, times(1)).apply(message); }
### Question: GetBlockMessage extends Message { @Override public void accept(MessageVisitor v) { v.apply(this); } GetBlockMessage(byte[] hash); @Override MessageType getMessageType(); @Override byte[] getEncodedMessage(); byte[] getBlockHash(); @Override void accept(MessageVisitor v); }### Answer: @Test public void accept() { byte[] hash = new byte[]{0x0F}; GetBlockMessage message = new GetBlockMessage(hash); MessageVisitor visitor = mock(MessageVisitor.class); message.accept(visitor); verify(visitor, times(1)).apply(message); }
### Question: BlockMessage extends Message { @Override public MessageType getMessageType() { return MessageType.BLOCK_MESSAGE; } BlockMessage(Block block); Block getBlock(); @Override MessageType getMessageType(); @Override byte[] getEncodedMessage(); @Override void accept(MessageVisitor v); }### Answer: @Test public void getMessageType() { BlockMessage message = new BlockMessage(null); Assert.assertEquals(MessageType.BLOCK_MESSAGE, message.getMessageType()); }
### Question: BlockMessage extends Message { public Block getBlock() { return this.block; } BlockMessage(Block block); Block getBlock(); @Override MessageType getMessageType(); @Override byte[] getEncodedMessage(); @Override void accept(MessageVisitor v); }### Answer: @Test public void getBlock() { Block block = mock(Block.class); BlockMessage message = new BlockMessage(block); Assert.assertSame(block, message.getBlock()); }
### Question: BlockMessage extends Message { @Override public void accept(MessageVisitor v) { v.apply(this); } BlockMessage(Block block); Block getBlock(); @Override MessageType getMessageType(); @Override byte[] getEncodedMessage(); @Override void accept(MessageVisitor v); }### Answer: @Test public void accept() { Block block = mock(Block.class); BlockMessage message = new BlockMessage(block); MessageVisitor visitor = mock(MessageVisitor.class); message.accept(visitor); verify(visitor, times(1)).apply(message); }
### Question: ECDSASignature { public static ECDSASignature fromComponentsWithRecoveryCalculation(byte[] r, byte[] s, byte[] hash, byte[] pub) { byte v = calculateRecoveryByte(r, s, hash, pub); return fromComponents(r, s, v); } ECDSASignature(BigInteger r, BigInteger s); ECDSASignature(BigInteger r, BigInteger s, byte v); static ECDSASignature fromComponentsWithRecoveryCalculation(byte[] r, byte[] s, byte[] hash, byte[] pub); static ECDSASignature fromSignature(ECKey.ECDSASignature sign); BigInteger getR(); BigInteger getS(); byte getV(); void setV(byte v); static ECDSASignature fromComponents(byte[] r, byte[] s); static ECDSASignature fromComponents(byte[] r, byte[] s, byte v); boolean validateComponents(); static boolean validateComponents(BigInteger r, BigInteger s, byte v); ECDSASignature toCanonicalised(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void fromComponentsWithRecoveryCalculation() { ECKey key = new ECKey(); byte[] hash = HashUtil.randomHash(); ECDSASignature signature = ECDSASignature.fromSignature(key.sign(hash)); ECDSASignature signatureWithCalculatedV = ECDSASignature.fromComponentsWithRecoveryCalculation( signature.getR().toByteArray(), signature.getS().toByteArray(), hash, key.getPubKey(false) ); Assert.assertEquals(signature.getR(), signatureWithCalculatedV.getR()); Assert.assertEquals(signature.getS(), signatureWithCalculatedV.getS()); Assert.assertEquals(signature.getV(), signatureWithCalculatedV.getV()); signatureWithCalculatedV = ECDSASignature.fromComponentsWithRecoveryCalculation( signature.getR().toByteArray(), signature.getS().toByteArray(), hash, key.getPubKey(true) ); Assert.assertEquals(signature.getR(), signatureWithCalculatedV.getR()); Assert.assertEquals(signature.getS(), signatureWithCalculatedV.getS()); Assert.assertEquals(signature.getV(), signatureWithCalculatedV.getV()); }
### Question: CallArgumentsToByteArray { public byte[] getData() { byte[] data = null; if (args.data != null && args.data.length() != 0) { data = stringHexToByteArray(args.data); } return data; } CallArgumentsToByteArray(Web3.CallArguments args); byte[] getGasPrice(); byte[] getGasLimit(); byte[] getToAddress(); byte[] getValue(); byte[] getData(); RskAddress getFromAddress(); }### Answer: @Test public void getDataWhenValueIsNull() throws Exception { Web3.CallArguments args = new Web3.CallArguments(); CallArgumentsToByteArray byteArrayArgs = new CallArgumentsToByteArray(args); Assert.assertNull(byteArrayArgs.getData()); } @Test public void getDataWhenValueIsEmpty() throws Exception { Web3.CallArguments args = new Web3.CallArguments(); args.data = ""; CallArgumentsToByteArray byteArrayArgs = new CallArgumentsToByteArray(args); Assert.assertNull(byteArrayArgs.getData()); }
### Question: NodeBlockProcessor implements BlockProcessor { @Override public boolean isAdvancedBlock(long blockNumber) { int syncMaxDistance = syncConfiguration.getChunkSize() * syncConfiguration.getMaxSkeletonChunks(); long bestBlockNumber = this.getBestBlockNumber(); return blockNumber > bestBlockNumber + syncMaxDistance; } NodeBlockProcessor( @Nonnull final NetBlockStore store, @Nonnull final Blockchain blockchain, @Nonnull final BlockNodeInformation nodeInformation, @Nonnull final BlockSyncService blockSyncService, @Nonnull final SyncConfiguration syncConfiguration); @Override boolean isAdvancedBlock(long blockNumber); @Override void processNewBlockHashesMessage(final Peer sender, final NewBlockHashesMessage message); @Override void processBlockHeaders(@Nonnull final Peer sender, @Nonnull final List<BlockHeader> blockHeaders); @Override void processGetBlock(@Nonnull final Peer sender, @Nonnull final byte[] hash); @Override void processBlockRequest(@Nonnull final Peer sender, long requestId, @Nonnull final byte[] hash); @Override void processBlockHeadersRequest(@Nonnull final Peer sender, long requestId, @Nonnull final byte[] hash, int count); @Override void processBodyRequest(@Nonnull final Peer sender, long requestId, @Nonnull final byte[] hash); @Override void processBlockHashRequest(@Nonnull final Peer sender, long requestId, long height); @Override void processSkeletonRequest(@Nonnull final Peer sender, long requestId, long startNumber); @Override boolean canBeIgnoredForUnclesRewards(long blockNumber); @Override BlockNodeInformation getNodeInformation(); long getBestBlockNumber(); @Override boolean hasBlock(@Nonnull final byte[] hash); @Override boolean hasBlockInProcessorStore(@Nonnull final byte[] hash); @Override BlockProcessResult processBlock(@Nullable final Peer sender, @Nonnull final Block block); @Override boolean hasBlockInSomeBlockchain(@Nonnull final byte[] hash); @Override boolean hasBetterBlockToSync(); @Override long getLastKnownBlockNumber(); }### Answer: @Test public void advancedBlock() throws UnknownHostException { final NetBlockStore store = new NetBlockStore(); final Peer sender = new SimplePeer(); final BlockNodeInformation nodeInformation = new BlockNodeInformation(); final SyncConfiguration syncConfiguration = SyncConfiguration.IMMEDIATE_FOR_TESTING; final Blockchain blockchain = new BlockChainBuilder().ofSize(0); final long advancedBlockNumber = syncConfiguration.getChunkSize() * syncConfiguration.getMaxSkeletonChunks() + blockchain.getBestBlock().getNumber() + 1; TestSystemProperties config = new TestSystemProperties(); BlockSyncService blockSyncService = new BlockSyncService(config, store, blockchain, nodeInformation, syncConfiguration); final NodeBlockProcessor processor = new NodeBlockProcessor(store, blockchain, nodeInformation, blockSyncService, syncConfiguration); Assert.assertTrue(processor.isAdvancedBlock(advancedBlockNumber)); Assert.assertFalse(processor.isAdvancedBlock(advancedBlockNumber - 1)); }
### Question: NodeBlockProcessor implements BlockProcessor { @Override public boolean canBeIgnoredForUnclesRewards(long blockNumber) { return blockSyncService.canBeIgnoredForUnclesRewards(blockNumber); } NodeBlockProcessor( @Nonnull final NetBlockStore store, @Nonnull final Blockchain blockchain, @Nonnull final BlockNodeInformation nodeInformation, @Nonnull final BlockSyncService blockSyncService, @Nonnull final SyncConfiguration syncConfiguration); @Override boolean isAdvancedBlock(long blockNumber); @Override void processNewBlockHashesMessage(final Peer sender, final NewBlockHashesMessage message); @Override void processBlockHeaders(@Nonnull final Peer sender, @Nonnull final List<BlockHeader> blockHeaders); @Override void processGetBlock(@Nonnull final Peer sender, @Nonnull final byte[] hash); @Override void processBlockRequest(@Nonnull final Peer sender, long requestId, @Nonnull final byte[] hash); @Override void processBlockHeadersRequest(@Nonnull final Peer sender, long requestId, @Nonnull final byte[] hash, int count); @Override void processBodyRequest(@Nonnull final Peer sender, long requestId, @Nonnull final byte[] hash); @Override void processBlockHashRequest(@Nonnull final Peer sender, long requestId, long height); @Override void processSkeletonRequest(@Nonnull final Peer sender, long requestId, long startNumber); @Override boolean canBeIgnoredForUnclesRewards(long blockNumber); @Override BlockNodeInformation getNodeInformation(); long getBestBlockNumber(); @Override boolean hasBlock(@Nonnull final byte[] hash); @Override boolean hasBlockInProcessorStore(@Nonnull final byte[] hash); @Override BlockProcessResult processBlock(@Nullable final Peer sender, @Nonnull final Block block); @Override boolean hasBlockInSomeBlockchain(@Nonnull final byte[] hash); @Override boolean hasBetterBlockToSync(); @Override long getLastKnownBlockNumber(); }### Answer: @Test public void canBeIgnoredForUncles() throws UnknownHostException { final NetBlockStore store = new NetBlockStore(); final Peer sender = new SimplePeer(); final BlockNodeInformation nodeInformation = new BlockNodeInformation(); final SyncConfiguration syncConfiguration = SyncConfiguration.IMMEDIATE_FOR_TESTING; final Blockchain blockchain = new BlockChainBuilder().ofSize(15); final TestSystemProperties config = new TestSystemProperties(); int uncleGenerationLimit = config.getNetworkConstants().getUncleGenerationLimit(); final long blockNumberThatCanBeIgnored = blockchain.getBestBlock().getNumber() - 1 - uncleGenerationLimit; BlockSyncService blockSyncService = new BlockSyncService(config, store, blockchain, nodeInformation, syncConfiguration); final NodeBlockProcessor processor = new NodeBlockProcessor(store, blockchain, nodeInformation, blockSyncService, syncConfiguration); Assert.assertTrue(processor.canBeIgnoredForUnclesRewards(blockNumberThatCanBeIgnored)); Assert.assertFalse(processor.canBeIgnoredForUnclesRewards(blockNumberThatCanBeIgnored + 1)); }
### Question: ECKey { @Override public int hashCode() { byte[] bits = getPubKey(true); return (bits[0] & 0xFF) | ((bits[1] & 0xFF) << 8) | ((bits[2] & 0xFF) << 16) | ((bits[3] & 0xFF) << 24); } ECKey(); ECKey(SecureRandom secureRandom); ECKey(@Nullable BigInteger priv, ECPoint pub); static ECPoint compressPoint(ECPoint uncompressed); static ECPoint decompressPoint(ECPoint compressed); static ECKey fromPrivate(BigInteger privKey); static ECKey fromPrivate(byte[] privKeyBytes); static ECKey fromPublicOnly(ECPoint pub); static ECKey fromPublicOnly(byte[] pub); ECKey decompress(); boolean isPubKeyOnly(); boolean hasPrivKey(); static byte[] publicKeyFromPrivate(BigInteger privKey, boolean compressed); byte[] getAddress(); byte[] getNodeId(); byte[] getPubKey(); byte[] getPubKey(boolean compressed); ECPoint getPubKeyPoint(); boolean equalsPub(ECKey other); BigInteger getPrivKey(); String toString(); ECDSASignature doSign(byte[] input); ECDSASignature sign(byte[] messageHash); @Deprecated static ECKey signatureToKey(byte[] messageHash, ECDSASignature signature); byte[] decryptAES(byte[] cipher); @Deprecated static boolean verify(byte[] data, ECDSASignature signature, byte[] pub); @Deprecated boolean verify(byte[] sigHash, ECDSASignature signature); boolean verify(byte[] sigHash, org.ethereum.crypto.signature.ECDSASignature signature); boolean isPubKeyCanonical(); static boolean isPubKeyCanonical(byte[] pubkey); @Deprecated @Nullable static ECKey recoverFromSignature(int recId, ECDSASignature sig, byte[] messageHash, boolean compressed); @Nullable byte[] getPrivKeyBytes(); @Override boolean equals(Object o); @Override int hashCode(); static final ECDomainParameters CURVE; static final BigInteger HALF_CURVE_ORDER; }### Answer: @Test public void testHashCode() { Assert.assertEquals(1866897155, ECKey.fromPrivate(privateKey).hashCode()); }
### Question: ECKey { public ECKey() { this(secureRandom); } ECKey(); ECKey(SecureRandom secureRandom); ECKey(@Nullable BigInteger priv, ECPoint pub); static ECPoint compressPoint(ECPoint uncompressed); static ECPoint decompressPoint(ECPoint compressed); static ECKey fromPrivate(BigInteger privKey); static ECKey fromPrivate(byte[] privKeyBytes); static ECKey fromPublicOnly(ECPoint pub); static ECKey fromPublicOnly(byte[] pub); ECKey decompress(); boolean isPubKeyOnly(); boolean hasPrivKey(); static byte[] publicKeyFromPrivate(BigInteger privKey, boolean compressed); byte[] getAddress(); byte[] getNodeId(); byte[] getPubKey(); byte[] getPubKey(boolean compressed); ECPoint getPubKeyPoint(); boolean equalsPub(ECKey other); BigInteger getPrivKey(); String toString(); ECDSASignature doSign(byte[] input); ECDSASignature sign(byte[] messageHash); @Deprecated static ECKey signatureToKey(byte[] messageHash, ECDSASignature signature); byte[] decryptAES(byte[] cipher); @Deprecated static boolean verify(byte[] data, ECDSASignature signature, byte[] pub); @Deprecated boolean verify(byte[] sigHash, ECDSASignature signature); boolean verify(byte[] sigHash, org.ethereum.crypto.signature.ECDSASignature signature); boolean isPubKeyCanonical(); static boolean isPubKeyCanonical(byte[] pubkey); @Deprecated @Nullable static ECKey recoverFromSignature(int recId, ECDSASignature sig, byte[] messageHash, boolean compressed); @Nullable byte[] getPrivKeyBytes(); @Override boolean equals(Object o); @Override int hashCode(); static final ECDomainParameters CURVE; static final BigInteger HALF_CURVE_ORDER; }### Answer: @Test public void testECKey() { ECKey key = new ECKey(); assertTrue(key.isPubKeyCanonical()); assertNotNull(key.getPubKey()); assertNotNull(key.getPrivKeyBytes()); log.debug(ByteUtil.toHexString(key.getPrivKeyBytes()) + " :Generated privkey"); log.debug(ByteUtil.toHexString(key.getPubKey()) + " :Generated pubkey"); }
### Question: NodeBlockProcessor implements BlockProcessor { @Override public void processBodyRequest(@Nonnull final Peer sender, long requestId, @Nonnull final byte[] hash) { logger.trace("Processing body request {} {} from {}", requestId, ByteUtil.toHexString(hash), sender.getPeerNodeID()); final Block block = blockSyncService.getBlockFromStoreOrBlockchain(hash); if (block == null) { return; } Message responseMessage = new BodyResponseMessage(requestId, block.getTransactionsList(), block.getUncleList()); sender.sendMessage(responseMessage); } NodeBlockProcessor( @Nonnull final NetBlockStore store, @Nonnull final Blockchain blockchain, @Nonnull final BlockNodeInformation nodeInformation, @Nonnull final BlockSyncService blockSyncService, @Nonnull final SyncConfiguration syncConfiguration); @Override boolean isAdvancedBlock(long blockNumber); @Override void processNewBlockHashesMessage(final Peer sender, final NewBlockHashesMessage message); @Override void processBlockHeaders(@Nonnull final Peer sender, @Nonnull final List<BlockHeader> blockHeaders); @Override void processGetBlock(@Nonnull final Peer sender, @Nonnull final byte[] hash); @Override void processBlockRequest(@Nonnull final Peer sender, long requestId, @Nonnull final byte[] hash); @Override void processBlockHeadersRequest(@Nonnull final Peer sender, long requestId, @Nonnull final byte[] hash, int count); @Override void processBodyRequest(@Nonnull final Peer sender, long requestId, @Nonnull final byte[] hash); @Override void processBlockHashRequest(@Nonnull final Peer sender, long requestId, long height); @Override void processSkeletonRequest(@Nonnull final Peer sender, long requestId, long startNumber); @Override boolean canBeIgnoredForUnclesRewards(long blockNumber); @Override BlockNodeInformation getNodeInformation(); long getBestBlockNumber(); @Override boolean hasBlock(@Nonnull final byte[] hash); @Override boolean hasBlockInProcessorStore(@Nonnull final byte[] hash); @Override BlockProcessResult processBlock(@Nullable final Peer sender, @Nonnull final Block block); @Override boolean hasBlockInSomeBlockchain(@Nonnull final byte[] hash); @Override boolean hasBetterBlockToSync(); @Override long getLastKnownBlockNumber(); }### Answer: @Test public void processBodyRequestMessageUsingBlockInBlockchain() throws UnknownHostException { final Blockchain blockchain = new BlockChainBuilder().ofSize(10); final Block block = blockchain.getBlockByNumber(3); final NetBlockStore store = new NetBlockStore(); BlockNodeInformation nodeInformation = new BlockNodeInformation(); SyncConfiguration syncConfiguration = SyncConfiguration.IMMEDIATE_FOR_TESTING; TestSystemProperties config = new TestSystemProperties(); BlockSyncService blockSyncService = new BlockSyncService(config, store, blockchain, nodeInformation, syncConfiguration); final NodeBlockProcessor processor = new NodeBlockProcessor(store, blockchain, nodeInformation, blockSyncService, syncConfiguration); final SimplePeer sender = new SimplePeer(); processor.processBodyRequest(sender, 100, block.getHash().getBytes()); Assert.assertFalse(sender.getMessages().isEmpty()); Assert.assertEquals(1, sender.getMessages().size()); final Message message = sender.getMessages().get(0); Assert.assertEquals(MessageType.BODY_RESPONSE_MESSAGE, message.getMessageType()); final BodyResponseMessage bMessage = (BodyResponseMessage) message; Assert.assertEquals(100, bMessage.getId()); Assert.assertEquals(block.getTransactionsList(), bMessage.getTransactions()); Assert.assertEquals(block.getUncleList(), bMessage.getUncles()); }
### Question: NodeBlockProcessor implements BlockProcessor { @Override public void processBlockHashRequest(@Nonnull final Peer sender, long requestId, long height) { logger.trace("Processing block hash request {} {} from {}", requestId, height, sender.getPeerNodeID()); if (height == 0){ return; } final Block block = this.getBlockFromBlockchainStore(height); if (block == null) { return; } BlockHashResponseMessage responseMessage = new BlockHashResponseMessage(requestId, block.getHash().getBytes()); sender.sendMessage(responseMessage); } NodeBlockProcessor( @Nonnull final NetBlockStore store, @Nonnull final Blockchain blockchain, @Nonnull final BlockNodeInformation nodeInformation, @Nonnull final BlockSyncService blockSyncService, @Nonnull final SyncConfiguration syncConfiguration); @Override boolean isAdvancedBlock(long blockNumber); @Override void processNewBlockHashesMessage(final Peer sender, final NewBlockHashesMessage message); @Override void processBlockHeaders(@Nonnull final Peer sender, @Nonnull final List<BlockHeader> blockHeaders); @Override void processGetBlock(@Nonnull final Peer sender, @Nonnull final byte[] hash); @Override void processBlockRequest(@Nonnull final Peer sender, long requestId, @Nonnull final byte[] hash); @Override void processBlockHeadersRequest(@Nonnull final Peer sender, long requestId, @Nonnull final byte[] hash, int count); @Override void processBodyRequest(@Nonnull final Peer sender, long requestId, @Nonnull final byte[] hash); @Override void processBlockHashRequest(@Nonnull final Peer sender, long requestId, long height); @Override void processSkeletonRequest(@Nonnull final Peer sender, long requestId, long startNumber); @Override boolean canBeIgnoredForUnclesRewards(long blockNumber); @Override BlockNodeInformation getNodeInformation(); long getBestBlockNumber(); @Override boolean hasBlock(@Nonnull final byte[] hash); @Override boolean hasBlockInProcessorStore(@Nonnull final byte[] hash); @Override BlockProcessResult processBlock(@Nullable final Peer sender, @Nonnull final Block block); @Override boolean hasBlockInSomeBlockchain(@Nonnull final byte[] hash); @Override boolean hasBetterBlockToSync(); @Override long getLastKnownBlockNumber(); }### Answer: @Test public void processBlockHashRequestMessageUsingOutOfBoundsHeight() throws UnknownHostException { final Blockchain blockchain = new BlockChainBuilder().ofSize(10); final NetBlockStore store = new NetBlockStore(); BlockNodeInformation nodeInformation = new BlockNodeInformation(); SyncConfiguration syncConfiguration = SyncConfiguration.IMMEDIATE_FOR_TESTING; TestSystemProperties config = new TestSystemProperties(); BlockSyncService blockSyncService = new BlockSyncService(config, store, blockchain, nodeInformation, syncConfiguration); final NodeBlockProcessor processor = new NodeBlockProcessor(store, blockchain, nodeInformation, blockSyncService, syncConfiguration); final SimplePeer sender = new SimplePeer(); processor.processBlockHashRequest(sender, 100, 99999); Assert.assertTrue(sender.getMessages().isEmpty()); }
### Question: ECKey { public boolean isPubKeyOnly() { return priv == null; } ECKey(); ECKey(SecureRandom secureRandom); ECKey(@Nullable BigInteger priv, ECPoint pub); static ECPoint compressPoint(ECPoint uncompressed); static ECPoint decompressPoint(ECPoint compressed); static ECKey fromPrivate(BigInteger privKey); static ECKey fromPrivate(byte[] privKeyBytes); static ECKey fromPublicOnly(ECPoint pub); static ECKey fromPublicOnly(byte[] pub); ECKey decompress(); boolean isPubKeyOnly(); boolean hasPrivKey(); static byte[] publicKeyFromPrivate(BigInteger privKey, boolean compressed); byte[] getAddress(); byte[] getNodeId(); byte[] getPubKey(); byte[] getPubKey(boolean compressed); ECPoint getPubKeyPoint(); boolean equalsPub(ECKey other); BigInteger getPrivKey(); String toString(); ECDSASignature doSign(byte[] input); ECDSASignature sign(byte[] messageHash); @Deprecated static ECKey signatureToKey(byte[] messageHash, ECDSASignature signature); byte[] decryptAES(byte[] cipher); @Deprecated static boolean verify(byte[] data, ECDSASignature signature, byte[] pub); @Deprecated boolean verify(byte[] sigHash, ECDSASignature signature); boolean verify(byte[] sigHash, org.ethereum.crypto.signature.ECDSASignature signature); boolean isPubKeyCanonical(); static boolean isPubKeyCanonical(byte[] pubkey); @Deprecated @Nullable static ECKey recoverFromSignature(int recId, ECDSASignature sig, byte[] messageHash, boolean compressed); @Nullable byte[] getPrivKeyBytes(); @Override boolean equals(Object o); @Override int hashCode(); static final ECDomainParameters CURVE; static final BigInteger HALF_CURVE_ORDER; }### Answer: @Test public void testIsPubKeyOnly() { ECKey key = ECKey.fromPublicOnly(pubKey); assertTrue(key.isPubKeyCanonical()); assertTrue(key.isPubKeyOnly()); assertArrayEquals(key.getPubKey(), pubKey); }
### Question: BlockCache { public Block getBlockByHash(byte[] hash) { return blockMap.get(new Keccak256(hash)); } BlockCache(int cacheSize); void removeBlock(Block block); void addBlock(Block block); Block getBlockByHash(byte[] hash); }### Answer: @Test public void getUnknownBlockAsNull() { BlockCache store = getSubject(); assertThat(store.getBlockByHash(HASH_1), nullValue()); }
### Question: TxValidatorNotRemascTxValidator implements TxValidatorStep { @Override public TransactionValidationResult validate(Transaction tx, @Nullable AccountState state, BigInteger gasLimit, Coin minimumGasPrice, long bestBlockNumber, boolean isFreeTx) { if (!(tx instanceof RemascTransaction)) { return TransactionValidationResult.ok(); } return TransactionValidationResult.withError("transaction is a remasc transaction"); } @Override TransactionValidationResult validate(Transaction tx, @Nullable AccountState state, BigInteger gasLimit, Coin minimumGasPrice, long bestBlockNumber, boolean isFreeTx); }### Answer: @Test public void remascTx() { TxValidatorNotRemascTxValidator validator = new TxValidatorNotRemascTxValidator(); Transaction tx1 = Mockito.mock(RemascTransaction.class); Mockito.when(tx1.getHash()).thenReturn(Keccak256.ZERO_HASH); Assert.assertFalse(validator.validate(tx1, null, null, null, 0, false).transactionIsValid()); } @Test public void commonTx() { TxValidatorNotRemascTxValidator validator = new TxValidatorNotRemascTxValidator(); Assert.assertTrue(validator.validate(Mockito.mock(Transaction.class), null, null, null, 0, false).transactionIsValid()); }
### Question: ECKey { public static byte[] publicKeyFromPrivate(BigInteger privKey, boolean compressed) { ECPoint point = CURVE.getG().multiply(privKey); return point.getEncoded(compressed); } ECKey(); ECKey(SecureRandom secureRandom); ECKey(@Nullable BigInteger priv, ECPoint pub); static ECPoint compressPoint(ECPoint uncompressed); static ECPoint decompressPoint(ECPoint compressed); static ECKey fromPrivate(BigInteger privKey); static ECKey fromPrivate(byte[] privKeyBytes); static ECKey fromPublicOnly(ECPoint pub); static ECKey fromPublicOnly(byte[] pub); ECKey decompress(); boolean isPubKeyOnly(); boolean hasPrivKey(); static byte[] publicKeyFromPrivate(BigInteger privKey, boolean compressed); byte[] getAddress(); byte[] getNodeId(); byte[] getPubKey(); byte[] getPubKey(boolean compressed); ECPoint getPubKeyPoint(); boolean equalsPub(ECKey other); BigInteger getPrivKey(); String toString(); ECDSASignature doSign(byte[] input); ECDSASignature sign(byte[] messageHash); @Deprecated static ECKey signatureToKey(byte[] messageHash, ECDSASignature signature); byte[] decryptAES(byte[] cipher); @Deprecated static boolean verify(byte[] data, ECDSASignature signature, byte[] pub); @Deprecated boolean verify(byte[] sigHash, ECDSASignature signature); boolean verify(byte[] sigHash, org.ethereum.crypto.signature.ECDSASignature signature); boolean isPubKeyCanonical(); static boolean isPubKeyCanonical(byte[] pubkey); @Deprecated @Nullable static ECKey recoverFromSignature(int recId, ECDSASignature sig, byte[] messageHash, boolean compressed); @Nullable byte[] getPrivKeyBytes(); @Override boolean equals(Object o); @Override int hashCode(); static final ECDomainParameters CURVE; static final BigInteger HALF_CURVE_ORDER; }### Answer: @Test public void testPublicKeyFromPrivate() { byte[] pubFromPriv = ECKey.publicKeyFromPrivate(privateKey, false); assertArrayEquals(pubKey, pubFromPriv); } @Test public void testPublicKeyFromPrivateCompressed() { byte[] pubFromPriv = ECKey.publicKeyFromPrivate(privateKey, true); assertArrayEquals(compressedPubKey, pubFromPriv); }
### Question: TxValidatorGasLimitValidator implements TxValidatorStep { @Override public TransactionValidationResult validate(Transaction tx, @Nullable AccountState state, BigInteger gasLimit, Coin minimumGasPrice, long bestBlockNumber, boolean isFreeTx) { BigInteger txGasLimit = tx.getGasLimitAsInteger(); if (txGasLimit.compareTo(gasLimit) <= 0 && txGasLimit.compareTo(Constants.getTransactionGasCap()) <= 0) { return TransactionValidationResult.ok(); } return TransactionValidationResult.withError(String.format( "transaction's gas limit of %s is higher than the block's gas limit of %s", txGasLimit, gasLimit )); } @Override TransactionValidationResult validate(Transaction tx, @Nullable AccountState state, BigInteger gasLimit, Coin minimumGasPrice, long bestBlockNumber, boolean isFreeTx); }### Answer: @Test public void validGasLimit() { Transaction tx1 = Mockito.mock(Transaction.class); Transaction tx2 = Mockito.mock(Transaction.class); Mockito.when(tx1.getGasLimitAsInteger()).thenReturn(BigInteger.valueOf(1)); Mockito.when(tx2.getGasLimitAsInteger()).thenReturn(BigInteger.valueOf(6)); BigInteger gl = BigInteger.valueOf(6); TxValidatorGasLimitValidator tvglv = new TxValidatorGasLimitValidator(); Assert.assertTrue(tvglv.validate(tx1, null, gl, null, Long.MAX_VALUE, false).transactionIsValid()); Assert.assertTrue(tvglv.validate(tx2, null, gl, null, Long.MAX_VALUE, false).transactionIsValid()); } @Test public void invalidGasLimit() { Transaction tx1 = Mockito.mock(Transaction.class); Mockito.when(tx1.getGasLimitAsInteger()).thenReturn(BigInteger.valueOf(6)); Mockito.when(tx1.getHash()).thenReturn(Keccak256.ZERO_HASH); BigInteger gl = BigInteger.valueOf(3); TxValidatorGasLimitValidator tvglv = new TxValidatorGasLimitValidator(); Assert.assertFalse(tvglv.validate(tx1, null, gl, null, Long.MAX_VALUE, false).transactionIsValid()); }
### Question: TxValidatorAccountStateValidator implements TxValidatorStep { @Override public TransactionValidationResult validate(Transaction tx, @Nullable AccountState state, BigInteger gasLimit, Coin minimumGasPrice, long bestBlockNumber, boolean isFreeTx) { if (isFreeTx) { return TransactionValidationResult.ok(); } if (state == null) { return TransactionValidationResult.withError("the sender account doesn't exist"); } if (state.isDeleted()) { return TransactionValidationResult.withError("the sender account is deleted"); } return TransactionValidationResult.ok(); } @Override TransactionValidationResult validate(Transaction tx, @Nullable AccountState state, BigInteger gasLimit, Coin minimumGasPrice, long bestBlockNumber, boolean isFreeTx); }### Answer: @Test public void validAccountState() { AccountState state = Mockito.mock(AccountState.class); Mockito.when(state.isDeleted()).thenReturn(false); TxValidatorAccountStateValidator tvasv = new TxValidatorAccountStateValidator(); Assert.assertTrue(tvasv.validate(null, state, null, null, Long.MAX_VALUE, false).transactionIsValid()); } @Test public void invalidAccountState() { AccountState state = Mockito.mock(AccountState.class); Mockito.when(state.isDeleted()).thenReturn(true); TxValidatorAccountStateValidator tvasv = new TxValidatorAccountStateValidator(); Assert.assertFalse(tvasv.validate(null, state, null, null, Long.MAX_VALUE, false).transactionIsValid()); }
### Question: TxValidatorNonceRangeValidator implements TxValidatorStep { @Override public TransactionValidationResult validate(Transaction tx, @Nullable AccountState state, BigInteger gasLimit, Coin minimumGasPrice, long bestBlockNumber, boolean isFreeTx) { BigInteger nonce = tx.getNonceAsInteger(); BigInteger stateNonce = state == null ? BigInteger.ZERO : state.getNonce(); if (stateNonce.compareTo(nonce) > 0) { return TransactionValidationResult.withError("transaction nonce too low"); } if (stateNonce.add(accountSlots).compareTo(nonce) <= 0) { return TransactionValidationResult.withError("transaction nonce too high"); } return TransactionValidationResult.ok(); } TxValidatorNonceRangeValidator(int accountSlots); @Override TransactionValidationResult validate(Transaction tx, @Nullable AccountState state, BigInteger gasLimit, Coin minimumGasPrice, long bestBlockNumber, boolean isFreeTx); }### Answer: @Test public void oneSlotRange() { Transaction tx1 = Mockito.mock(Transaction.class); Transaction tx2 = Mockito.mock(Transaction.class); Transaction tx3 = Mockito.mock(Transaction.class); AccountState as = Mockito.mock(AccountState.class); Mockito.when(tx1.getNonceAsInteger()).thenReturn(BigInteger.valueOf(0)); Mockito.when(tx2.getNonceAsInteger()).thenReturn(BigInteger.valueOf(1)); Mockito.when(tx3.getNonceAsInteger()).thenReturn(BigInteger.valueOf(2)); Mockito.when(as.getNonce()).thenReturn(BigInteger.valueOf(1)); TxValidatorNonceRangeValidator tvnrv = new TxValidatorNonceRangeValidator(1); Assert.assertFalse(tvnrv.validate(tx1, as, null, null, Long.MAX_VALUE, false).transactionIsValid()); Assert.assertTrue(tvnrv.validate(tx2, as, null, null, Long.MAX_VALUE, false).transactionIsValid()); Assert.assertFalse(tvnrv.validate(tx3, as, null, null, Long.MAX_VALUE, false).transactionIsValid()); } @Test public void fiveSlotsRange() { Transaction[] txs = new Transaction[7]; for (int i = 0; i < 7; i++) { txs[i] = Mockito.mock(Transaction.class); Mockito.when(txs[i].getNonceAsInteger()).thenReturn(BigInteger.valueOf(i)); } AccountState as = Mockito.mock(AccountState.class); Mockito.when(as.getNonce()).thenReturn(BigInteger.valueOf(1)); TxValidatorNonceRangeValidator tvnrv = new TxValidatorNonceRangeValidator(5); for (int i = 0; i < 7; i++) { Transaction tx = txs[i]; long txNonce = tx.getNonceAsInteger().longValue(); boolean isValid = tvnrv.validate(tx, as, null, null, Long.MAX_VALUE, false).transactionIsValid(); Assert.assertEquals(isValid, txNonce >= 1 && txNonce <= 5); } }
### Question: TxValidatorAccountBalanceValidator implements TxValidatorStep { @Override public TransactionValidationResult validate(Transaction tx, @Nullable AccountState state, BigInteger gasLimit, Coin minimumGasPrice, long bestBlockNumber, boolean isFreeTx) { if (isFreeTx) { return TransactionValidationResult.ok(); } if (state == null) { return TransactionValidationResult.withError("the sender account doesn't exist"); } BigInteger txGasLimit = tx.getGasLimitAsInteger(); Coin maximumPrice = tx.getGasPrice().multiply(txGasLimit); if (state.getBalance().compareTo(maximumPrice) >= 0) { return TransactionValidationResult.ok(); } return TransactionValidationResult.withError("insufficient funds"); } @Override TransactionValidationResult validate(Transaction tx, @Nullable AccountState state, BigInteger gasLimit, Coin minimumGasPrice, long bestBlockNumber, boolean isFreeTx); }### Answer: @Test public void validAccountBalance() { Transaction tx1 = Mockito.mock(Transaction.class); Transaction tx2 = Mockito.mock(Transaction.class); Transaction tx3 = Mockito.mock(Transaction.class); AccountState as = Mockito.mock(AccountState.class); Mockito.when(tx1.getGasLimitAsInteger()).thenReturn(BigInteger.valueOf(1)); Mockito.when(tx2.getGasLimitAsInteger()).thenReturn(BigInteger.valueOf(1)); Mockito.when(tx3.getGasLimitAsInteger()).thenReturn(BigInteger.valueOf(2)); Mockito.when(tx1.getGasPrice()).thenReturn(Coin.valueOf(1)); Mockito.when(tx2.getGasPrice()).thenReturn(Coin.valueOf(10000)); Mockito.when(tx3.getGasPrice()).thenReturn(Coin.valueOf(5000)); Mockito.when(as.getBalance()).thenReturn(Coin.valueOf(10000)); TxValidatorAccountBalanceValidator tvabv = new TxValidatorAccountBalanceValidator(); Assert.assertTrue(tvabv.validate(tx1, as, null, null, Long.MAX_VALUE, false).transactionIsValid()); Assert.assertTrue(tvabv.validate(tx2, as, null, null, Long.MAX_VALUE, false).transactionIsValid()); Assert.assertTrue(tvabv.validate(tx3, as, null, null, Long.MAX_VALUE, false).transactionIsValid()); } @Test public void invalidAccountBalance() { Transaction tx1 = Mockito.mock(Transaction.class); Transaction tx2 = Mockito.mock(Transaction.class); AccountState as = Mockito.mock(AccountState.class); Mockito.when(tx1.getGasLimitAsInteger()).thenReturn(BigInteger.valueOf(1)); Mockito.when(tx2.getGasLimitAsInteger()).thenReturn(BigInteger.valueOf(2)); Mockito.when(tx1.getGasPrice()).thenReturn(Coin.valueOf(20)); Mockito.when(tx2.getGasPrice()).thenReturn(Coin.valueOf(10)); Mockito.when(as.getBalance()).thenReturn(Coin.valueOf(19)); TxValidatorAccountBalanceValidator tvabv = new TxValidatorAccountBalanceValidator(); Assert.assertFalse(tvabv.validate(tx1, as, null, null, Long.MAX_VALUE, false).transactionIsValid()); Assert.assertFalse(tvabv.validate(tx2, as, null, null, Long.MAX_VALUE, false).transactionIsValid()); } @Test public void balanceIsNotValidatedIfFreeTx() { Transaction tx = new Transaction(BigInteger.ZERO.toByteArray(), BigInteger.ONE.toByteArray(), BigInteger.valueOf(21071).toByteArray(), new ECKey().getAddress(), BigInteger.ZERO.toByteArray(), Hex.decode("0001"), Constants.REGTEST_CHAIN_ID); tx.sign(new ECKey().getPrivKeyBytes()); TxValidatorAccountBalanceValidator tv = new TxValidatorAccountBalanceValidator(); Assert.assertTrue(tv.validate(tx, new AccountState(), BigInteger.ONE, Coin.valueOf(1L), Long.MAX_VALUE, true).transactionIsValid()); }
### Question: TxsPerAccount { public List<Transaction> getTransactions(){ return txs; } List<Transaction> getTransactions(); void setTransactions(List<Transaction> txs); @VisibleForTesting BigInteger getNextNonce(); }### Answer: @Test public void containsNoTransactions() { TxsPerAccount txspa = new TxsPerAccount(); Assert.assertNotNull(txspa.getTransactions()); Assert.assertTrue(txspa.getTransactions().isEmpty()); }
### Question: TxsPerAccount { @VisibleForTesting public BigInteger getNextNonce() { return this.nextNonce; } List<Transaction> getTransactions(); void setTransactions(List<Transaction> txs); @VisibleForTesting BigInteger getNextNonce(); }### Answer: @Test public void nextNonceIsNull() { TxsPerAccount txspa = new TxsPerAccount(); Assert.assertNull(txspa.getNextNonce()); }
### Question: TxsPerAccount { boolean containsNonce(BigInteger nonce) { for (Transaction tx : txs) { if (new BigInteger(1, tx.getNonce()).equals(nonce)) { return true; } } return false; } List<Transaction> getTransactions(); void setTransactions(List<Transaction> txs); @VisibleForTesting BigInteger getNextNonce(); }### Answer: @Test public void doesNotCointainNonce() { TxsPerAccount txspa = new TxsPerAccount(); Assert.assertFalse(txspa.containsNonce(BigInteger.ONE)); } @Test public void containsNonce() { TxsPerAccount txspa = new TxsPerAccount(); Transaction tx = buildTransaction(1); txspa.getTransactions().add(tx); Assert.assertTrue(txspa.containsNonce(BigInteger.ONE)); }
### Question: StatusResolver { public Status currentStatus() { Status status; if (blockStore.getMinNumber() != 0) { status = new Status( genesis.getNumber(), genesis.getHash().getBytes(), genesis.getParentHash().getBytes(), genesis.getCumulativeDifficulty()); } else { Block block = blockStore.getBestBlock(); BlockDifficulty totalDifficulty = blockStore.getTotalDifficultyForHash(block.getHash().getBytes()); status = new Status(block.getNumber(), block.getHash().getBytes(), block.getParentHash().getBytes(), totalDifficulty); } return status; } StatusResolver(BlockStore blockStore, Genesis genesis); Status currentStatus(); }### Answer: @Test public void status() { Block bestBlock = mock(Block.class); Keccak256 blockHash = mock(Keccak256.class); byte[] hashBytes = new byte[]{0x00}; long blockNumber = 52; BlockDifficulty totalDifficulty = mock(BlockDifficulty.class); when(blockStore.getBestBlock()).thenReturn(bestBlock); when(bestBlock.getHash()).thenReturn(blockHash); when(bestBlock.getParentHash()).thenReturn(blockHash); when(blockHash.getBytes()).thenReturn(hashBytes); when(bestBlock.getNumber()).thenReturn(blockNumber); when(blockStore.getTotalDifficultyForHash(eq(hashBytes))).thenReturn(totalDifficulty); Status status = target.currentStatus(); Assert.assertEquals(blockNumber, status.getBestBlockNumber()); Assert.assertEquals(hashBytes, status.getBestBlockHash()); Assert.assertEquals(hashBytes, status.getBestBlockParentHash()); Assert.assertEquals(totalDifficulty, status.getTotalDifficulty()); } @Test public void status_incompleteBlockchain() { when(blockStore.getMinNumber()).thenReturn(1L); Keccak256 genesisHash = new Keccak256("ee5c851e70650111887bb6c04e18ef4353391abe37846234c17895a9ca2b33d5"); Keccak256 parentHash = new Keccak256("133e83bb305ef21ea7fc86fcced355db2300887274961a136ca5e8c8763687d9"); when(genesis.getHash()).thenReturn(genesisHash); when(genesis.getParentHash()).thenReturn(parentHash); when(genesis.getNumber()).thenReturn(0L); BlockDifficulty genesisDifficulty = new BlockDifficulty(BigInteger.valueOf(10L)); when(genesis.getCumulativeDifficulty()).thenReturn(genesisDifficulty); Status status = target.currentStatus(); Assert.assertEquals(0L, status.getBestBlockNumber()); Assert.assertEquals(genesisHash.getBytes(), status.getBestBlockHash()); Assert.assertEquals(parentHash.getBytes(), status.getBestBlockParentHash()); Assert.assertEquals(genesisDifficulty, status.getTotalDifficulty()); }
### Question: BlockProcessResult { @VisibleForTesting public static String buildLogMessage(String blockHash, Duration processingTime, Map<Keccak256, ImportResult> result) { StringBuilder sb = new StringBuilder("[MESSAGE PROCESS] Block[") .append(blockHash) .append("] After[") .append(FormatUtils.formatNanosecondsToSeconds(processingTime.toNanos())) .append("] seconds, process result."); if (result == null || result.isEmpty()) { sb.append(" No block connections were made"); } else { sb.append(" Connections attempts: ") .append(result.size()) .append(" | "); for (Map.Entry<Keccak256, ImportResult> entry : result.entrySet()) { sb.append(entry.getKey().toString()) .append(" - ") .append(entry.getValue()) .append(" | "); } } return sb.toString(); } BlockProcessResult(boolean additionalValidations, Map<Keccak256, ImportResult> result, String blockHash, Duration processingTime); boolean wasBlockAdded(Block block); static boolean importOk(ImportResult blockResult); boolean isBest(); boolean isInvalidBlock(); @VisibleForTesting static String buildLogMessage(String blockHash, Duration processingTime, Map<Keccak256, ImportResult> result); static final Duration LOG_TIME_LIMIT; }### Answer: @Test public void buildSimpleLogMessage() { String blockHash = "0x01020304"; Duration processingTime = Duration.ofNanos(123_000_000L); String result = BlockProcessResult.buildLogMessage(blockHash, processingTime, null); Assert.assertNotNull(result); Assert.assertEquals("[MESSAGE PROCESS] Block[0x01020304] After[0.123000] seconds, process result. No block connections were made", result); } @Test public void buildLogMessageWithConnections() { String blockHash = "0x01020304"; Duration processingTime = Duration.ofNanos(123_000_000L); Map<Keccak256, ImportResult> connections = new HashMap<>(); Random random = new Random(); byte[] bytes = new byte[32]; random.nextBytes(bytes); Keccak256 hash = new Keccak256(bytes); connections.put(hash, ImportResult.IMPORTED_BEST); String result = BlockProcessResult.buildLogMessage(blockHash, processingTime, connections); Assert.assertNotNull(result); Assert.assertEquals("[MESSAGE PROCESS] Block[0x01020304] After[0.123000] seconds, process result. Connections attempts: 1 | " + hash.toHexString() + " - IMPORTED_BEST | ", result); }
### Question: ECKey { public byte[] getAddress() { if (pubKeyHash == null) { byte[] pubBytes = this.pub.getEncoded(false); pubKeyHash = HashUtil.keccak256Omit12(Arrays.copyOfRange(pubBytes, 1, pubBytes.length)); } return pubKeyHash; } ECKey(); ECKey(SecureRandom secureRandom); ECKey(@Nullable BigInteger priv, ECPoint pub); static ECPoint compressPoint(ECPoint uncompressed); static ECPoint decompressPoint(ECPoint compressed); static ECKey fromPrivate(BigInteger privKey); static ECKey fromPrivate(byte[] privKeyBytes); static ECKey fromPublicOnly(ECPoint pub); static ECKey fromPublicOnly(byte[] pub); ECKey decompress(); boolean isPubKeyOnly(); boolean hasPrivKey(); static byte[] publicKeyFromPrivate(BigInteger privKey, boolean compressed); byte[] getAddress(); byte[] getNodeId(); byte[] getPubKey(); byte[] getPubKey(boolean compressed); ECPoint getPubKeyPoint(); boolean equalsPub(ECKey other); BigInteger getPrivKey(); String toString(); ECDSASignature doSign(byte[] input); ECDSASignature sign(byte[] messageHash); @Deprecated static ECKey signatureToKey(byte[] messageHash, ECDSASignature signature); byte[] decryptAES(byte[] cipher); @Deprecated static boolean verify(byte[] data, ECDSASignature signature, byte[] pub); @Deprecated boolean verify(byte[] sigHash, ECDSASignature signature); boolean verify(byte[] sigHash, org.ethereum.crypto.signature.ECDSASignature signature); boolean isPubKeyCanonical(); static boolean isPubKeyCanonical(byte[] pubkey); @Deprecated @Nullable static ECKey recoverFromSignature(int recId, ECDSASignature sig, byte[] messageHash, boolean compressed); @Nullable byte[] getPrivKeyBytes(); @Override boolean equals(Object o); @Override int hashCode(); static final ECDomainParameters CURVE; static final BigInteger HALF_CURVE_ORDER; }### Answer: @Test public void testGetAddress() { ECKey key = ECKey.fromPublicOnly(pubKey); assertArrayEquals(Hex.decode(address), key.getAddress()); }
### Question: NodeMessageHandler implements MessageHandler, InternalService, Runnable { @Override public void postMessage(Peer sender, Message message) { logger.trace("Start post message (queue size {}) (message type {})", this.queue.size(), message.getMessageType()); cleanExpiredMessages(); tryAddMessage(sender, message); logger.trace("End post message (queue size {})", this.queue.size()); } NodeMessageHandler(RskSystemProperties config, final BlockProcessor blockProcessor, final SyncProcessor syncProcessor, @Nullable final ChannelManager channelManager, @Nullable final TransactionGateway transactionGateway, @Nullable final PeerScoringManager peerScoringManager, StatusResolver statusResolver); synchronized void processMessage(final Peer sender, @Nonnull final Message message); @Override void postMessage(Peer sender, Message message); @Override void start(); @Override void stop(); @Override long getMessageQueueSize(); @Override void run(); static final int MAX_NUMBER_OF_MESSAGES_CACHED; static final long RECEIVED_MESSAGES_CACHE_DURATION; }### Answer: @Test public void postBlockMessageTwice() throws InterruptedException, UnknownHostException { Peer sender = new SimplePeer(); PeerScoringManager scoring = createPeerScoringManager(); SimpleBlockProcessor sbp = new SimpleBlockProcessor(); NodeMessageHandler processor = new NodeMessageHandler(config, sbp, null, null, null, scoring, mock(StatusResolver.class)); Block block = new BlockChainBuilder().ofSize(1, true).getBestBlock(); Message message = new BlockMessage(block); processor.postMessage(sender, message); processor.postMessage(sender, message); PeerScoring pscoring = scoring.getPeerScoring(sender.getPeerNodeID()); Assert.assertNotNull(pscoring); Assert.assertFalse(pscoring.isEmpty()); Assert.assertEquals(1, pscoring.getTotalEventCounter()); Assert.assertEquals(1, pscoring.getEventCounter(EventType.REPEATED_MESSAGE)); }
### Question: ECKey { public String toString() { StringBuilder b = new StringBuilder(); b.append("pub:").append(ByteUtil.toHexString(pub.getEncoded(false))); return b.toString(); } ECKey(); ECKey(SecureRandom secureRandom); ECKey(@Nullable BigInteger priv, ECPoint pub); static ECPoint compressPoint(ECPoint uncompressed); static ECPoint decompressPoint(ECPoint compressed); static ECKey fromPrivate(BigInteger privKey); static ECKey fromPrivate(byte[] privKeyBytes); static ECKey fromPublicOnly(ECPoint pub); static ECKey fromPublicOnly(byte[] pub); ECKey decompress(); boolean isPubKeyOnly(); boolean hasPrivKey(); static byte[] publicKeyFromPrivate(BigInteger privKey, boolean compressed); byte[] getAddress(); byte[] getNodeId(); byte[] getPubKey(); byte[] getPubKey(boolean compressed); ECPoint getPubKeyPoint(); boolean equalsPub(ECKey other); BigInteger getPrivKey(); String toString(); ECDSASignature doSign(byte[] input); ECDSASignature sign(byte[] messageHash); @Deprecated static ECKey signatureToKey(byte[] messageHash, ECDSASignature signature); byte[] decryptAES(byte[] cipher); @Deprecated static boolean verify(byte[] data, ECDSASignature signature, byte[] pub); @Deprecated boolean verify(byte[] sigHash, ECDSASignature signature); boolean verify(byte[] sigHash, org.ethereum.crypto.signature.ECDSASignature signature); boolean isPubKeyCanonical(); static boolean isPubKeyCanonical(byte[] pubkey); @Deprecated @Nullable static ECKey recoverFromSignature(int recId, ECDSASignature sig, byte[] messageHash, boolean compressed); @Nullable byte[] getPrivKeyBytes(); @Override boolean equals(Object o); @Override int hashCode(); static final ECDomainParameters CURVE; static final BigInteger HALF_CURVE_ORDER; }### Answer: @Test public void testToString() { ECKey key = ECKey.fromPrivate(BigInteger.TEN); assertEquals("pub:04a0434d9e47f3c86235477c7b1ae6ae5d3442d49b1943c2b752a68e2a47e247c7893aba425419bc27a3b6c7e693a24c696f794c2ed877a1593cbee53b037368d7", key.toString()); }
### Question: ECKey { public boolean isPubKeyCanonical() { return isPubKeyCanonical(pub.getEncoded(false)); } ECKey(); ECKey(SecureRandom secureRandom); ECKey(@Nullable BigInteger priv, ECPoint pub); static ECPoint compressPoint(ECPoint uncompressed); static ECPoint decompressPoint(ECPoint compressed); static ECKey fromPrivate(BigInteger privKey); static ECKey fromPrivate(byte[] privKeyBytes); static ECKey fromPublicOnly(ECPoint pub); static ECKey fromPublicOnly(byte[] pub); ECKey decompress(); boolean isPubKeyOnly(); boolean hasPrivKey(); static byte[] publicKeyFromPrivate(BigInteger privKey, boolean compressed); byte[] getAddress(); byte[] getNodeId(); byte[] getPubKey(); byte[] getPubKey(boolean compressed); ECPoint getPubKeyPoint(); boolean equalsPub(ECKey other); BigInteger getPrivKey(); String toString(); ECDSASignature doSign(byte[] input); ECDSASignature sign(byte[] messageHash); @Deprecated static ECKey signatureToKey(byte[] messageHash, ECDSASignature signature); byte[] decryptAES(byte[] cipher); @Deprecated static boolean verify(byte[] data, ECDSASignature signature, byte[] pub); @Deprecated boolean verify(byte[] sigHash, ECDSASignature signature); boolean verify(byte[] sigHash, org.ethereum.crypto.signature.ECDSASignature signature); boolean isPubKeyCanonical(); static boolean isPubKeyCanonical(byte[] pubkey); @Deprecated @Nullable static ECKey recoverFromSignature(int recId, ECDSASignature sig, byte[] messageHash, boolean compressed); @Nullable byte[] getPrivKeyBytes(); @Override boolean equals(Object o); @Override int hashCode(); static final ECDomainParameters CURVE; static final BigInteger HALF_CURVE_ORDER; }### Answer: @Test public void testIsPubKeyCanonicalCorect() { byte[] canonicalPubkey1 = new byte[65]; canonicalPubkey1[0] = 0x04; assertTrue(ECKey.isPubKeyCanonical(canonicalPubkey1)); byte[] canonicalPubkey2 = new byte[33]; canonicalPubkey2[0] = 0x02; assertTrue(ECKey.isPubKeyCanonical(canonicalPubkey2)); byte[] canonicalPubkey3 = new byte[33]; canonicalPubkey3[0] = 0x03; assertTrue(ECKey.isPubKeyCanonical(canonicalPubkey3)); } @Test public void testIsPubKeyCanonicalWrongLength() { byte[] nonCanonicalPubkey1 = new byte[64]; nonCanonicalPubkey1[0] = 0x04; assertFalse(ECKey.isPubKeyCanonical(nonCanonicalPubkey1)); byte[] nonCanonicalPubkey2 = new byte[32]; nonCanonicalPubkey2[0] = 0x02; assertFalse(ECKey.isPubKeyCanonical(nonCanonicalPubkey2)); byte[] nonCanonicalPubkey3 = new byte[32]; nonCanonicalPubkey3[0] = 0x03; assertFalse(ECKey.isPubKeyCanonical(nonCanonicalPubkey3)); } @Test public void testIsPubKeyCanonicalWrongPrefix() { byte[] nonCanonicalPubkey4 = new byte[65]; assertFalse(ECKey.isPubKeyCanonical(nonCanonicalPubkey4)); byte[] nonCanonicalPubkey5 = new byte[33]; assertFalse(ECKey.isPubKeyCanonical(nonCanonicalPubkey5)); byte[] nonCanonicalPubkey6 = new byte[33]; assertFalse(ECKey.isPubKeyCanonical(nonCanonicalPubkey6)); }
### Question: DecidingSyncState extends BaseSyncState { @Override public void tick(Duration duration) { peersInformation.cleanExpired(); timeElapsed = timeElapsed.plus(duration); if (peersInformation.count() > 0 && timeElapsed.compareTo(syncConfiguration.getTimeoutWaitingPeers()) >= 0) { tryStartSyncing(); } } DecidingSyncState(SyncConfiguration syncConfiguration, SyncEventsHandler syncEventsHandler, PeersInformation peersInformation, BlockStore blockStore); @Override void newPeerStatus(); @Override void tick(Duration duration); }### Answer: @Test public void doesntStartSyncingWithNoPeersAfter2Minutes() { SyncConfiguration syncConfiguration = SyncConfiguration.DEFAULT; SimpleSyncEventsHandler syncEventsHandler = new SimpleSyncEventsHandler(); PeersInformation knownPeers = mock(PeersInformation.class); when(knownPeers.count()).thenReturn(0); when(knownPeers.getBestPeer()).thenReturn(Optional.empty()); SyncState syncState = new DecidingSyncState(syncConfiguration, syncEventsHandler, knownPeers, mock(BlockStore.class)); syncState.tick(Duration.ofMinutes(2)); Assert.assertFalse(syncEventsHandler.startSyncingWasCalled()); } @Test public void startsSyncingWith1PeerAfter2Minutes() { SyncConfiguration syncConfiguration = SyncConfiguration.DEFAULT; SyncEventsHandler syncEventsHandler = mock(SyncEventsHandler.class); PeersInformation peersInformation = mock(PeersInformation.class); when(peersInformation.count()).thenReturn(1); when(peersInformation.getBestPeer()).thenReturn(Optional.of(mock(Peer.class))); Status status = mock(Status.class); SyncPeerStatus bpStatus = mock(SyncPeerStatus.class); when(bpStatus.getStatus()).thenReturn(status); when(peersInformation.getPeer(any())).thenReturn(bpStatus); BlockStore blockStore = mock(BlockStore.class); Block bestBlock = mock(Block.class); when(blockStore.getBestBlock()).thenReturn(bestBlock); when(bestBlock.getNumber()).thenReturn(100L); SyncState syncState = new DecidingSyncState( syncConfiguration, syncEventsHandler, peersInformation, blockStore); verify(syncEventsHandler, never()).startSyncing(any()); syncState.tick(Duration.ofMinutes(2)); verify(syncEventsHandler).startSyncing(any()); }
### Question: DownloadingBackwardsBodiesSyncState extends BaseSyncState { @Override public void onEnter() { if (child.getNumber() == 1L) { connectGenesis(child); blockStore.flush(); syncEventsHandler.stopSyncing(); return; } if (toRequest.isEmpty()) { syncEventsHandler.stopSyncing(); return; } while (!toRequest.isEmpty() && inTransit.size() < syncConfiguration.getMaxRequestedBodies()) { BlockHeader headerToRequest = toRequest.remove(); requestBodies(headerToRequest); } } DownloadingBackwardsBodiesSyncState( SyncConfiguration syncConfiguration, SyncEventsHandler syncEventsHandler, PeersInformation peersInformation, Genesis genesis, BlockFactory blockFactory, BlockStore blockStore, Block child, List<BlockHeader> toRequest, Peer peer); @Override void newBody(BodyResponseMessage body, Peer peer); @Override void onEnter(); }### Answer: @Test(expected = IllegalStateException.class) public void onEnter_connectGenesis_genesisIsNotChildsParent() { List<BlockHeader> toRequest = new LinkedList<>(); DownloadingBackwardsBodiesSyncState target = new DownloadingBackwardsBodiesSyncState( syncConfiguration, syncEventsHandler, peersInformation, genesis, blockFactory, blockStore, child, toRequest, peer); when(child.getNumber()).thenReturn(1L); when(genesis.isParentOf(child)).thenReturn(false); target.onEnter(); } @Test(expected = IllegalStateException.class) public void onEnter_connectGenesis_difficultyDoesNotMatch() { List<BlockHeader> toRequest = new LinkedList<>(); DownloadingBackwardsBodiesSyncState target = new DownloadingBackwardsBodiesSyncState( syncConfiguration, syncEventsHandler, peersInformation, genesis, blockFactory, blockStore, child, toRequest, peer); Keccak256 childHash = new Keccak256(new byte[32]); when(child.getHash()).thenReturn(childHash); when(child.getNumber()).thenReturn(1L); when(genesis.isParentOf(child)).thenReturn(true); when(child.getCumulativeDifficulty()).thenReturn(new BlockDifficulty(BigInteger.valueOf(50))); when(genesis.getCumulativeDifficulty()).thenReturn(new BlockDifficulty(BigInteger.valueOf(50))); when(blockStore.getTotalDifficultyForHash(eq(childHash.getBytes()))) .thenReturn(new BlockDifficulty(BigInteger.valueOf(101))); target.onEnter(); } @Test public void onEnter_connectGenesis() { List<BlockHeader> toRequest = new LinkedList<>(); DownloadingBackwardsBodiesSyncState target = new DownloadingBackwardsBodiesSyncState( syncConfiguration, syncEventsHandler, peersInformation, genesis, blockFactory, blockStore, child, toRequest, peer); Keccak256 childHash = new Keccak256(new byte[32]); when(child.getHash()).thenReturn(childHash); when(child.getNumber()).thenReturn(1L); when(genesis.isParentOf(child)).thenReturn(true); when(child.getCumulativeDifficulty()).thenReturn(new BlockDifficulty(BigInteger.valueOf(50))); BlockDifficulty cumulativeDifficulty = new BlockDifficulty(BigInteger.valueOf(50)); when(genesis.getCumulativeDifficulty()).thenReturn(cumulativeDifficulty); when(blockStore.getTotalDifficultyForHash(eq(childHash.getBytes()))) .thenReturn(new BlockDifficulty(BigInteger.valueOf(100))); target.onEnter(); verify(blockStore).saveBlock(eq(genesis), eq(cumulativeDifficulty), eq(true)); verify(blockStore).flush(); verify(syncEventsHandler).stopSyncing(); }
### Question: DownloadingBackwardsHeadersSyncState extends BaseSyncState { @Override public void onEnter() { Keccak256 hashToRequest = child.getHash(); ChunkDescriptor chunkDescriptor = new ChunkDescriptor( hashToRequest.getBytes(), syncConfiguration.getChunkSize()); syncEventsHandler.sendBlockHeadersRequest(selectedPeer, chunkDescriptor); } DownloadingBackwardsHeadersSyncState( SyncConfiguration syncConfiguration, SyncEventsHandler syncEventsHandler, BlockStore blockStore, Peer peer); @Override void newBlockHeaders(List<BlockHeader> toRequest); @Override void onEnter(); }### Answer: @Test public void onEnter() { when(blockStore.getMinNumber()).thenReturn(50L); Block child = mock(Block.class); Keccak256 hash = new Keccak256(new byte[32]); when(child.getHash()).thenReturn(hash); when(blockStore.getChainBlockByNumber(50L)).thenReturn(child); DownloadingBackwardsHeadersSyncState target = new DownloadingBackwardsHeadersSyncState( syncConfiguration, syncEventsHandler, blockStore, selectedPeer); ArgumentCaptor<ChunkDescriptor> descriptorCaptor = ArgumentCaptor.forClass(ChunkDescriptor.class); target.onEnter(); verify(syncEventsHandler).sendBlockHeadersRequest(eq(selectedPeer), descriptorCaptor.capture()); verify(syncEventsHandler, never()).onSyncIssue(any(), any()); assertEquals(descriptorCaptor.getValue().getHash(), hash.getBytes()); assertEquals(descriptorCaptor.getValue().getCount(), syncConfiguration.getChunkSize()); }
### Question: DownloadingBackwardsHeadersSyncState extends BaseSyncState { @Override public void newBlockHeaders(List<BlockHeader> toRequest) { syncEventsHandler.backwardDownloadBodies( child, toRequest.stream().skip(1).collect(Collectors.toList()), selectedPeer ); } DownloadingBackwardsHeadersSyncState( SyncConfiguration syncConfiguration, SyncEventsHandler syncEventsHandler, BlockStore blockStore, Peer peer); @Override void newBlockHeaders(List<BlockHeader> toRequest); @Override void onEnter(); }### Answer: @Test public void newHeaders() { when(blockStore.getMinNumber()).thenReturn(50L); Block child = mock(Block.class); Keccak256 hash = new Keccak256(new byte[32]); when(child.getHash()).thenReturn(hash); when(blockStore.getChainBlockByNumber(50L)).thenReturn(child); DownloadingBackwardsHeadersSyncState target = new DownloadingBackwardsHeadersSyncState( syncConfiguration, syncEventsHandler, blockStore, selectedPeer); List<BlockHeader> receivedHeaders = new LinkedList<>(); target.newBlockHeaders(receivedHeaders); verify(syncEventsHandler).backwardDownloadBodies(eq(child), eq(receivedHeaders), eq(selectedPeer)); }
### Question: BlockNodeInformation { @Nonnull public synchronized Set<NodeID> getNodesByBlock(@Nonnull final Keccak256 blockHash) { Set<NodeID> result = nodesByBlock.get(blockHash); if (result == null) { result = new HashSet<>(); } return new HashSet<>(result); } BlockNodeInformation(final int maxBlocks); BlockNodeInformation(); synchronized void addBlockToNode(@Nonnull final Keccak256 blockHash, @Nonnull final NodeID nodeID); @Nonnull synchronized Set<NodeID> getNodesByBlock(@Nonnull final Keccak256 blockHash); @Nonnull Set<NodeID> getNodesByBlock(@Nonnull final byte[] blockHash); }### Answer: @Test public void getIsEmptyIfNotPresent() { final BlockNodeInformation nodeInformation = new BlockNodeInformation(); Assert.assertTrue(nodeInformation.getNodesByBlock(createBlockHash(0)).size() == 0); Assert.assertTrue(nodeInformation.getNodesByBlock(createBlockHash(0)).size() == 0); }
### Question: SyncProcessor implements SyncEventsHandler { @Override public void sendSkeletonRequest(Peer peer, long height) { logger.debug("Send skeleton request to node {} height {}", peer.getPeerNodeID(), height); MessageWithId message = new SkeletonRequestMessage(++lastRequestId, height); sendMessage(peer, message); } SyncProcessor(Blockchain blockchain, BlockStore blockStore, ConsensusValidationMainchainView consensusValidationMainchainView, BlockSyncService blockSyncService, SyncConfiguration syncConfiguration, BlockFactory blockFactory, BlockHeaderValidationRule blockHeaderValidationRule, SyncBlockValidatorRule syncBlockValidatorRule, DifficultyCalculator difficultyCalculator, PeersInformation peersInformation, Genesis genesis); void processStatus(Peer sender, Status status); void processSkeletonResponse(Peer peer, SkeletonResponseMessage message); void processBlockHashResponse(Peer peer, BlockHashResponseMessage message); void processBlockHeadersResponse(Peer peer, BlockHeadersResponseMessage message); void processBodyResponse(Peer peer, BodyResponseMessage message); void processNewBlockHash(Peer peer, NewBlockHashMessage message); void processBlockResponse(Peer peer, BlockResponseMessage message); @Override void sendSkeletonRequest(Peer peer, long height); @Override void sendBlockHashRequest(Peer peer, long height); @Override void sendBlockHeadersRequest(Peer peer, ChunkDescriptor chunk); @Override long sendBodyRequest(Peer peer, @Nonnull BlockHeader header); Set<NodeID> getKnownPeersNodeIDs(); void onTimePassed(Duration timePassed); @Override void startSyncing(Peer peer); @Override void startDownloadingBodies( List<Deque<BlockHeader>> pendingHeaders, Map<Peer, List<BlockIdentifier>> skeletons, Peer peer); @Override void startDownloadingHeaders(Map<Peer, List<BlockIdentifier>> skeletons, long connectionPoint, Peer peer); @Override void startDownloadingSkeleton(long connectionPoint, Peer peer); @Override void startFindingConnectionPoint(Peer peer); @Override void backwardSyncing(Peer peer); @Override void backwardDownloadBodies(Block child, List<BlockHeader> toRequest, Peer peer); @Override void stopSyncing(); @Override void onErrorSyncing(NodeID peerId, String message, EventType eventType, Object... arguments); @Override void onSyncIssue(String message, Object... arguments); @VisibleForTesting void registerExpectedMessage(MessageWithId message); @VisibleForTesting SyncState getSyncState(); @VisibleForTesting Map<Long, MessageType> getExpectedResponses(); }### Answer: @Test public void sendSkeletonRequest() { Blockchain blockchain = new BlockChainBuilder().ofSize(100); SimplePeer sender = new SimplePeer(new byte[] { 0x01 }); final ChannelManager channelManager = mock(ChannelManager.class); Peer channel = mock(Peer.class); when(channel.getPeerNodeID()).thenReturn(sender.getPeerNodeID()); when(channelManager.getActivePeers()).thenReturn(Collections.singletonList(channel)); SyncProcessor processor = new SyncProcessor( blockchain, mock(org.ethereum.db.BlockStore.class), mock(ConsensusValidationMainchainView.class), null, SyncConfiguration.IMMEDIATE_FOR_TESTING, blockFactory, new ProofOfWorkRule(config).setFallbackMiningEnabled(false), new SyncBlockValidatorRule( new BlockUnclesHashValidationRule(), new BlockRootValidationRule(config.getActivationConfig()) ), DIFFICULTY_CALCULATOR, new PeersInformation(channelManager, SyncConfiguration.IMMEDIATE_FOR_TESTING, blockchain, RskMockFactory.getPeerScoringManager()), mock(Genesis.class)); processor.sendSkeletonRequest(sender, 0); Assert.assertFalse(sender.getMessages().isEmpty()); Message message = sender.getMessages().get(0); Assert.assertEquals(MessageType.SKELETON_REQUEST_MESSAGE, message.getMessageType()); SkeletonRequestMessage request = (SkeletonRequestMessage) message; Assert.assertNotEquals(0, request.getId()); Assert.assertEquals(0, request.getStartNumber()); Assert.assertEquals(1, processor.getExpectedResponses().size()); }
### Question: SyncProcessor implements SyncEventsHandler { @Override public void sendBlockHashRequest(Peer peer, long height) { logger.debug("Send hash request to node {} height {}", peer.getPeerNodeID(), height); BlockHashRequestMessage message = new BlockHashRequestMessage(++lastRequestId, height); sendMessage(peer, message); } SyncProcessor(Blockchain blockchain, BlockStore blockStore, ConsensusValidationMainchainView consensusValidationMainchainView, BlockSyncService blockSyncService, SyncConfiguration syncConfiguration, BlockFactory blockFactory, BlockHeaderValidationRule blockHeaderValidationRule, SyncBlockValidatorRule syncBlockValidatorRule, DifficultyCalculator difficultyCalculator, PeersInformation peersInformation, Genesis genesis); void processStatus(Peer sender, Status status); void processSkeletonResponse(Peer peer, SkeletonResponseMessage message); void processBlockHashResponse(Peer peer, BlockHashResponseMessage message); void processBlockHeadersResponse(Peer peer, BlockHeadersResponseMessage message); void processBodyResponse(Peer peer, BodyResponseMessage message); void processNewBlockHash(Peer peer, NewBlockHashMessage message); void processBlockResponse(Peer peer, BlockResponseMessage message); @Override void sendSkeletonRequest(Peer peer, long height); @Override void sendBlockHashRequest(Peer peer, long height); @Override void sendBlockHeadersRequest(Peer peer, ChunkDescriptor chunk); @Override long sendBodyRequest(Peer peer, @Nonnull BlockHeader header); Set<NodeID> getKnownPeersNodeIDs(); void onTimePassed(Duration timePassed); @Override void startSyncing(Peer peer); @Override void startDownloadingBodies( List<Deque<BlockHeader>> pendingHeaders, Map<Peer, List<BlockIdentifier>> skeletons, Peer peer); @Override void startDownloadingHeaders(Map<Peer, List<BlockIdentifier>> skeletons, long connectionPoint, Peer peer); @Override void startDownloadingSkeleton(long connectionPoint, Peer peer); @Override void startFindingConnectionPoint(Peer peer); @Override void backwardSyncing(Peer peer); @Override void backwardDownloadBodies(Block child, List<BlockHeader> toRequest, Peer peer); @Override void stopSyncing(); @Override void onErrorSyncing(NodeID peerId, String message, EventType eventType, Object... arguments); @Override void onSyncIssue(String message, Object... arguments); @VisibleForTesting void registerExpectedMessage(MessageWithId message); @VisibleForTesting SyncState getSyncState(); @VisibleForTesting Map<Long, MessageType> getExpectedResponses(); }### Answer: @Test public void sendBlockHashRequest() { Blockchain blockchain = new BlockChainBuilder().ofSize(0); SimplePeer sender = new SimplePeer(new byte[] { 0x01 }); final ChannelManager channelManager = mock(ChannelManager.class); Peer channel = mock(Peer.class); when(channel.getPeerNodeID()).thenReturn(sender.getPeerNodeID()); when(channelManager.getActivePeers()).thenReturn(Collections.singletonList(channel)); SyncProcessor processor = new SyncProcessor( blockchain, mock(org.ethereum.db.BlockStore.class), mock(ConsensusValidationMainchainView.class), null, SyncConfiguration.IMMEDIATE_FOR_TESTING, blockFactory, new ProofOfWorkRule(config).setFallbackMiningEnabled(false), new SyncBlockValidatorRule( new BlockUnclesHashValidationRule(), new BlockRootValidationRule(config.getActivationConfig()) ), DIFFICULTY_CALCULATOR, new PeersInformation(channelManager, SyncConfiguration.IMMEDIATE_FOR_TESTING, blockchain, RskMockFactory.getPeerScoringManager()), mock(Genesis.class)); processor.sendBlockHashRequest(sender, 100); Assert.assertFalse(sender.getMessages().isEmpty()); Message message = sender.getMessages().get(0); Assert.assertEquals(MessageType.BLOCK_HASH_REQUEST_MESSAGE, message.getMessageType()); BlockHashRequestMessage request = (BlockHashRequestMessage) message; Assert.assertNotEquals(0, request.getId()); Assert.assertEquals(100, request.getHeight()); Assert.assertEquals(1, processor.getExpectedResponses().size()); }
### Question: SyncProcessor implements SyncEventsHandler { public void processStatus(Peer sender, Status status) { logger.debug("Receiving syncState from node {} block {} {}", sender.getPeerNodeID(), status.getBestBlockNumber(), HashUtil.toPrintableHash(status.getBestBlockHash())); peersInformation.registerPeer(sender).setStatus(status); syncState.newPeerStatus(); } SyncProcessor(Blockchain blockchain, BlockStore blockStore, ConsensusValidationMainchainView consensusValidationMainchainView, BlockSyncService blockSyncService, SyncConfiguration syncConfiguration, BlockFactory blockFactory, BlockHeaderValidationRule blockHeaderValidationRule, SyncBlockValidatorRule syncBlockValidatorRule, DifficultyCalculator difficultyCalculator, PeersInformation peersInformation, Genesis genesis); void processStatus(Peer sender, Status status); void processSkeletonResponse(Peer peer, SkeletonResponseMessage message); void processBlockHashResponse(Peer peer, BlockHashResponseMessage message); void processBlockHeadersResponse(Peer peer, BlockHeadersResponseMessage message); void processBodyResponse(Peer peer, BodyResponseMessage message); void processNewBlockHash(Peer peer, NewBlockHashMessage message); void processBlockResponse(Peer peer, BlockResponseMessage message); @Override void sendSkeletonRequest(Peer peer, long height); @Override void sendBlockHashRequest(Peer peer, long height); @Override void sendBlockHeadersRequest(Peer peer, ChunkDescriptor chunk); @Override long sendBodyRequest(Peer peer, @Nonnull BlockHeader header); Set<NodeID> getKnownPeersNodeIDs(); void onTimePassed(Duration timePassed); @Override void startSyncing(Peer peer); @Override void startDownloadingBodies( List<Deque<BlockHeader>> pendingHeaders, Map<Peer, List<BlockIdentifier>> skeletons, Peer peer); @Override void startDownloadingHeaders(Map<Peer, List<BlockIdentifier>> skeletons, long connectionPoint, Peer peer); @Override void startDownloadingSkeleton(long connectionPoint, Peer peer); @Override void startFindingConnectionPoint(Peer peer); @Override void backwardSyncing(Peer peer); @Override void backwardDownloadBodies(Block child, List<BlockHeader> toRequest, Peer peer); @Override void stopSyncing(); @Override void onErrorSyncing(NodeID peerId, String message, EventType eventType, Object... arguments); @Override void onSyncIssue(String message, Object... arguments); @VisibleForTesting void registerExpectedMessage(MessageWithId message); @VisibleForTesting SyncState getSyncState(); @VisibleForTesting Map<Long, MessageType> getExpectedResponses(); }### Answer: @Test(expected = Exception.class) public void processBlockHashResponseWithUnknownHash() { Blockchain blockchain = new BlockChainBuilder().ofSize(0); SimplePeer sender = new SimplePeer(new byte[] { 0x01 }); SyncProcessor processor = new SyncProcessor( blockchain, mock(org.ethereum.db.BlockStore.class), mock(ConsensusValidationMainchainView.class), null, SyncConfiguration.IMMEDIATE_FOR_TESTING, blockFactory, new ProofOfWorkRule(config).setFallbackMiningEnabled(false), new SyncBlockValidatorRule( new BlockUnclesHashValidationRule(), new BlockRootValidationRule(config.getActivationConfig()) ), DIFFICULTY_CALCULATOR, new PeersInformation(getChannelManager(), SyncConfiguration.IMMEDIATE_FOR_TESTING, blockchain, RskMockFactory.getPeerScoringManager()), mock(Genesis.class)); processor.processStatus(sender, new Status(100, null)); }
### Question: ABICallElection { public Map<ABICallSpec, List<RskAddress>> getVotes() { return votes; } ABICallElection(AddressBasedAuthorizer authorizer, Map<ABICallSpec, List<RskAddress>> votes); ABICallElection(AddressBasedAuthorizer authorizer); Map<ABICallSpec, List<RskAddress>> getVotes(); void clear(); boolean vote(ABICallSpec callSpec, RskAddress voter); ABICallSpec getWinner(); void clearWinners(); }### Answer: @Test public void emptyVotesConstructor() { ABICallElection electionBis = new ABICallElection(authorizer); Assert.assertEquals(0, electionBis.getVotes().size()); } @Test public void getVotes() { Assert.assertSame(votes, election.getVotes()); }