Search in sources :

Example 1 with ProgramInvokeImpl

use of org.ethereum.vm.program.invoke.ProgramInvokeImpl in project rskj by rsksmart.

the class TestProgramInvokeFactory method generalInvoke.

private ProgramInvoke generalInvoke(Transaction tx, int txindex, Repository repository, BlockStore blockStore) {
    /**
     *         ADDRESS op       **
     */
    // YP: Get address of currently executing account.
    RskAddress addr = tx.isContractCreation() ? tx.getContractAddress() : tx.getReceiveAddress();
    /**
     *         ORIGIN op       **
     */
    // YP: This is the sender of original transaction; it is never a contract.
    RskAddress origin = tx.getSender();
    /**
     *         CALLER op       **
     */
    // YP: This is the address of the account that is directly responsible for this execution.
    RskAddress caller = tx.getSender();
    /**
     *         BALANCE op       **
     */
    Coin balance = repository.getBalance(addr);
    /**
     *         GASPRICE op       **
     */
    Coin gasPrice = tx.getGasPrice();
    /**
     * GAS op **
     */
    byte[] gas = tx.getGasLimit();
    /**
     *        CALLVALUE op      **
     */
    Coin callValue = tx.getValue() == null ? Coin.ZERO : tx.getValue();
    /**
     *     CALLDATALOAD  op   **
     */
    /**
     *     CALLDATACOPY  op   **
     */
    /**
     *     CALLDATASIZE  op   **
     */
    byte[] data = tx.isContractCreation() ? ByteUtil.EMPTY_BYTE_ARRAY : (tx.getData() == null ? ByteUtil.EMPTY_BYTE_ARRAY : tx.getData());
    // byte[] data =  tx.getData() == null ? ByteUtil.EMPTY_BYTE_ARRAY : tx.getData() ;
    /**
     *    PREVHASH  op  **
     */
    byte[] lastHash = env.getPreviousHash();
    /**
     *   COINBASE  op **
     */
    byte[] coinbase = env.getCurrentCoinbase();
    /**
     * TIMESTAMP  op  **
     */
    long timestamp = ByteUtil.byteArrayToLong(env.getCurrentTimestamp());
    /**
     * NUMBER  op  **
     */
    long number = ByteUtil.byteArrayToLong(env.getCurrentNumber());
    /**
     * DIFFICULTY  op  **
     */
    byte[] difficulty = env.getCurrentDifficulty();
    /**
     * GASLIMIT op **
     */
    byte[] gaslimit = env.getCurrentGasLimit();
    return new ProgramInvokeImpl(addr.getBytes(), origin.getBytes(), caller.getBytes(), balance.getBytes(), gasPrice.getBytes(), gas, callValue.getBytes(), data, lastHash, coinbase, timestamp, number, txindex, difficulty, gaslimit, repository, blockStore);
}
Also used : Coin(co.rsk.core.Coin) RskAddress(co.rsk.core.RskAddress) ProgramInvokeImpl(org.ethereum.vm.program.invoke.ProgramInvokeImpl)

Example 2 with ProgramInvokeImpl

use of org.ethereum.vm.program.invoke.ProgramInvokeImpl 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)

Aggregations

Coin (co.rsk.core.Coin)2 RskAddress (co.rsk.core.RskAddress)2 ProgramInvokeImpl (org.ethereum.vm.program.invoke.ProgramInvokeImpl)2 RepositoryImpl (co.rsk.db.RepositoryImpl)1 IOException (java.io.IOException)1 ThreadMXBean (java.lang.management.ThreadMXBean)1 BigInteger (java.math.BigInteger)1 BlockchainConfig (org.ethereum.config.BlockchainConfig)1 Repository (org.ethereum.core.Repository)1 DataWord (org.ethereum.vm.DataWord)1 LogInfo (org.ethereum.vm.LogInfo)1 VM (org.ethereum.vm.VM)1 Program (org.ethereum.vm.program.Program)1 ProgramInvoke (org.ethereum.vm.program.invoke.ProgramInvoke)1