1
//! Arti consensus method plugin for C Tor
2
//!
3
//! Implements `authority-plugin.md` pursuant to `doc/dev/notes/dirauth-sketch.md`.
4
//!
5
//! This is the actual implementation.
6

            
7
use std::collections::HashSet;
8
use std::time::SystemTime;
9

            
10
use anyhow::{Context as _, anyhow};
11
use derive_deftly::{Deftly, define_derive_deftly};
12
use digest::Digest as _;
13
use educe::Educe;
14

            
15
use tor_checkable::TimeBound as _;
16
use tor_dirauth::consensus;
17
use tor_error::{Bug, ErrorReport as _, HasKind as _};
18
use tor_llcrypto::d::Sha256;
19
use tor_netdoc::{
20
    doc::netstatus::ConsensusMethod,
21
    doc::routerdesc::{RouterDesc, RouterDescUnverified},
22
    encode::{NetdocEncodable, encode_netdoc_unsigned},
23
    parse2::{self, NetdocParseable},
24
    types::{Base64Fingerprint, Ed25519Public, FixedB64, Iso8601TimeNoSp},
25
};
26

            
27
#[macro_use]
28
mod utils;
29
mod compute_mds;
30

            
31
use utils::{CTorAnnotated, FilenameOrStdio, Writing};
32

            
33
/// Options and arguments to plugin invocation
34
#[derive(Debug, clap::Parser)]
35
#[command(after_help =
36
//
37
"For details of semantics, exit status, input/output formats, etc., see the spec:
38
   arti-authority-plugin dump-spec
39
Latest version:
40
   https://gitlab.torproject.org/tpo/core/arti/-/blob/main/crates/arti-dirauth/authority-plugin.md
41
"
42
)]
43
struct CliArgs {
44
    /// Operation verb and its arguments
45
    #[command(subcommand)]
46
    op: CliOperation,
47
}
48

            
49
/// Operation verb and its arguments
50
#[derive(Debug, Clone, clap::Subcommand)]
51
enum CliOperation {
52
    /// `list-methods`, "mode 1"
53
    ListMethods {
54
        /// Output file
55
        #[arg(short = 'o')]
56
        output: FilenameOrStdio,
57
    },
58

            
59
    /// `compute-mds`, "mode 2"
60
    ComputeMds {
61
        /// Nominal time (for routerdesc verification)
62
        #[arg(short = 't')]
63
        nominal_time: Iso8601TimeNoSp,
64

            
65
        /// Microdescriptors out
66
        #[arg(short = 'i')]
67
        input: Vec<FilenameOrStdio>,
68

            
69
        /// Microdescriptors out
70
        #[arg(long)]
71
        mds_out: FilenameOrStdio,
72

            
73
        /// Metadata out
74
        #[arg(long)]
75
        meta_out: FilenameOrStdio,
76
    },
77

            
78
    /// Print the specification to stdout, in markdown format
79
    //
80
    // This is to save us from having to document everything again here.
81
    // Instead, this can be regarded as part of the program's help output.
82
    // Our help output has a link to the rendered version in gitlab
83
    // (`after_help` attribute on `CliArgs`)
84
    DumpSpec {},
85
}
86

            
87
/// Top-level error - program exits with this, or `Ok(())`
88
#[derive(Debug, thiserror::Error)]
89
enum CliError {
90
    /// Invalid operation or usage
91
    #[error("invalid operation or usage")]
92
    InvalidInputs(#[source] anyhow::Error),
93

            
94
    /// Unsupported consensus method
95
    #[error("fall back to C Tor")]
96
    #[allow(dead_code)] // TODO DIRAUTH
97
    UnsupportedConsensusMethod(#[from] consensus::UnsupportedConsensusMethod),
98

            
99
    /// Operational error
100
    #[error("failed")]
101
    OperationalError(#[source] anyhow::Error),
102
}
103

            
104
//==================== implementations ====================
105

            
106
/// Actual implementation of the plugin's invocations
107
///
108
/// Split off for ease of testing.
109
1
fn plugin_impl(args: CliArgs) -> Result<(), CliError> {
110
1
    match args.op {
111
        CliOperation::ListMethods { output } => output.write(|w| {
112
            for m in consensus::SupportedConsensusMethod::iter_all() {
113
                writeln!(w, "{m}")?;
114
            }
115
            Ok(())
116
        }),
117
        CliOperation::ComputeMds {
118
            nominal_time,
119
            input,
120
            mds_out,
121
            meta_out,
122
        } => {
123
1
            let mut mds_out = mds_out.start_writing()?;
124
1
            let mut meta_out = meta_out.start_writing()?;
125
            let mut processor =
126
1
                compute_mds::Processor::new(*nominal_time, &mut mds_out, &mut meta_out);
127
1
            for i in input {
128
3
                processor.process_input(&i.read_entire()?.netdoc_parse2())?;
129
            }
130
1
            mds_out.finish()?;
131
1
            meta_out.finish()?;
132
1
            Ok(())
133
        }
134

            
135
        CliOperation::DumpSpec {} => {
136
            print!("{}", include_str!("../authority-plugin.md"));
137
            Ok(())
138
        }
139
    }
140
1
}
141

            
142
/// Entrypoint for the Arti-in-C-Tor consensus method plugin
143
pub fn plugin_main() {
144
    match (|| {
145
        let args = <CliArgs as clap::Parser>::try_parse()
146
            .context("invalid arguments")
147
            .map_err(CliError::InvalidInputs)?;
148

            
149
        // TODO DIRAUTH set up logging
150

            
151
        plugin_impl(args)
152
    })() {
153
        Ok(()) => {}
154
        Err(e) => {
155
            eprintln!("arti-authority-plugin: error: {}", e.report());
156
            std::process::exit(i32::from(e.exit_status()));
157
        }
158
    }
159
}
160

            
161
impl CliError {
162
    /// Exit status corresponding to this error, as per `authority-plugin.md`
163
    ///
164
    /// Returns `u8` because that's what Unix processes can exit,
165
    /// `std::process:exit`'s `i32` argument notwithstanding.
166
    fn exit_status(&self) -> u8 {
167
        use CliError as E;
168
        match self {
169
            E::InvalidInputs { .. } => 8,
170
            E::UnsupportedConsensusMethod { .. } => 10,
171
            E::OperationalError { .. } => 32,
172
        }
173
    }
174
}
175

            
176
impl From<Bug> for CliError {
177
    fn from(bug: Bug) -> Self {
178
        CliError::OperationalError(bug.into())
179
    }
180
}
181

            
182
#[cfg(test)]
183
mod test {
184
    // @@ begin test lint list maintained by maint/add_warning @@
185
    #![allow(clippy::bool_assert_comparison)]
186
    #![allow(clippy::clone_on_copy)]
187
    #![allow(clippy::dbg_macro)]
188
    #![allow(clippy::mixed_attributes_style)]
189
    #![allow(clippy::print_stderr)]
190
    #![allow(clippy::print_stdout)]
191
    #![allow(clippy::single_char_pattern)]
192
    #![allow(clippy::unwrap_used)]
193
    #![allow(clippy::unchecked_time_subtraction)]
194
    #![allow(clippy::useless_vec)]
195
    #![allow(clippy::needless_pass_by_value)]
196
    #![allow(clippy::string_slice)] // See arti#2571
197
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
198
    use super::*;
199
    use itertools::chain;
200

            
201
    pub(super) fn test_invocation<'i>(
202
        args: impl IntoIterator<Item = &'i str>,
203
    ) -> anyhow::Result<()> {
204
        let args = clap::Parser::try_parse_from(chain!(["authority-plugin"], args))
205
            .context("parse args")?;
206
        plugin_impl(args).context("execute")?;
207
        Ok(())
208
    }
209
}