Repository navigation
Expand file tree
/
Copy pathservice_node_list.cpp
More file actions
1994 lines (1678 loc) · 77.5 KB
/
Copy pathservice_node_list.cpp
File metadata and controls
1994 lines (1678 loc) · 77.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2018, The Loki Project
// Copyright (c) 2018, The Worktips Project
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <functional>
#include <random>
#include <algorithm>
#include "ringct/rctSigs.h"
#include "wallet/wallet2.h"
#include "cryptonote_tx_utils.h"
#include "cryptonote_basic/tx_extra.h"
#include "int-util.h"
#include "common/scoped_message_writer.h"
#include "common/i18n.h"
#include "service_node_quorum_cop.h"
#include "service_node_list.h"
#include "service_node_rules.h"
#undef WORKTIPS_DEFAULT_LOG_CATEGORY
#define WORKTIPS_DEFAULT_LOG_CATEGORY "service_nodes"
namespace service_nodes
{
static int get_min_service_node_info_version_for_hf(int hf_version)
{
if (hf_version >= cryptonote::network_version_7 && hf_version <= cryptonote::network_version_9_service_nodes)
return service_node_info::version_0;
if (hf_version == cryptonote::network_version_10_bulletproofs)
return service_node_info::version_1_swarms;
return service_node_info::version_2_infinite_staking;
}
static uint64_t uniform_distribution_portable(std::mt19937_64& mersenne_twister, uint64_t n)
{
uint64_t secureMax = mersenne_twister.max() - mersenne_twister.max() % n;
uint64_t x;
do x = mersenne_twister(); while (x >= secureMax);
return x / (secureMax / n);
}
service_node_list::service_node_list(cryptonote::Blockchain& blockchain)
: m_blockchain(blockchain), m_hooks_registered(false), m_db(nullptr), m_service_node_pubkey(nullptr)
{
m_transient_state = {};
}
void service_node_list::register_hooks(service_nodes::quorum_cop &quorum_cop)
{
std::lock_guard<boost::recursive_mutex> lock(m_sn_mutex);
if (!m_hooks_registered)
{
m_hooks_registered = true;
m_blockchain.hook_block_added(*this);
m_blockchain.hook_blockchain_detached(*this);
m_blockchain.hook_init(*this);
m_blockchain.hook_validate_miner_tx(*this);
// NOTE: There is an implicit dependency on service node lists hooks
m_blockchain.hook_init(quorum_cop);
m_blockchain.hook_block_added(quorum_cop);
m_blockchain.hook_blockchain_detached(quorum_cop);
}
}
void service_node_list::init()
{
std::lock_guard<boost::recursive_mutex> lock(m_sn_mutex);
if (m_blockchain.get_current_hard_fork_version() < 9)
{
clear(true);
return;
}
uint64_t current_height = m_blockchain.get_current_blockchain_height();
bool loaded = load();
if (loaded && m_transient_state.height == current_height) return;
if (!loaded || m_transient_state.height > current_height) clear(true);
LOG_PRINT_L0("Recalculating service nodes list, scanning blockchain from height " << m_transient_state.height);
LOG_PRINT_L0("This may take some time...");
std::vector<std::pair<cryptonote::blobdata, cryptonote::block>> blocks;
for (uint64_t i = 0; m_transient_state.height < current_height; i++)
{
if (i > 0 && i % 10 == 0)
LOG_PRINT_L0("... scanning height " << m_transient_state.height);
blocks.clear();
if (!m_blockchain.get_blocks(m_transient_state.height, 1000, blocks))
{
MERROR("Unable to initialize service nodes list");
return;
}
std::vector<cryptonote::transaction> txs;
std::vector<crypto::hash> missed_txs;
for (const auto& block_pair : blocks)
{
txs.clear();
missed_txs.clear();
const cryptonote::block& block = block_pair.second;
std::vector<cryptonote::transaction> txs;
std::vector<crypto::hash> missed_txs;
if (!m_blockchain.get_transactions(block.tx_hashes, txs, missed_txs))
{
MERROR("Unable to get transactions for block " << block.hash);
return;
}
block_added_generic(block, txs);
}
}
LOG_PRINT_L0("Done recalculating service nodes list");
}
std::vector<crypto::public_key> service_node_list::get_service_nodes_pubkeys() const
{
std::vector<crypto::public_key> result;
for (const auto& iter : m_transient_state.service_nodes_infos)
if (iter.second.is_fully_funded())
result.push_back(iter.first);
std::sort(result.begin(), result.end(),
[](const crypto::public_key &a, const crypto::public_key &b) {
return memcmp(reinterpret_cast<const void*>(&a), reinterpret_cast<const void*>(&b), sizeof(a)) < 0;
});
return result;
}
const std::shared_ptr<const quorum_state> service_node_list::get_quorum_state(uint64_t height) const
{
std::lock_guard<boost::recursive_mutex> lock(m_sn_mutex);
const auto &it = m_transient_state.quorum_states.find(height);
if (it != m_transient_state.quorum_states.end())
{
return it->second;
}
return nullptr;
}
std::vector<service_node_pubkey_info> service_node_list::get_service_node_list_state(const std::vector<crypto::public_key> &service_node_pubkeys) const
{
std::lock_guard<boost::recursive_mutex> lock(m_sn_mutex);
std::vector<service_node_pubkey_info> result;
if (service_node_pubkeys.empty())
{
result.reserve(m_transient_state.service_nodes_infos.size());
for (const auto &it : m_transient_state.service_nodes_infos)
{
service_node_pubkey_info entry = {};
entry.pubkey = it.first;
entry.info = it.second;
result.push_back(entry);
}
}
else
{
result.reserve(service_node_pubkeys.size());
for (const auto &it : service_node_pubkeys)
{
const auto &find_it = m_transient_state.service_nodes_infos.find(it);
if (find_it == m_transient_state.service_nodes_infos.end())
continue;
service_node_pubkey_info entry = {};
entry.pubkey = (*find_it).first;
entry.info = (*find_it).second;
result.push_back(entry);
}
}
return result;
}
void service_node_list::set_db_pointer(cryptonote::BlockchainDB* db)
{
std::lock_guard<boost::recursive_mutex> lock(m_sn_mutex);
m_db = db;
}
void service_node_list::set_my_service_node_keys(crypto::public_key const *pub_key)
{
std::lock_guard<boost::recursive_mutex> lock(m_sn_mutex);
m_service_node_pubkey = pub_key;
}
bool service_node_list::is_service_node(const crypto::public_key& pubkey) const
{
std::lock_guard<boost::recursive_mutex> lock(m_sn_mutex);
return m_transient_state.service_nodes_infos.find(pubkey) != m_transient_state.service_nodes_infos.end();
}
bool service_node_list::is_key_image_locked(crypto::key_image const &check_image, uint64_t *unlock_height, service_node_info::contribution_t *the_locked_contribution) const
{
for (const auto& pubkey_info : m_transient_state.service_nodes_infos)
{
const service_node_info &info = pubkey_info.second;
for (const service_node_info::contributor_t &contributor : info.contributors)
{
for (const service_node_info::contribution_t &contribution : contributor.locked_contributions)
{
if (check_image == contribution.key_image)
{
if (the_locked_contribution) *the_locked_contribution = contribution;
if (unlock_height) *unlock_height = info.requested_unlock_height;
return true;
}
}
}
}
return false;
}
bool reg_tx_extract_fields(const cryptonote::transaction& tx, std::vector<cryptonote::account_public_address>& addresses, uint64_t& portions_for_operator, std::vector<uint64_t>& portions, uint64_t& expiration_timestamp, crypto::public_key& service_node_key, crypto::signature& signature)
{
cryptonote::tx_extra_service_node_register registration;
if (!get_service_node_register_from_tx_extra(tx.extra, registration))
return false;
if (!cryptonote::get_service_node_pubkey_from_tx_extra(tx.extra, service_node_key))
return false;
addresses.clear();
addresses.reserve(registration.m_public_spend_keys.size());
for (size_t i = 0; i < registration.m_public_spend_keys.size(); i++)
addresses.push_back(cryptonote::account_public_address{ registration.m_public_spend_keys[i], registration.m_public_view_keys[i] });
portions_for_operator = registration.m_portions_for_operator;
portions = registration.m_portions;
expiration_timestamp = registration.m_expiration_timestamp;
signature = registration.m_service_node_signature;
return true;
}
struct parsed_tx_contribution
{
cryptonote::account_public_address address;
uint64_t transferred;
crypto::secret_key tx_key;
std::vector<service_node_info::contribution_t> locked_contributions;
};
static uint64_t get_reg_tx_staking_output_contribution(const cryptonote::transaction& tx, int i, crypto::key_derivation const &derivation, hw::device& hwdev)
{
if (tx.vout[i].target.type() != typeid(cryptonote::txout_to_key))
{
return 0;
}
rct::key mask;
uint64_t money_transferred = 0;
crypto::secret_key scalar1;
hwdev.derivation_to_scalar(derivation, i, scalar1);
try
{
switch (tx.rct_signatures.type)
{
case rct::RCTTypeSimple:
case rct::RCTTypeBulletproof:
case rct::RCTTypeBulletproof2:
money_transferred = rct::decodeRctSimple(tx.rct_signatures, rct::sk2rct(scalar1), i, mask, hwdev);
break;
case rct::RCTTypeFull:
money_transferred = rct::decodeRct(tx.rct_signatures, rct::sk2rct(scalar1), i, mask, hwdev);
break;
default:
LOG_PRINT_L0("Unsupported rct type: " << tx.rct_signatures.type);
return 0;
}
}
catch (const std::exception &e)
{
LOG_PRINT_L0("Failed to decode input " << i);
return 0;
}
return money_transferred;
}
bool service_node_list::process_deregistration_tx(const cryptonote::transaction& tx, uint64_t block_height)
{
if (tx.get_type() != cryptonote::transaction::type_deregister)
return false;
cryptonote::tx_extra_service_node_deregister deregister;
if (!cryptonote::get_service_node_deregister_from_tx_extra(tx.extra, deregister))
{
MERROR("Transaction deregister did not have deregister data in tx extra, possibly corrupt tx in blockchain");
return false;
}
const auto state = get_quorum_state(deregister.block_height);
if (!state)
{
// TODO(worktips): Not being able to find a quorum is fatal! We want better caching abilities.
MERROR("Quorum state for height: " << deregister.block_height << ", was not stored by the daemon");
return false;
}
if (deregister.service_node_index >= state->nodes_to_test.size())
{
MERROR("Service node index to vote off has become invalid, quorum rules have changed without a hardfork.");
return false;
}
const crypto::public_key& key = state->nodes_to_test[deregister.service_node_index];
auto iter = m_transient_state.service_nodes_infos.find(key);
if (iter == m_transient_state.service_nodes_infos.end())
return false;
if (m_service_node_pubkey && *m_service_node_pubkey == key)
{
MGINFO_RED("Deregistration for service node (yours): " << key);
}
else
{
LOG_PRINT_L1("Deregistration for service node: " << key);
}
m_transient_state.rollback_events.push_back(std::unique_ptr<rollback_event>(new rollback_change(block_height, key, iter->second)));
int hard_fork_version = m_blockchain.get_hard_fork_version(block_height);
if (hard_fork_version >= cryptonote::network_version_11_infinite_staking)
{
for (const auto &contributor : iter->second.contributors)
{
for (const auto &contribution : contributor.locked_contributions)
{
key_image_blacklist_entry entry = {};
entry.key_image = contribution.key_image;
entry.unlock_height = block_height + staking_num_lock_blocks(m_blockchain.nettype());
m_transient_state.key_image_blacklist.push_back(entry);
const bool adding_to_blacklist = true;
m_transient_state.rollback_events.push_back(std::unique_ptr<rollback_event>(new rollback_key_image_blacklist(block_height, entry, adding_to_blacklist)));
}
}
}
m_transient_state.service_nodes_infos.erase(iter);
return true;
}
static uint64_t get_new_swarm_id(std::mt19937_64& mt, const std::vector<swarm_id_t>& ids)
{
uint64_t id_new = QUEUE_SWARM_ID;
while (id_new == QUEUE_SWARM_ID || ( std::find(ids.begin(), ids.end(), id_new) != ids.end() )) {
id_new = uniform_distribution_portable(mt, UINT64_MAX);
}
return id_new;
}
static std::vector<swarm_id_t> get_all_swarms(const std::map<swarm_id_t, std::vector<crypto::public_key>>& swarm_to_snodes)
{
std::vector<swarm_id_t> all_swarms;
all_swarms.reserve(swarm_to_snodes.size());
for (const auto& entry : swarm_to_snodes) {
all_swarms.push_back(entry.first);
}
return all_swarms;
}
static crypto::public_key pop_random_snode(std::mt19937_64& mt, std::vector<crypto::public_key>& vec)
{
const auto idx = uniform_distribution_portable(mt, vec.size());
const auto sn_pk = vec.at(idx);
auto it = vec.begin();
std::advance(it, idx);
vec.erase(it);
return sn_pk;
}
static void calc_swarm_changes(std::map<swarm_id_t, std::vector<crypto::public_key>>& swarm_to_snodes, uint64_t seed)
{
std::mt19937_64 mersenne_twister(seed);
std::vector<crypto::public_key> swarm_buffer = swarm_to_snodes[QUEUE_SWARM_ID];
swarm_to_snodes.erase(QUEUE_SWARM_ID);
auto all_swarms = get_all_swarms(swarm_to_snodes);
std::sort(all_swarms.begin(), all_swarms.end());
worktips_shuffle(all_swarms, seed);
const auto cmp_swarm_sizes =
[&swarm_to_snodes](swarm_id_t lhs, swarm_id_t rhs) {
return swarm_to_snodes.at(lhs).size() < swarm_to_snodes.at(rhs).size();
};
/// 1. If there are any swarms that are about to dissapear -> try to fill them first
std::vector<swarm_id_t> starving_swarms;
{
std::copy_if(all_swarms.begin(),
all_swarms.end(),
std::back_inserter(starving_swarms),
[&swarm_to_snodes](swarm_id_t id) { return swarm_to_snodes.at(id).size() < MIN_SWARM_SIZE; });
for (const auto swarm_id : starving_swarms) {
const size_t needed = MIN_SWARM_SIZE - swarm_to_snodes.at(swarm_id).size();
for (auto j = 0u; j < needed && !swarm_buffer.empty(); ++j) {
const auto sn_pk = pop_random_snode(mersenne_twister, swarm_buffer);
swarm_to_snodes.at(swarm_id).push_back(sn_pk);
}
if (swarm_buffer.empty()) break;
}
}
/// 2. Any starving swarms still left? If yes, steal nodes from larger swarms
{
bool can_continue = true; /// whether there are still large swarms to steal from
for (const auto swarm_id : starving_swarms) {
if (swarm_to_snodes.at(swarm_id).size() == MIN_SWARM_SIZE) continue;
const auto needed = MIN_SWARM_SIZE - swarm_to_snodes.at(swarm_id).size();
for (auto i = 0u; i < needed; ++i) {
const auto large_swarm =
*std::max_element(all_swarms.begin(), all_swarms.end(), cmp_swarm_sizes);
if (swarm_to_snodes.at(large_swarm).size() <= MIN_SWARM_SIZE) {
can_continue = false;
break;
}
const crypto::public_key sn_pk = pop_random_snode(mersenne_twister, swarm_to_snodes.at(large_swarm));
swarm_to_snodes.at(swarm_id).push_back(sn_pk);
}
if (!can_continue) break;
}
}
/// 3. Fill in "unsaturated" swarms (with fewer than max nodes) starting from smallest
{
while (!swarm_buffer.empty() && !all_swarms.empty()) {
const swarm_id_t smallest_swarm = *std::min_element(all_swarms.begin(), all_swarms.end(), cmp_swarm_sizes);
std::vector<crypto::public_key>& swarm = swarm_to_snodes.at(smallest_swarm);
if (swarm.size() == MAX_SWARM_SIZE) break;
const auto sn_pk = pop_random_snode(mersenne_twister, swarm_buffer);
swarm.push_back(sn_pk);
}
}
/// 4. If there are still enough nodes for MAX_SWARM_SIZE + some safety buffer, create a new swarm
while (swarm_buffer.size() >= MAX_SWARM_SIZE + SWARM_BUFFER) {
/// shuffle the queue and select MAX_SWARM_SIZE last elements
const auto new_swarm_id = get_new_swarm_id(mersenne_twister, all_swarms);
worktips_shuffle(swarm_buffer, seed + new_swarm_id);
std::vector<crypto::public_key> selected_snodes;
for (auto i = 0u; i < MAX_SWARM_SIZE; ++i) {
/// get next node from the buffer
const crypto::public_key fresh_snode = swarm_buffer.back();
swarm_buffer.pop_back();
/// Try replacing nodes in existing swarms
if (swarm_to_snodes.size() > 0) {
/// a. Select a random swarm
const uint64_t swarm_idx = uniform_distribution_portable(mersenne_twister, swarm_to_snodes.size());
auto it = swarm_to_snodes.begin();
std::advance(it, swarm_idx);
std::vector<crypto::public_key>& selected_swarm = it->second;
/// b. Select a random snode
const crypto::public_key snode = pop_random_snode(mersenne_twister, selected_swarm);
/// c. Swap that node with a node in the queue, the old node will form a new swarm
selected_snodes.push_back(snode);
selected_swarm.push_back(fresh_snode);
} else {
/// If there are no existing swarms, create the first swarm directly from the queue
selected_snodes.push_back(fresh_snode);
}
}
swarm_to_snodes.insert({new_swarm_id, std::move(selected_snodes)});
}
/// 5. If there is a swarm with less than MIN_SWARM_SIZE, decommission that swarm (should almost never happen due to the safety buffer).
for (auto entry : swarm_to_snodes) {
if (entry.second.size() < MIN_SWARM_SIZE) {
LOG_PRINT_L1("swarm " << entry.first << " is DECOMMISSIONED");
/// TODO: move data to other swarms, then put snodes back in the queue
}
}
/// 6. Put nodes from the buffer back to the "buffer agnostic" data structure
swarm_to_snodes.insert({QUEUE_SWARM_ID, std::move(swarm_buffer)});
}
void service_node_list::update_swarms(uint64_t height) {
crypto::hash hash = m_blockchain.get_block_id_by_height(height);
uint64_t seed = 0;
std::memcpy(&seed, hash.data, sizeof(seed));
/// Gather existing swarms from infos
std::map<swarm_id_t, std::vector<crypto::public_key>> existing_swarms;
for (const auto& entry : m_transient_state.service_nodes_infos) {
const auto id = entry.second.swarm_id;
existing_swarms[id].push_back(entry.first);
}
calc_swarm_changes(existing_swarms, seed);
/// Apply changes
for (const auto entry : existing_swarms) {
const swarm_id_t swarm_id = entry.first;
const std::vector<crypto::public_key>& snodes = entry.second;
for (const auto snode : snodes) {
auto& sn_info = m_transient_state.service_nodes_infos.at(snode);
if (sn_info.swarm_id == swarm_id) continue; /// nothing changed for this snode
/// modify info and record the change
m_transient_state.rollback_events.push_back(std::unique_ptr<rollback_event>(new rollback_change(height, snode, sn_info)));
sn_info.swarm_id = swarm_id;
}
}
}
static bool get_contribution(cryptonote::network_type nettype, int hard_fork_version, const cryptonote::transaction& tx, uint64_t block_height, parsed_tx_contribution &parsed_contribution)
{
if (!cryptonote::get_service_node_contributor_from_tx_extra(tx.extra, parsed_contribution.address))
return false;
if (!cryptonote::get_tx_secret_key_from_tx_extra(tx.extra, parsed_contribution.tx_key))
{
LOG_PRINT_L1("Contribution TX: There was a service node contributor but no secret key in the tx extra on height: " << block_height << " for tx: " << get_transaction_hash(tx));
return false;
}
crypto::key_derivation derivation;
if (!crypto::generate_key_derivation(parsed_contribution.address.m_view_public_key, parsed_contribution.tx_key, derivation))
{
LOG_PRINT_L1("Contribution TX: Failed to generate key derivation on height: " << block_height << " for tx: " << get_transaction_hash(tx));
return false;
}
hw::device& hwdev = hw::get_device("default");
parsed_contribution.transferred = 0;
if (hard_fork_version >= cryptonote::network_version_11_infinite_staking)
{
cryptonote::tx_extra_tx_key_image_proofs key_image_proofs;
if (!get_tx_key_image_proofs_from_tx_extra(tx.extra, key_image_proofs))
{
LOG_PRINT_L1("Contribution TX: Didn't have key image proofs in the tx_extra, rejected on height: " << block_height << " for tx: " << get_transaction_hash(tx));
return false;
}
for (size_t output_index = 0; output_index < tx.vout.size(); ++output_index)
{
uint64_t transferred = get_reg_tx_staking_output_contribution(tx, output_index, derivation, hwdev);
if (transferred == 0)
continue;
crypto::public_key ephemeral_pub_key;
{
if (!hwdev.derive_public_key(derivation, output_index, parsed_contribution.address.m_spend_public_key, ephemeral_pub_key))
{
LOG_PRINT_L1("Contribution TX: Could not derive TX ephemeral key on height: " << block_height << " for tx: " << get_transaction_hash(tx) << " for output: " << output_index);
continue;
}
const auto& out_to_key = boost::get<cryptonote::txout_to_key>(tx.vout[output_index].target);
if (out_to_key.key != ephemeral_pub_key)
{
LOG_PRINT_L1("Contribution TX: Derived TX ephemeral key did not match tx stored key on height: " << block_height << " for tx: " << get_transaction_hash(tx) << " for output: " << output_index);
continue;
}
}
crypto::public_key const *ephemeral_pub_key_ptr = &ephemeral_pub_key;
for (auto proof = key_image_proofs.proofs.begin(); proof != key_image_proofs.proofs.end(); proof++)
{
if (!crypto::check_ring_signature((const crypto::hash &)(proof->key_image), proof->key_image, &ephemeral_pub_key_ptr, 1, &proof->signature))
continue;
service_node_info::contribution_t entry = {};
entry.key_image_pub_key = ephemeral_pub_key;
entry.key_image = proof->key_image;
entry.amount = transferred;
parsed_contribution.locked_contributions.push_back(entry);
parsed_contribution.transferred += transferred;
key_image_proofs.proofs.erase(proof);
break;
}
}
}
else
{
for (size_t i = 0; i < tx.vout.size(); i++)
{
bool has_correct_unlock_time = false;
{
uint64_t unlock_time = tx.unlock_time;
if (tx.version >= cryptonote::transaction::version_3_per_output_unlock_times)
unlock_time = tx.output_unlock_times[i];
uint64_t min_height = block_height + staking_num_lock_blocks(nettype);
has_correct_unlock_time = unlock_time < CRYPTONOTE_MAX_BLOCK_NUMBER && unlock_time >= min_height;
}
if (has_correct_unlock_time)
parsed_contribution.transferred += get_reg_tx_staking_output_contribution(tx, i, derivation, hwdev);
}
}
return true;
}
bool service_node_list::is_registration_tx(const cryptonote::transaction& tx, uint64_t block_timestamp, uint64_t block_height, uint32_t index, crypto::public_key& key, service_node_info& info) const
{
crypto::public_key service_node_key;
std::vector<cryptonote::account_public_address> service_node_addresses;
std::vector<uint64_t> service_node_portions;
uint64_t portions_for_operator;
uint64_t expiration_timestamp;
crypto::signature signature;
if (!reg_tx_extract_fields(tx, service_node_addresses, portions_for_operator, service_node_portions, expiration_timestamp, service_node_key, signature))
return false;
if (service_node_portions.size() != service_node_addresses.size() || service_node_portions.empty())
{
LOG_PRINT_L1("Register TX: Extracted portions size: (" << service_node_portions.size() <<
") was empty or did not match address size: (" << service_node_addresses.size() <<
") on height: " << block_height <<
" for tx: " << cryptonote::get_transaction_hash(tx));
return false;
}
int hf_version = m_blockchain.get_hard_fork_version(block_height);
if (!check_service_node_portions(hf_version, service_node_portions)) return false;
if (portions_for_operator > STAKING_PORTIONS)
{
LOG_PRINT_L1("Register TX: Operator portions: " << portions_for_operator <<
" exceeded staking portions: " << STAKING_PORTIONS <<
" on height: " << block_height <<
" for tx: " << cryptonote::get_transaction_hash(tx));
return false;
}
// check the signature is all good
crypto::hash hash;
if (!get_registration_hash(service_node_addresses, portions_for_operator, service_node_portions, expiration_timestamp, hash))
{
LOG_PRINT_L1("Register TX: Failed to extract registration hash, on height: " << block_height << " for tx: " << cryptonote::get_transaction_hash(tx));
return false;
}
if (!crypto::check_key(service_node_key) || !crypto::check_signature(hash, service_node_key, signature))
{
LOG_PRINT_L1("Register TX: Has invalid key and/or signature, on height: " << block_height << " for tx: " << cryptonote::get_transaction_hash(tx));
return false;
}
if (expiration_timestamp < block_timestamp)
{
LOG_PRINT_L1("Register TX: Has expired. The block timestamp: " << block_timestamp <<
" is greater than the expiration timestamp: " << expiration_timestamp <<
" on height: " << block_height <<
" for tx:" << cryptonote::get_transaction_hash(tx));
return false;
}
// check the initial contribution exists
info.staking_requirement = get_staking_requirement(m_blockchain.nettype(), block_height, hf_version);
cryptonote::account_public_address address;
parsed_tx_contribution parsed_contribution = {};
if (!get_contribution(m_blockchain.nettype(), hf_version, tx, block_height, parsed_contribution))
{
LOG_PRINT_L1("Register TX: Had service node registration fields, but could not decode contribution on height: " << block_height << " for tx: " << cryptonote::get_transaction_hash(tx));
return false;
}
const uint64_t min_transfer = get_min_node_contribution(hf_version, info.staking_requirement, info.total_reserved, info.total_num_locked_contributions());
if (parsed_contribution.transferred < min_transfer)
{
LOG_PRINT_L1("Register TX: Contribution transferred: " << parsed_contribution.transferred << " didn't meet the minimum transfer requirement: " << min_transfer << " on height: " << block_height << " for tx: " << cryptonote::get_transaction_hash(tx));
return false;
}
size_t total_num_of_addr = service_node_addresses.size();
if (std::find(service_node_addresses.begin(), service_node_addresses.end(), parsed_contribution.address) == service_node_addresses.end())
total_num_of_addr++;
if (total_num_of_addr > MAX_NUMBER_OF_CONTRIBUTORS)
{
LOG_PRINT_L1("Register TX: Number of participants: " << total_num_of_addr <<
" exceeded the max number of contributors: " << MAX_NUMBER_OF_CONTRIBUTORS <<
" on height: " << block_height <<
" for tx: " << cryptonote::get_transaction_hash(tx));
return false;
}
// don't actually process this contribution now, do it when we fall through later.
key = service_node_key;
info.operator_address = service_node_addresses[0];
info.portions_for_operator = portions_for_operator;
info.registration_height = block_height;
info.last_reward_block_height = block_height;
info.last_reward_transaction_index = index;
info.total_contributed = 0;
info.total_reserved = 0;
info.version = get_min_service_node_info_version_for_hf(hf_version);
if (info.version >= service_node_info::version_1_swarms)
info.swarm_id = QUEUE_SWARM_ID; /// new nodes go into a "queue swarm"
info.contributors.clear();
for (size_t i = 0; i < service_node_addresses.size(); i++)
{
// Check for duplicates
auto iter = std::find(service_node_addresses.begin(), service_node_addresses.begin() + i, service_node_addresses[i]);
if (iter != service_node_addresses.begin() + i)
{
LOG_PRINT_L1("Register TX: There was a duplicate participant for service node on height: " << block_height << " for tx: " << cryptonote::get_transaction_hash(tx));
return false;
}
uint64_t hi, lo, resulthi, resultlo;
lo = mul128(info.staking_requirement, service_node_portions[i], &hi);
div128_64(hi, lo, STAKING_PORTIONS, &resulthi, &resultlo);
service_node_info::contributor_t contributor = {};
contributor.version = get_min_service_node_info_version_for_hf(hf_version);
contributor.reserved = resultlo;
contributor.address = service_node_addresses[i];
info.contributors.push_back(contributor);
info.total_reserved += resultlo;
}
return true;
}
bool service_node_list::process_registration_tx(const cryptonote::transaction& tx, uint64_t block_timestamp, uint64_t block_height, uint32_t index)
{
crypto::public_key key;
service_node_info info = {};
if (!is_registration_tx(tx, block_timestamp, block_height, index, key, info))
return false;
int hard_fork_version = m_blockchain.get_hard_fork_version(block_height);
if (hard_fork_version >= cryptonote::network_version_11_infinite_staking)
{
// NOTE(worktips): Grace period is not used anymore with infinite staking. So, if someone somehow reregisters, we just ignore it
const auto iter = m_transient_state.service_nodes_infos.find(key);
if (iter != m_transient_state.service_nodes_infos.end())
return false;
if (m_service_node_pubkey && *m_service_node_pubkey == key) MGINFO_GREEN("Service node registered (yours): " << key << " on height: " << block_height);
else LOG_PRINT_L1("New service node registered: " << key << " on height: " << block_height);
}
else
{
// NOTE: A node doesn't expire until registration_height + lock blocks excess now which acts as the grace period
// So it is possible to find the node still in our list.
bool registered_during_grace_period = false;
const auto iter = m_transient_state.service_nodes_infos.find(key);
if (iter != m_transient_state.service_nodes_infos.end())
{
if (hard_fork_version >= cryptonote::network_version_10_bulletproofs)
{
service_node_info const &old_info = iter->second;
uint64_t expiry_height = old_info.registration_height + staking_num_lock_blocks(m_blockchain.nettype());
if (block_height < expiry_height)
return false;
// NOTE: Node preserves its position in list if it reregisters during grace period.
registered_during_grace_period = true;
info.last_reward_block_height = old_info.last_reward_block_height;
info.last_reward_transaction_index = old_info.last_reward_transaction_index;
}
else
{
return false;
}
}
if (m_service_node_pubkey && *m_service_node_pubkey == key)
{
if (registered_during_grace_period)
{
MGINFO_GREEN("Service node re-registered (yours): " << key << " at block height: " << block_height);
}
else
{
MGINFO_GREEN("Service node registered (yours): " << key << " at block height: " << block_height);
}
}
else
{
LOG_PRINT_L1("New service node registered: " << key << " at block height: " << block_height);
}
}
m_transient_state.rollback_events.push_back(std::unique_ptr<rollback_event>(new rollback_new(block_height, key)));
m_transient_state.service_nodes_infos[key] = info;
return true;
}
void service_node_list::process_contribution_tx(const cryptonote::transaction& tx, uint64_t block_height, uint32_t index)
{
crypto::public_key pubkey;
if (!cryptonote::get_service_node_pubkey_from_tx_extra(tx.extra, pubkey))
return; // Is not a contribution TX don't need to check it.
parsed_tx_contribution parsed_contribution = {};
const int hf_version = m_blockchain.get_hard_fork_version(block_height);
if (!get_contribution(m_blockchain.nettype(), hf_version, tx, block_height, parsed_contribution))
{
LOG_PRINT_L1("Contribution TX: Could not decode contribution for service node: " << pubkey << " on height: " << block_height << " for tx: " << cryptonote::get_transaction_hash(tx));
return;
}
/// Service node must be registered
auto iter = m_transient_state.service_nodes_infos.find(pubkey);
if (iter == m_transient_state.service_nodes_infos.end())
{
LOG_PRINT_L1("Contribution TX: Contribution received for service node: " << pubkey <<
", but could not be found in the service node list on height: " << block_height <<
" for tx: " << cryptonote::get_transaction_hash(tx )<< "\n"
"This could mean that the service node was deregistered before the contribution was processed.");
return;
}
service_node_info& info = iter->second;
if (info.is_fully_funded())
{
LOG_PRINT_L1("Contribution TX: Service node: " << pubkey <<
" is already fully funded, but contribution received on height: " << block_height <<
" for tx: " << cryptonote::get_transaction_hash(tx));
return;
}
if (!cryptonote::get_tx_secret_key_from_tx_extra(tx.extra, parsed_contribution.tx_key))
{
LOG_PRINT_L1("Contribution TX: Failed to get tx secret key from contribution received on height: " << block_height << " for tx: " << cryptonote::get_transaction_hash(tx));
return;
}
auto& contributors = info.contributors;
auto contrib_iter = std::find_if(contributors.begin(), contributors.end(),
[&parsed_contribution](const service_node_info::contributor_t& contributor) { return contributor.address == parsed_contribution.address; });
const bool new_contributor = (contrib_iter == contributors.end());
if (new_contributor)
{
if (contributors.size() >= MAX_NUMBER_OF_CONTRIBUTORS)
{
LOG_PRINT_L1("Contribution TX: Node is full with max contributors: " << MAX_NUMBER_OF_CONTRIBUTORS <<
" for service node: " << pubkey <<
" on height: " << block_height <<
" for tx: " << cryptonote::get_transaction_hash(tx));
return;
}
/// Check that the contribution is large enough
const uint8_t hf_version = m_blockchain.get_hard_fork_version(block_height);
const uint64_t min_contribution = get_min_node_contribution(hf_version, info.staking_requirement, info.total_reserved, info.total_num_locked_contributions());
if (parsed_contribution.transferred < min_contribution)
{
LOG_PRINT_L1("Contribution TX: Amount " << parsed_contribution.transferred <<
" did not meet min " << min_contribution <<
" for service node: " << pubkey <<
" on height: " << block_height <<
" for tx: " << cryptonote::get_transaction_hash(tx));
return;
}
}
//
// Successfully Validated
//
m_transient_state.rollback_events.push_back(std::unique_ptr<rollback_event>(new rollback_change(block_height, pubkey, info)));
if (new_contributor)
{
service_node_info::contributor_t new_contributor = {};
new_contributor.version = get_min_service_node_info_version_for_hf(hf_version);
new_contributor.address = parsed_contribution.address;
info.contributors.push_back(new_contributor);
contrib_iter = --contributors.end();
}
service_node_info::contributor_t& contributor = *contrib_iter;
// In this action, we cannot
// increase total_reserved so much that it is >= staking_requirement
uint64_t can_increase_reserved_by = info.staking_requirement - info.total_reserved;
uint64_t max_amount = contributor.reserved + can_increase_reserved_by;
parsed_contribution.transferred = std::min(max_amount - contributor.amount, parsed_contribution.transferred);
contributor.amount += parsed_contribution.transferred;
info.total_contributed += parsed_contribution.transferred;
if (contributor.amount > contributor.reserved)
{
info.total_reserved += contributor.amount - contributor.reserved;
contributor.reserved = contributor.amount;
}
info.last_reward_block_height = block_height;
info.last_reward_transaction_index = index;
const size_t max_contributions_per_node = service_nodes::MAX_KEY_IMAGES_PER_CONTRIBUTOR * MAX_NUMBER_OF_CONTRIBUTORS;
if (hf_version >= cryptonote::network_version_11_infinite_staking)
{
std::vector<service_node_info::contribution_t> &locked_contributions = contributor.locked_contributions;
for (const service_node_info::contribution_t &contribution : parsed_contribution.locked_contributions)
{
if (info.total_num_locked_contributions() < max_contributions_per_node)
contributor.locked_contributions.push_back(contribution);
else
{
LOG_PRINT_L1("Contribution TX: Already hit the max number of contributions: " << max_contributions_per_node <<
" for contributor: " << cryptonote::get_account_address_as_str(m_blockchain.nettype(), false, contributor.address) <<
" on height: " << block_height <<
" for tx: " << cryptonote::get_transaction_hash(tx));
break;
}
}
}
LOG_PRINT_L1("Contribution of " << parsed_contribution.transferred << " received for service node " << pubkey);
}
void service_node_list::block_added(const cryptonote::block& block, const std::vector<cryptonote::transaction>& txs)