-
Notifications
You must be signed in to change notification settings - Fork 56
/
Copy pathlib.rs
206 lines (188 loc) · 6.48 KB
/
lib.rs
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
// Copyright (C) 2023 Polytope Labs.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
pub use crate::provider::system_events_key;
use std::sync::Arc;
use ismp::{consensus::ConsensusStateId, host::StateMachine};
use pallet_ismp::child_trie::{
request_commitment_storage_key, request_receipt_storage_key, response_commitment_storage_key,
response_receipt_storage_key,
};
use tesseract_primitives::{IsmpProvider, StateMachineUpdated, StreamError};
use serde::{Deserialize, Serialize};
use subxt::ext::sp_core::{bytes::from_hex, crypto, sr25519, Pair, H256};
use substrate_state_machine::HashAlgorithm;
use subxt::{
config::{
extrinsic_params::BaseExtrinsicParamsBuilder, polkadot::PlainTip, ExtrinsicParams, Header,
},
ext::sp_runtime::{traits::IdentifyAccount, MultiSignature, MultiSigner},
OnlineClient,
};
mod byzantine;
pub mod calls;
pub mod config;
pub mod extrinsic;
mod provider;
#[cfg(feature = "testing")]
pub use subxt_utils::gargantua as runtime;
#[cfg(feature = "testing")]
mod testing;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SubstrateConfig {
/// Hyperbridge network
#[serde(with = "serde_hex_utils::as_string")]
pub state_machine: StateMachine,
/// The hashing algorithm that substrate chain uses.
pub hashing: Option<HashAlgorithm>,
/// Consensus state id
pub consensus_state_id: Option<String>,
/// Websocket RPC url for the chain
pub rpc_ws: String,
/// Maximum size in bytes for the rpc payloads, both requests & responses.
pub max_rpc_payload_size: Option<u32>,
/// Relayer account seed
pub signer: Option<String>,
/// Initial height from which to start querying messages
pub initial_height: Option<u64>,
/// Max concurrent rpc requests allowed
pub max_concurent_queries: Option<u64>,
/// Frequency at which state machine updates will be queried in seconds
pub poll_interval: Option<u64>,
}
/// Core substrate client.
pub struct SubstrateClient<C: subxt::Config> {
/// Subxt client for the substrate chain
pub client: OnlineClient<C>,
/// Consensus state Id
consensus_state_id: ConsensusStateId,
/// State machine Identifier for this client.
state_machine: StateMachine,
/// The hashing algorithm that substrate chain uses.
hashing: HashAlgorithm,
/// Private key of the signing account
pub signer: sr25519::Pair,
/// Public Address
pub address: Vec<u8>,
/// Initial height from which to start querying messages
initial_height: u64,
/// Max concurrent rpc requests allowed
max_concurent_queries: Option<u64>,
/// Producer for state machine updated stream
state_machine_update_sender: Arc<
tokio::sync::Mutex<
Option<tokio::sync::broadcast::Sender<Result<StateMachineUpdated, StreamError>>>,
>,
>,
/// Substrate config
config: SubstrateConfig,
}
impl<C> SubstrateClient<C>
where
C: subxt::Config + Send + Sync + Clone,
<C::ExtrinsicParams as ExtrinsicParams<C::Hash>>::OtherParams:
Default + Send + Sync + From<BaseExtrinsicParamsBuilder<C, PlainTip>>,
C::Signature: From<MultiSignature> + Send + Sync,
C::AccountId: From<crypto::AccountId32> + Into<C::Address> + Clone + 'static + Send + Sync,
H256: From<<C as subxt::Config>::Hash>,
{
pub async fn new(config: SubstrateConfig) -> Result<Self, anyhow::Error> {
let max_rpc_payload_size = config.max_rpc_payload_size.unwrap_or(300u32 * 1024 * 1024);
let client =
subxt_utils::client::ws_client::<C>(&config.rpc_ws, max_rpc_payload_size).await?;
// If latest height of the state machine on the counterparty is not provided in config
// Set it to the latest parachain height
let initial_height = if let Some(initial_height) = config.initial_height {
initial_height
} else {
client
.rpc()
.header(None)
.await?
.expect("block header should be available")
.number()
.into()
};
let bytes = config
.signer
.clone()
.and_then(|seed| from_hex(&seed).ok())
.unwrap_or(H256::random().0.to_vec());
let signer = sr25519::Pair::from_seed_slice(&bytes)?;
let mut consensus_state_id: ConsensusStateId = Default::default();
consensus_state_id
.copy_from_slice(config.consensus_state_id.clone().unwrap_or("DOT0".into()).as_bytes());
let address = signer.public().0.to_vec();
Ok(Self {
client,
consensus_state_id,
state_machine: config.state_machine,
hashing: config.hashing.clone().unwrap_or(HashAlgorithm::Keccak),
signer,
address,
initial_height,
max_concurent_queries: config.max_concurent_queries,
state_machine_update_sender: Arc::new(tokio::sync::Mutex::new(None)),
config,
})
}
pub fn signer(&self) -> sr25519::Pair {
self.signer.clone()
}
pub fn account(&self) -> C::AccountId {
MultiSigner::Sr25519(self.signer.public()).into_account().into()
}
pub async fn set_latest_finalized_height(
&mut self,
counterparty: Arc<dyn IsmpProvider>,
) -> Result<(), anyhow::Error> {
let name = counterparty.name();
if self.config.initial_height.is_none() {
self.initial_height = self.query_finalized_height().await?.into();
}
log::info!(
"Initialized height for {:?}->{name} at {}",
self.state_machine,
self.initial_height
);
Ok(())
}
pub fn req_commitments_key(&self, commitment: H256) -> Vec<u8> {
request_commitment_storage_key(commitment)
}
pub fn res_commitments_key(&self, commitment: H256) -> Vec<u8> {
response_commitment_storage_key(commitment)
}
pub fn req_receipts_key(&self, commitment: H256) -> Vec<u8> {
request_receipt_storage_key(commitment)
}
pub fn res_receipt_key(&self, commitment: H256) -> Vec<u8> {
response_receipt_storage_key(commitment)
}
}
impl<C: subxt::Config> Clone for SubstrateClient<C> {
fn clone(&self) -> Self {
Self {
client: self.client.clone(),
consensus_state_id: self.consensus_state_id,
state_machine: self.state_machine,
hashing: self.hashing.clone(),
signer: self.signer.clone(),
address: self.address.clone(),
initial_height: self.initial_height,
max_concurent_queries: self.max_concurent_queries,
state_machine_update_sender: self.state_machine_update_sender.clone(),
config: self.config.clone(),
}
}
}