From 8bcf1c5ff20e90d9af3c92178093d32b2c5ae73d Mon Sep 17 00:00:00 2001 From: Zsolt Felfoldi Date: Sun, 5 Mar 2017 16:52:03 +0100 Subject: [PATCH 01/11] core, light: add canonical chain post-processor interface --- core/blockchain.go | 41 +++++++++- core/chain_processor.go | 176 ++++++++++++++++++++++++++++++++++++++++ core/headerchain.go | 11 ++- light/lightchain.go | 38 ++++++++- 4 files changed, 260 insertions(+), 6 deletions(-) create mode 100644 core/chain_processor.go diff --git a/core/blockchain.go b/core/blockchain.go index 794e1915fc..ecae115d7b 100644 --- a/core/blockchain.go +++ b/core/blockchain.go @@ -104,6 +104,8 @@ type BlockChain struct { procInterrupt int32 // interrupt signaler for block processing wg sync.WaitGroup // chain processing wait group for shutting down + chainProcessors []ChainProcessor // NewHead function called under chain lock after a new head has been written to the db + engine consensus.Engine processor Processor // block processor interface validator Validator // block and state validator interface @@ -168,6 +170,15 @@ func NewBlockChain(chainDb ethdb.Database, config *params.ChainConfig, engine co return bc, nil } +// AddChainProcessor adds a new head callback function that will be +// called under chain lock after a new head has been written to the db +func (self *BlockChain) AddChainProcessor(cp ChainProcessor) { + self.chainmu.Lock() + self.chainProcessors = append(self.chainProcessors, cp) + cp.NewHead(self.hc.CurrentHeader().Number.Uint64(), false) + self.chainmu.Unlock() +} + func (self *BlockChain) getProcInterrupt() bool { return atomic.LoadInt32(&self.procInterrupt) == 1 } @@ -243,6 +254,7 @@ func (bc *BlockChain) SetHead(head uint64) error { bc.mu.Lock() defer bc.mu.Unlock() + oldHead := bc.hc.CurrentHeader().Number.Uint64() // Rewind the header chain, deleting all block bodies until then delFn := func(hash common.Hash, num uint64) { DeleteBody(bc.chainDb, hash, num) @@ -256,6 +268,11 @@ func (bc *BlockChain) SetHead(head uint64) error { bc.blockCache.Purge() bc.futureBlocks.Purge() + if head < oldHead { + for _, cp := range bc.chainProcessors { + cp.NewHead(head, true) + } + } // Rewind the block chain, ensuring we don't end up with a stateless head block if bc.currentBlock != nil && currentHeader.Number.Uint64() < bc.currentBlock.NumberU64() { bc.currentBlock = bc.GetBlock(currentHeader.Hash(), currentHeader.Number.Uint64()) @@ -637,12 +654,15 @@ func (self *BlockChain) Rollback(chain []common.Hash) { self.mu.Lock() defer self.mu.Unlock() + var rollbackHead *types.Header + for i := len(chain) - 1; i >= 0; i-- { hash := chain[i] currentHeader := self.hc.CurrentHeader() if currentHeader.Hash() == hash { - self.hc.SetCurrentHeader(self.GetHeader(currentHeader.ParentHash, currentHeader.Number.Uint64()-1)) + rollbackHead = self.GetHeader(currentHeader.ParentHash, currentHeader.Number.Uint64()-1) + self.hc.SetCurrentHeader(rollbackHead) } if self.currentFastBlock.Hash() == hash { self.currentFastBlock = self.GetBlock(self.currentFastBlock.ParentHash(), self.currentFastBlock.NumberU64()-1) @@ -653,6 +673,12 @@ func (self *BlockChain) Rollback(chain []common.Hash) { WriteHeadBlockHash(self.chainDb, self.currentBlock.Hash()) } } + + if rollbackHead != nil { + for _, cp := range self.chainProcessors { + cp.NewHead(rollbackHead.Number.Uint64(), true) + } + } } // SetReceiptsData computes all the non-consensus fields of the receipts @@ -1316,7 +1342,16 @@ func (self *BlockChain) InsertHeaderChain(chain []*types.Header, checkFreq int) self.mu.Lock() defer self.mu.Unlock() - _, err := self.hc.WriteHeader(header) + _, err := self.hc.WriteHeader(header, func(head *types.Header) { + for _, cp := range self.chainProcessors { + cp.NewHead(head.Number.Uint64(), true) + } + }) + + for _, cp := range self.chainProcessors { + cp.NewHead(header.Number.Uint64(), false) + } + return err } @@ -1339,7 +1374,7 @@ func (self *BlockChain) writeHeader(header *types.Header) error { self.mu.Lock() defer self.mu.Unlock() - _, err := self.hc.WriteHeader(header) + _, err := self.hc.WriteHeader(header, nil) return err } diff --git a/core/chain_processor.go b/core/chain_processor.go new file mode 100644 index 0000000000..7112c3047c --- /dev/null +++ b/core/chain_processor.go @@ -0,0 +1,176 @@ +// Copyright 2017 The go-ethereum Authors +// This file is part of the go-ethereum library. +// +// The go-ethereum library is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// The go-ethereum library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with the go-ethereum library. If not, see . + +// Package core implements the Ethereum consensus protocol. +package core + +import ( + "sync" + "time" +) + +// ChainProcessor is an external process that creates auxiliary data structures +// using the canonical chain as an input. Its callback function NewHead is called every +// time a new head is added to the chain or it gets rolled back. The callback function +// should never block because it is called under the chain's mutex lock so that the +// structures can stay consistent with the canonical chain. +// The same interface can be used for chaining processors (one using the output of the +// other). +type ChainProcessor interface { + NewHead(headNum uint64, rollBack bool) +} + +// ChainSectionProcessor is a ChainProcessor that does a post-processing job for +// equally sized sections of the canonical chain (like BlooomBits and CHT structures). +// Further child ChainProcessors can be added which use the output of this section +// processor. These child processors receive NewHead calls only after an entire section +// has been finished or in case of rollbacks that might affect already finished sections. +type ChainSectionProcessor struct { + backend ChainSectionProcessorBackend + sectionSize, confirmReq uint64 + stop chan struct{} + updateChn chan uint64 + lock sync.Mutex + calcValid bool + procWait time.Duration + stored, calcIdx, lastForwarded uint64 + childProcessors []ChainProcessor +} + +// ChainSectionProcessorBackend does the actual post-processing job. +// GetStored and SetStored are called under the canonical chain lock and should +// not block. Process is called without a chain lock and may take longer to +// finish. If the chain gets rolled back while Process is running, the results +// are considered invalid and SetStored is not called. +type ChainSectionProcessorBackend interface { + Process(idx uint64) bool + GetStored() uint64 + SetStored(count uint64) +} + +// NewChainSectionProcessor creates a new ChainSectionProcessor +func NewChainSectionProcessor(backend ChainSectionProcessorBackend, sectionSize, confirmReq uint64, procWait time.Duration, stop chan struct{}) *ChainSectionProcessor { + csp := &ChainSectionProcessor{ + backend: backend, + sectionSize: sectionSize, + confirmReq: confirmReq, + stop: stop, + procWait: procWait, + updateChn: make(chan uint64, 100), + stored: backend.GetStored(), + } + go csp.updateLoop() + return csp +} + +func (csp *ChainSectionProcessor) updateLoop() { + tryUpdate := make(chan struct{}, 1) + updating := false + var targetCnt uint64 + + for { + select { + case <-csp.stop: + return + case targetCnt = <-csp.updateChn: + if !updating { + updating = true + tryUpdate <- struct{}{} + } + case <-tryUpdate: + csp.lock.Lock() + if targetCnt > csp.stored { + csp.calcValid = true + csp.calcIdx = csp.stored + + csp.lock.Unlock() + ok := csp.backend.Process(csp.calcIdx) + csp.lock.Lock() + + if ok && csp.calcValid { + csp.stored = csp.calcIdx + 1 + csp.backend.SetStored(csp.stored) + + csp.lastForwarded = csp.stored*csp.sectionSize - 1 + for _, cp := range csp.childProcessors { + cp.NewHead(csp.lastForwarded, false) + } + + } + csp.calcValid = false + } + stored := csp.stored + csp.lock.Unlock() + + if targetCnt > stored { + go func() { + time.Sleep(csp.procWait) + tryUpdate <- struct{}{} + }() + } else { + updating = false + } + } + } +} + +// NewHead implements the ChainProcessor interface +func (csp *ChainSectionProcessor) NewHead(headNum uint64, rollback bool) { + csp.lock.Lock() + defer csp.lock.Unlock() + + if rollback { + firstChanged := headNum / csp.sectionSize + if firstChanged <= csp.calcIdx { + csp.calcValid = false + } + if firstChanged < csp.stored { + csp.stored = firstChanged + csp.backend.SetStored(csp.stored) + select { + case <-csp.stop: + case csp.updateChn <- firstChanged: + } + } + + if headNum < csp.lastForwarded { + csp.lastForwarded = headNum + for _, cp := range csp.childProcessors { + cp.NewHead(csp.lastForwarded, true) + } + } + + } else { + var newCount uint64 + if headNum >= csp.confirmReq { + newCount = (headNum + 1 - csp.confirmReq) / csp.sectionSize + if newCount > csp.stored { + go func() { + select { + case <-csp.stop: + case csp.updateChn <- newCount: + } + }() + } + } + } +} + +// AddChildProcessor adds a child ChainProcessor that can use the output of this +// section processor. +func (csp *ChainSectionProcessor) AddChildProcessor(cp ChainProcessor) { + csp.childProcessors = append(csp.childProcessors, cp) +} diff --git a/core/headerchain.go b/core/headerchain.go index 9bb7f17937..4dce739f3c 100644 --- a/core/headerchain.go +++ b/core/headerchain.go @@ -119,6 +119,10 @@ func (hc *HeaderChain) GetBlockNumber(hash common.Hash) uint64 { return number } +// ReorgCallback is a callback function to be called in case of a chain reorg. +// The parameter is the header of the last unchanged canonical block. +type ReorgCallback func(*types.Header) + // WriteHeader writes a header into the local chain, given that its parent is // already known. If the total difficulty of the newly inserted header becomes // greater than the current known TD, the canonical chain is re-routed. @@ -128,7 +132,7 @@ func (hc *HeaderChain) GetBlockNumber(hash common.Hash) uint64 { // without the real blocks. Hence, writing headers directly should only be done // in two scenarios: pure-header mode of operation (light clients), or properly // separated header/block phases (non-archive clients). -func (hc *HeaderChain) WriteHeader(header *types.Header) (status WriteStatus, err error) { +func (hc *HeaderChain) WriteHeader(header *types.Header, reorgCallback ReorgCallback) (status WriteStatus, err error) { // Cache some values to prevent constant recalculation var ( hash = header.Hash() @@ -174,6 +178,11 @@ func (hc *HeaderChain) WriteHeader(header *types.Header) (status WriteStatus, er headNumber = headHeader.Number.Uint64() - 1 headHeader = hc.GetHeader(headHash, headNumber) } + + if reorgCallback != nil && headNumber < hc.currentHeader.Number.Uint64() { + reorgCallback(headHeader) + } + // Extend the canonical chain with the new header if err := WriteCanonicalHash(hc.chainDb, hash, number); err != nil { log.Crit("Failed to insert header number", "err", err) diff --git a/light/lightchain.go b/light/lightchain.go index 5b7e570417..26517b9b40 100644 --- a/light/lightchain.go +++ b/light/lightchain.go @@ -64,6 +64,8 @@ type LightChain struct { procInterrupt int32 // interrupt signaler for block processing wg sync.WaitGroup + chainProcessors []core.ChainProcessor // NewHead function called under chain lock after a new head has been written to the db + engine consensus.Engine } @@ -114,6 +116,15 @@ func NewLightChain(odr OdrBackend, config *params.ChainConfig, engine consensus. return bc, nil } +// AddChainProcessor adds a new head callback function that will be +// called under chain lock after a new head has been written to the db +func (self *LightChain) AddChainProcessor(cp core.ChainProcessor) { + self.chainmu.Lock() + self.chainProcessors = append(self.chainProcessors, cp) + cp.NewHead(self.hc.CurrentHeader().Number.Uint64(), false) + self.chainmu.Unlock() +} + func (self *LightChain) getProcInterrupt() bool { return atomic.LoadInt32(&self.procInterrupt) == 1 } @@ -149,7 +160,13 @@ func (bc *LightChain) SetHead(head uint64) { bc.mu.Lock() defer bc.mu.Unlock() + oldHead := bc.hc.CurrentHeader().Number.Uint64() bc.hc.SetHead(head, nil) + if head < oldHead { + for _, cp := range bc.chainProcessors { + cp.NewHead(head, true) + } + } bc.loadLastState() } @@ -312,11 +329,20 @@ func (self *LightChain) Rollback(chain []common.Hash) { self.mu.Lock() defer self.mu.Unlock() + var rollbackHead *types.Header + for i := len(chain) - 1; i >= 0; i-- { hash := chain[i] if head := self.hc.CurrentHeader(); head.Hash() == hash { - self.hc.SetCurrentHeader(self.GetHeader(head.ParentHash, head.Number.Uint64()-1)) + rollbackHead = self.GetHeader(head.ParentHash, head.Number.Uint64()-1) + self.hc.SetCurrentHeader(rollbackHead) + } + } + + if rollbackHead != nil { + for _, cp := range self.chainProcessors { + cp.NewHead(rollbackHead.Number.Uint64(), true) } } } @@ -367,7 +393,15 @@ func (self *LightChain) InsertHeaderChain(chain []*types.Header, checkFreq int) self.mu.Lock() defer self.mu.Unlock() - status, err := self.hc.WriteHeader(header) + status, err := self.hc.WriteHeader(header, func(head *types.Header) { + for _, cp := range self.chainProcessors { + cp.NewHead(head.Number.Uint64(), true) + } + }) + + for _, cp := range self.chainProcessors { + cp.NewHead(header.Number.Uint64(), false) + } switch status { case core.CanonStatTy: From 712b17a01909f3e99ac1e36efd86a3100a5efb31 Mon Sep 17 00:00:00 2001 From: Zsolt Felfoldi Date: Fri, 5 May 2017 21:25:06 +0200 Subject: [PATCH 02/11] core: added updateMsg to ChainSectionProcessorBackend interface --- core/chain_processor.go | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/core/chain_processor.go b/core/chain_processor.go index 7112c3047c..28335001f6 100644 --- a/core/chain_processor.go +++ b/core/chain_processor.go @@ -59,6 +59,7 @@ type ChainSectionProcessorBackend interface { Process(idx uint64) bool GetStored() uint64 SetStored(count uint64) + UpdateMsg(done, all uint64) } // NewChainSectionProcessor creates a new ChainSectionProcessor @@ -80,6 +81,7 @@ func (csp *ChainSectionProcessor) updateLoop() { tryUpdate := make(chan struct{}, 1) updating := false var targetCnt uint64 + updateMsg := false for { select { @@ -93,6 +95,10 @@ func (csp *ChainSectionProcessor) updateLoop() { case <-tryUpdate: csp.lock.Lock() if targetCnt > csp.stored { + if !updateMsg && targetCnt > csp.stored+1 { + updateMsg = true + csp.backend.UpdateMsg(csp.stored, targetCnt) + } csp.calcValid = true csp.calcIdx = csp.stored @@ -103,12 +109,16 @@ func (csp *ChainSectionProcessor) updateLoop() { if ok && csp.calcValid { csp.stored = csp.calcIdx + 1 csp.backend.SetStored(csp.stored) - + if updateMsg { + csp.backend.UpdateMsg(csp.stored, targetCnt) + if csp.stored >= targetCnt { + updateMsg = false + } + } csp.lastForwarded = csp.stored*csp.sectionSize - 1 for _, cp := range csp.childProcessors { cp.NewHead(csp.lastForwarded, false) } - } csp.calcValid = false } From f421827f71a1ac470913b918e5f25f55409dcedb Mon Sep 17 00:00:00 2001 From: Zsolt Felfoldi Date: Fri, 5 May 2017 22:08:28 +0200 Subject: [PATCH 03/11] core: added comments and renamed variables in ChainSectionProcessor --- core/chain_processor.go | 40 +++++++++++++++++++++++----------------- 1 file changed, 23 insertions(+), 17 deletions(-) diff --git a/core/chain_processor.go b/core/chain_processor.go index 28335001f6..9008a7d5d3 100644 --- a/core/chain_processor.go +++ b/core/chain_processor.go @@ -26,7 +26,8 @@ import ( // using the canonical chain as an input. Its callback function NewHead is called every // time a new head is added to the chain or it gets rolled back. The callback function // should never block because it is called under the chain's mutex lock so that the -// structures can stay consistent with the canonical chain. +// structures can stay consistent with the canonical chain. It should also not call +// any chain functions that use this mutex because that would cause a deadlock. // The same interface can be used for chaining processors (one using the output of the // other). type ChainProcessor interface { @@ -42,7 +43,7 @@ type ChainSectionProcessor struct { backend ChainSectionProcessorBackend sectionSize, confirmReq uint64 stop chan struct{} - updateChn chan uint64 + updateCh chan uint64 lock sync.Mutex calcValid bool procWait time.Duration @@ -56,13 +57,18 @@ type ChainSectionProcessor struct { // finish. If the chain gets rolled back while Process is running, the results // are considered invalid and SetStored is not called. type ChainSectionProcessorBackend interface { - Process(idx uint64) bool - GetStored() uint64 - SetStored(count uint64) - UpdateMsg(done, all uint64) + Process(idx uint64) bool // do the processing of section idx but do not mark it as valid yet; return false if processing failed + GetStored() uint64 // return the number of sections processed, stored and marked as valid + SetStored(count uint64) // set the number of stored and valid processed sections (called after Process returned true if no reorg happened in the meantime) + UpdateMsg(done, all uint64) // print a progress update message if necessary (only called when multiple sections need to be processed) } // NewChainSectionProcessor creates a new ChainSectionProcessor +// backend: an implementation of ChainSectionProcessorBackend +// sectionSize: the size of processable sections +// confirmReq: required number of confirmation blocks before a new section is being processed +// procWait: waiting time between processing sections (simple way of limiting the resource usage of a db upgrade) +// stop: quit channel func NewChainSectionProcessor(backend ChainSectionProcessorBackend, sectionSize, confirmReq uint64, procWait time.Duration, stop chan struct{}) *ChainSectionProcessor { csp := &ChainSectionProcessor{ backend: backend, @@ -70,7 +76,7 @@ func NewChainSectionProcessor(backend ChainSectionProcessorBackend, sectionSize, confirmReq: confirmReq, stop: stop, procWait: procWait, - updateChn: make(chan uint64, 100), + updateCh: make(chan uint64, 100), stored: backend.GetStored(), } go csp.updateLoop() @@ -80,24 +86,24 @@ func NewChainSectionProcessor(backend ChainSectionProcessorBackend, sectionSize, func (csp *ChainSectionProcessor) updateLoop() { tryUpdate := make(chan struct{}, 1) updating := false - var targetCnt uint64 + var targetCount uint64 updateMsg := false for { select { case <-csp.stop: return - case targetCnt = <-csp.updateChn: + case targetCount = <-csp.updateCh: if !updating { updating = true tryUpdate <- struct{}{} } case <-tryUpdate: csp.lock.Lock() - if targetCnt > csp.stored { - if !updateMsg && targetCnt > csp.stored+1 { + if targetCount > csp.stored { + if !updateMsg && targetCount > csp.stored+1 { updateMsg = true - csp.backend.UpdateMsg(csp.stored, targetCnt) + csp.backend.UpdateMsg(csp.stored, targetCount) } csp.calcValid = true csp.calcIdx = csp.stored @@ -110,8 +116,8 @@ func (csp *ChainSectionProcessor) updateLoop() { csp.stored = csp.calcIdx + 1 csp.backend.SetStored(csp.stored) if updateMsg { - csp.backend.UpdateMsg(csp.stored, targetCnt) - if csp.stored >= targetCnt { + csp.backend.UpdateMsg(csp.stored, targetCount) + if csp.stored >= targetCount { updateMsg = false } } @@ -125,7 +131,7 @@ func (csp *ChainSectionProcessor) updateLoop() { stored := csp.stored csp.lock.Unlock() - if targetCnt > stored { + if targetCount > stored { go func() { time.Sleep(csp.procWait) tryUpdate <- struct{}{} @@ -152,7 +158,7 @@ func (csp *ChainSectionProcessor) NewHead(headNum uint64, rollback bool) { csp.backend.SetStored(csp.stored) select { case <-csp.stop: - case csp.updateChn <- firstChanged: + case csp.updateCh <- firstChanged: } } @@ -171,7 +177,7 @@ func (csp *ChainSectionProcessor) NewHead(headNum uint64, rollback bool) { go func() { select { case <-csp.stop: - case csp.updateChn <- newCount: + case csp.updateCh <- newCount: } }() } From e860278a96790342660da8dff153d8ccfbf5b480 Mon Sep 17 00:00:00 2001 From: Zsolt Felfoldi Date: Sun, 5 Mar 2017 17:23:01 +0100 Subject: [PATCH 04/11] core/bloombits, eth/filter: transformed bloom bitmap based log search --- core/bloombits/fetcher_test.go | 101 ++++++ core/bloombits/matcher.go | 575 ++++++++++++++++++++++++++++++ core/bloombits/matcher_test.go | 180 ++++++++++ core/bloombits/utils.go | 186 ++++++++++ core/database_util.go | 39 ++ core/types/bloom9.go | 14 + eth/api_backend.go | 13 + eth/backend.go | 6 +- eth/db_upgrade.go | 62 ++++ eth/filters/api.go | 36 +- eth/filters/filter.go | 134 ++++++- eth/filters/filter_system_test.go | 25 +- eth/filters/filter_test.go | 16 +- eth/handler.go | 12 +- les/api_backend.go | 5 + les/backend.go | 2 +- 16 files changed, 1354 insertions(+), 52 deletions(-) create mode 100644 core/bloombits/fetcher_test.go create mode 100644 core/bloombits/matcher.go create mode 100644 core/bloombits/matcher_test.go create mode 100644 core/bloombits/utils.go diff --git a/core/bloombits/fetcher_test.go b/core/bloombits/fetcher_test.go new file mode 100644 index 0000000000..3f436dfaa3 --- /dev/null +++ b/core/bloombits/fetcher_test.go @@ -0,0 +1,101 @@ +// Copyright 2017 The go-ethereum Authors +// This file is part of the go-ethereum library. +// +// The go-ethereum library is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// The go-ethereum library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with the go-ethereum library. If not, see . +package bloombits + +import ( + "bytes" + "encoding/binary" + "math/rand" + "sync" + "sync/atomic" + "testing" + "time" +) + +const testFetcherReqCnt = 50000 + +func fetcherTestVector(b uint, s uint64) BitVector { + r := make(BitVector, 10) + binary.BigEndian.PutUint16(r[0:2], uint16(b)) + binary.BigEndian.PutUint64(r[2:10], s) + return r +} + +func TestFetcher(t *testing.T) { + testFetcher(t, 1) +} + +func TestFetcherMultipleReaders(t *testing.T) { + testFetcher(t, 10) +} + +func testFetcher(t *testing.T, cnt int) { + f := &fetcher{ + reqMap: make(map[uint64]req), + } + distChn := make(chan distReq, channelCap) + stop := make(chan struct{}) + var reqCnt uint32 + + for i := 0; i < 10; i++ { + go func() { + for { + req, ok := <-distChn + if !ok { + return + } + time.Sleep(time.Duration(rand.Intn(1000000))) + atomic.AddUint32(&reqCnt, 1) + f.deliver([]uint64{req.sectionIdx}, []BitVector{fetcherTestVector(req.bitIdx, req.sectionIdx)}) + } + }() + } + + var wg, wg2 sync.WaitGroup + for cc := 0; cc < cnt; cc++ { + wg.Add(1) + in := make(chan uint64, channelCap) + out := f.fetch(in, distChn, stop, &wg2) + + time.Sleep(time.Millisecond * 100 * time.Duration(cc)) + go func() { + for i := uint64(0); i < testFetcherReqCnt; i++ { + in <- i + } + }() + + go func() { + for i := uint64(0); i < testFetcherReqCnt; i++ { + bv := <-out + if !bytes.Equal(bv, fetcherTestVector(0, i)) { + if len(bv) != 10 { + t.Errorf("Vector #%d length is %d, expected 10", i, len(bv)) + } else { + j := binary.BigEndian.Uint64(bv[2:10]) + t.Errorf("Expected vector #%d, fetched #%d", i, j) + } + } + } + wg.Done() + }() + } + + wg.Wait() + close(stop) + if reqCnt != testFetcherReqCnt { + t.Errorf("Request count mismatch: expected %v, got %v", testFetcherReqCnt, reqCnt) + } +} diff --git a/core/bloombits/matcher.go b/core/bloombits/matcher.go new file mode 100644 index 0000000000..abd5bd734b --- /dev/null +++ b/core/bloombits/matcher.go @@ -0,0 +1,575 @@ +// Copyright 2017 The go-ethereum Authors +// This file is part of the go-ethereum library. +// +// The go-ethereum library is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// The go-ethereum library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with the go-ethereum library. If not, see . +package bloombits + +import ( + "sync" + "time" + + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/types" +) + +const ( + maxRequestLength = 16 + channelCap = 100 +) + +// fetcher handles bit vector retrieval pipelines for a single bit index +type fetcher struct { + bitIdx, ii uint + reqMap map[uint64]req + reqLock sync.RWMutex +} + +type req struct { + data BitVector + queued bool + fetched chan struct{} +} + +type distReq struct { + bitIdx uint + sectionIdx uint64 +} + +// fetch creates a retrieval pipeline, receiving section indexes from sectionChn and returning the results +// in the same order through the returned channel. Multiple fetch instances of the same fetcher are allowed +// to run in parallel, in case the same bit index appears multiple times in the filter structure. Each section +// is requested only once, requests are sent to the request distributor (part of Matcher) through distChn. +func (f *fetcher) fetch(sectionChn chan uint64, distChn chan distReq, stop chan struct{}, wg *sync.WaitGroup) chan BitVector { + dataChn := make(chan BitVector, channelCap) + returnChn := make(chan uint64, channelCap) + wg.Add(2) + + go func() { + defer func() { + close(returnChn) + wg.Done() + }() + + for { + select { + case <-stop: + return + case idx, ok := <-sectionChn: + if !ok { + return + } + + req := false + f.reqLock.Lock() + r := f.reqMap[idx] + if r.data == nil { + req = !r.queued + r.queued = true + if r.fetched == nil { + r.fetched = make(chan struct{}) + } + f.reqMap[idx] = r + } + f.reqLock.Unlock() + if req { + distChn <- distReq{bitIdx: f.bitIdx, sectionIdx: idx} // success is guaranteed, distibuteRequests shuts down after fetch + } + select { + case <-stop: + return + case returnChn <- idx: + } + } + } + }() + + go func() { + defer func() { + close(dataChn) + wg.Done() + }() + + for { + select { + case <-stop: + return + case idx, ok := <-returnChn: + if !ok { + return + } + + f.reqLock.RLock() + r := f.reqMap[idx] + f.reqLock.RUnlock() + + if r.data == nil { + select { + case <-stop: + return + case <-r.fetched: + f.reqLock.RLock() + r = f.reqMap[idx] + f.reqLock.RUnlock() + } + } + select { + case <-stop: + return + case dataChn <- r.data: + } + } + } + }() + + return dataChn +} + +// deliver is called by the request distributor when a reply to a request has +// arrived +func (f *fetcher) deliver(sectionIdxList []uint64, data []BitVector) { + f.reqLock.Lock() + defer f.reqLock.Unlock() + + for i, idx := range sectionIdxList { + r := f.reqMap[idx] + if r.data != nil { + panic("BloomBits section data delivered twice") + } + r.data = data[i] + close(r.fetched) + f.reqMap[idx] = r + } +} + +// Matcher is a pipelined structure of fetchers and logic matchers which perform +// binary and/or operations on the bitstreams, finally creating a stream of potential matches. +type Matcher struct { + addresses []types.BloomIndexList + topics [][]types.BloomIndexList + fetchers map[uint]*fetcher + sectionSize uint64 + + distChn chan distReq + reqs map[uint][]uint64 + getNextReqChn chan chan nextRequests + wg, distWg sync.WaitGroup +} + +// NewMatcher creates a new Matcher instance +func NewMatcher(sectionSize uint64) *Matcher { + return &Matcher{fetchers: make(map[uint]*fetcher), reqs: make(map[uint][]uint64), distChn: make(chan distReq, channelCap), sectionSize: sectionSize} +} + +// SetAddresses matches only logs that are generated from addresses that are included +// in the given addresses. +func (m *Matcher) SetAddresses(addr []common.Address) { + m.addresses = make([]types.BloomIndexList, len(addr)) + for i, b := range addr { + m.addresses[i] = types.BloomIndexes(b.Bytes()) + } + + for _, idxs := range m.addresses { + for _, idx := range idxs { + m.newFetcher(idx) + } + } +} + +// SetTopics matches only logs that have topics matching the given topics. +func (m *Matcher) SetTopics(topics [][]common.Hash) { + m.topics = nil +loop: + for _, topicList := range topics { + t := make([]types.BloomIndexList, len(topicList)) + for i, b := range topicList { + if (b == common.Hash{}) { + continue loop + } + t[i] = types.BloomIndexes(b.Bytes()) + } + m.topics = append(m.topics, t) + } + + for _, idxss := range m.topics { + for _, idxs := range idxss { + for _, idx := range idxs { + m.newFetcher(idx) + } + } + } +} + +// match creates a daisy-chain of sub-matchers, one for the address set and one for each topic set, each +// sub-matcher receiving a section only if the previous ones have all found a potential match in one of +// the blocks of the section, then binary and-ing its own matches and forwaring the result to the next one +func (m *Matcher) match(sectionChn chan uint64, stop chan struct{}) (chan uint64, chan BitVector) { + subIdx := m.topics + if len(m.addresses) > 0 { + subIdx = append([][]types.BloomIndexList{m.addresses}, subIdx...) + } + //fmt.Println("idx", subIdx) + m.getNextReqChn = make(chan chan nextRequests) // should be a blocking channel + m.distributeRequests(stop) + + s := sectionChn + var bv chan BitVector + for _, idx := range subIdx { + s, bv = m.subMatch(s, bv, idx, stop) + } + return s, bv +} + +// newFetcher adds a fetcher for the given bit index if it has not existed before +func (m *Matcher) newFetcher(idx uint) { + if _, ok := m.fetchers[idx]; ok { + return + } + f := &fetcher{ + bitIdx: idx, + reqMap: make(map[uint64]req), + } + m.fetchers[idx] = f +} + +// subMatch creates a sub-matcher that filters for a set of addresses or topics, binary or-s those matches, then +// binary and-s the result to the daisy-chain input (sectionChn/andVectorChn) and forwards it to the daisy-chain output. +// The matches of each address/topic are calculated by fetching the given sections of the three bloom bit indexes belonging to +// that address/topic, and binary and-ing those vectors together. +func (m *Matcher) subMatch(sectionChn chan uint64, andVectorChn chan BitVector, idxs []types.BloomIndexList, stop chan struct{}) (chan uint64, chan BitVector) { + // set up fetchers + fetchIdx := make([][3]chan uint64, len(idxs)) + fetchData := make([][3]chan BitVector, len(idxs)) + for i, idx := range idxs { + for j, ii := range idx { + fetchIdx[i][j] = make(chan uint64, channelCap) + fetchData[i][j] = m.fetchers[ii].fetch(fetchIdx[i][j], m.distChn, stop, &m.wg) + } + } + + processChn := make(chan uint64, channelCap) + resIdxChn := make(chan uint64, channelCap) + resDataChn := make(chan BitVector, channelCap) + + m.wg.Add(2) + // goroutine for starting retrievals + go func() { + defer m.wg.Done() + + for { + select { + case <-stop: + return + case s, ok := <-sectionChn: + if !ok { + close(processChn) + for _, ff := range fetchIdx { + for _, f := range ff { + close(f) + } + } + return + } + + select { + case <-stop: + return + case processChn <- s: + } + for _, ff := range fetchIdx { + for _, f := range ff { + select { + case <-stop: + return + case f <- s: + } + } + } + } + } + }() + + // goroutine for processing retrieved data + go func() { + defer m.wg.Done() + + for { + select { + case <-stop: + return + case s, ok := <-processChn: + if !ok { + close(resIdxChn) + close(resDataChn) + return + } + + var orVector BitVector + for _, ff := range fetchData { + var andVector BitVector + for _, f := range ff { + var data BitVector + select { + case <-stop: + return + case data = <-f: + } + if andVector == nil { + andVector = bvCopy(data, int(m.sectionSize)) + } else { + bvAnd(andVector, data) + } + } + if orVector == nil { + orVector = andVector + } else { + bvOr(orVector, andVector) + } + } + + if orVector == nil { + orVector = bvZero(int(m.sectionSize)) + } + if andVectorChn != nil { + select { + case <-stop: + return + case andVector := <-andVectorChn: + bvAnd(orVector, andVector) + } + } + if bvIsNonZero(orVector) { + select { + case <-stop: + return + case resIdxChn <- s: + } + select { + case <-stop: + return + case resDataChn <- orVector: + } + } + } + } + }() + + return resIdxChn, resDataChn +} + +// GetMatches returns a stream of bloom matches in a given range of blocks. +// It returns a results channel immediately and stops if the stop channel is closed or +// there are no more matches in the range (in which case the results channel is closed). +// GetMatches can be called multiple times for different ranges, in which case already +// delivered bit vectors are not requested again. +func (m *Matcher) GetMatches(start, end uint64, stop chan struct{}) chan uint64 { + m.distWg.Wait() + + sectionChn := make(chan uint64, channelCap) + resultsChn := make(chan uint64, channelCap) + + s, bv := m.match(sectionChn, stop) + + startSection := start / m.sectionSize + endSection := end / m.sectionSize + + m.wg.Add(2) + go func() { + defer func() { + close(sectionChn) + m.wg.Done() + }() + + for i := startSection; i <= endSection; i++ { + select { + case sectionChn <- i: + case <-stop: + return + } + } + }() + + go func() { + defer func() { + close(resultsChn) + m.wg.Done() + }() + + for { + select { + case idx, ok := <-s: + if !ok { + return + } + var match BitVector + select { + case <-stop: + return + case match = <-bv: + } + sectionStart := idx * m.sectionSize + s := sectionStart + if start > s { + s = start + } + e := sectionStart + m.sectionSize - 1 + if end < e { + e = end + } + for i := s; i <= e; i++ { + b := match[(i-sectionStart)/8] + bit := 7 - i%8 + if b != 0 { + if b&(1< queue[i] { + i++ + } + queue = append(queue, 0) + copy(queue[i+1:], queue[i:len(queue)-1]) + queue[i] = r.sectionIdx + + m.reqs[r.bitIdx] = queue + reqCnt++ + } + + storeReqs := func(r distReq) { + storeReq(r) + timeout := time.After(time.Microsecond) + for { + select { + case <-timeout: + return + case r := <-m.distChn: + storeReq(r) + case <-stopDist: + return + } + } + } + + for { + if reqCnt == 0 { + select { + case r := <-m.distChn: + storeReqs(r) + case <-stopDist: + return + } + } else { + select { + case r := <-m.distChn: + storeReqs(r) + case <-stopDist: + return + case c := <-m.getNextReqChn: + var ( + found bool + bestBit uint + bestSection uint64 + ) + + for bitIdx, queue := range m.reqs { + if len(queue) > 0 && (!found || queue[0] < bestSection) { + found = true + bestBit = bitIdx + bestSection = queue[0] + } + } + if !found { + panic(nil) + } + + bestQueue := m.reqs[bestBit] + cnt := len(bestQueue) + if cnt > maxRequestLength { + cnt = maxRequestLength + } + res := nextRequests{bestBit, bestQueue[:cnt]} + m.reqs[bestBit] = bestQueue[cnt:] + reqCnt -= cnt + + c <- res + } + } + } + }() +} + +// NextRequest asks for a request from the request distributor, returns immediately if there +// was a queued one, otherwise waits until the distributor forwards one of the requests sent +// by one of the fetchers. +func (m *Matcher) NextRequest(stop chan struct{}) (bitIdx uint, sectionIdxList []uint64) { + c := make(chan nextRequests) + select { + case m.getNextReqChn <- c: + r := <-c + return r.bitIdx, r.sectionIdxList + case <-stop: + return 0, nil + } +} + +// Deliver delivers a bit vector to the appropriate fetcher. +// It is possible to deliver data even after GetMatches has been stopped. Once a vector has been +// requested, the next call to GetMatches will keep waiting for delivery. +func (m *Matcher) Deliver(bitIdx uint, sectionIdxList []uint64, data []BitVector) { + m.fetchers[bitIdx].deliver(sectionIdxList, data) +} diff --git a/core/bloombits/matcher_test.go b/core/bloombits/matcher_test.go new file mode 100644 index 0000000000..21d617b840 --- /dev/null +++ b/core/bloombits/matcher_test.go @@ -0,0 +1,180 @@ +// Copyright 2017 The go-ethereum Authors +// This file is part of the go-ethereum library. +// +// The go-ethereum library is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// The go-ethereum library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with the go-ethereum library. If not, see . +package bloombits + +import ( + "math/rand" + "sync/atomic" + "testing" + + "github.com/ethereum/go-ethereum/core/types" +) + +const testSectionSize = 4096 + +func matcherTestVector(b uint, s uint64) BitVector { + r := make(BitVector, testSectionSize/8) + for i, _ := range r { + var bb byte + for bit := 0; bit < 8; bit++ { + blockIdx := s*testSectionSize + uint64(i*8+bit) + bb += bb + if (blockIdx % uint64(b)) == 0 { + bb++ + } + } + r[i] = bb + } + return r +} + +func expMatch1(idxs types.BloomIndexList, i uint64) bool { + for _, ii := range idxs { + if (i % uint64(ii)) != 0 { + return false + } + } + return true +} + +func expMatch2(idxs []types.BloomIndexList, i uint64) bool { + for _, ii := range idxs { + if expMatch1(ii, i) { + return true + } + } + return false +} + +func expMatch3(idxs [][]types.BloomIndexList, i uint64) bool { + for _, ii := range idxs { + if !expMatch2(ii, i) { + return false + } + } + return true +} + +func testServeMatcher(m *Matcher, stop chan struct{}, cnt *uint32) { + // serve matcher with test vectors + for i := 0; i < 10; i++ { + go func() { + for { + select { + case <-stop: + return + default: + } + b, s := m.NextRequest(stop) + if s == nil { + return + } + res := make([]BitVector, len(s)) + for i, ss := range s { + res[i] = matcherTestVector(b, ss) + atomic.AddUint32(cnt, 1) + } + m.Deliver(b, s, res) + } + }() + } +} + +func testMatcher(t *testing.T, idxs [][]types.BloomIndexList, cnt uint64, stopOnMatches bool, expCnt uint32) uint32 { + m := NewMatcher(testSectionSize) + + for _, idxss := range idxs { + for _, idxs := range idxss { + for _, idx := range idxs { + m.newFetcher(idx) + } + } + } + + m.addresses = idxs[0] + m.topics = idxs[1:] + var reqCnt uint32 + + stop := make(chan struct{}) + chn := m.GetMatches(0, cnt-1, stop) + testServeMatcher(m, stop, &reqCnt) + + for i := uint64(0); i < cnt; i++ { + if expMatch3(idxs, i) { + match, ok := <-chn + if !ok { + t.Errorf("Error matching idxs = %v count = %v stopOnMatches = %v: expected #%v, results channel closed", idxs, cnt, stopOnMatches, i) + return 0 + } + if match != i { + t.Errorf("Error matching idxs = %v count = %v stopOnMatches = %v: expected #%v, got #%v", idxs, cnt, stopOnMatches, i, match) + } + if stopOnMatches { + close(stop) + stop = make(chan struct{}) + chn = m.GetMatches(i+1, cnt-1, stop) + testServeMatcher(m, stop, &reqCnt) + } + } + } + match, ok := <-chn + if ok { + t.Errorf("Error matching idxs = %v count = %v stopOnMatches = %v: expected closed channel, got #%v", idxs, cnt, stopOnMatches, match) + } + close(stop) + + if expCnt != 0 && expCnt != reqCnt { + t.Errorf("Error matching idxs = %v count = %v stopOnMatches = %v: request count mismatch, expected #%v, got #%v", idxs, cnt, stopOnMatches, expCnt, reqCnt) + } + + return reqCnt +} + +func testRandomIdxs(l []int, max int) [][]types.BloomIndexList { + res := make([][]types.BloomIndexList, len(l)) + for i, ll := range l { + res[i] = make([]types.BloomIndexList, ll) + for j, _ := range res[i] { + for k, _ := range res[i][j] { + res[i][j][k] = uint(rand.Intn(max-1) + 2) + } + } + } + return res +} + +func TestMatcher(t *testing.T) { + testMatcher(t, [][]types.BloomIndexList{{{10, 20, 30}}}, 1000000, false, 735) + testMatcher(t, [][]types.BloomIndexList{{{32, 3125, 100}}, {{40, 50, 10}}}, 1000000, false, 768) + testMatcher(t, [][]types.BloomIndexList{{{4, 8, 11}, {7, 8, 17}}, {{9, 9, 12}, {15, 20, 13}}, {{18, 15, 15}, {12, 10, 4}}}, 100000, false, 300) +} + +func TestMatcherStopOnMatches(t *testing.T) { + testMatcher(t, [][]types.BloomIndexList{{{10, 20, 30}}}, 1000000, true, 735) + testMatcher(t, [][]types.BloomIndexList{{{4, 8, 11}, {7, 8, 17}}, {{9, 9, 12}, {15, 20, 13}}, {{18, 15, 15}, {12, 10, 4}}}, 100000, true, 300) +} + +func TestMatcherRandom(t *testing.T) { + for i := 0; i < 20; i++ { + testMatcher(t, testRandomIdxs([]int{1}, 50), 1000000, false, 0) + testMatcher(t, testRandomIdxs([]int{3}, 50), 1000000, false, 0) + testMatcher(t, testRandomIdxs([]int{2, 2, 2}, 20), 1000000, false, 0) + testMatcher(t, testRandomIdxs([]int{5, 5, 5}, 50), 1000000, false, 0) + idxs := testRandomIdxs([]int{2, 2, 2}, 20) + reqCnt := testMatcher(t, idxs, 100000, false, 0) + testMatcher(t, idxs, 100000, true, reqCnt) + } +} diff --git a/core/bloombits/utils.go b/core/bloombits/utils.go new file mode 100644 index 0000000000..166a7d6039 --- /dev/null +++ b/core/bloombits/utils.go @@ -0,0 +1,186 @@ +// Copyright 2017 The go-ethereum Authors +// This file is part of the go-ethereum library. +// +// The go-ethereum library is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// The go-ethereum library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with the go-ethereum library. If not, see . +package bloombits + +import ( + "github.com/ethereum/go-ethereum/core/types" +) + +type ( + BitVector []byte + CompVector []byte +) + +// bvAnd binary ANDs b to a +func bvAnd(a, b BitVector) { + for i, bb := range b { + a[i] &= bb + } +} + +// bvOr binary ORs b to a +func bvOr(a, b BitVector) { + for i, bb := range b { + a[i] |= bb + } +} + +// bvZero returns an all-zero bit vector +func bvZero(sectionSize int) BitVector { + return make(BitVector, sectionSize/8) +} + +// bvCopy creates a copy of the given bit vector +// If the source vector is nil, returns an all-zero bit vector +func bvCopy(a BitVector, sectionSize int) BitVector { + c := make(BitVector, sectionSize/8) + copy(c, a) + return c +} + +// bvIsNonZero returns true if the bit vector has at least one "1" bit +func bvIsNonZero(a BitVector) bool { + for _, b := range a { + if b != 0 { + return true + } + } + return false +} + +// CompressBloomBits compresses a bit vector for storage/network transfer purposes +func CompressBloomBits(bits BitVector, sectionSize int) CompVector { + if len(bits) != sectionSize/8 { + panic(nil) + } + c := compressBits(bits) + if len(c) >= sectionSize/8 { + // make a copy so that output is always detached from input + return CompVector(bvCopy(bits, sectionSize)) + } + return CompVector(c) +} + +func compressBits(bits []byte) []byte { + l := len(bits) + ll := l / 8 + if ll == 0 { + ll = 1 + } + b := make([]byte, ll) + c := make([]byte, l) + cl := 0 + for i, v := range bits { + if v != 0 { + c[cl] = v + cl++ + b[i/8] |= 1 << byte(7-i%8) + } + } + if cl == 0 { + return nil + } + if ll > 1 { + b = compressBits(b) + } + return append(b, c[0:cl]...) +} + +// DeompressBloomBits decompresses a bit vector +func DecompressBloomBits(bits CompVector, sectionSize int) BitVector { + if len(bits) == sectionSize/8 { + // make a copy so that output is always detached from input + return bvCopy(BitVector(bits), sectionSize) + } + dc, ofs := decompressBits(bits, sectionSize/8) + if ofs != len(bits) { + panic(nil) + } + return dc +} + +func decompressBits(bits []byte, targetLen int) ([]byte, int) { + lb := len(bits) + dc := make([]byte, targetLen) + if lb == 0 { + return dc, 0 + } + + l := targetLen / 8 + var ( + b []byte + ofs int + ) + if l <= 1 { + b = bits[0:1] + ofs = 1 + } else { + b, ofs = decompressBits(bits, l) + } + for i, _ := range dc { + if b[i/8]&(1<= b.sectionSize { + panic("too many header blooms added") + } + + byteIdx := b.bitIdx / 8 + bitMask := byte(1) << byte(7-b.bitIdx%8) + for bloomBitIdx, _ := range b.blooms { + bloomByteIdx := BloomLength/8 - 1 - bloomBitIdx/8 + bloomBitMask := byte(1) << byte(bloomBitIdx%8) + if (bloom[bloomByteIdx] & bloomBitMask) != 0 { + b.blooms[bloomBitIdx][byteIdx] |= bitMask + } + } + b.bitIdx++ +} + +// GetBitVector returns the bit vector belonging to the given bit index after header blooms have been added +func (b *BloomBitsCreator) GetBitVector(idx uint) BitVector { + if b.bitIdx != b.sectionSize { + panic("not enough header blooms added") + } + + return BitVector(b.blooms[idx][:]) +} diff --git a/core/database_util.go b/core/database_util.go index bcd99be5fb..affe6e4130 100644 --- a/core/database_util.go +++ b/core/database_util.go @@ -26,6 +26,7 @@ import ( "sync" "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/bloombits" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/log" @@ -70,6 +71,9 @@ var ( preimageCounter = metrics.NewCounter("db/preimage/total") preimageHitCounter = metrics.NewCounter("db/preimage/hits") + + bloomBitsPrefix = []byte("bloomBits-") + bloomBitsAvailKey = []byte("bloomBitsAvailable") ) // encodeBlockNumber encodes a block number as big endian uint64 @@ -675,3 +679,38 @@ func FindCommonAncestor(db ethdb.Database, a, b *types.Header) *types.Header { } return a } + +// GetBloomBits reads the compressed bloomBits vector belonging to the given section and bit index from the db +func GetBloomBits(db ethdb.Database, bitIdx, sectionIdx uint64) (bloombits.CompVector, error) { + var encKey [10]byte + binary.BigEndian.PutUint16(encKey[0:2], uint16(bitIdx)) + binary.BigEndian.PutUint64(encKey[2:10], sectionIdx) + key := append(bloomBitsPrefix, encKey[:]...) + bloomBits, err := db.Get(key) + return bloombits.CompVector(bloomBits), err +} + +// StoreBloomBits writes the compressed bloomBits vector belonging to the given section and bit index to the db +func StoreBloomBits(db ethdb.Database, bitIdx, sectionIdx uint64, bloomBits bloombits.CompVector) { + var encKey [10]byte + binary.BigEndian.PutUint16(encKey[0:2], uint16(bitIdx)) + binary.BigEndian.PutUint64(encKey[2:10], sectionIdx) + key := append(bloomBitsPrefix, encKey[:]...) + db.Put(key, bloomBits) +} + +// GetBloomBitsAvailable reads the number of available bloomBits sections from the db +func GetBloomBitsAvailable(db ethdb.Database) uint64 { + data, _ := db.Get(bloomBitsAvailKey) + if len(data) == 8 { + return binary.BigEndian.Uint64(data[:]) + } + return 0 +} + +// StoreBloomBitsAvailable writes the number of available bloomBits sections to the db +func StoreBloomBitsAvailable(db ethdb.Database, cnt uint64) { + var data [8]byte + binary.BigEndian.PutUint64(data[:], cnt) + db.Put(bloomBitsAvailKey, data[:]) +} diff --git a/core/types/bloom9.go b/core/types/bloom9.go index 60aacc3016..bdc6e60e79 100644 --- a/core/types/bloom9.go +++ b/core/types/bloom9.go @@ -106,6 +106,20 @@ func LogsBloom(logs []*Log) *big.Int { return bin } +type BloomIndexList [3]uint + +// BloomIndexes returns the bloom filter bit indexes belonging to the given key +func BloomIndexes(b []byte) BloomIndexList { + b = crypto.Keccak256(b[:]) + + var r [3]uint + for i, _ := range r { + r[i] = (uint(b[i+i+1]) + (uint(b[i+i]) << 8)) & 2047 + } + + return r +} + func bloom9(b []byte) *big.Int { b = crypto.Keccak256(b[:]) diff --git a/eth/api_backend.go b/eth/api_backend.go index fe108d2720..19c8ce271d 100644 --- a/eth/api_backend.go +++ b/eth/api_backend.go @@ -24,6 +24,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/math" "github.com/ethereum/go-ethereum/core" + "github.com/ethereum/go-ethereum/core/bloombits" "github.com/ethereum/go-ethereum/core/state" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/core/vm" @@ -201,6 +202,18 @@ func (b *EthApiBackend) AccountManager() *accounts.Manager { return b.eth.AccountManager() } +func (b *EthApiBackend) GetBloomBits(ctx context.Context, bitIdx uint64, sectionIdxList []uint64) ([]bloombits.CompVector, error) { + results := make([]bloombits.CompVector, len(sectionIdxList)) + var err error + for i, idx := range sectionIdxList { + results[i], err = core.GetBloomBits(b.eth.chainDb, bitIdx, idx) + if err != nil { + return nil, err + } + } + return results, nil +} + type EthApiState struct { state *state.StateDB } diff --git a/eth/backend.go b/eth/backend.go index f864b1d88b..7dd9eeddd3 100644 --- a/eth/backend.go +++ b/eth/backend.go @@ -239,6 +239,10 @@ func (s *Ethereum) APIs() []rpc.API { // Append any APIs exposed explicitly by the consensus engine apis = append(apis, s.engine.APIs(s.BlockChain())...) + var bbSection uint64 + if useBloomBits { + bbSection = bloomBitsSection + } // Append all the local APIs and return return append(apis, []rpc.API{ { @@ -264,7 +268,7 @@ func (s *Ethereum) APIs() []rpc.API { }, { Namespace: "eth", Version: "1.0", - Service: filters.NewPublicFilterAPI(s.ApiBackend, false), + Service: filters.NewPublicFilterAPI(s.ApiBackend, false, bbSection), Public: true, }, { Namespace: "admin", diff --git a/eth/db_upgrade.go b/eth/db_upgrade.go index 82cdd7e55e..2d63096df4 100644 --- a/eth/db_upgrade.go +++ b/eth/db_upgrade.go @@ -26,6 +26,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core" + "github.com/ethereum/go-ethereum/core/bloombits" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/log" @@ -294,3 +295,64 @@ func addMipmapBloomBins(db ethdb.Database) (err error) { log.Info("Bloom-bin upgrade completed", "elapsed", common.PrettyDuration(time.Since(tstart))) return nil } + +// BloomBitsProcessorBackend implements ChainSectionProcessorBackend +type BloomBitsProcessorBackend struct { + db ethdb.Database + lastCount, lastProg uint64 +} + +// number of confirmation blocks before a section is considered probably final and its bloom bits are calculated +const bloomBitsConfirmations = 512 + +// NewBloomBitsProcessor returns a chain processor that generates bloom bits data for the canonical chain +func NewBloomBitsProcessor(db ethdb.Database, stop chan struct{}) *core.ChainSectionProcessor { + backend := &BloomBitsProcessorBackend{db: db, lastCount: core.GetBloomBitsAvailable(db)} + return core.NewChainSectionProcessor(backend, bloomBitsSection, bloomBitsConfirmations, time.Millisecond*100, stop) +} + +// Process calculates bloom bits for a given section +func (b *BloomBitsProcessorBackend) Process(sectionIdx uint64) bool { + bc := bloombits.NewBloomBitsCreator(bloomBitsSection) + var header *types.Header + for i := sectionIdx * bloomBitsSection; i < (sectionIdx+1)*bloomBitsSection; i++ { + hash := core.GetCanonicalHash(b.db, i) + header = core.GetHeader(b.db, hash, i) + if header == nil { + log.Error("Error creating bloomBits data", "section", sectionIdx, "missing header", i) + return false + } + bc.AddHeaderBloom(header.Bloom) + } + + for i := 0; i < bloombits.BloomLength; i++ { + core.StoreBloomBits(b.db, uint64(i), sectionIdx, bloombits.CompressBloomBits(bc.GetBitVector(uint(i)), bloomBitsSection)) + } + + return true +} + +// SetStored sets the number of stored sections (last valid section is count-1) +func (b *BloomBitsProcessorBackend) SetStored(count uint64) { + if count > b.lastCount { + log.Debug("Stored bloomBits data", "count", count) + } else { + log.Debug("Rolled back bloomBits data", "count", count) + } + b.lastCount = count + core.StoreBloomBitsAvailable(b.db, count) +} + +// GetStored retrieves the number of stored sections (last valid section is count-1) +func (b *BloomBitsProcessorBackend) GetStored() uint64 { + return core.GetBloomBitsAvailable(b.db) +} + +// UpdateMsg prints an update message after each 5% of progress +func (b *BloomBitsProcessorBackend) UpdateMsg(done, all uint64) { + prog := done * 20 / all + if done == 0 || prog > b.lastProg { + b.lastProg = prog + log.Info("Updating quick bloom filter database", "%", prog*5) + } +} diff --git a/eth/filters/api.go b/eth/filters/api.go index 61647a5d07..7874ebac69 100644 --- a/eth/filters/api.go +++ b/eth/filters/api.go @@ -51,25 +51,27 @@ type filter struct { // PublicFilterAPI offers support to create and manage filters. This will allow external clients to retrieve various // information related to the Ethereum protocol such als blocks, transactions and logs. type PublicFilterAPI struct { - backend Backend - useMipMap bool - mux *event.TypeMux - quit chan struct{} - chainDb ethdb.Database - events *EventSystem - filtersMu sync.Mutex - filters map[rpc.ID]*filter + backend Backend + useMipMap bool + bloomBitsSection uint64 + mux *event.TypeMux + quit chan struct{} + chainDb ethdb.Database + events *EventSystem + filtersMu sync.Mutex + filters map[rpc.ID]*filter } // NewPublicFilterAPI returns a new PublicFilterAPI instance. -func NewPublicFilterAPI(backend Backend, lightMode bool) *PublicFilterAPI { +func NewPublicFilterAPI(backend Backend, lightMode bool, bloomBitsSection uint64) *PublicFilterAPI { api := &PublicFilterAPI{ - backend: backend, - useMipMap: !lightMode, - mux: backend.EventMux(), - chainDb: backend.ChainDb(), - events: NewEventSystem(backend.EventMux(), backend, lightMode), - filters: make(map[rpc.ID]*filter), + backend: backend, + useMipMap: bloomBitsSection == 0, + bloomBitsSection: bloomBitsSection, + mux: backend.EventMux(), + chainDb: backend.ChainDb(), + events: NewEventSystem(backend.EventMux(), backend, lightMode), + filters: make(map[rpc.ID]*filter), } go api.timeoutLoop() @@ -333,7 +335,7 @@ func (api *PublicFilterAPI) GetLogs(ctx context.Context, crit FilterCriteria) ([ crit.ToBlock = big.NewInt(rpc.LatestBlockNumber.Int64()) } - filter := New(api.backend, api.useMipMap) + filter := New(api.backend, api.useMipMap, api.bloomBitsSection) filter.SetBeginBlock(crit.FromBlock.Int64()) filter.SetEndBlock(crit.ToBlock.Int64()) filter.SetAddresses(crit.Addresses) @@ -373,7 +375,7 @@ func (api *PublicFilterAPI) GetFilterLogs(ctx context.Context, id rpc.ID) ([]*ty return nil, fmt.Errorf("filter not found") } - filter := New(api.backend, api.useMipMap) + filter := New(api.backend, api.useMipMap, api.bloomBitsSection) if f.crit.FromBlock != nil { filter.SetBeginBlock(f.crit.FromBlock.Int64()) } else { diff --git a/eth/filters/filter.go b/eth/filters/filter.go index 0a0b81224e..c17619abeb 100644 --- a/eth/filters/filter.go +++ b/eth/filters/filter.go @@ -24,6 +24,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core" + "github.com/ethereum/go-ethereum/core/bloombits" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/event" @@ -35,12 +36,14 @@ type Backend interface { EventMux() *event.TypeMux HeaderByNumber(ctx context.Context, blockNr rpc.BlockNumber) (*types.Header, error) GetReceipts(ctx context.Context, blockHash common.Hash) (types.Receipts, error) + GetBloomBits(ctx context.Context, bitIdx uint64, sectionIdxList []uint64) ([]bloombits.CompVector, error) } // Filter can be used to retrieve and filter logs. type Filter struct { - backend Backend - useMipMap bool + backend Backend + useMipMap, useBloomBits bool + bloomBitsSection uint64 created time.Time @@ -48,17 +51,22 @@ type Filter struct { begin, end int64 addresses []common.Address topics [][]common.Hash + + matcher *bloombits.Matcher } // New creates a new filter which uses a bloom filter on blocks to figure out whether // a particular block is interesting or not. // MipMaps allow past blocks to be searched much more efficiently, but are not available // to light clients. -func New(backend Backend, useMipMap bool) *Filter { +func New(backend Backend, useMipMap bool, bloomBitsSection uint64) *Filter { return &Filter{ - backend: backend, - useMipMap: useMipMap, - db: backend.ChainDb(), + backend: backend, + useMipMap: useMipMap, + useBloomBits: bloomBitsSection != 0, + bloomBitsSection: bloomBitsSection, + db: backend.ChainDb(), + matcher: bloombits.NewMatcher(bloomBitsSection), } } @@ -78,11 +86,17 @@ func (f *Filter) SetEndBlock(end int64) { // in the given addresses. func (f *Filter) SetAddresses(addr []common.Address) { f.addresses = addr + if f.useBloomBits { + f.matcher.SetAddresses(addr) + } } // SetTopics matches only logs that have topics matching the given topics. func (f *Filter) SetTopics(topics [][]common.Hash) { f.topics = topics + if f.useBloomBits { + f.matcher.SetTopics(topics) + } } // FindOnce searches the blockchain for matching log entries, returning @@ -166,7 +180,100 @@ func (f *Filter) mipFind(start, end uint64, depth int) (logs []*types.Log, block return nil, end } +// serveMatcher serves the bloomBits matcher by fetching the requested vectors +// through the filter backend +func (f *Filter) serveMatcher(ctx context.Context, stop chan struct{}) chan error { + errChn := make(chan error) + for i := 0; i < 10; i++ { + go func(i int) { + for { + b, s := f.matcher.NextRequest(stop) + if s == nil { + return + } + data, err := f.backend.GetBloomBits(ctx, uint64(b), s) + if err != nil { + errChn <- err + return + } + decomp := make([]bloombits.BitVector, len(data)) + for i, d := range data { + decomp[i] = bloombits.DecompressBloomBits(bloombits.CompVector(d), int(f.bloomBitsSection)) + } + f.matcher.Deliver(b, s, decomp) + } + }(i) + } + + return errChn +} + func (f *Filter) getLogs(ctx context.Context, start, end uint64) (logs []*types.Log, blockNumber uint64, err error) { + + checkBlock := func(i uint64, header *types.Header) (logs []*types.Log, blockNumber uint64, err error) { + // Get the logs of the block + receipts, err := f.backend.GetReceipts(ctx, header.Hash()) + if err != nil { + return nil, end, err + } + var unfiltered []*types.Log + for _, receipt := range receipts { + unfiltered = append(unfiltered, ([]*types.Log)(receipt.Logs)...) + } + logs = filterLogs(unfiltered, nil, nil, f.addresses, f.topics) + if len(logs) > 0 { + return logs, i, nil + } + return nil, i, nil + } + + if f.useBloomBits { + haveBloomBitsBefore := core.GetBloomBitsAvailable(f.db) * f.bloomBitsSection + e := end + if haveBloomBitsBefore <= e { + e = haveBloomBitsBefore - 1 + } + + stop := make(chan struct{}) + defer close(stop) + //fmt.Println("GetMatches") + matches := f.matcher.GetMatches(start, e, stop) + errChn := f.serveMatcher(ctx, stop) + + loop: + for { + select { + case i, ok := <-matches: + if !ok { + break loop + } + + blockNumber := rpc.BlockNumber(i) + header, err := f.backend.HeaderByNumber(ctx, blockNumber) + if header == nil || err != nil { + return logs, end, err + } + + l, b, e := checkBlock(i, header) + + if l != nil || e != nil { + return l, b, e + } + case err := <-errChn: + return logs, end, err + case <-ctx.Done(): + return nil, end, ctx.Err() + } + } + + if end < haveBloomBitsBefore { + return logs, end, nil + } else { + start = haveBloomBitsBefore + } + } + + // search the rest with regular block-by-block bloom filtering for i := start; i <= end; i++ { blockNumber := rpc.BlockNumber(i) header, err := f.backend.HeaderByNumber(ctx, blockNumber) @@ -177,18 +284,9 @@ func (f *Filter) getLogs(ctx context.Context, start, end uint64) (logs []*types. // Use bloom filtering to see if this block is interesting given the // current parameters if f.bloomFilter(header.Bloom) { - // Get the logs of the block - receipts, err := f.backend.GetReceipts(ctx, header.Hash()) - if err != nil { - return nil, end, err - } - var unfiltered []*types.Log - for _, receipt := range receipts { - unfiltered = append(unfiltered, ([]*types.Log)(receipt.Logs)...) - } - logs = filterLogs(unfiltered, nil, nil, f.addresses, f.topics) - if len(logs) > 0 { - return logs, uint64(blockNumber), nil + l, b, e := checkBlock(i, header) + if l != nil || e != nil { + return l, b, e } } } diff --git a/eth/filters/filter_system_test.go b/eth/filters/filter_system_test.go index 822580b56c..d614b119d4 100644 --- a/eth/filters/filter_system_test.go +++ b/eth/filters/filter_system_test.go @@ -25,6 +25,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core" + "github.com/ethereum/go-ethereum/core/bloombits" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/event" @@ -63,6 +64,18 @@ func (b *testBackend) GetReceipts(ctx context.Context, blockHash common.Hash) (t return core.GetBlockReceipts(b.db, blockHash, num), nil } +func (b *testBackend) GetBloomBits(ctx context.Context, bitIdx uint64, sectionIdxList []uint64) ([]bloombits.CompVector, error) { + results := make([]bloombits.CompVector, len(sectionIdxList)) + var err error + for i, idx := range sectionIdxList { + results[i], err = core.GetBloomBits(b.db, bitIdx, idx) + if err != nil { + return nil, err + } + } + return results, nil +} + // TestBlockSubscription tests if a block subscription returns block hashes for posted chain events. // It creates multiple subscriptions: // - one at the start and should receive all posted chain events and a second (blockHashes) @@ -75,7 +88,7 @@ func TestBlockSubscription(t *testing.T) { mux = new(event.TypeMux) db, _ = ethdb.NewMemDatabase() backend = &testBackend{mux, db} - api = NewPublicFilterAPI(backend, false) + api = NewPublicFilterAPI(backend, false, 0) genesis = new(core.Genesis).MustCommit(db) chain, _ = core.GenerateChain(params.TestChainConfig, genesis, db, 10, func(i int, gen *core.BlockGen) {}) chainEvents = []core.ChainEvent{} @@ -128,7 +141,7 @@ func TestPendingTxFilter(t *testing.T) { mux = new(event.TypeMux) db, _ = ethdb.NewMemDatabase() backend = &testBackend{mux, db} - api = NewPublicFilterAPI(backend, false) + api = NewPublicFilterAPI(backend, false, 0) transactions = []*types.Transaction{ types.NewTransaction(0, common.HexToAddress("0xb794f5ea0ba39494ce83a213fffba74279579268"), new(big.Int), new(big.Int), new(big.Int), nil), @@ -178,7 +191,7 @@ func TestLogFilterCreation(t *testing.T) { mux = new(event.TypeMux) db, _ = ethdb.NewMemDatabase() backend = &testBackend{mux, db} - api = NewPublicFilterAPI(backend, false) + api = NewPublicFilterAPI(backend, false, 0) testCases = []struct { crit FilterCriteria @@ -223,7 +236,7 @@ func TestInvalidLogFilterCreation(t *testing.T) { mux = new(event.TypeMux) db, _ = ethdb.NewMemDatabase() backend = &testBackend{mux, db} - api = NewPublicFilterAPI(backend, false) + api = NewPublicFilterAPI(backend, false, 0) ) // different situations where log filter creation should fail. @@ -249,7 +262,7 @@ func TestLogFilter(t *testing.T) { mux = new(event.TypeMux) db, _ = ethdb.NewMemDatabase() backend = &testBackend{mux, db} - api = NewPublicFilterAPI(backend, false) + api = NewPublicFilterAPI(backend, false, 0) firstAddr = common.HexToAddress("0x1111111111111111111111111111111111111111") secondAddr = common.HexToAddress("0x2222222222222222222222222222222222222222") @@ -357,7 +370,7 @@ func TestPendingLogsSubscription(t *testing.T) { mux = new(event.TypeMux) db, _ = ethdb.NewMemDatabase() backend = &testBackend{mux, db} - api = NewPublicFilterAPI(backend, false) + api = NewPublicFilterAPI(backend, false, 0) firstAddr = common.HexToAddress("0x1111111111111111111111111111111111111111") secondAddr = common.HexToAddress("0x2222222222222222222222222222222222222222") diff --git a/eth/filters/filter_test.go b/eth/filters/filter_test.go index cd5e7cafd5..ed32c71963 100644 --- a/eth/filters/filter_test.go +++ b/eth/filters/filter_test.go @@ -104,7 +104,7 @@ func BenchmarkMipmaps(b *testing.B) { } b.ResetTimer() - filter := New(backend, true) + filter := New(backend, true, 0) filter.SetAddresses([]common.Address{addr1, addr2, addr3, addr4}) filter.SetBeginBlock(0) filter.SetEndBlock(-1) @@ -207,7 +207,7 @@ func TestFilters(t *testing.T) { } } - filter := New(backend, true) + filter := New(backend, true, 0) filter.SetAddresses([]common.Address{addr}) filter.SetTopics([][]common.Hash{{hash1, hash2, hash3, hash4}}) filter.SetBeginBlock(0) @@ -218,7 +218,7 @@ func TestFilters(t *testing.T) { t.Error("expected 4 log, got", len(logs)) } - filter = New(backend, true) + filter = New(backend, true, 0) filter.SetAddresses([]common.Address{addr}) filter.SetTopics([][]common.Hash{{hash3}}) filter.SetBeginBlock(900) @@ -231,7 +231,7 @@ func TestFilters(t *testing.T) { t.Errorf("expected log[0].Topics[0] to be %x, got %x", hash3, logs[0].Topics[0]) } - filter = New(backend, true) + filter = New(backend, true, 0) filter.SetAddresses([]common.Address{addr}) filter.SetTopics([][]common.Hash{{hash3}}) filter.SetBeginBlock(990) @@ -244,7 +244,7 @@ func TestFilters(t *testing.T) { t.Errorf("expected log[0].Topics[0] to be %x, got %x", hash3, logs[0].Topics[0]) } - filter = New(backend, true) + filter = New(backend, true, 0) filter.SetTopics([][]common.Hash{{hash1, hash2}}) filter.SetBeginBlock(1) filter.SetEndBlock(10) @@ -255,7 +255,7 @@ func TestFilters(t *testing.T) { } failHash := common.BytesToHash([]byte("fail")) - filter = New(backend, true) + filter = New(backend, true, 0) filter.SetTopics([][]common.Hash{{failHash}}) filter.SetBeginBlock(0) filter.SetEndBlock(-1) @@ -266,7 +266,7 @@ func TestFilters(t *testing.T) { } failAddr := common.BytesToAddress([]byte("failmenow")) - filter = New(backend, true) + filter = New(backend, true, 0) filter.SetAddresses([]common.Address{failAddr}) filter.SetBeginBlock(0) filter.SetEndBlock(-1) @@ -276,7 +276,7 @@ func TestFilters(t *testing.T) { t.Error("expected 0 log, got", len(logs)) } - filter = New(backend, true) + filter = New(backend, true, 0) filter.SetTopics([][]common.Hash{{failHash}, {hash1}}) filter.SetBeginBlock(0) filter.SetEndBlock(-1) diff --git a/eth/handler.go b/eth/handler.go index 16e3712273..d8684c3bf0 100644 --- a/eth/handler.go +++ b/eth/handler.go @@ -45,6 +45,9 @@ import ( const ( softResponseLimit = 2 * 1024 * 1024 // Target maximum size of returned blocks, headers or node data. estHeaderRlpSize = 500 // Approximate size of an RLP encoded block header + + useBloomBits = false + bloomBitsSection = 4096 ) var ( @@ -87,7 +90,8 @@ type ProtocolManager struct { quitSync chan struct{} noMorePeers chan struct{} - lesServer LesServer + lesServer LesServer + bloomBitsProcessor *core.ChainSectionProcessor // wait group is used for graceful shutdowns during downloading // and processing @@ -112,6 +116,12 @@ func NewProtocolManager(config *params.ChainConfig, mode downloader.SyncMode, ne txsyncCh: make(chan *txsync), quitSync: make(chan struct{}), } + + if useBloomBits { + manager.bloomBitsProcessor = NewBloomBitsProcessor(manager.chaindb, manager.quitSync) + blockchain.AddChainProcessor(manager.bloomBitsProcessor) + } + // Figure out whether to allow fast sync or not if mode == downloader.FastSync && blockchain.CurrentBlock().NumberU64() > 0 { log.Warn("Blockchain not empty, fast sync disabled") diff --git a/les/api_backend.go b/les/api_backend.go index 7d69046deb..9bfc286feb 100644 --- a/les/api_backend.go +++ b/les/api_backend.go @@ -24,6 +24,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/math" "github.com/ethereum/go-ethereum/core" + "github.com/ethereum/go-ethereum/core/bloombits" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/core/vm" "github.com/ethereum/go-ethereum/eth/downloader" @@ -155,3 +156,7 @@ func (b *LesApiBackend) EventMux() *event.TypeMux { func (b *LesApiBackend) AccountManager() *accounts.Manager { return b.eth.accountManager } + +func (b *LesApiBackend) GetBloomBits(ctx context.Context, bitIdx uint64, sectionIdxList []uint64) ([]bloombits.CompVector, error) { + return nil, nil // implemented in a subsequent PR +} diff --git a/les/backend.go b/les/backend.go index 646c81a7b1..75f999aaa0 100644 --- a/les/backend.go +++ b/les/backend.go @@ -155,7 +155,7 @@ func (s *LightEthereum) APIs() []rpc.API { }, { Namespace: "eth", Version: "1.0", - Service: filters.NewPublicFilterAPI(s.ApiBackend, true), + Service: filters.NewPublicFilterAPI(s.ApiBackend, true, 0), Public: true, }, { Namespace: "net", From d85fb130bde4f0b34f85b7b75aa7f680c02587aa Mon Sep 17 00:00:00 2001 From: Zsolt Felfoldi Date: Wed, 19 Apr 2017 18:34:59 +0200 Subject: [PATCH 05/11] eth/filters: removed mip map filtering, always using bloombits --- core/blockchain.go | 14 ----- core/database_util.go | 48 ---------------- core/database_util_test.go | 112 ------------------------------------- eth/backend.go | 9 +-- eth/backend_test.go | 83 --------------------------- eth/db_upgrade.go | 45 --------------- eth/filters/api.go | 6 +- eth/filters/filter.go | 74 +++--------------------- eth/filters/filter_test.go | 29 +++++----- eth/handler.go | 7 +-- miner/worker.go | 2 - 11 files changed, 27 insertions(+), 402 deletions(-) delete mode 100644 eth/backend_test.go diff --git a/core/blockchain.go b/core/blockchain.go index ecae115d7b..816b357b95 100644 --- a/core/blockchain.go +++ b/core/blockchain.go @@ -783,12 +783,6 @@ func (self *BlockChain) InsertReceiptChain(blockChain types.Blocks, receiptChain log.Crit("Failed to write block receipts", "err", err) return } - if err := WriteMipmapBloom(self.chainDb, block.NumberU64(), receipts); err != nil { - errs[index] = fmt.Errorf("failed to write log blooms: %v", err) - atomic.AddInt32(&failed, 1) - log.Crit("Failed to write log blooms", "err", err) - return - } if err := WriteTransactions(self.chainDb, block); err != nil { errs[index] = fmt.Errorf("failed to write individual transactions: %v", err) atomic.AddInt32(&failed, 1) @@ -1041,10 +1035,6 @@ func (self *BlockChain) InsertChain(chain types.Blocks) (int, error) { if err := WriteReceipts(self.chainDb, receipts); err != nil { return i, err } - // Write map map bloom filters - if err := WriteMipmapBloom(self.chainDb, block.NumberU64(), receipts); err != nil { - return i, err - } // Write hash preimages if err := WritePreimages(self.chainDb, block.NumberU64(), self.stateCache.Preimages()); err != nil { return i, err @@ -1207,10 +1197,6 @@ func (self *BlockChain) reorg(oldBlock, newBlock *types.Block) error { if err := WriteReceipts(self.chainDb, receipts); err != nil { return err } - // Write map map bloom filters - if err := WriteMipmapBloom(self.chainDb, block.NumberU64(), receipts); err != nil { - return err - } addedTxs = append(addedTxs, block.Transactions()...) } diff --git a/core/database_util.go b/core/database_util.go index affe6e4130..5d1f8518d1 100644 --- a/core/database_util.go +++ b/core/database_util.go @@ -23,7 +23,6 @@ import ( "errors" "fmt" "math/big" - "sync" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/bloombits" @@ -51,9 +50,6 @@ var ( txMetaSuffix = []byte{0x01} receiptsPrefix = []byte("receipts-") - mipmapPre = []byte("mipmap-log-bloom-") - MIPMapLevels = []uint64{1000000, 500000, 100000, 50000, 1000} - configPrefix = []byte("ethereum-config-") // config prefix for the db // used by old (non-sequential keys) db, now only used for conversion @@ -67,8 +63,6 @@ var ( ChainConfigNotFoundErr = errors.New("ChainConfig not found") // general config not found error - mipmapBloomMu sync.Mutex // protect against race condition when updating mipmap blooms - preimageCounter = metrics.NewCounter("db/preimage/total") preimageHitCounter = metrics.NewCounter("db/preimage/hits") @@ -539,48 +533,6 @@ func DeleteReceipt(db ethdb.Database, hash common.Hash) { db.Delete(append(receiptsPrefix, hash.Bytes()...)) } -// returns a formatted MIP mapped key by adding prefix, canonical number and level -// -// ex. fn(98, 1000) = (prefix || 1000 || 0) -func mipmapKey(num, level uint64) []byte { - lkey := make([]byte, 8) - binary.BigEndian.PutUint64(lkey, level) - key := new(big.Int).SetUint64(num / level * level) - - return append(mipmapPre, append(lkey, key.Bytes()...)...) -} - -// WriteMapmapBloom writes each address included in the receipts' logs to the -// MIP bloom bin. -func WriteMipmapBloom(db ethdb.Database, number uint64, receipts types.Receipts) error { - mipmapBloomMu.Lock() - defer mipmapBloomMu.Unlock() - - batch := db.NewBatch() - for _, level := range MIPMapLevels { - key := mipmapKey(number, level) - bloomDat, _ := db.Get(key) - bloom := types.BytesToBloom(bloomDat) - for _, receipt := range receipts { - for _, log := range receipt.Logs { - bloom.Add(log.Address.Big()) - } - } - batch.Put(key, bloom.Bytes()) - } - if err := batch.Write(); err != nil { - return fmt.Errorf("mipmap write fail for: %d: %v", number, err) - } - return nil -} - -// GetMipmapBloom returns a bloom filter using the number and level as input -// parameters. For available levels see MIPMapLevels. -func GetMipmapBloom(db ethdb.Database, number, level uint64) types.Bloom { - bloomDat, _ := db.Get(mipmapKey(number, level)) - return types.BytesToBloom(bloomDat) -} - // PreimageTable returns a Database instance with the key prefix for preimage entries. func PreimageTable(db ethdb.Database) ethdb.Database { return ethdb.NewTable(db, preimagePrefix) diff --git a/core/database_util_test.go b/core/database_util_test.go index 9f16b660a9..3036b46bc0 100644 --- a/core/database_util_test.go +++ b/core/database_util_test.go @@ -18,17 +18,13 @@ package core import ( "bytes" - "io/ioutil" "math/big" - "os" "testing" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto/sha3" "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/rlp" ) @@ -446,111 +442,3 @@ func TestBlockReceiptStorage(t *testing.T) { t.Fatalf("deleted receipts returned: %v", rs) } } - -func TestMipmapBloom(t *testing.T) { - db, _ := ethdb.NewMemDatabase() - - receipt1 := new(types.Receipt) - receipt1.Logs = []*types.Log{ - {Address: common.BytesToAddress([]byte("test"))}, - {Address: common.BytesToAddress([]byte("address"))}, - } - receipt2 := new(types.Receipt) - receipt2.Logs = []*types.Log{ - {Address: common.BytesToAddress([]byte("test"))}, - {Address: common.BytesToAddress([]byte("address1"))}, - } - - WriteMipmapBloom(db, 1, types.Receipts{receipt1}) - WriteMipmapBloom(db, 2, types.Receipts{receipt2}) - - for _, level := range MIPMapLevels { - bloom := GetMipmapBloom(db, 2, level) - if !bloom.Test(new(big.Int).SetBytes([]byte("address1"))) { - t.Error("expected test to be included on level:", level) - } - } - - // reset - db, _ = ethdb.NewMemDatabase() - receipt := new(types.Receipt) - receipt.Logs = []*types.Log{ - {Address: common.BytesToAddress([]byte("test"))}, - } - WriteMipmapBloom(db, 999, types.Receipts{receipt1}) - - receipt = new(types.Receipt) - receipt.Logs = []*types.Log{ - {Address: common.BytesToAddress([]byte("test 1"))}, - } - WriteMipmapBloom(db, 1000, types.Receipts{receipt}) - - bloom := GetMipmapBloom(db, 1000, 1000) - if bloom.TestBytes([]byte("test")) { - t.Error("test should not have been included") - } -} - -func TestMipmapChain(t *testing.T) { - dir, err := ioutil.TempDir("", "mipmap") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(dir) - - var ( - db, _ = ethdb.NewLDBDatabase(dir, 0, 0) - key1, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") - addr = crypto.PubkeyToAddress(key1.PublicKey) - addr2 = common.BytesToAddress([]byte("jeff")) - - hash1 = common.BytesToHash([]byte("topic1")) - ) - defer db.Close() - - gspec := &Genesis{ - Config: params.TestChainConfig, - Alloc: GenesisAlloc{addr: {Balance: big.NewInt(1000000)}}, - } - genesis := gspec.MustCommit(db) - chain, receipts := GenerateChain(params.TestChainConfig, genesis, db, 1010, func(i int, gen *BlockGen) { - var receipts types.Receipts - switch i { - case 1: - receipt := types.NewReceipt(nil, new(big.Int)) - receipt.Logs = []*types.Log{{Address: addr, Topics: []common.Hash{hash1}}} - gen.AddUncheckedReceipt(receipt) - receipts = types.Receipts{receipt} - case 1000: - receipt := types.NewReceipt(nil, new(big.Int)) - receipt.Logs = []*types.Log{{Address: addr2}} - gen.AddUncheckedReceipt(receipt) - receipts = types.Receipts{receipt} - - } - - // store the receipts - err := WriteReceipts(db, receipts) - if err != nil { - t.Fatal(err) - } - WriteMipmapBloom(db, uint64(i+1), receipts) - }) - for i, block := range chain { - WriteBlock(db, block) - if err := WriteCanonicalHash(db, block.Hash(), block.NumberU64()); err != nil { - t.Fatalf("failed to insert block number: %v", err) - } - if err := WriteHeadBlockHash(db, block.Hash()); err != nil { - t.Fatalf("failed to insert block number: %v", err) - } - if err := WriteBlockReceipts(db, block.Hash(), block.NumberU64(), receipts[i]); err != nil { - t.Fatal("error writing block receipts:", err) - } - } - - bloom := GetMipmapBloom(db, 0, 1000) - if bloom.TestBytes(addr2[:]) { - t.Error("address was included in bloom and should not have") - } -} diff --git a/eth/backend.go b/eth/backend.go index 7dd9eeddd3..8e65ebb6e7 100644 --- a/eth/backend.go +++ b/eth/backend.go @@ -123,9 +123,6 @@ func New(ctx *node.ServiceContext, config *Config) (*Ethereum, error) { MinerThreads: config.MinerThreads, } - if err := addMipmapBloomBins(chainDb); err != nil { - return nil, err - } log.Info("Initialising Ethereum protocol", "versions", ProtocolVersions, "network", config.NetworkId) if !config.SkipBcVersionCheck { @@ -239,10 +236,6 @@ func (s *Ethereum) APIs() []rpc.API { // Append any APIs exposed explicitly by the consensus engine apis = append(apis, s.engine.APIs(s.BlockChain())...) - var bbSection uint64 - if useBloomBits { - bbSection = bloomBitsSection - } // Append all the local APIs and return return append(apis, []rpc.API{ { @@ -268,7 +261,7 @@ func (s *Ethereum) APIs() []rpc.API { }, { Namespace: "eth", Version: "1.0", - Service: filters.NewPublicFilterAPI(s.ApiBackend, false, bbSection), + Service: filters.NewPublicFilterAPI(s.ApiBackend, false, bloomBitsSection), Public: true, }, { Namespace: "admin", diff --git a/eth/backend_test.go b/eth/backend_test.go deleted file mode 100644 index f60e3214c3..0000000000 --- a/eth/backend_test.go +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright 2015 The go-ethereum Authors -// This file is part of the go-ethereum library. -// -// The go-ethereum library is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// The go-ethereum library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with the go-ethereum library. If not, see . - -package eth - -import ( - "math/big" - "testing" - - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core" - "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/params" -) - -func TestMipmapUpgrade(t *testing.T) { - db, _ := ethdb.NewMemDatabase() - addr := common.BytesToAddress([]byte("jeff")) - genesis := new(core.Genesis).MustCommit(db) - - chain, receipts := core.GenerateChain(params.TestChainConfig, genesis, db, 10, func(i int, gen *core.BlockGen) { - var receipts types.Receipts - switch i { - case 1: - receipt := types.NewReceipt(nil, new(big.Int)) - receipt.Logs = []*types.Log{{Address: addr}} - gen.AddUncheckedReceipt(receipt) - receipts = types.Receipts{receipt} - case 2: - receipt := types.NewReceipt(nil, new(big.Int)) - receipt.Logs = []*types.Log{{Address: addr}} - gen.AddUncheckedReceipt(receipt) - receipts = types.Receipts{receipt} - } - - // store the receipts - err := core.WriteReceipts(db, receipts) - if err != nil { - t.Fatal(err) - } - }) - for i, block := range chain { - core.WriteBlock(db, block) - if err := core.WriteCanonicalHash(db, block.Hash(), block.NumberU64()); err != nil { - t.Fatalf("failed to insert block number: %v", err) - } - if err := core.WriteHeadBlockHash(db, block.Hash()); err != nil { - t.Fatalf("failed to insert block number: %v", err) - } - if err := core.WriteBlockReceipts(db, block.Hash(), block.NumberU64(), receipts[i]); err != nil { - t.Fatal("error writing block receipts:", err) - } - } - - err := addMipmapBloomBins(db) - if err != nil { - t.Fatal(err) - } - - bloom := core.GetMipmapBloom(db, 1, core.MIPMapLevels[0]) - if (bloom == types.Bloom{}) { - t.Error("got empty bloom filter") - } - - data, _ := db.Get([]byte("setting-mipmap-version")) - if len(data) == 0 { - t.Error("setting-mipmap-version not written to database") - } -} diff --git a/eth/db_upgrade.go b/eth/db_upgrade.go index 2d63096df4..c21b1ca9b3 100644 --- a/eth/db_upgrade.go +++ b/eth/db_upgrade.go @@ -20,11 +20,9 @@ package eth import ( "bytes" "encoding/binary" - "fmt" "math/big" "time" - "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/core/bloombits" "github.com/ethereum/go-ethereum/core/types" @@ -253,49 +251,6 @@ func upgradeSequentialBlockData(db ethdb.Database, hash []byte) error { return nil } -func addMipmapBloomBins(db ethdb.Database) (err error) { - const mipmapVersion uint = 2 - - // check if the version is set. We ignore data for now since there's - // only one version so we can easily ignore it for now - var data []byte - data, _ = db.Get([]byte("setting-mipmap-version")) - if len(data) > 0 { - var version uint - if err := rlp.DecodeBytes(data, &version); err == nil && version == mipmapVersion { - return nil - } - } - - defer func() { - if err == nil { - var val []byte - val, err = rlp.EncodeToBytes(mipmapVersion) - if err == nil { - err = db.Put([]byte("setting-mipmap-version"), val) - } - return - } - }() - latestHash := core.GetHeadBlockHash(db) - latestBlock := core.GetBlock(db, latestHash, core.GetBlockNumber(db, latestHash)) - if latestBlock == nil { // clean database - return - } - - tstart := time.Now() - log.Warn("Upgrading db log bloom bins") - for i := uint64(0); i <= latestBlock.NumberU64(); i++ { - hash := core.GetCanonicalHash(db, i) - if (hash == common.Hash{}) { - return fmt.Errorf("chain db corrupted. Could not find block %d.", i) - } - core.WriteMipmapBloom(db, i, core.GetBlockReceipts(db, hash, i)) - } - log.Info("Bloom-bin upgrade completed", "elapsed", common.PrettyDuration(time.Since(tstart))) - return nil -} - // BloomBitsProcessorBackend implements ChainSectionProcessorBackend type BloomBitsProcessorBackend struct { db ethdb.Database diff --git a/eth/filters/api.go b/eth/filters/api.go index 7874ebac69..24ac789009 100644 --- a/eth/filters/api.go +++ b/eth/filters/api.go @@ -52,7 +52,6 @@ type filter struct { // information related to the Ethereum protocol such als blocks, transactions and logs. type PublicFilterAPI struct { backend Backend - useMipMap bool bloomBitsSection uint64 mux *event.TypeMux quit chan struct{} @@ -66,7 +65,6 @@ type PublicFilterAPI struct { func NewPublicFilterAPI(backend Backend, lightMode bool, bloomBitsSection uint64) *PublicFilterAPI { api := &PublicFilterAPI{ backend: backend, - useMipMap: bloomBitsSection == 0, bloomBitsSection: bloomBitsSection, mux: backend.EventMux(), chainDb: backend.ChainDb(), @@ -335,7 +333,7 @@ func (api *PublicFilterAPI) GetLogs(ctx context.Context, crit FilterCriteria) ([ crit.ToBlock = big.NewInt(rpc.LatestBlockNumber.Int64()) } - filter := New(api.backend, api.useMipMap, api.bloomBitsSection) + filter := New(api.backend, api.bloomBitsSection) filter.SetBeginBlock(crit.FromBlock.Int64()) filter.SetEndBlock(crit.ToBlock.Int64()) filter.SetAddresses(crit.Addresses) @@ -375,7 +373,7 @@ func (api *PublicFilterAPI) GetFilterLogs(ctx context.Context, id rpc.ID) ([]*ty return nil, fmt.Errorf("filter not found") } - filter := New(api.backend, api.useMipMap, api.bloomBitsSection) + filter := New(api.backend, api.bloomBitsSection) if f.crit.FromBlock != nil { filter.SetBeginBlock(f.crit.FromBlock.Int64()) } else { diff --git a/eth/filters/filter.go b/eth/filters/filter.go index c17619abeb..2d9a1c04fa 100644 --- a/eth/filters/filter.go +++ b/eth/filters/filter.go @@ -18,7 +18,6 @@ package filters import ( "context" - "math" "math/big" "time" @@ -41,9 +40,8 @@ type Backend interface { // Filter can be used to retrieve and filter logs. type Filter struct { - backend Backend - useMipMap, useBloomBits bool - bloomBitsSection uint64 + backend Backend + bloomBitsSection uint64 created time.Time @@ -57,13 +55,9 @@ type Filter struct { // New creates a new filter which uses a bloom filter on blocks to figure out whether // a particular block is interesting or not. -// MipMaps allow past blocks to be searched much more efficiently, but are not available -// to light clients. -func New(backend Backend, useMipMap bool, bloomBitsSection uint64) *Filter { +func New(backend Backend, bloomBitsSection uint64) *Filter { return &Filter{ backend: backend, - useMipMap: useMipMap, - useBloomBits: bloomBitsSection != 0, bloomBitsSection: bloomBitsSection, db: backend.ChainDb(), matcher: bloombits.NewMatcher(bloomBitsSection), @@ -86,17 +80,13 @@ func (f *Filter) SetEndBlock(end int64) { // in the given addresses. func (f *Filter) SetAddresses(addr []common.Address) { f.addresses = addr - if f.useBloomBits { - f.matcher.SetAddresses(addr) - } + f.matcher.SetAddresses(addr) } // SetTopics matches only logs that have topics matching the given topics. func (f *Filter) SetTopics(topics [][]common.Hash) { f.topics = topics - if f.useBloomBits { - f.matcher.SetTopics(topics) - } + f.matcher.SetTopics(topics) } // FindOnce searches the blockchain for matching log entries, returning @@ -119,18 +109,9 @@ func (f *Filter) FindOnce(ctx context.Context) ([]*types.Log, error) { endBlockNo = headBlockNumber } - // if no addresses are present we can't make use of fast search which - // uses the mipmap bloom filters to check for fast inclusion and uses - // higher range probability in order to ensure at least a false positive - if !f.useMipMap || len(f.addresses) == 0 { - logs, blockNumber, err := f.getLogs(ctx, beginBlockNo, endBlockNo) - f.begin = int64(blockNumber + 1) - return logs, err - } - - logs, blockNumber := f.mipFind(beginBlockNo, endBlockNo, 0) + logs, blockNumber, err := f.getLogs(ctx, beginBlockNo, endBlockNo) f.begin = int64(blockNumber + 1) - return logs, nil + return logs, err } // Run filters logs with the current parameters set @@ -144,42 +125,6 @@ func (f *Filter) Find(ctx context.Context) (logs []*types.Log, err error) { } } -func (f *Filter) mipFind(start, end uint64, depth int) (logs []*types.Log, blockNumber uint64) { - level := core.MIPMapLevels[depth] - // normalise numerator so we can work in level specific batches and - // work with the proper range checks - for num := start / level * level; num <= end; num += level { - // find addresses in bloom filters - bloom := core.GetMipmapBloom(f.db, num, level) - // Don't bother checking the first time through the loop - we're probably picking - // up where a previous run left off. - first := true - for _, addr := range f.addresses { - if first || bloom.TestBytes(addr[:]) { - first = false - // range check normalised values and make sure that - // we're resolving the correct range instead of the - // normalised values. - start := uint64(math.Max(float64(num), float64(start))) - end := uint64(math.Min(float64(num+level-1), float64(end))) - if depth+1 == len(core.MIPMapLevels) { - l, blockNumber, _ := f.getLogs(context.Background(), start, end) - if len(l) > 0 { - return l, blockNumber - } - } else { - l, blockNumber := f.mipFind(start, end, depth+1) - if len(l) > 0 { - return l, blockNumber - } - } - } - } - } - - return nil, end -} - // serveMatcher serves the bloomBits matcher by fetching the requested vectors // through the filter backend func (f *Filter) serveMatcher(ctx context.Context, stop chan struct{}) chan error { @@ -227,8 +172,8 @@ func (f *Filter) getLogs(ctx context.Context, start, end uint64) (logs []*types. return nil, i, nil } - if f.useBloomBits { - haveBloomBitsBefore := core.GetBloomBitsAvailable(f.db) * f.bloomBitsSection + haveBloomBitsBefore := core.GetBloomBitsAvailable(f.db) * f.bloomBitsSection + if haveBloomBitsBefore > start { e := end if haveBloomBitsBefore <= e { e = haveBloomBitsBefore - 1 @@ -236,7 +181,6 @@ func (f *Filter) getLogs(ctx context.Context, start, end uint64) (logs []*types. stop := make(chan struct{}) defer close(stop) - //fmt.Println("GetMatches") matches := f.matcher.GetMatches(start, e, stop) errChn := f.serveMatcher(ctx, stop) diff --git a/eth/filters/filter_test.go b/eth/filters/filter_test.go index ed32c71963..0848557dec 100644 --- a/eth/filters/filter_test.go +++ b/eth/filters/filter_test.go @@ -32,6 +32,8 @@ import ( "github.com/ethereum/go-ethereum/params" ) +const testBloomBitsSection = 4096 + func makeReceipt(addr common.Address) *types.Receipt { receipt := types.NewReceipt(nil, new(big.Int)) receipt.Logs = []*types.Log{ @@ -41,8 +43,8 @@ func makeReceipt(addr common.Address) *types.Receipt { return receipt } -func BenchmarkMipmaps(b *testing.B) { - dir, err := ioutil.TempDir("", "mipmap") +func BenchmarkFilters(b *testing.B) { + dir, err := ioutil.TempDir("", "filtertest") if err != nil { b.Fatal(err) } @@ -88,7 +90,6 @@ func BenchmarkMipmaps(b *testing.B) { if err != nil { b.Fatal(err) } - core.WriteMipmapBloom(db, uint64(i+1), receipts) }) for i, block := range chain { core.WriteBlock(db, block) @@ -104,7 +105,7 @@ func BenchmarkMipmaps(b *testing.B) { } b.ResetTimer() - filter := New(backend, true, 0) + filter := New(backend, testBloomBitsSection) filter.SetAddresses([]common.Address{addr1, addr2, addr3, addr4}) filter.SetBeginBlock(0) filter.SetEndBlock(-1) @@ -118,7 +119,7 @@ func BenchmarkMipmaps(b *testing.B) { } func TestFilters(t *testing.T) { - dir, err := ioutil.TempDir("", "mipmap") + dir, err := ioutil.TempDir("", "filtertest") if err != nil { t.Fatal(err) } @@ -189,10 +190,6 @@ func TestFilters(t *testing.T) { if err != nil { t.Fatal(err) } - // i is used as block number for the writes but since the i - // starts at 0 and block 0 (genesis) is already present increment - // by one - core.WriteMipmapBloom(db, uint64(i+1), receipts) }) for i, block := range chain { core.WriteBlock(db, block) @@ -207,7 +204,7 @@ func TestFilters(t *testing.T) { } } - filter := New(backend, true, 0) + filter := New(backend, testBloomBitsSection) filter.SetAddresses([]common.Address{addr}) filter.SetTopics([][]common.Hash{{hash1, hash2, hash3, hash4}}) filter.SetBeginBlock(0) @@ -218,7 +215,7 @@ func TestFilters(t *testing.T) { t.Error("expected 4 log, got", len(logs)) } - filter = New(backend, true, 0) + filter = New(backend, testBloomBitsSection) filter.SetAddresses([]common.Address{addr}) filter.SetTopics([][]common.Hash{{hash3}}) filter.SetBeginBlock(900) @@ -231,7 +228,7 @@ func TestFilters(t *testing.T) { t.Errorf("expected log[0].Topics[0] to be %x, got %x", hash3, logs[0].Topics[0]) } - filter = New(backend, true, 0) + filter = New(backend, testBloomBitsSection) filter.SetAddresses([]common.Address{addr}) filter.SetTopics([][]common.Hash{{hash3}}) filter.SetBeginBlock(990) @@ -244,7 +241,7 @@ func TestFilters(t *testing.T) { t.Errorf("expected log[0].Topics[0] to be %x, got %x", hash3, logs[0].Topics[0]) } - filter = New(backend, true, 0) + filter = New(backend, testBloomBitsSection) filter.SetTopics([][]common.Hash{{hash1, hash2}}) filter.SetBeginBlock(1) filter.SetEndBlock(10) @@ -255,7 +252,7 @@ func TestFilters(t *testing.T) { } failHash := common.BytesToHash([]byte("fail")) - filter = New(backend, true, 0) + filter = New(backend, testBloomBitsSection) filter.SetTopics([][]common.Hash{{failHash}}) filter.SetBeginBlock(0) filter.SetEndBlock(-1) @@ -266,7 +263,7 @@ func TestFilters(t *testing.T) { } failAddr := common.BytesToAddress([]byte("failmenow")) - filter = New(backend, true, 0) + filter = New(backend, testBloomBitsSection) filter.SetAddresses([]common.Address{failAddr}) filter.SetBeginBlock(0) filter.SetEndBlock(-1) @@ -276,7 +273,7 @@ func TestFilters(t *testing.T) { t.Error("expected 0 log, got", len(logs)) } - filter = New(backend, true, 0) + filter = New(backend, testBloomBitsSection) filter.SetTopics([][]common.Hash{{failHash}, {hash1}}) filter.SetBeginBlock(0) filter.SetEndBlock(-1) diff --git a/eth/handler.go b/eth/handler.go index d8684c3bf0..49f68dac9a 100644 --- a/eth/handler.go +++ b/eth/handler.go @@ -46,7 +46,6 @@ const ( softResponseLimit = 2 * 1024 * 1024 // Target maximum size of returned blocks, headers or node data. estHeaderRlpSize = 500 // Approximate size of an RLP encoded block header - useBloomBits = false bloomBitsSection = 4096 ) @@ -117,10 +116,8 @@ func NewProtocolManager(config *params.ChainConfig, mode downloader.SyncMode, ne quitSync: make(chan struct{}), } - if useBloomBits { - manager.bloomBitsProcessor = NewBloomBitsProcessor(manager.chaindb, manager.quitSync) - blockchain.AddChainProcessor(manager.bloomBitsProcessor) - } + manager.bloomBitsProcessor = NewBloomBitsProcessor(manager.chaindb, manager.quitSync) + blockchain.AddChainProcessor(manager.bloomBitsProcessor) // Figure out whether to allow fast sync or not if mode == downloader.FastSync && blockchain.CurrentBlock().NumberU64() > 0 { diff --git a/miner/worker.go b/miner/worker.go index 01241b3f30..7a307e3566 100644 --- a/miner/worker.go +++ b/miner/worker.go @@ -300,8 +300,6 @@ func (self *worker) wait() { core.WriteTransactions(self.chainDb, block) // store the receipts core.WriteReceipts(self.chainDb, work.receipts) - // Write map map bloom filters - core.WriteMipmapBloom(self.chainDb, block.NumberU64(), work.receipts) // implicit by posting ChainHeadEvent mustCommitNewWork = false } From 3dcccfb27c6c4aaba1f4862ceba189ebe380e3bc Mon Sep 17 00:00:00 2001 From: Zsolt Felfoldi Date: Tue, 9 May 2017 00:38:37 +0200 Subject: [PATCH 06/11] core/bloombits: removed bit vector aliases, using bitutil functions --- core/bloombits/fetcher_test.go | 6 +- core/bloombits/matcher.go | 42 +++++----- core/bloombits/matcher_test.go | 6 +- core/bloombits/utils.go | 127 +----------------------------- core/database_util.go | 7 +- eth/api_backend.go | 5 +- eth/db_upgrade.go | 4 +- eth/filters/filter.go | 11 ++- eth/filters/filter_system_test.go | 5 +- les/api_backend.go | 3 +- 10 files changed, 49 insertions(+), 167 deletions(-) diff --git a/core/bloombits/fetcher_test.go b/core/bloombits/fetcher_test.go index 3f436dfaa3..97425df532 100644 --- a/core/bloombits/fetcher_test.go +++ b/core/bloombits/fetcher_test.go @@ -27,8 +27,8 @@ import ( const testFetcherReqCnt = 50000 -func fetcherTestVector(b uint, s uint64) BitVector { - r := make(BitVector, 10) +func fetcherTestVector(b uint, s uint64) []byte { + r := make([]byte, 10) binary.BigEndian.PutUint16(r[0:2], uint16(b)) binary.BigEndian.PutUint64(r[2:10], s) return r @@ -59,7 +59,7 @@ func testFetcher(t *testing.T, cnt int) { } time.Sleep(time.Duration(rand.Intn(1000000))) atomic.AddUint32(&reqCnt, 1) - f.deliver([]uint64{req.sectionIdx}, []BitVector{fetcherTestVector(req.bitIdx, req.sectionIdx)}) + f.deliver([]uint64{req.sectionIdx}, [][]byte{fetcherTestVector(req.bitIdx, req.sectionIdx)}) } }() } diff --git a/core/bloombits/matcher.go b/core/bloombits/matcher.go index abd5bd734b..67970a9df8 100644 --- a/core/bloombits/matcher.go +++ b/core/bloombits/matcher.go @@ -20,6 +20,7 @@ import ( "time" "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/bitutil" "github.com/ethereum/go-ethereum/core/types" ) @@ -36,7 +37,7 @@ type fetcher struct { } type req struct { - data BitVector + data []byte queued bool fetched chan struct{} } @@ -50,8 +51,8 @@ type distReq struct { // in the same order through the returned channel. Multiple fetch instances of the same fetcher are allowed // to run in parallel, in case the same bit index appears multiple times in the filter structure. Each section // is requested only once, requests are sent to the request distributor (part of Matcher) through distChn. -func (f *fetcher) fetch(sectionChn chan uint64, distChn chan distReq, stop chan struct{}, wg *sync.WaitGroup) chan BitVector { - dataChn := make(chan BitVector, channelCap) +func (f *fetcher) fetch(sectionChn chan uint64, distChn chan distReq, stop chan struct{}, wg *sync.WaitGroup) chan []byte { + dataChn := make(chan []byte, channelCap) returnChn := make(chan uint64, channelCap) wg.Add(2) @@ -137,7 +138,7 @@ func (f *fetcher) fetch(sectionChn chan uint64, distChn chan distReq, stop chan // deliver is called by the request distributor when a reply to a request has // arrived -func (f *fetcher) deliver(sectionIdxList []uint64, data []BitVector) { +func (f *fetcher) deliver(sectionIdxList []uint64, data [][]byte) { f.reqLock.Lock() defer f.reqLock.Unlock() @@ -213,7 +214,7 @@ loop: // match creates a daisy-chain of sub-matchers, one for the address set and one for each topic set, each // sub-matcher receiving a section only if the previous ones have all found a potential match in one of // the blocks of the section, then binary and-ing its own matches and forwaring the result to the next one -func (m *Matcher) match(sectionChn chan uint64, stop chan struct{}) (chan uint64, chan BitVector) { +func (m *Matcher) match(sectionChn chan uint64, stop chan struct{}) (chan uint64, chan []byte) { subIdx := m.topics if len(m.addresses) > 0 { subIdx = append([][]types.BloomIndexList{m.addresses}, subIdx...) @@ -223,7 +224,7 @@ func (m *Matcher) match(sectionChn chan uint64, stop chan struct{}) (chan uint64 m.distributeRequests(stop) s := sectionChn - var bv chan BitVector + var bv chan []byte for _, idx := range subIdx { s, bv = m.subMatch(s, bv, idx, stop) } @@ -246,10 +247,10 @@ func (m *Matcher) newFetcher(idx uint) { // binary and-s the result to the daisy-chain input (sectionChn/andVectorChn) and forwards it to the daisy-chain output. // The matches of each address/topic are calculated by fetching the given sections of the three bloom bit indexes belonging to // that address/topic, and binary and-ing those vectors together. -func (m *Matcher) subMatch(sectionChn chan uint64, andVectorChn chan BitVector, idxs []types.BloomIndexList, stop chan struct{}) (chan uint64, chan BitVector) { +func (m *Matcher) subMatch(sectionChn chan uint64, andVectorChn chan []byte, idxs []types.BloomIndexList, stop chan struct{}) (chan uint64, chan []byte) { // set up fetchers fetchIdx := make([][3]chan uint64, len(idxs)) - fetchData := make([][3]chan BitVector, len(idxs)) + fetchData := make([][3]chan []byte, len(idxs)) for i, idx := range idxs { for j, ii := range idx { fetchIdx[i][j] = make(chan uint64, channelCap) @@ -259,7 +260,7 @@ func (m *Matcher) subMatch(sectionChn chan uint64, andVectorChn chan BitVector, processChn := make(chan uint64, channelCap) resIdxChn := make(chan uint64, channelCap) - resDataChn := make(chan BitVector, channelCap) + resDataChn := make(chan []byte, channelCap) m.wg.Add(2) // goroutine for starting retrievals @@ -314,41 +315,42 @@ func (m *Matcher) subMatch(sectionChn chan uint64, andVectorChn chan BitVector, return } - var orVector BitVector + var orVector []byte for _, ff := range fetchData { - var andVector BitVector + var andVector []byte for _, f := range ff { - var data BitVector + var data []byte select { case <-stop: return case data = <-f: } if andVector == nil { - andVector = bvCopy(data, int(m.sectionSize)) + andVector = make([]byte, int(m.sectionSize/8)) + copy(andVector, data) } else { - bvAnd(andVector, data) + bitutil.ANDBytes(andVector, andVector, data) } } if orVector == nil { orVector = andVector } else { - bvOr(orVector, andVector) + bitutil.ORBytes(orVector, orVector, andVector) } } if orVector == nil { - orVector = bvZero(int(m.sectionSize)) + orVector = make([]byte, int(m.sectionSize/8)) } if andVectorChn != nil { select { case <-stop: return case andVector := <-andVectorChn: - bvAnd(orVector, andVector) + bitutil.ANDBytes(orVector, orVector, andVector) } } - if bvIsNonZero(orVector) { + if bitutil.TestBytes(orVector) { select { case <-stop: return @@ -411,7 +413,7 @@ func (m *Matcher) GetMatches(start, end uint64, stop chan struct{}) chan uint64 if !ok { return } - var match BitVector + var match []byte select { case <-stop: return @@ -570,6 +572,6 @@ func (m *Matcher) NextRequest(stop chan struct{}) (bitIdx uint, sectionIdxList [ // Deliver delivers a bit vector to the appropriate fetcher. // It is possible to deliver data even after GetMatches has been stopped. Once a vector has been // requested, the next call to GetMatches will keep waiting for delivery. -func (m *Matcher) Deliver(bitIdx uint, sectionIdxList []uint64, data []BitVector) { +func (m *Matcher) Deliver(bitIdx uint, sectionIdxList []uint64, data [][]byte) { m.fetchers[bitIdx].deliver(sectionIdxList, data) } diff --git a/core/bloombits/matcher_test.go b/core/bloombits/matcher_test.go index 21d617b840..ac32b2de85 100644 --- a/core/bloombits/matcher_test.go +++ b/core/bloombits/matcher_test.go @@ -25,8 +25,8 @@ import ( const testSectionSize = 4096 -func matcherTestVector(b uint, s uint64) BitVector { - r := make(BitVector, testSectionSize/8) +func matcherTestVector(b uint, s uint64) []byte { + r := make([]byte, testSectionSize/8) for i, _ := range r { var bb byte for bit := 0; bit < 8; bit++ { @@ -82,7 +82,7 @@ func testServeMatcher(m *Matcher, stop chan struct{}, cnt *uint32) { if s == nil { return } - res := make([]BitVector, len(s)) + res := make([][]byte, len(s)) for i, ss := range s { res[i] = matcherTestVector(b, ss) atomic.AddUint32(cnt, 1) diff --git a/core/bloombits/utils.go b/core/bloombits/utils.go index 166a7d6039..e76d51f24a 100644 --- a/core/bloombits/utils.go +++ b/core/bloombits/utils.go @@ -19,129 +19,6 @@ import ( "github.com/ethereum/go-ethereum/core/types" ) -type ( - BitVector []byte - CompVector []byte -) - -// bvAnd binary ANDs b to a -func bvAnd(a, b BitVector) { - for i, bb := range b { - a[i] &= bb - } -} - -// bvOr binary ORs b to a -func bvOr(a, b BitVector) { - for i, bb := range b { - a[i] |= bb - } -} - -// bvZero returns an all-zero bit vector -func bvZero(sectionSize int) BitVector { - return make(BitVector, sectionSize/8) -} - -// bvCopy creates a copy of the given bit vector -// If the source vector is nil, returns an all-zero bit vector -func bvCopy(a BitVector, sectionSize int) BitVector { - c := make(BitVector, sectionSize/8) - copy(c, a) - return c -} - -// bvIsNonZero returns true if the bit vector has at least one "1" bit -func bvIsNonZero(a BitVector) bool { - for _, b := range a { - if b != 0 { - return true - } - } - return false -} - -// CompressBloomBits compresses a bit vector for storage/network transfer purposes -func CompressBloomBits(bits BitVector, sectionSize int) CompVector { - if len(bits) != sectionSize/8 { - panic(nil) - } - c := compressBits(bits) - if len(c) >= sectionSize/8 { - // make a copy so that output is always detached from input - return CompVector(bvCopy(bits, sectionSize)) - } - return CompVector(c) -} - -func compressBits(bits []byte) []byte { - l := len(bits) - ll := l / 8 - if ll == 0 { - ll = 1 - } - b := make([]byte, ll) - c := make([]byte, l) - cl := 0 - for i, v := range bits { - if v != 0 { - c[cl] = v - cl++ - b[i/8] |= 1 << byte(7-i%8) - } - } - if cl == 0 { - return nil - } - if ll > 1 { - b = compressBits(b) - } - return append(b, c[0:cl]...) -} - -// DeompressBloomBits decompresses a bit vector -func DecompressBloomBits(bits CompVector, sectionSize int) BitVector { - if len(bits) == sectionSize/8 { - // make a copy so that output is always detached from input - return bvCopy(BitVector(bits), sectionSize) - } - dc, ofs := decompressBits(bits, sectionSize/8) - if ofs != len(bits) { - panic(nil) - } - return dc -} - -func decompressBits(bits []byte, targetLen int) ([]byte, int) { - lb := len(bits) - dc := make([]byte, targetLen) - if lb == 0 { - return dc, 0 - } - - l := targetLen / 8 - var ( - b []byte - ofs int - ) - if l <= 1 { - b = bits[0:1] - ofs = 1 - } else { - b, ofs = decompressBits(bits, l) - } - for i, _ := range dc { - if b[i/8]&(1< Date: Tue, 9 May 2017 11:52:23 +0200 Subject: [PATCH 07/11] core/bloombits, eth/filters: cosmetic improvements --- core/bloombits/fetcher_test.go | 20 ++--- core/bloombits/matcher.go | 135 +++++++++++++++------------------ core/bloombits/matcher_test.go | 18 ++--- eth/filters/filter.go | 58 +++++++------- 4 files changed, 114 insertions(+), 117 deletions(-) diff --git a/core/bloombits/fetcher_test.go b/core/bloombits/fetcher_test.go index 97425df532..c610c34909 100644 --- a/core/bloombits/fetcher_test.go +++ b/core/bloombits/fetcher_test.go @@ -25,7 +25,7 @@ import ( "time" ) -const testFetcherReqCnt = 50000 +const testFetcherReqCount = 50000 func fetcherTestVector(b uint, s uint64) []byte { r := make([]byte, 10) @@ -46,19 +46,19 @@ func testFetcher(t *testing.T, cnt int) { f := &fetcher{ reqMap: make(map[uint64]req), } - distChn := make(chan distReq, channelCap) + distCh := make(chan distReq, channelCap) stop := make(chan struct{}) - var reqCnt uint32 + var reqCount uint32 for i := 0; i < 10; i++ { go func() { for { - req, ok := <-distChn + req, ok := <-distCh if !ok { return } time.Sleep(time.Duration(rand.Intn(1000000))) - atomic.AddUint32(&reqCnt, 1) + atomic.AddUint32(&reqCount, 1) f.deliver([]uint64{req.sectionIdx}, [][]byte{fetcherTestVector(req.bitIdx, req.sectionIdx)}) } }() @@ -68,17 +68,17 @@ func testFetcher(t *testing.T, cnt int) { for cc := 0; cc < cnt; cc++ { wg.Add(1) in := make(chan uint64, channelCap) - out := f.fetch(in, distChn, stop, &wg2) + out := f.fetch(in, distCh, stop, &wg2) time.Sleep(time.Millisecond * 100 * time.Duration(cc)) go func() { - for i := uint64(0); i < testFetcherReqCnt; i++ { + for i := uint64(0); i < testFetcherReqCount; i++ { in <- i } }() go func() { - for i := uint64(0); i < testFetcherReqCnt; i++ { + for i := uint64(0); i < testFetcherReqCount; i++ { bv := <-out if !bytes.Equal(bv, fetcherTestVector(0, i)) { if len(bv) != 10 { @@ -95,7 +95,7 @@ func testFetcher(t *testing.T, cnt int) { wg.Wait() close(stop) - if reqCnt != testFetcherReqCnt { - t.Errorf("Request count mismatch: expected %v, got %v", testFetcherReqCnt, reqCnt) + if reqCount != testFetcherReqCount { + t.Errorf("Request count mismatch: expected %v, got %v", testFetcherReqCount, reqCount) } } diff --git a/core/bloombits/matcher.go b/core/bloombits/matcher.go index 67970a9df8..2423146e0d 100644 --- a/core/bloombits/matcher.go +++ b/core/bloombits/matcher.go @@ -31,9 +31,9 @@ const ( // fetcher handles bit vector retrieval pipelines for a single bit index type fetcher struct { - bitIdx, ii uint - reqMap map[uint64]req - reqLock sync.RWMutex + bitIdx uint + reqMap map[uint64]req + reqLock sync.RWMutex } type req struct { @@ -47,26 +47,24 @@ type distReq struct { sectionIdx uint64 } -// fetch creates a retrieval pipeline, receiving section indexes from sectionChn and returning the results +// fetch creates a retrieval pipeline, receiving section indexes from sectionCh and returning the results // in the same order through the returned channel. Multiple fetch instances of the same fetcher are allowed // to run in parallel, in case the same bit index appears multiple times in the filter structure. Each section -// is requested only once, requests are sent to the request distributor (part of Matcher) through distChn. -func (f *fetcher) fetch(sectionChn chan uint64, distChn chan distReq, stop chan struct{}, wg *sync.WaitGroup) chan []byte { - dataChn := make(chan []byte, channelCap) - returnChn := make(chan uint64, channelCap) +// is requested only once, requests are sent to the request distributor (part of Matcher) through distCh. +func (f *fetcher) fetch(sectionCh chan uint64, distCh chan distReq, stop chan struct{}, wg *sync.WaitGroup) chan []byte { + dataCh := make(chan []byte, channelCap) + returnCh := make(chan uint64, channelCap) wg.Add(2) go func() { - defer func() { - close(returnChn) - wg.Done() - }() + defer wg.Done() + defer close(returnCh) for { select { case <-stop: return - case idx, ok := <-sectionChn: + case idx, ok := <-sectionCh: if !ok { return } @@ -84,28 +82,26 @@ func (f *fetcher) fetch(sectionChn chan uint64, distChn chan distReq, stop chan } f.reqLock.Unlock() if req { - distChn <- distReq{bitIdx: f.bitIdx, sectionIdx: idx} // success is guaranteed, distibuteRequests shuts down after fetch + distCh <- distReq{bitIdx: f.bitIdx, sectionIdx: idx} // success is guaranteed, distibuteRequests shuts down after fetch } select { case <-stop: return - case returnChn <- idx: + case returnCh <- idx: } } } }() go func() { - defer func() { - close(dataChn) - wg.Done() - }() + defer wg.Done() + defer close(dataCh) for { select { case <-stop: return - case idx, ok := <-returnChn: + case idx, ok := <-returnCh: if !ok { return } @@ -127,13 +123,13 @@ func (f *fetcher) fetch(sectionChn chan uint64, distChn chan distReq, stop chan select { case <-stop: return - case dataChn <- r.data: + case dataCh <- r.data: } } } }() - return dataChn + return dataCh } // deliver is called by the request distributor when a reply to a request has @@ -161,15 +157,15 @@ type Matcher struct { fetchers map[uint]*fetcher sectionSize uint64 - distChn chan distReq - reqs map[uint][]uint64 - getNextReqChn chan chan nextRequests - wg, distWg sync.WaitGroup + distCh chan distReq + reqs map[uint][]uint64 + getNextReqCh chan chan nextRequests + wg, distWg sync.WaitGroup } // NewMatcher creates a new Matcher instance func NewMatcher(sectionSize uint64) *Matcher { - return &Matcher{fetchers: make(map[uint]*fetcher), reqs: make(map[uint][]uint64), distChn: make(chan distReq, channelCap), sectionSize: sectionSize} + return &Matcher{fetchers: make(map[uint]*fetcher), reqs: make(map[uint][]uint64), distCh: make(chan distReq, channelCap), sectionSize: sectionSize} } // SetAddresses matches only logs that are generated from addresses that are included @@ -214,16 +210,15 @@ loop: // match creates a daisy-chain of sub-matchers, one for the address set and one for each topic set, each // sub-matcher receiving a section only if the previous ones have all found a potential match in one of // the blocks of the section, then binary and-ing its own matches and forwaring the result to the next one -func (m *Matcher) match(sectionChn chan uint64, stop chan struct{}) (chan uint64, chan []byte) { +func (m *Matcher) match(sectionCh chan uint64, stop chan struct{}) (chan uint64, chan []byte) { subIdx := m.topics if len(m.addresses) > 0 { subIdx = append([][]types.BloomIndexList{m.addresses}, subIdx...) } - //fmt.Println("idx", subIdx) - m.getNextReqChn = make(chan chan nextRequests) // should be a blocking channel + m.getNextReqCh = make(chan chan nextRequests) // should be a blocking channel m.distributeRequests(stop) - s := sectionChn + s := sectionCh var bv chan []byte for _, idx := range subIdx { s, bv = m.subMatch(s, bv, idx, stop) @@ -244,23 +239,23 @@ func (m *Matcher) newFetcher(idx uint) { } // subMatch creates a sub-matcher that filters for a set of addresses or topics, binary or-s those matches, then -// binary and-s the result to the daisy-chain input (sectionChn/andVectorChn) and forwards it to the daisy-chain output. +// binary and-s the result to the daisy-chain input (sectionCh/andVectorCh) and forwards it to the daisy-chain output. // The matches of each address/topic are calculated by fetching the given sections of the three bloom bit indexes belonging to // that address/topic, and binary and-ing those vectors together. -func (m *Matcher) subMatch(sectionChn chan uint64, andVectorChn chan []byte, idxs []types.BloomIndexList, stop chan struct{}) (chan uint64, chan []byte) { +func (m *Matcher) subMatch(sectionCh chan uint64, andVectorCh chan []byte, idxs []types.BloomIndexList, stop chan struct{}) (chan uint64, chan []byte) { // set up fetchers fetchIdx := make([][3]chan uint64, len(idxs)) fetchData := make([][3]chan []byte, len(idxs)) for i, idx := range idxs { for j, ii := range idx { fetchIdx[i][j] = make(chan uint64, channelCap) - fetchData[i][j] = m.fetchers[ii].fetch(fetchIdx[i][j], m.distChn, stop, &m.wg) + fetchData[i][j] = m.fetchers[ii].fetch(fetchIdx[i][j], m.distCh, stop, &m.wg) } } - processChn := make(chan uint64, channelCap) - resIdxChn := make(chan uint64, channelCap) - resDataChn := make(chan []byte, channelCap) + processCh := make(chan uint64, channelCap) + resIdxCh := make(chan uint64, channelCap) + resDataCh := make(chan []byte, channelCap) m.wg.Add(2) // goroutine for starting retrievals @@ -271,9 +266,9 @@ func (m *Matcher) subMatch(sectionChn chan uint64, andVectorChn chan []byte, idx select { case <-stop: return - case s, ok := <-sectionChn: + case s, ok := <-sectionCh: if !ok { - close(processChn) + close(processCh) for _, ff := range fetchIdx { for _, f := range ff { close(f) @@ -285,7 +280,7 @@ func (m *Matcher) subMatch(sectionChn chan uint64, andVectorChn chan []byte, idx select { case <-stop: return - case processChn <- s: + case processCh <- s: } for _, ff := range fetchIdx { for _, f := range ff { @@ -308,10 +303,10 @@ func (m *Matcher) subMatch(sectionChn chan uint64, andVectorChn chan []byte, idx select { case <-stop: return - case s, ok := <-processChn: + case s, ok := <-processCh: if !ok { - close(resIdxChn) - close(resDataChn) + close(resIdxCh) + close(resDataCh) return } @@ -342,11 +337,11 @@ func (m *Matcher) subMatch(sectionChn chan uint64, andVectorChn chan []byte, idx if orVector == nil { orVector = make([]byte, int(m.sectionSize/8)) } - if andVectorChn != nil { + if andVectorCh != nil { select { case <-stop: return - case andVector := <-andVectorChn: + case andVector := <-andVectorCh: bitutil.ANDBytes(orVector, orVector, andVector) } } @@ -354,19 +349,19 @@ func (m *Matcher) subMatch(sectionChn chan uint64, andVectorChn chan []byte, idx select { case <-stop: return - case resIdxChn <- s: + case resIdxCh <- s: } select { case <-stop: return - case resDataChn <- orVector: + case resDataCh <- orVector: } } } } }() - return resIdxChn, resDataChn + return resIdxCh, resDataCh } // GetMatches returns a stream of bloom matches in a given range of blocks. @@ -377,24 +372,22 @@ func (m *Matcher) subMatch(sectionChn chan uint64, andVectorChn chan []byte, idx func (m *Matcher) GetMatches(start, end uint64, stop chan struct{}) chan uint64 { m.distWg.Wait() - sectionChn := make(chan uint64, channelCap) - resultsChn := make(chan uint64, channelCap) + sectionCh := make(chan uint64, channelCap) + resultsCh := make(chan uint64, channelCap) - s, bv := m.match(sectionChn, stop) + s, bv := m.match(sectionCh, stop) startSection := start / m.sectionSize endSection := end / m.sectionSize m.wg.Add(2) go func() { - defer func() { - close(sectionChn) - m.wg.Done() - }() + defer m.wg.Done() + defer close(sectionCh) for i := startSection; i <= endSection; i++ { select { - case sectionChn <- i: + case sectionCh <- i: case <-stop: return } @@ -402,10 +395,8 @@ func (m *Matcher) GetMatches(start, end uint64, stop chan struct{}) chan uint64 }() go func() { - defer func() { - close(resultsChn) - m.wg.Done() - }() + defer m.wg.Done() + defer close(resultsCh) for { select { @@ -436,7 +427,7 @@ func (m *Matcher) GetMatches(start, end uint64, stop chan struct{}) chan uint64 select { case <-stop: return - case resultsChn <- i: + case resultsCh <- i: } } } else { @@ -450,7 +441,7 @@ func (m *Matcher) GetMatches(start, end uint64, stop chan struct{}) chan uint64 } }() - return resultsChn + return resultsCh } type nextRequests struct { @@ -473,9 +464,9 @@ func (m *Matcher) distributeRequests(stop chan struct{}) { go func() { defer m.distWg.Done() - reqCnt := 0 + reqCount := 0 for _, s := range m.reqs { - reqCnt += len(s) + reqCount += len(s) } storeReq := func(r distReq) { @@ -489,7 +480,7 @@ func (m *Matcher) distributeRequests(stop chan struct{}) { queue[i] = r.sectionIdx m.reqs[r.bitIdx] = queue - reqCnt++ + reqCount++ } storeReqs := func(r distReq) { @@ -499,7 +490,7 @@ func (m *Matcher) distributeRequests(stop chan struct{}) { select { case <-timeout: return - case r := <-m.distChn: + case r := <-m.distCh: storeReq(r) case <-stopDist: return @@ -508,20 +499,20 @@ func (m *Matcher) distributeRequests(stop chan struct{}) { } for { - if reqCnt == 0 { + if reqCount == 0 { select { - case r := <-m.distChn: + case r := <-m.distCh: storeReqs(r) case <-stopDist: return } } else { select { - case r := <-m.distChn: + case r := <-m.distCh: storeReqs(r) case <-stopDist: return - case c := <-m.getNextReqChn: + case c := <-m.getNextReqCh: var ( found bool bestBit uint @@ -546,7 +537,7 @@ func (m *Matcher) distributeRequests(stop chan struct{}) { } res := nextRequests{bestBit, bestQueue[:cnt]} m.reqs[bestBit] = bestQueue[cnt:] - reqCnt -= cnt + reqCount -= cnt c <- res } @@ -561,7 +552,7 @@ func (m *Matcher) distributeRequests(stop chan struct{}) { func (m *Matcher) NextRequest(stop chan struct{}) (bitIdx uint, sectionIdxList []uint64) { c := make(chan nextRequests) select { - case m.getNextReqChn <- c: + case m.getNextReqCh <- c: r := <-c return r.bitIdx, r.sectionIdxList case <-stop: diff --git a/core/bloombits/matcher_test.go b/core/bloombits/matcher_test.go index ac32b2de85..a2f786204e 100644 --- a/core/bloombits/matcher_test.go +++ b/core/bloombits/matcher_test.go @@ -93,7 +93,7 @@ func testServeMatcher(m *Matcher, stop chan struct{}, cnt *uint32) { } } -func testMatcher(t *testing.T, idxs [][]types.BloomIndexList, cnt uint64, stopOnMatches bool, expCnt uint32) uint32 { +func testMatcher(t *testing.T, idxs [][]types.BloomIndexList, cnt uint64, stopOnMatches bool, expCount uint32) uint32 { m := NewMatcher(testSectionSize) for _, idxss := range idxs { @@ -106,11 +106,11 @@ func testMatcher(t *testing.T, idxs [][]types.BloomIndexList, cnt uint64, stopOn m.addresses = idxs[0] m.topics = idxs[1:] - var reqCnt uint32 + var reqCount uint32 stop := make(chan struct{}) chn := m.GetMatches(0, cnt-1, stop) - testServeMatcher(m, stop, &reqCnt) + testServeMatcher(m, stop, &reqCount) for i := uint64(0); i < cnt; i++ { if expMatch3(idxs, i) { @@ -126,7 +126,7 @@ func testMatcher(t *testing.T, idxs [][]types.BloomIndexList, cnt uint64, stopOn close(stop) stop = make(chan struct{}) chn = m.GetMatches(i+1, cnt-1, stop) - testServeMatcher(m, stop, &reqCnt) + testServeMatcher(m, stop, &reqCount) } } } @@ -136,11 +136,11 @@ func testMatcher(t *testing.T, idxs [][]types.BloomIndexList, cnt uint64, stopOn } close(stop) - if expCnt != 0 && expCnt != reqCnt { - t.Errorf("Error matching idxs = %v count = %v stopOnMatches = %v: request count mismatch, expected #%v, got #%v", idxs, cnt, stopOnMatches, expCnt, reqCnt) + if expCount != 0 && expCount != reqCount { + t.Errorf("Error matching idxs = %v count = %v stopOnMatches = %v: request count mismatch, expected #%v, got #%v", idxs, cnt, stopOnMatches, expCount, reqCount) } - return reqCnt + return reqCount } func testRandomIdxs(l []int, max int) [][]types.BloomIndexList { @@ -174,7 +174,7 @@ func TestMatcherRandom(t *testing.T) { testMatcher(t, testRandomIdxs([]int{2, 2, 2}, 20), 1000000, false, 0) testMatcher(t, testRandomIdxs([]int{5, 5, 5}, 50), 1000000, false, 0) idxs := testRandomIdxs([]int{2, 2, 2}, 20) - reqCnt := testMatcher(t, idxs, 100000, false, 0) - testMatcher(t, idxs, 100000, true, reqCnt) + reqCount := testMatcher(t, idxs, 100000, false, 0) + testMatcher(t, idxs, 100000, true, reqCount) } } diff --git a/eth/filters/filter.go b/eth/filters/filter.go index 0ca7fa2a43..a4e3e88349 100644 --- a/eth/filters/filter.go +++ b/eth/filters/filter.go @@ -158,24 +158,26 @@ func (f *Filter) serveMatcher(ctx context.Context, stop chan struct{}) chan erro return errChn } -func (f *Filter) getLogs(ctx context.Context, start, end uint64) (logs []*types.Log, blockNumber uint64, err error) { - - checkBlock := func(i uint64, header *types.Header) (logs []*types.Log, blockNumber uint64, err error) { - // Get the logs of the block - receipts, err := f.backend.GetReceipts(ctx, header.Hash()) - if err != nil { - return nil, end, err - } - var unfiltered []*types.Log - for _, receipt := range receipts { - unfiltered = append(unfiltered, ([]*types.Log)(receipt.Logs)...) - } - logs = filterLogs(unfiltered, nil, nil, f.addresses, f.topics) - if len(logs) > 0 { - return logs, i, nil - } - return nil, i, nil +// checkMatches checks if the receipts belonging to the given header contain any log events that +// match the filter criteria. This function is called when the bloom filter signals a potential match. +func (f *Filter) checkMatches(ctx context.Context, header *types.Header) (logs []*types.Log, err error) { + // Get the logs of the block + receipts, err := f.backend.GetReceipts(ctx, header.Hash()) + if err != nil { + return nil, err } + var unfiltered []*types.Log + for _, receipt := range receipts { + unfiltered = append(unfiltered, ([]*types.Log)(receipt.Logs)...) + } + logs = filterLogs(unfiltered, nil, nil, f.addresses, f.topics) + if len(logs) > 0 { + return logs, nil + } + return nil, nil +} + +func (f *Filter) getLogs(ctx context.Context, start, end uint64) (logs []*types.Log, blockNumber uint64, err error) { haveBloomBitsBefore := core.GetBloomBitsAvailable(f.db) * f.bloomBitsSection if haveBloomBitsBefore > start { @@ -203,10 +205,12 @@ func (f *Filter) getLogs(ctx context.Context, start, end uint64) (logs []*types. return logs, end, err } - l, b, e := checkBlock(i, header) - - if l != nil || e != nil { - return l, b, e + logs, err := f.checkMatches(ctx, header) + if err != nil { + return nil, end, err + } + if logs != nil { + return logs, i, nil } case err := <-errChn: return logs, end, err @@ -217,9 +221,8 @@ func (f *Filter) getLogs(ctx context.Context, start, end uint64) (logs []*types. if end < haveBloomBitsBefore { return logs, end, nil - } else { - start = haveBloomBitsBefore } + start = haveBloomBitsBefore } // search the rest with regular block-by-block bloom filtering @@ -233,9 +236,12 @@ func (f *Filter) getLogs(ctx context.Context, start, end uint64) (logs []*types. // Use bloom filtering to see if this block is interesting given the // current parameters if f.bloomFilter(header.Bloom) { - l, b, e := checkBlock(i, header) - if l != nil || e != nil { - return l, b, e + logs, err := f.checkMatches(ctx, header) + if err != nil { + return nil, end, err + } + if logs != nil { + return logs, i, nil } } } From 0957393047e15c9b58b41f479d0bd7788ead2201 Mon Sep 17 00:00:00 2001 From: Zsolt Felfoldi Date: Tue, 9 May 2017 12:27:41 +0200 Subject: [PATCH 08/11] eth/filters: add WaitGroup to serveMatcher --- eth/filters/filter.go | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/eth/filters/filter.go b/eth/filters/filter.go index a4e3e88349..5fc918c30b 100644 --- a/eth/filters/filter.go +++ b/eth/filters/filter.go @@ -19,6 +19,7 @@ package filters import ( "context" "math/big" + "sync" "time" "github.com/ethereum/go-ethereum/common" @@ -128,10 +129,13 @@ func (f *Filter) Find(ctx context.Context) (logs []*types.Log, err error) { // serveMatcher serves the bloomBits matcher by fetching the requested vectors // through the filter backend -func (f *Filter) serveMatcher(ctx context.Context, stop chan struct{}) chan error { +func (f *Filter) serveMatcher(ctx context.Context, stop chan struct{}, wg *sync.WaitGroup) chan error { errChn := make(chan error) + wg.Add(10) for i := 0; i < 10; i++ { go func(i int) { + defer wg.Done() + for { b, s := f.matcher.NextRequest(stop) if s == nil { @@ -187,9 +191,12 @@ func (f *Filter) getLogs(ctx context.Context, start, end uint64) (logs []*types. } stop := make(chan struct{}) - defer close(stop) + var wg sync.WaitGroup matches := f.matcher.GetMatches(start, e, stop) - errChn := f.serveMatcher(ctx, stop) + errChn := f.serveMatcher(ctx, stop, &wg) + + defer wg.Wait() + defer close(stop) loop: for { From b9b9db2f9980d2fb73f8b9181bf9f5e622178b95 Mon Sep 17 00:00:00 2001 From: Zsolt Felfoldi Date: Tue, 9 May 2017 13:21:25 +0200 Subject: [PATCH 09/11] core/bloombits: using partialMatches instead of separate idx/bv channels --- core/bloombits/matcher.go | 92 +++++++++++++++++---------------------- 1 file changed, 40 insertions(+), 52 deletions(-) diff --git a/core/bloombits/matcher.go b/core/bloombits/matcher.go index 2423146e0d..f9d9aefc5a 100644 --- a/core/bloombits/matcher.go +++ b/core/bloombits/matcher.go @@ -150,7 +150,7 @@ func (f *fetcher) deliver(sectionIdxList []uint64, data [][]byte) { } // Matcher is a pipelined structure of fetchers and logic matchers which perform -// binary and/or operations on the bitstreams, finally creating a stream of potential matches. +// binary AND/OR operations on the bitstreams, finally creating a stream of potential matches. type Matcher struct { addresses []types.BloomIndexList topics [][]types.BloomIndexList @@ -209,8 +209,8 @@ loop: // match creates a daisy-chain of sub-matchers, one for the address set and one for each topic set, each // sub-matcher receiving a section only if the previous ones have all found a potential match in one of -// the blocks of the section, then binary and-ing its own matches and forwaring the result to the next one -func (m *Matcher) match(sectionCh chan uint64, stop chan struct{}) (chan uint64, chan []byte) { +// the blocks of the section, then binary AND-ing its own matches and forwaring the result to the next one +func (m *Matcher) match(processCh chan partialMatches, stop chan struct{}) chan partialMatches { subIdx := m.topics if len(m.addresses) > 0 { subIdx = append([][]types.BloomIndexList{m.addresses}, subIdx...) @@ -218,12 +218,18 @@ func (m *Matcher) match(sectionCh chan uint64, stop chan struct{}) (chan uint64, m.getNextReqCh = make(chan chan nextRequests) // should be a blocking channel m.distributeRequests(stop) - s := sectionCh - var bv chan []byte for _, idx := range subIdx { - s, bv = m.subMatch(s, bv, idx, stop) + processCh = m.subMatch(processCh, idx, stop) } - return s, bv + return processCh +} + +// partialMatches with a non-nil vector represents a section in which some sub-matchers have already +// found potential matches. Subsequent sub-matchers will binary AND their matches with this vector. +// If vector is nil, it represents a section to be processed by the first sub-matcher. +type partialMatches struct { + sectionIdx uint64 + vector []byte } // newFetcher adds a fetcher for the given bit index if it has not existed before @@ -238,11 +244,11 @@ func (m *Matcher) newFetcher(idx uint) { m.fetchers[idx] = f } -// subMatch creates a sub-matcher that filters for a set of addresses or topics, binary or-s those matches, then -// binary and-s the result to the daisy-chain input (sectionCh/andVectorCh) and forwards it to the daisy-chain output. +// subMatch creates a sub-matcher that filters for a set of addresses or topics, binary OR-s those matches, then +// binary AND-s the result to the daisy-chain input (processCh) and forwards it to the daisy-chain output. // The matches of each address/topic are calculated by fetching the given sections of the three bloom bit indexes belonging to -// that address/topic, and binary and-ing those vectors together. -func (m *Matcher) subMatch(sectionCh chan uint64, andVectorCh chan []byte, idxs []types.BloomIndexList, stop chan struct{}) (chan uint64, chan []byte) { +// that address/topic, and binary AND-ing those vectors together. +func (m *Matcher) subMatch(processCh chan partialMatches, idxs []types.BloomIndexList, stop chan struct{}) chan partialMatches { // set up fetchers fetchIdx := make([][3]chan uint64, len(idxs)) fetchData := make([][3]chan []byte, len(idxs)) @@ -253,9 +259,8 @@ func (m *Matcher) subMatch(sectionCh chan uint64, andVectorCh chan []byte, idxs } } - processCh := make(chan uint64, channelCap) - resIdxCh := make(chan uint64, channelCap) - resDataCh := make(chan []byte, channelCap) + fetchedCh := make(chan partialMatches, channelCap) // entries from processCh are forwarded here after fetches have been initiated + resultsCh := make(chan partialMatches, channelCap) m.wg.Add(2) // goroutine for starting retrievals @@ -266,9 +271,9 @@ func (m *Matcher) subMatch(sectionCh chan uint64, andVectorCh chan []byte, idxs select { case <-stop: return - case s, ok := <-sectionCh: + case s, ok := <-processCh: if !ok { - close(processCh) + close(fetchedCh) for _, ff := range fetchIdx { for _, f := range ff { close(f) @@ -277,20 +282,20 @@ func (m *Matcher) subMatch(sectionCh chan uint64, andVectorCh chan []byte, idxs return } - select { - case <-stop: - return - case processCh <- s: - } for _, ff := range fetchIdx { for _, f := range ff { select { case <-stop: return - case f <- s: + case f <- s.sectionIdx: } } } + select { + case <-stop: + return + case fetchedCh <- s: + } } } }() @@ -303,10 +308,9 @@ func (m *Matcher) subMatch(sectionCh chan uint64, andVectorCh chan []byte, idxs select { case <-stop: return - case s, ok := <-processCh: + case s, ok := <-fetchedCh: if !ok { - close(resIdxCh) - close(resDataCh) + close(resultsCh) return } @@ -337,31 +341,21 @@ func (m *Matcher) subMatch(sectionCh chan uint64, andVectorCh chan []byte, idxs if orVector == nil { orVector = make([]byte, int(m.sectionSize/8)) } - if andVectorCh != nil { - select { - case <-stop: - return - case andVector := <-andVectorCh: - bitutil.ANDBytes(orVector, orVector, andVector) - } + if s.vector != nil { + bitutil.ANDBytes(orVector, orVector, s.vector) } if bitutil.TestBytes(orVector) { select { case <-stop: return - case resIdxCh <- s: - } - select { - case <-stop: - return - case resDataCh <- orVector: + case resultsCh <- partialMatches{s.sectionIdx, orVector}: } } } } }() - return resIdxCh, resDataCh + return resultsCh } // GetMatches returns a stream of bloom matches in a given range of blocks. @@ -372,10 +366,10 @@ func (m *Matcher) subMatch(sectionCh chan uint64, andVectorCh chan []byte, idxs func (m *Matcher) GetMatches(start, end uint64, stop chan struct{}) chan uint64 { m.distWg.Wait() - sectionCh := make(chan uint64, channelCap) + processCh := make(chan partialMatches, channelCap) resultsCh := make(chan uint64, channelCap) - s, bv := m.match(sectionCh, stop) + res := m.match(processCh, stop) startSection := start / m.sectionSize endSection := end / m.sectionSize @@ -383,11 +377,11 @@ func (m *Matcher) GetMatches(start, end uint64, stop chan struct{}) chan uint64 m.wg.Add(2) go func() { defer m.wg.Done() - defer close(sectionCh) + defer close(processCh) for i := startSection; i <= endSection; i++ { select { - case sectionCh <- i: + case processCh <- partialMatches{i, nil}: case <-stop: return } @@ -400,17 +394,11 @@ func (m *Matcher) GetMatches(start, end uint64, stop chan struct{}) chan uint64 for { select { - case idx, ok := <-s: + case r, ok := <-res: if !ok { return } - var match []byte - select { - case <-stop: - return - case match = <-bv: - } - sectionStart := idx * m.sectionSize + sectionStart := r.sectionIdx * m.sectionSize s := sectionStart if start > s { s = start @@ -420,7 +408,7 @@ func (m *Matcher) GetMatches(start, end uint64, stop chan struct{}) chan uint64 e = end } for i := s; i <= e; i++ { - b := match[(i-sectionStart)/8] + b := r.vector[(i-sectionStart)/8] bit := 7 - i%8 if b != 0 { if b&(1< Date: Tue, 9 May 2017 16:52:57 +0200 Subject: [PATCH 10/11] eth/filters: added bloombits filter benchmarks --- eth/filters/bench_test.go | 246 ++++++++++++++++++++++++++++++++++++++ eth/filters/filter.go | 18 ++- 2 files changed, 259 insertions(+), 5 deletions(-) create mode 100644 eth/filters/bench_test.go diff --git a/eth/filters/bench_test.go b/eth/filters/bench_test.go new file mode 100644 index 0000000000..64a9dc57b3 --- /dev/null +++ b/eth/filters/bench_test.go @@ -0,0 +1,246 @@ +// Copyright 2017 The go-ethereum Authors +// This file is part of the go-ethereum library. +// +// The go-ethereum library is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// The go-ethereum library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with the go-ethereum library. If not, see . + +package filters + +import ( + "bytes" + "context" + "fmt" + "testing" + "time" + + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/bitutil" + "github.com/ethereum/go-ethereum/core" + "github.com/ethereum/go-ethereum/core/bloombits" + "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/event" + "github.com/ethereum/go-ethereum/node" + "github.com/golang/snappy" +) + +func BenchmarkBloomBits512(b *testing.B) { + benchmarkBloomBitsForSize(b, 512) +} + +func BenchmarkBloomBits1k(b *testing.B) { + benchmarkBloomBitsForSize(b, 1024) +} + +func BenchmarkBloomBits2k(b *testing.B) { + benchmarkBloomBitsForSize(b, 2048) +} + +func BenchmarkBloomBits4k(b *testing.B) { + benchmarkBloomBitsForSize(b, 4096) +} + +func BenchmarkBloomBits8k(b *testing.B) { + benchmarkBloomBitsForSize(b, 8192) +} + +func BenchmarkBloomBits16k(b *testing.B) { + benchmarkBloomBitsForSize(b, 16384) +} + +func BenchmarkBloomBits32k(b *testing.B) { + benchmarkBloomBitsForSize(b, 32768) +} + +func benchmarkBloomBitsForSize(b *testing.B, sectionSize uint64) { + benchmarkBloomBits(b, sectionSize, 0) + benchmarkBloomBits(b, sectionSize, 1) + benchmarkBloomBits(b, sectionSize, 2) +} + +const benchFilterCnt = 2000 + +func benchmarkBloomBits(b *testing.B, sectionSize uint64, comp int) { + benchDataDir := node.DefaultDataDir() + "/geth/chaindata" + fmt.Println("Running bloombits benchmark section size:", sectionSize, " compression method:", comp) + + var ( + compressFn func([]byte) []byte + decompressFn func([]byte, int) ([]byte, error) + ) + switch comp { + case 0: + // no compression + compressFn = func(data []byte) []byte { + return data + } + decompressFn = func(data []byte, target int) ([]byte, error) { + if len(data) != target { + panic(nil) + } + return data, nil + } + case 1: + // bitutil/compress.go + compressFn = bitutil.CompressBytes + decompressFn = bitutil.DecompressBytes + case 2: + // go snappy + compressFn = func(data []byte) []byte { + return snappy.Encode(nil, data) + } + decompressFn = func(data []byte, target int) ([]byte, error) { + decomp, err := snappy.Decode(nil, data) + if err != nil || len(decomp) != target { + panic(err) + } + return decomp, nil + } + } + + db, err := ethdb.NewLDBDatabase(benchDataDir, 128, 1024) + if err != nil { + b.Fatalf("error opening database at %v: %v", benchDataDir, err) + } + head := core.GetHeadBlockHash(db) + if head == (common.Hash{}) { + b.Fatalf("chain data not found at %v", benchDataDir) + } + + clearBloomBits(db) + fmt.Println("Generating bloombits data...") + headNum := core.GetBlockNumber(db, head) + if headNum < sectionSize+512 { + b.Fatalf("not enough blocks for running a benchmark") + } + + start := time.Now() + cnt := (headNum - 512) / sectionSize + var dataSize, compSize uint64 + for sectionIdx := uint64(0); sectionIdx < cnt; sectionIdx++ { + bc := bloombits.NewBloomBitsCreator(sectionSize) + var header *types.Header + for i := sectionIdx * sectionSize; i < (sectionIdx+1)*sectionSize; i++ { + hash := core.GetCanonicalHash(db, i) + header = core.GetHeader(db, hash, i) + if header == nil { + b.Fatalf("Error creating bloomBits data") + } + bc.AddHeaderBloom(header.Bloom) + } + for i := 0; i < bloombits.BloomLength; i++ { + data := bc.GetBitVector(uint(i)) + comp := compressFn(data) + dataSize += uint64(len(data)) + compSize += uint64(len(comp)) + core.StoreBloomBits(db, uint64(i), sectionIdx, comp) + } + //if sectionIdx%50 == 0 { + // fmt.Println(" section", sectionIdx, "/", cnt) + //} + } + core.StoreBloomBitsAvailable(db, cnt) + + d := time.Since(start) + fmt.Println("Finished generating bloombits data") + fmt.Println(" ", d, "total ", d/time.Duration(cnt*sectionSize), "per block") + fmt.Println(" data size:", dataSize, " compressed size:", compSize, " compression ratio:", float64(compSize)/float64(dataSize)) + + fmt.Println("Running filter benchmarks...") + start = time.Now() + mux := new(event.TypeMux) + var backend *testBackend + + for i := 0; i < benchFilterCnt; i++ { + if i%20 == 0 { + db.Close() + db, _ = ethdb.NewLDBDatabase(benchDataDir, 128, 1024) + backend = &testBackend{mux, db} + } + filter := New(backend, sectionSize) + filter.decompress = decompressFn + var addr common.Address + addr[0] = byte(i) + addr[1] = byte(i / 256) + filter.SetAddresses([]common.Address{addr}) + filter.SetBeginBlock(0) + filter.SetEndBlock(int64(cnt*sectionSize - 1)) + if _, err := filter.Find(context.Background()); err != nil { + b.Error("filter.Find error:", err) + } + } + d = time.Since(start) + fmt.Println("Finished running filter benchmarks") + fmt.Println(" ", d, "total ", d/time.Duration(benchFilterCnt), "per address", d*time.Duration(1000000)/time.Duration(benchFilterCnt*cnt*sectionSize), "per million blocks") + db.Close() +} + +func forEachKey(db ethdb.Database, startPrefix, endPrefix []byte, fn func(key []byte)) { + it := db.(*ethdb.LDBDatabase).NewIterator() + it.Seek(startPrefix) + for it.Valid() { + key := it.Key() + cmpLen := len(key) + if len(endPrefix) < cmpLen { + cmpLen = len(endPrefix) + } + if bytes.Compare(key[:cmpLen], endPrefix) == 1 { + break + } + fn(common.CopyBytes(key)) + it.Next() + } + it.Release() +} + +var bloomBitsPrefix = []byte("bloomBits-") + +func clearBloomBits(db ethdb.Database) { + fmt.Println("Clearing bloombits data...") + forEachKey(db, bloomBitsPrefix, bloomBitsPrefix, func(key []byte) { + db.Delete(key) + }) + core.StoreBloomBitsAvailable(db, 0) + fmt.Println("Cleared bloombits data") +} + +func BenchmarkNoBloomBits(b *testing.B) { + benchDataDir := node.DefaultDataDir() + "/geth/chaindata" + fmt.Println("Running benchmark without bloombits") + db, err := ethdb.NewLDBDatabase(benchDataDir, 128, 1024) + if err != nil { + b.Fatalf("error opening database at %v: %v", benchDataDir, err) + } + head := core.GetHeadBlockHash(db) + if head == (common.Hash{}) { + b.Fatalf("chain data not found at %v", benchDataDir) + } + headNum := core.GetBlockNumber(db, head) + + clearBloomBits(db) + + fmt.Println("Running filter benchmarks...") + start := time.Now() + mux := new(event.TypeMux) + backend := &testBackend{mux, db} + filter := New(backend, 4096) // give any dummy section size, no bloombits data is available + var addr common.Address + filter.SetAddresses([]common.Address{addr}) + filter.SetBeginBlock(0) + filter.SetEndBlock(int64(headNum)) + filter.Find(context.Background()) + d := time.Since(start) + fmt.Println("Finished running filter benchmarks") + fmt.Println(" ", d, "total ", d*time.Duration(1000000)/time.Duration(headNum+1), "per million blocks") + db.Close() +} diff --git a/eth/filters/filter.go b/eth/filters/filter.go index 5fc918c30b..6f902c750c 100644 --- a/eth/filters/filter.go +++ b/eth/filters/filter.go @@ -52,7 +52,8 @@ type Filter struct { addresses []common.Address topics [][]common.Hash - matcher *bloombits.Matcher + decompress func([]byte, int) ([]byte, error) + matcher *bloombits.Matcher } // New creates a new filter which uses a bloom filter on blocks to figure out whether @@ -63,6 +64,7 @@ func New(backend Backend, bloomBitsSection uint64) *Filter { bloomBitsSection: bloomBitsSection, db: backend.ChainDb(), matcher: bloombits.NewMatcher(bloomBitsSection), + decompress: bitutil.DecompressBytes, } } @@ -130,7 +132,7 @@ func (f *Filter) Find(ctx context.Context) (logs []*types.Log, err error) { // serveMatcher serves the bloomBits matcher by fetching the requested vectors // through the filter backend func (f *Filter) serveMatcher(ctx context.Context, stop chan struct{}, wg *sync.WaitGroup) chan error { - errChn := make(chan error) + errChn := make(chan error, 1) wg.Add(10) for i := 0; i < 10; i++ { go func(i int) { @@ -143,14 +145,20 @@ func (f *Filter) serveMatcher(ctx context.Context, stop chan struct{}, wg *sync. } data, err := f.backend.GetBloomBits(ctx, uint64(b), s) if err != nil { - errChn <- err + select { + case errChn <- err: + case <-stop: + } return } decomp := make([][]byte, len(data)) for i, d := range data { var err error - if decomp[i], err = bitutil.DecompressBytes(d, int(f.bloomBitsSection)); err != nil { - errChn <- err + if decomp[i], err = f.decompress(d, int(f.bloomBitsSection/8)); err != nil { + select { + case errChn <- err: + case <-stop: + } return } } From 4f2b101d2776c36180aea1c3e7422bf7204f8673 Mon Sep 17 00:00:00 2001 From: Zsolt Felfoldi Date: Tue, 9 May 2017 21:15:54 +0200 Subject: [PATCH 11/11] eth/filter, core/bloombits: pass begin, end, addresses and topics at create time --- core/bloombits/matcher.go | 15 ++++++----- core/bloombits/matcher_test.go | 2 +- eth/api_backend.go | 4 +++ eth/filters/api.go | 19 +++++--------- eth/filters/bench_test.go | 13 +++------- eth/filters/filter.go | 36 ++++++-------------------- eth/filters/filter_system_test.go | 4 +++ eth/filters/filter_test.go | 43 ++++++------------------------- les/api_backend.go | 4 +++ 9 files changed, 48 insertions(+), 92 deletions(-) diff --git a/core/bloombits/matcher.go b/core/bloombits/matcher.go index f9d9aefc5a..3c9457ee9b 100644 --- a/core/bloombits/matcher.go +++ b/core/bloombits/matcher.go @@ -164,13 +164,16 @@ type Matcher struct { } // NewMatcher creates a new Matcher instance -func NewMatcher(sectionSize uint64) *Matcher { - return &Matcher{fetchers: make(map[uint]*fetcher), reqs: make(map[uint][]uint64), distCh: make(chan distReq, channelCap), sectionSize: sectionSize} +func NewMatcher(sectionSize uint64, addresses []common.Address, topics [][]common.Hash) *Matcher { + m := &Matcher{fetchers: make(map[uint]*fetcher), reqs: make(map[uint][]uint64), distCh: make(chan distReq, channelCap), sectionSize: sectionSize} + m.setAddresses(addresses) + m.setTopics(topics) + return m } -// SetAddresses matches only logs that are generated from addresses that are included +// setAddresses matches only logs that are generated from addresses that are included // in the given addresses. -func (m *Matcher) SetAddresses(addr []common.Address) { +func (m *Matcher) setAddresses(addr []common.Address) { m.addresses = make([]types.BloomIndexList, len(addr)) for i, b := range addr { m.addresses[i] = types.BloomIndexes(b.Bytes()) @@ -183,8 +186,8 @@ func (m *Matcher) SetAddresses(addr []common.Address) { } } -// SetTopics matches only logs that have topics matching the given topics. -func (m *Matcher) SetTopics(topics [][]common.Hash) { +// setTopics matches only logs that have topics matching the given topics. +func (m *Matcher) setTopics(topics [][]common.Hash) { m.topics = nil loop: for _, topicList := range topics { diff --git a/core/bloombits/matcher_test.go b/core/bloombits/matcher_test.go index a2f786204e..3b3436da76 100644 --- a/core/bloombits/matcher_test.go +++ b/core/bloombits/matcher_test.go @@ -94,7 +94,7 @@ func testServeMatcher(m *Matcher, stop chan struct{}, cnt *uint32) { } func testMatcher(t *testing.T, idxs [][]types.BloomIndexList, cnt uint64, stopOnMatches bool, expCount uint32) uint32 { - m := NewMatcher(testSectionSize) + m := NewMatcher(testSectionSize, nil, nil) for _, idxss := range idxs { for _, idxs := range idxss { diff --git a/eth/api_backend.go b/eth/api_backend.go index 6b675da22c..b960d5d9e0 100644 --- a/eth/api_backend.go +++ b/eth/api_backend.go @@ -213,6 +213,10 @@ func (b *EthApiBackend) GetBloomBits(ctx context.Context, bitIdx uint64, section return results, nil } +func (b *EthApiBackend) BloomBitsSectionSize() uint64 { + return bloomBitsSection +} + type EthApiState struct { state *state.StateDB } diff --git a/eth/filters/api.go b/eth/filters/api.go index 24ac789009..11767753e3 100644 --- a/eth/filters/api.go +++ b/eth/filters/api.go @@ -333,11 +333,7 @@ func (api *PublicFilterAPI) GetLogs(ctx context.Context, crit FilterCriteria) ([ crit.ToBlock = big.NewInt(rpc.LatestBlockNumber.Int64()) } - filter := New(api.backend, api.bloomBitsSection) - filter.SetBeginBlock(crit.FromBlock.Int64()) - filter.SetEndBlock(crit.ToBlock.Int64()) - filter.SetAddresses(crit.Addresses) - filter.SetTopics(crit.Topics) + filter := New(api.backend, crit.FromBlock.Int64(), crit.ToBlock.Int64(), crit.Addresses, crit.Topics) logs, err := filter.Find(ctx) return returnLogs(logs), err @@ -373,19 +369,18 @@ func (api *PublicFilterAPI) GetFilterLogs(ctx context.Context, id rpc.ID) ([]*ty return nil, fmt.Errorf("filter not found") } - filter := New(api.backend, api.bloomBitsSection) + var begin, end int64 if f.crit.FromBlock != nil { - filter.SetBeginBlock(f.crit.FromBlock.Int64()) + begin = f.crit.FromBlock.Int64() } else { - filter.SetBeginBlock(rpc.LatestBlockNumber.Int64()) + begin = rpc.LatestBlockNumber.Int64() } if f.crit.ToBlock != nil { - filter.SetEndBlock(f.crit.ToBlock.Int64()) + end = f.crit.ToBlock.Int64() } else { - filter.SetEndBlock(rpc.LatestBlockNumber.Int64()) + end = rpc.LatestBlockNumber.Int64() } - filter.SetAddresses(f.crit.Addresses) - filter.SetTopics(f.crit.Topics) + filter := New(api.backend, begin, end, f.crit.Addresses, f.crit.Topics) logs, err := filter.Find(ctx) if err != nil { diff --git a/eth/filters/bench_test.go b/eth/filters/bench_test.go index 64a9dc57b3..59183f4e42 100644 --- a/eth/filters/bench_test.go +++ b/eth/filters/bench_test.go @@ -167,14 +167,11 @@ func benchmarkBloomBits(b *testing.B, sectionSize uint64, comp int) { db, _ = ethdb.NewLDBDatabase(benchDataDir, 128, 1024) backend = &testBackend{mux, db} } - filter := New(backend, sectionSize) - filter.decompress = decompressFn var addr common.Address addr[0] = byte(i) addr[1] = byte(i / 256) - filter.SetAddresses([]common.Address{addr}) - filter.SetBeginBlock(0) - filter.SetEndBlock(int64(cnt*sectionSize - 1)) + filter := New(backend, 0, int64(cnt*sectionSize-1), []common.Address{addr}, nil) + filter.decompress = decompressFn if _, err := filter.Find(context.Background()); err != nil { b.Error("filter.Find error:", err) } @@ -233,11 +230,7 @@ func BenchmarkNoBloomBits(b *testing.B) { start := time.Now() mux := new(event.TypeMux) backend := &testBackend{mux, db} - filter := New(backend, 4096) // give any dummy section size, no bloombits data is available - var addr common.Address - filter.SetAddresses([]common.Address{addr}) - filter.SetBeginBlock(0) - filter.SetEndBlock(int64(headNum)) + filter := New(backend, 0, int64(headNum), []common.Address{common.Address{}}, nil) filter.Find(context.Background()) d := time.Since(start) fmt.Println("Finished running filter benchmarks") diff --git a/eth/filters/filter.go b/eth/filters/filter.go index 6f902c750c..a0dc230b38 100644 --- a/eth/filters/filter.go +++ b/eth/filters/filter.go @@ -38,6 +38,7 @@ type Backend interface { HeaderByNumber(ctx context.Context, blockNr rpc.BlockNumber) (*types.Header, error) GetReceipts(ctx context.Context, blockHash common.Hash) (types.Receipts, error) GetBloomBits(ctx context.Context, bitIdx uint64, sectionIdxList []uint64) ([][]byte, error) + BloomBitsSectionSize() uint64 } // Filter can be used to retrieve and filter logs. @@ -58,41 +59,20 @@ type Filter struct { // New creates a new filter which uses a bloom filter on blocks to figure out whether // a particular block is interesting or not. -func New(backend Backend, bloomBitsSection uint64) *Filter { +func New(backend Backend, begin, end int64, addresses []common.Address, topics [][]common.Hash) *Filter { return &Filter{ backend: backend, - bloomBitsSection: bloomBitsSection, + begin: begin, + end: end, + addresses: addresses, + topics: topics, + bloomBitsSection: backend.BloomBitsSectionSize(), db: backend.ChainDb(), - matcher: bloombits.NewMatcher(bloomBitsSection), + matcher: bloombits.NewMatcher(backend.BloomBitsSectionSize(), addresses, topics), decompress: bitutil.DecompressBytes, } } -// SetBeginBlock sets the earliest block for filtering. -// -1 = latest block (i.e., the current block) -// hash = particular hash from-to -func (f *Filter) SetBeginBlock(begin int64) { - f.begin = begin -} - -// SetEndBlock sets the latest block for filtering. -func (f *Filter) SetEndBlock(end int64) { - f.end = end -} - -// SetAddresses matches only logs that are generated from addresses that are included -// in the given addresses. -func (f *Filter) SetAddresses(addr []common.Address) { - f.addresses = addr - f.matcher.SetAddresses(addr) -} - -// SetTopics matches only logs that have topics matching the given topics. -func (f *Filter) SetTopics(topics [][]common.Hash) { - f.topics = topics - f.matcher.SetTopics(topics) -} - // FindOnce searches the blockchain for matching log entries, returning // all matching entries from the first block that contains matches, // updating the start point of the filter accordingly. If no results are diff --git a/eth/filters/filter_system_test.go b/eth/filters/filter_system_test.go index aa017c2ff5..0cf73c4a0c 100644 --- a/eth/filters/filter_system_test.go +++ b/eth/filters/filter_system_test.go @@ -75,6 +75,10 @@ func (b *testBackend) GetBloomBits(ctx context.Context, bitIdx uint64, sectionId return results, nil } +func (b *testBackend) BloomBitsSectionSize() uint64 { + return testBloomBitsSection +} + // TestBlockSubscription tests if a block subscription returns block hashes for posted chain events. // It creates multiple subscriptions: // - one at the start and should receive all posted chain events and a second (blockHashes) diff --git a/eth/filters/filter_test.go b/eth/filters/filter_test.go index 0848557dec..c92bec8518 100644 --- a/eth/filters/filter_test.go +++ b/eth/filters/filter_test.go @@ -105,10 +105,7 @@ func BenchmarkFilters(b *testing.B) { } b.ResetTimer() - filter := New(backend, testBloomBitsSection) - filter.SetAddresses([]common.Address{addr1, addr2, addr3, addr4}) - filter.SetBeginBlock(0) - filter.SetEndBlock(-1) + filter := New(backend, 0, -1, []common.Address{addr1, addr2, addr3, addr4}, nil) for i := 0; i < b.N; i++ { logs, _ := filter.Find(context.Background()) @@ -204,22 +201,14 @@ func TestFilters(t *testing.T) { } } - filter := New(backend, testBloomBitsSection) - filter.SetAddresses([]common.Address{addr}) - filter.SetTopics([][]common.Hash{{hash1, hash2, hash3, hash4}}) - filter.SetBeginBlock(0) - filter.SetEndBlock(-1) + filter := New(backend, 0, -1, []common.Address{addr}, [][]common.Hash{{hash1, hash2, hash3, hash4}}) logs, _ := filter.Find(context.Background()) if len(logs) != 4 { t.Error("expected 4 log, got", len(logs)) } - filter = New(backend, testBloomBitsSection) - filter.SetAddresses([]common.Address{addr}) - filter.SetTopics([][]common.Hash{{hash3}}) - filter.SetBeginBlock(900) - filter.SetEndBlock(999) + filter = New(backend, 900, 999, []common.Address{addr}, [][]common.Hash{{hash3}}) logs, _ = filter.Find(context.Background()) if len(logs) != 1 { t.Error("expected 1 log, got", len(logs)) @@ -228,11 +217,7 @@ func TestFilters(t *testing.T) { t.Errorf("expected log[0].Topics[0] to be %x, got %x", hash3, logs[0].Topics[0]) } - filter = New(backend, testBloomBitsSection) - filter.SetAddresses([]common.Address{addr}) - filter.SetTopics([][]common.Hash{{hash3}}) - filter.SetBeginBlock(990) - filter.SetEndBlock(-1) + filter = New(backend, 990, -1, []common.Address{addr}, [][]common.Hash{{hash3}}) logs, _ = filter.Find(context.Background()) if len(logs) != 1 { t.Error("expected 1 log, got", len(logs)) @@ -241,10 +226,7 @@ func TestFilters(t *testing.T) { t.Errorf("expected log[0].Topics[0] to be %x, got %x", hash3, logs[0].Topics[0]) } - filter = New(backend, testBloomBitsSection) - filter.SetTopics([][]common.Hash{{hash1, hash2}}) - filter.SetBeginBlock(1) - filter.SetEndBlock(10) + filter = New(backend, 1, 10, nil, [][]common.Hash{{hash1, hash2}}) logs, _ = filter.Find(context.Background()) if len(logs) != 2 { @@ -252,10 +234,7 @@ func TestFilters(t *testing.T) { } failHash := common.BytesToHash([]byte("fail")) - filter = New(backend, testBloomBitsSection) - filter.SetTopics([][]common.Hash{{failHash}}) - filter.SetBeginBlock(0) - filter.SetEndBlock(-1) + filter = New(backend, 0, -1, nil, [][]common.Hash{{failHash}}) logs, _ = filter.Find(context.Background()) if len(logs) != 0 { @@ -263,20 +242,14 @@ func TestFilters(t *testing.T) { } failAddr := common.BytesToAddress([]byte("failmenow")) - filter = New(backend, testBloomBitsSection) - filter.SetAddresses([]common.Address{failAddr}) - filter.SetBeginBlock(0) - filter.SetEndBlock(-1) + filter = New(backend, 0, -1, []common.Address{failAddr}, nil) logs, _ = filter.Find(context.Background()) if len(logs) != 0 { t.Error("expected 0 log, got", len(logs)) } - filter = New(backend, testBloomBitsSection) - filter.SetTopics([][]common.Hash{{failHash}, {hash1}}) - filter.SetBeginBlock(0) - filter.SetEndBlock(-1) + filter = New(backend, 0, -1, nil, [][]common.Hash{{failHash}, {hash1}}) logs, _ = filter.Find(context.Background()) if len(logs) != 0 { diff --git a/les/api_backend.go b/les/api_backend.go index 175118e334..01d8584782 100644 --- a/les/api_backend.go +++ b/les/api_backend.go @@ -159,3 +159,7 @@ func (b *LesApiBackend) AccountManager() *accounts.Manager { func (b *LesApiBackend) GetBloomBits(ctx context.Context, bitIdx uint64, sectionIdxList []uint64) ([][]byte, error) { return nil, nil // implemented in a subsequent PR } + +func (b *LesApiBackend) BloomBitsSectionSize() uint64 { + return 0 +}