1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
// Copyright 2015-2020 Parity Technologies (UK) Ltd.
// This file is part of OpenEthereum.

// OpenEthereum is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// OpenEthereum is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with OpenEthereum.  If not, see <http://www.gnu.org/licenses/>.

use api::TransactionStats;
use ethereum_types::{H256, H512};
use fastmap::H256FastMap;
use std::{
    collections::{HashMap, HashSet},
    hash::BuildHasher,
};
use types::BlockNumber;

type NodeId = H512;

#[derive(Debug, PartialEq, Clone)]
pub struct Stats {
    first_seen: BlockNumber,
    propagated_to: HashMap<NodeId, usize>,
}

impl Stats {
    pub fn new(number: BlockNumber) -> Self {
        Stats {
            first_seen: number,
            propagated_to: Default::default(),
        }
    }
}

impl<'a> From<&'a Stats> for TransactionStats {
    fn from(other: &'a Stats) -> Self {
        TransactionStats {
            first_seen: other.first_seen,
            propagated_to: other
                .propagated_to
                .iter()
                .map(|(hash, size)| (*hash, *size))
                .collect(),
        }
    }
}

#[derive(Debug, Default)]
pub struct TransactionsStats {
    pending_transactions: H256FastMap<Stats>,
    new_transactions: H256FastMap<Stats>,
}

impl TransactionsStats {
    /// Increases number of propagations to given `enodeid`.
    pub fn propagated(
        &mut self,
        hash: &H256,
        is_new: bool,
        enode_id: Option<NodeId>,
        current_block_num: BlockNumber,
    ) {
        let enode_id = enode_id.unwrap_or_default();
        let stats = if is_new {
            self.new_transactions
                .entry(*hash)
                .or_insert_with(|| Stats::new(current_block_num))
        } else {
            self.pending_transactions
                .entry(*hash)
                .or_insert_with(|| Stats::new(current_block_num))
        };
        let count = stats.propagated_to.entry(enode_id).or_insert(0);
        *count = count.saturating_add(1);
    }

    /// Returns propagation stats for given hash or `None` if hash is not known or
    /// does not correspond to pending transaction.
    #[cfg(test)]
    pub fn get_pending(&self, hash: &H256) -> Option<&Stats> {
        self.pending_transactions.get(hash)
    }

    /// Returns propagation stats for given hash or `None` if hash is not known or
    /// does not correspond to new transaction.
    #[cfg(test)]
    pub fn get_new(&self, hash: &H256) -> Option<&Stats> {
        self.new_transactions.get(hash)
    }

    /// Stats for pending transactions.
    pub fn pending_transactions_stats(&self) -> &H256FastMap<Stats> {
        &self.pending_transactions
    }

    /// Stats for new transactions.
    pub fn new_transactions_stats(&self) -> &H256FastMap<Stats> {
        &self.new_transactions
    }

    /// Retains only pending transactions present in given `HashSet`.
    pub fn retain_pending<S: BuildHasher>(&mut self, hashes: &HashSet<H256, S>) {
        let to_remove = self
            .pending_transactions
            .keys()
            .filter(|hash| !hashes.contains(hash))
            .cloned()
            .collect::<Vec<_>>();

        for hash in to_remove {
            self.pending_transactions.remove(&hash);
        }
    }

    pub fn retain_new(
        &mut self,
        current_block_num: BlockNumber,
        new_transactions_stats_period: BlockNumber,
    ) {
        let to_remove = self
            .new_transactions
            .iter()
            .filter(|(_, stats)| {
                current_block_num.saturating_sub(stats.first_seen) > new_transactions_stats_period
            })
            .map(|(hash, _)| hash.clone())
            .collect::<Vec<_>>();

        for hash in to_remove {
            self.new_transactions.remove(&hash);
        }
    }
}

#[cfg(test)]
mod tests {

    use super::{Stats, TransactionsStats};
    use ethereum_types::{H256, H512};
    use std::collections::{HashMap, HashSet};

    #[test]
    fn should_keep_track_of_propagations() {
        // given
        let hash = H256::from_low_u64_be(5);
        let enodeid1 = H512::from_low_u64_be(2);
        let enodeid2 = H512::from_low_u64_be(5);

        {
            // given
            let mut stats = TransactionsStats::default();

            // when
            stats.propagated(&hash, false, Some(enodeid1), 5);
            stats.propagated(&hash, false, Some(enodeid1), 10);
            stats.propagated(&hash, false, Some(enodeid2), 15);

            // then
            let pending_stats = stats.get_pending(&hash);
            assert_eq!(
                pending_stats,
                Some(&Stats {
                    first_seen: 5,
                    propagated_to: hash_map![
                        enodeid1 => 2,
                        enodeid2 => 1
                    ],
                }),
                "Pending transactions propagation should update pending_transactions stats"
            );

            let new_stats = stats.get_new(&hash);
            assert_eq!(
                new_stats, None,
                "Pending transactions propagation should not update new_transactions stats"
            );
        }

        {
            // given
            let mut stats = TransactionsStats::default();

            // when
            stats.propagated(&hash, true, Some(enodeid1), 5);
            stats.propagated(&hash, true, Some(enodeid1), 10);
            stats.propagated(&hash, true, Some(enodeid2), 15);

            // then
            let pending_stats = stats.get_pending(&hash);
            assert_eq!(
                pending_stats, None,
                "New transactions propagation should not update pending_transactions stats"
            );

            let new_stats = stats.get_new(&hash);
            assert_eq!(
                new_stats,
                Some(&Stats {
                    first_seen: 5,
                    propagated_to: hash_map![
                        enodeid1 => 2,
                        enodeid2 => 1
                    ],
                }),
                "New transactions propagation should update new_transactions stats"
            );
        }
    }

    #[test]
    fn should_remove_pending_hash_from_tracking() {
        // given
        let mut stats = TransactionsStats::default();
        let hash = H256::from_low_u64_be(5);
        let enodeid1 = H512::from_low_u64_be(5);
        stats.propagated(&hash, false, Some(enodeid1), 10);

        // when
        stats.retain_pending(&HashSet::new());

        // then
        let stats = stats.get_pending(&hash);
        assert_eq!(stats, None);
    }

    #[test]
    fn should_remove_expired_new_hashes_from_tracking() {
        //given
        let mut stats = TransactionsStats::default();

        let hash1 = H256::from_low_u64_be(5);
        let hash2 = H256::from_low_u64_be(6);
        let hash3 = H256::from_low_u64_be(7);

        let enodeid1 = H512::from_low_u64_be(5);
        let enodeid2 = H512::from_low_u64_be(6);
        let enodeid3 = H512::from_low_u64_be(7);

        stats.propagated(&hash1, true, Some(enodeid1), 5);
        stats.propagated(&hash2, true, Some(enodeid2), 6);
        stats.propagated(&hash3, true, Some(enodeid3), 7);

        // when
        stats.retain_new(10, 3);

        // then
        assert_eq!(stats.get_new(&hash1), None);
        assert_eq!(stats.get_new(&hash2), None);
        assert_eq!(
            stats.get_new(&hash3),
            Some(&Stats {
                first_seen: 7,
                propagated_to: hash_map![
                    enodeid3 => 1
                ],
            }),
        )
    }
}