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
//
// Wildland Project
//
// Copyright © 2022 Golem Foundation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3 as published by
// the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

use std::path::PathBuf;

use anyhow::{anyhow, Context as _};
use reedline_repl_rs::clap::{Arg, ArgMatches, Command};
use reedline_repl_rs::Repl;
use s_macro::s;

use crate::{match_context, Context};

/*
   ===========================
   handler implementations
   ===========================
*/

#[tracing::instrument(level = "trace", err(Debug), skip(args, context))]
fn h_cargo_generate_mnemonic_to_file(
    args: ArgMatches,
    context: &mut Context,
) -> anyhow::Result<Option<String>> {
    let cargo = match_context!(context, cargo => Some(_))?;

    let filepath = args
        .get_one::<String>("filepath")
        .context("filepath not provided")?;
    let filepath = PathBuf::from(filepath);
    if !filepath.exists() {
        return Err(anyhow!("Filepath does not exist"));
    }
    let mnemonic = cargo
        .user_api()
        .generate_mnemonic()
        .context("Mnemonic generation error")?;

    let mut file = std::fs::File::create(filepath.clone())?;
    std::io::Write::write_all(&mut file, mnemonic.stringify().as_bytes())?;
    Ok(Some(format!(
        "{} created or replaced",
        filepath.as_path().to_str().unwrap()
    )))
}

#[tracing::instrument(level = "trace", err(Debug), skip(_args, context))]
fn h_cargo_generate_mnemonic_words(
    _args: ArgMatches,
    context: &mut Context,
) -> anyhow::Result<Option<String>> {
    let cargo = match_context!(context, cargo => Some(_))?;
    let mnemonic = cargo
        .user_api()
        .generate_mnemonic()
        .context("Mnemonic generation error")?;
    Ok(Some(mnemonic.stringify()))
}

#[tracing::instrument(level = "trace", err(Debug), skip(args, context))]
fn h_cargo_create_user_mnemonic_file(
    args: ArgMatches,
    context: &mut Context,
) -> anyhow::Result<Option<String>> {
    let cargo = match_context!(context, cargo => Some(_), cargo_user => None)?;
    let devicename = args
        .get_one::<String>("devicename")
        .context("device name not provided")?;
    let filepath = args
        .get_one::<String>("filepath")
        .context("mnemonic-containing file not provided")?;
    let filepath = PathBuf::from(filepath);

    let userapi = cargo.user_api();
    let mnemonic_string = std::fs::read_to_string(filepath)?;
    let mnemonic_payload = userapi
        .create_mnemonic_from_string(mnemonic_string)
        .context("Mnemonic creation error")?;

    _ = userapi
        .create_user_from_mnemonic(&mnemonic_payload, s!(devicename))
        .context("User creation error")?;
    context.set_cargo_user()?;
    Ok(Some(format!("User created with device {devicename}")))
}

#[tracing::instrument(level = "trace", err(Debug), skip(args, context))]
fn h_cargo_create_user_mnemonic_words(
    args: ArgMatches,
    context: &mut Context,
) -> anyhow::Result<Option<String>> {
    let cargo = match_context!(context, cargo => Some(_), cargo_user => None)?;
    let devicename = args
        .get_one::<String>("devicename")
        .context("device name not provided")?;
    let mnemonic_string = args
        .get_one::<String>("words")
        .context("mnemonic words not provided, remember to use \" \"")?;
    let userapi = cargo.user_api();
    let mnemonic_payload = userapi
        .create_mnemonic_from_string(s!(mnemonic_string))
        .context("Mnemonic creation error")?;

    _ = userapi
        .create_user_from_mnemonic(&mnemonic_payload, s!(devicename))
        .context("User creation error")?;
    context.set_cargo_user()?;
    Ok(Some(format!("User created with device {devicename}")))
}

#[tracing::instrument(level = "trace", err(Debug), skip(args, context))]
fn h_cargo_create_user_random(
    args: ArgMatches,
    context: &mut Context,
) -> anyhow::Result<Option<String>> {
    match_context!(context, cargo => Some(_))?;

    let devicename = args
        .get_one::<String>("devicename")
        .context("devicename not provided")?;

    let userapi = context.cargo.as_ref().unwrap().user_api();
    let mnemonic_payload = userapi
        .generate_mnemonic()
        .context("Mnemonic generation error")?;

    // we can drop the result, as it is already stored in the catlib,
    // just get_user() will return it
    _ = userapi
        .create_user_from_mnemonic(&mnemonic_payload, s!(devicename))
        .context("User creation error")?;
    context.set_cargo_user()?;
    Ok(Some(format!("User created with device {devicename}")))
}

// we will return user if it exists, i.e. handle is either loaded from lss or
// user was explicitely created
#[tracing::instrument(level = "trace", err(Debug), skip(_args, context))]
fn h_cargo_user_get(_args: ArgMatches, context: &mut Context) -> anyhow::Result<Option<String>> {
    match_context!(context, cargo => Some(_), cargo_user => Some(_))?;

    Ok(Some(format!(
        "User: {}",
        context.cargo_user.as_ref().unwrap().stringify()
    )))
}

#[tracing::instrument(level = "trace", err(Debug), skip(_args, context))]
fn h_cargo_user_get_public_key(
    _args: ArgMatches,
    context: &mut Context,
) -> anyhow::Result<Option<String>> {
    let cargo_user = match_context!(context, cargo_user => Some(_))?;
    let pubkey = cargo_user.get_user_public_key();
    Ok(Some(hex::encode(pubkey)))
}

// extend the repl with cargo commands
pub fn extend(repl: Repl<Context, anyhow::Error>) -> Repl<Context, anyhow::Error> {
    repl.with_command(
        Command::new("user-mnemonic-file")
            .about("generate mnemonic and save it to file")
            .arg(Arg::new("filepath").required(true).index(1)),
        h_cargo_generate_mnemonic_to_file,
    )
    .with_command(
        Command::new("user-mnemonic-words").about("generate menmonic and return it to console"),
        h_cargo_generate_mnemonic_words,
    )
    .with_command(
        Command::new("user-from-mnemonic-file")
            .about("create user from mnemonic-containing file")
            .arg(Arg::new("devicename").required(true).index(1))
            .arg(Arg::new("filepath").required(true).index(2)),
        h_cargo_create_user_mnemonic_file,
    )
    .with_command(
        Command::new("user-from-mnemonic-words")
            .about("create user from mnemonic argument")
            .arg(Arg::new("devicename").required(true).index(1))
            .arg(Arg::new("words").required(true).index(2)),
        h_cargo_create_user_mnemonic_words,
    )
    .with_command(
        Command::new("user-show").about("get stringified representation of user"),
        h_cargo_user_get,
    )
    .with_command(
        Command::new("user-create-random")
            .about("create user from random mnemonic")
            .arg(Arg::new("devicename").required(true).index(1)),
        h_cargo_create_user_random,
    )
    .with_command(
        Command::new("user-public-key").about("get user public key"),
        h_cargo_user_get_public_key,
    )
}