以太坊预编译合约

  • Ashton
  • 更新于 2019-10-14 19:03
  • 阅读 7436

以太坊预编译合约

由于 EVM 是一个基于堆栈的虚拟机,它根据交易所要执行的操作指令内容来计算 gas 消耗,如果计算非常复杂,在 EVM 中执行相关操作指令就会非常低效,而且会消耗大量的 gas。 例如,在 zk-snark 中,需要对椭圆曲线进行加减运算和配对运算。 在 EVM 中执行这些操作是非常复杂和不现实的。所幸以太坊还支持预编译合约。

预编译合约是 EVM 中用于提供更复杂库函数(通常用于加密、散列等复杂操作)的一种折衷方法,这些函数不适合编写操作码。 它们适用于简单但经常调用的合约,或逻辑上固定但计算量很大的合约。 预编译合约是在使用节点客户端代码实现的,因为它们不需要 EVM,所以运行速度很快。 与使用直接在 EVM 中运行的函数相比,它对开发人员来说成本也更低。

在以太坊中已经实现了不少预编译合约了,比如下面这些:

预编译合约

在代码层面,所谓的地址实际上是合约数组的索引,每一个索引唯一对应一个预编一个合约。

在 EVM.go 文件中,调用智能合约有4个函数: Call ()、 CallCode ()、 DelegateCall ()、 StaticCall ()。 这四个函数所做的工作是生成合约对象,但是诸如参数之类的具体细节会有一些差异。 在合约实例化之后,将调用 evm.go 中的 run 函数来运行智能合约。 该函数考虑了预编译合同和非预编译合同调用的情况。 在下面的代码中,第一个分支是通过指定预编译索引来实例化参数 p,以指定预编译合约。 这里数组的索引实际上对应于声明预编译的合同数组时地址的概念。 然后调用 RunPrecompiledContract 函数来执行预编译合约。 如果它是一个未预编译的合约,则 EVM 的解释器会被调用。

// run runs the given contract and takes care of running precompiles with a fallback to the byte code interpreter.
func run(evm *EVM, contract *Contract, input []byte, readOnly bool) ([]byte, error) {
   if contract.CodeAddr != nil {
      precompiles := PrecompiledContractsHomestead
      if evm.ChainConfig().IsByzantium(evm.BlockNumber) {
         precompiles = PrecompiledContractsByzantium
      }
      if p := precompiles[*contract.CodeAddr]; p != nil {
         return RunPrecompiledContract(p, input, contract)
      }
   }
   for _, interpreter := range evm.interpreters {
      if interpreter.CanRun(contract.Code) {
         if evm.interpreter != interpreter {
            // Ensure that the interpreter pointer is set back
            // to its current value upon return.
            defer func(i Interpreter) {
               evm.interpreter = i
            }(evm.interpreter)
            evm.interpreter = interpreter
         }
         return interpreter.Run(contract, input, readOnly)
      }
   }
   return nil, ErrNoCompatibleInterpreter
}

在 RunPrecompiledContract 函数中,可以看到 p 变量实现了 bn256曲线加法操作,然后返回结果。 可以清楚地看到,这部分操作是在客户端执行期间计算出来的。

// RunPrecompiledContract runs and evaluates the output of a precompiled contract.
func RunPrecompiledContract(p PrecompiledContract, input []byte, contract *Contract) (ret []byte, err error) {
   gas := p.RequiredGas(input)
   if contract.UseGas(gas) {
      return p.Run(input)
   }
   return nil, ErrOutOfGas
}
// bn256Add implements a native elliptic curve point addition.
type bn256Add struct{}
// RequiredGas returns the gas required to execute the pre-compiled contract.
func (c *bn256Add) RequiredGas(input []byte) uint64 {
   return params.Bn256AddGas
}
func (c *bn256Add) Run(input []byte) ([]byte, error) {
   x, err := newCurvePoint(getData(input, 0, 64))
   if err != nil {
      return nil, err
   }
   y, err := newCurvePoint(getData(input, 64, 64))
   if err != nil {
      return nil, err
   }
   res := new(bn256.G1)
   res.Add(x, y)
   return res.Marshal(), nil

在智能合约代码中,可以像普通合约一样在合约文件中直接调用预编译合约,但调用方式有所不同。 我们可以在汇编代码块中对预编译合约进行调用。

assembly {
    if iszero(call(gasLimit, contractAddress, value, input, inputLength, output, outputLength)) {
        revert(0, 0)
    }
}
点赞 1
收藏 0
分享

0 条评论

请先 登录 后评论
Ashton
Ashton
专注于 EVM 和比特币生态的区块链开发者