Solidity accessing private variable
currently, I'm practicing solidity. However, I'm a little confused about accessing a private variable in a contract.
For example here;
address private a;
address private b;
mapping (bytes32 => uint) public people;
mapping (bytes32 => mapping(address => uint)) public listOfEmp;
bytes32[] public list;
bytes32 private z;
I can access 'a' with
web3.eth.getStorageAt("0x501...", 0)
How can I access 'z' here? From a different contract.
Thank you
Solution 1:
You can access the storage of your contract even if it's private.
Try this:
web3.eth.getStorageAt("0x501...", 5)
If you want to access the map or array, check this document for layout of state variables: https://solidity.readthedocs.io/en/v0.4.24/miscellaneous.html
By the way, you should always use getProof to validate the value.
Solution 2:
Think of Ethereum as a process running on your machine or remotely. Using web3.eth.getStorageAt
you read data from the process memory. In the same way you can read the data of every program on your computer.
On other hands, high level programming languages like Java, C++ or Solidity frequently define access rules on variables and functions (private, protected, etc). But these rules only hold in the context of the program execution. For Solidity that context is the execution of transaction.
It means that the private field is private only for other contracts trying to read it. But can be read by external (and pretty low-level) API's like web3.eth.getStorageAt
.