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
// This file is part of Substrate.

// Copyright (C) 2021 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0

// This program 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.

// This program 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 this program. If not, see <https://www.gnu.org/licenses/>.

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;

/// This holds a reference to a running node on another thread,
/// the node process is dropped when this struct is dropped
/// also holds logs from the process.
pub struct Node<T: ChainInfo> {
	/// rpc handler for communicating with the node over rpc.
	rpc_handler: Arc<MetaIoHandler<sc_rpc::Metadata, sc_rpc_server::RpcMiddleware>>,
	/// handle to the running node.
	task_manager: Option<TaskManager>,
	/// client instance
	client: Arc<TFullClient<T::Block, T::RuntimeApi, T::Executor>>,
	/// transaction pool
	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,
			>,
		>,
	>,
	/// channel to communicate with manual seal on.
	manual_seal_command_sink: mpsc::Sender<EngineCommand<<T::Block as BlockT>::Hash>>,
	/// backend type.
	backend: Arc<TFullBackend<T::Block>>,
	/// Block number at initialization of this Node.
	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>,
{
	/// Creates a new node.
	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,
		}
	}

	/// Returns a reference to the rpc handlers, use this to send rpc requests.
	/// eg
	/// ```ignore
	/// 	let request = r#"{"jsonrpc":"2.0","method":"engine_createBlock","params": [true, true],"id":1}"#;
	/// 		let response = node.rpc_handler()
	/// 		.handle_request_sync(request, Default::default());
	/// ```
	pub fn rpc_handler(
		&self,
	) -> Arc<MetaIoHandler<sc_rpc::Metadata, sc_rpc_server::RpcMiddleware>> {
		self.rpc_handler.clone()
	}

	/// Return a reference to the Client
	pub fn client(&self) -> Arc<TFullClient<T::Block, T::RuntimeApi, T::Executor>> {
		self.client.clone()
	}

	/// Return a reference to the pool.
	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()
	}

	/// Executes closure in an externalities provided environment.
	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)
	}

	/// submit some extrinsic to the node. if signer is None, will submit unsigned_extrinsic.
	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
	}

	/// Get the events of the most recently produced block
	pub fn events(&self) -> Vec<EventRecord<T::Runtime>> {
		self.with_state(|| frame_system::Pallet::<T::Runtime>::events())
	}

	/// Instructs manual seal to seal new, possibly empty blocks.
	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),
			}
		}
	}

	/// Revert count number of blocks from the chain.
	pub fn revert_blocks(&self, count: NumberFor<T::Block>) {
		self.backend.revert(count, true).expect("Failed to revert blocks: ");
	}

	/// so you've decided to run the test runner as a binary, use this to shutdown gracefully.
	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;
			// we don't really care whichever comes first.
			task_manager.clean_shutdown().await
		}
	}
}

impl<T: ChainInfo> Drop for Node<T> {
	fn drop(&mut self) {
		// Revert all blocks added since creation of the node.
		let diff = self.client.info().best_number - self.initial_block_number;
		self.revert_blocks(diff);
	}
}