/
wallet.cpp
5060 lines (4353 loc) · 186 KB
/
wallet.cpp
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 (c) 2017 Cryptonomex, Inc., and contributors.
*
* The MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <algorithm>
#include <cctype>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
#include <list>
#include <boost/version.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/range/adaptor/map.hpp>
#include <boost/range/algorithm_ext/erase.hpp>
#include <boost/range/algorithm/unique.hpp>
#include <boost/range/algorithm/sort.hpp>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/mem_fun.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/random_access_index.hpp>
#include <boost/multi_index/tag.hpp>
#include <boost/multi_index/sequenced_index.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <fc/git_revision.hpp>
#include <fc/io/fstream.hpp>
#include <fc/io/json.hpp>
#include <fc/io/stdio.hpp>
#include <fc/network/http/websocket.hpp>
#include <fc/rpc/cli.hpp>
#include <fc/rpc/websocket_api.hpp>
#include <fc/crypto/hex.hpp>
#include <fc/thread/mutex.hpp>
#include <fc/thread/scoped_lock.hpp>
#include <fc/rpc/api_connection.hpp>
#include <fc/crypto/base58.hpp>
#include <graphene/app/api.hpp>
#include <graphene/app/util.hpp>
#include <graphene/chain/asset_object.hpp>
#include <graphene/protocol/fee_schedule.hpp>
#include <graphene/protocol/pts_address.hpp>
#include <graphene/chain/hardfork.hpp>
#include <graphene/utilities/git_revision.hpp>
#include <graphene/utilities/key_conversion.hpp>
#include <graphene/utilities/words.hpp>
#include <graphene/wallet/wallet.hpp>
#include <graphene/wallet/api_documentation.hpp>
#include <graphene/wallet/reflect_util.hpp>
#include <graphene/debug_witness/debug_api.hpp>
#include <fc/crypto/aes.hpp>
#ifndef WIN32
# include <sys/types.h>
# include <sys/stat.h>
#endif
// explicit instantiation for later use
namespace fc {
template class api<graphene::wallet::wallet_api, identity_member_with_optionals>;
}
#define BRAIN_KEY_WORD_COUNT 16
#define RANGE_PROOF_MANTISSA 49 // Minimum mantissa bits to "hide" in the range proof.
// If this number is set too low, then for large value
// commitments the length of the range proof will hint
// strongly at the value amount that is being hidden.
namespace graphene { namespace wallet {
using std::ostream;
using std::stringstream;
using std::to_string;
using std::setprecision;
using std::fixed;
using std::ios;
using std::setiosflags;
using std::setw;
using std::endl;
namespace detail {
struct operation_result_printer
{
public:
explicit operation_result_printer( const wallet_api_impl& w )
: _wallet(w) {}
const wallet_api_impl& _wallet;
typedef std::string result_type;
std::string operator()(const void_result& x) const;
std::string operator()(const object_id_type& oid);
std::string operator()(const asset& a);
};
// BLOCK TRX OP VOP
struct operation_printer
{
private:
ostream& out;
const wallet_api_impl& wallet;
operation_result result;
operation_history_object hist;
std::string fee(const asset& a) const;
public:
operation_printer( ostream& out, const wallet_api_impl& wallet, const operation_history_object& obj )
: out(out),
wallet(wallet),
result(obj.result),
hist(obj)
{}
typedef std::string result_type;
template<typename T>
std::string operator()(const T& op)const;
std::string operator()(const transfer_operation& op)const;
std::string operator()(const transfer_from_blind_operation& op)const;
std::string operator()(const transfer_to_blind_operation& op)const;
std::string operator()(const account_create_operation& op)const;
std::string operator()(const account_update_operation& op)const;
std::string operator()(const asset_create_operation& op)const;
std::string operator()(const htlc_create_operation& op)const;
std::string operator()(const htlc_redeem_operation& op)const;
};
template<class T>
optional<T> maybe_id( const string& name_or_id )
{
if( std::isdigit( name_or_id.front() ) )
{
try
{
return fc::variant(name_or_id, 1).as<T>(1);
}
catch (const fc::exception&)
{ // not an ID
}
}
return optional<T>();
}
string address_to_shorthash( const address& addr )
{
uint32_t x = addr.addr._hash[0].value();
static const char hd[] = "0123456789abcdef";
string result;
result += hd[(x >> 0x1c) & 0x0f];
result += hd[(x >> 0x18) & 0x0f];
result += hd[(x >> 0x14) & 0x0f];
result += hd[(x >> 0x10) & 0x0f];
result += hd[(x >> 0x0c) & 0x0f];
result += hd[(x >> 0x08) & 0x0f];
result += hd[(x >> 0x04) & 0x0f];
result += hd[(x ) & 0x0f];
return result;
}
fc::ecc::private_key derive_private_key( const std::string& prefix_string,
int sequence_number )
{
std::string sequence_string = std::to_string(sequence_number);
fc::sha512 h = fc::sha512::hash(prefix_string + " " + sequence_string);
fc::ecc::private_key derived_key = fc::ecc::private_key::regenerate(fc::sha256::hash(h));
return derived_key;
}
string normalize_brain_key( string s )
{
size_t i = 0, n = s.length();
std::string result;
char c;
result.reserve( n );
bool preceded_by_whitespace = false;
bool non_empty = false;
while( i < n )
{
c = s[i++];
switch( c )
{
case ' ': case '\t': case '\r': case '\n': case '\v': case '\f':
preceded_by_whitespace = true;
continue;
case 'a': c = 'A'; break;
case 'b': c = 'B'; break;
case 'c': c = 'C'; break;
case 'd': c = 'D'; break;
case 'e': c = 'E'; break;
case 'f': c = 'F'; break;
case 'g': c = 'G'; break;
case 'h': c = 'H'; break;
case 'i': c = 'I'; break;
case 'j': c = 'J'; break;
case 'k': c = 'K'; break;
case 'l': c = 'L'; break;
case 'm': c = 'M'; break;
case 'n': c = 'N'; break;
case 'o': c = 'O'; break;
case 'p': c = 'P'; break;
case 'q': c = 'Q'; break;
case 'r': c = 'R'; break;
case 's': c = 'S'; break;
case 't': c = 'T'; break;
case 'u': c = 'U'; break;
case 'v': c = 'V'; break;
case 'w': c = 'W'; break;
case 'x': c = 'X'; break;
case 'y': c = 'Y'; break;
case 'z': c = 'Z'; break;
default:
break;
}
if( preceded_by_whitespace && non_empty )
result.push_back(' ');
result.push_back(c);
preceded_by_whitespace = false;
non_empty = true;
}
return result;
}
struct op_prototype_visitor
{
typedef void result_type;
int t = 0;
flat_map< std::string, operation >& name2op;
op_prototype_visitor(
int _t,
flat_map< std::string, operation >& _prototype_ops
):t(_t), name2op(_prototype_ops) {}
template<typename Type>
result_type operator()( const Type& op )const
{
string name = fc::get_typename<Type>::name();
size_t p = name.rfind(':');
if( p != string::npos )
name = name.substr( p+1 );
name2op[ name ] = Type();
}
};
class htlc_hash_to_string_visitor
{
public:
typedef std::string result_type;
result_type operator()( const fc::ripemd160& hash )const
{
return "RIPEMD160 " + hash.str();
}
result_type operator()( const fc::sha1& hash )const
{
return "SHA1 " + hash.str();
}
result_type operator()( const fc::sha256& hash )const
{
return "SHA256 " + hash.str();
}
};
class wallet_api_impl
{
public:
api_documentation method_documentation;
private:
void claim_registered_account(const account_object& account)
{
bool import_keys = false;
auto it = _wallet.pending_account_registrations.find( account.name );
FC_ASSERT( it != _wallet.pending_account_registrations.end() );
for (const std::string& wif_key : it->second) {
if( !import_key( account.name, wif_key ) )
{
// somebody else beat our pending registration, there is
// nothing we can do except log it and move on
elog( "account ${name} registered by someone else first!",
("name", account.name) );
// might as well remove it from pending regs,
// because there is now no way this registration
// can become valid (even in the extremely rare
// possibility of migrating to a fork where the
// name is available, the user can always
// manually re-register)
} else {
import_keys = true;
}
}
_wallet.pending_account_registrations.erase( it );
if( import_keys ) {
save_wallet_file();
}
}
// after a witness registration succeeds, this saves the private key in the wallet permanently
//
void claim_registered_witness(const std::string& witness_name)
{
auto iter = _wallet.pending_witness_registrations.find(witness_name);
FC_ASSERT(iter != _wallet.pending_witness_registrations.end());
std::string wif_key = iter->second;
// get the list key id this key is registered with in the chain
fc::optional<fc::ecc::private_key> witness_private_key = wif_to_key(wif_key);
FC_ASSERT(witness_private_key);
auto pub_key = witness_private_key->get_public_key();
_keys[pub_key] = wif_key;
_wallet.pending_witness_registrations.erase(iter);
}
fc::mutex _resync_mutex;
void resync()
{
fc::scoped_lock<fc::mutex> lock(_resync_mutex);
// this method is used to update wallet_data annotations
// e.g. wallet has been restarted and was not notified
// of events while it was down
//
// everything that is done "incremental style" when a push
// notification is received, should also be done here
// "batch style" by querying the blockchain
if( !_wallet.pending_account_registrations.empty() )
{
// make a vector of the account names pending registration
std::vector<string> pending_account_names =
boost::copy_range<std::vector<string> >(boost::adaptors::keys(_wallet.pending_account_registrations));
// look those up on the blockchain
std::vector<fc::optional<graphene::chain::account_object >>
pending_account_objects = _remote_db->lookup_account_names( pending_account_names );
// if any of them exist, claim them
for( const fc::optional<graphene::chain::account_object>& optional_account : pending_account_objects )
if( optional_account )
claim_registered_account(*optional_account);
}
if (!_wallet.pending_witness_registrations.empty())
{
// make a vector of the owner accounts for witnesses pending registration
std::vector<string> pending_witness_names =
boost::copy_range<std::vector<string> >(boost::adaptors::keys(_wallet.pending_witness_registrations));
// look up the owners on the blockchain
std::vector<fc::optional<graphene::chain::account_object>> owner_account_objects =
_remote_db->lookup_account_names(pending_witness_names);
// if any of them have registered witnesses, claim them
for( const fc::optional<graphene::chain::account_object>& optional_account : owner_account_objects )
if (optional_account)
{
std::string account_id = account_id_to_string(optional_account->id);
fc::optional<witness_object> witness_obj = _remote_db->get_witness_by_account(account_id);
if (witness_obj)
claim_registered_witness(optional_account->name);
}
}
}
void enable_umask_protection()
{
#ifdef __unix__
_old_umask = umask( S_IRWXG | S_IRWXO );
#endif
}
void disable_umask_protection()
{
#ifdef __unix__
umask( _old_umask );
#endif
}
void init_prototype_ops()
{
operation op;
for( int t=0; t<op.count(); t++ )
{
op.set_which( t );
op.visit( op_prototype_visitor(t, _prototype_ops) );
}
return;
}
map<transaction_handle_type, signed_transaction> _builder_transactions;
// if the user executes the same command twice in quick succession,
// we might generate the same transaction id, and cause the second
// transaction to be rejected. This can be avoided by altering the
// second transaction slightly (bumping up the expiration time by
// a second). Keep track of recent transaction ids we've generated
// so we can know if we need to do this
struct recently_generated_transaction_record
{
fc::time_point_sec generation_time;
graphene::chain::transaction_id_type transaction_id;
};
struct timestamp_index{};
typedef boost::multi_index_container<
recently_generated_transaction_record,
boost::multi_index::indexed_by<
boost::multi_index::hashed_unique<
boost::multi_index::member<
recently_generated_transaction_record,
graphene::chain::transaction_id_type,
&recently_generated_transaction_record::transaction_id
>,
std::hash<graphene::chain::transaction_id_type>
>,
boost::multi_index::ordered_non_unique<
boost::multi_index::tag<timestamp_index>,
boost::multi_index::member<
recently_generated_transaction_record,
fc::time_point_sec,
&recently_generated_transaction_record::generation_time
>
>
>
> recently_generated_transaction_set_type;
recently_generated_transaction_set_type _recently_generated_transactions;
public:
wallet_api& self;
wallet_api_impl( wallet_api& s, const wallet_data& initial_data, fc::api<login_api> rapi )
: self(s),
_chain_id(initial_data.chain_id),
_remote_api(rapi),
_remote_db(rapi->database()),
_remote_net_broadcast(rapi->network_broadcast()),
_remote_hist(rapi->history())
{
chain_id_type remote_chain_id = _remote_db->get_chain_id();
if( remote_chain_id != _chain_id )
{
FC_THROW( "Remote server gave us an unexpected chain_id",
("remote_chain_id", remote_chain_id)
("chain_id", _chain_id) );
}
init_prototype_ops();
_remote_db->set_block_applied_callback( [this](const variant& block_id )
{
on_block_applied( block_id );
} );
_wallet.chain_id = _chain_id;
_wallet.ws_server = initial_data.ws_server;
_wallet.ws_user = initial_data.ws_user;
_wallet.ws_password = initial_data.ws_password;
}
virtual ~wallet_api_impl()
{
try
{
_remote_db->cancel_all_subscriptions();
}
catch (const fc::exception& e)
{
// Right now the wallet_api has no way of knowing if the connection to the
// witness has already disconnected (via the witness node exiting first).
// If it has exited, cancel_all_subscriptsions() will throw and there's
// nothing we can do about it.
// dlog("Caught exception ${e} while canceling database subscriptions", ("e", e));
}
}
void encrypt_keys()
{
if( !is_locked() )
{
plain_keys data;
data.keys = _keys;
data.checksum = _checksum;
auto plain_txt = fc::raw::pack(data);
_wallet.cipher_keys = fc::aes_encrypt( data.checksum, plain_txt );
}
}
void on_block_applied( const variant& block_id )
{
fc::async([this]{resync();}, "Resync after block");
}
bool copy_wallet_file( string destination_filename )
{
fc::path src_path = get_wallet_filename();
if( !fc::exists( src_path ) )
return false;
fc::path dest_path = destination_filename + _wallet_filename_extension;
int suffix = 0;
while( fc::exists(dest_path) )
{
++suffix;
dest_path = destination_filename + "-" + to_string( suffix ) + _wallet_filename_extension;
}
wlog( "backing up wallet ${src} to ${dest}",
("src", src_path)
("dest", dest_path) );
fc::path dest_parent = fc::absolute(dest_path).parent_path();
try
{
enable_umask_protection();
if( !fc::exists( dest_parent ) )
fc::create_directories( dest_parent );
fc::copy( src_path, dest_path );
disable_umask_protection();
}
catch(...)
{
disable_umask_protection();
throw;
}
return true;
}
bool is_locked()const
{
return _checksum == fc::sha512();
}
template<typename ID>
graphene::db::object_downcast_t<ID> get_object(ID id)const
{
auto ob = _remote_db->get_objects({id}).front();
return ob.template as<graphene::db::object_downcast_t<ID>>( GRAPHENE_MAX_NESTED_OBJECTS );
}
void set_operation_fees( signed_transaction& tx, const fee_schedule& s )
{
for( auto& op : tx.operations )
s.set_fee(op);
}
variant info() const
{
auto chain_props = get_chain_properties();
auto global_props = get_global_properties();
auto dynamic_props = get_dynamic_global_properties();
fc::mutable_variant_object result;
result["head_block_num"] = dynamic_props.head_block_number;
result["head_block_id"] = fc::variant(dynamic_props.head_block_id, 1);
result["head_block_age"] = fc::get_approximate_relative_time_string(dynamic_props.time,
time_point_sec(time_point::now()),
" old");
result["next_maintenance_time"] =
fc::get_approximate_relative_time_string(dynamic_props.next_maintenance_time);
result["chain_id"] = chain_props.chain_id;
stringstream participation;
participation << fixed << std::setprecision(2) << (100*dynamic_props.recent_slots_filled.popcount()) / 128.0;
result["participation"] = participation.str();
result["active_witnesses"] = fc::variant(global_props.active_witnesses, GRAPHENE_MAX_NESTED_OBJECTS);
result["active_committee_members"] =
fc::variant(global_props.active_committee_members, GRAPHENE_MAX_NESTED_OBJECTS);
return result;
}
variant_object about() const
{
string client_version( graphene::utilities::git_revision_description );
const size_t pos = client_version.find( '/' );
if( pos != string::npos && client_version.size() > pos )
client_version = client_version.substr( pos + 1 );
fc::mutable_variant_object result;
//result["blockchain_name"] = BLOCKCHAIN_NAME;
//result["blockchain_description"] = BTS_BLOCKCHAIN_DESCRIPTION;
result["client_version"] = client_version;
result["graphene_revision"] = graphene::utilities::git_revision_sha;
result["graphene_revision_age"] = fc::get_approximate_relative_time_string( fc::time_point_sec(
graphene::utilities::git_revision_unix_timestamp ) );
result["fc_revision"] = fc::git_revision_sha;
result["fc_revision_age"] = fc::get_approximate_relative_time_string( fc::time_point_sec(
fc::git_revision_unix_timestamp ) );
result["compile_date"] = "compiled on " __DATE__ " at " __TIME__;
result["boost_version"] = boost::replace_all_copy(std::string(BOOST_LIB_VERSION), "_", ".");
result["openssl_version"] = OPENSSL_VERSION_TEXT;
std::string bitness = boost::lexical_cast<std::string>(8 * sizeof(int*)) + "-bit";
#if defined(__APPLE__)
std::string os = "osx";
#elif defined(__linux__)
std::string os = "linux";
#elif defined(_MSC_VER)
std::string os = "win32";
#else
std::string os = "other";
#endif
result["build"] = os + " " + bitness;
return result;
}
chain_property_object get_chain_properties() const
{
return _remote_db->get_chain_properties();
}
global_property_object get_global_properties() const
{
return _remote_db->get_global_properties();
}
dynamic_global_property_object get_dynamic_global_properties() const
{
return _remote_db->get_dynamic_global_properties();
}
std::string account_id_to_string(account_id_type id) const
{
std::string account_id = fc::to_string(id.space_id)
+ "." + fc::to_string(id.type_id)
+ "." + fc::to_string(id.instance.value);
return account_id;
}
account_object get_account(account_id_type id) const
{
std::string account_id = account_id_to_string(id);
auto rec = _remote_db->get_accounts({account_id}).front();
FC_ASSERT(rec);
return *rec;
}
account_object get_account(string account_name_or_id) const
{
FC_ASSERT( account_name_or_id.size() > 0 );
if( auto id = maybe_id<account_id_type>(account_name_or_id) )
{
// It's an ID
return get_account(*id);
} else {
auto rec = _remote_db->lookup_account_names({account_name_or_id}).front();
FC_ASSERT( rec && rec->name == account_name_or_id );
return *rec;
}
}
account_id_type get_account_id(string account_name_or_id) const
{
return get_account(account_name_or_id).get_id();
}
std::string asset_id_to_string(asset_id_type id) const
{
std::string asset_id = fc::to_string(id.space_id) +
"." + fc::to_string(id.type_id) +
"." + fc::to_string(id.instance.value);
return asset_id;
}
optional<asset_object> find_asset(asset_id_type id)const
{
auto rec = _remote_db->get_assets({asset_id_to_string(id)}).front();
return rec;
}
optional<asset_object> find_asset(string asset_symbol_or_id)const
{
FC_ASSERT( asset_symbol_or_id.size() > 0 );
if( auto id = maybe_id<asset_id_type>(asset_symbol_or_id) )
{
// It's an ID
return find_asset(*id);
} else {
// It's a symbol
auto rec = _remote_db->lookup_asset_symbols({asset_symbol_or_id}).front();
if( rec )
{
if( rec->symbol != asset_symbol_or_id )
return optional<asset_object>();
}
return rec;
}
}
asset_object get_asset(asset_id_type id)const
{
auto opt = find_asset(id);
FC_ASSERT(opt);
return *opt;
}
asset_object get_asset(string asset_symbol_or_id)const
{
auto opt = find_asset(asset_symbol_or_id);
FC_ASSERT(opt);
return *opt;
}
fc::optional<htlc_object> get_htlc(string htlc_id) const
{
htlc_id_type id;
fc::from_variant(htlc_id, id);
auto obj = _remote_db->get_objects( { id }).front();
if ( !obj.is_null() )
{
return fc::optional<htlc_object>(obj.template as<htlc_object>(GRAPHENE_MAX_NESTED_OBJECTS));
}
return fc::optional<htlc_object>();
}
asset_id_type get_asset_id(string asset_symbol_or_id) const
{
FC_ASSERT( asset_symbol_or_id.size() > 0 );
vector<optional<asset_object>> opt_asset;
if( std::isdigit( asset_symbol_or_id.front() ) )
return fc::variant(asset_symbol_or_id, 1).as<asset_id_type>( 1 );
opt_asset = _remote_db->lookup_asset_symbols( {asset_symbol_or_id} );
FC_ASSERT( (opt_asset.size() > 0) && (opt_asset[0].valid()) );
return opt_asset[0]->id;
}
string get_wallet_filename() const
{
return _wallet_filename;
}
fc::ecc::private_key get_private_key(const public_key_type& id)const
{
auto it = _keys.find(id);
FC_ASSERT( it != _keys.end() );
fc::optional< fc::ecc::private_key > privkey = wif_to_key( it->second );
FC_ASSERT( privkey );
return *privkey;
}
fc::ecc::private_key get_private_key_for_account(const account_object& account)const
{
vector<public_key_type> active_keys = account.active.get_keys();
if (active_keys.size() != 1)
FC_THROW("Expecting a simple authority with one active key");
return get_private_key(active_keys.front());
}
// imports the private key into the wallet, and associate it in some way (?) with the
// given account name.
// @returns true if the key matches a current active/owner/memo key for the named
// account, false otherwise (but it is stored either way)
bool import_key(string account_name_or_id, string wif_key)
{
fc::optional<fc::ecc::private_key> optional_private_key = wif_to_key(wif_key);
if (!optional_private_key)
FC_THROW("Invalid private key");
graphene::chain::public_key_type wif_pub_key = optional_private_key->get_public_key();
account_object account = get_account( account_name_or_id );
// make a list of all current public keys for the named account
flat_set<public_key_type> all_keys_for_account;
std::vector<public_key_type> active_keys = account.active.get_keys();
std::vector<public_key_type> owner_keys = account.owner.get_keys();
std::copy(active_keys.begin(), active_keys.end(),
std::inserter(all_keys_for_account, all_keys_for_account.end()));
std::copy(owner_keys.begin(), owner_keys.end(),
std::inserter(all_keys_for_account, all_keys_for_account.end()));
all_keys_for_account.insert(account.options.memo_key);
_keys[wif_pub_key] = wif_key;
_wallet.update_account(account);
_wallet.extra_keys[account.id].insert(wif_pub_key);
return all_keys_for_account.find(wif_pub_key) != all_keys_for_account.end();
}
vector< signed_transaction > import_balance( string name_or_id, const vector<string>& wif_keys, bool broadcast );
bool load_wallet_file(string wallet_filename = "")
{
// TODO: Merge imported wallet with existing wallet,
// instead of replacing it
if( wallet_filename == "" )
wallet_filename = _wallet_filename;
if( ! fc::exists( wallet_filename ) )
return false;
_wallet = fc::json::from_file( wallet_filename ).as< wallet_data >( 2 * GRAPHENE_MAX_NESTED_OBJECTS );
if( _wallet.chain_id != _chain_id )
FC_THROW( "Wallet chain ID does not match",
("wallet.chain_id", _wallet.chain_id)
("chain_id", _chain_id) );
size_t account_pagination = 100;
vector< std::string > account_ids_to_send;
size_t n = _wallet.my_accounts.size();
account_ids_to_send.reserve( std::min( account_pagination, n ) );
auto it = _wallet.my_accounts.begin();
for( size_t start=0; start<n; start+=account_pagination )
{
size_t end = std::min( start+account_pagination, n );
assert( end > start );
account_ids_to_send.clear();
std::vector< account_object > old_accounts;
for( size_t i=start; i<end; i++ )
{
assert( it != _wallet.my_accounts.end() );
old_accounts.push_back( *it );
std::string account_id = account_id_to_string(old_accounts.back().id);
account_ids_to_send.push_back( account_id );
++it;
}
std::vector< optional< account_object > > accounts = _remote_db->get_accounts(account_ids_to_send);
// server response should be same length as request
FC_ASSERT( accounts.size() == account_ids_to_send.size() );
size_t i = 0;
for( const optional< account_object >& acct : accounts )
{
account_object& old_acct = old_accounts[i];
if( !acct.valid() )
{
elog( "Could not find account ${id} : \"${name}\" does not exist on the chain!",
("id", old_acct.id)("name", old_acct.name) );
i++;
continue;
}
// this check makes sure the server didn't send results
// in a different order, or accounts we didn't request
FC_ASSERT( acct->id == old_acct.id );
if( fc::json::to_string(*acct) != fc::json::to_string(old_acct) )
{
wlog( "Account ${id} : \"${name}\" updated on chain", ("id", acct->id)("name", acct->name) );
}
_wallet.update_account( *acct );
i++;
}
}
return true;
}
/**
* Get the required public keys to sign the transaction which had been
* owned by us
*
* NOTE, if `erase_existing_sigs` set to true, the original trasaction's
* signatures will be erased
*
* @param tx The transaction to be signed
* @param erase_existing_sigs
* The transaction could have been partially signed already,
* if set to false, the corresponding public key of existing
* signatures won't be returned.
* If set to true, the existing signatures will be erased and
* all required keys returned.
*/
set<public_key_type> get_owned_required_keys( signed_transaction &tx,
bool erase_existing_sigs = true)
{
set<public_key_type> pks = _remote_db->get_potential_signatures( tx );
flat_set<public_key_type> owned_keys;
owned_keys.reserve( pks.size() );
std::copy_if( pks.begin(), pks.end(),
std::inserter( owned_keys, owned_keys.end() ),
[this]( const public_key_type &pk ) {
return _keys.find( pk ) != _keys.end();
} );
if ( erase_existing_sigs )
tx.signatures.clear();
return _remote_db->get_required_signatures( tx, owned_keys );
}
signed_transaction add_transaction_signature( signed_transaction tx,
bool broadcast )
{
set<public_key_type> approving_key_set = get_owned_required_keys(tx, false);
if ( ( ( tx.ref_block_num == 0 && tx.ref_block_prefix == 0 ) ||
tx.expiration == fc::time_point_sec() ) &&
tx.signatures.empty() )
{
auto dyn_props = get_dynamic_global_properties();
auto parameters = get_global_properties().parameters;
fc::time_point_sec now = dyn_props.time;
tx.set_reference_block( dyn_props.head_block_id );
tx.set_expiration( now + parameters.maximum_time_until_expiration );
}
for ( const public_key_type &key : approving_key_set )
tx.sign( get_private_key( key ), _chain_id );
if ( broadcast )
{
try
{
_remote_net_broadcast->broadcast_transaction( tx );
}
catch ( const fc::exception &e )
{
elog( "Caught exception while broadcasting tx ${id}: ${e}",
( "id", tx.id().str() )( "e", e.to_detail_string() ) );
FC_THROW( "Caught exception while broadcasting tx" );
}
}
return tx;
}
void quit()
{
ilog( "Quitting Cli Wallet ..." );
throw fc::canceled_exception();
}
void save_wallet_file(string wallet_filename = "")
{
//
// Serialize in memory, then save to disk
//
// This approach lessens the risk of a partially written wallet
// if exceptions are thrown in serialization
//
encrypt_keys();
if( wallet_filename == "" )
wallet_filename = _wallet_filename;
wlog( "saving wallet to file ${fn}", ("fn", wallet_filename) );
string data = fc::json::to_pretty_string( _wallet );
try
{
enable_umask_protection();
//
// Parentheses on the following declaration fails to compile,
// due to the Most Vexing Parse. Thanks, C++
//
// http://en.wikipedia.org/wiki/Most_vexing_parse
//
std::string tmp_wallet_filename = wallet_filename + ".tmp";
fc::ofstream outfile{ fc::path( tmp_wallet_filename ) };
outfile.write( data.c_str(), data.length() );
outfile.flush();
outfile.close();
wlog( "saved successfully wallet to tmp file ${fn}", ("fn", tmp_wallet_filename) );
std::string wallet_file_content;
fc::read_file_contents(tmp_wallet_filename, wallet_file_content);
if (wallet_file_content == data) {
wlog( "validated successfully tmp wallet file ${fn}", ("fn", tmp_wallet_filename) );
fc::rename( tmp_wallet_filename, wallet_filename );
wlog( "renamed successfully tmp wallet file ${fn}", ("fn", tmp_wallet_filename) );
}
else
{
FC_THROW("tmp wallet file cannot be validated ${fn}", ("fn", tmp_wallet_filename) );
}
wlog( "successfully saved wallet to file ${fn}", ("fn", wallet_filename) );
disable_umask_protection();
}
catch(...)
{
string ws_password = _wallet.ws_password;