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
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
// Copyright 2019 The Exonum Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#![allow(missing_debug_implementations)]

//! This module implement all core commands.
// spell-checker:ignore exts, rsplitn

use std::{
    collections::{BTreeMap, HashMap},
    fs,
    net::{IpAddr, SocketAddr},
    path::{Path, PathBuf},
};

use super::{
    super::path_relative_from,
    internal::{CollectedCommand, Command, Feedback},
    keys,
    password::{PassInputMethod, SecretKeyType},
    shared::{
        AbstractConfig, CommonConfigTemplate, NodePrivateConfig, NodePublicConfig, NodeRunConfig,
        SharedConfig,
    },
    Argument, CommandName, Context, DEFAULT_EXONUM_LISTEN_PORT,
};
use crate::api::backends::actix::AllowOrigin;
use crate::blockchain::{config::ValidatorKeys, GenesisConfig};
use crate::crypto::{generate_keys_file, PublicKey};
use crate::helpers::{config::ConfigFile, ZeroizeOnDrop};
use crate::node::{ConnectListConfig, NodeApiConfig, NodeConfig};
use crate::storage::{Database, DbOptions, RocksDB};

const DATABASE_PATH: &str = "DATABASE_PATH";
const PEER_ADDRESS: &str = "PEER_ADDRESS";
const LISTEN_ADDRESS: &str = "LISTEN_ADDRESS";
const NODE_CONFIG_PATH: &str = "NODE_CONFIG_PATH";
const PUBLIC_API_ADDRESS: &str = "PUBLIC_API_ADDRESS";
const PRIVATE_API_ADDRESS: &str = "PRIVATE_API_ADDRESS";
const PUBLIC_ALLOW_ORIGIN: &str = "PUBLIC_ALLOW_ORIGIN";
const PRIVATE_ALLOW_ORIGIN: &str = "PRIVATE_ALLOW_ORIGIN";
const CONSENSUS_KEY_PATH: &str = "CONSENSUS_KEY_PATH";
const SERVICE_KEY_PATH: &str = "SERVICE_KEY_PATH";
const NO_PASSWORD: &str = "NO_PASSWORD";
const CONSENSUS_KEY_PASS_METHOD: &str = "CONSENSUS_KEY_PASS_METHOD";
const SERVICE_KEY_PASS_METHOD: &str = "SERVICE_KEY_PASS_METHOD";

/// Run command.
pub struct Run;

impl Run {
    /// Returns created database instance.
    pub fn db_helper(ctx: &Context, options: &DbOptions) -> Box<dyn Database> {
        let path = ctx
            .arg::<String>(DATABASE_PATH)
            .unwrap_or_else(|_| panic!("{} not found.", DATABASE_PATH));
        Box::new(RocksDB::open(Path::new(&path), options).expect("Can't load database file"))
    }

    fn node_config_path(ctx: &Context) -> String {
        ctx.arg::<String>(NODE_CONFIG_PATH)
            .unwrap_or_else(|_| panic!("{} not found.", NODE_CONFIG_PATH))
    }

    fn node_config(path: String) -> NodeConfig<PathBuf> {
        ConfigFile::load(path).expect("Can't load node config file")
    }

    fn public_api_address(ctx: &Context) -> Option<SocketAddr> {
        ctx.arg(PUBLIC_API_ADDRESS).ok()
    }

    fn private_api_address(ctx: &Context) -> Option<SocketAddr> {
        ctx.arg(PRIVATE_API_ADDRESS).ok()
    }

    fn pass_input_method(ctx: &Context, key_type: SecretKeyType) -> String {
        let arg_key = match key_type {
            SecretKeyType::Consensus => CONSENSUS_KEY_PASS_METHOD,
            SecretKeyType::Service => SERVICE_KEY_PASS_METHOD,
        };
        ctx.arg(arg_key).unwrap_or_default()
    }
}

impl Command for Run {
    fn args(&self) -> Vec<Argument> {
        vec![
            Argument::new_named(
                NODE_CONFIG_PATH,
                true,
                "Path to node configuration file.",
                "c",
                "node-config",
                false,
            ),
            Argument::new_named(
                DATABASE_PATH,
                true,
                "Use database with the given path.",
                "d",
                "db-path",
                false,
            ),
            Argument::new_named(
                PUBLIC_API_ADDRESS,
                false,
                "Listen address for public api.",
                None,
                "public-api-address",
                false,
            ),
            Argument::new_named(
                PRIVATE_API_ADDRESS,
                false,
                "Listen address for private api.",
                None,
                "private-api-address",
                false,
            ),
            Argument::new_named(
                CONSENSUS_KEY_PASS_METHOD,
                false,
                "Passphrase entry method for consensus key.\n\
                 Possible values are: stdin, env{:ENV_VAR_NAME}, pass:PASSWORD (default: stdin)\n\
                 If ENV_VAR_NAME is not specified $EXONUM_CONSENSUS_PASS is used",
                None,
                "consensus-key-pass",
                false,
            ),
            Argument::new_named(
                SERVICE_KEY_PASS_METHOD,
                false,
                "Passphrase entry method for service key.\n\
                 Possible values are: stdin, env{:ENV_VAR_NAME}, pass:PASSWORD (default: stdin)\n\
                 If ENV_VAR_NAME is not specified $EXONUM_SERVICE_PASS is used",
                None,
                "service-key-pass",
                false,
            ),
        ]
    }

    fn name(&self) -> CommandName {
        "run"
    }

    fn about(&self) -> &str {
        "Run application"
    }

    fn execute(
        &self,
        _commands: &HashMap<CommandName, CollectedCommand>,
        mut context: Context,
        exts: &dyn Fn(Context) -> Context,
    ) -> Feedback {
        let config_path = Self::node_config_path(&context);

        let config = Self::node_config(config_path.clone());
        let public_addr = Self::public_api_address(&context);
        let private_addr = Self::private_api_address(&context);

        context.set(keys::NODE_CONFIG, config);
        context.set(keys::NODE_CONFIG_PATH, config_path);
        let mut new_context = exts(context);
        let mut config = new_context
            .get(keys::NODE_CONFIG)
            .expect("cant load node_config");
        // Override api options
        if let Some(public_addr) = public_addr {
            config.api.public_api_address = Some(public_addr);
        }

        if let Some(private_api_address) = private_addr {
            config.api.private_api_address = Some(private_api_address);
        }

        new_context.set(keys::NODE_CONFIG, config);

        let run_config = {
            let consensus_pass_method =
                Run::pass_input_method(&new_context, SecretKeyType::Consensus);
            let service_pass_method = Run::pass_input_method(&new_context, SecretKeyType::Service);
            NodeRunConfig {
                consensus_pass_method,
                service_pass_method,
            }
        };
        new_context.set(keys::RUN_CONFIG, run_config);

        Feedback::RunNode(new_context)
    }
}

/// Command for running service in dev mode.
pub struct RunDev;

impl RunDev {
    fn artifacts_directory(ctx: &Context) -> PathBuf {
        let directory = ctx
            .arg::<String>("ARTIFACTS_DIR")
            .unwrap_or_else(|_| ".exonum".into());
        PathBuf::from(&directory)
    }

    fn artifacts_path(inner_path: &str, ctx: &Context) -> String {
        let mut path = Self::artifacts_directory(ctx);
        path.push(inner_path);
        path.to_str().expect("Expected correct path").into()
    }

    fn set_config_command_arguments(ctx: &mut Context) {
        let common_config_path = Self::artifacts_path("common.toml", &ctx);
        let validators_count = "1";
        let peer_addr = "127.0.0.1";
        let pub_config_path = Self::artifacts_path("public.toml", &ctx);
        let sec_config_path = Self::artifacts_path("secret.toml", &ctx);
        let output_config_path = Self::artifacts_path("output.toml", &ctx);
        let consensus_key_path = Self::artifacts_path("consensus.toml", &ctx);
        let service_key_path = Self::artifacts_path("service.toml", &ctx);

        // Arguments for common config command.
        ctx.set_arg("COMMON_CONFIG", common_config_path.clone());
        ctx.set_arg("VALIDATORS_COUNT", validators_count.into());

        // Arguments for node config command.
        ctx.set_arg("COMMON_CONFIG", common_config_path.clone());
        ctx.set_arg("PUB_CONFIG", pub_config_path.clone());
        ctx.set_arg("SEC_CONFIG", sec_config_path.clone());
        ctx.set_arg(PEER_ADDRESS, peer_addr.into());
        ctx.set_arg(CONSENSUS_KEY_PATH, consensus_key_path);
        ctx.set_arg(SERVICE_KEY_PATH, service_key_path);
        ctx.set_flag_occurrences(NO_PASSWORD, 1);

        // Arguments for finalize config command.
        ctx.set_arg_multiple("PUBLIC_CONFIGS", vec![pub_config_path.clone()]);
        ctx.set_arg(PUBLIC_API_ADDRESS, "127.0.0.1:8080".to_string());
        ctx.set_arg(PRIVATE_API_ADDRESS, "127.0.0.1:8081".to_string());
        ctx.set_arg(
            PUBLIC_ALLOW_ORIGIN,
            "http://127.0.0.1, http://localhost".to_string(),
        );
        ctx.set_arg(
            PRIVATE_ALLOW_ORIGIN,
            "http://127.0.0.1, http://localhost".to_string(),
        );
        ctx.set_arg("SECRET_CONFIG", sec_config_path.clone());
        ctx.set_arg("OUTPUT_CONFIG_PATH", output_config_path.clone());

        // Arguments for run command.
        ctx.set_arg(NODE_CONFIG_PATH, output_config_path.clone());
        ctx.set_arg(CONSENSUS_KEY_PASS_METHOD, "pass:".to_owned());
        ctx.set_arg(SERVICE_KEY_PASS_METHOD, "pass:".to_owned());
    }

    fn generate_config(commands: &HashMap<CommandName, CollectedCommand>, ctx: Context) -> Context {
        let common_config_command = commands
            .get(GenerateCommonConfig.name())
            .expect("Expected GenerateCommonConfig in the commands list.");
        common_config_command.execute(commands, ctx.clone());

        let node_config_command = commands
            .get(GenerateNodeConfig.name())
            .expect("Expected GenerateNodeConfig in the commands list.");
        node_config_command.execute(commands, ctx.clone());

        let finalize_command = commands
            .get(Finalize.name())
            .expect("Expected Finalize in the commands list.");
        finalize_command.execute(commands, ctx.clone());

        ctx
    }

    fn cleanup(ctx: &Context) {
        let database_dir_path = ctx
            .arg::<String>(DATABASE_PATH)
            .expect("Expected DATABASE_PATH being set.");
        let database_dir = Path::new(&database_dir_path);
        if database_dir.exists() {
            fs::remove_dir_all(Self::artifacts_directory(ctx))
                .expect("Expected DATABASE_PATH folder being removable.");
        }
    }
}

impl Command for RunDev {
    fn args(&self) -> Vec<Argument> {
        vec![Argument::new_named(
            "ARTIFACTS_DIR",
            false,
            "The path where configuration and db files will be generated.",
            "a",
            "artifacts-dir",
            false,
        )]
    }

    fn name(&self) -> CommandName {
        "run-dev"
    }

    fn about(&self) -> &str {
        "Run application in development mode (generate configuration and db files automatically)"
    }

    fn execute(
        &self,
        commands: &HashMap<CommandName, CollectedCommand>,
        mut context: Context,
        exts: &dyn Fn(Context) -> Context,
    ) -> Feedback {
        let db_path = Self::artifacts_path("db", &context);
        context.set_arg(DATABASE_PATH, db_path);
        Self::cleanup(&context);

        Self::set_config_command_arguments(&mut context);
        let context = exts(context);
        let context = Self::generate_config(commands, context);

        commands
            .get(Run.name())
            .expect("Expected Run in the commands list.")
            .execute(commands, context)
    }
}

/// Command for the template generation.
pub struct GenerateCommonConfig;

impl Command for GenerateCommonConfig {
    fn args(&self) -> Vec<Argument> {
        vec![
            Argument::new_positional("COMMON_CONFIG", true, "Path to common config."),
            Argument::new_named(
                "VALIDATORS_COUNT",
                true,
                "Number of validators",
                None,
                "validators-count",
                false,
            ),
        ]
    }

    fn name(&self) -> CommandName {
        "generate-template"
    }

    fn about(&self) -> &str {
        "Generate basic config template."
    }

    fn execute(
        &self,
        _commands: &HashMap<CommandName, CollectedCommand>,
        mut context: Context,
        exts: &dyn Fn(Context) -> Context,
    ) -> Feedback {
        let template_path = context
            .arg::<String>("COMMON_CONFIG")
            .expect("COMMON_CONFIG not found");

        let validators_count = context
            .arg::<u16>("VALIDATORS_COUNT")
            .expect("VALIDATORS_COUNT not found");

        context.set(keys::SERVICES_CONFIG, AbstractConfig::default());
        let new_context = exts(context);
        let services_config = new_context.get(keys::SERVICES_CONFIG).unwrap_or_default();

        let mut general_config = AbstractConfig::default();
        general_config.insert(
            String::from("validators_count"),
            u32::from(validators_count).into(),
        );

        let template = CommonConfigTemplate {
            services_config,
            general_config,
            ..CommonConfigTemplate::default()
        };

        ConfigFile::save(&template, template_path).expect("Could not write template file.");
        Feedback::None
    }
}

/// Command for the node configuration generation.
pub struct GenerateNodeConfig;

impl GenerateNodeConfig {
    fn addresses(context: &Context) -> (String, SocketAddr) {
        let external_address_str = &context.arg::<String>(PEER_ADDRESS).unwrap_or_default();
        let listen_address_str = &context.arg::<String>(LISTEN_ADDRESS).ok();

        // Try case where peer external address is socket address or ip address.
        let external_address_socket = external_address_str.parse().or_else(|_| {
            external_address_str
                .parse()
                .map(|ip| SocketAddr::new(ip, DEFAULT_EXONUM_LISTEN_PORT))
        });

        let (external_address, external_port) = if let Ok(addr) = external_address_socket {
            (addr.to_string(), addr.port())
        } else {
            let port = external_address_str
                .rsplitn(2, ':')
                .next()
                .and_then(|p| p.parse::<u16>().ok());
            if let Some(port) = port {
                (external_address_str.clone(), port)
            } else {
                let port = DEFAULT_EXONUM_LISTEN_PORT;
                (format!("{}:{}", external_address_str, port), port)
            }
        };

        let listen_address: SocketAddr = listen_address_str.as_ref().map_or_else(
            || {
                let listen_ip = match external_address_socket {
                    Ok(addr) => match addr.ip() {
                        IpAddr::V4(_) => "0.0.0.0".parse().unwrap(),
                        IpAddr::V6(_) => "::".parse().unwrap(),
                    },
                    Err(_) => "0.0.0.0".parse().unwrap(),
                };
                SocketAddr::new(listen_ip, external_port)
            },
            |a| {
                a.parse().unwrap_or_else(|_| {
                    panic!(
                        "Correct socket address is expected for {}: {:?}",
                        LISTEN_ADDRESS, a
                    )
                })
            },
        );

        (external_address, listen_address)
    }

    fn get_passphrase(
        context: &Context,
        method: PassInputMethod,
        secret_key_type: SecretKeyType,
    ) -> ZeroizeOnDrop<String> {
        if context.get_flag_occurrences(NO_PASSWORD).is_some() {
            ZeroizeOnDrop::default()
        } else {
            method.get_passphrase(secret_key_type, false)
        }
    }
}

impl Command for GenerateNodeConfig {
    fn args(&self) -> Vec<Argument> {
        vec![
            Argument::new_positional("COMMON_CONFIG", true, "Path to common config."),
            Argument::new_positional("PUB_CONFIG", true, "Path where save public config."),
            Argument::new_positional("SEC_CONFIG", true, "Path where save private config."),
            Argument::new_named(
                PEER_ADDRESS,
                true,
                "Remote peer address",
                "a",
                "peer-address",
                false,
            ),
            Argument::new_named(
                LISTEN_ADDRESS,
                false,
                "Listen address",
                "l",
                "listen-address",
                false,
            ),
            Argument::new_named(
                CONSENSUS_KEY_PATH,
                false,
                "Path to the file storing consensus private key (default: ./consensus.toml)",
                "c",
                "consensus-path",
                false,
            ),
            Argument::new_named(
                SERVICE_KEY_PATH,
                false,
                "Path to the file storing service private key (default: ./service.toml)",
                "s",
                "service-path",
                false,
            ),
            Argument::new_flag(
                NO_PASSWORD,
                "Don't prompt for passwords when generating private keys (leave empty)",
                "n",
                "no-password",
                false,
            ),
            Argument::new_named(
                CONSENSUS_KEY_PASS_METHOD,
                false,
                "Passphrase entry method for consensus key.\n\
                 Possible values are: stdin, env{:ENV_VAR_NAME}, pass:PASSWORD (default: stdin)\n\
                 If ENV_VAR_NAME is not specified $EXONUM_CONSENSUS_PASS is used",
                None,
                "consensus-key-pass",
                false,
            ),
            Argument::new_named(
                SERVICE_KEY_PASS_METHOD,
                false,
                "Passphrase entry method for service key.\n\
                 Possible values are: stdin, env{:ENV_VAR_NAME}, pass:PASSWORD (default: stdin)\n\
                 If ENV_VAR_NAME is not specified $EXONUM_SERVICE_PASS is used",
                None,
                "service-key-pass",
                false,
            ),
        ]
    }

    fn name(&self) -> CommandName {
        "generate-config"
    }

    fn about(&self) -> &str {
        "Generate node secret and public configs."
    }

    fn execute(
        &self,
        _commands: &HashMap<CommandName, CollectedCommand>,
        mut context: Context,
        exts: &dyn Fn(Context) -> Context,
    ) -> Feedback {
        let common_config_path = context
            .arg::<String>("COMMON_CONFIG")
            .expect("expected common config path");
        let pub_config_path = context
            .arg::<String>("PUB_CONFIG")
            .expect("expected public config path");
        let private_config_path = context
            .arg::<String>("SEC_CONFIG")
            .expect("expected secret config path");
        let consensus_secret_key_path: PathBuf = context
            .arg::<String>(CONSENSUS_KEY_PATH)
            .unwrap_or_else(|_| "consensus.toml".into())
            .into();
        let service_secret_key_path: PathBuf = context
            .arg::<String>(SERVICE_KEY_PATH)
            .unwrap_or_else(|_| "service.toml".into())
            .into();
        let consensus_key_pass_method: PassInputMethod = context
            .arg::<String>(CONSENSUS_KEY_PASS_METHOD)
            .unwrap_or_default()
            .parse()
            .expect("expected correct passphrase input method for consensus key");
        let service_key_pass_method: PassInputMethod = context
            .arg::<String>(SERVICE_KEY_PASS_METHOD)
            .unwrap_or_default()
            .parse()
            .expect("expected correct passphrase input method for service key");

        let addresses = Self::addresses(&context);
        let common: CommonConfigTemplate =
            ConfigFile::load(&common_config_path).expect("Could not load common config");
        context.set(keys::COMMON_CONFIG, common.clone());
        context.set(
            keys::SERVICES_PUBLIC_CONFIGS,
            BTreeMap::<String, toml::Value>::default(),
        );
        context.set(
            keys::SERVICES_SECRET_CONFIGS,
            BTreeMap::<String, toml::Value>::default(),
        );
        let new_context = exts(context);
        let services_public_configs = new_context.get(keys::SERVICES_PUBLIC_CONFIGS).unwrap();
        let services_secret_configs = new_context.get(keys::SERVICES_SECRET_CONFIGS);

        let consensus_public_key = {
            let passphrase = Self::get_passphrase(
                &new_context,
                consensus_key_pass_method,
                SecretKeyType::Consensus,
            );
            create_secret_key_file(&consensus_secret_key_path, passphrase.as_bytes())
        };
        let service_public_key = {
            let passphrase = Self::get_passphrase(
                &new_context,
                service_key_pass_method,
                SecretKeyType::Service,
            );
            create_secret_key_file(&service_secret_key_path, passphrase.as_bytes())
        };

        let pub_config_dir = Path::new(&pub_config_path)
            .parent()
            .expect("Cannot get directory with configuration file");
        let consensus_secret_key = if consensus_secret_key_path.is_absolute() {
            consensus_secret_key_path
        } else {
            path_relative_from(&consensus_secret_key_path, &pub_config_dir).unwrap()
        };
        let service_secret_key = if service_secret_key_path.is_absolute() {
            service_secret_key_path
        } else {
            path_relative_from(&service_secret_key_path, &pub_config_dir).unwrap()
        };

        let validator_keys = ValidatorKeys {
            consensus_key: consensus_public_key,
            service_key: service_public_key,
        };
        let node_pub_config = NodePublicConfig {
            address: addresses.0.clone(),
            validator_keys,
            services_public_configs,
        };
        let shared_config = SharedConfig {
            node: node_pub_config,
            common,
        };
        // Save public config separately.
        ConfigFile::save(&shared_config, &pub_config_path)
            .expect("Could not write public config file.");

        let private_config = NodePrivateConfig {
            listen_address: addresses.1,
            external_address: addresses.0.clone(),
            consensus_public_key,
            consensus_secret_key,
            service_public_key,
            service_secret_key,
            services_secret_configs: services_secret_configs
                .expect("services_secret_configs not found after exts call"),
        };

        ConfigFile::save(&private_config, private_config_path)
            .expect("Could not write secret config file.");
        Feedback::None
    }
}

/// Finalize command.
pub struct Finalize;

impl Finalize {
    /// Returns `GenesisConfig` from the template.
    fn genesis_from_template(
        template: CommonConfigTemplate,
        configs: &[NodePublicConfig],
    ) -> GenesisConfig {
        GenesisConfig::new_with_consensus(
            template.consensus_config,
            configs.iter().map(|c| c.validator_keys),
        )
    }

    fn reduce_configs(
        public_configs: Vec<SharedConfig>,
        our_config: &NodePrivateConfig,
    ) -> (
        CommonConfigTemplate,
        Vec<NodePublicConfig>,
        Option<NodePublicConfig>,
    ) {
        let mut map = BTreeMap::new();
        let mut config_iter = public_configs.into_iter();
        let first = config_iter
            .next()
            .expect("Expected at least one config in PUBLIC_CONFIGS");
        let common = first.common;
        map.insert(first.node.validator_keys.consensus_key, first.node);

        for config in config_iter {
            if common != config.common {
                panic!("Found config with different common part.");
            };
            if map
                .insert(config.node.validator_keys.consensus_key, config.node)
                .is_some()
            {
                panic!("Found duplicate consensus keys in PUBLIC_CONFIGS");
            }
        }
        (
            common,
            map.iter().map(|(_, c)| c.clone()).collect(),
            map.get(&our_config.consensus_public_key).cloned(),
        )
    }

    fn public_allow_origin(context: &Context) -> Option<AllowOrigin> {
        context.arg(PUBLIC_ALLOW_ORIGIN).ok()
    }

    fn private_allow_origin(context: &Context) -> Option<AllowOrigin> {
        context.arg(PRIVATE_ALLOW_ORIGIN).ok()
    }
}

impl Command for Finalize {
    fn args(&self) -> Vec<Argument> {
        vec![
            Argument::new_named(
                "PUBLIC_CONFIGS",
                true,
                "Path to validators public configs",
                "p",
                "public-configs",
                true,
            ),
            Argument::new_named(
                PUBLIC_API_ADDRESS,
                false,
                "Listen address for public api.",
                None,
                "public-api-address",
                false,
            ),
            Argument::new_named(
                PRIVATE_API_ADDRESS,
                false,
                "Listen address for private api.",
                None,
                "private-api-address",
                false,
            ),
            Argument::new_named(
                PUBLIC_ALLOW_ORIGIN,
                false,
                "Cross-origin resource sharing options for responses returned by public API handlers.",
                None,
                "public-allow-origin",
                false,
            ),
            Argument::new_named(
                PRIVATE_ALLOW_ORIGIN,
                false,
                "Cross-origin resource sharing options for responses returned by private API handlers.",
                None,
                "private-allow-origin",
                false,
            ),
            Argument::new_positional("SECRET_CONFIG", true, "Path to our secret config."),
            Argument::new_positional("OUTPUT_CONFIG_PATH", true, "Path to output node config."),
        ]
    }

    fn name(&self) -> CommandName {
        "finalize"
    }

    fn about(&self) -> &str {
        "Collect public and secret configs into node config."
    }

    fn execute(
        &self,
        _commands: &HashMap<CommandName, CollectedCommand>,
        mut context: Context,
        exts: &dyn Fn(Context) -> Context,
    ) -> Feedback {
        let public_configs_path = context
            .arg_multiple::<String>("PUBLIC_CONFIGS")
            .expect("public config path not found");
        let secret_config_path = context
            .arg::<String>("SECRET_CONFIG")
            .expect("private config path not found");
        let output_config_path = context
            .arg::<String>("OUTPUT_CONFIG_PATH")
            .expect("output config path not found");

        let public_api_address = Run::public_api_address(&context);
        let private_api_address = Run::private_api_address(&context);
        let public_allow_origin = Self::public_allow_origin(&context);
        let private_allow_origin = Self::private_allow_origin(&context);

        let secret_config: NodePrivateConfig =
            ConfigFile::load(secret_config_path).expect("Failed to load key config.");
        let public_configs: Vec<SharedConfig> = public_configs_path
            .into_iter()
            .map(|path| ConfigFile::load(path).expect("Failed to load validator public config."))
            .collect();

        let (common, list, our) = Self::reduce_configs(public_configs, &secret_config);

        let validators_count = common
            .general_config
            .get("validators_count")
            .expect("validators_count not found in common config.")
            .as_integer()
            .unwrap() as usize;

        if validators_count != list.len() {
            panic!(
                "The number of validators configs does not match the number of validators keys."
            );
        }

        context.set(keys::AUDITOR_MODE, our.is_none());

        let genesis = Self::genesis_from_template(common.clone(), &list);

        let connect_list = ConnectListConfig::from_node_config(&list, &secret_config);

        let config = {
            NodeConfig {
                listen_address: secret_config.listen_address,
                external_address: secret_config.external_address,
                network: Default::default(),
                consensus_public_key: secret_config.consensus_public_key,
                consensus_secret_key: secret_config.consensus_secret_key,
                service_public_key: secret_config.service_public_key,
                service_secret_key: secret_config.service_secret_key,
                genesis,
                api: NodeApiConfig {
                    public_api_address,
                    private_api_address,
                    public_allow_origin,
                    private_allow_origin,
                    ..Default::default()
                },
                mempool: Default::default(),
                services_configs: Default::default(),
                database: Default::default(),
                connect_list,
                thread_pool_size: Default::default(),
            }
        };

        context.set(keys::PUBLIC_CONFIG_LIST, list);
        context.set(keys::NODE_CONFIG, config);
        context.set(keys::COMMON_CONFIG, common);
        context.set(
            keys::SERVICES_SECRET_CONFIGS,
            secret_config.services_secret_configs,
        );

        let new_context = exts(context);

        let config = new_context
            .get(keys::NODE_CONFIG)
            .expect("Could not create config from template, services return error");
        ConfigFile::save(&config, output_config_path).expect("Could not write config file.");

        Feedback::None
    }
}

fn create_secret_key_file(
    secret_key_path: impl AsRef<Path>,
    passphrase: impl AsRef<[u8]>,
) -> PublicKey {
    let secret_key_path = secret_key_path.as_ref();
    if secret_key_path.exists() {
        panic!(
            "Failed to create secret key file. File exists: {}",
            secret_key_path.to_string_lossy(),
        );
    } else {
        if let Some(dir) = secret_key_path.parent() {
            fs::create_dir_all(dir).unwrap();
        }
        generate_keys_file(&secret_key_path, &passphrase).unwrap()
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_generate_node_config_addresses() {
        let mut ctx = Context::default();

        let external = "127.0.0.1:1234";
        ctx.set_arg(PEER_ADDRESS, external.to_string());
        assert_eq!(
            GenerateNodeConfig::addresses(&ctx),
            (external.to_string(), "0.0.0.0:1234".parse().unwrap())
        );

        let external = "127.0.0.1";
        ctx.set_arg(PEER_ADDRESS, external.to_string());
        assert_eq!(
            GenerateNodeConfig::addresses(&ctx),
            (
                SocketAddr::new(external.parse().unwrap(), DEFAULT_EXONUM_LISTEN_PORT).to_string(),
                SocketAddr::new("0.0.0.0".parse().unwrap(), DEFAULT_EXONUM_LISTEN_PORT)
            )
        );

        let external = "2001:db8::1";
        ctx.set_arg(PEER_ADDRESS, external.to_string());
        assert_eq!(
            GenerateNodeConfig::addresses(&ctx),
            (
                SocketAddr::new(external.parse().unwrap(), DEFAULT_EXONUM_LISTEN_PORT).to_string(),
                SocketAddr::new("::".parse().unwrap(), DEFAULT_EXONUM_LISTEN_PORT)
            )
        );

        let external = "[2001:db8::1]:1234";
        ctx.set_arg(PEER_ADDRESS, external.to_string());
        assert_eq!(
            GenerateNodeConfig::addresses(&ctx),
            (external.to_string(), "[::]:1234".parse().unwrap())
        );

        let external = "localhost";
        ctx.set_arg(PEER_ADDRESS, external.to_string());
        assert_eq!(
            GenerateNodeConfig::addresses(&ctx),
            (
                format!("{}:{}", external, DEFAULT_EXONUM_LISTEN_PORT),
                SocketAddr::new("0.0.0.0".parse().unwrap(), DEFAULT_EXONUM_LISTEN_PORT)
            )
        );

        let external = "localhost:1234";
        ctx.set_arg(PEER_ADDRESS, external.to_string());
        assert_eq!(
            GenerateNodeConfig::addresses(&ctx),
            (
                external.to_string(),
                SocketAddr::new("0.0.0.0".parse().unwrap(), 1234)
            )
        );

        let external = "127.0.0.1:1234";
        let listen = "1.2.3.4:5678";
        ctx.set_arg(PEER_ADDRESS, external.to_string());
        ctx.set_arg(LISTEN_ADDRESS, listen.to_string());
        assert_eq!(
            GenerateNodeConfig::addresses(&ctx),
            (external.to_string(), listen.parse().unwrap())
        );

        let external = "127.0.0.1:1234";
        let listen = "1.2.3.4:5678";
        ctx.set_arg(PEER_ADDRESS, external.to_string());
        ctx.set_arg(LISTEN_ADDRESS, listen.to_string());
        assert_eq!(
            GenerateNodeConfig::addresses(&ctx),
            (external.to_string(), listen.parse().unwrap())
        );

        let external = "example.com";
        let listen = "[2001:db8::1]:5678";
        ctx.set_arg(PEER_ADDRESS, external.to_string());
        ctx.set_arg(LISTEN_ADDRESS, listen.to_string());
        assert_eq!(
            GenerateNodeConfig::addresses(&ctx),
            (
                format!("{}:{}", external, DEFAULT_EXONUM_LISTEN_PORT),
                listen.parse().unwrap()
            )
        );
    }

}