-
Notifications
You must be signed in to change notification settings - Fork 111
/
Copy pathinvalid_events.rs
385 lines (345 loc) · 13.1 KB
/
invalid_events.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
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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
//! This is a test for invalid string based deposits, the goal is to torture test the implementation
//! with every possible variant of invalid data and ensure that in all cases the community pool deposit
//! works correctly.
use crate::happy_path::test_erc20_deposit_panic;
use crate::happy_path_v2::deploy_cosmos_representing_erc20_and_check_adoption;
use crate::one_eth;
use crate::utils::create_default_test_config;
use crate::utils::footoken_metadata;
use crate::utils::get_event_nonce_safe;
use crate::utils::get_user_key;
use crate::utils::start_orchestrators;
use crate::utils::ValidatorKeys;
use crate::MINER_ADDRESS;
use crate::MINER_PRIVATE_KEY;
use crate::TOTAL_TIMEOUT;
use clarity::abi::encode_call;
use clarity::abi::AbiToken as Token;
use clarity::Address as EthAddress;
use clarity::Address;
use deep_space::Contact;
use ethereum_gravity::send_to_cosmos::SEND_TO_COSMOS_GAS_LIMIT;
use gravity_proto::gravity::query_client::QueryClient as GravityQueryClient;
use rand::distributions::Alphanumeric;
use rand::thread_rng;
use rand::Rng;
use std::time::Instant;
use tonic::transport::Channel;
use web30::client::Web3;
use web30::types::SendTxOption;
pub async fn invalid_events(
web30: &Web3,
contact: &Contact,
keys: Vec<ValidatorKeys>,
gravity_address: EthAddress,
erc20_address: EthAddress,
grpc_client: GravityQueryClient<Channel>,
) {
let mut grpc_client = grpc_client;
let erc20_denom = format!("gravity{}", erc20_address);
// figure out how many of a given erc20 we already have on startup so that we can
// keep track of incrementation. This makes it possible to run this test again without
// having to restart your test chain
let community_pool_contents = contact.query_community_pool().await.unwrap();
let mut starting_pool_amount = None;
for coin in community_pool_contents {
if coin.denom == erc20_denom {
starting_pool_amount = Some(coin.amount);
break;
}
}
if starting_pool_amount.is_none() {
starting_pool_amount = Some(0u8.into())
}
let mut starting_pool_amount = starting_pool_amount.unwrap();
let no_relay_market_config = create_default_test_config();
start_orchestrators(keys.clone(), gravity_address, false, no_relay_market_config).await;
for test_value in get_deposit_test_strings() {
// next we send an invalid string deposit, we use byte encoding here so that we can attempt a totally invalid send
send_to_cosmos_invalid(erc20_address, gravity_address, test_value, web30).await;
// send some coins across the correct way, make sure they arrive
// note send_to_cosmos_invalid does not wait for the actual oracle
// to complete like this function does, since this deposit will have
// a latter event nonce it will effectively wait for the invalid deposit
// to complete as well
let user_keys = get_user_key(None);
test_erc20_deposit_panic(
web30,
contact,
&mut grpc_client,
user_keys.cosmos_address,
gravity_address,
erc20_address,
one_eth(),
None,
None,
)
.await;
// finally we check that the deposit has been added to the community pool
let community_pool_contents = contact.query_community_pool().await.unwrap();
for coin in community_pool_contents {
if coin.denom == erc20_denom {
let expected = starting_pool_amount + one_eth();
if coin.amount != expected {
error!(
"Expected {} in the community pool found {}.",
expected, coin.amount
);
error!("This means an invalid deposit has been 'lost' in the bridge, instead of allowing it's funds to be used by the Community pool");
panic!("Lost an invalid deposit!");
} else {
starting_pool_amount = expected;
}
}
}
}
for test_value in get_erc20_test_values() {
deploy_invalid_erc20(gravity_address, web30, keys.clone(), test_value).await;
web30.wait_for_next_block(TOTAL_TIMEOUT).await.unwrap();
}
web30.wait_for_next_block(TOTAL_TIMEOUT).await.unwrap();
// make sure this actual deployment works after all the bad ones
let _ = deploy_cosmos_representing_erc20_and_check_adoption(
gravity_address,
web30,
None,
&mut grpc_client,
false,
footoken_metadata(contact).await,
)
.await;
info!("Successfully completed the invalid events test")
}
fn get_deposit_test_strings() -> Vec<Vec<u8>> {
// A series of test strings designed to torture our implementation.
let mut test_strings = Vec::new();
// the maximum size of a message I could get Geth 1.10.8 to accept
// may be larger in the future.
const MAX_SIZE: usize = 100_000;
// normal utf-8
let bad = "bad destination".to_string();
test_strings.push(bad.as_bytes().to_vec());
// someone is trying to deposit to an eth address
let incorrect = "0x00000000000000000000000089bde264cc4e819326482e041d4ae167981935ce";
test_strings.push(incorrect.as_bytes().to_vec());
// a very long, but valid utf8 string
let rand_string: String = thread_rng()
.sample_iter(&Alphanumeric)
.take(MAX_SIZE)
.map(char::from)
.collect();
test_strings.push(rand_string.as_bytes().to_vec());
// generate a random but invalid utf-8 string
let mut rand_invalid: Vec<u8> = (0..32).map(|_| rand::random::<u8>()).collect();
while String::from_utf8(rand_invalid.clone()).is_ok() {
rand_invalid = (0..32).map(|_| rand::random::<u8>()).collect();
}
test_strings.push(rand_invalid);
// generate a random but invalid utf-8 string, but this time longer
let mut rand_invalid_long: Vec<u8> = (0..MAX_SIZE).map(|_| rand::random::<u8>()).collect();
while String::from_utf8(rand_invalid_long.clone()).is_ok() {
rand_invalid_long = (0..MAX_SIZE).map(|_| rand::random::<u8>()).collect();
}
test_strings.push(rand_invalid_long);
test_strings
}
fn get_erc20_test_values() -> Vec<Erc20Params> {
// A series of test strings designed to torture our implementation.
let mut test_strings = Vec::new();
// the maximum size I could get OpenEthereum ERC20 to accept
// maybe higher in the future
const MAX_SIZE: usize = 5_000;
// start with normal utf-8 and odd decimals values
let bad = "bad".to_string().as_bytes().to_vec();
test_strings.push(Erc20Params {
erc20_symbol: bad.clone(),
erc20_name: bad.clone(),
cosmos_denom: bad.clone(),
decimals: 0,
});
test_strings.push(Erc20Params {
erc20_symbol: bad.clone(),
erc20_name: bad.clone(),
cosmos_denom: bad,
decimals: 255,
});
let blank = String::new().as_bytes().to_vec();
test_strings.push(Erc20Params {
erc20_symbol: blank.clone(),
erc20_name: blank.clone(),
cosmos_denom: blank,
decimals: 6,
});
// move into testing long but valid utf8
// a very long, but valid utf8 string
let rand_string: String = thread_rng()
.sample_iter(&Alphanumeric)
.take(MAX_SIZE)
.map(char::from)
.collect();
let rand_string = rand_string.as_bytes().to_vec();
test_strings.push(Erc20Params {
erc20_symbol: rand_string.clone(),
erc20_name: rand_string.clone(),
cosmos_denom: rand_string,
decimals: 0,
});
// generate a random but invalid utf-8 string
let mut rand_invalid: Vec<u8> = (0..32).map(|_| rand::random::<u8>()).collect();
while String::from_utf8(rand_invalid.clone()).is_ok() {
rand_invalid = (0..32).map(|_| rand::random::<u8>()).collect();
}
test_strings.push(Erc20Params {
erc20_symbol: rand_invalid.clone(),
erc20_name: rand_invalid.clone(),
cosmos_denom: rand_invalid,
decimals: 0,
});
// generate a random but invalid utf-8 string, but this time longer
let mut rand_invalid_long: Vec<u8> = (0..MAX_SIZE).map(|_| rand::random::<u8>()).collect();
while String::from_utf8(rand_invalid_long.clone()).is_ok() {
rand_invalid_long = (0..MAX_SIZE).map(|_| rand::random::<u8>()).collect();
}
test_strings.push(Erc20Params {
erc20_symbol: rand_invalid_long.clone(),
erc20_name: rand_invalid_long.clone(),
cosmos_denom: rand_invalid_long,
decimals: 0,
});
test_strings
}
/// produces an invalid send to cosmos, accepts bytes so that we can test
/// all sorts of invalid utf-8
pub async fn send_to_cosmos_invalid(
erc20: Address,
gravity_contract: Address,
cosmos_destination: Vec<u8>,
web3: &Web3,
) {
let mut approve_nonce = None;
// rapidly changing gas prices can cause this to fail, a quick retry loop here
// retries in a way that assists our transaction stress test
let mut approved = web3
.get_erc20_allowance(erc20, *MINER_ADDRESS, gravity_contract)
.await
.unwrap()
>= web3.get_erc20_balance(erc20, *MINER_ADDRESS).await.unwrap();
let start = Instant::now();
// keep trying while there's still time
while !approved && Instant::now() - start < TOTAL_TIMEOUT {
approved = web3
.get_erc20_allowance(erc20, *MINER_ADDRESS, gravity_contract)
.await
.unwrap()
>= web3.get_erc20_balance(erc20, *MINER_ADDRESS).await.unwrap();
}
if !approved {
let nonce = web3
.eth_get_transaction_count(*MINER_ADDRESS)
.await
.unwrap();
let options = vec![SendTxOption::Nonce(nonce)];
approve_nonce = Some(nonce);
let txid = web3
.erc20_approve(
erc20,
web3.get_erc20_balance(erc20, *MINER_ADDRESS).await.unwrap(),
*MINER_PRIVATE_KEY,
gravity_contract,
None,
options,
)
.await
.unwrap();
trace!(
"We are not approved for ERC20 transfers, approving txid: {:#066x}",
txid
);
web3.wait_for_transaction(txid, TOTAL_TIMEOUT, None)
.await
.unwrap();
}
let mut options = vec![SendTxOption::GasLimit(SEND_TO_COSMOS_GAS_LIMIT.into())];
// if we have run an approval we should increment our nonce by one so that
// we can be sure our actual tx can go in immediately behind
if let Some(nonce) = approve_nonce {
options.push(SendTxOption::Nonce(nonce + 1u8.into()));
}
// unbounded bytes shares the same actual encoding as strings
let encoded_destination_address = Token::UnboundedBytes(cosmos_destination);
let tx_hash = web3
.send_prepared_transaction(
web3.prepare_transaction(
gravity_contract,
encode_call(
"sendToCosmos(address,string,uint256)",
&[erc20.into(), encoded_destination_address, one_eth().into()],
)
.unwrap(),
0u32.into(),
*MINER_PRIVATE_KEY,
vec![SendTxOption::GasLimitMultiplier(3.0)],
)
.await
.unwrap(),
)
.await
.unwrap();
web3.wait_for_transaction(tx_hash, TOTAL_TIMEOUT, None)
.await
.unwrap();
}
struct Erc20Params {
cosmos_denom: Vec<u8>,
erc20_name: Vec<u8>,
erc20_symbol: Vec<u8>,
decimals: u8,
}
async fn deploy_invalid_erc20(
gravity_address: EthAddress,
web30: &Web3,
keys: Vec<ValidatorKeys>,
erc20_params: Erc20Params,
) {
let starting_event_nonce =
get_event_nonce_safe(gravity_address, web30, keys[0].eth_key.to_address())
.await
.unwrap();
let tx_hash = web30
.send_prepared_transaction(
web30
.prepare_transaction(
gravity_address,
encode_call(
"deployERC20(string,string,string,uint8)",
&[
Token::UnboundedBytes(erc20_params.cosmos_denom),
Token::UnboundedBytes(erc20_params.erc20_name),
Token::UnboundedBytes(erc20_params.erc20_symbol),
erc20_params.decimals.into(),
],
)
.unwrap(),
0u32.into(),
*MINER_PRIVATE_KEY,
vec![SendTxOption::GasPriceMultiplier(2.0)],
)
.await
.unwrap(),
)
.await
.unwrap();
web30
.wait_for_transaction(tx_hash, TOTAL_TIMEOUT, None)
.await
.unwrap();
let ending_event_nonce =
get_event_nonce_safe(gravity_address, web30, keys[0].eth_key.to_address())
.await
.unwrap();
assert!(starting_event_nonce != ending_event_nonce);
info!(
"Successfully deployed an invalid ERC20 on Cosmos with event nonce {}",
ending_event_nonce
);
}