-
Notifications
You must be signed in to change notification settings - Fork 137
/
command.rs
1476 lines (1393 loc) · 36.3 KB
/
command.rs
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
// Copyright 2021 The Grin Developers
//
// 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.
//! Grin wallet command-line function implementations
use crate::api::TLSConfig;
use crate::apiwallet::{try_slatepack_sync_workflow, Owner};
use crate::config::{TorConfig, WalletConfig, WALLET_CONFIG_FILE_NAME};
use crate::core::{core, global};
use crate::error::Error;
use crate::impls::PathToSlatepack;
use crate::impls::SlateGetter as _;
use crate::keychain;
use crate::libwallet::{
self, InitTxArgs, IssueInvoiceTxArgs, NodeClient, PaymentProof, Slate, SlateState, Slatepack,
SlatepackAddress, Slatepacker, SlatepackerArgs, WalletLCProvider,
};
use crate::util::secp::key::SecretKey;
use crate::util::{Mutex, ZeroingString};
use crate::{controller, display};
use ::core::time;
use qr_code::QrCode;
use serde_json as json;
use std::convert::TryFrom;
use std::fs::File;
use std::io::{Read, Write};
use std::sync::atomic::Ordering;
use std::sync::Arc;
use std::thread;
use std::time::Duration;
use uuid::Uuid;
fn show_recovery_phrase(phrase: ZeroingString) {
println!("Your recovery phrase is:");
println!();
println!("{}", &*phrase);
println!();
println!("Please back-up these words in a non-digital format.");
}
/// Arguments common to all wallet commands
#[derive(Clone)]
pub struct GlobalArgs {
pub account: String,
pub api_secret: Option<String>,
pub node_api_secret: Option<String>,
pub show_spent: bool,
pub password: Option<ZeroingString>,
pub tls_conf: Option<TLSConfig>,
}
/// Arguments for init command
pub struct InitArgs {
/// BIP39 recovery phrase length
pub list_length: usize,
pub password: ZeroingString,
pub config: WalletConfig,
pub recovery_phrase: Option<ZeroingString>,
pub restore: bool,
}
pub fn init<L, C, K>(
owner_api: &mut Owner<L, C, K>,
_g_args: &GlobalArgs,
args: InitArgs,
test_mode: bool,
) -> Result<(), Error>
where
L: WalletLCProvider<'static, C, K> + 'static,
C: NodeClient + 'static,
K: keychain::Keychain + 'static,
{
// Assume global chain type has already been initialized.
let chain_type = global::get_chain_type();
let mut w_lock = owner_api.wallet_inst.lock();
let p = w_lock.lc_provider()?;
p.create_config(&chain_type, WALLET_CONFIG_FILE_NAME, None, None, None)?;
p.create_wallet(
None,
args.recovery_phrase,
args.list_length,
args.password.clone(),
test_mode,
)?;
let m = p.get_mnemonic(None, args.password)?;
show_recovery_phrase(m);
Ok(())
}
/// Argument for recover
pub struct RecoverArgs {
pub passphrase: ZeroingString,
}
pub fn recover<L, C, K>(owner_api: &mut Owner<L, C, K>, args: RecoverArgs) -> Result<(), Error>
where
L: WalletLCProvider<'static, C, K> + 'static,
C: NodeClient + 'static,
K: keychain::Keychain + 'static,
{
let mut w_lock = owner_api.wallet_inst.lock();
let p = w_lock.lc_provider()?;
let m = p.get_mnemonic(None, args.passphrase)?;
show_recovery_phrase(m);
Ok(())
}
pub fn rewind_hash<'a, L, C, K>(
owner_api: &mut Owner<L, C, K>,
keychain_mask: Option<&SecretKey>,
) -> Result<(), Error>
where
L: WalletLCProvider<'static, C, K>,
C: NodeClient + 'static,
K: keychain::Keychain + 'static,
{
controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| {
let rewind_hash = api.get_rewind_hash(m)?;
println!();
println!("Wallet Rewind Hash");
println!("-------------------------------------");
println!("{}", rewind_hash);
println!();
Ok(())
})?;
Ok(())
}
/// Arguments for rewind hash view wallet scan command
pub struct ViewWalletScanArgs {
pub rewind_hash: String,
pub start_height: Option<u64>,
pub backwards_from_tip: Option<u64>,
}
pub fn scan_rewind_hash<L, C, K>(
owner_api: &mut Owner<L, C, K>,
args: ViewWalletScanArgs,
dark_scheme: bool,
) -> Result<(), Error>
where
L: WalletLCProvider<'static, C, K> + 'static,
C: NodeClient + 'static,
K: keychain::Keychain + 'static,
{
controller::owner_single_use(None, None, Some(owner_api), |api, m| {
let rewind_hash = args.rewind_hash;
let tip_height = api.node_height(m)?.height;
let start_height = match args.backwards_from_tip {
Some(b) => tip_height.saturating_sub(b),
None => match args.start_height {
Some(s) => s,
None => 1,
},
};
warn!(
"Starting view wallet output scan from height {} ...",
start_height
);
let result = api.scan_rewind_hash(rewind_hash, Some(start_height));
let deci_sec = time::Duration::from_millis(100);
thread::sleep(deci_sec);
match result {
Ok(res) => {
warn!("View wallet check complete");
if res.total_balance != 0 {
display::view_wallet_output(res.clone(), tip_height, dark_scheme)?;
}
display::view_wallet_balance(res.clone(), tip_height, dark_scheme);
Ok(())
}
Err(e) => {
error!("View wallet check failed: {}", e);
Err(e)
}
}
})?;
Ok(())
}
/// Arguments for listen command
pub struct ListenArgs {}
pub fn listen<L, C, K>(
owner_api: &mut Owner<L, C, K>,
keychain_mask: Arc<Mutex<Option<SecretKey>>>,
config: &WalletConfig,
tor_config: &TorConfig,
_args: &ListenArgs,
g_args: &GlobalArgs,
cli_mode: bool,
test_mode: bool,
) -> Result<(), Error>
where
L: WalletLCProvider<'static, C, K> + 'static,
C: NodeClient + 'static,
K: keychain::Keychain + 'static,
{
let wallet_inst = owner_api.wallet_inst.clone();
let config = config.clone();
let tor_config = tor_config.clone();
let g_args = g_args.clone();
let api_thread = thread::Builder::new()
.name("wallet-http-listener".to_string())
.spawn(move || {
let res = controller::foreign_listener(
wallet_inst,
keychain_mask,
&config.api_listen_addr(),
g_args.tls_conf.clone(),
tor_config.use_tor_listener,
test_mode,
Some(tor_config.clone()),
);
if let Err(e) = res {
error!("Error starting listener: {}", e);
}
});
if let Ok(t) = api_thread {
if !cli_mode {
let r = t.join();
if let Err(_) = r {
error!("Error starting listener");
return Err(Error::ListenerError);
}
}
}
Ok(())
}
pub fn owner_api<L, C, K>(
owner_api: &mut Owner<L, C, K>,
keychain_mask: Option<SecretKey>,
config: &WalletConfig,
tor_config: &TorConfig,
g_args: &GlobalArgs,
test_mode: bool,
) -> Result<(), Error>
where
L: WalletLCProvider<'static, C, K> + Send + Sync + 'static,
C: NodeClient + 'static,
K: keychain::Keychain + 'static,
{
// keychain mask needs to be a sinlge instance, in case the foreign API is
// also being run at the same time
let km = Arc::new(Mutex::new(keychain_mask));
let res = controller::owner_listener(
owner_api.wallet_inst.clone(),
km,
config.owner_api_listen_addr().as_str(),
g_args.api_secret.clone(),
g_args.tls_conf.clone(),
config.owner_api_include_foreign,
Some(tor_config.clone()),
test_mode,
);
if let Err(e) = res {
return Err(Error::LibWallet(e));
}
Ok(())
}
/// Arguments for account command
pub struct AccountArgs {
pub create: Option<String>,
}
pub fn account<L, C, K>(
owner_api: &mut Owner<L, C, K>,
keychain_mask: Option<&SecretKey>,
args: AccountArgs,
) -> Result<(), Error>
where
L: WalletLCProvider<'static, C, K> + 'static,
C: NodeClient + 'static,
K: keychain::Keychain + 'static,
{
if args.create.is_none() {
let res = controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| {
let acct_mappings = api.accounts(m)?;
// give logging thread a moment to catch up
thread::sleep(Duration::from_millis(200));
display::accounts(acct_mappings);
Ok(())
});
if let Err(e) = res {
error!("Error listing accounts: {}", e);
return Err(Error::LibWallet(e));
}
} else {
let label = args.create.unwrap();
let res = controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| {
api.create_account_path(m, &label)?;
thread::sleep(Duration::from_millis(200));
info!("Account: '{}' Created!", label);
Ok(())
});
if let Err(e) = res {
thread::sleep(Duration::from_millis(200));
error!("Error creating account '{}': {}", label, e);
return Err(Error::LibWallet(e));
}
}
Ok(())
}
/// Arguments for the send command
#[derive(Clone)]
pub struct SendArgs {
pub amount: u64,
pub amount_includes_fee: bool,
pub use_max_amount: bool,
pub minimum_confirmations: u64,
pub selection_strategy: String,
pub estimate_selection_strategies: bool,
pub late_lock: bool,
pub dest: String,
pub change_outputs: usize,
pub fluff: bool,
pub max_outputs: usize,
pub target_slate_version: Option<u16>,
pub payment_proof_address: Option<SlatepackAddress>,
pub ttl_blocks: Option<u64>,
pub skip_tor: bool,
pub outfile: Option<String>,
pub bridge: Option<String>,
pub slatepack_qr: bool,
}
pub fn send<L, C, K>(
owner_api: &mut Owner<L, C, K>,
keychain_mask: Option<&SecretKey>,
tor_config: Option<TorConfig>,
args: SendArgs,
dark_scheme: bool,
test_mode: bool,
) -> Result<(), Error>
where
L: WalletLCProvider<'static, C, K> + 'static,
C: NodeClient + 'static,
K: keychain::Keychain + 'static,
{
let mut slate = Slate::blank(2, false);
let mut amount = args.amount;
if args.use_max_amount {
controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| {
let (_, wallet_info) =
api.retrieve_summary_info(m, true, args.minimum_confirmations)?;
amount = wallet_info.amount_currently_spendable;
Ok(())
})?;
};
controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| {
if args.estimate_selection_strategies {
let strategies = vec!["smallest", "all"]
.into_iter()
.map(|strategy| {
let init_args = InitTxArgs {
src_acct_name: None,
amount: amount,
amount_includes_fee: Some(args.amount_includes_fee),
minimum_confirmations: args.minimum_confirmations,
max_outputs: args.max_outputs as u32,
num_change_outputs: args.change_outputs as u32,
selection_strategy_is_use_all: strategy == "all",
estimate_only: Some(true),
..Default::default()
};
let slate = api.init_send_tx(m, init_args)?;
Ok((strategy, slate.amount, slate.fee_fields))
})
.collect::<Result<Vec<_>, grin_wallet_libwallet::Error>>()?;
display::estimate(amount, strategies, dark_scheme);
return Ok(());
} else {
let init_args = InitTxArgs {
src_acct_name: None,
amount: amount,
amount_includes_fee: Some(args.amount_includes_fee),
minimum_confirmations: args.minimum_confirmations,
max_outputs: args.max_outputs as u32,
num_change_outputs: args.change_outputs as u32,
selection_strategy_is_use_all: args.selection_strategy == "all",
target_slate_version: args.target_slate_version,
payment_proof_recipient_address: args.payment_proof_address.clone(),
ttl_blocks: args.ttl_blocks,
send_args: None,
late_lock: Some(args.late_lock),
..Default::default()
};
let result = api.init_send_tx(m, init_args);
slate = match result {
Ok(s) => {
info!(
"Tx created: {} grin to {} (strategy '{}')",
core::amount_to_hr_string(amount, false),
args.dest,
args.selection_strategy,
);
s
}
Err(e) => {
info!("Tx not created: {}", e);
return Err(e);
}
};
}
Ok(())
})?;
if args.estimate_selection_strategies {
return Ok(());
}
let tor_config = match tor_config {
Some(mut c) => {
if let Some(b) = args.bridge.clone() {
c.bridge.bridge_line = Some(b);
}
c.skip_send_attempt = Some(args.skip_tor);
Some(c)
}
None => None,
};
let res = try_slatepack_sync_workflow(&slate, &args.dest, tor_config, None, false, test_mode);
match res {
Ok(Some(s)) => {
controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| {
api.tx_lock_outputs(m, &s)?;
let ret_slate = api.finalize_tx(m, &s)?;
let result = api.post_tx(m, &ret_slate, args.fluff);
match result {
Ok(_) => {
println!("Tx sent successfully",);
Ok(())
}
Err(e) => {
error!("Tx sent fail: {}", e);
Err(e.into())
}
}
})?;
}
Ok(None) => {
output_slatepack(
owner_api,
keychain_mask,
&slate,
args.dest.as_str(),
args.outfile,
true,
false,
args.slatepack_qr,
)?;
}
Err(e) => return Err(e.into()),
}
Ok(())
}
pub fn output_slatepack<L, C, K>(
owner_api: &mut Owner<L, C, K>,
keychain_mask: Option<&SecretKey>,
slate: &Slate,
dest: &str,
out_file_override: Option<String>,
lock: bool,
finalizing: bool,
show_qr: bool,
) -> Result<(), libwallet::Error>
where
L: WalletLCProvider<'static, C, K> + 'static,
C: NodeClient + 'static,
K: keychain::Keychain + 'static,
{
// Output the slatepack file to stdout and to a file
let mut message = String::from("");
let mut address = None;
let mut tld = String::from("");
controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| {
address = match SlatepackAddress::try_from(dest) {
Ok(a) => Some(a),
Err(_) => None,
};
// encrypt for recipient by default
let recipients = match address.clone() {
Some(a) => vec![a],
None => vec![],
};
message = api.create_slatepack_message(m, &slate, Some(0), recipients)?;
tld = api.get_top_level_directory()?;
Ok(())
})?;
// create a directory to which files will be output
let slate_dir = format!("{}/{}", tld, "slatepack");
let _ = std::fs::create_dir_all(slate_dir.clone());
let out_file_name = match out_file_override {
None => format!("{}/{}.{}.slatepack", slate_dir, slate.id, slate.state),
Some(f) => f,
};
if lock {
controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| {
api.tx_lock_outputs(m, &slate)?;
Ok(())
})?;
}
println!("{}", out_file_name);
let mut output = File::create(out_file_name.clone())?;
output.write_all(&message.as_bytes())?;
output.sync_all()?;
println!();
if !finalizing {
println!("Slatepack data follows. Please provide this output to the other party");
} else {
println!("Slatepack data follows.");
}
println!();
println!("--- CUT BELOW THIS LINE ---");
println!();
println!("{}", message);
println!("--- CUT ABOVE THIS LINE ---");
println!();
println!("Slatepack data was also output to");
println!();
println!("{}", out_file_name);
println!();
if show_qr {
if let Ok(qr_string) = QrCode::new(message) {
println!("{}", qr_string.to_string(false, 3));
println!();
}
}
if address.is_some() {
println!("The slatepack data is encrypted for the recipient only");
} else {
println!("The slatepack data is NOT encrypted");
}
println!();
Ok(())
}
// Parse a slate and slatepack from a message
pub fn parse_slatepack<L, C, K>(
owner_api: &mut Owner<L, C, K>,
keychain_mask: Option<&SecretKey>,
filename: Option<String>,
message: Option<String>,
) -> Result<(Slate, Option<SlatepackAddress>), Error>
where
L: WalletLCProvider<'static, C, K>,
C: NodeClient + 'static,
K: keychain::Keychain + 'static,
{
let mut ret_address = None;
let slate = match filename {
Some(f) => {
// otherwise, get slate from slatepack
let mut sl = None;
controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| {
let dec_key = api.get_slatepack_secret_key(m, 0)?;
let packer = Slatepacker::new(SlatepackerArgs {
sender: None,
recipients: vec![],
dec_key: Some(&dec_key),
});
let pts = PathToSlatepack::new(f.into(), &packer, true);
sl = Some(pts.get_tx()?.0);
ret_address = pts.get_slatepack(true)?.sender;
Ok(())
})?;
sl
}
None => None,
};
let slate = match slate {
Some(s) => s,
None => {
// try and parse directly from input_slatepack_message
let mut slate = Slate::blank(2, false);
match message {
Some(message) => {
controller::owner_single_use(
None,
keychain_mask,
Some(owner_api),
|api, m| {
slate =
api.slate_from_slatepack_message(m, message.clone(), vec![0])?;
let slatepack =
api.decode_slatepack_message(m, message.clone(), vec![0])?;
ret_address = slatepack.sender;
Ok(())
},
)?;
}
None => {
let msg = "No slate provided via file or direct input";
return Err(Error::GenericError(msg.into()).into());
}
}
slate
}
};
Ok((slate, ret_address))
}
/// Receive command argument
#[derive(Clone)]
pub struct ReceiveArgs {
pub input_file: Option<String>,
pub input_slatepack_message: Option<String>,
pub skip_tor: bool,
pub outfile: Option<String>,
pub bridge: Option<String>,
pub slatepack_qr: bool,
}
pub fn receive<L, C, K>(
owner_api: &mut Owner<L, C, K>,
keychain_mask: Option<&SecretKey>,
g_args: &GlobalArgs,
args: ReceiveArgs,
tor_config: Option<TorConfig>,
test_mode: bool,
) -> Result<(), Error>
where
L: WalletLCProvider<'static, C, K>,
C: NodeClient + 'static,
K: keychain::Keychain + 'static,
{
let (mut slate, ret_address) = parse_slatepack(
owner_api,
keychain_mask,
args.input_file,
args.input_slatepack_message,
)?;
let km = match keychain_mask.as_ref() {
None => None,
Some(&m) => Some(m.to_owned()),
};
let tor_config = match tor_config {
Some(mut c) => {
if let Some(b) = args.bridge {
c.bridge.bridge_line = Some(b);
}
c.skip_send_attempt = Some(args.skip_tor);
Some(c)
}
None => None,
};
controller::foreign_single_use(owner_api.wallet_inst.clone(), km, |api| {
slate = api.receive_tx(&slate, Some(&g_args.account), None)?;
Ok(())
})?;
let dest = match ret_address {
Some(a) => String::try_from(&a).unwrap(),
None => String::from(""),
};
let res = try_slatepack_sync_workflow(&slate, &dest, tor_config, None, true, test_mode);
match res {
Ok(Some(_)) => {
println!();
println!(
"Transaction recieved and sent back to sender at {} for finalization.",
dest
);
println!();
Ok(())
}
Ok(None) => {
output_slatepack(
owner_api,
keychain_mask,
&slate,
&dest,
args.outfile,
false,
false,
args.slatepack_qr,
)?;
Ok(())
}
Err(e) => Err(e.into()),
}
}
pub fn unpack<L, C, K>(
owner_api: &mut Owner<L, C, K>,
keychain_mask: Option<&SecretKey>,
args: ReceiveArgs,
) -> Result<(), Error>
where
L: WalletLCProvider<'static, C, K> + 'static,
C: NodeClient + 'static,
K: keychain::Keychain + 'static,
{
let mut slatepack = match args.input_file {
Some(f) => {
let packer = Slatepacker::new(SlatepackerArgs {
sender: None,
recipients: vec![],
dec_key: None,
});
PathToSlatepack::new(f.into(), &packer, true).get_slatepack(false)?
}
None => match args.input_slatepack_message {
Some(mes) => {
let mut sp = Slatepack::default();
controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| {
sp = api.decode_slatepack_message(m, mes, vec![])?;
Ok(())
})?;
sp
}
None => {
return Err(Error::ArgumentError("Invalid Slatepack Input".into()).into());
}
},
};
println!();
println!("SLATEPACK CONTENTS");
println!("------------------");
println!("{}", slatepack);
println!("------------------");
let packer = Slatepacker::new(SlatepackerArgs {
sender: None,
recipients: vec![],
dec_key: None,
});
if slatepack.mode == 1 {
controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| {
let dec_key = api.get_slatepack_secret_key(m, 0)?;
match slatepack.try_decrypt_payload(Some(&dec_key)) {
Ok(_) => {
println!("Slatepack is encrypted for this wallet");
println!();
println!("DECRYPTED SLATEPACK");
println!("-------------------");
println!("{}", slatepack);
let slate = packer.get_slate(&slatepack)?;
println!();
println!("DECRYPTED SLATE");
println!("---------------");
println!("{}", slate);
}
Err(_) => {
println!("Slatepack payload cannot be decrypted by this wallet");
}
}
Ok(())
})?;
} else {
let slate = packer.get_slate(&slatepack)?;
println!("Slatepack is not encrypted");
println!();
println!("SLATE");
println!("-----");
println!("{}", slate);
}
Ok(())
}
/// Finalize command args
#[derive(Clone)]
pub struct FinalizeArgs {
pub input_file: Option<String>,
pub input_slatepack_message: Option<String>,
pub fluff: bool,
pub nopost: bool,
pub outfile: Option<String>,
pub slatepack_qr: bool,
}
pub fn finalize<L, C, K>(
owner_api: &mut Owner<L, C, K>,
keychain_mask: Option<&SecretKey>,
args: FinalizeArgs,
) -> Result<(), Error>
where
L: WalletLCProvider<'static, C, K> + 'static,
C: NodeClient + 'static,
K: keychain::Keychain + 'static,
{
let (mut slate, _ret_address) = parse_slatepack(
owner_api,
keychain_mask,
args.input_file.clone(),
args.input_slatepack_message.clone(),
)?;
// Rather than duplicating the entire command, we'll just
// try to determine what kind of finalization this is
// based on the slate state
let is_invoice = slate.state == SlateState::Invoice2;
if is_invoice {
let km = match keychain_mask.as_ref() {
None => None,
Some(&m) => Some(m.to_owned()),
};
controller::foreign_single_use(owner_api.wallet_inst.clone(), km, |api| {
slate = api.finalize_tx(&slate, false)?;
Ok(())
})?;
} else {
controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| {
slate = api.finalize_tx(m, &slate)?;
Ok(())
})?;
}
if !&args.nopost {
controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| {
let result = api.post_tx(m, &slate, args.fluff);
match result {
Ok(_) => {
info!(
"Transaction sent successfully, check the wallet again for confirmation."
);
println!("Transaction posted");
Ok(())
}
Err(e) => {
error!("Tx not sent: {}", e);
Err(e)
}
}
})?;
}
println!("Transaction finalized successfully");
output_slatepack(
owner_api,
keychain_mask,
&slate,
"",
args.outfile,
false,
true,
args.slatepack_qr,
)?;
Ok(())
}
/// Issue Invoice Args
pub struct IssueInvoiceArgs {
/// Slatepack address
pub dest: String,
/// issue invoice tx args
pub issue_args: IssueInvoiceTxArgs,
/// output file override
pub outfile: Option<String>,
/// show slatepack as QR code
pub slatepack_qr: bool,
}
pub fn issue_invoice_tx<L, C, K>(
owner_api: &mut Owner<L, C, K>,
keychain_mask: Option<&SecretKey>,
args: IssueInvoiceArgs,
) -> Result<(), Error>
where
L: WalletLCProvider<'static, C, K> + 'static,
C: NodeClient + 'static,
K: keychain::Keychain + 'static,
{
let issue_args = args.issue_args.clone();
let mut slate = Slate::blank(2, false);
controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| {
slate = api.issue_invoice_tx(m, issue_args)?;
Ok(())
})?;
output_slatepack(
owner_api,
keychain_mask,
&slate,
args.dest.as_str(),
args.outfile,
false,
false,
args.slatepack_qr,
)?;
Ok(())
}
/// Arguments for the process_invoice command
pub struct ProcessInvoiceArgs {
pub minimum_confirmations: u64,
pub selection_strategy: String,
pub ret_address: Option<SlatepackAddress>,
pub max_outputs: usize,
pub slate: Slate,
pub estimate_selection_strategies: bool,
pub ttl_blocks: Option<u64>,
pub skip_tor: bool,
pub outfile: Option<String>,
pub bridge: Option<String>,
pub slatepack_qr: bool,
}
/// Process invoice
pub fn process_invoice<L, C, K>(
owner_api: &mut Owner<L, C, K>,
keychain_mask: Option<&SecretKey>,
tor_config: Option<TorConfig>,
args: ProcessInvoiceArgs,
dark_scheme: bool,
test_mode: bool,
) -> Result<(), Error>
where
L: WalletLCProvider<'static, C, K> + 'static,
C: NodeClient + 'static,
K: keychain::Keychain + 'static,
{
let mut slate = args.slate.clone();
let dest = match args.ret_address.clone() {
Some(a) => String::try_from(&a).unwrap(),
None => String::from(""),
};
controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| {
if args.estimate_selection_strategies {
let strategies = vec!["smallest", "all"]
.into_iter()
.map(|strategy| {
let init_args = InitTxArgs {
src_acct_name: None,
amount: slate.amount,
minimum_confirmations: args.minimum_confirmations,
max_outputs: args.max_outputs as u32,
num_change_outputs: 1u32,
selection_strategy_is_use_all: strategy == "all",
estimate_only: Some(true),
..Default::default()
};
let slate = api.init_send_tx(m, init_args).unwrap();
(strategy, slate.amount, slate.fee_fields)
})
.collect();
display::estimate(slate.amount, strategies, dark_scheme);
return Ok(());
} else {
let init_args = InitTxArgs {
src_acct_name: None,
amount: 0,
minimum_confirmations: args.minimum_confirmations,
max_outputs: args.max_outputs as u32,
num_change_outputs: 1u32,
selection_strategy_is_use_all: args.selection_strategy == "all",
ttl_blocks: args.ttl_blocks,
send_args: None,
..Default::default()
};
let result = api.process_invoice_tx(m, &slate, init_args);
slate = match result {
Ok(s) => {
info!(
"Invoice processed: {} grin (strategy '{}')",
core::amount_to_hr_string(slate.amount, false),
args.selection_strategy,
);
s
}
Err(e) => {
info!("Tx not created: {}", e);
return Err(e);
}
};