This repository has been archived by the owner on Feb 21, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 174
/
wallet.cpp
4445 lines (3693 loc) · 171 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
#include <bts/wallet/config.hpp>
#include <bts/wallet/exceptions.hpp>
#include <bts/wallet/wallet.hpp>
#include <bts/wallet/wallet_impl.hpp>
#include <bts/blockchain/time.hpp>
#include <bts/cli/pretty.hpp>
#include <bts/utilities/git_revision.hpp>
#include <bts/utilities/key_conversion.hpp>
#include <thread>
#include <fstream>
namespace bts { namespace wallet {
namespace detail {
wallet_impl::wallet_impl()
{
_num_scanner_threads = std::max( _num_scanner_threads, std::thread::hardware_concurrency() );
_scanner_threads.reserve( _num_scanner_threads );
for( uint32_t i = 0; i < _num_scanner_threads; ++i )
_scanner_threads.push_back( std::unique_ptr<fc::thread>( new fc::thread( "wallet_scanner_" + std::to_string( i ) ) ) );
}
wallet_impl::~wallet_impl()
{
}
void wallet_impl::state_changed( const pending_chain_state_ptr& state )
{
if( !self->is_open() || !self->is_unlocked() ) return;
const auto last_unlocked_scanned_number = self->get_last_scanned_block_number();
if ( _blockchain->get_head_block_num() < last_unlocked_scanned_number )
{
self->set_last_scanned_block_number( _blockchain->get_head_block_num() );
}
}
void wallet_impl::block_applied( const block_summary& summary )
{
if( !self->is_open() || !self->is_unlocked() ) return;
if( !self->get_transaction_scanning() ) return;
if( summary.block_data.block_num <= self->get_last_scanned_block_number() ) return;
if( _scan_in_progress.valid() && !_scan_in_progress.ready() ) return;
self->scan_chain( self->get_last_scanned_block_number(), summary.block_data.block_num );
}
vector<wallet_transaction_record> wallet_impl::get_pending_transactions()const
{
return _wallet_db.get_pending_transactions();
}
void wallet_impl::withdraw_to_transaction(
const asset& amount_to_withdraw,
const string& from_account_name,
signed_transaction& trx,
unordered_set<address>& required_signatures
)
{ try {
FC_ASSERT( !from_account_name.empty() );
auto amount_remaining = amount_to_withdraw;
const account_balance_record_summary_type balance_records = self->get_account_balance_records( from_account_name );
if( balance_records.find( from_account_name ) == balance_records.end() )
FC_CAPTURE_AND_THROW( insufficient_funds, (from_account_name)(amount_to_withdraw)(balance_records) );
for( const auto& record : balance_records.at( from_account_name ) )
{
const asset balance = record.get_spendable_balance( _blockchain->get_pending_state()->now() );
if( balance.amount <= 0 || balance.asset_id != amount_remaining.asset_id )
continue;
if( amount_remaining.amount > balance.amount )
{
trx.withdraw( record.id(), balance.amount );
required_signatures.insert( record.owner() );
amount_remaining -= balance;
}
else
{
trx.withdraw( record.id(), amount_remaining.amount );
required_signatures.insert( record.owner() );
return;
}
}
const string required = _blockchain->to_pretty_asset( amount_to_withdraw );
const string available = _blockchain->to_pretty_asset( amount_to_withdraw - amount_remaining );
FC_CAPTURE_AND_THROW( insufficient_funds, (required)(available)(balance_records) );
} FC_CAPTURE_AND_RETHROW( (amount_to_withdraw)(from_account_name)(trx)(required_signatures) ) }
// TODO: What about retracted accounts?
void wallet_impl::authorize_update(unordered_set<address>& required_signatures, oaccount_record account, bool need_owner_key )
{
owallet_key_record oauthority_key = _wallet_db.lookup_key(account->owner_key);
// We do this check a lot and it doesn't fit conveniently into a loop because we're interested in two types of keys.
// Instead, we extract it into a function.
auto accept_key = [&]()->bool
{
if( oauthority_key.valid() && oauthority_key->has_private_key() )
{
required_signatures.insert( oauthority_key->get_address() );
return true;
}
return false;
};
if( accept_key() ) return;
if( !need_owner_key )
{
oauthority_key = _wallet_db.lookup_key(account->active_address());
if( accept_key() ) return;
}
auto dot = account->name.find('.');
while( dot != string::npos )
{
account = _blockchain->get_account_record( account->name.substr( dot+1 ) );
FC_ASSERT( account.valid(), "Parent account is not valid; this should never happen." );
oauthority_key = _wallet_db.lookup_key(account->active_address());
if( accept_key() ) return;
oauthority_key = _wallet_db.lookup_key(account->owner_key);
if( accept_key() ) return;
dot = account->name.find('.');
}
}
secret_hash_type wallet_impl::get_secret( uint32_t block_num,
const private_key_type& delegate_key )const
{
block_id_type header_id;
if( block_num != uint32_t(-1) && block_num > 1 )
{
auto block_header = _blockchain->get_block_header( block_num - 1 );
header_id = block_header.id();
}
fc::sha512::encoder key_enc;
fc::raw::pack( key_enc, delegate_key );
fc::sha512::encoder enc;
fc::raw::pack( enc, key_enc.result() );
fc::raw::pack( enc, header_id );
return fc::ripemd160::hash( enc.result() );
}
void wallet_impl::reschedule_relocker()
{
if( !_relocker_done.valid() || _relocker_done.ready() )
_relocker_done = fc::async( [this](){ relocker(); }, "wallet_relocker" );
}
void wallet_impl::relocker()
{
fc::time_point now = fc::time_point::now();
ilog( "Starting wallet relocker task at time: ${t}", ("t", now) );
if( !_scheduled_lock_time.valid() || now >= *_scheduled_lock_time )
{
/* Don't relock if we have enabled delegates */
if( !self->get_my_delegates( enabled_delegate_status ).empty() )
{
ulog( "Wallet not automatically relocking because there are enabled delegates!" );
return;
}
self->lock();
}
else
{
if (!_relocker_done.canceled())
{
ilog( "Scheduling wallet relocker task for time: ${t}", ("t", *_scheduled_lock_time) );
_relocker_done = fc::schedule( [this](){ relocker(); },
*_scheduled_lock_time,
"wallet_relocker" );
}
}
}
void wallet_impl::scan_chain_task( uint32_t start, uint32_t end, bool fast_scan )
{
auto min_end = std::min<size_t>( _blockchain->get_head_block_num(), end );
try
{
const auto now = blockchain::now();
_scan_progress = 0;
// Collect private keys
const auto account_keys = _wallet_db.get_account_private_keys( _wallet_password );
vector<private_key_type> private_keys;
private_keys.reserve( account_keys.size() );
for( const auto& item : account_keys )
private_keys.push_back( item.first );
// Collect balances
map<address, string> account_balances;
const account_balance_id_summary_type balance_id_summary = self->get_account_balance_ids();
for( const auto& balance_item : balance_id_summary )
{
const string& account_name = balance_item.first;
for( const auto& balance_id : balance_item.second )
account_balances[ balance_id ] = account_name;
}
// Collect accounts
set<string> account_names;
const vector<wallet_account_record> accounts = self->list_my_accounts();
for( const wallet_account_record& account : accounts )
account_names.insert( account.name );
if( min_end > start + 1 )
ulog( "Beginning scan at block ${n}...", ("n",start) );
for( auto block_num = start; !_scan_in_progress.canceled() && block_num <= min_end; ++block_num )
{
scan_block( block_num, private_keys, now );
#ifdef BTS_TEST_NETWORK
try
{
scan_block_experimental( block_num, account_keys, account_balances, account_names );
}
catch( ... )
{
}
#endif
_scan_progress = float(block_num-start)/(min_end-start+1);
self->set_last_scanned_block_number( block_num );
if( block_num > start )
{
if( (block_num - start) % 10000 == 0 )
ulog( "Scanning ${p} done...", ("p",cli::pretty_percent( _scan_progress, 1 )) );
if( !fast_scan && (block_num - start) % 100 == 0 )
fc::usleep( fc::microseconds( 100 ) );
}
}
// Update local accounts
{
const auto accounts = _wallet_db.get_accounts();
for( auto acct : accounts )
{
auto blockchain_acct_rec = _blockchain->get_account_record( acct.second.id );
if( blockchain_acct_rec.valid() )
_wallet_db.store_account( *blockchain_acct_rec );
}
}
_scan_progress = 1;
if( min_end > start + 1 )
ulog( "Scan completed." );
}
catch(...)
{
_scan_progress = -1;
ulog( "Scan failure." );
throw;
}
}
void wallet_impl::upgrade_version()
{
const uint32_t current_version = self->get_version();
if( current_version > BTS_WALLET_VERSION )
{
FC_THROW_EXCEPTION( unsupported_version, "Wallet version newer than client supports!",
("wallet_version",current_version)("supported_version",BTS_WALLET_VERSION) );
}
else if( current_version == BTS_WALLET_VERSION )
{
return;
}
ulog( "Upgrading wallet..." );
std::exception_ptr upgrade_failure_exception;
try
{
self->auto_backup( "version_upgrade" );
/* Example
if( current_version < 101 )
{
// Upgrade here
}
*/
if( _unlocked_upgrade_tasks.empty() )
{
self->set_version( BTS_WALLET_VERSION );
ulog( "Wallet successfully upgraded." );
}
else
{
ulog( "Please unlock your wallet to complete the upgrade..." );
}
}
catch( ... )
{
upgrade_failure_exception = std::current_exception();
}
if (upgrade_failure_exception)
{
ulog( "Wallet upgrade failure." );
std::rethrow_exception(upgrade_failure_exception);
}
}
void wallet_impl::upgrade_version_unlocked()
{
if( _unlocked_upgrade_tasks.empty() ) return;
ulog( "Continuing wallet upgrade..." );
std::exception_ptr upgrade_failure_exception;
try
{
for( const auto& task : _unlocked_upgrade_tasks ) task();
_unlocked_upgrade_tasks.clear();
self->set_version( BTS_WALLET_VERSION );
ulog( "Wallet successfully upgraded." );
}
catch( ... )
{
upgrade_failure_exception = std::current_exception();
}
if (upgrade_failure_exception)
{
ulog( "Wallet upgrade failure." );
std::rethrow_exception(upgrade_failure_exception);
}
}
void wallet_impl::apply_order_to_builder(order_type_enum order_type,
transaction_builder_ptr builder,
const string& account_name,
const string& balance,
const string& order_price,
const string& base_symbol,
const string& quote_symbol,
const string& limit)
{
if( !is_receive_account(account_name) )
FC_CAPTURE_AND_THROW( unknown_receive_account, (account_name) );
asset quantity = _blockchain->to_ugly_asset(balance, base_symbol);
if( quantity.amount < 0 )
FC_CAPTURE_AND_THROW( invalid_asset_amount, (balance) );
if( quantity.amount == 0 && order_type != cover_order )
FC_CAPTURE_AND_THROW( invalid_asset_amount, (balance) );
if( order_type != cover_order && atof(order_price.c_str()) < 0 )
FC_CAPTURE_AND_THROW( invalid_price, (order_price) );
if( (order_type == bid_order || order_type == ask_order) && atof(order_price.c_str()) == 0 )
FC_CAPTURE_AND_THROW( invalid_price, (order_price) );
if( (order_type == relative_bid_order || order_type == relative_ask_order) && atof(order_price.c_str()) == 0 )
FC_CAPTURE_AND_THROW( invalid_price, (order_price) );
price price_arg = _blockchain->to_ugly_price(order_price,
base_symbol,
quote_symbol,
order_type != short_order);
//This affects shorts only.
oprice price_limit;
if( !limit.empty() && atof(limit.c_str()) > 0 )
price_limit = _blockchain->to_ugly_price(limit, base_symbol, quote_symbol);
if( order_type == bid_order )
builder->submit_bid(self->get_account(account_name), quantity, price_arg);
else if( order_type == ask_order )
builder->submit_ask(self->get_account(account_name), quantity, price_arg);
else if( order_type == relative_bid_order )
builder->submit_relative_bid(self->get_account(account_name), quantity, price_arg, price_limit);
else if( order_type == relative_ask_order )
builder->submit_relative_ask(self->get_account(account_name), quantity, price_arg, price_limit);
else if( order_type == short_order )
{
price_arg.ratio /= 100;
FC_ASSERT( price_arg.ratio < fc::uint128( 10, 0 ), "APR must be less than 1000%" );
builder->submit_short(self->get_account(account_name), quantity, price_arg, price_limit);
}
else
FC_THROW_EXCEPTION( invalid_operation, "This function only supports bids, asks and shorts." );
}
void wallet_impl::create_file( const path& wallet_file_path,
const string& password,
const string& brainkey )
{ try {
FC_ASSERT( self->is_enabled(), "Wallet is disabled in this client!" );
if( fc::exists( wallet_file_path ) )
FC_THROW_EXCEPTION( wallet_already_exists, "Wallet file already exists!", ("wallet_file_path",wallet_file_path) );
if( password.size() < BTS_WALLET_MIN_PASSWORD_LENGTH )
FC_THROW_EXCEPTION( password_too_short, "Password too short!", ("size",password.size()) );
std::exception_ptr create_file_failure;
try
{
self->close();
_wallet_db.open( wallet_file_path );
_wallet_password = fc::sha512::hash( password.c_str(), password.size() );
master_key new_master_key;
extended_private_key epk;
if( !brainkey.empty() )
{
auto base = fc::sha512::hash( brainkey.c_str(), brainkey.size() );
/* strengthen the key a bit */
for( uint32_t i = 0; i < 100ll*1000ll; ++i )
base = fc::sha512::hash( base );
epk = extended_private_key( base );
}
else
{
wlog( "generating random" );
epk = extended_private_key( private_key_type::generate() );
}
_wallet_db.set_master_key( epk, _wallet_password);
self->set_version( BTS_WALLET_VERSION );
self->set_automatic_backups( true );
self->set_transaction_scanning( true );
self->set_last_scanned_block_number( _blockchain->get_head_block_num() );
self->set_transaction_fee( asset( BTS_WALLET_DEFAULT_TRANSACTION_FEE ) );
self->set_transaction_expiration( BTS_WALLET_DEFAULT_TRANSACTION_EXPIRATION_SEC );
_wallet_db.close();
_wallet_db.open( wallet_file_path );
_current_wallet_path = wallet_file_path;
FC_ASSERT( _wallet_db.validate_password( _wallet_password ) );
}
catch( ... )
{
create_file_failure = std::current_exception();
}
if (create_file_failure)
{
self->close();
fc::remove_all( wallet_file_path );
std::rethrow_exception(create_file_failure);
}
} FC_RETHROW_EXCEPTIONS( warn, "Unable to create wallet '${wallet_file_path}'", ("wallet_file_path",wallet_file_path) ) }
void wallet_impl::open_file( const path& wallet_file_path )
{ try {
FC_ASSERT( self->is_enabled(), "Wallet is disabled in this client!" );
if ( !fc::exists( wallet_file_path ) )
FC_THROW_EXCEPTION( no_such_wallet, "No such wallet exists!", ("wallet_file_path", wallet_file_path) );
if( self->is_open() && _current_wallet_path == wallet_file_path )
return;
std::exception_ptr open_file_failure;
try
{
self->close();
_current_wallet_path = wallet_file_path;
_wallet_db.open( wallet_file_path );
upgrade_version();
self->set_data_directory( fc::absolute( wallet_file_path.parent_path() ) );
}
catch( ... )
{
open_file_failure = std::current_exception();
}
if (open_file_failure)
{
self->close();
std::rethrow_exception(open_file_failure);
}
} FC_RETHROW_EXCEPTIONS( warn, "Unable to open wallet ${wallet_file_path}", ("wallet_file_path",wallet_file_path) ) }
/**
* Creates a new private key under the specified account. This key
* will not be valid for sending TITAN transactions to, but will
* be able to receive payments directly.
*/
private_key_type wallet_impl::get_new_private_key( const string& account_name )
{ try {
if( NOT self->is_open() ) FC_CAPTURE_AND_THROW( wallet_closed );
if( NOT self->is_unlocked() ) FC_CAPTURE_AND_THROW( wallet_locked );
if( NOT is_receive_account(account_name) )
FC_CAPTURE_AND_THROW( unknown_receive_account, (account_name) );
const auto current_account = _wallet_db.lookup_account( account_name );
FC_ASSERT( current_account.valid() );
return _wallet_db.generate_new_account_child_key( _wallet_password, account_name );
} FC_CAPTURE_AND_RETHROW( (account_name) ) }
public_key_type wallet_impl::get_new_public_key( const string& account_name )
{ try {
return get_new_private_key( account_name ).get_public_key();
} FC_CAPTURE_AND_RETHROW( (account_name) ) }
address wallet_impl::get_new_address( const string& account_name, const string& label )
{ try {
auto addr = address( get_new_public_key( account_name ) );
auto okey = _wallet_db.lookup_key( addr );
FC_ASSERT( okey.valid(), "Key I just created does not exist" );
//okey->btc_data->label = label;
_wallet_db.store_key( *okey );
return addr;
} FC_CAPTURE_AND_RETHROW( (account_name) ) }
slate_id_type wallet_impl::select_slate( signed_transaction& transaction, const asset_id_type& deposit_asset_id,
vote_selection_method selection_method )
{
auto slate_id = slate_id_type( 0 );
if( deposit_asset_id != asset_id_type( 0 ) ) return slate_id;
const auto slate = select_delegate_vote( selection_method );
slate_id = slate.id();
if( slate_id != slate_id_type( 0 ) && !_blockchain->get_delegate_slate( slate_id ).valid() )
transaction.define_delegate_slate( slate );
return slate_id;
}
void wallet_impl::scan_state()
{ try {
ilog( "WALLET: Scanning blockchain state" );
scan_balances();
scan_registered_accounts();
} FC_CAPTURE_AND_RETHROW() }
/**
* A valid account is any named account registered in the blockchain or
* any local named account.
*/
bool wallet_impl::is_valid_account( const string& account_name )const
{
if( !_blockchain->is_valid_account_name( account_name ) )
FC_THROW_EXCEPTION( invalid_name, "Invalid account name!", ("account_name",account_name) );
FC_ASSERT( self->is_open() );
if( _wallet_db.lookup_account( account_name ).valid() )
return true;
return _blockchain->get_account_record( account_name ).valid();
}
/**
* Any account for which this wallet owns the active private key.
*/
bool wallet_impl::is_receive_account( const string& account_name )const
{
FC_ASSERT( self->is_open() );
if( !_blockchain->is_valid_account_name( account_name ) ) return false;
auto opt_account = _wallet_db.lookup_account( account_name );
if( !opt_account.valid() ) return false;
auto opt_key = _wallet_db.lookup_key( opt_account->active_address() );
if( !opt_key.valid() ) return false;
return opt_key->has_private_key();
}
bool wallet_impl::is_unique_account( const string& account_name )const
{
//There are two possibilities here. First, the wallet has multiple records named account_name
//Second, the wallet has a different record named account_name than the blockchain does.
//Check that the wallet has at most one account named account_name
auto known_accounts = _wallet_db.get_accounts();
bool found = false;
for( const auto& known_account : known_accounts )
{
if( known_account.second.name == account_name )
{
if( found ) return false;
found = true;
}
}
if( !found )
//The wallet does not contain an account with this name. No conflict is possible.
return true;
//The wallet has an account named account_name. Check that it matches with the blockchain
auto local_account = _wallet_db.lookup_account( account_name );
auto registered_account = _blockchain->get_account_record( account_name );
if( local_account && registered_account )
return local_account->owner_key == registered_account->owner_key;
return local_account || registered_account;
}
/**
* Select a slate of delegates from those approved by this wallet. Specify
* selection_method as vote_none, vote_all, or vote_random. The slate
* returned will contain no more than BTS_BLOCKCHAIN_MAX_SLATE_SIZE delegates.
*/
delegate_slate wallet_impl::select_delegate_vote( vote_selection_method selection_method )
{
if( selection_method == vote_none )
return delegate_slate();
vector<account_id_type> for_candidates;
const auto account_items = _wallet_db.get_accounts();
for( const auto& item : account_items )
{
const auto account_record = item.second;
if( !account_record.is_delegate() && selection_method != vote_recommended ) continue;
if( account_record.approved <= 0 ) continue;
for_candidates.push_back( account_record.id );
}
std::random_shuffle( for_candidates.begin(), for_candidates.end() );
size_t slate_size = 0;
if( selection_method == vote_all )
{
slate_size = std::min<size_t>( BTS_BLOCKCHAIN_MAX_SLATE_SIZE, for_candidates.size() );
}
else if( selection_method == vote_random )
{
slate_size = std::min<size_t>( BTS_BLOCKCHAIN_MAX_SLATE_SIZE / 3, for_candidates.size() );
slate_size = rand() % ( slate_size + 1 );
}
else if( selection_method == vote_recommended && for_candidates.size() < BTS_BLOCKCHAIN_MAX_SLATE_SIZE )
{
unordered_map<account_id_type, int> recommended_candidate_ranks;
//Tally up the recommendation count for all delegates recommended by delegates I approve of
for( const auto& approved_candidate : for_candidates )
{
oaccount_record candidate_record = _blockchain->get_account_record(approved_candidate);
if( !candidate_record.valid() ) continue;
if( candidate_record->is_retracted() ) continue;
if( !candidate_record->public_data.is_object()
|| !candidate_record->public_data.get_object().contains("slate_id"))
continue;
if( !candidate_record->public_data.get_object()["slate_id"].is_uint64() )
{
//Delegate is doing something non-kosher with their slate_id. Disapprove of them.
self->set_account_approval( candidate_record->name, -1 );
continue;
}
odelegate_slate recomendations = _blockchain->get_delegate_slate(candidate_record->public_data.get_object()["slate_id"].as<slate_id_type>());
if( !recomendations.valid() )
{
//Delegate is doing something non-kosher with their slate_id. Disapprove of them.
self->set_account_approval( candidate_record->name, -1 );
continue;
}
for( const auto& recommended_candidate : recomendations->supported_delegates )
++recommended_candidate_ranks[recommended_candidate];
}
//Disqualify non-delegates and delegates I actively disapprove of
for( const auto& acct_rec : account_items )
if( !acct_rec.second.is_delegate() || acct_rec.second.approved < 0 )
recommended_candidate_ranks.erase(acct_rec.second.id);
//Remove from rankings candidates I already approve of
for( const auto& approved_id : for_candidates )
if( recommended_candidate_ranks.find(approved_id) != recommended_candidate_ranks.end() )
recommended_candidate_ranks.erase(approved_id);
//Remove non-delegates from for_candidates
vector<account_id_type> delegates;
for( const auto& id : for_candidates )
{
const oaccount_record record = _blockchain->get_account_record( id );
if( !record.valid() ) continue;
if( !record->is_delegate() ) continue;
if( record->is_retracted() ) continue;
delegates.push_back(id);
}
for_candidates = delegates;
//While I can vote for more candidates, and there are more recommendations to vote for...
while( for_candidates.size() < BTS_BLOCKCHAIN_MAX_SLATE_SIZE && recommended_candidate_ranks.size() > 0 )
{
int best_rank = 0;
account_id_type best_ranked_candidate;
//Add highest-ranked candidate to my list to vote for and remove him from rankings
for( const auto& ranked_candidate : recommended_candidate_ranks )
if( ranked_candidate.second > best_rank )
{
best_rank = ranked_candidate.second;
best_ranked_candidate = ranked_candidate.first;
}
for_candidates.push_back(best_ranked_candidate);
recommended_candidate_ranks.erase(best_ranked_candidate);
}
slate_size = for_candidates.size();
}
auto slate = delegate_slate();
slate.supported_delegates = for_candidates;
slate.supported_delegates.resize( slate_size );
FC_ASSERT( slate.supported_delegates.size() <= BTS_BLOCKCHAIN_MAX_SLATE_SIZE );
std::sort( slate.supported_delegates.begin(), slate.supported_delegates.end() );
return slate;
}
} // bts::wallet::detail
wallet::wallet( chain_database_ptr blockchain, bool enabled )
: my( new detail::wallet_impl() )
{
my->self = this;
my->_is_enabled = enabled;
my->_blockchain = blockchain;
my->_blockchain->add_observer( my.get() );
}
wallet::~wallet()
{
close();
}
void wallet::set_data_directory( const path& data_dir )
{
my->_data_directory = data_dir;
}
path wallet::get_data_directory()const
{
return my->_data_directory;
}
void wallet::create( const string& wallet_name,
const string& password,
const string& brainkey )
{ try {
FC_ASSERT(is_enabled(), "Wallet is disabled in this client!");
if( !my->_blockchain->is_valid_account_name( wallet_name ) )
FC_THROW_EXCEPTION( invalid_name, "Invalid name for a wallet!", ("wallet_name",wallet_name) );
auto wallet_file_path = fc::absolute( get_data_directory() ) / wallet_name;
if( fc::exists( wallet_file_path ) )
FC_THROW_EXCEPTION( wallet_already_exists, "Wallet name already exists!", ("wallet_name",wallet_name) );
if( password.size() < BTS_WALLET_MIN_PASSWORD_LENGTH )
FC_THROW_EXCEPTION( password_too_short, "Password too short!", ("size",password.size()) );
std::exception_ptr wallet_create_failure;
try
{
my->create_file( wallet_file_path, password, brainkey );
open( wallet_name );
unlock( password, BTS_WALLET_DEFAULT_UNLOCK_TIME_SEC );
}
catch( ... )
{
wallet_create_failure = std::current_exception();
}
if (wallet_create_failure)
{
close();
std::rethrow_exception(wallet_create_failure);
}
} FC_RETHROW_EXCEPTIONS( warn, "Unable to create wallet '${wallet_name}'", ("wallet_name",wallet_name) ) }
void wallet::open( const string& wallet_name )
{ try {
FC_ASSERT(is_enabled(), "Wallet is disabled in this client!");
if( !my->_blockchain->is_valid_account_name( wallet_name ) )
FC_THROW_EXCEPTION( invalid_name, "Invalid name for a wallet!", ("wallet_name",wallet_name) );
auto wallet_file_path = fc::absolute( get_data_directory() ) / wallet_name;
if ( !fc::exists( wallet_file_path ) )
FC_THROW_EXCEPTION( no_such_wallet, "No such wallet exists!", ("wallet_name", wallet_name) );
std::exception_ptr open_file_failure;
try
{
my->open_file( wallet_file_path );
}
catch( ... )
{
open_file_failure = std::current_exception();
}
if (open_file_failure)
{
close();
std::rethrow_exception(open_file_failure);
}
} FC_CAPTURE_AND_RETHROW( (wallet_name) ) }
void wallet::close()
{ try {
try
{
ilog( "Canceling wallet scan_chain_task..." );
my->_scan_in_progress.cancel_and_wait("wallet::close()");
ilog( "Wallet scan_chain_task canceled..." );
}
catch( const fc::exception& e )
{
wlog("Unexpected exception from wallet's scan_chain_task() : ${e}", ("e", e));
}
catch( ... )
{
wlog("Unexpected exception from wallet's scan_chain_task()");
}
lock();
try
{
ilog( "Canceling wallet relocker task..." );
my->_relocker_done.cancel_and_wait("wallet::close()");
ilog( "Wallet relocker task canceled" );
}
catch( const fc::exception& e )
{
wlog("Unexpected exception from wallet's relocker() : ${e}", ("e", e));
}
catch( ... )
{
wlog("Unexpected exception from wallet's relocker()");
}
my->_wallet_db.close();
my->_current_wallet_path = fc::path();
} FC_CAPTURE_AND_RETHROW() }
bool wallet::is_enabled() const
{
return my->_is_enabled;
}
bool wallet::is_open()const
{
return my->_wallet_db.is_open();
}
string wallet::get_wallet_name()const
{
return my->_current_wallet_path.filename().generic_string();
}
void wallet::export_to_json( const path& filename )const
{ try {
if( fc::exists( filename ) )
FC_THROW_EXCEPTION( file_already_exists, "Filename to export to already exists!", ("filename",filename) );
FC_ASSERT( is_open() );
my->_wallet_db.export_to_json( filename );
} FC_CAPTURE_AND_RETHROW( (filename) ) }
void wallet::create_from_json( const path& filename, const string& wallet_name, const string& passphrase )
{ try {
FC_ASSERT(is_enabled(), "Wallet is disabled in this client!");
if( !fc::exists( filename ) )
FC_THROW_EXCEPTION( file_not_found, "Filename to import from could not be found!", ("filename",filename) );
if( !my->_blockchain->is_valid_account_name( wallet_name ) )
FC_THROW_EXCEPTION( invalid_wallet_name, "Invalid name for a wallet!", ("wallet_name",wallet_name) );
create( wallet_name, passphrase );
std::exception_ptr import_failure;
try
{
set_version( 0 );
my->_wallet_db.import_from_json( filename );
close();
open( wallet_name );
unlock( passphrase, BTS_WALLET_DEFAULT_UNLOCK_TIME_SEC );
}
catch( ... )
{
import_failure = std::current_exception();
}
if (import_failure)
{
close();
fc::path wallet_file_path = fc::absolute( get_data_directory() ) / wallet_name;
fc::remove_all( wallet_file_path );
std::rethrow_exception(import_failure);
}
} FC_CAPTURE_AND_RETHROW( (filename)(wallet_name) ) }
void wallet::auto_backup( const string& reason )const
{ try {
if( !get_automatic_backups() ) return;
ulog( "Backing up wallet..." );
fc::path wallet_path = my->_current_wallet_path;
std::string wallet_name = wallet_path.filename().string();
fc::path wallet_dir = wallet_path.parent_path();
fc::path backup_path;
while( true )
{
fc::time_point_sec now( time_point::now() );
std::string backup_filename = wallet_name + "-" + now.to_non_delimited_iso_string();
if( !reason.empty() ) backup_filename += "-" + reason;
backup_filename += ".json";
backup_path = wallet_dir / ".backups" / wallet_name / backup_filename;
if( !fc::exists( backup_path ) ) break;
fc::usleep( fc::seconds( 1 ) );
}
export_to_json( backup_path );
ulog( "Wallet automatically backed up to: ${f}", ("f",backup_path) );
} FC_CAPTURE_AND_RETHROW() }
void wallet::set_version( uint32_t v )
{ try {
FC_ASSERT( is_open() );
my->_wallet_db.set_property( version, variant( v ) );
} FC_CAPTURE_AND_RETHROW() }
uint32_t wallet::get_version()const
{ try {
FC_ASSERT( is_open() );
try
{
return my->_wallet_db.get_property( version ).as<uint32_t>();
}
catch( ... )
{
}
return 0;
} FC_CAPTURE_AND_RETHROW() }
void wallet::set_automatic_backups( bool enabled )
{ try {
FC_ASSERT( is_open() );
my->_wallet_db.set_property( automatic_backups, variant( enabled ) );
} FC_CAPTURE_AND_RETHROW() }
bool wallet::get_automatic_backups()const
{ try {
FC_ASSERT( is_open() );
try
{
return my->_wallet_db.get_property( automatic_backups ).as<bool>();
}
catch( ... )
{
}
return true;
} FC_CAPTURE_AND_RETHROW() }
void wallet::set_transaction_scanning( bool enabled )
{ try {
FC_ASSERT( is_open() );
my->_wallet_db.set_property( transaction_scanning, variant( enabled ) );
} FC_CAPTURE_AND_RETHROW() }
bool wallet::get_transaction_scanning()const
{ try {
FC_ASSERT( is_open() );
if( list_my_accounts().empty() )
return false;
try
{
return my->_wallet_db.get_property( transaction_scanning ).as<bool>();
}
catch( ... )
{
}
return true;
} FC_CAPTURE_AND_RETHROW() }
void wallet::unlock( const string& password, uint32_t timeout_seconds )
{ try {
std::exception_ptr unlock_error;
try
{
FC_ASSERT( is_open() );
if( timeout_seconds < 1 )
FC_THROW_EXCEPTION( invalid_timeout, "Invalid timeout!" );