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
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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
use crate::jsonrpc::Params;
#[cfg(test)]
use crate::tests::mock::Mock;
use crate::types::{
BlockNumber, Bytes, CallRequest, FilterBuilder, Log, SubstrateBlockLimited,
SubstrateHeaderLimited, Transaction, TransactionReceipt,
};
use crate::util::serialize;
use crate::{
types, BridgeContractAddress, Config, Error, NodeParams, Pallet, DEPOSIT_TOPIC,
HTTP_REQUEST_TIMEOUT_SECS, STORAGE_ETH_NODE_PARAMS, STORAGE_SUB_NODE_URL_KEY, SUB_NODE_URL,
};
use alloc::string::String;
use alloc::vec::Vec;
use frame_support::log::{error, trace, warn};
use frame_support::sp_runtime::offchain as rt_offchain;
use frame_support::sp_runtime::offchain::storage::StorageValueRef;
use frame_support::traits::Get;
use frame_support::{fail, sp_io};
use frame_system::offchain::CreateSignedTransaction;
use hex_literal::hex;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use sp_core::{H160, H256};
use sp_std::convert::TryInto;
impl<T: Config> Pallet<T> {
pub fn http_request(
url: &str,
body: Vec<u8>,
headers: &[(&'static str, String)],
) -> Result<Vec<u8>, Error<T>> {
trace!("Sending request to: {}", url);
let mut request = rt_offchain::http::Request::post(url, vec![body.clone()]);
let timeout = sp_io::offchain::timestamp().add(rt_offchain::Duration::from_millis(
HTTP_REQUEST_TIMEOUT_SECS * 1000,
));
for (key, value) in headers {
request = request.add_header(*key, &*value);
}
#[allow(unused_mut)]
let mut pending = request.deadline(timeout).send().map_err(|e| {
error!("Failed to send a request {:?}", e);
<Error<T>>::HttpFetchingError
})?;
#[cfg(test)]
T::Mock::on_request(&mut pending, url, String::from_utf8_lossy(&body));
let response = pending
.try_wait(timeout)
.map_err(|e| {
error!("Failed to get a response: {:?}", e);
<Error<T>>::HttpFetchingError
})?
.map_err(|e| {
error!("Failed to get a response: {:?}", e);
<Error<T>>::HttpFetchingError
})?;
if response.code != 200 {
error!("Unexpected http request status code: {}", response.code);
return Err(<Error<T>>::HttpFetchingError);
}
let resp = response.body().collect::<Vec<u8>>();
Ok(resp)
}
pub fn json_rpc_request<I: Serialize, O: for<'de> Deserialize<'de>>(
url: &str,
id: u64,
method: &str,
params: &I,
headers: &[(&'static str, String)],
) -> Result<O, Error<T>> {
let params = match serialize(params) {
Value::Null => Params::None,
Value::Array(v) => Params::Array(v),
Value::Object(v) => Params::Map(v),
_ => {
error!("json_rpc_request: got invalid params");
fail!(Error::<T>::JsonSerializationError);
}
};
let raw_response = Self::http_request(
url,
serde_json::to_vec(&jsonrpc::Request::Single(jsonrpc::Call::MethodCall(
jsonrpc::MethodCall {
jsonrpc: Some(jsonrpc::Version::V2),
method: method.into(),
params,
id: jsonrpc::Id::Num(id as u64),
},
)))
.map_err(|_| Error::<T>::JsonSerializationError)?,
&headers,
)
.and_then(|x| {
String::from_utf8(x).map_err(|e| {
error!("json_rpc_request: from utf8 failed, {}", e);
Error::<T>::HttpFetchingError
})
})?;
let response = jsonrpc::Response::from_json(&raw_response)
.map_err(|e| {
error!("json_rpc_request: from_json failed, {}", e);
})
.map_err(|_| Error::<T>::FailedToLoadTransaction)?;
let result = match response {
jsonrpc::Response::Batch(_xs) => {
unreachable!("we've just sent a `Single` request; qed")
}
jsonrpc::Response::Single(x) => x,
};
match result {
jsonrpc::Output::Success(s) => {
if s.result.is_null() {
Err(Error::<T>::FailedToLoadTransaction)
} else {
serde_json::from_value(s.result).map_err(|e| {
error!("json_rpc_request: from_value failed, {}", e);
Error::<T>::JsonDeserializationError.into()
})
}
}
_ => {
error!("json_rpc_request: request failed");
Err(Error::<T>::JsonDeserializationError.into())
}
}
}
pub fn eth_json_rpc_request<I: Serialize, O: for<'de> Deserialize<'de>>(
method: &str,
params: &I,
network_id: T::NetworkId,
) -> Result<O, Error<T>> {
let string = format!("{}-{:?}", STORAGE_ETH_NODE_PARAMS, network_id);
let s_node_params = StorageValueRef::persistent(string.as_bytes());
let node_params = match s_node_params.get::<NodeParams>().ok().flatten() {
Some(v) => v,
None => {
warn!("Failed to make JSON-RPC request, make sure to set node parameters.");
fail!(Error::<T>::FailedToLoadSidechainNodeParams);
}
};
let mut headers: Vec<(_, String)> = vec![("content-type", "application/json".into())];
if let Some(node_credentials) = node_params.credentials {
headers.push(("Authorization", node_credentials));
}
Self::json_rpc_request(&node_params.url, 0, method, params, &headers)
}
pub fn substrate_json_rpc_request<I: Serialize, O: for<'de> Deserialize<'de>>(
method: &str,
params: &I,
) -> Result<O, Error<T>> {
let s_node_url = StorageValueRef::persistent(STORAGE_SUB_NODE_URL_KEY);
let node_url = s_node_url
.get::<String>()
.ok()
.flatten()
.unwrap_or_else(|| SUB_NODE_URL.into());
let headers: Vec<(_, String)> = vec![("content-type", "application/json".into())];
Self::json_rpc_request(&node_url, 0, method, params, &headers)
}
pub fn load_is_used(hash: H256, network_id: T::NetworkId) -> Result<bool, Error<T>> {
let mut data: Vec<_> = hex!("b07c411f").to_vec();
data.extend(&hash.0);
let contract_address = types::H160(BridgeContractAddress::<T>::get(network_id).0);
let contracts = if network_id == T::GetEthNetworkId::get() {
vec![
contract_address,
types::H160(Self::xor_master_contract_address().0),
types::H160(Self::val_master_contract_address().0),
]
} else {
vec![contract_address]
};
for contract in contracts {
let is_used = Self::eth_json_rpc_request::<_, bool>(
"eth_call",
&vec![
serialize(&CallRequest {
to: Some(contract),
data: Some(Bytes(data.clone())),
..Default::default()
}),
Value::String("latest".into()),
],
network_id,
)?;
if is_used {
return Ok(true);
}
}
Ok(false)
}
pub fn load_current_height(network_id: T::NetworkId) -> Result<u64, Error<T>> {
Self::eth_json_rpc_request::<_, types::U64>("eth_blockNumber", &(), network_id)
.map(|x| x.as_u64())
}
pub fn load_tx(hash: H256, network_id: T::NetworkId) -> Result<Transaction, Error<T>> {
let hash = types::H256(hash.0);
let tx_receipt = Self::eth_json_rpc_request::<_, Transaction>(
"eth_getTransactionByHash",
&vec![hash],
network_id,
)?;
let to = tx_receipt
.to
.map(|x| H160(x.0))
.ok_or(Error::<T>::UnknownContractAddress)?;
Self::ensure_known_contract(to, network_id)?;
Ok(tx_receipt)
}
pub fn load_tx_receipt(
hash: H256,
network_id: T::NetworkId,
) -> Result<TransactionReceipt, Error<T>> {
let hash = types::H256(hash.0);
let tx_receipt = Self::eth_json_rpc_request::<_, TransactionReceipt>(
"eth_getTransactionReceipt",
&vec![hash],
network_id,
)?;
let to = tx_receipt
.to
.map(|x| H160(x.0))
.ok_or(Error::<T>::UnknownContractAddress)?;
Self::ensure_known_contract(to, network_id)?;
Ok(tx_receipt)
}
pub fn load_substrate_finalized_header() -> Result<SubstrateHeaderLimited, Error<T>>
where
T: CreateSignedTransaction<<T as Config>::RuntimeCall>,
{
let hash =
Self::substrate_json_rpc_request::<_, types::H256>("chain_getFinalizedHead", &())?;
let header = Self::substrate_json_rpc_request::<_, types::SubstrateHeaderLimited>(
"chain_getHeader",
&[hash],
)?;
Ok(header)
}
pub fn load_substrate_block(number: T::BlockNumber) -> Result<SubstrateBlockLimited, Error<T>>
where
T: CreateSignedTransaction<<T as Config>::RuntimeCall>,
{
let int: u32 = number
.try_into()
.map_err(|_| ())
.expect("block number is always at least u32; qed");
let hash =
Self::substrate_json_rpc_request::<_, types::H256>("chain_getBlockHash", &[int])?;
let block = Self::substrate_json_rpc_request::<_, types::SubstrateSignedBlockLimited>(
"chain_getBlock",
&[hash],
)?;
Ok(block.block)
}
pub fn load_transfers_logs(
network_id: T::NetworkId,
from_block: u64,
to_block: u64,
) -> Result<Vec<Log>, Error<T>> {
trace!(
"Loading transfer logs from block {:?} to block {:?}",
from_block,
to_block,
);
Self::eth_json_rpc_request(
"eth_getLogs",
&[FilterBuilder::default()
.topics(Some(vec![types::H256(DEPOSIT_TOPIC.0)]), None, None, None)
.from_block(BlockNumber::Number(from_block.into()))
.to_block(BlockNumber::Number(to_block.into()))
.address(vec![types::H160(
BridgeContractAddress::<T>::get(network_id).0,
)])
.build()],
network_id,
)
}
}