lib.rs 17.6 KB
Newer Older
Gav's avatar
Gav committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// Copyright 2017 Parity Technologies (UK) Ltd.
// This file is part of Polkadot.

// Polkadot 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.

// Polkadot 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 Polkadot.  If not, see <http://www.gnu.org/licenses/>.

17
//! Collation node logic.
Gav's avatar
Gav committed
18
19
20
21
22
23
24
25
26
27
28
29
30
//!
//! A collator node lives on a distinct parachain and submits a proposal for
//! a state transition, along with a proof for its validity
//! (what we might call a witness or block data).
//!
//! One of collators' other roles is to route messages between chains.
//! Each parachain produces a list of "egress" posts of messages for each other
//! parachain on each block, for a total of N^2 lists all together.
//!
//! We will refer to the egress list at relay chain block X of parachain A with
//! destination B as egress(X)[A -> B]
//!
//! On every block, each parachain will be intended to route messages from some
31
//! subset of all the other parachains. (NOTE: in practice this is not done until PoC-3)
Gav's avatar
Gav committed
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
//!
//! Since the egress information is unique to every block, when routing from a
//! parachain a collator must gather all egress posts from that parachain
//! up to the last point in history that messages were successfully routed
//! from that parachain, accounting for relay chain blocks where no candidate
//! from the collator's parachain was produced.
//!
//! In the case that all parachains route to each other and a candidate for the
//! collator's parachain was included in the last relay chain block, the collator
//! only has to gather egress posts from other parachains one block back in relay
//! chain history.
//!
//! This crate defines traits which provide context necessary for collation logic
//! to be performed, as the collation logic itself.

47
use std::collections::HashSet;
48
use std::fmt;
49
use std::sync::Arc;
50
use std::time::Duration;
Gav's avatar
Gav committed
51

Ashley's avatar
Ashley committed
52
use futures::{future, Future, Stream, FutureExt, TryFutureExt, StreamExt, task::Spawn};
53
use log::{warn, error};
54
use client::BlockchainEvents;
55
use primitives::{Pair, Blake2Hasher};
56
use polkadot_primitives::{
57
	BlockId, Hash, Block,
58
	parachain::{
59
60
		self, BlockData, DutyRoster, HeadData, ConsolidatedIngress, Message, Id as ParaId,
		OutgoingMessages, PoVBlock, Status as ParachainStatus, ValidatorId, CollatorPair,
61
62
63
	}
};
use polkadot_cli::{
64
	Worker, IntoExit, ProvideRuntimeApi, AbstractService, CustomConfiguration, ParachainHost,
65
};
66
67
use polkadot_network::validation::{LeafWorkParams, ValidationNetwork};
use polkadot_network::{PolkadotNetworkService, PolkadotProtocol};
68
use polkadot_runtime::RuntimeApi;
69

Ashley's avatar
Ashley committed
70
pub use polkadot_cli::VersionInfo;
71
pub use polkadot_network::validation::Incoming;
72
73
pub use polkadot_validation::SignedStatement;
pub use polkadot_primitives::parachain::CollatorId;
74
pub use sc_network::PeerId;
75

76
const COLLATION_TIMEOUT: Duration = Duration::from_secs(30);
Gav's avatar
Gav committed
77

78
/// An abstraction over the `Network` with useful functions for a `Collator`.
79
pub trait Network: Send + Sync {
80
81
	/// Convert the given `CollatorId` to a `PeerId`.
	fn collator_id_to_peer_id(&self, collator_id: CollatorId) ->
82
		Box<dyn Future<Output=Option<PeerId>> + Unpin + Send>;
83
84
85
86
87
88

	/// Create a `Stream` of checked statements for the given `relay_parent`.
	///
	/// The returned stream will not terminate, so it is required to make sure that the stream is
	/// dropped when it is not required anymore. Otherwise, it will stick around in memory
	/// infinitely.
89
	fn checked_statements(&self, relay_parent: Hash) -> Box<dyn Stream<Item=SignedStatement>>;
90
91
}

Ashley's avatar
Ashley committed
92
impl<P, E, SP> Network for ValidationNetwork<P, E, PolkadotNetworkService, SP> where
93
94
	P: 'static + Send + Sync,
	E: 'static + Send + Sync,
Ashley's avatar
Ashley committed
95
	SP: 'static + Spawn + Clone + Send + Sync,
96
97
{
	fn collator_id_to_peer_id(&self, collator_id: CollatorId) ->
98
		Box<dyn Future<Output=Option<PeerId>> + Unpin + Send>
99
	{
Ashley's avatar
Ashley committed
100
		Box::new(Self::collator_id_to_peer_id(self, collator_id))
101
102
	}

103
	fn checked_statements(&self, relay_parent: Hash) -> Box<dyn Stream<Item=SignedStatement>> {
Ashley's avatar
Ashley committed
104
		Box::new(Self::checked_statements(self, relay_parent))
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
/// Error to return when the head data was invalid.
#[derive(Clone, Copy, Debug)]
pub struct InvalidHead;

/// Collation errors.
#[derive(Debug)]
pub enum Error<R> {
	/// Error on the relay-chain side of things.
	Polkadot(R),
	/// Error on the collator side of things.
	Collator(InvalidHead),
}

impl<R: fmt::Display> fmt::Display for Error<R> {
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
		match *self {
			Error::Polkadot(ref err) => write!(f, "Polkadot node error: {}", err),
			Error::Collator(_) => write!(f, "Collator node error: Invalid head data"),
		}
	}
}

130
131
132
/// The Polkadot client type.
pub type PolkadotClient<B, E> = client::Client<B, E, Block, RuntimeApi>;

133
134
135
136
137
138
/// Something that can build a `ParachainContext`.
pub trait BuildParachainContext {
	/// The parachain context produced by the `build` function.
	type ParachainContext: self::ParachainContext;

	/// Build the `ParachainContext`.
Ashley's avatar
Ashley committed
139
	fn build<B, E, SP>(
140
141
		self,
		client: Arc<PolkadotClient<B, E>>,
Ashley's avatar
Ashley committed
142
		spawner: SP,
143
144
145
		network: Arc<dyn Network>,
	) -> Result<Self::ParachainContext, ()>
		where
146
			B: client_api::backend::Backend<Block, Blake2Hasher> + 'static,
Ashley's avatar
Ashley committed
147
148
			E: client::CallExecutor<Block, Blake2Hasher> + Clone + Send + Sync + 'static,
			SP: Spawn + Clone;
149
150
}

Gav's avatar
Gav committed
151
152
153
/// Parachain context needed for collation.
///
/// This can be implemented through an externally attached service or a stub.
154
155
/// This is expected to be a lightweight, shared type like an Arc.
pub trait ParachainContext: Clone {
156
	type ProduceCandidate: Future<Output = Result<(BlockData, HeadData, OutgoingMessages), InvalidHead>>;
157

158
159
	/// Produce a candidate, given the relay parent hash, the latest ingress queue information
	/// and the last parachain head.
Gav's avatar
Gav committed
160
	fn produce_candidate<I: IntoIterator<Item=(ParaId, Message)>>(
161
		&mut self,
162
		relay_parent: Hash,
163
		status: ParachainStatus,
Gav's avatar
Gav committed
164
		ingress: I,
165
	) -> Self::ProduceCandidate;
Gav's avatar
Gav committed
166
167
168
169
170
171
}

/// Relay chain context needed to collate.
/// This encapsulates a network and local database which may store
/// some of the input.
pub trait RelayChainContext {
172
	type Error: std::fmt::Debug;
Gav's avatar
Gav committed
173
174
175

	/// Future that resolves to the un-routed egress queues of a parachain.
	/// The first item is the oldest.
176
	type FutureEgress: Future<Output = Result<ConsolidatedIngress, Self::Error>>;
Gav's avatar
Gav committed
177
178

	/// Get un-routed egress queues from a parachain to the local parachain.
179
	fn unrouted_egress(&self, _id: ParaId) -> Self::FutureEgress;
Gav's avatar
Gav committed
180
181
}

182
/// Produce a candidate for the parachain, with given contexts, parent head, and signing key.
183
pub async fn collate<R, P>(
184
	relay_parent: Hash,
185
	local_id: ParaId,
186
	parachain_status: ParachainStatus,
187
	relay_context: R,
188
	mut para_context: P,
189
	key: Arc<CollatorPair>,
190
)
191
	-> Result<(parachain::Collation, OutgoingMessages), Error<R::Error>>
Gav's avatar
Gav committed
192
	where
193
		R: RelayChainContext,
194
195
		P: ParachainContext,
		P::ProduceCandidate: Send,
Gav's avatar
Gav committed
196
{
197
198
199
200
201
202
203
204
205
206
207
208
209
	let ingress = relay_context.unrouted_egress(local_id).await.map_err(Error::Polkadot)?;

	let (block_data, head_data, mut outgoing) = para_context.produce_candidate(
		relay_parent,
		parachain_status,
		ingress.0.iter().flat_map(|&(id, ref msgs)| msgs.iter().cloned().map(move |msg| (id, msg)))
	).map_err(Error::Collator).await?;

	let block_data_hash = block_data.hash();
	let signature = key.sign(block_data_hash.as_ref());
	let egress_queue_roots =
		polkadot_validation::egress_roots(&mut outgoing.outgoing_messages);

210
	let info = parachain::CollationInfo {
211
212
213
214
		parachain_index: local_id,
		collator: key.public(),
		signature,
		egress_queue_roots,
215
		head_data,
216
217
218
219
220
		block_data_hash,
		upward_messages: Vec::new(),
	};

	let collation = parachain::Collation {
221
		info,
222
223
224
225
226
227
228
		pov: PoVBlock {
			block_data,
			ingress,
		},
	};

	Ok((collation, outgoing))
Gav's avatar
Gav committed
229
230
}

231
/// Polkadot-api context.
Ashley's avatar
Ashley committed
232
233
struct ApiContext<P, E, SP> {
	network: Arc<ValidationNetwork<P, E, PolkadotNetworkService, SP>>,
234
	parent_hash: Hash,
235
	validators: Vec<ValidatorId>,
236
}
237

Ashley's avatar
Ashley committed
238
impl<P: 'static, E: 'static, SP: 'static> RelayChainContext for ApiContext<P, E, SP> where
239
240
	P: ProvideRuntimeApi + Send + Sync,
	P::Api: ParachainHost<Block>,
Gavin Wood's avatar
Gavin Wood committed
241
	E: futures::Future<Output=()> + Clone + Send + Sync + 'static,
Ashley's avatar
Ashley committed
242
	SP: Spawn + Clone + Send + Sync
243
244
{
	type Error = String;
245
	type FutureEgress = Box<dyn Future<Output=Result<ConsolidatedIngress, String>> + Unpin + Send>;
246

247
248
249
250
	fn unrouted_egress(&self, _id: ParaId) -> Self::FutureEgress {
		// TODO: https://github.com/paritytech/polkadot/issues/253
		//
		// Fetch ingress and accumulate all unrounted egress
251
		let _session = self.network.instantiate_leaf_work(LeafWorkParams {
252
253
			local_session_key: None,
			parent_hash: self.parent_hash,
254
			authorities: self.validators.clone(),
255
256
		})
			.map_err(|e| format!("unable to instantiate validation session: {:?}", e));
257

258
		Box::new(future::ok(ConsolidatedIngress(Vec::new())))
259
260
261
262
	}
}

struct CollationNode<P, E> {
263
	build_parachain_context: P,
264
265
	exit: E,
	para_id: ParaId,
266
	key: Arc<CollatorPair>,
267
268
}

269
impl<P, E> IntoExit for CollationNode<P, E> where
Gavin Wood's avatar
Gavin Wood committed
270
	E: futures::Future<Output=()> + Unpin + Send + 'static
271
{
Gavin Wood's avatar
Gavin Wood committed
272
	type Exit = E;
273
	fn into_exit(self) -> Self::Exit {
Gavin Wood's avatar
Gavin Wood committed
274
		self.exit
275
276
277
	}
}

278
impl<P, E> Worker for CollationNode<P, E> where
279
280
	P: BuildParachainContext + Send + 'static,
	P::ParachainContext: Send + 'static,
281
	<P::ParachainContext as ParachainContext>::ProduceCandidate: Send + 'static,
Gavin Wood's avatar
Gavin Wood committed
282
	E: futures::Future<Output=()> + Clone + Unpin + Send + Sync + 'static,
283
{
284
	type Work = Box<dyn Future<Output=()> + Unpin + Send>;
285

286
287
288
	fn configuration(&self) -> CustomConfiguration {
		let mut config = CustomConfiguration::default();
		config.collating_for = Some((
Gav Wood's avatar
Gav Wood committed
289
			self.key.public(),
290
			self.para_id,
291
292
293
294
		));
		config
	}

Ashley's avatar
Ashley committed
295
	fn work<S, SC, B, CE, SP>(self, service: &S, spawner: SP) -> Self::Work
296
297
298
299
300
301
302
303
304
305
	where
		S: AbstractService<
			Block = Block,
			RuntimeApi = RuntimeApi,
			Backend = B,
			SelectChain = SC,
			NetworkSpecialization = PolkadotProtocol,
			CallExecutor = CE,
		>,
		SC: polkadot_service::SelectChain<Block> + 'static,
306
		B: client_api::backend::Backend<Block, Blake2Hasher> + 'static,
Ashley's avatar
Ashley committed
307
308
		CE: client::CallExecutor<Block, Blake2Hasher> + Clone + Send + Sync + 'static,
		SP: Spawn + Clone + Send + Sync + 'static,
309
	{
310
		let CollationNode { build_parachain_context, exit, para_id, key } = self;
311
		let client = service.client();
312
		let network = service.network();
313
		let known_oracle = client.clone();
thiolliere's avatar
thiolliere committed
314
315
316
		let select_chain = if let Some(select_chain) = service.select_chain() {
			select_chain
		} else {
317
			error!("The node cannot work because it can't select chain.");
318
			return Box::new(future::ready(()));
thiolliere's avatar
thiolliere committed
319
		};
320

321
		let is_known = move |block_hash: &Hash| {
322
			use consensus_common::BlockStatus;
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
			use polkadot_network::gossip::Known;

			match known_oracle.block_status(&BlockId::hash(*block_hash)) {
				Err(_) | Ok(BlockStatus::Unknown) | Ok(BlockStatus::Queued) => None,
				Ok(BlockStatus::KnownBad) => Some(Known::Bad),
				Ok(BlockStatus::InChainWithState) | Ok(BlockStatus::InChainPruned) =>
					match select_chain.leaves() {
						Err(_) => None,
						Ok(leaves) => if leaves.contains(block_hash) {
							Some(Known::Leaf)
						} else {
							Some(Known::Old)
						},
					}
			}
		};

340
		let message_validator = polkadot_network::gossip::register_validator(
341
			network.clone(),
342
			(is_known, client.clone()),
343
344
		);

345
		let validation_network = Arc::new(ValidationNetwork::new(
346
347
348
349
			network.clone(),
			exit.clone(),
			message_validator,
			client.clone(),
Ashley's avatar
Ashley committed
350
			spawner.clone(),
351
		));
352

353
354
		let parachain_context = match build_parachain_context.build(
			client.clone(),
Ashley's avatar
Ashley committed
355
			spawner,
356
357
358
359
360
			validation_network.clone(),
		) {
			Ok(ctx) => ctx,
			Err(()) => {
				error!("Could not build the parachain context!");
361
				return Box::new(future::ready(()))
362
363
364
			}
		};

365
		let inner_exit = exit.clone();
366
		let work = client.import_notification_stream()
367
368
369
370
371
			.for_each(move |notification| {
				macro_rules! try_fr {
					($e:expr) => {
						match $e {
							Ok(x) => x,
372
							Err(e) => return future::Either::Left(future::err(Error::Polkadot(
373
374
								format!("{:?}", e)
							))),
375
						}
376
					}
377
378
379
380
381
382
				}

				let relay_parent = notification.hash;
				let id = BlockId::hash(relay_parent);

				let network = network.clone();
383
				let client = client.clone();
384
385
				let key = key.clone();
				let parachain_context = parachain_context.clone();
386
				let validation_network = validation_network.clone();
387
				let inner_exit_2 = inner_exit.clone();
388

389
				let work = future::lazy(move |_| {
390
					let api = client.runtime_api();
391
392
					let status = match try_fr!(api.parachain_status(&id, para_id)) {
						Some(status) => status,
393
						None => return future::Either::Left(future::ok(())),
394
395
					};

396
					let validators = try_fr!(api.validators(&id));
397

398
399
					let targets = compute_targets(
						para_id,
400
						validators.as_slice(),
401
402
403
						try_fr!(api.duty_roster(&id)),
					);

404
405
406
					let context = ApiContext {
						network: validation_network,
						parent_hash: relay_parent,
407
						validators,
408
409
					};

410
					let collation_work = collate(
411
						relay_parent,
412
						para_id,
413
						status,
414
						context,
415
416
						parachain_context,
						key,
417
					).map_ok(move |(collation, outgoing)| {
418
419
420
421
422
423
424
425
426
						network.with_spec(move |spec, ctx| {
							let res = spec.add_local_collation(
								ctx,
								relay_parent,
								targets,
								collation,
								outgoing,
							);

Ashley's avatar
Ashley committed
427
428
							let exit = inner_exit_2.clone();
							tokio::spawn(future::select(res, exit).map(drop));
429
						})
430
431
					});

432
					future::Either::Right(collation_work)
Ashley's avatar
Ashley committed
433
				});
434

435
436
437
438
439
440
441
442
443
444
445
446
447
448
				let deadlined = future::select(
					work,
					futures_timer::Delay::new(COLLATION_TIMEOUT)
				);

				let silenced = deadlined
					.map(|either| {
						if let future::Either::Right(_) = either {
							warn!("Collation failure: timeout");
						}
					});

				let future = future::select(
					silenced,
Gavin Wood's avatar
Gavin Wood committed
449
					inner_exit.clone()
Ashley's avatar
Ashley committed
450
				).map(drop);
451
452
453

				tokio::spawn(future);
				future::ready(())
454
455
			});

Gavin Wood's avatar
Gavin Wood committed
456
457
		let work_and_exit = future::select(work, exit)
			.map(|_| ());
458
459

		Box::new(work_and_exit)
460
461
462
	}
}

463
fn compute_targets(para_id: ParaId, session_keys: &[ValidatorId], roster: DutyRoster) -> HashSet<ValidatorId> {
464
465
466
467
468
469
470
471
472
	use polkadot_primitives::parachain::Chain;

	roster.validator_duty.iter().enumerate()
		.filter(|&(_, c)| c == &Chain::Parachain(para_id))
		.filter_map(|(i, _)| session_keys.get(i))
		.cloned()
		.collect()
}

473
474
/// Run a collator node with the given `RelayChainContext` and `ParachainContext`
/// build by the given `BuildParachainContext` and arguments to the underlying polkadot node.
475
476
477
///
/// Provide a future which resolves when the node should exit.
/// This function blocks until done.
478
pub fn run_collator<P, E>(
479
	build_parachain_context: P,
480
481
	para_id: ParaId,
	exit: E,
482
	key: Arc<CollatorPair>,
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
483
	version: VersionInfo,
484
) -> polkadot_cli::error::Result<()> where
485
486
	P: BuildParachainContext + Send + 'static,
	P::ParachainContext: Send + 'static,
487
	<P::ParachainContext as ParachainContext>::ProduceCandidate: Send + 'static,
Gavin Wood's avatar
Gavin Wood committed
488
	E: futures::Future<Output = ()> + Unpin + Send + Clone + Sync + 'static,
489
{
490
	let node_logic = CollationNode { build_parachain_context, exit, para_id, key };
491
	polkadot_cli::run(node_logic, version)
492
493
}

Gav's avatar
Gav committed
494
495
#[cfg(test)]
mod tests {
496
	use std::collections::HashMap;
497
	use polkadot_primitives::parachain::{TargetedMessage, FeeSchedule};
498
	use keyring::Sr25519Keyring;
Gav's avatar
Gav committed
499
500
	use super::*;

501
502
503
	#[derive(Default, Clone)]
	struct DummyRelayChainContext {
		ingress: HashMap<ParaId, ConsolidatedIngress>
Gav's avatar
Gav committed
504
505
	}

506
	impl RelayChainContext for DummyRelayChainContext {
Gav's avatar
Gav committed
507
		type Error = ();
508
		type FutureEgress = Box<dyn Future<Output=Result<ConsolidatedIngress,()>> + Unpin>;
Gav's avatar
Gav committed
509

510
511
512
		fn unrouted_egress(&self, para_id: ParaId) -> Self::FutureEgress {
			match self.ingress.get(&para_id) {
				Some(ingress) => Box::new(future::ok(ingress.clone())),
513
				None => Box::new(future::pending()),
514
			}
Gav's avatar
Gav committed
515
		}
516
	}
Gav's avatar
Gav committed
517

518
519
520
521
	#[derive(Clone)]
	struct DummyParachainContext;

	impl ParachainContext for DummyParachainContext {
522
		type ProduceCandidate = future::Ready<Result<(BlockData, HeadData, OutgoingMessages), InvalidHead>>;
523

524
		fn produce_candidate<I: IntoIterator<Item=(ParaId, Message)>>(
525
			&mut self,
526
			_relay_parent: Hash,
527
			_status: ParachainStatus,
528
			ingress: I,
529
		) -> Self::ProduceCandidate {
530
			// send messages right back.
531
			future::ok((
532
533
				BlockData(vec![1, 2, 3, 4, 5,]),
				HeadData(vec![9, 9, 9]),
534
535
				OutgoingMessages {
					outgoing_messages: ingress.into_iter().map(|(id, msg)| TargetedMessage {
536
537
538
539
540
						target: id,
						data: msg.0,
					}).collect(),
				}
			))
Gav's avatar
Gav committed
541
542
543
		}
	}

544
	#[test]
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
	fn collates_correct_queue_roots() {
		let mut context = DummyRelayChainContext::default();

		let id = ParaId::from(100);

		let a = ParaId::from(123);
		let b = ParaId::from(456);

		let messages_from_a = vec![
			Message(vec![1, 1, 1]),
			Message(b"helloworld".to_vec()),
		];
		let messages_from_b = vec![
			Message(b"dogglesworth".to_vec()),
			Message(b"buy_1_chili_con_carne_here_is_my_cash".to_vec()),
		];

		let root_a = ::polkadot_validation::message_queue_root(
			messages_from_a.iter().map(|msg| &msg.0)
		);

		let root_b = ::polkadot_validation::message_queue_root(
			messages_from_b.iter().map(|msg| &msg.0)
		);

		context.ingress.insert(id, ConsolidatedIngress(vec![
			(b, messages_from_b),
			(a, messages_from_a),
		]));

575
		let future = collate(
576
			Default::default(),
577
			id,
578
579
580
581
582
583
584
585
			ParachainStatus {
				head_data: HeadData(vec![5]),
				balance: 10,
				fee_schedule: FeeSchedule {
					base: 0,
					per_byte: 1,
				},
			},
586
587
			context.clone(),
			DummyParachainContext,
588
			Arc::new(Sr25519Keyring::Alice.pair().into()),
589
590
591
		);

		let collation = futures::executor::block_on(future).unwrap().0;
592
593

		// ascending order by root.
594
		assert_eq!(collation.info.egress_queue_roots, vec![(a, root_a), (b, root_b)]);
Gav's avatar
Gav committed
595
596
	}
}
597