use of co.rsk.core.bc.BlockChainImpl in project rskj by rsksmart.
the class MainNetMinerTest method submitBitcoinBlockInvalidBlockDoesntEliminateCache.
/*
* This test is much more likely to fail than the
* submitBitcoinBlockProofOfWorkNotGoodEnough test. Even then
* it should almost never fail.
*/
@Test
public void submitBitcoinBlockInvalidBlockDoesntEliminateCache() {
// ////////////////////////////////////////////////////////////////////
// To make this test work we need a special network spec with
// medium minimum difficulty (this is not the mainnet nor the regnet)
// //////////////////////////////////////////////////////////////////
/* We need a low, but not too low, target */
BlockChainImpl bc = new BlockChainBuilder().build();
Genesis gen = (Genesis) BlockChainImplTest.getGenesisBlock(bc);
gen.getHeader().setDifficulty(new BlockDifficulty(BigInteger.valueOf(300000)));
bc.setStatus(gen, gen.getCumulativeDifficulty());
World world = new World(bc, gen);
blockchain = world.getBlockChain();
EthereumImpl ethereumImpl = Mockito.mock(EthereumImpl.class);
Mockito.when(ethereumImpl.addNewMinedBlock(Mockito.any())).thenReturn(ImportResult.IMPORTED_BEST);
MinerServer minerServer = new MinerServerImpl(config, ethereumImpl, this.blockchain, world.getBlockProcessor(), DIFFICULTY_CALCULATOR, new ProofOfWorkRule(config).setFallbackMiningEnabled(false), blockToMineBuilder(), ConfigUtils.getDefaultMiningConfig());
try {
minerServer.start();
MinerWork work = minerServer.getWork();
co.rsk.bitcoinj.core.BtcBlock bitcoinMergedMiningBlock = getMergedMiningBlock(work);
bitcoinMergedMiningBlock.setNonce(1);
// Try to submit a block with invalid PoW, this should not eliminate the block from the cache
SubmitBlockResult result1 = minerServer.submitBitcoinBlock(work.getBlockHashForMergedMining(), bitcoinMergedMiningBlock);
Assert.assertEquals("ERROR", result1.getStatus());
Assert.assertNull(result1.getBlockInfo());
Mockito.verify(ethereumImpl, Mockito.times(0)).addNewMinedBlock(Mockito.any());
// Now try to submit the same block, this should work fine since the block remains in the cache
// This WON't work in mainnet because difficulty is HIGH
/*---------------------------------------------------------
findNonce(work, bitcoinMergedMiningBlock);
SubmitBlockResult result2 = minerServer.submitBitcoinBlock(work.getBlockHashForMergedMining(), bitcoinMergedMiningBlock);
Assert.assertEquals("OK", result2.getStatus());
Assert.assertNotNull(result2.getBlockInfo());
Mockito.verify(ethereumImpl, Mockito.times(1)).addNewMinedBlock(Mockito.any());
// Finally, submit the same block again and validate that addNewMinedBlock is called again
SubmitBlockResult result3 = minerServer.submitBitcoinBlock(work.getBlockHashForMergedMining(), bitcoinMergedMiningBlock);
Assert.assertEquals("OK", result3.getStatus());
Assert.assertNotNull(result3.getBlockInfo());
Mockito.verify(ethereumImpl, Mockito.times(2)).addNewMinedBlock(Mockito.any());
-------------------------------*/
} finally {
minerServer.stop();
}
}
use of co.rsk.core.bc.BlockChainImpl in project rskj by rsksmart.
the class NodeBlockProcessorUnclesTest method addBlockWithTwoKnownUncles.
@Test
public void addBlockWithTwoKnownUncles() throws UnknownHostException {
BlockChainImpl blockChain = new BlockChainBuilder().build();
NodeBlockProcessor processor = createNodeBlockProcessor(blockChain);
Block genesis = blockChain.getBestBlock();
BlockBuilder blockBuilder = new BlockBuilder(blockChain, new BlockGenerator());
Block block1 = blockBuilder.parent(genesis).build();
Block uncle1 = blockBuilder.parent(genesis).build();
Block uncle2 = blockBuilder.parent(genesis).build();
List<BlockHeader> uncles = new ArrayList<>();
uncles.add(uncle1.getHeader());
uncles.add(uncle2.getHeader());
Block block2 = blockBuilder.parent(block1).uncles(uncles).build();
processor.processBlock(null, block1);
processor.processBlock(null, uncle1);
processor.processBlock(null, uncle2);
SimpleMessageChannel sender = new SimpleMessageChannel();
processor.processBlock(sender, block2);
Assert.assertEquals(2, processor.getBlockchain().getBestBlock().getNumber());
Assert.assertArrayEquals(block2.getHash().getBytes(), processor.getBlockchain().getBestBlockHash());
Assert.assertTrue(sender.getGetBlockMessages().isEmpty());
}
use of co.rsk.core.bc.BlockChainImpl in project rskj by rsksmart.
the class TestRunner method runTestCase.
public List<String> runTestCase(BlockTestCase testCase) {
/* 1 */
// Create genesis + init pre state
Block genesis = BlockBuilder.build(testCase.getGenesisBlockHeader(), null, null);
Repository repository = RepositoryBuilder.build(testCase.getPre());
IndexedBlockStore blockStore = new IndexedBlockStore(new HashMap<>(), new HashMapDB(), null);
blockStore.saveBlock(genesis, genesis.getCumulativeDifficulty(), true);
EthereumListener listener = new CompositeEthereumListener();
KeyValueDataSource ds = new HashMapDB();
ds.init();
ReceiptStore receiptStore = new ReceiptStoreImpl(ds);
BlockChainImpl blockchain = new BlockChainImpl(config, repository, blockStore, receiptStore, null, null, null, new DummyBlockValidator());
// BlockchainImpl blockchain = new BlockchainImpl(blockStore, repository, wallet, adminInfo, listener,
// new CommonConfig().parentHeaderValidator(), receiptStore);
blockchain.setNoValidation(true);
TransactionPoolImpl transactionPool = new TransactionPoolImpl(config, repository, null, receiptStore, null, listener, 10, 100);
blockchain.setBestBlock(genesis);
blockchain.setTotalDifficulty(genesis.getCumulativeDifficulty());
blockchain.setTransactionPool(transactionPool);
/* 2 */
// Create block traffic list
List<Block> blockTraffic = new ArrayList<>();
for (BlockTck blockTck : testCase.getBlocks()) {
Block block = BlockBuilder.build(blockTck.getBlockHeader(), blockTck.getTransactions(), blockTck.getUncleHeaders());
setNewStateRoot = !((blockTck.getTransactions() == null) && (blockTck.getUncleHeaders() == null) && (blockTck.getBlockHeader() == null));
Block tBlock = null;
try {
byte[] rlp = parseData(blockTck.getRlp());
tBlock = new Block(rlp);
ArrayList<String> outputSummary = BlockHeaderValidator.valid(tBlock.getHeader(), block.getHeader());
if (!outputSummary.isEmpty()) {
for (String output : outputSummary) logger.error("at block {}: {}", Integer.toString(blockTraffic.size()), output);
}
blockTraffic.add(tBlock);
} catch (Exception e) {
System.out.println("*** Exception");
}
}
// Inject blocks to the blockchain execution
for (Block block : blockTraffic) {
ImportResult importResult = blockchain.tryToConnect(block);
logger.debug("{} ~ {} difficulty: {} ::: {}", block.getShortHash(), shortHash(block.getParentHash().getBytes()), block.getCumulativeDifficulty(), importResult.toString());
}
// Check state root matches last valid block
List<String> results = new ArrayList<>();
String currRoot = Hex.toHexString(repository.getRoot());
byte[] bestHash = Hex.decode(testCase.getLastblockhash());
String finalRoot = Hex.toHexString(blockStore.getBlockByHash(bestHash).getStateRoot());
/*
if (!blockchain.byTest) // If this comes from ETH, it won't match
if (!finalRoot.equals(currRoot)){
String formattedString = String.format("Root hash doesn't match best: expected: %s current: %s",
finalRoot, currRoot);
results.add(formattedString);
}
*/
Repository postRepository = RepositoryBuilder.build(testCase.getPostState());
List<String> repoResults = RepositoryValidator.valid(repository, postRepository, false);
results.addAll(repoResults);
return results;
}
use of co.rsk.core.bc.BlockChainImpl in project rskj by rsksmart.
the class StateTestRunner method runImpl.
public List<String> runImpl() {
logger.info("");
repository = RepositoryBuilder.build(stateTestCase.getPre());
logger.info("loaded repository");
transaction = TransactionBuilder.build(stateTestCase.getTransaction());
logger.info("transaction: {}", transaction.toString());
BlockStore blockStore = new IndexedBlockStore(new HashMap<>(), new HashMapDB(), null);
blockchain = new BlockChainImpl(config, repository, blockStore, null, null, null, null, null);
env = EnvBuilder.build(stateTestCase.getEnv());
invokeFactory = new TestProgramInvokeFactory(env);
block = BlockBuilder.build(env);
block.setStateRoot(repository.getRoot());
block.flushRLP();
blockchain.setBestBlock(block);
// blockchain.setProgramInvokeFactory(invokeFactory);
// blockchain.startTracking();
ProgramResult programResult = executeTransaction(transaction);
repository.flushNoReconnect();
List<LogInfo> origLogs = programResult.getLogInfoList();
List<LogInfo> postLogs = LogBuilder.build(stateTestCase.getLogs());
List<String> logsResult = LogsValidator.valid(origLogs, postLogs);
Repository postRepository = RepositoryBuilder.build(stateTestCase.getPost());
List<String> repoResults = RepositoryValidator.valid(repository, postRepository, false);
logger.info("--------- POST Validation---------");
List<String> outputResults = OutputValidator.valid(Hex.toHexString(programResult.getHReturn()), stateTestCase.getOut());
List<String> results = new ArrayList<>();
results.addAll(repoResults);
results.addAll(logsResult);
results.addAll(outputResults);
for (String result : results) {
logger.error(result);
}
logger.info("\n\n");
return results;
}
use of co.rsk.core.bc.BlockChainImpl in project rskj by rsksmart.
the class Web3ImplLogsTest method newFilterGetChangesAfterBlock.
@Test
public void newFilterGetChangesAfterBlock() throws Exception {
World world = new World();
Account acc1 = new AccountBuilder(world).name("notDefault").balance(Coin.valueOf(10000000)).build();
BlockChainImpl blockChain = world.getBlockChain();
TransactionPool transactionPool = new TransactionPoolImpl(config, world.getRepository(), blockChain.getBlockStore(), null, null, null, 10, 100);
SimpleEthereum eth = new SimpleEthereum();
eth.repository = world.getBlockChain().getRepository();
eth.blockchain = world.getBlockChain();
Web3Impl web3 = createWeb3(eth, world.getBlockChain(), transactionPool, WalletFactory.createWallet());
// TODO tricky link to listener
blockChain.setListener(web3.setupListener());
web3.personal_newAccountWithSeed("notDefault");
Web3.FilterRequest fr = new Web3.FilterRequest();
fr.fromBlock = "earliest";
String id = web3.eth_newFilter(fr);
Block genesis = world.getBlockByName("g00");
Transaction tx;
tx = getContractTransaction(acc1);
List<Transaction> txs = new ArrayList<>();
txs.add(tx);
Block block1 = new BlockBuilder(world).parent(genesis).transactions(txs).build();
blockChain.tryToConnect(block1);
Object[] logs = web3.eth_getFilterChanges(id);
Assert.assertNotNull(id);
Assert.assertNotNull(logs);
// TODO Fix
Assert.assertEquals(1, logs.length);
Assert.assertEquals("0x" + tx.getContractAddress().toString(), ((LogFilterElement) logs[0]).address);
}
Aggregations