分享
  1. 首页
  2. 文章

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

兄弟连区块链培训 · · 1176 次点击 · · 开始浏览
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

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
}

有疑问加站长微信联系(非本文作者)

本文来自:Segmentfault

感谢作者:兄弟连区块链培训

查看原文:兄弟连区块链教程以太坊源码分析core-state-process源码分析

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

关注微信
1176 次点击
暂无回复
添加一条新回复 (您需要 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传

用户登录

没有账号?注册
(追記) (追記ここまで)

今日阅读排行

    加载中
(追記) (追記ここまで)

一周阅读排行

    加载中

关注我

  • 扫码关注领全套学习资料 关注微信公众号
  • 加入 QQ 群:
    • 192706294(已满)
    • 731990104(已满)
    • 798786647(已满)
    • 729884609(已满)
    • 977810755(已满)
    • 815126783(已满)
    • 812540095(已满)
    • 1006366459(已满)
    • 692541889

  • 关注微信公众号
  • 加入微信群:liuxiaoyan-s,备注入群
  • 也欢迎加入知识星球 Go粉丝们(免费)

给该专栏投稿 写篇新文章

每篇文章有总共有 5 次投稿机会

收入到我管理的专栏 新建专栏