<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Alejandro Santander on Medium]]></title>
        <description><![CDATA[Stories by Alejandro Santander on Medium]]></description>
        <link>https://medium.com/@_ajsantander?source=rss-c006b5d53b8e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*_mZVdCntRGHnHsJ5.jpeg</url>
            <title>Stories by Alejandro Santander on Medium</title>
            <link>https://medium.com/@_ajsantander?source=rss-c006b5d53b8e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 00:53:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@_ajsantander/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Deconstructing a Solidity Contract — Part VI: The Metadata Hash]]></title>
            <link>https://medium.com/@_ajsantander/deconstructing-a-solidity-contract-part-vi-the-swarm-hash-70f069e22aef?source=rss-c006b5d53b8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/70f069e22aef</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[guide]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[ipfs]]></category>
            <category><![CDATA[swarm]]></category>
            <dc:creator><![CDATA[Alejandro Santander]]></dc:creator>
            <pubDate>Fri, 28 Sep 2018 14:00:27 GMT</pubDate>
            <atom:updated>2019-02-13T20:50:52.978Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*97azscARnvqGWYRjBwBwmw.png" /></figure><p><em>By</em><a href="https://twitter.com/_ajsantander"><em> Alejandro Santander</em></a><em> in collaboration with</em><a href="https://twitter.com/yoelopio"><em> Leo Arias</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*__Zz_t77MXdJjdOHbvahZQ.jpeg" /><figcaption>Image from <a href="https://pixabay.com/en/finger-fingerprint-security-digital-2081169/">pixbay.com</a></figcaption></figure><p><em>Note: This article is part of a series. If you haven’t read the previous article, please have a look at it first. We’re deconstructing the </em><a href="https://gist.github.com/ajsantander/03a4a183756980ef0865825bea96d6f5"><em>EVM bytecode</em></a><em> of a simple </em><a href="https://gist.github.com/ajsantander/dce951a95e7608bc29d7f5deeb6e2ecf"><em>Solidity contract</em></a><em>.</em></p><ol><li><a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-i-introduction-832efd2d7737">Deconstructing a Solidity Contract — Part I: Introduction</a> ✔</li><li><a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-ii-creation-vs-runtime-6b9d60ecb44c">Deconstructing a Solidity Contract — Part II: Creation vs. Runtime</a> ✔</li><li><a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-iii-the-function-selector-6a9b6886ea49">Deconstructing a Solidity Contract — Part III: The Function Selector</a> ✔</li><li><a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-iv-function-wrappers-d8e46672b0ed">Deconstructing a Solidity Contract — Part IV: Function Wrappers</a> ✔</li><li><a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-v-function-bodies-2d19d4bef8be">Deconstructing a Solidity Contract — Part V: Function Bodies</a> ✔</li><li>Deconstructing a Solidity Contract — Part VI: The Metadata Hash ⬅</li></ol><p><strong><em>Update: </em></strong><em>This article initially contained mistakes and missed a few important points about the design of the metadata hash, which were pointed out by </em><a href="https://github.com/chriseth"><em>chriseth</em></a><em> from the Solidity team. Thank you!</em><strong><em> </em></strong><em>Among the corrections made by Chris, is the fact that the structure is known as the “Metadata hash” instead of the “Swarm hash”, and that the Solidity compiler is agnostic in terms of the system used to store contract metadata.</em></p><p>In the last article, we noticed that the runtime bytecode generated by the Solidity compiler appends a strange structure after the function bodies block. You can see this in the <a href="https://cdn.rawgit.com/ajsantander/23c032ec7a722890feed94d93dff574a/raw/a453b28077e9669d5b51f2dc6d93b539a76834b8/BasicToken.svg">deconstruction diagram</a> or in the image below referred to as the “metadata hash”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*07vt6obMDNLssCWZj5DNKA.png" /><figcaption>Figure 1: The metadata hash can be found in the last few opcodes of the runtime bytecode of a contract.</figcaption></figure><p>What exactly are these opcodes doing?</p><p>Notice the STOP opcode at instruction 421. You may think that if there’s a STOP opcode there, whatever comes after it is basically unreachable bytecode, right? Well, not exactly: the code could be JUMP-ing over the STOP opcode. However, there are no JUMPDEST instructions after it, so that rules out the possibility of any execution reaching this part of the bytecode via a JUMP.</p><p>In fact, if you analyze all the possible execution flows in this contract (which, believe it or not, is what we have done in this series!), you’ll see that indeed this code is totally unreachable.</p><p>So why would the Solidity compiler append non-executable code to its generated output? Actually, this isn’t the first time that this happens. We’ve seen it before in <a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-ii-creation-vs-runtime-6b9d60ecb44c">Part II of the series</a>, where a constructor’s arguments were appended to the end of the creation bytecode. That code wasn’t supposed to be executed by the EVM either; it was just there as a sort of hack to store the initialization values of a contract for consumption in constructors.</p><p>Alright, we still haven’t answered the question of what this block of code is. To do that, let’s walk through the opcodes and try to make some sense out of them, shall we?</p><p>The first thing we see is a LOG1. If we look this opcode up in the <a href="http://gavwood.com/paper.pdf">Yellow Paper</a> or in the <a href="https://solidity.readthedocs.io/en/v0.4.25/julia.html#low-level-functions">Solidity documentation</a>, we can see that LOG0 to LOG4 opcodes are used for logging events in the Ethereum blockchain. Which…makes no sense, since we won’t be executing any of this code...</p><p>After that, we can see a PUSH6 of 0x627a7a723058, a SHA3, a couple of INVALIDs, a SWAP10, a DELEGATECALL, etc. Wait, INVALIDs? What does that even mean?! Yup, total nonsense in terms of EVM interpretation. Clearly, looking at these bytes as EVM opcode representation is absolutely pointless. We need to look at this as raw byte data, which as you remember can be found in Remix’s <em>Compile</em> tab &gt; <em>Details</em> panel &gt; <em>Runtime Bytecode</em> section &gt; <em>object</em> property. The LOG1 opcode is really an 0xa1 byte, so the whole block of code at the end of the contract looks like this:</p><pre>// …a165627a7a723058202c27c1ef4be478b21f663f0d0ecdd1c73638730ffebbff1e3c7a234db7df6fd10029<br>// END OF CONTRACT</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*67hU84wF_V25Vwm9zZFfIg.png" /></figure><p>The answer to this riddle can be found in Solidity’s documentation, in the <a href="https://solidity.readthedocs.io/en/v0.4.25/metadata.html#encoding-of-the-metadata-hash-in-the-bytecode">Encoding of the Metadata Hash in the Bytecode</a> section. The documentation is brief, but it gives us exactly what we need. The compiler is hashing the contract’s metadata (which includes information about the contract such as its source code, how it was compiled, etc.) and injecting this hash into the contract’s own bytecode! This metadata can also be seen in Remix: Remix’s <em>Compile</em> tab &gt; <em>Details</em> panel &gt; <em>Metadata</em> section.</p><p>This hash can be used in <a href="https://swarm-guide.readthedocs.io/en/latest/introduction.html">Swarm</a> as a lookup URL to find the contract’s metadata. Swarm is basically a decentralized storage system, similar to <a href="https://ipfs.io/">IPFS</a>. The idea here is that some platform like <a href="https://etherscan.io/">Etherscan</a> identifies this structure in the bytecode and provides the location of the bytecode’s metadata within a decentralized storage system. A user can query such metadata and use it as a means to prove that the bytecode being seen is in fact the product of a given Solidity source code, with a certain version and precise configuration of the Solidity compiler in a deterministic manner. This hash is a digital signature of sorts, that ties together a piece of compiled bytecode with its origins. If you wanted to verify that the bytecode is legit, you would have to hash the metadata yourself and verify that you get the same hash.</p><p>And that’s not all, the metadata hash can be used by wallet applications to fetch the contract’s metadata, extract it’s source, recompile it with the compiler settings used originally, verify that the produced bytecode matches the contract’s bytecode, then fetch the contract’s JSON ABI and look at the <a href="https://github.com/ethereum/wiki/wiki/Ethereum-Natural-Specification-Format">NATSPEC</a> documentation of the function being called.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*Rce1pOiQd3O-CZ3J-ORNeQ.jpeg" /></figure><p>This end-to-end authentication path built into bytecode generated by the Solidity compiler can not only be used to provide a user with information of the action about to be performed, but also to validate the legitimacy of such action.</p><p>For example, if we look at <a href="https://etherscan.io/address/0x06012c8cf97bead5deae237070f9587f8e7a266d#code">the CryptoKitties contract in Etherscan</a>, we can see that at the end of the page, Etherscan provides us with the contract’s metadata address in Swarm, which was extracted from the bytecode in the way we’ve just seen: bzzr://a6465fc1ce7ab1a92906ff7206b23d80a21bbd50b85b4bde6a91f8e6b2e3edde. You can <a href="https://swarm-guide.readthedocs.io/en/latest/usage/bzz.html?highlight=bzz">look into Swarm’s documentation to better understand this URL scheme</a>.</p><p>Let’s go back to our BasicToken’s bytecode and understand how Etherscan (or any other similar utility for that matter) actually finds the hash in the bytecode.</p><p>As the <a href="https://solidity.readthedocs.io/en/v0.4.25/metadata.html?highlight=swarm%20hash#encoding-of-the-metadata-hash-in-the-bytecode">Solidity documentation</a> states, an 0xa1 and an 0x65 will be injected to the bytecode. In EVM bytecode, these two hexadecimal values would translate to LOG1 and PUSH6. Now, if <a href="https://www.browserling.com/tools/utf8-to-hex">we decoded the letter “b” as UTF to hex</a>, we would get 0x62, “z” would be 0x7a, and so on. You can see the whole thing decoded in the following diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jvtyB5uFIQLAKkkl" /><figcaption>Figure 2: The metadata hash decoded as a Swarm URL.</figcaption></figure><p>So, any application trying to find the metadata hash in the bytecode would look for these bytes at the end of the contract, this particular pattern, and extract the URL from it.</p><p>Solidity uses a type of encoding called <a href="https://tools.ietf.org/html/rfc7049">CBOR encoding</a>, with which not only the hash is stored, but the specific decentralized storage system and version used is stored. In this case, it’s using Swarm’s version zero bzz:// URL scheme and that’s why the structure contains the chars “b”, “z”, “z”, “r”, “0”. Alternatively, it could use something like “i”, “p”, “f”, “s”, “r”, “0”, indicating that the structure encodes an IPFS URL scheme. This makes it agnostic in terms of which storage system is used. It could be changed in the future, or we could even get to choose which storage system we want the bytecode to reference upon compilation.</p><p>To retrieve the metadata file, we would have to connect to the same Swarm network to which the metadata file was uploaded to, using something like <a href="https://swarm-gateways.net/">swarm-gateways.net</a> or setting up a local Swarm node. Right now, this is something that is quite difficult to do, because Swarm is still under heavy development and has not yet stabilized its hashing scheme, <a href="https://github.com/ethereum/solidity/issues/4092">which can be seen is something being addressed by Solidity in issue #4092</a>.</p><p>The actual hash itself is a specific hashing algorithm executed on the metadata file of a contract, which the Solidity compiler calculates after it has run all its other tasks — mainly, compiling =D. When we were trying to interpret these bytes as EVM opcodes, some of the hash’s bytes didn’t have a corresponding opcode, and that’s why we were getting INVALIDs. In fact, a hash may just by chance produce any set of opcodes, which will make all hashes different and look weird when using tools like Remix. What I do is ignore the bytecode when I see a LOG1, followed by a PUSH6 and a few INVALIDs, understanding that what I am seeing is the metadata hash injection that the Solidity compiler makes.</p><p>And this concludes our analysis of this bizarre structure found at the end of every contract produced by Solidity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/128/1*QZYQtnN6BOnhnnC6PONgiQ.png" /></figure><p>Better yet, this concludes the entire series. Yay! If you followed along and digested this considerable amount of highly technical, horrendously boring material (at least to most people), then I salute you! I hope that by now you feel right at home when you see EVM bytecode in the wild, and that you add this skill to your toolset when analyzing and developing smart contracts for Ethereum.</p><p>Thanks for reading!</p><ol><li><a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-i-introduction-832efd2d7737">Deconstructing a Solidity Contract — Part I: Introduction</a> ✔</li><li><a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-ii-creation-vs-runtime-6b9d60ecb44c">Deconstructing a Solidity Contract — Part II: Creation vs. Runtime</a> ✔</li><li><a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-iii-the-function-selector-6a9b6886ea49">Deconstructing a Solidity Contract — Part III: The Function Selector</a> ✔</li><li><a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-iv-function-wrappers-d8e46672b0ed">Deconstructing a Solidity Contract — Part IV: Function Wrappers</a> ✔</li><li><a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-v-function-bodies-2d19d4bef8be">Deconstructing a Solidity Contract — Part V: Function Bodies</a> ✔</li><li>Deconstructing a Solidity Contract — Part VI: The Metadata Hash ✔</li></ol><h3>Be part of the community</h3><ul><li>Continue the discussion on our <a href="https://forum.zeppelin.solutions/?utm_campaign=zep&amp;utm_medium=blog&amp;utm_source=medium">forum</a></li><li>Join our <a href="http://zpl.in/telegram">Telegram group</a></li><li>Follow us on <a href="https://twitter.com/ZeppelinOrg">Twitter</a></li><li>Even better, <a href="https://zeppelin.solutions/jobs/?utm_campaign=zep&amp;utm_medium=blog&amp;utm_source=medium">join the team</a> 🚀</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70f069e22aef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deconstructing a Solidity Contract — Part V: Function Bodies]]></title>
            <link>https://medium.com/@_ajsantander/deconstructing-a-solidity-contract-part-v-function-bodies-2d19d4bef8be?source=rss-c006b5d53b8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d19d4bef8be</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[guide]]></category>
            <category><![CDATA[solidity]]></category>
            <dc:creator><![CDATA[Alejandro Santander]]></dc:creator>
            <pubDate>Thu, 20 Sep 2018 15:23:20 GMT</pubDate>
            <atom:updated>2019-02-13T20:51:08.530Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8tNbycupaCoLqU4LwI0yOQ.png" /></figure><p><em>By</em><a href="https://twitter.com/_ajsantander"><em> Alejandro Santander</em></a><em> in collaboration with</em><a href="https://twitter.com/yoelopio"><em> Leo Arias</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x1Z1fpJcCulneMi6frVqbg.jpeg" /><figcaption>Image from <a href="https://snappygoat.com/s/?q=gears#084475c20d261724a951eb44fca543d2cdd473e3,1,1674.b06def783e353364ff0d98800ff10de367471e7f">www.snappygoat.com</a></figcaption></figure><p><em>Note: This article is part of a series. If you haven’t read the previous article, please have a look at it first. We’re deconstructing the </em><a href="https://gist.github.com/ajsantander/03a4a183756980ef0865825bea96d6f5"><em>EVM bytecode</em></a><em> of a simple </em><a href="https://gist.github.com/ajsantander/dce951a95e7608bc29d7f5deeb6e2ecf"><em>Solidity contract</em></a><em>.</em></p><ol><li><a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-i-introduction-832efd2d7737">Deconstructing a Solidity Contract — Part I: Introduction</a> ✔</li><li><a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-ii-creation-vs-runtime-6b9d60ecb44c">Deconstructing a Solidity Contract — Part II: Creation vs. Runtime</a> ✔</li><li><a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-iii-the-function-selector-6a9b6886ea49">Deconstructing a Solidity Contract — Part III: The Function Selector</a> ✔</li><li><a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-iv-function-wrappers-d8e46672b0ed">Deconstructing a Solidity Contract — Part IV: Function Wrappers</a> ✔</li><li>Deconstructing a Solidity Contract — Part V: Function Bodies ⬅</li><li><a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-vi-the-swarm-hash-70f069e22aef">Deconstructing a Solidity Contract — Part VI: The Metadata Hash</a></li></ol><p>Hey there! We’ve come a long way, haven’t we? First, we understood the difference between a contract’s creation time and runtime bytecode; next, we understood how the entry point of execution from any call or transaction is routed to specific functions via the function selector; and finally, we saw how incoming transaction data is unpacked for a function to consume, and the data produced by a function is repacked for the user via function wrappers. In this section, we will (at last) look at the actual execution of a function, or what we’ve been calling so far a “function’s <em>body</em>”.</p><p>The function body is precisely what the function wrappers detour to, after unpacking the incoming calldata. By the time a function body is executed, the function’s arguments should be sitting comfortably in the stack (or in memory if the data is dynamic), anxious to be used. Let’s see this in action with the balanceOf(address) function. This function should receive an address and return the corresponding uint256 balance of such an address.</p><p>Let’s go back to Remix and compile and deploy the contract as we’ve done before, and then call the balanceOf function with the address you used to deploy the contract as the argument. This should return the number 10000, since it is what is initially assigned to whatever address deploys the contract in the constructor’s code, which we used when deploying the contract.</p><p>Right, now let’s debug the transaction.</p><p>The first thing you’ll notice is that the debugger placed us at instruction 252. If you look at the <a href="https://cdn.rawgit.com/ajsantander/23c032ec7a722890feed94d93dff574a/raw/a453b28077e9669d5b51f2dc6d93b539a76834b8/BasicToken.svg">deconstruction diagram</a>, in the wrappers’ blue section, you should see that the balanceOf function wrapper redirects flow at instruction 175 to the JUMPDEST instruction in 251. As we’ve seen multiple times before, Remix places us precisely at the point when a function’s body is about to be executed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*kPwfJTJdjp82zFGzInChyg.png" /><figcaption>Figure 1. Function wrapper redirects execution to the function body (blue dashed line at instruction 175).</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*qfAR0q1D4PDIzBGmzTlV_A.png" /><figcaption>Figure 2. Function body execution, coming from the function’s wrapper (blue dashed line at instruction 251).</figcaption></figure><p>Now, if you look at the stack, you’ll notice that its topmost value is the address we called balanceOf with. The wrapper has done its job of unpacking the calldata correctly. So we’re ready to step through instructions 251 to 290, the body of the balanceOf function.</p><p>Instruction 252 pushes a 20-byte 0xffffffffffffffffffffffffffffffffffffffff value and uses the AND opcode to “mask” the 32-byte address into its correct type (remember, addresses in Ethereum are 20 bytes long while the stack operates in 32-byte words).</p><p>In instructions 274 to 278,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/152/1*M0G8ze6nHRS6hKrW7my4Vw.png" /></figure><p>the bytecode will upload the address from the stack to memory. It needs it there for the upcoming SHA3 opcode. If you look in the <a href="https://gavwood.com/paper.pdf">Yellow Paper</a>, the SHA3 opcode has two parameters: the position in memory to calculate the hash from, and the number of bytes to hash.</p><p>But why will the code be using a SHA3 opcode? This function wants to read from the balances mapping. More specifically, it wants to read the value mapped for the incoming address. If you recall <a href="https://solidity.readthedocs.io/en/v0.4.24/miscellaneous.html#layout-of-state-variables-in-storage">how a mapping is laid out in storage</a>, the hash of the concatenation of the variable’s slot — in this case 1, because balances is defined as the second variable (totalSupply_ is the first, at slot 0), with the actual key itself as the address — is the position in storage where the value we are looking for is stored. SHA3 will need both these values in memory to do its magic, and that is precisely what’s happening here.</p><p>So, we’ve got the address in memory, but now we need the slot in memory. And that’s what happens next between instructions 279 and 283.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/148/1*fBxOgQUKh9_3RaAQ1JQagg.png" /></figure><p>The number 0x01 is stored at memory position 0x20. Now memory holds the address at the first word, memory position 0x00, and the slot at the second word, memory position 0x20. Yay! We’re ready to call SHA3.</p><p>And so it’s called between instructions 284 and 287.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/161/1*v0RYHprCTg2tNsD6oBwZzg.png" /></figure><p>By the time SHA3 is called in instruction 287, the stack contains 0x00 (start position for SHA3) and 0x40 (length for SHA3), which is basically telling the EVM to hash whatever is in memory in the first two 32-byte words. Thirty-two bytes in hex is 0x20, so 0x20 + 0x20 equals 0x40.</p><p>Now, SHA3 leaves the 32-byte hash in the stack, which is an awfully long hexadecimal number, considerably longer than an Ethereum address. This hash is the location in the contract’s storage where the balance of the address passed to balanceOf is stored. You can visualize this using the <em>Storage completely loaded</em> panel in Remix’s debugger. You should find a matching location in the second storage object.</p><p>What’s stored at this location? The number 10000, or 0x2710 in hex. At instruction 288, SLOAD takes the argument of where to read from storage (our hash) and pushes 0x2710 to the stack.</p><p>Finally, at instruction 289, SWAP1 resurfaces the function wrapper’s JUMPDEST location (0x70, or 112), and a JUMP in instruction 290 takes us back to the outgoing portion of the function wrapper, which will repack 0x2710 for returning it to the user.</p><p>I strongly advise you to go over the same debugging process we just did with balanceOf, this time with the totalSupply and transfer functions. The former is very straightforward, if not trivial, and the latter is considerably more complex but elementally made up of the same building blocks. The secret is understanding how values are read from mappings and written to mappings. There’s really not much more to it.</p><p>Now let’s go back to the big picture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*SjVy1vn9Hx2Bp6-NlK2pAg.png" /><figcaption>Figure 3. Function bodies after function wrappers.</figcaption></figure><p>As we’ve discussed before, the function bodies are all packed together right after the function wrappers. Execution flow jumps to them from the wrappers and returns to the wrappers after performing each function’s instructions.</p><p>If you look carefully at the diagram, there’s a chunk of code that comes after the function bodies called the “metadata hash.” This is a very simple structure that we’ll look at next in the final part of the series.</p><p>See you there!</p><ol><li><a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-i-introduction-832efd2d7737">Deconstructing a Solidity Contract — Part I: Introduction</a> ✔</li><li><a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-ii-creation-vs-runtime-6b9d60ecb44c">Deconstructing a Solidity Contract — Part II: Creation vs. Runtime</a> ✔</li><li><a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-iii-the-function-selector-6a9b6886ea49">Deconstructing a Solidity Contract — Part III: The Function Selector</a> ✔</li><li><a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-iv-function-wrappers-d8e46672b0ed">Deconstructing a Solidity Contract — Part IV: Function Wrappers</a> ✔</li><li>Deconstructing a Solidity Contract — Part V: Function Bodies ✔</li><li><a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-vi-the-swarm-hash-70f069e22aef">Deconstructing a Solidity Contract — Part VI: The Metadata Hash</a></li></ol><h3>Be part of the community</h3><ul><li>Continue the discussion on our <a href="https://forum.zeppelin.solutions/?utm_campaign=zep&amp;utm_medium=blog&amp;utm_source=medium">forum</a></li><li>Join our <a href="http://zpl.in/telegram">Telegram group</a></li><li>Follow us on <a href="https://twitter.com/ZeppelinOrg">Twitter</a></li><li>Even better, <a href="https://zeppelin.solutions/jobs/?utm_campaign=zep&amp;utm_medium=blog&amp;utm_source=medium">join the team</a> 🚀</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d19d4bef8be" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deconstructing a Solidity Contract — Part IV: Function Wrappers]]></title>
            <link>https://medium.com/@_ajsantander/deconstructing-a-solidity-contract-part-iv-function-wrappers-d8e46672b0ed?source=rss-c006b5d53b8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8e46672b0ed</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[guide]]></category>
            <category><![CDATA[solidity]]></category>
            <dc:creator><![CDATA[Alejandro Santander]]></dc:creator>
            <pubDate>Wed, 12 Sep 2018 15:10:34 GMT</pubDate>
            <atom:updated>2019-02-13T20:51:31.069Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*otL4fQBJRO1TOLrknRGfGw.png" /></figure><p><em>By </em><a href="https://twitter.com/_ajsantander"><em>Alejandro Santander</em></a><em> in collaboration with </em><a href="https://twitter.com/yoelopio"><em>Leo Arias</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pPctB3hG7zjxmUB9MEqzVA.jpeg" /><figcaption>Image from <a href="https://www.planetpaper.com/biodegradable-recyclable-packaging-material/">www.planetpaper.com</a></figcaption></figure><p><em>Note: This article is part of a series. If you haven’t read the previous article, please have a look at it first. We’re deconstructing the </em><a href="https://gist.github.com/ajsantander/03a4a183756980ef0865825bea96d6f5"><em>EVM bytecode</em></a><em> of a simple </em><a href="https://gist.github.com/ajsantander/dce951a95e7608bc29d7f5deeb6e2ecf"><em>Solidity contract</em></a><em>.</em></p><ol><li><a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-i-introduction-832efd2d7737">Deconstructing a Solidity Contract — Part I: Introduction</a> ✔</li><li><a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-ii-creation-vs-runtime-6b9d60ecb44c">Deconstructing a Solidity Contract — Part II: Creation vs. Runtime</a> ✔</li><li><a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-iii-the-function-selector-6a9b6886ea49">Deconstructing a Solidity Contract — Part III: The Function Selector</a> ✔</li><li>Deconstructing a Solidity Contract — Part IV: Function Wrappers ⬅</li><li><a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-v-function-bodies-2d19d4bef8be">Deconstructing a Solidity Contract — Part V: Function Bodies</a></li><li><a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-vi-the-swarm-hash-70f069e22aef">Deconstructing a Solidity Contract — Part VI: The Metadata Hash</a></li></ol><p>In the last article, we saw how the function selector acts as a hub or a switch of sorts in our <a href="https://gist.github.com/ajsantander/dce951a95e7608bc29d7f5deeb6e2ecf">BasicToken.sol</a> contract. It sits at the entry point of a contract and redirects execution to the matched function of the contract the caller wants to run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*At2aleYoe02_eL9Or2B4Zg.png" /><figcaption>Figure 1. Redirection from the function selector, as seen in the <a href="https://cdn.rawgit.com/ajsantander/23c032ec7a722890feed94d93dff574a/raw/a453b28077e9669d5b51f2dc6d93b539a76834b8/BasicToken.svg">deconstruction diagram</a>.</figcaption></figure><p>If the totalSupply function is called, execution will be redirected to location 91, balanceOf to 130, and so on.</p><p>Now let’s start a new debugging session in Remix as we’ve done before, and call the totalSupply function again. Make sure to always expand the <em>Instructions</em> panel, where the heart of Remix’s debugger is. As we saw before, Remix will place you at instruction 246, where the function’s body is just about to be executed. Last time, we took the <em>Transaction</em> slider from this position back to instruction 0, because we wanted to study the contract’s entry point and how it got to the function’s entry point from there. This time, we’re also going back (sorry!), but to instruction 91 instead of instruction 0, because there’s this <em>thing</em> that Solidity uses to wrap a function’s body. Don’t worry, we’ll get to the function’s body soon enough in the next article. We’re almost there; your patience will be rewarded!</p><p>So, step back to instruction 91, which is where the function selector leaves us because the function id matched totalSupply (0x18160ddd). At this point, the stack should only contain the function’s id. Now let’s walk through the code from here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*UjV04YS6oqNzXGqOOAuM8w.png" /><figcaption>Figure 2. The non-payable check structure.</figcaption></figure><p>Instructions 92 to 103 will basically revert if there is value (i.e., ether) involved in the transaction. Again, this is a very common structure injected by the Solidity compiler whenever a function isn’t payable. We saw this exact same thing being used in the constructor, <a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-ii-creation-vs-runtime-6b9d60ecb44c">in Part II of the series</a>, and it was also a non-payable function. This “non-payable check” structure will check if CALLVALUE ISZERO, and if so, will jump to instruction 103 (0x67), skipping the REVERT opcode in instruction 102.</p><p>If you called totalSupply on Remix without setting any value, we’ll reach instruction 103. Instruction 104 cleans up a zero that was left over in the stack, and then 112 (hex 0x0070) and 245 (hex 0x00f5) are pushed to the stack. Execution immediately jumps to the latter location: instruction 245. Notice that the jump occurs at instruction 111, and previously it pushed 112, so it wouldn’t be outrageous to imagine that the code is about to go do something, somewhere, and then come back that is, it will remember where we left off (112), jump, and then return.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*8150d0TfwxKn9Rn_URlk5Q.png" /><figcaption>Figure 3. Function wrapper jumping into the function body (yellow dashed lines).</figcaption></figure><p>Let’s see if that’s actually what happens by stepping to that mysterious 245 location.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*nxP5IQrYpnA84GvQBRm7Xw.png" /><figcaption>Figure 4. totalSupply function body.</figcaption></figure><p>If you step through 245 to 250, you’ll see that our theory was indeed correct. This “something” that the code detoured to is the actual function body, whose inner workings are not important to us right now. What’s important to the scope of this article is how the code reaches and leaves this “body-thing”, that is, how it wraps around it. It jumped <strong>into</strong> the body and <strong>out of</strong> the body. So, we see that the JUMP at 250 takes us back to 112, as we so cleverly predicted.</p><p>If this was <em>Age of Empires</em>, we should be hearing the <em>Bronze Age</em> fanfare by now. That’s right, we’re navigating through the bytecode using JUMP and JUMPI like crazy! Go ahead, <a href="https://www.zedge.net/ringtone/02d77eb2-81cb-3ae3-ac59-dd4abc512121">play it</a> — you deserve it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*FjeXGreIr6qV9hBR8A4KQg.png" /><figcaption>Image from <a href="https://en0.forgeofempires.com/page/the_game/buildings/good+buildings/iron+age/ebony+woodworks/">en0.forgeofempires.com</a></figcaption></figure><p>BUT! There’s something new this time around in the stack: the number 10000 (hex 0x2710) ✨. The function body we just traversed was kind enough to put it there for us. If you were a smart contract, what would you do now? (Please don’t say, “I’d run away with all the ether”!).</p><p>Remember that we’re calling the totalSupply function. Somehow, you need to get that value from the stack into a RETURN opcode, so that it can be returned to the user. And that’s exactly what the code does between the instructions 113 to 129, where there’s an actual RETURN opcode at the end.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*If4PBiS27dTEb8pdy7JDPA.png" /><figcaption>Figure 5. An uint256 memory returner structure.</figcaption></figure><p>It will first read the current free memory pointer (instructions 113 to 116), and then copy the value that the body of the function placed in the stack to that free space (instructions 117 to 119), which ends up storing the number 10000 (hex 0x2710) in memory. See? we’re getting good at this! If you don’t believe me, just step through the opcodes in Remix. Sounds complex but it’s not.</p><p>Finally, the code will figure out the size of the data that needs to be returned. Let’s look at that next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/116/1*x5DnhCrl8UnoTZ8MoR8Cmw.png" /><figcaption>Figure 6. Memory pointer offset?</figcaption></figure><p>It first loads the memory pointer again, and compares it using a subtraction to the previous memory pointer in instructions 120 to 124, most likely in an attempt to calculate the size of the data to be returned. This value seems to be hardcoded anyway in instruction 125, which may seem redundant. It’s probably the result of the optimizer realizing that the return data size can be hardcoded to save some gas and, after applying the optimization, some residual opcodes are left behind.</p><p>This is a perfect example of strange bytecode that apparently does nothing relevant or seems redundant. It’s OK to ignore opcodes that don’t seem to be accomplishing anything, and learn to live with them (or “through them” let’s say) and simply move on. As you read more and more bytecode, you’ll start identifying the purpose of these generic, apparently hollow structures in sudden short bursts of enlightenment.</p><p>That’s enough esoteric nonsense for now. Let’s get our feet back on the ground.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/136/1*ACZwoySxRhuoAIQl4aSmaQ.png" /><figcaption>Figure 7. Returning values to the user.</figcaption></figure><p>Instruction 125 will push the number 32 to the stack (hex 0x20) and add it to whatever our magical offset was, from our previous generic calculation (which was 0 anyway) swap the values around to match the order in which RETURN consumes its values …aaaand <strong>BOOM</strong>, the user has the totalSupply value returned.</p><p>OK. So, we saw how the code was routed from the function selector, into this wrapper structure that went into the function body, and out of the function body and then dealt with the translation of whatever the function body produced, and packed this data for returning it to the user. Well, shall we look at the other functions and see if we can observe a similar pattern in them as well?</p><p>If you’d like to take a break first, though, this would be the perfect time for it. What we’ll do next is simply reassure the structure we’ve just analyzed in the other two functions, with a little eye candy and a bit magic here and there along the way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/0*7P3HhB9QVnF4PiRX" /><figcaption>Coffee break!</figcaption></figure><p>So, that’s one function; two to go. Let’s look at thebalanceOf function next.</p><p>It ’s strongly advisable that you have a quick look around in the <a href="https://cdn.rawgit.com/ajsantander/23c032ec7a722890feed94d93dff574a/raw/a453b28077e9669d5b51f2dc6d93b539a76834b8/BasicToken.svg">deconstruction diagram</a>, to verify visually what just happened with totalSupply, and to get an idea of what we’re about to do with balanceOf.</p><p>The function selector should take us to instruction 130, which is balanceOf’s wrapper, and from there take us into the function’s body and out of it, packaging the return value for the user. However, if you notice in the diagram, the code does jump into the function’s body as expected, but it returns to totalSupply’s wrapper instead of it’s own. Why?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*5vsSykojVf-77bXtVqV7Kw.png" /><figcaption>Figure 8. balanceOf’s blue wrapper jumps back to totalSupply’s yellow wrapper.</figcaption></figure><p>A tempting reason for this to happen could be that since totalSupply and balanceOf both return a uint256 value, the chunk of code that grabs a uint256 value from the stack and returns a uint256 via memory is identical, and could be reused. The Solidity compiler could be noticing that part of the code generated for these two wrappers is the same, and deciding to reuse the code to save on gas. Well, it actually does just that, and we wouldn’t be observing this if optimizations were not enabled when we compiled the contract. Let’s call this structure that’s being reused the “wrappers’ uint256 memory returner”. A nice exercise would be to compile the contract without optimizations and verify this yourself ;D</p><p>Remix time. Let’s start a new debugging session by using the same address that we used to deploy the contract and call thebalanceOf function. It should return the number 10000, since the creator of the token initially holds all the goodies. In the <em>Debug</em> area, step back to instruction 142, which is where the function selector left us this time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*iKvMk6gNSTuvAsPQAnfyNQ.png" /><figcaption>Figure 9. balanceOf function wrapper.</figcaption></figure><p>At instruction 144, 112 (hex 0x0070) is pushed to the stack — which, not surprisingly, is the location of the “uint256 memory returner” structure we just saw. The code is about to jump off to balanceOf’s body, and it’s remembering where to jump back to after the body is executed.</p><p>However, the jump into the function body at instruction 175 doesn’t happen right away. Something is going on before it actually makes the jump, between instructions 147 and 172.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*Uqs_ZhePlnW0L1MHGkaUzg.png" /><figcaption>Figure 10. The calldata unpacker.</figcaption></figure><p>At instruction 147, a hexadecimal number with 40 f’s (20 bytes) is pushed to the stack, and then a 4. CALLDATALOAD is called with the 4 as an argument, which has the effect of reading the first word of data (32 bytes) from our calldata after the function id. If this sounds weird, then I’d recommend that you look at <a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-iii-the-function-selector-6a9b6886ea49">part III of the series</a>, where we analyze how calldata works. This word is the argument we passed into the function call, which is the address whose balance we want to check in the call to balanceOf. This address is masked with the big 0xffffffffffffffffffffffffffffffffffffffff number for type checking/masking, and then the jump in instruction 175 is made to the function body targeted at instruction 251 (hex 0x00fb), with the address that was read from calldata, sitting comfortably in the stack and ready for use by the body.</p><p>And so, we witness that a function wrapper’s job is not only to redirect into a function’s body, and package whatever comes back from the body for the user, but also to package stuff coming from the user for the function’s body to consume. The function wrapper’s nature thus reveals itself to us in its full glory!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ry_p_sHfRENGIz_G04nWcA.jpeg" /></figure><p>A function’s wrapper is an intermediary that unpacks the calldata for a function’s body to use, routes execution to it, and then repacks whatever comes back for the user. This wrapper structure is there for all functions that are part of the public interface of a contract in Solidity.</p><p>How this packing and unpacking is done, is something that is meticulously defined in <a href="https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html">Ethereum’s Application Binary Interface Specification</a>, which specifies how incoming and outgoing arguments in function calls are encoded.</p><p>Now, let’s have a quick look at the 3 function wrappers altogether:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IfMIceD_OvuZ5ZXfA9LqJg.png" /><figcaption>Figure 11. The function wrappers following after the function selector.</figcaption></figure><p>It’s easy to see, in a smart contract compiled by Solidity, that the big chunk of code that comes after the function selector is the function wrappers, one after the other. And yes, the actual function bodies is the next big chunk of code that comes after the wrappers, and after that there is this small peculiarity called the “metadata hash” that we’ll also see in a future post. But that’s it.</p><p>We’re beginning to see a grand architecture in EVM output produced by the Solidity compiler, and it’s slowly becoming less mysterious/chaotic. When analyzing a contract’s bytecode, you will quickly learn to first try to see where you are in terms of this grand structure before actually diving into the bytecode stepping details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*53-adxHACeum-XRxI2GsrQ.png" /><figcaption>Figure 12. The grand structure: function selector, wrappers and bodies.</figcaption></figure><p>As we did in the previous parts of this series, we leave debugging of a call to the transfer function to you. You should see how the wrapper unpacks two values this time — the beneficiary’s _to address, and the _value transferred — sends that to the function’s body, and then grabs the body’s response and packs it back up for the user. Makes sense, right?</p><p>In the next part of the series we’ll finally look into the function bodies. Once we do that, there’s not really much else to do… Only a couple of details to cover, and we’re done. This divide-and-conquer strategy is really starting to give us dominion over the problem we set out to tackle at the start of the series, which seemed overwhelming at first but now is starting to become a pattern we can familiarize ourselves with. The next time you see an opcode, you will not be scared. You’ll look it in the eye and fiercely say “Oh yeah? You and what opcode army!” You’ll skim through any bytecode like a true Ethereum ninja.</p><p>Let’s look at the function bodies next.</p><ol><li><a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-i-introduction-832efd2d7737">Deconstructing a Solidity Contract — Part I: Introduction</a> ✔</li><li><a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-ii-creation-vs-runtime-6b9d60ecb44c">Deconstructing a Solidity Contract — Part II: Creation vs. Runtime</a> ✔</li><li><a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-iii-the-function-selector-6a9b6886ea49">Deconstructing a Solidity Contract — Part III: The Function Selector</a> ✔</li><li>Deconstructing a Solidity Contract — Part IV: Function Wrappers ✔</li><li><a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-v-function-bodies-2d19d4bef8be">Deconstructing a Solidity Contract — Part V: Function Bodies</a></li><li><a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-vi-the-swarm-hash-70f069e22aef">Deconstructing a Solidity Contract — Part VI: The Metadata Hash</a></li></ol><h3>Be part of the community</h3><ul><li>Continue the discussion on our <a href="https://forum.zeppelin.solutions/?utm_campaign=zep&amp;utm_medium=blog&amp;utm_source=medium">forum</a></li><li>Join our <a href="http://zpl.in/telegram">Telegram group</a></li><li>Follow us on <a href="https://twitter.com/ZeppelinOrg">Twitter</a></li><li>Even better, <a href="https://zeppelin.solutions/jobs/?utm_campaign=zep&amp;utm_medium=blog&amp;utm_source=medium">join the team</a> 🚀</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8e46672b0ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deconstructing a Solidity Contract — Part III: The Function Selector]]></title>
            <link>https://medium.com/@_ajsantander/deconstructing-a-solidity-contract-part-iii-the-function-selector-6a9b6886ea49?source=rss-c006b5d53b8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a9b6886ea49</guid>
            <category><![CDATA[guide]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[solidity]]></category>
            <dc:creator><![CDATA[Alejandro Santander]]></dc:creator>
            <pubDate>Wed, 05 Sep 2018 14:28:28 GMT</pubDate>
            <atom:updated>2019-02-13T20:52:06.912Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_VbgLKIWQ67d4pxcccuJAA.png" /></figure><p><em>By </em><a href="https://twitter.com/_ajsantander"><em>Alejandro Santander</em></a><em> in collaboration with </em><a href="https://twitter.com/yoelopio"><em>Leo Arias</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*lILlaL7OCB6BeUwYOP3gZQ.png" /><figcaption>Image from <a href="http://texample.net/tikz/examples/multiplexer/">texsample.net</a></figcaption></figure><p><em>Note: This article is part of a series. If you haven’t read the previous article, please have a look at it first. We’re deconstructing the </em><a href="https://gist.github.com/ajsantander/03a4a183756980ef0865825bea96d6f5"><em>EVM bytecode</em></a><em> of a simple </em><a href="https://gist.github.com/ajsantander/dce951a95e7608bc29d7f5deeb6e2ecf"><em>Solidity contract</em></a><em>.</em></p><ol><li><a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-i-introduction-832efd2d7737">Deconstructing a Solidity Contract — Part I: Introduction</a> ✔</li><li><a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-ii-creation-vs-runtime-6b9d60ecb44c">Deconstructing a Solidity Contract — Part II: Creation vs. Runtime</a> ✔</li><li>Deconstructing a Solidity Contract — Part III: The Function Selector ⬅</li><li><a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-iv-function-wrappers-d8e46672b0ed">Deconstructing a Solidity Contract — Part IV: Function Wrappers</a></li><li><a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-v-function-bodies-2d19d4bef8be">Deconstructing a Solidity Contract — Part V: Function Bodies</a></li><li><a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-vi-the-swarm-hash-70f069e22aef">Deconstructing a Solidity Contract — Part VI: The Metadata Hash</a></li></ol><p>In the previous article, we identified the need to separate a contract’s bytecode into creation-time and runtime code. Having made a deep dive into the creation part, it’s now time to begin our quest into the runtime part. If you look at the <a href="https://cdn.rawgit.com/ajsantander/23c032ec7a722890feed94d93dff574a/raw/a453b28077e9669d5b51f2dc6d93b539a76834b8/BasicToken.svg">deconstruction diagram</a>, we’re going to start by looking at the second big split block titled <em>BasicToken.evm (runtime)</em>.</p><p>This might seem a bit scary at first because the runtime code looks at least four times the size of the creation code! But don’t worry, the skills we’ve developed in the previous articles for understanding EVM code, combined with our infallible divide-and-conquer strategy, will make addressing the challenge surprisingly systematic, and perhaps even easy. It’s simply a matter of starting to look at the code, identifying stand-alone structures, and continuing to split until there’s nothing else to split.</p><p>So, to get started, let’s go back to <a href="https://remix.ethereum.org/">Remix</a> and initiate a debugging session with the runtime bytecode only. How do we do that? Last time, we deployed the contract and debugged the deployment transaction. This time, we’ll interact with the deployed contract’s interface, with one of its functions, and debug that transaction instead. Recall our contract:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8218617b4dcb095ee600deb56a823079/href">https://medium.com/media/8218617b4dcb095ee600deb56a823079/href</a></iframe><p>Deploy it in Remix using the Javascript VM, v0.4.24 of the compiler with optimizations enabled, and 10000 as the initial supply. Once the contract is deployed, you should see it listed in the <em>Deployed Contracts</em> section of Remix’s <em>Run</em> panel. Click on it to expand the contract’s interface.</p><p>What is this interface? It’s a list of all the methods of the contract that are either public or external — i.e., that any Ethereum account or contract can interact with. Private and internal methods will not show here and are in fact not reachable from “the outside world”. How to interact with particular portions of the runtime code of a contract will be the focus of this article.</p><p>Should we try it out? Click on the <em>totalSupply</em> button in Remix’s <em>Run</em> panel. You should immediately see a response below the button: 0: uint256: 10000, which is what we would expect, since we deployed the contract with 10000 as the initial token supply. Now, in the <em>Console</em> panel, click on the <em>Debug</em> button to start a debugging session with this paticular transaction. Notice that there will be multiple <em>Debug</em> buttons in the <em>Console</em> panel; make sure you’re using the latest one.</p><p>In this case, we’re not debugging a transaction to the 0x0 address, which as we saw in the previous article creates a contract. Instead, we’re debugging a transaction made to the contract itself — i.e., to its runtime code.</p><p>If you pop open the <em>Instructions</em> panel, you should be able to verify that the instructions listed by Remix are identical to those in the <em>BasicToken.evm (runtime)</em> section in the <a href="https://cdn.rawgit.com/ajsantander/23c032ec7a722890feed94d93dff574a/raw/a453b28077e9669d5b51f2dc6d93b539a76834b8/BasicToken.svg">deconstruction diagram</a>. If they don’t match, something went wrong. Try starting over and making sure that you’re using the the right settings as described above.</p><p>All good? The first thing you may notice is that the debugger placed you at instruction 246 and that the <em>Transaction Slider</em> is positioned at about 60% of the bytecode. Why? Well, because Remix is a really nice and generous program, and it takes you directly to the part in which the EVM is just about to execute the body of the <em>totalSupply</em> function. However, a LOT of things happened before this point, and those are what we want to pay attention to here. In fact, we won’t even look into the execution of the body of the function in this article. Our single concern here is how Solidity’s generated EVM code routes incoming transactions, which is the job of what we will come to understand as a contract’s “Function Selector”.</p><p>So, grab that slider and drag it all the way to the left so that we start from instruction zero. As we saw before, the EVM <strong>always</strong> executes code from instruction 0, no exceptions, and then flows through the rest of the code. Let’s walk through this execution opcode by opcode.</p><p>The first structure that appears is something we’ve seen before (and that we’ll see a lot of, actually):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*8cJ_PXVxuym_8MKvvPhydg.png" /><figcaption>Figure 1. The free memory pointer.</figcaption></figure><p>This is something Solidity-generated EVM code will always do before anything else in a call: save a spot in memory to be used later.</p><p>Let’s see what happens next:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*wZ0YkY1z1eBpBTxjznT7hA.png" /><figcaption>Figure 2. Calldata length check.</figcaption></figure><p>If you open Remix’s <em>Stack</em> panel in the <em>Debug</em> tab and step past instructions 5 to 7, you will see that the stack now contains the number 4 twice. If you’re having trouble reading these super long numbers, note that you adjust the width of Remix’s Debug panel so that the numbers fit nicely into single lines. The first one came from a regular push, but the second one is the result of executing the opcode CALLDATASIZE, which <a href="https://ethereum.github.io/yellowpaper/paper.pdf">as the Yellow Paper states</a>, takes no arguments and returns the size of the “input data in the current environment”, or what we often refer to as the <em>calldata</em>.</p><p>What is the calldata? <a href="https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html">As explained in Solidity’s documentation ABI specification</a>, the calldata is an encoded chunk of hexadecimal numbers that contains information about what function of the contract we want to call, and it’s arguments or data. Simply put, it consists of a “function id”, which is generated by hashing the function’s signature (truncated to the first leading four bytes) followed by the packed arguments data. You may study the documentation link in detail if you want, but don’t worry about understanding how this packaging works to the finest detail just yet. It’s explained in the documentation, but is a little hard to grasp all at once. It’s much easier to understand with practical examples.</p><p>Let’s see what this calldata is. Open the <em>Call Data</em> panel in Remix’s debugger to see: 0x18160ddd. That’s four bytes produced precisely by applying the keccak256 algorithm on the function signature as a string — &quot;totalSupply()&quot; — and performing the said truncation. Since this particular function takes no arguments, it’s just that: a four-byte function id. When CALLDATASIZE is called, it simply pushes the second 4 on to the stack.</p><p>Instruction 8 then uses LT to verify if the calldata size is less than four. If so, the following two instructions perform a JUMPI to instruction 86 (0x0056). That is less than four bytes, so in that case there will be no jump, and the execution flow will continue to instruction 13. But before we do that, let’s imagine that we made a call to our contract with empty calldata — that is, 0x0 instead of 0x18160ddd. You can’t do that with Remix btw, but you could if you constructed the transaction manually.</p><p>In that case, we’d end up in instruction 86, which basically pushes a couple of zeroes to the stack and feeds them to a REVERT opcode. Why? Well, because this contract doesn’t have a <a href="https://solidity.readthedocs.io/en/v0.4.24/contracts.html?highlight=fallback%20function#fallback-function">fallback function</a>. If the bytecode doesn’t identify the incoming data, it will divert the flow to the fallback function, and if that structure doesn’t “catch” the call, this revert structure will, terminating the execution with absolutely no regret or compassion. Ruthlessly. If there’s nothing to fall back to, then there is nothing to do and the call is completely reverted.</p><p>Now, let’s do something a little more interesting. Go back to Remix’s <em>Run</em> tab, copy the <em>Account</em> address, and use it as a parameter to call balanceOf instead of totalSupply and debug that transaction. This is a completely new debugging session; let’s forget about totalSupply for now. Navigate to instruction 8, where CALLDATASIZE will now have pushed 36 (0x24) to the stack. And if you look at the calldata, it’s now 0x70a08231000000000000000000000000ca35b7d915458ef540ade6068dfe2f44e8fa733c.</p><p>This new calldata is actually super easy to break apart: the first four bytes 70a08231 are the hash of the signature &quot;balanceOf(address)&quot;, and the 32 bytes that follow contain the address we passed as a parameter. Why 32 bytes if Ethereum addresses are only 20 bytes long, the inquisitive reader may ask? The ABI always uses 32-byte “words” or “slots” to hold parameters used in function calls.</p><p>Continuing in the context of our balanceOf call, let’s pick up where we left off at instruction 13, at which point there’s nothing in the stack. Instruction 13 then pushes 0xffffffff to the stack, and the next instruction pushes a 29 byte long 0x000000001000…000 number to the stack. We’ll see why in just a moment. For now, simply notice that one contains four bytes of f&#39;s, and the other contains four bytes of 0&#39;s.</p><p>Next up CALLDATALOAD takes one parameter (the one pushed to the stack at instruction 48) and reads a chunk of 32 bytes from the calldata at that position, which in this case in <a href="https://solidity.readthedocs.io/en/v0.4.24/julia.html">Yul</a> would be:</p><pre>calldataload(0)</pre><p>Basically pushing our entire calldata to the stack. Now comes the funny part. DIV consumes two arguments from the stack, taking the calldata and dividing it by that weird 0x000000001000…000 number, effectively filtering everything <em>but</em> the function signature from the calldata and leaving that alone on the stack: 0x000…000070a08231. The next instruction uses AND, which also consumes two elements from the stack: our function id and the number with four bytes of f’s. This is to make sure that the signature hash is exactly eight bytes long, masking out anything else, if anything were present. A safety measure used by Solidity, I presume.</p><p>Long story short, we’ve simply checked if the calldata is too short, and if so, reverted, and then shuffled things a bit so that we have our function id in the stack: 70a08231.</p><p>Aaaaand, we’re almost done here. The next part is really easy to understand:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IgrF4NZNL4UNpnTKn33S1A.png" /><figcaption>Figure 3. The function selector.</figcaption></figure><p>At instruction 53, the code pushes 18160ddd (the function id of totalSuppy) to the stack and then uses a DUP2 to duplicate our incoming calldata 70a08231 value, currently present at the second position in the stack. Why the dup? Because the EQ opcode at instruction 59 will consume two values from the stack and we want to keep the 70a08231 value around, as we went through so much trouble to extract it from the calldata.</p><p>The code will now try to match the function id from the calldata with one of the known function ids. Since 70a08231 is coming in, it will not match 18160ddd, skipping the JUMPI at instruction 63. But it will match in the next check and jump into the JUMPI at instruction 74.</p><p>Let’s take a moment to observe that there is one of these equality checks for each public or external function of the contract. This is the function selector’s core: acting as some sort of switch statement that simply routes execution to the correct part of the code. It is our “hub”.</p><p>So, since the last case was a match, execution flow takes us to the JUMPDEST at location 130, which is, as we will see in the next part of the series, the ABI “wrapper” of the balanceOf function. As we will see, this wrapper will be in charge of un-packaging the transaction’s data for the function’s body to consume.</p><p>Go ahead and try debugging the transfer function this time. There’s really no mystery to the function selector. It’s a simple and effective structure that sits at the gate of every contract out there (at least all those compiled from Solidity) and redirects execution to the appropriate location in the code. It’s the way in which Solidity gives a contract’s bytecode the ability to emulate multiple entry points, and hence, an interface.</p><p>Looking at the <a href="https://cdn.rawgit.com/ajsantander/23c032ec7a722890feed94d93dff574a/raw/a453b28077e9669d5b51f2dc6d93b539a76834b8/BasicToken.svg">deconstruction diagram</a>, this is what we’ve just deconstructed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H1f1__xgVIBWNIw0l3RDmw.png" /><figcaption>Figure 4. The function selector and a contract’s runtime code main entry point.</figcaption></figure><p>That’s all, folks! For now :)</p><p>See you in the next part!</p><ol><li><a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-i-introduction-832efd2d7737">Deconstructing a Solidity Contract — Part I: Introduction</a> ✔</li><li><a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-ii-creation-vs-runtime-6b9d60ecb44c">Deconstructing a Solidity Contract — Part II: Creation vs. Runtime</a> ✔</li><li>Deconstructing a Solidity Contract — Part III: The Function Selector ✔</li><li><a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-iv-function-wrappers-d8e46672b0ed">Deconstructing a Solidity Contract — Part IV: Function Wrappers</a></li><li><a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-v-function-bodies-2d19d4bef8be">Deconstructing a Solidity Contract — Part V: Function Bodies</a></li><li><a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-vi-the-swarm-hash-70f069e22aef">Deconstructing a Solidity Contract — Part VI: The Metadata Hash</a></li></ol><h3>Be part of the community</h3><ul><li>Continue the discussion on our <a href="https://forum.zeppelin.solutions/?utm_campaign=zep&amp;utm_medium=blog&amp;utm_source=medium">forum</a></li><li>Join our <a href="http://zpl.in/telegram">Telegram group</a></li><li>Follow us on <a href="https://twitter.com/ZeppelinOrg">Twitter</a></li><li>Even better, <a href="https://zeppelin.solutions/jobs/?utm_campaign=zep&amp;utm_medium=blog&amp;utm_source=medium">join the team</a> 🚀</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a9b6886ea49" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deconstructing a Solidity Contract — Part II: Creation vs. Runtime]]></title>
            <link>https://medium.com/@_ajsantander/deconstructing-a-solidity-contract-part-ii-creation-vs-runtime-6b9d60ecb44c?source=rss-c006b5d53b8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b9d60ecb44c</guid>
            <category><![CDATA[guide]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[Alejandro Santander]]></dc:creator>
            <pubDate>Mon, 13 Aug 2018 15:54:27 GMT</pubDate>
            <atom:updated>2019-02-13T20:52:31.179Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UQC1sHA5IZIC-RRbZ7Wz2w.png" /></figure><p><em>By </em><a href="https://twitter.com/_ajsantander"><em>Alejandro Santander</em></a><em> in collaboration with </em><a href="https://twitter.com/yoelopio"><em>Leo Arias</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*BIdVX8j6PVoPxg9a" /><figcaption>Image from <a href="https://commons.wikimedia.org/wiki/File:Single-cylinder_T-head_engine_(Autocar_Handbook,_13th_ed,_1935).jpg">commons.wikimedia.org</a></figcaption></figure><p><em>Note: This article is part of a series. If you haven’t read the introduction, please have a look at it first. We’re deconstructing the </em><a href="https://gist.github.com/ajsantander/03a4a183756980ef0865825bea96d6f5"><em>EVM bytecode</em></a><em> of a simple </em><a href="https://gist.github.com/ajsantander/dce951a95e7608bc29d7f5deeb6e2ecf"><em>Solidity contract</em></a><em>.</em></p><ol><li><a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-i-introduction-832efd2d7737">Deconstructing a Solidity Contract — Part I: Introduction</a> ✔</li><li>Deconstructing a Solidity Contract — Part II: Creation vs. Runtime ⬅</li><li><a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-iii-the-function-selector-6a9b6886ea49">Deconstructing a Solidity Contract — Part III: The Function Selector</a></li><li><a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-iv-function-wrappers-d8e46672b0ed">Deconstructing a Solidity Contract — Part IV: Function Wrappers</a></li><li><a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-v-function-bodies-2d19d4bef8be">Deconstructing a Solidity Contract — Part V: Function Bodies</a></li><li><a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-vi-the-swarm-hash-70f069e22aef">Deconstructing a Solidity Contract — Part VI: The Metadata Hash</a></li></ol><p>Let’s get started by attacking the <a href="https://gist.github.com/ajsantander/60bd8d6f88725663f89a67a7c51672c7">disassembled gibberish of our contract</a> with our divide-and-conquer lightsaber. As we saw in the introductory article, this disassembled code is very low-level, but quite readable compared to the raw bytecode. Make sure you’ve followed along in the Introduction, and that you have the BasicToken contract compiled and deployed in <a href="https://remix.ethereum.org/">Remix</a>. Debug the creation transaction and open up the <em>Instructions</em> panel. Also, have the <a href="https://cdn.rawgit.com/ajsantander/23c032ec7a722890feed94d93dff574a/raw/a453b28077e9669d5b51f2dc6d93b539a76834b8/BasicToken.svg">deconstruction diagram</a> at hand while we go along.</p><p><em>DISCLAIMER: All instructions provided in this article are subject to my own interpretation of how things work. Please feel free to make comments below in case I need to be corrected in any way, and I’ll be sure to update the article accordingly.</em></p><p>For now, let’s focus on the JUMP, JUMPI, JUMPDEST, RETURN, and STOP opcodes, and <strong>ignore all others</strong>. Whenever we find an opcode that is not one of these, we will ignore it and skip to the next instruction, pretending that nothing intervened.</p><p>When the EVM executes code, it does so top down with no exceptions — i.e., there are no other entry points to the code. It always starts from the top. It can jump around, yes, and that’s exactly what JUMP and JUMPI do. JUMP takes the topmost value from the stack and moves execution to that location. The target location must contain a JUMPDEST opcode, though, otherwise execution will fail. That is the sole purpose of JUMPDEST: to mark a location as a valid jump target. JUMPI is exactly the same, but there must not be a “0” in the second position of the stack, otherwise there will be no jump. So this is a conditional jump. STOP completely halts execution of the contract, and RETURN halts execution too, but returns data from a portion of the EVM’s memory, which is handy.</p><p>So, let’s start interpreting the code with all of this in mind. In Remix’s debugger, move the <em>Transaction slider </em>all the way to the left and open up the <em>Instructions</em> section. You can walk through the instructions with the <em>Step Into</em> button (the one that looks like a little down-pointing arrow). The first instructions can be ignored, but at instruction 11 we find our first JUMPI. If it doesn’t jump, it will continue through instructions 12 to 15 and end up in a REVERT, which would halt execution. But if it does jump, it will skip these instructions to the location 16 (hex 0x0010, which was pushed to the stack at instruction 8). Instruction 16 is a JUMPDEST. So far so good.</p><p>Keep on stepping through the opcodes until the <em>Transaction slider</em> is all the way to the right. A lot of blah-blah just happened, but only in location 68 do we find a RETURN opcode (and a STOP opcode in instruction 69, just in case). This is rather curious. If you think about it, the control flow of this contract will always end at instructions 15 or 68. We’ve just walked through it and determined that there are no other possible flows, so what are the remaining instructions for? (If you slide down the <em>Instructions</em> panel, you’ll see that the code ends at location 566).</p><p>The set of instructions we’ve just traversed (0 to 69) is what’s known as the “creation code” of a contract. It will never be a part of the contract’s code per se, but is only executed by the EVM once during the transaction that creates the contract. As we will soon discover, this piece of code is in charge of setting the created contract’s initial state, as well as returning a copy of its runtime code. The remaining 497 instructions (70 to 566) which, as we saw, will never be reached by the execution flow, are precisely the code that will be part of the deployed contract.</p><p>If you open the <a href="https://cdn.rawgit.com/ajsantander/23c032ec7a722890feed94d93dff574a/raw/a453b28077e9669d5b51f2dc6d93b539a76834b8/BasicToken.svg">deconstruction diagram</a>, you should see how we’ve just made our first split: we’ve differentiated creation-time vs. runtime code.</p><p>We will now take a deep dive into the creation part of the code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Lw5_OC9scTKG-1hz9AH6Q.png" /><figcaption>Figure 1. Deconstruction of the creation-time EVM bytecode of BasicToken.sol.</figcaption></figure><p>This is the most important concept to understand in this article. The creation code gets executed in a transaction, which returns a copy of the runtime code, which is the actual code of the contract. As we will see, the constructor is part of the creation code, and not part of the runtime code. The contract’s constructor is part of the creation code; it will not be present in the contract’s code once it is deployed.</p><p>How does this magic happen? That’s what we’ll analyze now, step by step.</p><p>Alright. So now our problem is reduced to understanding these ~70 instructions corresponding to the creation-time code.</p><p>Let’s re-take our top-down approach, this time understanding all the instructions as we go along, not skipping any of them. First, let’s focus on instructions 0 to 2, which use the PUSH1 and MSTORE opcodes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/247/0*5OMq5NuSFD0tpsNM" /><figcaption>Figure 2. The free memory pointer EVM bytecode structure.</figcaption></figure><p>PUSH1 simply pushes one byte onto the top of the stack, and MSTORE grabs the two last items from the stack and stores one of them in memory:</p><pre>mstore(0x40, 0x80)<br>       |     |<br>       |     What to store.<br>       Where to store.</pre><pre>(in memory)</pre><p><em>NOTE: The above snippet is Yul-ish code. Notice how it consumes elements from the stack from left to right, always consuming what’s on the top of the stack first.</em></p><p>This basically stores the number 0x80 (decimal 128) into memory at position 0x40 (decimal 64). What for? At this point of our narrative, who cares ¯\_(ツ)_/¯?! There must be a reason (which we’ll actually see later). For now, open the <em>Stack</em> and <em>Memory</em> panels in Remix’s <em>Debugger</em> tab to visualize the values as you step back and forth through these instructions.</p><p>You might be wondering: what happened to instructions 1 and 3? PUSH instructions are the only EVM instructions that are actually composed of two or more bytes. So, PUSH 80 is really two instructions. The mystery is revealed, then: instruction 1 is 0x80 and instruction 3 is 0x40.</p><p>Next up are instructions 5 to 15.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/0*BLGQ4rprV7YR3fpU" /><figcaption>Figure 3. The non-payable check EVM bytecode structure.</figcaption></figure><p>Here we have a bunch of new opcodes: CALLVALUE, DUP1, ISZERO, PUSH2, and REVERT. CALLVALUE pushes the amount of wei involved in the creation transaction, DUP1 duplicates the first element on the stack, ISZERO pushes a 1 to the stack if the topmost value of the stack is zero, PUSH2 is just like PUSH1 but it can push two bytes to the stack instead of just one, and REVERT halts execution.</p><p>So what’s going on here? In Solidity, we could write this chunk of assembly like this:</p><pre>if(msg.value != 0) revert();</pre><p>This code was not actually part of our original Solidity source, but was instead injected by the compiler because we did not declare the constructor as payable. In the most recent versions of Solidity, functions that do not explicitly declare themselves as payable cannot receive ether. Going back to the assembly code, the JUMPI at instruction 11 will skip instructions 12 through 15 and jump to 16 if there is no ether involved. Otherwise, REVERT will execute with both parameters as 0 (meaning that no useful data will be returned).</p><p>Alright! Coffee break. The next part will be a bit trickier, so it might be a good idea to take a few minutes off. Go ahead and prepare yourself a nice cup of coffee while you summon your powers of concentration. Make sure you understand what we’ve seen so far, because the next part is a bit more complicated.</p><p>If you’d like yet another way to visualize what we’ve just done, try out this simple tool I’ve built: <a href="https://solmap.zeppelin.solutions/">solmap</a>. It allows you to compile Solidity code on real-time and then click on EVM opcodes to highlight the associated Solidity code. The disassembly is a bit different from Remix’s, but you should be able to understand it by comparison.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/0*O71S1DRNNv7peg9F" /><figcaption>Coffee break!</figcaption></figure><p>Ready to move on? Great! Next up are instructions 16 to 37. Keep following with Remix’s debugger. (Remember, Remix is your friend ^^).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/1*V8dQHrbSylBCfpE6di-DEQ.png" /><figcaption>Figure 4. EVM bytecode structure for retrieving constructor parameters from code appended at the end of a contract’s bytecode.</figcaption></figure><p>The first four instructions (17 to 20) read whatever is in memory at position 0x40 and push that to the stack. If you recall from a little earlier, that should be the number 0x80. The following instructions then push 0x20 (decimal 32) to the stack (instruction 21), duplicate that value (instruction 23), push 0x0217 (decimal 535) (instruction 24), and finally duplicate the fourth value (instruction 27), which should be 0x80 again. Phew! I almost ran out breath while writing that sentence. When looking at EVM instructions like this, it’s okay to not understand what’s going on for a while. Don’t worry, it will suddenly click in your mind.</p><p>On instruction 28, CODECOPY is executed, which takes three arguments: target memory position to copy the code to, instruction number to copy from, and number of bytes of code to copy. So, in this case, it targets memory at position 0x80, from byte position 535 in code, 32 bytes of code length. Why?</p><p>If you look at the entire disassembled code, there are 566 instructions. So why is this code trying to copy the last 32 bytes of code? Actually, when deploying a contract whose constructor contains parameters, the arguments are appended to the end of the code as raw hex data. Scroll down the <em>Instructions</em> panel all the way to see this. In this case, the constructor takes one uint256 parameter, so all this code is doing is copying the argument to memory from the value appended at the end of the code. These 32 instructions don’t make sense as disassembled code, but they do in raw hex: 0x0000000000000000000000000...0000000000000000000002710. Which is, of course, the decimal value 10000 we passed to the constructor when we deployed the contract!</p><p>See why you needed that coffee? Again, feel free to repeat this part in Remix step by step, making sure that you understand what just happened. The end result should be that you see the number 0x00..002710 stored in memory at position 0x80.</p><p>Okay. For the next part, you might want to fix yourself a nice double measure of whisky. It’s about to get weird.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/128/0*ZFl01bRK92u3lHAP" /><figcaption>Whisky break!</figcaption></figure><p>Just kidding. No more magic, I promise. It’s all downhill from here.</p><p>The next set of instructions (29 to 35) update the value stored in memory at position 0x40 from the number 0x80 to the number 0xa0: that is, they offset the value by 0x20 (32) bytes. Now we can start making sense of instructions 0 to 2 (remember when we shrugged?). Solidity keeps track of something called a “free memory pointer”: that is, a place in memory we can use to store stuff, with the guarantee that no one will overwrite it (except us if we make a mistake, of course, using inline assembly or Yul). So, since we stored the number 10000 in the old free memory position, we updated the free memory pointer by shifting it 32 bytes forward.</p><p>Even experienced Solidity developers can be confused when they see the expression “free memory pointer” or the code mload(0x40, 0x80). These are just saying, “We’ll be writing to memory from this point on and keeping a record of the offset, each time we write a new entry.” Every single function in Solidity, when compiled to EVM bytecode, will initialize this pointer.</p><p>What’s in memory between 0x00 to 0x40, you may wonder. Nothing. It’s just a chunk of memory that Solidity reserves for calculating hashes, which, as we’ll see soon, are necessary for mappings and other types of dynamic data.</p><p>Now, on instruction 37, MLOAD reads from memory at position 0x40 and basically downloads our 10000 value from memory into the stack, where it will be fresh and ready for consumption in the next set of instructions.</p><p>This is a common pattern in EVM bytecode generated by Solidity: before a function’s body is executed, the function’s parameters are loaded into the stack (whenever possible), so that the upcoming code can consume them — and that’s exactly what’s going to happen next.</p><p>Let’s continue with instructions 38 to 55.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*UuDb5zBQTz_OJXYM6UPp3A.png" /><figcaption>Figure 5. The constructor’s body EVM code.</figcaption></figure><p>These instructions are nothing more and nothing less than the constructor’s body: that is, the Solidity code:</p><pre>totalSupply_ = _initialSupply;<br>balances[msg.sender] =  _initialSupply;</pre><p>The first four instructions are pretty self-explanatory (38 to 42). First, 0 is pushed to the stack, then the second item in the stack is duplicated (that’s our 10000 number), and then the number 0 is duplicated and pushed to the stack, which is the position slot in storage of totalSupply_. Now, SSTORE can consume the values and still keep 10000 lying around for future use:</p><pre>sstore(0x00, 0x2710) <br>       |     |<br>       |     What to store.<br>       Where to store.</pre><pre>(in storage)</pre><p>Voila! We stored the number 10000 in the variable totalSupply_. Isn’t that amaaaazing???</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/127/0*0ZGwOkiZQMuQ4Jrk" /></figure><p>Be sure to visualize this value in Remix’s <em>Debugger</em> tab too. You’ll find it in the <em>Storage completely loaded</em> panel.</p><p>The next set of instructions (43 to 54) are a bit disconcerting, but will basically deal with storing 10000 in the balances mapping for the key of msg.sender. Before moving forward, make sure you understand <a href="https://solidity.readthedocs.io/en/v0.4.24/miscellaneous.html#layout-of-state-variables-in-storage">this part of the Solidity documentation, which explains how a mapping is saved in storage</a>. Long story short, it will concatenate the slot of the mapping value (in this case the number 1, because it’s the second variable declared in the contract) with the key used (in this case, msg.sender, obtained with the opcode CALLER), then hash that with the SHA3 opcode and use that as the target position in storage. Storage, in the end, is just a simple dictionary or hash table.</p><p>Moving on with instructions 43 to 45, the msg.sender address is stored in memory (this time at position 0x00), and then in instructions 46 to 50, the value 1 (the slot of the mapping) is stored at memory position 0x20. Finally, the SHA3 opcode calculates the Keccak256 hash of whatever is in memory from position 0x00 to position 0x40 — that is, the concatenation of the mapping’s slot/position with the key used. This is precisely where the value 10000 will be stored in our mapping:</p><pre>sstore(hash..., 0x2710)<br>       |        |<br>       |        What to store.<br>       Where to store.</pre><p>And that’s it. At this point, the constructor’s body has been fully executed.</p><p>All this may be a bit overwhelming at first, but it’s a fundamental part of how storage works in Solidity. If you didn’t quite get it, I recommend that you go over it a few times following along with Remix’s debugger, keeping the <em>Stack</em> and <em>Memory</em> panels in sight. Also, feel free to ask questions below. This pattern is used all over the place in EVM bytecode generated by Solidity, and you will quickly learn to identify it effortlessly. In the end, it is nothing more than calculating where to save, in storage, the value for a certain key for a mapping.</p><p>Alright, we’re almost done here. If you got this far, the next part will be a piece of cake.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/1*yGXyjnCMUq6K-683jHZ6SA.png" /><figcaption>Figure 6. The runtime code copy structure.</figcaption></figure><p>In instructions 56 to 65, we’re performing a code copy again. Only this time, we’re not copying the last 32 bytes of the code to memory; we’re copying 0x01d1 (decimal 465) bytes starting from position 0x0046 (decimal 70) into memory at position 0. That’s one big chunk of code to copy!</p><p>If you slide the <em>Transaction slider</em> all the way to the right again, you’ll notice that position 70 is right after our creation-time EVM code, where execution stopped. The runtime bytecode is contained in those 465 bytes. This is the part of the code that will be saved in the blockchain as the contract’s runtime code, which will be the code that will be executed every time someone or something interacts with the contract. (We’ll cover the runtime code in future parts of this series).</p><p>And this is exactly what instructions 66 to 69 do: the code that we copied to memory is returned.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/216/1*gxYX1LuP_NU8hYzrR9jgMQ.png" /><figcaption>Figure 7. The runtime code return EVM bytecode structure.</figcaption></figure><p>RETURN grabs the code copied to memory and hands it over to the EVM. If this creation code is executed in the context of a transaction to the 0x0 address, the EVM will execute the code and store the return value as the created contract’s runtime code.</p><p>That’s it! By now, our BasicToken contract instance will be created and deployed with its initial state and runtime code ready for use. If you take a step back and look at Figure 2, you’ll see that all the EVM bytecode structures we analyzed are generic, except the one highlighted in purple: that is, they will be in creation-time bytecode generated by the Solidity compiler. What will differ from constructor to constructor is just the purple part — the constructor function’s actual body. The structure that fetches parameters embedded at the end of the bytecode, as well as the structures that copy the runtime code and return it, can be considered boilerplate code and generic EVM opcode structures. You should be able to look at any constructor now, and before studying it instruction by instruction, you should have a general idea of the components that make it up.</p><p>In the next article of this series, we’ll look at the actual runtime code, starting with how you can interact with a contract’s EVM code at different entry points. For now, give yourself a well-deserved pat on the back, because you have just digested the most difficult part of the series. You should also have developed a strong ability to read through and debug EVM bytecode, understand generic structures, and, most importantly, understand the difference between creation-time and runtime EVM bytecode. This is what makes the constructor function of a contract so special in Solidity.</p><p>See you in the next episode!</p><ol><li><a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-i-introduction-832efd2d7737">Deconstructing a Solidity Contract — Part I: Introduction</a> ✔</li><li>Deconstructing a Solidity Contract — Part II: Creation vs. Runtime ✔</li><li><a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-iii-the-function-selector-6a9b6886ea49">Deconstructing a Solidity Contract — Part III: The Function Selector</a></li><li><a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-iv-function-wrappers-d8e46672b0ed">Deconstructing a Solidity Contract — Part IV: Function Wrappers</a></li><li><a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-v-function-bodies-2d19d4bef8be">Deconstructing a Solidity Contract — Part V: Function Bodies</a></li><li><a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-vi-the-swarm-hash-70f069e22aef">Deconstructing a Solidity Contract — Part VI: The Metadata Hash</a></li></ol><h3>Be part of the community</h3><ul><li>Continue the discussion on our <a href="https://forum.zeppelin.solutions/?utm_campaign=zep&amp;utm_medium=blog&amp;utm_source=medium">forum</a></li><li>Join our <a href="http://zpl.in/telegram">Telegram group</a></li><li>Follow us on <a href="https://twitter.com/ZeppelinOrg">Twitter</a></li><li>Even better, <a href="https://zeppelin.solutions/jobs/?utm_campaign=zep&amp;utm_medium=blog&amp;utm_source=medium">join the team</a> 🚀</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b9d60ecb44c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deconstructing a Solidity Contract —Part I: Introduction]]></title>
            <link>https://medium.com/@_ajsantander/deconstructing-a-solidity-contract-part-i-introduction-832efd2d7737?source=rss-c006b5d53b8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/832efd2d7737</guid>
            <category><![CDATA[guide]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[Alejandro Santander]]></dc:creator>
            <pubDate>Mon, 13 Aug 2018 15:15:40 GMT</pubDate>
            <atom:updated>2019-02-13T20:52:45.782Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DPTUIIXvwggm1Hy8RAG_XA.png" /></figure><p><em>By </em><a href="https://twitter.com/_ajsantander"><em>Alejandro Santander</em></a><em> in collaboration with </em><a href="https://twitter.com/yoelopio"><em>Leo Arias</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kwEkUJQ1b6rHFxP9" /><figcaption>Image from <a href="http://szzljy.com/assets/download.php?file=/data/12/wallpapers/34/818705.jpg">www.szzljy.com</a></figcaption></figure><p>You’re on the road, driving fast in your rare, fully restored 1969 Mustang Mach 1. The sunlight shimmers on the all-original, gorgeous plated rims. It’s just you, the road, the desert, and the never-ending chase of the horizon. Perfection!</p><p>In the blink of an eye, your 335 hp beast is engulfed in white smoke, as if transformed into a steam locomotive, and you’re forced to stop on the side of the road. With determination, you pop the hood, only to realize that you have absolutely no idea what you’re looking at. How does this damn machine work? You grab your phone and discover that you have no signal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*XIjfOJYqy0n-h8jl" /><figcaption>Image from <a href="http://www.mustangandfords.com/featured-vehicles/mdmp-0704-2003-ford-mustang-mach-1/photo-gallery/#11">www.mustangandfords.com</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/128/0*kmPuMjzhuC6xgfu2" /></figure><p>Could this perhaps be an analogy for your current knowledge of dApp development? In the analogy, the Mustang is your set of smart contracts, the rims are all those well-thought-out little details and the ❤ you put into them. And the popping of the hood is you looking into your contract’s EVM bytecode and having absolutely no idea what’s going on.</p><p>If this sounds familiar, then not to worry! The purpose of this series of articles is to deconstruct a simple Solidity contract, look at its bytecode, and break it apart into identifiable structures down to the lowest level. We’ll pop the hood on Solidity. By the end of the series, you should feel comfortable when looking at or debugging EVM bytecode. The whole point of the series is to demystify the EVM bytecode produced by the Solidity compiler. And it’s really much simpler than it seems.</p><p><em>Note: This series is aimed at developers who already feel comfortable with and have experience in developing Solidity contracts, but want to understand how things work at a slightly deeper/lower level — that is, how Solidity is translated into EVM bytecode by the Solidity compiler, and how the EVM executes such bytecode. If you aren’t there just yet, I recommend reading this great introduction by Facu Spagnuolo: </em><a href="https://blog.zeppelin.solutions/a-gentle-introduction-to-ethereum-programming-part-1-783cc7796094"><em>A Gentle Introduction to Ethereum Programming</em></a><em>.</em></p><p>Here’s the contract we’ll deconstruct:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8218617b4dcb095ee600deb56a823079/href">https://medium.com/media/8218617b4dcb095ee600deb56a823079/href</a></iframe><p><em>Note: This contract is susceptible to an </em><a href="https://consensys.github.io/smart-contract-best-practices/known_attacks/#integer-overflow-and-underflow"><em>overflow attack</em></a><em>, but we’re just keeping it simple here for the purpose at hand.</em></p><h4><strong>Compiling the contract</strong></h4><p>To compile the contract, we’ll be using <a href="https://remix.ethereum.org/">Remix</a>. Go ahead and create a new contract by clicking on the + button on the top left, above the file browser area. Set the filename to BasicToken.sol. Now, paste the above code into the editor section.</p><p>In the right-hand section, go to the <em>Settings</em> tab and <strong>make sure <em>Enable Optimization</em> is selected</strong>. Also, verify that the selected version of the Solidity compiler is “<strong>version:0.4.24+commit.e67f0147.Emscripten.clang</strong>”. These two details are very important, otherwise you’ll be looking at slightly different bytecode from what will be discussed here.</p><p>If you go to the <em>Compile</em> tab and click on the <em>Details</em> button, you should see a popup with all the stuff that the Solidity compiler generates, one of which is a JSON object named <em>BYTECODE </em>that has an “object” property, which is the compiled code of the contract. It looks like this:</p><pre>608060405234801561001057600080fd5b5060405160208061021783398101604090815290516000818155338152600160205291909120556101d1806100466000396000f3006080604052600436106100565763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166318160ddd811461005b57806370a0823114610082578063a9059cbb146100b0575b600080fd5b34801561006757600080fd5b506100706100f5565b60408051918252519081900360200190f35b34801561008e57600080fd5b5061007073ffffffffffffffffffffffffffffffffffffffff600435166100fb565b3480156100bc57600080fd5b506100e173ffffffffffffffffffffffffffffffffffffffff60043516602435610123565b604080519115158252519081900360200190f35b60005490565b73ffffffffffffffffffffffffffffffffffffffff1660009081526001602052604090205490565b600073ffffffffffffffffffffffffffffffffffffffff8316151561014757600080fd5b3360009081526001602052604090205482111561016357600080fd5b503360009081526001602081905260408083208054859003905573ffffffffffffffffffffffffffffffffffffffff85168352909120805483019055929150505600a165627a7a72305820a5d999f4459642872a29be93a490575d345e40fc91a7cccb2cf29c88bcdaf3be0029</pre><p>Yup. That’s completely unreadable (at least for a normal human being).</p><h4>Deploying the contract</h4><p>Next, go to the <em>Run</em> section in Remix. At the top, make sure you’re using the <em>Javascript VM</em>. This is basically an embedded Javascript EVM + network, our ideal Ethereum playground. Make sure BasicToken is selected in the <em>ComboBox</em>, and enter the number 10000 in the <em>Deploy input box</em>. Next, click the <em>Deploy</em> button. This should deploy an instance of our BasicToken contract, with an initial supply of 10000 tokens owned by the account currently selected at the top of the account <em>ComboBox</em>, which will hold the totality of our token supply.</p><p>Lower in the <em>Run</em> tab, in the <em>Deployed Contracts</em> section, you should see the deployed contract, with fields to interact with its three functions: transfer, balanceOf, and totalSupply. Here, we’ll be able to interact with the instance of the contract we just deployed.</p><p>But before that, let’s take a look at exactly what “deploying” the contract means. At the bottom of the page, in the console area, you should see the log “creation of BasicToken pending…”, followed by a transaction entry with various fields: from, to, value, data, logs, and hash. Click on this entry to expand the transaction’s info. Even though abbreviated, you should see that the data/input of the transaction is the same bytecode we presented above. This transaction is sent to the 0x0 address, and as a result, a new contract instance is created, with its own address and code. We’ll examine this process in detail in the next article.</p><h4>Disassembling the bytecode</h4><p>To the right of the transaction’s data, still in the console, click on the <em>Debug</em> button. This will activate the <em>Debugger</em> tab in Remix’s right-hand area. Let’s take a look at the <em>Instructions </em>section. If you scroll down, you should see the following:</p><pre>000 PUSH1 80<br>002 PUSH1 40<br>004 MSTORE<br>005 CALLVALUE<br>006 DUP1<br>007 ISZERO<br>008 PUSH2 0010<br>011 JUMPI<br>012 PUSH1 00<br>014 DUP1<br>015 REVERT<br>016 JUMPDEST<br>017 POP<br>018 PUSH1 40<br>020 MLOAD<br>021 PUSH1 20<br>023 DUP1<br>024 PUSH2 0217<br>027 DUP4<br>028 CODECOPY<br>029 DUP2<br>030 ADD<br>031 PUSH1 40<br>033 SWAP1<br>034 DUP2<br>035 MSTORE<br>036 SWAP1<br>037 MLOAD<br>038 PUSH1 00<br>040 DUP2<br>041 DUP2<br>042 SSTORE<br>043 CALLER<br>044 DUP2<br>045 MSTORE<br>046 PUSH1 01<br>048 PUSH1 20<br>050 MSTORE<br>051 SWAP2<br>… (abbreviated)</pre><p>To make sure that you’re following the same set of opcodes described in this series, please compare what you see in Remix with the <a href="https://gist.github.com/ajsantander/60bd8d6f88725663f89a67a7c51672c7">bytecode in this gist</a>.</p><p>This is the disassembled bytecode of the contract. Disassembly sounds rather intimidating, but it’s quite simple, really. If you scan the raw bytecode by bytes (two characters at a time), the EVM identifies specific opcodes that it associates to particular actions. For example:</p><pre>0x60 =&gt; PUSH<br>0x01 =&gt; ADD<br>0x02 =&gt; MUL<br>0x00 =&gt; STOP<br>...</pre><p>The disassembled code is still very low-level and difficult to read, but as you will see, we can start making sense out of it.</p><h4>Opcodes</h4><p>Before we get started on our ambitious endeavour of completely deconstructing the bytecode, you’re going to need a basic tool set for understanding individual opcodes such as PUSH, ADD, SWAP, DUP, etc. An opcode, in the end, can only push or consume items from the EVM’s stack, memory, or storage belonging to the contract. That’s it.</p><p>To see all the available opcodes that the EVM can process, check out <a href="https://github.com/ethereum/pyethereum/blob/develop/ethereum/opcodes.py">this handy gist from Pyethereum showing a list of the opcodes</a>. To understand what each one does and how it works, <a href="https://github.com/ethereum/solidity/blob/develop/docs/assembly.rst#opcodes">Solidity’s assembly documentation</a> is a great reference. Even though it’s not a one-on-one relationship with the raw opcodes, it’s pretty close (it’s actually Yul, an intermediate language between Solidity and EVM bytecode). Finally, if you can speak scientician, there’s always the <a href="http://gavwood.com/paper.pdf">Ethereum Yellow Paper</a> to fall back on.</p><p>There’s no point in reading these resources from start to finish right now; just keep them around for reference. We’ll be using them as we go along.</p><h4>Instructions</h4><p>Each line in the disassembled code above is an instruction for the EVM to execute. Each instruction contains an opcode. For example, let’s take one of those instructions, instruction 88, which pushes the number 4 to the stack. This particular disassembler interprets instructions as follows:</p><pre>88 PUSH1 0x04<br>|  |     |     <br>|  |     Hex value for push.<br>|  Opcode.<br>Instruction number.</pre><p>Even though the disassembled code brings us one step closer to understanding what’s going on, it’s still quite intimidating. We’re going to need a strategy for deconstructing the whole thing, which has 596 instructions!</p><h4>The Strategy</h4><p>Problems that appear to be overwhelming at first usually succumb to the all-powerful, all-mighty “divide-and-conquer” strategy, and this problem is no exception to the rule. We’ll identify split points in the disassembled code and reduce it bit by bit, until we end up with small, digestible chunks, which we’ll walk through step by step in Remix’s debugger. In the following diagram, we can see the first split we can make on the disassembled code, which we’ll analyze completely in the next article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/0*5tQKNjSfe2ar7ZUq" /></figure><p>You can find the end result of the entire deconstruction in the <a href="https://cdn.rawgit.com/ajsantander/23c032ec7a722890feed94d93dff574a/raw/a453b28077e9669d5b51f2dc6d93b539a76834b8/BasicToken.svg">deconstruction diagram</a>. Don’t worry if you don’t understand the diagram at first. You’re not supposed to. This series will go through it step by step. Keep it around so you can keep track of the big picture as we go along.</p><p>The series is divided into the following set of articles. If you’re up for the challenge, get started with the actual deconstruction in <a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-ii-creation-vs-runtime-6b9d60ecb44c">Part II</a>. See you there!</p><ol><li>Deconstructing a Solidity Contract — Part I: Introduction ✔</li><li><a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-ii-creation-vs-runtime-6b9d60ecb44c">Deconstructing a Solidity Contract — Part II: Creation vs. Runtime</a></li><li><a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-iii-the-function-selector-6a9b6886ea49">Deconstructing a Solidity Contract — Part III: The Function Selector</a></li><li><a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-iv-function-wrappers-d8e46672b0ed">Deconstructing a Solidity Contract — Part IV: Function Wrappers</a></li><li><a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-v-function-bodies-2d19d4bef8be">Deconstructing a Solidity Contract — Part V: Function Bodies</a></li><li><a href="https://blog.zeppelin.solutions/deconstructing-a-solidity-contract-part-vi-the-swarm-hash-70f069e22aef">Deconstructing a Solidity Contract — Part VI: The Metadata Hash</a></li></ol><h3>Be part of the community</h3><ul><li>Continue the discussion on our <a href="https://forum.zeppelin.solutions/?utm_campaign=zep&amp;utm_medium=blog&amp;utm_source=medium">forum</a></li><li>Join our <a href="http://zpl.in/telegram">Telegram group</a></li><li>Follow us on <a href="https://twitter.com/ZeppelinOrg">Twitter</a></li><li>Even better, <a href="https://zeppelin.solutions/jobs/?utm_campaign=zep&amp;utm_medium=blog&amp;utm_source=medium">join the team</a> 🚀</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=832efd2d7737" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>