<?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[Santony’s Blog - Medium]]></title>
        <description><![CDATA[Blockchain engineering - Medium]]></description>
        <link>https://medium.com/santonychoi?source=rss----6b768b0f4b9e---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Santony’s Blog - Medium</title>
            <link>https://medium.com/santonychoi?source=rss----6b768b0f4b9e---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 10:26:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/santonychoi" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Ethereum Transaction Structure — Part 2]]></title>
            <link>https://medium.com/santonychoi/ethereum-transaction-structure-part-2-474fd3bf5e78?source=rss----6b768b0f4b9e---4</link>
            <guid isPermaLink="false">https://medium.com/p/474fd3bf5e78</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[transactions]]></category>
            <dc:creator><![CDATA[Santony Choi]]></dc:creator>
            <pubDate>Sun, 01 Jul 2018 10:09:04 GMT</pubDate>
            <atom:updated>2018-11-20T04:08:14.953Z</atom:updated>
            <content:encoded><![CDATA[<p>Series:<br><em>• </em><a href="https://medium.com/santonychoi/ethereum-transaction-structure-part-1-77a88fc0674e"><em>Ethereum Transaction Structure— Part 1</em></a></p><p>We’ve covered RLP, which is a way of encoding data in Ethereum, in the part one. A value encoded in RLP was left at the end of the last part. Let’s look at it again.</p><pre>0xf87f81c98504a817c80083061a80941234567890123456789012345678901234567890880de0b6b3a764000091d08773616e746f6e7982697384636f6f6c29a0fd3263ef5b7550ec3b9ad789c8ae5930c78f55b2e4ac1984e22bf276cf4ba4e7a0399b9daad024031975346d195043e49e3a3a1ebbec494502978b0aa86a00bae7</pre><p>Starting with the conclusion, the value above is a signed and RLP encoded plain transaction below with a private key, 0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef .</p><pre>nonce: ‘0xc9’,<br>gasPrice: ‘0x4a817c800’,<br>gasLimit: ‘0x61a80’,<br>to: ‘0x1234567890123456789012345678901234567890’,<br>value: ‘0xde0b6b3a7640000’,<br>data: ‘0xd08773616e746f6e7982697384636f6f6c’,<br>chainId: 3</pre><p>We now know about RLP encoding, I will not care about decoding and interpreting the value. I know you can do it by yourself. There are several cool libraries that encode / decode RLP in various languages, but it would be good to do it with your hand at least once.</p><p>Let’s get back to today’s topic and see what information does the transaction contain.</p><h4>nonce</h4><p>What comes first is nonce. It’s a hexadecimal number that indicates “the order of the transaction being sent among transactions triggered by the account”. Ethereum utilizes this field to prevent malicious actions like Double-spend or to place transaction in a order. Since transaction above is the 201st, the next transaction MUST have nonce of 0xca(202). Otherwise, it will be considered as a wrongful transaction by a client and not going to be included in the chain.</p><h4>gasPrice &amp; gasLimit</h4><p>Gas is a way of setting cost and restricting the block size in Ethereum. In <a href="https://hackernoon.com/the-ethereum-blockchain-size-has-exceeded-1tb-and-yes-its-an-issue-2b650b5f4f62">a conversation which was hot in May</a>, Vitalik Buterin also <a href="https://medium.com/@VitalikButerin/because-of-ethereums-exponentially-growing-blocksize-the-bottleneck-is-not-regulated-8c0acd77b3a2">mentioned that Gas restricts the size of block</a>. Let’s look into why it does.</p><p>Every operations in EVM spends Gas. How much Gas each OPCODE spend is represented in Ethereum <a href="https://github.com/ethereum/yellowpaper">Yellowpaper</a>(compared to Whitepaper for the public, it’s more detailed technical specification). While static operations such as ADD, SUB have fixed value, some operations like SSTORE, which stores value in the storage, gets its Gas at runtime. I will cover the Yellowpaper later.</p><p>Then, what is Price and what is Limit? Price is simple. In the Yellowpaer, Gas is not written in the unit of Wei. It’s just a constant number. Price is a coefficient of the unit gas consumption. Even if transactions consume the same Gas amount, you will spend 10 times more Wei when you set Price as 10 than when you set it as 1.</p><p>Limit is estimated maximum consumption of gas amount for a transaction. The value is set by a user. However, it is recommended to calculate the value using client programs such as Geth, Parity or software libraries of each languages.</p><p>What if a transacion exceeds GasLimit or spends less Gas than the limit? The former will fail, spending all the Ether, and the latter will succeeds leaving the Ether unspent.</p><p>In conclusion, the maximum Ether(not Gas) that is consumed by a transaction can be represented as, (gasPrice * gasLimit) Wei. The actual consumption is (gasPrice * gas spent actually) Wei.</p><p>In our case, gasPrice is 20 Gwei and gasLimit is 400,000. So, the maximum possible consumption will be 8,000,000 Gwei, which equals to 0.008 Ether.</p><p><strong>to</strong></p><p>It’s a transaction’s destination. It can be an External Account to send a message, or it can be a Contract Account to call a contract function.</p><p><strong>value</strong></p><p>Transferring Ether value represented in Wei unit. If you want to transfer 1 Ether, put 1x10¹⁸ in decimal representation, i.e., 0xde0b6b3a7640000 in hexadecimal. The transaction above is also transferring 1 Ether.</p><p>I have kept using Wei unit in this article. As similar to Satoshi in Bitcoin, it’s the minimum unit representing currency amount in Ehtereum. As Satoshi divides 1 BTC by 100 milions, Wei divides 1 ETH by 10¹⁸. Mwei, which is 10⁶ Wei, and Gwei, 10⁹ wei, are also commonly used. You can try <a href="https://etherconverter.online/">converting the units on the web</a>.</p><h4>data</h4><p>Users can put arbitrary data in the transaction. Recently, <a href="https://etherscan.io/tx/0x2d6a7b0f6adeff38423d4c62cd8b6ccb708ddad85da5d3d06756ad4d8a04a6a2">a student in Peking Univerity sent a transaction with an article encoded in UTF8 to resist government’s censorship</a>. The field the student used to put the article was it, data. The transaction’s to and from fields were same. Other than these special purposed case, data field doesn’t have specific meanings when you send a transaction to an external account.</p><p>If you send a transaction to a Contract Account, data field does more significant role. The execution of a contract function. You can put a specially formed — ABI encoded — value in the data field for a recipient contract to decode the data into function name and parameters, and to execute pre-programmed function. ABI encoding will be covered later.</p><p>I think that this data field is the thing that separates Ethereum from Bitcoin. There also have been numerous attempts to send messages in Bitcoin. But the core developers in Bitcoin community were negative to this idea, whereas Ethereum developers have actively endorsed creating a protocol supporting it. As a result, Ethereum, blockchain supporting the turing-complete language, protocol has come to the world.</p><p><strong>ChainId</strong></p><p>The last field is related with a hard fork. You may find out the details about this from <a href="https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md">EIP-155</a>. It says the field was devised at <a href="https://blog.ethereum.org/2016/11/18/hard-fork-no-4-spurious-dragon/">Spurious Dragon hard fork</a> to prevent replay attacks.</p><p>Frankly speaking, we don’t have to be an expert of all, if we just want to use it. Just remember that Ethereum mainnet uses 1 and Ropsten testnet uses 3 for this field. For a backward compatibility, Ethereum supports ChainId 0, the legacy, and it works on any chain.</p><p>By the way, we can’t find ChainId in the RawTransaction above. Do you know why?</p><h4>The rest</h4><p>You might see that the description is not sufficient if you decoded it by your hand. Among 129 Bytes total, top 62 Bytes are encoded value we described in this article. But ChainId is not included and the rest 67 Bytes contain 3 more items and it’s not easy to catch what the items refer to.</p><p>They are v, r and s. Those are for guaranteeing that the raw transaction is from it’s owner account by signing the transaction with the owner’s key. You should understand ECDSA algorithm and secp256k1 curve in order to see what’s actually happening here. I recommend you to google those topics because there are plenty of cool stuffs about those.</p><p>ChainId also can be inferred from the value v. In our transaction, the value v is 0x29, i.e. decimal number 41. In the transactions for Ropsten of ChainId 3, the value v is decided either 41 or 42. Therefore, you can catch that we are sending the transaction to ChainId 3.</p><p><strong>Interim Summary</strong></p><p>You have finally became able to read the tricky cryptography-like(also actually cryptographic) value. Of course you don’t need to create it with typing calculator by yourself. Ethereum is already a popular project and all the common languages have library helping this. Even a language that I use recently, that might be unfamiliar to the most of the readers, Elixir has multiple libraries supporting this process.</p><p>In the next article, we will be covering ABI encoding, the final topic of this series.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=474fd3bf5e78" width="1" height="1" alt=""><hr><p><a href="https://medium.com/santonychoi/ethereum-transaction-structure-part-2-474fd3bf5e78">Ethereum Transaction Structure — Part 2</a> was originally published in <a href="https://medium.com/santonychoi">Santony’s Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[이더리움의 트랜잭션 분석 — Part 2]]></title>
            <link>https://medium.com/santonychoi/%EC%9D%B4%EB%8D%94%EB%A6%AC%EC%9B%80%EC%9D%98-%ED%8A%B8%EB%9E%9C%EC%9E%AD%EC%85%98-%EB%B6%84%EC%84%9D-part-2-6c2751d5775?source=rss----6b768b0f4b9e---4</link>
            <guid isPermaLink="false">https://medium.com/p/6c2751d5775</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[transactions]]></category>
            <dc:creator><![CDATA[Santony Choi]]></dc:creator>
            <pubDate>Sat, 26 May 2018 05:48:57 GMT</pubDate>
            <atom:updated>2018-05-26T04:09:53.312Z</atom:updated>
            <content:encoded><![CDATA[<p><em>이전 시리즈:<br>• </em><a href="https://medium.com/santonychoi/%EC%9D%B4%EB%8D%94%EB%A6%AC%EC%9B%80%EC%9D%98-%ED%8A%B8%EB%9E%9C%EC%9E%AD%EC%85%98-%EB%B6%84%EC%84%9D-part-1-c20c39ca7d26"><em>이더리움의 트랜잭션 분석 — Part 1</em></a></p><p>지난 시간에는 이더리움에서 데이터를 인코딩하는 방식인 RLP를 살펴보았다. 말미에 RLP로 인코딩된 값 하나를 던지며 끝이 났는데, 다시 한 번 불러오자.</p><pre>0xf87f81c98504a817c80083061a80941234567890123456789012345678901234567890880de0b6b3a764000091d08773616e746f6e7982697384636f6f6c29a0fd3263ef5b7550ec3b9ad789c8ae5930c78f55b2e4ac1984e22bf276cf4ba4e7a0399b9daad024031975346d195043e49e3a3a1ebbec494502978b0aa86a00bae7</pre><p>결론부터 말하면, 위의 값은 아래의 평문 트랜잭션을 개인키 0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef 으로 사인(Sign)한 후, RLP 인코딩한 결과 값이다.</p><pre>nonce: ‘0xc9’,<br>gasPrice: ‘0x4a817c800’,<br>gasLimit: ‘0x61a80’,<br>to: ‘0x1234567890123456789012345678901234567890’,<br>value: ‘0xde0b6b3a7640000’,<br>data: ‘0xd08773616e746f6e7982697384636f6f6c’,<br>chainId: 3</pre><p>이제 우리는 RLP 인코딩을 알고 있기 때문에 직접 값을 디코딩하고 해석하는 것은 독자 여러분께 맡기겠다. 물론 각 언어별로 RLP를 인코딩 / 디코딩하는 편리한 라이브러리가 존재하지만 학습을 위해 한 번쯤 손으로 디코딩해보는 것도 좋다.</p><p>다시 오늘의 주제로 돌아가 위의 트랜잭션이 어떤 정보를 담고 있는지 순서대로 살펴보자.</p><h4>nonce</h4><p>가장 위에 위치한 nonce는 “이 트랜잭션이 트랜잭션을 생성하는 어카운트 내에서 몇 번째로 발생하는 트랜잭션인지”를 나타내는 16진수 값이다. 이더리움은 이중 지불과 같은 악의적인 공격이나 트랜잭션 순서가 뒤섞이는 것을 방지하기 위해 nonce 값을 활용한다. 201번째인 위 트랜잭션이 성공적으로 수행된 뒤에는 반드시 nonce 값 0xca(202)를 가진 트랜잭션이 발생해야 하며 그 외의 경우에는 client가 잘못된 트랜잭션으로 판단해 네트워크에 반영하지 않는다.</p><h4>gasPrice &amp; gasLimit</h4><p>가스는 이더리움에서 비용을 책정하는 방법이며 블록사이즈를 제한하는 방법이기도 하다. 이번주 미디엄에서 뜨거웠던 <a href="https://hackernoon.com/the-ethereum-blockchain-size-has-exceeded-1tb-and-yes-its-an-issue-2b650b5f4f62">이더리움의 블록체인 사이즈에 관한 논쟁</a>에서 비탈릭 뷰테린은 <a href="https://medium.com/@VitalikButerin/because-of-ethereums-exponentially-growing-blocksize-the-bottleneck-is-not-regulated-8c0acd77b3a2">가스가 블록 사이즈를 제한하는 역할을 한다고 언급</a>했다. 왜 그런지 한 번 보자.</p><p>가스는 EVM에서 실행되는 처리에 할당되는 비용이다. 각 OPCODE가 얼마의 가스를 소모하는지는 이더리움 <a href="https://github.com/ethereum/yellowpaper">옐로 페이퍼</a>(일반 대중을 대상으로 하는 화이트페이퍼와 달리 기술적인 부분을 상세히 기술한 명세서)에 표로 자세히 나와 있다. ADD, SUB과 같이 정적으로 값이 정해지는 OPCODE도 있는 반면 SSTORE(값을 Stroage에 저장하는 OPCODE)처럼 런타임에 동적으로 가스 값을 정하는 OPCODE도 있다. 옐로 페이퍼의 내용에 대해서는 기회가 될 때 보다 상세히 설명하겠다.</p><p>그렇다면 Price는 무엇이고 Limit은 무엇일까? Price는 단순하다. 옐로 페이퍼에서 OPCODE가 소비하는 가스의 양은 이더리움의 화폐 단위인 Wei 단위가 아니라 그저 상수로 정해져있다. Price는 바로 이 상수 단위 소모량에 곱하는 계수로서 동일한 100 가스를 소모하는 트랜잭션이라 하더라도 Price를 10으로 설정하면 1로 설정한 경우에 비해 10배의 Wei가 소모된다.</p><p>Limit은 이 트랜잭션이 최대로 소모할 것으로 예상하는 가스 값이다. 이 값은 트랜잭션을 생성하는 사용자가 임의로 정하도록 되어있는데, 일반적인 경우에는 사용자가 숫자를 입력하기보다 트랜잭션의 내용을 Geth, Parity 등의 클라이언트 혹은 언어별 라이브러리를 활용해 계산하는 것을 권장한다.</p><p>만약 Limit을 넘어가거나 Limit보다 적은 양의 gas만 소모한 경우에는 어떻게 처리될까? 전자의 경우에는 사용자의 Ether는 모두 소모된 채로 트랜잭션이 실패하고, 후자의 경우에는 사용한 만큼의 Ether만 지불하고 트랜잭션이 정상 종료한다.</p><p>지금까지의 설명을 정리해보면, 한 트랜잭션이 최대로 소모하는 Ether의 양(가스의 양이 아니라)은 곧, (gasPrice * gasLimit) Wei 로 계산할 수 있다. 실제로 소모된 값은 (gasPrice * 실제 소모된 gas의 양) Wei로 계산된다.</p><p>우리의 예시에서 gasPrice는 20 GWei, gasLimit 400,000 이므로 최대 소모 가능한 값은 8,000,000 Gwei, 즉, 0.008 Ether 가 된다.</p><h4>to</h4><p>트랜잭션의 목적지이다. Ether나 메시지를 전송하기 위해 외부 계정(External Account)이 목적지가 될 수도 있고 컨트랙트의 함수를 호출하기 위해 컨트랙트 계정(Contract Account)의 주소를 목적지로 둘 수도 있다.</p><h4>value</h4><p>16진수로 표현한 Wei 단위의 Ether 전송량이다. 1 Ether를 전송하기 위해서는 10진수로 1x10¹⁸, 즉, 0xde0b6b3a7640000 를 담으면 된다. 예시에서도 1 Ether를 전송하고 있다.</p><p>앞서 Wei라는 단위를 쓰고 있는데, 이는 비트코인의 Satoshi와 마찬가지로 ETH를 쪼갤 수 있는 최소 단위이다. Satoshi가 BTC를 1억분의 1로 나눈 것처럼, Wei는 ETH를 10¹⁸분의 1로 나눈 값이다. Wei의 10⁶배인 Mwei, 10⁹배인 Gwei 등이 흔히 쓰이는 변환 단위이다. <a href="https://etherconverter.online/">단위를 즉시 변환해볼 수 있는 사이트</a>도 많이 있으니 직접 테스트해보길 바란다.</p><h4>data</h4><p>이더리움은 트랜잭션에 사용자가 임의의 값을 담아 보낼 수 있다. 최근 <a href="https://etherscan.io/tx/0x2d6a7b0f6adeff38423d4c62cd8b6ccb708ddad85da5d3d06756ad4d8a04a6a2">중국 북경대의 한 학생이 정부의 검열에 저항하기 위해 트랜잭션에 UTF8로 인코딩된 글</a>을 올렸는데, 이 때 글을 담은 필드가 바로 data이다. 해당 트랜잭션은 송신자와 수신자가 같다. 즉, 수신자가 외부 계정이란 뜻인데, 위의 경우처럼 특수한 목적을 가진 경우 외에는 외부 계정으로 트랜잭션을 발송하는 경우에 data 필드 값이 특별한 역할을 가지지는 않는다.</p><p>컨트랙트 계정으로 트랜잭션을 보내는 경우에는 보다 중요한 역할을 수행할 수 있다. 바로 컨트랙트 함수의 실행이다. data 필드에 ABI라는 방식으로 인코딩된 값을 담아 보내면 수신하는 측의 컨트랙트가 이를 함수명과 인자로 디코딩하여 미리 프로그램된 기능을 실행한다. ABI 인코딩에 대해서는 다음 포스팅에서 설명하겠다.</p><p>필자는 이 data 필드가 바로 비트코인과 이더리움을 결정적으로 분리하는 요인이라 본다. 비트코인에도 트랜잭션에 메시지를 담아 보내려는 시도들이 있었고, 라이트닝 프로토콜 등이 여기서 발전했으나 비트코인 코어 개발자들은 이 기능을 핵심이라 생각하지 않았고 코어가 아닌 하위 레이어 등을 응용해서 처리하는 방향으로 발전했다. 반면, 이더리움 개발자들은 적극적으로 이 기능을 지원하는 프로토콜을 만들고 싶어했다. 그 결과 이더리움이라는, 튜링 완전한 컴퓨팅 언어를 지원하는 프로토콜이 등장하게 된 것이다.</p><h4>ChainId</h4><p>마지막 필드는 하드포크와 관련된 필드이다. <a href="https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md">EIP-155</a> 에서 여기에 관련된 상세한 배경을 알 수 있는데, <a href="https://blog.ethereum.org/2016/11/18/hard-fork-no-4-spurious-dragon/">Spurious Dragon 하드포크</a> 과정에서 리플레이 공격을 막기 위한 수단으로 이 필드를 도입했다고 설명하고 있다.</p><p>사실 이더리움 메인 체인을 사용하는 우리 입장에서는 그저 사용만 할 수 있으면 된다. 이더리움 메인넷은 이 필드의 값으로 1을, 테스트넷인 Ropsten은 3을 사용하고 있다는 것정도만 알아두자. 그 외에 Backward compatibility를 위해 legacy 방식인 ChainId 0 도 지원하고 있으며 이 값은 체인의 종류와 관계없이 수행된다.</p><p>그런데 이 ChainId 값은 위의 RawTransaction에서 찾을 수가 없다. 어찌된 일일까?</p><h4>나머지 값</h4><p>위의 RawTransaction을 직접 디코딩해본 독자라면 여기까지의 설명이 부족하다는 것을 알 수 있을 것이다. 총 129 바이트의 값 중, 상위 62 바이트는 위에서 설명한 필드들의 값을 차례로 인코딩한 값으로 우리가 손으로 풀어볼 수 있었다. 하지만 ChainId의 값은 여기 포함되어 있지 않고 나머지 67바이트는 총 세 개의 아이템을 담고 있는데 값을 쉽게 유추할 수 없다.</p><p>이 값들은 각각 v, r, s라는 필드로 표현되는 값으로 트랜잭션을 개인키로 사인(Sign)하여 이 값이 주소의 소유자로부터 생성된 내용이라는 것을 보증해주는 역할을 한다. 여기에 대해서는 이더리움이 사용하고 있는 ECDSA 알고리즘과 secp256k1 커브에 대해 알아야 정확히 이해할 수 있다. 구글에 관련된 설명이 충분히 있으니 보다 심화된 이해를 원하는 독자라면 해당 키워드로 구글링하길 추천한다.</p><p>우리가 찾지 못했던 ChainId의 값도 v 값에서 유추할 수 있다. 우리의 트랜잭션에서 v 값은 0x29, 즉 10진수 41이다. ChainId가 3인 Ropsten용 트랜잭션에서 v 값은 41과 42중 하나로 결정된다. 따라서 41을 역산하면 우리가 ChainId 3으로 트랜잭션을 보낸다는 것을 알 수 있다.</p><h4>중간 결산</h4><p>우리는 이제 16진수로 표현된 암호같은(실제로도 암호를 포함한) 값을 읽을 수 있게 되었다. 물론 우리가 계산기를 써가며 이 트랜잭션을 만들 일은 없을 것이다. 이미 이더리움은 유명한 프로젝트가 되었고 흔히 사용되는 대부분의 언어에서 이런 일을 대신해주는 라이브러리가 있기 때문이다. 필자가 요즘 사용하고 있는, 아마도 많은 독자들에게 생소할 언어인, Elixir에도 이런 역할을 하는 라이브러리가 복수개 존재할 정도이니 말이다.</p><p>다음 포스팅은 이 시리즈의 마지막 주제인 ABI 디코딩에 대해 다뤄보겠다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c2751d5775" width="1" height="1" alt=""><hr><p><a href="https://medium.com/santonychoi/%EC%9D%B4%EB%8D%94%EB%A6%AC%EC%9B%80%EC%9D%98-%ED%8A%B8%EB%9E%9C%EC%9E%AD%EC%85%98-%EB%B6%84%EC%84%9D-part-2-6c2751d5775">이더리움의 트랜잭션 분석 — Part 2</a> was originally published in <a href="https://medium.com/santonychoi">Santony’s Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ethereum Transaction Structure — Part 1]]></title>
            <link>https://medium.com/santonychoi/ethereum-transaction-structure-part-1-77a88fc0674e?source=rss----6b768b0f4b9e---4</link>
            <guid isPermaLink="false">https://medium.com/p/77a88fc0674e</guid>
            <category><![CDATA[rlp]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[transactions]]></category>
            <dc:creator><![CDATA[Santony Choi]]></dc:creator>
            <pubDate>Tue, 22 May 2018 16:10:11 GMT</pubDate>
            <atom:updated>2018-05-22T16:10:11.132Z</atom:updated>
            <content:encoded><![CDATA[<p>Most of Ethereum users connect to Ethereum network using wallet programs, such as MEW(My Ether Wallet) and Metamask, or a special browser like Mist. For more advanced purpose, there are clients programs, such as Geth and Parity. These client programs include most of functionalities the wallets have and provide higher level of controllability with CLI and JSON RPC interface. Mining Ethereum also has done with it.</p><p>However, tools above need to import private keys. Although they protect keys in appropriate way, it somehow has a potential risk of key exposure. So, in some extremely sensitive cases, you are supposed to make signed binary transactions by yourself in an offline environment without any help of those convenient and smart tools.</p><p>This series is made for this special case. We are going to analyze the Ethereum transaction and follow the process of creating a RawTransaction.</p><h4>RLP Encoding</h4><p>The first topic we cover is RLP, the way Ethereum serializes data. RLP, standing for Recursive Length Prefix, is a rule that expresses data and its prefix in a recursive way. Let’s start with an example.</p><pre>0x8773616e746f6e79</pre><p>That is an encoded value of a string santony. You can easily discover an ascii string santony starting from the second byte 0x73. Then what is 0x87 at the first position?</p><h4>String Encoding Rules of RLP</h4><p>1. A single byte value between [0x00, 0x7f] is written just as it is.</p><p>2. If the length of a string is between 0 byte and 55 bytes, write 0x80 + length of the string at the head and then write the content of the string. The value of the first byte is thus in the range of [0x80, 0xb7].</p><p>3. If the length of a string is longer than 55 bytes, write 0xb7 + the bytes of the length prefix first, and then the length of the string , and the content of the string at the end. For example, a 1024 bytes-long string will be encoded as 0xb90400 + the content of the string. The value of the first byte is thus in the range of [0xb8, 0xbf].</p><p>The rules are simper than you might have worried. With looking at the first prefix byte, we can easily figure out if the following byte is a beginning of an item(Rule 1) or the content of a string(Rule 2) or the length of a string(Rule 3). Even if several strings are linked consecutively, we can simply encode / decode those recursively, as the byte comes after decoding a string represents a prefix for the next item.</p><p>Let’s look at a new example.</p><pre>0xd08773616e746f6e7982697384636f6f6c</pre><p>Can you guess what 0xd0 at the head mean?</p><p>List Encoding Rules of RLP</p><p>1. If the sum of all elements in a list is in the range from 0 byte to 55 bytes, write 0xc0 + the length of all elements and then write the elements of the list. The value of the first byte is thus in the range of [0xc0, 0xf7].</p><p>2. If the sum of all elements in a list is over 55 bytes, it’s similar to Rule 3 of String Encoding. Write 0xf7 +the bytes of length prefix first, and then the length of the list, and the content of the list at the end. The means, the value of the first byte is in the range of [0xf8, 0xff].</p><p>RLP has only two type of items, String and List and there are rules only for these two. That is, we’ve learned all the rules of RLP! I will reorganize the example in a prettier way.</p><pre>0x d0 87 73616e746f6e79 82 6973 84 636f6f6c</pre><p>You can figure out it is a list of 16 bytes of elements by its 0xd0 prefix. Note that the prefix doesn’t tell the number of items and we can get it after decoding. Besides, prefix bytes of the items under a list are also included when counting the length. It might look unfriendly or intricate, but under the Ethereum’s structural restriction of saving bytes, it looks like a brilliant choice.</p><p>So, back to the example, you can find out the 7 bytes subsequent to the second byte 0x87 would be ascii string. Following delimiters 0x82, 0x84 also shows that the bytes subsequent would be 2 bytes and 4 bytes strings. In summary, the example can be decoded as 1 byte of list prefix + 1 byte of string prefix + 7 bytes of ascii + 1 byte of string prefix + 2 bytes of ascii + 1 byte of string prefix + 4 bytes of ascii, and the decoded value is below.</p><pre>[“santony”,”is”,”cool”]</pre><p>RLP, which we covered in this article, is very important to understand Ethereum because it is the finalized form of a Ethereum transaction we may create afterward.</p><pre>0xf86f128609184e72a00082271094566f1850d6aad76b3d219c7782d90ba25b5846ac8a31373438373645383030802aa08c53bce1bae2949275685e9a7dcea2b0e0c35bcbfc46f6c8abf48829f46c736ca0434124904285519e387b925a20431cf26dfc37441ec001968130c96987ed7911</pre><p>See you again with the next article trying decoding a real RPL encoded transaction like above.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77a88fc0674e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/santonychoi/ethereum-transaction-structure-part-1-77a88fc0674e">Ethereum Transaction Structure — Part 1</a> was originally published in <a href="https://medium.com/santonychoi">Santony’s Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[이더리움의 트랜잭션 분석 — Part 1]]></title>
            <link>https://medium.com/santonychoi/%EC%9D%B4%EB%8D%94%EB%A6%AC%EC%9B%80%EC%9D%98-%ED%8A%B8%EB%9E%9C%EC%9E%AD%EC%85%98-%EB%B6%84%EC%84%9D-part-1-c20c39ca7d26?source=rss----6b768b0f4b9e---4</link>
            <guid isPermaLink="false">https://medium.com/p/c20c39ca7d26</guid>
            <category><![CDATA[rlp]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[transactions]]></category>
            <dc:creator><![CDATA[Santony Choi]]></dc:creator>
            <pubDate>Tue, 22 May 2018 05:04:21 GMT</pubDate>
            <atom:updated>2018-05-26T01:13:12.047Z</atom:updated>
            <content:encoded><![CDATA[<p>이더리움을 사용하는 대다수의 사용자는 MEW(My Ether Wallet)이나 Metamask와 같은 지갑 프로그램, 혹은 Mist와 같은 전용 브라우저를 활용해 이더리움 네트워크와 통신한다. 이보다 높은 수준의 컨트롤이 필요한 경우에는 Geth와 Parity라는 클라이언트를 활용한다. 이 클라이언트들은 위에 언급된 지갑 / 브라우저의 많은 기능을 포함하고 있으며 커맨드라인 툴, JSON RPC 인터페이스 등을 제공해 높은 수준의 컨트롤을 가능하게 한다. 이더리움의 채굴 역시 이 클라이언트들을 통해 가능하다.</p><p>하지만 위에 나열된 도구들은 사용자의 개인키를 프로그램에 불러들이는 과정이 필요하다. 나름의 방식으로 키를 보호하고 있지만, 그리고 그 방식이 충분히 납득할 만큼 안전하긴 하지만, 키가 노출될 가능성이 있다는 것은 부인할 수 없다. 따라서 보안이 극도로 강조되는 특수한 케이스에서는 이런 도구들이 제공하는 편리한 기능을 쓰는 대신, 오프라인에서 개인키를 활용해 직접 바이너리 형태의 트랜잭션을 만들어야 할 필요가 있다.</p><p>본 시리즈에서는 이처럼 특수한 케이스에서 활용할 수 있도록 이더리움 트랜잭션을 분석하고 이를 RawTransaction의 형태로 만드는 과정을 따라가보겠다.</p><h4>RLP 인코딩</h4><p>가장 첫 번째로 다룰 내용은 이더리움이 데이터를 serialize하는 방식인 RLP 인코딩이다. RLP는 Recursive Length Prefix의 약자로, 길이와 타입을 나타내는 prefix와 데이터를 재귀적인 형태로 나타내는 규칙을 말한다. 예시를 보며 시작하자.</p><pre>0x8773616e746f6e79</pre><p>santony라는 문자열을 RLP 인코딩한 결과다. 앞의 0x87을 제외하고 남은 7바이트의 16진수 값을 ascii로 변환하면 santony가 된다는 것을 쉽게 알 수 있다. 그렇다면 0x87은 무엇일까?</p><h4>RLP의 문자열 인코딩 규칙</h4><p>1. 값이 [0x00, 0x7f]에 속하는 1바이트 값은 그대로 적는다.</p><p>2. 문자열이 0바이트에서 55바이트 길이라면 문자열 앞에 0x80 + 문자열의 길이를 적고 문자열의 값을 뒤에 이어 적는다. 따라서 첫 바이트의 값은 [0x80, 0xb7] 에 속한다.</p><p>3. 문자열이 55바이트보다 길다면 첫 바이트는 0xb7 + 문자열의 길이를 나타낼 바이트의 자릿수를 적고 이어서 문자열의 길이를 적은 후 문자열의 값을 뒤에 이어 적는다. 예를 들어 1024바이트 길이의 문자열은, 0xb90400 + 문자열의 형태로 표현된다. 첫 바이트의 값은 [0xb8, 0xbf]에 속한다.</p><p>규칙은 생각보다 간단하다. 우리는 인코딩된 값의 첫 바이트를 통해 뒤에 붙은 값이 새로운 아이템(Item, RLP에서 항목을 구분하는 단위)의 시작인지(규칙 1), 문자열 본문 값인지(규칙2), 문자열의 길이를 나타내는 값인지(규칙3) 구분할 수 있다. 여러 문자열이 이어져있어도 한 단위의 문자열을 길이에 맞춰 디코딩한 뒤에 나오는 바이트가 새로운 아이템을 나타내는 prefix라는 것을 쉽게 알 수 있으므로 재귀적으로(Recursively) 인코딩/디코딩 할 수 있는 것이다.</p><p>새로운 예시를 보자.</p><pre>0xd08773616e746f6e7982697384636f6f6c</pre><p>첫 자리에 위치한 0xd0은 무엇을 나타내는 prefix일까?</p><h4>RLP의 리스트 인코딩</h4><ol><li>리스트에 담긴 요소의 길이를 모두 합친 것이 0바이트에서 55바이트 길이라면 리스트의 머리에 0xc0 + 모든 요소의 길이를 더한 값을 적고 각 요소의 값을 이어서 적는다. 첫 바이트의 값은 [0xc0, 0xf7]에 속한다.</li></ol><p>2. 요소 길이의 합이 55바이트보다 크다면 문자열에서와 유사하게 첫 바이트는 0xf7 + 요소 길이의 합을 나타낼 바이트의 자릿수를 적고 이어서 요소 길이의 합을 적은 후 요소의 값을 이어서 적는다. 첫 바이트의 값은 곧, [0xf8, 0xff]에 속하게 된다.</p><p>RLP에는 문자열과 리스트라는 두 종류의 아이템만 존재하고 규칙 역시 문자열 인코딩과 리스트 인코딩 두 가지 뿐이다. 즉, 우린 규칙을 모두 알게 된 것이다. 규칙에 맞추어 예시로 든 값을 보기 좋게 구분해서 써보겠다.</p><pre>0x d0 87 73616e746f6e79 82 6973 84 636f6f6c</pre><p>우리는 0xd0을 통해 이 값이 16바이트를 담고 있는 리스트라는 사실을 알 수 있다. 주의할 점은 리스트의 요소가 총 몇 개인지는 나타내지 않으며, 이를 알기 위해서는 직접 디코딩을 해보아야 한다는 사실이다. 또한 리스트의 요소 아이템들을 표현하는 prefix도 전체 길이에 포함된다는 점 역시 짚고 가자. 어찌보면 불친절하고 난해할 수 있으나 저장되는 데이터를 1바이트라도 줄여야하는 이더리움의 구조적 제약을 고려한다면 영리한 선택이라고 보인다.</p><p>다시 예시로 돌아가서, 두 번째 바이트인 0x87을 통해 이어질 7바이트가 ascii코드라는 것을 예측할 수 있다. 뒤의 구분자인 0x82, 0x84 역시 뒤에 이어질 값이 각각 2바이트, 4바이트의 문자열이라는 것을 보여준다. 결국 1바이트 리스트 prefix + 1바이트 문자열 prefix + 7바이트 ascii + 1바이트 문자열 prefix + 2바이트 ascii + 1바이트 문자열 prefix + 4바이트 ascii로 디코딩을 할 수 있고, 그 값은</p><pre>[“santony”,”is”,”cool”]</pre><p>이 된다.</p><p>RLP는 복잡한 과정을 통해 생성될 이더리움의 트랜잭션이 최종적으로 네트워크로 전송되는 형태이므로 이더리움을 이해하는 데에 매우 중요하다.</p><p>다음 순서에서는 RLP로 인코딩된</p><pre>0xf87f81c98504a817c80083061a80941234567890123456789012345678901234567890880de0b6b3a764000091d08773616e746f6e7982697384636f6f6c29a0fd3263ef5b7550ec3b9ad789c8ae5930c78f55b2e4ac1984e22bf276cf4ba4e7a0399b9daad024031975346d195043e49e3a3a1ebbec494502978b0aa86a00bae7</pre><p>값이 무엇을 뜻하는지 하나씩 분해해보겠다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c20c39ca7d26" width="1" height="1" alt=""><hr><p><a href="https://medium.com/santonychoi/%EC%9D%B4%EB%8D%94%EB%A6%AC%EC%9B%80%EC%9D%98-%ED%8A%B8%EB%9E%9C%EC%9E%AD%EC%85%98-%EB%B6%84%EC%84%9D-part-1-c20c39ca7d26">이더리움의 트랜잭션 분석 — Part 1</a> was originally published in <a href="https://medium.com/santonychoi">Santony’s Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>