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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
// 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/>.

//! Local Transactions List.

use std::{fmt, sync::Arc};

use ethereum_types::H256;
use linked_hash_map::LinkedHashMap;
use pool::{ScoredTransaction, VerifiedTransaction as Transaction};
use txpool::{self, VerifiedTransaction};

/// Status of local transaction.
/// Can indicate that the transaction is currently part of the queue (`Pending/Future`)
/// or gives a reason why the transaction was removed.
#[derive(Debug, PartialEq, Clone)]
pub enum Status {
    /// The transaction is currently in the transaction queue.
    Pending(Arc<Transaction>),
    /// Transaction is already mined.
    Mined(Arc<Transaction>),
    /// Transaction didn't get into any block, but some other tx with the same nonce got.
    Culled(Arc<Transaction>),
    /// Transaction is dropped because of limit
    Dropped(Arc<Transaction>),
    /// Replaced because of higher gas price of another transaction.
    Replaced {
        /// Replaced transaction
        old: Arc<Transaction>,
        /// Transaction that replaced this one.
        new: Arc<Transaction>,
    },
    /// Transaction was never accepted to the queue.
    /// It means that it was too cheap to replace any transaction already in the pool.
    Rejected(Arc<Transaction>, String),
    /// Transaction is invalid.
    Invalid(Arc<Transaction>),
    /// Transaction was canceled.
    Canceled(Arc<Transaction>),
}

impl Status {
    fn is_pending(&self) -> bool {
        match *self {
            Status::Pending(_) => true,
            _ => false,
        }
    }
}

/// Keeps track of local transactions that are in the queue or were mined/dropped recently.
pub struct LocalTransactionsList {
    max_old: usize,
    transactions: LinkedHashMap<H256, Status>,
    pending: usize,
    in_chain: Option<Box<dyn Fn(&H256) -> bool + Send + Sync>>,
}

impl fmt::Debug for LocalTransactionsList {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt.debug_struct("LocalTransactionsList")
            .field("max_old", &self.max_old)
            .field("transactions", &self.transactions)
            .field("pending", &self.pending)
            .field("in_chain", &self.in_chain.is_some())
            .finish()
    }
}

impl Default for LocalTransactionsList {
    fn default() -> Self {
        Self::new(10)
    }
}

impl LocalTransactionsList {
    /// Create a new list of local transactions.
    pub fn new(max_old: usize) -> Self {
        LocalTransactionsList {
            max_old,
            transactions: Default::default(),
            pending: 0,
            in_chain: None,
        }
    }

    /// Set blockchain checker.
    ///
    /// The function should return true if transaction is included in chain.
    pub fn set_in_chain_checker<F, T>(&mut self, checker: T)
    where
        T: Into<Option<F>>,
        F: Fn(&H256) -> bool + Send + Sync + 'static,
    {
        self.in_chain = checker.into().map(|f| Box::new(f) as _);
    }

    /// Returns true if the transaction is already in local transactions.
    pub fn contains(&self, hash: &H256) -> bool {
        self.transactions.contains_key(hash)
    }

    /// Return a map of all currently stored transactions.
    pub fn all_transactions(&self) -> &LinkedHashMap<H256, Status> {
        &self.transactions
    }

    /// Returns true if there are pending local transactions.
    pub fn has_pending(&self) -> bool {
        self.pending > 0
    }

    fn clear_old(&mut self) {
        let number_of_old = self.transactions.len() - self.pending;
        if self.max_old >= number_of_old {
            return;
        }

        let to_remove: Vec<_> = self
            .transactions
            .iter()
            .filter(|&(_, status)| !status.is_pending())
            .map(|(hash, _)| *hash)
            .take(number_of_old - self.max_old)
            .collect();

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

    fn insert(&mut self, hash: H256, status: Status) {
        let result = self.transactions.insert(hash, status);
        if let Some(old) = result {
            if old.is_pending() {
                self.pending -= 1;
            }
        }
    }
}

impl txpool::Listener<Transaction> for LocalTransactionsList {
    fn added(&mut self, tx: &Arc<Transaction>, old: Option<&Arc<Transaction>>) {
        if !tx.priority().is_local() {
            return;
        }

        debug!(target: "own_tx", "Imported to the pool (hash {:?})", tx.hash());
        self.clear_old();
        self.insert(*tx.hash(), Status::Pending(tx.clone()));
        self.pending += 1;

        if let Some(old) = old {
            if self.transactions.contains_key(old.hash()) {
                self.insert(
                    *old.hash(),
                    Status::Replaced {
                        old: old.clone(),
                        new: tx.clone(),
                    },
                );
            }
        }
    }

    fn rejected<H: fmt::Debug + fmt::LowerHex>(
        &mut self,
        tx: &Arc<Transaction>,
        reason: &txpool::Error<H>,
    ) {
        if !tx.priority().is_local() {
            return;
        }

        debug!(target: "own_tx", "Transaction rejected (hash {:?}). {}", tx.hash(), reason);
        self.insert(
            *tx.hash(),
            Status::Rejected(tx.clone(), format!("{}", reason)),
        );
        self.clear_old();
    }

    fn dropped(&mut self, tx: &Arc<Transaction>, new: Option<&Transaction>) {
        if !tx.priority().is_local() {
            return;
        }

        match new {
            Some(new) => {
                warn!(target: "own_tx", "Transaction pushed out because of limit (hash {:?}, replacement: {:?})", tx.hash(), new.hash())
            }
            None => {
                warn!(target: "own_tx", "Transaction dropped because of limit (hash: {:?})", tx.hash())
            }
        }
        self.insert(*tx.hash(), Status::Dropped(tx.clone()));
        self.clear_old();
    }

    fn invalid(&mut self, tx: &Arc<Transaction>) {
        if !tx.priority().is_local() {
            return;
        }

        warn!(target: "own_tx", "Transaction marked invalid (hash {:?})", tx.hash());
        self.insert(*tx.hash(), Status::Invalid(tx.clone()));
        self.clear_old();
    }

    fn canceled(&mut self, tx: &Arc<Transaction>) {
        if !tx.priority().is_local() {
            return;
        }

        warn!(target: "own_tx", "Transaction canceled (hash {:?})", tx.hash());
        self.insert(*tx.hash(), Status::Canceled(tx.clone()));
        self.clear_old();
    }

    fn culled(&mut self, tx: &Arc<Transaction>) {
        if !tx.priority().is_local() {
            return;
        }

        let is_in_chain = self
            .in_chain
            .as_ref()
            .map(|checker| checker(tx.hash()))
            .unwrap_or(false);
        if is_in_chain {
            info!(target: "own_tx", "Transaction mined (hash {:?})", tx.hash());
            self.insert(*tx.hash(), Status::Mined(tx.clone()));
            return;
        }

        info!(target: "own_tx", "Transaction culled (hash {:?})", tx.hash());
        self.insert(*tx.hash(), Status::Culled(tx.clone()));
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crypto::publickey::{Generator, Random};
    use ethereum_types::U256;
    use txpool::Listener;
    use types::transaction;

    use pool;

    #[test]
    fn should_add_transaction_as_pending() {
        // given
        let mut list = LocalTransactionsList::default();
        let tx1 = new_tx(10);
        let tx2 = new_tx(20);

        // when
        list.added(&tx1, None);
        list.added(&tx2, None);

        // then
        assert!(list.contains(tx1.hash()));
        assert!(list.contains(tx2.hash()));
        let statuses = list
            .all_transactions()
            .values()
            .cloned()
            .collect::<Vec<Status>>();
        assert_eq!(statuses, vec![Status::Pending(tx1), Status::Pending(tx2)]);
    }

    #[test]
    fn should_use_in_chain_checker_if_present() {
        // given
        let mut list = LocalTransactionsList::default();
        let tx1 = new_tx(10);
        let tx2 = new_tx(20);
        list.culled(&tx1);
        list.culled(&tx2);
        let statuses = list
            .all_transactions()
            .values()
            .cloned()
            .collect::<Vec<Status>>();
        assert_eq!(
            statuses,
            vec![Status::Culled(tx1.clone()), Status::Culled(tx2.clone())]
        );

        // when
        list.set_in_chain_checker(|_: &_| true);
        list.culled(&tx1);

        // then
        let statuses = list
            .all_transactions()
            .values()
            .cloned()
            .collect::<Vec<Status>>();
        assert_eq!(statuses, vec![Status::Culled(tx2), Status::Mined(tx1)]);
    }

    #[test]
    fn should_clear_old_transactions() {
        // given
        let mut list = LocalTransactionsList::new(1);
        let tx1 = new_tx(10);
        let tx2 = new_tx(50);
        let tx3 = new_tx(51);

        list.added(&tx1, None);
        list.invalid(&tx1);
        list.dropped(&tx2, None);
        assert!(!list.contains(tx1.hash()));
        assert!(list.contains(tx2.hash()));
        assert!(!list.contains(tx3.hash()));

        // when
        list.added(&tx3, Some(&tx1));

        // then
        assert!(!list.contains(tx1.hash()));
        assert!(list.contains(tx2.hash()));
        assert!(list.contains(tx3.hash()));
    }

    fn new_tx<T: Into<U256>>(nonce: T) -> Arc<Transaction> {
        let keypair = Random.generate();
        let signed = transaction::TypedTransaction::Legacy(transaction::Transaction {
            action: transaction::Action::Create,
            value: U256::from(100),
            data: Default::default(),
            gas: U256::from(10),
            gas_price: U256::from(1245),
            nonce: nonce.into(),
        })
        .sign(keypair.secret(), None);

        let mut tx = Transaction::from_pending_block_transaction(signed);
        tx.priority = pool::Priority::Local;

        Arc::new(tx)
    }
}