定义和检测智能合约中低效率的Gas模式
Characterizing and Detecting Gas-Inefficient Patterns in Smart Contracts
-
摘要: 1、研究背景
区块链是一种新的中间件,智能合约是在区块链上运行的程序。由于智能合约具有去中心化和不可篡改的特性,各种数字资产可以被灵活地嵌入到智能合约来实现安全和高效的信息交换和价值转移,为供应链、智能家居、电子商务、资产管理等不同行业和领域提供了巨大的机遇。以太坊(第一个支持智能合约的区块链平台)为了避免用户过度消耗资源和确保合约终止,引入了Gas机制,规定合约每执行一个操作码都要消耗一定的Gas,Gas需要使用以太币购买。换句话说,合约执行越多操作码,合约消耗的金钱越多。然而,由于合约开发者对合约运行机制了解不够或者没有意识到一些编码模式会来带不必要的gas消耗,智能合约存在很多优化空间。然而,现有的Gas优化方法集中在字节码层级的窥孔优化,对于每一个基本块的字节码序列,寻找Gas消耗更少语义相同的字节码序列替代它,较少考虑合约开发者引入的低效率Gas模式。
2、目的
本文的研究目标是发现常见的低效率Gas模式,并提出一种自动去除合约中低效率Gas模式的方法,帮助智能合约使用者节约成本,同时提供给Solidity编译器开发者提供优化方案。
3、方法
在本文中,我们总结了6个常见的低效率Gas模式和提出了一个低效率Gas模式的检测和优化方法。具体地,首先从Ethereum Stack Exchange论坛的超过25,000的帖子中人工总结低效率Gas模式。然后,利用抽象语法树检测智能合约中的低效率Gas模式。最后,为这些低效率Gas模式设计了源代码到源代码的优化方法。
4、结果
将上述方法应用到以太坊上160,000个开源的真实智能合约,发现52.75%的合约至少具有一种低效率Gas模式。如果移除合约中所有低效率Gas模式,每个合约至少可以节省0.3美元。
5、结论
智能合约中存在大量低效率Gas模式,这些模式会引发大量的不必要Gas消耗,从而增加使用合约的手续费和合约执行时间。在将来的工作中,我们将从Solidity项目的提交信息中挖掘更多的低效率Gas模式,减少合约开发人员引入的不必要Gas消耗。Abstract: Ethereum blockchain is a new internetware with tens of millions of smart contracts running on it. Different from general programs, smart contracts are decentralized, tamper-resistant and permanently running. Moreover, to avoid resource abuse, Ethereum charges users for deploying and invoking smart contracts according to the size of contract and the operations executed by contracts. It is necessary to optimize smart contracts to save money. However, since developers are not familiar with the operating environment of smart contracts (i.e., Ethereum virtual machine) or do not pay attention to resource consumption during development, there are many optimization opportunities for smart contracts. To fill this gap, this paper defines six gas-inefficient patterns from more than 25,000 posts and proposes an optimization approach at the source code level to let users know clearly where the contract is optimized. To evaluate the prevalence and economic benefits of gas-inefficient patterns, this paper conducts an empirical study on more than 160,000 real smart contracts. The promising experimental results demonstrate that 52.75% of contracts contain at least one gas-inefficient pattern proposed in this paper. If these patterns are removed from the contract, at least 0.30 can be saved per contract.