ETH源码阅读(交易Gas计算)

2018-09-29  本文已影响0人  坠叶飘香

1.交易携带的data所需要gas

// IntrinsicGas computes the 'intrinsic gas' for a message with the given data.
func IntrinsicGas(data []byte, contractCreation, homestead bool) (uint64, error) {
    // Set the starting gas for the raw transaction
    var gas uint64
    if contractCreation && homestead {
        gas = params.TxGasContractCreation  //53000
    } else {
        gas = params.TxGas  //21000
    }
    // Bump the required gas by the amount of transactional data
    if len(data) > 0 { //交易携带的data的长度
        // Zero and non-zero bytes are priced differently
        var nz uint64
        for _, byt := range data {
            if byt != 0 { //统计byte有多少个不为0的byte
                nz++
            }
        }
        fmt.Println("test state_transition.got IntrinsicGas math.MaxUint64 = ", math.MaxUint64)

        // Make sure we don't exceed uint64 for all data combinations
        if (math.MaxUint64-gas)/params.TxDataNonZeroGas < nz { //不会因为nz太大导致导致最终gas超过 math.MaxUint64
            return 0, vm.ErrOutOfGas
        }
        gas += nz * params.TxDataNonZeroGas //每个非0byte的gas为68

        z := uint64(len(data)) - nz  //byte为0的个数
        if (math.MaxUint64-gas)/params.TxDataZeroGas < z {  //每个0 byte的gas为4
            return 0, vm.ErrOutOfGas
        }
        gas += z * params.TxDataZeroGas
    }
    return gas, nil
}
上一篇 下一篇

猜你喜欢

热点阅读