gitee.com/liu-zhao234568/cntest@v1.0.0/eth/filters/filter_system.go (about) 1 // Copyright 2015 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 implements an ethereum filtering system for block, 18 // transactions and log events. 19 package filters 20 21 import ( 22 "context" 23 "fmt" 24 "sync" 25 "time" 26 27 ethereum "gitee.com/liu-zhao234568/cntest" 28 "gitee.com/liu-zhao234568/cntest/common" 29 "gitee.com/liu-zhao234568/cntest/core" 30 "gitee.com/liu-zhao234568/cntest/core/rawdb" 31 "gitee.com/liu-zhao234568/cntest/core/types" 32 "gitee.com/liu-zhao234568/cntest/event" 33 "gitee.com/liu-zhao234568/cntest/log" 34 "gitee.com/liu-zhao234568/cntest/rpc" 35 ) 36 37 // Type determines the kind of filter and is used to put the filter in to 38 // the correct bucket when added. 39 type Type byte 40 41 const ( 42 // UnknownSubscription indicates an unknown subscription type 43 UnknownSubscription Type = iota 44 // LogsSubscription queries for new or removed (chain reorg) logs 45 LogsSubscription 46 // PendingLogsSubscription queries for logs in pending blocks 47 PendingLogsSubscription 48 // MinedAndPendingLogsSubscription queries for logs in mined and pending blocks. 49 MinedAndPendingLogsSubscription 50 // PendingTransactionsSubscription queries tx hashes for pending 51 // transactions entering the pending state 52 PendingTransactionsSubscription 53 // BlocksSubscription queries hashes for blocks that are imported 54 BlocksSubscription 55 // LastSubscription keeps track of the last index 56 LastIndexSubscription 57 ) 58 59 const ( 60 // txChanSize is the size of channel listening to NewTxsEvent. 61 // The number is referenced from the size of tx pool. 62 txChanSize = 4096 63 // rmLogsChanSize is the size of channel listening to RemovedLogsEvent. 64 rmLogsChanSize = 10 65 // logsChanSize is the size of channel listening to LogsEvent. 66 logsChanSize = 10 67 // chainEvChanSize is the size of channel listening to ChainEvent. 68 chainEvChanSize = 10 69 ) 70 71 type subscription struct { 72 id rpc.ID 73 typ Type 74 created time.Time 75 logsCrit ethereum.FilterQuery 76 logs chan []*types.Log 77 hashes chan []common.Hash 78 headers chan *types.Header 79 installed chan struct{} // closed when the filter is installed 80 err chan error // closed when the filter is uninstalled 81 } 82 83 // EventSystem creates subscriptions, processes events and broadcasts them to the 84 // subscription which match the subscription criteria. 85 type EventSystem struct { 86 backend Backend 87 lightMode bool 88 lastHead *types.Header 89 90 // Subscriptions 91 txsSub event.Subscription // Subscription for new transaction event 92 logsSub event.Subscription // Subscription for new log event 93 rmLogsSub event.Subscription // Subscription for removed log event 94 pendingLogsSub event.Subscription // Subscription for pending log event 95 chainSub event.Subscription // Subscription for new chain event 96 97 // Channels 98 install chan *subscription // install filter for event notification 99 uninstall chan *subscription // remove filter for event notification 100 txsCh chan core.NewTxsEvent // Channel to receive new transactions event 101 logsCh chan []*types.Log // Channel to receive new log event 102 pendingLogsCh chan []*types.Log // Channel to receive new log event 103 rmLogsCh chan core.RemovedLogsEvent // Channel to receive removed log event 104 chainCh chan core.ChainEvent // Channel to receive new chain event 105 } 106 107 // NewEventSystem creates a new manager that listens for event on the given mux, 108 // parses and filters them. It uses the all map to retrieve filter changes. The 109 // work loop holds its own index that is used to forward events to filters. 110 // 111 // The returned manager has a loop that needs to be stopped with the Stop function 112 // or by stopping the given mux. 113 func NewEventSystem(backend Backend, lightMode bool) *EventSystem { 114 m := &EventSystem{ 115 backend: backend, 116 lightMode: lightMode, 117 install: make(chan *subscription), 118 uninstall: make(chan *subscription), 119 txsCh: make(chan core.NewTxsEvent, txChanSize), 120 logsCh: make(chan []*types.Log, logsChanSize), 121 rmLogsCh: make(chan core.RemovedLogsEvent, rmLogsChanSize), 122 pendingLogsCh: make(chan []*types.Log, logsChanSize), 123 chainCh: make(chan core.ChainEvent, chainEvChanSize), 124 } 125 126 // Subscribe events 127 m.txsSub = m.backend.SubscribeNewTxsEvent(m.txsCh) 128 m.logsSub = m.backend.SubscribeLogsEvent(m.logsCh) 129 m.rmLogsSub = m.backend.SubscribeRemovedLogsEvent(m.rmLogsCh) 130 m.chainSub = m.backend.SubscribeChainEvent(m.chainCh) 131 m.pendingLogsSub = m.backend.SubscribePendingLogsEvent(m.pendingLogsCh) 132 133 // Make sure none of the subscriptions are empty 134 if m.txsSub == nil || m.logsSub == nil || m.rmLogsSub == nil || m.chainSub == nil || m.pendingLogsSub == nil { 135 log.Crit("Subscribe for event system failed") 136 } 137 138 go m.eventLoop() 139 return m 140 } 141 142 // Subscription is created when the client registers itself for a particular event. 143 type Subscription struct { 144 ID rpc.ID 145 f *subscription 146 es *EventSystem 147 unsubOnce sync.Once 148 } 149 150 // Err returns a channel that is closed when unsubscribed. 151 func (sub *Subscription) Err() <-chan error { 152 return sub.f.err 153 } 154 155 // Unsubscribe uninstalls the subscription from the event broadcast loop. 156 func (sub *Subscription) Unsubscribe() { 157 sub.unsubOnce.Do(func() { 158 uninstallLoop: 159 for { 160 // write uninstall request and consume logs/hashes. This prevents 161 // the eventLoop broadcast method to deadlock when writing to the 162 // filter event channel while the subscription loop is waiting for 163 // this method to return (and thus not reading these events). 164 select { 165 case sub.es.uninstall <- sub.f: 166 break uninstallLoop 167 case <-sub.f.logs: 168 case <-sub.f.hashes: 169 case <-sub.f.headers: 170 } 171 } 172 173 // wait for filter to be uninstalled in work loop before returning 174 // this ensures that the manager won't use the event channel which 175 // will probably be closed by the client asap after this method returns. 176 <-sub.Err() 177 }) 178 } 179 180 // subscribe installs the subscription in the event broadcast loop. 181 func (es *EventSystem) subscribe(sub *subscription) *Subscription { 182 es.install <- sub 183 <-sub.installed 184 return &Subscription{ID: sub.id, f: sub, es: es} 185 } 186 187 // SubscribeLogs creates a subscription that will write all logs matching the 188 // given criteria to the given logs channel. Default value for the from and to 189 // block is "latest". If the fromBlock > toBlock an error is returned. 190 func (es *EventSystem) SubscribeLogs(crit ethereum.FilterQuery, logs chan []*types.Log) (*Subscription, error) { 191 var from, to rpc.BlockNumber 192 if crit.FromBlock == nil { 193 from = rpc.LatestBlockNumber 194 } else { 195 from = rpc.BlockNumber(crit.FromBlock.Int64()) 196 } 197 if crit.ToBlock == nil { 198 to = rpc.LatestBlockNumber 199 } else { 200 to = rpc.BlockNumber(crit.ToBlock.Int64()) 201 } 202 203 // only interested in pending logs 204 if from == rpc.PendingBlockNumber && to == rpc.PendingBlockNumber { 205 return es.subscribePendingLogs(crit, logs), nil 206 } 207 // only interested in new mined logs 208 if from == rpc.LatestBlockNumber && to == rpc.LatestBlockNumber { 209 return es.subscribeLogs(crit, logs), nil 210 } 211 // only interested in mined logs within a specific block range 212 if from >= 0 && to >= 0 && to >= from { 213 return es.subscribeLogs(crit, logs), nil 214 } 215 // interested in mined logs from a specific block number, new logs and pending logs 216 if from >= rpc.LatestBlockNumber && to == rpc.PendingBlockNumber { 217 return es.subscribeMinedPendingLogs(crit, logs), nil 218 } 219 // interested in logs from a specific block number to new mined blocks 220 if from >= 0 && to == rpc.LatestBlockNumber { 221 return es.subscribeLogs(crit, logs), nil 222 } 223 return nil, fmt.Errorf("invalid from and to block combination: from > to") 224 } 225 226 // subscribeMinedPendingLogs creates a subscription that returned mined and 227 // pending logs that match the given criteria. 228 func (es *EventSystem) subscribeMinedPendingLogs(crit ethereum.FilterQuery, logs chan []*types.Log) *Subscription { 229 sub := &subscription{ 230 id: rpc.NewID(), 231 typ: MinedAndPendingLogsSubscription, 232 logsCrit: crit, 233 created: time.Now(), 234 logs: logs, 235 hashes: make(chan []common.Hash), 236 headers: make(chan *types.Header), 237 installed: make(chan struct{}), 238 err: make(chan error), 239 } 240 return es.subscribe(sub) 241 } 242 243 // subscribeLogs creates a subscription that will write all logs matching the 244 // given criteria to the given logs channel. 245 func (es *EventSystem) subscribeLogs(crit ethereum.FilterQuery, logs chan []*types.Log) *Subscription { 246 sub := &subscription{ 247 id: rpc.NewID(), 248 typ: LogsSubscription, 249 logsCrit: crit, 250 created: time.Now(), 251 logs: logs, 252 hashes: make(chan []common.Hash), 253 headers: make(chan *types.Header), 254 installed: make(chan struct{}), 255 err: make(chan error), 256 } 257 return es.subscribe(sub) 258 } 259 260 // subscribePendingLogs creates a subscription that writes transaction hashes for 261 // transactions that enter the transaction pool. 262 func (es *EventSystem) subscribePendingLogs(crit ethereum.FilterQuery, logs chan []*types.Log) *Subscription { 263 sub := &subscription{ 264 id: rpc.NewID(), 265 typ: PendingLogsSubscription, 266 logsCrit: crit, 267 created: time.Now(), 268 logs: logs, 269 hashes: make(chan []common.Hash), 270 headers: make(chan *types.Header), 271 installed: make(chan struct{}), 272 err: make(chan error), 273 } 274 return es.subscribe(sub) 275 } 276 277 // SubscribeNewHeads creates a subscription that writes the header of a block that is 278 // imported in the chain. 279 func (es *EventSystem) SubscribeNewHeads(headers chan *types.Header) *Subscription { 280 sub := &subscription{ 281 id: rpc.NewID(), 282 typ: BlocksSubscription, 283 created: time.Now(), 284 logs: make(chan []*types.Log), 285 hashes: make(chan []common.Hash), 286 headers: headers, 287 installed: make(chan struct{}), 288 err: make(chan error), 289 } 290 return es.subscribe(sub) 291 } 292 293 // SubscribePendingTxs creates a subscription that writes transaction hashes for 294 // transactions that enter the transaction pool. 295 func (es *EventSystem) SubscribePendingTxs(hashes chan []common.Hash) *Subscription { 296 sub := &subscription{ 297 id: rpc.NewID(), 298 typ: PendingTransactionsSubscription, 299 created: time.Now(), 300 logs: make(chan []*types.Log), 301 hashes: hashes, 302 headers: make(chan *types.Header), 303 installed: make(chan struct{}), 304 err: make(chan error), 305 } 306 return es.subscribe(sub) 307 } 308 309 type filterIndex map[Type]map[rpc.ID]*subscription 310 311 func (es *EventSystem) handleLogs(filters filterIndex, ev []*types.Log) { 312 if len(ev) == 0 { 313 return 314 } 315 for _, f := range filters[LogsSubscription] { 316 matchedLogs := filterLogs(ev, f.logsCrit.FromBlock, f.logsCrit.ToBlock, f.logsCrit.Addresses, f.logsCrit.Topics) 317 if len(matchedLogs) > 0 { 318 f.logs <- matchedLogs 319 } 320 } 321 } 322 323 func (es *EventSystem) handlePendingLogs(filters filterIndex, ev []*types.Log) { 324 if len(ev) == 0 { 325 return 326 } 327 for _, f := range filters[PendingLogsSubscription] { 328 matchedLogs := filterLogs(ev, nil, f.logsCrit.ToBlock, f.logsCrit.Addresses, f.logsCrit.Topics) 329 if len(matchedLogs) > 0 { 330 f.logs <- matchedLogs 331 } 332 } 333 } 334 335 func (es *EventSystem) handleRemovedLogs(filters filterIndex, ev core.RemovedLogsEvent) { 336 for _, f := range filters[LogsSubscription] { 337 matchedLogs := filterLogs(ev.Logs, f.logsCrit.FromBlock, f.logsCrit.ToBlock, f.logsCrit.Addresses, f.logsCrit.Topics) 338 if len(matchedLogs) > 0 { 339 f.logs <- matchedLogs 340 } 341 } 342 } 343 344 func (es *EventSystem) handleTxsEvent(filters filterIndex, ev core.NewTxsEvent) { 345 hashes := make([]common.Hash, 0, len(ev.Txs)) 346 for _, tx := range ev.Txs { 347 hashes = append(hashes, tx.Hash()) 348 } 349 for _, f := range filters[PendingTransactionsSubscription] { 350 f.hashes <- hashes 351 } 352 } 353 354 func (es *EventSystem) handleChainEvent(filters filterIndex, ev core.ChainEvent) { 355 for _, f := range filters[BlocksSubscription] { 356 f.headers <- ev.Block.Header() 357 } 358 if es.lightMode && len(filters[LogsSubscription]) > 0 { 359 es.lightFilterNewHead(ev.Block.Header(), func(header *types.Header, remove bool) { 360 for _, f := range filters[LogsSubscription] { 361 if matchedLogs := es.lightFilterLogs(header, f.logsCrit.Addresses, f.logsCrit.Topics, remove); len(matchedLogs) > 0 { 362 f.logs <- matchedLogs 363 } 364 } 365 }) 366 } 367 } 368 369 func (es *EventSystem) lightFilterNewHead(newHeader *types.Header, callBack func(*types.Header, bool)) { 370 oldh := es.lastHead 371 es.lastHead = newHeader 372 if oldh == nil { 373 return 374 } 375 newh := newHeader 376 // find common ancestor, create list of rolled back and new block hashes 377 var oldHeaders, newHeaders []*types.Header 378 for oldh.Hash() != newh.Hash() { 379 if oldh.Number.Uint64() >= newh.Number.Uint64() { 380 oldHeaders = append(oldHeaders, oldh) 381 oldh = rawdb.ReadHeader(es.backend.ChainDb(), oldh.ParentHash, oldh.Number.Uint64()-1) 382 } 383 if oldh.Number.Uint64() < newh.Number.Uint64() { 384 newHeaders = append(newHeaders, newh) 385 newh = rawdb.ReadHeader(es.backend.ChainDb(), newh.ParentHash, newh.Number.Uint64()-1) 386 if newh == nil { 387 // happens when CHT syncing, nothing to do 388 newh = oldh 389 } 390 } 391 } 392 // roll back old blocks 393 for _, h := range oldHeaders { 394 callBack(h, true) 395 } 396 // check new blocks (array is in reverse order) 397 for i := len(newHeaders) - 1; i >= 0; i-- { 398 callBack(newHeaders[i], false) 399 } 400 } 401 402 // filter logs of a single header in light client mode 403 func (es *EventSystem) lightFilterLogs(header *types.Header, addresses []common.Address, topics [][]common.Hash, remove bool) []*types.Log { 404 if bloomFilter(header.Bloom, addresses, topics) { 405 // Get the logs of the block 406 ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) 407 defer cancel() 408 logsList, err := es.backend.GetLogs(ctx, header.Hash()) 409 if err != nil { 410 return nil 411 } 412 var unfiltered []*types.Log 413 for _, logs := range logsList { 414 for _, log := range logs { 415 logcopy := *log 416 logcopy.Removed = remove 417 unfiltered = append(unfiltered, &logcopy) 418 } 419 } 420 logs := filterLogs(unfiltered, nil, nil, addresses, topics) 421 if len(logs) > 0 && logs[0].TxHash == (common.Hash{}) { 422 // We have matching but non-derived logs 423 receipts, err := es.backend.GetReceipts(ctx, header.Hash()) 424 if err != nil { 425 return nil 426 } 427 unfiltered = unfiltered[:0] 428 for _, receipt := range receipts { 429 for _, log := range receipt.Logs { 430 logcopy := *log 431 logcopy.Removed = remove 432 unfiltered = append(unfiltered, &logcopy) 433 } 434 } 435 logs = filterLogs(unfiltered, nil, nil, addresses, topics) 436 } 437 return logs 438 } 439 return nil 440 } 441 442 // eventLoop (un)installs filters and processes mux events. 443 func (es *EventSystem) eventLoop() { 444 // Ensure all subscriptions get cleaned up 445 defer func() { 446 es.txsSub.Unsubscribe() 447 es.logsSub.Unsubscribe() 448 es.rmLogsSub.Unsubscribe() 449 es.pendingLogsSub.Unsubscribe() 450 es.chainSub.Unsubscribe() 451 }() 452 453 index := make(filterIndex) 454 for i := UnknownSubscription; i < LastIndexSubscription; i++ { 455 index[i] = make(map[rpc.ID]*subscription) 456 } 457 458 for { 459 select { 460 case ev := <-es.txsCh: 461 es.handleTxsEvent(index, ev) 462 case ev := <-es.logsCh: 463 es.handleLogs(index, ev) 464 case ev := <-es.rmLogsCh: 465 es.handleRemovedLogs(index, ev) 466 case ev := <-es.pendingLogsCh: 467 es.handlePendingLogs(index, ev) 468 case ev := <-es.chainCh: 469 es.handleChainEvent(index, ev) 470 471 case f := <-es.install: 472 if f.typ == MinedAndPendingLogsSubscription { 473 // the type are logs and pending logs subscriptions 474 index[LogsSubscription][f.id] = f 475 index[PendingLogsSubscription][f.id] = f 476 } else { 477 index[f.typ][f.id] = f 478 } 479 close(f.installed) 480 481 case f := <-es.uninstall: 482 if f.typ == MinedAndPendingLogsSubscription { 483 // the type are logs and pending logs subscriptions 484 delete(index[LogsSubscription], f.id) 485 delete(index[PendingLogsSubscription], f.id) 486 } else { 487 delete(index[f.typ], f.id) 488 } 489 close(f.err) 490 491 // System stopped 492 case <-es.txsSub.Err(): 493 return 494 case <-es.logsSub.Err(): 495 return 496 case <-es.rmLogsSub.Err(): 497 return 498 case <-es.chainSub.Err(): 499 return 500 } 501 } 502 }