Go-ethereum 源码解析之 core/types/receipt.go

Go-ethereum 源码解析之 core/types/receipt.go

package types

import (
    "bytes"
    "fmt"
    "io"
    "unsafe"

    "github.com/ethereum/go-ethereum/common"
    "github.com/ethereum/go-ethereum/common/hexutil"
    "github.com/ethereum/go-ethereum/rlp"
)

//go:generate gencodec -type Receipt -field-override receiptMarshaling -out gen_receipt_json.go

var (
    receiptStatusFailedRLP     = []byte{}
    receiptStatusSuccessfulRLP = []byte{0x01}
)

const (
    // ReceiptStatusFailed is the status code of a transaction if execution failed.
    ReceiptStatusFailed = uint64(0)

    // ReceiptStatusSuccessful is the status code of a transaction if execution succeeded.
    ReceiptStatusSuccessful = uint64(1)
)

// Receipt represents the results of a transaction.
type Receipt struct {
    // Consensus fields
    PostState         []byte `json:"root"`
    Status            uint64 `json:"status"`
    CumulativeGasUsed uint64 `json:"cumulativeGasUsed" gencodec:"required"`
    Bloom             Bloom  `json:"logsBloom"         gencodec:"required"`
    Logs              []*Log `json:"logs"              gencodec:"required"`

    // Implementation fields (don't reorder!)
    TxHash          common.Hash    `json:"transactionHash" gencodec:"required"`
    ContractAddress common.Address `json:"contractAddress"`
    GasUsed         uint64         `json:"gasUsed" gencodec:"required"`
}

type receiptMarshaling struct {
    PostState         hexutil.Bytes
    Status            hexutil.Uint64
    CumulativeGasUsed hexutil.Uint64
    GasUsed           hexutil.Uint64
}

// receiptRLP is the consensus encoding of a receipt.
type receiptRLP struct {
    PostStateOrStatus []byte
    CumulativeGasUsed uint64
    Bloom             Bloom
    Logs              []*Log
}

type receiptStorageRLP struct {
    PostStateOrStatus []byte
    CumulativeGasUsed uint64
    Bloom             Bloom
    TxHash            common.Hash
    ContractAddress   common.Address
    Logs              []*LogForStorage
    GasUsed           uint64
}

// NewReceipt creates a barebone transaction receipt, copying the init fields.
func NewReceipt(root []byte, failed bool, cumulativeGasUsed uint64) *Receipt {
    r := &Receipt{PostState: common.CopyBytes(root), CumulativeGasUsed: cumulativeGasUsed}
    if failed {
        r.Status = ReceiptStatusFailed
    } else {
        r.Status = ReceiptStatusSuccessful
    }
    return r
}

// EncodeRLP implements rlp.Encoder, and flattens the consensus fields of a receipt
// into an RLP stream. If no post state is present, byzantium fork is assumed.
func (r *Receipt) EncodeRLP(w io.Writer) error {
    return rlp.Encode(w, &receiptRLP{r.statusEncoding(), r.CumulativeGasUsed, r.Bloom, r.Logs})
}

// DecodeRLP implements rlp.Decoder, and loads the consensus fields of a receipt
// from an RLP stream.
func (r *Receipt) DecodeRLP(s *rlp.Stream) error {
    var dec receiptRLP
    if err := s.Decode(&dec); err != nil {
        return err
    }
    if err := r.setStatus(dec.PostStateOrStatus); err != nil {
        return err
    }
    r.CumulativeGasUsed, r.Bloom, r.Logs = dec.CumulativeGasUsed, dec.Bloom, dec.Logs
    return nil
}

func (r *Receipt) setStatus(postStateOrStatus []byte) error {
    switch {
    case bytes.Equal(postStateOrStatus, receiptStatusSuccessfulRLP):
        r.Status = ReceiptStatusSuccessful
    case bytes.Equal(postStateOrStatus, receiptStatusFailedRLP):
        r.Status = ReceiptStatusFailed
    case len(postStateOrStatus) == len(common.Hash{}):
        r.PostState = postStateOrStatus
    default:
        return fmt.Errorf("invalid receipt status %x", postStateOrStatus)
    }
    return nil
}

func (r *Receipt) statusEncoding() []byte {
    if len(r.PostState) == 0 {
        if r.Status == ReceiptStatusFailed {
            return receiptStatusFailedRLP
        }
        return receiptStatusSuccessfulRLP
    }
    return r.PostState
}

// Size returns the approximate memory used by all internal contents. It is used
// to approximate and limit the memory consumption of various caches.
func (r *Receipt) Size() common.StorageSize {
    size := common.StorageSize(unsafe.Sizeof(*r)) + common.StorageSize(len(r.PostState))

    size += common.StorageSize(len(r.Logs)) * common.StorageSize(unsafe.Sizeof(Log{}))
    for _, log := range r.Logs {
        size += common.StorageSize(len(log.Topics)*common.HashLength + len(log.Data))
    }
    return size
}

// ReceiptForStorage is a wrapper around a Receipt that flattens and parses the
// entire content of a receipt, as opposed to only the consensus fields originally.
type ReceiptForStorage Receipt

// EncodeRLP implements rlp.Encoder, and flattens all content fields of a receipt
// into an RLP stream.
func (r *ReceiptForStorage) EncodeRLP(w io.Writer) error {
    enc := &receiptStorageRLP{
        PostStateOrStatus: (*Receipt)(r).statusEncoding(),
        CumulativeGasUsed: r.CumulativeGasUsed,
        Bloom:             r.Bloom,
        TxHash:            r.TxHash,
        ContractAddress:   r.ContractAddress,
        Logs:              make([]*LogForStorage, len(r.Logs)),
        GasUsed:           r.GasUsed,
    }
    for i, log := range r.Logs {
        enc.Logs[i] = (*LogForStorage)(log)
    }
    return rlp.Encode(w, enc)
}

// DecodeRLP implements rlp.Decoder, and loads both consensus and implementation
// fields of a receipt from an RLP stream.
func (r *ReceiptForStorage) DecodeRLP(s *rlp.Stream) error {
    var dec receiptStorageRLP
    if err := s.Decode(&dec); err != nil {
        return err
    }
    if err := (*Receipt)(r).setStatus(dec.PostStateOrStatus); err != nil {
        return err
    }
    // Assign the consensus fields
    r.CumulativeGasUsed, r.Bloom = dec.CumulativeGasUsed, dec.Bloom
    r.Logs = make([]*Log, len(dec.Logs))
    for i, log := range dec.Logs {
        r.Logs[i] = (*Log)(log)
    }
    // Assign the implementation fields
    r.TxHash, r.ContractAddress, r.GasUsed = dec.TxHash, dec.ContractAddress, dec.GasUsed
    return nil
}

// Receipts is a wrapper around a Receipt array to implement DerivableList.
type Receipts []*Receipt

// Len returns the number of receipts in this list.
func (r Receipts) Len() int { return len(r) }

// GetRlp returns the RLP encoding of one receipt from the list.
func (r Receipts) GetRlp(i int) []byte {
    bytes, err := rlp.EncodeToBytes(r[i])
    if err != nil {
        panic(err)
    }
    return bytes
}

Appendix A. 总体批注

文件 core/types/receipt.go 中主要定义了数据结构 Receipt,用于存储事务处理结果的详细信息。

数据结构 Receipt 中包含共识字段和实现字段两部分。

- 共识字段同时支持 JSON 和 RLP 编码,分别由数据结构 receiptMarshaling 和 receiptRLP 表示。
- 共识字段和实现字段需要一起采用 RLP 编码进行归档,由数据结构 receiptStorageRLP。
- 数据结构 receiptMarshaling、receiptRLP、receiptStorageRLP 是流形式。
- 通过函数 NewReceipt() 新建空的 Receipt。
- 通过方法 EncodeRLP() 编码 Receipt。
- 通过方法 DecodeRLP() 解码 Receipt。
- 通过方法 Size() 评估 Receipt 的内存消耗。

数据结构 ReceiptForStorage 只是 Receipt 的封装器,便于与数据结构 receiptStorageRLP 进行映射。
- 通过方法 EncodeRLP() 编码 ReceiptForStorage。
- 通过方法 DecodeRLP() 解码 ReceiptForStorage。

数据结构 Receipts 表示 Receipt 列表的封装器。
- 通过方法 Len() 返回 Receipt 的元素个数。
- 通过方法 GetRlp() 返回某个 Receipt 的 RLP 编码。

Appendix B. 详细批注

var

  • receiptStatusFailedRLP: 收据状态为失败的 RLP 编码
  • receiptStatusSuccessfulRLP: 收据状态为成功的 RLP 编码

const

  • ReceiptStatusFailed: 事务执行失败时的状态码
  • ReceiptStatusSuccessful: 事务执行成功时的状态码

type Receipt struct

收据描述了事务的结果。

// Consensus fields
- PostState         []byte:    receiptStatusFailedRLP 或 receiptStatusSuccessfulRLP
- Status            uint64:    ReceiptStatusFailed 或 ReceiptStatusSuccessful
- CumulativeGasUsed uint64:    到此事务时累计使用掉的 gas
- Bloom             Bloom:     ??? 用于描述什么的布隆过滤器呢
- Logs              []*Log:    事务中用于描述智能合约的日志事件列表

// Implementation fields (don't reorder!)
- TxHash          common.Hash:     事务的哈希
- ContractAddress common.Address:  智能合约地址
- GasUsed         uint64:          此事务使用的 gas
  1. func (r *Receipt) EncodeRLP(w io.Writer) error
    方法 EncodeRLP() 实现了 rlp.Encoder 接口,并将收据的共识字段扁平化成 RLP 流。

将收据的 RLP 编码写入到参数 w 中。

- 具体的实现是调用函数 rlp.Encode() 完成的。
  1. func (r *Receipt) DecodeRLP(s *rlp.Stream) error
    方法 DecodeRLP() 实现了 rlp.Decoder 接口,并从 RLP 流中加载收据的共识字段。

从参数 s 中加载共识字段。

- 具体的实现是调用方法 rlp.Stream.Decode() 完成的。
- 通过方法 setStatus() 完成 receiptRLP.PostStateOrStatus 与 Receipt.PostState & Receipt.Status 字段之间的映射。
  1. func (r *Receipt) setStatus(postStateOrStatus []byte) error
    方法 setStatus() 从参数 postStateOrStatus 中映射出 Status 或 PostState 字段。

  2. func (r *Receipt) statusEncoding() []byte
    方法 statusEncoding() 返回状态的 RLP 编码。

    • 如果 PostState 为空,则根据 Status 的值来决定
      • 如果 Status 为 ReceiptStatusFailed,则返回 receiptStatusFailedRLP,否则返回 receiptStatusSuccessfulRLP
    • 否则,返回 PostState
  3. func (r *Receipt) Size() common.StorageSize
    方法 Size() 返回所由内部内容所使用的大致内存。它被用于评估或限制各种缓存对于内存的消耗。

    • 主要是深度计算了字段 PostState 和 Logs 的大小。

type receiptMarshaling struct

收据序列化所包含的成员。

- PostState         hexutil.Bytes:     
- Status            hexutil.Uint64:    
- CumulativeGasUsed hexutil.Uint64:    
- GasUsed           hexutil.Uint64:    

type receiptRLP struct

收据的共识 RLP 编码。

- PostStateOrStatus []byte:    
- CumulativeGasUsed uint64:    
- Bloom             Bloom:     
- Logs              []*Log:    

type receiptStorageRLP struct

收据存储的 RLP 编码。

PostStateOrStatus []byte
CumulativeGasUsed uint64
Bloom             Bloom
TxHash            common.Hash
ContractAddress   common.Address
Logs              []*LogForStorage
GasUsed           uint64

type ReceiptForStorage Receipt

ReceiptForStorage 是 Receipt 的封装器,用于扁平化和分析 Receipt 的整个内容,而不仅仅是原始的共识字段。

  1. func (r *ReceiptForStorage) EncodeRLP(w io.Writer) error
    方法 EncodeRLP() 实现了 rlp.Encoder 接口,并将收据的共识字段扁平化成 RLP 流。

将 ReceiptForStorage 的 RLP 编码写入到参数 w 中。

- 具体的实现是调用函数 rlp.Encode() 完成的。
  1. func (r *ReceiptForStorage) DecodeRLP(s *rlp.Stream) error
    方法 DecodeRLP() 实现了 rlp.Decoder 接口,并从 RLP 流中加载收据的共识字段。

从参数 s 中同时加载共识字段和实现字段。

- 具体的实现是调用方法 rlp.Stream.Decode() 完成的。
- 通过方法 setStatus() 完成 receiptStorageRLP.PostStateOrStatus 与 PostState & Status 字段之间的映射。
- 从解码后的 receiptStorageRLP 中还原其它字段。

type Receipts []*Receipt

Receipts 表示 Receipt 列表的封装器

  1. func (r Receipts) Len()
    方法 Len() 返回列表中 Receipt 的元素个数。

  2. func (r Receipts) GetRlp(i int) []byte
    方法 GetRlp() 返回列表中某个 Receipt 的 RLP 编码。

func NewReceipt(root []byte, failed bool, cumulativeGasUsed uint64) *Receipt

函数 NewReceipt() 创建空的事务收据,拷贝初始成员。

Reference

  1. https://github.com/ethereum/go-ethereum/blob/master/core/types/receipt.go

Contributor

  1. Windstamp
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,319评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,801评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,567评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,156评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,019评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,090评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,500评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,192评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,474评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,566评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,338评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,212评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,572评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,890评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,169评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,478评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,661评论 2 335