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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
// Copyright (c) 2023 MASSA LABS <info@massa.net>

use crate::cmds::ExtendedWallet;
use console::style;
use erased_serde::{Serialize, Serializer};
use massa_api_exports::{
    address::AddressInfo, block::BlockInfo, datastore::DatastoreEntryOutput,
    endorsement::EndorsementInfo, execution::ExecuteReadOnlyResponse, node::NodeStatus,
    operation::OperationInfo,
};
use massa_models::composite::PubkeySig;
use massa_models::output_event::SCOutputEvent;
use massa_models::prehash::PreHashSet;
use massa_models::stats::{ConsensusStats, ExecutionStats, NetworkStats};
use massa_models::{address::Address, config::CompactConfig, operation::OperationId};
use massa_signature::{KeyPair, PublicKey};
use massa_wallet::Wallet;
use std::net::IpAddr;
use std::str;

#[macro_export]
/// Display the MASSA logo on the CLI with fancy colors
macro_rules! massa_fancy_ascii_art_logo {
    () => {
        println!(
            "{}\n{}\n{}\n{}\n{}\n",
            style("███    ███  █████  ███████ ███████  █████ ").color256(160),
            style("████  ████ ██   ██ ██      ██      ██   ██").color256(161),
            style("██ ████ ██ ███████ ███████ ███████ ███████").color256(162),
            style("██  ██  ██ ██   ██      ██      ██ ██   ██").color256(163),
            style("██      ██ ██   ██ ███████ ███████ ██   ██").color256(164)
        );
    };
}

#[macro_export]
/// bail a shinny RPC error
macro_rules! rpc_error {
    ($e:expr) => {
        bail!("check if your node is running: {}", $e)
    };
}

#[macro_export]
/// bail a shinny RPC error
macro_rules! grpc_error {
    ($e:expr) => {
        bail!("check if your node is running and grpc api enabled: {}", $e)
    };
}

#[macro_export]
/// print a yellow warning
macro_rules! client_warning {
    ($e:expr) => {
        println!("{}: {}", style("WARNING").yellow(), $e)
    };
}

pub enum Style {
    /// Any information that identifies an element
    Id,
    /// If a process is ongoing, not final, will change in the future
    Pending,
    /// If a process is finished, fixed, and won't evolve in the future
    Finished,
    /// Good things in general, success of an operation
    Good,
    /// Bad things in general, failure of an operation
    Bad,
    /// For any information that is unknown
    Unknown,
    /// Any amount of Massa coin displayed
    Coins,
    /// Any information related to the protocol, staking, peers and the consensus
    Protocol,
    /// Any information concerning a block of the blockchain
    Block,
    /// For cryptographic signature
    Signature,
    /// For any information related to the wallet, addresses or public keys
    Wallet,
    /// For any secret information
    Secret,
    /// To separate some information on the screen by barely visible characters
    Separator,
    /// When displaying a timestamp or date
    Time,
}

impl Style {
    fn style<T: ToString>(&self, msg: T) -> console::StyledObject<std::string::String> {
        style(msg.to_string()).color256(match self {
            Style::Id => 218,        // #ffafd7
            Style::Pending => 172,   // #d78700
            Style::Finished => 81,   // #5fd7ff
            Style::Good => 112,      // #87d700
            Style::Bad => 160,       // #d70000
            Style::Unknown => 248,   // #a8a8a8
            Style::Coins => 141,     // #af87ff
            Style::Protocol => 151,  // #afd7af
            Style::Block => 158,     // #afffd7
            Style::Signature => 220, // #ffd700
            Style::Wallet => 213,    // #ff87ff
            Style::Secret => 64,     // #5f8700
            Style::Separator => 239, // #4e4e4e
            Style::Time => 117,      // #87d7ff
        })
    }
}

pub trait Output: Serialize {
    fn pretty_print(&self);
}

impl dyn Output {
    pub(crate) fn stdout_json(&self) -> anyhow::Result<()> {
        let json = &mut serde_json::Serializer::new(std::io::stdout());
        let mut format: Box<dyn Serializer> = Box::new(<dyn Serializer>::erase(json));
        self.erased_serialize(&mut format)?;
        Ok(())
    }
}

impl Output for Wallet {
    fn pretty_print(&self) {
        println!("{}", self);
    }
}

impl Output for ExtendedWallet {
    fn pretty_print(&self) {
        if self.0.is_empty() {
            client_warning!("your wallet does not contain any key, use 'wallet_generate_secret_key' to generate a new key and add it to your wallet");
        }
        println!("{}", Style::Separator.style("====="));
        for entry in self.0.values() {
            if entry.show_keys {
                println!("Secret key: {}", Style::Secret.style(&entry.keypair));
                println!(
                    "Public key: {}",
                    Style::Wallet.style(entry.keypair.get_public_key())
                );
            }
            println!(
                "Address: {} (thread {}):",
                Style::Wallet.style(entry.address_info.address),
                Style::Protocol.style(entry.address_info.thread),
            );
            println!(
                "\tBalance: {}={}, {}={}",
                Style::Finished.style("final"),
                Style::Coins.style(entry.address_info.final_balance),
                Style::Pending.style("candidate"),
                Style::Coins.style(entry.address_info.candidate_balance),
            );
            println!(
                "\tRolls: {}={}, {}={}, {}={}",
                Style::Good.style("active"),
                Style::Protocol.style(entry.address_info.active_rolls),
                Style::Finished.style("final"),
                Style::Protocol.style(entry.address_info.final_rolls),
                Style::Pending.style("candidate"),
                Style::Protocol.style(entry.address_info.candidate_rolls),
            );
            println!("{}", Style::Separator.style("====="));
        }
    }
}

impl Output for Vec<(Address, PublicKey)> {
    fn pretty_print(&self) {
        match self.len() {
            1 => println!("{}", self[0].1),
            _ => {
                for address_pubkey in self {
                    println!("Address: {}", address_pubkey.0);
                    println!("Public key: {}", address_pubkey.1);
                    println!();
                }
            }
        }
    }
}

impl Output for Vec<(Address, KeyPair)> {
    fn pretty_print(&self) {
        match self.len() {
            1 => println!("{}", self[0].1),
            _ => {
                for address_seckey in self {
                    println!("Address: {}", address_seckey.0);
                    println!("Secret key: {}", address_seckey.1);
                    println!();
                }
            }
        }
    }
}

impl Output for () {
    fn pretty_print(&self) {}
}

impl Output for String {
    fn pretty_print(&self) {
        println!("{}", self);
    }
}

impl Output for &str {
    fn pretty_print(&self) {
        println!("{}", self)
    }
}

impl Output for NodeStatus {
    fn pretty_print(&self) {
        println!("Node's ID: {}", Style::Id.style(self.node_id));
        if self.node_ip.is_some() {
            println!(
                "Node's IP: {}",
                Style::Protocol.style(self.node_ip.unwrap())
            );
        } else {
            println!("{}", Style::Unknown.style("No routable IP set"));
        }
        println!();

        println!("Version: {}", Style::Id.style(self.version));
        self.config.pretty_print();
        println!();

        println!("Current time: {}", self.current_time.format_instant());
        println!(
            "Current cycle: {}",
            Style::Protocol.style(self.current_cycle)
        );
        if self.last_slot.is_some() {
            println!(
                "Last slot: {}",
                Style::Protocol.style(self.last_slot.unwrap())
            );
        }
        println!("Next slot: {}", Style::Protocol.style(self.next_slot));
        println!();

        self.consensus_stats.pretty_print();

        println!("Pool stats:");
        println!(
            "\tOperations count: {}",
            Style::Protocol.style(self.pool_stats.0)
        );
        println!(
            "\tEndorsements count: {}",
            Style::Protocol.style(self.pool_stats.1)
        );
        println!();

        self.network_stats.pretty_print();
        self.execution_stats.pretty_print();

        if !self.connected_nodes.is_empty() {
            println!("Connected nodes:");
            for (node_id, (ip_addr, is_outgoing)) in &self.connected_nodes {
                println!(
                    "Node's ID: {} / IP address: {} / {} connection",
                    Style::Id.style(node_id),
                    Style::Protocol.style(ip_addr),
                    if *is_outgoing { "Out" } else { "In" }
                )
            }
        }

        println!();
        println!("Chain id: {}", self.chain_id);
        println!("Current MIP version: {}", self.current_mip_version);
    }
}

impl Output for ExecutionStats {
    fn pretty_print(&self) {
        println!("Execution stats:");
        println!(
            "\tStart stats timespan time: {}",
            Style::Time.style(self.time_window_start.format_instant())
        );
        println!(
            "\tEnd stats timespan time: {}",
            Style::Time.style(self.time_window_end.format_instant())
        );
        println!(
            "\tFinal executed block count: {}",
            Style::Block.style(self.final_block_count)
        );
        println!(
            "\tFinal executed operation count: {}",
            Style::Protocol.style(self.final_executed_operations_count)
        );
        println!(
            "\tActive cursor: {}",
            Style::Protocol.style(self.active_cursor)
        );
        println!(
            "\tFinal cursor: {}",
            Style::Protocol.style(self.final_cursor)
        );
    }
}

impl Output for NetworkStats {
    fn pretty_print(&self) {
        println!("Network stats:");
        println!(
            "\tIn connections: {}",
            Style::Protocol.style(self.in_connection_count)
        );
        println!(
            "\tOut connections: {}",
            Style::Protocol.style(self.out_connection_count)
        );
        println!(
            "\tKnown peers: {}",
            Style::Protocol.style(self.known_peer_count)
        );
        println!(
            "\tBanned peers: {}",
            Style::Bad.style(self.banned_peer_count)
        );
        println!(
            "\tActive nodes: {}",
            Style::Good.style(self.active_node_count)
        );
    }
}

impl Output for CompactConfig {
    fn pretty_print(&self) {
        println!("Config:");
        println!(
            "\tGenesis time: {}",
            Style::Time.style(self.genesis_timestamp.format_instant())
        );
        if let Some(end) = self.end_timestamp {
            println!("\tEnd time: {}", Style::Time.style(end.format_instant()));
        }
        println!(
            "\tThread count: {}",
            Style::Protocol.style(self.thread_count)
        );
        println!("\tt0: {}", Style::Time.style(self.t0));
        println!("\tdelta_f0: {}", Style::Protocol.style(self.delta_f0));
        println!(
            "\tOperation validity periods: {}",
            Style::Protocol.style(self.operation_validity_periods)
        );
        println!(
            "\tPeriods per cycle: {}",
            Style::Protocol.style(self.periods_per_cycle)
        );
        println!("\tBlock reward: {}", Style::Coins.style(self.block_reward));
        println!("\tRoll price: {}", Style::Coins.style(self.roll_price));
        println!(
            "\tMax block size (in bytes): {}",
            Style::Block.style(self.max_block_size)
        );
    }
}

impl Output for ConsensusStats {
    fn pretty_print(&self) {
        println!("Consensus stats:");
        println!(
            "\tStart stats timespan time: {}",
            Style::Time.style(self.start_timespan.format_instant())
        );
        println!(
            "\tEnd stats timespan time: {}",
            Style::Time.style(self.end_timespan.format_instant())
        );
        println!(
            "\tFinal block count: {}",
            Style::Block.style(self.final_block_count)
        );
        println!(
            "\tStale block count: {}",
            Style::Block.style(self.stale_block_count)
        );
        println!(
            "\tClique count: {}",
            Style::Protocol.style(self.clique_count)
        );
    }
}

impl Output for BlockInfo {
    fn pretty_print(&self) {
        println!("{}", self);
    }
}

impl Output for PreHashSet<Address> {
    fn pretty_print(&self) {
        println!(
            "{}",
            self.iter()
                .fold("".to_string(), |acc, a| format!("{}{}\n", acc, a))
        )
    }
}

impl Output for Vec<AddressInfo> {
    fn pretty_print(&self) {
        for info in self {
            println!("{}", Style::Separator.style("========"));
            println!(
                "Address {} (thread {}):",
                Style::Wallet.style(info.address),
                Style::Protocol.style(info.thread),
            );
            println!(
                "\tBalance: {}={}, {}={}",
                Style::Finished.style("final"),
                Style::Coins.style(info.final_balance),
                Style::Pending.style("candidate"),
                Style::Coins.style(info.candidate_balance),
            );
            println!(
                "\tRolls: {}={}, {}={}",
                Style::Finished.style("final"),
                Style::Protocol.style(info.final_roll_count),
                Style::Pending.style("candidate"),
                Style::Protocol.style(info.candidate_roll_count),
            );

            print!("\tLocked coins:");
            if info.deferred_credits.is_empty() {
                println!(" {}", Style::Coins.style("0"));
            } else {
                println!();
                for slot_amount in &info.deferred_credits {
                    println!(
                        "\t\t{} locked coins will be unlocked at slot {}",
                        Style::Coins.style(slot_amount.amount),
                        Style::Protocol.style(slot_amount.slot),
                    );
                }
            }
            if !info.cycle_infos.is_empty() {
                println!("\tCycle infos:");
            }
            for cycle_info in &info.cycle_infos {
                println!(
                    "\t\tCycle {} ({}): produced {} and missed {} blocks{}",
                    Style::Protocol.style(cycle_info.cycle),
                    if cycle_info.is_final {
                        Style::Finished.style("final")
                    } else {
                        Style::Pending.style("candidate")
                    },
                    Style::Good.style(cycle_info.ok_count),
                    Style::Bad.style(cycle_info.nok_count),
                    match cycle_info.active_rolls {
                        Some(rolls) => format!(" with {} active rolls", Style::Good.style(rolls)),
                        None => "".into(),
                    },
                );
            }
        }
    }
}

impl Output for Vec<DatastoreEntryOutput> {
    fn pretty_print(&self) {
        for data_entry in self {
            println!("{}", data_entry);
        }
    }
}

impl Output for Vec<EndorsementInfo> {
    fn pretty_print(&self) {
        for endorsement_info in self {
            println!("{}", endorsement_info);
        }
    }
}

impl Output for Vec<IpAddr> {
    fn pretty_print(&self) {
        for ips in self {
            println!("{}", ips);
        }
    }
}

impl Output for Vec<OperationInfo> {
    fn pretty_print(&self) {
        for info in self {
            println!("{}", style("==========").color256(237));
            print!("Operation {}", Style::Id.style(info.id));
            if info.in_pool {
                print!(", {}", Style::Pending.style("in pool"));
            }
            if let Some(f) = info.is_operation_final {
                print!(
                    ", operation is {}",
                    if f {
                        Style::Finished.style("final")
                    } else {
                        Style::Pending.style("not final")
                    }
                );
            } else {
                print!(", finality {}", Style::Unknown.style("unknown"));
            }
            println!(
                ", {}",
                match info.op_exec_status {
                    Some(true) => Style::Good.style("success"),
                    Some(false) => Style::Bad.style("failed"),
                    None => Style::Unknown.style("unknown status"),
                }
            );
            if info.in_blocks.is_empty() {
                println!("{}", Style::Block.style("Not in any blocks"));
            } else {
                println!("In blocks:");
                for bid in info.in_blocks.iter() {
                    println!("\t- {}", Style::Block.style(bid));
                }
            }
            println!(
                "Signature: {}",
                Style::Signature.style(info.operation.signature)
            );
            println!(
                "Creator pubkey: {}",
                Style::Wallet.style(info.operation.content_creator_pub_key)
            );
            println!(
                "Creator address: {}",
                Style::Wallet.style(info.operation.content_creator_address)
            );
            println!("Fee: {}", Style::Coins.style(info.operation.content.fee));
            println!(
                "Expire period: {}",
                Style::Pending.style(info.operation.content.expire_period)
            );
            println!(
                "Operation type: {}",
                Style::Id.style(&info.operation.content.op)
            );
        }
    }
}

impl Output for Vec<BlockInfo> {
    fn pretty_print(&self) {
        for block_info in self {
            println!("{}", block_info);
        }
    }
}

impl Output for Vec<OperationId> {
    fn pretty_print(&self) {
        for operation_id in self {
            println!("{}", operation_id);
        }
    }
}

impl Output for Vec<Address> {
    fn pretty_print(&self) {
        for addr in self {
            println!("{}", addr);
        }
    }
}

impl Output for Vec<SCOutputEvent> {
    fn pretty_print(&self) {
        for addr in self {
            println!("{}", addr);
        }
    }
}

impl Output for PubkeySig {
    fn pretty_print(&self) {
        println!("{}", self);
    }
}

impl Output for ExecuteReadOnlyResponse {
    fn pretty_print(&self) {
        println!("{}", self);
    }
}