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
use std::{fmt, sync::Arc, time::Duration};
use ethcore_db::KeyValueDB;
use io::IoHandler;
use types::transaction::{
Condition as TransactionCondition, PendingTransaction, SignedTransaction, TypedTransaction,
UnverifiedTransaction,
};
extern crate common_types as types;
extern crate ethcore_db;
extern crate ethcore_io as io;
extern crate kvdb;
extern crate parity_crypto as crypto;
extern crate rlp;
extern crate serde;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate log;
#[cfg(test)]
extern crate ethkey;
#[cfg(test)]
extern crate kvdb_memorydb;
const LOCAL_TRANSACTIONS_KEY: &'static [u8] = &*b"LOCAL_TXS";
const UPDATE_TIMER: ::io::TimerToken = 0;
const UPDATE_TIMEOUT: Duration = Duration::from_secs(15 * 60);
#[derive(Debug)]
pub enum Error {
Io(::std::io::Error),
Json(::serde_json::Error),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::Io(ref val) => write!(f, "{}", val),
Error::Json(ref err) => write!(f, "{}", err),
}
}
}
#[derive(Serialize, Deserialize)]
enum Condition {
Number(types::BlockNumber),
Timestamp(u64),
}
impl From<TransactionCondition> for Condition {
fn from(cond: TransactionCondition) -> Self {
match cond {
TransactionCondition::Number(num) => Condition::Number(num),
TransactionCondition::Timestamp(tm) => Condition::Timestamp(tm),
}
}
}
impl Into<TransactionCondition> for Condition {
fn into(self) -> TransactionCondition {
match self {
Condition::Number(num) => TransactionCondition::Number(num),
Condition::Timestamp(tm) => TransactionCondition::Timestamp(tm),
}
}
}
#[derive(Serialize, Deserialize)]
struct TransactionEntry {
rlp_bytes: Vec<u8>,
condition: Option<Condition>,
}
impl TransactionEntry {
fn into_pending(self) -> Option<PendingTransaction> {
let tx: UnverifiedTransaction = match TypedTransaction::decode(&self.rlp_bytes) {
Err(e) => {
warn!(target: "local_store", "Invalid persistent transaction stored: {}", e);
return None;
}
Ok(tx) => tx,
};
let hash = tx.hash();
match SignedTransaction::new(tx) {
Ok(tx) => Some(PendingTransaction::new(tx, self.condition.map(Into::into))),
Err(_) => {
warn!(target: "local_store", "Bad signature on persistent transaction: {}", hash);
return None;
}
}
}
}
impl From<PendingTransaction> for TransactionEntry {
fn from(pending: PendingTransaction) -> Self {
TransactionEntry {
rlp_bytes: pending.transaction.encode(),
condition: pending.condition.map(Into::into),
}
}
}
pub trait NodeInfo: Send + Sync {
fn pending_transactions(&self) -> Vec<PendingTransaction>;
}
pub fn create<T: NodeInfo>(
db: Arc<dyn KeyValueDB>,
col: Option<u32>,
node: T,
) -> LocalDataStore<T> {
LocalDataStore {
db: db,
col: col,
node: node,
}
}
pub struct LocalDataStore<T: NodeInfo> {
db: Arc<dyn KeyValueDB>,
col: Option<u32>,
node: T,
}
impl<T: NodeInfo> LocalDataStore<T> {
pub fn pending_transactions(&self) -> Result<Vec<PendingTransaction>, Error> {
if let Some(val) = self
.db
.get(self.col, LOCAL_TRANSACTIONS_KEY)
.map_err(Error::Io)?
{
let local_txs: Vec<_> = ::serde_json::from_slice::<Vec<TransactionEntry>>(&val)
.map_err(Error::Json)?
.into_iter()
.filter_map(TransactionEntry::into_pending)
.collect();
Ok(local_txs)
} else {
Ok(Vec::new())
}
}
pub fn update(&self) -> Result<(), Error> {
trace!(target: "local_store", "Updating local store entries.");
let local_entries: Vec<TransactionEntry> = self
.node
.pending_transactions()
.into_iter()
.map(Into::into)
.collect();
self.write_txs(&local_entries)
}
pub fn clear(&self) -> Result<(), Error> {
trace!(target: "local_store", "Clearing local store entries.");
self.write_txs(&[])
}
fn write_txs(&self, txs: &[TransactionEntry]) -> Result<(), Error> {
let mut batch = self.db.transaction();
let local_json = ::serde_json::to_value(txs).map_err(Error::Json)?;
let json_str = format!("{}", local_json);
batch.put_vec(self.col, LOCAL_TRANSACTIONS_KEY, json_str.into_bytes());
self.db.write(batch).map_err(Error::Io)
}
}
impl<T: NodeInfo, M: Send + Sync + 'static> IoHandler<M> for LocalDataStore<T> {
fn initialize(&self, io: &::io::IoContext<M>) {
if let Err(e) = io.register_timer(UPDATE_TIMER, UPDATE_TIMEOUT) {
warn!(target: "local_store", "Error registering local store update timer: {}", e);
}
}
fn timeout(&self, _io: &::io::IoContext<M>, timer: ::io::TimerToken) {
if let UPDATE_TIMER = timer {
if let Err(e) = self.update() {
debug!(target: "local_store", "Error updating local store: {}", e);
}
}
}
}
impl<T: NodeInfo> Drop for LocalDataStore<T> {
fn drop(&mut self) {
debug!(target: "local_store", "Updating node data store on shutdown.");
let _ = self.update();
}
}
#[cfg(test)]
mod tests {
use super::NodeInfo;
use ethkey::Brain;
use std::sync::Arc;
use types::transaction::{Condition, PendingTransaction, Transaction, TypedTransaction};
struct Dummy(Vec<PendingTransaction>);
impl NodeInfo for Dummy {
fn pending_transactions(&self) -> Vec<PendingTransaction> {
self.0.clone()
}
}
#[test]
fn twice_empty() {
let db = Arc::new(ethcore_db::InMemoryWithMetrics::create(0));
{
let store = super::create(db.clone(), None, Dummy(vec![]));
assert_eq!(store.pending_transactions().unwrap(), vec![])
}
{
let store = super::create(db.clone(), None, Dummy(vec![]));
assert_eq!(store.pending_transactions().unwrap(), vec![])
}
}
#[test]
fn with_condition() {
let keypair = Brain::new("abcd".into()).generate();
let transactions: Vec<_> = (0..10u64)
.map(|nonce| {
let mut tx = TypedTransaction::Legacy(Transaction::default());
tx.tx_mut().nonce = nonce.into();
let signed = tx.sign(keypair.secret(), None);
let condition = match nonce {
5 => Some(Condition::Number(100_000)),
_ => None,
};
PendingTransaction::new(signed, condition)
})
.collect();
let db = Arc::new(ethcore_db::InMemoryWithMetrics::create(0));
{
let store = super::create(db.clone(), None, Dummy(transactions.clone()));
assert_eq!(store.pending_transactions().unwrap(), vec![])
}
{
let store = super::create(db.clone(), None, Dummy(vec![]));
assert_eq!(store.pending_transactions().unwrap(), transactions)
}
{
let store = super::create(db.clone(), None, Dummy(vec![]));
assert_eq!(store.pending_transactions().unwrap(), vec![])
}
}
#[test]
fn skips_bad_transactions() {
let keypair = Brain::new("abcd".into()).generate();
let mut transactions: Vec<_> = (0..10u64)
.map(|nonce| {
let mut tx = TypedTransaction::Legacy(Transaction::default());
tx.tx_mut().nonce = nonce.into();
let signed = tx.sign(keypair.secret(), None);
PendingTransaction::new(signed, None)
})
.collect();
transactions.push({
let mut tx = TypedTransaction::Legacy(Transaction::default());
tx.tx_mut().nonce = 10.into();
let signed = tx.fake_sign(Default::default());
PendingTransaction::new(signed, None)
});
let db = Arc::new(ethcore_db::InMemoryWithMetrics::create(0));
{
let store = super::create(db.clone(), None, Dummy(transactions.clone()));
assert_eq!(store.pending_transactions().unwrap(), vec![])
}
{
let store = super::create(db.clone(), None, Dummy(vec![]));
let loaded = store.pending_transactions().unwrap();
transactions.pop();
assert_eq!(loaded, transactions);
}
}
}