区块链教程以太坊源码分析core-state-process源码分析

StateTransition

状态转换模型

/*
The State Transitioning Model
状态转换模型
A state transition is a change made when a transaction is applied to the current world state
状态转换 是指用当前的world state来执行交易,并改变当前的world state
The state transitioning model does all all the necessary work to work out a valid new state root.
状态转换做了所有所需的工作来产生一个新的有效的state root
1) Nonce handling Nonce 处理
2) Pre pay gas 预先支付Gas
3) Create a new state object if the recipient is \0*32 如果接收人是空,那么创建一个新的state object
4) Value transfer 转账
== If contract creation ==
 4a) Attempt to run transaction data 尝试运行输入的数据
 4b) If valid, use result as code for the new state object 如果有效,那么用运行的结果作为新的state object的code
== end ==
5) Run Script section 运行脚本部分
6) Derive new state root 导出新的state root
*/
type StateTransition struct {
    gp *GasPool //用来追踪区块内部的Gas的使用情况
    msg Message      // Message Call
    gas uint64
    gasPrice *big.Int     // gas的价格
    initialGas *big.Int     // 最开始的gas
    value *big.Int     // 转账的值
    data []byte       // 输入数据
    state vm.StateDB   // StateDB
    evm *vm.EVM      // 虚拟机
}

// Message represents a message sent to a contract.
type Message interface {
    From() common.Address
    //FromFrontier() (common.Address, error)
    To() *common.Address    //

    GasPrice() *big.Int // Message 的 GasPrice
    Gas() *big.Int      //message 的 GasLimit
    Value() *big.Int

    Nonce() uint64
    CheckNonce() bool
    Data() []byte
}

构造

// NewStateTransition initialises and returns a new state transition object.
func NewStateTransition(evm *vm.EVM, msg Message, gp *GasPool) *StateTransition {
    return &StateTransition{
        gp: gp,
        evm: evm,
        msg: msg,
        gasPrice: msg.GasPrice(),
        initialGas: new(big.Int),
        value: msg.Value(),
        data: msg.Data(),
        state: evm.StateDB,
    }
}

执行Message

// ApplyMessage computes the new state by applying the given message
// against the old state within the environment.
// ApplyMessage 通过应用给定的Message 和状态来生成新的状态
// ApplyMessage returns the bytes returned by any EVM execution (if it took place),
// the gas used (which includes gas refunds) and an error if it failed. An error always
// indicates a core error meaning that the message would always fail for that particular
// state and would never be accepted within a block.
// ApplyMessage返回由任何EVM执行(如果发生)返回的字节,
// 使用的Gas(包括Gas退款),如果失败则返回错误。 一个错误总是表示一个核心错误,
// 意味着这个消息对于这个特定的状态将总是失败,并且永远不会在一个块中被接受。
func ApplyMessage(evm *vm.EVM, msg Message, gp *GasPool) ([]byte, *big.Int, bool, error) {
    st := NewStateTransition(evm, msg, gp)

    ret, _, gasUsed, failed, err := st.TransitionDb()
    return ret, gasUsed, failed, err
}

TransitionDb

// TransitionDb will transition the state by applying the current message and returning the result
// including the required gas for the operation as well as the used gas. It returns an error if it
// failed. An error indicates a consensus issue.
// TransitionDb
func (st *StateTransition) TransitionDb() (ret []byte, requiredGas, usedGas *big.Int, failed bool, err error) {
    if err = st.preCheck(); err != nil {
        return
    }
    msg := st.msg
    sender := st.from() // err checked in preCheck

    homestead := st.evm.ChainConfig().IsHomestead(st.evm.BlockNumber)
    contractCreation := msg.To() == nil // 如果msg.To是nil 那么认为是一个合约创建

    // Pay intrinsic gas
    // TODO convert to uint64
    // 计算最开始的Gas g0
    intrinsicGas := IntrinsicGas(st.data, contractCreation, homestead)
    if intrinsicGas.BitLen() > 64 {
        return nil, nil, nil, false, vm.ErrOutOfGas
    }
    if err = st.useGas(intrinsicGas.Uint64()); err != nil {
        return nil, nil, nil, false, err
    }

    var (
        evm = st.evm
        // vm errors do not effect consensus and are therefor
        // not assigned to err, except for insufficient balance
        // error.
        vmerr error
    )
    if contractCreation { //如果是合约创建, 那么调用evm的Create方法
        ret, _, st.gas, vmerr = evm.Create(sender, st.data, st.gas, st.value)
    } else {
        // Increment the nonce for the next transaction
        // 如果是方法调用。那么首先设置sender的nonce。
        st.state.SetNonce(sender.Address(), st.state.GetNonce(sender.Address())+1)
        ret, st.gas, vmerr = evm.Call(sender, st.to().Address(), st.data, st.gas, st.value)
    }
    if vmerr != nil {
        log.Debug("VM returned with error", "err", vmerr)
        // The only possible consensus-error would be if there wasn‘t
        // sufficient balance to make the transfer happen. The first
        // balance transfer may never fail.
        if vmerr == vm.ErrInsufficientBalance {
            return nil, nil, nil, false, vmerr
        }
    }
    requiredGas = new(big.Int).Set(st.gasUsed()) // 计算被使用的Gas数量

    st.refundGas() //计算Gas的退费 会增加到 st.gas上面。 所以矿工拿到的是退税后的
    st.state.AddBalance(st.evm.Coinbase, new(big.Int).Mul(st.gasUsed(), st.gasPrice)) // 给矿工增加收入。
    // requiredGas和gasUsed的区别一个是没有退税的, 一个是退税了的。
    // 看上面的调用 ApplyMessage直接丢弃了requiredGas, 说明返回的是退税了的。
    return ret, requiredGas, st.gasUsed(), vmerr != nil, err
}

原文地址:http://blog.51cto.com/14035944/2307348

时间: 2024-08-01 04:59:05

区块链教程以太坊源码分析core-state-process源码分析的相关文章

区块链教程以太坊源码分析core-state-process源码分析(二)

兄弟连区块链教程以太坊源码分析core-state-process源码分析(二):关于g0的计算,在黄皮书上由详细的介绍和黄皮书有一定出入的部分在于if contractCreation && homestead {igas.SetUint64(params.TxGasContractCreation) 这是因为 Gtxcreate+Gtransaction = TxGasContractCreation func IntrinsicGas(data []byte, contractCre

{区块链教程}以太坊源码分析fast sync算法二

{区块链教程}以太坊源码分析fast sync算法二:上面的表格应该这样解释:如果我们每隔K个区块头验证一次区块头,在N个区块头之后,伪造的概率小于***者产生SHA3冲突的概率.这也意味着,如果确实发现了伪造,那么最后的N个头部应该被丢弃,因为不够安全.可以从上表中选择任何{N,K}对,为了选择一个看起来好看点的数字,我们选择N = 2048,K = 100.后续可能会根据网络带宽/延迟影响以及可能在一些CPU性能比较受限的设备上运行的情况来进行调整. Using this caveat ho

区块链教程以太坊源码分析core-state源码分析(二)

## statedb.go stateDB用来存储以太坊中关于merkle trie的所有内容. StateDB负责缓存和存储嵌套状态. 这是检索合约和账户的一般查询界面: 数据结构 type StateDB struct { db Database // 后端的数据库 trie Trie // trie树 main account trie // This map holds 'live' objects, which will get modified while processing a

区块链教程以太源码分析accounts账户管理分析

区块链教程以太源码分析accounts账户管理分析. 数据结构分析 ETH的账户管理定义在accounts/manager.go中,其数据结构为: // Manager is an overarching account manager that can communicate with various // backends for signing transactions. type Manager struct { backends map[reflect.Type][]Backend /

【区块链】以太坊(Ethereum )高级进阶实战视频教程

[区块链]以太坊(Ethereum )高级进阶实战视频教程视频教程地址:http://edu.51cto.com/course/14785.html 课程大纲: 课程概要介绍使用bootnode搭建以太坊私有链web3j介绍及基本使用使用web3j管理账户default block parameter以太坊交易详解ERC20代币介绍使用web3j部署ERC20代币合约账户解锁web3j调用代币合约方法(一)web3j调用代币合约方法(二)web3j调用代币合约方法(三)深入sendTransac

4.区块链平台以太坊从入门到精通之 以太币

1.以太币简介 以太币( ether) 是以太坊中使用的货币的名字.它是用于支付在虚拟机中的运算的费用. 了解就可以 2.获取和发送以太币 有三种方式获取 1.成为一名矿工,通过挖矿来获得以太币的奖励. 2.从交易平台处购买或兑换 3. 图形化界面的以太坊客户端集成了https://shapeshift.io/#/coins 接口. 可以直接在客户端上购买以太币. (需要在主网上才可以) 3.集中的交易兑换市场

区块链教程以太源码分析accounts包简介

accounts包实现了eth客户端的钱包和账户管理.账号的数据结构:typeAccount struct { Address common.Address json:"address" // Ethereum account addressderived from the key URLURL json:"url" // Optional resource locator within a backend }钱包interface,是指包含了一个或多个账户的软件钱

区块链:以太坊基础之安装Geth

1.安装cmake 智能合约需要cmake3.x版本才可以编译 # 下载包 wget https://cmake.org/files/v3.3/cmake-3.3.2.tar.gz # 解压 tar zxvf cmake-3.3.2.tar.gz cd cmake-3.3.2 # 安装 ./configure make make install # 编辑环境变量配置文件 vim /etc/profile # 在末尾加上 export PATH=/usr/cmake/cmake-3.3.2/bin

区块链:以太坊基础之搭建私链

1.新建genesis.json {  "config": {    "chainId": 666,    "homesteadBlock": 0,    "eip150Block": 0,    "eip150Hash": "0x0000000000000000000000000000000000000000000000000000000000000000",    "eip