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
use futures::{
prelude::*,
task::{Context, Poll},
};
use futures_timer::Delay;
use log::*;
use sc_client_api::ImportNotifications;
use sp_consensus::{
import_queue::BoxBlockImport, BlockImportParams, BlockOrigin, Proposal, StateAction,
StorageChanges,
};
use sp_runtime::{
generic::BlockId,
traits::{Block as BlockT, Header as HeaderT},
DigestItem,
};
use std::{borrow::Cow, collections::HashMap, pin::Pin, time::Duration};
use crate::{PowAlgorithm, PowIntermediate, Seal, INTERMEDIATE_KEY, POW_ENGINE_ID};
#[derive(Clone, Eq, PartialEq)]
pub struct MiningMetadata<H, D> {
pub best_hash: H,
pub pre_hash: H,
pub pre_runtime: Option<Vec<u8>>,
pub difficulty: D,
}
pub struct MiningBuild<
Block: BlockT,
Algorithm: PowAlgorithm<Block>,
C: sp_api::ProvideRuntimeApi<Block>,
Proof,
> {
pub metadata: MiningMetadata<Block::Hash, Algorithm::Difficulty>,
pub proposal: Proposal<Block, sp_api::TransactionFor<C, Block>, Proof>,
}
pub struct MiningWorker<
Block: BlockT,
Algorithm: PowAlgorithm<Block>,
C: sp_api::ProvideRuntimeApi<Block>,
L: sp_consensus::JustificationSyncLink<Block>,
Proof,
> {
pub(crate) build: Option<MiningBuild<Block, Algorithm, C, Proof>>,
pub(crate) algorithm: Algorithm,
pub(crate) block_import: BoxBlockImport<Block, sp_api::TransactionFor<C, Block>>,
pub(crate) justification_sync_link: L,
}
impl<Block, Algorithm, C, L, Proof> MiningWorker<Block, Algorithm, C, L, Proof>
where
Block: BlockT,
C: sp_api::ProvideRuntimeApi<Block>,
Algorithm: PowAlgorithm<Block>,
Algorithm::Difficulty: 'static + Send,
L: sp_consensus::JustificationSyncLink<Block>,
sp_api::TransactionFor<C, Block>: Send + 'static,
{
pub fn best_hash(&self) -> Option<Block::Hash> {
self.build.as_ref().map(|b| b.metadata.best_hash)
}
pub(crate) fn on_major_syncing(&mut self) {
self.build = None;
}
pub(crate) fn on_build(&mut self, build: MiningBuild<Block, Algorithm, C, Proof>) {
self.build = Some(build);
}
pub fn metadata(&self) -> Option<MiningMetadata<Block::Hash, Algorithm::Difficulty>> {
self.build.as_ref().map(|b| b.metadata.clone())
}
pub async fn submit(&mut self, seal: Seal) -> bool {
if let Some(build) = self.build.take() {
match self.algorithm.verify(
&BlockId::Hash(build.metadata.best_hash),
&build.metadata.pre_hash,
build.metadata.pre_runtime.as_ref().map(|v| &v[..]),
&seal,
build.metadata.difficulty,
) {
Ok(true) => (),
Ok(false) => {
warn!(
target: "pow",
"Unable to import mined block: seal is invalid",
);
return false
},
Err(err) => {
warn!(
target: "pow",
"Unable to import mined block: {:?}",
err,
);
return false
},
}
let seal = DigestItem::Seal(POW_ENGINE_ID, seal);
let (header, body) = build.proposal.block.deconstruct();
let mut import_block = BlockImportParams::new(BlockOrigin::Own, header);
import_block.post_digests.push(seal);
import_block.body = Some(body);
import_block.state_action =
StateAction::ApplyChanges(StorageChanges::Changes(build.proposal.storage_changes));
let intermediate = PowIntermediate::<Algorithm::Difficulty> {
difficulty: Some(build.metadata.difficulty),
};
import_block
.intermediates
.insert(Cow::from(INTERMEDIATE_KEY), Box::new(intermediate) as Box<_>);
let header = import_block.post_header();
match self.block_import.import_block(import_block, HashMap::default()).await {
Ok(res) => {
res.handle_justification(
&header.hash(),
*header.number(),
&mut self.justification_sync_link,
);
info!(
target: "pow",
"✅ Successfully mined block on top of: {}",
build.metadata.best_hash
);
true
},
Err(err) => {
warn!(
target: "pow",
"Unable to import mined block: {:?}",
err,
);
false
},
}
} else {
warn!(
target: "pow",
"Unable to import mined block: build does not exist",
);
false
}
}
}
pub struct UntilImportedOrTimeout<Block: BlockT> {
import_notifications: ImportNotifications<Block>,
timeout: Duration,
inner_delay: Option<Delay>,
}
impl<Block: BlockT> UntilImportedOrTimeout<Block> {
pub fn new(import_notifications: ImportNotifications<Block>, timeout: Duration) -> Self {
Self { import_notifications, timeout, inner_delay: None }
}
}
impl<Block: BlockT> Stream for UntilImportedOrTimeout<Block> {
type Item = ();
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<()>> {
let mut fire = false;
loop {
match Stream::poll_next(Pin::new(&mut self.import_notifications), cx) {
Poll::Pending => break,
Poll::Ready(Some(_)) => {
fire = true;
},
Poll::Ready(None) => return Poll::Ready(None),
}
}
let timeout = self.timeout.clone();
let inner_delay = self.inner_delay.get_or_insert_with(|| Delay::new(timeout));
match Future::poll(Pin::new(inner_delay), cx) {
Poll::Pending => (),
Poll::Ready(()) => {
fire = true;
},
}
if fire {
self.inner_delay = None;
Poll::Ready(Some(()))
} else {
Poll::Pending
}
}
}