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
use std::sync::Arc;
use crate::ChainInfo;
use futures::{
channel::{mpsc, oneshot},
FutureExt, SinkExt,
};
use jsonrpc_core::MetaIoHandler;
use manual_seal::EngineCommand;
use sc_client_api::{
backend::{self, Backend},
CallExecutor, ExecutorProvider,
};
use sc_service::{TFullBackend, TFullCallExecutor, TFullClient, TaskManager};
use sc_transaction_pool_api::TransactionPool;
use sp_api::{OverlayedChanges, StorageTransactionCache};
use sp_blockchain::HeaderBackend;
use sp_core::ExecutionContext;
use sp_runtime::{
generic::{BlockId, UncheckedExtrinsic},
traits::{Block as BlockT, Extrinsic, Header, NumberFor},
transaction_validity::TransactionSource,
MultiAddress, MultiSignature,
};
use sp_state_machine::Ext;
pub struct Node<T: ChainInfo> {
rpc_handler: Arc<MetaIoHandler<sc_rpc::Metadata, sc_rpc_server::RpcMiddleware>>,
task_manager: Option<TaskManager>,
client: Arc<TFullClient<T::Block, T::RuntimeApi, T::Executor>>,
pool: Arc<
dyn TransactionPool<
Block = <T as ChainInfo>::Block,
Hash = <<T as ChainInfo>::Block as BlockT>::Hash,
Error = sc_transaction_pool::error::Error,
InPoolTransaction = sc_transaction_pool::Transaction<
<<T as ChainInfo>::Block as BlockT>::Hash,
<<T as ChainInfo>::Block as BlockT>::Extrinsic,
>,
>,
>,
manual_seal_command_sink: mpsc::Sender<EngineCommand<<T::Block as BlockT>::Hash>>,
backend: Arc<TFullBackend<T::Block>>,
initial_block_number: NumberFor<T::Block>,
}
type EventRecord<T> = frame_system::EventRecord<
<T as frame_system::Config>::Event,
<T as frame_system::Config>::Hash,
>;
impl<T> Node<T>
where
T: ChainInfo,
<<T::Block as BlockT>::Header as Header>::Number: From<u32>,
{
pub fn new(
rpc_handler: Arc<MetaIoHandler<sc_rpc::Metadata, sc_rpc_server::RpcMiddleware>>,
task_manager: TaskManager,
client: Arc<TFullClient<T::Block, T::RuntimeApi, T::Executor>>,
pool: Arc<
dyn TransactionPool<
Block = <T as ChainInfo>::Block,
Hash = <<T as ChainInfo>::Block as BlockT>::Hash,
Error = sc_transaction_pool::error::Error,
InPoolTransaction = sc_transaction_pool::Transaction<
<<T as ChainInfo>::Block as BlockT>::Hash,
<<T as ChainInfo>::Block as BlockT>::Extrinsic,
>,
>,
>,
command_sink: mpsc::Sender<EngineCommand<<T::Block as BlockT>::Hash>>,
backend: Arc<TFullBackend<T::Block>>,
) -> Self {
Self {
rpc_handler,
task_manager: Some(task_manager),
client: client.clone(),
pool,
backend,
manual_seal_command_sink: command_sink,
initial_block_number: client.info().best_number,
}
}
pub fn rpc_handler(
&self,
) -> Arc<MetaIoHandler<sc_rpc::Metadata, sc_rpc_server::RpcMiddleware>> {
self.rpc_handler.clone()
}
pub fn client(&self) -> Arc<TFullClient<T::Block, T::RuntimeApi, T::Executor>> {
self.client.clone()
}
pub fn pool(
&self,
) -> Arc<
dyn TransactionPool<
Block = <T as ChainInfo>::Block,
Hash = <<T as ChainInfo>::Block as BlockT>::Hash,
Error = sc_transaction_pool::error::Error,
InPoolTransaction = sc_transaction_pool::Transaction<
<<T as ChainInfo>::Block as BlockT>::Hash,
<<T as ChainInfo>::Block as BlockT>::Extrinsic,
>,
>,
> {
self.pool.clone()
}
pub fn with_state<R>(&self, closure: impl FnOnce() -> R) -> R
where
<TFullCallExecutor<T::Block, T::Executor> as CallExecutor<T::Block>>::Error:
std::fmt::Debug,
{
let id = BlockId::Hash(self.client.info().best_hash);
let mut overlay = OverlayedChanges::default();
let changes_trie =
backend::changes_tries_state_at_block(&id, self.backend.changes_trie_storage())
.unwrap();
let mut cache = StorageTransactionCache::<
T::Block,
<TFullBackend<T::Block> as Backend<T::Block>>::State,
>::default();
let mut extensions = self
.client
.execution_extensions()
.extensions(&id, ExecutionContext::BlockConstruction);
let state_backend = self
.backend
.state_at(id.clone())
.expect(&format!("State at block {} not found", id));
let mut ext = Ext::new(
&mut overlay,
&mut cache,
&state_backend,
changes_trie.clone(),
Some(&mut extensions),
);
sp_externalities::set_and_run_with_externalities(&mut ext, closure)
}
pub async fn submit_extrinsic(
&self,
call: impl Into<<T::Runtime as frame_system::Config>::Call>,
signer: Option<<T::Runtime as frame_system::Config>::AccountId>,
) -> Result<<T::Block as BlockT>::Hash, sc_transaction_pool::error::Error>
where
<T::Block as BlockT>::Extrinsic: From<
UncheckedExtrinsic<
MultiAddress<
<T::Runtime as frame_system::Config>::AccountId,
<T::Runtime as frame_system::Config>::Index,
>,
<T::Runtime as frame_system::Config>::Call,
MultiSignature,
T::SignedExtras,
>,
>,
{
let signed_data = if let Some(signer) = signer {
let extra = self.with_state(|| T::signed_extras(signer.clone()));
Some((signer.into(), MultiSignature::Sr25519(Default::default()), extra))
} else {
None
};
let ext = UncheckedExtrinsic::<
MultiAddress<
<T::Runtime as frame_system::Config>::AccountId,
<T::Runtime as frame_system::Config>::Index,
>,
<T::Runtime as frame_system::Config>::Call,
MultiSignature,
T::SignedExtras,
>::new(call.into(), signed_data)
.expect("UncheckedExtrinsic::new() always returns Some");
let at = self.client.info().best_hash;
self.pool
.submit_one(&BlockId::Hash(at), TransactionSource::Local, ext.into())
.await
}
pub fn events(&self) -> Vec<EventRecord<T::Runtime>> {
self.with_state(|| frame_system::Pallet::<T::Runtime>::events())
}
pub async fn seal_blocks(&self, num: usize) {
let mut sink = self.manual_seal_command_sink.clone();
for count in 0..num {
let (sender, future_block) = oneshot::channel();
let future = sink.send(EngineCommand::SealNewBlock {
create_empty: true,
finalize: false,
parent_hash: None,
sender: Some(sender),
});
const ERROR: &'static str = "manual-seal authorship task is shutting down";
future.await.expect(ERROR);
match future_block.await.expect(ERROR) {
Ok(block) =>
log::info!("sealed {} (hash: {}) of {} blocks", count + 1, block.hash, num),
Err(err) =>
log::error!("failed to seal block {} of {}, error: {:?}", count + 1, num, err),
}
}
}
pub fn revert_blocks(&self, count: NumberFor<T::Block>) {
self.backend.revert(count, true).expect("Failed to revert blocks: ");
}
pub async fn until_shutdown(mut self) {
let manager = self.task_manager.take();
if let Some(mut task_manager) = manager {
let task = task_manager.future().fuse();
let signal = tokio::signal::ctrl_c();
futures::pin_mut!(signal);
futures::future::select(task, signal).await;
task_manager.clean_shutdown().await
}
}
}
impl<T: ChainInfo> Drop for Node<T> {
fn drop(&mut self) {
let diff = self.client.info().best_number - self.initial_block_number;
self.revert_blocks(diff);
}
}