feat: initialize Kurdistan SDK - independent fork of Polkadot SDK
This commit is contained in:
@@ -0,0 +1,268 @@
|
||||
// Copyright (C) Parity Technologies (UK) Ltd.
|
||||
// This file is part of Pezkuwi.
|
||||
|
||||
// Pezkuwi 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.
|
||||
|
||||
// Pezkuwi 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 Pezkuwi. 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 pezkuwi_primitives::{
|
||||
CandidateReceiptV2 as 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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,343 @@
|
||||
// Copyright (C) Parity Technologies (UK) Ltd.
|
||||
// This file is part of Pezkuwi.
|
||||
|
||||
// Pezkuwi 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.
|
||||
|
||||
// Pezkuwi 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 Pezkuwi. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
use std::collections::{
|
||||
btree_map::{Entry as Bentry, Keys as Bkeys},
|
||||
BTreeMap, BTreeSet,
|
||||
};
|
||||
|
||||
use codec::{Decode, Encode};
|
||||
|
||||
use sp_application_crypto::AppCrypto;
|
||||
use sp_keystore::{Error as KeystoreError, KeystorePtr};
|
||||
|
||||
use pezkuwi_primitives::{
|
||||
CandidateHash, CandidateReceiptV2 as CandidateReceipt, CompactStatement, DisputeStatement,
|
||||
EncodeAs, InvalidDisputeStatementKind, SessionIndex, SigningContext, UncheckedSigned,
|
||||
ValidDisputeStatementKind, ValidatorId, ValidatorIndex, ValidatorSignature,
|
||||
};
|
||||
|
||||
/// `DisputeMessage` and related types.
|
||||
mod message;
|
||||
pub use message::{DisputeMessage, Error as DisputeMessageCheckError, UncheckedDisputeMessage};
|
||||
mod status;
|
||||
pub use status::{dispute_is_inactive, DisputeStatus, Timestamp, ACTIVE_DURATION_SECS};
|
||||
|
||||
/// A checked dispute statement from an associated validator.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SignedDisputeStatement {
|
||||
dispute_statement: DisputeStatement,
|
||||
candidate_hash: CandidateHash,
|
||||
validator_public: ValidatorId,
|
||||
validator_signature: ValidatorSignature,
|
||||
session_index: SessionIndex,
|
||||
}
|
||||
|
||||
/// Errors encountered while signing a dispute statement
|
||||
#[derive(Debug)]
|
||||
pub enum SignedDisputeStatementError {
|
||||
/// Encountered a keystore error while signing
|
||||
KeyStoreError(KeystoreError),
|
||||
/// Could not generate signing payload
|
||||
PayloadError,
|
||||
}
|
||||
|
||||
/// Tracked votes on candidates, for the purposes of dispute resolution.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CandidateVotes {
|
||||
/// The receipt of the candidate itself.
|
||||
pub candidate_receipt: CandidateReceipt,
|
||||
/// Votes of validity, sorted by validator index.
|
||||
pub valid: ValidCandidateVotes,
|
||||
/// Votes of invalidity, sorted by validator index.
|
||||
pub invalid: BTreeMap<ValidatorIndex, (InvalidDisputeStatementKind, ValidatorSignature)>,
|
||||
}
|
||||
|
||||
/// Type alias for retrieving valid votes from `CandidateVotes`
|
||||
pub type ValidVoteData = (ValidatorIndex, (ValidDisputeStatementKind, ValidatorSignature));
|
||||
|
||||
/// Type alias for retrieving invalid votes from `CandidateVotes`
|
||||
pub type InvalidVoteData = (ValidatorIndex, (InvalidDisputeStatementKind, ValidatorSignature));
|
||||
|
||||
impl CandidateVotes {
|
||||
/// Get the set of all validators who have votes in the set, ascending.
|
||||
pub fn voted_indices(&self) -> BTreeSet<ValidatorIndex> {
|
||||
let mut keys: BTreeSet<_> = self.valid.keys().cloned().collect();
|
||||
keys.extend(self.invalid.keys().cloned());
|
||||
keys
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
/// Valid candidate votes.
|
||||
///
|
||||
/// Prefer backing votes over other votes.
|
||||
pub struct ValidCandidateVotes {
|
||||
votes: BTreeMap<ValidatorIndex, (ValidDisputeStatementKind, ValidatorSignature)>,
|
||||
}
|
||||
|
||||
impl ValidCandidateVotes {
|
||||
/// Create new empty `ValidCandidateVotes`
|
||||
pub fn new() -> Self {
|
||||
Self { votes: BTreeMap::new() }
|
||||
}
|
||||
/// Insert a vote, replacing any already existing vote.
|
||||
///
|
||||
/// Except, for backing votes: Backing votes are always kept, and will never get overridden.
|
||||
/// Import of other king of `valid` votes, will be ignored if a backing vote is already
|
||||
/// present. Any already existing `valid` vote, will be overridden by any given backing vote.
|
||||
///
|
||||
/// Returns: true, if the insert had any effect.
|
||||
pub fn insert_vote(
|
||||
&mut self,
|
||||
validator_index: ValidatorIndex,
|
||||
kind: ValidDisputeStatementKind,
|
||||
sig: ValidatorSignature,
|
||||
) -> bool {
|
||||
match self.votes.entry(validator_index) {
|
||||
Bentry::Vacant(vacant) => {
|
||||
vacant.insert((kind, sig));
|
||||
true
|
||||
},
|
||||
Bentry::Occupied(mut occupied) => match occupied.get().0 {
|
||||
ValidDisputeStatementKind::BackingValid(_) |
|
||||
ValidDisputeStatementKind::BackingSeconded(_) => false,
|
||||
ValidDisputeStatementKind::Explicit |
|
||||
ValidDisputeStatementKind::ApprovalChecking |
|
||||
ValidDisputeStatementKind::ApprovalCheckingMultipleCandidates(_) => {
|
||||
occupied.insert((kind.clone(), sig));
|
||||
kind != occupied.get().0
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Retain any votes that match the given criteria.
|
||||
pub fn retain<F>(&mut self, f: F)
|
||||
where
|
||||
F: FnMut(&ValidatorIndex, &mut (ValidDisputeStatementKind, ValidatorSignature)) -> bool,
|
||||
{
|
||||
self.votes.retain(f)
|
||||
}
|
||||
|
||||
/// Get all the validator indices we have votes for.
|
||||
pub fn keys(
|
||||
&self,
|
||||
) -> Bkeys<'_, ValidatorIndex, (ValidDisputeStatementKind, ValidatorSignature)> {
|
||||
self.votes.keys()
|
||||
}
|
||||
|
||||
/// Get read only direct access to underlying map.
|
||||
pub fn raw(
|
||||
&self,
|
||||
) -> &BTreeMap<ValidatorIndex, (ValidDisputeStatementKind, ValidatorSignature)> {
|
||||
&self.votes
|
||||
}
|
||||
}
|
||||
|
||||
impl FromIterator<(ValidatorIndex, (ValidDisputeStatementKind, ValidatorSignature))>
|
||||
for ValidCandidateVotes
|
||||
{
|
||||
fn from_iter<T>(iter: T) -> Self
|
||||
where
|
||||
T: IntoIterator<Item = (ValidatorIndex, (ValidDisputeStatementKind, ValidatorSignature))>,
|
||||
{
|
||||
Self { votes: BTreeMap::from_iter(iter) }
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ValidCandidateVotes>
|
||||
for BTreeMap<ValidatorIndex, (ValidDisputeStatementKind, ValidatorSignature)>
|
||||
{
|
||||
fn from(wrapped: ValidCandidateVotes) -> Self {
|
||||
wrapped.votes
|
||||
}
|
||||
}
|
||||
impl IntoIterator for ValidCandidateVotes {
|
||||
type Item = (ValidatorIndex, (ValidDisputeStatementKind, ValidatorSignature));
|
||||
type IntoIter = <BTreeMap<ValidatorIndex, (ValidDisputeStatementKind, ValidatorSignature)> as IntoIterator>::IntoIter;
|
||||
|
||||
fn into_iter(self) -> Self::IntoIter {
|
||||
self.votes.into_iter()
|
||||
}
|
||||
}
|
||||
|
||||
impl SignedDisputeStatement {
|
||||
/// Create a new `SignedDisputeStatement` from information
|
||||
/// that is available on-chain, and hence already can be trusted.
|
||||
///
|
||||
/// Attention: Not to be used other than with guaranteed fetches.
|
||||
pub fn new_unchecked_from_trusted_source(
|
||||
dispute_statement: DisputeStatement,
|
||||
candidate_hash: CandidateHash,
|
||||
session_index: SessionIndex,
|
||||
validator_public: ValidatorId,
|
||||
validator_signature: ValidatorSignature,
|
||||
) -> Self {
|
||||
SignedDisputeStatement {
|
||||
dispute_statement,
|
||||
candidate_hash,
|
||||
validator_public,
|
||||
validator_signature,
|
||||
session_index,
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a new `SignedDisputeStatement`, which is only possible by checking the signature.
|
||||
pub fn new_checked(
|
||||
dispute_statement: DisputeStatement,
|
||||
candidate_hash: CandidateHash,
|
||||
session_index: SessionIndex,
|
||||
validator_public: ValidatorId,
|
||||
validator_signature: ValidatorSignature,
|
||||
) -> Result<Self, ()> {
|
||||
dispute_statement
|
||||
.check_signature(&validator_public, candidate_hash, session_index, &validator_signature)
|
||||
.map(|_| SignedDisputeStatement {
|
||||
dispute_statement,
|
||||
candidate_hash,
|
||||
validator_public,
|
||||
validator_signature,
|
||||
session_index,
|
||||
})
|
||||
}
|
||||
|
||||
/// Sign this statement with the given keystore and key. Pass `valid = true` to
|
||||
/// indicate validity of the candidate, and `valid = false` to indicate invalidity.
|
||||
pub fn sign_explicit(
|
||||
keystore: &KeystorePtr,
|
||||
valid: bool,
|
||||
candidate_hash: CandidateHash,
|
||||
session_index: SessionIndex,
|
||||
validator_public: ValidatorId,
|
||||
) -> Result<Option<Self>, SignedDisputeStatementError> {
|
||||
let dispute_statement = if valid {
|
||||
DisputeStatement::Valid(ValidDisputeStatementKind::Explicit)
|
||||
} else {
|
||||
DisputeStatement::Invalid(InvalidDisputeStatementKind::Explicit)
|
||||
};
|
||||
|
||||
let data = dispute_statement
|
||||
.payload_data(candidate_hash, session_index)
|
||||
.map_err(|_| SignedDisputeStatementError::PayloadError)?;
|
||||
let signature = keystore
|
||||
.sr25519_sign(ValidatorId::ID, validator_public.as_ref(), &data)
|
||||
.map_err(SignedDisputeStatementError::KeyStoreError)?
|
||||
.map(|sig| Self {
|
||||
dispute_statement,
|
||||
candidate_hash,
|
||||
validator_public,
|
||||
validator_signature: sig.into(),
|
||||
session_index,
|
||||
});
|
||||
Ok(signature)
|
||||
}
|
||||
|
||||
/// Access the underlying dispute statement
|
||||
pub fn statement(&self) -> &DisputeStatement {
|
||||
&self.dispute_statement
|
||||
}
|
||||
|
||||
/// Access the underlying candidate hash.
|
||||
pub fn candidate_hash(&self) -> &CandidateHash {
|
||||
&self.candidate_hash
|
||||
}
|
||||
|
||||
/// Access the underlying validator public key.
|
||||
pub fn validator_public(&self) -> &ValidatorId {
|
||||
&self.validator_public
|
||||
}
|
||||
|
||||
/// Access the underlying validator signature.
|
||||
pub fn validator_signature(&self) -> &ValidatorSignature {
|
||||
&self.validator_signature
|
||||
}
|
||||
|
||||
/// Consume self to return the signature.
|
||||
pub fn into_validator_signature(self) -> ValidatorSignature {
|
||||
self.validator_signature
|
||||
}
|
||||
|
||||
/// Access the underlying session index.
|
||||
pub fn session_index(&self) -> SessionIndex {
|
||||
self.session_index
|
||||
}
|
||||
|
||||
/// Convert a unchecked backing statement to a [`SignedDisputeStatement`]
|
||||
///
|
||||
/// As the unchecked backing statement contains only the validator index and
|
||||
/// not the validator public key, the public key must be passed as well,
|
||||
/// along with the signing context.
|
||||
///
|
||||
/// This does signature checks again with the data provided.
|
||||
pub fn from_backing_statement<T>(
|
||||
backing_statement: &UncheckedSigned<T, CompactStatement>,
|
||||
signing_context: SigningContext,
|
||||
validator_public: ValidatorId,
|
||||
) -> Result<Self, ()>
|
||||
where
|
||||
for<'a> &'a T: Into<CompactStatement>,
|
||||
T: EncodeAs<CompactStatement>,
|
||||
{
|
||||
let (statement_kind, candidate_hash) = match backing_statement.unchecked_payload().into() {
|
||||
CompactStatement::Seconded(candidate_hash) => (
|
||||
ValidDisputeStatementKind::BackingSeconded(signing_context.parent_hash),
|
||||
candidate_hash,
|
||||
),
|
||||
CompactStatement::Valid(candidate_hash) => (
|
||||
ValidDisputeStatementKind::BackingValid(signing_context.parent_hash),
|
||||
candidate_hash,
|
||||
),
|
||||
};
|
||||
|
||||
let dispute_statement = DisputeStatement::Valid(statement_kind);
|
||||
Self::new_checked(
|
||||
dispute_statement,
|
||||
candidate_hash,
|
||||
signing_context.session_index,
|
||||
validator_public,
|
||||
backing_statement.unchecked_signature().clone(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Any invalid vote (currently only explicit).
|
||||
#[derive(Clone, Encode, Decode, Debug)]
|
||||
pub struct InvalidDisputeVote {
|
||||
/// The voting validator index.
|
||||
pub validator_index: ValidatorIndex,
|
||||
|
||||
/// The validator signature, that can be verified when constructing a
|
||||
/// `SignedDisputeStatement`.
|
||||
pub signature: ValidatorSignature,
|
||||
|
||||
/// Kind of dispute statement.
|
||||
pub kind: InvalidDisputeStatementKind,
|
||||
}
|
||||
|
||||
/// Any valid vote (backing, approval, explicit).
|
||||
#[derive(Clone, Encode, Decode, Debug)]
|
||||
pub struct ValidDisputeVote {
|
||||
/// The voting validator index.
|
||||
pub validator_index: ValidatorIndex,
|
||||
|
||||
/// The validator signature, that can be verified when constructing a
|
||||
/// `SignedDisputeStatement`.
|
||||
pub signature: ValidatorSignature,
|
||||
|
||||
/// Kind of dispute statement.
|
||||
pub kind: ValidDisputeStatementKind,
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
// Copyright (C) Parity Technologies (UK) Ltd.
|
||||
// This file is part of Pezkuwi.
|
||||
|
||||
// Pezkuwi 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.
|
||||
|
||||
// Pezkuwi 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 Pezkuwi. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
use codec::{Decode, Encode};
|
||||
|
||||
/// Timestamp based on the 1 Jan 1970 UNIX base, which is persistent across node restarts and OS
|
||||
/// reboots.
|
||||
pub type Timestamp = u64;
|
||||
|
||||
/// The status of dispute.
|
||||
///
|
||||
/// As managed by the dispute coordinator.
|
||||
///
|
||||
/// NOTE: This status is persisted to the database, any changes have to be versioned and a db
|
||||
/// migration will be needed.
|
||||
#[derive(Debug, Clone, Copy, Encode, Decode, PartialEq)]
|
||||
pub enum DisputeStatus {
|
||||
/// The dispute is active and unconcluded.
|
||||
#[codec(index = 0)]
|
||||
Active,
|
||||
/// The dispute has been concluded in favor of the candidate
|
||||
/// since the given timestamp.
|
||||
#[codec(index = 1)]
|
||||
ConcludedFor(Timestamp),
|
||||
/// The dispute has been concluded against the candidate
|
||||
/// since the given timestamp.
|
||||
///
|
||||
/// This takes precedence over `ConcludedFor` in the case that
|
||||
/// both are true, which is impossible unless a large amount of
|
||||
/// validators are participating on both sides.
|
||||
#[codec(index = 2)]
|
||||
ConcludedAgainst(Timestamp),
|
||||
/// Dispute has been confirmed (more than `byzantine_threshold` have already participated/ or
|
||||
/// we have seen the candidate included already/participated successfully ourselves).
|
||||
#[codec(index = 3)]
|
||||
Confirmed,
|
||||
}
|
||||
|
||||
impl DisputeStatus {
|
||||
/// Initialize the status to the active state.
|
||||
pub fn active() -> DisputeStatus {
|
||||
DisputeStatus::Active
|
||||
}
|
||||
|
||||
/// Move status to confirmed status, if not yet concluded/confirmed already.
|
||||
pub fn confirm(self) -> DisputeStatus {
|
||||
match self {
|
||||
DisputeStatus::Active => DisputeStatus::Confirmed,
|
||||
DisputeStatus::Confirmed => DisputeStatus::Confirmed,
|
||||
DisputeStatus::ConcludedFor(_) | DisputeStatus::ConcludedAgainst(_) => self,
|
||||
}
|
||||
}
|
||||
|
||||
/// Check whether the dispute is not a spam dispute.
|
||||
pub fn is_confirmed_concluded(&self) -> bool {
|
||||
match self {
|
||||
&DisputeStatus::Confirmed |
|
||||
&DisputeStatus::ConcludedFor(_) |
|
||||
DisputeStatus::ConcludedAgainst(_) => true,
|
||||
&DisputeStatus::Active => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Concluded valid?
|
||||
pub fn has_concluded_for(&self) -> bool {
|
||||
match self {
|
||||
&DisputeStatus::ConcludedFor(_) => true,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
/// Concluded invalid?
|
||||
pub fn has_concluded_against(&self) -> bool {
|
||||
match self {
|
||||
&DisputeStatus::ConcludedAgainst(_) => true,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Transition the status to a new status after observing the dispute has concluded for the
|
||||
/// candidate. This may be a no-op if the status was already concluded.
|
||||
pub fn conclude_for(self, now: Timestamp) -> DisputeStatus {
|
||||
match self {
|
||||
DisputeStatus::Active | DisputeStatus::Confirmed => DisputeStatus::ConcludedFor(now),
|
||||
DisputeStatus::ConcludedFor(at) => DisputeStatus::ConcludedFor(std::cmp::min(at, now)),
|
||||
against => against,
|
||||
}
|
||||
}
|
||||
|
||||
/// Transition the status to a new status after observing the dispute has concluded against the
|
||||
/// candidate. This may be a no-op if the status was already concluded.
|
||||
pub fn conclude_against(self, now: Timestamp) -> DisputeStatus {
|
||||
match self {
|
||||
DisputeStatus::Active | DisputeStatus::Confirmed =>
|
||||
DisputeStatus::ConcludedAgainst(now),
|
||||
DisputeStatus::ConcludedFor(at) =>
|
||||
DisputeStatus::ConcludedAgainst(std::cmp::min(at, now)),
|
||||
DisputeStatus::ConcludedAgainst(at) =>
|
||||
DisputeStatus::ConcludedAgainst(std::cmp::min(at, now)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the disputed candidate is possibly invalid.
|
||||
pub fn is_possibly_invalid(&self) -> bool {
|
||||
match self {
|
||||
DisputeStatus::Active |
|
||||
DisputeStatus::Confirmed |
|
||||
DisputeStatus::ConcludedAgainst(_) => true,
|
||||
DisputeStatus::ConcludedFor(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Yields the timestamp this dispute concluded at, if any.
|
||||
pub fn concluded_at(&self) -> Option<Timestamp> {
|
||||
match self {
|
||||
DisputeStatus::Active | DisputeStatus::Confirmed => None,
|
||||
DisputeStatus::ConcludedFor(at) | DisputeStatus::ConcludedAgainst(at) => Some(*at),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The choice here is fairly arbitrary. But any dispute that concluded more than a few minutes ago
|
||||
/// is not worth considering anymore. Changing this value has little to no bearing on consensus,
|
||||
/// and really only affects the work that the node might do on startup during periods of many
|
||||
/// disputes.
|
||||
pub const ACTIVE_DURATION_SECS: Timestamp = 180;
|
||||
|
||||
/// Returns true if the dispute has concluded for longer than [`ACTIVE_DURATION_SECS`].
|
||||
pub fn dispute_is_inactive(status: &DisputeStatus, now: &Timestamp) -> bool {
|
||||
let at = status.concluded_at();
|
||||
|
||||
at.is_some() && at.unwrap() + ACTIVE_DURATION_SECS < *now
|
||||
}
|
||||
Reference in New Issue
Block a user