Search code examples
ethereumblockchainsoliditysmartcontracts

Can ETH miners check all the data which is stored in Ethereum?


My doubt is from the below code:

contract RandomNumber{

    uint number;

    function get_random() public{
        bytes32 ramdonNumber = keccak256(abi.encodePacked(block.timestamp,blockhash(block.number-1)));
        number = uint(ramdonNumber);
    }
}

We assign a random number to the variable number but if I don't set number public or create another public function to retrieve the value then nobody would know the exactly value through Etherscan. But what about the miners? Can they retrieve these unrevealed data in some ways?

I have tried: Google, Ethereum whitepaper, Solidity documentation


Solution

  • Assuming that the contract is deployed on a public network (e.g. Ethereum), then the value is always readable.

    Not directly through the autogenerated getter function (that's available only for public properties), which means it's not available onchain.

    But anyone (including miners) can create an offchain app (for example in JavaScript) that queries the specific storage slot where the value is stored - in this case it's in slot number 0. And it returns the "secret" value.

    JS code using ethers library, a wrapper to RPC API of Ethereum nodes:

    const number = await provider.getStorageAt(CONTRACT_ADDRESS, SLOT_NUMBER);
    

    Docs: https://docs.ethers.org/v5/api/providers/provider/#Provider-getStorageAt

    And the actual RPC API method: https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getstorageat