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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
// Copyright (c) 2023 MASSA LABS <info@massa.net>

use std::net::IpAddr;
use std::str::FromStr;

use crate::error::GrpcError;
use crate::server::MassaPrivateGrpc;
use massa_execution_exports::ExecutionQueryRequest;
use massa_hash::Hash;
use massa_models::config::CompactConfig;
use massa_models::node::NodeId;
use massa_models::slot::Slot;
use massa_models::timeslots::get_latest_block_slot_at_timestamp;
use massa_proto_rs::massa::api::v1 as grpc_api;
use massa_proto_rs::massa::model::v1 as grpc_model;
use massa_protocol_exports::{PeerConnectionType, PeerId};
use massa_signature::KeyPair;
use massa_time::MassaTime;
use tracing::warn;
// use massa_proto_rs::massa::model::v1 "add_to_bootstrap_blacklist"as grpc_model;

/// Add IP addresses to node bootstrap blacklist
pub(crate) fn add_to_bootstrap_blacklist(
    grpc: &MassaPrivateGrpc,
    request: tonic::Request<grpc_api::AddToBootstrapBlacklistRequest>,
) -> Result<grpc_api::AddToBootstrapBlacklistResponse, GrpcError> {
    let inner_req = request.into_inner();

    let ips = inner_req
        .ips
        .into_iter()
        .filter_map(|ip| match IpAddr::from_str(&ip) {
            Ok(ip_addr) => Some(ip_addr),
            Err(e) => {
                warn!("error when parsing address : {}", e);
                None
            }
        })
        .collect();

    if let Some(bs_list) = &grpc.bs_white_black_list {
        if let Err(e) = bs_list.add_ips_to_blacklist(ips) {
            warn!("error when adding ips to bootstrap blacklist : {}", e)
        }
    }

    Ok(grpc_api::AddToBootstrapBlacklistResponse {})
}
/// Add IP addresses to node bootstrap whitelist
pub(crate) fn add_to_bootstrap_whitelist(
    grpc: &MassaPrivateGrpc,
    request: tonic::Request<grpc_api::AddToBootstrapWhitelistRequest>,
) -> Result<grpc_api::AddToBootstrapWhitelistResponse, GrpcError> {
    let inner_req = request.into_inner();

    let ips = inner_req
        .ips
        .into_iter()
        .filter_map(|ip| match IpAddr::from_str(&ip) {
            Ok(ip_addr) => Some(ip_addr),
            Err(e) => {
                warn!("error when parsing address : {}", e);
                None
            }
        })
        .collect();

    if let Some(bs_list) = &grpc.bs_white_black_list {
        if let Err(e) = bs_list.add_ips_to_whitelist(ips) {
            warn!("error when adding ips to bootstrap whitelist : {}", e)
        }
    }

    Ok(grpc_api::AddToBootstrapWhitelistResponse {})
}
/// Add IP addresses to node peers whitelist. No confirmation to expect.
/// Note: If the ip was unknown it adds it to the known peers, otherwise it updates the peer type
pub(crate) fn add_to_peers_whitelist(
    _grpc: &MassaPrivateGrpc,
    _request: tonic::Request<grpc_api::AddToPeersWhitelistRequest>,
) -> Result<grpc_api::AddToPeersWhitelistResponse, GrpcError> {
    Err(GrpcError::Unimplemented(
        "add_to_peers_whitelist".to_string(),
    ))
}
/// Add staking secret keys to wallet
pub(crate) fn add_staking_secret_keys(
    grpc: &MassaPrivateGrpc,
    request: tonic::Request<grpc_api::AddStakingSecretKeysRequest>,
) -> Result<grpc_api::AddStakingSecretKeysResponse, GrpcError> {
    let secret_keys = request.into_inner().secret_keys;

    if secret_keys.is_empty() {
        return Err(GrpcError::InvalidArgument(
            "no secret key received".to_string(),
        ));
    }

    if secret_keys.len() as u64 > grpc.grpc_config.max_arguments {
        return Err(GrpcError::InvalidArgument(format!(
            "too many secret keys received. Only a maximum of {} secret keys are accepted per request",
            grpc.grpc_config.max_arguments
        )));
    }

    let keypairs = match secret_keys.iter().map(|x| KeyPair::from_str(x)).collect() {
        Ok(keypairs) => keypairs,
        Err(e) => return Err(GrpcError::InvalidArgument(e.to_string())),
    };

    grpc.node_wallet.write().add_keypairs(keypairs)?;

    Ok(grpc_api::AddStakingSecretKeysResponse {})
}

/// Ban multiple nodes by their individual ids
pub(crate) fn ban_nodes_by_ids(
    grpc: &MassaPrivateGrpc,
    request: tonic::Request<grpc_api::BanNodesByIdsRequest>,
) -> Result<grpc_api::BanNodesByIdsResponse, GrpcError> {
    let node_ids = request.into_inner().node_ids;

    if node_ids.is_empty() {
        return Err(GrpcError::InvalidArgument(
            "no node id received".to_string(),
        ));
    }

    if node_ids.len() as u64 > grpc.grpc_config.max_arguments {
        return Err(GrpcError::InvalidArgument(format!(
            "too many node ids received. Only a maximum of {} node ids are accepted per request",
            grpc.grpc_config.max_arguments
        )));
    }

    //TODO: Change when unify node id and peer id
    let peer_ids = node_ids
        .into_iter()
        .map(|id| {
            NodeId::from_str(&id).map(|node_id| PeerId::from_public_key(node_id.get_public_key()))
        })
        .collect::<Result<Vec<_>, _>>()?;

    grpc.protocol_controller.ban_peers(peer_ids)?;

    Ok(grpc_api::BanNodesByIdsResponse {})
}

/// Ban multiple nodes by their individual IP addresses
pub(crate) fn ban_nodes_by_ips(
    _grpc: &MassaPrivateGrpc,
    _request: tonic::Request<grpc_api::BanNodesByIpsRequest>,
) -> Result<grpc_api::BanNodesByIpsResponse, GrpcError> {
    Err(GrpcError::Unimplemented("ban_nodes_by_ips".to_string()))
}

/// Get node bootstrap blacklist IP addresses
pub(crate) fn get_bootstrap_blacklist(
    grpc: &MassaPrivateGrpc,
    _request: tonic::Request<grpc_api::GetBootstrapBlacklistRequest>,
) -> Result<grpc_api::GetBootstrapBlacklistResponse, GrpcError> {
    let list = {
        match grpc.bs_white_black_list {
            Some(ref bs_list) => bs_list
                .get_black_list()
                .unwrap_or_default()
                .into_iter()
                .map(|ip| ip.to_string())
                .collect(),
            None => Vec::new(),
        }
    };
    Ok(grpc_api::GetBootstrapBlacklistResponse { ips: list })
}
/// Get node bootstrap whitelist IP addresses
pub(crate) fn get_bootstrap_whitelist(
    grpc: &MassaPrivateGrpc,
    _request: tonic::Request<grpc_api::GetBootstrapWhitelistRequest>,
) -> Result<grpc_api::GetBootstrapWhitelistResponse, GrpcError> {
    let list = {
        match grpc.bs_white_black_list {
            Some(ref bs_list) => bs_list
                .get_white_list()
                .unwrap_or_default()
                .into_iter()
                .map(|ip| ip.to_string())
                .collect(),
            None => Vec::new(),
        }
    };

    Ok(grpc_api::GetBootstrapWhitelistResponse { ips: list })
}
// Get MIP store dump
pub(crate) fn get_mip_status(
    grpc: &MassaPrivateGrpc,
    _request: tonic::Request<grpc_api::GetMipStatusRequest>,
) -> Result<grpc_api::GetMipStatusResponse, GrpcError> {
    let mip_store_status_ = grpc.mip_store.get_mip_status();
    let mip_store_status: Result<Vec<grpc_model::MipStatusEntry>, GrpcError> = mip_store_status_
        .iter()
        .map(|(mip_info, state_id_)| {
            let state_id = grpc_model::ComponentStateId::from(state_id_);
            Ok(grpc_model::MipStatusEntry {
                mip_info: Some(grpc_model::MipInfo::from(mip_info)),
                state_id: i32::from(state_id),
            })
        })
        .collect();

    Ok(grpc_api::GetMipStatusResponse {
        mipstatus_entries: mip_store_status?,
    })
}

/// Allow everyone to bootstrap from the node by removing bootstrap whitelist configuration file
pub(crate) fn allow_everyone_to_bootstrap(
    _grpc: &MassaPrivateGrpc,
    _request: tonic::Request<grpc_api::AllowEveryoneToBootstrapRequest>,
) -> Result<grpc_api::AllowEveryoneToBootstrapResponse, GrpcError> {
    Err(GrpcError::Unimplemented(
        "allow_everyone_to_bootstrap".to_string(),
    ))
}
/// Get node status
pub(crate) fn get_node_status(
    grpc: &MassaPrivateGrpc,
    _request: tonic::Request<grpc_api::GetNodeStatusRequest>,
) -> Result<grpc_api::GetNodeStatusResponse, GrpcError> {
    let config = CompactConfig::default();
    let now = MassaTime::now();
    let last_slot = get_latest_block_slot_at_timestamp(
        grpc.grpc_config.thread_count,
        grpc.grpc_config.t0,
        grpc.grpc_config.genesis_timestamp,
        now,
    )?;
    let execution_stats = grpc.execution_controller.get_stats();
    let consensus_stats = grpc.consensus_controller.get_stats()?;
    let (network_stats, peers) = grpc.protocol_controller.get_stats()?;
    let pool_stats = grpc_model::PoolStats {
        operations_count: grpc.pool_controller.get_denunciation_count() as u64,
        endorsements_count: grpc.pool_controller.get_endorsement_count() as u64,
    };

    let mut connected_nodes = peers
        .iter()
        .map(|(id, peer)| {
            let connection_type = match peer.1 {
                PeerConnectionType::IN => grpc_model::ConnectionType::Incoming,
                PeerConnectionType::OUT => grpc_model::ConnectionType::Outgoing,
            };

            grpc_model::ConnectedNode {
                node_id: NodeId::new(id.get_public_key()).to_string(),
                node_ip: peer.0.ip().to_string(),
                connection_type: connection_type as i32,
            }
        })
        .collect::<Vec<_>>();
    connected_nodes.sort_by(|a, b| a.node_ip.cmp(&b.node_ip));

    let current_cycle = last_slot
        .unwrap_or_else(|| Slot::new(0, 0))
        .get_cycle(grpc.grpc_config.periods_per_cycle);
    let cycle_duration = grpc
        .grpc_config
        .t0
        .checked_mul(grpc.grpc_config.periods_per_cycle)?;
    let current_cycle_time = if current_cycle == 0 {
        grpc.grpc_config.genesis_timestamp
    } else {
        cycle_duration
            .checked_mul(current_cycle)
            .and_then(|elapsed_time_before_current_cycle| {
                grpc.grpc_config
                    .genesis_timestamp
                    .checked_add(elapsed_time_before_current_cycle)
            })?
    };
    let next_cycle_time = current_cycle_time.checked_add(cycle_duration)?;
    let empty_request = ExecutionQueryRequest { requests: vec![] };
    let state = grpc.execution_controller.query_state(empty_request);
    let node_ip = grpc
        .protocol_config
        .routable_ip
        .map(|ip| ip.to_string())
        .unwrap_or_default();

    let status = grpc_model::NodeStatus {
        node_id: grpc.node_id.to_string(),
        node_ip,
        version: grpc.version.to_string(),
        current_time: Some(now.into()),
        current_cycle,
        current_cycle_time: Some(current_cycle_time.into()),
        next_cycle_time: Some(next_cycle_time.into()),
        connected_nodes,
        last_executed_final_slot: Some(state.final_cursor.into()),
        last_executed_speculative_slot: Some(state.candidate_cursor.into()),
        final_state_fingerprint: state.final_state_fingerprint.to_string(),
        consensus_stats: Some(consensus_stats.into()),
        pool_stats: Some(pool_stats),
        network_stats: Some(network_stats.into()),
        execution_stats: Some(execution_stats.into()),
        config: Some(config.into()),
        chain_id: grpc.grpc_config.chain_id,
    };

    Ok(grpc_api::GetNodeStatusResponse {
        status: Some(status),
    })
}
/// Get node peers whitelist IP addresses
pub(crate) fn get_peers_whitelist(
    _grpc: &MassaPrivateGrpc,
    _request: tonic::Request<grpc_api::GetPeersWhitelistRequest>,
) -> Result<grpc_api::GetPeersWhitelistResponse, GrpcError> {
    Err(GrpcError::Unimplemented("get_peers_whitelist".to_string()))
}
/// Remove from bootstrap blacklist given IP addresses
pub(crate) fn remove_from_bootstrap_blacklist(
    grpc: &MassaPrivateGrpc,
    request: tonic::Request<grpc_api::RemoveFromBootstrapBlacklistRequest>,
) -> Result<grpc_api::RemoveFromBootstrapBlacklistResponse, GrpcError> {
    let inner_req = request.into_inner();
    let ips = inner_req
        .ips
        .into_iter()
        .filter_map(|ip| match IpAddr::from_str(&ip) {
            Ok(ip_addr) => Some(ip_addr),
            Err(e) => {
                warn!("error when parsing address : {}", e);
                None
            }
        })
        .collect();

    if let Some(bs_list) = &grpc.bs_white_black_list {
        if let Err(e) = bs_list.remove_ips_from_blacklist(ips) {
            warn!("error when removing ips to bootstrap blacklist : {}", e)
        }
    }

    Ok(grpc_api::RemoveFromBootstrapBlacklistResponse {})
}
/// Remove from bootstrap whitelist given IP addresses
pub(crate) fn remove_from_bootstrap_whitelist(
    grpc: &MassaPrivateGrpc,
    request: tonic::Request<grpc_api::RemoveFromBootstrapWhitelistRequest>,
) -> Result<grpc_api::RemoveFromBootstrapWhitelistResponse, GrpcError> {
    let inner_req = request.into_inner();
    let ips = inner_req
        .ips
        .into_iter()
        .filter_map(|ip| match IpAddr::from_str(&ip) {
            Ok(ip_addr) => Some(ip_addr),
            Err(e) => {
                warn!("error when parsing address : {}", e);
                None
            }
        })
        .collect();

    if let Some(bs_list) = &grpc.bs_white_black_list {
        if let Err(e) = bs_list.remove_ips_from_whitelist(ips) {
            warn!("error when removing ips to bootstrap whitelist : {}", e)
        }
    }

    Ok(grpc_api::RemoveFromBootstrapWhitelistResponse {})
}
/// Remove from peers whitelist given IP addresses
pub(crate) fn remove_from_peers_whitelist(
    _grpc: &MassaPrivateGrpc,
    _request: tonic::Request<grpc_api::RemoveFromPeersWhitelistRequest>,
) -> Result<grpc_api::RemoveFromPeersWhitelistResponse, GrpcError> {
    Err(GrpcError::Unimplemented(
        "remove_from_peers_whitelist".to_string(),
    ))
}
/// Remove addresses from staking
pub(crate) fn remove_staking_addresses(
    _grpc: &MassaPrivateGrpc,
    _request: tonic::Request<grpc_api::RemoveStakingAddressesRequest>,
) -> Result<grpc_api::RemoveStakingAddressesResponse, GrpcError> {
    Err(GrpcError::Unimplemented(
        "remove_staking_addresses".to_string(),
    ))
}
/// Sign messages with node's key
pub(crate) fn sign_messages(
    grpc: &MassaPrivateGrpc,
    request: tonic::Request<grpc_api::SignMessagesRequest>,
) -> Result<grpc_api::SignMessagesResponse, GrpcError> {
    let messages = request.into_inner().messages;

    if messages.is_empty() {
        return Err(GrpcError::InvalidArgument(
            "no message received".to_string(),
        ));
    }

    if messages.len() as u64 > grpc.grpc_config.max_arguments {
        return Err(GrpcError::InvalidArgument(format!(
            "too many messages received. Only a maximum of {} messages are accepted per request",
            grpc.grpc_config.max_arguments
        )));
    }

    let keypair = grpc.grpc_config.keypair.clone();
    let signatures = messages
        .into_iter()
        .map(|message| {
            keypair
                .sign(&Hash::compute_from(&message))
                .map(|signature| signature.to_string())
        })
        .collect::<Result<Vec<_>, _>>()?;

    Ok(grpc_api::SignMessagesResponse {
        public_key: keypair.get_public_key().to_string(),
        signatures,
    })
}
/// Shutdown the node gracefully
pub(crate) fn shutdown_gracefully(
    _grpc: &MassaPrivateGrpc,
    _request: tonic::Request<grpc_api::ShutdownGracefullyRequest>,
) -> Result<grpc_api::ShutdownGracefullyResponse, GrpcError> {
    Err(GrpcError::Unimplemented("shutdown_gracefully".to_string()))
}

/// Unban multiple nodes by their individual ids
pub(crate) fn unban_nodes_by_ids(
    grpc: &MassaPrivateGrpc,
    request: tonic::Request<grpc_api::UnbanNodesByIdsRequest>,
) -> Result<grpc_api::UnbanNodesByIdsResponse, GrpcError> {
    let node_ids = request.into_inner().node_ids;

    if node_ids.is_empty() {
        return Err(GrpcError::InvalidArgument(
            "no node id received".to_string(),
        ));
    }

    if node_ids.len() as u64 > grpc.grpc_config.max_arguments {
        return Err(GrpcError::InvalidArgument(format!(
            "too many node ids received. Only a maximum of {} node ids are accepted per request",
            grpc.grpc_config.max_arguments
        )));
    }

    //TODO: Change when unify node id and peer id
    let peer_ids = node_ids
        .into_iter()
        .map(|id| {
            NodeId::from_str(&id).map(|node_id| PeerId::from_public_key(node_id.get_public_key()))
        })
        .collect::<Result<Vec<_>, _>>()?;

    grpc.protocol_controller.unban_peers(peer_ids)?;

    Ok(grpc_api::UnbanNodesByIdsResponse {})
}

/// Unban multiple nodes by their individual IP addresses
pub(crate) fn unban_nodes_by_ips(
    _grpc: &MassaPrivateGrpc,
    _request: tonic::Request<grpc_api::UnbanNodesByIpsRequest>,
) -> Result<grpc_api::UnbanNodesByIpsResponse, GrpcError> {
    Err(GrpcError::Unimplemented("unban_nodes_by_ips".to_string()))
}