Search in sources :

Example 81 with Coin

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

the class TestRunner method runTestCase.

public List<String> runTestCase(TestCase testCase) {
    logger.info("\n***");
    logger.info(" Running test case: [" + testCase.getName() + "]");
    logger.info("***\n");
    List<String> results = new ArrayList<>();
    logger.info("--------- PRE ---------");
    Repository repository = loadRepository(new RepositoryImpl(config).startTracking(), testCase.getPre());
    try {
        /* 2. Create ProgramInvoke - Env/Exec */
        Env env = testCase.getEnv();
        Exec exec = testCase.getExec();
        Logs logs = testCase.getLogs();
        byte[] address = exec.getAddress();
        byte[] origin = exec.getOrigin();
        byte[] caller = exec.getCaller();
        byte[] balance = ByteUtil.bigIntegerToBytes(repository.getBalance(new RskAddress(exec.getAddress())).asBigInteger());
        byte[] gasPrice = exec.getGasPrice();
        byte[] gas = exec.getGas();
        byte[] callValue = exec.getValue();
        byte[] msgData = exec.getData();
        byte[] lastHash = env.getPreviousHash();
        byte[] coinbase = env.getCurrentCoinbase();
        long timestamp = ByteUtil.byteArrayToLong(env.getCurrentTimestamp());
        long number = ByteUtil.byteArrayToLong(env.getCurrentNumber());
        byte[] difficulty = env.getCurrentDifficulty();
        byte[] gaslimit = env.getCurrentGasLimit();
        // Origin and caller need to exist in order to be able to execute
        if (repository.getAccountState(new RskAddress(origin)) == null)
            repository.createAccount(new RskAddress(origin));
        if (repository.getAccountState(new RskAddress(caller)) == null)
            repository.createAccount(new RskAddress(caller));
        ProgramInvoke programInvoke = new ProgramInvokeImpl(address, origin, caller, balance, gasPrice, gas, callValue, msgData, lastHash, coinbase, timestamp, number, 0, difficulty, gaslimit, repository, new BlockStoreDummy(), true);
        /* 3. Create Program - exec.code */
        /* 4. run VM */
        VM vm = new VM(vmConfig, precompiledContracts);
        Program program = new Program(vmConfig, precompiledContracts, mock(BlockchainConfig.class), exec.getCode(), programInvoke, null);
        boolean vmDidThrowAnEception = false;
        Exception e = null;
        ThreadMXBean thread;
        Boolean oldMode;
        long startTime = 0;
        thread = ManagementFactory.getThreadMXBean();
        if (thread.isThreadCpuTimeSupported()) {
            oldMode = thread.isThreadCpuTimeEnabled();
            thread.setThreadCpuTimeEnabled(true);
            // in nanoseconds.
            startTime = thread.getCurrentThreadCpuTime();
        }
        try {
            vm.steps(program, Long.MAX_VALUE);
            ;
        } catch (RuntimeException ex) {
            vmDidThrowAnEception = true;
            e = ex;
        }
        if (startTime != 0) {
            long endTime = thread.getCurrentThreadCpuTime();
            // de nano a micro.
            long deltaTime = (endTime - startTime) / 1000;
            logger.info("Time elapsed [uS]: " + Long.toString(deltaTime));
        }
        try {
            saveProgramTraceFile(config, testCase.getName(), program.getTrace());
        } catch (IOException ioe) {
            vmDidThrowAnEception = true;
            e = ioe;
        }
        if (testCase.getPost().size() == 0) {
            if (vmDidThrowAnEception != true) {
                String output = "VM was expected to throw an exception";
                logger.info(output);
                results.add(output);
            } else
                logger.info("VM did throw an exception: " + e.toString());
        } else {
            if (vmDidThrowAnEception) {
                String output = "VM threw an unexpected exception: " + e.toString();
                logger.info(output, e);
                results.add(output);
                return results;
            }
            this.trace = program.getTrace();
            logger.info("--------- POST --------");
            /* 5. Assert Post values */
            for (RskAddress addr : testCase.getPost().keySet()) {
                AccountState accountState = testCase.getPost().get(addr);
                long expectedNonce = accountState.getNonceLong();
                Coin expectedBalance = accountState.getBalance();
                byte[] expectedCode = accountState.getCode();
                boolean accountExist = (null != repository.getAccountState(addr));
                if (!accountExist) {
                    String output = String.format("The expected account does not exist. key: [ %s ]", addr);
                    logger.info(output);
                    results.add(output);
                    continue;
                }
                long actualNonce = repository.getNonce(addr).longValue();
                Coin actualBalance = repository.getBalance(addr);
                byte[] actualCode = repository.getCode(addr);
                if (actualCode == null)
                    actualCode = "".getBytes();
                if (expectedNonce != actualNonce) {
                    String output = String.format("The nonce result is different. key: [ %s ],  expectedNonce: [ %d ] is actualNonce: [ %d ] ", addr, expectedNonce, actualNonce);
                    logger.info(output);
                    results.add(output);
                }
                if (!expectedBalance.equals(actualBalance)) {
                    String output = String.format("The balance result is different. key: [ %s ],  expectedBalance: [ %s ] is actualBalance: [ %s ] ", addr, expectedBalance.toString(), actualBalance.toString());
                    logger.info(output);
                    results.add(output);
                }
                if (!Arrays.equals(expectedCode, actualCode)) {
                    String output = String.format("The code result is different. account: [ %s ],  expectedCode: [ %s ] is actualCode: [ %s ] ", addr, Hex.toHexString(expectedCode), Hex.toHexString(actualCode));
                    logger.info(output);
                    results.add(output);
                }
                // assert storage
                Map<DataWord, DataWord> storage = accountState.getStorage();
                for (DataWord storageKey : storage.keySet()) {
                    byte[] expectedStValue = storage.get(storageKey).getData();
                    ContractDetails contractDetails = program.getStorage().getContractDetails(accountState.getAddress());
                    if (contractDetails == null) {
                        String output = String.format("Storage raw doesn't exist: key [ %s ], expectedValue: [ %s ]", Hex.toHexString(storageKey.getData()), Hex.toHexString(expectedStValue));
                        logger.info(output);
                        results.add(output);
                        continue;
                    }
                    Map<DataWord, DataWord> testStorage = contractDetails.getStorage();
                    DataWord actualValue = testStorage.get(new DataWord(storageKey.getData()));
                    if (actualValue == null || !Arrays.equals(expectedStValue, actualValue.getData())) {
                        String output = String.format("Storage value different: key [ %s ], expectedValue: [ %s ], actualValue: [ %s ]", Hex.toHexString(storageKey.getData()), Hex.toHexString(expectedStValue), actualValue == null ? "" : Hex.toHexString(actualValue.getNoLeadZeroesData()));
                        logger.info(output);
                        results.add(output);
                    }
                }
                /* asset logs */
                List<LogInfo> logResult = program.getResult().getLogInfoList();
                Iterator<LogInfo> postLogs = logs.getIterator();
                int i = 0;
                while (postLogs.hasNext()) {
                    LogInfo expectedLogInfo = postLogs.next();
                    LogInfo foundLogInfo = null;
                    if (logResult.size() > i) {
                        foundLogInfo = logResult.get(i);
                    }
                    if (foundLogInfo == null) {
                        String output = String.format("Expected log [ %s ]", expectedLogInfo.toString());
                        logger.info(output);
                        results.add(output);
                    } else {
                        if (!Arrays.equals(expectedLogInfo.getAddress(), foundLogInfo.getAddress())) {
                            String output = String.format("Expected address [ %s ], found [ %s ]", Hex.toHexString(expectedLogInfo.getAddress()), Hex.toHexString(foundLogInfo.getAddress()));
                            logger.info(output);
                            results.add(output);
                        }
                        if (!Arrays.equals(expectedLogInfo.getData(), foundLogInfo.getData())) {
                            String output = String.format("Expected data [ %s ], found [ %s ]", Hex.toHexString(expectedLogInfo.getData()), Hex.toHexString(foundLogInfo.getData()));
                            logger.info(output);
                            results.add(output);
                        }
                        if (!expectedLogInfo.getBloom().equals(foundLogInfo.getBloom())) {
                            String output = String.format("Expected bloom [ %s ], found [ %s ]", Hex.toHexString(expectedLogInfo.getBloom().getData()), Hex.toHexString(foundLogInfo.getBloom().getData()));
                            logger.info(output);
                            results.add(output);
                        }
                        if (expectedLogInfo.getTopics().size() != foundLogInfo.getTopics().size()) {
                            String output = String.format("Expected number of topics [ %d ], found [ %d ]", expectedLogInfo.getTopics().size(), foundLogInfo.getTopics().size());
                            logger.info(output);
                            results.add(output);
                        } else {
                            int j = 0;
                            for (DataWord topic : expectedLogInfo.getTopics()) {
                                byte[] foundTopic = foundLogInfo.getTopics().get(j).getData();
                                if (!Arrays.equals(topic.getData(), foundTopic)) {
                                    String output = String.format("Expected topic [ %s ], found [ %s ]", Hex.toHexString(topic.getData()), Hex.toHexString(foundTopic));
                                    logger.info(output);
                                    results.add(output);
                                }
                                ++j;
                            }
                        }
                    }
                    ++i;
                }
            }
            // TODO: assert that you have no extra accounts in the repository
            // TODO:  -> basically the deleted by suicide should be deleted
            // TODO:  -> and no unexpected created
            List<org.ethereum.vm.CallCreate> resultCallCreates = program.getResult().getCallCreateList();
            // assert call creates
            for (int i = 0; i < testCase.getCallCreateList().size(); ++i) {
                org.ethereum.vm.CallCreate resultCallCreate = null;
                if (resultCallCreates != null && resultCallCreates.size() > i) {
                    resultCallCreate = resultCallCreates.get(i);
                }
                CallCreate expectedCallCreate = testCase.getCallCreateList().get(i);
                if (resultCallCreate == null && expectedCallCreate != null) {
                    String output = String.format("Missing call/create invoke: to: [ %s ], data: [ %s ], gas: [ %s ], value: [ %s ]", Hex.toHexString(expectedCallCreate.getDestination()), Hex.toHexString(expectedCallCreate.getData()), Long.toHexString(expectedCallCreate.getGasLimit()), Hex.toHexString(expectedCallCreate.getValue()));
                    logger.info(output);
                    results.add(output);
                    continue;
                }
                boolean assertDestination = Arrays.equals(expectedCallCreate.getDestination(), resultCallCreate.getDestination());
                if (!assertDestination) {
                    String output = String.format("Call/Create destination is different. Expected: [ %s ], result: [ %s ]", Hex.toHexString(expectedCallCreate.getDestination()), Hex.toHexString(resultCallCreate.getDestination()));
                    logger.info(output);
                    results.add(output);
                }
                boolean assertData = Arrays.equals(expectedCallCreate.getData(), resultCallCreate.getData());
                if (!assertData) {
                    String output = String.format("Call/Create data is different. Expected: [ %s ], result: [ %s ]", Hex.toHexString(expectedCallCreate.getData()), Hex.toHexString(resultCallCreate.getData()));
                    logger.info(output);
                    results.add(output);
                }
                boolean assertGasLimit = expectedCallCreate.getGasLimit() == resultCallCreate.getGasLimit();
                if (!assertGasLimit) {
                    String output = String.format("Call/Create gasLimit is different. Expected: [ %s ], result: [ %s ]", Long.toHexString(expectedCallCreate.getGasLimit()), Long.toHexString(resultCallCreate.getGasLimit()));
                    logger.info(output);
                    results.add(output);
                }
                boolean assertValue = Arrays.equals(expectedCallCreate.getValue(), resultCallCreate.getValue());
                if (!assertValue) {
                    String output = String.format("Call/Create value is different. Expected: [ %s ], result: [ %s ]", Hex.toHexString(expectedCallCreate.getValue()), Hex.toHexString(resultCallCreate.getValue()));
                    logger.info(output);
                    results.add(output);
                }
            }
            // assert out
            byte[] expectedHReturn = testCase.getOut();
            byte[] actualHReturn = EMPTY_BYTE_ARRAY;
            if (program.getResult().getHReturn() != null) {
                actualHReturn = program.getResult().getHReturn();
            }
            if (!Arrays.equals(expectedHReturn, actualHReturn)) {
                String output = String.format("HReturn is different. Expected hReturn: [ %s ], actual hReturn: [ %s ]", Hex.toHexString(expectedHReturn), Hex.toHexString(actualHReturn));
                logger.info(output);
                results.add(output);
            }
            // assert gas
            BigInteger expectedGas = new BigInteger(1, testCase.getGas());
            BigInteger actualGas = new BigInteger(1, gas).subtract(BigInteger.valueOf(program.getResult().getGasUsed()));
            if (validateGasUsed)
                if (!expectedGas.equals(actualGas)) {
                    String output = String.format("Gas remaining is different. Expected gas remaining: [ %s ], actual gas remaining: [ %s ]", expectedGas.toString(), actualGas.toString());
                    logger.info(output);
                    results.add(output);
                }
        /*
                 * end of if(testCase.getPost().size() == 0)
                 */
        }
        return results;
    } finally {
    // repository.close();
    }
}
Also used : DataWord(org.ethereum.vm.DataWord) ProgramInvokeImpl(org.ethereum.vm.program.invoke.ProgramInvokeImpl) ProgramInvoke(org.ethereum.vm.program.invoke.ProgramInvoke) Coin(co.rsk.core.Coin) RskAddress(co.rsk.core.RskAddress) ThreadMXBean(java.lang.management.ThreadMXBean) Program(org.ethereum.vm.program.Program) LogInfo(org.ethereum.vm.LogInfo) IOException(java.io.IOException) IOException(java.io.IOException) Repository(org.ethereum.core.Repository) BlockchainConfig(org.ethereum.config.BlockchainConfig) RepositoryImpl(co.rsk.db.RepositoryImpl) VM(org.ethereum.vm.VM) BigInteger(java.math.BigInteger)

Example 82 with Coin

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

the class RemascFeesPayerTest method payMiningFees.

@Test
public void payMiningFees() {
    // Setup objects
    Repository repositoryMock = Mockito.mock(Repository.class);
    RemascFeesPayer feesPayer = new RemascFeesPayer(repositoryMock, PrecompiledContracts.REMASC_ADDR);
    byte[] blockHash = { 0x1, 0x2 };
    Coin value = Coin.valueOf(7L);
    RskAddress toAddress = new RskAddress("6c386a4b26f73c802f34673f7248bb118f97424a");
    List<LogInfo> logs = new ArrayList<>();
    // Do call
    feesPayer.payMiningFees(blockHash, value, toAddress, logs);
    Assert.assertEquals(1, logs.size());
    // Assert address that made the log
    LogInfo result = logs.get(0);
    Assert.assertArrayEquals(PrecompiledContracts.REMASC_ADDR.getBytes(), result.getAddress());
    // Assert log topics
    Assert.assertEquals(2, result.getTopics().size());
    Assert.assertEquals("000000000000000000000000000000006d696e696e675f6665655f746f706963", result.getTopics().get(0).toString());
    Assert.assertEquals("0000000000000000000000006c386a4b26f73c802f34673f7248bb118f97424a", result.getTopics().get(1).toString());
    // Assert log data
    Assert.assertNotNull(result.getData());
    List<RLPElement> rlpData = RLP.decode2(result.getData());
    Assert.assertEquals(1, rlpData.size());
    RLPList dataList = (RLPList) rlpData.get(0);
    Assert.assertEquals(2, dataList.size());
    Assert.assertArrayEquals(blockHash, dataList.get(0).getRLPData());
    Assert.assertEquals(value, RLP.parseCoin(dataList.get(1).getRLPData()));
    // Assert repository calls are made right
    verify(repositoryMock, times(1)).addBalance(PrecompiledContracts.REMASC_ADDR, value.negate());
    verify(repositoryMock, times(1)).addBalance(toAddress, value);
}
Also used : Coin(co.rsk.core.Coin) Repository(org.ethereum.core.Repository) LogInfo(org.ethereum.vm.LogInfo) RLPElement(org.ethereum.util.RLPElement) RskAddress(co.rsk.core.RskAddress) ArrayList(java.util.ArrayList) RLPList(org.ethereum.util.RLPList) Test(org.junit.Test)

Example 83 with Coin

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

the class RemascProcessMinerFeesTest method processMinersFeesWithOneSiblingBrokenSelectionRule.

private void processMinersFeesWithOneSiblingBrokenSelectionRule(String reasonForBrokenSelectionRule) throws IOException, BlockStoreException {
    BlockChainBuilder builder = new BlockChainBuilder();
    Blockchain blockchain = builder.setTesting(true).setGenesis(genesisBlock).build();
    final long NUMBER_OF_TXS_WITH_FEES = 3;
    List<Block> blocks = createSimpleBlocks(this.genesisBlock, 4);
    Block blockWithOneTxA;
    Block blockWithOneTxB;
    if ("higherFees".equals(reasonForBrokenSelectionRule)) {
        blockWithOneTxA = RemascTestRunner.createBlock(this.genesisBlock, blocks.get(blocks.size() - 1), PegTestUtils.createHash3(), coinbaseA, null, minerFee, 0, txValue, cowKey);
        blockWithOneTxB = RemascTestRunner.createBlock(this.genesisBlock, blocks.get(blocks.size() - 1), PegTestUtils.createHash3(), coinbaseB, null, minerFee * 3, 0, txValue, cowKey);
    } else {
        Keccak256 blockWithOneTxBHash = PegTestUtils.createHash3();
        Keccak256 blockWithOneTxAHash = PegTestUtils.createHash3();
        blockWithOneTxA = RemascTestRunner.createBlock(this.genesisBlock, blocks.get(blocks.size() - 1), blockWithOneTxAHash, coinbaseA, null, minerFee, 0, txValue, cowKey);
        blockWithOneTxB = RemascTestRunner.createBlock(this.genesisBlock, blocks.get(blocks.size() - 1), blockWithOneTxBHash, coinbaseB, null, (long) (minerFee * 1.5), 0, txValue, cowKey);
    }
    blocks.add(blockWithOneTxA);
    Block blockThatIncludesUncleC = RemascTestRunner.createBlock(this.genesisBlock, blockWithOneTxA, PegTestUtils.createHash3(), coinbaseC, Lists.newArrayList(blockWithOneTxB.getHeader()), minerFee, 1, txValue, cowKey);
    blocks.add(blockThatIncludesUncleC);
    Block blockWithOneTxD = RemascTestRunner.createBlock(this.genesisBlock, blockThatIncludesUncleC, PegTestUtils.createHash3(), coinbaseD, null, minerFee, 2, txValue, cowKey);
    blocks.add(blockWithOneTxD);
    blocks.addAll(createSimpleBlocks(blockWithOneTxD, 7));
    BlockExecutor blockExecutor = new BlockExecutor(config, blockchain.getRepository(), null, blockchain.getBlockStore(), null);
    for (Block b : blocks) {
        blockExecutor.executeAndFillAll(b, blockchain.getBestBlock());
        blockchain.tryToConnect(b);
    }
    // validate that the blockchain's and REMASC's initial states are correct
    Coin cowRemainingBalance = cowInitialBalance.subtract(Coin.valueOf(minerFee * NUMBER_OF_TXS_WITH_FEES + txValue * NUMBER_OF_TXS_WITH_FEES));
    List<Long> otherAccountsBalance = new ArrayList<>(Arrays.asList(null, null, null, null));
    this.validateAccountsCurrentBalanceIsCorrect(blockchain.getRepository(), cowRemainingBalance, minerFee * NUMBER_OF_TXS_WITH_FEES, null, this.getAccountsWithExpectedBalance(otherAccountsBalance));
    this.validateRemascsStorageIsCorrect(this.getRemascStorageProvider(blockchain), Coin.ZERO, Coin.ZERO, 1L);
    // add block to pay fees of blocks on blockchain's height 5
    Block blockToPayFeesOnHeightFive = RemascTestRunner.createBlock(this.genesisBlock, blocks.get(blocks.size() - 1), PegTestUtils.createHash3(), TestUtils.randomAddress(), null, null);
    blockExecutor.executeAndFillAll(blockToPayFeesOnHeightFive, blockchain.getBestBlock());
    blockchain.tryToConnect(blockToPayFeesOnHeightFive);
    // -- After executing REMASC's contract for paying height 5 blocks
    // validate that account's balances are correct
    long blockRewardOnHeightFive = minerFee / remascConfig.getSyntheticSpan();
    long remascCurrentBalance = minerFee * 3 - blockRewardOnHeightFive;
    long rskReward = blockRewardOnHeightFive / remascConfig.getRskLabsDivisor();
    long rskCurrentBalance = rskReward;
    blockRewardOnHeightFive -= rskReward;
    long federationReward = blockRewardOnHeightFive / remascConfig.getFederationDivisor();
    blockRewardOnHeightFive -= federationReward;
    long publisherReward = blockRewardOnHeightFive / remascConfig.getPublishersDivisor();
    blockRewardOnHeightFive -= publisherReward;
    long minerRewardOnHeightFive = blockRewardOnHeightFive / 2;
    List<Long> otherAccountsBalanceOnHeightFive = new ArrayList<>(Arrays.asList(minerRewardOnHeightFive, minerRewardOnHeightFive, publisherReward, null));
    this.validateFederatorsBalanceIsCorrect(blockchain.getRepository(), federationReward);
    // TODO review value + 1
    this.validateAccountsCurrentBalanceIsCorrect(blockchain.getRepository(), cowRemainingBalance, remascCurrentBalance + 1, rskCurrentBalance, this.getAccountsWithExpectedBalance(otherAccountsBalanceOnHeightFive));
    // validate that REMASC's state is correct
    blockRewardOnHeightFive = minerFee / remascConfig.getSyntheticSpan();
    Coin expectedRewardBalance = Coin.valueOf(minerFee - blockRewardOnHeightFive);
    // TODO review burned value 1
    this.validateRemascsStorageIsCorrect(this.getRemascStorageProvider(blockchain), expectedRewardBalance, Coin.valueOf(1), 0L);
    // add block to pay fees of blocks on blockchain's height 6
    Block blockToPayFeesOnHeightSix = RemascTestRunner.createBlock(this.genesisBlock, blockToPayFeesOnHeightFive, PegTestUtils.createHash3(), TestUtils.randomAddress(), null, null);
    blockExecutor.executeAndFillAll(blockToPayFeesOnHeightSix, blockchain.getBestBlock());
    blockchain.tryToConnect(blockToPayFeesOnHeightSix);
    // -- After executing REMASC's contract for paying height 6 blocks
    // validate that account's balances are correct
    long rewardBalance = minerFee - blockRewardOnHeightFive + minerFee;
    long blockRewardOnHeightSix = rewardBalance / remascConfig.getSyntheticSpan();
    rewardBalance -= blockRewardOnHeightSix;
    rskReward = blockRewardOnHeightSix / remascConfig.getRskLabsDivisor();
    long blockRewardWithoutRskFee = blockRewardOnHeightSix - rskReward;
    long federationReward2 = blockRewardWithoutRskFee / remascConfig.getFederationDivisor();
    long blockRewardWithoutRskAndFederationFee = blockRewardWithoutRskFee - federationReward2;
    long burnedBalance = blockRewardWithoutRskAndFederationFee / remascConfig.getPunishmentDivisor();
    remascCurrentBalance = minerFee * NUMBER_OF_TXS_WITH_FEES - blockRewardOnHeightFive - blockRewardOnHeightSix + burnedBalance;
    rskCurrentBalance += blockRewardOnHeightSix / remascConfig.getRskLabsDivisor();
    blockRewardOnHeightSix -= blockRewardOnHeightSix / remascConfig.getRskLabsDivisor();
    blockRewardOnHeightSix -= blockRewardOnHeightSix / remascConfig.getFederationDivisor();
    blockRewardOnHeightSix -= blockRewardOnHeightSix / remascConfig.getPunishmentDivisor();
    List<Long> otherAccountsBalanceOnHeightSix = new ArrayList<>(Arrays.asList(minerRewardOnHeightFive, minerRewardOnHeightFive, publisherReward + blockRewardOnHeightSix, null));
    // TODO review + 1
    this.validateAccountsCurrentBalanceIsCorrect(blockchain.getRepository(), cowRemainingBalance, remascCurrentBalance + 1, rskCurrentBalance, this.getAccountsWithExpectedBalance(otherAccountsBalanceOnHeightSix));
    this.validateFederatorsBalanceIsCorrect(blockchain.getRepository(), federationReward + federationReward2);
    // TODO review + 1
    this.validateRemascsStorageIsCorrect(this.getRemascStorageProvider(blockchain), Coin.valueOf(rewardBalance), Coin.valueOf(burnedBalance + 1), 0L);
}
Also used : Coin(co.rsk.core.Coin) BlockExecutor(co.rsk.core.bc.BlockExecutor) Keccak256(co.rsk.crypto.Keccak256) BlockChainBuilder(co.rsk.test.builders.BlockChainBuilder)

Example 84 with Coin

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

the class RemascProcessMinerFeesTest method siblingIncludedSevenBlocksLater.

@Test
public void siblingIncludedSevenBlocksLater() throws IOException {
    BlockChainBuilder builder = new BlockChainBuilder().setTesting(true).setGenesis(genesisBlock);
    List<SiblingElement> siblings = Lists.newArrayList(new SiblingElement(5, 12, this.minerFee));
    RemascTestRunner testRunner = new RemascTestRunner(builder, this.genesisBlock).txValue(txValue).minerFee(this.minerFee).initialHeight(15).siblingElements(siblings).txSigningKey(this.cowKey);
    testRunner.start();
    Blockchain blockchain = testRunner.getBlockChain();
    Block blockAtHeightTwelve = blockchain.getBlockByNumber(13);
    assertEquals(Coin.valueOf(1680L - 17), testRunner.getAccountBalance(blockAtHeightTwelve.getCoinbase()));
    Block blockAtHeightFiveMainchain = blockchain.getBlockByNumber(6);
    assertEquals(Coin.valueOf(7560L - 76), testRunner.getAccountBalance(blockAtHeightFiveMainchain.getCoinbase()));
    Block blockAtHeightFiveSibling = testRunner.getAddedSiblings().get(0);
    assertEquals(Coin.valueOf(5292L - 53), testRunner.getAccountBalance(blockAtHeightFiveSibling.getCoinbase()));
    Coin remascCurrentBalance = testRunner.getAccountBalance(PrecompiledContracts.REMASC_ADDR);
    // TODO review value -22
    assertEquals(Coin.valueOf(296268L - 22), remascCurrentBalance);
    // TODO review value -22
    this.validateRemascsStorageIsCorrect(this.getRemascStorageProvider(blockchain), Coin.valueOf(84000L), Coin.valueOf(2268L - 22), 0L);
}
Also used : Coin(co.rsk.core.Coin) BlockChainBuilder(co.rsk.test.builders.BlockChainBuilder) Test(org.junit.Test)

Example 85 with Coin

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

the class RemascProcessMinerFeesTest method validateAccountsCurrentBalanceIsCorrect.

private void validateAccountsCurrentBalanceIsCorrect(Repository repository, Coin cowBalance, Long remascBalance, Long rskBalance, HashMap<byte[], Coin> otherAccountsBalance) {
    assertEquals(cowBalance, RemascTestRunner.getAccountBalance(repository, cowAddress));
    Coin remascExpectedBalance = Coin.valueOf(remascBalance);
    Coin remascActualBalance = RemascTestRunner.getAccountBalance(repository, PrecompiledContracts.REMASC_ADDR);
    assertEquals(remascExpectedBalance, remascActualBalance);
    Coin rskExpectedBalance = rskBalance == null ? null : Coin.valueOf(rskBalance);
    assertEquals(rskExpectedBalance, RemascTestRunner.getAccountBalance(repository, remascConfig.getRskLabsAddress()));
    for (Map.Entry<byte[], Coin> entry : otherAccountsBalance.entrySet()) {
        Coin actualBalance = RemascTestRunner.getAccountBalance(repository, entry.getKey());
        assertEquals("Failed for: " + Hex.toHexString(entry.getKey()), entry.getValue(), actualBalance);
    }
}
Also used : Coin(co.rsk.core.Coin)

Aggregations

Coin (co.rsk.core.Coin)95 Test (org.junit.Test)46 RskAddress (co.rsk.core.RskAddress)37 BigInteger (java.math.BigInteger)32 Repository (org.ethereum.core.Repository)23 Transaction (org.ethereum.core.Transaction)23 Program (org.ethereum.vm.program.Program)12 AccountState (org.ethereum.core.AccountState)10 ArrayList (java.util.ArrayList)9 Ignore (org.junit.Ignore)9 ProgramInvokeMockImpl (org.ethereum.vm.program.invoke.ProgramInvokeMockImpl)8 Account (org.ethereum.core.Account)7 BlockExecutor (co.rsk.core.bc.BlockExecutor)6 BlockChainBuilder (co.rsk.test.builders.BlockChainBuilder)6 Keccak256 (co.rsk.crypto.Keccak256)5 Block (org.ethereum.core.Block)5 DataWord (org.ethereum.vm.DataWord)5 ProgramInvoke (org.ethereum.vm.program.invoke.ProgramInvoke)5 BlockGenerator (co.rsk.blockchain.utils.BlockGenerator)4 RskSystemProperties (co.rsk.config.RskSystemProperties)4