github.com/etherite/go-etherite@v0.0.0-20171015192807-5f4dd87b2f6e/eth/filters/filter.go (about) 1 // Copyright 2014 The go-ethereum Authors 2 // This file is part of the go-ethereum library. 3 // 4 // The go-ethereum library is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // The go-ethereum library is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU Lesser General Public License for more details. 13 // 14 // You should have received a copy of the GNU Lesser General Public License 15 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 16 17 package filters 18 19 import ( 20 "context" 21 "math/big" 22 "time" 23 24 "github.com/etherite/go-etherite/common" 25 "github.com/etherite/go-etherite/core" 26 "github.com/etherite/go-etherite/core/bloombits" 27 "github.com/etherite/go-etherite/core/types" 28 "github.com/etherite/go-etherite/ethdb" 29 "github.com/etherite/go-etherite/event" 30 "github.com/etherite/go-etherite/rpc" 31 ) 32 33 type Backend interface { 34 ChainDb() ethdb.Database 35 EventMux() *event.TypeMux 36 HeaderByNumber(ctx context.Context, blockNr rpc.BlockNumber) (*types.Header, error) 37 GetReceipts(ctx context.Context, blockHash common.Hash) (types.Receipts, error) 38 39 SubscribeTxPreEvent(chan<- core.TxPreEvent) event.Subscription 40 SubscribeChainEvent(ch chan<- core.ChainEvent) event.Subscription 41 SubscribeRemovedLogsEvent(ch chan<- core.RemovedLogsEvent) event.Subscription 42 SubscribeLogsEvent(ch chan<- []*types.Log) event.Subscription 43 44 BloomStatus() (uint64, uint64) 45 ServiceFilter(ctx context.Context, session *bloombits.MatcherSession) 46 } 47 48 // Filter can be used to retrieve and filter logs. 49 type Filter struct { 50 backend Backend 51 52 db ethdb.Database 53 begin, end int64 54 addresses []common.Address 55 topics [][]common.Hash 56 57 matcher *bloombits.Matcher 58 } 59 60 // New creates a new filter which uses a bloom filter on blocks to figure out whether 61 // a particular block is interesting or not. 62 func New(backend Backend, begin, end int64, addresses []common.Address, topics [][]common.Hash) *Filter { 63 // Flatten the address and topic filter clauses into a single bloombits filter 64 // system. Since the bloombits are not positional, nil topics are permitted, 65 // which get flattened into a nil byte slice. 66 var filters [][][]byte 67 if len(addresses) > 0 { 68 filter := make([][]byte, len(addresses)) 69 for i, address := range addresses { 70 filter[i] = address.Bytes() 71 } 72 filters = append(filters, filter) 73 } 74 for _, topicList := range topics { 75 filter := make([][]byte, len(topicList)) 76 for i, topic := range topicList { 77 filter[i] = topic.Bytes() 78 } 79 filters = append(filters, filter) 80 } 81 // Assemble and return the filter 82 size, _ := backend.BloomStatus() 83 84 return &Filter{ 85 backend: backend, 86 begin: begin, 87 end: end, 88 addresses: addresses, 89 topics: topics, 90 db: backend.ChainDb(), 91 matcher: bloombits.NewMatcher(size, filters), 92 } 93 } 94 95 // Logs searches the blockchain for matching log entries, returning all from the 96 // first block that contains matches, updating the start of the filter accordingly. 97 func (f *Filter) Logs(ctx context.Context) ([]*types.Log, error) { 98 // Figure out the limits of the filter range 99 header, _ := f.backend.HeaderByNumber(ctx, rpc.LatestBlockNumber) 100 if header == nil { 101 return nil, nil 102 } 103 head := header.Number.Uint64() 104 105 if f.begin == -1 { 106 f.begin = int64(head) 107 } 108 end := uint64(f.end) 109 if f.end == -1 { 110 end = head 111 } 112 // Gather all indexed logs, and finish with non indexed ones 113 var ( 114 logs []*types.Log 115 err error 116 ) 117 size, sections := f.backend.BloomStatus() 118 if indexed := sections * size; indexed > uint64(f.begin) { 119 if indexed > end { 120 logs, err = f.indexedLogs(ctx, end) 121 } else { 122 logs, err = f.indexedLogs(ctx, indexed-1) 123 } 124 if err != nil { 125 return logs, err 126 } 127 } 128 rest, err := f.unindexedLogs(ctx, end) 129 logs = append(logs, rest...) 130 return logs, err 131 } 132 133 // indexedLogs returns the logs matching the filter criteria based on the bloom 134 // bits indexed available locally or via the network. 135 func (f *Filter) indexedLogs(ctx context.Context, end uint64) ([]*types.Log, error) { 136 // Create a matcher session and request servicing from the backend 137 matches := make(chan uint64, 64) 138 139 session, err := f.matcher.Start(uint64(f.begin), end, matches) 140 if err != nil { 141 return nil, err 142 } 143 defer session.Close(time.Second) 144 145 f.backend.ServiceFilter(ctx, session) 146 147 // Iterate over the matches until exhausted or context closed 148 var logs []*types.Log 149 150 for { 151 select { 152 case number, ok := <-matches: 153 // Abort if all matches have been fulfilled 154 if !ok { 155 f.begin = int64(end) + 1 156 return logs, nil 157 } 158 // Retrieve the suggested block and pull any truly matching logs 159 header, err := f.backend.HeaderByNumber(ctx, rpc.BlockNumber(number)) 160 if header == nil || err != nil { 161 return logs, err 162 } 163 found, err := f.checkMatches(ctx, header) 164 if err != nil { 165 return logs, err 166 } 167 logs = append(logs, found...) 168 169 case <-ctx.Done(): 170 return logs, ctx.Err() 171 } 172 } 173 } 174 175 // indexedLogs returns the logs matching the filter criteria based on raw block 176 // iteration and bloom matching. 177 func (f *Filter) unindexedLogs(ctx context.Context, end uint64) ([]*types.Log, error) { 178 var logs []*types.Log 179 180 for ; f.begin <= int64(end); f.begin++ { 181 header, err := f.backend.HeaderByNumber(ctx, rpc.BlockNumber(f.begin)) 182 if header == nil || err != nil { 183 return logs, err 184 } 185 if bloomFilter(header.Bloom, f.addresses, f.topics) { 186 found, err := f.checkMatches(ctx, header) 187 if err != nil { 188 return logs, err 189 } 190 logs = append(logs, found...) 191 } 192 } 193 return logs, nil 194 } 195 196 // checkMatches checks if the receipts belonging to the given header contain any log events that 197 // match the filter criteria. This function is called when the bloom filter signals a potential match. 198 func (f *Filter) checkMatches(ctx context.Context, header *types.Header) (logs []*types.Log, err error) { 199 // Get the logs of the block 200 receipts, err := f.backend.GetReceipts(ctx, header.Hash()) 201 if err != nil { 202 return nil, err 203 } 204 var unfiltered []*types.Log 205 for _, receipt := range receipts { 206 unfiltered = append(unfiltered, ([]*types.Log)(receipt.Logs)...) 207 } 208 logs = filterLogs(unfiltered, nil, nil, f.addresses, f.topics) 209 if len(logs) > 0 { 210 return logs, nil 211 } 212 return nil, nil 213 } 214 215 func includes(addresses []common.Address, a common.Address) bool { 216 for _, addr := range addresses { 217 if addr == a { 218 return true 219 } 220 } 221 222 return false 223 } 224 225 // filterLogs creates a slice of logs matching the given criteria. 226 func filterLogs(logs []*types.Log, fromBlock, toBlock *big.Int, addresses []common.Address, topics [][]common.Hash) []*types.Log { 227 var ret []*types.Log 228 Logs: 229 for _, log := range logs { 230 if fromBlock != nil && fromBlock.Int64() >= 0 && fromBlock.Uint64() > log.BlockNumber { 231 continue 232 } 233 if toBlock != nil && toBlock.Int64() >= 0 && toBlock.Uint64() < log.BlockNumber { 234 continue 235 } 236 237 if len(addresses) > 0 && !includes(addresses, log.Address) { 238 continue 239 } 240 // If the to filtered topics is greater than the amount of topics in logs, skip. 241 if len(topics) > len(log.Topics) { 242 continue Logs 243 } 244 for i, topics := range topics { 245 match := len(topics) == 0 // empty rule set == wildcard 246 for _, topic := range topics { 247 if log.Topics[i] == topic { 248 match = true 249 break 250 } 251 } 252 if !match { 253 continue Logs 254 } 255 } 256 ret = append(ret, log) 257 } 258 return ret 259 } 260 261 func bloomFilter(bloom types.Bloom, addresses []common.Address, topics [][]common.Hash) bool { 262 if len(addresses) > 0 { 263 var included bool 264 for _, addr := range addresses { 265 if types.BloomLookup(bloom, addr) { 266 included = true 267 break 268 } 269 } 270 if !included { 271 return false 272 } 273 } 274 275 for _, sub := range topics { 276 included := len(sub) == 0 // empty rule set == wildcard 277 for _, topic := range sub { 278 if types.BloomLookup(bloom, topic) { 279 included = true 280 break 281 } 282 } 283 if !included { 284 return false 285 } 286 } 287 return true 288 }