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