cfx_rpc/helpers/poll_filter.rs
1// Copyright 2015-2020 Parity Technologies (UK) Ltd.
2// This file is part of OpenEthereum.
3
4// OpenEthereum is free software: you can redistribute it and/or modify
5// it under the terms of the GNU 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// OpenEthereum 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 General Public License for more details.
13
14// You should have received a copy of the GNU General Public License
15// along with OpenEthereum. If not, see <http://www.gnu.org/licenses/>.
16
17//! Helper type with all filter state data.
18
19use cfx_types::H256;
20
21use parking_lot::Mutex;
22use primitives::filter::LogFilter;
23use std::{
24 collections::{BTreeSet, VecDeque},
25 sync::Arc,
26};
27
28pub type EpochNumber = u64;
29
30/// Thread-safe filter state.
31#[derive(Clone)]
32pub struct SyncPollFilter<T>(Arc<Mutex<PollFilter<T>>>);
33
34impl<T> SyncPollFilter<T> {
35 /// New `SyncPollFilter`
36 pub fn new(f: PollFilter<T>) -> Self {
37 SyncPollFilter(Arc::new(Mutex::new(f)))
38 }
39
40 /// Modify underlying filter
41 pub fn modify<F, R>(&self, f: F) -> R
42 where F: FnOnce(&mut PollFilter<T>) -> R {
43 f(&mut self.0.lock())
44 }
45}
46
47/// Filter state.
48#[derive(Clone)]
49pub enum PollFilter<T> {
50 /// Number of last block which client was notified about.
51 Block {
52 last_epoch_number: EpochNumber,
53 #[doc(hidden)]
54 recent_reported_epochs: VecDeque<(EpochNumber, Vec<H256>)>,
55 },
56 /// Hashes of all pending transactions the client knows about.
57 PendingTransaction(BTreeSet<H256>),
58 /// Number of From block number, last seen block hash, pending logs and log
59 /// filter itself.
60 Logs {
61 last_epoch_number: EpochNumber,
62 recent_reported_epochs: VecDeque<(EpochNumber, Vec<H256>)>,
63 previous_logs: VecDeque<Vec<T>>,
64 filter: LogFilter,
65 include_pending: bool,
66 },
67}
68
69pub const MAX_BLOCK_HISTORY_SIZE: usize = 200;
70
71/// Returns only last `n` logs
72pub fn limit_logs<T>(mut logs: Vec<T>, limit: Option<usize>) -> Vec<T> {
73 let len = logs.len();
74 match limit {
75 Some(limit) if len >= limit => logs.split_off(len - limit),
76 _ => logs,
77 }
78}