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