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
use configuration::types::Arg;
use support::constants::THIS_IS_A_BUG;

use crate::{network_spec::node::NodeSpec, shared::constants::*};

pub struct GenCmdOptions<'a> {
    pub relay_chain_name: &'a str,
    pub cfg_path: &'a str,
    pub data_path: &'a str,
    pub relay_data_path: &'a str,
    pub use_wrapper: bool,
    pub bootnode_addr: Vec<String>,
    pub use_default_ports_in_cmd: bool,
}

impl<'a> Default for GenCmdOptions<'a> {
    fn default() -> Self {
        Self {
            relay_chain_name: "rococo-local",
            cfg_path: "/cfg",
            data_path: "/data",
            relay_data_path: "/relay-data",
            use_wrapper: true,
            bootnode_addr: vec![],
            use_default_ports_in_cmd: false,
        }
    }
}

const FLAGS_ADDED_BY_US: [&str; 5] = [
    "--unsafe-rpc-external",
    "--no-telemetry",
    "--no-mdns",
    "--collator",
    "--",
];
const OPS_ADDED_BY_US: [&str; 6] = [
    "--chain",
    "--name",
    "--rpc-cors",
    "--rpc-methods",
    "--parachain-id",
    "--node-key",
];

// TODO: can we abstract this and use only one fn (or at least split and reuse in small fns)
pub fn generate_for_cumulus_node(
    node: &NodeSpec,
    options: GenCmdOptions,
    para_id: u32,
    full_p2p_port: u16,
) -> (String, Vec<String>) {
    let NodeSpec {
        key,
        args,
        is_validator,
        bootnodes_addresses,
        ..
    } = node;

    let mut tmp_args: Vec<String> = vec!["--node-key".into(), key.clone()];

    if !args.contains(&Arg::Flag("--prometheus-external".into())) {
        tmp_args.push("--prometheus-external".into())
    }

    if *is_validator && !args.contains(&Arg::Flag("--validator".into())) {
        tmp_args.push("--collator".into())
    }

    if !bootnodes_addresses.is_empty() {
        tmp_args.push("--bootnodes".into());
        let bootnodes = bootnodes_addresses
            .iter()
            .map(|m| m.to_string())
            .collect::<Vec<String>>()
            .join(" ");
        tmp_args.push(bootnodes)
    }

    // ports
    let (prometheus_port, rpc_port, p2p_port) =
        resolve_ports(node, options.use_default_ports_in_cmd);

    tmp_args.push("--prometheus-port".into());
    tmp_args.push(prometheus_port.to_string());

    tmp_args.push("--rpc-port".into());
    tmp_args.push(rpc_port.to_string());

    tmp_args.push("--listen-addr".into());
    tmp_args.push(format!("/ip4/0.0.0.0/tcp/{}/ws", p2p_port));

    let mut collator_args: &[Arg] = &[];
    let mut full_node_args: &[Arg] = &[];
    if !args.is_empty() {
        if let Some(index) = args.iter().position(|arg| match arg {
            Arg::Flag(flag) => flag.eq("--"),
            Arg::Option(..) => false,
        }) {
            (collator_args, full_node_args) = args.split_at(index);
        } else {
            // Assume args are those specified for collator only
            collator_args = args;
        }
    }

    // set our base path
    tmp_args.push("--base-path".into());
    tmp_args.push(options.data_path.into());

    let node_specific_bootnodes: Vec<String> = node
        .bootnodes_addresses
        .iter()
        .map(|b| b.to_string())
        .collect();
    let full_bootnodes = [node_specific_bootnodes, options.bootnode_addr].concat();
    if !full_bootnodes.is_empty() {
        tmp_args.push("--bootnodes".into());
        tmp_args.push(full_bootnodes.join(" "));
    }

    let mut full_node_p2p_needs_to_be_injected = false;
    let mut full_node_args_filtered = full_node_args
        .iter()
        .filter_map(|arg| match arg {
            Arg::Flag(flag) => {
                if FLAGS_ADDED_BY_US.contains(&flag.as_str()) {
                    None
                } else {
                    Some(vec![flag.to_owned()])
                }
            },
            Arg::Option(k, v) => {
                if OPS_ADDED_BY_US.contains(&k.as_str()) {
                    None
                } else if k.eq(&"port") && v.eq(&"30333") {
                    full_node_p2p_needs_to_be_injected = true;
                    None
                } else {
                    Some(vec![k.to_owned(), v.to_owned()])
                }
            },
        })
        .flatten()
        .collect::<Vec<String>>();

    // change p2p port if is the default
    full_node_args_filtered.push("--port".into());
    full_node_args_filtered.push(full_p2p_port.to_string());

    let mut args_filtered = collator_args
        .iter()
        .filter_map(|arg| match arg {
            Arg::Flag(flag) => {
                if FLAGS_ADDED_BY_US.contains(&flag.as_str()) {
                    None
                } else {
                    Some(vec![flag.to_owned()])
                }
            },
            Arg::Option(k, v) => {
                if OPS_ADDED_BY_US.contains(&k.as_str()) {
                    None
                } else {
                    Some(vec![k.to_owned(), v.to_owned()])
                }
            },
        })
        .flatten()
        .collect::<Vec<String>>();

    tmp_args.append(&mut args_filtered);

    let parachain_spec_path = format!("{}/{}.json", options.cfg_path, para_id);
    let mut final_args = vec![
        node.command.as_str().to_string(),
        "--chain".into(),
        parachain_spec_path,
        "--name".into(),
        node.name.clone(),
        "--rpc-cors".into(),
        "all".into(),
        "--unsafe-rpc-external".into(),
        "--rpc-methods".into(),
        "unsafe".into(),
    ];

    final_args.append(&mut tmp_args);

    let relaychain_spec_path = format!("{}/{}.json", options.cfg_path, options.relay_chain_name);
    let mut full_node_injected: Vec<String> = vec![
        "--".into(),
        "--base-path".into(),
        options.relay_data_path.into(),
        "--chain".into(),
        relaychain_spec_path,
        "--execution".into(),
        "wasm".into(),
    ];

    final_args.append(&mut full_node_injected);
    final_args.append(&mut full_node_args_filtered);

    if options.use_wrapper {
        ("/cfg/zombie-wrapper.sh".to_string(), final_args)
    } else {
        (final_args.remove(0), final_args)
    }
}

pub fn generate_for_node(
    node: &NodeSpec,
    options: GenCmdOptions,
    para_id: Option<u32>,
) -> (String, Vec<String>) {
    let NodeSpec {
        key,
        args,
        is_validator,
        bootnodes_addresses,
        ..
    } = node;
    let mut tmp_args: Vec<String> = vec![
        "--node-key".into(),
        key.clone(),
        // TODO:(team) we should allow to set the telemetry url from config
        "--no-telemetry".into(),
    ];

    if !args.contains(&Arg::Flag("--prometheus-external".into())) {
        tmp_args.push("--prometheus-external".into())
    }

    if let Some(para_id) = para_id {
        tmp_args.push("--parachain-id".into());
        tmp_args.push(para_id.to_string());
    }

    if *is_validator && !args.contains(&Arg::Flag("--validator".into())) {
        tmp_args.push("--validator".into());
        if node.supports_arg("--insecure-validator-i-know-what-i-do") {
            tmp_args.push("--insecure-validator-i-know-what-i-do".into());
        }
    }

    if !bootnodes_addresses.is_empty() {
        tmp_args.push("--bootnodes".into());
        let bootnodes = bootnodes_addresses
            .iter()
            .map(|m| m.to_string())
            .collect::<Vec<String>>()
            .join(" ");
        tmp_args.push(bootnodes)
    }

    // ports
    let (prometheus_port, rpc_port, p2p_port) =
        resolve_ports(node, options.use_default_ports_in_cmd);

    // Prometheus
    tmp_args.push("--prometheus-port".into());
    tmp_args.push(prometheus_port.to_string());

    // RPC
    // TODO (team): do we want to support old --ws-port?
    tmp_args.push("--rpc-port".into());
    tmp_args.push(rpc_port.to_string());

    let listen_value = if let Some(listen_val) = args.iter().find_map(|arg| match arg {
        Arg::Flag(_) => None,
        Arg::Option(k, v) => {
            if k.eq("--listen-addr") {
                Some(v)
            } else {
                None
            }
        },
    }) {
        let mut parts = listen_val.split('/').collect::<Vec<&str>>();
        // TODO: move this to error
        let port_part = parts
            .get_mut(4)
            .expect(&format!("should have at least 5 parts {THIS_IS_A_BUG}"));
        let port_to_use = p2p_port.to_string();
        *port_part = port_to_use.as_str();
        parts.join("/")
    } else {
        format!("/ip4/0.0.0.0/tcp/{}/ws", p2p_port)
    };

    tmp_args.push("--listen-addr".into());
    tmp_args.push(listen_value);

    // set our base path
    tmp_args.push("--base-path".into());
    tmp_args.push(options.data_path.into());

    let node_specific_bootnodes: Vec<String> = node
        .bootnodes_addresses
        .iter()
        .map(|b| b.to_string())
        .collect();
    let full_bootnodes = [node_specific_bootnodes, options.bootnode_addr].concat();
    if !full_bootnodes.is_empty() {
        tmp_args.push("--bootnodes".into());
        tmp_args.push(full_bootnodes.join(" "));
    }

    // add the rest of the args
    let mut args_filtered = args
        .iter()
        .filter_map(|arg| match arg {
            Arg::Flag(flag) => {
                if FLAGS_ADDED_BY_US.contains(&flag.as_str()) {
                    None
                } else {
                    Some(vec![flag.to_owned()])
                }
            },
            Arg::Option(k, v) => {
                if OPS_ADDED_BY_US.contains(&k.as_str()) {
                    None
                } else {
                    Some(vec![k.to_owned(), v.to_owned()])
                }
            },
        })
        .flatten()
        .collect::<Vec<String>>();

    tmp_args.append(&mut args_filtered);

    let chain_spec_path = format!("{}/{}.json", options.cfg_path, options.relay_chain_name);
    let mut final_args = vec![
        node.command.as_str().to_string(),
        "--chain".into(),
        chain_spec_path,
        "--name".into(),
        node.name.clone(),
        "--rpc-cors".into(),
        "all".into(),
        "--unsafe-rpc-external".into(),
        "--rpc-methods".into(),
        "unsafe".into(),
    ];

    final_args.append(&mut tmp_args);

    if let Some(ref subcommand) = node.subcommand {
        final_args.insert(1, subcommand.as_str().to_string());
    }

    if options.use_wrapper {
        ("/cfg/zombie-wrapper.sh".to_string(), final_args)
    } else {
        (final_args.remove(0), final_args)
    }
}

/// Returns (prometheus, rpc, p2p) ports to use in the command
fn resolve_ports(node: &NodeSpec, use_default_ports_in_cmd: bool) -> (u16, u16, u16) {
    if use_default_ports_in_cmd {
        (PROMETHEUS_PORT, RPC_PORT, P2P_PORT)
    } else {
        (node.prometheus_port.0, node.rpc_port.0, node.p2p_port.0)
    }
}