src_fm_fc_ms_ff stringlengths 43 86.8k | target stringlengths 20 276k |
|---|---|
EthSubscriptionNotificationEmitter implements EthSubscribeParamsVisitor { public boolean unsubscribe(SubscriptionId subscriptionId) { boolean unsubscribedBlockHeader = blockHeader.unsubscribe(subscriptionId); boolean unsubscribedLogs = logs.unsubscribe(subscriptionId); return unsubscribedBlockHeader || unsubscribedLogs... | @Test public void unsubscribeUnsuccessfully() { SubscriptionId subscriptionId = mock(SubscriptionId.class); boolean unsubscribed = emitter.unsubscribe(subscriptionId); assertThat(unsubscribed, is(false)); verify(newHeads).unsubscribe(subscriptionId); verify(logs).unsubscribe(subscriptionId); }
@Test public void unsubsc... |
TxPoolModuleImpl implements TxPoolModule { @Override public JsonNode content() { Map<String, JsonNode> contentProps = new HashMap<>(); Map<RskAddress, Map<BigInteger, List<Transaction>>> pendingGrouped = groupTransactions(transactionPool.getPendingTransactions()); Map<RskAddress, Map<BigInteger, List<Transaction>>> que... | @Test public void txpool_content_basic() throws IOException { JsonNode node = txPoolModule.content(); checkFieldIsObject(node,"pending"); checkFieldIsObject(node,"queued"); }
@Test public void txpool_content_oneTx() throws Exception { Transaction tx = createSampleTransaction(); when(transactionPool.getPendingTransactio... |
TxPoolModuleImpl implements TxPoolModule { @Override public JsonNode inspect() { Map<String, JsonNode> contentProps = new HashMap<>(); Map<RskAddress, Map<BigInteger, List<Transaction>>> pendingGrouped = groupTransactions(transactionPool.getPendingTransactions()); Map<RskAddress, Map<BigInteger, List<Transaction>>> que... | @Test public void txpool_inspect_basic() throws IOException { JsonNode node = txPoolModule.inspect(); checkFieldIsObject(node,"pending"); checkFieldIsObject(node,"queued"); }
@Test public void txpool_inspect_oneTx() throws Exception { Transaction tx = createSampleTransaction(); when(transactionPool.getPendingTransactio... |
TxPoolModuleImpl implements TxPoolModule { @Override public JsonNode status() { Map<String, JsonNode> txProps = new HashMap<>(); txProps.put(PENDING, jsonNodeFactory.numberNode(transactionPool.getPendingTransactions().size())); txProps.put(QUEUED, jsonNodeFactory.numberNode(transactionPool.getQueuedTransactions().size(... | @Test public void txpool_status_basic() throws IOException { JsonNode node = txPoolModule.status(); checkFieldIsNumber(node,"pending"); checkFieldIsNumber(node,"queued"); }
@Test public void txpool_status_oneTx() throws Exception { Transaction tx = createSampleTransaction(); when(transactionPool.getPendingTransactions(... |
Web3Impl implements Web3 { @Override public BlockResultDTO eth_getUncleByBlockNumberAndIndex(String blockId, String uncleIdx) { BlockResultDTO s = null; try { Optional<Block> block = web3InformationRetriever.getBlock(blockId); if (!block.isPresent()) { return null; } s = getUncleResultDTO(uncleIdx, block.get()); return... | @Test public void getUncleByBlockNumberAndIndexBlockWithUncles() { World world = new World(); Web3Impl web3 = createWeb3(world); Block genesis = world.getBlockChain().getBestBlock(); Block blockA = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()) .trieStore(world.getTrieSt... |
CallArgumentsToByteArray { public byte[] getToAddress() { byte[] toAddress = null; if (args.to != null) { toAddress = stringHexToByteArray(args.to); } return toAddress; } CallArgumentsToByteArray(Web3.CallArguments args); byte[] getGasPrice(); byte[] getGasLimit(); byte[] getToAddress(); byte[] getValue(); byte[] getDa... | @Test public void getToAddressWhenValueIsNull() throws Exception { Web3.CallArguments args = new Web3.CallArguments(); CallArgumentsToByteArray byteArrayArgs = new CallArgumentsToByteArray(args); Assert.assertNull(byteArrayArgs.getToAddress()); } |
DebugModuleImpl implements DebugModule { @Override public String wireProtocolQueueSize() { long n = messageHandler.getMessageQueueSize(); return TypeConverter.toQuantityJsonHex(n); } DebugModuleImpl(
BlockStore blockStore,
ReceiptStore receiptStore,
MessageHandler messageHandler,
... | @Test public void debug_wireProtocolQueueSize_basic() throws IOException { String result = debugModule.wireProtocolQueueSize(); try { TypeConverter.JSonHexToLong(result); } catch (NumberFormatException e) { Assert.fail("This method is not returning a 0x Long"); } }
@Test public void debug_wireProtocolQueueSize_value() ... |
DebugModuleImpl implements DebugModule { @Override public JsonNode traceTransaction(String transactionHash, Map<String, String> traceOptions) throws Exception { logger.trace("debug_traceTransaction({}, {})", transactionHash, traceOptions); if (traceOptions != null && !traceOptions.isEmpty()) { logger.warn("Received {} ... | @Test public void debug_traceTransaction_retrieveUnknownTransactionAsNull() throws Exception { byte[] hash = stringHexToByteArray("0x00"); when(receiptStore.getAll(hash)).thenReturn(Collections.emptyList()); when(receiptStore.getInMainChain(hash, blockStore)).thenReturn(null); JsonNode result = debugModule.traceTransac... |
EthModule implements EthModuleWallet, EthModuleTransaction { public String call(Web3.CallArguments args, String bnOrId) { String s = null; try { BlockResult blockResult = executionBlockRetriever.getExecutionBlock_workaround(bnOrId); ProgramResult res; if (blockResult.getFinalState() != null) { res = callConstant_workar... | @Test public void callSmokeTest() { Web3.CallArguments args = new Web3.CallArguments(); BlockResult blockResult = mock(BlockResult.class); Block block = mock(Block.class); ExecutionBlockRetriever retriever = mock(ExecutionBlockRetriever.class); when(retriever.getExecutionBlock_workaround("latest")) .thenReturn(blockRes... |
Web3Impl implements Web3 { @Override public String personal_newAccountWithSeed(String seed) { return personalModule.newAccountWithSeed(seed); } protected Web3Impl(
Ethereum eth,
Blockchain blockchain,
BlockStore blockStore,
ReceiptStore receiptStore,
RskSyste... | @Test public void callFromAddressInWallet() throws Exception { World world = new World(); Account acc1 = new AccountBuilder(world).name("notDefault").balance(Coin.valueOf(10000000)).build(); Block genesis = world.getBlockByName("g00"); Transaction tx = new TransactionBuilder() .sender(acc1) .gasLimit(BigInteger.valueOf... |
EthModule implements EthModuleWallet, EthModuleTransaction { public String getCode(String address, String blockId) { if (blockId == null) { throw new NullPointerException(); } String s = null; try { RskAddress addr = new RskAddress(address); AccountInformationProvider accountInformationProvider = getAccountInformationP... | @Test public void getCode() { byte[] expectedCode = new byte[] {1, 2, 3}; TransactionPool mockTransactionPool = mock(TransactionPool.class); PendingState mockPendingState = mock(PendingState.class); doReturn(expectedCode).when(mockPendingState).getCode(any(RskAddress.class)); doReturn(mockPendingState).when(mockTransac... |
EthModule implements EthModuleWallet, EthModuleTransaction { public String chainId() { return TypeConverter.toJsonHex(new byte[] { chainId }); } EthModule(
BridgeConstants bridgeConstants,
byte chainId,
Blockchain blockchain,
TransactionPool transactionPool,
R... | @Test public void chainId() { EthModule eth = new EthModule( mock(BridgeConstants.class), (byte) 33, mock(Blockchain.class), mock(TransactionPool.class), mock(ReversibleTransactionExecutor.class), mock(ExecutionBlockRetriever.class), mock(RepositoryLocator.class), mock(EthModuleWallet.class), mock(EthModuleTransaction.... |
EthUnsubscribeRequest extends RskJsonRpcRequest { @JsonInclude(JsonInclude.Include.NON_NULL) public EthUnsubscribeParams getParams() { return params; } @JsonCreator EthUnsubscribeRequest(
@JsonProperty("jsonrpc") JsonRpcVersion version,
@JsonProperty("method") RskJsonRpcMethod method,
... | @Test public void deserializeUnsubscribe() throws IOException { String message = "{\"jsonrpc\":\"2.0\",\"id\":100,\"method\":\"eth_unsubscribe\",\"params\":[\"0x0204\"]}"; RskJsonRpcRequest request = serializer.deserializeRequest( new ByteArrayInputStream(message.getBytes(StandardCharsets.UTF_8)) ); assertThat(request,... |
LogsNotification implements EthSubscriptionNotificationDTO { public String getLogIndex() { if (lazyLogIndex == null) { lazyLogIndex = toQuantityJsonHex(logInfoIndex); } return lazyLogIndex; } LogsNotification(LogInfo logInfo, Block b, int txIndex, Transaction tx, int logIdx, boolean r); String getLogIndex(); String get... | @Test public void getLogIndex() { assertThat(logsNotification.getLogIndex(), is(QUANTITY_JSON_HEX)); } |
LogsNotification implements EthSubscriptionNotificationDTO { public String getBlockNumber() { if (lazyBlockNumber == null) { lazyBlockNumber = toQuantityJsonHex(block.getNumber()); } return lazyBlockNumber; } LogsNotification(LogInfo logInfo, Block b, int txIndex, Transaction tx, int logIdx, boolean r); String getLogIn... | @Test public void getBlockNumber() { doReturn(42L).when(block).getNumber(); assertThat(logsNotification.getBlockNumber(), is(QUANTITY_JSON_HEX)); } |
LogsNotification implements EthSubscriptionNotificationDTO { public String getBlockHash() { if (lazyBlockHash == null) { lazyBlockHash = block.getHashJsonString(); } return lazyBlockHash; } LogsNotification(LogInfo logInfo, Block b, int txIndex, Transaction tx, int logIdx, boolean r); String getLogIndex(); String getBl... | @Test public void getBlockHash() { Keccak256 blockHash = TestUtils.randomHash(); doReturn(blockHash).when(block).getHash(); doCallRealMethod().when(block).getHashJsonString(); assertThat(logsNotification.getBlockHash(), is(toUnformattedJsonHex(blockHash.getBytes()))); } |
LogsNotification implements EthSubscriptionNotificationDTO { public String getTransactionHash() { if (lazyTransactionHash == null) { lazyTransactionHash = transaction.getHash().toJsonString(); } return lazyTransactionHash; } LogsNotification(LogInfo logInfo, Block b, int txIndex, Transaction tx, int logIdx, boolean r);... | @Test public void getTransactionHash() { Keccak256 transactionHash = TestUtils.randomHash(); doReturn(transactionHash).when(transaction).getHash(); assertThat(logsNotification.getTransactionHash(), is(toUnformattedJsonHex(transactionHash.getBytes()))); } |
LogsNotification implements EthSubscriptionNotificationDTO { public String getTransactionIndex() { if (lazyTransactionIndex == null) { lazyTransactionIndex = toQuantityJsonHex(transactionIndex); } return lazyTransactionIndex; } LogsNotification(LogInfo logInfo, Block b, int txIndex, Transaction tx, int logIdx, boolean ... | @Test public void getTransactionIndex() { assertThat(logsNotification.getTransactionIndex(), is(QUANTITY_JSON_HEX)); } |
LogsNotification implements EthSubscriptionNotificationDTO { public String getAddress() { if (lazyAddress == null) { lazyAddress = toJsonHex(logInfo.getAddress()); } return lazyAddress; } LogsNotification(LogInfo logInfo, Block b, int txIndex, Transaction tx, int logIdx, boolean r); String getLogIndex(); String getBloc... | @Test public void getAddress() { byte[] logSender = TestUtils.randomAddress().getBytes(); doReturn(logSender).when(logInfo).getAddress(); assertThat(logsNotification.getAddress(), is(toJsonHex(logSender))); } |
LogsNotification implements EthSubscriptionNotificationDTO { public String getData() { if (lazyData == null) { lazyData = toJsonHex(logInfo.getData()); } return lazyData; } LogsNotification(LogInfo logInfo, Block b, int txIndex, Transaction tx, int logIdx, boolean r); String getLogIndex(); String getBlockNumber(); Stri... | @Test public void getData() { byte[] logData = TestUtils.randomBytes(random.nextInt(1024)); doReturn(logData).when(logInfo).getData(); assertThat(logsNotification.getData(), is(toJsonHex(logData))); } |
Web3Impl implements Web3 { @Override public boolean net_listening() { Boolean s = null; try { return s = peerServer.isListening(); } finally { if (logger.isDebugEnabled()) { logger.debug("net_listening(): {}", s); } } } protected Web3Impl(
Ethereum eth,
Blockchain blockchain,
BlockS... | @Test public void net_listening() { World world = new World(); SimpleEthereum eth = new SimpleEthereum(world.getBlockChain()); SimplePeerServer peerServer = new SimplePeerServer(); Web3Impl web3 = createWeb3(eth, peerServer); assertTrue("Node is not listening", !web3.net_listening()); peerServer.isListening = true; ass... |
LogsNotification implements EthSubscriptionNotificationDTO { public List<String> getTopics() { if (lazyTopics == null) { lazyTopics = logInfo.getTopics().stream() .map(t -> toJsonHex(t.getData())) .collect(Collectors.toList()); } return Collections.unmodifiableList(lazyTopics); } LogsNotification(LogInfo logInfo, Block... | @Test public void getTopics() { List<DataWord> logTopics = IntStream.range(0, random.nextInt(1024)).mapToObj(i -> TestUtils.randomDataWord()).collect(Collectors.toList()); doReturn(logTopics).when(logInfo).getTopics(); for (int i = 0; i < logTopics.size(); i++) { assertThat(logsNotification.getTopics().get(i), is(toJso... |
LogsNotificationEmitter { public void subscribe(SubscriptionId subscriptionId, Channel channel, EthSubscribeLogsParams params) { subscriptions.put(subscriptionId, new Subscription(channel, params)); } LogsNotificationEmitter(
Ethereum ethereum,
JsonRpcSerializer jsonRpcSerializer,
Re... | @Test public void onBestBlockEventTriggersMessageToChannel() throws JsonProcessingException { SubscriptionId subscriptionId = mock(SubscriptionId.class); Channel channel = mock(Channel.class); EthSubscribeLogsParams params = mock(EthSubscribeLogsParams.class); emitter.subscribe(subscriptionId, channel, params); when(se... |
BlockHeaderNotificationEmitter { public void subscribe(SubscriptionId subscriptionId, Channel channel) { subscriptions.put(subscriptionId, channel); } BlockHeaderNotificationEmitter(Ethereum ethereum, JsonRpcSerializer jsonRpcSerializer); void subscribe(SubscriptionId subscriptionId, Channel channel); boolean unsubscri... | @Test public void ethereumOnBlockEventTriggersMessageToChannel() throws JsonProcessingException { SubscriptionId subscriptionId = mock(SubscriptionId.class); Channel channel = mock(Channel.class); emitter.subscribe(subscriptionId, channel); when(serializer.serializeMessage(any())) .thenReturn("serialized"); listener.on... |
TraceAddress { @JsonValue public int[] toAddress() { if (this.parent == null) { return EMPTY_ADDRESS; } int[] parentAddress = this.parent.toAddress(); int[] address = Arrays.copyOf(parentAddress, parentAddress.length + 1); address[address.length - 1] = this.index; return address; } TraceAddress(); TraceAddress(TraceAd... | @Test public void getTopAddress() { TraceAddress address = new TraceAddress(); Assert.assertArrayEquals(new int[0], address.toAddress()); }
@Test public void getChildAddress() { TraceAddress parent = new TraceAddress(); TraceAddress address = new TraceAddress(parent, 1); Assert.assertArrayEquals(new int[] { 1 }, addres... |
TraceTransformer { public static TraceAction toAction(TraceType traceType, InvokeData invoke, CallType callType, byte[] creationInput, String creationMethod, DataWord codeAddress) { String from; if (callType == CallType.DELEGATECALL) { from = new RskAddress(invoke.getOwnerAddress().getLast20Bytes()).toJsonString(); } e... | @Test public void getActionFromInvokeData() { DataWord address = DataWord.valueOf(1); DataWord origin = DataWord.valueOf(2); DataWord caller = DataWord.valueOf(3); long gas = 1000000; DataWord callValue = DataWord.valueOf(100000); byte[] data = new byte[]{0x01, 0x02, 0x03, 0x04}; ProgramInvoke invoke = new ProgramInvok... |
Web3Impl implements Web3 { @Override public String eth_coinbase() { String s = null; try { s = minerServer.getCoinbaseAddress().toJsonString(); return s; } finally { if (logger.isDebugEnabled()) { logger.debug("eth_coinbase(): {}", s); } } } protected Web3Impl(
Ethereum eth,
Blockchain blockcha... | @Test public void eth_coinbase() { String originalCoinbase = "1dcc4de8dec75d7aab85b513f0a142fd40d49347"; MinerServer minerServerMock = mock(MinerServer.class); when(minerServerMock.getCoinbaseAddress()).thenReturn(new RskAddress(originalCoinbase)); Ethereum ethMock = Web3Mocks.getMockEthereum(); Blockchain blockchain =... |
TraceModuleImpl implements TraceModule { @Override public JsonNode traceTransaction(String transactionHash) throws Exception { logger.trace("trace_transaction({})", transactionHash); byte[] hash = stringHexToByteArray(transactionHash); TransactionInfo txInfo = this.receiptStore.getInMainChain(hash, this.blockStore); if... | @Test public void retrieveUnknownTransactionAsNull() throws Exception { ReceiptStore receiptStore = new ReceiptStoreImpl(new HashMapDB()); World world = new World(receiptStore); TraceModuleImpl traceModule = new TraceModuleImpl(world.getBlockChain(), world.getBlockStore(), receiptStore, world.getBlockExecutor()); JsonN... |
TraceModuleImpl implements TraceModule { @Override public JsonNode traceBlock(String blockArgument) throws Exception { logger.trace("trace_block({})", blockArgument); Block block = this.getByJsonArgument(blockArgument); if (block == null) { logger.trace("No block for {}", blockArgument); return null; } Block parent = t... | @Test public void retrieveUnknownBlockAsNull() throws Exception { ReceiptStore receiptStore = new ReceiptStoreImpl(new HashMapDB()); World world = new World(receiptStore); TraceModuleImpl traceModule = new TraceModuleImpl(world.getBlockChain(), world.getBlockStore(), receiptStore, world.getBlockExecutor()); JsonNode re... |
RskJsonRpcHandler extends SimpleChannelInboundHandler<ByteBufHolder> implements RskJsonRpcRequestVisitor { @Override public JsonRpcResultOrError visit(EthUnsubscribeRequest request, ChannelHandlerContext ctx) { boolean unsubscribed = emitter.unsubscribe(request.getParams().getSubscriptionId()); return new JsonRpcBoolea... | @Test public void visitUnsubscribe() { EthUnsubscribeRequest unsubscribe = new EthUnsubscribeRequest( JsonRpcVersion.V2_0, RskJsonRpcMethod.ETH_UNSUBSCRIBE, 35, new EthUnsubscribeParams(SAMPLE_SUBSCRIPTION_ID) ); when(emitter.unsubscribe(SAMPLE_SUBSCRIPTION_ID)) .thenReturn(true); assertThat( handler.visit(unsubscribe,... |
Web3RskImpl extends Web3Impl { public void ext_dumpState() { Block bestBlcock = blockStore.getBestBlock(); logger.info("Dumping state for block hash {}, block number {}", bestBlcock.getHash(), bestBlcock.getNumber()); networkStateExporter.exportStatus(System.getProperty("user.dir") + "/" + "rskdump.json"); } Web3RskImp... | @Test public void web3_ext_dumpState() { Ethereum rsk = mock(Ethereum.class); Blockchain blockchain = mock(Blockchain.class); MiningMainchainView mainchainView = mock(MiningMainchainView.class); NetworkStateExporter networkStateExporter = mock(NetworkStateExporter.class); Mockito.when(networkStateExporter.exportStatus(... |
Web3InformationRetriever { public Optional<Block> getBlock(String identifier) { if (PENDING.equals(identifier)) { throw unimplemented("This method doesn't support 'pending' as a parameter"); } Block block; if (LATEST.equals(identifier)) { block = blockchain.getBestBlock(); } else if (EARLIEST.equals(identifier)) { bloc... | @Test public void getBlock_pending() { RskJsonRpcRequestException e = TestUtils .assertThrows(RskJsonRpcRequestException.class, () -> target.getBlock("pending")); assertEquals(UNIMPLEMENTED_ERROR_CODE, (int) e.getCode()); }
@Test public void getBlock_invalidIdentifier() { RskJsonRpcRequestException e = TestUtils .asser... |
Web3Impl implements Web3 { @Override public String personal_newAccount(String passphrase) { return personalModule.newAccount(passphrase); } protected Web3Impl(
Ethereum eth,
Blockchain blockchain,
BlockStore blockStore,
ReceiptStore receiptStore,
RskSystemPro... | @Test public void createNewAccount() { Web3Impl web3 = createWeb3(); String addr = web3.personal_newAccount("passphrase1"); Account account = null; try { account = wallet.getAccount(new RskAddress(addr), "passphrase1"); } catch (Exception e) { e.printStackTrace(); return; } assertNotNull(account); org.junit.Assert.asse... |
Web3InformationRetriever { public List<Transaction> getTransactions(String identifier) { if (PENDING.equals(identifier)) { return transactionPool.getPendingTransactions(); } Optional<Block> block = getBlock(identifier); return block.map(Block::getTransactionsList) .orElseThrow(() -> blockNotFound(String.format("Block %... | @Test public void getTransactions_pending() { List<Transaction> txs = new LinkedList<>(); txs.add(mock(Transaction.class)); txs.add(mock(Transaction.class)); when(txPool.getPendingTransactions()).thenReturn(txs); List<Transaction> result = target.getTransactions("pending"); assertEquals(txs, result); }
@Test public voi... |
Web3InformationRetriever { public AccountInformationProvider getInformationProvider(String identifier) { if (PENDING.equals(identifier)) { return transactionPool.getPendingState(); } Optional<Block> optBlock = getBlock(identifier); if (!optBlock.isPresent()) { throw blockNotFound(String.format("Block %s not found", ide... | @Test public void getState_pending() { PendingState aip = mock(PendingState.class); when(txPool.getPendingState()).thenReturn(aip); AccountInformationProvider result = target.getInformationProvider("pending"); assertEquals(aip, result); }
@Test public void getState_earliest() { Block block = mock(Block.class); BlockHea... |
Web3Impl implements Web3 { @Override public String personal_importRawKey(String key, String passphrase) { return personalModule.importRawKey(key, passphrase); } protected Web3Impl(
Ethereum eth,
Blockchain blockchain,
BlockStore blockStore,
ReceiptStore receiptStore,
... | @Test public void importAccountUsingRawKey() { Web3Impl web3 = createWeb3(); ECKey eckey = new ECKey(); byte[] privKeyBytes = eckey.getPrivKeyBytes(); ECKey privKey = ECKey.fromPrivate(privKeyBytes); RskAddress addr = new RskAddress(privKey.getAddress()); Account account = wallet.getAccount(addr); org.junit.Assert.asse... |
JsonRpcMethodFilter implements RequestInterceptor { @Override public void interceptRequest(JsonNode node) throws IOException { if (node.hasNonNull(JsonRpcBasicServer.METHOD)) { checkMethod(node.get(JsonRpcBasicServer.METHOD).asText()); } } JsonRpcMethodFilter(List<ModuleDescription> modules); @Override void interceptRe... | @Test public void checkModuleNames() throws Throwable { RequestInterceptor jsonRpcMethodFilter = new JsonRpcMethodFilter(getModules()); jsonRpcMethodFilter.interceptRequest(getMethodInvocation("evm_snapshot")); jsonRpcMethodFilter.interceptRequest(getMethodInvocation("evm_revert")); try { jsonRpcMethodFilter.interceptR... |
OriginValidator { public boolean isValidReferer(String referer) { if (this.allowAllOrigins) { return true; } URL refererUrl = null; try { refererUrl = new URL(referer); } catch (MalformedURLException e) { return false; } String refererProtocol = refererUrl.getProtocol(); if (refererProtocol == null) { return false; } S... | @Test public void invalidRefererWithDifferentProtocol() throws URISyntaxException { OriginValidator validator = new OriginValidator("http: Assert.assertFalse(validator.isValidReferer("https: }
@Test public void invalidRefererWithDifferentHost() throws URISyntaxException { OriginValidator validator = new OriginValidator... |
ModuleDescription { public boolean methodIsInModule(String methodName) { if (methodName == null) { return false; } if (!methodName.startsWith(this.name)) { return false; } if (methodName.length() == this.name.length()) { return false; } if (methodName.charAt(this.name.length()) != '_') { return false; } return true; } ... | @Test public void methodIsInModule() { ModuleDescription description = new ModuleDescription("evm", "1.0", true, null, null); Assert.assertTrue(description.methodIsInModule("evm_snapshot")); Assert.assertTrue(description.methodIsInModule("evm_do")); Assert.assertFalse(description.methodIsInModule("eth_getBlock")); Asse... |
ModuleDescription { public boolean methodIsEnable(String methodName) { if (!this.isEnabled()) { return false; } if (!this.methodIsInModule(methodName)) { return false; } if (this.disabledMethods.contains(methodName)) { return false; } if (this.enabledMethods.isEmpty() && this.disabledMethods.isEmpty()) { return true; }... | @Test public void methodIsEnabledWhenEmptyNameList() { ModuleDescription description = new ModuleDescription("evm", "1.0", true, null, null); Assert.assertTrue(description.methodIsEnable("evm_snapshot")); Assert.assertTrue(description.methodIsEnable("evm_do")); Assert.assertFalse(description.methodIsEnable("eth_getBloc... |
Web3Impl implements Web3 { @Override public String[] personal_listAccounts() { return personalModule.listAccounts(); } protected Web3Impl(
Ethereum eth,
Blockchain blockchain,
BlockStore blockStore,
ReceiptStore receiptStore,
RskSystemProperties config,
... | @Test public void eth_sendTransaction() { BigInteger nonce = BigInteger.ONE; ReceiptStore receiptStore = new ReceiptStoreImpl(new HashMapDB()); World world = new World(receiptStore); BlockChainImpl blockChain = world.getBlockChain(); BlockStore blockStore = world.getBlockStore(); TransactionExecutorFactory transactionE... |
EncryptedData { public EncryptedData(byte[] initialisationVector, byte[] encryptedBytes) { this.initialisationVector = Arrays.copyOf(initialisationVector, initialisationVector.length); this.encryptedBytes = Arrays.copyOf(encryptedBytes, encryptedBytes.length); } EncryptedData(byte[] initialisationVector, byte[] encrypt... | @Test public void testEncryptedData() { EncryptedData ed = new EncryptedData(new byte[]{1,2,3}, new byte[]{4,5,6}); EncryptedData ed2 = new EncryptedData(new byte[]{1,2,3}, new byte[]{4,5,6}); EncryptedData ed3 = new EncryptedData(new byte[]{1,2,3}, new byte[]{4,5,7}); Assert.assertEquals(ed.toString(), ed2.toString())... |
MinerManager { public void mineBlock(MinerClient minerClient, MinerServer minerServer) { minerServer.buildBlockToMine(false); minerClient.mineBlock(); } void mineBlock(MinerClient minerClient, MinerServer minerServer); } | @Test public void refreshWorkRunOnce() { Assert.assertEquals(0, blockchain.getBestBlock().getNumber()); MinerServerImpl minerServer = getMinerServer(); MinerClientImpl minerClient = getMinerClient(minerServer); MinerClientImpl.RefreshWork refreshWork = minerClient.createRefreshWork(); Assert.assertNotNull(refreshWork);... |
MinerUtils { public List<org.ethereum.core.Transaction> getAllTransactions(TransactionPool transactionPool) { List<Transaction> txs = transactionPool.getPendingTransactions(); return PendingState.sortByPriceTakingIntoAccountSenderAndNonce(txs); } static co.rsk.bitcoinj.core.BtcTransaction getBitcoinMergedMiningCoinbas... | @Test public void getAllTransactionsTest() { TransactionPool transactionPool = Mockito.mock(TransactionPool.class); Transaction tx1 = Mockito.mock(Transaction.class); Transaction tx2 = Mockito.mock(Transaction.class); byte[] s1 = new byte[32]; byte[] s2 = new byte[32]; s1[0] = 0; s2[0] = 1; byte[] addressBytes = ByteUt... |
MinerUtils { public List<org.ethereum.core.Transaction> filterTransactions(List<Transaction> txsToRemove, List<Transaction> txs, Map<RskAddress, BigInteger> accountNonces, RepositorySnapshot originalRepo, Coin minGasPrice) { List<org.ethereum.core.Transaction> txsResult = new ArrayList<>(); for (org.ethereum.core.Trans... | @Test public void validTransactionRepositoryNonceTest() { Transaction tx = Tx.create(config, 0, 50000, 5, 0, 0, 0); List<Transaction> txs = new LinkedList<>(); txs.add(tx); Map<RskAddress, BigInteger> accountNounces = new HashMap(); Repository repository = Mockito.mock(Repository.class); Mockito.when(repository.getNonc... |
BlockToMineBuilder { public BlockResult build(List<BlockHeader> mainchainHeaders, byte[] extraData) { BlockHeader newBlockParentHeader = mainchainHeaders.get(0); List<BlockHeader> uncles = FamilyUtils.getUnclesHeaders( blockStore, newBlockParentHeader.getNumber() + 1, newBlockParentHeader.getHash(), miningConfig.getUnc... | @Test public void BuildBlockHasEmptyUnclesWhenCreateAnInvalidBlock() { BlockHeader parent = buildBlockHeaderWithSibling(); BlockResult expectedResult = mock(BlockResult.class); ArgumentCaptor<Block> blockCaptor = ArgumentCaptor.forClass(Block.class); when(validationRules.isValid(any())).thenReturn(false); when(blockExe... |
AutoMinerClient implements MinerClient { @Override public boolean isMining() { return this.isMining; } AutoMinerClient(MinerServer minerServer); @Override void start(); @Override boolean isMining(); @Override boolean mineBlock(); @Override void stop(); } | @Test public void byDefaultIsDisabled() { assertThat(autoMinerClient.isMining(), is(false)); } |
GasLimitCalculator { public BigInteger calculateBlockGasLimit(BigInteger parentGasLimit, BigInteger parentGasUsed, BigInteger minGasLimit, BigInteger targetGasLimit, boolean forceTarget) { BigInteger newGasLimit = parentGasLimit; BigInteger deltaMax = parentGasLimit .divide(BigInteger.valueOf(constants.getGasLimitBound... | @Test public void NextBlockGasLimitIsDecreasedByAFactor() { GasLimitCalculator calc = new GasLimitCalculator(config.getNetworkConstants()); BigInteger minGasLimit = BigInteger.valueOf(constants.getMinGasLimit()); BigInteger parentGasLimit = minGasLimit.add(BigInteger.valueOf(21000)); BigInteger targetGasLimit = BigInte... |
LogFilter extends Filter { @Override public void newBlockReceived(Block b) { if (this.fromLatestBlock) { this.clearEvents(); onBlock(b); } else if (this.toLatestBlock) { onBlock(b); } } LogFilter(AddressesTopicsFilter addressesTopicsFilter, Blockchain blockchain, boolean fromLatestBlock, boolean toLatestBlock); @Overri... | @Test public void noEventsAfterEmptyBlock() { LogFilter filter = new LogFilter(null, null, false, false); Block block = new BlockGenerator().getBlock(1); filter.newBlockReceived(block); Object[] result = filter.getEvents(); Assert.assertNotNull(result); Assert.assertEquals(0, result.length); }
@Test public void eventAf... |
CallArgumentsToByteArray { public byte[] getValue() { byte[] value = new byte[] { 0 }; if (args.value != null && args.value.length() != 0) { value = stringHexToByteArray(args.value); } return value; } CallArgumentsToByteArray(Web3.CallArguments args); byte[] getGasPrice(); byte[] getGasLimit(); byte[] getToAddress(); b... | @Test public void getValueWhenValueIsNull() throws Exception { Web3.CallArguments args = new Web3.CallArguments(); CallArgumentsToByteArray byteArrayArgs = new CallArgumentsToByteArray(args); Assert.assertArrayEquals(new byte[] {0}, byteArrayArgs.getValue()); }
@Test public void getValueWhenValueIsEmpty() throws Except... |
MinerClock { public long calculateTimestampForChild(BlockHeader parentHeader) { long previousTimestamp = parentHeader.getTimestamp(); if (isFixedClock) { return previousTimestamp + timeAdjustment; } long ret = clock.instant().plusSeconds(timeAdjustment).getEpochSecond(); return Long.max(ret, previousTimestamp + 1); } M... | @Test public void timestampForChildIsParentTimestampIfRegtest() { MinerClock minerClock = new MinerClock(true, clock); BlockHeader parent = mockBlockHeaderWithTimestamp(54L); assertEquals( 54L, minerClock.calculateTimestampForChild(parent) ); }
@Test public void timestampForChildIsClockTimeIfNotRegtest() { MinerClock m... |
MinimumGasPriceCalculator { public Coin calculate(Coin previousMGP) { BlockGasPriceRange priceRange = new BlockGasPriceRange(previousMGP); if (priceRange.inRange(targetMGP)) { return targetMGP; } if (previousMGP.compareTo(targetMGP) < 0) { return priceRange.getUpperLimit(); } return priceRange.getLowerLimit(); } Minimu... | @Test public void increaseMgp() { Coin target = Coin.valueOf(2000L); Coin prev = Coin.valueOf(1000L); MinimumGasPriceCalculator mgpCalculator = new MinimumGasPriceCalculator(target); Coin mgp = mgpCalculator.calculate(prev); Assert.assertEquals(Coin.valueOf(1010), mgp); }
@Test public void decreaseMGP() { Coin prev = C... |
HashRateCalculator { public abstract BigInteger calculateNodeHashRate(Duration duration); HashRateCalculator(BlockStore blockStore, RskCustomCache<Keccak256, BlockHeaderElement> headerCache); void start(); void stop(); abstract BigInteger calculateNodeHashRate(Duration duration); BigInteger calculateNetHashRate(Duratio... | @Test public void calculateNodeHashRate() { long ts = System.currentTimeMillis() / 1000L; Mockito.when(blockHeader.getTimestamp()).thenReturn(ts); Mockito.when(blockHeader.getCoinbase()) .thenReturn(NOT_MY_COINBASE) .thenReturn(FAKE_COINBASE) .thenReturn(FAKE_COINBASE) .thenReturn(NOT_MY_COINBASE); Mockito.when(block.g... |
HashRateCalculator { public BigInteger calculateNetHashRate(Duration period) { return calculateHashRate(b -> true, period); } HashRateCalculator(BlockStore blockStore, RskCustomCache<Keccak256, BlockHeaderElement> headerCache); void start(); void stop(); abstract BigInteger calculateNodeHashRate(Duration duration); Big... | @Test public void calculateNetHashRate() { long ts = System.currentTimeMillis() / 1000L; Mockito.when(blockHeader.getTimestamp()).thenReturn(ts); Mockito.when(blockHeader.getCoinbase()) .thenReturn(NOT_MY_COINBASE) .thenReturn(FAKE_COINBASE) .thenReturn(FAKE_COINBASE) .thenReturn(NOT_MY_COINBASE); Mockito.when(block.ge... |
ListArrayUtil { public static List<Byte> asByteList(byte[] primitiveByteArray) { Byte[] arrayObj = convertTo(primitiveByteArray); return Arrays.asList(arrayObj); } private ListArrayUtil(); static List<Byte> asByteList(byte[] primitiveByteArray); static boolean isEmpty(@Nullable byte[] array); static int getLength(@Nul... | @Test public void testAsByteList() { byte[] array = new byte[]{'a','b','c','d'}; List<Byte> result = ListArrayUtil.asByteList(array); for(int i = 0; i < array.length; i++) { Assert.assertEquals(array[i], result.get(i).byteValue()); } } |
ListArrayUtil { public static boolean isEmpty(@Nullable byte[] array) { return array == null || array.length == 0; } private ListArrayUtil(); static List<Byte> asByteList(byte[] primitiveByteArray); static boolean isEmpty(@Nullable byte[] array); static int getLength(@Nullable byte[] array); static byte[] nullToEmpty(... | @Test public void testNullIsEmpty() { Assert.assertTrue(ListArrayUtil.isEmpty(null)); }
@Test public void testEmptyIsEmpty() { Assert.assertTrue(ListArrayUtil.isEmpty(new byte[]{})); }
@Test public void testNotEmptyIsEmpty() { Assert.assertFalse(ListArrayUtil.isEmpty(new byte[]{'a'})); } |
ListArrayUtil { public static byte[] nullToEmpty(@Nullable byte[] array) { if (array == null) { return new byte[0]; } return array; } private ListArrayUtil(); static List<Byte> asByteList(byte[] primitiveByteArray); static boolean isEmpty(@Nullable byte[] array); static int getLength(@Nullable byte[] array); static by... | @Test public void testNullToEmpty() { Assert.assertNotNull(ListArrayUtil.nullToEmpty(null)); }
@Test public void testNonNullToEmpty() { byte[] array = new byte[1]; Assert.assertSame(array, ListArrayUtil.nullToEmpty(array)); } |
ListArrayUtil { public static int getLength(@Nullable byte[] array) { if (array == null) { return 0; } return array.length; } private ListArrayUtil(); static List<Byte> asByteList(byte[] primitiveByteArray); static boolean isEmpty(@Nullable byte[] array); static int getLength(@Nullable byte[] array); static byte[] nul... | @Test public void testNullGetLength() { Assert.assertEquals(0, ListArrayUtil.getLength(null)); }
@Test public void testNonNullGetLength() { byte[] array = new byte[1]; Assert.assertEquals(1, ListArrayUtil.getLength(array)); } |
ListArrayUtil { public static int lastIndexOfSubList(byte[] source, byte[] target) { if (source == null || target == null) { return -1; } if (target.length == 0) { return source.length; } if (source.length < target.length) { return -1; } final int max = source.length - target.length; for (int i = max; i >= 0; i--) { bo... | @Test public void testLastIndexOfSublistEmptyArrays() { byte[] source = new byte[] {}; byte[] target = new byte[] {}; int res = ListArrayUtil.lastIndexOfSubList(source, target); Assert.assertEquals( 0, res); }
@Test public void testLastIndexOfSublistSearchEmpty() { byte[] source = new byte[] { 1, 2, 3, 4, 5 }; byte[] t... |
Topic { @Override public boolean equals(Object other) { if (this == other) { return true; } if (other == null || this.getClass() != other.getClass()) { return false; } Topic otherTopic = (Topic) other; return Arrays.equals(bytes, otherTopic.bytes); } Topic(String topic); Topic(byte[] bytes); byte[] getBytes(); @Overri... | @Test public void testEquals() { Topic topicA = new Topic("0000000000000000000000000000000000000000000000000000000000000001"); Topic topicB = new Topic("0000000000000000000000000000000000000000000000000000000000000001"); Topic topicC = new Topic("0000000000000000000000000000000000000000000000000000000000000002"); Topic... |
IpUtils { public static InetSocketAddress parseAddress(String address) { if(StringUtils.isBlank(address)) { return null; } Matcher matcher = ipv6Pattern.matcher(address); if(matcher.matches()) { return parseMatch(matcher); } matcher = ipv4Pattern.matcher(address); if (matcher.matches() && matcher.groupCount() == 2) { r... | @Test public void parseIPv6() { InetSocketAddress result = IpUtils.parseAddress(IPV6_WITH_PORT); Assert.assertNotNull(result); }
@Test public void parseIPv6NoPort() { InetSocketAddress result = IpUtils.parseAddress(IPV6_NO_PORT); Assert.assertNull(result); }
@Test public void parseIPv6InvalidFormat() { InetSocketAddres... |
PendingTransactionFilter extends Filter { @Override public void newPendingTx(Transaction tx) { add(new PendingTransactionFilterEvent(tx)); } @Override void newPendingTx(Transaction tx); } | @Test public void oneTransactionAndEvents() { PendingTransactionFilter filter = new PendingTransactionFilter(); Account sender = new AccountBuilder().name("sender").build(); Account receiver = new AccountBuilder().name("receiver").build(); Transaction tx = new TransactionBuilder() .sender(sender) .receiver(receiver) .v... |
IpUtils { public static List<InetSocketAddress> parseAddresses(List<String> addresses) { List<InetSocketAddress> result = new ArrayList<>(); for(String a : addresses) { InetSocketAddress res = parseAddress(a); if (res != null) { result.add(res); } } return result; } static InetSocketAddress parseAddress(String address... | @Test public void parseAddresses() { List<String> addresses = new ArrayList<>(); addresses.add(IPV6_WITH_PORT); addresses.add(IPV6_NO_PORT); addresses.add(IPV6_INVALID); addresses.add(IPV4_WITH_PORT); addresses.add(IPV4_NO_PORT); List<InetSocketAddress> result = IpUtils.parseAddresses(addresses); Assert.assertFalse(res... |
FormatUtils { public static String formatNanosecondsToSeconds(long nanoseconds) { return String.format("%.6f", nanoseconds / 1_000_000_000.0); } private FormatUtils(); static String formatNanosecondsToSeconds(long nanoseconds); } | @Test public void formatNanosecondsToSeconds() { Assert.assertEquals("1.234568", FormatUtils.formatNanosecondsToSeconds(1_234_567_890L)); Assert.assertEquals("1234.567890", FormatUtils.formatNanosecondsToSeconds(1_234_567_890_123L)); Assert.assertEquals("1234567.890123", FormatUtils.formatNanosecondsToSeconds(1_234_567... |
FullNodeRunner implements NodeRunner { @Override public void run() { logger.info("Starting RSK"); logger.info( "Running {}, core version: {}-{}", rskSystemProperties.genesisInfo(), rskSystemProperties.projectVersion(), rskSystemProperties.projectVersionModifier() ); buildInfo.printInfo(logger); for (InternalService int... | @Test public void callingRunStartsInternalServices() { runner.run(); for (InternalService internalService : internalServices) { verify(internalService).start(); } } |
FullNodeRunner implements NodeRunner { @Override public void stop() { logger.info("Shutting down RSK node"); for (int i = internalServices.size() - 1; i >= 0; i--) { internalServices.get(i).stop(); } logger.info("RSK node Shut down"); } FullNodeRunner(
List<InternalService> internalServices,
Rsk... | @Test public void callingStopStopsInternalServices() { runner.stop(); for (InternalService internalService : internalServices) { verify(internalService).stop(); } } |
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(blockStor... | @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.a... |
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 calcDi... | @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(... |
ForkDetectionDataRule implements BlockValidationRule, BlockHeaderValidationRule { @Override public boolean isValid(Block block) { return isValid(block.getHeader()); } ForkDetectionDataRule(
ActivationConfig activationConfig,
ConsensusValidationMainchainView mainchainView,
ForkDetecti... | @Test public void validForBlocksBeforeRskip110UsingMethodThatReceivesBlockAsParameter() { long blockNumber = 4242; ForkDetectionDataRule rule = new ForkDetectionDataRule( activationConfig, mock(ConsensusValidationMainchainView.class), mock(ForkDetectionDataCalculator.class), 449 ); BlockHeader header = mock(BlockHeader... |
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.isEmpt... | @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); B... |
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(... | @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... |
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 pa... | @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(bloc... |
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[] ... | @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(); RskAddre... |
BlockTimeStampValidationRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule, BlockValidationRule, BlockHeaderValidationRule { @Override public boolean isValid(Block block) { return isValid(block.getHeader()); } BlockTimeStampValidationRule(int validPeriodLength); @Override boole... | @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.... |
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.pa... | @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("00000... |
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 parent... | @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(... |
RepositoryLocator { public RepositorySnapshot snapshotAt(BlockHeader header) { return mutableTrieSnapshotAt(header) .map(MutableRepository::new) .orElseThrow(() -> trieNotFoundException(header)); } RepositoryLocator(TrieStore store, StateRootHandler stateRootHandler); Optional<RepositorySnapshot> findSnapshotAt(BlockHe... | @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());... |
RepositoryLocator { public Optional<RepositorySnapshot> findSnapshotAt(BlockHeader header) { return mutableTrieSnapshotAt(header).map(MutableRepository::new); } RepositoryLocator(TrieStore store, StateRootHandler stateRootHandler); Optional<RepositorySnapshot> findSnapshotAt(BlockHeader header); RepositorySnapshot snap... | @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(trieSt... |
MutableTrieCache implements MutableTrie { public Iterator<DataWord> getStorageKeys(RskAddress addr) { byte[] accountStoragePrefixKey = trieKeyMapper.getAccountStoragePrefixKey(addr); ByteArrayWrapper accountWrapper = getAccountWrapper(new ByteArrayWrapper(accountStoragePrefixKey)); boolean isDeletedAccount = deleteRecu... | @Test public void testStorageKeysMixOneLevel() { MutableTrieImpl baseMutableTrie = new MutableTrieImpl(null, new Trie()); MutableTrieCache mtCache = new MutableTrieCache(baseMutableTrie); MutableTrieCache otherCache = new MutableTrieCache(mtCache); MutableRepository baseRepository = new MutableRepository(baseMutableTri... |
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 ... | @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(baseMuta... |
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)... | @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"... |
BootstrapDataVerifier { public int verifyEntries(Map<String, BootstrapDataEntry> selectedEntries) { int verifications = 0; if (selectedEntries.isEmpty()) { return 0; } String hashToVerify = selectedEntries.values().iterator().next().getHash(); byte[] dbHash = Hex.decode(hashToVerify); for (Map.Entry<String, BootstrapDa... | @Test public void verifyFileEmpty() { BootstrapDataVerifier bootstrapDataVerifier = new BootstrapDataVerifier(); assertEquals(0, bootstrapDataVerifier.verifyEntries(new HashMap<>())); }
@Test public void verifyFileMany() { BootstrapDataVerifier bootstrapDataVerifier = new BootstrapDataVerifier(); HashMap<String, Bootst... |
BootstrapDataProvider { public void retrieveData() { BootstrapIndexCandidateSelector.HeightCandidate heightCandidate = bootstrapIndexCandidateSelector.getHeightData(getIndices()); Map<String, BootstrapDataEntry> selectedEntries = heightCandidate.getEntries(); verify(heightCandidate); height = heightCandidate.getHeight(... | @Test(expected = BootstrapImportException.class) public void retrieveDataInsufficientsSources() { BootstrapDataVerifier bootstrapDataVerifier = mock(BootstrapDataVerifier.class); when(bootstrapDataVerifier.verifyEntries(any())).thenReturn(1); BootstrapFileHandler bootstrapFileHandler = mock(BootstrapFileHandler.class);... |
BootstrapIndexCandidateSelector { public HeightCandidate getHeightData(List<BootstrapDataIndex> indexes) { Map<Long, Map<String, BootstrapDataEntry>> entriesPerHeight = getEntriesPerHeight(indexes); return getHeightCandidate(entriesPerHeight); } BootstrapIndexCandidateSelector(List<String> publicKeys, int minimumRequir... | @Test(expected= BootstrapImportException.class) public void getMaximumCommonHeightDataEmpty() { List<String> keys = Arrays.asList("key1", "key2"); BootstrapIndexCandidateSelector indexMCH = new BootstrapIndexCandidateSelector(keys, 2); List<BootstrapDataIndex> indexes = new ArrayList<>(); indexMCH.getHeightData(indexes... |
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; } Bootstr... | @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 ... |
BootstrapImporter { public void importData() { bootstrapDataProvider.retrieveData(); updateDatabase(); } BootstrapImporter(
BlockStore blockStore,
TrieStore trieStore,
BlockFactory blockFactory, BootstrapDataProvider bootstrapDataProvider); void importData(); } | @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); Bootstr... |
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 bo... | @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 (MalformedU... |
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()... | @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.getMinN... |
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(); @O... | @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(targe... |
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<I... | @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)); } |
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(); @Overri... | @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); } |
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 = getMaxN... | @Test(expected = IllegalArgumentException.class) public void putBlocks_nullList() { target.putBlocks(20L, null); } |
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> getB... | @Test public void isEmpty_empty() { assertTrue(target.isEmpty()); } |
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> getBlocksByNumb... | @Test public void flush() { target.flush(); verify(indexDB, times(1)).commit(); } |
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 ? contentTypeVa... | @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.CONTEN... |
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()... | @Test public void getCliArgsSmokeTest() { RskTestContext devnetContext = new RskTestContext(new String[] { "--devnet" }); assertThat(devnetContext.getCliArgs(), notNullValue()); assertThat(devnetContext.getCliArgs().getFlags(), contains(NodeCliFlags.NETWORK_DEVNET)); } |
RskContext implements NodeBootstrapper { public TrieStore getTrieStore() { if (trieStore == null) { trieStore = buildAbstractTrieStore(Paths.get(getRskSystemProperties().databaseDir())); } return trieStore; } RskContext(String[] args); private RskContext(CliArgs<NodeCliOptions, NodeCliFlags> cliArgs); BootstrapImporte... | @Test public void shouldBuildSimpleTrieStore() throws IOException { Path testDatabasesDirectory = databaseDir.getRoot().toPath(); doReturn(new GarbageCollectorConfig(false, 1000, 3)).when(testProperties).garbageCollectorConfig(); doReturn(testDatabasesDirectory.toString()).when(testProperties).databaseDir(); TrieStore ... |
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, Key... | @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 Bloc... |
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"); } ... | @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(Un... |
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); } | @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(bl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.