forked from hyperledger-iroha/iroha
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.rs
More file actions
1630 lines (1437 loc) · 52.6 KB
/
main.rs
File metadata and controls
1630 lines (1437 loc) · 52.6 KB
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
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Iroha client CLI
use std::{
fs::{self, read as read_file},
io::{stdin, stdout},
path::PathBuf,
str::FromStr,
time::Duration,
};
use erased_serde::Serialize;
use error_stack::{fmt::ColorMode, IntoReportCompat, ResultExt};
use eyre::{eyre, Error, Result, WrapErr};
use futures::TryStreamExt;
use iroha::{client::Client, config::Config, data_model::prelude::*};
use iroha_primitives::json::Json;
use thiserror::Error;
use tokio::runtime::Runtime;
/// Re-usable clap `--metadata <PATH>` (`-m`) argument.
/// Should be combined with `#[command(flatten)]` attr.
#[derive(clap::Args, Debug, Clone)]
pub struct MetadataArgs {
/// The JSON/JSON5 file with key-value metadata pairs
#[arg(short, long, value_name("PATH"), value_hint(clap::ValueHint::FilePath))]
metadata: Option<PathBuf>,
}
impl MetadataArgs {
fn load(self) -> Result<Metadata> {
let value: Option<Metadata> = self
.metadata
.map(|path| {
let content = fs::read_to_string(&path).wrap_err_with(|| {
eyre!("Failed to read the metadata file `{}`", path.display())
})?;
let metadata: Metadata = json5::from_str(&content).wrap_err_with(|| {
eyre!(
"Failed to deserialize metadata from file `{}`",
path.display()
)
})?;
Ok::<_, eyre::Report>(metadata)
})
.transpose()?;
Ok(value.unwrap_or_default())
}
}
/// Re-usable clap `--value <MetadataValue>` (`-v`) argument.
/// Should be combined with `#[command(flatten)]` attr.
#[derive(clap::Args, Debug, Clone, PartialEq, Eq)]
pub struct MetadataValueArg {
/// Wrapper around `MetadataValue` to accept possible values and fallback to json.
///
/// The following types are supported:
/// Numbers: decimal with optional point
/// Booleans: false/true
/// Objects: e.g. {"Vec":[{"String":"a"},{"String":"b"}]}
#[arg(short, long)]
value: Json,
}
impl FromStr for MetadataValueArg {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(MetadataValueArg {
value: Json::from_str(s)?,
})
}
}
/// Iroha CLI Client provides an ability to interact with Iroha Peers Web API without direct network usage.
#[derive(clap::Parser, Debug)]
#[command(name = "iroha", version = concat!("version=", env!("CARGO_PKG_VERSION"), " git_commit_sha=", env!("VERGEN_GIT_SHA")), author)]
struct Args {
/// Path to the configuration file
#[arg(short, long, value_name("PATH"), value_hint(clap::ValueHint::FilePath))]
#[clap(default_value = "client.toml")]
config: PathBuf,
/// More verbose output
#[arg(short, long)]
verbose: bool,
/// Subcommands of client cli
#[command(subcommand)]
subcommand: Subcommand,
}
#[derive(clap::Subcommand, Debug)]
enum Subcommand {
/// The subcommand related to domains
#[clap(subcommand)]
Domain(domain::Args),
/// The subcommand related to accounts
#[clap(subcommand)]
Account(account::Args),
/// The subcommand related to assets
#[clap(subcommand)]
Asset(asset::Args),
/// The subcommand related to p2p networking
#[clap(subcommand)]
Peer(peer::Args),
/// The subcommand related to event streaming
Events(events::Args),
/// The subcommand related to Wasm
Wasm(wasm::Args),
/// The subcommand related to block streaming
Blocks(blocks::Args),
/// The subcommand related to multi-instructions as Json or Json5
Json(json::Args),
/// The subcommand related to multisig accounts and transactions
#[clap(subcommand)]
Multisig(multisig::Args),
}
/// Context inside which command is executed
trait RunContext {
/// Get access to configuration
fn configuration(&self) -> &Config;
fn client_from_config(&self) -> Client {
Client::new(self.configuration().clone())
}
/// Serialize and print data
///
/// # Errors
/// - if serialization fails
/// - if printing fails
fn print_data(&mut self, data: &dyn Serialize) -> Result<()>;
}
struct PrintJsonContext<W> {
write: W,
config: Config,
}
impl<W: std::io::Write> RunContext for PrintJsonContext<W> {
fn configuration(&self) -> &Config {
&self.config
}
fn print_data(&mut self, data: &dyn Serialize) -> Result<()> {
writeln!(&mut self.write, "{}", serde_json::to_string_pretty(data)?)?;
Ok(())
}
}
/// Runs subcommand
trait RunArgs {
/// Runs command
///
/// # Errors
/// if inner command errors
fn run(self, context: &mut dyn RunContext) -> Result<()>;
}
macro_rules! match_all {
(($self:ident, $context:ident), { $($variants:path),* $(,)?}) => {
match $self {
$($variants(variant) => RunArgs::run(variant, $context),)*
}
};
}
impl RunArgs for Subcommand {
fn run(self, context: &mut dyn RunContext) -> Result<()> {
use Subcommand::*;
match_all!((self, context), { Domain, Account, Asset, Peer, Events, Wasm, Blocks, Json, Multisig })
}
}
#[derive(Error, Debug)]
enum MainError {
#[error("Failed to load Iroha client configuration")]
Config,
#[error("Failed to serialize config")]
SerializeConfig,
#[error("Failed to run the command")]
Subcommand,
}
fn main() -> error_stack::Result<(), MainError> {
let Args {
config: config_path,
subcommand,
verbose,
} = clap::Parser::parse();
error_stack::Report::set_color_mode(color_mode());
let config = Config::load(config_path)
// FIXME: would be nice to NOT change the context, it's unnecessary
.change_context(MainError::Config)
.attach_printable("config path was set by `--config` argument")?;
if verbose {
eprintln!(
"Configuration: {}",
&serde_json::to_string_pretty(&config)
.change_context(MainError::SerializeConfig)
.attach_printable("caused by `--verbose` argument")?
);
}
let mut context = PrintJsonContext {
write: stdout(),
config,
};
subcommand
.run(&mut context)
.into_report()
.map_err(|report| report.change_context(MainError::Subcommand))?;
Ok(())
}
fn color_mode() -> ColorMode {
if supports_color::on(supports_color::Stream::Stdout).is_some()
&& supports_color::on(supports_color::Stream::Stderr).is_some()
{
ColorMode::Color
} else {
ColorMode::None
}
}
/// Submit instruction with metadata to network.
///
/// # Errors
/// Fails if submitting over network fails
#[allow(clippy::shadow_unrelated)]
fn submit(
instructions: impl Into<Executable>,
metadata: Metadata,
context: &mut dyn RunContext,
) -> Result<()> {
let client = context.client_from_config();
let instructions = instructions.into();
let tx = client.build_transaction(instructions, metadata);
#[cfg(not(debug_assertions))]
let err_msg = "Failed to submit transaction.";
#[cfg(debug_assertions)]
let err_msg = format!("Failed to submit transaction {tx:?}");
let hash = client.submit_transaction_blocking(&tx).wrap_err(err_msg)?;
context.print_data(&hash)?;
Ok(())
}
mod filter {
use iroha::data_model::query::dsl::CompoundPredicate;
use serde::Deserialize;
use super::*;
/// Filter for domain queries
#[derive(Clone, Debug, clap::Parser)]
pub struct DomainFilter {
/// Predicate for filtering given as JSON5 string
#[clap(value_parser = parse_json5::<CompoundPredicate<Domain>>)]
pub predicate: CompoundPredicate<Domain>,
}
/// Filter for account queries
#[derive(Clone, Debug, clap::Parser)]
pub struct AccountFilter {
/// Predicate for filtering given as JSON5 string
#[clap(value_parser = parse_json5::<CompoundPredicate<Account>>)]
pub predicate: CompoundPredicate<Account>,
}
/// Filter for asset queries
#[derive(Clone, Debug, clap::Parser)]
pub struct AssetFilter {
/// Predicate for filtering given as JSON5 string
#[clap(value_parser = parse_json5::<CompoundPredicate<Asset>>)]
pub predicate: CompoundPredicate<Asset>,
}
/// Filter for asset definition queries
#[derive(Clone, Debug, clap::Parser)]
pub struct AssetDefinitionFilter {
/// Predicate for filtering given as JSON5 string
#[clap(value_parser = parse_json5::<CompoundPredicate<AssetDefinition>>)]
pub predicate: CompoundPredicate<AssetDefinition>,
}
fn parse_json5<T>(s: &str) -> Result<T, String>
where
T: for<'a> Deserialize<'a>,
{
json5::from_str(s).map_err(|err| format!("Failed to deserialize filter from JSON5: {err}"))
}
}
mod events {
use iroha::data_model::events::pipeline::{BlockEventFilter, TransactionEventFilter};
use super::*;
#[derive(clap::Args, Debug, Clone, Copy)]
pub struct Args {
/// Wait timeout
#[clap(short, long, global = true)]
timeout: Option<humantime::Duration>,
#[clap(subcommand)]
command: Command,
}
/// Get event stream from Iroha peer
#[derive(clap::Subcommand, Debug, Clone, Copy)]
enum Command {
/// Gets block pipeline events
BlockPipeline,
/// Gets transaction pipeline events
TransactionPipeline,
/// Gets data events
Data,
/// Get execute trigger events
ExecuteTrigger,
/// Get trigger completed events
TriggerCompleted,
}
impl RunArgs for Args {
fn run(self, context: &mut dyn RunContext) -> Result<()> {
let timeout: Option<Duration> = self.timeout.map(Into::into);
match self.command {
Command::TransactionPipeline => {
listen(TransactionEventFilter::default(), context, timeout)
}
Command::BlockPipeline => listen(BlockEventFilter::default(), context, timeout),
Command::Data => listen(DataEventFilter::Any, context, timeout),
Command::ExecuteTrigger => {
listen(ExecuteTriggerEventFilter::new(), context, timeout)
}
Command::TriggerCompleted => {
listen(TriggerCompletedEventFilter::new(), context, timeout)
}
}
}
}
fn listen(
filter: impl Into<EventFilterBox>,
context: &mut dyn RunContext,
timeout: Option<Duration>,
) -> Result<()> {
let filter = filter.into();
let client = context.client_from_config();
if let Some(timeout) = timeout {
eprintln!("Listening to events with filter: {filter:?} and timeout: {timeout:?}");
let rt = Runtime::new().wrap_err("Failed to create runtime.")?;
rt.block_on(async {
let mut stream = client
.listen_for_events_async([filter])
.await
.expect("Failed to listen for events.");
while let Ok(event) = tokio::time::timeout(timeout, stream.try_next()).await {
context.print_data(&event?)?;
}
eprintln!("Timeout period has expired.");
Result::<()>::Ok(())
})?;
} else {
eprintln!("Listening to events with filter: {filter:?}");
client
.listen_for_events([filter])
.wrap_err("Failed to listen for events.")?
.try_for_each(|event| context.print_data(&event?))?;
}
Ok(())
}
}
mod blocks {
use std::num::NonZeroU64;
use super::*;
/// Get block stream from Iroha peer
#[derive(clap::Args, Debug, Clone, Copy)]
pub struct Args {
/// Block height from which to start streaming blocks
height: NonZeroU64,
/// Wait timeout
#[clap(short, long)]
timeout: Option<humantime::Duration>,
}
impl RunArgs for Args {
fn run(self, context: &mut dyn RunContext) -> Result<()> {
let Args { height, timeout } = self;
let timeout: Option<Duration> = timeout.map(Into::into);
listen(height, context, timeout)
}
}
fn listen(
height: NonZeroU64,
context: &mut dyn RunContext,
timeout: Option<Duration>,
) -> Result<()> {
let client = context.client_from_config();
if let Some(timeout) = timeout {
eprintln!("Listening to blocks from height: {height} and timeout: {timeout:?}");
let rt = Runtime::new().wrap_err("Failed to create runtime.")?;
rt.block_on(async {
let mut stream = client
.listen_for_blocks_async(height)
.await
.expect("Failed to listen for blocks.");
while let Ok(event) = tokio::time::timeout(timeout, stream.try_next()).await {
context.print_data(&event?)?;
}
eprintln!("Timeout period has expired.");
Result::<()>::Ok(())
})?;
} else {
eprintln!("Listening to blocks from height: {height}");
client
.listen_for_blocks(height)
.wrap_err("Failed to listen for blocks.")?
.try_for_each(|event| context.print_data(&event?))?;
}
Ok(())
}
}
mod domain {
use super::*;
/// Arguments for domain subcommand
#[derive(Debug, clap::Subcommand)]
pub enum Args {
/// Register domain
Register(Register),
/// List domains
#[clap(subcommand)]
List(List),
/// Transfer domain
Transfer(Transfer),
/// Edit domain metadata
#[clap(subcommand)]
Metadata(metadata::Args),
}
impl RunArgs for Args {
fn run(self, context: &mut dyn RunContext) -> Result<()> {
match_all!((self, context), { Args::Register, Args::List, Args::Transfer, Args::Metadata, })
}
}
/// Add subcommand for domain
#[derive(Debug, clap::Args)]
pub struct Register {
/// Domain name as double-quoted string
#[arg(short, long)]
pub id: DomainId,
#[command(flatten)]
pub metadata: MetadataArgs,
}
impl RunArgs for Register {
fn run(self, context: &mut dyn RunContext) -> Result<()> {
let Self { id, metadata } = self;
let create_domain = iroha::data_model::isi::Register::domain(Domain::new(id));
submit([create_domain], metadata.load()?, context).wrap_err("Failed to create domain")
}
}
/// List domains with this command
#[derive(clap::Subcommand, Debug, Clone)]
pub enum List {
/// All domains
All,
/// Filter domains by given predicate
Filter(filter::DomainFilter),
}
impl RunArgs for List {
fn run(self, context: &mut dyn RunContext) -> Result<()> {
let client = context.client_from_config();
let query = client.query(FindDomains::new());
let query = match self {
List::All => query,
List::Filter(filter) => query.filter(filter.predicate),
};
let result = query.execute_all().wrap_err("Failed to get all accounts")?;
context.print_data(&result)?;
Ok(())
}
}
/// Transfer a domain between accounts
#[derive(Debug, clap::Args)]
pub struct Transfer {
/// Domain name as double-quited string
#[arg(short, long)]
pub id: DomainId,
/// Account from which to transfer (in form `name@domain_name`)
#[arg(short, long)]
pub from: AccountId,
/// Account to which to transfer (in form `name@domain_name`)
#[arg(short, long)]
pub to: AccountId,
#[command(flatten)]
pub metadata: MetadataArgs,
}
impl RunArgs for Transfer {
fn run(self, context: &mut dyn RunContext) -> Result<()> {
let Self {
id,
from,
to,
metadata,
} = self;
let transfer_domain = iroha::data_model::isi::Transfer::domain(from, id, to);
submit([transfer_domain], metadata.load()?, context)
.wrap_err("Failed to transfer domain")
}
}
mod metadata {
use iroha::data_model::domain::DomainId;
use super::*;
/// Edit domain subcommands
#[derive(Debug, Clone, clap::Subcommand)]
pub enum Args {
/// Set domain metadata
Set(Set),
/// Remove domain metadata
Remove(Remove),
}
impl RunArgs for Args {
fn run(self, context: &mut dyn RunContext) -> Result<()> {
match_all!((self, context), { Args::Set, Args::Remove, })
}
}
/// Set metadata into domain
#[derive(Debug, Clone, clap::Args)]
pub struct Set {
/// A domain id from which metadata is to be removed
#[arg(short, long)]
id: DomainId,
/// A key of metadata
#[arg(short, long)]
key: Name,
#[command(flatten)]
value: MetadataValueArg,
}
impl RunArgs for Set {
fn run(self, context: &mut dyn RunContext) -> Result<()> {
let Self {
id,
key,
value: MetadataValueArg { value },
} = self;
let set_key_value = SetKeyValue::domain(id, key, value);
submit([set_key_value], Metadata::default(), context)
.wrap_err("Failed to submit Set instruction")
}
}
/// Remove metadata into domain by key
#[derive(Debug, Clone, clap::Args)]
pub struct Remove {
/// A domain id from which metadata is to be removed
#[arg(short, long)]
id: DomainId,
/// A key of metadata
#[arg(short, long)]
key: Name,
}
impl RunArgs for Remove {
fn run(self, context: &mut dyn RunContext) -> Result<()> {
let Self { id, key } = self;
let remove_key_value = RemoveKeyValue::domain(id, key);
submit([remove_key_value], Metadata::default(), context)
.wrap_err("Failed to submit Remove instruction")
}
}
}
}
mod account {
use std::fmt::Debug;
use super::{Permission as DataModelPermission, *};
/// subcommands for account subcommand
#[derive(clap::Subcommand, Debug)]
pub enum Args {
/// Register account
Register(Register),
/// List accounts
#[command(subcommand)]
List(List),
/// Grant a permission to the account
Grant(Grant),
/// List all account permissions
ListPermissions(ListPermissions),
}
impl RunArgs for Args {
fn run(self, context: &mut dyn RunContext) -> Result<()> {
match_all!((self, context), {
Args::Register,
Args::List,
Args::Grant,
Args::ListPermissions,
})
}
}
/// Register account
#[derive(clap::Args, Debug)]
pub struct Register {
/// Id of account in form `name@domain_name`
#[arg(short, long)]
pub id: AccountId,
#[command(flatten)]
pub metadata: MetadataArgs,
}
impl RunArgs for Register {
fn run(self, context: &mut dyn RunContext) -> Result<()> {
let Self { id, metadata } = self;
let create_account = iroha::data_model::isi::Register::account(Account::new(id));
submit([create_account], metadata.load()?, context)
.wrap_err("Failed to register account")
}
}
/// List accounts with this command
#[derive(clap::Subcommand, Debug, Clone)]
pub enum List {
/// All accounts
All,
/// Filter accounts by given predicate
Filter(filter::AccountFilter),
}
impl RunArgs for List {
fn run(self, context: &mut dyn RunContext) -> Result<()> {
let client = context.client_from_config();
let query = client.query(FindAccounts::new());
let query = match self {
List::All => query,
List::Filter(filter) => query.filter(filter.predicate),
};
let result = query.execute_all().wrap_err("Failed to get all accounts")?;
context.print_data(&result)?;
Ok(())
}
}
#[derive(clap::Args, Debug)]
pub struct Grant {
/// Account id
#[arg(short, long)]
pub id: AccountId,
/// The JSON/JSON5 file with a permission token
#[arg(short, long)]
pub permission: Permission,
#[command(flatten)]
pub metadata: MetadataArgs,
}
/// [`DataModelPermission`] wrapper implementing [`FromStr`]
#[derive(Debug, Clone)]
pub struct Permission(DataModelPermission);
impl FromStr for Permission {
type Err = Error;
fn from_str(s: &str) -> Result<Self> {
let content = fs::read_to_string(s)
.wrap_err(format!("Failed to read the permission token file {}", &s))?;
let permission: DataModelPermission = json5::from_str(&content).wrap_err(format!(
"Failed to deserialize the permission token from file {}",
&s
))?;
Ok(Self(permission))
}
}
impl RunArgs for Grant {
fn run(self, context: &mut dyn RunContext) -> Result<()> {
let Self {
id,
permission,
metadata,
} = self;
let grant = iroha::data_model::isi::Grant::account_permission(permission.0, id);
submit([grant], metadata.load()?, context)
.wrap_err("Failed to grant the permission to the account")
}
}
/// List all account permissions
#[derive(clap::Args, Debug)]
pub struct ListPermissions {
/// Account id
#[arg(short, long)]
id: AccountId,
}
impl RunArgs for ListPermissions {
fn run(self, context: &mut dyn RunContext) -> Result<()> {
let client = context.client_from_config();
let find_all_permissions = FindPermissionsByAccountId::new(self.id);
let permissions = client
.query(find_all_permissions)
.execute_all()
.wrap_err("Failed to get all account permissions")?;
context.print_data(&permissions)?;
Ok(())
}
}
}
mod asset {
use iroha::data_model::name::Name;
use super::*;
/// Subcommand for dealing with asset
#[derive(clap::Subcommand, Debug)]
pub enum Args {
/// Command for managing asset definitions
#[clap(subcommand)]
Definition(definition::Args),
/// Command for minting asset in existing Iroha account
Mint(Mint),
/// Command for burning asset in existing Iroha account
Burn(Burn),
/// Transfer asset between accounts
Transfer(Transfer),
/// Get info of asset
Get(Get),
/// List assets
#[clap(subcommand)]
List(List),
/// Get a value from a Store asset
GetKeyValue(GetKeyValue),
/// Set a key-value entry in a Store asset
SetKeyValue(SetKeyValue),
/// Remove a key-value entry from a Store asset
RemoveKeyValue(RemoveKeyValue),
}
impl RunArgs for Args {
fn run(self, context: &mut dyn RunContext) -> Result<()> {
match_all!(
(self, context),
{ Args::Definition, Args::Mint, Args::Burn, Args::Transfer, Args::Get, Args::List, Args::SetKeyValue, Args::RemoveKeyValue, Args::GetKeyValue}
)
}
}
mod definition {
use iroha::data_model::asset::{AssetDefinition, AssetDefinitionId, AssetType};
use super::*;
/// Subcommand for managing asset definitions
#[derive(clap::Subcommand, Debug)]
pub enum Args {
/// Command for Registering a new asset
Register(Register),
/// List asset definitions
#[clap(subcommand)]
List(List),
}
impl RunArgs for Args {
fn run(self, context: &mut dyn RunContext) -> Result<()> {
match_all!(
(self, context),
{ Args::Register, Args::List }
)
}
}
/// Register subcommand of asset
#[derive(clap::Args, Debug)]
pub struct Register {
/// Asset definition id for registering (in form of `asset#domain_name`)
#[arg(long)]
pub id: AssetDefinitionId,
/// Mintability of asset
#[arg(short, long)]
pub unmintable: bool,
/// Value type stored in asset
#[arg(short, long)]
pub r#type: AssetType,
#[command(flatten)]
pub metadata: MetadataArgs,
}
impl RunArgs for Register {
fn run(self, context: &mut dyn RunContext) -> Result<()> {
let Self {
id: asset_id,
r#type,
unmintable,
metadata,
} = self;
let mut asset_definition = AssetDefinition::new(asset_id, r#type);
if unmintable {
asset_definition = asset_definition.mintable_once();
}
let create_asset_definition =
iroha::data_model::isi::Register::asset_definition(asset_definition);
submit([create_asset_definition], metadata.load()?, context)
.wrap_err("Failed to register asset")
}
}
/// List asset definitions with this command
#[derive(clap::Subcommand, Debug, Clone)]
pub enum List {
/// All asset definitions
All,
/// Filter asset definitions by given predicate
Filter(filter::AssetDefinitionFilter),
}
impl RunArgs for List {
fn run(self, context: &mut dyn RunContext) -> Result<()> {
let client = context.client_from_config();
let query = client.query(FindAssetsDefinitions::new());
let query = match self {
List::All => query,
List::Filter(filter) => query.filter(filter.predicate),
};
let result = query
.execute_all()
.wrap_err("Failed to get all asset definitions")?;
context.print_data(&result)?;
Ok(())
}
}
}
/// Command for minting asset in existing Iroha account
#[derive(clap::Args, Debug)]
pub struct Mint {
/// Asset id for the asset (in form of `asset##account@domain_name`)
#[arg(long)]
pub id: AssetId,
/// Quantity to mint
#[arg(short, long)]
pub quantity: Numeric,
#[command(flatten)]
pub metadata: MetadataArgs,
}
impl RunArgs for Mint {
fn run(self, context: &mut dyn RunContext) -> Result<()> {
let Self {
id: asset_id,
quantity,
metadata,
} = self;
let mint_asset = iroha::data_model::isi::Mint::asset_numeric(quantity, asset_id);
submit([mint_asset], metadata.load()?, context)
.wrap_err("Failed to mint asset of type `Numeric`")
}
}
/// Command for minting asset in existing Iroha account
#[derive(clap::Args, Debug)]
pub struct Burn {
/// Asset id for the asset (in form of `asset##account@domain_name`)
#[arg(long)]
pub id: AssetId,
/// Quantity to mint
#[arg(short, long)]
pub quantity: Numeric,
#[command(flatten)]
pub metadata: MetadataArgs,
}
impl RunArgs for Burn {
fn run(self, context: &mut dyn RunContext) -> Result<()> {
let Self {
id: asset_id,
quantity,
metadata,
} = self;
let burn_asset = iroha::data_model::isi::Burn::asset_numeric(quantity, asset_id);
submit([burn_asset], metadata.load()?, context)
.wrap_err("Failed to burn asset of type `Numeric`")
}
}
/// Transfer asset between accounts
#[derive(clap::Args, Debug)]
pub struct Transfer {
/// Account to which to transfer (in form `name@domain_name`)
#[arg(long)]
pub to: AccountId,
/// Asset id to transfer (in form like `asset##account@domain_name`)
#[arg(long)]
pub id: AssetId,
/// Quantity of asset as number
#[arg(short, long)]
pub quantity: Numeric,
#[command(flatten)]
pub metadata: MetadataArgs,
}
impl RunArgs for Transfer {
fn run(self, context: &mut dyn RunContext) -> Result<()> {
let Self {
to,
id: asset_id,
quantity,
metadata,
} = self;
let transfer_asset =
iroha::data_model::isi::Transfer::asset_numeric(asset_id, quantity, to);
submit([transfer_asset], metadata.load()?, context).wrap_err("Failed to transfer asset")
}
}
/// Get info of asset
#[derive(clap::Args, Debug)]
pub struct Get {
/// Asset id for the asset (in form of `asset##account@domain_name`)
#[arg(long)]
pub id: AssetId,
}
impl RunArgs for Get {
fn run(self, context: &mut dyn RunContext) -> Result<()> {
let Self { id: asset_id } = self;
let client = context.client_from_config();
let asset = client
.query(FindAssets::new())
.filter_with(|asset| asset.id.eq(asset_id))
.execute_single()
.wrap_err("Failed to get asset.")?;
context.print_data(&asset)?;
Ok(())
}
}
/// List assets with this command
#[derive(clap::Subcommand, Debug, Clone)]
pub enum List {
/// All assets
All,
/// Filter assets by given predicate
Filter(filter::AssetFilter),
}
impl RunArgs for List {
fn run(self, context: &mut dyn RunContext) -> Result<()> {
let client = context.client_from_config();
let query = client.query(FindAssets::new());
let query = match self {
List::All => query,
List::Filter(filter) => query.filter(filter.predicate),
};
let result = query.execute_all().wrap_err("Failed to get all accounts")?;
context.print_data(&result)?;
Ok(())