Search in sources :

Example 21 with ProofOfWorkRule

use of co.rsk.validators.ProofOfWorkRule in project rskj by rsksmart.

the class SyncProcessorTest method processBlockHeadersResponseWithManyHeadersMissingFirstParent.

@Test
public void processBlockHeadersResponseWithManyHeadersMissingFirstParent() {
    Blockchain blockchain = BlockChainBuilder.ofSize(0);
    Blockchain otherBlockchain = BlockChainBuilder.ofSize(10, true);
    SimpleMessageChannel sender = new SimpleMessageChannel(new byte[] { 0x01 });
    SyncConfiguration syncConfiguration = SyncConfiguration.IMMEDIATE_FOR_TESTING;
    RskSystemProperties config = new RskSystemProperties();
    BlockSyncService blockSyncService = new BlockSyncService(config, new BlockStore(), blockchain, new BlockNodeInformation(), syncConfiguration);
    SyncProcessor processor = new SyncProcessor(config, blockchain, blockSyncService, RskMockFactory.getPeerScoringManager(), getChannelManager(), syncConfiguration, new ProofOfWorkRule(config).setFallbackMiningEnabled(false), DIFFICULTY_CALCULATOR);
    processor.setSelectedPeer(sender, StatusUtils.getFakeStatus(), 0);
    List<BlockHeader> headers = new ArrayList<>();
    for (int k = 10; k >= 2; k--) headers.add(otherBlockchain.getBlockByNumber(k).getHeader());
    BlockHeadersResponseMessage response = new BlockHeadersResponseMessage(new Random().nextLong(), headers);
    processor.registerExpectedMessage(response);
    processor.processBlockHeadersResponse(sender, response);
    Assert.assertEquals(0, sender.getMessages().size());
    Assert.assertEquals(0, processor.getExpectedResponses().size());
}
Also used : SimpleMessageChannel(co.rsk.net.simples.SimpleMessageChannel) ProofOfWorkRule(co.rsk.validators.ProofOfWorkRule) RskSystemProperties(co.rsk.config.RskSystemProperties) SyncConfiguration(co.rsk.net.sync.SyncConfiguration) Test(org.junit.Test)

Example 22 with ProofOfWorkRule

use of co.rsk.validators.ProofOfWorkRule in project rskj by rsksmart.

the class SyncProcessorTest method syncWithAdvancedPeerAfterTimeoutWaitingPeers.

@Test
public void syncWithAdvancedPeerAfterTimeoutWaitingPeers() {
    final BlockStore store = new BlockStore();
    Blockchain blockchain = BlockChainBuilder.ofSize(0);
    byte[] hash = HashUtil.randomHash();
    byte[] parentHash = HashUtil.randomHash();
    Status status = new Status(100, hash, parentHash, blockchain.getTotalDifficulty().add(new BlockDifficulty(BigInteger.TEN)));
    BlockNodeInformation nodeInformation = new BlockNodeInformation();
    RskSystemProperties config = new RskSystemProperties();
    BlockSyncService blockSyncService = new BlockSyncService(config, store, blockchain, nodeInformation, SyncConfiguration.IMMEDIATE_FOR_TESTING);
    SyncConfiguration syncConfiguration = SyncConfiguration.DEFAULT;
    SimpleMessageChannel sender = new SimpleMessageChannel(new byte[] { 0x01 });
    final ChannelManager channelManager = mock(ChannelManager.class);
    Channel channel = mock(Channel.class);
    when(channel.getNodeId()).thenReturn(sender.getPeerNodeID());
    when(channelManager.getActivePeers()).thenReturn(Collections.singletonList(channel));
    final List<Message> messages = new ArrayList<>();
    when(channelManager.sendMessageTo(eq(sender.getPeerNodeID()), any())).then((InvocationOnMock invocation) -> {
        messages.add(invocation.getArgumentAt(1, Message.class));
        return true;
    });
    SyncProcessor processor = new SyncProcessor(config, blockchain, blockSyncService, RskMockFactory.getPeerScoringManager(), channelManager, syncConfiguration, new ProofOfWorkRule(config).setFallbackMiningEnabled(false), DIFFICULTY_CALCULATOR);
    processor.processStatus(sender, status);
    Assert.assertEquals(1, processor.getPeersCount());
    Assert.assertEquals(1, processor.getNoAdvancedPeers());
    Set<NodeID> ids = processor.getKnownPeersNodeIDs();
    Assert.assertFalse(ids.isEmpty());
    Assert.assertTrue(ids.contains(sender.getPeerNodeID()));
    Assert.assertTrue(messages.isEmpty());
    processor.onTimePassed(syncConfiguration.getTimeoutWaitingPeers().dividedBy(2));
    Assert.assertTrue(messages.isEmpty());
    processor.onTimePassed(syncConfiguration.getTimeoutWaitingPeers().dividedBy(2));
    Assert.assertFalse(messages.isEmpty());
    Assert.assertEquals(1, messages.size());
    Message message = messages.get(0);
    Assert.assertEquals(MessageType.BLOCK_HEADERS_REQUEST_MESSAGE, message.getMessageType());
    BlockHeadersRequestMessage request = (BlockHeadersRequestMessage) message;
    Assert.assertEquals(status.getBestBlockHash(), request.getHash());
}
Also used : SimpleChannelManager(org.ethereum.rpc.Simples.SimpleChannelManager) ChannelManager(org.ethereum.net.server.ChannelManager) SimpleMessageChannel(co.rsk.net.simples.SimpleMessageChannel) SimpleMessageChannel(co.rsk.net.simples.SimpleMessageChannel) Channel(org.ethereum.net.server.Channel) ProofOfWorkRule(co.rsk.validators.ProofOfWorkRule) BlockDifficulty(co.rsk.core.BlockDifficulty) InvocationOnMock(org.mockito.invocation.InvocationOnMock) RskSystemProperties(co.rsk.config.RskSystemProperties) SyncConfiguration(co.rsk.net.sync.SyncConfiguration) Test(org.junit.Test)

Example 23 with ProofOfWorkRule

use of co.rsk.validators.ProofOfWorkRule in project rskj by rsksmart.

the class SyncProcessorTest method processBlockHeadersResponseWithOneExistingHeader.

@Test
public void processBlockHeadersResponseWithOneExistingHeader() {
    Blockchain blockchain = BlockChainBuilder.ofSize(3);
    Block block = blockchain.getBlockByNumber(2);
    SimpleMessageChannel sender = new SimpleMessageChannel(new byte[] { 0x01 });
    SyncConfiguration syncConfiguration = SyncConfiguration.IMMEDIATE_FOR_TESTING;
    RskSystemProperties config = new RskSystemProperties();
    BlockSyncService blockSyncService = new BlockSyncService(config, new BlockStore(), blockchain, new BlockNodeInformation(), syncConfiguration);
    SyncProcessor processor = new SyncProcessor(config, blockchain, blockSyncService, RskMockFactory.getPeerScoringManager(), getChannelManager(), syncConfiguration, new ProofOfWorkRule(config).setFallbackMiningEnabled(false), DIFFICULTY_CALCULATOR);
    processor.setSelectedPeer(sender, StatusUtils.getFakeStatus(), 0);
    List<BlockHeader> headers = new ArrayList<>();
    headers.add(block.getHeader());
    BlockHeadersResponseMessage response = new BlockHeadersResponseMessage(new Random().nextLong(), headers);
    processor.registerExpectedMessage(response);
    processor.processBlockHeadersResponse(sender, response);
    Assert.assertEquals(0, sender.getMessages().size());
    Assert.assertEquals(0, processor.getExpectedResponses().size());
}
Also used : SimpleMessageChannel(co.rsk.net.simples.SimpleMessageChannel) ProofOfWorkRule(co.rsk.validators.ProofOfWorkRule) RskSystemProperties(co.rsk.config.RskSystemProperties) SyncConfiguration(co.rsk.net.sync.SyncConfiguration) Test(org.junit.Test)

Example 24 with ProofOfWorkRule

use of co.rsk.validators.ProofOfWorkRule in project rskj by rsksmart.

the class MainNetMinerTest method generateFallbackMinedBlock.

@Test
public void generateFallbackMinedBlock() throws InterruptedException, IOException {
    // generate private keys for testing now.
    ECKey privateMiningKey0 = ECKey.fromPrivate(BigInteger.TEN);
    ECKey privateMiningKey1 = ECKey.fromPrivate(BigInteger.TEN.add(BigInteger.ONE));
    byte[] privKey0 = privateMiningKey0.getPrivKeyBytes();
    saveToFile(privKey0, new File(folder.getRoot().getCanonicalPath(), "privkey0.bin"));
    byte[] privKey1 = privateMiningKey1.getPrivKeyBytes();
    saveToFile(privKey1, new File(folder.getRoot().getCanonicalPath(), "privkey1.bin"));
    RskSystemProperties tempConfig = new RskSystemProperties() {

        BlockchainNetConfig blockchainNetConfig = config.getBlockchainConfig();

        @Override
        public String fallbackMiningKeysDir() {
            try {
                return folder.getRoot().getCanonicalPath();
            } catch (Exception e) {
            }
            return null;
        }

        @Override
        public BlockchainNetConfig getBlockchainConfig() {
            return new BlockchainNetConfig() {

                @Override
                public BlockchainConfig getConfigForBlock(long blockNumber) {
                    return blockchainNetConfig.getConfigForBlock(blockNumber);
                }

                @Override
                public Constants getCommonConstants() {
                    return new Constants() {

                        @Override
                        public byte[] getFallbackMiningPubKey0() {
                            return privateMiningKey0.getPubKey();
                        }

                        @Override
                        public byte[] getFallbackMiningPubKey1() {
                            return privateMiningKey1.getPubKey();
                        }
                    };
                }
            };
        }
    };
    EthereumImpl ethereumImpl = Mockito.mock(EthereumImpl.class);
    Mockito.when(ethereumImpl.addNewMinedBlock(Mockito.any())).thenReturn(ImportResult.IMPORTED_BEST);
    MinerServer minerServer = new MinerServerImpl(tempConfig, ethereumImpl, blockchain, null, DIFFICULTY_CALCULATOR, new ProofOfWorkRule(tempConfig).setFallbackMiningEnabled(true), blockToMineBuilder(), ConfigUtils.getDefaultMiningConfig());
    try {
        minerServer.setFallbackMining(true);
        // Accelerate mining
        ((MinerServerImpl) minerServer).setSecsBetweenFallbackMinedBlocks(1);
        minerServer.start();
        // Blocks are generated auomatically
        // but we can call minerServer.generateFallbackBlock() to generate it manually
        // boolean result = minerServer.generateFallbackBlock();
        // Assert.assertTrue(result);
        long start = System.currentTimeMillis();
        while (((MinerServerImpl) minerServer).getFallbackBlocksGenerated() == 0) {
            if (System.currentTimeMillis() - start > 20 * 1000) {
                Assert.assertTrue(false);
            }
            // 
            Thread.sleep(1000);
        }
        Mockito.verify(ethereumImpl, Mockito.times(1)).addNewMinedBlock(Mockito.any());
        // mine another
        // NOTE that is NOT using the next block (parity change) because of the blockchain mockito
        // to mine a subsequent block, use a real blockchain, not the mockito.
        minerServer.buildBlockToMine(blockchain.getBestBlock(), false);
        // result = minerServer.generateFallbackBlock();
        // Assert.assertTrue(result);
        start = System.currentTimeMillis();
        while (((MinerServerImpl) minerServer).getFallbackBlocksGenerated() == 1) {
            if (System.currentTimeMillis() - start > 20 * 1000) {
                Assert.assertTrue(false);
            }
            // 
            Thread.sleep(1000);
        }
        Mockito.verify(ethereumImpl, Mockito.times(2)).addNewMinedBlock(Mockito.any());
    } finally {
        minerServer.stop();
    }
}
Also used : Constants(org.ethereum.config.Constants) ECKey(org.ethereum.crypto.ECKey) BlockchainNetConfig(org.ethereum.config.BlockchainNetConfig) EthereumImpl(org.ethereum.facade.EthereumImpl) File(java.io.File) RskSystemProperties(co.rsk.config.RskSystemProperties) IOException(java.io.IOException) ProofOfWorkRule(co.rsk.validators.ProofOfWorkRule) Test(org.junit.Test) BlockChainImplTest(co.rsk.core.bc.BlockChainImplTest)

Example 25 with ProofOfWorkRule

use of co.rsk.validators.ProofOfWorkRule in project rskj by rsksmart.

the class MinerServerTest method submitBitcoinBlockPartialMerkleWhenBlockIsEmpty.

@Test
public void submitBitcoinBlockPartialMerkleWhenBlockIsEmpty() {
    EthereumImpl ethereumImpl = Mockito.mock(EthereumImpl.class);
    Mockito.when(ethereumImpl.addNewMinedBlock(Mockito.any())).thenReturn(ImportResult.IMPORTED_BEST);
    BlockUnclesValidationRule unclesValidationRule = Mockito.mock(BlockUnclesValidationRule.class);
    Mockito.when(unclesValidationRule.isValid(Mockito.any())).thenReturn(true);
    MinerServer minerServer = new MinerServerImpl(config, ethereumImpl, blockchain, null, DIFFICULTY_CALCULATOR, new ProofOfWorkRule(config).setFallbackMiningEnabled(false), new BlockToMineBuilder(ConfigUtils.getDefaultMiningConfig(), blockchain.getRepository(), blockchain.getBlockStore(), blockchain.getTransactionPool(), DIFFICULTY_CALCULATOR, new GasLimitCalculator(config), unclesValidationRule, config, null), ConfigUtils.getDefaultMiningConfig());
    try {
        minerServer.start();
        MinerWork work = minerServer.getWork();
        BtcBlock bitcoinMergedMiningBlock = getMergedMiningBlockWithOnlyCoinbase(work);
        findNonce(work, bitcoinMergedMiningBlock);
        // noinspection ConstantConditions
        BtcTransaction coinbase = bitcoinMergedMiningBlock.getTransactions().get(0);
        List<String> coinbaseReversedHash = Collections.singletonList(Sha256Hash.wrap(coinbase.getHash().getReversedBytes()).toString());
        SubmitBlockResult result = minerServer.submitBitcoinBlockPartialMerkle(work.getBlockHashForMergedMining(), bitcoinMergedMiningBlock, coinbase, coinbaseReversedHash, 1);
        Assert.assertEquals("OK", result.getStatus());
        Assert.assertNotNull(result.getBlockInfo());
        Assert.assertEquals("0x1", result.getBlockInfo().getBlockIncludedHeight());
        Assert.assertEquals("0x494d504f525445445f42455354", result.getBlockInfo().getBlockImportedResult());
        Mockito.verify(ethereumImpl, Mockito.times(1)).addNewMinedBlock(Mockito.any());
    } finally {
        minerServer.stop();
    }
}
Also used : EthereumImpl(org.ethereum.facade.EthereumImpl) ProofOfWorkRule(co.rsk.validators.ProofOfWorkRule) BlockUnclesValidationRule(co.rsk.validators.BlockUnclesValidationRule) Test(org.junit.Test)

Aggregations

ProofOfWorkRule (co.rsk.validators.ProofOfWorkRule)61 Test (org.junit.Test)57 SimpleMessageChannel (co.rsk.net.simples.SimpleMessageChannel)40 RskSystemProperties (co.rsk.config.RskSystemProperties)21 BlockGenerator (co.rsk.blockchain.utils.BlockGenerator)16 SyncConfiguration (co.rsk.net.sync.SyncConfiguration)16 SimpleBlockProcessor (co.rsk.net.simples.SimpleBlockProcessor)14 EthereumImpl (org.ethereum.facade.EthereumImpl)14 SimpleChannelManager (org.ethereum.rpc.Simples.SimpleChannelManager)13 World (co.rsk.test.World)11 BlockUnclesValidationRule (co.rsk.validators.BlockUnclesValidationRule)11 PeerScoringManager (co.rsk.scoring.PeerScoringManager)9 ChannelManager (org.ethereum.net.server.ChannelManager)9 Channel (org.ethereum.net.server.Channel)8 InvocationOnMock (org.mockito.invocation.InvocationOnMock)8 TxHandler (co.rsk.net.handler.TxHandler)7 PeerScoring (co.rsk.scoring.PeerScoring)7 BlockDifficulty (co.rsk.core.BlockDifficulty)6 SimpleTransactionPool (co.rsk.net.simples.SimpleTransactionPool)5 DownloadingBodiesSyncState (co.rsk.net.sync.DownloadingBodiesSyncState)4