Search in sources :

Example 16 with PrecompiledContracts

use of org.ethereum.vm.PrecompiledContracts in project rskj by rsksmart.

the class RskForksBridgeTest method callGetStateForDebuggingTx.

private BridgeState callGetStateForDebuggingTx() throws IOException {
    TestSystemProperties beforeBambooProperties = new TestSystemProperties();
    Transaction rskTx = CallTransaction.createRawTransaction(0, Long.MAX_VALUE, Long.MAX_VALUE, PrecompiledContracts.BRIDGE_ADDR, 0, Bridge.GET_STATE_FOR_DEBUGGING.encode(new Object[] {}), beforeBambooProperties.getNetworkConstants().getChainId());
    rskTx.sign(new byte[] {});
    TransactionExecutorFactory transactionExecutorFactory = new TransactionExecutorFactory(beforeBambooProperties, blockStore, null, new BlockFactory(beforeBambooProperties.getActivationConfig()), new ProgramInvokeFactoryImpl(), new PrecompiledContracts(beforeBambooProperties, world.getBridgeSupportFactory()), world.getBlockTxSignatureCache());
    Repository track = repository.startTracking();
    TransactionExecutor executor = transactionExecutorFactory.newInstance(rskTx, 0, blockChain.getBestBlock().getCoinbase(), track, blockChain.getBestBlock(), 0).setLocalCall(true);
    executor.executeTransaction();
    ProgramResult res = executor.getResult();
    Object[] result = Bridge.GET_STATE_FOR_DEBUGGING.decodeResult(res.getHReturn());
    ActivationConfig.ForBlock activations = beforeBambooProperties.getActivationConfig().forBlock(blockChain.getBestBlock().getNumber());
    return BridgeState.create(beforeBambooProperties.getNetworkConstants().getBridgeConstants(), (byte[]) result[0], activations);
}
Also used : ProgramResult(org.ethereum.vm.program.ProgramResult) ProgramInvokeFactoryImpl(org.ethereum.vm.program.invoke.ProgramInvokeFactoryImpl) TransactionExecutorFactory(co.rsk.core.TransactionExecutorFactory) ActivationConfig(org.ethereum.config.blockchain.upgrades.ActivationConfig) PrecompiledContracts(org.ethereum.vm.PrecompiledContracts) TestSystemProperties(co.rsk.config.TestSystemProperties)

Example 17 with PrecompiledContracts

use of org.ethereum.vm.PrecompiledContracts in project rskj by rsksmart.

the class TransactionTest method constantCallConflictTest.

@Test
public void constantCallConflictTest() throws Exception {
    /*
          0x095e7baea6a6c7c4c2dfeb977efac326af552d87 contract is the following Solidity code:

         contract Test {
            uint a = 256;

            function set(uint s) {
                a = s;
            }

            function get() returns (uint) {
                return a;
            }
        }
        */
    String json = "{ " + "    'test1' : { " + "        'env' : { " + "            'currentCoinbase' : '2adc25665018aa1fe0e6bc666dac8fc2697ff9ba', " + "            'currentDifficulty' : '0x0100', " + "            'currentGasLimit' : '0x0f4240', " + "            'currentNumber' : '0x00', " + "            'currentTimestamp' : '0x01', " + "            'previousHash' : '5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6' " + "        }, " + "        'logs' : [ " + "        ], " + "        'out' : '0x', " + "        'post' : { " + "            '095e7baea6a6c7c4c2dfeb977efac326af552d87' : { " + "                'balance' : '0x0de0b6b3a76586a0', " + "                'code' : '0x606060405260e060020a600035046360fe47b1811460245780636d4ce63c14602e575b005b6004356000556022565b6000546060908152602090f3', " + "                'nonce' : '0x00', " + "                'storage' : { " + "                    '0x00' : '0x0400' " + "                } " + "            }, " + "            '0000000000000000000000000000000001000008' : { " + "                'balance' : '0x67EB', " + "                'code' : '0x', " + "                'nonce' : '0x00', " + "                'storage' : { " + "                } " + "            }, " + "            'a94f5374fce5edbc8e2a8697c15331677e6ebf0b' : { " + "                'balance' : '0x0DE0B6B3A7621175', " + "                'code' : '0x', " + "                'nonce' : '0x01', " + "                'storage' : { " + "                } " + "            } " + "        }, " + "        'postStateRoot' : '17454a767e5f04461256f3812ffca930443c04a47d05ce3f38940c4a14b8c479', " + "        'pre' : { " + "            '095e7baea6a6c7c4c2dfeb977efac326af552d87' : { " + "                'balance' : '0x0de0b6b3a7640000', " + "                'code' : '0x606060405260e060020a600035046360fe47b1811460245780636d4ce63c14602e575b005b6004356000556022565b6000546060908152602090f3', " + "                'nonce' : '0x00', " + "                'storage' : { " + "                    '0x00' : '0x02' " + "                } " + "            }, " + "            'a94f5374fce5edbc8e2a8697c15331677e6ebf0b' : { " + "                'balance' : '0x0de0b6b3a7640000', " + "                'code' : '0x', " + "                'nonce' : '0x00', " + "                'storage' : { " + "                } " + "            } " + "        }, " + "        'transaction' : { " + "            'data' : '0x60fe47b10000000000000000000000000000000000000000000000000000000000000400', " + "            'gasLimit' : '0x061a80', " + "            'gasPrice' : '0x01', " + "            'nonce' : '0x00', " + "            'secretKey' : '45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8', " + "            'to' : '095e7baea6a6c7c4c2dfeb977efac326af552d87', " + "            'value' : '0x0186a0' " + "        } " + "    } " + "}";
    StateTestSuite stateTestSuite = new StateTestSuite(json.replaceAll("'", "\""));
    List<String> res = new StateTestRunner(stateTestSuite.getTestCases().get("test1")) {

        @Override
        protected ProgramResult executeTransaction(Transaction tx) {
            // first emulating the constant call (Ethereum.callConstantFunction)
            // to ensure it doesn't affect the final state
            {
                Repository track = repository.startTracking();
                Transaction txConst = CallTransaction.createCallTransaction(0, 0, 100000000000000L, new RskAddress("095e7baea6a6c7c4c2dfeb977efac326af552d87"), 0, CallTransaction.Function.fromSignature("get"), config.getNetworkConstants().getChainId());
                txConst.sign(new byte[] {});
                Block bestBlock = block;
                BridgeSupportFactory bridgeSupportFactory = new BridgeSupportFactory(new RepositoryBtcBlockStoreWithCache.Factory(config.getNetworkConstants().getBridgeConstants().getBtcParams()), config.getNetworkConstants().getBridgeConstants(), config.getActivationConfig());
                TransactionExecutorFactory transactionExecutorFactory = new TransactionExecutorFactory(config, new BlockStoreDummy(), null, blockFactory, invokeFactory, new PrecompiledContracts(config, bridgeSupportFactory), new BlockTxSignatureCache(new ReceivedTxSignatureCache()));
                TransactionExecutor executor = transactionExecutorFactory.newInstance(txConst, 0, bestBlock.getCoinbase(), track, bestBlock, 0).setLocalCall(true);
                executor.executeTransaction();
                track.rollback();
                System.out.println("Return value: " + new CallTransaction.IntType("uint").decode(executor.getResult().getHReturn()));
            }
            // now executing the JSON test transaction
            return super.executeTransaction(tx);
        }
    }.setstateTestUSeREMASC(true).runImpl();
    if (!res.isEmpty())
        throw new RuntimeException("Test failed: " + res);
}
Also used : BridgeSupportFactory(co.rsk.peg.BridgeSupportFactory) TransactionExecutorFactory(co.rsk.core.TransactionExecutorFactory) TransactionExecutorFactory(co.rsk.core.TransactionExecutorFactory) BlockStoreDummy(org.ethereum.db.BlockStoreDummy) MutableRepository(org.ethereum.db.MutableRepository) PrecompiledContracts(org.ethereum.vm.PrecompiledContracts) StateTestRunner(org.ethereum.jsontestsuite.runners.StateTestRunner) StateTestSuite(org.ethereum.jsontestsuite.StateTestSuite) RskAddress(co.rsk.core.RskAddress) BridgeSupportFactory(co.rsk.peg.BridgeSupportFactory) Test(org.junit.Test)

Example 18 with PrecompiledContracts

use of org.ethereum.vm.PrecompiledContracts in project rskj by rsksmart.

the class PrecompiledContractAddressTests method testGetPrecompile.

@Test
public void testGetPrecompile() {
    PrecompiledContracts pcList = new PrecompiledContracts(config, null);
    checkAddr(pcList, ECRECOVER_ADDR, "ECRecover");
    checkAddr(pcList, SHA256_ADDR, "Sha256");
    checkAddr(pcList, RIPEMPD160_ADDR, "Ripempd160");
    checkAddr(pcList, IDENTITY_ADDR_STR, "Identity");
    checkAddr(pcList, BIG_INT_MODEXP_ADDR, "BigIntegerModexp");
    checkAddr(pcList, BRIDGE_ADDR_STR, "Bridge");
    checkAddr(pcList, REMASC_ADDR_STR, "RemascContract");
    checkAddr(pcList, BLOCK_HEADER_ADDR_STR, "BlockHeaderContract");
    checkAddr(pcList, HDWALLETUTILS_ADDR_STR, "HDWalletUtils");
}
Also used : PrecompiledContracts(org.ethereum.vm.PrecompiledContracts) Test(org.junit.Test)

Example 19 with PrecompiledContracts

use of org.ethereum.vm.PrecompiledContracts in project rskj by rsksmart.

the class BridgeTestPowerMock method testCallFromContract_afterOrchid.

@Test
public void testCallFromContract_afterOrchid() {
    doReturn(false).when(activationConfig).isActive(eq(RSKIP87), anyLong());
    doReturn(true).when(activationConfig).isActive(eq(RSKIP88), anyLong());
    blockFactory = new BlockFactory(activationConfig);
    BridgeSupportFactory bridgeSupportFactory = new BridgeSupportFactory(new RepositoryBtcBlockStoreWithCache.Factory(constants.getBridgeConstants().getBtcParams()), constants.getBridgeConstants(), activationConfig);
    PrecompiledContracts precompiledContracts = new PrecompiledContracts(config, bridgeSupportFactory);
    EVMAssembler assembler = new EVMAssembler();
    ProgramInvoke invoke = new ProgramInvokeMockImpl();
    // Save code on the sender's address so that the bridge
    // thinks its being called by a contract
    byte[] callerCode = assembler.assemble("0xaabb 0xccdd 0xeeff");
    invoke.getRepository().saveCode(new RskAddress(invoke.getOwnerAddress().getLast20Bytes()), callerCode);
    VM vm = new VM(config.getVmConfig(), precompiledContracts);
    // Encode a call to the bridge's getMinimumLockTxValue function
    // That means first pushing the corresponding encoded ABI storage to memory (MSTORE)
    // and then doing a DELEGATECALL to the corresponding address with the correct parameters
    String bridgeFunctionHex = ByteUtil.toHexString(Bridge.GET_MINIMUM_LOCK_TX_VALUE.encode());
    bridgeFunctionHex = String.format("0x%s%s", bridgeFunctionHex, String.join("", Collections.nCopies(32 * 2 - bridgeFunctionHex.length(), "0")));
    String asm = String.format("%s 0x00 MSTORE 0x20 0x30 0x20 0x00 0x0000000000000000000000000000000001000006 0x6000 DELEGATECALL", bridgeFunctionHex);
    int numOps = asm.split(" ").length;
    byte[] code = assembler.assemble(asm);
    // Mock a transaction, all we really need is a hash
    Transaction tx = mock(Transaction.class);
    when(tx.getHash()).thenReturn(new Keccak256("001122334455667788990011223344556677889900112233445566778899aabb"));
    // Run the program on the VM
    Program program = new Program(config.getVmConfig(), precompiledContracts, blockFactory, activationConfig.forBlock(0), code, invoke, tx, new HashSet<>());
    try {
        for (int i = 0; i < numOps; i++) {
            vm.step(program);
        }
        Assert.fail();
    } catch (RuntimeException e) {
        Assert.assertTrue(e.getMessage().contains("Non-local-call"));
    }
}
Also used : Program(org.ethereum.vm.program.Program) Keccak256(co.rsk.crypto.Keccak256) EVMAssembler(co.rsk.asm.EVMAssembler) ProgramInvoke(org.ethereum.vm.program.invoke.ProgramInvoke) ProgramInvokeMockImpl(org.ethereum.vm.program.invoke.ProgramInvokeMockImpl) PrecompiledContracts(org.ethereum.vm.PrecompiledContracts) SimpleBtcTransaction(co.rsk.peg.bitcoin.SimpleBtcTransaction) VM(org.ethereum.vm.VM) RskAddress(co.rsk.core.RskAddress) ActivationConfigsForTest(org.ethereum.config.blockchain.upgrades.ActivationConfigsForTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 20 with PrecompiledContracts

use of org.ethereum.vm.PrecompiledContracts in project rskj by rsksmart.

the class BlockHeaderContractTest method setUp.

@Before
public void setUp() {
    config = new TestSystemProperties();
    blockFactory = new BlockFactory(config.getActivationConfig());
    PrecompiledContracts precompiledContracts = new PrecompiledContracts(config, null);
    ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class);
    // Enabling necessary RSKIPs for every precompiled contract to be available
    when(activations.isActive(ConsensusRule.RSKIP119)).thenReturn(true);
    world = new World();
    contract = (BlockHeaderContract) precompiledContracts.getContractForAddress(activations, DataWord.valueFromHex(BLOCK_HEADER_CONTRACT_ADDRESS));
    // contract methods
    getCoinbaseFunction = getContractFunction(contract, GetCoinbaseAddress.class);
    getMinGasPriceFunction = getContractFunction(contract, GetMinimumGasPrice.class);
    getBlockHashFunction = getContractFunction(contract, GetBlockHash.class);
    getMergedMiningTagsFunction = getContractFunction(contract, GetMergedMiningTags.class);
    getGasLimitFunction = getContractFunction(contract, GetGasLimit.class);
    getGasUsedFunction = getContractFunction(contract, GetGasUsed.class);
    getDifficultyFunction = getContractFunction(contract, GetDifficulty.class);
    getBitcoinHeaderFunction = getContractFunction(contract, GetBitcoinHeader.class);
    getUncleCoinbaseAddressFunction = getContractFunction(contract, GetUncleCoinbaseAddress.class);
    // invoke transaction
    rskTx = Transaction.builder().nonce(NONCE).gasPrice(GAS_PRICE).gasLimit(GAS_LIMIT).destination(Hex.decode(PrecompiledContracts.BLOCK_HEADER_ADDR_STR)).data(Hex.decode(DATA)).chainId(Constants.REGTEST_CHAIN_ID).value(AMOUNT).build();
    rskTx.sign(new ECKey().getPrivKeyBytes());
    executionEnvironment = mock(ExecutionEnvironment.class);
    Whitebox.setInternalState(contract, "executionEnvironment", executionEnvironment);
}
Also used : ExecutionEnvironment(co.rsk.pcc.ExecutionEnvironment) ECKey(org.ethereum.crypto.ECKey) World(co.rsk.test.World) ActivationConfig(org.ethereum.config.blockchain.upgrades.ActivationConfig) PrecompiledContracts(org.ethereum.vm.PrecompiledContracts) TestSystemProperties(co.rsk.config.TestSystemProperties) Before(org.junit.Before)

Aggregations

PrecompiledContracts (org.ethereum.vm.PrecompiledContracts)23 TransactionExecutorFactory (co.rsk.core.TransactionExecutorFactory)11 BridgeSupportFactory (co.rsk.peg.BridgeSupportFactory)11 ProgramInvokeFactoryImpl (org.ethereum.vm.program.invoke.ProgramInvokeFactoryImpl)11 Test (org.junit.Test)9 TestSystemProperties (co.rsk.config.TestSystemProperties)8 RskAddress (co.rsk.core.RskAddress)6 RepositoryBtcBlockStoreWithCache (co.rsk.peg.RepositoryBtcBlockStoreWithCache)6 BlockExecutor (co.rsk.core.bc.BlockExecutor)5 ActivationConfigsForTest (org.ethereum.config.blockchain.upgrades.ActivationConfigsForTest)5 VM (org.ethereum.vm.VM)5 HashMapDB (org.ethereum.datasource.HashMapDB)4 Keccak256 (co.rsk.crypto.Keccak256)3 RepositoryLocator (co.rsk.db.RepositoryLocator)3 BlockChainBuilder (co.rsk.test.builders.BlockChainBuilder)3 EVMAssembler (co.rsk.asm.EVMAssembler)2 BlockGenerator (co.rsk.blockchain.utils.BlockGenerator)2 Coin (co.rsk.core.Coin)2 StateRootHandler (co.rsk.db.StateRootHandler)2 StateRootsStoreImpl (co.rsk.db.StateRootsStoreImpl)2