Search in sources :

Example 26 with BlockDifficulty

use of co.rsk.core.BlockDifficulty in project rskj by rsksmart.

the class LocalBasicTest method runJsonTest.

private void runJsonTest(String jsonName, ActivationConfig activationConfig, Constants networkConstants) throws IOException {
    BlockFactory blockFactory = new BlockFactory(activationConfig);
    String json = getJSON(jsonName);
    DifficultyTestSuite testSuite = new DifficultyTestSuite(json);
    for (DifficultyTestCase testCase : testSuite.getTestCases()) {
        logger.info("Running {}\n", testCase.getName());
        BlockHeader current = testCase.getCurrent(blockFactory);
        BlockHeader parent = testCase.getParent(blockFactory);
        BlockDifficulty calc = new DifficultyCalculator(activationConfig, networkConstants).calcDifficulty(current, parent);
        int c = calc.compareTo(parent.getDifficulty());
        if (c > 0)
            logger.info(" Difficulty increase test\n");
        else if (c < 0)
            logger.info(" Difficulty decrease test\n");
        else
            logger.info(" Difficulty without change test\n");
        assertEquals(testCase.getExpectedDifficulty(), calc);
    }
}
Also used : DifficultyTestCase(org.ethereum.jsontestsuite.DifficultyTestCase) BlockDifficulty(co.rsk.core.BlockDifficulty) DifficultyCalculator(co.rsk.core.DifficultyCalculator) BlockFactory(org.ethereum.core.BlockFactory) BlockHeader(org.ethereum.core.BlockHeader) DifficultyTestSuite(org.ethereum.jsontestsuite.DifficultyTestSuite)

Example 27 with BlockDifficulty

use of co.rsk.core.BlockDifficulty in project rskj by rsksmart.

the class BlockToMineBuilderTest method setUp.

@Before
public void setUp() {
    validationRules = mock(BlockValidationRule.class);
    RepositoryLocator repositoryLocator = mock(RepositoryLocator.class);
    StateRootHandler stateRootHandler = mock(StateRootHandler.class);
    MiningConfig miningConfig = mock(MiningConfig.class);
    DifficultyCalculator difficultyCalculator = mock(DifficultyCalculator.class);
    MinimumGasPriceCalculator minimumGasPriceCalculator = mock(MinimumGasPriceCalculator.class);
    MinerUtils minerUtils = mock(MinerUtils.class);
    activationConfig = mock(ActivationConfig.class);
    blockExecutor = mock(BlockExecutor.class);
    blockBuilder = new BlockToMineBuilder(activationConfig, miningConfig, repositoryLocator, mock(BlockStore.class), mock(TransactionPool.class), difficultyCalculator, new GasLimitCalculator(Constants.mainnet()), new ForkDetectionDataCalculator(), validationRules, mock(MinerClock.class), new BlockFactory(activationConfig), blockExecutor, minimumGasPriceCalculator, minerUtils);
    BlockDifficulty blockDifficulty = mock(BlockDifficulty.class);
    Repository snapshot = mock(Repository.class);
    GasLimitConfig gasLimitConfig = new GasLimitConfig(0, 0, false);
    when(minerUtils.getAllTransactions(any())).thenReturn(new ArrayList<>());
    when(minerUtils.filterTransactions(any(), any(), any(), any(), any())).thenReturn(new ArrayList<>());
    when(repositoryLocator.snapshotAt(any())).thenReturn(snapshot);
    when(minimumGasPriceCalculator.calculate(any())).thenReturn(mock(Coin.class));
    when(stateRootHandler.translate(any())).thenReturn(TestUtils.randomHash());
    when(miningConfig.getGasLimit()).thenReturn(gasLimitConfig);
    when(miningConfig.getUncleListLimit()).thenReturn(10);
    when(miningConfig.getCoinbaseAddress()).thenReturn(TestUtils.randomAddress());
    when(difficultyCalculator.calcDifficulty(any(), any())).thenReturn(blockDifficulty);
}
Also used : BlockExecutor(co.rsk.core.bc.BlockExecutor) ActivationConfig(org.ethereum.config.blockchain.upgrades.ActivationConfig) RepositoryLocator(co.rsk.db.RepositoryLocator) StateRootHandler(co.rsk.db.StateRootHandler) MiningConfig(co.rsk.config.MiningConfig) DifficultyCalculator(co.rsk.core.DifficultyCalculator) BlockDifficulty(co.rsk.core.BlockDifficulty) Coin(co.rsk.core.Coin) GasLimitConfig(co.rsk.config.GasLimitConfig) BlockValidationRule(co.rsk.validators.BlockValidationRule) Before(org.junit.Before)

Example 28 with BlockDifficulty

use of co.rsk.core.BlockDifficulty in project rskj by rsksmart.

the class BlockFactory method decodeHeader.

private BlockHeader decodeHeader(RLPList rlpHeader, boolean sealed) {
    byte[] parentHash = rlpHeader.get(0).getRLPData();
    byte[] unclesHash = rlpHeader.get(1).getRLPData();
    byte[] coinBaseBytes = rlpHeader.get(2).getRLPData();
    RskAddress coinbase = RLP.parseRskAddress(coinBaseBytes);
    byte[] stateRoot = rlpHeader.get(3).getRLPData();
    if (stateRoot == null) {
        stateRoot = EMPTY_TRIE_HASH;
    }
    byte[] txTrieRoot = rlpHeader.get(4).getRLPData();
    if (txTrieRoot == null) {
        txTrieRoot = EMPTY_TRIE_HASH;
    }
    byte[] receiptTrieRoot = rlpHeader.get(5).getRLPData();
    if (receiptTrieRoot == null) {
        receiptTrieRoot = EMPTY_TRIE_HASH;
    }
    byte[] logsBloom = rlpHeader.get(6).getRLPData();
    byte[] difficultyBytes = rlpHeader.get(7).getRLPData();
    BlockDifficulty difficulty = RLP.parseBlockDifficulty(difficultyBytes);
    byte[] nrBytes = rlpHeader.get(8).getRLPData();
    byte[] glBytes = rlpHeader.get(9).getRLPData();
    byte[] guBytes = rlpHeader.get(10).getRLPData();
    byte[] tsBytes = rlpHeader.get(11).getRLPData();
    long blockNumber = parseBigInteger(nrBytes).longValueExact();
    long gasUsed = parseBigInteger(guBytes).longValueExact();
    long timestamp = parseBigInteger(tsBytes).longValueExact();
    byte[] extraData = rlpHeader.get(12).getRLPData();
    Coin paidFees = RLP.parseCoin(rlpHeader.get(13).getRLPData());
    byte[] minimumGasPriceBytes = rlpHeader.get(14).getRLPData();
    Coin minimumGasPrice = RLP.parseSignedCoinNonNullZero(minimumGasPriceBytes);
    if (!canBeDecoded(rlpHeader, blockNumber)) {
        throw new IllegalArgumentException(String.format("A block header must have 16/17 elements or 19/20 including merged-mining fields but it had %d", rlpHeader.size()));
    }
    int r = 15;
    boolean isUmm = activationConfig.isActive(ConsensusRule.RSKIPUMM, blockNumber);
    boolean includeUncleCount = isUmm || // sizes prior to UMM activation
    rlpHeader.size() == (RLP_HEADER_SIZE - 1) || rlpHeader.size() == (RLP_HEADER_SIZE_WITH_MERGED_MINING - 1);
    int uncleCount = 0;
    if (includeUncleCount) {
        byte[] ucBytes = rlpHeader.get(r++).getRLPData();
        uncleCount = parseBigInteger(ucBytes).intValueExact();
    }
    byte[] ummRoot = null;
    if (isUmm) {
        ummRoot = rlpHeader.get(r++).getRLPRawData();
    }
    byte[] bitcoinMergedMiningHeader = null;
    byte[] bitcoinMergedMiningMerkleProof = null;
    byte[] bitcoinMergedMiningCoinbaseTransaction = null;
    if (rlpHeader.size() > r) {
        bitcoinMergedMiningHeader = rlpHeader.get(r++).getRLPData();
        bitcoinMergedMiningMerkleProof = rlpHeader.get(r++).getRLPRawData();
        bitcoinMergedMiningCoinbaseTransaction = rlpHeader.get(r++).getRLPData();
    }
    boolean useRskip92Encoding = activationConfig.isActive(ConsensusRule.RSKIP92, blockNumber);
    boolean includeForkDetectionData = activationConfig.isActive(ConsensusRule.RSKIP110, blockNumber) && blockNumber >= MiningConfig.REQUIRED_NUMBER_OF_BLOCKS_FOR_FORK_DETECTION_CALCULATION;
    if (blockNumber == Genesis.NUMBER) {
        return new GenesisHeader(parentHash, unclesHash, logsBloom, difficultyBytes, blockNumber, glBytes, gasUsed, timestamp, extraData, bitcoinMergedMiningHeader, bitcoinMergedMiningMerkleProof, bitcoinMergedMiningCoinbaseTransaction, minimumGasPriceBytes, useRskip92Encoding, coinBaseBytes, stateRoot);
    }
    return new BlockHeader(parentHash, unclesHash, coinbase, stateRoot, txTrieRoot, receiptTrieRoot, logsBloom, difficulty, blockNumber, glBytes, gasUsed, timestamp, extraData, paidFees, bitcoinMergedMiningHeader, bitcoinMergedMiningMerkleProof, bitcoinMergedMiningCoinbaseTransaction, new byte[0], minimumGasPrice, uncleCount, sealed, useRskip92Encoding, includeForkDetectionData, ummRoot);
}
Also used : BlockDifficulty(co.rsk.core.BlockDifficulty) Coin(co.rsk.core.Coin) RskAddress(co.rsk.core.RskAddress)

Example 29 with BlockDifficulty

use of co.rsk.core.BlockDifficulty in project rskj by rsksmart.

the class BlockDifficultyRule method isValid.

@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;
}
Also used : BlockDifficulty(co.rsk.core.BlockDifficulty)

Example 30 with BlockDifficulty

use of co.rsk.core.BlockDifficulty in project rskj by rsksmart.

the class CliToolsTest method exportBlocks.

@Test
public void exportBlocks() throws IOException, DslProcessorException {
    DslParser parser = DslParser.fromResource("dsl/blocks01.txt");
    World world = new World();
    WorldDslProcessor processor = new WorldDslProcessor(world);
    processor.processCommands(parser);
    File blocksFile = new File(tempFolder.getRoot(), "blocks.txt");
    String[] args = new String[] { "0", "2", blocksFile.getAbsolutePath() };
    RskContext rskContext = mock(RskContext.class);
    doReturn(world.getBlockStore()).when(rskContext).getBlockStore();
    NodeStopper stopper = mock(NodeStopper.class);
    ExportBlocks exportBlocksCliTool = new ExportBlocks();
    exportBlocksCliTool.execute(args, () -> rskContext, stopper);
    String data = new String(Files.readAllBytes(blocksFile.toPath()), StandardCharsets.UTF_8);
    Blockchain blockchain = world.getBlockChain();
    BlockStore blockStore = world.getBlockStore();
    for (long n = 0; n < 3; n++) {
        Block block = blockchain.getBlockByNumber(n);
        BlockDifficulty totalDifficulty = blockStore.getTotalDifficultyForHash(block.getHash().getBytes());
        String line = block.getNumber() + "," + block.getHash().toHexString() + "," + ByteUtil.toHexString(totalDifficulty.getBytes()) + "," + ByteUtil.toHexString(block.getEncoded());
        Assert.assertTrue(data.contains(line));
    }
    verify(stopper).stop(0);
}
Also used : WorldDslProcessor(co.rsk.test.dsl.WorldDslProcessor) IndexedBlockStore(org.ethereum.db.IndexedBlockStore) BlockStore(org.ethereum.db.BlockStore) Blockchain(org.ethereum.core.Blockchain) World(co.rsk.test.World) BlockDifficulty(co.rsk.core.BlockDifficulty) RskContext(co.rsk.RskContext) DslParser(co.rsk.test.dsl.DslParser) NodeStopper(co.rsk.util.NodeStopper) Block(org.ethereum.core.Block) Test(org.junit.Test) ActivationConfigsForTest(org.ethereum.config.blockchain.upgrades.ActivationConfigsForTest)

Aggregations

BlockDifficulty (co.rsk.core.BlockDifficulty)60 Test (org.junit.Test)32 Block (org.ethereum.core.Block)23 BigInteger (java.math.BigInteger)14 HashMapDB (org.ethereum.datasource.HashMapDB)11 Keccak256 (co.rsk.crypto.Keccak256)9 Ignore (org.junit.Ignore)9 BlockGenerator (co.rsk.blockchain.utils.BlockGenerator)8 BlockHeader (org.ethereum.core.BlockHeader)7 ActivationConfigsForTest (org.ethereum.config.blockchain.upgrades.ActivationConfigsForTest)6 KeyValueDataSource (org.ethereum.datasource.KeyValueDataSource)6 Coin (co.rsk.core.Coin)5 MapDBBlocksIndex (co.rsk.db.MapDBBlocksIndex)5 LevelDbDataSource (org.ethereum.datasource.LevelDbDataSource)5 BlockStore (org.ethereum.db.BlockStore)5 DifficultyCalculator (co.rsk.core.DifficultyCalculator)4 BlockChainImpl (co.rsk.core.bc.BlockChainImpl)4 HashMapBlocksIndex (co.rsk.db.HashMapBlocksIndex)4 BlockChainBuilder (co.rsk.test.builders.BlockChainBuilder)4 ArrayList (java.util.ArrayList)4