github.com/tuotoo/go-ethereum@v1.7.4-0.20171121184211-049797d40a24/eth/filters/api.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 18 19 import ( 20 "context" 21 "encoding/json" 22 "errors" 23 "fmt" 24 "math/big" 25 "sync" 26 "time" 27 28 "github.com/ethereum/go-ethereum/common" 29 "github.com/ethereum/go-ethereum/common/hexutil" 30 "github.com/ethereum/go-ethereum/core/types" 31 "github.com/ethereum/go-ethereum/ethdb" 32 "github.com/ethereum/go-ethereum/event" 33 "github.com/ethereum/go-ethereum/rpc" 34 ) 35 36 var ( 37 deadline = 5 * time.Minute // consider a filter inactive if it has not been polled for within deadline 38 ) 39 40 // filter is a helper struct that holds meta information over the filter type 41 // and associated subscription in the event system. 42 type filter struct { 43 typ Type 44 deadline *time.Timer // filter is inactiv when deadline triggers 45 hashes []common.Hash 46 crit FilterCriteria 47 logs []*types.Log 48 s *Subscription // associated subscription in event system 49 } 50 51 // PublicFilterAPI offers support to create and manage filters. This will allow external clients to retrieve various 52 // information related to the Ethereum protocol such als blocks, transactions and logs. 53 type PublicFilterAPI struct { 54 backend Backend 55 mux *event.TypeMux 56 quit chan struct{} 57 chainDb ethdb.Database 58 events *EventSystem 59 filtersMu sync.Mutex 60 filters map[rpc.ID]*filter 61 } 62 63 // NewPublicFilterAPI returns a new PublicFilterAPI instance. 64 func NewPublicFilterAPI(backend Backend, lightMode bool) *PublicFilterAPI { 65 api := &PublicFilterAPI{ 66 backend: backend, 67 mux: backend.EventMux(), 68 chainDb: backend.ChainDb(), 69 events: NewEventSystem(backend.EventMux(), backend, lightMode), 70 filters: make(map[rpc.ID]*filter), 71 } 72 go api.timeoutLoop() 73 74 return api 75 } 76 77 // timeoutLoop runs every 5 minutes and deletes filters that have not been recently used. 78 // Tt is started when the api is created. 79 func (api *PublicFilterAPI) timeoutLoop() { 80 ticker := time.NewTicker(5 * time.Minute) 81 for { 82 <-ticker.C 83 api.filtersMu.Lock() 84 for id, f := range api.filters { 85 select { 86 case <-f.deadline.C: 87 f.s.Unsubscribe() 88 delete(api.filters, id) 89 default: 90 continue 91 } 92 } 93 api.filtersMu.Unlock() 94 } 95 } 96 97 // NewPendingTransactionFilter creates a filter that fetches pending transaction hashes 98 // as transactions enter the pending state. 99 // 100 // It is part of the filter package because this filter can be used throug the 101 // `eth_getFilterChanges` polling method that is also used for log filters. 102 // 103 // https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_newpendingtransactionfilter 104 func (api *PublicFilterAPI) NewPendingTransactionFilter() rpc.ID { 105 var ( 106 pendingTxs = make(chan common.Hash) 107 pendingTxSub = api.events.SubscribePendingTxEvents(pendingTxs) 108 ) 109 110 api.filtersMu.Lock() 111 api.filters[pendingTxSub.ID] = &filter{typ: PendingTransactionsSubscription, deadline: time.NewTimer(deadline), hashes: make([]common.Hash, 0), s: pendingTxSub} 112 api.filtersMu.Unlock() 113 114 go func() { 115 for { 116 select { 117 case ph := <-pendingTxs: 118 api.filtersMu.Lock() 119 if f, found := api.filters[pendingTxSub.ID]; found { 120 f.hashes = append(f.hashes, ph) 121 } 122 api.filtersMu.Unlock() 123 case <-pendingTxSub.Err(): 124 api.filtersMu.Lock() 125 delete(api.filters, pendingTxSub.ID) 126 api.filtersMu.Unlock() 127 return 128 } 129 } 130 }() 131 132 return pendingTxSub.ID 133 } 134 135 // NewPendingTransactions creates a subscription that is triggered each time a transaction 136 // enters the transaction pool and was signed from one of the transactions this nodes manages. 137 func (api *PublicFilterAPI) NewPendingTransactions(ctx context.Context) (*rpc.Subscription, error) { 138 notifier, supported := rpc.NotifierFromContext(ctx) 139 if !supported { 140 return &rpc.Subscription{}, rpc.ErrNotificationsUnsupported 141 } 142 143 rpcSub := notifier.CreateSubscription() 144 145 go func() { 146 txHashes := make(chan common.Hash) 147 pendingTxSub := api.events.SubscribePendingTxEvents(txHashes) 148 149 for { 150 select { 151 case h := <-txHashes: 152 notifier.Notify(rpcSub.ID, h) 153 case <-rpcSub.Err(): 154 pendingTxSub.Unsubscribe() 155 return 156 case <-notifier.Closed(): 157 pendingTxSub.Unsubscribe() 158 return 159 } 160 } 161 }() 162 163 return rpcSub, nil 164 } 165 166 // NewBlockFilter creates a filter that fetches blocks that are imported into the chain. 167 // It is part of the filter package since polling goes with eth_getFilterChanges. 168 // 169 // https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_newblockfilter 170 func (api *PublicFilterAPI) NewBlockFilter() rpc.ID { 171 var ( 172 headers = make(chan *types.Header) 173 headerSub = api.events.SubscribeNewHeads(headers) 174 ) 175 176 api.filtersMu.Lock() 177 api.filters[headerSub.ID] = &filter{typ: BlocksSubscription, deadline: time.NewTimer(deadline), hashes: make([]common.Hash, 0), s: headerSub} 178 api.filtersMu.Unlock() 179 180 go func() { 181 for { 182 select { 183 case h := <-headers: 184 api.filtersMu.Lock() 185 if f, found := api.filters[headerSub.ID]; found { 186 f.hashes = append(f.hashes, h.Hash()) 187 } 188 api.filtersMu.Unlock() 189 case <-headerSub.Err(): 190 api.filtersMu.Lock() 191 delete(api.filters, headerSub.ID) 192 api.filtersMu.Unlock() 193 return 194 } 195 } 196 }() 197 198 return headerSub.ID 199 } 200 201 // NewHeads send a notification each time a new (header) block is appended to the chain. 202 func (api *PublicFilterAPI) NewHeads(ctx context.Context) (*rpc.Subscription, error) { 203 notifier, supported := rpc.NotifierFromContext(ctx) 204 if !supported { 205 return &rpc.Subscription{}, rpc.ErrNotificationsUnsupported 206 } 207 208 rpcSub := notifier.CreateSubscription() 209 210 go func() { 211 headers := make(chan *types.Header) 212 headersSub := api.events.SubscribeNewHeads(headers) 213 214 for { 215 select { 216 case h := <-headers: 217 notifier.Notify(rpcSub.ID, h) 218 case <-rpcSub.Err(): 219 headersSub.Unsubscribe() 220 return 221 case <-notifier.Closed(): 222 headersSub.Unsubscribe() 223 return 224 } 225 } 226 }() 227 228 return rpcSub, nil 229 } 230 231 // Logs creates a subscription that fires for all new log that match the given filter criteria. 232 func (api *PublicFilterAPI) Logs(ctx context.Context, crit FilterCriteria) (*rpc.Subscription, error) { 233 notifier, supported := rpc.NotifierFromContext(ctx) 234 if !supported { 235 return &rpc.Subscription{}, rpc.ErrNotificationsUnsupported 236 } 237 238 var ( 239 rpcSub = notifier.CreateSubscription() 240 matchedLogs = make(chan []*types.Log) 241 ) 242 243 logsSub, err := api.events.SubscribeLogs(crit, matchedLogs) 244 if err != nil { 245 return nil, err 246 } 247 248 go func() { 249 250 for { 251 select { 252 case logs := <-matchedLogs: 253 for _, log := range logs { 254 notifier.Notify(rpcSub.ID, &log) 255 } 256 case <-rpcSub.Err(): // client send an unsubscribe request 257 logsSub.Unsubscribe() 258 return 259 case <-notifier.Closed(): // connection dropped 260 logsSub.Unsubscribe() 261 return 262 } 263 } 264 }() 265 266 return rpcSub, nil 267 } 268 269 // FilterCriteria represents a request to create a new filter. 270 type FilterCriteria struct { 271 FromBlock *big.Int 272 ToBlock *big.Int 273 Addresses []common.Address 274 Topics [][]common.Hash 275 } 276 277 // NewFilter creates a new filter and returns the filter id. It can be 278 // used to retrieve logs when the state changes. This method cannot be 279 // used to fetch logs that are already stored in the state. 280 // 281 // Default criteria for the from and to block are "latest". 282 // Using "latest" as block number will return logs for mined blocks. 283 // Using "pending" as block number returns logs for not yet mined (pending) blocks. 284 // In case logs are removed (chain reorg) previously returned logs are returned 285 // again but with the removed property set to true. 286 // 287 // In case "fromBlock" > "toBlock" an error is returned. 288 // 289 // https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_newfilter 290 func (api *PublicFilterAPI) NewFilter(crit FilterCriteria) (rpc.ID, error) { 291 logs := make(chan []*types.Log) 292 logsSub, err := api.events.SubscribeLogs(crit, logs) 293 if err != nil { 294 return rpc.ID(""), err 295 } 296 297 api.filtersMu.Lock() 298 api.filters[logsSub.ID] = &filter{typ: LogsSubscription, crit: crit, deadline: time.NewTimer(deadline), logs: make([]*types.Log, 0), s: logsSub} 299 api.filtersMu.Unlock() 300 301 go func() { 302 for { 303 select { 304 case l := <-logs: 305 api.filtersMu.Lock() 306 if f, found := api.filters[logsSub.ID]; found { 307 f.logs = append(f.logs, l...) 308 } 309 api.filtersMu.Unlock() 310 case <-logsSub.Err(): 311 api.filtersMu.Lock() 312 delete(api.filters, logsSub.ID) 313 api.filtersMu.Unlock() 314 return 315 } 316 } 317 }() 318 319 return logsSub.ID, nil 320 } 321 322 // GetLogs returns logs matching the given argument that are stored within the state. 323 // 324 // https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_getlogs 325 func (api *PublicFilterAPI) GetLogs(ctx context.Context, crit FilterCriteria) ([]*types.Log, error) { 326 // Convert the RPC block numbers into internal representations 327 if crit.FromBlock == nil { 328 crit.FromBlock = big.NewInt(rpc.LatestBlockNumber.Int64()) 329 } 330 if crit.ToBlock == nil { 331 crit.ToBlock = big.NewInt(rpc.LatestBlockNumber.Int64()) 332 } 333 // Create and run the filter to get all the logs 334 filter := New(api.backend, crit.FromBlock.Int64(), crit.ToBlock.Int64(), crit.Addresses, crit.Topics) 335 336 logs, err := filter.Logs(ctx) 337 if err != nil { 338 return nil, err 339 } 340 return returnLogs(logs), err 341 } 342 343 // UninstallFilter removes the filter with the given filter id. 344 // 345 // https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_uninstallfilter 346 func (api *PublicFilterAPI) UninstallFilter(id rpc.ID) bool { 347 api.filtersMu.Lock() 348 f, found := api.filters[id] 349 if found { 350 delete(api.filters, id) 351 } 352 api.filtersMu.Unlock() 353 if found { 354 f.s.Unsubscribe() 355 } 356 357 return found 358 } 359 360 // GetFilterLogs returns the logs for the filter with the given id. 361 // If the filter could not be found an empty array of logs is returned. 362 // 363 // https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_getfilterlogs 364 func (api *PublicFilterAPI) GetFilterLogs(ctx context.Context, id rpc.ID) ([]*types.Log, error) { 365 api.filtersMu.Lock() 366 f, found := api.filters[id] 367 api.filtersMu.Unlock() 368 369 if !found || f.typ != LogsSubscription { 370 return nil, fmt.Errorf("filter not found") 371 } 372 373 begin := rpc.LatestBlockNumber.Int64() 374 if f.crit.FromBlock != nil { 375 begin = f.crit.FromBlock.Int64() 376 } 377 end := rpc.LatestBlockNumber.Int64() 378 if f.crit.ToBlock != nil { 379 end = f.crit.ToBlock.Int64() 380 } 381 // Create and run the filter to get all the logs 382 filter := New(api.backend, begin, end, f.crit.Addresses, f.crit.Topics) 383 384 logs, err := filter.Logs(ctx) 385 if err != nil { 386 return nil, err 387 } 388 return returnLogs(logs), nil 389 } 390 391 // GetFilterChanges returns the logs for the filter with the given id since 392 // last time it was called. This can be used for polling. 393 // 394 // For pending transaction and block filters the result is []common.Hash. 395 // (pending)Log filters return []Log. 396 // 397 // https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_getfilterchanges 398 func (api *PublicFilterAPI) GetFilterChanges(id rpc.ID) (interface{}, error) { 399 api.filtersMu.Lock() 400 defer api.filtersMu.Unlock() 401 402 if f, found := api.filters[id]; found { 403 if !f.deadline.Stop() { 404 // timer expired but filter is not yet removed in timeout loop 405 // receive timer value and reset timer 406 <-f.deadline.C 407 } 408 f.deadline.Reset(deadline) 409 410 switch f.typ { 411 case PendingTransactionsSubscription, BlocksSubscription: 412 hashes := f.hashes 413 f.hashes = nil 414 return returnHashes(hashes), nil 415 case LogsSubscription: 416 logs := f.logs 417 f.logs = nil 418 return returnLogs(logs), nil 419 } 420 } 421 422 return []interface{}{}, fmt.Errorf("filter not found") 423 } 424 425 // returnHashes is a helper that will return an empty hash array case the given hash array is nil, 426 // otherwise the given hashes array is returned. 427 func returnHashes(hashes []common.Hash) []common.Hash { 428 if hashes == nil { 429 return []common.Hash{} 430 } 431 return hashes 432 } 433 434 // returnLogs is a helper that will return an empty log array in case the given logs array is nil, 435 // otherwise the given logs array is returned. 436 func returnLogs(logs []*types.Log) []*types.Log { 437 if logs == nil { 438 return []*types.Log{} 439 } 440 return logs 441 } 442 443 // UnmarshalJSON sets *args fields with given data. 444 func (args *FilterCriteria) UnmarshalJSON(data []byte) error { 445 type input struct { 446 From *rpc.BlockNumber `json:"fromBlock"` 447 ToBlock *rpc.BlockNumber `json:"toBlock"` 448 Addresses interface{} `json:"address"` 449 Topics []interface{} `json:"topics"` 450 } 451 452 var raw input 453 if err := json.Unmarshal(data, &raw); err != nil { 454 return err 455 } 456 457 if raw.From != nil { 458 args.FromBlock = big.NewInt(raw.From.Int64()) 459 } 460 461 if raw.ToBlock != nil { 462 args.ToBlock = big.NewInt(raw.ToBlock.Int64()) 463 } 464 465 args.Addresses = []common.Address{} 466 467 if raw.Addresses != nil { 468 // raw.Address can contain a single address or an array of addresses 469 switch rawAddr := raw.Addresses.(type) { 470 case []interface{}: 471 for i, addr := range rawAddr { 472 if strAddr, ok := addr.(string); ok { 473 addr, err := decodeAddress(strAddr) 474 if err != nil { 475 return fmt.Errorf("invalid address at index %d: %v", i, err) 476 } 477 args.Addresses = append(args.Addresses, addr) 478 } else { 479 return fmt.Errorf("non-string address at index %d", i) 480 } 481 } 482 case string: 483 addr, err := decodeAddress(rawAddr) 484 if err != nil { 485 return fmt.Errorf("invalid address: %v", err) 486 } 487 args.Addresses = []common.Address{addr} 488 default: 489 return errors.New("invalid addresses in query") 490 } 491 } 492 493 // topics is an array consisting of strings and/or arrays of strings. 494 // JSON null values are converted to common.Hash{} and ignored by the filter manager. 495 if len(raw.Topics) > 0 { 496 args.Topics = make([][]common.Hash, len(raw.Topics)) 497 for i, t := range raw.Topics { 498 switch topic := t.(type) { 499 case nil: 500 // ignore topic when matching logs 501 502 case string: 503 // match specific topic 504 top, err := decodeTopic(topic) 505 if err != nil { 506 return err 507 } 508 args.Topics[i] = []common.Hash{top} 509 510 case []interface{}: 511 // or case e.g. [null, "topic0", "topic1"] 512 for _, rawTopic := range topic { 513 if rawTopic == nil { 514 // null component, match all 515 args.Topics[i] = nil 516 break 517 } 518 if topic, ok := rawTopic.(string); ok { 519 parsed, err := decodeTopic(topic) 520 if err != nil { 521 return err 522 } 523 args.Topics[i] = append(args.Topics[i], parsed) 524 } else { 525 return fmt.Errorf("invalid topic(s)") 526 } 527 } 528 default: 529 return fmt.Errorf("invalid topic(s)") 530 } 531 } 532 } 533 534 return nil 535 } 536 537 func decodeAddress(s string) (common.Address, error) { 538 b, err := hexutil.Decode(s) 539 if err == nil && len(b) != common.AddressLength { 540 err = fmt.Errorf("hex has invalid length %d after decoding", len(b)) 541 } 542 return common.BytesToAddress(b), err 543 } 544 545 func decodeTopic(s string) (common.Hash, error) { 546 b, err := hexutil.Decode(s) 547 if err == nil && len(b) != common.HashLength { 548 err = fmt.Errorf("hex has invalid length %d after decoding", len(b)) 549 } 550 return common.BytesToHash(b), err 551 }