forked from mimblewimble/grin-wallet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathowner.rs
2554 lines (2454 loc) · 87.6 KB
/
owner.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.
//! Owner API External Definition
use chrono::prelude::*;
use ed25519_dalek::SecretKey as DalekSecretKey;
use uuid::Uuid;
use crate::config::{TorConfig, WalletConfig};
use crate::core::global;
use crate::impls::HttpSlateSender;
use crate::impls::SlateSender as _;
use crate::keychain::{Identifier, Keychain};
use crate::libwallet::api_impl::owner_updater::{start_updater_log_thread, StatusMessage};
use crate::libwallet::api_impl::{owner, owner_updater};
use crate::libwallet::{
AcctPathMapping, Error, InitTxArgs, IssueInvoiceTxArgs, NodeClient, NodeHeightResult,
OutputCommitMapping, PaymentProof, Slate, Slatepack, SlatepackAddress, TxLogEntry, ViewWallet,
WalletInfo, WalletInst, WalletLCProvider,
};
use crate::util::logger::LoggingConfig;
use crate::util::secp::key::SecretKey;
use crate::util::{from_hex, static_secp_instance, Mutex, ZeroingString};
use grin_wallet_util::OnionV3Address;
use std::convert::TryFrom;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{channel, Sender};
use std::sync::Arc;
use std::thread;
use std::time::Duration;
/// Main interface into all wallet API functions.
/// Wallet APIs are split into two seperate blocks of functionality
/// called the ['Owner'](struct.Owner.html) and ['Foreign'](struct.Foreign.html) APIs
///
/// * The 'Owner' API is intended to expose methods that are to be
/// used by the wallet owner only. It is vital that this API is not
/// exposed to anyone other than the owner of the wallet (i.e. the
/// person with access to the seed and password.
///
/// Methods in both APIs are intended to be 'single use', that is to say each
/// method will 'open' the wallet (load the keychain with its master seed), perform
/// its operation, then 'close' the wallet (unloading references to the keychain and master
/// seed).
pub struct Owner<L, C, K>
where
L: WalletLCProvider<'static, C, K> + 'static,
C: NodeClient + 'static,
K: Keychain + 'static,
{
/// contain all methods to manage the wallet
pub wallet_inst: Arc<Mutex<Box<dyn WalletInst<'static, L, C, K>>>>,
/// Flag to normalize some output during testing. Can mostly be ignored.
pub doctest_mode: bool,
/// retail TLD during doctest
pub doctest_retain_tld: bool,
/// Share ECDH key
pub shared_key: Arc<Mutex<Option<SecretKey>>>,
/// Update thread
updater: Arc<Mutex<owner_updater::Updater<'static, L, C, K>>>,
/// Stop state for update thread
pub updater_running: Arc<AtomicBool>,
/// Sender for update messages
status_tx: Mutex<Option<Sender<StatusMessage>>>,
/// Holds all update and status messages returned by the
/// updater process
updater_messages: Arc<Mutex<Vec<StatusMessage>>>,
/// Optional TOR configuration, holding address of sender and
/// data directory
tor_config: Mutex<Option<TorConfig>>,
}
impl<L, C, K> Owner<L, C, K>
where
L: WalletLCProvider<'static, C, K> + 'static,
C: NodeClient,
K: Keychain,
{
/// Create a new API instance with the given wallet instance. All subsequent
/// API calls will operate on this instance of the wallet.
///
/// Each method will call the [`WalletBackend`](../grin_wallet_libwallet/types/trait.WalletBackend.html)'s
/// [`open_with_credentials`](../grin_wallet_libwallet/types/trait.WalletBackend.html#tymethod.open_with_credentials)
/// (initialising a keychain with the master seed,) perform its operation, then close the keychain
/// with a call to [`close`](../grin_wallet_libwallet/types/trait.WalletBackend.html#tymethod.close)
///
/// # Arguments
/// * `wallet_in` - A reference-counted mutex containing an implementation of the
/// * `custom_channel` - A custom MPSC Tx/Rx pair to capture status
/// updates
/// [`WalletBackend`](../grin_wallet_libwallet/types/trait.WalletBackend.html) trait.
///
/// # Returns
/// * An instance of the OwnerApi holding a reference to the provided wallet
///
/// # Example
/// ```
/// use grin_wallet_util::grin_keychain as keychain;
/// use grin_wallet_util::grin_util as util;
/// use grin_wallet_util::grin_core;
/// use grin_wallet_api as api;
/// use grin_wallet_config as config;
/// use grin_wallet_impls as impls;
/// use grin_wallet_libwallet as libwallet;
///
/// use grin_core::global;
/// use keychain::ExtKeychain;
/// use tempfile::tempdir;
///
/// use std::sync::Arc;
/// use util::{Mutex, ZeroingString};
///
/// use api::Owner;
/// use config::WalletConfig;
/// use impls::{DefaultWalletImpl, DefaultLCProvider, HTTPNodeClient};
/// use libwallet::WalletInst;
///
/// global::set_local_chain_type(global::ChainTypes::AutomatedTesting);
///
/// let mut wallet_config = WalletConfig::default();
/// # let dir = tempdir().map_err(|e| format!("{:#?}", e)).unwrap();
/// # let dir = dir
/// # .path()
/// # .to_str()
/// # .ok_or("Failed to convert tmpdir path to string.".to_owned())
/// # .unwrap();
/// # wallet_config.data_file_dir = dir.to_owned();
///
/// // A NodeClient must first be created to handle communication between
/// // the wallet and the node.
/// let node_client = HTTPNodeClient::new(&wallet_config.check_node_api_http_addr, None).unwrap();
///
/// // impls::DefaultWalletImpl is provided for convenience in instantiating the wallet
/// // It contains the LMDBBackend, DefaultLCProvider (lifecycle) and ExtKeychain used
/// // by the reference wallet implementation.
/// // These traits can be replaced with alternative implementations if desired
///
/// let mut wallet = Box::new(DefaultWalletImpl::<'static, HTTPNodeClient>::new(node_client.clone()).unwrap())
/// as Box<WalletInst<'static, DefaultLCProvider<HTTPNodeClient, ExtKeychain>, HTTPNodeClient, ExtKeychain>>;
///
/// // Wallet LifeCycle Provider provides all functions init wallet and work with seeds, etc...
/// let lc = wallet.lc_provider().unwrap();
///
/// // The top level wallet directory should be set manually (in the reference implementation,
/// // this is provided in the WalletConfig)
/// let _ = lc.set_top_level_directory(&wallet_config.data_file_dir);
///
/// // Wallet must be opened with the password (TBD)
/// let pw = ZeroingString::from("wallet_password");
/// lc.open_wallet(None, pw, false, false);
///
/// // All wallet functions operate on an Arc::Mutex to allow multithreading where needed
/// let mut wallet = Arc::new(Mutex::new(wallet));
///
/// let api_owner = Owner::new(wallet.clone(), None);
/// // .. perform wallet operations
///
/// ```
pub fn new(
wallet_inst: Arc<Mutex<Box<dyn WalletInst<'static, L, C, K>>>>,
custom_channel: Option<Sender<StatusMessage>>,
) -> Self {
let updater_running = Arc::new(AtomicBool::new(false));
let updater = Arc::new(Mutex::new(owner_updater::Updater::new(
wallet_inst.clone(),
updater_running.clone(),
)));
let updater_messages = Arc::new(Mutex::new(vec![]));
let tx = match custom_channel {
Some(c) => c,
None => {
let (tx, rx) = channel();
let _ = start_updater_log_thread(rx, updater_messages.clone());
tx
}
};
Owner {
wallet_inst,
doctest_mode: false,
doctest_retain_tld: false,
shared_key: Arc::new(Mutex::new(None)),
updater,
updater_running,
status_tx: Mutex::new(Some(tx)),
updater_messages,
tor_config: Mutex::new(None),
}
}
/// Set the TOR configuration for this instance of the OwnerAPI, used during
/// `init_send_tx` when send args are present and a TOR address is specified
///
/// # Arguments
/// * `tor_config` - The optional [TorConfig](#) to use
/// # Returns
/// * Nothing
pub fn set_tor_config(&self, tor_config: Option<TorConfig>) {
let mut lock = self.tor_config.lock();
*lock = tor_config;
}
/// Returns a list of accounts stored in the wallet (i.e. mappings between
/// user-specified labels and BIP32 derivation paths.
/// # Arguments
/// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if
/// being used.
///
/// # Returns
/// * Result Containing:
/// * A Vector of [`AcctPathMapping`](../grin_wallet_libwallet/types/struct.AcctPathMapping.html) data
/// * or [`libwallet::Error`](../grin_wallet_libwallet/struct.Error.html) if an error is encountered.
///
/// # Remarks
///
/// * A wallet should always have the path with the label 'default' path defined,
/// with path m/0/0
/// * This method does not need to use the wallet seed or keychain.
///
/// # Example
/// Set up as in [`new`](struct.Owner.html#method.new) method above.
/// ```
/// # grin_wallet_api::doctest_helper_setup_doc_env!(wallet, wallet_config);
///
/// let api_owner = Owner::new(wallet.clone(), None);
///
/// let result = api_owner.accounts(None);
///
/// if let Ok(accts) = result {
/// //...
/// }
/// ```
pub fn accounts(
&self,
keychain_mask: Option<&SecretKey>,
) -> Result<Vec<AcctPathMapping>, Error> {
let mut w_lock = self.wallet_inst.lock();
let w = w_lock.lc_provider()?.wallet_inst()?;
// Test keychain mask, to keep API consistent
let _ = w.keychain(keychain_mask)?;
owner::accounts(&mut **w)
}
/// Creates a new 'account', which is a mapping of a user-specified
/// label to a BIP32 path
///
/// # Arguments
///
/// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if
/// being used.
/// * `label` - A human readable label to which to map the new BIP32 Path
///
/// # Returns
/// * Result Containing:
/// * A [Keychain Identifier](../grin_keychain/struct.Identifier.html) for the new path
/// * or [`libwallet::Error`](../grin_wallet_libwallet/struct.Error.html) if an error is encountered.
///
/// # Remarks
///
/// * Wallets should be initialised with the 'default' path mapped to `m/0/0`
/// * Each call to this function will increment the first element of the path
/// so the first call will create an account at `m/1/0` and the second at
/// `m/2/0` etc. . .
/// * The account path is used throughout as the parent key for most key-derivation
/// operations. See [`set_active_account`](struct.Owner.html#method.set_active_account) for
/// further details.
///
/// * This function does not need to use the root wallet seed or keychain.
///
/// # Example
/// Set up as in [`new`](struct.Owner.html#method.new) method above.
/// ```
/// # grin_wallet_api::doctest_helper_setup_doc_env!(wallet, wallet_config);
///
/// let api_owner = Owner::new(wallet.clone(), None);
///
/// let result = api_owner.create_account_path(None, "account1");
///
/// if let Ok(identifier) = result {
/// //...
/// }
/// ```
pub fn create_account_path(
&self,
keychain_mask: Option<&SecretKey>,
label: &str,
) -> Result<Identifier, Error> {
let mut w_lock = self.wallet_inst.lock();
let w = w_lock.lc_provider()?.wallet_inst()?;
owner::create_account_path(&mut **w, keychain_mask, label)
}
/// Sets the wallet's currently active account. This sets the
/// BIP32 parent path used for most key-derivation operations.
///
/// # Arguments
/// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if
/// being used.
/// * `label` - The human readable label for the account. Accounts can be retrieved via
/// the [`account`](struct.Owner.html#method.accounts) method
///
/// # Returns
/// * Result Containing:
/// * `Ok(())` if the path was correctly set
/// * or [`libwallet::Error`](../grin_wallet_libwallet/struct.Error.html) if an error is encountered.
///
/// # Remarks
///
/// * Wallet parent paths are 2 path elements long, e.g. `m/0/0` is the path
/// labelled 'default'. Keys derived from this parent path are 3 elements long,
/// e.g. the secret keys derived from the `m/0/0` path will be at paths `m/0/0/0`,
/// `m/0/0/1` etc...
///
/// * This function does not need to use the root wallet seed or keychain.
///
/// # Example
/// Set up as in [`new`](struct.Owner.html#method.new) method above.
/// ```
/// # grin_wallet_api::doctest_helper_setup_doc_env!(wallet, wallet_config);
///
/// let api_owner = Owner::new(wallet.clone(), None);
///
/// let result = api_owner.create_account_path(None, "account1");
///
/// if let Ok(identifier) = result {
/// // set the account active
/// let result2 = api_owner.set_active_account(None, "account1");
/// }
/// ```
pub fn set_active_account(
&self,
keychain_mask: Option<&SecretKey>,
label: &str,
) -> Result<(), Error> {
let mut w_lock = self.wallet_inst.lock();
let w = w_lock.lc_provider()?.wallet_inst()?;
// Test keychain mask, to keep API consistent
let _ = w.keychain(keychain_mask)?;
owner::set_active_account(&mut **w, label)
}
/// Returns a list of outputs from the active account in the wallet.
///
/// # Arguments
/// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if
/// being used.
/// * `include_spent` - If `true`, outputs that have been marked as 'spent'
/// in the wallet will be returned. If `false`, spent outputs will omitted
/// from the results.
/// * `refresh_from_node` - If true, the wallet will attempt to contact
/// a node (via the [`NodeClient`](../grin_wallet_libwallet/types/trait.NodeClient.html)
/// provided during wallet instantiation). If `false`, the results will
/// contain output information that may be out-of-date (from the last time
/// the wallet's output set was refreshed against the node).
/// Note this setting is ignored if the updater process is running via a call to
/// [`start_updater`](struct.Owner.html#method.start_updater)
/// * `tx_id` - If `Some(i)`, only return the outputs associated with
/// the transaction log entry of id `i`.
///
/// # Returns
/// * `(bool, Vec<OutputCommitMapping>)` - A tuple:
/// * The first `bool` element indicates whether the data was successfully
/// refreshed from the node (note this may be false even if the `refresh_from_node`
/// argument was set to `true`.
/// * The second element contains a vector of
/// [OutputCommitMapping](../grin_wallet_libwallet/types/struct.OutputCommitMapping.html)
/// of which each element is a mapping between the wallet's internal
/// [OutputData](../grin_wallet_libwallet/types/struct.Output.html)
/// and the Output commitment as identified in the chain's UTXO set
///
/// # Example
/// Set up as in [`new`](struct.Owner.html#method.new) method above.
/// ```
/// # grin_wallet_api::doctest_helper_setup_doc_env!(wallet, wallet_config);
///
/// let api_owner = Owner::new(wallet.clone(), None);
/// let show_spent = false;
/// let update_from_node = true;
/// let tx_id = None;
///
/// let result = api_owner.retrieve_outputs(None, show_spent, update_from_node, tx_id);
///
/// if let Ok((was_updated, output_mappings)) = result {
/// //...
/// }
/// ```
pub fn retrieve_outputs(
&self,
keychain_mask: Option<&SecretKey>,
include_spent: bool,
refresh_from_node: bool,
tx_id: Option<u32>,
) -> Result<(bool, Vec<OutputCommitMapping>), Error> {
let tx = {
let t = self.status_tx.lock();
t.clone()
};
let refresh_from_node = match self.updater_running.load(Ordering::Relaxed) {
true => false,
false => refresh_from_node,
};
owner::retrieve_outputs(
self.wallet_inst.clone(),
keychain_mask,
&tx,
include_spent,
refresh_from_node,
tx_id,
)
}
/// Returns a list of [Transaction Log Entries](../grin_wallet_libwallet/types/struct.TxLogEntry.html)
/// from the active account in the wallet.
///
/// # Arguments
/// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if
/// being used.
/// * `refresh_from_node` - If true, the wallet will attempt to contact
/// a node (via the [`NodeClient`](../grin_wallet_libwallet/types/trait.NodeClient.html)
/// provided during wallet instantiation). If `false`, the results will
/// contain transaction information that may be out-of-date (from the last time
/// the wallet's output set was refreshed against the node).
/// Note this setting is ignored if the updater process is running via a call to
/// [`start_updater`](struct.Owner.html#method.start_updater)
/// * `tx_id` - If `Some(i)`, only return the transactions associated with
/// the transaction log entry of id `i`.
/// * `tx_slate_id` - If `Some(uuid)`, only return transactions associated with
/// the given [`Slate`](../grin_wallet_libwallet/slate/struct.Slate.html) uuid.
///
/// # Returns
/// * `(bool, Vec<TxLogEntry)` - A tuple:
/// * The first `bool` element indicates whether the data was successfully
/// refreshed from the node (note this may be false even if the `refresh_from_node`
/// argument was set to `true`.
/// * The second element contains the set of retrieved
/// [TxLogEntries](../grin_wallet_libwallet/types/struct.TxLogEntry.html)
///
/// # Example
/// Set up as in [`new`](struct.Owner.html#method.new) method above.
/// ```
/// # grin_wallet_api::doctest_helper_setup_doc_env!(wallet, wallet_config);
///
/// let api_owner = Owner::new(wallet.clone(), None);
/// let update_from_node = true;
/// let tx_id = None;
/// let tx_slate_id = None;
///
/// // Return all TxLogEntries
/// let result = api_owner.retrieve_txs(None, update_from_node, tx_id, tx_slate_id);
///
/// if let Ok((was_updated, tx_log_entries)) = result {
/// //...
/// }
/// ```
pub fn retrieve_txs(
&self,
keychain_mask: Option<&SecretKey>,
refresh_from_node: bool,
tx_id: Option<u32>,
tx_slate_id: Option<Uuid>,
) -> Result<(bool, Vec<TxLogEntry>), Error> {
let tx = {
let t = self.status_tx.lock();
t.clone()
};
let refresh_from_node = match self.updater_running.load(Ordering::Relaxed) {
true => false,
false => refresh_from_node,
};
let mut res = owner::retrieve_txs(
self.wallet_inst.clone(),
keychain_mask,
&tx,
refresh_from_node,
tx_id,
tx_slate_id,
)?;
if self.doctest_mode {
res.1 = res
.1
.into_iter()
.map(|mut t| {
t.confirmation_ts = Some(Utc.ymd(2019, 1, 15).and_hms(16, 1, 26));
t.creation_ts = Utc.ymd(2019, 1, 15).and_hms(16, 1, 26);
t
})
.collect();
}
Ok(res)
}
/// Returns summary information from the active account in the wallet.
///
/// # Arguments
/// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if
/// being used.
/// * `refresh_from_node` - If true, the wallet will attempt to contact
/// a node (via the [`NodeClient`](../grin_wallet_libwallet/types/trait.NodeClient.html)
/// provided during wallet instantiation). If `false`, the results will
/// contain transaction information that may be out-of-date (from the last time
/// the wallet's output set was refreshed against the node).
/// Note this setting is ignored if the updater process is running via a call to
/// [`start_updater`](struct.Owner.html#method.start_updater)
/// * `minimum_confirmations` - The minimum number of confirmations an output
/// should have before it's included in the 'amount_currently_spendable' total
///
/// # Returns
/// * (`bool`, [`WalletInfo`](../grin_wallet_libwallet/types/struct.WalletInfo.html)) - A tuple:
/// * The first `bool` element indicates whether the data was successfully
/// refreshed from the node (note this may be false even if the `refresh_from_node`
/// argument was set to `true`.
/// * The second element contains the Summary [`WalletInfo`](../grin_wallet_libwallet/types/struct.WalletInfo.html)
///
/// # Example
/// Set up as in [`new`](struct.Owner.html#method.new) method above.
/// ```
/// # grin_wallet_api::doctest_helper_setup_doc_env!(wallet, wallet_config);
///
/// let mut api_owner = Owner::new(wallet.clone(), None);
/// let update_from_node = true;
/// let minimum_confirmations=10;
///
/// // Return summary info for active account
/// let result = api_owner.retrieve_summary_info(None, update_from_node, minimum_confirmations);
///
/// if let Ok((was_updated, summary_info)) = result {
/// //...
/// }
/// ```
pub fn retrieve_summary_info(
&self,
keychain_mask: Option<&SecretKey>,
refresh_from_node: bool,
minimum_confirmations: u64,
) -> Result<(bool, WalletInfo), Error> {
let tx = {
let t = self.status_tx.lock();
t.clone()
};
let refresh_from_node = match self.updater_running.load(Ordering::Relaxed) {
true => false,
false => refresh_from_node,
};
owner::retrieve_summary_info(
self.wallet_inst.clone(),
keychain_mask,
&tx,
refresh_from_node,
minimum_confirmations,
)
}
/// Initiates a new transaction as the sender, creating a new
/// [`Slate`](../grin_wallet_libwallet/slate/struct.Slate.html) object containing
/// the sender's inputs, change outputs, and public signature data. This slate can
/// then be sent to the recipient to continue the transaction via the
/// [Foreign API's `receive_tx`](struct.Foreign.html#method.receive_tx) method.
///
/// When a transaction is created, the wallet must also lock inputs (and create unconfirmed
/// outputs) corresponding to the transaction created in the slate, so that the wallet doesn't
/// attempt to re-spend outputs that are already included in a transaction before the transaction
/// is confirmed. This method also returns a function that will perform that locking, and it is
/// up to the caller to decide the best time to call the lock function
/// (via the [`tx_lock_outputs`](struct.Owner.html#method.tx_lock_outputs) method).
/// If the exchange method is intended to be synchronous (such as via a direct http call,)
/// then the lock call can wait until the response is confirmed. If it is asynchronous, (such
/// as via file transfer,) the lock call should happen immediately (before the file is sent
/// to the recipient).
///
/// If the `send_args` [`InitTxSendArgs`](../grin_wallet_libwallet/types/struct.InitTxSendArgs.html),
/// of the [`args`](../grin_wallet_libwallet/types/struct.InitTxArgs.html), field is Some, this
/// function will attempt to send the slate back to the sender using the slatepack sync
/// send (TOR). If providing this argument, check the `state` field of the slate to see if the
/// sync_send was successful (it should be S2 if the sync sent successfully). It will also post
/// the transction if the `post_tx` field is set.
///
/// # Arguments
/// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if
/// being used.
/// * `args` - [`InitTxArgs`](../grin_wallet_libwallet/types/struct.InitTxArgs.html),
/// transaction initialization arguments. See struct documentation for further detail.
///
/// # Returns
/// * a result containing:
/// * The transaction [Slate](../grin_wallet_libwallet/slate/struct.Slate.html),
/// which can be forwarded to the recieving party by any means. Once the caller is relatively
/// certain that the transaction has been sent to the recipient, the associated wallet
/// transaction outputs should be locked via a call to
/// [`tx_lock_outputs`](struct.Owner.html#method.tx_lock_outputs). This must be called before calling
/// [`finalize_tx`](struct.Owner.html#method.finalize_tx).
/// * or [`libwallet::Error`](../grin_wallet_libwallet/struct.Error.html) if an error is encountered.
///
/// # Remarks
///
/// * This method requires an active connection to a node, and will fail with error if a node
/// cannot be contacted to refresh output statuses.
/// * This method will store a partially completed transaction in the wallet's transaction log,
/// which will be updated on the corresponding call to [`finalize_tx`](struct.Owner.html#method.finalize_tx).
///
/// # Example
/// Set up as in [new](struct.Owner.html#method.new) method above.
/// ```
/// # grin_wallet_api::doctest_helper_setup_doc_env!(wallet, wallet_config);
///
/// let mut api_owner = Owner::new(wallet.clone(), None);
/// // Attempt to create a transaction using the 'default' account
/// let args = InitTxArgs {
/// src_acct_name: None,
/// amount: 2_000_000_000,
/// minimum_confirmations: 2,
/// max_outputs: 500,
/// num_change_outputs: 1,
/// selection_strategy_is_use_all: false,
/// ..Default::default()
/// };
/// let result = api_owner.init_send_tx(
/// None,
/// args,
/// );
///
/// if let Ok(slate) = result {
/// // Send slate somehow
/// // ...
/// // Lock our outputs if we're happy the slate was (or is being) sent
/// api_owner.tx_lock_outputs(None, &slate);
/// }
/// ```
pub fn init_send_tx(
&self,
keychain_mask: Option<&SecretKey>,
args: InitTxArgs,
) -> Result<Slate, Error> {
let send_args = args.send_args.clone();
let slate = {
let mut w_lock = self.wallet_inst.lock();
let w = w_lock.lc_provider()?.wallet_inst()?;
owner::init_send_tx(&mut **w, keychain_mask, args, self.doctest_mode)?
};
// Helper functionality. If send arguments exist, attempt to send sync and
// finalize
let skip_tor = match send_args.as_ref() {
None => false,
Some(sa) => sa.skip_tor,
};
match send_args {
Some(sa) => {
let tor_config_lock = self.tor_config.lock();
let tc = tor_config_lock.clone();
let tc = match tc {
Some(mut c) => {
c.skip_send_attempt = Some(skip_tor);
Some(c)
}
None => None,
};
let res = try_slatepack_sync_workflow(
&slate,
&sa.dest,
tc,
None,
false,
self.doctest_mode,
);
match res {
Ok(Some(s)) => {
if sa.post_tx {
self.tx_lock_outputs(keychain_mask, &s)?;
let ret_slate = self.finalize_tx(keychain_mask, &s)?;
let result = self.post_tx(keychain_mask, &ret_slate, sa.fluff);
match result {
Ok(_) => {
info!("Tx sent ok",);
return Ok(ret_slate);
}
Err(e) => {
error!("Tx sent fail: {}", e);
return Err(e);
}
}
} else {
self.tx_lock_outputs(keychain_mask, &s)?;
let ret_slate = self.finalize_tx(keychain_mask, &s)?;
return Ok(ret_slate);
}
}
Ok(None) => Ok(slate),
Err(_) => Ok(slate),
}
}
None => Ok(slate),
}
}
/// Issues a new invoice transaction slate, essentially a `request for payment`.
/// The slate created by this function will contain the amount, an output for the amount,
/// as well as round 1 of singature creation complete. The slate should then be send
/// to the payer, who should add their inputs and signature data and return the slate
/// via the [Foreign API's `finalize_tx`](struct.Foreign.html#method.finalize_tx) method.
///
/// # Arguments
/// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if
/// being used.
/// * `args` - [`IssueInvoiceTxArgs`](../grin_wallet_libwallet/types/struct.IssueInvoiceTxArgs.html),
/// invoice transaction initialization arguments. See struct documentation for further detail.
///
/// # Returns
/// * ``Ok([`slate`](../grin_wallet_libwallet/slate/struct.Slate.html))` if successful,
/// containing the updated slate.
/// * or [`libwallet::Error`](../grin_wallet_libwallet/struct.Error.html) if an error is encountered.
///
/// # Example
/// Set up as in [`new`](struct.Owner.html#method.new) method above.
/// ```
/// # grin_wallet_api::doctest_helper_setup_doc_env!(wallet, wallet_config);
///
/// let mut api_owner = Owner::new(wallet.clone(), None);
///
/// let args = IssueInvoiceTxArgs {
/// amount: 60_000_000_000,
/// ..Default::default()
/// };
/// let result = api_owner.issue_invoice_tx(None, args);
///
/// if let Ok(slate) = result {
/// // if okay, send to the payer to add their inputs
/// // . . .
/// }
/// ```
pub fn issue_invoice_tx(
&self,
keychain_mask: Option<&SecretKey>,
args: IssueInvoiceTxArgs,
) -> Result<Slate, Error> {
let mut w_lock = self.wallet_inst.lock();
let w = w_lock.lc_provider()?.wallet_inst()?;
owner::issue_invoice_tx(&mut **w, keychain_mask, args, self.doctest_mode)
}
/// Processes an invoice tranaction created by another party, essentially
/// a `request for payment`. The incoming slate should contain a requested
/// amount, an output created by the invoicer convering the amount, and
/// part 1 of signature creation completed. This function will add inputs
/// equalling the amount + fees, as well as perform round 1 and 2 of signature
/// creation.
///
/// Callers should note that no prompting of the user will be done by this function
/// it is up to the caller to present the request for payment to the user
/// and verify that payment should go ahead.
///
/// If the `send_args` [`InitTxSendArgs`](../grin_wallet_libwallet/types/struct.InitTxSendArgs.html),
/// of the [`args`](../grin_wallet_libwallet/types/struct.InitTxArgs.html), field is Some, this
/// function will attempt to send the slate back to the initiator using the slatepack sync
/// send (TOR). If providing this argument, check the `state` field of the slate to see if the
/// sync_send was successful (it should be I3 if the sync sent successfully).
///
/// This function also stores the final transaction in the user's wallet files for retrieval
/// via the [`get_stored_tx`](struct.Owner.html#method.get_stored_tx) function.
///
/// # Arguments
/// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if
/// being used.
/// * `slate` - The transaction [`Slate`](../grin_wallet_libwallet/slate/struct.Slate.html). The
/// payer should have filled in round 1 and 2.
/// * `args` - [`InitTxArgs`](../grin_wallet_libwallet/types/struct.InitTxArgs.html),
/// transaction initialization arguments. See struct documentation for further detail.
///
/// # Returns
/// * ``Ok([`slate`](../grin_wallet_libwallet/slate/struct.Slate.html))` if successful,
/// containing the updated slate.
/// * or [`libwallet::Error`](../grin_wallet_libwallet/struct.Error.html) if an error is encountered.
///
/// # Example
/// Set up as in [`new`](struct.Owner.html#method.new) method above.
/// ```
/// # grin_wallet_api::doctest_helper_setup_doc_env!(wallet, wallet_config);
///
/// let mut api_owner = Owner::new(wallet.clone(), None);
///
/// // . . .
/// // The slate has been recieved from the invoicer, somehow
/// # let slate = Slate::blank(2, true);
/// let args = InitTxArgs {
/// src_acct_name: None,
/// amount: slate.amount,
/// minimum_confirmations: 2,
/// max_outputs: 500,
/// num_change_outputs: 1,
/// selection_strategy_is_use_all: false,
/// ..Default::default()
/// };
///
/// let result = api_owner.process_invoice_tx(None, &slate, args);
///
/// if let Ok(slate) = result {
/// // If result okay, send back to the invoicer
/// // . . .
/// }
/// ```
pub fn process_invoice_tx(
&self,
keychain_mask: Option<&SecretKey>,
slate: &Slate,
args: InitTxArgs,
) -> Result<Slate, Error> {
let mut w_lock = self.wallet_inst.lock();
let w = w_lock.lc_provider()?.wallet_inst()?;
let send_args = args.send_args.clone();
let slate =
owner::process_invoice_tx(&mut **w, keychain_mask, slate, args, self.doctest_mode)?;
// Helper functionality. If send arguments exist, attempt to send
match send_args {
Some(sa) => {
let tor_config_lock = self.tor_config.lock();
let tc = tor_config_lock.clone();
let tc = match tc {
Some(mut c) => {
c.skip_send_attempt = Some(sa.skip_tor);
Some(c)
}
None => None,
};
let res = try_slatepack_sync_workflow(
&slate,
&sa.dest,
tc,
None,
true,
self.doctest_mode,
);
match res {
Ok(s) => Ok(s.unwrap()),
Err(_) => Ok(slate),
}
}
None => Ok(slate),
}
}
/// Locks the outputs associated with the inputs to the transaction in the given
/// [`Slate`](../grin_wallet_libwallet/slate/struct.Slate.html),
/// making them unavailable for use in further transactions. This function is called
/// by the sender, (or more generally, all parties who have put inputs into the transaction,)
/// and must be called before the corresponding call to [`finalize_tx`](struct.Owner.html#method.finalize_tx)
/// that completes the transaction.
///
/// Outputs will generally remain locked until they are removed from the chain,
/// at which point they will become `Spent`. It is commonplace for transactions not to complete
/// for various reasons over which a particular wallet has no control. For this reason,
/// [`cancel_tx`](struct.Owner.html#method.cancel_tx) can be used to manually unlock outputs
/// and return them to the `Unspent` state.
///
/// # Arguments
/// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if
/// being used.
/// * `slate` - The transaction [`Slate`](../grin_wallet_libwallet/slate/struct.Slate.html). All
/// * `participant_id` - The participant id, generally 0 for the party putting in funds, 1 for the
/// party receiving.
/// elements in the `input` vector of the `tx` field that are found in the wallet's currently
/// active account will be set to status `Locked`
///
/// # Returns
/// * Ok(()) if successful
/// * or [`libwallet::Error`](../grin_wallet_libwallet/struct.Error.html) if an error is encountered.
///
/// # Example
/// Set up as in [`new`](struct.Owner.html#method.new) method above.
/// ```
/// # grin_wallet_api::doctest_helper_setup_doc_env!(wallet, wallet_config);
///
/// let mut api_owner = Owner::new(wallet.clone(), None);
/// let args = InitTxArgs {
/// src_acct_name: None,
/// amount: 2_000_000_000,
/// minimum_confirmations: 10,
/// max_outputs: 500,
/// num_change_outputs: 1,
/// selection_strategy_is_use_all: false,
/// ..Default::default()
/// };
/// let result = api_owner.init_send_tx(
/// None,
/// args,
/// );
///
/// if let Ok(slate) = result {
/// // Send slate somehow
/// // ...
/// // Lock our outputs if we're happy the slate was (or is being) sent
/// api_owner.tx_lock_outputs(None, &slate);
/// }
/// ```
pub fn tx_lock_outputs(
&self,
keychain_mask: Option<&SecretKey>,
slate: &Slate,
) -> Result<(), Error> {
let mut w_lock = self.wallet_inst.lock();
let w = w_lock.lc_provider()?.wallet_inst()?;
owner::tx_lock_outputs(&mut **w, keychain_mask, slate)
}
/// Finalizes a transaction, after all parties
/// have filled in both rounds of Slate generation. This step adds
/// all participants partial signatures to create the final signature,
/// resulting in a final transaction that is ready to post to a node.
///
/// Note that this function DOES NOT POST the transaction to a node
/// for validation. This is done in separately via the
/// [`post_tx`](struct.Owner.html#method.post_tx) function.
///
/// This function also stores the final transaction in the user's wallet files for retrieval
/// via the [`get_stored_tx`](struct.Owner.html#method.get_stored_tx) function.
///
/// # Arguments
/// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if
/// being used.
/// * `slate` - The transaction [`Slate`](../grin_wallet_libwallet/slate/struct.Slate.html). All
/// participants must have filled in both rounds, and the sender should have locked their
/// outputs (via the [`tx_lock_outputs`](struct.Owner.html#method.tx_lock_outputs) function).
///
/// # Returns
/// * ``Ok([`slate`](../grin_wallet_libwallet/slate/struct.Slate.html))` if successful,
/// containing the new finalized slate.
/// * or [`libwallet::Error`](../grin_wallet_libwallet/struct.Error.html) if an error is encountered.
///
/// # Example
/// Set up as in [`new`](struct.Owner.html#method.new) method above.
/// ```
/// # grin_wallet_api::doctest_helper_setup_doc_env!(wallet, wallet_config);
///
/// let mut api_owner = Owner::new(wallet.clone(), None);
/// let args = InitTxArgs {
/// src_acct_name: None,
/// amount: 2_000_000_000,
/// minimum_confirmations: 10,
/// max_outputs: 500,
/// num_change_outputs: 1,
/// selection_strategy_is_use_all: false,
/// ..Default::default()
/// };
/// let result = api_owner.init_send_tx(
/// None,
/// args,
/// );
///
/// if let Ok(slate) = result {
/// // Send slate somehow
/// // ...
/// // Lock our outputs if we're happy the slate was (or is being) sent
/// let res = api_owner.tx_lock_outputs(None, &slate);
/// //
/// // Retrieve slate back from recipient
/// //
/// let res = api_owner.finalize_tx(None, &slate);
/// }
/// ```
pub fn finalize_tx(
&self,
keychain_mask: Option<&SecretKey>,
slate: &Slate,
) -> Result<Slate, Error> {
let mut w_lock = self.wallet_inst.lock();
let w = w_lock.lc_provider()?.wallet_inst()?;
owner::finalize_tx(&mut **w, keychain_mask, slate)
}
/// Posts a completed transaction to the listening node for validation and inclusion in a block
/// for mining.
///
/// # Arguments
/// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if
/// being used.
/// * `tx` - A completed [`Transaction`](../grin_core/core/transaction/struct.Transaction.html),
/// typically the `tx` field in the transaction [`Slate`](../grin_wallet_libwallet/slate/struct.Slate.html).