3

Lets say I store some data into a variable in a smart contract on creation. Since everything is public/stored on chain and it isn't encrypted with smart contract private key(Where is the private key for a contract stored?).

Would I be able to find this the data stored in the variable if I don't create a getter function to return the value? Or can I look through the storage associated with this contract and find the data?

I understand that if the variable is public, solidity automatically creates a getter. But if the variable is private, it says that only the contract can read that data.

1
  • Karan! I have encountered the same question as you , have you addressed it? Is there any way to access data in a contract without getter function?
    – Jocelyn
    Commented Sep 3, 2019 at 7:00

2 Answers 2

2

As you said, all the data is public. Anyone can read anything. From https://programtheblockchain.com/posts/2018/01/02/making-smart-contracts-with-public-variables/:

Due to the public nature of the Ethereum blockchain, it is impossible for a smart contract to contain truly hidden data. This is doubly true of state variables, because Ethereum provides a simple API to read them!

...

web3.eth.getStorageAt reads the storage for a contract by direct address lookup.

2

Naturally, Every public variable of contract is accessible by it's auto-generated getter function from outside. Every private variable is only accessible inside the contract and if you want to access the private variable from outside the contract you need to write a getter function.

Contract does not have any private key because contract is a programming code which execute the logic which we have coded and run's on EVM which is already secured.

Although if you are developer and can understand the memory lookup you can read the private variables also. There is a way to lookup the private variables by investigation into transaction which change the state.

E.g. to modify a private variable in the contract you need to pass the "private" value while calling the function which changes the value of private variable. But all the function parameters (transaction data) is visible to every node so you can easily read the private variables if you know the transaction.

For every function call the transaction have 2 fields

  1. function selector
  2. function parameter

e.g. this is an transaction

0x6587f6ec0000000000000000000000000000000000000000000000000000000000000064

in this, first 4 bytes are function selector 0x6587f6ec and other fields are showing parameter value in hex 0x0000000000000000000000000000000000000000000000000000000000000064 which is equal to 100. Value of private variable. You can check more details in here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.