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; } EthSubscriptionNotificationEmitter(
BlockHeaderNotificationEmitter blockHeader,
LogsNotificationEmitter logs); @Override SubscriptionId visit(EthSubscribeNewHeadsParams params, Channel channel); @Override SubscriptionId visit(EthSubscribeLogsParams params, Channel channel); boolean unsubscribe(SubscriptionId subscriptionId); void unsubscribe(Channel channel); } | @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 unsubscribeSuccessfullyFromNewHeads() { SubscriptionId subscriptionId = mock(SubscriptionId.class); when(newHeads.unsubscribe(subscriptionId)).thenReturn(true); boolean unsubscribed = emitter.unsubscribe(subscriptionId); assertThat(unsubscribed, is(true)); verify(newHeads).unsubscribe(subscriptionId); verify(logs).unsubscribe(subscriptionId); }
@Test public void unsubscribeSuccessfullyFromLogs() { SubscriptionId subscriptionId = mock(SubscriptionId.class); when(logs.unsubscribe(subscriptionId)).thenReturn(true); boolean unsubscribed = emitter.unsubscribe(subscriptionId); assertThat(unsubscribed, is(true)); verify(newHeads).unsubscribe(subscriptionId); verify(logs).unsubscribe(subscriptionId); }
@Test public void unsubscribeChannel() { Channel channel = mock(Channel.class); emitter.unsubscribe(channel); verify(newHeads).unsubscribe(channel); verify(logs).unsubscribe(channel); } |
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>>> queuedGrouped = groupTransactions(transactionPool.getQueuedTransactions()); contentProps.put(PENDING, serializeTransactions(pendingGrouped, this::fullSerializer)); contentProps.put(QUEUED, serializeTransactions(queuedGrouped, this::fullSerializer)); JsonNode node = jsonNodeFactory.objectNode().setAll(contentProps); return node; } TxPoolModuleImpl(TransactionPool transactionPool); @Override JsonNode content(); @Override JsonNode inspect(); @Override JsonNode status(); static final String PENDING; static final String QUEUED; } | @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.getPendingTransactions()).thenReturn(Collections.singletonList(tx)); JsonNode node = txPoolModule.content(); checkFieldIsEmpty(node, "queued"); JsonNode pendingNode = checkFieldIsObject(node, "pending"); JsonNode senderNode = checkFieldIsObject(pendingNode, tx.getSender().toString()); JsonNode nonceNode = checkFieldIsArray(senderNode, tx.getNonceAsInteger().toString()); nonceNode.elements().forEachRemaining(item -> assertFullTransaction(tx, item)); }
@Test public void txpool_content_sameNonce() throws Exception { Transaction tx1 = createSampleTransaction(); Transaction tx2 = createSampleTransaction(); Transaction tx3 = createSampleTransaction(); List<Transaction> transactions = Arrays.asList(tx1, tx2, tx3); when(transactionPool.getPendingTransactions()).thenReturn(transactions); JsonNode node = txPoolModule.content(); checkFieldIsEmpty(node, "queued"); JsonNode pendingNode = checkFieldIsObject(node, "pending"); JsonNode senderNode = checkFieldIsObject(pendingNode, tx1.getSender().toString()); JsonNode nonceNode = checkFieldIsArray(senderNode, tx1.getNonceAsInteger().toString()); int i = 0; for (Iterator<JsonNode> iter = nonceNode.elements(); iter.hasNext();){ JsonNode item = iter.next(); assertFullTransaction(transactions.get(i), item); i++; } }
@Test public void txpool_content_sameSender() throws Exception { Transaction tx1 = createSampleTransaction(0, 1, 1, 0); Transaction tx2 = createSampleTransaction(0, 2, 1, 1); Transaction tx3 = createSampleTransaction(0, 3, 1, 2); Transaction tx4 = createSampleTransaction(1, 3, 1, 0); Transaction tx5 = createSampleTransaction(1, 3, 1, 1); List<Transaction> transactions = Arrays.asList(tx1, tx2, tx3, tx4, tx5); List<Transaction> txs = Arrays.asList(tx4, tx5); when(transactionPool.getPendingTransactions()).thenReturn(transactions); when(transactionPool.getQueuedTransactions()).thenReturn(txs); JsonNode node = txPoolModule.content(); JsonNode pendingNode = checkFieldIsObject(node, "pending"); JsonNode queuedNode = checkFieldIsObject(node, "queued"); checkGroupedTransactions(transactions, pendingNode, this::assertFullTransaction); checkGroupedTransactions(txs, queuedNode, this::assertFullTransaction); }
@Test public void txpool_content_manyTxs() throws Exception { Transaction tx1 = createSampleTransaction(0, 1, 1, 0); Transaction tx2 = createSampleTransaction(0, 2, 1, 0); Transaction tx3 = createSampleTransaction(0, 3, 1, 0); Transaction tx4 = createSampleTransaction(1, 3, 1, 0); Transaction tx5 = createSampleTransaction(1, 3, 1, 1); Transaction tx6 = createSampleTransaction(1, 3, 1, 2); Transaction tx7 = createSampleTransaction(2, 3, 1, 0); Transaction tx8 = createSampleTransaction(2, 3, 1, 1); List<Transaction> transactions = Arrays.asList(tx1, tx2, tx3, tx4, tx5); List<Transaction> txs = Arrays.asList(tx7, tx8, tx6); when(transactionPool.getPendingTransactions()).thenReturn(transactions); when(transactionPool.getQueuedTransactions()).thenReturn(txs); JsonNode node = txPoolModule.content(); JsonNode pendingNode = checkFieldIsObject(node, "pending"); JsonNode queuedNode = checkFieldIsObject(node, "queued"); checkGroupedTransactions(transactions, pendingNode, this::assertFullTransaction); checkGroupedTransactions(txs, queuedNode, this::assertFullTransaction); } |
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>>> queuedGrouped = groupTransactions(transactionPool.getQueuedTransactions()); contentProps.put(PENDING, serializeTransactions(pendingGrouped, this::summarySerializer)); contentProps.put(QUEUED, serializeTransactions(queuedGrouped, this::summarySerializer)); JsonNode node = jsonNodeFactory.objectNode().setAll(contentProps); return node; } TxPoolModuleImpl(TransactionPool transactionPool); @Override JsonNode content(); @Override JsonNode inspect(); @Override JsonNode status(); static final String PENDING; static final String QUEUED; } | @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.getPendingTransactions()).thenReturn(Collections.singletonList(tx)); JsonNode node = txPoolModule.inspect(); checkFieldIsEmpty(node, "queued"); JsonNode pendingNode = checkFieldIsObject(node, "pending"); JsonNode senderNode = checkFieldIsObject(pendingNode, tx.getSender().toString()); JsonNode nonceNode = checkFieldIsArray(senderNode, tx.getNonceAsInteger().toString()); nonceNode.elements().forEachRemaining(item -> assertSummaryTransaction(tx, item)); }
@Test public void txpool_inspect_sameNonce() throws Exception { Transaction tx1 = createSampleTransaction(); Transaction tx2 = createSampleTransaction(); Transaction tx3 = createSampleTransaction(); List<Transaction> transactions = Arrays.asList(tx1, tx2, tx3); when(transactionPool.getPendingTransactions()).thenReturn(transactions); JsonNode node = txPoolModule.inspect(); checkFieldIsEmpty(node, "queued"); JsonNode pendingNode = checkFieldIsObject(node, "pending"); JsonNode senderNode = checkFieldIsObject(pendingNode, tx1.getSender().toString()); JsonNode nonceNode = checkFieldIsArray(senderNode, tx1.getNonceAsInteger().toString()); int i = 0; for (Iterator<JsonNode> iter = nonceNode.elements(); iter.hasNext();){ JsonNode item = iter.next(); assertSummaryTransaction(transactions.get(i), item); i++; } }
@Test public void txpool_inspect_sameSender() throws Exception { Transaction tx1 = createSampleTransaction(0, 1, 1, 0); Transaction tx2 = createSampleTransaction(0, 2, 1, 1); Transaction tx3 = createSampleTransaction(0, 3, 1, 2); Transaction tx4 = createSampleTransaction(1, 3, 1, 0); Transaction tx5 = createSampleTransaction(1, 3, 1, 1); List<Transaction> transactions = Arrays.asList(tx1, tx2, tx3, tx4, tx5); List<Transaction> txs = Arrays.asList(tx4, tx5); when(transactionPool.getPendingTransactions()).thenReturn(transactions); when(transactionPool.getQueuedTransactions()).thenReturn(txs); JsonNode node = txPoolModule.inspect(); JsonNode pendingNode = checkFieldIsObject(node, "pending"); JsonNode queuedNode = checkFieldIsObject(node, "queued"); checkGroupedTransactions(transactions, pendingNode, this::assertSummaryTransaction); checkGroupedTransactions(txs, queuedNode, this::assertSummaryTransaction); }
@Test public void txpool_inspect_manyTxs() throws Exception { Transaction tx1 = createSampleTransaction(0, 1, 1, 0); Transaction tx2 = createSampleTransaction(0, 2, 1, 0); Transaction tx3 = createSampleTransaction(0, 3, 1, 0); Transaction tx4 = createSampleTransaction(1, 3, 1, 0); Transaction tx5 = createSampleTransaction(1, 3, 1, 1); Transaction tx6 = createSampleTransaction(1, 3, 1, 2); Transaction tx7 = createSampleTransaction(2, 3, 1, 0); Transaction tx8 = createSampleTransaction(2, 3, 1, 1); List<Transaction> transactions = Arrays.asList(tx1, tx2, tx3, tx4, tx5); List<Transaction> txs = Arrays.asList(tx7, tx8, tx6); when(transactionPool.getPendingTransactions()).thenReturn(transactions); when(transactionPool.getQueuedTransactions()).thenReturn(txs); JsonNode node = txPoolModule.inspect(); JsonNode pendingNode = checkFieldIsObject(node, "pending"); JsonNode queuedNode = checkFieldIsObject(node, "queued"); checkGroupedTransactions(transactions, pendingNode, this::assertSummaryTransaction); checkGroupedTransactions(txs, queuedNode, this::assertSummaryTransaction); } |
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())); JsonNode node = jsonNodeFactory.objectNode().setAll(txProps); return node; } TxPoolModuleImpl(TransactionPool transactionPool); @Override JsonNode content(); @Override JsonNode inspect(); @Override JsonNode status(); static final String PENDING; static final String QUEUED; } | @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()).thenReturn(Collections.singletonList(tx)); JsonNode node = txPoolModule.status(); JsonNode queuedNode = checkFieldIsNumber(node, "queued"); JsonNode pendingNode = checkFieldIsNumber(node, "pending"); Assert.assertEquals(0, queuedNode.asInt()); Assert.assertEquals(1, pendingNode.asInt()); }
@Test public void txpool_status_manyPending() throws Exception { Transaction tx1 = createSampleTransaction(); Transaction tx2 = createSampleTransaction(); Transaction tx3 = createSampleTransaction(); List<Transaction> transactions = Arrays.asList(tx1, tx2, tx3); when(transactionPool.getPendingTransactions()).thenReturn(transactions); JsonNode node = txPoolModule.status(); JsonNode queuedNode = checkFieldIsNumber(node, "queued"); JsonNode pendingNode = checkFieldIsNumber(node, "pending"); Assert.assertEquals(0, queuedNode.asInt()); Assert.assertEquals(transactions.size(), pendingNode.asInt()); }
@Test public void txpool_status_manyTxs() throws Exception { Transaction tx1 = createSampleTransaction(); Transaction tx2 = createSampleTransaction(); Transaction tx3 = createSampleTransaction(); Transaction tx4 = createSampleTransaction(); List<Transaction> transactions = Arrays.asList(tx1, tx2, tx3); List<Transaction> txs = Arrays.asList(tx1, tx4); when(transactionPool.getPendingTransactions()).thenReturn(transactions); when(transactionPool.getQueuedTransactions()).thenReturn(txs); JsonNode node = txPoolModule.status(); JsonNode queuedNode = checkFieldIsNumber(node, "queued"); JsonNode pendingNode = checkFieldIsNumber(node, "pending"); Assert.assertEquals(txs.size(), queuedNode.asInt()); Assert.assertEquals(transactions.size(), pendingNode.asInt()); } |
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 s; } finally { if (logger.isDebugEnabled()) { logger.debug("eth_getUncleByBlockNumberAndIndex({}, {}): {}", blockId, uncleIdx, s); } } } protected Web3Impl(
Ethereum eth,
Blockchain blockchain,
BlockStore blockStore,
ReceiptStore receiptStore,
RskSystemProperties config,
MinerClient minerClient,
MinerServer minerServer,
PersonalModule personalModule,
EthModule ethModule,
EvmModule evmModule,
TxPoolModule txPoolModule,
MnrModule mnrModule,
DebugModule debugModule,
TraceModule traceModule,
RskModule rskModule,
ChannelManager channelManager,
PeerScoringManager peerScoringManager,
PeerServer peerServer,
BlockProcessor nodeBlockProcessor,
HashRateCalculator hashRateCalculator,
ConfigCapabilities configCapabilities,
BuildInfo buildInfo,
BlocksBloomStore blocksBloomStore,
Web3InformationRetriever web3InformationRetriever); @Override void start(); @Override void stop(); @Override String web3_clientVersion(); @Override String web3_sha3(String data); @Override String net_version(); @Override String net_peerCount(); @Override boolean net_listening(); @Override String rsk_protocolVersion(); @Override String eth_protocolVersion(); @Override Object eth_syncing(); @Override String eth_coinbase(); @Override boolean eth_mining(); @Override BigInteger eth_hashrate(); @Override BigInteger eth_netHashrate(); @Override String[] net_peerList(); @Override String eth_gasPrice(); @Override String eth_blockNumber(); @Override String eth_getBalance(String address, String block); @Override String eth_getBalance(String address); @Override String eth_getStorageAt(String address, String storageIdx, String blockId); @Override String eth_getTransactionCount(String address, String blockId); Block getBlockByJSonHash(String blockHash); @Override String eth_getBlockTransactionCountByHash(String blockHash); static Block getBlockByNumberOrStr(String bnOrId, Blockchain blockchain); @Override String eth_getBlockTransactionCountByNumber(String bnOrId); @Override String eth_getUncleCountByBlockHash(String blockHash); @Override String eth_getUncleCountByBlockNumber(String bnOrId); BlockInformationResult getBlockInformationResult(BlockInformation blockInformation); BlockResultDTO getBlockResult(Block b, boolean fullTx); BlockInformationResult[] eth_getBlocksByNumber(String number); @Override BlockResultDTO eth_getBlockByHash(String blockHash, Boolean fullTransactionObjects); @Override BlockResultDTO eth_getBlockByNumber(String bnOrId, Boolean fullTransactionObjects); @Override TransactionResultDTO eth_getTransactionByHash(String transactionHash); @Override TransactionResultDTO eth_getTransactionByBlockHashAndIndex(String blockHash, String index); @Override TransactionResultDTO eth_getTransactionByBlockNumberAndIndex(String bnOrId, String index); @Override TransactionReceiptDTO eth_getTransactionReceipt(String transactionHash); @Override BlockResultDTO eth_getUncleByBlockHashAndIndex(String blockHash, String uncleIdx); @Override BlockResultDTO eth_getUncleByBlockNumberAndIndex(String blockId, String uncleIdx); @Override String[] eth_getCompilers(); @Override Map<String, CompilationResultDTO> eth_compileLLL(String contract); @Override Map<String, CompilationResultDTO> eth_compileSerpent(String contract); @Override Map<String, CompilationResultDTO> eth_compileSolidity(String contract); @Override String eth_newFilter(FilterRequest fr); @Override String eth_newBlockFilter(); @Override String eth_newPendingTransactionFilter(); @Override boolean eth_uninstallFilter(String id); @Override Object[] eth_getFilterChanges(String id); @Override Object[] eth_getFilterLogs(String id); @Override Object[] eth_getLogs(FilterRequest fr); @Override Map<String, String> rpc_modules(); @Override void db_putString(); @Override void db_getString(); @Override boolean eth_submitWork(String nonce, String header, String mince); @Override boolean eth_submitHashrate(String hashrate, String id); @Override void db_putHex(); @Override void db_getHex(); @Override String personal_newAccountWithSeed(String seed); @Override String personal_newAccount(String passphrase); @Override String personal_importRawKey(String key, String passphrase); @Override String personal_dumpRawKey(String address); @Override String[] personal_listAccounts(); @Override String personal_sendTransaction(CallArguments args, String passphrase); @Override boolean personal_unlockAccount(String address, String passphrase, String duration); @Override boolean personal_lockAccount(String address); @Override EthModule getEthModule(); @Override EvmModule getEvmModule(); @Override TxPoolModule getTxPoolModule(); @Override MnrModule getMnrModule(); @Override DebugModule getDebugModule(); @Override TraceModule getTraceModule(); @Override RskModule getRskModule(); @Override void sco_banAddress(String address); @Override void sco_unbanAddress(String address); @Override PeerScoringInformation[] sco_peerList(); @Override String[] sco_bannedAddresses(); public Ethereum eth; } | @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.getTrieStore()).difficulty(10).parent(genesis).build(); blockA.setBitcoinMergedMiningHeader(new byte[]{0x01}); org.junit.Assert.assertEquals(ImportResult.IMPORTED_BEST, world.getBlockChain().tryToConnect(blockA)); Block blockB = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()) .trieStore(world.getTrieStore()).difficulty(10).parent(genesis).build(); blockB.setBitcoinMergedMiningHeader(new byte[]{0x02}); org.junit.Assert.assertEquals(ImportResult.IMPORTED_NOT_BEST, world.getBlockChain().tryToConnect(blockB)); Block blockC = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()) .trieStore(world.getTrieStore()).difficulty(10).parent(genesis).build(); blockC.setBitcoinMergedMiningHeader(new byte[]{0x03}); org.junit.Assert.assertEquals(ImportResult.IMPORTED_NOT_BEST, world.getBlockChain().tryToConnect(blockC)); Block blockD = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()) .trieStore(world.getTrieStore()).difficulty(100).parent(blockA).build(); blockD.setBitcoinMergedMiningHeader(new byte[]{0x04}); org.junit.Assert.assertEquals(ImportResult.IMPORTED_BEST, world.getBlockChain().tryToConnect(blockD)); List<BlockHeader> blockEUncles = Arrays.asList(blockB.getHeader(), blockC.getHeader()); Block blockE = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()) .trieStore(world.getTrieStore()).difficulty(10).parent(blockA).uncles(blockEUncles).build(); blockE.setBitcoinMergedMiningHeader(new byte[]{0x05}); org.junit.Assert.assertEquals(ImportResult.IMPORTED_NOT_BEST, world.getBlockChain().tryToConnect(blockE)); List<BlockHeader> blockFUncles = Arrays.asList(blockE.getHeader()); Block blockF = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()) .trieStore(world.getTrieStore()).difficulty(10).parent(blockD).uncles(blockFUncles).build(); blockF.setBitcoinMergedMiningHeader(new byte[]{0x06}); org.junit.Assert.assertEquals(ImportResult.IMPORTED_BEST, world.getBlockChain().tryToConnect(blockF)); String blockEhash = "0x" + blockE.getHash(); String blockBhash = "0x" + blockB.getHash(); String blockChash = "0x" + blockC.getHash(); BlockResultDTO result = web3.eth_getUncleByBlockNumberAndIndex("0x03", "0x00"); Assert.assertEquals(blockEhash, result.getHash()); Assert.assertEquals(2, result.getUncles().size()); Assert.assertTrue(result.getUncles().contains(blockBhash)); Assert.assertTrue(result.getUncles().contains(blockChash)); Assert.assertEquals(TypeConverter.toQuantityJsonHex(30), result.getCumulativeDifficulty()); }
@Test public void getUncleByBlockNumberAndIndexBlockWithUnclesCorrespondingToAnUnknownBlock() { World world = new World(); Account acc1 = new AccountBuilder(world).name("acc1").balance(Coin.valueOf(10000)).build(); Web3Impl web3 = createWeb3(world); Block genesis = world.getBlockChain().getBestBlock(); Block blockA = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()) .trieStore(world.getTrieStore()).difficulty(10).parent(genesis).build(); blockA.setBitcoinMergedMiningHeader(new byte[]{0x01}); org.junit.Assert.assertEquals(ImportResult.IMPORTED_BEST, world.getBlockChain().tryToConnect(blockA)); Block blockB = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()) .trieStore(world.getTrieStore()).difficulty(10).parent(genesis).build(); blockB.setBitcoinMergedMiningHeader(new byte[]{0x02}); org.junit.Assert.assertEquals(ImportResult.IMPORTED_NOT_BEST, world.getBlockChain().tryToConnect(blockB)); Block blockC = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()) .trieStore(world.getTrieStore()).difficulty(10).parent(genesis).build(); blockC.setBitcoinMergedMiningHeader(new byte[]{0x03}); org.junit.Assert.assertEquals(ImportResult.IMPORTED_NOT_BEST, world.getBlockChain().tryToConnect(blockC)); Block blockD = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()) .trieStore(world.getTrieStore()).difficulty(100).parent(blockA).build(); blockD.setBitcoinMergedMiningHeader(new byte[]{0x04}); org.junit.Assert.assertEquals(ImportResult.IMPORTED_BEST, world.getBlockChain().tryToConnect(blockD)); Transaction tx = new TransactionBuilder() .sender(acc1) .gasLimit(BigInteger.valueOf(100000)) .gasPrice(BigInteger.ONE) .build(); List<Transaction> txs = new ArrayList<>(); txs.add(tx); List<BlockHeader> blockEUncles = Arrays.asList(blockB.getHeader(), blockC.getHeader()); Block blockE = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()) .trieStore(world.getTrieStore()).difficulty(10).parent(blockA).uncles(blockEUncles) .transactions(txs).buildWithoutExecution(); blockE.setBitcoinMergedMiningHeader(new byte[]{0x05}); Assert.assertEquals(1, blockE.getTransactionsList().size()); Assert.assertFalse(Arrays.equals(blockC.getTxTrieRoot(), blockE.getTxTrieRoot())); List<BlockHeader> blockFUncles = Arrays.asList(blockE.getHeader()); Block blockF = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()) .trieStore(world.getTrieStore()).difficulty(10).parent(blockD).uncles(blockFUncles).build(); blockF.setBitcoinMergedMiningHeader(new byte[]{0x06}); org.junit.Assert.assertEquals(ImportResult.IMPORTED_BEST, world.getBlockChain().tryToConnect(blockF)); String blockEhash = "0x" + blockE.getHash(); BlockResultDTO result = web3.eth_getUncleByBlockNumberAndIndex("0x" + blockF.getNumber(), "0x00"); Assert.assertEquals(blockEhash, result.getHash()); Assert.assertEquals(0, result.getUncles().size()); Assert.assertEquals(0, result.getTransactions().size()); Assert.assertEquals("0x" + ByteUtil.toHexString(blockE.getTxTrieRoot()), result.getTransactionsRoot()); } |
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[] getData(); RskAddress getFromAddress(); } | @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,
BlockExecutor blockExecutor); @Override String wireProtocolQueueSize(); @Override JsonNode traceTransaction(String transactionHash, Map<String, String> traceOptions); } | @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() throws IOException { when(messageHandler.getMessageQueueSize()).thenReturn(5L); String result = debugModule.wireProtocolQueueSize(); try { long value = TypeConverter.JSonHexToLong(result); Assert.assertEquals(5L, value); } catch (NumberFormatException e) { Assert.fail("This method is not returning a 0x Long"); } } |
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 {} trace options. For now trace options are being ignored", traceOptions); } byte[] hash = stringHexToByteArray(transactionHash); TransactionInfo txInfo = receiptStore.getInMainChain(hash, blockStore); if (txInfo == null) { logger.trace("No transaction info for {}", transactionHash); return null; } Block block = blockStore.getBlockByHash(txInfo.getBlockHash()); Block parent = blockStore.getBlockByHash(block.getParentHash().getBytes()); Transaction tx = block.getTransactionsList().get(txInfo.getIndex()); txInfo.setTransaction(tx); ProgramTraceProcessor programTraceProcessor = new ProgramTraceProcessor(); blockExecutor.traceBlock(programTraceProcessor, 0, block, parent.getHeader(), false, false); return programTraceProcessor.getProgramTraceAsJsonNode(tx.getHash()); } DebugModuleImpl(
BlockStore blockStore,
ReceiptStore receiptStore,
MessageHandler messageHandler,
BlockExecutor blockExecutor); @Override String wireProtocolQueueSize(); @Override JsonNode traceTransaction(String transactionHash, Map<String, String> traceOptions); } | @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.traceTransaction("0x00", null); Assert.assertNull(result); }
@Test public void debug_traceTransaction_retrieveSimpleContractCreationTrace() throws Exception { DslParser parser = DslParser.fromResource("dsl/contracts01.txt"); ReceiptStore receiptStore = new ReceiptStoreImpl(new HashMapDB()); World world = new World(receiptStore); WorldDslProcessor processor = new WorldDslProcessor(world); processor.processCommands(parser); Transaction transaction = world.getTransactionByName("tx01"); DebugModuleImpl debugModule = new DebugModuleImpl(world.getBlockStore(), receiptStore, messageHandler, world.getBlockExecutor()); JsonNode result = debugModule.traceTransaction(transaction.getHash().toJsonString(), null); Assert.assertNotNull(result); Assert.assertTrue(result.isObject()); ObjectNode oResult = (ObjectNode) result; Assert.assertTrue(oResult.get("error").textValue().isEmpty()); Assert.assertTrue(oResult.get("result").isTextual()); JsonNode structLogs = oResult.get("structLogs"); Assert.assertTrue(structLogs.isArray()); Assert.assertTrue(structLogs.size() > 0); }
@Test public void debug_traceTransaction_retrieveEmptyContractCreationTrace() throws Exception { DslParser parser = DslParser.fromResource("dsl/contracts09.txt"); ReceiptStore receiptStore = new ReceiptStoreImpl(new HashMapDB()); World world = new World(receiptStore); WorldDslProcessor processor = new WorldDslProcessor(world); processor.processCommands(parser); Transaction transaction = world.getTransactionByName("tx01"); DebugModuleImpl debugModule = new DebugModuleImpl(world.getBlockStore(), receiptStore, messageHandler, world.getBlockExecutor()); JsonNode result = debugModule.traceTransaction(transaction.getHash().toJsonString(), null); Assert.assertNotNull(result); Assert.assertTrue(result.isObject()); ObjectNode oResult = (ObjectNode) result; Assert.assertTrue(oResult.get("error").isNull()); Assert.assertTrue(oResult.get("result").isNull()); JsonNode structLogs = oResult.get("structLogs"); Assert.assertNull(structLogs); }
@Test public void debug_traceTransaction_retrieveSimpleContractInvocationTrace() throws Exception { DslParser parser = DslParser.fromResource("dsl/contracts02.txt"); ReceiptStore receiptStore = new ReceiptStoreImpl(new HashMapDB()); World world = new World(receiptStore); WorldDslProcessor processor = new WorldDslProcessor(world); processor.processCommands(parser); Transaction transaction = world.getTransactionByName("tx02"); DebugModuleImpl debugModule = new DebugModuleImpl(world.getBlockStore(), receiptStore, messageHandler, world.getBlockExecutor()); JsonNode result = debugModule.traceTransaction(transaction.getHash().toJsonString(), null); Assert.assertNotNull(result); Assert.assertTrue(result.isObject()); ObjectNode oResult = (ObjectNode) result; Assert.assertTrue(oResult.get("error").textValue().isEmpty()); Assert.assertTrue(oResult.get("result").textValue().isEmpty()); JsonNode structLogs = oResult.get("structLogs"); Assert.assertTrue(structLogs.isArray()); Assert.assertTrue(structLogs.size() > 0); }
@Test public void debug_traceTransaction_retrieveSimpleAccountTransfer() throws Exception { DslParser parser = DslParser.fromResource("dsl/transfers01.txt"); ReceiptStore receiptStore = new ReceiptStoreImpl(new HashMapDB()); World world = new World(receiptStore); WorldDslProcessor processor = new WorldDslProcessor(world); processor.processCommands(parser); Transaction transaction = world.getTransactionByName("tx01"); DebugModuleImpl debugModule = new DebugModuleImpl(world.getBlockStore(), receiptStore, messageHandler, world.getBlockExecutor()); JsonNode result = debugModule.traceTransaction(transaction.getHash().toJsonString(), null); Assert.assertNotNull(result); Assert.assertTrue(result.isObject()); ObjectNode oResult = (ObjectNode) result; Assert.assertTrue(oResult.get("error").isNull()); Assert.assertTrue(oResult.get("result").isNull()); JsonNode structLogs = oResult.get("structLogs"); Assert.assertNull(structLogs); }
@Test public void debug_traceTransaction_retrieveSimpleAccountTransferWithTraceOptions() throws Exception { DslParser parser = DslParser.fromResource("dsl/transfers01.txt"); ReceiptStore receiptStore = new ReceiptStoreImpl(new HashMapDB()); World world = new World(receiptStore); WorldDslProcessor processor = new WorldDslProcessor(world); processor.processCommands(parser); Transaction transaction = world.getTransactionByName("tx01"); DebugModuleImpl debugModule = new DebugModuleImpl(world.getBlockStore(), receiptStore, messageHandler, world.getBlockExecutor()); JsonNode resultWithNoOptions = debugModule.traceTransaction(transaction.getHash().toJsonString(), null); JsonNode resultWithEmptyOptions = debugModule.traceTransaction(transaction.getHash().toJsonString(), Collections.emptyMap()); Assert.assertEquals(resultWithNoOptions, resultWithEmptyOptions); JsonNode resultWithNonEmptyOptions = debugModule.traceTransaction(transaction.getHash().toJsonString(), Collections.singletonMap("disableStorage", "true")); Assert.assertEquals(resultWithNoOptions, resultWithNonEmptyOptions); } |
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_workaround(args, blockResult); } else { res = callConstant(args, blockResult.getBlock()); } if (res.isRevert()) { throw RskJsonRpcRequestException.transactionRevertedExecutionError(); } return s = toJsonHex(res.getHReturn()); } finally { LOGGER.debug("eth_call(): {}", s); } } EthModule(
BridgeConstants bridgeConstants,
byte chainId,
Blockchain blockchain,
TransactionPool transactionPool,
ReversibleTransactionExecutor reversibleTransactionExecutor,
ExecutionBlockRetriever executionBlockRetriever,
RepositoryLocator repositoryLocator,
EthModuleWallet ethModuleWallet,
EthModuleTransaction ethModuleTransaction,
BridgeSupportFactory bridgeSupportFactory); @Override String[] accounts(); Map<String, Object> bridgeState(); String call(Web3.CallArguments args, String bnOrId); String estimateGas(Web3.CallArguments args); @Override String sendTransaction(Web3.CallArguments args); @Override String sendRawTransaction(String rawData); @Override String sign(String addr, String data); String chainId(); String getCode(String address, String blockId); } | @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(blockResult); when(blockResult.getBlock()).thenReturn(block); byte[] hreturn = TypeConverter.stringToByteArray("hello"); ProgramResult executorResult = mock(ProgramResult.class); when(executorResult.getHReturn()) .thenReturn(hreturn); ReversibleTransactionExecutor executor = mock(ReversibleTransactionExecutor.class); when(executor.executeTransaction(eq(blockResult.getBlock()), any(), any(), any(), any(), any(), any(), any())) .thenReturn(executorResult); EthModule eth = new EthModule( null, anyByte(), null, null, executor, retriever, null, null, null, new BridgeSupportFactory( null, null, null)); String result = eth.call(args, "latest"); assertThat(result, is(TypeConverter.toJsonHex(hreturn))); } |
Web3Impl implements Web3 { @Override public String personal_newAccountWithSeed(String seed) { return personalModule.newAccountWithSeed(seed); } protected Web3Impl(
Ethereum eth,
Blockchain blockchain,
BlockStore blockStore,
ReceiptStore receiptStore,
RskSystemProperties config,
MinerClient minerClient,
MinerServer minerServer,
PersonalModule personalModule,
EthModule ethModule,
EvmModule evmModule,
TxPoolModule txPoolModule,
MnrModule mnrModule,
DebugModule debugModule,
TraceModule traceModule,
RskModule rskModule,
ChannelManager channelManager,
PeerScoringManager peerScoringManager,
PeerServer peerServer,
BlockProcessor nodeBlockProcessor,
HashRateCalculator hashRateCalculator,
ConfigCapabilities configCapabilities,
BuildInfo buildInfo,
BlocksBloomStore blocksBloomStore,
Web3InformationRetriever web3InformationRetriever); @Override void start(); @Override void stop(); @Override String web3_clientVersion(); @Override String web3_sha3(String data); @Override String net_version(); @Override String net_peerCount(); @Override boolean net_listening(); @Override String rsk_protocolVersion(); @Override String eth_protocolVersion(); @Override Object eth_syncing(); @Override String eth_coinbase(); @Override boolean eth_mining(); @Override BigInteger eth_hashrate(); @Override BigInteger eth_netHashrate(); @Override String[] net_peerList(); @Override String eth_gasPrice(); @Override String eth_blockNumber(); @Override String eth_getBalance(String address, String block); @Override String eth_getBalance(String address); @Override String eth_getStorageAt(String address, String storageIdx, String blockId); @Override String eth_getTransactionCount(String address, String blockId); Block getBlockByJSonHash(String blockHash); @Override String eth_getBlockTransactionCountByHash(String blockHash); static Block getBlockByNumberOrStr(String bnOrId, Blockchain blockchain); @Override String eth_getBlockTransactionCountByNumber(String bnOrId); @Override String eth_getUncleCountByBlockHash(String blockHash); @Override String eth_getUncleCountByBlockNumber(String bnOrId); BlockInformationResult getBlockInformationResult(BlockInformation blockInformation); BlockResultDTO getBlockResult(Block b, boolean fullTx); BlockInformationResult[] eth_getBlocksByNumber(String number); @Override BlockResultDTO eth_getBlockByHash(String blockHash, Boolean fullTransactionObjects); @Override BlockResultDTO eth_getBlockByNumber(String bnOrId, Boolean fullTransactionObjects); @Override TransactionResultDTO eth_getTransactionByHash(String transactionHash); @Override TransactionResultDTO eth_getTransactionByBlockHashAndIndex(String blockHash, String index); @Override TransactionResultDTO eth_getTransactionByBlockNumberAndIndex(String bnOrId, String index); @Override TransactionReceiptDTO eth_getTransactionReceipt(String transactionHash); @Override BlockResultDTO eth_getUncleByBlockHashAndIndex(String blockHash, String uncleIdx); @Override BlockResultDTO eth_getUncleByBlockNumberAndIndex(String blockId, String uncleIdx); @Override String[] eth_getCompilers(); @Override Map<String, CompilationResultDTO> eth_compileLLL(String contract); @Override Map<String, CompilationResultDTO> eth_compileSerpent(String contract); @Override Map<String, CompilationResultDTO> eth_compileSolidity(String contract); @Override String eth_newFilter(FilterRequest fr); @Override String eth_newBlockFilter(); @Override String eth_newPendingTransactionFilter(); @Override boolean eth_uninstallFilter(String id); @Override Object[] eth_getFilterChanges(String id); @Override Object[] eth_getFilterLogs(String id); @Override Object[] eth_getLogs(FilterRequest fr); @Override Map<String, String> rpc_modules(); @Override void db_putString(); @Override void db_getString(); @Override boolean eth_submitWork(String nonce, String header, String mince); @Override boolean eth_submitHashrate(String hashrate, String id); @Override void db_putHex(); @Override void db_getHex(); @Override String personal_newAccountWithSeed(String seed); @Override String personal_newAccount(String passphrase); @Override String personal_importRawKey(String key, String passphrase); @Override String personal_dumpRawKey(String address); @Override String[] personal_listAccounts(); @Override String personal_sendTransaction(CallArguments args, String passphrase); @Override boolean personal_unlockAccount(String address, String passphrase, String duration); @Override boolean personal_lockAccount(String address); @Override EthModule getEthModule(); @Override EvmModule getEvmModule(); @Override TxPoolModule getTxPoolModule(); @Override MnrModule getMnrModule(); @Override DebugModule getDebugModule(); @Override TraceModule getTraceModule(); @Override RskModule getRskModule(); @Override void sco_banAddress(String address); @Override void sco_unbanAddress(String address); @Override PeerScoringInformation[] sco_peerList(); @Override String[] sco_bannedAddresses(); public Ethereum eth; } | @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(100000)) .gasPrice(BigInteger.ONE) .data("60606040525b33600060006101000a81548173ffffffffffffffffffffffffffffffffffffffff02191690836c010000000000000000000000009081020402179055505b610181806100516000396000f360606040526000357c010000000000000000000000000000000000000000000000000000000090048063ead710c41461003c57610037565b610002565b34610002576100956004808035906020019082018035906020019191908080601f016020809104026020016040519081016040528093929190818152602001838380828437820191505050505050909091905050610103565b60405180806020018281038252838181518152602001915080519060200190808383829060006004602084601f0104600302600f01f150905090810190601f1680156100f55780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6020604051908101604052806000815260200150600060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614151561017357610002565b81905061017b565b5b91905056") .build(); List<Transaction> txs = new ArrayList<>(); txs.add(tx); Block block1 = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()).trieStore(world.getTrieStore()).parent(genesis).transactions(txs).build(); world.getBlockChain().tryToConnect(block1); Web3Impl web3 = createWeb3Mocked(world); web3.personal_newAccountWithSeed("default"); web3.personal_newAccountWithSeed("notDefault"); Web3.CallArguments argsForCall = new Web3.CallArguments(); argsForCall.from = TypeConverter.toJsonHex(acc1.getAddress().getBytes()); argsForCall.to = TypeConverter.toJsonHex(tx.getContractAddress().getBytes()); argsForCall.data = "0xead710c40000000000000000000000000000000000000000000000000000000064617665"; String result = web3.eth_call(argsForCall, "latest"); org.junit.Assert.assertEquals("0x0000000000000000000000000000000000000000000000000000000064617665", result); }
@Test public void eth_sign() { Web3Impl web3 = createWeb3(); String addr1 = web3.personal_newAccountWithSeed("sampleSeed1"); byte[] hash = Keccak256Helper.keccak256("this is the data to hash".getBytes()); String signature = web3.eth_sign(addr1, "0x" + ByteUtil.toHexString(hash)); Assert.assertThat( signature, is("0xc8be87722c6452172a02a62fdea70c8b25cfc9613d28647bf2aeb3c7d1faa1a91b861fccc05bb61e25ff4300502812750706ca8df189a0b8163540b9bccabc9f1b") ); }
@Test public void createNewAccountWithoutDuplicates(){ Web3Impl web3 = createWeb3(); int originalAccountSize = wallet.getAccountAddresses().size(); String testAccountAddress = web3.personal_newAccountWithSeed("testAccount"); assertEquals("The number of accounts was not increased", originalAccountSize + 1, wallet.getAccountAddresses().size()); web3.personal_newAccountWithSeed("testAccount"); assertEquals("The number of accounts was increased", originalAccountSize + 1, wallet.getAccountAddresses().size()); } |
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 = getAccountInformationProvider(blockId); if(accountInformationProvider != null) { byte[] code = accountInformationProvider.getCode(addr); if (code == null) { code = new byte[0]; } s = TypeConverter.toJsonHex(code); } return s; } finally { if (LOGGER.isDebugEnabled()) { LOGGER.debug("eth_getCode({}, {}): {}", address, blockId, s); } } } EthModule(
BridgeConstants bridgeConstants,
byte chainId,
Blockchain blockchain,
TransactionPool transactionPool,
ReversibleTransactionExecutor reversibleTransactionExecutor,
ExecutionBlockRetriever executionBlockRetriever,
RepositoryLocator repositoryLocator,
EthModuleWallet ethModuleWallet,
EthModuleTransaction ethModuleTransaction,
BridgeSupportFactory bridgeSupportFactory); @Override String[] accounts(); Map<String, Object> bridgeState(); String call(Web3.CallArguments args, String bnOrId); String estimateGas(Web3.CallArguments args); @Override String sendTransaction(Web3.CallArguments args); @Override String sendRawTransaction(String rawData); @Override String sign(String addr, String data); String chainId(); String getCode(String address, String blockId); } | @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(mockTransactionPool).getPendingState(); EthModule eth = new EthModule( null, (byte) 0, null, mockTransactionPool, null, null, null, null, null, new BridgeSupportFactory( null, null, null ) ); String addr = eth.getCode(TestUtils.randomAddress().toHexString(), "pending"); Assert.assertThat(Hex.decode(addr.substring("0x".length())), is(expectedCode)); } |
EthModule implements EthModuleWallet, EthModuleTransaction { public String chainId() { return TypeConverter.toJsonHex(new byte[] { chainId }); } EthModule(
BridgeConstants bridgeConstants,
byte chainId,
Blockchain blockchain,
TransactionPool transactionPool,
ReversibleTransactionExecutor reversibleTransactionExecutor,
ExecutionBlockRetriever executionBlockRetriever,
RepositoryLocator repositoryLocator,
EthModuleWallet ethModuleWallet,
EthModuleTransaction ethModuleTransaction,
BridgeSupportFactory bridgeSupportFactory); @Override String[] accounts(); Map<String, Object> bridgeState(); String call(Web3.CallArguments args, String bnOrId); String estimateGas(Web3.CallArguments args); @Override String sendTransaction(Web3.CallArguments args); @Override String sendRawTransaction(String rawData); @Override String sign(String addr, String data); String chainId(); String getCode(String address, String blockId); } | @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.class), mock(BridgeSupportFactory.class) ); assertThat(eth.chainId(), is("0x21")); } |
EthUnsubscribeRequest extends RskJsonRpcRequest { @JsonInclude(JsonInclude.Include.NON_NULL) public EthUnsubscribeParams getParams() { return params; } @JsonCreator EthUnsubscribeRequest(
@JsonProperty("jsonrpc") JsonRpcVersion version,
@JsonProperty("method") RskJsonRpcMethod method,
@JsonProperty("id") int id,
@JsonProperty("params") EthUnsubscribeParams params); @JsonInclude(JsonInclude.Include.NON_NULL) EthUnsubscribeParams getParams(); @Override JsonRpcResultOrError accept(RskJsonRpcRequestVisitor visitor, ChannelHandlerContext ctx); } | @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, instanceOf(EthUnsubscribeRequest.class)); EthUnsubscribeRequest unsubscribeRequest = (EthUnsubscribeRequest) request; assertThat(unsubscribeRequest.getParams().getSubscriptionId(), is(new SubscriptionId("0x0204"))); } |
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 getBlockNumber(); String getBlockHash(); String getTransactionHash(); String getTransactionIndex(); String getAddress(); String getData(); List<String> getTopics(); @JsonInclude(JsonInclude.Include.NON_EMPTY) boolean getRemoved(); @JsonIgnore LogInfo getLogInfo(); } | @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 getLogIndex(); String getBlockNumber(); String getBlockHash(); String getTransactionHash(); String getTransactionIndex(); String getAddress(); String getData(); List<String> getTopics(); @JsonInclude(JsonInclude.Include.NON_EMPTY) boolean getRemoved(); @JsonIgnore LogInfo getLogInfo(); } | @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 getBlockNumber(); String getBlockHash(); String getTransactionHash(); String getTransactionIndex(); String getAddress(); String getData(); List<String> getTopics(); @JsonInclude(JsonInclude.Include.NON_EMPTY) boolean getRemoved(); @JsonIgnore LogInfo getLogInfo(); } | @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); String getLogIndex(); String getBlockNumber(); String getBlockHash(); String getTransactionHash(); String getTransactionIndex(); String getAddress(); String getData(); List<String> getTopics(); @JsonInclude(JsonInclude.Include.NON_EMPTY) boolean getRemoved(); @JsonIgnore LogInfo getLogInfo(); } | @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 r); String getLogIndex(); String getBlockNumber(); String getBlockHash(); String getTransactionHash(); String getTransactionIndex(); String getAddress(); String getData(); List<String> getTopics(); @JsonInclude(JsonInclude.Include.NON_EMPTY) boolean getRemoved(); @JsonIgnore LogInfo getLogInfo(); } | @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 getBlockNumber(); String getBlockHash(); String getTransactionHash(); String getTransactionIndex(); String getAddress(); String getData(); List<String> getTopics(); @JsonInclude(JsonInclude.Include.NON_EMPTY) boolean getRemoved(); @JsonIgnore LogInfo getLogInfo(); } | @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(); String getBlockHash(); String getTransactionHash(); String getTransactionIndex(); String getAddress(); String getData(); List<String> getTopics(); @JsonInclude(JsonInclude.Include.NON_EMPTY) boolean getRemoved(); @JsonIgnore LogInfo getLogInfo(); } | @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,
BlockStore blockStore,
ReceiptStore receiptStore,
RskSystemProperties config,
MinerClient minerClient,
MinerServer minerServer,
PersonalModule personalModule,
EthModule ethModule,
EvmModule evmModule,
TxPoolModule txPoolModule,
MnrModule mnrModule,
DebugModule debugModule,
TraceModule traceModule,
RskModule rskModule,
ChannelManager channelManager,
PeerScoringManager peerScoringManager,
PeerServer peerServer,
BlockProcessor nodeBlockProcessor,
HashRateCalculator hashRateCalculator,
ConfigCapabilities configCapabilities,
BuildInfo buildInfo,
BlocksBloomStore blocksBloomStore,
Web3InformationRetriever web3InformationRetriever); @Override void start(); @Override void stop(); @Override String web3_clientVersion(); @Override String web3_sha3(String data); @Override String net_version(); @Override String net_peerCount(); @Override boolean net_listening(); @Override String rsk_protocolVersion(); @Override String eth_protocolVersion(); @Override Object eth_syncing(); @Override String eth_coinbase(); @Override boolean eth_mining(); @Override BigInteger eth_hashrate(); @Override BigInteger eth_netHashrate(); @Override String[] net_peerList(); @Override String eth_gasPrice(); @Override String eth_blockNumber(); @Override String eth_getBalance(String address, String block); @Override String eth_getBalance(String address); @Override String eth_getStorageAt(String address, String storageIdx, String blockId); @Override String eth_getTransactionCount(String address, String blockId); Block getBlockByJSonHash(String blockHash); @Override String eth_getBlockTransactionCountByHash(String blockHash); static Block getBlockByNumberOrStr(String bnOrId, Blockchain blockchain); @Override String eth_getBlockTransactionCountByNumber(String bnOrId); @Override String eth_getUncleCountByBlockHash(String blockHash); @Override String eth_getUncleCountByBlockNumber(String bnOrId); BlockInformationResult getBlockInformationResult(BlockInformation blockInformation); BlockResultDTO getBlockResult(Block b, boolean fullTx); BlockInformationResult[] eth_getBlocksByNumber(String number); @Override BlockResultDTO eth_getBlockByHash(String blockHash, Boolean fullTransactionObjects); @Override BlockResultDTO eth_getBlockByNumber(String bnOrId, Boolean fullTransactionObjects); @Override TransactionResultDTO eth_getTransactionByHash(String transactionHash); @Override TransactionResultDTO eth_getTransactionByBlockHashAndIndex(String blockHash, String index); @Override TransactionResultDTO eth_getTransactionByBlockNumberAndIndex(String bnOrId, String index); @Override TransactionReceiptDTO eth_getTransactionReceipt(String transactionHash); @Override BlockResultDTO eth_getUncleByBlockHashAndIndex(String blockHash, String uncleIdx); @Override BlockResultDTO eth_getUncleByBlockNumberAndIndex(String blockId, String uncleIdx); @Override String[] eth_getCompilers(); @Override Map<String, CompilationResultDTO> eth_compileLLL(String contract); @Override Map<String, CompilationResultDTO> eth_compileSerpent(String contract); @Override Map<String, CompilationResultDTO> eth_compileSolidity(String contract); @Override String eth_newFilter(FilterRequest fr); @Override String eth_newBlockFilter(); @Override String eth_newPendingTransactionFilter(); @Override boolean eth_uninstallFilter(String id); @Override Object[] eth_getFilterChanges(String id); @Override Object[] eth_getFilterLogs(String id); @Override Object[] eth_getLogs(FilterRequest fr); @Override Map<String, String> rpc_modules(); @Override void db_putString(); @Override void db_getString(); @Override boolean eth_submitWork(String nonce, String header, String mince); @Override boolean eth_submitHashrate(String hashrate, String id); @Override void db_putHex(); @Override void db_getHex(); @Override String personal_newAccountWithSeed(String seed); @Override String personal_newAccount(String passphrase); @Override String personal_importRawKey(String key, String passphrase); @Override String personal_dumpRawKey(String address); @Override String[] personal_listAccounts(); @Override String personal_sendTransaction(CallArguments args, String passphrase); @Override boolean personal_unlockAccount(String address, String passphrase, String duration); @Override boolean personal_lockAccount(String address); @Override EthModule getEthModule(); @Override EvmModule getEvmModule(); @Override TxPoolModule getTxPoolModule(); @Override MnrModule getMnrModule(); @Override DebugModule getDebugModule(); @Override TraceModule getTraceModule(); @Override RskModule getRskModule(); @Override void sco_banAddress(String address); @Override void sco_unbanAddress(String address); @Override PeerScoringInformation[] sco_peerList(); @Override String[] sco_bannedAddresses(); public Ethereum eth; } | @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; assertTrue("Node is listening", web3.net_listening()); } |
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 b, int txIndex, Transaction tx, int logIdx, boolean r); String getLogIndex(); String getBlockNumber(); String getBlockHash(); String getTransactionHash(); String getTransactionIndex(); String getAddress(); String getData(); List<String> getTopics(); @JsonInclude(JsonInclude.Include.NON_EMPTY) boolean getRemoved(); @JsonIgnore LogInfo getLogInfo(); } | @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(toJsonHex(logTopics.get(i).getData()))); } } |
LogsNotificationEmitter { public void subscribe(SubscriptionId subscriptionId, Channel channel, EthSubscribeLogsParams params) { subscriptions.put(subscriptionId, new Subscription(channel, params)); } LogsNotificationEmitter(
Ethereum ethereum,
JsonRpcSerializer jsonRpcSerializer,
ReceiptStore receiptStore,
BlockchainBranchComparator branchComparator); void subscribe(SubscriptionId subscriptionId, Channel channel, EthSubscribeLogsParams params); boolean unsubscribe(SubscriptionId subscriptionId); void unsubscribe(Channel channel); } | @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(serializer.serializeMessage(any())) .thenReturn("serialized"); listener.onBestBlock(testBlock(logInfo()), null); verify(channel).write(new TextWebSocketFrame("serialized")); verify(channel).flush(); }
@Test public void onBestBlockEventTriggersOneMessageToChannelPerLogInfoAndSubscription() throws JsonProcessingException { SubscriptionId subscriptionId1 = mock(SubscriptionId.class); SubscriptionId subscriptionId2 = mock(SubscriptionId.class); Channel channel1 = mock(Channel.class); Channel channel2 = mock(Channel.class); EthSubscribeLogsParams params = mock(EthSubscribeLogsParams.class); emitter.subscribe(subscriptionId1, channel1, params); emitter.subscribe(subscriptionId2, channel2, params); when(serializer.serializeMessage(any())) .thenReturn("serializedLog1") .thenReturn("serializedLog2") .thenReturn("serializedLog1") .thenReturn("serializedLog2"); listener.onBestBlock(testBlock(logInfo(), logInfo()), null); verify(channel1).write(new TextWebSocketFrame("serializedLog1")); verify(channel1).write(new TextWebSocketFrame("serializedLog2")); verify(channel1).flush(); verify(channel2).write(new TextWebSocketFrame("serializedLog1")); verify(channel2).write(new TextWebSocketFrame("serializedLog2")); verify(channel2).flush(); }
@Test public void filterEmittedLog() throws JsonProcessingException { SubscriptionId subscriptionId = mock(SubscriptionId.class); Channel channel = mock(Channel.class); EthSubscribeLogsParams params = mock(EthSubscribeLogsParams.class); RskAddress logSender = TestUtils.randomAddress(); when(params.getAddresses()).thenReturn(new RskAddress[] { logSender }); emitter.subscribe(subscriptionId, channel, params); byte[] log1Data = {0x1}; byte[] log2Data = {0x2}; Block block1 = testBlock(logInfo(logSender, log1Data)); Block block2 = testBlock(logInfo(log2Data)); listener.onBestBlock(block1, null); verifyLogsData(log1Data); BlockFork blockFork = mock(BlockFork.class); when(blockFork.getNewBlocks()).thenReturn(Collections.singletonList(block2)); when(comparator.calculateFork(block1, block2)).thenReturn(blockFork); clearInvocations(channel); listener.onBestBlock(block2, null); verify(channel, never()).write(any(ByteBufHolder.class)); }
@Test public void emitsNewAndRemovedLogs() throws JsonProcessingException { SubscriptionId subscriptionId = mock(SubscriptionId.class); Channel channel = mock(Channel.class); EthSubscribeLogsParams params = mock(EthSubscribeLogsParams.class); emitter.subscribe(subscriptionId, channel, params); byte[] log1Data = {0x1}; byte[] log2Data = {0x2}; Block block1 = testBlock(logInfo(log1Data)); Block block2 = testBlock(logInfo(log2Data)); listener.onBestBlock(block1, null); verifyLogsData(log1Data); verifyLogsRemovedStatus(false); BlockFork blockFork = mock(BlockFork.class); when(blockFork.getOldBlocks()).thenReturn(Collections.singletonList(block1)); when(blockFork.getNewBlocks()).thenReturn(Collections.singletonList(block2)); when(comparator.calculateFork(block1, block2)) .thenReturn(blockFork); listener.onBestBlock(block2, null); verifyLogsData(log1Data, log1Data, log2Data); verifyLogsRemovedStatus(false, true, false); } |
BlockHeaderNotificationEmitter { public void subscribe(SubscriptionId subscriptionId, Channel channel) { subscriptions.put(subscriptionId, channel); } BlockHeaderNotificationEmitter(Ethereum ethereum, JsonRpcSerializer jsonRpcSerializer); void subscribe(SubscriptionId subscriptionId, Channel channel); boolean unsubscribe(SubscriptionId subscriptionId); void unsubscribe(Channel channel); } | @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.onBlock(TEST_BLOCK, null); verify(channel).writeAndFlush(new TextWebSocketFrame("serialized")); } |
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(TraceAddress parent, int index); @JsonValue int[] toAddress(); } | @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 }, address.toAddress()); }
@Test public void getGrandChildAddress() { TraceAddress grandparent = new TraceAddress(); TraceAddress parent = new TraceAddress(grandparent, 1); TraceAddress address = new TraceAddress(parent, 2); Assert.assertArrayEquals(new int[] { 1, 2 }, address.toAddress()); } |
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(); } else { from = new RskAddress(invoke.getCallerAddress().getLast20Bytes()).toJsonString(); } String to = null; String gas = null; DataWord callValue = invoke.getCallValue(); String input = null; String value = null; String address = null; String refundAddress = null; String balance = null; String init = null; if (traceType == TraceType.CREATE) { init = TypeConverter.toUnformattedJsonHex(creationInput); value = TypeConverter.toQuantityJsonHex(callValue.getData()); gas = TypeConverter.toQuantityJsonHex(invoke.getGas()); } if (traceType == TraceType.CALL) { input = TypeConverter.toUnformattedJsonHex(invoke.getDataCopy(DataWord.ZERO, invoke.getDataSize()));; value = TypeConverter.toQuantityJsonHex(callValue.getData()); if (callType == CallType.DELEGATECALL) { if (codeAddress != null) { to = new RskAddress(codeAddress.getLast20Bytes()).toJsonString(); } } else { to = new RskAddress(invoke.getOwnerAddress().getLast20Bytes()).toJsonString(); } gas = TypeConverter.toQuantityJsonHex(invoke.getGas()); } if (traceType == TraceType.SUICIDE) { address = from; from = null; balance = TypeConverter.toQuantityJsonHex(callValue.getData()); refundAddress = new RskAddress(invoke.getOwnerAddress().getLast20Bytes()).toJsonString(); } return new TraceAction( callType, from, to, gas, input, init, creationMethod, value, address, refundAddress, balance ); } private TraceTransformer(); static List<TransactionTrace> toTraces(SummarizedProgramTrace trace, TransactionInfo txInfo, long blockNumber); static TransactionTrace toTrace(TraceType traceType, InvokeData invoke, ProgramResult programResult, TransactionInfo txInfo, long blockNumber, TraceAddress traceAddress, CallType callType, CreationData creationData, String creationMethod, String err, int nsubtraces, DataWord codeAddress); static TraceResult toResult(ProgramResult programResult, byte[] createdCode, RskAddress createdAddress); static TraceAction toAction(TraceType traceType, InvokeData invoke, CallType callType, byte[] creationInput, String creationMethod, DataWord codeAddress); } | @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 ProgramInvokeImpl( address, origin, caller, null, null, gas, callValue, data, null, null, null, null, null, null, null, null, 0, null, false, false); TraceAction action = TraceTransformer.toAction(TraceType.CALL, invoke, CallType.CALL, null, null, null); Assert.assertNotNull(action); Assert.assertEquals("call", action.getCallType()); Assert.assertEquals("0x0000000000000000000000000000000000000001", action.getTo()); Assert.assertEquals("0x0000000000000000000000000000000000000003", action.getFrom()); Assert.assertEquals("0x01020304", action.getInput()); Assert.assertEquals("0xf4240", action.getGas()); Assert.assertEquals("0x186a0", action.getValue()); }
@Test public void getActionFromInvokeDataWithCreationData() { 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 ProgramInvokeImpl( address, origin, caller, null, null, gas, callValue, null, null, null, null, null, null, null, null, null, 0, null, false, false); TraceAction action = TraceTransformer.toAction(TraceType.CREATE, invoke, CallType.NONE, data, null, null); Assert.assertNotNull(action); Assert.assertNull(action.getCallType()); Assert.assertNull(action.getTo()); Assert.assertEquals("0x0000000000000000000000000000000000000003", action.getFrom()); Assert.assertEquals("0x01020304", action.getInit()); Assert.assertNull(action.getCreationMethod()); Assert.assertEquals("0xf4240", action.getGas()); Assert.assertEquals("0x186a0", action.getValue()); }
@Test public void getActionFromInvokeDataWithCreationDataUsingCreationMethod() { 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 ProgramInvokeImpl( address, origin, caller, null, null, gas, callValue, null, null, null, null, null, null, null, null, null, 0, null, false, false); TraceAction action = TraceTransformer.toAction(TraceType.CREATE, invoke, CallType.NONE, data, "create2", null); Assert.assertNotNull(action); Assert.assertNull(action.getCallType()); Assert.assertNull(action.getTo()); Assert.assertEquals("0x0000000000000000000000000000000000000003", action.getFrom()); Assert.assertEquals("0x01020304", action.getInit()); Assert.assertEquals("create2", action.getCreationMethod()); Assert.assertEquals("0xf4240", action.getGas()); Assert.assertEquals("0x186a0", action.getValue()); } |
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 blockchain,
BlockStore blockStore,
ReceiptStore receiptStore,
RskSystemProperties config,
MinerClient minerClient,
MinerServer minerServer,
PersonalModule personalModule,
EthModule ethModule,
EvmModule evmModule,
TxPoolModule txPoolModule,
MnrModule mnrModule,
DebugModule debugModule,
TraceModule traceModule,
RskModule rskModule,
ChannelManager channelManager,
PeerScoringManager peerScoringManager,
PeerServer peerServer,
BlockProcessor nodeBlockProcessor,
HashRateCalculator hashRateCalculator,
ConfigCapabilities configCapabilities,
BuildInfo buildInfo,
BlocksBloomStore blocksBloomStore,
Web3InformationRetriever web3InformationRetriever); @Override void start(); @Override void stop(); @Override String web3_clientVersion(); @Override String web3_sha3(String data); @Override String net_version(); @Override String net_peerCount(); @Override boolean net_listening(); @Override String rsk_protocolVersion(); @Override String eth_protocolVersion(); @Override Object eth_syncing(); @Override String eth_coinbase(); @Override boolean eth_mining(); @Override BigInteger eth_hashrate(); @Override BigInteger eth_netHashrate(); @Override String[] net_peerList(); @Override String eth_gasPrice(); @Override String eth_blockNumber(); @Override String eth_getBalance(String address, String block); @Override String eth_getBalance(String address); @Override String eth_getStorageAt(String address, String storageIdx, String blockId); @Override String eth_getTransactionCount(String address, String blockId); Block getBlockByJSonHash(String blockHash); @Override String eth_getBlockTransactionCountByHash(String blockHash); static Block getBlockByNumberOrStr(String bnOrId, Blockchain blockchain); @Override String eth_getBlockTransactionCountByNumber(String bnOrId); @Override String eth_getUncleCountByBlockHash(String blockHash); @Override String eth_getUncleCountByBlockNumber(String bnOrId); BlockInformationResult getBlockInformationResult(BlockInformation blockInformation); BlockResultDTO getBlockResult(Block b, boolean fullTx); BlockInformationResult[] eth_getBlocksByNumber(String number); @Override BlockResultDTO eth_getBlockByHash(String blockHash, Boolean fullTransactionObjects); @Override BlockResultDTO eth_getBlockByNumber(String bnOrId, Boolean fullTransactionObjects); @Override TransactionResultDTO eth_getTransactionByHash(String transactionHash); @Override TransactionResultDTO eth_getTransactionByBlockHashAndIndex(String blockHash, String index); @Override TransactionResultDTO eth_getTransactionByBlockNumberAndIndex(String bnOrId, String index); @Override TransactionReceiptDTO eth_getTransactionReceipt(String transactionHash); @Override BlockResultDTO eth_getUncleByBlockHashAndIndex(String blockHash, String uncleIdx); @Override BlockResultDTO eth_getUncleByBlockNumberAndIndex(String blockId, String uncleIdx); @Override String[] eth_getCompilers(); @Override Map<String, CompilationResultDTO> eth_compileLLL(String contract); @Override Map<String, CompilationResultDTO> eth_compileSerpent(String contract); @Override Map<String, CompilationResultDTO> eth_compileSolidity(String contract); @Override String eth_newFilter(FilterRequest fr); @Override String eth_newBlockFilter(); @Override String eth_newPendingTransactionFilter(); @Override boolean eth_uninstallFilter(String id); @Override Object[] eth_getFilterChanges(String id); @Override Object[] eth_getFilterLogs(String id); @Override Object[] eth_getLogs(FilterRequest fr); @Override Map<String, String> rpc_modules(); @Override void db_putString(); @Override void db_getString(); @Override boolean eth_submitWork(String nonce, String header, String mince); @Override boolean eth_submitHashrate(String hashrate, String id); @Override void db_putHex(); @Override void db_getHex(); @Override String personal_newAccountWithSeed(String seed); @Override String personal_newAccount(String passphrase); @Override String personal_importRawKey(String key, String passphrase); @Override String personal_dumpRawKey(String address); @Override String[] personal_listAccounts(); @Override String personal_sendTransaction(CallArguments args, String passphrase); @Override boolean personal_unlockAccount(String address, String passphrase, String duration); @Override boolean personal_lockAccount(String address); @Override EthModule getEthModule(); @Override EvmModule getEvmModule(); @Override TxPoolModule getTxPoolModule(); @Override MnrModule getMnrModule(); @Override DebugModule getDebugModule(); @Override TraceModule getTraceModule(); @Override RskModule getRskModule(); @Override void sco_banAddress(String address); @Override void sco_unbanAddress(String address); @Override PeerScoringInformation[] sco_peerList(); @Override String[] sco_bannedAddresses(); public Ethereum eth; } | @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 = Web3Mocks.getMockBlockchain(); TransactionPool transactionPool = Web3Mocks.getMockTransactionPool(); BlockStore blockStore = Web3Mocks.getMockBlockStore(); RskSystemProperties mockProperties = Web3Mocks.getMockProperties(); PersonalModule personalModule = new PersonalModuleWalletDisabled(); Web3 web3 = new Web3Impl( ethMock, blockchain, blockStore, null, mockProperties, null, minerServerMock, personalModule, null, null, null, null, null, null, null, Web3Mocks.getMockChannelManager(), null, null, null, null, null, null, null, mock(Web3InformationRetriever.class)); Assert.assertEquals("0x" + originalCoinbase, web3.eth_coinbase()); verify(minerServerMock, times(1)).getCoinbaseAddress(); } |
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 (txInfo == null) { logger.trace("No transaction info for {}", transactionHash); return null; } Block block = this.blockchain.getBlockByHash(txInfo.getBlockHash()); Block parent = this.blockchain.getBlockByHash(block.getParentHash().getBytes()); Transaction tx = block.getTransactionsList().get(txInfo.getIndex()); txInfo.setTransaction(tx); ProgramTraceProcessor programTraceProcessor = new ProgramTraceProcessor(); this.blockExecutor.traceBlock(programTraceProcessor, VmConfig.LIGHT_TRACE, block, parent.getHeader(), false, false); SummarizedProgramTrace programTrace = (SummarizedProgramTrace)programTraceProcessor.getProgramTrace(tx.getHash()); if (programTrace == null) { return null; } List<TransactionTrace> traces = TraceTransformer.toTraces(programTrace, txInfo, block.getNumber()); ObjectMapper mapper = Serializers.createMapper(true); return mapper.valueToTree(traces); } TraceModuleImpl(
Blockchain blockchain,
BlockStore blockStore,
ReceiptStore receiptStore,
BlockExecutor blockExecutor); @Override JsonNode traceTransaction(String transactionHash); @Override JsonNode traceBlock(String blockArgument); } | @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()); JsonNode result = traceModule.traceTransaction("0x00"); Assert.assertNull(result); }
@Test public void retrieveSimpleContractCreationTrace() throws Exception { DslParser parser = DslParser.fromResource("dsl/contracts01.txt"); ReceiptStore receiptStore = new ReceiptStoreImpl(new HashMapDB()); World world = new World(receiptStore); WorldDslProcessor processor = new WorldDslProcessor(world); processor.processCommands(parser); Transaction transaction = world.getTransactionByName("tx01"); TraceModuleImpl traceModule = new TraceModuleImpl(world.getBlockChain(), world.getBlockStore(), receiptStore, world.getBlockExecutor()); JsonNode result = traceModule.traceTransaction(transaction.getHash().toJsonString()); Assert.assertNotNull(result); Assert.assertTrue(result.isArray()); ArrayNode aresult = (ArrayNode)result; Assert.assertEquals(1, aresult.size()); Assert.assertTrue(result.get(0).isObject()); ObjectNode oresult = (ObjectNode)result.get(0); Assert.assertNotNull(oresult.get("type")); Assert.assertEquals("\"create\"", oresult.get("type").toString()); Assert.assertNotNull(oresult.get("action")); Assert.assertNull(oresult.get("action").get("creationMethod")); Assert.assertNotNull(oresult.get("action").get("init")); Assert.assertNull(oresult.get("action").get("input")); }
@Test public void retrieveEmptyContractCreationTrace() throws Exception { DslParser parser = DslParser.fromResource("dsl/contracts09.txt"); ReceiptStore receiptStore = new ReceiptStoreImpl(new HashMapDB()); World world = new World(receiptStore); WorldDslProcessor processor = new WorldDslProcessor(world); processor.processCommands(parser); Transaction transaction = world.getTransactionByName("tx01"); TraceModuleImpl traceModule = new TraceModuleImpl(world.getBlockChain(), world.getBlockStore(), receiptStore, world.getBlockExecutor()); JsonNode result = traceModule.traceTransaction(transaction.getHash().toJsonString()); Assert.assertNotNull(result); Assert.assertTrue(result.isArray()); ArrayNode aresult = (ArrayNode)result; Assert.assertEquals(1, aresult.size()); Assert.assertTrue(result.get(0).isObject()); ObjectNode oresult = (ObjectNode)result.get(0); Assert.assertNotNull(oresult.get("type")); Assert.assertEquals("\"create\"", oresult.get("type").toString()); }
@Test public void retrieveSimpleContractInvocationTrace() throws Exception { DslParser parser = DslParser.fromResource("dsl/contracts02.txt"); ReceiptStore receiptStore = new ReceiptStoreImpl(new HashMapDB()); World world = new World(receiptStore); WorldDslProcessor processor = new WorldDslProcessor(world); processor.processCommands(parser); Transaction transaction = world.getTransactionByName("tx02"); TraceModuleImpl traceModule = new TraceModuleImpl(world.getBlockChain(), world.getBlockStore(), receiptStore, world.getBlockExecutor()); JsonNode result = traceModule.traceTransaction(transaction.getHash().toJsonString()); Assert.assertNotNull(result); Assert.assertTrue(result.isArray()); ArrayNode aresult = (ArrayNode)result; Assert.assertEquals(1, aresult.size()); Assert.assertTrue(result.get(0).isObject()); ObjectNode oresult = (ObjectNode)result.get(0); Assert.assertNotNull(oresult.get("type")); Assert.assertEquals("\"call\"", oresult.get("type").toString()); }
@Test public void retrieveSimpleAccountTransfer() throws Exception { DslParser parser = DslParser.fromResource("dsl/transfers01.txt"); ReceiptStore receiptStore = new ReceiptStoreImpl(new HashMapDB()); World world = new World(receiptStore); WorldDslProcessor processor = new WorldDslProcessor(world); processor.processCommands(parser); Transaction transaction = world.getTransactionByName("tx01"); TraceModuleImpl traceModule = new TraceModuleImpl(world.getBlockChain(), world.getBlockStore(), receiptStore, world.getBlockExecutor()); JsonNode result = traceModule.traceTransaction(transaction.getHash().toJsonString()); Assert.assertNotNull(result); Assert.assertTrue(result.isArray()); ArrayNode aresult = (ArrayNode)result; Assert.assertEquals(1, aresult.size()); Assert.assertTrue(result.get(0).isObject()); ObjectNode oresult = (ObjectNode)result.get(0); Assert.assertNotNull(oresult.get("type")); Assert.assertEquals("\"call\"", oresult.get("type").toString()); }
@Test public void executeContractWithCall() throws Exception { DslParser parser = DslParser.fromResource("dsl/call01.txt"); ReceiptStore receiptStore = new ReceiptStoreImpl(new HashMapDB()); World world = new World(receiptStore); WorldDslProcessor processor = new WorldDslProcessor(world); processor.processCommands(parser); Account callAccount = world.getAccountByName("call"); Account calledAccount = world.getAccountByName("called"); Assert.assertNotNull(callAccount); Assert.assertNotNull(calledAccount); Transaction transaction = world.getTransactionByName("tx01"); TraceModuleImpl traceModule = new TraceModuleImpl(world.getBlockChain(), world.getBlockStore(), receiptStore, world.getBlockExecutor()); JsonNode result = traceModule.traceTransaction(transaction.getHash().toJsonString()); Assert.assertNotNull(result); Assert.assertTrue(result.isArray()); ArrayNode aresult = (ArrayNode)result; Assert.assertEquals(2, aresult.size()); Assert.assertTrue(result.get(0).isObject()); ObjectNode oresult = (ObjectNode)result.get(1); Assert.assertNotNull(oresult.get("action")); Assert.assertNotNull(oresult.get("action").get("callType")); Assert.assertEquals("\"call\"", oresult.get("action").get("callType").toString()); Assert.assertEquals("\"" + calledAccount.getAddress().toJsonString() + "\"", oresult.get("action").get("to").toString()); Assert.assertEquals("\"" + callAccount.getAddress().toJsonString() + "\"", oresult.get("action").get("from").toString()); }
@Test public void executeContractWithDelegateCall() throws Exception { DslParser parser = DslParser.fromResource("dsl/delegatecall01.txt"); ReceiptStore receiptStore = new ReceiptStoreImpl(new HashMapDB()); World world = new World(receiptStore); WorldDslProcessor processor = new WorldDslProcessor(world); processor.processCommands(parser); Account delegateCallAccount = world.getAccountByName("delegatecall"); Account delegatedAccount = world.getAccountByName("delegated"); Assert.assertNotNull(delegateCallAccount); Assert.assertNotNull(delegatedAccount); Transaction transaction = world.getTransactionByName("tx01"); TraceModuleImpl traceModule = new TraceModuleImpl(world.getBlockChain(), world.getBlockStore(), receiptStore, world.getBlockExecutor()); JsonNode result = traceModule.traceTransaction(transaction.getHash().toJsonString()); Assert.assertNotNull(result); Assert.assertTrue(result.isArray()); ArrayNode aresult = (ArrayNode)result; Assert.assertEquals(2, aresult.size()); Assert.assertTrue(result.get(0).isObject()); ObjectNode oresult = (ObjectNode)result.get(1); Assert.assertNotNull(oresult.get("action")); Assert.assertNotNull(oresult.get("action").get("callType")); Assert.assertEquals("\"delegatecall\"", oresult.get("action").get("callType").toString()); Assert.assertEquals("\"" + delegatedAccount.getAddress().toJsonString() + "\"", oresult.get("action").get("to").toString()); Assert.assertEquals("\"" + delegateCallAccount.getAddress().toJsonString() + "\"", oresult.get("action").get("from").toString()); }
@Test public void executeContractWithCreate2() throws Exception { DslParser parser = DslParser.fromResource("dsl/create201.txt"); ReceiptStore receiptStore = new ReceiptStoreImpl(new HashMapDB()); World world = new World(receiptStore); WorldDslProcessor processor = new WorldDslProcessor(world); processor.processCommands(parser); Transaction transaction = world.getTransactionByName("tx01"); TraceModuleImpl traceModule = new TraceModuleImpl(world.getBlockChain(), world.getBlockStore(), receiptStore, world.getBlockExecutor()); JsonNode result = traceModule.traceTransaction(transaction.getHash().toJsonString()); Assert.assertNotNull(result); Assert.assertTrue(result.isArray()); ArrayNode aresult = (ArrayNode)result; Assert.assertEquals(2, aresult.size()); Assert.assertTrue(result.get(0).isObject()); ObjectNode oresult = (ObjectNode)result.get(1); Assert.assertNotNull(oresult.get("action")); Assert.assertNotNull(oresult.get("action").get("creationMethod")); Assert.assertEquals("\"create2\"", oresult.get("action").get("creationMethod").toString()); } |
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 = this.blockchain.getBlockByHash(block.getParentHash().getBytes()); List<TransactionTrace> blockTraces = new ArrayList<>(); if (block.getNumber() != 0) { ProgramTraceProcessor programTraceProcessor = new ProgramTraceProcessor(); this.blockExecutor.traceBlock(programTraceProcessor, VmConfig.LIGHT_TRACE, block, parent.getHeader(), false, false); for (Transaction tx : block.getTransactionsList()) { TransactionInfo txInfo = receiptStore.getInMainChain(tx.getHash().getBytes(), this.blockStore); txInfo.setTransaction(tx); SummarizedProgramTrace programTrace = (SummarizedProgramTrace) programTraceProcessor.getProgramTrace(tx.getHash()); if (programTrace == null) { return null; } List<TransactionTrace> traces = TraceTransformer.toTraces(programTrace, txInfo, block.getNumber()); blockTraces.addAll(traces); } } ObjectMapper mapper = Serializers.createMapper(true); return mapper.valueToTree(blockTraces); } TraceModuleImpl(
Blockchain blockchain,
BlockStore blockStore,
ReceiptStore receiptStore,
BlockExecutor blockExecutor); @Override JsonNode traceTransaction(String transactionHash); @Override JsonNode traceBlock(String blockArgument); } | @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 result = traceModule.traceBlock("0x0001020300010203000102030001020300010203000102030001020300010203"); Assert.assertNull(result); } |
RskJsonRpcHandler extends SimpleChannelInboundHandler<ByteBufHolder> implements RskJsonRpcRequestVisitor { @Override public JsonRpcResultOrError visit(EthUnsubscribeRequest request, ChannelHandlerContext ctx) { boolean unsubscribed = emitter.unsubscribe(request.getParams().getSubscriptionId()); return new JsonRpcBooleanResult(unsubscribed); } RskJsonRpcHandler(EthSubscriptionNotificationEmitter emitter, JsonRpcSerializer serializer); @Override void channelInactive(ChannelHandlerContext ctx); @Override JsonRpcResultOrError visit(EthUnsubscribeRequest request, ChannelHandlerContext ctx); @Override JsonRpcResultOrError visit(EthSubscribeRequest request, ChannelHandlerContext ctx); } | @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, null), is(new JsonRpcBooleanResult(true)) ); }
@Test public void visitSubscribe() { Channel channel = mock(Channel.class); ChannelHandlerContext ctx = mock(ChannelHandlerContext.class); when(ctx.channel()) .thenReturn(channel); when(emitter.visit(any(EthSubscribeNewHeadsParams.class), eq(channel))) .thenReturn(SAMPLE_SUBSCRIPTION_ID); assertThat( handler.visit(SAMPLE_SUBSCRIBE_REQUEST, ctx), is(SAMPLE_SUBSCRIPTION_ID) ); }
@Test public void handlerDeserializesAndHandlesRequest() throws Exception { Channel channel = mock(Channel.class); ChannelHandlerContext ctx = mock(ChannelHandlerContext.class); when(ctx.channel()) .thenReturn(channel); when(serializer.deserializeRequest(any())) .thenReturn(SAMPLE_SUBSCRIBE_REQUEST); when(emitter.visit(any(EthSubscribeNewHeadsParams.class), eq(channel))) .thenReturn(SAMPLE_SUBSCRIPTION_ID); when(serializer.serializeMessage(any())) .thenReturn("serialized"); DefaultByteBufHolder msg = new DefaultByteBufHolder(Unpooled.copiedBuffer("raw".getBytes())); handler.channelRead(ctx, msg); verify(ctx, times(1)).writeAndFlush(new TextWebSocketFrame("serialized")); verify(ctx, never()).fireChannelRead(any()); } |
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"); } Web3RskImpl(
Ethereum eth,
Blockchain blockchain,
RskSystemProperties properties,
MinerClient minerClient,
MinerServer minerServer,
PersonalModule personalModule,
EthModule ethModule,
EvmModule evmModule,
TxPoolModule txPoolModule,
MnrModule mnrModule,
DebugModule debugModule,
TraceModule traceModule, RskModule rskModule,
ChannelManager channelManager,
PeerScoringManager peerScoringManager,
NetworkStateExporter networkStateExporter,
BlockStore blockStore,
ReceiptStore receiptStore,
PeerServer peerServer,
BlockProcessor nodeBlockProcessor,
HashRateCalculator hashRateCalculator,
ConfigCapabilities configCapabilities,
BuildInfo buildInfo,
BlocksBloomStore blocksBloomStore,
Web3InformationRetriever retriever); void ext_dumpState(); void ext_dumpBlockchain(long numberOfBlocks, boolean includeUncles); } | @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(Mockito.anyString())).thenReturn(true); Block block = mock(Block.class); Mockito.when(block.getHash()).thenReturn(PegTestUtils.createHash3()); Mockito.when(block.getNumber()).thenReturn(1L); BlockStore blockStore = mock(BlockStore.class); Mockito.when(blockStore.getBestBlock()).thenReturn(block); Mockito.when(networkStateExporter.exportStatus(Mockito.anyString())).thenReturn(true); Mockito.when(blockchain.getBestBlock()).thenReturn(block); Wallet wallet = WalletFactory.createWallet(); TestSystemProperties config = new TestSystemProperties(); PersonalModule pm = new PersonalModuleWalletEnabled(config, rsk, wallet, null); EthModule em = new EthModule( config.getNetworkConstants().getBridgeConstants(), config.getNetworkConstants().getChainId(), blockchain, null, null, new ExecutionBlockRetriever(mainchainView, blockchain, null, null), null, new EthModuleWalletEnabled(wallet), null, new BridgeSupportFactory( null, config.getNetworkConstants().getBridgeConstants(), config.getActivationConfig()) ); TxPoolModule tpm = new TxPoolModuleImpl(Web3Mocks.getMockTransactionPool()); DebugModule dm = new DebugModuleImpl(null, null, Web3Mocks.getMockMessageHandler(), null); Web3RskImpl web3 = new Web3RskImpl( rsk, blockchain, config, Web3Mocks.getMockMinerClient(), Web3Mocks.getMockMinerServer(), pm, em, null, tpm, null, dm, null, null, Web3Mocks.getMockChannelManager(), null, networkStateExporter, blockStore, null, null, null, null, null, null, null, null); web3.ext_dumpState(); } |
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)) { block = blockchain.getBlockByNumber(0); } else { block = this.blockchain.getBlockByNumber(getBlockNumber(identifier)); } return Optional.ofNullable(block); } Web3InformationRetriever(TransactionPool transactionPool, Blockchain blockchain, RepositoryLocator locator); Optional<Block> getBlock(String identifier); AccountInformationProvider getInformationProvider(String identifier); List<Transaction> getTransactions(String identifier); } | @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 .assertThrows(RskJsonRpcRequestException.class, () -> target.getBlock("pending2")); assertEquals(INVALID_PARAM_ERROR_CODE, (int) e.getCode()); }
@Test public void getBlock_latest() { Block bestBlock = mock(Block.class); when(blockchain.getBestBlock()).thenReturn(bestBlock); Optional<Block> result = target.getBlock("latest"); assertTrue(result.isPresent()); assertEquals(bestBlock, result.get()); }
@Test public void getBlock_earliest() { Block earliestBlock = mock(Block.class); when(blockchain.getBlockByNumber(0)).thenReturn(earliestBlock); Optional<Block> result = target.getBlock("earliest"); assertTrue(result.isPresent()); assertEquals(earliestBlock, result.get()); }
@Test public void getBlock_number() { Block secondBlock = mock(Block.class); when(blockchain.getBlockByNumber(2)).thenReturn(secondBlock); Optional<Block> result = target.getBlock("0x2"); assertTrue(result.isPresent()); assertEquals(secondBlock, result.get()); }
@Test public void getBlock_notFound() { Optional<Block> result = target.getBlock("0x2"); assertFalse(result.isPresent()); } |
Web3Impl implements Web3 { @Override public String personal_newAccount(String passphrase) { return personalModule.newAccount(passphrase); } protected Web3Impl(
Ethereum eth,
Blockchain blockchain,
BlockStore blockStore,
ReceiptStore receiptStore,
RskSystemProperties config,
MinerClient minerClient,
MinerServer minerServer,
PersonalModule personalModule,
EthModule ethModule,
EvmModule evmModule,
TxPoolModule txPoolModule,
MnrModule mnrModule,
DebugModule debugModule,
TraceModule traceModule,
RskModule rskModule,
ChannelManager channelManager,
PeerScoringManager peerScoringManager,
PeerServer peerServer,
BlockProcessor nodeBlockProcessor,
HashRateCalculator hashRateCalculator,
ConfigCapabilities configCapabilities,
BuildInfo buildInfo,
BlocksBloomStore blocksBloomStore,
Web3InformationRetriever web3InformationRetriever); @Override void start(); @Override void stop(); @Override String web3_clientVersion(); @Override String web3_sha3(String data); @Override String net_version(); @Override String net_peerCount(); @Override boolean net_listening(); @Override String rsk_protocolVersion(); @Override String eth_protocolVersion(); @Override Object eth_syncing(); @Override String eth_coinbase(); @Override boolean eth_mining(); @Override BigInteger eth_hashrate(); @Override BigInteger eth_netHashrate(); @Override String[] net_peerList(); @Override String eth_gasPrice(); @Override String eth_blockNumber(); @Override String eth_getBalance(String address, String block); @Override String eth_getBalance(String address); @Override String eth_getStorageAt(String address, String storageIdx, String blockId); @Override String eth_getTransactionCount(String address, String blockId); Block getBlockByJSonHash(String blockHash); @Override String eth_getBlockTransactionCountByHash(String blockHash); static Block getBlockByNumberOrStr(String bnOrId, Blockchain blockchain); @Override String eth_getBlockTransactionCountByNumber(String bnOrId); @Override String eth_getUncleCountByBlockHash(String blockHash); @Override String eth_getUncleCountByBlockNumber(String bnOrId); BlockInformationResult getBlockInformationResult(BlockInformation blockInformation); BlockResultDTO getBlockResult(Block b, boolean fullTx); BlockInformationResult[] eth_getBlocksByNumber(String number); @Override BlockResultDTO eth_getBlockByHash(String blockHash, Boolean fullTransactionObjects); @Override BlockResultDTO eth_getBlockByNumber(String bnOrId, Boolean fullTransactionObjects); @Override TransactionResultDTO eth_getTransactionByHash(String transactionHash); @Override TransactionResultDTO eth_getTransactionByBlockHashAndIndex(String blockHash, String index); @Override TransactionResultDTO eth_getTransactionByBlockNumberAndIndex(String bnOrId, String index); @Override TransactionReceiptDTO eth_getTransactionReceipt(String transactionHash); @Override BlockResultDTO eth_getUncleByBlockHashAndIndex(String blockHash, String uncleIdx); @Override BlockResultDTO eth_getUncleByBlockNumberAndIndex(String blockId, String uncleIdx); @Override String[] eth_getCompilers(); @Override Map<String, CompilationResultDTO> eth_compileLLL(String contract); @Override Map<String, CompilationResultDTO> eth_compileSerpent(String contract); @Override Map<String, CompilationResultDTO> eth_compileSolidity(String contract); @Override String eth_newFilter(FilterRequest fr); @Override String eth_newBlockFilter(); @Override String eth_newPendingTransactionFilter(); @Override boolean eth_uninstallFilter(String id); @Override Object[] eth_getFilterChanges(String id); @Override Object[] eth_getFilterLogs(String id); @Override Object[] eth_getLogs(FilterRequest fr); @Override Map<String, String> rpc_modules(); @Override void db_putString(); @Override void db_getString(); @Override boolean eth_submitWork(String nonce, String header, String mince); @Override boolean eth_submitHashrate(String hashrate, String id); @Override void db_putHex(); @Override void db_getHex(); @Override String personal_newAccountWithSeed(String seed); @Override String personal_newAccount(String passphrase); @Override String personal_importRawKey(String key, String passphrase); @Override String personal_dumpRawKey(String address); @Override String[] personal_listAccounts(); @Override String personal_sendTransaction(CallArguments args, String passphrase); @Override boolean personal_unlockAccount(String address, String passphrase, String duration); @Override boolean personal_lockAccount(String address); @Override EthModule getEthModule(); @Override EvmModule getEvmModule(); @Override TxPoolModule getTxPoolModule(); @Override MnrModule getMnrModule(); @Override DebugModule getDebugModule(); @Override TraceModule getTraceModule(); @Override RskModule getRskModule(); @Override void sco_banAddress(String address); @Override void sco_unbanAddress(String address); @Override PeerScoringInformation[] sco_peerList(); @Override String[] sco_bannedAddresses(); public Ethereum eth; } | @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.assertEquals(addr, "0x" + ByteUtil.toHexString(account.getAddress().getBytes())); } |
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 %s not found", identifier))); } Web3InformationRetriever(TransactionPool transactionPool, Blockchain blockchain, RepositoryLocator locator); Optional<Block> getBlock(String identifier); AccountInformationProvider getInformationProvider(String identifier); List<Transaction> getTransactions(String identifier); } | @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 void getTransactions_earliest() { List<Transaction> txs = new LinkedList<>(); txs.add(mock(Transaction.class)); txs.add(mock(Transaction.class)); Block block = mock(Block.class); when(block.getTransactionsList()).thenReturn(txs); when(blockchain.getBlockByNumber(0)).thenReturn(block); List<Transaction> result = target.getTransactions("earliest"); assertEquals(txs, result); }
@Test public void getTransactions_latest() { List<Transaction> txs = new LinkedList<>(); txs.add(mock(Transaction.class)); txs.add(mock(Transaction.class)); Block block = mock(Block.class); when(block.getTransactionsList()).thenReturn(txs); when(blockchain.getBestBlock()).thenReturn(block); List<Transaction> result = target.getTransactions("latest"); assertEquals(txs, result); }
@Test public void getTransactions_number() { List<Transaction> txs = new LinkedList<>(); txs.add(mock(Transaction.class)); txs.add(mock(Transaction.class)); Block block = mock(Block.class); when(block.getTransactionsList()).thenReturn(txs); when(blockchain.getBlockByNumber(3)).thenReturn(block); List<Transaction> result = target.getTransactions("0x3"); assertEquals(txs, result); }
@Test public void getTransactions_blockNotFound() { RskJsonRpcRequestException e = TestUtils .assertThrows(RskJsonRpcRequestException.class, () -> target.getTransactions("0x3")); assertEquals(-32600, (int) e.getCode()); } |
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", identifier)); } Block block = optBlock.get(); return locator.findSnapshotAt(block.getHeader()).orElseThrow(() -> RskJsonRpcRequestException .stateNotFound(String.format("State not found for block with hash %s", block.getHash()))); } Web3InformationRetriever(TransactionPool transactionPool, Blockchain blockchain, RepositoryLocator locator); Optional<Block> getBlock(String identifier); AccountInformationProvider getInformationProvider(String identifier); List<Transaction> getTransactions(String identifier); } | @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); BlockHeader header = mock(BlockHeader.class); when(block.getHeader()).thenReturn(header); when(blockchain.getBlockByNumber(0)).thenReturn(block); RepositorySnapshot snapshot = mock(RepositorySnapshot.class); when(locator.findSnapshotAt(eq(header))).thenReturn(Optional.of(snapshot)); AccountInformationProvider result = target.getInformationProvider("earliest"); assertEquals(snapshot, result); }
@Test public void getState_latest() { Block block = mock(Block.class); BlockHeader header = mock(BlockHeader.class); when(block.getHeader()).thenReturn(header); when(blockchain.getBestBlock()).thenReturn(block); RepositorySnapshot snapshot = mock(RepositorySnapshot.class); when(locator.findSnapshotAt(eq(header))).thenReturn(Optional.of(snapshot)); AccountInformationProvider result = target.getInformationProvider("latest"); assertEquals(snapshot, result); }
@Test public void getState_number() { Block block = mock(Block.class); BlockHeader header = mock(BlockHeader.class); when(block.getHeader()).thenReturn(header); when(blockchain.getBlockByNumber(4)).thenReturn(block); RepositorySnapshot snapshot = mock(RepositorySnapshot.class); when(locator.findSnapshotAt(eq(header))).thenReturn(Optional.of(snapshot)); AccountInformationProvider result = target.getInformationProvider("0x4"); assertEquals(snapshot, result); }
@Test public void getState_blockNotFound() { RskJsonRpcRequestException e = TestUtils .assertThrows(RskJsonRpcRequestException.class, () -> target.getInformationProvider("0x4")); assertEquals("Block 0x4 not found", e.getMessage()); }
@Test public void getTransactions_stateNotFound() { Block block = mock(Block.class); BlockHeader header = mock(BlockHeader.class); when(block.getHeader()).thenReturn(header); Keccak256 blockHash = new Keccak256(new byte[32]); when(block.getHash()).thenReturn(blockHash); when(blockchain.getBlockByNumber(4)).thenReturn(block); RskJsonRpcRequestException e = TestUtils .assertThrows(RskJsonRpcRequestException.class, () -> target.getInformationProvider("0x4")); assertEquals("State not found for block with hash " + blockHash.toString(), e.getMessage()); } |
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,
RskSystemProperties config,
MinerClient minerClient,
MinerServer minerServer,
PersonalModule personalModule,
EthModule ethModule,
EvmModule evmModule,
TxPoolModule txPoolModule,
MnrModule mnrModule,
DebugModule debugModule,
TraceModule traceModule,
RskModule rskModule,
ChannelManager channelManager,
PeerScoringManager peerScoringManager,
PeerServer peerServer,
BlockProcessor nodeBlockProcessor,
HashRateCalculator hashRateCalculator,
ConfigCapabilities configCapabilities,
BuildInfo buildInfo,
BlocksBloomStore blocksBloomStore,
Web3InformationRetriever web3InformationRetriever); @Override void start(); @Override void stop(); @Override String web3_clientVersion(); @Override String web3_sha3(String data); @Override String net_version(); @Override String net_peerCount(); @Override boolean net_listening(); @Override String rsk_protocolVersion(); @Override String eth_protocolVersion(); @Override Object eth_syncing(); @Override String eth_coinbase(); @Override boolean eth_mining(); @Override BigInteger eth_hashrate(); @Override BigInteger eth_netHashrate(); @Override String[] net_peerList(); @Override String eth_gasPrice(); @Override String eth_blockNumber(); @Override String eth_getBalance(String address, String block); @Override String eth_getBalance(String address); @Override String eth_getStorageAt(String address, String storageIdx, String blockId); @Override String eth_getTransactionCount(String address, String blockId); Block getBlockByJSonHash(String blockHash); @Override String eth_getBlockTransactionCountByHash(String blockHash); static Block getBlockByNumberOrStr(String bnOrId, Blockchain blockchain); @Override String eth_getBlockTransactionCountByNumber(String bnOrId); @Override String eth_getUncleCountByBlockHash(String blockHash); @Override String eth_getUncleCountByBlockNumber(String bnOrId); BlockInformationResult getBlockInformationResult(BlockInformation blockInformation); BlockResultDTO getBlockResult(Block b, boolean fullTx); BlockInformationResult[] eth_getBlocksByNumber(String number); @Override BlockResultDTO eth_getBlockByHash(String blockHash, Boolean fullTransactionObjects); @Override BlockResultDTO eth_getBlockByNumber(String bnOrId, Boolean fullTransactionObjects); @Override TransactionResultDTO eth_getTransactionByHash(String transactionHash); @Override TransactionResultDTO eth_getTransactionByBlockHashAndIndex(String blockHash, String index); @Override TransactionResultDTO eth_getTransactionByBlockNumberAndIndex(String bnOrId, String index); @Override TransactionReceiptDTO eth_getTransactionReceipt(String transactionHash); @Override BlockResultDTO eth_getUncleByBlockHashAndIndex(String blockHash, String uncleIdx); @Override BlockResultDTO eth_getUncleByBlockNumberAndIndex(String blockId, String uncleIdx); @Override String[] eth_getCompilers(); @Override Map<String, CompilationResultDTO> eth_compileLLL(String contract); @Override Map<String, CompilationResultDTO> eth_compileSerpent(String contract); @Override Map<String, CompilationResultDTO> eth_compileSolidity(String contract); @Override String eth_newFilter(FilterRequest fr); @Override String eth_newBlockFilter(); @Override String eth_newPendingTransactionFilter(); @Override boolean eth_uninstallFilter(String id); @Override Object[] eth_getFilterChanges(String id); @Override Object[] eth_getFilterLogs(String id); @Override Object[] eth_getLogs(FilterRequest fr); @Override Map<String, String> rpc_modules(); @Override void db_putString(); @Override void db_getString(); @Override boolean eth_submitWork(String nonce, String header, String mince); @Override boolean eth_submitHashrate(String hashrate, String id); @Override void db_putHex(); @Override void db_getHex(); @Override String personal_newAccountWithSeed(String seed); @Override String personal_newAccount(String passphrase); @Override String personal_importRawKey(String key, String passphrase); @Override String personal_dumpRawKey(String address); @Override String[] personal_listAccounts(); @Override String personal_sendTransaction(CallArguments args, String passphrase); @Override boolean personal_unlockAccount(String address, String passphrase, String duration); @Override boolean personal_lockAccount(String address); @Override EthModule getEthModule(); @Override EvmModule getEvmModule(); @Override TxPoolModule getTxPoolModule(); @Override MnrModule getMnrModule(); @Override DebugModule getDebugModule(); @Override TraceModule getTraceModule(); @Override RskModule getRskModule(); @Override void sco_banAddress(String address); @Override void sco_unbanAddress(String address); @Override PeerScoringInformation[] sco_peerList(); @Override String[] sco_bannedAddresses(); public Ethereum eth; } | @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.assertNull(account); String address = web3.personal_importRawKey(ByteUtil.toHexString(privKeyBytes), "passphrase1"); assertNotNull(address); account = wallet.getAccount(addr); assertNotNull(account); org.junit.Assert.assertEquals(address, "0x" + ByteUtil.toHexString(account.getAddress().getBytes())); org.junit.Assert.assertArrayEquals(privKeyBytes, account.getEcKey().getPrivKeyBytes()); } |
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 interceptRequest(JsonNode node); } | @Test public void checkModuleNames() throws Throwable { RequestInterceptor jsonRpcMethodFilter = new JsonRpcMethodFilter(getModules()); jsonRpcMethodFilter.interceptRequest(getMethodInvocation("evm_snapshot")); jsonRpcMethodFilter.interceptRequest(getMethodInvocation("evm_revert")); try { jsonRpcMethodFilter.interceptRequest(getMethodInvocation("evm_reset")); Assert.fail("evm_reset is enabled AND disabled, disabled take precedence"); } catch (IOException ex) { } try { jsonRpcMethodFilter.interceptRequest(getMethodInvocation("evm_increaseTime")); Assert.fail("evm_increaseTime is disabled"); } catch (IOException ex) { } try { jsonRpcMethodFilter.interceptRequest(getMethodInvocation("eth_getBlock")); Assert.fail("The whole eth namespace is disabled"); } catch (IOException ex) { } } |
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; } String refererHost = refererUrl.getHost(); if (refererHost == null) { return false; } int refererPort = refererUrl.getPort(); for (int k = 0; k < origins.length; k++) { if (refererProtocol.equals(origins[k].getScheme()) && refererHost.equals(origins[k].getHost()) && refererPort == origins[k].getPort()) { return true; } } return false; } OriginValidator(); OriginValidator(String uriList); boolean isValidOrigin(String origin); boolean isValidReferer(String referer); } | @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("http: Assert.assertFalse(validator.isValidReferer("http: }
@Test public void invalidRefererWithDifferentPort() throws URISyntaxException { OriginValidator validator = new OriginValidator("http: Assert.assertFalse(validator.isValidReferer("http: } |
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; } ModuleDescription(String name, String version, boolean enabled, List<String> enabledMethods, List<String> disabledMethods); String getName(); String getVersion(); boolean isEnabled(); List<String> getEnabledMethods(); List<String> getDisabledMethods(); boolean methodIsInModule(String methodName); boolean methodIsEnable(String methodName); } | @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")); Assert.assertFalse(description.methodIsInModule("eth")); Assert.assertFalse(description.methodIsInModule("evm")); Assert.assertFalse(description.methodIsInModule("evm2")); Assert.assertFalse(description.methodIsInModule("evmsnapshot")); Assert.assertFalse(description.methodIsInModule(null)); } |
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; } if (this.enabledMethods.contains(methodName)) { return true; } if (!this.enabledMethods.isEmpty()) { return false; } return true; } ModuleDescription(String name, String version, boolean enabled, List<String> enabledMethods, List<String> disabledMethods); String getName(); String getVersion(); boolean isEnabled(); List<String> getEnabledMethods(); List<String> getDisabledMethods(); boolean methodIsInModule(String methodName); boolean methodIsEnable(String methodName); } | @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_getBlock")); Assert.assertFalse(description.methodIsEnable("eth")); Assert.assertFalse(description.methodIsEnable("evm")); Assert.assertFalse(description.methodIsEnable("evm2")); Assert.assertFalse(description.methodIsEnable("evmsnapshot")); Assert.assertFalse(description.methodIsEnable(null)); }
@Test public void methodIsEnabledWhenEnabledNameList() { List<String> enabledMethods = new ArrayList<>(); enabledMethods.add("evm_snapshot"); enabledMethods.add("evm_revert"); ModuleDescription description = new ModuleDescription("evm", "1.0", true, enabledMethods, null); Assert.assertTrue(description.methodIsEnable("evm_snapshot")); Assert.assertTrue(description.methodIsEnable("evm_revert")); Assert.assertFalse(description.methodIsEnable("evm_do")); Assert.assertFalse(description.methodIsEnable("evm_reset")); Assert.assertFalse(description.methodIsEnable("evm_increaseTime")); Assert.assertFalse(description.methodIsEnable("eth_getBlock")); Assert.assertFalse(description.methodIsEnable("eth")); Assert.assertFalse(description.methodIsEnable("evm")); Assert.assertFalse(description.methodIsEnable("evm2")); Assert.assertFalse(description.methodIsEnable("evmsnapshot")); Assert.assertFalse(description.methodIsEnable(null)); }
@Test public void methodIsEnabledWhenDisabledNameList() { List<String> disabledMethods = new ArrayList<>(); disabledMethods.add("evm_reset"); disabledMethods.add("evm_increaseTime"); ModuleDescription description = new ModuleDescription("evm", "1.0", true, null, disabledMethods); Assert.assertTrue(description.methodIsEnable("evm_snapshot")); Assert.assertTrue(description.methodIsEnable("evm_revert")); Assert.assertTrue(description.methodIsEnable("evm_do")); Assert.assertFalse(description.methodIsEnable("evm_reset")); Assert.assertFalse(description.methodIsEnable("evm_increaseTime")); Assert.assertFalse(description.methodIsEnable("eth_getBlock")); Assert.assertFalse(description.methodIsEnable("eth")); Assert.assertFalse(description.methodIsEnable("evm")); Assert.assertFalse(description.methodIsEnable("evm2")); Assert.assertFalse(description.methodIsEnable("evmsnapshot")); Assert.assertFalse(description.methodIsEnable(null)); }
@Test public void methodIsEnabledWhenEnabledAndDisabledNameLists() { List<String> enabledMethods = new ArrayList<>(); enabledMethods.add("evm_snapshot"); enabledMethods.add("evm_revert"); enabledMethods.add("evm_reset"); List<String> disabledMethods = new ArrayList<>(); disabledMethods.add("evm_reset"); disabledMethods.add("evm_increaseTime"); ModuleDescription description = new ModuleDescription("evm", "1.0", true, enabledMethods, disabledMethods); Assert.assertTrue(description.methodIsEnable("evm_snapshot")); Assert.assertTrue(description.methodIsEnable("evm_revert")); Assert.assertFalse(description.methodIsEnable("evm_do")); Assert.assertFalse(description.methodIsEnable("evm_reset")); Assert.assertFalse(description.methodIsEnable("evm_increaseTime")); Assert.assertFalse(description.methodIsEnable("eth_getBlock")); Assert.assertFalse(description.methodIsEnable("eth")); Assert.assertFalse(description.methodIsEnable("evm")); Assert.assertFalse(description.methodIsEnable("evm2")); Assert.assertFalse(description.methodIsEnable("evmsnapshot")); Assert.assertFalse(description.methodIsEnable(null)); } |
Web3Impl implements Web3 { @Override public String[] personal_listAccounts() { return personalModule.listAccounts(); } protected Web3Impl(
Ethereum eth,
Blockchain blockchain,
BlockStore blockStore,
ReceiptStore receiptStore,
RskSystemProperties config,
MinerClient minerClient,
MinerServer minerServer,
PersonalModule personalModule,
EthModule ethModule,
EvmModule evmModule,
TxPoolModule txPoolModule,
MnrModule mnrModule,
DebugModule debugModule,
TraceModule traceModule,
RskModule rskModule,
ChannelManager channelManager,
PeerScoringManager peerScoringManager,
PeerServer peerServer,
BlockProcessor nodeBlockProcessor,
HashRateCalculator hashRateCalculator,
ConfigCapabilities configCapabilities,
BuildInfo buildInfo,
BlocksBloomStore blocksBloomStore,
Web3InformationRetriever web3InformationRetriever); @Override void start(); @Override void stop(); @Override String web3_clientVersion(); @Override String web3_sha3(String data); @Override String net_version(); @Override String net_peerCount(); @Override boolean net_listening(); @Override String rsk_protocolVersion(); @Override String eth_protocolVersion(); @Override Object eth_syncing(); @Override String eth_coinbase(); @Override boolean eth_mining(); @Override BigInteger eth_hashrate(); @Override BigInteger eth_netHashrate(); @Override String[] net_peerList(); @Override String eth_gasPrice(); @Override String eth_blockNumber(); @Override String eth_getBalance(String address, String block); @Override String eth_getBalance(String address); @Override String eth_getStorageAt(String address, String storageIdx, String blockId); @Override String eth_getTransactionCount(String address, String blockId); Block getBlockByJSonHash(String blockHash); @Override String eth_getBlockTransactionCountByHash(String blockHash); static Block getBlockByNumberOrStr(String bnOrId, Blockchain blockchain); @Override String eth_getBlockTransactionCountByNumber(String bnOrId); @Override String eth_getUncleCountByBlockHash(String blockHash); @Override String eth_getUncleCountByBlockNumber(String bnOrId); BlockInformationResult getBlockInformationResult(BlockInformation blockInformation); BlockResultDTO getBlockResult(Block b, boolean fullTx); BlockInformationResult[] eth_getBlocksByNumber(String number); @Override BlockResultDTO eth_getBlockByHash(String blockHash, Boolean fullTransactionObjects); @Override BlockResultDTO eth_getBlockByNumber(String bnOrId, Boolean fullTransactionObjects); @Override TransactionResultDTO eth_getTransactionByHash(String transactionHash); @Override TransactionResultDTO eth_getTransactionByBlockHashAndIndex(String blockHash, String index); @Override TransactionResultDTO eth_getTransactionByBlockNumberAndIndex(String bnOrId, String index); @Override TransactionReceiptDTO eth_getTransactionReceipt(String transactionHash); @Override BlockResultDTO eth_getUncleByBlockHashAndIndex(String blockHash, String uncleIdx); @Override BlockResultDTO eth_getUncleByBlockNumberAndIndex(String blockId, String uncleIdx); @Override String[] eth_getCompilers(); @Override Map<String, CompilationResultDTO> eth_compileLLL(String contract); @Override Map<String, CompilationResultDTO> eth_compileSerpent(String contract); @Override Map<String, CompilationResultDTO> eth_compileSolidity(String contract); @Override String eth_newFilter(FilterRequest fr); @Override String eth_newBlockFilter(); @Override String eth_newPendingTransactionFilter(); @Override boolean eth_uninstallFilter(String id); @Override Object[] eth_getFilterChanges(String id); @Override Object[] eth_getFilterLogs(String id); @Override Object[] eth_getLogs(FilterRequest fr); @Override Map<String, String> rpc_modules(); @Override void db_putString(); @Override void db_getString(); @Override boolean eth_submitWork(String nonce, String header, String mince); @Override boolean eth_submitHashrate(String hashrate, String id); @Override void db_putHex(); @Override void db_getHex(); @Override String personal_newAccountWithSeed(String seed); @Override String personal_newAccount(String passphrase); @Override String personal_importRawKey(String key, String passphrase); @Override String personal_dumpRawKey(String address); @Override String[] personal_listAccounts(); @Override String personal_sendTransaction(CallArguments args, String passphrase); @Override boolean personal_unlockAccount(String address, String passphrase, String duration); @Override boolean personal_lockAccount(String address); @Override EthModule getEthModule(); @Override EvmModule getEvmModule(); @Override TxPoolModule getTxPoolModule(); @Override MnrModule getMnrModule(); @Override DebugModule getDebugModule(); @Override TraceModule getTraceModule(); @Override RskModule getRskModule(); @Override void sco_banAddress(String address); @Override void sco_unbanAddress(String address); @Override PeerScoringInformation[] sco_peerList(); @Override String[] sco_bannedAddresses(); public Ethereum eth; } | @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 transactionExecutorFactory = buildTransactionExecutorFactory(blockStore, world.getBlockTxSignatureCache()); TransactionPool transactionPool = new TransactionPoolImpl(config, world.getRepositoryLocator(), blockStore, blockFactory, null, transactionExecutorFactory, world.getReceivedTxSignatureCache(), 10, 100); Web3Impl web3 = createWeb3(world, transactionPool, receiptStore); String[] accounts = web3.personal_listAccounts(); String addr1 = accounts[0]; String addr2 = accounts[1]; transactionPool.processBest(blockChain.getBestBlock()); String toAddress = addr2; BigInteger value = BigInteger.valueOf(7); BigInteger gasPrice = BigInteger.valueOf(8); BigInteger gasLimit = BigInteger.valueOf(300000); String data = "0xff"; Web3.CallArguments args = new Web3.CallArguments(); args.from = addr1; args.to = addr2; args.data = data; args.gas = TypeConverter.toQuantityJsonHex(gasLimit); args.gasPrice= TypeConverter.toQuantityJsonHex(gasPrice); args.value = value.toString(); args.nonce = nonce.toString(); String txHash = web3.eth_sendTransaction(args); Transaction tx = new Transaction(toAddress.substring(2), value, nonce, gasPrice, gasLimit, args.data, config.getNetworkConstants().getChainId()); tx.sign(wallet.getAccount(new RskAddress(addr1)).getEcKey().getPrivKeyBytes()); String expectedHash = tx.getHash().toJsonString(); assertTrue("Method is not creating the expected transaction", expectedHash.compareTo(txHash) == 0); } |
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[] encryptedBytes); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); final byte[] initialisationVector; final byte[] encryptedBytes; } | @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()); Assert.assertEquals(ed.hashCode(), ed2.hashCode()); Assert.assertEquals(ed, ed); Assert.assertEquals(ed, ed2); Assert.assertFalse(ed.equals(null)); Assert.assertFalse(ed.equals("aa")); Assert.assertFalse(ed.equals(ed3)); } |
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); try { minerServer.buildBlockToMine(false); refreshWork.run(); Assert.assertTrue(minerClient.mineBlock()); Assert.assertEquals(1, blockchain.getBestBlock().getNumber()); } finally { refreshWork.cancel(); } }
@Test public void refreshWorkRunTwice() { Assert.assertEquals(0, blockchain.getBestBlock().getNumber()); MinerServerImpl minerServer = getMinerServer(); MinerClientImpl minerClient = getMinerClient(minerServer); MinerClientImpl.RefreshWork refreshWork = minerClient.createRefreshWork(); Assert.assertNotNull(refreshWork); try { minerServer.buildBlockToMine( false); refreshWork.run(); Assert.assertTrue(minerClient.mineBlock()); miningMainchainView.addBest(blockchain.getBestBlock().getHeader()); minerServer.buildBlockToMine( false); refreshWork.run(); Assert.assertTrue(minerClient.mineBlock()); Assert.assertEquals(2, blockchain.getBestBlock().getNumber()); } finally { refreshWork.cancel(); } }
@Test public void mineBlockTwiceReusingTheSameWork() { Assert.assertEquals(0, blockchain.getBestBlock().getNumber()); MinerServerImpl minerServer = getMinerServer(); MinerClientImpl minerClient = getMinerClient(minerServer); minerServer.buildBlockToMine( false); MinerWork minerWork = minerServer.getWork(); Assert.assertNotNull(minerWork); Assert.assertTrue(minerClient.mineBlock()); Block bestBlock = blockchain.getBestBlock(); Assert.assertNotNull(bestBlock); Assert.assertEquals(1, bestBlock.getNumber()); Assert.assertNotNull(minerServer.getWork()); Assert.assertTrue(minerClient.mineBlock()); List<Block> blocks = blockchain.getBlocksByNumber(1); Assert.assertNotNull(blocks); Assert.assertEquals(2, blocks.size()); Assert.assertFalse(blocks.get(0).getHash().equals(blocks.get(1).getHash())); }
@Test public void mineBlockWhileSyncingBlocks() { Assert.assertEquals(0, blockchain.getBestBlock().getNumber()); NodeBlockProcessor nodeBlockProcessor = mock(NodeBlockProcessor.class); when(nodeBlockProcessor.hasBetterBlockToSync()).thenReturn(true); MinerServerImpl minerServer = getMinerServer(); MinerClientImpl minerClient = getMinerClient(nodeBlockProcessor, minerServer); minerServer.buildBlockToMine( false); Assert.assertFalse(minerClient.mineBlock()); Assert.assertEquals(0, blockchain.getBestBlock().getNumber()); }
@Test public void mineBlock() { Assert.assertEquals(0, blockchain.getBestBlock().getNumber()); MinerManager manager = new MinerManager(); MinerServerImpl minerServer = getMinerServer(); MinerClientImpl minerClient = getMinerClient(minerServer); manager.mineBlock(minerClient, minerServer); Assert.assertEquals(1, blockchain.getBestBlock().getNumber()); Assert.assertFalse(blockchain.getBestBlock().getTransactionsList().isEmpty()); SnapshotManager snapshotManager = new SnapshotManager(blockchain, blockStore, transactionPool, minerServer); snapshotManager.resetSnapshots(); Assert.assertEquals(0, blockchain.getBestBlock().getNumber()); manager.mineBlock(minerClient, minerServer); miningMainchainView.addBest(blockchain.getBestBlock().getHeader()); manager.mineBlock(minerClient, minerServer); Assert.assertEquals(2, blockchain.getBestBlock().getNumber()); snapshotManager.resetSnapshots(); Assert.assertTrue(transactionPool.getPendingTransactions().isEmpty()); manager.mineBlock(minerClient, minerServer); Assert.assertTrue(transactionPool.getPendingTransactions().isEmpty()); } |
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 getBitcoinMergedMiningCoinbaseTransaction(co.rsk.bitcoinj.core.NetworkParameters params, MinerWork work); static co.rsk.bitcoinj.core.BtcTransaction getBitcoinMergedMiningCoinbaseTransaction(co.rsk.bitcoinj.core.NetworkParameters params, byte[] blockHashForMergedMining); static co.rsk.bitcoinj.core.BtcTransaction getBitcoinMergedMiningCoinbaseTransactionWithTwoTags(
co.rsk.bitcoinj.core.NetworkParameters params,
MinerWork work,
MinerWork work2); static co.rsk.bitcoinj.core.BtcTransaction getBitcoinMergedMiningCoinbaseTransactionWithTwoTags(
co.rsk.bitcoinj.core.NetworkParameters params,
byte[] blockHashForMergedMining1,
byte[] blockHashForMergedMining2); static co.rsk.bitcoinj.core.BtcBlock getBitcoinMergedMiningBlock(co.rsk.bitcoinj.core.NetworkParameters params, BtcTransaction transaction); static co.rsk.bitcoinj.core.BtcBlock getBitcoinMergedMiningBlock(co.rsk.bitcoinj.core.NetworkParameters params, List<BtcTransaction> transactions); static byte[] buildMerkleProof(
ActivationConfig activationConfig,
Function<MerkleProofBuilder, byte[]> proofBuilderFunction,
long blockNumber); List<org.ethereum.core.Transaction> getAllTransactions(TransactionPool transactionPool); List<org.ethereum.core.Transaction> filterTransactions(List<Transaction> txsToRemove, List<Transaction> txs, Map<RskAddress, BigInteger> accountNonces, RepositorySnapshot originalRepo, Coin minGasPrice); } | @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 = ByteUtil.leftPadBytes(BigInteger.valueOf(new Random(0).nextLong()).toByteArray(), 20); Mockito.when(tx1.getHash()).thenReturn(new Keccak256(s1)); Mockito.when(tx2.getHash()).thenReturn(new Keccak256(s2)); Mockito.when(tx1.getNonce()).thenReturn(ByteUtil.cloneBytes( BigInteger.ZERO.toByteArray())); Mockito.when(tx2.getNonce()).thenReturn(ByteUtil.cloneBytes( BigInteger.TEN.toByteArray())); Mockito.when(tx1.getGasPrice()).thenReturn(Coin.valueOf(1)); Mockito.when(tx2.getGasPrice()).thenReturn(Coin.valueOf(1)); Mockito.when(tx1.getSender()).thenReturn(new RskAddress(addressBytes)); Mockito.when(tx2.getSender()).thenReturn(new RskAddress(addressBytes)); List<Transaction> txs = new LinkedList<>(); txs.add(tx1); txs.add(tx2); Mockito.when(transactionPool.getPendingTransactions()).thenReturn(txs); List<Transaction> res = new MinerUtils().getAllTransactions(transactionPool); Assert.assertEquals(2, res.size()); }
@Test public void getAllTransactionsCheckOrderTest() { TransactionPool transactionPool = Mockito.mock(TransactionPool.class); Transaction tx0 = Mockito.mock(Transaction.class); Transaction tx1 = Mockito.mock(Transaction.class); Transaction tx2 = Mockito.mock(Transaction.class); Transaction tx3 = Mockito.mock(Transaction.class); byte[] nonce0 = ByteUtil.cloneBytes( BigInteger.valueOf(0).toByteArray()); byte[] nonce1 = ByteUtil.cloneBytes( BigInteger.valueOf(1).toByteArray()); byte[] nonce2 = ByteUtil.cloneBytes( BigInteger.valueOf(2).toByteArray()); byte[] addressBytes = ByteUtil.leftPadBytes(BigInteger.valueOf(new Random(0).nextLong()).toByteArray(), 20); Mockito.when(tx0.getSender()).thenReturn(new RskAddress(addressBytes)); Mockito.when(tx0.getNonce()).thenReturn(ByteUtil.cloneBytes(nonce0)); Mockito.when(tx0.getGasPrice()).thenReturn(Coin.valueOf(10)); Mockito.when(tx1.getSender()).thenReturn(new RskAddress(addressBytes)); Mockito.when(tx1.getNonce()).thenReturn(ByteUtil.cloneBytes(nonce0)); Mockito.when(tx1.getGasPrice()).thenReturn(Coin.valueOf(1)); Mockito.when(tx2.getSender()).thenReturn(new RskAddress(addressBytes)); Mockito.when(tx2.getNonce()).thenReturn(ByteUtil.cloneBytes(nonce1)); Mockito.when(tx2.getGasPrice()).thenReturn(Coin.valueOf(10)); Mockito.when(tx3.getSender()).thenReturn(new RskAddress(addressBytes)); Mockito.when(tx3.getNonce()).thenReturn(ByteUtil.cloneBytes(nonce2)); Mockito.when(tx3.getGasPrice()).thenReturn(Coin.valueOf(100)); List<Transaction> txs = new LinkedList<>(); txs.add(tx0); txs.add(tx1); Mockito.when(transactionPool.getPendingTransactions()).thenReturn(txs); List<Transaction> res = new MinerUtils().getAllTransactions(transactionPool); Assert.assertEquals(2, res.size()); Assert.assertEquals(res.get(0).getGasPrice(), Coin.valueOf(10)); Assert.assertEquals(res.get(1).getGasPrice(), Coin.valueOf(1)); txs = new LinkedList<>(); txs.add(tx3); txs.add(tx1); txs.add(tx2); Mockito.when(transactionPool.getPendingTransactions()).thenReturn(txs); res = new MinerUtils().getAllTransactions(transactionPool); Assert.assertEquals(3, res.size()); Assert.assertEquals(res.get(0).getNonce(), tx1.getNonce()); Assert.assertEquals(res.get(1).getNonce(), tx2.getNonce()); Assert.assertEquals(res.get(2).getNonce(), tx3.getNonce()); Assert.assertEquals(res.get(0).getGasPrice(), Coin.valueOf(1)); Assert.assertEquals(res.get(1).getGasPrice(), Coin.valueOf(10)); Assert.assertEquals(res.get(2).getGasPrice(), Coin.valueOf(100)); Transaction tx4 = Mockito.mock(Transaction.class); Transaction tx5 = Mockito.mock(Transaction.class); Transaction tx6 = Mockito.mock(Transaction.class); byte[] addressBytes2 = ByteUtil.leftPadBytes(BigInteger.valueOf(new Random(100).nextLong()).toByteArray(), 20); Mockito.when(tx4.getSender()).thenReturn(new RskAddress(addressBytes2)); Mockito.when(tx4.getNonce()).thenReturn(ByteUtil.cloneBytes(nonce0)); Mockito.when(tx4.getGasPrice()).thenReturn(Coin.valueOf(50)); Mockito.when(tx5.getSender()).thenReturn(new RskAddress(addressBytes2)); Mockito.when(tx5.getNonce()).thenReturn(ByteUtil.cloneBytes(nonce1)); Mockito.when(tx5.getGasPrice()).thenReturn(Coin.valueOf(1000)); Mockito.when(tx6.getSender()).thenReturn(new RskAddress(addressBytes2)); Mockito.when(tx6.getNonce()).thenReturn(ByteUtil.cloneBytes(nonce2)); Mockito.when(tx6.getGasPrice()).thenReturn(Coin.valueOf(1)); txs.add(tx6); txs.add(tx5); txs.add(tx4); Mockito.when(transactionPool.getPendingTransactions()).thenReturn(txs); res = new MinerUtils().getAllTransactions(transactionPool); Assert.assertEquals(6, res.size()); Assert.assertEquals(res.get(0).getGasPrice(), Coin.valueOf(50)); Assert.assertEquals(res.get(1).getGasPrice(), Coin.valueOf(1000)); Assert.assertEquals(res.get(2).getGasPrice(), Coin.valueOf(1)); Assert.assertEquals(res.get(3).getGasPrice(), Coin.valueOf(10)); Assert.assertEquals(res.get(4).getGasPrice(), Coin.valueOf(100)); Assert.assertEquals(res.get(5).getGasPrice(), Coin.valueOf(1)); Transaction tx7 = Mockito.mock(Transaction.class); Transaction tx8 = Mockito.mock(Transaction.class); Transaction tx9 = Mockito.mock(Transaction.class); byte[] addressBytes3 = ByteUtil.leftPadBytes(BigInteger.valueOf(new Random(1000).nextLong()).toByteArray(), 20); Mockito.when(tx7.getSender()).thenReturn(new RskAddress(addressBytes3)); Mockito.when(tx7.getNonce()).thenReturn(ByteUtil.cloneBytes(nonce0)); Mockito.when(tx7.getGasPrice()).thenReturn(Coin.valueOf(500)); Mockito.when(tx8.getSender()).thenReturn(new RskAddress(addressBytes3)); Mockito.when(tx8.getNonce()).thenReturn(ByteUtil.cloneBytes(nonce1)); Mockito.when(tx8.getGasPrice()).thenReturn(Coin.valueOf(500)); Mockito.when(tx9.getSender()).thenReturn(new RskAddress(addressBytes3)); Mockito.when(tx9.getNonce()).thenReturn(ByteUtil.cloneBytes(nonce2)); Mockito.when(tx9.getGasPrice()).thenReturn(Coin.valueOf(2000)); txs.add(tx7); txs.add(tx8); txs.add(tx9); Mockito.when(transactionPool.getPendingTransactions()).thenReturn(txs); res = new MinerUtils().getAllTransactions(transactionPool); Assert.assertEquals(9, res.size()); Assert.assertEquals(res.get(0).getGasPrice(), Coin.valueOf(500)); Assert.assertEquals(res.get(1).getGasPrice(), Coin.valueOf(500)); Assert.assertEquals(res.get(2).getGasPrice(), Coin.valueOf(2000)); Assert.assertEquals(res.get(3).getGasPrice(), Coin.valueOf(50)); Assert.assertEquals(res.get(4).getGasPrice(), Coin.valueOf(1000)); Assert.assertEquals(res.get(5).getGasPrice(), Coin.valueOf(1)); Assert.assertEquals(res.get(6).getGasPrice(), Coin.valueOf(10)); Assert.assertEquals(res.get(7).getGasPrice(), Coin.valueOf(100)); Assert.assertEquals(res.get(8).getGasPrice(), Coin.valueOf(1)); } |
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.Transaction tx : txs) { try { Keccak256 hash = tx.getHash(); Coin txValue = tx.getValue(); BigInteger txNonce = new BigInteger(1, tx.getNonce()); RskAddress txSender = tx.getSender(); logger.debug("Examining tx={} sender: {} value: {} nonce: {}", hash, txSender, txValue, txNonce); BigInteger expectedNonce; if (accountNonces.containsKey(txSender)) { expectedNonce = accountNonces.get(txSender).add(BigInteger.ONE); } else { expectedNonce = originalRepo.getNonce(txSender); } if (!(tx instanceof RemascTransaction) && tx.getGasPrice().compareTo(minGasPrice) < 0) { logger.warn("Rejected tx={} because of low gas account {}, removing tx from pending state.", hash, txSender); txsToRemove.add(tx); continue; } if (!expectedNonce.equals(txNonce)) { logger.warn("Invalid nonce, expected {}, found {}, tx={}", expectedNonce, txNonce, hash); continue; } accountNonces.put(txSender, txNonce); logger.debug("Accepted tx={} sender: {} value: {} nonce: {}", hash, txSender, txValue, txNonce); } catch (Exception e) { logger.warn(String.format("Error when processing tx=%s", tx.getHash()), e); if (txsToRemove != null) { txsToRemove.add(tx); } else { logger.error("Can't remove invalid txs from pending state."); } continue; } txsResult.add(tx); } logger.debug("Ending getTransactions {}", txsResult.size()); return txsResult; } static co.rsk.bitcoinj.core.BtcTransaction getBitcoinMergedMiningCoinbaseTransaction(co.rsk.bitcoinj.core.NetworkParameters params, MinerWork work); static co.rsk.bitcoinj.core.BtcTransaction getBitcoinMergedMiningCoinbaseTransaction(co.rsk.bitcoinj.core.NetworkParameters params, byte[] blockHashForMergedMining); static co.rsk.bitcoinj.core.BtcTransaction getBitcoinMergedMiningCoinbaseTransactionWithTwoTags(
co.rsk.bitcoinj.core.NetworkParameters params,
MinerWork work,
MinerWork work2); static co.rsk.bitcoinj.core.BtcTransaction getBitcoinMergedMiningCoinbaseTransactionWithTwoTags(
co.rsk.bitcoinj.core.NetworkParameters params,
byte[] blockHashForMergedMining1,
byte[] blockHashForMergedMining2); static co.rsk.bitcoinj.core.BtcBlock getBitcoinMergedMiningBlock(co.rsk.bitcoinj.core.NetworkParameters params, BtcTransaction transaction); static co.rsk.bitcoinj.core.BtcBlock getBitcoinMergedMiningBlock(co.rsk.bitcoinj.core.NetworkParameters params, List<BtcTransaction> transactions); static byte[] buildMerkleProof(
ActivationConfig activationConfig,
Function<MerkleProofBuilder, byte[]> proofBuilderFunction,
long blockNumber); List<org.ethereum.core.Transaction> getAllTransactions(TransactionPool transactionPool); List<org.ethereum.core.Transaction> filterTransactions(List<Transaction> txsToRemove, List<Transaction> txs, Map<RskAddress, BigInteger> accountNonces, RepositorySnapshot originalRepo, Coin minGasPrice); } | @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.getNonce(tx.getSender())).thenReturn(BigInteger.valueOf(0)); Coin minGasPrice = Coin.valueOf(1L); List<Transaction> res = new MinerUtils().filterTransactions(new LinkedList<>(), txs, accountNounces, repository, minGasPrice); Assert.assertEquals(1, res.size()); }
@Test public void validTransactionAccWrapNonceTest() { Transaction tx = Tx.create(config, 0, 50000, 5, 1, 0, 0); List<Transaction> txs = new LinkedList<>(); txs.add(tx); Map<RskAddress, BigInteger> accountNounces = new HashMap(); accountNounces.put(tx.getSender(), BigInteger.valueOf(0)); Repository repository = Mockito.mock(Repository.class); Coin minGasPrice = Coin.valueOf(1L); List<Transaction> res = new MinerUtils().filterTransactions(new LinkedList<>(), txs, accountNounces, repository, minGasPrice); Assert.assertEquals(1, res.size()); }
@Test public void invalidNonceTransactionTest() { Transaction tx = Tx.create(config, 0, 50000, 2, 0, 0, 0); List<Transaction> txs = new LinkedList<>(); txs.add(tx); Map<RskAddress, BigInteger> accountNounces = new HashMap(); accountNounces.put(tx.getSender(), BigInteger.valueOf(0)); Repository repository = Mockito.mock(Repository.class); Coin minGasPrice = Coin.valueOf(1L); List<Transaction> txsToRemove = new LinkedList<>(); List<Transaction> res = new MinerUtils().filterTransactions(txsToRemove, txs, accountNounces, repository, minGasPrice); Assert.assertEquals(0, res.size()); Assert.assertEquals(0, txsToRemove.size()); }
@Test public void invalidGasPriceTransactionTest() { Transaction tx = Tx.create(config, 0, 50000, 1, 0, 0, 0); List<Transaction> txs = new LinkedList<>(); txs.add(tx); Map<RskAddress, BigInteger> accountNounces = new HashMap(); byte[] addressBytes = ByteUtil.leftPadBytes(BigInteger.valueOf(new Random(0).nextLong()).toByteArray(), 20); accountNounces.put(new RskAddress(addressBytes), BigInteger.valueOf(0)); Repository repository = Mockito.mock(Repository.class); Coin minGasPrice = Coin.valueOf(2L); LinkedList<Transaction> txsToRemove = new LinkedList<>(); List<Transaction> res = new MinerUtils().filterTransactions(txsToRemove, txs, accountNounces, repository, minGasPrice); Assert.assertEquals(0, res.size()); Assert.assertEquals(1, txsToRemove.size()); }
@Test public void harmfulTransactionTest() { Transaction tx = Tx.create(config, 0, 50000, 1, 0, 0, 0); List<Transaction> txs = new LinkedList<>(); txs.add(tx); Mockito.when(tx.getGasPrice()).thenReturn(null); Map<RskAddress, BigInteger> accountNounces = new HashMap(); byte[] addressBytes = ByteUtil.leftPadBytes(BigInteger.valueOf(new Random(0).nextLong()).toByteArray(), 20); accountNounces.put(new RskAddress(addressBytes), BigInteger.valueOf(0)); Repository repository = Mockito.mock(Repository.class); Coin minGasPrice = Coin.valueOf(2L); LinkedList<Transaction> txsToRemove = new LinkedList<>(); List<Transaction> res = new MinerUtils().filterTransactions(txsToRemove, txs, accountNounces, repository, minGasPrice); Assert.assertEquals(0, res.size()); Assert.assertEquals(1, txsToRemove.size()); } |
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.getUncleGenerationLimit() ); if (uncles.size() > miningConfig.getUncleListLimit()) { uncles = uncles.subList(0, miningConfig.getUncleListLimit()); } Coin minimumGasPrice = minimumGasPriceCalculator.calculate(newBlockParentHeader.getMinimumGasPrice()); final List<Transaction> txsToRemove = new ArrayList<>(); final List<Transaction> txs = getTransactions(txsToRemove, newBlockParentHeader, minimumGasPrice); final Block newBlock = createBlock(mainchainHeaders, uncles, txs, minimumGasPrice, extraData); removePendingTransactions(txsToRemove); return executor.executeAndFill(newBlock, newBlockParentHeader); } BlockToMineBuilder(
ActivationConfig activationConfig,
MiningConfig miningConfig,
RepositoryLocator repositoryLocator,
BlockStore blockStore,
TransactionPool transactionPool,
DifficultyCalculator difficultyCalculator,
GasLimitCalculator gasLimitCalculator,
ForkDetectionDataCalculator forkDetectionDataCalculator,
BlockValidationRule validationRules,
MinerClock clock,
BlockFactory blockFactory,
BlockExecutor blockExecutor,
MinimumGasPriceCalculator minimumGasPriceCalculator,
MinerUtils minerUtils); BlockResult build(List<BlockHeader> mainchainHeaders, byte[] extraData); @VisibleForTesting Block createBlock(
List<BlockHeader> mainchainHeaders,
List<BlockHeader> uncles,
List<Transaction> txs,
Coin minimumGasPrice,
byte[] extraData); } | @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(blockExecutor.executeAndFill(blockCaptor.capture(), any())).thenReturn(expectedResult); blockBuilder.build(new ArrayList<>(Collections.singletonList(parent)), new byte[0]); assertThat(blockCaptor.getValue().getUncleList(), empty()); }
@Test public void BuildBlockHasUnclesWhenCreateAnInvalidBlock() { BlockHeader parent = buildBlockHeaderWithSibling(); BlockResult expectedResult = mock(BlockResult.class); ArgumentCaptor<Block> blockCaptor = ArgumentCaptor.forClass(Block.class); when(validationRules.isValid(any())).thenReturn(true); when(blockExecutor.executeAndFill(blockCaptor.capture(), any())).thenReturn(expectedResult); blockBuilder.build(new ArrayList<>(Collections.singletonList(parent)), new byte[0]); assertThat(blockCaptor.getValue().getUncleList(), hasSize(1)); }
@Test public void buildBlockBeforeUMMActivation() { Keccak256 parentHash = TestUtils.randomHash(); BlockHeader parent = mock(BlockHeader.class); when(parent.getNumber()).thenReturn(500L); when(parent.getHash()).thenReturn(parentHash); when(parent.getGasLimit()).thenReturn(new byte[0]); when(parent.getMinimumGasPrice()).thenReturn(mock(Coin.class)); when(validationRules.isValid(any())).thenReturn(true); when(activationConfig.isActive(ConsensusRule.RSKIPUMM, 501L)).thenReturn(false); BlockResult expectedResult = mock(BlockResult.class); ArgumentCaptor<Block> blockCaptor = ArgumentCaptor.forClass(Block.class); when(blockExecutor.executeAndFill(blockCaptor.capture(), any())).thenReturn(expectedResult); blockBuilder.build(new ArrayList<>(Collections.singletonList(parent)), new byte[0]); Block actualBlock = blockCaptor.getValue(); assertNull(actualBlock.getHeader().getUmmRoot()); }
@Test public void buildBlockAfterUMMActivation() { Keccak256 parentHash = TestUtils.randomHash(); BlockHeader parent = mock(BlockHeader.class); when(parent.getNumber()).thenReturn(500L); when(parent.getHash()).thenReturn(parentHash); when(parent.getGasLimit()).thenReturn(new byte[0]); when(parent.getMinimumGasPrice()).thenReturn(mock(Coin.class)); when(validationRules.isValid(any())).thenReturn(true); when(activationConfig.isActive(ConsensusRule.RSKIPUMM, 501L)).thenReturn(true); BlockResult expectedResult = mock(BlockResult.class); ArgumentCaptor<Block> blockCaptor = ArgumentCaptor.forClass(Block.class); when(blockExecutor.executeAndFill(blockCaptor.capture(), any())).thenReturn(expectedResult); blockBuilder.build(new ArrayList<>(Collections.singletonList(parent)), new byte[0]); Block actualBlock = blockCaptor.getValue(); assertThat(actualBlock.getHeader().getUmmRoot(), is(new byte[0])); } |
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.getGasLimitBoundDivisor())); if (targetGasLimit.compareTo(minGasLimit) < 0) { targetGasLimit = minGasLimit; } if (forceTarget) { if (targetGasLimit.compareTo(parentGasLimit) < 0) { newGasLimit = newGasLimit.subtract(deltaMax); if (targetGasLimit.compareTo(newGasLimit) > 0) { newGasLimit = targetGasLimit; } return newGasLimit; } else { newGasLimit = newGasLimit.add(deltaMax); if (targetGasLimit.compareTo(newGasLimit) < 0) { newGasLimit = targetGasLimit; } return newGasLimit; } } BigInteger contrib = parentGasUsed.multiply(BigInteger.valueOf(3)); contrib = contrib.divide(BigInteger.valueOf(2)); contrib = contrib.divide(BigInteger.valueOf(constants.getGasLimitBoundDivisor())); newGasLimit = newGasLimit.subtract(deltaMax); newGasLimit = newGasLimit.add(contrib); if (newGasLimit.compareTo(minGasLimit) < 0) { newGasLimit = minGasLimit; } if (newGasLimit.compareTo(targetGasLimit) > 0) { newGasLimit = targetGasLimit; } if (newGasLimit.compareTo(parentGasLimit.subtract(deltaMax)) < 0) { newGasLimit = parentGasLimit; } if (newGasLimit.compareTo(parentGasLimit.add(deltaMax)) > 0) { newGasLimit = parentGasLimit; } return newGasLimit; } GasLimitCalculator(Constants networkConstants); BigInteger calculateBlockGasLimit(BigInteger parentGasLimit, BigInteger parentGasUsed, BigInteger minGasLimit, BigInteger targetGasLimit, boolean forceTarget); } | @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 = BigInteger.valueOf(config.getTargetGasLimit()); BigInteger newGasLimit = calc.calculateBlockGasLimit(parentGasLimit, BigInteger.ZERO, minGasLimit, targetGasLimit, false); BigInteger factor = parentGasLimit.divide(BigInteger.valueOf(constants.getGasLimitBoundDivisor())); Assert.assertTrue(newGasLimit.compareTo(parentGasLimit) < 0); Assert.assertTrue(newGasLimit.compareTo(parentGasLimit.subtract(factor)) == 0); }
@Test public void NextBlockGasLimitIsNotDecreasedLowerThanMinGasLimit() { GasLimitCalculator calc = new GasLimitCalculator(config.getNetworkConstants()); BigInteger minGasLimit = BigInteger.valueOf(constants.getMinGasLimit()); BigInteger targetGasLimit = BigInteger.valueOf(config.getTargetGasLimit()); BigInteger newGasLimit = calc.calculateBlockGasLimit(minGasLimit, BigInteger.ZERO, minGasLimit, targetGasLimit, false); Assert.assertTrue(newGasLimit.compareTo(minGasLimit) == 0); }
@Test public void NextBlockGasLimitIsIncreasedBasedOnGasUsed() { GasLimitCalculator calc = new GasLimitCalculator(config.getNetworkConstants()); BigInteger parentGas = BigInteger.valueOf(3500000); BigInteger gasUsed = BigInteger.valueOf(3000000); BigInteger targetGasLimit = BigInteger.valueOf(config.getTargetGasLimit()); BigInteger newGasLimit = calc.calculateBlockGasLimit(parentGas, gasUsed, BigInteger.ZERO, targetGasLimit, false); BigInteger expected = BigInteger.valueOf(3500977); Assert.assertTrue(newGasLimit.compareTo(expected) == 0); }
@Test public void NextBlockGasLimitIsIncreasedBasedOnFullGasUsed() { GasLimitCalculator calc = new GasLimitCalculator(config.getNetworkConstants()); BigInteger parentGas = BigInteger.valueOf(3500000); BigInteger gasUsed = BigInteger.valueOf(3500000); BigInteger targetGasLimit = BigInteger.valueOf(config.getTargetGasLimit()); BigInteger newGasLimit = calc.calculateBlockGasLimit(parentGas, gasUsed, BigInteger.ZERO, targetGasLimit, false); BigInteger expected = BigInteger.valueOf(3501709); Assert.assertTrue(newGasLimit.compareTo(expected) == 0); }
@Test public void NextBlockGasLimitIsNotIncreasedMoreThanTargetGasLimit() { GasLimitCalculator calc = new GasLimitCalculator(config.getNetworkConstants()); BigInteger targetGasLimit = BigInteger.valueOf(config.getTargetGasLimit()); BigInteger gasUsed = targetGasLimit; BigInteger newGasLimit = calc.calculateBlockGasLimit(targetGasLimit, gasUsed, BigInteger.ZERO, targetGasLimit, false); Assert.assertTrue(newGasLimit.compareTo(targetGasLimit) == 0); }
@Test public void NextBlockGasLimitRemainsTheSame() { GasLimitCalculator calc = new GasLimitCalculator(config.getNetworkConstants()); BigInteger minGasLimit = BigInteger.valueOf(config.getTargetGasLimit()); BigInteger targetGasLimit = BigInteger.valueOf(config.getTargetGasLimit()); BigInteger newGasLimit = calc.calculateBlockGasLimit(targetGasLimit, BigInteger.ZERO, minGasLimit, targetGasLimit, true); Assert.assertTrue(newGasLimit.compareTo(targetGasLimit) == 0); Assert.assertTrue(validByConsensus(newGasLimit, targetGasLimit)); }
@Test public void NextBlockGasLimitIsIncreasedByMaximumValue() { GasLimitCalculator calc = new GasLimitCalculator(config.getNetworkConstants()); BigInteger minGasLimit = BigInteger.valueOf(constants.getMinGasLimit()); BigInteger targetGasLimit = BigInteger.valueOf(config.getTargetGasLimit()); BigInteger newGasLimit = calc.calculateBlockGasLimit(minGasLimit, BigInteger.ZERO, minGasLimit, targetGasLimit, true); BigInteger newGasLimit2 = calc.calculateBlockGasLimit(minGasLimit, minGasLimit, minGasLimit, targetGasLimit, true); Assert.assertTrue(newGasLimit.compareTo(newGasLimit2) == 0); Assert.assertTrue(newGasLimit.compareTo(minGasLimit.add(minGasLimit.divide(BigInteger.valueOf(1024)))) == 0); Assert.assertTrue(validByConsensus(newGasLimit, minGasLimit)); Assert.assertTrue(validByConsensus(newGasLimit2, minGasLimit)); Assert.assertFalse(validByConsensus(newGasLimit.add(BigInteger.ONE), minGasLimit)); }
@Test public void NextBlockGasLimitIsIncreasedToTarget() { GasLimitCalculator calc = new GasLimitCalculator(config.getNetworkConstants()); BigInteger minGasLimit = BigInteger.valueOf(constants.getMinGasLimit()); BigInteger targetGasLimit = minGasLimit.add(BigInteger.ONE); BigInteger newGasLimit = calc.calculateBlockGasLimit(minGasLimit, BigInteger.ZERO, minGasLimit, targetGasLimit, true); BigInteger newGasLimit2 = calc.calculateBlockGasLimit(minGasLimit, minGasLimit, minGasLimit, targetGasLimit, true); Assert.assertTrue(newGasLimit.compareTo(targetGasLimit) == 0); Assert.assertTrue(newGasLimit.compareTo(newGasLimit2) == 0); Assert.assertTrue(validByConsensus(newGasLimit, minGasLimit)); Assert.assertTrue(validByConsensus(newGasLimit2, minGasLimit)); }
@Test public void NextBlockGasLimitIsDecreasedToTarget() { GasLimitCalculator calc = new GasLimitCalculator(config.getNetworkConstants()); BigInteger minGasLimit = BigInteger.valueOf(constants.getMinGasLimit()); BigInteger targetGasLimit = minGasLimit.add(BigInteger.ONE); BigInteger usedGas = targetGasLimit.add(BigInteger.ONE); BigInteger newGasLimit = calc.calculateBlockGasLimit(usedGas, usedGas, minGasLimit, targetGasLimit, true); BigInteger newGasLimit2 = calc.calculateBlockGasLimit(usedGas, BigInteger.ZERO, minGasLimit, targetGasLimit, true); Assert.assertTrue(newGasLimit.compareTo(targetGasLimit) == 0); Assert.assertTrue(newGasLimit.compareTo(newGasLimit2) == 0); Assert.assertTrue(validByConsensus(newGasLimit, usedGas)); Assert.assertTrue(validByConsensus(newGasLimit2, usedGas)); }
@Test public void NextBlockGasLimitIsDecreasedToMinimum() { GasLimitCalculator calc = new GasLimitCalculator(config.getNetworkConstants()); BigInteger minGasLimit = BigInteger.valueOf(constants.getMinGasLimit()); BigInteger targetGasLimit = minGasLimit.subtract(BigInteger.ONE); BigInteger usedGas = minGasLimit.add(BigInteger.ONE); BigInteger newGasLimit = calc.calculateBlockGasLimit(usedGas, usedGas, minGasLimit, targetGasLimit, true); BigInteger newGasLimit2 = calc.calculateBlockGasLimit(usedGas, BigInteger.ZERO, minGasLimit, targetGasLimit, true); Assert.assertTrue(newGasLimit.compareTo(minGasLimit) == 0); Assert.assertTrue(newGasLimit.compareTo(newGasLimit2) == 0); Assert.assertTrue(validByConsensus(newGasLimit, usedGas)); Assert.assertTrue(validByConsensus(newGasLimit2, usedGas)); }
@Test public void NextBlockGasLimitIsDecreasedByMaximumValue() { GasLimitCalculator calc = new GasLimitCalculator(config.getNetworkConstants()); BigInteger minGasLimit = BigInteger.valueOf(constants.getMinGasLimit()); BigInteger targetGasLimit = BigInteger.valueOf(config.getTargetGasLimit()); BigInteger usedGas = targetGasLimit.multiply(BigInteger.valueOf(2)); BigInteger newGasLimit = calc.calculateBlockGasLimit(usedGas, BigInteger.ZERO, minGasLimit, targetGasLimit, true); BigInteger newGasLimit2 = calc.calculateBlockGasLimit(usedGas, usedGas, minGasLimit, targetGasLimit, true); Assert.assertTrue(newGasLimit.compareTo(newGasLimit2) == 0); Assert.assertTrue(newGasLimit.compareTo(usedGas.subtract(usedGas.divide(BigInteger.valueOf(1024)))) == 0); Assert.assertTrue(validByConsensus(newGasLimit, usedGas)); Assert.assertTrue(validByConsensus(newGasLimit2, usedGas)); Assert.assertFalse(validByConsensus(newGasLimit.subtract(BigInteger.ONE), usedGas)); } |
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); @Override void newBlockReceived(Block b); @Override void newPendingTx(Transaction tx); static LogFilter fromFilterRequest(Web3.FilterRequest fr, Blockchain blockchain, BlocksBloomStore blocksBloomStore); } | @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 eventAfterBlockWithEvent() { RskTestFactory factory = new RskTestFactory(); Blockchain blockchain = factory.getBlockchain(); BlockStore blockStore = factory.getBlockStore(); RepositoryLocator repositoryLocator = factory.getRepositoryLocator(); Web3ImplLogsTest.addEmptyBlockToBlockchain(blockchain, blockStore, repositoryLocator, factory.getTrieStore()); Block block = blockchain.getBestBlock(); AddressesTopicsFilter atfilter = new AddressesTopicsFilter(new RskAddress[0], null); LogFilter filter = new LogFilter(atfilter, blockchain, false, true); filter.newBlockReceived(block); Object[] result = filter.getEvents(); Assert.assertNotNull(result); Assert.assertEquals(1, result.length); }
@Test public void twoEventsAfterTwoBlocksWithEventAndToLatestBlock() { RskTestFactory factory = new RskTestFactory(); Blockchain blockchain = factory.getBlockchain(); BlockStore blockStore = factory.getBlockStore(); RepositoryLocator repositoryLocator = factory.getRepositoryLocator(); Web3ImplLogsTest.addEmptyBlockToBlockchain(blockchain, blockStore, repositoryLocator, factory.getTrieStore()); Block block = blockchain.getBestBlock(); AddressesTopicsFilter atfilter = new AddressesTopicsFilter(new RskAddress[0], null); LogFilter filter = new LogFilter(atfilter, blockchain, false, true); filter.newBlockReceived(block); filter.newBlockReceived(block); Object[] result = filter.getEvents(); Assert.assertNotNull(result); Assert.assertEquals(2, result.length); }
@Test public void onlyOneEventAfterTwoBlocksWithEventAndFromLatestBlock() { RskTestFactory factory = new RskTestFactory(); Blockchain blockchain = factory.getBlockchain(); BlockStore blockStore = factory.getBlockStore(); RepositoryLocator repositoryLocator = factory.getRepositoryLocator(); Web3ImplLogsTest.addEmptyBlockToBlockchain(blockchain, blockStore, repositoryLocator, factory.getTrieStore()); Block block = blockchain.getBestBlock(); AddressesTopicsFilter atfilter = new AddressesTopicsFilter(new RskAddress[0], null); LogFilter filter = new LogFilter(atfilter, blockchain, true, true); filter.newBlockReceived(block); filter.newBlockReceived(block); Object[] result = filter.getEvents(); Assert.assertNotNull(result); Assert.assertEquals(1, result.length); } |
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(); byte[] getValue(); byte[] getData(); RskAddress getFromAddress(); } | @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 Exception { Web3.CallArguments args = new Web3.CallArguments(); args.value = ""; CallArgumentsToByteArray byteArrayArgs = new CallArgumentsToByteArray(args); Assert.assertArrayEquals(new byte[] {0}, byteArrayArgs.getValue()); } |
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); } MinerClock(boolean isFixedClock, Clock clock); long calculateTimestampForChild(BlockHeader parentHeader); long increaseTime(long seconds); void clearIncreaseTime(); } | @Test public void timestampForChildIsParentTimestampIfRegtest() { MinerClock minerClock = new MinerClock(true, clock); BlockHeader parent = mockBlockHeaderWithTimestamp(54L); assertEquals( 54L, minerClock.calculateTimestampForChild(parent) ); }
@Test public void timestampForChildIsClockTimeIfNotRegtest() { MinerClock minerClock = new MinerClock(false, clock); BlockHeader parent = mockBlockHeaderWithTimestamp(54L); assertEquals( clock.instant().getEpochSecond(), minerClock.calculateTimestampForChild(parent) ); }
@Test public void timestampForChildIsTimestampPlusOneIfNotRegtest() { MinerClock minerClock = new MinerClock(false, clock); BlockHeader parent = mockBlockHeaderWithTimestamp(clock.instant().getEpochSecond()); assertEquals( clock.instant().getEpochSecond() + 1, minerClock.calculateTimestampForChild(parent) ); } |
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(); } MinimumGasPriceCalculator(Coin targetMGP); Coin calculate(Coin previousMGP); } | @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 = Coin.valueOf(1000L); Coin target = Coin.valueOf(900L); MinimumGasPriceCalculator mgpCalculator = new MinimumGasPriceCalculator(target); Coin mgp = mgpCalculator.calculate(prev); Assert.assertEquals(Coin.valueOf(990), mgp); }
@Test public void mgpOnRage() { Coin prev = Coin.valueOf(1000L); Coin target = Coin.valueOf(995L); MinimumGasPriceCalculator mgpCalculator = new MinimumGasPriceCalculator(target); Coin mgp = mgpCalculator.calculate(prev); Assert.assertEquals(target, mgp); }
@Test public void previousMgpEqualsTarget() { Coin prev = Coin.valueOf(1000L); Coin target = Coin.valueOf(1000L); MinimumGasPriceCalculator mgpCalculator = new MinimumGasPriceCalculator(target); Coin mgp = mgpCalculator.calculate(prev); Assert.assertEquals(target, mgp); }
@Test public void previousValueIsZero() { Coin target = Coin.valueOf(1000L); MinimumGasPriceCalculator mgpCalculator = new MinimumGasPriceCalculator(target); Coin mgp = mgpCalculator.calculate(Coin.ZERO); Assert.assertEquals(Coin.valueOf(1L), mgp); }
@Test public void previousValueIsSmallTargetIsZero() { Coin target = Coin.ZERO; MinimumGasPriceCalculator mgpCalculator = new MinimumGasPriceCalculator(target); Coin mgp = mgpCalculator.calculate(Coin.valueOf(1L)); Assert.assertEquals(Coin.ZERO, mgp); }
@Test public void cantGetMGPtoBeNegative() { Coin previous = Coin.ZERO; Coin target = Coin.valueOf(-100L); MinimumGasPriceCalculator mgpCalculator = new MinimumGasPriceCalculator(target); previous = mgpCalculator.calculate(previous); Assert.assertTrue(previous.compareTo(Coin.valueOf(-1)) > 0); } |
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(Duration period); } | @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.getCumulativeDifficulty()).thenReturn(TEST_DIFFICULTY); HashRateCalculator hashRateCalculator = new HashRateCalculatorMining(blockStore, new RskCustomCache<>(1000L), FAKE_COINBASE); BigInteger hashRate = hashRateCalculator.calculateNodeHashRate(Duration.ofHours(1)); Assert.assertEquals(new BigInteger("+2"), hashRate); }
@Test public void calculateNodeHashRateWithMiningDisabled() { 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.getCumulativeDifficulty()).thenReturn(TEST_DIFFICULTY); HashRateCalculator hashRateCalculator = new HashRateCalculatorNonMining(blockStore, new RskCustomCache<>(1000L)); BigInteger hashRate = hashRateCalculator.calculateNodeHashRate(Duration.ofHours(1)); Assert.assertEquals(BigInteger.ZERO, hashRate); }
@Test public void calculateNodeHashRateOldBlock() { long ts = System.currentTimeMillis() / 1000L; Mockito.when(blockHeader.getTimestamp()) .thenReturn(ts - 10000L); Mockito.when(blockHeader.getCoinbase()).thenReturn(FAKE_COINBASE); Mockito.when(block.getCumulativeDifficulty()).thenReturn(TEST_DIFFICULTY); HashRateCalculator hashRateCalculator = new HashRateCalculatorMining(blockStore, new RskCustomCache<>(1000L), FAKE_COINBASE); BigInteger hashRate = hashRateCalculator.calculateNodeHashRate(Duration.ofHours(1)); Assert.assertEquals(hashRate, BigInteger.ZERO); } |
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); BigInteger calculateNetHashRate(Duration period); } | @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.getCumulativeDifficulty()).thenReturn(TEST_DIFFICULTY); HashRateCalculator hashRateCalculator = new HashRateCalculatorMining(blockStore, new RskCustomCache<>(1000L), FAKE_COINBASE); BigInteger hashRate = hashRateCalculator.calculateNetHashRate(Duration.ofHours(1)); Assert.assertEquals(hashRate, new BigInteger("+4")); }
@Test public void calculateNetHashRateOldBlock() { long ts = System.currentTimeMillis() / 1000L; Mockito.when(blockHeader.getTimestamp()) .thenReturn(ts - 10000L); Mockito.when(blockHeader.getCoinbase()).thenReturn(FAKE_COINBASE); Mockito.when(block.getCumulativeDifficulty()).thenReturn(TEST_DIFFICULTY); HashRateCalculator hashRateCalculator = new HashRateCalculatorMining(blockStore, new RskCustomCache<>(1000L), FAKE_COINBASE); BigInteger hashRate = hashRateCalculator.calculateNetHashRate(Duration.ofHours(1)); Assert.assertEquals(hashRate, BigInteger.ZERO); } |
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(@Nullable byte[] array); static byte[] nullToEmpty(@Nullable byte[] array); static int lastIndexOfSubList(byte[] source, byte[] target); } | @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(@Nullable byte[] array); static int lastIndexOfSubList(byte[] source, byte[] target); } | @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 byte[] nullToEmpty(@Nullable byte[] array); static int lastIndexOfSubList(byte[] source, byte[] target); } | @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[] nullToEmpty(@Nullable byte[] array); static int lastIndexOfSubList(byte[] source, byte[] target); } | @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--) { boolean found = true; for (int j = 0; j < target.length; j++) { if (source[i + j] != target[j]) { found = false; break; } } if (found) { return i; } } return -1; } private ListArrayUtil(); static List<Byte> asByteList(byte[] primitiveByteArray); static boolean isEmpty(@Nullable byte[] array); static int getLength(@Nullable byte[] array); static byte[] nullToEmpty(@Nullable byte[] array); static int lastIndexOfSubList(byte[] source, byte[] target); } | @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[] target = new byte[] { }; int res = ListArrayUtil.lastIndexOfSubList(source, target); Assert.assertEquals(5, res); }
@Test public void testLastIndexOfSublistFindsMatch1() { byte[] source = new byte[] { 1, 2, 3, 4, 5 }; byte[] target = new byte[] { 3, 4 }; int res = ListArrayUtil.lastIndexOfSubList(source, target); Assert.assertEquals(2, res); }
@Test public void testLastIndexOfSublistFindsMatch2() { byte[] source = new byte[] { 1, 2, 3, 4, 5 }; byte[] target = new byte[] { 4, 5 }; int res = ListArrayUtil.lastIndexOfSubList(source, target); Assert.assertEquals(3, res); }
@Test public void testLastIndexOfSublistSameArray() { byte[] source = new byte[] { 1, 2, 3, 4, 5 }; byte[] target = new byte[] { 1, 2, 3, 4, 5 }; int res = ListArrayUtil.lastIndexOfSubList(source, target); Assert.assertEquals(0, res); }
@Test public void testLastIndexOfSublistTargetLongerThanSource() { byte[] source = new byte[] { 1, 2, 3, 4, 5 }; byte[] target = new byte[] { 1, 2, 3, 4, 5, 6 }; int res = ListArrayUtil.lastIndexOfSubList(source, target); Assert.assertEquals(-1, res); }
@Test public void testLastIndexOfSublistPartialOverlapOnBeginning() { byte[] source = new byte[] { 1, 2, 3, 4, 5 }; byte[] target = new byte[] { 0, 1, 2 }; int res = ListArrayUtil.lastIndexOfSubList(source, target); Assert.assertEquals(-1, res); }
@Test public void testLastIndexOfSublistPartialOverlapOnEnd() { byte[] source = new byte[] { 1, 2, 3, 4, 5 }; byte[] target = new byte[] { 4, 5, 6 }; int res = ListArrayUtil.lastIndexOfSubList(source, target); Assert.assertEquals(-1, res); }
@Test public void testLastIndexOfSublist6ArraysWithNoSharedElements() { byte[] source = new byte[] { 1, 2, 3, 4, 5 }; byte[] target = new byte[] { 6, 7, 8, 9, 10 }; int res = ListArrayUtil.lastIndexOfSubList(source, target); Assert.assertEquals(-1, res); }
@Test public void testLastIndexOfSublistNullSource() { byte[] source = null; byte[] target = new byte[] { 6, 7, 8, 9, 10 }; int res = ListArrayUtil.lastIndexOfSubList(source, target); Assert.assertEquals(-1, res); }
@Test public void testLastIndexOfSublistNullTarget() { byte[] source = new byte[] { 1, 2, 3, 4, 5 }; byte[] target = null; int res = ListArrayUtil.lastIndexOfSubList(source, target); Assert.assertEquals(-1, res); }
@Test public void testLastIndexOfSublistMatchesSecondOcurrence() { byte[] source = new byte[] { 3, 4, 5, 3, 4, 5 }; byte[] target = new byte[] { 3, 4, 5 }; int res = ListArrayUtil.lastIndexOfSubList(source, target); Assert.assertEquals(3, res); }
@Test public void testLastIndexOfSublistMatchesThirdOcurrence() { byte[] source = new byte[] { 1, 2, 3, 1, 2, 3, 1, 2, 3 }; byte[] target = new byte[] { 1, 2, 3 }; int res = ListArrayUtil.lastIndexOfSubList(source, target); Assert.assertEquals(6, res); }
@Test public void testLastIndexOfSublistMatchesLastOcurrence() { byte[] source = new byte[] { 1, 2, 3, 3, 4, 5, 1, 2, 3 }; byte[] target = new byte[] { 1, 2, 3 }; int res = ListArrayUtil.lastIndexOfSubList(source, target); Assert.assertEquals(6, res); } |
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(); @Override boolean equals(Object other); @Override int hashCode(); @Override String toString(); String toJsonString(); } | @Test public void testEquals() { Topic topicA = new Topic("0000000000000000000000000000000000000000000000000000000000000001"); Topic topicB = new Topic("0000000000000000000000000000000000000000000000000000000000000001"); Topic topicC = new Topic("0000000000000000000000000000000000000000000000000000000000000002"); Topic topicD = new Topic("0x0000000000000000000000000000000000000000000000000000000000000003"); Assert.assertEquals(topicA, topicB); Assert.assertNotEquals(topicA, topicC); Assert.assertNotEquals(topicA, topicD); } |
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) { return parseMatch(matcher); } logger.debug("Invalid address: {}. For ipv6 use de convention [address]:port. For ipv4 address:port", address); return null; } static InetSocketAddress parseAddress(String address); static List<InetSocketAddress> parseAddresses(List<String> addresses); } | @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() { InetSocketAddress result = IpUtils.parseAddress(IPV6_INVALID); Assert.assertNull(result); }
@Test public void parseIPv4() { InetSocketAddress result = IpUtils.parseAddress(IPV4_WITH_PORT); Assert.assertNotNull(result); }
@Test public void parseIPv4NoPort() { InetSocketAddress result = IpUtils.parseAddress(IPV4_NO_PORT); Assert.assertNull(result); }
@Test public void parseHostnameWithPort() { InetSocketAddress result = IpUtils.parseAddress(HOSTNAME_WITH_PORT); Assert.assertNotNull(result); } |
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) .value(BigInteger.TEN) .build(); filter.newPendingTx(tx); Object[] result = filter.getEvents(); Assert.assertNotNull(result); Assert.assertEquals(1, result.length); Assert.assertEquals("0x" + tx.getHash().toHexString(), result[0]); }
@Test public void twoTransactionsAndEvents() { PendingTransactionFilter filter = new PendingTransactionFilter(); Account sender = new AccountBuilder().name("sender").build(); Account receiver = new AccountBuilder().name("receiver").build(); Transaction tx1 = new TransactionBuilder() .sender(sender) .receiver(receiver) .value(BigInteger.TEN) .build(); Transaction tx2 = new TransactionBuilder() .sender(sender) .receiver(receiver) .value(BigInteger.ONE) .build(); filter.newPendingTx(tx1); filter.newPendingTx(tx2); Object[] result = filter.getEvents(); Assert.assertNotNull(result); Assert.assertEquals(2, result.length); Assert.assertEquals("0x" + tx1.getHash().toHexString(), result[0]); Assert.assertEquals("0x" + tx2.getHash().toHexString(), result[1]); } |
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); static List<InetSocketAddress> parseAddresses(List<String> addresses); } | @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(result.isEmpty()); Assert.assertEquals(2, result.size()); } |
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_890_123_000L)); Assert.assertEquals("0.000000", FormatUtils.formatNanosecondsToSeconds(0L)); Assert.assertEquals("0.000001", FormatUtils.formatNanosecondsToSeconds(1_234L)); } |
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 internalService : internalServices) { internalService.start(); } if (logger.isInfoEnabled()) { String versions = EthVersion.supported().stream().map(EthVersion::name).collect(Collectors.joining(", ")); logger.info("Capability eth version: [{}]", versions); } logger.info("done"); } FullNodeRunner(
List<InternalService> internalServices,
RskSystemProperties rskSystemProperties,
BuildInfo buildInfo); @Override void run(); @Override void stop(); } | @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,
RskSystemProperties rskSystemProperties,
BuildInfo buildInfo); @Override void run(); @Override void stop(); } | @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(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; } | @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)); } |
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); } | @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)); } |
ForkDetectionDataRule implements BlockValidationRule, BlockHeaderValidationRule { @Override public boolean isValid(Block block) { return isValid(block.getHeader()); } ForkDetectionDataRule(
ActivationConfig activationConfig,
ConsensusValidationMainchainView mainchainView,
ForkDetectionDataCalculator forkDetectionDataCalculator,
int requiredBlocksForForkDetectionDataCalculation); @Override boolean isValid(Block block); @Override boolean isValid(BlockHeader header); } | @Test public void validForBlocksBeforeRskip110UsingMethodThatReceivesBlockAsParameter() { long blockNumber = 4242; ForkDetectionDataRule rule = new ForkDetectionDataRule( activationConfig, mock(ConsensusValidationMainchainView.class), mock(ForkDetectionDataCalculator.class), 449 ); BlockHeader header = mock(BlockHeader.class); when(header.getNumber()).thenReturn(blockNumber); Block block = mock(Block.class); when(block.getHeader()).thenReturn(header); assertTrue(rule.isValid(header)); }
@Test public void validForBlocksBeforeRskip110() { long blockNumber = 4242; ForkDetectionDataRule rule = new ForkDetectionDataRule( activationConfig, mock(ConsensusValidationMainchainView.class), mock(ForkDetectionDataCalculator.class), 449 ); BlockHeader header = mock(BlockHeader.class); when(header.getNumber()).thenReturn(blockNumber); assertTrue(rule.isValid(header)); }
@Test public void invalidForRskip110ActiveButForkDetectionData() { long blockNumber = 42; enableRulesAt(blockNumber, ConsensusRule.RSKIP110); ForkDetectionDataRule rule = new ForkDetectionDataRule( activationConfig, mock(ConsensusValidationMainchainView.class), mock(ForkDetectionDataCalculator.class), 449 ); BlockHeader header = mock(BlockHeader.class); when(header.getNumber()).thenReturn(blockNumber); when(header.getMiningForkDetectionData()).thenReturn(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }); assertFalse(rule.isValid(header)); }
@Test public void validForRskip110ActiveButNoForkDetectionDataBecauseNoEnoughBlocksToCalculateIt() { long blockNumber = 42; enableRulesAt(blockNumber, ConsensusRule.RSKIP110); ForkDetectionDataRule rule = new ForkDetectionDataRule( activationConfig, mock(ConsensusValidationMainchainView.class), mock(ForkDetectionDataCalculator.class), 449 ); BlockHeader header = mock(BlockHeader.class); when(header.getNumber()).thenReturn(blockNumber); when(header.getMiningForkDetectionData()).thenReturn(new byte[0]); assertTrue(rule.isValid(header)); }
@Test public void invalidForRskip110ActiveAndForkDetectionDataButMissingBlocksForCalculation() { long blockNumber = 4242; enableRulesAt(blockNumber, ConsensusRule.RSKIP110); Keccak256 parentBlockHash = new Keccak256(getRandomHash()); int requiredBlocksForForkDataCalculation = 449; ConsensusValidationMainchainView mainchainView = mock(ConsensusValidationMainchainView.class); when(mainchainView.get(parentBlockHash, requiredBlocksForForkDataCalculation)).thenReturn(new ArrayList<>()); ForkDetectionDataRule rule = new ForkDetectionDataRule( activationConfig, mainchainView, mock(ForkDetectionDataCalculator.class), requiredBlocksForForkDataCalculation ); BlockHeader header = mock(BlockHeader.class); when(header.getNumber()).thenReturn(blockNumber); when(header.getParentHash()).thenReturn(parentBlockHash); Keccak256 blockHash = new Keccak256(getRandomHash()); when(header.getHash()).thenReturn(blockHash); byte[] forkDetectionData = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }; when(header.getMiningForkDetectionData()).thenReturn(forkDetectionData); assertFalse(rule.isValid(header)); }
@Test public void validForRskip110ActiveAndForkDetectionData() { long blockNumber = 4242; enableRulesAt(blockNumber, ConsensusRule.RSKIP110); Keccak256 parentBlockHash = new Keccak256(getRandomHash()); int requiredBlocksForForkDataCalculation = 449; List<BlockHeader> previousBlocks = IntStream .range(0, requiredBlocksForForkDataCalculation) .mapToObj(i -> mock(BlockHeader.class)) .collect(Collectors.toList()); ConsensusValidationMainchainView mainchainView = mock(ConsensusValidationMainchainView.class); when(mainchainView.get(parentBlockHash, requiredBlocksForForkDataCalculation)).thenReturn(previousBlocks); ForkDetectionDataCalculator calculator = mock(ForkDetectionDataCalculator.class); Keccak256 blockHash = new Keccak256(getRandomHash()); byte[] forkDetectionData = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }; when(calculator.calculateWithBlockHeaders(previousBlocks)).thenReturn(forkDetectionData); ForkDetectionDataRule rule = new ForkDetectionDataRule( activationConfig, mainchainView, calculator, requiredBlocksForForkDataCalculation ); BlockHeader header = mock(BlockHeader.class); when(header.getNumber()).thenReturn(blockNumber); when(header.getHash()).thenReturn(blockHash); when(header.getParentHash()).thenReturn(parentBlockHash); when(header.getMiningForkDetectionData()).thenReturn(forkDetectionData); assertTrue(rule.isValid(header)); }
@Test public void invalidForRskip110ActiveAndForkDetectionDataBecauseDataDoesNotMatch() { long blockNumber = 4242; enableRulesAt(blockNumber, ConsensusRule.RSKIP110); Keccak256 parentBlockHash = new Keccak256(getRandomHash()); int requiredBlocksForForkDataCalculation = 449; List<BlockHeader> previousBlocks = IntStream .range(0, requiredBlocksForForkDataCalculation) .mapToObj(i -> mock(BlockHeader.class)) .collect(Collectors.toList()); ConsensusValidationMainchainView mainchainView = mock(ConsensusValidationMainchainView.class); when(mainchainView.get(parentBlockHash, requiredBlocksForForkDataCalculation)).thenReturn(previousBlocks); ForkDetectionDataCalculator calculator = mock(ForkDetectionDataCalculator.class); Keccak256 blockHash = new Keccak256(getRandomHash()); byte[] forkDetectionData = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }; when(calculator.calculateWithBlockHeaders(previousBlocks)).thenReturn(forkDetectionData); ForkDetectionDataRule rule = new ForkDetectionDataRule( activationConfig, mainchainView, calculator, requiredBlocksForForkDataCalculation ); BlockHeader header = mock(BlockHeader.class); when(header.getNumber()).thenReturn(blockNumber); when(header.getHash()).thenReturn(blockHash); when(header.getParentHash()).thenReturn(parentBlockHash); byte[] headerForkDetectionData = new byte[] { 1, 2, 3, 4, 5, 6, 42, 8, 9, 10, 11, 12 }; when(header.getMiningForkDetectionData()).thenReturn(headerForkDetectionData); assertFalse(rule.isValid(header)); } |
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); } | @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)); } |
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); } | @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())); } |
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); } | @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)); } |
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); } | @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())); } |
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); } | @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)); } |
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); } | @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)); } |
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); } | @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)); } |
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); } | @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())); } |
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); } | @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()); } |
MutableTrieCache implements MutableTrie { public Iterator<DataWord> getStorageKeys(RskAddress addr) { byte[] accountStoragePrefixKey = trieKeyMapper.getAccountStoragePrefixKey(addr); ByteArrayWrapper accountWrapper = getAccountWrapper(new ByteArrayWrapper(accountStoragePrefixKey)); boolean isDeletedAccount = deleteRecursiveLog.contains(accountWrapper); Map<ByteArrayWrapper, byte[]> accountItems = cache.get(accountWrapper); if (accountItems == null && isDeletedAccount) { return Collections.emptyIterator(); } if (isDeletedAccount) { return new StorageKeysIterator(Collections.emptyIterator(), accountItems, addr, trieKeyMapper); } Iterator<DataWord> storageKeys = trie.getStorageKeys(addr); if (accountItems == null) { return storageKeys; } return new StorageKeysIterator(storageKeys, accountItems, addr, trieKeyMapper); } 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); } | @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(baseMutableTrie); MutableRepository cacheRepository = new MutableRepository(mtCache); MutableRepository otherCacheRepository = new MutableRepository(otherCache); RskAddress addr = new RskAddress("b86ca7db8c7ae687ac8d098789987eee12333fc7"); baseRepository.createAccount(addr); baseRepository.setupContract(addr); DataWord sk120 = toStorageKey("120"); DataWord sk121 = toStorageKey("121"); DataWord sk122 = toStorageKey("122"); DataWord sk123 = toStorageKey("123"); DataWord sk124 = toStorageKey("124"); baseRepository.addStorageBytes(addr, sk120, toBytes("HAL")); baseRepository.addStorageBytes(addr, sk121, toBytes("HAL")); baseRepository.addStorageBytes(addr, sk122, toBytes("HAL")); cacheRepository.addStorageBytes(addr, sk120, null); cacheRepository.addStorageBytes(addr, sk121, toBytes("LAH")); cacheRepository.addStorageBytes(addr, sk123, toBytes("LAH")); otherCacheRepository.addStorageBytes(addr, sk124, toBytes("HAL")); Iterator<DataWord> storageKeys = mtCache.getStorageKeys(addr); Set<DataWord> keys = new HashSet<>(); storageKeys.forEachRemaining(keys::add); assertFalse(keys.contains(sk120)); assertTrue(keys.contains(sk121)); assertTrue(keys.contains(sk122)); assertTrue(keys.contains(sk123)); assertFalse(keys.contains(sk124)); assertEquals(3, keys.size()); storageKeys = otherCache.getStorageKeys(addr); keys = new HashSet<>(); storageKeys.forEachRemaining(keys::add); assertFalse(keys.contains(sk120)); assertTrue(keys.contains(sk121)); assertTrue(keys.contains(sk122)); assertTrue(keys.contains(sk123)); assertTrue(keys.contains(sk124)); assertEquals(4, keys.size()); }
@Test public void testStorageKeysNoCache() { MutableTrieImpl baseMutableTrie = new MutableTrieImpl(null, new Trie()); MutableTrieCache mtCache = new MutableTrieCache(baseMutableTrie); MutableRepository baseRepository = new MutableRepository(baseMutableTrie); RskAddress addr = new RskAddress("b86ca7db8c7ae687ac8d098789987eee12333fc7"); DataWord sk120 = toStorageKey("120"); DataWord sk121 = toStorageKey("121"); baseRepository.addStorageBytes(addr, sk120, toBytes("HAL")); baseRepository.addStorageBytes(addr, sk121, toBytes("HAL")); Iterator<DataWord> storageKeys = mtCache.getStorageKeys(addr); Set<DataWord> keys = new HashSet<>(); storageKeys.forEachRemaining(keys::add); assertTrue(keys.contains(sk120)); assertTrue(keys.contains(sk121)); assertEquals(2, keys.size()); }
@Test public void testStorageKeysNoTrie() { MutableTrieImpl baseMutableTrie = new MutableTrieImpl(null, new Trie()); MutableTrieCache mtCache = new MutableTrieCache(baseMutableTrie); MutableRepository cacheRepository = new MutableRepository(mtCache); RskAddress addr = new RskAddress("b86ca7db8c7ae687ac8d098789987eee12333fc7"); DataWord skzero = DataWord.ZERO; DataWord sk120 = toStorageKey("120"); DataWord sk121 = toStorageKey("121"); cacheRepository.addStorageBytes(addr, sk120, toBytes("HAL")); cacheRepository.addStorageBytes(addr, sk121, toBytes("HAL")); cacheRepository.addStorageBytes(addr, skzero, toBytes("HAL")); Iterator<DataWord> storageKeys = mtCache.getStorageKeys(addr); Set<DataWord> keys = new HashSet<>(); storageKeys.forEachRemaining(keys::add); assertTrue(keys.contains(sk120)); assertTrue(keys.contains(sk121)); assertTrue(keys.contains(skzero)); assertEquals(3, keys.size()); }
@Test public void testStorageKeysDeletedAccount() { MutableTrieImpl baseMutableTrie = new MutableTrieImpl(null, new Trie()); MutableTrieCache mtCache = new MutableTrieCache(baseMutableTrie); MutableRepository cacheRepository = new MutableRepository(mtCache); MutableRepository baseRepository = new MutableRepository(baseMutableTrie); RskAddress addr = new RskAddress("b86ca7db8c7ae687ac8d098789987eee12333fc7"); DataWord sk120 = toStorageKey("120"); DataWord sk121 = toStorageKey("121"); baseRepository.addStorageBytes(addr, sk120, toBytes("HAL")); cacheRepository.delete(addr); Iterator<DataWord> storageKeys = mtCache.getStorageKeys(addr); Set<DataWord> keys = new HashSet<>(); storageKeys.forEachRemaining(keys::add); assertFalse(keys.contains(sk120)); assertFalse(keys.contains(sk121)); assertEquals(0, keys.size()); cacheRepository.addStorageBytes(addr, sk121, toBytes("HAL")); storageKeys = mtCache.getStorageKeys(addr); keys = new HashSet<>(); storageKeys.forEachRemaining(keys::add); assertFalse(keys.contains(sk120)); assertTrue(keys.contains(sk121)); assertEquals(1, keys.size()); } |
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); } | @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); } |
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); } | @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); } |
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, BootstrapDataEntry> entry : selectedEntries.entrySet()) { BootstrapDataEntry bde = entry.getValue(); String currentHash = bde.getHash(); if (!hashToVerify.equals(currentHash)){ throw new BootstrapImportException(String.format( "Error trying to verify different hashes: %s vs %s", hashToVerify, currentHash)); } BootstrapDataSignature bds = bde.getSig(); byte[] publicKey = Hex.decode(entry.getKey()); BigInteger r = new BigInteger(1, Hex.decode(bds.getR())); BigInteger s = new BigInteger(1, Hex.decode(bds.getS())); ECDSASignature signature = new ECDSASignature(r, s); if (Secp256k1.getInstance().verify(dbHash, signature, publicKey)) { verifications++; } } return verifications; } int verifyEntries(Map<String, BootstrapDataEntry> selectedEntries); } | @Test public void verifyFileEmpty() { BootstrapDataVerifier bootstrapDataVerifier = new BootstrapDataVerifier(); assertEquals(0, bootstrapDataVerifier.verifyEntries(new HashMap<>())); }
@Test public void verifyFileMany() { BootstrapDataVerifier bootstrapDataVerifier = new BootstrapDataVerifier(); HashMap<String, BootstrapDataEntry> entries = new HashMap<>(); List<String> keys = new ArrayList<>(); keys.add("04330037e82c177d7108077c80440821e13c1c62105f85e030214b48d7b5dff0b8e7c158b171546a71139e4de56c8535c964514033b89a669a8e87a5e8770c147c"); keys.add("0473602083afe175e7cae12dbc27da54ec5ac77f99920787f3e891e7af303aaed480770c0de4c991aea1712729260175e158fa73f63c60f0f1de057139c52714de"); keys.add("04bf74915a14e96df0b520a659acc28ae21aada3b0415e35f82f0c7b546338fc48bbfdce858ce3e4690feeb443d7f4955881ba0b793999e4fef7e46732e7fedf02"); String hash = "53cb8e93030183c5ba198433e8cd1f013f3d113e0f4d1756de0d1f124ead155a"; String r1 = "8dba957877d5bdcb26d551dfa2fa509dfe3fe327caf0166130b9f467a0a0c249"; String s1 = "dab3fdf2031515d2de1d420310c69153fcc356f22b50dfd53c6e13e74e346eee"; String r2 = "f0e8aab4fdd83382292a1bbc5480e2ae8084dc245f000f4bc4534d383a3a7919"; String s2 = "a30891f2176bd87b4a3ac5c75167f2442453c17c6e2fbfb36c3b972ee67a4c2d"; String r3 = "00"; String s3 = "00"; entries.put(keys.get(0), new BootstrapDataEntry(1, "", "dbPath", hash, new BootstrapDataSignature(r1, s1))); entries.put(keys.get(1), new BootstrapDataEntry(1, "", "dbPath", hash, new BootstrapDataSignature(r2, s2))); entries.put(keys.get(2), new BootstrapDataEntry(1, "", "dbPath", hash, new BootstrapDataSignature(r3, s3))); assertEquals(2, bootstrapDataVerifier.verifyEntries(entries)); }
@Test(expected = BootstrapImportException.class) public void doNotVerifyForDifferentHashes() { BootstrapDataVerifier bootstrapDataVerifier = new BootstrapDataVerifier(); HashMap<String, BootstrapDataEntry> entries = new HashMap<>(); List<String> keys = new ArrayList<>(); keys.add("04330037e82c177d7108077c80440821e13c1c62105f85e030214b48d7b5dff0b8e7c158b171546a71139e4de56c8535c964514033b89a669a8e87a5e8770c147c"); keys.add("04dffaa346b18c26230d6050c6ab67f0761ab12136b0dc3a1f1c6ed31890ffac38baa3d8da1df4aa2acc72e45dc3599797ba668666c5395280217f2fd215262b8a"); keys.add("04bf74915a14e96df0b520a659acc28ae21aada3b0415e35f82f0c7b546338fc48bbfdce858ce3e4690feeb443d7f4955881ba0b793999e4fef7e46732e7fedf02"); String hash1 = "53cb8e93030183c5ba198433e8cd1f013f3d113e0f4d1756de0d1f124ead155a"; String hash2 = "87d149cb424c0387656f211d2589fb5b1e16229921309e98588419ccca8a7362"; String hash3 = "53cb8e93030183c5ba198433e8cd1f013f3d113e0f4d1756de0d1f124ead155c"; String r1 = "8dba957877d5bdcb26d551dfa2fa509dfe3fe327caf0166130b9f467a0a0c249"; String s1 = "dab3fdf2031515d2de1d420310c69153fcc356f22b50dfd53c6e13e74e346eee"; String r2 = "0efa8e0738468e434e443676b5a91fe15b0c416ff7190d8d912dff65161ad33c"; String s2 = "aae27edef80e137dc1a0e92b6ae7fed0d1dc1b4a0ea8930bad6abec5ca1297c1"; String r3 = "00"; String s3 = "00"; entries.put(keys.get(0), new BootstrapDataEntry(1, "", "dbPath", hash1, new BootstrapDataSignature(r1, s1))); entries.put(keys.get(1), new BootstrapDataEntry(1, "", "dbPath", hash2, new BootstrapDataSignature(r2, s2))); entries.put(keys.get(2), new BootstrapDataEntry(1, "", "dbPath", hash3, new BootstrapDataSignature(r3, s3))); bootstrapDataVerifier.verifyEntries(entries); } |
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(); } | @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(); } |
BootstrapIndexCandidateSelector { public HeightCandidate getHeightData(List<BootstrapDataIndex> indexes) { Map<Long, Map<String, BootstrapDataEntry>> entriesPerHeight = getEntriesPerHeight(indexes); return getHeightCandidate(entriesPerHeight); } BootstrapIndexCandidateSelector(List<String> publicKeys, int minimumRequiredSources); HeightCandidate getHeightData(List<BootstrapDataIndex> indexes); } | @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); }
@Test(expected=BootstrapImportException.class) public void getMaximumCommonHeightDataOneEntry() { List<String> keys = Arrays.asList("key1", "key2"); BootstrapIndexCandidateSelector indexMCH = new BootstrapIndexCandidateSelector(keys, 2); List<BootstrapDataIndex> indexes = new ArrayList<>(); ArrayList<BootstrapDataEntry> entries = new ArrayList<>(); entries.add(new BootstrapDataEntry(1, "", "dbPath", "hash", new BootstrapDataSignature("r", "s"))); indexes.add(new BootstrapDataIndex(entries)); indexMCH.getHeightData(indexes); }
@Test(expected=BootstrapImportException.class) public void getMaximumCommonHeightDataDuplicatedEntries() { List<String> keys = Arrays.asList("key1", "key2"); BootstrapIndexCandidateSelector indexMCH = new BootstrapIndexCandidateSelector(keys, 2); List<BootstrapDataIndex> indexes = new ArrayList<>(); ArrayList<BootstrapDataEntry> entries = new ArrayList<>(); entries.add(new BootstrapDataEntry(1, "", "dbPath", "hash", new BootstrapDataSignature("r", "s"))); entries.add(new BootstrapDataEntry(1, "", "dbPath", "hash", new BootstrapDataSignature("r", "s"))); indexes.add(new BootstrapDataIndex(entries)); indexMCH.getHeightData(indexes); }
@Test public void getMaximumCommonHeightDataTwoEntries() { List<String> keys = Arrays.asList("key1", "key2"); BootstrapIndexCandidateSelector indexMCH = new BootstrapIndexCandidateSelector(keys, 2); List<BootstrapDataIndex> indexes = new ArrayList<>(); ArrayList<BootstrapDataEntry> entries = new ArrayList<>(); ArrayList<BootstrapDataEntry> entries2 = new ArrayList<>(); entries.add(new BootstrapDataEntry(1, "", "dbPath", "hash", new BootstrapDataSignature("r", "s"))); entries2.add(new BootstrapDataEntry(1, "", "dbPath", "hash", new BootstrapDataSignature("r", "s"))); indexes.add(new BootstrapDataIndex(entries)); indexes.add(new BootstrapDataIndex(entries2)); BootstrapIndexCandidateSelector.HeightCandidate heightCandidate = indexMCH.getHeightData(indexes); assertEquals(1, heightCandidate.getHeight()); }
@Test public void getMaximumCommonHeightDataThreeEntries() { List<String> keys = Arrays.asList("key1", "key2"); BootstrapIndexCandidateSelector indexMCH = new BootstrapIndexCandidateSelector(keys, 2); List<BootstrapDataIndex> indexes = new ArrayList<>(); ArrayList<BootstrapDataEntry> entries = new ArrayList<>(); ArrayList<BootstrapDataEntry> entries2 = new ArrayList<>(); entries.add(new BootstrapDataEntry(1, "", "dbPath", "hash", new BootstrapDataSignature("r", "s"))); entries.add(new BootstrapDataEntry(2, "", "dbPath", "hash", new BootstrapDataSignature("r", "s"))); entries2.add(new BootstrapDataEntry(1, "", "dbPath", "hash", new BootstrapDataSignature("r", "s"))); indexes.add(new BootstrapDataIndex(entries)); indexes.add(new BootstrapDataIndex(entries2)); BootstrapIndexCandidateSelector.HeightCandidate heightCandidate = indexMCH.getHeightData(indexes); assertEquals(1, heightCandidate.getHeight()); }
@Test public void getMaximumCommonHeightDataManyEntries() { List<String> keys = Arrays.asList("key1", "key2", "keys3"); BootstrapIndexCandidateSelector indexMCH = new BootstrapIndexCandidateSelector(keys, 2); List<BootstrapDataIndex> indexes = new ArrayList<>(); ArrayList<BootstrapDataEntry> entries = new ArrayList<>(); ArrayList<BootstrapDataEntry> entries2 = new ArrayList<>(); ArrayList<BootstrapDataEntry> entries3 = new ArrayList<>(); entries.add(new BootstrapDataEntry(1, "", "dbPath", "hash", new BootstrapDataSignature("r", "s"))); entries2.add(new BootstrapDataEntry(1, "", "dbPath", "hash", new BootstrapDataSignature("r", "s"))); entries3.add(new BootstrapDataEntry(1, "", "dbPath", "hash", new BootstrapDataSignature("r", "s"))); entries.add(new BootstrapDataEntry(2, "", "dbPath", "hash", new BootstrapDataSignature("r", "s"))); entries2.add(new BootstrapDataEntry(2, "", "dbPath", "hash", new BootstrapDataSignature("r", "s"))); entries3.add(new BootstrapDataEntry(2, "", "dbPath", "hash", new BootstrapDataSignature("r", "s"))); indexes.add(new BootstrapDataIndex(entries)); indexes.add(new BootstrapDataIndex(entries2)); indexes.add(new BootstrapDataIndex(entries3)); BootstrapIndexCandidateSelector.HeightCandidate heightCandidate = indexMCH.getHeightData(indexes); assertEquals(heightCandidate.getHeight(), 2L); } |
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(); } | @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)); } |
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); 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()); } |
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); } | @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); } |
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(); } | @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()); } |
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(); } | @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); } |
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(); } | @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(); @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(); } | @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 = 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(); } | @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> getBlocksByNumber(long blockNumber); @Override void putBlocks(long blockNumber, List<IndexedBlockStore.BlockInfo> blocks); @Override List<IndexedBlockStore.BlockInfo> removeLast(); @Override void flush(); @Override void close(); } | @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> getBlocksByNumber(long blockNumber); @Override void putBlocks(long blockNumber, List<IndexedBlockStore.BlockInfo> blocks); @Override List<IndexedBlockStore.BlockInfo> removeLast(); @Override void flush(); @Override void close(); } | @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 ? contentTypeValue : null; } } static String getMimeType(String contentTypeValue); } | @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)); } |
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); } | @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); 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); } | @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 trieStore = rskContext.getTrieStore(); Assert.assertThat(trieStore, is(instanceOf(TrieStoreImpl.class))); Assert.assertThat(Files.list(testDatabasesDirectory).count(), is(1L)); }
@Test public void shouldBuildSimpleTrieStoreCleaningUpMultiTrieStore() throws IOException, InterruptedException { Path testDatabasesDirectory = databaseDir.getRoot().toPath(); doReturn(new GarbageCollectorConfig(false, 1000, 3)).when(testProperties).garbageCollectorConfig(); doReturn(testDatabasesDirectory.toString()).when(testProperties).databaseDir(); long preExistingEpochs = 4; for (int i = 0; i < preExistingEpochs; i++) { Files.createDirectory(testDatabasesDirectory.resolve(String.format("unitrie_%d", i))); } Assert.assertThat(Files.list(testDatabasesDirectory).count(), is(preExistingEpochs)); TrieStore trieStore = rskContext.getTrieStore(); Assert.assertThat(trieStore, is(instanceOf(TrieStoreImpl.class))); Assert.assertThat(Files.list(testDatabasesDirectory).count(), is(1L)); }
@Test public void shouldBuildMultiTrieStore() throws IOException { long numberOfEpochs = 3; Path testDatabasesDirectory = databaseDir.getRoot().toPath(); doReturn(new GarbageCollectorConfig(true, 1000, (int) numberOfEpochs)).when(testProperties).garbageCollectorConfig(); doReturn(testDatabasesDirectory.toString()).when(testProperties).databaseDir(); TrieStore trieStore = rskContext.getTrieStore(); Assert.assertThat(trieStore, is(instanceOf(MultiTrieStore.class))); Assert.assertThat(Files.list(testDatabasesDirectory).count(), is(numberOfEpochs)); }
@Test public void shouldBuildMultiTrieStoreMigratingSingleTrieStore() throws IOException { long numberOfEpochs = 3; Path testDatabasesDirectory = databaseDir.getRoot().toPath(); doReturn(new GarbageCollectorConfig(true, 1000, (int) numberOfEpochs)).when(testProperties).garbageCollectorConfig(); doReturn(testDatabasesDirectory.toString()).when(testProperties).databaseDir(); Files.createDirectory(testDatabasesDirectory.resolve("unitrie")); TrieStore trieStore = rskContext.getTrieStore(); Assert.assertThat(trieStore, is(instanceOf(MultiTrieStore.class))); Assert.assertThat(Files.list(testDatabasesDirectory).count(), is(numberOfEpochs)); Assert.assertThat(Files.list(testDatabasesDirectory).noneMatch(p -> p.getFileName().toString().equals("unitrie")), is(true)); }
@Test public void shouldBuildMultiTrieStoreFromExistingDirectories() throws IOException { int numberOfEpochs = 3; Path testDatabasesDirectory = databaseDir.getRoot().toPath(); doReturn(new GarbageCollectorConfig(true, 1000, numberOfEpochs)).when(testProperties).garbageCollectorConfig(); doReturn(testDatabasesDirectory.toString()).when(testProperties).databaseDir(); int initialEpoch = 3; for (int i = initialEpoch; i < initialEpoch + numberOfEpochs; i++) { Files.createDirectory(testDatabasesDirectory.resolve(String.format("unitrie_%d", i))); } TrieStore trieStore = rskContext.getTrieStore(); Assert.assertThat(trieStore, is(instanceOf(MultiTrieStore.class))); Assert.assertThat(Files.list(testDatabasesDirectory).count(), is((long) numberOfEpochs)); int[] directorySufixes = Files.list(testDatabasesDirectory) .map(Path::getFileName) .map(Path::toString) .map(fileName -> fileName.replaceAll("unitrie_", "")) .mapToInt(Integer::valueOf) .sorted() .toArray(); Assert.assertThat(directorySufixes, is(IntStream.range(initialEpoch, initialEpoch + numberOfEpochs).toArray())); }
@Test(expected = IllegalStateException.class) @Ignore("Permissions set fails under CircleCI") public void shouldFailIfCannotBuildMultiTrieStore() throws IOException { Path testDatabasesDirectory = Files.createTempDirectory("test", PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("---------"))); doReturn(new GarbageCollectorConfig(true, 1000, 3)).when(testProperties).garbageCollectorConfig(); doReturn(testDatabasesDirectory.toString()).when(testProperties).databaseDir(); RskContext rskContext = new RskContext(new String[0]) { @Override public RskSystemProperties getRskSystemProperties() { return testProperties; } }; rskContext.getTrieStore(); } |
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); } | @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())); } |
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); } | @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); } |
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(bloom1)); Assert.assertFalse(blocksBloom.matches(bloom2)); bloom1.or(bloom2); Assert.assertFalse(blocksBloom.matches(bloom1)); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.