exochain-node 0.2.0-beta

EXOCHAIN distributed node — single binary for joining and participating in the constitutional governance network
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
// Copyright 2026 Exochain Foundation
//
// 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:
//
//     https://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.
//
// SPDX-License-Identifier: Apache-2.0

//! Command-line interface for the exochain node.

use std::path::PathBuf;

use clap::{Args, Parser, Subcommand};

pub const ROOT_GENESIS_LONG_HELP: &str = "\
Root genesis creates a 7-of-13 institutional root authority. Genesis DKG \
requires all 13 rostered certifiers to complete the ceremony; if any \
certifier fails, abort and restart with a new signed roster.

Certifier rules: keep private material offline, maintain an offline backup, \
never submit plaintext shares, encrypt round-two payloads per recipient, and \
run verify-bundle before trusting the result. Secret-producing commands require \
explicit unique --output files and refuse stdout.";

pub const DEFAULT_ROUND_TIMEOUT_MS: u64 = 5_000;
pub const MIN_ROUND_TIMEOUT_MS: u64 = 250;
pub const MAX_ROUND_TIMEOUT_MS: u64 = 300_000;

fn parse_round_timeout_ms(value: &str) -> Result<u64, String> {
    let timeout_ms = value
        .parse::<u64>()
        .map_err(|error| format!("round timeout must be a millisecond integer: {error}"))?;
    if !(MIN_ROUND_TIMEOUT_MS..=MAX_ROUND_TIMEOUT_MS).contains(&timeout_ms) {
        return Err(format!(
            "round timeout must be between {MIN_ROUND_TIMEOUT_MS} and {MAX_ROUND_TIMEOUT_MS} milliseconds"
        ));
    }
    Ok(timeout_ms)
}

#[derive(Parser)]
#[command(
    name = "exochain",
    about = "EXOCHAIN distributed constitutional governance node",
    version,
    propagate_version = true
)]
/// Top-level CLI argument parser for the exochain node.
pub struct Cli {
    #[command(subcommand)]
    pub command: Command,
}

#[derive(Subcommand)]
/// Subcommands available to the exochain node (start, join, status, peers).
pub enum Command {
    /// Start a standalone node.
    Start {
        /// HTTP API port.
        #[arg(long, default_value = None)]
        api_port: Option<u16>,

        /// HTTP API bind host. Default is `127.0.0.1` (loopback only).
        /// Set to `0.0.0.0` to expose the admin-write API on all
        /// interfaces — do so ONLY when you have a front-door TLS
        /// terminator AND your admin bearer token is appropriately
        /// scoped (see auth.rs). Exposing 0.0.0.0 with the default
        /// bearer model is equivalent to publishing your node's
        /// governance-write credential on the open internet.
        #[arg(long, default_value = "127.0.0.1")]
        api_host: String,

        /// P2P listen port.
        #[arg(long, default_value = None)]
        p2p_port: Option<u16>,

        /// Consensus round timeout in milliseconds.
        #[arg(
            long,
            default_value_t = DEFAULT_ROUND_TIMEOUT_MS,
            value_parser = parse_round_timeout_ms
        )]
        round_timeout_ms: u64,

        /// Data directory (default: ~/.exochain).
        #[arg(long)]
        data_dir: Option<PathBuf>,

        /// Run as a BFT consensus validator.
        #[arg(long, default_value_t = false)]
        validator: bool,

        /// Validator DIDs for the initial validator set (comma-separated).
        /// If not provided, this node's DID is used as the sole validator.
        #[arg(long, value_delimiter = ',')]
        validators: Option<Vec<String>>,

        /// Validator public keys as `did:exo:...=<64 hex bytes>` entries.
        /// Required for every non-local validator DID because consensus
        /// proposals/votes/certificates are verified against these keys.
        #[arg(long = "validator-public-key", value_delimiter = ',')]
        validator_public_keys: Option<Vec<String>>,
    },

    /// Join an existing network via seed node(s).
    Join {
        /// Seed node addresses (e.g., seed1.exochain.io:4001).
        #[arg(long, required = true, num_args = 1..)]
        seed: Vec<String>,

        /// HTTP API port.
        #[arg(long, default_value = None)]
        api_port: Option<u16>,

        /// HTTP API bind host. Default is `127.0.0.1` (loopback only).
        /// See `Start --api-host` for rationale on 0.0.0.0.
        #[arg(long, default_value = "127.0.0.1")]
        api_host: String,

        /// P2P listen port.
        #[arg(long, default_value = None)]
        p2p_port: Option<u16>,

        /// Consensus round timeout in milliseconds.
        #[arg(
            long,
            default_value_t = DEFAULT_ROUND_TIMEOUT_MS,
            value_parser = parse_round_timeout_ms
        )]
        round_timeout_ms: u64,

        /// Data directory (default: ~/.exochain).
        #[arg(long)]
        data_dir: Option<PathBuf>,

        /// Run as a BFT consensus validator.
        #[arg(long, default_value_t = false)]
        validator: bool,

        /// Validator DIDs for the initial validator set (comma-separated).
        #[arg(long, value_delimiter = ',')]
        validators: Option<Vec<String>>,

        /// Validator public keys as `did:exo:...=<64 hex bytes>` entries.
        /// Required for every non-local validator DID because consensus
        /// proposals/votes/certificates are verified against these keys.
        #[arg(long = "validator-public-key", value_delimiter = ',')]
        validator_public_keys: Option<Vec<String>>,
    },

    /// Show node status.
    Status {
        /// Data directory (default: ~/.exochain).
        #[arg(long)]
        data_dir: Option<PathBuf>,
    },

    /// List connected peers.
    Peers {
        /// Data directory (default: ~/.exochain).
        #[arg(long)]
        data_dir: Option<PathBuf>,
    },

    /// Start the MCP (Model Context Protocol) server on stdio or HTTP+SSE.
    /// Enables AI agents to interact with the governance fabric.
    Mcp {
        /// Data directory (default: ~/.exochain).
        #[arg(long)]
        data_dir: Option<PathBuf>,

        /// DID for the MCP actor. If not provided, uses the node's identity.
        #[arg(long)]
        actor_did: Option<String>,

        /// Use HTTP+SSE transport instead of stdio. The value is the bind
        /// address (host:port). Example: `--sse 127.0.0.1:3030`.
        #[arg(long)]
        sse: Option<String>,
    },

    /// Run root genesis FROST DKG and root trust bundle operations.
    Genesis {
        #[command(subcommand)]
        command: GenesisCommand,
    },
}

#[derive(Subcommand)]
#[command(after_long_help = ROOT_GENESIS_LONG_HELP)]
/// Root genesis ceremony commands.
pub enum GenesisCommand {
    /// Certifier-local setup commands.
    Certifier {
        #[command(subcommand)]
        command: GenesisCertifierCommand,
    },

    /// Ceremony operator setup commands.
    Ceremony {
        #[command(subcommand)]
        command: GenesisCeremonyCommand,
    },

    /// Serve the untrusted root genesis relay portal.
    Portal(GenesisPortalArgs),

    /// Produce or verify DKG round-one material.
    Round1(GenesisIoArgs),

    /// Produce encrypted DKG round-two material.
    Round2(GenesisIoArgs),

    /// Finalize DKG once all thirteen certifiers have completed both rounds.
    #[command(name = "finalize-dkg")]
    FinalizeDkg(GenesisIoArgs),

    /// Build CBOR payload bytes for this certifier's final key confirmation.
    #[command(name = "build-final-key-confirmation")]
    BuildFinalKeyConfirmation(GenesisIoArgs),

    /// Sign a root-governance artifact with the exact predeclared signing set.
    #[command(name = "sign-root-artifact")]
    SignRootArtifact(GenesisIoArgs),

    /// Assemble a root trust bundle after artifact signing.
    #[command(name = "assemble-bundle")]
    AssembleBundle(GenesisIoArgs),

    /// Verify a root trust bundle before trusting any AVC issuer delegation.
    #[command(name = "verify-bundle")]
    VerifyBundle(GenesisIoArgs),

    /// Seal a serialized certifier share artifact.
    #[command(name = "seal-share")]
    SealShare(GenesisIoArgs),

    /// Open a sealed certifier share artifact.
    #[command(name = "unseal-share")]
    UnsealShare(GenesisIoArgs),

    /// Sign a ceremony portal envelope ready for submission.
    #[command(name = "sign-envelope")]
    SignEnvelope(GenesisSignEnvelopeArgs),

    /// Encrypt a DKG round-two payload for exactly one recipient.
    #[command(name = "encrypt-pairwise")]
    EncryptPairwise(GenesisIoArgs),

    /// Decrypt a recipient-bound DKG round-two payload.
    #[command(name = "decrypt-pairwise")]
    DecryptPairwise(GenesisIoArgs),

    /// Emit the exact root-artifact bytes that `sign-root-artifact` must sign.
    #[command(name = "emit-artifact-bytes")]
    EmitArtifactBytes(GenesisIoArgs),

    /// Submit a signed envelope to a running root genesis portal.
    #[command(name = "submit-envelope")]
    SubmitEnvelope(GenesisSubmitEnvelopeArgs),

    /// Pull accepted envelopes back from a running portal (read half of the relay).
    #[command(name = "pull-envelopes")]
    PullEnvelopes(GenesisPullEnvelopesArgs),

    /// Replay accepted envelopes and emit the completed DKG transcript hash.
    #[command(name = "compute-dkg-transcript-hash")]
    ComputeDkgTranscriptHash(GenesisIoArgs),

    /// Replay accepted envelopes and emit the final ceremony transcript hash.
    #[command(name = "compute-final-transcript-hash")]
    ComputeFinalTranscriptHash(GenesisIoArgs),

    /// CBOR-encode an encrypted round-two payload into envelope `payload_bytes`.
    #[command(name = "encode-encrypted-payload")]
    EncodeEncryptedPayload(GenesisIoArgs),

    /// CBOR-decode envelope `payload_bytes` back into an encrypted round-two payload.
    #[command(name = "decode-encrypted-payload")]
    DecodeEncryptedPayload(GenesisIoArgs),

    /// Distributed signing — produce one signer's public commitment (and a
    /// separate local-only secret-nonces file).
    #[command(name = "sign-commit")]
    SignCommit(GenesisSignCommitArgs),

    /// Distributed signing — coordinator builds the signing package from the declared set.
    #[command(name = "build-signing-package")]
    BuildSigningPackage(GenesisIoArgs),

    /// Distributed signing — produce one signer's signature share.
    #[command(name = "sign-share")]
    SignShare(GenesisSignShareArgs),

    /// Distributed signing — coordinator aggregates the declared set into the root signature.
    #[command(name = "aggregate-signature")]
    AggregateSignature(GenesisIoArgs),
}

#[derive(Subcommand)]
/// Certifier-local root genesis commands.
pub enum GenesisCertifierCommand {
    /// Generate certifier signing and transport material.
    Init(GenesisCertifierInitArgs),
}

#[derive(Subcommand)]
/// Ceremony-operator root genesis commands.
pub enum GenesisCeremonyCommand {
    /// Build a signed-roster ceremony configuration.
    Init(GenesisCeremonyInitArgs),
}

#[derive(Args)]
/// Generate local certifier key material.
pub struct GenesisCertifierInitArgs {
    /// Certifier DID.
    #[arg(long)]
    pub did: String,

    /// FROST identifier in the inclusive range 1..=13.
    #[arg(long)]
    pub frost_identifier: u16,

    /// Public certifier contact output path.
    #[arg(long)]
    pub certifier_out: PathBuf,

    /// Private certifier material output path.
    #[arg(long)]
    pub private_out: PathBuf,
}

#[derive(Args)]
/// Build a ceremony configuration from a roster.
pub struct GenesisCeremonyInitArgs {
    /// Ceremony identifier.
    #[arg(long)]
    pub ceremony_id: String,

    /// EXOCHAIN network identifier.
    #[arg(long)]
    pub network_id: String,

    /// Reviewed repository commit.
    #[arg(long)]
    pub repo_commit: String,

    /// 32-byte constitution hash as lowercase or uppercase hex.
    #[arg(long)]
    pub constitution_hash: String,

    /// HLC physical milliseconds supplied by the operator.
    #[arg(long)]
    pub created_physical_ms: u64,

    /// JSON roster path containing thirteen certifier contacts.
    #[arg(long)]
    pub roster: PathBuf,

    /// Predeclared signing set: exactly `threshold` (7) rostered FROST identifiers
    /// that will sign root artifacts, comma-separated (e.g. `1,2,3,4,5,6,7`).
    #[arg(long, value_delimiter = ',')]
    pub signing_set: Vec<u16>,

    /// Ceremony configuration output path.
    #[arg(long)]
    pub out: PathBuf,
}

#[derive(Args)]
/// Serve the root genesis relay portal.
pub struct GenesisPortalArgs {
    /// Ceremony configuration JSON path.
    #[arg(long)]
    pub config: PathBuf,

    /// Portal bind address.
    #[arg(long, default_value = "127.0.0.1:3017")]
    pub bind: String,
}

#[derive(Args)]
/// File-based root genesis command inputs.
pub struct GenesisIoArgs {
    /// Input JSON or binary path.
    #[arg(long)]
    pub input: Option<PathBuf>,

    /// Output JSON or binary path.
    #[arg(long)]
    pub output: Option<PathBuf>,
}

#[derive(Args)]
/// Sign a ceremony portal envelope.
///
/// The signing secret is read from the certifier's `0600` private-material file
/// (`--private-input`, the file written by `certifier init --private-out`), never
/// passed on the command line. Passing key material through argv would leak it
/// through process listings, shell history, terminal capture, and operator
/// transcripts — unacceptable for a ceremony artifact that may later be
/// challenged by a third-party auditor.
pub struct GenesisSignEnvelopeArgs {
    /// Envelope draft JSON path (ceremony_id, phase, payload_kind, sender_did,
    /// recipient_did, sequence, payload_bytes).
    #[arg(long)]
    pub input: Option<PathBuf>,

    /// Signed envelope output path. Omit to print to stdout.
    #[arg(long)]
    pub output: Option<PathBuf>,

    /// Path to the certifier's private-material JSON (`certifier-NN.private.json`,
    /// `0600`). The 32-byte Ed25519 signing secret is read from this file's
    /// `signing_secret_hex` field; it is never accepted as a CLI argument.
    #[arg(long)]
    pub private_input: PathBuf,
}

#[derive(Args)]
/// Pull accepted envelopes back from a running portal.
pub struct GenesisPullEnvelopesArgs {
    /// Portal base URL (for example `http://127.0.0.1:3017`). The
    /// `/api/v1/root-genesis/portal/envelopes` path is appended automatically.
    #[arg(long)]
    pub portal_url: String,

    /// Optional ceremony phase filter (Round1, Round2, Finalize, RootSigning, ...).
    #[arg(long)]
    pub phase: Option<String>,

    /// Optional payload-kind filter (Round1Package, Round2EncryptedPackage, ...).
    #[arg(long)]
    pub payload_kind: Option<String>,

    /// Optional recipient DID filter (for recipient-bound round-two packages).
    #[arg(long)]
    pub recipient_did: Option<String>,

    /// Output path for the JSON array of matching envelopes.
    #[arg(long)]
    pub output: Option<PathBuf>,
}

#[derive(Args)]
/// Submit a signed envelope to a running portal.
pub struct GenesisSubmitEnvelopeArgs {
    /// Portal base URL (for example `http://127.0.0.1:3017`). The
    /// `/api/v1/root-genesis/portal/envelopes` path is appended automatically
    /// when it is not already present.
    #[arg(long)]
    pub portal_url: String,

    /// Signed envelope JSON path to POST.
    #[arg(long)]
    pub input: Option<PathBuf>,
}

#[derive(Args)]
/// Distributed signing round one — emit a public commitment and a separate
/// local-only secret-nonces file.
///
/// The commitment is relay-safe and is broadcast to the coordinator; the nonces
/// file is SECRET, written `0600`, and must stay on the signer's host until
/// `sign-share`. They are written to two distinct paths so the secret nonces are
/// never co-located with the artifact that leaves the signer.
pub struct GenesisSignCommitArgs {
    /// Input JSON path (`config`, `key_package`).
    #[arg(long)]
    pub input: Option<PathBuf>,

    /// Output path for the PUBLIC `RootSigningCommitment` (safe to transmit to
    /// the coordinator). Refused if it already exists.
    #[arg(long)]
    pub commitment_out: PathBuf,

    /// Output path for the SECRET `RootSigningNonces` (`0600`, local-only, fed to
    /// `sign-share`). Refused if it already exists.
    #[arg(long)]
    pub nonces_out: PathBuf,
}

#[derive(Args)]
/// Distributed signing round two — produce one signer's signature share.
pub struct GenesisSignShareArgs {
    /// Input JSON path (`config`, `key_package`, `signing_package_hex`).
    #[arg(long)]
    pub input: Option<PathBuf>,

    /// Path to this signer's local-only `RootSigningNonces` file produced by
    /// `sign-commit --nonces-out`.
    #[arg(long)]
    pub nonces: PathBuf,

    /// Signature-share output path. Omit to print to stdout (the share is public).
    #[arg(long)]
    pub output: Option<PathBuf>,
}

#[cfg(test)]
mod tests {
    use clap::CommandFactory;

    use super::Cli;

    fn long_help_for(path: &[&str]) -> String {
        let mut command = Cli::command();
        let mut current = &mut command;
        for segment in path {
            current = current
                .find_subcommand_mut(segment)
                .expect("subcommand should exist");
        }
        let mut help = Vec::new();
        current
            .write_long_help(&mut help)
            .expect("help should render");
        String::from_utf8(help).expect("help should be utf8")
    }

    #[test]
    fn genesis_cli_exposes_complete_operator_command_set() {
        let help = long_help_for(&["genesis"]);
        for command in [
            "certifier",
            "ceremony",
            "portal",
            "round1",
            "round2",
            "finalize-dkg",
            "build-final-key-confirmation",
            "sign-root-artifact",
            "assemble-bundle",
            "verify-bundle",
            "seal-share",
            "unseal-share",
            "sign-envelope",
            "encrypt-pairwise",
            "decrypt-pairwise",
            "emit-artifact-bytes",
            "submit-envelope",
            "pull-envelopes",
            "compute-dkg-transcript-hash",
            "compute-final-transcript-hash",
            "encode-encrypted-payload",
            "decode-encrypted-payload",
            "sign-commit",
            "build-signing-package",
            "sign-share",
            "aggregate-signature",
        ] {
            assert!(help.contains(command), "missing genesis command {command}");
        }
    }

    #[test]
    fn genesis_build_round1_attestation_command_is_absent_pending_ratification() {
        // The unratified round-one set attestation command was removed; it must
        // not reappear on the production ceremony CLI until a ratified payload
        // shape lands and the portal validates it.
        let help = long_help_for(&["genesis"]);
        assert!(!help.contains("build-round1-attestation"));
    }

    #[test]
    fn genesis_sign_envelope_takes_no_signing_secret_through_argv() {
        use clap::Parser;

        // The signing secret comes from a `0600` private-material file path.
        let with_file = Cli::try_parse_from([
            "exochain",
            "genesis",
            "sign-envelope",
            "--input",
            "draft.json",
            "--private-input",
            "certifier-01.private.json",
            "--output",
            "envelope.json",
        ]);
        assert!(
            with_file.is_ok(),
            "private-material file path must be accepted"
        );

        // A 32-byte hex secret cannot be passed as a CLI argument: the old flag
        // is gone and any attempt to supply key material on argv is rejected.
        let with_argv_secret = Cli::try_parse_from([
            "exochain",
            "genesis",
            "sign-envelope",
            "--input",
            "draft.json",
            "--signing-key-hex",
            &"ab".repeat(32),
        ]);
        assert!(
            with_argv_secret.is_err(),
            "no CLI argument may carry 32-byte signing-secret material"
        );
    }

    #[test]
    fn genesis_cli_help_warns_certifiers_about_secret_handling_and_restart_rules() {
        let help = long_help_for(&["genesis"]);
        for required in [
            "7-of-13",
            "all 13 rostered certifiers",
            "abort and restart",
            "offline backup",
            "never submit plaintext shares",
            "explicit unique --output files",
            "verify-bundle",
        ] {
            assert!(help.contains(required), "missing help text {required}");
        }
    }
}