github.com/linapex/ethereum-go-chinese@v0.0.0-20190316121929-f8b7a73c3fa1/core/bloombits/generator.go (about) 1 2 //<developer> 3 // <name>linapex 曹一峰</name> 4 // <email>linapex@163.com</email> 5 // <wx>superexc</wx> 6 // <qqgroup>128148617</qqgroup> 7 // <url>https://jsq.ink</url> 8 // <role>pku engineer</role> 9 // <date>2019-03-16 19:16:35</date> 10 //</624450078098067456> 11 12 13 package bloombits 14 15 import ( 16 "errors" 17 18 "github.com/ethereum/go-ethereum/core/types" 19 ) 20 21 var ( 22 //如果用户尝试添加更多Bloom筛选器,则返回errSectionOutofBounds 23 //批处理的可用空间不足,或者如果尝试检索超过容量。 24 errSectionOutOfBounds = errors.New("section out of bounds") 25 26 //如果用户尝试检索指定的 27 //比容量大一点。 28 errBloomBitOutOfBounds = errors.New("bloom bit out of bounds") 29 ) 30 31 //发电机接收许多布卢姆滤波器并生成旋转的布卢姆位 32 //用于批量过滤。 33 type Generator struct { 34 blooms [types.BloomBitLength][]byte //每比特匹配的旋转花束 35 sections uint //要一起批处理的节数 36 nextSec uint //添加花束时要设置的下一节 37 } 38 39 //NewGenerator创建一个旋转的Bloom Generator,它可以迭代填充 40 //批量布卢姆过滤器的钻头。 41 func NewGenerator(sections uint) (*Generator, error) { 42 if sections%8 != 0 { 43 return nil, errors.New("section count not multiple of 8") 44 } 45 b := &Generator{sections: sections} 46 for i := 0; i < types.BloomBitLength; i++ { 47 b.blooms[i] = make([]byte, sections/8) 48 } 49 return b, nil 50 } 51 52 //addbloom接受一个bloom过滤器并设置相应的位列 53 //在记忆中。 54 func (b *Generator) AddBloom(index uint, bloom types.Bloom) error { 55 //确保我们添加的布卢姆过滤器不会超过我们的容量 56 if b.nextSec >= b.sections { 57 return errSectionOutOfBounds 58 } 59 if b.nextSec != index { 60 return errors.New("bloom filter with unexpected index") 61 } 62 //旋转花束并插入我们的收藏 63 byteIndex := b.nextSec / 8 64 bitMask := byte(1) << byte(7-b.nextSec%8) 65 66 for i := 0; i < types.BloomBitLength; i++ { 67 bloomByteIndex := types.BloomByteLength - 1 - i/8 68 bloomBitMask := byte(1) << byte(i%8) 69 70 if (bloom[bloomByteIndex] & bloomBitMask) != 0 { 71 b.blooms[i][byteIndex] |= bitMask 72 } 73 } 74 b.nextSec++ 75 76 return nil 77 } 78 79 //位集返回属于给定位索引的位向量。 80 //花开了。 81 func (b *Generator) Bitset(idx uint) ([]byte, error) { 82 if b.nextSec != b.sections { 83 return nil, errors.New("bloom not fully generated yet") 84 } 85 if idx >= types.BloomBitLength { 86 return nil, errBloomBitOutOfBounds 87 } 88 return b.blooms[idx], nil 89 } 90