vade-evan 0.3.0

zero-knowledge-proof VC and TnT DID handling for vade
Documentation
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
/*
  Copyright (c) 2018-present evan GmbH.

  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.
*/

extern crate clap;

mod vade_utils;

use clap::{App, AppSettings, Arg, ArgMatches, SubCommand};
use vade::Vade;
use vade_utils::get_vade as get_vade_from_utils;

macro_rules! wrap_vade2 {
    ($func_name:ident, $sub_m:ident) => {{
        let options = get_argument_value($sub_m, "options", None);
        let payload = get_argument_value($sub_m, "payload", None);
        get_vade($sub_m)?.$func_name(&options, &payload).await?
    }};
}

macro_rules! wrap_vade3 {
    ($func_name:ident, $sub_m:ident) => {{
        let method = get_argument_value($sub_m, "method", None);
        let options = get_argument_value($sub_m, "options", None);
        let payload = get_argument_value($sub_m, "payload", None);
        get_vade($sub_m)?
            .$func_name(&method, &options, &payload)
            .await?
    }};
}

const EVAN_METHOD: &str = "did:evan";
const TYPE_OPTIONS_CL: &str = r###"{ "type": "cl" }"###;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let matches = get_argument_matches()?;

    let results = match matches.subcommand() {
        ("did", Some(sub_m)) => match sub_m.subcommand() {
            #[cfg(feature = "did-write")]
            ("create", Some(sub_m)) => {
                let method = get_argument_value(&sub_m, "method", None);
                let options = get_argument_value(&sub_m, "options", None);
                get_vade(&sub_m)?
                    .did_create(&method, &options, &String::new())
                    .await?
            }
            #[cfg(feature = "did-read")]
            ("resolve", Some(sub_m)) => {
                let did = get_argument_value(&sub_m, "did", None);
                get_vade(&sub_m)?.did_resolve(&did).await?
            }
            #[cfg(feature = "did-write")]
            ("update", Some(sub_m)) => {
                let did = get_argument_value(&sub_m, "did", None);
                let options = get_argument_value(&sub_m, "options", None);
                let payload = get_argument_value(&sub_m, "payload", None);
                get_vade(&sub_m)?
                    .did_update(&did, &options, &payload)
                    .await?
            }
            _ => {
                return Err(Box::from(clap::Error::with_description(
                    "invalid subcommand",
                    clap::ErrorKind::InvalidSubcommand,
                )));
            }
        },
        ("didcomm", Some(sub_m)) => match sub_m.subcommand() {
            ("send", Some(sub_m)) => {
                wrap_vade2!(didcomm_send, sub_m)
            }
            ("receive", Some(sub_m)) => {
                wrap_vade2!(didcomm_receive, sub_m)
            }
            ("create_keys", Some(sub_m)) => {
                get_vade(&sub_m)?
                    .run_custom_function(EVAN_METHOD, "create_keys", "{}", "{}")
                    .await?
            }
            ("query_didcomm_messages", Some(sub_m)) => {
                let payload = get_argument_value(&sub_m, "payload", None);
                get_vade(&sub_m)?
                    .run_custom_function(EVAN_METHOD, "query_didcomm_messages", "{}", &payload)
                    .await?
            }
            _ => {
                return Err(Box::from(clap::Error::with_description(
                    "invalid subcommand",
                    clap::ErrorKind::InvalidSubcommand,
                )));
            }
        },
        ("vc_zkp", Some(sub_m)) => match sub_m.subcommand() {
            #[cfg(feature = "vc-zkp-cl")]
            ("create_credential_definition", Some(sub_m)) => {
                wrap_vade3!(vc_zkp_create_credential_definition, sub_m)
            }
            #[cfg(any(feature = "vc-zkp-cl", feature = "vc-zkp-bbs"))]
            ("create_credential_schema", Some(sub_m)) => {
                wrap_vade3!(vc_zkp_create_credential_schema, sub_m)
            }
            #[cfg(any(feature = "vc-zkp-cl", feature = "vc-zkp-bbs"))]
            ("create_master_secret", Some(sub_m)) => {
                let options = get_argument_value(sub_m, "options", None);
                get_vade(&sub_m)?
                    .run_custom_function(EVAN_METHOD, "create_master_secret", options, "")
                    .await?
            }
            #[cfg(any(feature = "vc-zkp-cl", feature = "vc-zkp-bbs"))]
            ("create_revocation_registry_definition", Some(sub_m)) => {
                wrap_vade3!(vc_zkp_create_revocation_registry_definition, sub_m)
            }
            #[cfg(feature = "vc-zkp-cl")]
            ("generate_safe_prime", Some(sub_m)) => {
                get_vade(&sub_m)?
                    .run_custom_function(EVAN_METHOD, "generate_safe_prime", TYPE_OPTIONS_CL, "")
                    .await?
            }
            #[cfg(feature = "vc-zkp-bbs")]
            ("create_new_keys", Some(sub_m)) => {
                let payload = get_argument_value(sub_m, "payload", None);
                let options = get_argument_value(sub_m, "options", None);
                get_vade(&sub_m)?
                    .run_custom_function(EVAN_METHOD, "create_new_keys", options, payload)
                    .await?
            }
            #[cfg(any(feature = "vc-zkp-cl", feature = "vc-zkp-bbs", feature = "vc-jwt"))]
            ("issue_credential", Some(sub_m)) => {
                wrap_vade3!(vc_zkp_issue_credential, sub_m)
            }
            #[cfg(any(feature = "vc-zkp-cl", feature = "vc-zkp-bbs"))]
            ("finish_credential", Some(sub_m)) => {
                wrap_vade3!(vc_zkp_finish_credential, sub_m)
            }
            #[cfg(any(feature = "vc-zkp-cl", feature = "vc-zkp-bbs"))]
            ("create_credential_offer", Some(sub_m)) => {
                wrap_vade3!(vc_zkp_create_credential_offer, sub_m)
            }
            #[cfg(any(feature = "vc-zkp-cl", feature = "vc-zkp-bbs"))]
            ("present_proof", Some(sub_m)) => {
                wrap_vade3!(vc_zkp_present_proof, sub_m)
            }
            #[cfg(any(feature = "vc-zkp-cl", feature = "vc-zkp-bbs"))]
            ("create_credential_proposal", Some(sub_m)) => {
                wrap_vade3!(vc_zkp_create_credential_proposal, sub_m)
            }
            #[cfg(any(feature = "vc-zkp-cl", feature = "vc-zkp-bbs"))]
            ("request_credential", Some(sub_m)) => {
                wrap_vade3!(vc_zkp_request_credential, sub_m)
            }
            #[cfg(any(feature = "vc-zkp-cl", feature = "vc-zkp-bbs"))]
            ("request_proof", Some(sub_m)) => {
                wrap_vade3!(vc_zkp_request_proof, sub_m)
            }
            #[cfg(any(feature = "vc-zkp-cl", feature = "vc-zkp-bbs"))]
            ("revoke_credential", Some(sub_m)) => {
                wrap_vade3!(vc_zkp_revoke_credential, sub_m)
            }
            #[cfg(any(feature = "vc-zkp-cl", feature = "vc-zkp-bbs", feature = "vc-jwt"))]
            ("verify_proof", Some(sub_m)) => {
                wrap_vade3!(vc_zkp_verify_proof, sub_m)
            }
            _ => {
                return Err(Box::from(clap::Error::with_description(
                    "invalid subcommand",
                    clap::ErrorKind::InvalidSubcommand,
                )));
            }
        },
        _ => {
            return Err(Box::from(clap::Error::with_description(
                "invalid subcommand",
                clap::ErrorKind::InvalidSubcommand,
            )));
        }
    };
    if results.is_empty() {
        panic!("no results");
    }

    let empty_result = String::new();
    let result_string = results[0]
        .as_ref()
        .or(Some(&empty_result))
        .unwrap()
        .to_string();

    println!("{}", &result_string);

    Ok(())
}

fn get_app<'a>() -> Result<App<'a, 'a>, Box<dyn std::error::Error>> {
    Ok(App::new("vade_evan_bin")
        .version("0.0.8")
        .author("evan GmbH")
        .about("Allows you to use to work with DIDs and zero knowledge proof VCs on Trust and Trace")
        .setting(AppSettings::DeriveDisplayOrder)
        .setting(AppSettings::SubcommandRequiredElseHelp)
        .subcommand(
            SubCommand::with_name("did")
                .about("Works with DIDs on TRUST & TRACE.")
                .setting(AppSettings::DeriveDisplayOrder)
                .setting(AppSettings::SubcommandRequiredElseHelp)
                .subcommand(
                    SubCommand::with_name("create")
                        .about("Creates a new DID on substrate.")
                        .arg(get_clap_argument("method")?)
                        .arg(get_clap_argument("options")?)
                        .arg(get_clap_argument("target")?)
                        .arg(get_clap_argument("signer")?),
                )
                .subcommand(
                    SubCommand::with_name("resolve")
                        .about("Fetch data about a DID, which returns this DID's DID document.")
                        .arg(get_clap_argument("did")?)
                        .arg(get_clap_argument("target")?)
                        .arg(get_clap_argument("signer")?),
                )
                .subcommand(
                    SubCommand::with_name("update")
                        .about(r###"Updates data related to a DID. Two updates are supported depending on the value of `options.operation`.
            - whitelistIdentity: whitelists identity `did` on substrate, this is required to be able to perform transactions this this identity
            - setDidDocument: sets the DID document for `did`"###)
                        .arg(get_clap_argument("did")?)
                        .arg(get_clap_argument("options")?)
                        .arg(get_clap_argument("payload")?)
                        .arg(get_clap_argument("target")?)
                        .arg(get_clap_argument("signer")?),
                )
        )
        .subcommand(
            SubCommand::with_name("didcomm")
                .about("Processes DIDComm message")
                .setting(AppSettings::DeriveDisplayOrder)
                .setting(AppSettings::SubcommandRequiredElseHelp)
                .subcommand(
                    SubCommand::with_name("send")
                        .about(r###"Prepare a plain DIDComm json message to be sent, including encryption and protocol specific message enhancement.
The DIDComm options can include a shared secret to encrypt the message with a specific key.
If no key was given and the message should be encrypted (depends on protocol implementation), the DIDComm keypair from a db provider will be used."###)
                        .arg(get_clap_argument("options")?)
                        .arg(get_clap_argument("payload")?),
                )
                .subcommand(
                    SubCommand::with_name("receive")
                        .about(r###"Receive a plain DIDComm json message, including decryption and protocol specific message parsing.
The DIDComm options can include a shared secret to encrypt the message with a specific key.
If no key was given and the message is encrypted the DIDComm keypair from a db will be used."###)
                        .arg(get_clap_argument("options")?)
                        .arg(get_clap_argument("payload")?),
                )
                .subcommand(
                    SubCommand::with_name("create_keys")
                        .about(r###"Create X25519 secret/public keys, which can be used in options while sending and receiving DIDComm message."###)
                )
                .subcommand(
                    SubCommand::with_name("query_didcomm_messages")
                        .about(r###"Query stored DIDComm messages by prefix (message_{thid}_*) or messageid (message_{thid}_{msgid})."###)
                        .arg(get_clap_argument("payload")?),
                )
        )
        .subcommand(
            SubCommand::with_name("vc_zkp")
                .about("Works with zero knowledge proof VCs on TRUST & TRACE.")
                .setting(AppSettings::DeriveDisplayOrder)
                .setting(AppSettings::SubcommandRequiredElseHelp)
                .subcommand(
                    SubCommand::with_name("create_master_secret")
                        .about("Creates a new master secret.")
                        .arg(get_clap_argument("options")?)
                )
                .subcommand(
                    SubCommand::with_name("create_new_keys")
                        .about("Creates a new key pair and stores it in the DID document.")
                        .arg(get_clap_argument("options")?)
                        .arg(get_clap_argument("payload")?)
                        .arg(get_clap_argument("signer")?),
                )
                .subcommand(
                    SubCommand::with_name("generate_safe_prime")
                        .about("Generates a new safe prime number, that can be used in combination with `create_credential_definition` to for key pair generation.")
                )
                .subcommand(
                    SubCommand::with_name("create_credential_definition")
                        .about("Creates a new credential definition and stores the public part on-chain. The private part (key) needs to be stored in a safe way and must not be shared. A credential definition holds cryptographic material needed to verify proofs. Every definition is bound to one credential schema. Note that `options.identity` needs to be whitelisted for this function.")
                        .arg(get_clap_argument("method")?)
                        .arg(get_clap_argument("options")?)
                        .arg(get_clap_argument("payload")?)
                        .arg(get_clap_argument("target")?)
                        .arg(get_clap_argument("signer")?),
                )
                .subcommand(
                    SubCommand::with_name("create_credential_schema")
                        .about("Creates a new zero-knowledge proof credential schema. Note that `options.identity` needs to be whitelisted for this function.")
                        .arg(get_clap_argument("method")?)
                        .arg(get_clap_argument("options")?)
                        .arg(get_clap_argument("payload")?)
                        .arg(get_clap_argument("target")?)
                        .arg(get_clap_argument("signer")?),
                )
                .subcommand(
                    SubCommand::with_name("create_revocation_registry_definition")
                        .about("Creates a new revocation registry definition and stores it on-chain. The definition consists of a public and a private part. The public part holds the cryptographic material needed to create non-revocation proofs. The private part needs to reside with the registry owner and is used to revoke credentials. Note that `options.identity` needs to be whitelisted for this function.")
                        .arg(get_clap_argument("method")?)
                        .arg(get_clap_argument("options")?)
                        .arg(get_clap_argument("payload")?)
                        .arg(get_clap_argument("target")?)
                        .arg(get_clap_argument("signer")?),
                )
                .subcommand(
                    SubCommand::with_name("issue_credential")
                        .about("Finishes a credential by incorporating the prover's master secret into the credential signature after issuance.")
                        .arg(get_clap_argument("method")?)
                        .arg(get_clap_argument("options")?)
                        .arg(get_clap_argument("payload")?)
                        .arg(get_clap_argument("target")?)
                        .arg(get_clap_argument("signer")?),
                )
                .subcommand(
                    SubCommand::with_name("finish_credential")
                        .about("Issues a new credential. This requires an issued schema, credential definition, an active revocation registry and a credential request message.")
                        .arg(get_clap_argument("method")?)
                        .arg(get_clap_argument("options")?)
                        .arg(get_clap_argument("payload")?)
                        .arg(get_clap_argument("target")?)
                        .arg(get_clap_argument("signer")?),
                )
                .subcommand(
                    SubCommand::with_name("create_credential_offer")
                        .about("Creates a `CredentialOffer` message. A `CredentialOffer` is sent by an issuer and is the response to a `CredentialProposal`. The `CredentialOffer` specifies which schema and definition the issuer is capable and willing to use for credential issuance.")
                        .arg(get_clap_argument("method")?)
                        .arg(get_clap_argument("options")?)
                        .arg(get_clap_argument("payload")?)
                        .arg(get_clap_argument("target")?)
                        .arg(get_clap_argument("signer")?),
                )
                .subcommand(
                    SubCommand::with_name("present_proof")
                        .about("Presents a proof for one or more credentials. A proof presentation is the response to a proof request. The proof needs to incorporate all required fields from all required schemas requested in the proof request.")
                        .arg(get_clap_argument("method")?)
                        .arg(get_clap_argument("options")?)
                        .arg(get_clap_argument("payload")?)
                        .arg(get_clap_argument("target")?)
                        .arg(get_clap_argument("signer")?),
                )
                .subcommand(
                    SubCommand::with_name("create_credential_proposal")
                        .about("Creates a new zero-knowledge proof credential proposal. This message is the first in the credential issuance flow and is sent by the potential credential holder to the credential issuer.")
                        .arg(get_clap_argument("method")?)
                        .arg(get_clap_argument("options")?)
                        .arg(get_clap_argument("payload")?)
                        .arg(get_clap_argument("target")?)
                        .arg(get_clap_argument("signer")?),
                )
                .subcommand(
                    SubCommand::with_name("request_credential")
                        .about("Requests a credential. This message is the response to a credential offering and is sent by the potential credential holder. It incorporates the target schema, credential definition offered by the issuer, and the encoded values the holder wants to get signed. The credential is not stored on-chain and needs to be kept private.")
                        .arg(get_clap_argument("method")?)
                        .arg(get_clap_argument("options")?)
                        .arg(get_clap_argument("payload")?)
                        .arg(get_clap_argument("target")?)
                        .arg(get_clap_argument("signer")?),
                )
                .subcommand(
                    SubCommand::with_name("request_proof")
                        .about("Requests a zero-knowledge proof for one or more credentials issued under one or more specific schemas and is sent by a verifier to a prover. The proof request consists of the fields the verifier wants to be revealed per schema.")
                        .arg(get_clap_argument("method")?)
                        .arg(get_clap_argument("options")?)
                        .arg(get_clap_argument("payload")?)
                        .arg(get_clap_argument("target")?)
                        .arg(get_clap_argument("signer")?),
                )
                .subcommand(
                    SubCommand::with_name("revoke_credential")
                        .about("Revokes a credential. After revocation the published revocation registry needs to be updated with information returned by this function. To revoke a credential, tbe revoker must be in possession of the private key associated with the credential's revocation registry. After revocation, the published revocation registry must be updated. Only then is the credential truly revoked. Note that `options.identity` needs to be whitelisted for this function.")
                        .arg(get_clap_argument("method")?)
                        .arg(get_clap_argument("options")?)
                        .arg(get_clap_argument("payload")?)
                        .arg(get_clap_argument("target")?)
                        .arg(get_clap_argument("signer")?),
                )
                .subcommand(
                    SubCommand::with_name("verify_proof")
                        .about("Verifies a one or multiple proofs sent in a proof presentation.")
                        .arg(get_clap_argument("method")?)
                        .arg(get_clap_argument("options")?)
                        .arg(get_clap_argument("payload")?)
                        .arg(get_clap_argument("target")?)
                        .arg(get_clap_argument("signer")?),
                )
        )
    )
}

fn get_argument_matches<'a>() -> Result<ArgMatches<'a>, Box<dyn std::error::Error>> {
    Ok(get_app()?.get_matches())
}

fn get_argument_value<'a>(
    matches: &'a ArgMatches,
    arg_name: &'a str,
    fallback: Option<&'a str>,
) -> &'a str {
    match matches.value_of(arg_name) {
        Some(value) => value,
        None => match fallback {
            Some(value) => value,
            None => {
                panic!("no value for {} given", arg_name);
            }
        },
    }
}

fn get_vade(matches: &ArgMatches) -> Result<Vade, Box<dyn std::error::Error>> {
    let target = get_argument_value(&matches, "target", Some("substrate-dev.trust-trace.com"));
    let signer = get_argument_value(&matches, "signer", Some("local"));
    #[cfg(feature = "sdk")]
    let request_id = get_argument_value(&matches, "request_id", Some("local")).parse().expect("Request id should be Unsigned Integer");
    return get_vade_from_utils(
        target,
        signer,
        #[cfg(feature = "sdk")]
        request_id,
    );
}

fn get_clap_argument(arg_name: &str) -> Result<Arg, Box<dyn std::error::Error>> {
    Ok(match arg_name {
        "did" => Arg::with_name("did")
            .long("did")
            .short("d")
            .value_name("did")
            .required(true)
            .help("a DID to work on, e.g. 'did:evan:testcore:0x0d87204c3957d73b68ae28d0af961d3c72403906'")
            .takes_value(true),
        "method" => Arg::with_name("method")
            .long("method")
            .short("m")
            .value_name("method")
            .required(true)
            .help("method to work on, e.g. 'did:evan'")
            .takes_value(true),
        "options" => Arg::with_name("options")
            .long("options")
            .short("o")
            .value_name("options")
            .required(true)
            .help("options to send to vade call, serialized JSON, e.g. '{ \"identity\": \"...\", \"privateKey\": \"...\" }'")
            .takes_value(true),
        "payload" => Arg::with_name("payload")
            .long("payload")
            .short("p")
            .value_name("payload")
            .required(true)
            .help("options to send to vade call, serialized JSON, e.g. '{ \"foo\": \"bar\" }'")
            .takes_value(true),
        "target" => Arg::with_name("target")
            .long("target")
            .short("t")
            .value_name("target")
            .help("substrate to use for DID handling, e.g. '127.0.0.1'")
            .takes_value(true),
        "signer" => Arg::with_name("signer")
            .long("signer")
            .short("s")
            .value_name("signer")
            .help("signer to use to sign messages with, e.g. 'local' or 'remote|http://somewhere'")
            .takes_value(true),
        _ => {
            return Err(Box::from(format!("invalid arg_name: '{}'", &arg_name)));
        },
    })
}