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
mod worker;
pub use crate::worker::{MiningBuild, MiningMetadata, MiningWorker};
use crate::worker::UntilImportedOrTimeout;
use codec::{Decode, Encode};
use futures::{Future, StreamExt};
use log::*;
use parking_lot::Mutex;
use prometheus_endpoint::Registry;
use sc_client_api::{self, backend::AuxStore, BlockOf, BlockchainEvents};
use sc_consensus::{
BasicQueue, BlockCheckParams, BlockImport, BlockImportParams, BoxBlockImport,
BoxJustificationImport, ForkChoiceStrategy, ImportResult, Verifier,
};
use sp_api::ProvideRuntimeApi;
use sp_block_builder::BlockBuilder as BlockBuilderApi;
use sp_blockchain::{well_known_cache_keys::Id as CacheKeyId, HeaderBackend, ProvideCache};
use sp_consensus::{
CanAuthorWith, Environment, Error as ConsensusError, Proposer, SelectChain, SyncOracle,
};
use sp_consensus_pow::{Seal, TotalDifficulty, POW_ENGINE_ID};
use sp_core::ExecutionContext;
use sp_inherents::{CreateInherentDataProviders, InherentDataProvider};
use sp_runtime::{
generic::{BlockId, Digest, DigestItem},
traits::{Block as BlockT, Header as HeaderT},
RuntimeString,
};
use std::{
borrow::Cow, cmp::Ordering, collections::HashMap, marker::PhantomData, sync::Arc,
time::Duration,
};
#[derive(derive_more::Display, Debug)]
pub enum Error<B: BlockT> {
#[display(fmt = "Header uses the wrong engine {:?}", _0)]
WrongEngine([u8; 4]),
#[display(fmt = "Header {:?} is unsealed", _0)]
HeaderUnsealed(B::Hash),
#[display(fmt = "PoW validation error: invalid seal")]
InvalidSeal,
#[display(fmt = "PoW validation error: preliminary verification failed")]
FailedPreliminaryVerify,
#[display(fmt = "Rejecting block too far in future")]
TooFarInFuture,
#[display(fmt = "Fetching best header failed using select chain: {:?}", _0)]
BestHeaderSelectChain(ConsensusError),
#[display(fmt = "Fetching best header failed: {:?}", _0)]
BestHeader(sp_blockchain::Error),
#[display(fmt = "Best header does not exist")]
NoBestHeader,
#[display(fmt = "Block proposing error: {:?}", _0)]
BlockProposingError(String),
#[display(fmt = "Fetch best hash failed via select chain: {:?}", _0)]
BestHashSelectChain(ConsensusError),
#[display(fmt = "Error with block built on {:?}: {:?}", _0, _1)]
BlockBuiltError(B::Hash, ConsensusError),
#[display(fmt = "Creating inherents failed: {}", _0)]
CreateInherents(sp_inherents::Error),
#[display(fmt = "Checking inherents failed: {}", _0)]
CheckInherents(sp_inherents::Error),
#[display(
fmt = "Checking inherents unknown error for identifier: {:?}",
"String::from_utf8_lossy(_0)"
)]
CheckInherentsUnknownError(sp_inherents::InherentIdentifier),
#[display(fmt = "Multiple pre-runtime digests")]
MultiplePreRuntimeDigests,
Client(sp_blockchain::Error),
Codec(codec::Error),
Environment(String),
Runtime(RuntimeString),
Other(String),
}
impl<B: BlockT> std::convert::From<Error<B>> for String {
fn from(error: Error<B>) -> String {
error.to_string()
}
}
impl<B: BlockT> std::convert::From<Error<B>> for ConsensusError {
fn from(error: Error<B>) -> ConsensusError {
ConsensusError::ClientImport(error.to_string())
}
}
pub const POW_AUX_PREFIX: [u8; 4] = *b"PoW:";
fn aux_key<T: AsRef<[u8]>>(hash: &T) -> Vec<u8> {
POW_AUX_PREFIX.iter().chain(hash.as_ref()).copied().collect()
}
#[derive(Encode, Decode, Clone, Debug, Default)]
pub struct PowIntermediate<Difficulty> {
pub difficulty: Option<Difficulty>,
}
pub static INTERMEDIATE_KEY: &[u8] = b"pow1";
#[derive(Encode, Decode, Clone, Debug, Default)]
pub struct PowAux<Difficulty> {
pub difficulty: Difficulty,
pub total_difficulty: Difficulty,
}
impl<Difficulty> PowAux<Difficulty>
where
Difficulty: Decode + Default,
{
pub fn read<C: AuxStore, B: BlockT>(client: &C, hash: &B::Hash) -> Result<Self, Error<B>> {
let key = aux_key(&hash);
match client.get_aux(&key).map_err(Error::Client)? {
Some(bytes) => Self::decode(&mut &bytes[..]).map_err(Error::Codec),
None => Ok(Self::default()),
}
}
}
pub trait PowAlgorithm<B: BlockT> {
type Difficulty: TotalDifficulty + Default + Encode + Decode + Ord + Clone + Copy;
fn difficulty(&self, parent: B::Hash) -> Result<Self::Difficulty, Error<B>>;
fn preliminary_verify(
&self,
_pre_hash: &B::Hash,
_seal: &Seal,
) -> Result<Option<bool>, Error<B>> {
Ok(None)
}
fn break_tie(&self, _own_seal: &Seal, _new_seal: &Seal) -> bool {
false
}
fn verify(
&self,
parent: &BlockId<B>,
pre_hash: &B::Hash,
pre_digest: Option<&[u8]>,
seal: &Seal,
difficulty: Self::Difficulty,
) -> Result<bool, Error<B>>;
}
pub struct PowBlockImport<B: BlockT, I, C, S, Algorithm, CAW, CIDP> {
algorithm: Algorithm,
inner: I,
select_chain: S,
client: Arc<C>,
create_inherent_data_providers: Arc<CIDP>,
check_inherents_after: <<B as BlockT>::Header as HeaderT>::Number,
can_author_with: CAW,
}
impl<B: BlockT, I: Clone, C, S: Clone, Algorithm: Clone, CAW: Clone, CIDP> Clone
for PowBlockImport<B, I, C, S, Algorithm, CAW, CIDP>
{
fn clone(&self) -> Self {
Self {
algorithm: self.algorithm.clone(),
inner: self.inner.clone(),
select_chain: self.select_chain.clone(),
client: self.client.clone(),
create_inherent_data_providers: self.create_inherent_data_providers.clone(),
check_inherents_after: self.check_inherents_after.clone(),
can_author_with: self.can_author_with.clone(),
}
}
}
impl<B, I, C, S, Algorithm, CAW, CIDP> PowBlockImport<B, I, C, S, Algorithm, CAW, CIDP>
where
B: BlockT,
I: BlockImport<B, Transaction = sp_api::TransactionFor<C, B>> + Send + Sync,
I::Error: Into<ConsensusError>,
C: ProvideRuntimeApi<B> + Send + Sync + HeaderBackend<B> + AuxStore + ProvideCache<B> + BlockOf,
C::Api: BlockBuilderApi<B>,
Algorithm: PowAlgorithm<B>,
CAW: CanAuthorWith<B>,
CIDP: CreateInherentDataProviders<B, ()>,
{
pub fn new(
inner: I,
client: Arc<C>,
algorithm: Algorithm,
check_inherents_after: <<B as BlockT>::Header as HeaderT>::Number,
select_chain: S,
create_inherent_data_providers: CIDP,
can_author_with: CAW,
) -> Self {
Self {
inner,
client,
algorithm,
check_inherents_after,
select_chain,
create_inherent_data_providers: Arc::new(create_inherent_data_providers),
can_author_with,
}
}
async fn check_inherents(
&self,
block: B,
block_id: BlockId<B>,
inherent_data_providers: CIDP::InherentDataProviders,
execution_context: ExecutionContext,
) -> Result<(), Error<B>> {
if *block.header().number() < self.check_inherents_after {
return Ok(())
}
if let Err(e) = self.can_author_with.can_author_with(&block_id) {
debug!(
target: "pow",
"Skipping `check_inherents` as authoring version is not compatible: {}",
e,
);
return Ok(())
}
let inherent_data = inherent_data_providers
.create_inherent_data()
.map_err(|e| Error::CreateInherents(e))?;
let inherent_res = self
.client
.runtime_api()
.check_inherents_with_context(&block_id, execution_context, block, inherent_data)
.map_err(|e| Error::Client(e.into()))?;
if !inherent_res.ok() {
for (identifier, error) in inherent_res.into_errors() {
match inherent_data_providers.try_handle_error(&identifier, &error).await {
Some(res) => res.map_err(Error::CheckInherents)?,
None => return Err(Error::CheckInherentsUnknownError(identifier)),
}
}
}
Ok(())
}
}
#[async_trait::async_trait]
impl<B, I, C, S, Algorithm, CAW, CIDP> BlockImport<B>
for PowBlockImport<B, I, C, S, Algorithm, CAW, CIDP>
where
B: BlockT,
I: BlockImport<B, Transaction = sp_api::TransactionFor<C, B>> + Send + Sync,
I::Error: Into<ConsensusError>,
S: SelectChain<B>,
C: ProvideRuntimeApi<B> + Send + Sync + HeaderBackend<B> + AuxStore + ProvideCache<B> + BlockOf,
C::Api: BlockBuilderApi<B>,
Algorithm: PowAlgorithm<B> + Send + Sync,
Algorithm::Difficulty: 'static + Send,
CAW: CanAuthorWith<B> + Send + Sync,
CIDP: CreateInherentDataProviders<B, ()> + Send + Sync,
{
type Error = ConsensusError;
type Transaction = sp_api::TransactionFor<C, B>;
async fn check_block(
&mut self,
block: BlockCheckParams<B>,
) -> Result<ImportResult, Self::Error> {
self.inner.check_block(block).await.map_err(Into::into)
}
async fn import_block(
&mut self,
mut block: BlockImportParams<B, Self::Transaction>,
new_cache: HashMap<CacheKeyId, Vec<u8>>,
) -> Result<ImportResult, Self::Error> {
let best_header = self
.select_chain
.best_chain()
.await
.map_err(|e| format!("Fetch best chain failed via select chain: {:?}", e))?;
let best_hash = best_header.hash();
let parent_hash = *block.header.parent_hash();
let best_aux = PowAux::read::<_, B>(self.client.as_ref(), &best_hash)?;
let mut aux = PowAux::read::<_, B>(self.client.as_ref(), &parent_hash)?;
if let Some(inner_body) = block.body.take() {
let check_block = B::new(block.header.clone(), inner_body);
self.check_inherents(
check_block.clone(),
BlockId::Hash(parent_hash),
self.create_inherent_data_providers
.create_inherent_data_providers(parent_hash, ())
.await?,
block.origin.into(),
)
.await?;
block.body = Some(check_block.deconstruct().1);
}
let inner_seal = fetch_seal::<B>(block.post_digests.last(), block.header.hash())?;
let intermediate =
block.take_intermediate::<PowIntermediate<Algorithm::Difficulty>>(INTERMEDIATE_KEY)?;
let difficulty = match intermediate.difficulty {
Some(difficulty) => difficulty,
None => self.algorithm.difficulty(parent_hash)?,
};
let pre_hash = block.header.hash();
let pre_digest = find_pre_digest::<B>(&block.header)?;
if !self.algorithm.verify(
&BlockId::hash(parent_hash),
&pre_hash,
pre_digest.as_ref().map(|v| &v[..]),
&inner_seal,
difficulty,
)? {
return Err(Error::<B>::InvalidSeal.into())
}
aux.difficulty = difficulty;
aux.total_difficulty.increment(difficulty);
let key = aux_key(&block.post_hash());
block.auxiliary.push((key, Some(aux.encode())));
if block.fork_choice.is_none() {
block.fork_choice = Some(ForkChoiceStrategy::Custom(
match aux.total_difficulty.cmp(&best_aux.total_difficulty) {
Ordering::Less => false,
Ordering::Greater => true,
Ordering::Equal => {
let best_inner_seal =
fetch_seal::<B>(best_header.digest().logs.last(), best_hash)?;
self.algorithm.break_tie(&best_inner_seal, &inner_seal)
},
},
));
}
self.inner.import_block(block, new_cache).await.map_err(Into::into)
}
}
pub struct PowVerifier<B: BlockT, Algorithm> {
algorithm: Algorithm,
_marker: PhantomData<B>,
}
impl<B: BlockT, Algorithm> PowVerifier<B, Algorithm> {
pub fn new(algorithm: Algorithm) -> Self {
Self { algorithm, _marker: PhantomData }
}
fn check_header(
&self,
mut header: B::Header,
) -> Result<(B::Header, DigestItem<B::Hash>), Error<B>>
where
Algorithm: PowAlgorithm<B>,
{
let hash = header.hash();
let (seal, inner_seal) = match header.digest_mut().pop() {
Some(DigestItem::Seal(id, seal)) =>
if id == POW_ENGINE_ID {
(DigestItem::Seal(id, seal.clone()), seal)
} else {
return Err(Error::WrongEngine(id))
},
_ => return Err(Error::HeaderUnsealed(hash)),
};
let pre_hash = header.hash();
if !self.algorithm.preliminary_verify(&pre_hash, &inner_seal)?.unwrap_or(true) {
return Err(Error::FailedPreliminaryVerify)
}
Ok((header, seal))
}
}
#[async_trait::async_trait]
impl<B: BlockT, Algorithm> Verifier<B> for PowVerifier<B, Algorithm>
where
Algorithm: PowAlgorithm<B> + Send + Sync,
Algorithm::Difficulty: 'static + Send,
{
async fn verify(
&mut self,
mut block: BlockImportParams<B, ()>,
) -> Result<(BlockImportParams<B, ()>, Option<Vec<(CacheKeyId, Vec<u8>)>>), String> {
let hash = block.header.hash();
let (checked_header, seal) = self.check_header(block.header)?;
let intermediate = PowIntermediate::<Algorithm::Difficulty> { difficulty: None };
block.header = checked_header;
block.post_digests.push(seal);
block
.intermediates
.insert(Cow::from(INTERMEDIATE_KEY), Box::new(intermediate) as Box<_>);
block.post_hash = Some(hash);
Ok((block, None))
}
}
pub type PowImportQueue<B, Transaction> = BasicQueue<B, Transaction>;
pub fn import_queue<B, Transaction, Algorithm>(
block_import: BoxBlockImport<B, Transaction>,
justification_import: Option<BoxJustificationImport<B>>,
algorithm: Algorithm,
spawner: &impl sp_core::traits::SpawnEssentialNamed,
registry: Option<&Registry>,
) -> Result<PowImportQueue<B, Transaction>, sp_consensus::Error>
where
B: BlockT,
Transaction: Send + Sync + 'static,
Algorithm: PowAlgorithm<B> + Clone + Send + Sync + 'static,
Algorithm::Difficulty: Send,
{
let verifier = PowVerifier::new(algorithm);
Ok(BasicQueue::new(verifier, block_import, justification_import, spawner, registry))
}
pub fn start_mining_worker<Block, C, S, Algorithm, E, SO, L, CIDP, CAW>(
block_import: BoxBlockImport<Block, sp_api::TransactionFor<C, Block>>,
client: Arc<C>,
select_chain: S,
algorithm: Algorithm,
mut env: E,
mut sync_oracle: SO,
justification_sync_link: L,
pre_runtime: Option<Vec<u8>>,
create_inherent_data_providers: CIDP,
timeout: Duration,
build_time: Duration,
can_author_with: CAW,
) -> (
Arc<Mutex<MiningWorker<Block, Algorithm, C, L, <E::Proposer as Proposer<Block>>::Proof>>>,
impl Future<Output = ()>,
)
where
Block: BlockT,
C: ProvideRuntimeApi<Block> + BlockchainEvents<Block> + 'static,
S: SelectChain<Block> + 'static,
Algorithm: PowAlgorithm<Block> + Clone,
Algorithm::Difficulty: Send + 'static,
E: Environment<Block> + Send + Sync + 'static,
E::Error: std::fmt::Debug,
E::Proposer: Proposer<Block, Transaction = sp_api::TransactionFor<C, Block>>,
SO: SyncOracle + Clone + Send + Sync + 'static,
L: sc_consensus::JustificationSyncLink<Block>,
CIDP: CreateInherentDataProviders<Block, ()>,
CAW: CanAuthorWith<Block> + Clone + Send + 'static,
{
let mut timer = UntilImportedOrTimeout::new(client.import_notification_stream(), timeout);
let worker = Arc::new(Mutex::new(MiningWorker {
build: None,
algorithm: algorithm.clone(),
block_import,
justification_sync_link,
}));
let worker_ret = worker.clone();
let task = async move {
loop {
if timer.next().await.is_none() {
break
}
if sync_oracle.is_major_syncing() {
debug!(target: "pow", "Skipping proposal due to sync.");
worker.lock().on_major_syncing();
return
}
let best_header = match select_chain.best_chain().await {
Ok(x) => x,
Err(err) => {
warn!(
target: "pow",
"Unable to pull new block for authoring. \
Select best chain error: {:?}",
err
);
return
},
};
let best_hash = best_header.hash();
if let Err(err) = can_author_with.can_author_with(&BlockId::Hash(best_hash)) {
warn!(
target: "pow",
"Skipping proposal `can_author_with` returned: {} \
Probably a node update is required!",
err,
);
return
}
if worker.lock().best_hash() == Some(best_hash) {
return
}
let difficulty = match algorithm.difficulty(best_hash) {
Ok(x) => x,
Err(err) => {
warn!(
target: "pow",
"Unable to propose new block for authoring. \
Fetch difficulty failed: {:?}",
err,
);
return
},
};
let inherent_data_providers = match create_inherent_data_providers
.create_inherent_data_providers(best_hash, ())
.await
{
Ok(x) => x,
Err(err) => {
warn!(
target: "pow",
"Unable to propose new block for authoring. \
Creating inherent data providers failed: {:?}",
err,
);
return
},
};
let inherent_data = match inherent_data_providers.create_inherent_data() {
Ok(r) => r,
Err(e) => {
warn!(
target: "pow",
"Unable to propose new block for authoring. \
Creating inherent data failed: {:?}",
e,
);
return
},
};
let mut inherent_digest = Digest::<Block::Hash>::default();
if let Some(pre_runtime) = &pre_runtime {
inherent_digest.push(DigestItem::PreRuntime(POW_ENGINE_ID, pre_runtime.to_vec()));
}
let pre_runtime = pre_runtime.clone();
let proposer = match env.init(&best_header).await {
Ok(x) => x,
Err(err) => {
warn!(
target: "pow",
"Unable to propose new block for authoring. \
Creating proposer failed: {:?}",
err,
);
return
},
};
let proposal = match proposer
.propose(inherent_data, inherent_digest, build_time.clone(), None)
.await
{
Ok(x) => x,
Err(err) => {
warn!(
target: "pow",
"Unable to propose new block for authoring. \
Creating proposal failed: {:?}",
err,
);
return
},
};
let build = MiningBuild::<Block, Algorithm, C, _> {
metadata: MiningMetadata {
best_hash,
pre_hash: proposal.block.header().hash(),
pre_runtime: pre_runtime.clone(),
difficulty,
},
proposal,
};
worker.lock().on_build(build);
}
};
(worker_ret, task)
}
fn find_pre_digest<B: BlockT>(header: &B::Header) -> Result<Option<Vec<u8>>, Error<B>> {
let mut pre_digest: Option<_> = None;
for log in header.digest().logs() {
trace!(target: "pow", "Checking log {:?}, looking for pre runtime digest", log);
match (log, pre_digest.is_some()) {
(DigestItem::PreRuntime(POW_ENGINE_ID, _), true) =>
return Err(Error::MultiplePreRuntimeDigests),
(DigestItem::PreRuntime(POW_ENGINE_ID, v), false) => {
pre_digest = Some(v.clone());
},
(_, _) => trace!(target: "pow", "Ignoring digest not meant for us"),
}
}
Ok(pre_digest)
}
fn fetch_seal<B: BlockT>(
digest: Option<&DigestItem<B::Hash>>,
hash: B::Hash,
) -> Result<Vec<u8>, Error<B>> {
match digest {
Some(DigestItem::Seal(id, seal)) =>
if id == &POW_ENGINE_ID {
Ok(seal.clone())
} else {
return Err(Error::<B>::WrongEngine(*id).into())
},
_ => return Err(Error::<B>::HeaderUnsealed(hash).into()),
}
}