This repository has been archived by the owner on May 24, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 350
/
miner_service.rs
389 lines (338 loc) · 12 KB
/
miner_service.rs
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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
// 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/>.
//! Test implementation of miner service.
use std::{
collections::{BTreeMap, BTreeSet, HashMap},
sync::Arc,
};
use bytes::Bytes;
use ethcore::{
block::SealedBlock,
client::{
test_client::TestState, traits::ForceUpdateSealing, EngineInfo, Nonce, PrepareOpenBlock,
StateClient,
},
engines::{signer::EngineSigner, EthEngine},
error::Error,
miner::{self, AuthoringParams, MinerService, TransactionFilter},
};
use ethereum_types::{Address, H256, U256};
use miner::pool::{
local_transactions::Status as LocalTransactionStatus, verifier, QueueStatus,
VerifiedTransaction,
};
use parking_lot::{Mutex, RwLock};
use types::{
block::Block,
header::Header,
ids::BlockId,
receipt::RichReceipt,
transaction::{self, PendingTransaction, SignedTransaction, UnverifiedTransaction},
BlockNumber,
};
/// Test miner service.
pub struct TestMinerService {
/// Imported transactions.
pub imported_transactions: Mutex<Vec<SignedTransaction>>,
/// Pre-existed pending transactions
pub pending_transactions: Mutex<HashMap<H256, SignedTransaction>>,
/// Pre-existed local transactions
pub local_transactions: Mutex<BTreeMap<H256, LocalTransactionStatus>>,
/// Pre-existed pending receipts
pub pending_receipts: Mutex<Vec<RichReceipt>>,
/// Next nonces.
pub next_nonces: RwLock<HashMap<Address, U256>>,
/// Minimum gas price
pub min_gas_price: RwLock<Option<U256>>,
/// Signer (if any)
pub signer: RwLock<Option<Box<dyn EngineSigner>>>,
authoring_params: RwLock<AuthoringParams>,
}
impl Default for TestMinerService {
fn default() -> TestMinerService {
TestMinerService {
imported_transactions: Default::default(),
pending_transactions: Default::default(),
local_transactions: Default::default(),
pending_receipts: Default::default(),
next_nonces: Default::default(),
min_gas_price: RwLock::new(Some(0.into())),
authoring_params: RwLock::new(AuthoringParams {
author: Address::zero(),
gas_range_target: (12345.into(), 54321.into()),
extra_data: vec![1, 2, 3, 4],
}),
signer: RwLock::new(None),
}
}
}
impl TestMinerService {
/// Increments nonce for given address.
pub fn increment_nonce(&self, address: &Address) {
let mut next_nonces = self.next_nonces.write();
let nonce = next_nonces.entry(*address).or_insert_with(|| 0.into());
*nonce = *nonce + 1;
}
}
impl StateClient for TestMinerService {
// State will not be used by test client anyway, since all methods that accept state are mocked
type State = TestState;
fn latest_state_and_header(&self) -> (Self::State, Header) {
(TestState, Header::default())
}
fn state_at(&self, _id: BlockId) -> Option<Self::State> {
Some(TestState)
}
}
impl EngineInfo for TestMinerService {
fn engine(&self) -> &dyn EthEngine {
unimplemented!()
}
}
impl MinerService for TestMinerService {
type State = TestState;
fn pending_state(&self, _latest_block_number: BlockNumber) -> Option<Self::State> {
None
}
fn pending_block_header(&self, _latest_block_number: BlockNumber) -> Option<Header> {
None
}
fn pending_block(&self, _latest_block_number: BlockNumber) -> Option<Block> {
None
}
fn authoring_params(&self) -> AuthoringParams {
self.authoring_params.read().clone()
}
fn set_author<T: Into<Option<miner::Author>>>(&self, author: T) {
let author_opt = author.into();
self.authoring_params.write().author = author_opt
.as_ref()
.map(miner::Author::address)
.unwrap_or_default();
match author_opt {
Some(miner::Author::Sealer(signer)) => *self.signer.write() = Some(signer),
Some(miner::Author::External(_addr)) => (),
None => *self.signer.write() = None,
}
}
fn set_extra_data(&self, extra_data: Bytes) {
self.authoring_params.write().extra_data = extra_data;
}
fn set_gas_range_target(&self, target: (U256, U256)) {
self.authoring_params.write().gas_range_target = target;
}
/// Imports transactions to transaction queue.
fn import_external_transactions<C: Nonce + Sync>(
&self,
chain: &C,
transactions: Vec<UnverifiedTransaction>,
) -> Vec<Result<(), transaction::Error>> {
// lets assume that all txs are valid
let transactions: Vec<_> = transactions
.into_iter()
.map(|tx| SignedTransaction::new(tx).unwrap())
.collect();
self.imported_transactions
.lock()
.extend_from_slice(&transactions);
for sender in transactions.iter().map(|tx| tx.sender()) {
let nonce = self.next_nonce(chain, &sender);
self.next_nonces.write().insert(sender, nonce);
}
transactions.iter().map(|_| Ok(())).collect()
}
/// Imports transactions to transaction queue.
fn import_own_transaction<C: Nonce + Sync>(
&self,
_chain: &C,
_pending: PendingTransaction,
) -> Result<(), transaction::Error> {
// this function is no longer called directly from RPC
unimplemented!();
}
/// Imports transactions to queue - treats as local based on trusted flag, config, and tx source
fn import_claimed_local_transaction<C: Nonce + Sync>(
&self,
chain: &C,
pending: PendingTransaction,
_trusted: bool,
) -> Result<(), transaction::Error> {
// keep the pending nonces up to date
let sender = pending.transaction.sender();
let nonce = self.next_nonce(chain, &sender);
self.next_nonces.write().insert(sender, nonce);
// lets assume that all txs are valid
self.imported_transactions.lock().push(pending.transaction);
Ok(())
}
/// Called when blocks are imported to chain, updates transactions queue.
fn chain_new_blocks<C>(
&self,
_chain: &C,
_imported: &[H256],
_invalid: &[H256],
_enacted: &[H256],
_retracted: &[H256],
_is_internal: bool,
) {
unimplemented!();
}
/// New chain head event. Restart mining operation.
fn update_sealing<C>(&self, _chain: &C, _force: ForceUpdateSealing) {
unimplemented!();
}
fn work_package<C: PrepareOpenBlock>(
&self,
chain: &C,
) -> Option<(H256, BlockNumber, u64, U256)> {
let params = self.authoring_params();
let open_block = chain
.prepare_open_block(params.author, params.gas_range_target, params.extra_data)
.unwrap();
let closed = open_block.close().unwrap();
let header = &closed.header;
Some((
header.hash(),
header.number(),
header.timestamp(),
*header.difficulty(),
))
}
fn transaction(&self, hash: &H256) -> Option<Arc<VerifiedTransaction>> {
self.pending_transactions
.lock()
.get(hash)
.cloned()
.map(|tx| Arc::new(VerifiedTransaction::from_pending_block_transaction(tx)))
}
fn transactions(&self, hashes: Vec<H256>) -> Vec<Arc<VerifiedTransaction>> {
unimplemented!()
}
fn remove_transaction(&self, hash: &H256) -> Option<Arc<VerifiedTransaction>> {
self.pending_transactions
.lock()
.remove(hash)
.map(|tx| Arc::new(VerifiedTransaction::from_pending_block_transaction(tx)))
}
fn pending_transactions(&self, _best_block: BlockNumber) -> Option<Vec<SignedTransaction>> {
Some(self.pending_transactions.lock().values().cloned().collect())
}
fn local_transactions(&self) -> BTreeMap<H256, LocalTransactionStatus> {
self.local_transactions
.lock()
.iter()
.map(|(hash, stats)| (*hash, stats.clone()))
.collect()
}
fn ready_transactions_filtered<C>(
&self,
_chain: &C,
_max_len: usize,
filter: Option<TransactionFilter>,
_ordering: miner::PendingOrdering,
) -> Vec<Arc<VerifiedTransaction>> {
match filter {
Some(f) => self
.queued_transactions()
.into_iter()
.filter(|tx| f.matches(tx))
.collect(),
None => self.queued_transactions(),
}
}
fn pending_transaction_hashes<C>(&self, _chain: &C) -> BTreeSet<H256> {
self.queued_transactions()
.into_iter()
.map(|tx| tx.signed().hash())
.collect()
}
fn queued_transactions(&self) -> Vec<Arc<VerifiedTransaction>> {
self.pending_transactions
.lock()
.values()
.cloned()
.map(|tx| Arc::new(VerifiedTransaction::from_pending_block_transaction(tx)))
.collect()
}
fn queued_transaction_hashes(&self) -> Vec<H256> {
self.pending_transactions
.lock()
.keys()
.cloned()
.map(|hash| hash)
.collect()
}
fn pending_receipts(&self, _best_block: BlockNumber) -> Option<Vec<RichReceipt>> {
Some(self.pending_receipts.lock().clone())
}
fn next_nonce<C: Nonce + Sync>(&self, _chain: &C, address: &Address) -> U256 {
self.next_nonces
.read()
.get(address)
.cloned()
.unwrap_or_default()
}
fn is_currently_sealing(&self) -> bool {
false
}
fn queue_status(&self) -> QueueStatus {
QueueStatus {
options: verifier::Options {
minimal_gas_price: 0x1312d00.into(),
block_gas_limit: 5_000_000.into(),
tx_gas_limit: 5_000_000.into(),
no_early_reject: false,
block_base_fee: None,
allow_non_eoa_sender: false,
},
status: txpool::LightStatus {
mem_usage: 1_000,
transaction_count: 52,
senders: 1,
},
limits: txpool::Options {
max_count: 1_024,
max_per_sender: 16,
max_mem_usage: 5_000,
},
}
}
/// Submit `seal` as a valid solution for the header of `pow_hash`.
/// Will check the seal, but not actually insert the block into the chain.
fn submit_seal(&self, _pow_hash: H256, _seal: Vec<Bytes>) -> Result<SealedBlock, Error> {
unimplemented!();
}
fn sensible_gas_price(&self) -> U256 {
20_000_000_000u64.into()
}
fn sensible_max_priority_fee(&self) -> U256 {
2_000_000_000u64.into()
}
fn sensible_gas_limit(&self) -> U256 {
0x5208.into()
}
fn set_minimal_gas_price(&self, gas_price: U256) -> Result<bool, &str> {
let mut new_price = self.min_gas_price.write();
match *new_price {
Some(ref mut v) => {
*v = gas_price;
Ok(true)
}
None => {
let error_msg =
"Can't update fixed gas price while automatic gas calibration is enabled.";
Err(error_msg)
}
}
}
}