ibc-test-framework 0.32.2

Framework for writing integration tests for IBC relayers
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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
use core::str::FromStr;
use eyre::eyre;
use ibc_relayer_types::applications::transfer::amount::Amount;
use serde_json as json;
use serde_yaml as yaml;
use std::collections::HashMap;
use tracing::debug;

use crate::chain::exec::simple_exec;
use crate::error::{handle_generic_error, Error};
use crate::prelude::*;

pub fn query_balance(
    chain_id: &str,
    command_path: &str,
    rpc_listen_address: &str,
    wallet_id: &str,
    denom: &str,
) -> Result<Amount, Error> {
    // SDK v0.50 has removed the `--denom` flag from the `query bank balances` CLI.
    // It also changed the JSON output.
    match simple_exec(
        chain_id,
        command_path,
        &[
            "--node",
            rpc_listen_address,
            "query",
            "bank",
            "balances",
            wallet_id,
            "--denom",
            denom,
            "--output",
            "json",
        ],
    ) {
        Ok(output) => {
            let amount_str = json::from_str::<json::Value>(&output.stdout)
                .map_err(handle_generic_error)?
                .get("amount")
                .ok_or_else(|| eyre!("expected amount field"))?
                .as_str()
                .ok_or_else(|| eyre!("expected string field"))?
                .to_string();

            let amount = Amount::from_str(&amount_str).map_err(handle_generic_error)?;

            Ok(amount)
        }
        Err(_) => {
            let res = simple_exec(
                chain_id,
                command_path,
                &[
                    "--node",
                    rpc_listen_address,
                    "query",
                    "bank",
                    "balances",
                    wallet_id,
                    "--output",
                    "json",
                ],
            )?;
            let output = if res.stdout.is_empty() {
                res.stderr
            } else {
                res.stdout
            };
            let amounts_array =
                json::from_str::<json::Value>(&output).map_err(handle_generic_error)?;

            let balances = amounts_array
                .get("balances")
                .ok_or_else(|| eyre!("expected balances field"))?
                .as_array()
                .ok_or_else(|| eyre!("expected array field"))?;

            let amount_str = balances.iter().find(|a| {
                a.get("denom")
                    .ok_or_else(|| eyre!("expected denom field"))
                    .unwrap()
                    == denom
            });

            match amount_str {
                Some(amount_str) => {
                    let amount_str = amount_str
                        .get("amount")
                        .ok_or_else(|| eyre!("expected amount field"))?
                        .as_str()
                        .ok_or_else(|| eyre!("expected amount to be in string format"))?;

                    let amount = Amount::from_str(amount_str).map_err(handle_generic_error)?;

                    Ok(amount)
                }
                None => {
                    debug!(
                        "Denom `{denom}` not found when querying for balance, will return 0{denom}"
                    );
                    Ok(Amount::from_str("0").map_err(handle_generic_error)?)
                }
            }
        }
    }
}

pub fn query_namada_balance(
    chain_id: &str,
    _command_path: &str,
    home_path: &str,
    denom: &Denom,
    wallet_id: &str,
    rpc_listen_address: &str,
) -> Result<Amount, Error> {
    let output = simple_exec(
        chain_id,
        "namadac",
        &[
            "--base-dir",
            home_path,
            "balance",
            "--owner",
            wallet_id,
            "--token",
            &denom.hash_only(),
            "--node",
            rpc_listen_address,
        ],
    )?;

    let words: Vec<&str> = output.stdout.split_whitespace().collect();
    let raw_addr = &format!("{}:", denom.hash_only());

    if let Some(derived_index) = words.iter().position(|&w| w.contains(raw_addr)) {
        if let Some(&amount_str) = words.get(derived_index + 1) {
            return Amount::from_str(amount_str).map_err(handle_generic_error);
        }
        Err(Error::generic(eyre!(
            "chain id is not 1 words after `{raw_addr}`: raw output `{}` split output `{words:#?}`",
            output.stdout
        )))
    } else {
        let denom_display_name = &format!("{}:", denom.namada_display_name());
        if let Some(derived_index) = words.iter().position(|&w| w.contains(denom_display_name)) {
            if let Some(&amount_str) = words.get(derived_index + 1) {
                return Amount::from_str(amount_str).map_err(handle_generic_error);
            }
            Err(Error::generic(eyre!(
                "chain id is not 1 words after `{denom_display_name}`: raw output `{}` split output `{words:#?}`",
                output.stdout
            )))
        } else {
            debug!("Denom `{denom_display_name}` not found when querying for balance, will return 0{denom}");
            Ok(Amount::from_str("0").map_err(handle_generic_error)?)
        }
    }
}

/**
    Query for the transactions related to a wallet on `Chain`
    receiving token transfer from others.
*/
pub fn query_recipient_transactions(
    chain_id: &str,
    command_path: &str,
    rpc_listen_address: &str,
    recipient_address: &str,
) -> Result<json::Value, Error> {
    let res = match simple_exec(
        chain_id,
        command_path,
        &[
            "--node",
            rpc_listen_address,
            "query",
            "txs",
            "--events",
            &format!("transfer.recipient={recipient_address}"),
        ],
    ) {
        Ok(output) => output.stdout,
        // Cosmos SDK v0.50.1 changed the `query txs` CLI flag from `--events` to `--query`
        Err(_) => {
            simple_exec(
                chain_id,
                command_path,
                &[
                    "--node",
                    rpc_listen_address,
                    "query",
                    "txs",
                    "--query",
                    &format!("transfer.recipient='{recipient_address}'"),
                ],
            )?
            .stdout
        }
    };

    tracing::debug!("parsing tx result: {}", res);

    match json::from_str(&res) {
        Ok(res) => Ok(res),
        _ => {
            let value: yaml::Value = yaml::from_str(&res).map_err(handle_generic_error)?;
            Ok(yaml_to_json_value(value)?)
        }
    }
}

// Hack to convert yaml::Value to json::Value. Unfortunately there is
// no builtin conversion provided even though both Value types are
// essentially the same. We just convert the two types to and from
// strings as a shortcut.
//
// TODO: properly implement a common trait that is implemented by
// dynamic types like json::Value, yaml::Value, and toml::Value.
// That way we can write generic functions that work with any of
// the dynamic value types for testing purposes.
fn yaml_to_json_value(value: yaml::Value) -> Result<json::Value, Error> {
    let json_str = json::to_string(&value).map_err(handle_generic_error)?;

    let parsed = json::from_str(&json_str).map_err(handle_generic_error)?;

    Ok(parsed)
}

/// Query pending Cross Chain Queries
pub fn query_cross_chain_query(
    chain_id: &str,
    command_path: &str,
    rpc_listen_address: &str,
) -> Result<String, Error> {
    let res = simple_exec(
        chain_id,
        command_path,
        &[
            "--node",
            rpc_listen_address,
            "query",
            "interchainquery",
            "list-pending-queries",
            "--output",
            "json",
        ],
    )?
    .stdout;

    Ok(res)
}

/// Query authority account for a specific module
pub fn query_auth_module(
    chain_id: &str,
    command_path: &str,
    home_path: &str,
    rpc_listen_address: &str,
    module_name: &str,
) -> Result<String, Error> {
    let account = match simple_exec(
        chain_id,
        command_path,
        &[
            "--home",
            home_path,
            "--node",
            rpc_listen_address,
            "query",
            "auth",
            "module-account",
            module_name,
            "--output",
            "json",
        ],
    ) {
        Ok(raw_output) => {
            let output = if raw_output.stdout.is_empty() {
                raw_output.stderr
            } else {
                raw_output.stdout
            };
            let json_res: HashMap<String, serde_json::Value> =
                serde_json::from_str(&output).map_err(handle_generic_error)?;

            json_res
                .get("account")
                .ok_or_else(|| eyre!("expect `account` string field to be present in json result"))?
                .clone()
        }
        Err(e) => {
            debug!("CLI `query auth module-account` failed, will try with `query auth module-accounts`: {e}");
            let raw_output = simple_exec(
                chain_id,
                command_path,
                &[
                    "--home",
                    home_path,
                    "--node",
                    rpc_listen_address,
                    "query",
                    "auth",
                    "module-accounts",
                    "--output",
                    "json",
                ],
            )?;
            let output = if raw_output.stdout.is_empty() {
                raw_output.stderr
            } else {
                raw_output.stdout
            };
            let json_res: HashMap<String, serde_json::Value> =
                serde_json::from_str(&output).map_err(handle_generic_error)?;

            let accounts = json_res
                .get("accounts")
                .ok_or_else(|| {
                    eyre!("expect `accounts` string field to be present in json result")
                })?
                .as_array()
                .ok_or_else(|| eyre!("expected `accounts` to be an array"))?;

            accounts
                .iter()
                .find(|&account| {
                    if let Some(name) = account.get("name") {
                        name == module_name
                    } else {
                        false
                    }
                })
                .ok_or_else(|| {
                    eyre!("expected to find the account for the `{module_name}` module")
                })?
                .clone()
        }
    };

    // Depending on the version used the CLI `query auth module-account` will have a field `base_account` or
    // or a field `value` containing the address.
    let res = match account.get("base_account") {
        Some(base_account) => base_account
            .get("address")
            .ok_or_else(|| eyre!("expect `address` string field to be present in json result"))?
            .as_str()
            .ok_or_else(|| eyre!("failed to convert value to &str"))?,
        None => account
            .get("value")
            .ok_or_else(|| eyre!("expect `value` string field to be present in json result"))?
            .get("address")
            .ok_or_else(|| eyre!("expect `address` string field to be present in json result"))?
            .as_str()
            .ok_or_else(|| eyre!("failed to convert value to &str"))?,
    };

    Ok(res.to_owned())
}

pub fn query_tx_hash(
    chain_id: &str,
    command_path: &str,
    home_path: &str,
    rpc_listen_address: &str,
    command_output: &str,
) -> Result<(), Error> {
    let json_output: serde_json::Value =
        serde_json::from_str(command_output).map_err(handle_generic_error)?;

    let output_tx_hash = json_output
        .get("txhash")
        .and_then(|code| code.as_str())
        .ok_or_else(|| {
            Error::generic(eyre!(
                "failed to extract 'txhash' from command output: {command_output}"
            ))
        })?;

    let raw_output = simple_exec(
        chain_id,
        command_path,
        &[
            "--home",
            home_path,
            "--node",
            rpc_listen_address,
            "query",
            "tx",
            output_tx_hash,
            "--output",
            "json",
        ],
    )?;

    let json_output: serde_json::Value =
        serde_json::from_str(&raw_output.stdout).map_err(handle_generic_error)?;

    let code = json_output
        .get("code")
        .and_then(|code| code.as_u64())
        .ok_or_else(|| eyre!("Failed to retrieve 'code' from 'query tx' command output"))?;

    if code != 0 {
        let raw_log = json_output
            .get("raw_log")
            .and_then(|code| code.as_str())
            .ok_or_else(|| eyre!("Failed to retrieve 'raw_log' from 'query tx' command output"))?;
        return Err(Error::generic(eyre!(
            "command failed with error code {code}. Detail: {raw_log}"
        )));
    }

    Ok(())
}