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

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

package types

import (
    "fmt"
    "math/big"

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

type bytesBacked interface {
    Bytes() []byte
}

const (
    // BloomByteLength represents the number of bytes used in a header log bloom.
    BloomByteLength = 256

    // BloomBitLength represents the number of bits used in a header log bloom.
    BloomBitLength = 8 * BloomByteLength
)

// Bloom represents a 2048 bit bloom filter.
type Bloom [BloomByteLength]byte

// BytesToBloom converts a byte slice to a bloom filter.
// It panics if b is not of suitable size.
func BytesToBloom(b []byte) Bloom {
    var bloom Bloom
    bloom.SetBytes(b)
    return bloom
}

// SetBytes sets the content of b to the given bytes.
// It panics if d is not of suitable size.
func (b *Bloom) SetBytes(d []byte) {
    if len(b) < len(d) {
        panic(fmt.Sprintf("bloom bytes too big %d %d", len(b), len(d)))
    }
    copy(b[BloomByteLength-len(d):], d)
}

// Add adds d to the filter. Future calls of Test(d) will return true.
func (b *Bloom) Add(d *big.Int) {
    bin := new(big.Int).SetBytes(b[:])
    bin.Or(bin, bloom9(d.Bytes()))
    b.SetBytes(bin.Bytes())
}

// Big converts b to a big integer.
func (b Bloom) Big() *big.Int {
    return new(big.Int).SetBytes(b[:])
}

func (b Bloom) Bytes() []byte {
    return b[:]
}

func (b Bloom) Test(test *big.Int) bool {
    return BloomLookup(b, test)
}

func (b Bloom) TestBytes(test []byte) bool {
    return b.Test(new(big.Int).SetBytes(test))

}

// MarshalText encodes b as a hex string with 0x prefix.
func (b Bloom) MarshalText() ([]byte, error) {
    return hexutil.Bytes(b[:]).MarshalText()
}

// UnmarshalText b as a hex string with 0x prefix.
func (b *Bloom) UnmarshalText(input []byte) error {
    return hexutil.UnmarshalFixedText("Bloom", input, b[:])
}

func CreateBloom(receipts Receipts) Bloom {
    bin := new(big.Int)
    for _, receipt := range receipts {
        bin.Or(bin, LogsBloom(receipt.Logs))
    }

    return BytesToBloom(bin.Bytes())
}

func LogsBloom(logs []*Log) *big.Int {
    bin := new(big.Int)
    for _, log := range logs {
        bin.Or(bin, bloom9(log.Address.Bytes()))
        for _, b := range log.Topics {
            bin.Or(bin, bloom9(b[:]))
        }
    }

    return bin
}

func bloom9(b []byte) *big.Int {
    b = crypto.Keccak256(b)

    r := new(big.Int)

    for i := 0; i < 6; i += 2 {
        t := big.NewInt(1)
        b := (uint(b[i+1]) + (uint(b[i]) << 8)) & 2047
        r.Or(r, t.Lsh(t, b))
    }

    return r
}

var Bloom9 = bloom9

func BloomLookup(bin Bloom, topic bytesBacked) bool {
    bloom := bin.Big()
    cmp := bloom9(topic.Bytes())

    return bloom.And(bloom, cmp).Cmp(cmp) == 0
}

Appendix A. 批注

type bytesBacked interface

定义接口 bytesBacked。

  1. Bytes() []byte
    方法 Bytes() 返回字节列表。

const

  • BloomByteLength:表示区块头中日志布隆过滤器的字节数。
  • BloomBitLength:表示区块头中日志布隆过滤器的位数。

type Bloom [BloomByteLength]byte

Bloom 表示 2048 位的布隆过滤器。

  1. func (b *Bloom) SetBytes(d []byte)
    方法 SetBytes() 将 b 的内容设为 d。

主要的实现细节:

  • 校验输入的字节数
  • 调用函数 copy() 完成字节的拷贝操作
  1. func (b *Bloom) Add(d *big.Int)
    方法 Add() 向布隆过滤器添加 d。

主要的实现细节:

  • 将布隆过滤器恢复为 big.Int
  • 通过函数 bloom9() 对输入 d 进行转换,然后通过或操作添加进原布隆过滤器
  • 将 big.Int 转换为布隆过滤器
  1. func (b Bloom) Big() *big.Int
    方法 Big() 将布隆过滤器转换为 big.Int。

  2. func (b Bloom) Bytes() []byte
    方法 Bytes() 返回布隆过滤器的字节。

  3. func (b Bloom) Test(test *big.Int) bool
    方法 Test() 返回给定输入是否存在于布隆过滤器中。

主要的实现细节:

  • 通过函数 BloomLookup() 实现主要操作。
  1. func (b Bloom) TestBytes(test []byte) bool
    方法 Test() 返回给定输入是否存在于布隆过滤器中。

主要的实现细节:

  • 将输入 []byte 转换为 big.Int
  • 再将具体实现转发给方法 Test()
  1. func (b Bloom) MarshalText() ([]byte, error)
    方法 MarshalText() 将布隆过滤器编码为带前缀 0x 的 16 进制字符串。

主要的实现细节:

  • 通过方法 hexutil.Bytes.MarshalText() 实现主要操作。
  1. func (b *Bloom) UnmarshalText(input []byte) error
    方法 UnmarshalText() 将带前缀 0x 的 16 进制字符串解码为布隆过滤器。

主要的实现细节:

  • 这里参数 input 的字节数应该就是布隆过滤器的字节数
  • 通过方法 hexutil.UnmarshalFixedText() 实现主要操作。

func BytesToBloom(b []byte) Bloom

函数 BytesToBloom() 将字节切片转换成布隆过滤器。

func CreateBloom(receipts Receipts) Bloom

函数 CreateBloom() 根据给定的收据列表(Receipts)创建布隆过滤器。

主要的实现细节:

  • 通过函数 LogsBloom() 对 Receipts 中每个 Receipt 中的 Logs 生成 big.Int,并添加进布隆过滤器中
  • 通过函数 BytesToBloom() 将计算出的字节转换成布隆过滤器

func LogsBloom(logs []*Log) *big.Int

函数 LogsBloom() 对给定的输入 logs (日志列表)生成对应的布隆项。

主要的实现细节:

  • 对 logs 中的每个 log 做累积计算
  • 对 log 中的 Address 和 Topics 调用函数 bloom9()

func bloom9(b []byte) *big.Int

函数 bloom9() 根据 Keccak256 将字节转换成 big.Int。

var Bloom9 = bloom9

func BloomLookup(bin Bloom, topic bytesBacked) bool

函数 BloomLookup() 在 Bloom 中查找是否包含接口 bytesBacked 返回的字节。

主要的实现细节:

  • 实现方法很巧妙
  • 通过 bit 的 And 和 Cmp 操作判定是否包含
func BloomLookup(bin Bloom, topic bytesBacked) bool {
    bloom := bin.Big()
    cmp := bloom9(topic.Bytes())

    return bloom.And(bloom, cmp).Cmp(cmp) == 0
}

Reference

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

Contributor

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

推荐阅读更多精彩内容