3

Hope you are doing well. We were running a simple contract and trying to analyse the assembly code generated by the browser compiler. In the .data part we found a section where the compiler executes a specific logic where it matches the method id of the methods, written in the code and generates the specific tags. But before it matches the method id it executes some logic which we could not figure out why it is required? May you please explain the algorithm behind this....

The contract

pragma solidity ^0.4.0;
contract Test 
{
    uint x = 0;
    uint y = 8;

    function calculate() 
    {
        uint z = x+y;
    }
}

-----------------.data section in the assembly code--------------------

PUSH1 0x60
PUSH1 0x40
MSTORE
PUSH1 0x0
CALLDATALOAD
PUSH29 0x100000000000000000000000000000000000000000000000000000000
SWAP1
DIV
PUSH4 0xFFFFFFFF
AND
DUP1
PUSH4 0xCA77AB65
EQ
PUSH1 0x3C
JUMPI

It will be immensely helpful if you can help us to understand this algorithm and why it does this.

Thank you in advance.

Thanks, Shamik.

2

When you compiled:

  • it compiled the contract you showed us
  • it packed this compiled stuff along with an unpacking code.

When you deploy, the unpacking code takes the contract code out of the payload, and saves it at the address. So the contract code per-se appears as .data for the unpacking code. That explains why you have this code in .data.

Now in fact, what you see is all or part of your contract code. This contract has 1 function. function calculate(). If you do Kecca256 of this function, and keep the fist 4 bytes, you get its signature: 0x28a635c3.

In your code, it is 0xCA77AB65, so the function must be different. Anyway, the code will check if the first 4 bytes (0xFFFFFFFF) of the call data (CALLDATALOAD) contains this signature. If it does, then it will JUMPI to the location of the function's body, here 0x3C.

To summarise, this piece of code finds out which function was called. Then, it is routing the rest of the execution.

  • Thank you Xavier for the explanation. Yes I copied the wrong source code, that is my bad though this algorithm is same for any code. I am sorry for that. – Shamik Jan 31 '17 at 11:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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