Skip to content

Commit e43d827

Browse files
core/types: optimize bloom filters (#21624)
* core/types: tests for bloom * core/types: refactored bloom filter for receipts, added tests core/types: replaced old bloom implementation core/types: change interface of bloom add+test * core/types: refactor bloom * core/types: minor tweak on LogsBloom Co-authored-by: Marius van der Wijden <m.vanderwijden@live.de>
1 parent eb87121 commit e43d827

2 files changed

Lines changed: 161 additions & 62 deletions

File tree

‎core/types/bloom9.go‎

Lines changed: 62 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
package types
1818

1919
import (
20+
"encoding/binary"
2021
"fmt"
2122
"math/big"
2223

@@ -57,28 +58,36 @@ func (b *Bloom) SetBytes(d []byte) {
5758
}
5859

5960
// Add adds d to the filter. Future calls of Test(d) will return true.
60-
func (b *Bloom) Add(d *big.Int) {
61-
bin := new(big.Int).SetBytes(b[:])
62-
bin.Or(bin, bloom9(d.Bytes()))
63-
b.SetBytes(bin.Bytes())
61+
func (b *Bloom) Add(d []byte) {
62+
b.add(d, make([]byte, 6))
63+
}
64+
65+
// add is internal version of Add, which takes a scratch buffer for reuse (needs to be at least 6 bytes)
66+
func (b *Bloom) add(d []byte, buf []byte) {
67+
i1, v1, i2, v2, i3, v3 := bloomValues(d, buf)
68+
b[i1] |= v1
69+
b[i2] |= v2
70+
b[i3] |= v3
6471
}
6572

6673
// Big converts b to a big integer.
74+
// Note: Converting a bloom filter to a big.Int and then calling GetBytes
75+
// does not return the same bytes, since big.Int will trim leading zeroes
6776
func (b Bloom) Big() *big.Int {
6877
return new(big.Int).SetBytes(b[:])
6978
}
7079

80+
// Bytes returns the backing byte slice of the bloom
7181
func (b Bloom) Bytes() []byte {
7282
return b[:]
7383
}
7484

75-
func (b Bloom) Test(test *big.Int) bool {
76-
return BloomLookup(b, test)
77-
}
78-
79-
func (b Bloom) TestBytes(test []byte) bool {
80-
return b.Test(new(big.Int).SetBytes(test))
81-
85+
// Test checks if the given topic is present in the bloom filter
86+
func (b Bloom) Test(topic []byte) bool {
87+
i1, v1, i2, v2, i3, v3 := bloomValues(topic, make([]byte, 6))
88+
return v1 == v1&b[i1] &&
89+
v2 == v2&b[i2] &&
90+
v3 == v3&b[i3]
8291
}
8392

8493
// MarshalText encodes b as a hex string with 0x prefix.
@@ -91,46 +100,61 @@ func (b *Bloom) UnmarshalText(input []byte) error {
91100
return hexutil.UnmarshalFixedText("Bloom", input, b[:])
92101
}
93102

103+
// CreateBloom creates a bloom filter out of the give Receipts (+Logs)
94104
func CreateBloom(receipts Receipts) Bloom {
95-
bin := new(big.Int)
105+
buf := make([]byte, 6)
106+
var bin Bloom
96107
for _, receipt := range receipts {
97-
bin.Or(bin, LogsBloom(receipt.Logs))
108+
for _, log := range receipt.Logs {
109+
bin.add(log.Address.Bytes(), buf)
110+
for _, b := range log.Topics {
111+
bin.add(b[:], buf)
112+
}
113+
}
98114
}
99-
100-
return BytesToBloom(bin.Bytes())
115+
return bin
101116
}
102117

103-
func LogsBloom(logs []*Log) *big.Int {
104-
bin := new(big.Int)
118+
// LogsBloom returns the bloom bytes for the given logs
119+
func LogsBloom(logs []*Log) []byte {
120+
buf := make([]byte, 6)
121+
var bin Bloom
105122
for _, log := range logs {
106-
bin.Or(bin, bloom9(log.Address.Bytes()))
123+
bin.add(log.Address.Bytes(), buf)
107124
for _, b := range log.Topics {
108-
bin.Or(bin, bloom9(b[:]))
125+
bin.add(b[:], buf)
109126
}
110127
}
111-
112-
return bin
128+
return bin[:]
113129
}
114130

115-
func bloom9(b []byte) *big.Int {
116-
b = crypto.Keccak256(b)
117-
118-
r := new(big.Int)
119-
120-
for i := 0; i < 6; i += 2 {
121-
t := big.NewInt(1)
122-
b := (uint(b[i+1]) + (uint(b[i]) << 8)) & 2047
123-
r.Or(r, t.Lsh(t, b))
124-
}
125-
126-
return r
131+
// Bloom9 returns the bloom filter for the given data
132+
func Bloom9(data []byte) []byte {
133+
var b Bloom
134+
b.SetBytes(data)
135+
return b.Bytes()
127136
}
128137

129-
var Bloom9 = bloom9
138+
// bloomValues returns the bytes (index-value pairs) to set for the given data
139+
func bloomValues(data []byte, hashbuf []byte) (uint, byte, uint, byte, uint, byte) {
140+
sha := hasherPool.Get().(crypto.KeccakState)
141+
sha.Reset()
142+
sha.Write(data)
143+
sha.Read(hashbuf)
144+
hasherPool.Put(sha)
145+
// The actual bits to flip
146+
v1 := byte(1 << (hashbuf[1] & 0x7))
147+
v2 := byte(1 << (hashbuf[3] & 0x7))
148+
v3 := byte(1 << (hashbuf[5] & 0x7))
149+
// The indices for the bytes to OR in
150+
i1 := BloomByteLength - uint((binary.BigEndian.Uint16(hashbuf)&0x7ff)>>3) - 1
151+
i2 := BloomByteLength - uint((binary.BigEndian.Uint16(hashbuf[2:])&0x7ff)>>3) - 1
152+
i3 := BloomByteLength - uint((binary.BigEndian.Uint16(hashbuf[4:])&0x7ff)>>3) - 1
153+
154+
return i1, v1, i2, v2, i3, v3
155+
}
130156

157+
// BloomLookup is a convenience-method to check presence int he bloom filter
131158
func BloomLookup(bin Bloom, topic bytesBacked) bool {
132-
bloom := bin.Big()
133-
cmp := bloom9(topic.Bytes())
134-
135-
return bloom.And(bloom, cmp).Cmp(cmp) == 0
159+
return bin.Test(topic.Bytes())
136160
}

‎core/types/bloom9_test.go‎

Lines changed: 99 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,12 @@
1717
package types
1818

1919
import (
20+
"fmt"
2021
"math/big"
2122
"testing"
23+
24+
"github.com/ethereum/go-ethereum/common"
25+
"github.com/ethereum/go-ethereum/crypto"
2226
)
2327

2428
func TestBloom(t *testing.T) {
@@ -35,47 +39,118 @@ func TestBloom(t *testing.T) {
3539

3640
var bloom Bloom
3741
for _, data := range positive {
38-
bloom.Add(new(big.Int).SetBytes([]byte(data)))
42+
bloom.Add([]byte(data))
3943
}
4044

4145
for _, data := range positive {
42-
if !bloom.TestBytes([]byte(data)) {
46+
if !bloom.Test([]byte(data)) {
4347
t.Error("expected", data, "to test true")
4448
}
4549
}
4650
for _, data := range negative {
47-
if bloom.TestBytes([]byte(data)) {
51+
if bloom.Test([]byte(data)) {
4852
t.Error("did not expect", data, "to test true")
4953
}
5054
}
5155
}
5256

53-
/*
54-
import (
55-
"testing"
56-
57-
"github.com/ethereum/go-ethereum/core/state"
58-
)
57+
// TestBloomExtensively does some more thorough tests
58+
func TestBloomExtensively(t *testing.T) {
59+
var exp = common.HexToHash("c8d3ca65cdb4874300a9e39475508f23ed6da09fdbc487f89a2dcf50b09eb263")
60+
var b Bloom
61+
// Add 100 "random" things
62+
for i := 0; i < 100; i++ {
63+
data := fmt.Sprintf("xxxxxxxxxx data %d yyyyyyyyyyyyyy", i)
64+
b.Add([]byte(data))
65+
//b.Add(new(big.Int).SetBytes([]byte(data)))
66+
}
67+
got := crypto.Keccak256Hash(b.Bytes())
68+
if got != exp {
69+
t.Errorf("Got %x, exp %x", got, exp)
70+
}
71+
var b2 Bloom
72+
b2.SetBytes(b.Bytes())
73+
got2 := crypto.Keccak256Hash(b2.Bytes())
74+
if got != got2 {
75+
t.Errorf("Got %x, exp %x", got, got2)
76+
}
77+
}
5978

60-
func TestBloom9(t *testing.T) {
61-
testCase := []byte("testtest")
62-
bin := LogsBloom([]state.Log{
63-
{testCase, [][]byte{[]byte("hellohello")}, nil},
64-
}).Bytes()
65-
res := BloomLookup(bin, testCase)
79+
func BenchmarkBloom9(b *testing.B) {
80+
test := []byte("testestestest")
81+
for i := 0; i < b.N; i++ {
82+
Bloom9(test)
83+
}
84+
}
6685

67-
if !res {
68-
t.Errorf("Bloom lookup failed")
86+
func BenchmarkBloom9Lookup(b *testing.B) {
87+
toTest := []byte("testtest")
88+
bloom := new(Bloom)
89+
for i := 0; i < b.N; i++ {
90+
bloom.Test(toTest)
6991
}
7092
}
7193

94+
func BenchmarkCreateBloom(b *testing.B) {
7295

73-
func TestAddress(t *testing.T) {
74-
block := &Block{}
75-
block.Coinbase = common.Hex2Bytes("22341ae42d6dd7384bc8584e50419ea3ac75b83f")
76-
fmt.Printf("%x\n", crypto.Keccak256(block.Coinbase))
96+
var txs = Transactions{
97+
NewContractCreation(1, big.NewInt(1), 1, big.NewInt(1), nil),
98+
NewTransaction(2, common.HexToAddress("0x2"), big.NewInt(2), 2, big.NewInt(2), nil),
99+
}
100+
var rSmall = Receipts{
101+
&Receipt{
102+
Status: ReceiptStatusFailed,
103+
CumulativeGasUsed: 1,
104+
Logs: []*Log{
105+
{Address: common.BytesToAddress([]byte{0x11})},
106+
{Address: common.BytesToAddress([]byte{0x01, 0x11})},
107+
},
108+
TxHash: txs[0].Hash(),
109+
ContractAddress: common.BytesToAddress([]byte{0x01, 0x11, 0x11}),
110+
GasUsed: 1,
111+
},
112+
&Receipt{
113+
PostState: common.Hash{2}.Bytes(),
114+
CumulativeGasUsed: 3,
115+
Logs: []*Log{
116+
{Address: common.BytesToAddress([]byte{0x22})},
117+
{Address: common.BytesToAddress([]byte{0x02, 0x22})},
118+
},
119+
TxHash: txs[1].Hash(),
120+
ContractAddress: common.BytesToAddress([]byte{0x02, 0x22, 0x22}),
121+
GasUsed: 2,
122+
},
123+
}
77124

78-
bin := CreateBloom(block)
79-
fmt.Printf("bin = %x\n", common.LeftPadBytes(bin, 64))
125+
var rLarge = make(Receipts, 200)
126+
// Fill it with 200 receipts x 2 logs
127+
for i := 0; i < 200; i += 2 {
128+
copy(rLarge[i:], rSmall)
129+
}
130+
b.Run("small", func(b *testing.B) {
131+
b.ReportAllocs()
132+
var bl Bloom
133+
for i := 0; i < b.N; i++ {
134+
bl = CreateBloom(rSmall)
135+
}
136+
b.StopTimer()
137+
var exp = common.HexToHash("c384c56ece49458a427c67b90fefe979ebf7104795be65dc398b280f24104949")
138+
got := crypto.Keccak256Hash(bl.Bytes())
139+
if got != exp {
140+
b.Errorf("Got %x, exp %x", got, exp)
141+
}
142+
})
143+
b.Run("large", func(b *testing.B) {
144+
b.ReportAllocs()
145+
var bl Bloom
146+
for i := 0; i < b.N; i++ {
147+
bl = CreateBloom(rLarge)
148+
}
149+
b.StopTimer()
150+
var exp = common.HexToHash("c384c56ece49458a427c67b90fefe979ebf7104795be65dc398b280f24104949")
151+
got := crypto.Keccak256Hash(bl.Bytes())
152+
if got != exp {
153+
b.Errorf("Got %x, exp %x", got, exp)
154+
}
155+
})
80156
}
81-
*/

0 commit comments

Comments
 (0)