attestation.rs 11.1 KB
Newer Older
Shawn Tabrizi's avatar
Shawn Tabrizi committed
1
// Copyright 2019-2020 Parity Technologies (UK) Ltd.
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
// 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/>.

//! Gossip messages and structures for dealing with attestations (statements of
//! validity of invalidity on parachain candidates).
//!
//! This follows the same principles as other gossip modules (see parent
//! documentation for more details) by being aware of our current chain
//! heads and accepting only information relative to them. Attestations are localized to
//! relay chain head, so this is easily doable.
//!
//! This module also provides a filter, so we can only broadcast messages to
//! peers that are relevant to chain heads they have advertised.
//!
//! Furthermore, since attestations are bottlenecked by the `Candidate` statement,
//! we only accept attestations which are themselves `Candidate` messages, or reference
//! a `Candidate` we are aware of. Otherwise, it is possible we could be forced to
//! consider an infinite amount of attestations produced by a misbehaving validator.

33
use sc_network_gossip::{ValidationResult as GossipValidationResult};
34
use sc_network::ReputationChange;
35
use polkadot_validation::GenericStatement;
asynchronous rob's avatar
asynchronous rob committed
36
use polkadot_primitives::v0::Hash;
37

asynchronous rob's avatar
asynchronous rob committed
38
use std::collections::HashMap;
39
40
41

use log::warn;

42
43
44
use super::{
	cost, benefit, attestation_topic, MAX_CHAIN_HEADS, LeavesVec,
	ChainContext, Known, MessageValidationData, GossipStatement,
45
};
46

asynchronous rob's avatar
asynchronous rob committed
47
48
49
50
51
52
53
/// Meta-data that we keep about a candidate in the `Knowledge`.
#[derive(Debug, Clone)]
pub(super) struct CandidateMeta {
	/// The hash of the pov-block data.
	pub(super) pov_block_hash: Hash,
}

54
55
56
// knowledge about attestations on a single parent-hash.
#[derive(Default)]
pub(super) struct Knowledge {
asynchronous rob's avatar
asynchronous rob committed
57
	candidates: HashMap<Hash, CandidateMeta>,
58
59
60
61
62
}

impl Knowledge {
	// whether the peer is aware of a candidate with given hash.
	fn is_aware_of(&self, candidate_hash: &Hash) -> bool {
asynchronous rob's avatar
asynchronous rob committed
63
64
65
66
67
68
		self.candidates.contains_key(candidate_hash)
	}

	// Get candidate meta data for a candidate by hash.
	fn candidate_meta(&self, candidate_hash: &Hash) -> Option<&CandidateMeta> {
		self.candidates.get(candidate_hash)
69
70
71
72
	}

	// note that the peer is aware of a candidate with given hash. this should
	// be done after observing an incoming candidate message via gossip.
asynchronous rob's avatar
asynchronous rob committed
73
74
	fn note_aware(&mut self, candidate_hash: Hash, candidate_meta: CandidateMeta) {
		self.candidates.insert(candidate_hash, candidate_meta);
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
	}
}

#[derive(Default)]
pub(super) struct PeerData {
	live: HashMap<Hash, Knowledge>,
}

impl PeerData {
	/// Update leaves, returning a list of which leaves are new.
	pub(super) fn update_leaves(&mut self, leaves: &LeavesVec) -> LeavesVec {
		let mut new = LeavesVec::new();
		self.live.retain(|k, _| leaves.contains(k));
		for &leaf in leaves {
			self.live.entry(leaf).or_insert_with(|| {
				new.push(leaf);
				Default::default()
			});
		}

		new
	}

	#[cfg(test)]
asynchronous rob's avatar
asynchronous rob committed
99
100
101
102
103
104
	pub(super) fn note_aware_under_leaf(
		&mut self,
		relay_chain_leaf: &Hash,
		candidate_hash: Hash,
		meta: CandidateMeta,
	) {
105
		if let Some(knowledge) = self.live.get_mut(relay_chain_leaf) {
asynchronous rob's avatar
asynchronous rob committed
106
			knowledge.note_aware(candidate_hash, meta);
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
		}
	}

	pub(super) fn knowledge_at_mut(&mut self, parent_hash: &Hash) -> Option<&mut Knowledge> {
		self.live.get_mut(parent_hash)
	}
}

/// An impartial view of what topics and data are valid based on attestation session data.
pub(super) struct View {
	leaf_work: Vec<(Hash, LeafView)>, // hashes of the best DAG-leaves paired with validation data.
	topics: HashMap<Hash, Hash>, // maps topic hashes to block hashes.
}

impl Default for View {
	fn default() -> Self {
		View {
			leaf_work: Vec::with_capacity(MAX_CHAIN_HEADS),
			topics: Default::default(),
		}
	}
}

impl View {
	fn leaf_view(&self, relay_chain_leaf: &Hash) -> Option<&LeafView> {
		self.leaf_work.iter()
			.find_map(|&(ref h, ref leaf)| if h == relay_chain_leaf { Some(leaf) } else { None } )
	}

	fn leaf_view_mut(&mut self, relay_chain_leaf: &Hash) -> Option<&mut LeafView> {
		self.leaf_work.iter_mut()
			.find_map(|&mut (ref h, ref mut leaf)| if h == relay_chain_leaf { Some(leaf) } else { None } )
	}

	/// Get our leaves-set. Guaranteed to have length <= MAX_CHAIN_HEADS.
	pub(super) fn neighbor_info<'a>(&'a self) -> impl Iterator<Item=Hash> + 'a + Clone {
		self.leaf_work.iter().take(MAX_CHAIN_HEADS).map(|(p, _)| p.clone())
	}

	/// Note new leaf in our local view and validation data necessary to check signatures
	/// of statements issued under this leaf.
	///
	/// This will be pruned later on a call to `prune_old_leaves`, when this leaf
	/// is not a leaf anymore.
151
152
153
154
155
	pub(super) fn new_local_leaf(
		&mut self,
		validation_data: MessageValidationData,
	) {
		let relay_chain_leaf = validation_data.signing_context.parent_hash.clone();
156
		self.leaf_work.push((
157
			validation_data.signing_context.parent_hash.clone(),
158
159
160
161
162
163
			LeafView {
				validation_data,
				knowledge: Default::default(),
			},
		));
		self.topics.insert(attestation_topic(relay_chain_leaf), relay_chain_leaf);
asynchronous rob's avatar
asynchronous rob committed
164
		self.topics.insert(super::pov_block_topic(relay_chain_leaf), relay_chain_leaf);
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
	}

	/// Prune old leaf-work that fails the leaf predicate.
	pub(super) fn prune_old_leaves<F: Fn(&Hash) -> bool>(&mut self, is_leaf: F) {
		let leaf_work = &mut self.leaf_work;
		leaf_work.retain(|&(ref relay_chain_leaf, _)| is_leaf(relay_chain_leaf));
		self.topics.retain(|_, v| leaf_work.iter().find(|(p, _)| p == v).is_some());
	}

	/// Whether a message topic is considered live relative to our view. non-live
	/// topics do not pertain to our perceived leaves, and are uninteresting to us.
	pub(super) fn is_topic_live(&self, topic: &Hash) -> bool {
		self.topics.contains_key(topic)
	}

	/// The relay-chain block hash corresponding to a topic.
	pub(super) fn topic_block(&self, topic: &Hash) -> Option<&Hash> {
		self.topics.get(topic)
	}

asynchronous rob's avatar
asynchronous rob committed
185
186
187
188
189
190
191
192
193
194
195
	#[cfg(test)]
	pub(super) fn note_aware_under_leaf(
		&mut self,
		relay_chain_leaf: &Hash,
		candidate_hash: Hash,
		meta: CandidateMeta,
	) {
		if let Some(view) = self.leaf_view_mut(relay_chain_leaf) {
			view.knowledge.note_aware(candidate_hash, meta);
		}
	}
196
197
198
199
200
201
202
203

	/// Validate the signature on an attestation statement of some kind. Should be done before
	/// any repropagation of that statement.
	pub(super) fn validate_statement_signature<C: ChainContext + ?Sized>(
		&mut self,
		message: GossipStatement,
		chain: &C,
	)
204
		-> (GossipValidationResult<Hash>, ReputationChange)
205
206
207
208
209
210
211
212
213
214
215
216
217
	{
		// message must reference one of our chain heads and
		// if message is not a `Candidate` we should have the candidate available
		// in `attestation_view`.
		match self.leaf_view(&message.relay_chain_leaf) {
			None => {
				let cost = match chain.is_known(&message.relay_chain_leaf) {
					Some(Known::Leaf) => {
						warn!(
							target: "network",
							"Leaf block {} not considered live for attestation",
							message.relay_chain_leaf,
						);
218
						cost::NONE
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
					}
					Some(Known::Old) => cost::PAST_MESSAGE,
					_ => cost::FUTURE_MESSAGE,
				};

				(GossipValidationResult::Discard, cost)
			}
			Some(view) => {
				// first check that we are capable of receiving this message
				// in a DoS-proof manner.
				let benefit = match message.signed_statement.statement {
					GenericStatement::Candidate(_) => benefit::NEW_CANDIDATE,
					GenericStatement::Valid(ref h) | GenericStatement::Invalid(ref h) => {
						if !view.knowledge.is_aware_of(h) {
							let cost = cost::ATTESTATION_NO_CANDIDATE;
							return (GossipValidationResult::Discard, cost);
						}

						benefit::NEW_ATTESTATION
					}
				};

				// validate signature.
				let res = view.validation_data.check_statement(
					&message.signed_statement,
				);

				match res {
					Ok(()) => {
						let topic = attestation_topic(message.relay_chain_leaf);
						(GossipValidationResult::ProcessAndKeep(topic), benefit)
					}
					Err(()) => (GossipValidationResult::Discard, cost::BAD_SIGNATURE),
				}
			}
		}
	}

asynchronous rob's avatar
asynchronous rob committed
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
	/// Validate a pov-block message.
	pub(super) fn validate_pov_block_message<C: ChainContext + ?Sized>(
		&mut self,
		message: &super::GossipPoVBlock,
		chain: &C,
	)
		-> (GossipValidationResult<Hash>, ReputationChange)
	{
		match self.leaf_view(&message.relay_chain_leaf) {
			None => {
				let cost = match chain.is_known(&message.relay_chain_leaf) {
					Some(Known::Leaf) => {
						warn!(
							target: "network",
							"Leaf block {} not considered live for attestation",
							message.relay_chain_leaf,
						);
						cost::NONE
					}
					Some(Known::Old) => cost::POV_BLOCK_UNWANTED,
					_ => cost::FUTURE_MESSAGE,
				};

				(GossipValidationResult::Discard, cost)
			}
			Some(view) => {
				// we only accept pov-blocks for candidates that we have
				// and consider active.
				match view.knowledge.candidate_meta(&message.candidate_hash) {
					None => (GossipValidationResult::Discard, cost::POV_BLOCK_UNWANTED),
					Some(meta) => {
						// check that the pov-block hash is actually correct.
						if meta.pov_block_hash == message.pov_block.hash() {
							let topic = super::pov_block_topic(message.relay_chain_leaf);
							(GossipValidationResult::ProcessAndKeep(topic), benefit::NEW_POV_BLOCK)
						} else {
							(GossipValidationResult::Discard, cost::POV_BLOCK_BAD_DATA)
						}
					}
				}
			}
		}
	}

301
302
303
304
305
306
307
308
	/// whether it's allowed to send a statement to a peer with given knowledge
	/// about the relay parent the statement refers to.
	pub(super) fn statement_allowed(
		&mut self,
		statement: &GossipStatement,
		peer_knowledge: &mut Knowledge,
	) -> bool {
		let signed = &statement.signed_statement;
asynchronous rob's avatar
asynchronous rob committed
309
		let relay_chain_leaf = &statement.relay_chain_leaf;
310
311
312
313
314
315
316
317
318
319
320

		match signed.statement {
			GenericStatement::Valid(ref h) | GenericStatement::Invalid(ref h) => {
				// `valid` and `invalid` statements can only be propagated after
				// a candidate message is known by that peer.
				peer_knowledge.is_aware_of(h)
			}
			GenericStatement::Candidate(ref c) => {
				// if we are sending a `Candidate` message we should make sure that
				// attestation_view and their_view reflects that we know about the candidate.
				let hash = c.hash();
asynchronous rob's avatar
asynchronous rob committed
321
322
				let meta = CandidateMeta { pov_block_hash: c.pov_block_hash };
				peer_knowledge.note_aware(hash, meta.clone());
323
				if let Some(attestation_view) = self.leaf_view_mut(&relay_chain_leaf) {
asynchronous rob's avatar
asynchronous rob committed
324
					attestation_view.knowledge.note_aware(hash, meta);
325
326
327
328
329
330
331
332
				}

				// at this point, the peer hasn't seen the message or the candidate
				// and has knowledge of the relevant relay-chain parent.
				true
			}
		}
	}
asynchronous rob's avatar
asynchronous rob committed
333
334
335
336
337
338
339
340
341

	/// whether it's allowed to send a pov-block to a peer.
	pub(super) fn pov_block_allowed(
		&mut self,
		statement: &super::GossipPoVBlock,
		peer_knowledge: &mut Knowledge,
	) -> bool {
		peer_knowledge.is_aware_of(&statement.candidate_hash)
	}
342
343
344
345
346
347
}

struct LeafView {
	validation_data: MessageValidationData,
	knowledge: Knowledge,
}