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
use crate::{
    config::{CustodyConfig, GovernanceCustodyConfig, PcliConfig},
    terminal::ActualTerminal,
    App, Command,
};
use anyhow::Result;
use camino::Utf8PathBuf;
use clap::Parser;
use directories::ProjectDirs;
use penumbra_custody::soft_kms::SoftKms;
use penumbra_proto::box_grpc_svc;
use penumbra_proto::{
    custody::v1::{
        custody_service_client::CustodyServiceClient, custody_service_server::CustodyServiceServer,
    },
    view::v1::{view_service_client::ViewServiceClient, view_service_server::ViewServiceServer},
};
use penumbra_view::ViewServer;
use std::io::IsTerminal as _;
use tracing_subscriber::EnvFilter;

#[derive(Debug, Parser)]
#[clap(name = "pcli", about = "The Penumbra command-line interface.", version)]
pub struct Opt {
    #[clap(subcommand)]
    pub cmd: Command,
    /// The home directory used to store configuration and data.
    #[clap(long, default_value_t = default_home(), env = "PENUMBRA_PCLI_HOME")]
    pub home: Utf8PathBuf,
}

impl Opt {
    pub fn init_tracing(&mut self) {
        tracing_subscriber::fmt()
            .with_ansi(std::io::stdout().is_terminal())
            .with_env_filter(
                EnvFilter::from_default_env()
                    // Without explicitly disabling the `r1cs` target, the ZK proof implementations
                    // will spend an enormous amount of CPU and memory building useless tracing output.
                    .add_directive(
                        "r1cs=off"
                            .parse()
                            .expect("rics=off is a valid filter directive"),
                    ),
            )
            .with_writer(std::io::stderr)
            .init();
    }

    pub fn load_config(&self) -> Result<PcliConfig> {
        let path = self.home.join(crate::CONFIG_FILE_NAME);
        PcliConfig::load(path)
    }

    pub async fn into_app(self) -> Result<(App, Command)> {
        let config = self.load_config()?;

        // Build the custody service...
        let custody = match &config.custody {
            CustodyConfig::ViewOnly => {
                tracing::info!("using view-only custody service");
                let null_kms = penumbra_custody::null_kms::NullKms::default();
                let custody_svc = CustodyServiceServer::new(null_kms);
                CustodyServiceClient::new(box_grpc_svc::local(custody_svc))
            }
            CustodyConfig::SoftKms(config) => {
                tracing::info!("using software KMS custody service");
                let soft_kms = SoftKms::new(config.clone());
                let custody_svc = CustodyServiceServer::new(soft_kms);
                CustodyServiceClient::new(box_grpc_svc::local(custody_svc))
            }
            CustodyConfig::Threshold(config) => {
                tracing::info!("using manual threshold custody service");
                let threshold_kms =
                    penumbra_custody::threshold::Threshold::new(config.clone(), ActualTerminal);
                let custody_svc = CustodyServiceServer::new(threshold_kms);
                CustodyServiceClient::new(box_grpc_svc::local(custody_svc))
            }
        };

        // Build the governance custody service...
        let governance_custody = match &config.governance_custody {
            Some(separate_governance_custody) => match separate_governance_custody {
                GovernanceCustodyConfig::SoftKms(config) => {
                    tracing::info!(
                        "using separate software KMS custody service for validator voting"
                    );
                    let soft_kms = SoftKms::new(config.clone());
                    let custody_svc = CustodyServiceServer::new(soft_kms);
                    CustodyServiceClient::new(box_grpc_svc::local(custody_svc))
                }
                GovernanceCustodyConfig::Threshold(config) => {
                    tracing::info!(
                        "using separate manual threshold custody service for validator voting"
                    );
                    let threshold_kms =
                        penumbra_custody::threshold::Threshold::new(config.clone(), ActualTerminal);
                    let custody_svc = CustodyServiceServer::new(threshold_kms);
                    CustodyServiceClient::new(box_grpc_svc::local(custody_svc))
                }
            },
            None => custody.clone(), // If no separate custody for validator voting, use the same one
        };

        // ...and the view service...
        let view = match (self.cmd.offline(), &config.view_url) {
            // In offline mode, don't construct a view service at all.
            (true, _) => None,
            (false, Some(view_url)) => {
                // Use a remote view service.
                tracing::info!(%view_url, "using remote view service");

                let ep = tonic::transport::Endpoint::new(view_url.to_string())?;
                Some(ViewServiceClient::new(box_grpc_svc::connect(ep).await?))
            }
            (false, None) => {
                // Use an in-memory view service.
                let path = self.home.join(crate::VIEW_FILE_NAME);
                tracing::info!(%path, "using local view service");

                let svc = ViewServer::load_or_initialize(
                    Some(path),
                    &config.full_viewing_key,
                    config.grpc_url.clone(),
                )
                .await?;

                // Now build the view and custody clients, doing gRPC with ourselves
                let svc = ViewServiceServer::new(svc);
                Some(ViewServiceClient::new(box_grpc_svc::local(svc)))
            }
        };

        let app = App {
            view,
            custody,
            governance_custody,
            config,
        };
        Ok((app, self.cmd))
    }
}

fn default_home() -> Utf8PathBuf {
    let path = ProjectDirs::from("zone", "penumbra", "pcli")
        .expect("Failed to get platform data dir")
        .data_dir()
        .to_path_buf();
    Utf8PathBuf::from_path_buf(path).expect("Platform default data dir was not UTF-8")
}