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
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
// This file is part of Parity Bridges Common.

// Parity Bridges Common 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.

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

//! Defines traits which represent a common interface for Substrate pallets which want to
//! incorporate bridge functionality.

use crate::bridges::runtime::ChainId;
use codec::{Codec, Decode, Encode, EncodeLike, MaxEncodedLen};
use core::{clone::Clone, cmp::Eq, default::Default, fmt::Debug};
use scale_info::TypeInfo;
#[cfg(feature = "std")]
use serde::{Deserialize, Serialize};
use sp_consensus_grandpa::{AuthorityList, ConsensusLog, SetId, GRANDPA_ENGINE_ID};
use sp_runtime::{generic::OpaqueDigestItemId, traits::Header as HeaderT, RuntimeDebug};
pub mod justification;

/// A type that can be used as a parameter in a dispatchable function.
///
/// When using `decl_module` all arguments for call functions must implement this trait.
pub trait Parameter: Codec + EncodeLike + Clone + Eq + Debug {}

impl<T> Parameter for T where T: Codec + EncodeLike + Clone + Eq + Debug {}

/// A GRANDPA Authority List and ID.
#[derive(Default, Encode, Decode, RuntimeDebug, TypeInfo, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
pub struct AuthoritySet {
    /// List of GRANDPA authorities for the current round.
    pub authorities: AuthorityList,
    /// Monotonic identifier of the current GRANDPA authority set.
    pub set_id: SetId,
}

impl MaxEncodedLen for AuthoritySet {
    fn max_encoded_len() -> usize {
        4096
    }
}
impl AuthoritySet {
    /// Create a new GRANDPA Authority Set.
    pub fn new(authorities: AuthorityList, set_id: SetId) -> Self {
        Self {
            authorities,
            set_id,
        }
    }
}

/// Data required for initializing the bridge pallet.
///
/// The bridge needs to know where to start its sync from, and this provides that initial context.
#[derive(Default, Encode, Decode, RuntimeDebug, TypeInfo, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
pub struct InitializationData<H: HeaderT> {
    /// The header from which we should start syncing.
    pub header: H,
    /// The initial authorities of the pallet.
    pub authority_list: AuthorityList,
    /// The ID of the initial authority set.
    pub set_id: SetId,
    /// Should the pallet block transaction immediately after initialization.
    pub is_halted: bool,
    /// 4-byte gateway identifier.
    pub gateway_id: ChainId,
}

/// base trait for verifying transaction inclusion proofs.
pub trait InclusionProofVerifier {
    /// Transaction type.
    type Transaction: Parameter;
    /// Transaction inclusion proof type.
    type TransactionInclusionProof: Parameter;

    /// Verify that transaction is a part of given block.
    ///
    /// Returns Some(transaction) if proof is valid and None otherwise.
    fn verify_transaction_inclusion_proof(
        proof: &Self::TransactionInclusionProof,
    ) -> Option<Self::Transaction>;
}

/// A trait for pallets which want to keep track of finalized headers from a bridged chain.
pub trait HeaderChain<H, E> {
    /// Get the best finalized header known to the header chain.
    fn best_finalized() -> H;

    /// Get the best authority set known to the header chain.
    fn authority_set() -> AuthoritySet;

    /// Write a header finalized by GRANDPA to the underlying pallet storage.
    fn append_header(header: H) -> Result<(), E>;
}

impl<H: Default, E> HeaderChain<H, E> for () {
    fn best_finalized() -> H {
        H::default()
    }

    fn authority_set() -> AuthoritySet {
        AuthoritySet::default()
    }

    fn append_header(_header: H) -> Result<(), E> {
        Ok(())
    }
}

/// Abstract finality proof that is justifying block finality.
pub trait FinalityProof<Number>: Clone + Send + Sync + Debug {
    /// Return number of header that this proof is generated for.
    fn target_header_number(&self) -> Number;
}

/// Find header digest that schedules next GRANDPA authorities set.
pub fn find_grandpa_authorities_scheduled_change<H: HeaderT>(
    header: &H,
) -> Option<sp_consensus_grandpa::ScheduledChange<H::Number>> {
    let id = OpaqueDigestItemId::Consensus(&GRANDPA_ENGINE_ID);

    let filter_log = |log: ConsensusLog<H::Number>| match log {
        ConsensusLog::ScheduledChange(change) => Some(change),
        _ => None,
    };

    // find the first consensus digest with the right ID which converts to
    // the right kind of consensus log.
    header
        .digest()
        .convert_first(|l| l.try_to(id).and_then(filter_log))
}

/// Inclusion proofs of different tries
#[derive(Encode, Decode, Clone, Debug, PartialEq, Eq, TypeInfo)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
pub enum ProofTriePointer {
    /// Proof is a merkle path in the state trie
    State,
    /// Proof is a merkle path in the transaction trie (extrisics in Substrate)
    Transaction,
    /// Proof is a merkle path in the receipts trie (in Substrate logs are entries in state trie, this doesn't apply)
    Receipts,
}