This repository was archived by the owner on Nov 6, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathminer.rs
1580 lines (1386 loc) · 53.6 KB
/
miner.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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2015-2018 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity 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.
// Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>.
use std::cmp;
use std::time::{Instant, Duration};
use std::collections::{BTreeMap, BTreeSet, HashSet};
use std::sync::Arc;
use ansi_term::Colour;
use bytes::Bytes;
use engines::{EthEngine, Seal};
use error::{Error, ErrorKind, ExecutionError};
use ethcore_miner::gas_pricer::GasPricer;
use ethcore_miner::pool::{self, TransactionQueue, VerifiedTransaction, QueueStatus, PrioritizationStrategy};
#[cfg(feature = "work-notify")]
use ethcore_miner::work_notify::NotifyWork;
use ethereum_types::{H256, U256, Address};
use io::IoChannel;
use parking_lot::{Mutex, RwLock};
use rayon::prelude::*;
use transaction::{
self,
Action,
UnverifiedTransaction,
SignedTransaction,
PendingTransaction,
};
use using_queue::{UsingQueue, GetAction};
use account_provider::{AccountProvider, SignError as AccountError};
use block::{ClosedBlock, IsBlock, Block, SealedBlock};
use client::{
BlockChain, ChainInfo, CallContract, BlockProducer, SealedBlockImporter, Nonce, TransactionInfo, TransactionId
};
use client::{BlockId, ClientIoMessage};
use executive::contract_address;
use header::{Header, BlockNumber};
use miner;
use miner::pool_client::{PoolClient, CachedNonceClient, NonceCache};
use receipt::RichReceipt;
use spec::Spec;
use state::State;
use ethkey::Password;
/// Different possible definitions for pending transaction set.
#[derive(Debug, PartialEq)]
pub enum PendingSet {
/// Always just the transactions in the queue. These have had only cheap checks.
AlwaysQueue,
/// Always just the transactions in the sealing block. These have had full checks but
/// may be empty if the node is not actively mining or has no force_sealing enabled.
AlwaysSealing,
/// Takes from sealing if mining, from queue otherwise.
SealingOrElseQueue,
}
/// Transaction queue penalization settings.
///
/// Senders of long-running transactions (above defined threshold)
/// will get lower priority.
#[derive(Debug, PartialEq, Clone)]
pub enum Penalization {
/// Penalization in transaction queue is disabled
Disabled,
/// Penalization in transaction queue is enabled
Enabled {
/// Upper limit of transaction processing time before penalizing.
offend_threshold: Duration,
},
}
/// Pending block preparation status.
#[derive(Debug, PartialEq)]
pub enum BlockPreparationStatus {
/// We had to prepare new pending block and the preparation succeeded.
Succeeded,
/// We had to prepare new pending block but the preparation failed.
Failed,
/// We didn't have to prepare a new block.
NotPrepared,
}
/// Initial minimal gas price.
///
/// Gas price should be later overwritten externally
/// for instance by a dynamic gas price mechanism or CLI parameter.
/// This constant controls the initial value.
const DEFAULT_MINIMAL_GAS_PRICE: u64 = 20_000_000_000;
/// Allowed number of skipped transactions when constructing pending block.
///
/// When we push transactions to pending block, some of the transactions might
/// get skipped because of block gas limit being reached.
/// This constant controls how many transactions we can skip because of that
/// before stopping attempts to push more transactions to the block.
/// This is an optimization that prevents traversing the entire pool
/// in case we have only a fraction of available block gas limit left.
const MAX_SKIPPED_TRANSACTIONS: usize = 128;
/// Configures the behaviour of the miner.
#[derive(Debug, PartialEq)]
pub struct MinerOptions {
/// Force the miner to reseal, even when nobody has asked for work.
pub force_sealing: bool,
/// Reseal on receipt of new external transactions.
pub reseal_on_external_tx: bool,
/// Reseal on receipt of new local transactions.
pub reseal_on_own_tx: bool,
/// Reseal when new uncle block has been imported.
pub reseal_on_uncle: bool,
/// Minimum period between transaction-inspired reseals.
pub reseal_min_period: Duration,
/// Maximum period between blocks (enables force sealing after that).
pub reseal_max_period: Duration,
/// Whether we should fallback to providing all the queue's transactions or just pending.
pub pending_set: PendingSet,
/// How many historical work packages can we store before running out?
pub work_queue_size: usize,
/// Can we submit two different solutions for the same block and expect both to result in an import?
pub enable_resubmission: bool,
/// Create a pending block with maximal possible gas limit.
/// NOTE: Such block will contain all pending transactions but
/// will be invalid if mined.
pub infinite_pending_block: bool,
/// Strategy to use for prioritizing transactions in the queue.
pub tx_queue_strategy: PrioritizationStrategy,
/// Simple senders penalization.
pub tx_queue_penalization: Penalization,
/// Do we want to mark transactions recieved locally (e.g. RPC) as local if we don't have the sending account?
pub tx_queue_no_unfamiliar_locals: bool,
/// Do we refuse to accept service transactions even if sender is certified.
pub refuse_service_transactions: bool,
/// Transaction pool limits.
pub pool_limits: pool::Options,
/// Initial transaction verification options.
pub pool_verification_options: pool::verifier::Options,
}
impl Default for MinerOptions {
fn default() -> Self {
MinerOptions {
force_sealing: false,
reseal_on_external_tx: false,
reseal_on_own_tx: true,
reseal_on_uncle: false,
reseal_min_period: Duration::from_secs(2),
reseal_max_period: Duration::from_secs(120),
pending_set: PendingSet::AlwaysQueue,
work_queue_size: 20,
enable_resubmission: true,
infinite_pending_block: false,
tx_queue_strategy: PrioritizationStrategy::GasPriceOnly,
tx_queue_penalization: Penalization::Disabled,
tx_queue_no_unfamiliar_locals: false,
refuse_service_transactions: false,
pool_limits: pool::Options {
max_count: 8_192,
max_per_sender: 81,
max_mem_usage: 4 * 1024 * 1024,
},
pool_verification_options: pool::verifier::Options {
minimal_gas_price: DEFAULT_MINIMAL_GAS_PRICE.into(),
block_gas_limit: U256::max_value(),
tx_gas_limit: U256::max_value(),
no_early_reject: false,
},
}
}
}
/// Configurable parameters of block authoring.
#[derive(Debug, Default, Clone)]
pub struct AuthoringParams {
/// Lower and upper bound of block gas limit that we are targeting
pub gas_range_target: (U256, U256),
/// Block author
pub author: Address,
/// Block extra data
pub extra_data: Bytes,
}
struct SealingWork {
queue: UsingQueue<ClosedBlock>,
enabled: bool,
next_allowed_reseal: Instant,
next_mandatory_reseal: Instant,
// block number when sealing work was last requested
last_request: Option<u64>,
}
impl SealingWork {
/// Are we allowed to do a non-mandatory reseal?
fn reseal_allowed(&self) -> bool {
Instant::now() > self.next_allowed_reseal
}
}
/// Keeps track of transactions using priority queue and holds currently mined block.
/// Handles preparing work for "work sealing" or seals "internally" if Engine does not require work.
pub struct Miner {
// NOTE [ToDr] When locking always lock in this order!
sealing: Mutex<SealingWork>,
params: RwLock<AuthoringParams>,
#[cfg(feature = "work-notify")]
listeners: RwLock<Vec<Box<NotifyWork>>>,
nonce_cache: NonceCache,
gas_pricer: Mutex<GasPricer>,
options: MinerOptions,
// TODO [ToDr] Arc is only required because of price updater
transaction_queue: Arc<TransactionQueue>,
engine: Arc<EthEngine>,
accounts: Option<Arc<AccountProvider>>,
io_channel: RwLock<Option<IoChannel<ClientIoMessage>>>,
}
impl Miner {
/// Push listener that will handle new jobs
#[cfg(feature = "work-notify")]
pub fn add_work_listener(&self, notifier: Box<NotifyWork>) {
self.listeners.write().push(notifier);
self.sealing.lock().enabled = true;
}
/// Set a callback to be notified about imported transactions' hashes.
pub fn add_transactions_listener(&self, f: Box<Fn(&[H256]) + Send + Sync>) {
self.transaction_queue.add_listener(f);
}
/// Creates new instance of miner Arc.
pub fn new(
options: MinerOptions,
gas_pricer: GasPricer,
spec: &Spec,
accounts: Option<Arc<AccountProvider>>,
) -> Self {
let limits = options.pool_limits.clone();
let verifier_options = options.pool_verification_options.clone();
let tx_queue_strategy = options.tx_queue_strategy;
let nonce_cache_size = cmp::max(4096, limits.max_count / 4);
Miner {
sealing: Mutex::new(SealingWork {
queue: UsingQueue::new(options.work_queue_size),
enabled: options.force_sealing
|| spec.engine.seals_internally().is_some(),
next_allowed_reseal: Instant::now(),
next_mandatory_reseal: Instant::now() + options.reseal_max_period,
last_request: None,
}),
params: RwLock::new(AuthoringParams::default()),
#[cfg(feature = "work-notify")]
listeners: RwLock::new(vec![]),
gas_pricer: Mutex::new(gas_pricer),
nonce_cache: NonceCache::new(nonce_cache_size),
options,
transaction_queue: Arc::new(TransactionQueue::new(limits, verifier_options, tx_queue_strategy)),
accounts,
engine: spec.engine.clone(),
io_channel: RwLock::new(None),
}
}
/// Creates new instance of miner with given spec and accounts.
///
/// NOTE This should be only used for tests.
pub fn new_for_tests(spec: &Spec, accounts: Option<Arc<AccountProvider>>) -> Miner {
let minimal_gas_price = 0.into();
Miner::new(MinerOptions {
pool_verification_options: pool::verifier::Options {
minimal_gas_price,
block_gas_limit: U256::max_value(),
tx_gas_limit: U256::max_value(),
no_early_reject: false,
},
reseal_min_period: Duration::from_secs(0),
..Default::default()
}, GasPricer::new_fixed(minimal_gas_price), spec, accounts)
}
/// Sets `IoChannel`
pub fn set_io_channel(&self, io_channel: IoChannel<ClientIoMessage>) {
*self.io_channel.write() = Some(io_channel);
}
/// Sets in-blockchain checker for transactions.
pub fn set_in_chain_checker<C>(&self, chain: &Arc<C>) where
C: TransactionInfo + Send + Sync + 'static,
{
let client = Arc::downgrade(chain);
self.transaction_queue.set_in_chain_checker(move |hash| {
match client.upgrade() {
Some(info) => info.transaction_block(TransactionId::Hash(*hash)).is_some(),
None => false,
}
});
}
/// Clear all pending block states
pub fn clear(&self) {
self.sealing.lock().queue.reset();
}
/// Updates transaction queue verification limits.
///
/// Limits consist of current block gas limit and minimal gas price.
pub fn update_transaction_queue_limits(&self, block_gas_limit: U256) {
trace!(target: "miner", "minimal_gas_price: recalibrating...");
let txq = self.transaction_queue.clone();
let mut options = self.options.pool_verification_options.clone();
self.gas_pricer.lock().recalibrate(move |gas_price| {
debug!(target: "miner", "minimal_gas_price: Got gas price! {}", gas_price);
options.minimal_gas_price = gas_price;
options.block_gas_limit = block_gas_limit;
txq.set_verifier_options(options);
});
}
/// Retrieves an existing pending block iff it's not older than given block number.
///
/// NOTE: This will not prepare a new pending block if it's not existing.
fn map_existing_pending_block<F, T>(&self, f: F, latest_block_number: BlockNumber) -> Option<T> where
F: FnOnce(&ClosedBlock) -> T,
{
self.sealing.lock().queue
.peek_last_ref()
.and_then(|b| {
// to prevent a data race between block import and updating pending block
// we allow the number to be equal.
if b.block().header().number() >= latest_block_number {
Some(f(b))
} else {
None
}
})
}
fn pool_client<'a, C: 'a>(&'a self, chain: &'a C) -> PoolClient<'a, C> where
C: BlockChain + CallContract,
{
PoolClient::new(
chain,
&self.nonce_cache,
&*self.engine,
self.accounts.as_ref().map(|x| &**x),
self.options.refuse_service_transactions,
)
}
/// Prepares new block for sealing including top transactions from queue.
fn prepare_block<C>(&self, chain: &C) -> Option<(ClosedBlock, Option<H256>)> where
C: BlockChain + CallContract + BlockProducer + Nonce + Sync,
{
trace_time!("prepare_block");
let chain_info = chain.chain_info();
// Open block
let (mut open_block, original_work_hash) = {
let mut sealing = self.sealing.lock();
let last_work_hash = sealing.queue.peek_last_ref().map(|pb| pb.block().header().hash());
let best_hash = chain_info.best_block_hash;
// check to see if last ClosedBlock in would_seals is actually same parent block.
// if so
// duplicate, re-open and push any new transactions.
// if at least one was pushed successfully, close and enqueue new ClosedBlock;
// otherwise, leave everything alone.
// otherwise, author a fresh block.
let mut open_block = match sealing.queue.get_pending_if(|b| b.block().header().parent_hash() == &best_hash) {
Some(old_block) => {
trace!(target: "miner", "prepare_block: Already have previous work; updating and returning");
// add transactions to old_block
chain.reopen_block(old_block)
}
None => {
// block not found - create it.
trace!(target: "miner", "prepare_block: No existing work - making new block");
let params = self.params.read().clone();
match chain.prepare_open_block(
params.author,
params.gas_range_target,
params.extra_data,
) {
Ok(block) => block,
Err(err) => {
warn!(target: "miner", "Open new block failed with error {:?}. This is likely an error in chain specificiations or on-chain consensus smart contracts.", err);
return None;
}
}
}
};
if self.options.infinite_pending_block {
open_block.remove_gas_limit();
}
(open_block, last_work_hash)
};
let mut invalid_transactions = HashSet::new();
let mut not_allowed_transactions = HashSet::new();
let mut senders_to_penalize = HashSet::new();
let block_number = open_block.block().header().number();
let mut tx_count = 0usize;
let mut skipped_transactions = 0usize;
let client = self.pool_client(chain);
let engine_params = self.engine.params();
let min_tx_gas: U256 = self.engine.schedule(chain_info.best_block_number).tx_gas.into();
let nonce_cap: Option<U256> = if chain_info.best_block_number + 1 >= engine_params.dust_protection_transition {
Some((engine_params.nonce_cap_increment * (chain_info.best_block_number + 1)).into())
} else {
None
};
// we will never need more transactions than limit divided by min gas
let max_transactions = if min_tx_gas.is_zero() {
usize::max_value()
} else {
MAX_SKIPPED_TRANSACTIONS.saturating_add(cmp::min(*open_block.block().header().gas_limit() / min_tx_gas, u64::max_value().into()).as_u64() as usize)
};
let pending: Vec<Arc<_>> = self.transaction_queue.pending(
client.clone(),
pool::PendingSettings {
block_number: chain_info.best_block_number,
current_timestamp: chain_info.best_block_timestamp,
nonce_cap,
max_len: max_transactions,
ordering: miner::PendingOrdering::Priority,
}
);
let took_ms = |elapsed: &Duration| {
elapsed.as_secs() * 1000 + elapsed.subsec_nanos() as u64 / 1_000_000
};
let block_start = Instant::now();
debug!(target: "miner", "Attempting to push {} transactions.", pending.len());
for tx in pending {
let start = Instant::now();
let transaction = tx.signed().clone();
let hash = transaction.hash();
let sender = transaction.sender();
// Re-verify transaction again vs current state.
let result = client.verify_signed(&transaction)
.map_err(|e| e.into())
.and_then(|_| {
open_block.push_transaction(transaction, None)
});
let took = start.elapsed();
// Check for heavy transactions
match self.options.tx_queue_penalization {
Penalization::Enabled { ref offend_threshold } if &took > offend_threshold => {
senders_to_penalize.insert(sender);
debug!(target: "miner", "Detected heavy transaction ({} ms). Penalizing sender.", took_ms(&took));
},
_ => {},
}
debug!(target: "miner", "Adding tx {:?} took {} ms", hash, took_ms(&took));
match result {
Err(Error(ErrorKind::Execution(ExecutionError::BlockGasLimitReached { gas_limit, gas_used, gas }), _)) => {
debug!(target: "miner", "Skipping adding transaction to block because of gas limit: {:?} (limit: {:?}, used: {:?}, gas: {:?})", hash, gas_limit, gas_used, gas);
// Penalize transaction if it's above current gas limit
if gas > gas_limit {
debug!(target: "txqueue", "[{:?}] Transaction above block gas limit.", hash);
invalid_transactions.insert(hash);
}
// Exit early if gas left is smaller then min_tx_gas
let gas_left = gas_limit - gas_used;
if gas_left < min_tx_gas {
debug!(target: "miner", "Remaining gas is lower than minimal gas for a transaction. Block is full.");
break;
}
// Avoid iterating over the entire queue in case block is almost full.
skipped_transactions += 1;
if skipped_transactions > MAX_SKIPPED_TRANSACTIONS {
debug!(target: "miner", "Reached skipped transactions threshold. Assuming block is full.");
break;
}
},
// Invalid nonce error can happen only if previous transaction is skipped because of gas limit.
// If there is errornous state of transaction queue it will be fixed when next block is imported.
Err(Error(ErrorKind::Execution(ExecutionError::InvalidNonce { expected, got }), _)) => {
debug!(target: "miner", "Skipping adding transaction to block because of invalid nonce: {:?} (expected: {:?}, got: {:?})", hash, expected, got);
},
// already have transaction - ignore
Err(Error(ErrorKind::Transaction(transaction::Error::AlreadyImported), _)) => {},
Err(Error(ErrorKind::Transaction(transaction::Error::NotAllowed), _)) => {
not_allowed_transactions.insert(hash);
debug!(target: "miner", "Skipping non-allowed transaction for sender {:?}", hash);
},
Err(e) => {
debug!(target: "txqueue", "[{:?}] Marking as invalid: {:?}.", hash, e);
debug!(
target: "miner", "Error adding transaction to block: number={}. transaction_hash={:?}, Error: {:?}", block_number, hash, e
);
invalid_transactions.insert(hash);
},
// imported ok
_ => tx_count += 1,
}
}
let elapsed = block_start.elapsed();
debug!(target: "miner", "Pushed {} transactions in {} ms", tx_count, took_ms(&elapsed));
let block = match open_block.close() {
Ok(block) => block,
Err(err) => {
warn!(target: "miner", "Closing the block failed with error {:?}. This is likely an error in chain specificiations or on-chain consensus smart contracts.", err);
return None;
}
};
{
self.transaction_queue.remove(invalid_transactions.iter(), true);
self.transaction_queue.remove(not_allowed_transactions.iter(), false);
self.transaction_queue.penalize(senders_to_penalize.iter());
}
Some((block, original_work_hash))
}
/// Returns `true` if we should create pending block even if some other conditions are not met.
///
/// In general we always seal iff:
/// 1. --force-sealing CLI parameter is provided
/// 2. There are listeners awaiting new work packages (e.g. remote work notifications or stratum).
fn forced_sealing(&self) -> bool {
let listeners_empty = {
#[cfg(feature = "work-notify")]
{ self.listeners.read().is_empty() }
#[cfg(not(feature = "work-notify"))]
{ true }
};
self.options.force_sealing || !listeners_empty
}
/// Check is reseal is allowed and necessary.
fn requires_reseal(&self, best_block: BlockNumber) -> bool {
let mut sealing = self.sealing.lock();
if !sealing.enabled {
trace!(target: "miner", "requires_reseal: sealing is disabled");
return false
}
if !sealing.reseal_allowed() {
trace!(target: "miner", "requires_reseal: reseal too early");
return false
}
trace!(target: "miner", "requires_reseal: sealing enabled");
// Disable sealing if there were no requests for SEALING_TIMEOUT_IN_BLOCKS
let had_requests = sealing.last_request.map(|last_request| {
best_block > last_request
&& best_block - last_request <= SEALING_TIMEOUT_IN_BLOCKS
}).unwrap_or(false);
// keep sealing enabled if any of the conditions is met
let sealing_enabled = self.forced_sealing()
|| self.transaction_queue.has_local_pending_transactions()
|| self.engine.seals_internally() == Some(true)
|| had_requests;
let should_disable_sealing = !sealing_enabled;
trace!(target: "miner", "requires_reseal: should_disable_sealing={}; forced={:?}, has_local={:?}, internal={:?}, had_requests={:?}",
should_disable_sealing,
self.forced_sealing(),
self.transaction_queue.has_local_pending_transactions(),
self.engine.seals_internally(),
had_requests,
);
if should_disable_sealing {
trace!(target: "miner", "Miner sleeping (current {}, last {})", best_block, sealing.last_request.unwrap_or(0));
sealing.enabled = false;
sealing.queue.reset();
false
} else {
// sealing enabled and we don't want to sleep.
sealing.next_allowed_reseal = Instant::now() + self.options.reseal_min_period;
true
}
}
/// Attempts to perform internal sealing (one that does not require work) and handles the result depending on the type of Seal.
fn seal_and_import_block_internally<C>(&self, chain: &C, block: ClosedBlock) -> bool
where C: BlockChain + SealedBlockImporter,
{
{
let sealing = self.sealing.lock();
if block.transactions().is_empty()
&& !self.forced_sealing()
&& Instant::now() <= sealing.next_mandatory_reseal
{
return false
}
}
trace!(target: "miner", "seal_block_internally: attempting internal seal.");
let parent_header = match chain.block_header(BlockId::Hash(*block.header().parent_hash())) {
Some(h) => {
match h.decode() {
Ok(decoded_hdr) => decoded_hdr,
Err(_) => return false
}
}
None => return false,
};
match self.engine.generate_seal(block.block(), &parent_header) {
// Save proposal for later seal submission and broadcast it.
Seal::Proposal(seal) => {
trace!(target: "miner", "Received a Proposal seal.");
{
let mut sealing = self.sealing.lock();
sealing.next_mandatory_reseal = Instant::now() + self.options.reseal_max_period;
sealing.queue.set_pending(block.clone());
sealing.queue.use_last_ref();
}
block
.lock()
.seal(&*self.engine, seal)
.map(|sealed| {
chain.broadcast_proposal_block(sealed);
true
})
.unwrap_or_else(|e| {
warn!("ERROR: seal failed when given internally generated seal: {}", e);
false
})
},
// Directly import a regular sealed block.
Seal::Regular(seal) => {
trace!(target: "miner", "Received a Regular seal.");
{
let mut sealing = self.sealing.lock();
sealing.next_mandatory_reseal = Instant::now() + self.options.reseal_max_period;
}
block
.lock()
.seal(&*self.engine, seal)
.map(|sealed| {
chain.import_sealed_block(sealed).is_ok()
})
.unwrap_or_else(|e| {
warn!("ERROR: seal failed when given internally generated seal: {}", e);
false
})
},
Seal::None => false,
}
}
/// Prepares work which has to be done to seal.
fn prepare_work(&self, block: ClosedBlock, original_work_hash: Option<H256>) {
let (work, is_new) = {
let block_header = block.block().header().clone();
let block_hash = block_header.hash();
let mut sealing = self.sealing.lock();
let last_work_hash = sealing.queue.peek_last_ref().map(|pb| pb.block().header().hash());
trace!(
target: "miner",
"prepare_work: Checking whether we need to reseal: orig={:?} last={:?}, this={:?}",
original_work_hash, last_work_hash, block_hash
);
let (work, is_new) = if last_work_hash.map_or(true, |h| h != block_hash) {
trace!(
target: "miner",
"prepare_work: Pushing a new, refreshed or borrowed pending {}...",
block_hash
);
let is_new = original_work_hash.map_or(true, |h| h != block_hash);
sealing.queue.set_pending(block);
#[cfg(feature = "work-notify")]
{
// If push notifications are enabled we assume all work items are used.
if is_new && !self.listeners.read().is_empty() {
sealing.queue.use_last_ref();
}
}
(Some((block_hash, *block_header.difficulty(), block_header.number())), is_new)
} else {
(None, false)
};
trace!(
target: "miner",
"prepare_work: leaving (last={:?})",
sealing.queue.peek_last_ref().map(|b| b.block().header().hash())
);
(work, is_new)
};
#[cfg(feature = "work-notify")]
{
if is_new {
work.map(|(pow_hash, difficulty, number)| {
for notifier in self.listeners.read().iter() {
notifier.notify(pow_hash, difficulty, number)
}
});
}
}
// NB: hack to use variables to avoid warning.
#[cfg(not(feature = "work-notify"))]
{
let _work = work;
let _is_new = is_new;
}
}
/// Prepare a pending block. Returns the preparation status.
fn prepare_pending_block<C>(&self, client: &C) -> BlockPreparationStatus where
C: BlockChain + CallContract + BlockProducer + SealedBlockImporter + Nonce + Sync,
{
trace!(target: "miner", "prepare_pending_block: entering");
let prepare_new = {
let mut sealing = self.sealing.lock();
let have_work = sealing.queue.peek_last_ref().is_some();
trace!(target: "miner", "prepare_pending_block: have_work={}", have_work);
if !have_work {
sealing.enabled = true;
true
} else {
false
}
};
let preparation_status = if prepare_new {
// --------------------------------------------------------------------------
// | NOTE Code below requires sealing locks. |
// | Make sure to release the locks before calling that method. |
// --------------------------------------------------------------------------
match self.prepare_block(client) {
Some((block, original_work_hash)) => {
self.prepare_work(block, original_work_hash);
BlockPreparationStatus::Succeeded
},
None => BlockPreparationStatus::Failed,
}
} else {
BlockPreparationStatus::NotPrepared
};
let best_number = client.chain_info().best_block_number;
let mut sealing = self.sealing.lock();
if sealing.last_request != Some(best_number) {
trace!(
target: "miner",
"prepare_pending_block: Miner received request (was {}, now {}) - waking up.",
sealing.last_request.unwrap_or(0), best_number
);
sealing.last_request = Some(best_number);
}
preparation_status
}
/// Prepare pending block, check whether sealing is needed, and then update sealing.
fn prepare_and_update_sealing<C: miner::BlockChainClient>(&self, chain: &C) {
use miner::MinerService;
// Make sure to do it after transaction is imported and lock is dropped.
// We need to create pending block and enable sealing.
if self.engine.seals_internally().unwrap_or(false) || self.prepare_pending_block(chain) == BlockPreparationStatus::NotPrepared {
// If new block has not been prepared (means we already had one)
// or Engine might be able to seal internally,
// we need to update sealing.
self.update_sealing(chain);
}
}
}
const SEALING_TIMEOUT_IN_BLOCKS : u64 = 5;
impl miner::MinerService for Miner {
type State = State<::state_db::StateDB>;
fn authoring_params(&self) -> AuthoringParams {
self.params.read().clone()
}
fn set_gas_range_target(&self, gas_range_target: (U256, U256)) {
self.params.write().gas_range_target = gas_range_target;
}
fn set_extra_data(&self, extra_data: Bytes) {
self.params.write().extra_data = extra_data;
}
fn set_author(&self, address: Address, password: Option<Password>) -> Result<(), AccountError> {
self.params.write().author = address;
if self.engine.seals_internally().is_some() && password.is_some() {
if let Some(ref ap) = self.accounts {
let password = password.unwrap_or_else(|| Password::from(String::new()));
// Sign test message
ap.sign(address.clone(), Some(password.clone()), Default::default())?;
// Enable sealing
self.sealing.lock().enabled = true;
// --------------------------------------------------------------------------
// | NOTE Code below may require author and sealing locks |
// | (some `Engine`s call `EngineClient.update_sealing()`) |
// | Make sure to release the locks before calling that method. |
// --------------------------------------------------------------------------
self.engine.set_signer(ap.clone(), address, password);
Ok(())
} else {
warn!(target: "miner", "No account provider");
Err(AccountError::NotFound)
}
} else {
Ok(())
}
}
fn sensible_gas_price(&self) -> U256 {
// 10% above our minimum.
self.transaction_queue.current_worst_gas_price() * 110u32 / 100
}
fn sensible_gas_limit(&self) -> U256 {
self.params.read().gas_range_target.0 / 5
}
fn import_external_transactions<C: miner::BlockChainClient>(
&self,
chain: &C,
transactions: Vec<UnverifiedTransaction>
) -> Vec<Result<(), transaction::Error>> {
trace!(target: "external_tx", "Importing external transactions");
let client = self.pool_client(chain);
let results = self.transaction_queue.import(
client,
transactions.into_iter().map(pool::verifier::Transaction::Unverified).collect(),
);
// --------------------------------------------------------------------------
// | NOTE Code below requires sealing locks. |
// | Make sure to release the locks before calling that method. |
// --------------------------------------------------------------------------
if !results.is_empty() && self.options.reseal_on_external_tx && self.sealing.lock().reseal_allowed() {
self.prepare_and_update_sealing(chain);
}
results
}
fn import_own_transaction<C: miner::BlockChainClient>(
&self,
chain: &C,
pending: PendingTransaction
) -> Result<(), transaction::Error> {
// note: you may want to use `import_claimed_local_transaction` instead of this one.
trace!(target: "own_tx", "Importing transaction: {:?}", pending);
let client = self.pool_client(chain);
let imported = self.transaction_queue.import(
client,
vec![pool::verifier::Transaction::Local(pending)]
).pop().expect("one result returned per added transaction; one added => one result; qed");
// --------------------------------------------------------------------------
// | NOTE Code below requires sealing locks. |
// | Make sure to release the locks before calling that method. |
// --------------------------------------------------------------------------
if imported.is_ok() && self.options.reseal_on_own_tx && self.sealing.lock().reseal_allowed() {
self.prepare_and_update_sealing(chain);
}
imported
}
fn import_claimed_local_transaction<C: miner::BlockChainClient>(
&self,
chain: &C,
pending: PendingTransaction,
trusted: bool
) -> Result<(), transaction::Error> {
// treat the tx as local if the option is enabled, or if we have the account
let sender = pending.sender();
let treat_as_local = trusted
|| !self.options.tx_queue_no_unfamiliar_locals
|| self.accounts.as_ref().map(|accts| accts.has_account(sender)).unwrap_or(false);
if treat_as_local {
self.import_own_transaction(chain, pending)
} else {
// We want to replicate behaviour for external transactions if we're not going to treat
// this as local. This is important with regards to sealing blocks
self.import_external_transactions(chain, vec![pending.transaction.into()])
.pop().expect("one result per tx, as in `import_own_transaction`")
}
}
fn local_transactions(&self) -> BTreeMap<H256, pool::local_transactions::Status> {
self.transaction_queue.local_transactions()
}
fn queued_transactions(&self) -> Vec<Arc<VerifiedTransaction>> {
self.transaction_queue.all_transactions()
}
fn queued_transaction_hashes(&self) -> Vec<H256> {
self.transaction_queue.all_transaction_hashes()
}
fn pending_transaction_hashes<C>(&self, chain: &C) -> BTreeSet<H256> where
C: ChainInfo + Sync,
{
let chain_info = chain.chain_info();
let from_queue = || self.transaction_queue.pending_hashes(
|sender| self.nonce_cache.get(sender),
);
let from_pending = || {
self.map_existing_pending_block(|sealing| {
sealing.transactions()
.iter()
.map(|signed| signed.hash())
.collect()
}, chain_info.best_block_number)
};
match self.options.pending_set {
PendingSet::AlwaysQueue => {
from_queue()
},
PendingSet::AlwaysSealing => {
from_pending().unwrap_or_default()
},
PendingSet::SealingOrElseQueue => {
from_pending().unwrap_or_else(from_queue)
},
}
}
fn ready_transactions<C>(&self, chain: &C, max_len: usize, ordering: miner::PendingOrdering)
-> Vec<Arc<VerifiedTransaction>>
where
C: ChainInfo + Nonce + Sync,
{
let chain_info = chain.chain_info();
let from_queue = || {
// We propagate transactions over the nonce cap.
// The mechanism is only to limit number of transactions in pending block
// those transactions are valid and will just be ready to be included in next block.
let nonce_cap = None;
self.transaction_queue.pending(
CachedNonceClient::new(chain, &self.nonce_cache),
pool::PendingSettings {
block_number: chain_info.best_block_number,
current_timestamp: chain_info.best_block_timestamp,
nonce_cap,
max_len,
ordering,
},
)
};