hopli/
network_registry.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
//! This module contains arguments and functions to interact with the Network Registry contract for a privileged account.
//! To participate in the HOPR network, a node must be included in the network registry contract.
//! Nodes and the staking account (Safe) that manages them should be registered as a pair in the Network registry contrat.
//! Nodes and safes can be registered by either a manager or by the staking account itself.
//!
//! Note the currently only manager wallet can register node-safe pairs. Node runners cannot self-register their nodes.
//!
//! A manager (i.e. an account with `MANAGER_ROLE` role), can perform the following actions with `hopli network-registry`,
//! by specifying the subcommand:
//! A manager account can register nodes and safes with `manager-regsiter`
//! A manager account can deregister nodes with `manager-deregsiter`
//! A manager account can set eligibility of staking accounts with `manager-force-sync`
//!
//! Some sample commands:
//! - Manager registers nodes:
//! ```text
//! hopli network-registry manager-register \
//!     --network anvil-localhost \
//!     --contracts-root "../ethereum/contracts" \
//!     --identity-directory "./test" --password-path "./test/pwd" \
//!     --node-address 0x9e820e68f8c024779ebcb6cd2edda1885e1dbe1f,0xb3724772badf4d8fffa186a5ca0bea87693a6c2a \
//!     --safe-address 0x0aa7420c43b8c1a7b165d216948870c8ecfe1ee1,0x0aa7420c43b8c1a7b165d216948870c8ecfe1ee1,0x0aa7420c43b8c1a7b165d216948870c8ecfe1ee1,0xd057604a14982fe8d88c5fc25aac3267ea142a08,0xd057604a14982fe8d88c5fc25aac3267ea142a08 \
//!     --private-key ac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80 \
//!     --provider-url "http://localhost:8545"
//! ```
//!
//! - Manager deregisters nodes:
//! ```text
//! hopli network-registry manager-deregister \
//!     --network anvil-localhost \
//!     --contracts-root "../ethereum/contracts" \
//!     --node-address 0x9e820e68f8c024779ebcb6cd2edda1885e1dbe1f,0xb3724772badf4d8fffa186a5ca0bea87693a6c2a \
//!     --private-key ac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80 \
//!     --provider-url "http://localhost:8545"
//! ````
//!
//! - Manager syncs the eligibility of safes
//! ```text
//! hopli network-registry manager-force-sync \
//!     --network anvil-localhost \
//!     --contracts-root "../ethereum/contracts" \
//!     --safe-address 0x9e820e68f8c024779ebcb6cd2edda1885e1dbe1f,0xb3724772badf4d8fffa186a5ca0bea87693a6c2a \
//!     --eligibility true \
//!     --private-key ac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80 \
//!     --provider-url "http://localhost:8545"
//! ```
use crate::key_pair::ArgEnvReader;
use crate::{
    environment_config::NetworkProviderArgs,
    key_pair::{IdentityFileArgs, PrivateKeyArgs},
    methods::{
        deregister_nodes_from_network_registry, force_sync_safes_on_network_registry,
        register_safes_and_nodes_on_network_registry,
    },
    utils::{Cmd, HelperErrors},
};
use clap::Parser;
use ethers::types::H160;
use hopr_bindings::hopr_network_registry::HoprNetworkRegistry;
use std::str::FromStr;
use tracing::info;

/// CLI arguments for `hopli network-registry`
#[derive(Clone, Debug, Parser)]
pub enum NetworkRegistrySubcommands {
    // Register nodes and safes with a manager account
    #[command(visible_alias = "mr")]
    ManagerRegister {
        /// Network name, contracts config file root, and customized provider, if available
        #[command(flatten)]
        network_provider: NetworkProviderArgs,

        /// node addresses
        #[clap(
            help = "Comma separated node Ethereum addresses",
            long,
            short = 'o',
            default_value = None
        )]
        node_address: Option<String>,

        /// Addresses of the safe proxy instances
        #[clap(
            help = "Comma separated Safe Ethereum addresses",
            long,
            short,
            default_value = None
        )]
        safe_address: Option<String>,

        /// Arguments to locate identity file(s) of HOPR node(s)
        #[command(flatten)]
        local_identity: IdentityFileArgs,

        /// Access to the private key of a manager of Network Registry contract
        #[command(flatten)]
        private_key: PrivateKeyArgs,
    },

    /// Remove nodes and safes with a manager account
    #[command(visible_alias = "md")]
    ManagerDeregister {
        /// Network name, contracts config file root, and customized provider, if available
        #[command(flatten)]
        network_provider: NetworkProviderArgs,

        /// node addresses
        #[clap(
            help = "Comma separated node Ethereum addresses",
            long,
            short = 'o',
            default_value = None
        )]
        node_address: Option<String>,

        /// Arguments to locate identity file(s) of HOPR node(s)
        #[command(flatten)]
        local_identity: IdentityFileArgs,

        /// Access to the private key of a manager of Network Registry contract
        #[command(flatten)]
        private_key: PrivateKeyArgs,
    },

    /// Force sync the eligibility of safe accounts
    #[command(visible_alias = "ms")]
    ManagerForceSync {
        /// Network name, contracts config file root, and customized provider, if available
        #[command(flatten)]
        network_provider: NetworkProviderArgs,

        /// Addresses of the safe proxy instances
        #[clap(
            help = "Comma separated Safe Ethereum addresses",
            long,
            short,
            default_value = None
        )]
        safe_address: Option<String>,

        /// Access to the private key of a manager of Network Registry contract
        #[command(flatten)]
        private_key: PrivateKeyArgs,

        /// Eligibility of safes when calling `hopli network-registry -a manager-force-sync`
        #[clap(
            help = "Desired eligibility of safes",
            long,
            short,
            default_value = None
        )]
        eligibility: Option<bool>,
    },
}

impl NetworkRegistrySubcommands {
    /// Execute command to register a node and its staking account (safe) with manager privilege and make the safe eligible.
    ///
    /// Manager wallet registers nodes with associated staking accounts
    pub async fn execute_manager_register(
        network_provider: NetworkProviderArgs,
        local_identity: IdentityFileArgs,
        node_address: Option<String>,
        safe_address: Option<String>,
        private_key: PrivateKeyArgs,
    ) -> Result<(), HelperErrors> {
        // read all the node addresses
        let mut node_eth_addresses: Vec<H160> = Vec::new();
        if let Some(addresses) = node_address {
            node_eth_addresses.extend(
                addresses
                    .split(',')
                    .map(|addr| {
                        H160::from_str(addr)
                            .map_err(|e| HelperErrors::InvalidAddress(format!("Invalid node address: {:?}", e)))
                    })
                    .collect::<Result<Vec<_>, _>>()?,
            );
        }
        // if local identity dirs/path is provided, read addresses from identity files
        node_eth_addresses.extend(
            local_identity
                .to_addresses()
                .map_err(|e| HelperErrors::InvalidAddress(format!("Invalid node address: {:?}", e)))?
                .into_iter()
                .map(H160::from),
        );

        // read all the safe addresses
        let mut safe_eth_addresses: Vec<H160> = Vec::new();
        if let Some(addresses) = safe_address {
            safe_eth_addresses.extend(addresses.split(',').map(|addr| H160::from_str(addr).unwrap()));
        }

        // Read the private key from arguments or the "MANAGER_PRIVATE_KEY" environment variable
        let signer_private_key = private_key.read("MANAGER_PRIVATE_KEY")?;

        // get RPC provider for the given network and environment
        let rpc_provider = network_provider.get_provider_with_signer(&signer_private_key).await?;
        let contract_addresses = network_provider.get_network_details_from_name()?;

        let hopr_network_registry =
            HoprNetworkRegistry::new(contract_addresses.addresses.network_registry, rpc_provider.clone());

        // get registered safe of all the nodes
        // check if any of the node has been registered to a different address than the given safe address.
        // if the node has been registered to the given safe address, skip any action on it
        // if the node has not been registered to any safe address, register it.
        // if the node has been registered to a different safe address, remove the old safe and register the new one
        let (removed_pairs_num, added_pairs_num) =
            register_safes_and_nodes_on_network_registry(hopr_network_registry, safe_eth_addresses, node_eth_addresses)
                .await?;
        info!(
            "{:?} pairs have been removed and {:?} pairs have been added to the network registry.",
            removed_pairs_num, added_pairs_num
        );
        Ok(())
    }

    /// Execute command to deregister a node and its staking account with manager privilege
    ///
    /// This action does not need to provide safe_address
    /// Manager wallet deregisters nodes from associated staking accounts
    pub async fn execute_manager_deregister(
        network_provider: NetworkProviderArgs,
        local_identity: IdentityFileArgs,
        node_address: Option<String>,
        private_key: PrivateKeyArgs,
    ) -> Result<(), HelperErrors> {
        // read all the node addresses
        let mut node_eth_addresses: Vec<H160> = Vec::new();
        if let Some(addresses) = node_address {
            node_eth_addresses.extend(
                addresses
                    .split(',')
                    .map(|addr| {
                        H160::from_str(addr)
                            .map_err(|e| HelperErrors::InvalidAddress(format!("Invalid node address: {:?}", e)))
                    })
                    .collect::<Result<Vec<_>, _>>()?,
            );
        }
        // if local identity dirs/path is provided, read addresses from identity files
        node_eth_addresses.extend(
            local_identity
                .to_addresses()
                .map_err(|e| HelperErrors::InvalidAddress(format!("Invalid node address: {:?}", e)))?
                .into_iter()
                .map(H160::from),
        );
        info!(
            "Will deregister {:?} nodes from the network registry",
            node_eth_addresses.len()
        );

        // read private key
        let signer_private_key = private_key.read("MANAGER_PRIVATE_KEY")?;

        // get RPC provider for the given network and environment
        let rpc_provider = network_provider.get_provider_with_signer(&signer_private_key).await?;
        let contract_addresses = network_provider.get_network_details_from_name()?;

        let hopr_network_registry =
            HoprNetworkRegistry::new(contract_addresses.addresses.network_registry, rpc_provider.clone());

        // deregister all the given nodes from the network registry
        let removed_pairs_num =
            deregister_nodes_from_network_registry(hopr_network_registry, node_eth_addresses).await?;
        info!(
            "{:?} pairs have been removed from the network registry.",
            removed_pairs_num
        );
        Ok(())
    }

    /// Execute command to force sync eligibility of staking accounts with manager privilege
    ///
    /// This action does not need to provide node_address
    /// Manager wallet sync eligibility of staking accounts to a given value
    pub async fn execute_manager_force_sync(
        network_provider: NetworkProviderArgs,
        safe_address: Option<String>,
        private_key: PrivateKeyArgs,
        eligibility: Option<bool>,
    ) -> Result<(), HelperErrors> {
        // read all the safe addresses
        let mut safe_eth_addresses: Vec<H160> = Vec::new();
        if let Some(addresses) = safe_address {
            safe_eth_addresses.extend(addresses.split(',').map(|addr| H160::from_str(addr).unwrap()));
        }

        info!(
            "Will force sync {:?} safes in the network registry",
            safe_eth_addresses.len()
        );

        // read private key
        let signer_private_key = private_key.read("MANAGER_PRIVATE_KEY")?;

        // get RPC provider for the given network and environment
        let rpc_provider = network_provider.get_provider_with_signer(&signer_private_key).await?;
        let contract_addresses = network_provider.get_network_details_from_name()?;

        let hopr_network_registry =
            HoprNetworkRegistry::new(contract_addresses.addresses.network_registry, rpc_provider.clone());

        // deregister all the given nodes from the network registry
        match eligibility {
            Some(safe_eligibility) => {
                force_sync_safes_on_network_registry(
                    hopr_network_registry,
                    safe_eth_addresses.clone(),
                    vec![safe_eligibility; safe_eth_addresses.len()],
                )
                .await?;
                info!(
                    "synced the eligibility of {:?} safes in the network registry to {:?}",
                    safe_eth_addresses.len(),
                    safe_eligibility
                );
                Ok(())
            }
            None => Err(HelperErrors::MissingParameter("eligibility".to_string())),
        }
    }
}

impl Cmd for NetworkRegistrySubcommands {
    /// Run the execute_register function.
    /// By default, registration is done by manager wallet
    fn run(self) -> Result<(), HelperErrors> {
        Ok(())
    }

    async fn async_run(self) -> Result<(), HelperErrors> {
        match self {
            NetworkRegistrySubcommands::ManagerRegister {
                network_provider,
                local_identity,
                node_address,
                safe_address,
                private_key,
            } => {
                NetworkRegistrySubcommands::execute_manager_register(
                    network_provider,
                    local_identity,
                    node_address,
                    safe_address,
                    private_key,
                )
                .await?;
            }
            NetworkRegistrySubcommands::ManagerDeregister {
                network_provider,
                local_identity,
                node_address,
                private_key,
            } => {
                NetworkRegistrySubcommands::execute_manager_deregister(
                    network_provider,
                    local_identity,
                    node_address,
                    private_key,
                )
                .await?;
            }
            NetworkRegistrySubcommands::ManagerForceSync {
                network_provider,
                safe_address,
                private_key,
                eligibility,
            } => {
                NetworkRegistrySubcommands::execute_manager_force_sync(
                    network_provider,
                    safe_address,
                    private_key,
                    eligibility,
                )
                .await?;
            }
        }
        Ok(())
    }
}