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
// Copyright (C) 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/>.

//! `DisputeMessage` and associated types.
//!
//! A `DisputeMessage` is a message that indicates a node participating in a dispute and is used
//! for interfacing with `DisputeDistribution` to send out our vote in a spam detectable way.

use thiserror::Error;

use codec::{Decode, Encode};

use super::{InvalidDisputeVote, SignedDisputeStatement, ValidDisputeVote};
use polkadot_primitives::{
	CandidateReceipt, DisputeStatement, SessionIndex, SessionInfo, ValidatorIndex,
};

/// A dispute initiating/participating message that have been built from signed
/// statements.
///
/// And most likely has been constructed correctly. This is used with
/// `DisputeDistributionMessage::SendDispute` for sending out votes.
///
/// NOTE: This is sent over the wire, any changes are a change in protocol and need to be
/// versioned.
#[derive(Debug, Clone)]
pub struct DisputeMessage(UncheckedDisputeMessage);

/// A `DisputeMessage` where signatures of statements have not yet been checked.
#[derive(Clone, Encode, Decode, Debug)]
pub struct UncheckedDisputeMessage {
	/// The candidate being disputed.
	pub candidate_receipt: CandidateReceipt,

	/// The session the candidate appears in.
	pub session_index: SessionIndex,

	/// The invalid vote data that makes up this dispute.
	pub invalid_vote: InvalidDisputeVote,

	/// The valid vote that makes this dispute request valid.
	pub valid_vote: ValidDisputeVote,
}

/// Things that can go wrong when constructing a `DisputeMessage`.
#[derive(Error, Debug)]
pub enum Error {
	/// The statements concerned different candidates.
	#[error("Candidate hashes of the two votes did not match up")]
	CandidateHashMismatch,

	/// The statements concerned different sessions.
	#[error("Session indices of the two votes did not match up")]
	SessionIndexMismatch,

	/// The valid statement validator key did not correspond to passed in `SessionInfo`.
	#[error("Valid statement validator key did not match session information")]
	InvalidValidKey,

	/// The invalid statement validator key did not correspond to passed in `SessionInfo`.
	#[error("Invalid statement validator key did not match session information")]
	InvalidInvalidKey,

	/// Provided receipt had different hash than the `CandidateHash` in the signed statements.
	#[error("Hash of candidate receipt did not match provided hash")]
	InvalidCandidateReceipt,

	/// Valid statement should have `ValidDisputeStatementKind`.
	#[error("Valid statement has kind `invalid`")]
	ValidStatementHasInvalidKind,

	/// Invalid statement should have `InvalidDisputeStatementKind`.
	#[error("Invalid statement has kind `valid`")]
	InvalidStatementHasValidKind,

	/// Provided index could not be found in `SessionInfo`.
	#[error("The valid statement had an invalid validator index")]
	ValidStatementInvalidValidatorIndex,

	/// Provided index could not be found in `SessionInfo`.
	#[error("The invalid statement had an invalid validator index")]
	InvalidStatementInvalidValidatorIndex,
}

impl DisputeMessage {
	/// Build a `SignedDisputeMessage` and check what can be checked.
	///
	/// This function checks that:
	///
	/// - both statements concern the same candidate
	/// - both statements concern the same session
	/// - the invalid statement is indeed an invalid one
	/// - the valid statement is indeed a valid one
	/// - The passed `CandidateReceipt` has the correct hash (as signed in the statements).
	/// - the given validator indices match with the given `ValidatorId`s in the statements, given a
	///   `SessionInfo`.
	///
	/// We don't check whether the given `SessionInfo` matches the `SessionIndex` in the
	/// statements, because we can't without doing a runtime query. Nevertheless this smart
	/// constructor gives relative strong guarantees that the resulting `SignedDisputeStatement` is
	/// valid and good.  Even the passed `SessionInfo` is most likely right if this function
	/// returns `Some`, because otherwise the passed `ValidatorId`s in the `SessionInfo` at
	/// their given index would very likely not match the `ValidatorId`s in the statements.
	///
	/// So in summary, this smart constructor should be smart enough to prevent from almost all
	/// programming errors that one could realistically make here.
	pub fn from_signed_statements(
		valid_statement: SignedDisputeStatement,
		valid_index: ValidatorIndex,
		invalid_statement: SignedDisputeStatement,
		invalid_index: ValidatorIndex,
		candidate_receipt: CandidateReceipt,
		session_info: &SessionInfo,
	) -> Result<Self, Error> {
		let candidate_hash = *valid_statement.candidate_hash();
		// Check statements concern same candidate:
		if candidate_hash != *invalid_statement.candidate_hash() {
			return Err(Error::CandidateHashMismatch)
		}

		let session_index = valid_statement.session_index();
		if session_index != invalid_statement.session_index() {
			return Err(Error::SessionIndexMismatch)
		}

		let valid_id = session_info
			.validators
			.get(valid_index)
			.ok_or(Error::ValidStatementInvalidValidatorIndex)?;
		let invalid_id = session_info
			.validators
			.get(invalid_index)
			.ok_or(Error::InvalidStatementInvalidValidatorIndex)?;

		if valid_id != valid_statement.validator_public() {
			return Err(Error::InvalidValidKey)
		}

		if invalid_id != invalid_statement.validator_public() {
			return Err(Error::InvalidInvalidKey)
		}

		if candidate_receipt.hash() != candidate_hash {
			return Err(Error::InvalidCandidateReceipt)
		}

		let valid_kind = match valid_statement.statement() {
			DisputeStatement::Valid(v) => v,
			_ => return Err(Error::ValidStatementHasInvalidKind),
		};

		let invalid_kind = match invalid_statement.statement() {
			DisputeStatement::Invalid(v) => v,
			_ => return Err(Error::InvalidStatementHasValidKind),
		};

		let valid_vote = ValidDisputeVote {
			validator_index: valid_index,
			signature: valid_statement.validator_signature().clone(),
			kind: valid_kind.clone(),
		};

		let invalid_vote = InvalidDisputeVote {
			validator_index: invalid_index,
			signature: invalid_statement.validator_signature().clone(),
			kind: *invalid_kind,
		};

		Ok(DisputeMessage(UncheckedDisputeMessage {
			candidate_receipt,
			session_index,
			valid_vote,
			invalid_vote,
		}))
	}

	/// Read only access to the candidate receipt.
	pub fn candidate_receipt(&self) -> &CandidateReceipt {
		&self.0.candidate_receipt
	}

	/// Read only access to the `SessionIndex`.
	pub fn session_index(&self) -> SessionIndex {
		self.0.session_index
	}

	/// Read only access to the invalid vote.
	pub fn invalid_vote(&self) -> &InvalidDisputeVote {
		&self.0.invalid_vote
	}

	/// Read only access to the valid vote.
	pub fn valid_vote(&self) -> &ValidDisputeVote {
		&self.0.valid_vote
	}
}

impl UncheckedDisputeMessage {
	/// Try to recover the two signed dispute votes from an `UncheckedDisputeMessage`.
	pub fn try_into_signed_votes(
		self,
		session_info: &SessionInfo,
	) -> Result<
		(
			CandidateReceipt,
			(SignedDisputeStatement, ValidatorIndex),
			(SignedDisputeStatement, ValidatorIndex),
		),
		(),
	> {
		let Self { candidate_receipt, session_index, valid_vote, invalid_vote } = self;
		let candidate_hash = candidate_receipt.hash();

		let vote_valid = {
			let ValidDisputeVote { validator_index, signature, kind } = valid_vote;
			let validator_public = session_info.validators.get(validator_index).ok_or(())?.clone();

			(
				SignedDisputeStatement::new_checked(
					DisputeStatement::Valid(kind),
					candidate_hash,
					session_index,
					validator_public,
					signature,
				)?,
				validator_index,
			)
		};

		let vote_invalid = {
			let InvalidDisputeVote { validator_index, signature, kind } = invalid_vote;
			let validator_public = session_info.validators.get(validator_index).ok_or(())?.clone();

			(
				SignedDisputeStatement::new_checked(
					DisputeStatement::Invalid(kind),
					candidate_hash,
					session_index,
					validator_public,
					signature,
				)?,
				validator_index,
			)
		};

		Ok((candidate_receipt, vote_valid, vote_invalid))
	}
}

impl From<DisputeMessage> for UncheckedDisputeMessage {
	fn from(message: DisputeMessage) -> Self {
		message.0
	}
}