-
Notifications
You must be signed in to change notification settings - Fork 95
/
Copy pathservicenode_tests.cpp
1731 lines (1564 loc) · 90 KB
/
servicenode_tests.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) 2019-2020 The Blocknet developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <test/staking_tests.h>
#include <node/transaction.h>
#include <rpc/server.h>
#include <servicenode/servicenode.h>
#define protected public
#include <servicenode/servicenodemgr.h>
#undef protected
#include <wallet/coincontrol.h>
#include <xbridge/xbridgeapp.h>
sn::ServiceNode snodeNetwork(const CPubKey & snodePubKey, const uint8_t & tier, const CKeyID & paymentAddr,
const std::vector<COutPoint> & collateral, const uint32_t & blockNumber,
const uint256 & blockHash, const std::vector<unsigned char> & sig)
{
auto ss = CDataStream(SER_NETWORK, PROTOCOL_VERSION);
ss << snodePubKey << tier << paymentAddr << collateral << blockNumber << blockHash << sig;
sn::ServiceNode snode; ss >> snode;
return snode;
}
/**
* Save configuration files to the specified path.
*/
void saveFile(const boost::filesystem::path& p, const std::string& str) {
boost::filesystem::ofstream file;
file.exceptions(std::ofstream::failbit | std::ofstream::badbit);
file.open(p, std::ios_base::binary);
file.write(str.c_str(), str.size());
}
void cleanupSn() {
sn::ServiceNodeMgr::writeSnConfig(std::vector<sn::ServiceNodeConfigEntry>(), false); // reset
sn::ServiceNodeMgr::instance().reset();
mempool.clear();
}
bool ServiceNodeSetupFixtureSetup{false};
struct ServiceNodeSetupFixture {
explicit ServiceNodeSetupFixture() {
if (ServiceNodeSetupFixtureSetup) return; ServiceNodeSetupFixtureSetup = true;
chain_1000_50();
chain_1250_50();
}
void chain_1000_50() {
auto pos = std::make_shared<TestChainPoS>(false);
auto *params = (CChainParams*)&Params();
params->consensus.GetBlockSubsidy = [](const int & blockHeight, const Consensus::Params & consensusParams) {
if (blockHeight <= consensusParams.lastPOWBlock)
return 1000 * COIN;
return 50 * COIN;
};
pos->Init("1000,50");
pos.reset();
}
void chain_1250_50() {
auto pos = std::make_shared<TestChainPoS>(false);
auto *params = (CChainParams*)&Params();
params->consensus.GetBlockSubsidy = [](const int & blockHeight, const Consensus::Params & consensusParams) {
if (blockHeight <= consensusParams.lastPOWBlock)
return 1250 * COIN;
return 50 * COIN;
};
pos->Init("1250,50");
pos.reset();
}
};
BOOST_FIXTURE_TEST_SUITE(servicenode_tests, ServiceNodeSetupFixture)
/// Check case where servicenode is properly validated under normal circumstances
BOOST_AUTO_TEST_CASE(servicenode_tests_isvalid)
{
auto pos_ptr = std::make_shared<TestChainPoS>(false);
auto & pos = *pos_ptr;
auto *params = (CChainParams*)&Params();
params->consensus.GetBlockSubsidy = [](const int & blockHeight, const Consensus::Params & consensusParams) {
if (blockHeight <= consensusParams.lastPOWBlock)
return 1000 * COIN;
return 50 * COIN;
};
pos.Init("1000,50");
const auto snodePubKey = pos.coinbaseKey.GetPubKey();
const auto tier = sn::ServiceNode::Tier::SPV;
CAmount totalAmount{0};
std::vector<COutPoint> collateral;
for (const auto & tx : pos.m_coinbase_txns) {
CTransactionRef txx;
if (!GetTxFunc({tx->GetHash(), 0}, txx)) // make sure tx exists
continue;
totalAmount += tx->vout[0].nValue;
collateral.emplace_back(tx->GetHash(), 0);
if (totalAmount >= sn::ServiceNode::COLLATERAL_SPV)
break;
}
// Generate the signature from sig hash
const auto & sighash = sn::ServiceNode::CreateSigHash(snodePubKey, tier, snodePubKey.GetID(), collateral, chainActive.Height(), chainActive.Tip()->GetBlockHash());
std::vector<unsigned char> sig;
BOOST_CHECK(pos.coinbaseKey.SignCompact(sighash, sig));
// Deserialize servicenode obj from network stream
sn::ServiceNode snode;
BOOST_CHECK_NO_THROW(snode = snodeNetwork(snodePubKey, tier, snodePubKey.GetID(), collateral, chainActive.Height(), chainActive.Tip()->GetBlockHash(), sig));
BOOST_CHECK(snode.isValid(GetTxFunc, IsServiceNodeBlockValidFunc));
cleanupSn();
pos_ptr.reset();
}
/// Check open tier case
BOOST_FIXTURE_TEST_CASE(servicenode_tests_opentier, TestChainPoS)
{
CKey key; key.MakeNewKey(true);
const auto snodePubKey = key.GetPubKey();
const auto tier = sn::ServiceNode::Tier::OPEN;
const auto collateral = std::vector<COutPoint>();
// Valid check
{
// Generate the signature from sig hash
const auto & sighash = sn::ServiceNode::CreateSigHash(snodePubKey, tier, snodePubKey.GetID(), collateral, chainActive.Height(), chainActive.Tip()->GetBlockHash());
std::vector<unsigned char> sig;
BOOST_CHECK(key.SignCompact(sighash, sig));
// Deserialize servicenode obj from network stream
sn::ServiceNode snode;
BOOST_CHECK_NO_THROW(snode = snodeNetwork(snodePubKey, tier, snodePubKey.GetID(), collateral, chainActive.Height(), chainActive.Tip()->GetBlockHash(), sig));
// TODO Blocknet OPEN tier snodes, support non-SPV snode tiers (invert the isValid check below)
BOOST_CHECK_MESSAGE(!snode.isValid(GetTxFunc, IsServiceNodeBlockValidFunc), "OPEN tier should not be supported at this time");
}
// Case where wrong key is used to generate sig. For the open tier the snode private key
// must be used to generate the signature. In this test we use another key.
{
// Generate the signature from sig hash
const auto & sighash = sn::ServiceNode::CreateSigHash(snodePubKey, tier, snodePubKey.GetID(), collateral, chainActive.Height(), chainActive.Tip()->GetBlockHash());
std::vector<unsigned char> sig;
BOOST_CHECK(coinbaseKey.SignCompact(sighash, sig)); // use invalid coinbase key (invalid for open tier)
// Deserialize servicenode obj from network stream
sn::ServiceNode snode;
BOOST_CHECK_NO_THROW(snode = snodeNetwork(snodePubKey, tier, snodePubKey.GetID(), collateral, chainActive.Height(), chainActive.Tip()->GetBlockHash(), sig));
BOOST_CHECK_MESSAGE(!snode.isValid(GetTxFunc, IsServiceNodeBlockValidFunc), "Failed on invalid snode key sig");
}
cleanupSn();
}
/// Check case where duplicate collateral utxos are used
BOOST_FIXTURE_TEST_CASE(servicenode_tests_duplicate_collateral, TestChainPoS)
{
CKey key; key.MakeNewKey(true);
const auto snodePubKey = key.GetPubKey();
const auto tier = sn::ServiceNode::Tier::SPV;
// Assumes total input amounts below adds up to ServiceNode::COLLATERAL_SPV
CAmount totalAmount{0};
std::vector<COutPoint> collateral;
while (totalAmount < sn::ServiceNode::COLLATERAL_SPV) {
collateral.emplace_back(m_coinbase_txns[0]->GetHash(), 0);
totalAmount += m_coinbase_txns[0]->GetValueOut();
}
// Generate the signature from sig hash
const auto & sighash = sn::ServiceNode::CreateSigHash(snodePubKey, tier, snodePubKey.GetID(), collateral, chainActive.Height(), chainActive.Tip()->GetBlockHash());
std::vector<unsigned char> sig;
BOOST_CHECK(coinbaseKey.SignCompact(sighash, sig));
// Deserialize servicenode obj from network stream
sn::ServiceNode snode;
BOOST_CHECK_NO_THROW(snode = snodeNetwork(snodePubKey, tier, snodePubKey.GetID(), collateral, chainActive.Height(), chainActive.Tip()->GetBlockHash(), sig));
BOOST_CHECK(!snode.isValid(GetTxFunc, IsServiceNodeBlockValidFunc));
cleanupSn();
}
/// Check case where there's not enough snode inputs
BOOST_FIXTURE_TEST_CASE(servicenode_tests_insufficient_collateral, TestChainPoS)
{
CKey key; key.MakeNewKey(true);
const auto snodePubKey = key.GetPubKey();
const auto tier = sn::ServiceNode::Tier::SPV;
// Assumes total input amounts below adds up to ServiceNode::COLLATERAL_SPV
std::vector<COutPoint> collateral;
collateral.emplace_back(m_coinbase_txns[0]->GetHash(), 0);
BOOST_CHECK(m_coinbase_txns[0]->GetValueOut() < sn::ServiceNode::COLLATERAL_SPV);
// Generate the signature from sig hash
const auto & sighash = sn::ServiceNode::CreateSigHash(snodePubKey, tier, snodePubKey.GetID(), collateral, chainActive.Height(), chainActive.Tip()->GetBlockHash());
std::vector<unsigned char> sig;
BOOST_CHECK(coinbaseKey.SignCompact(sighash, sig));
// Deserialize servicenode obj from network stream
sn::ServiceNode snode;
BOOST_CHECK_NO_THROW(snode = snodeNetwork(snodePubKey, tier, snodePubKey.GetID(), collateral, chainActive.Height(), chainActive.Tip()->GetBlockHash(), sig));
BOOST_CHECK(!snode.isValid(GetTxFunc, IsServiceNodeBlockValidFunc));
cleanupSn();
}
/// Check case where collateral inputs are spent
BOOST_AUTO_TEST_CASE(servicenode_tests_spent_collateral)
{
auto pos_ptr = std::make_shared<TestChainPoS>(false);
auto & pos = *pos_ptr;
auto *params = (CChainParams*)&Params();
params->consensus.GetBlockSubsidy = [](const int & blockHeight, const Consensus::Params & consensusParams) {
if (blockHeight <= consensusParams.lastPOWBlock)
return 1000 * COIN;
return 50 * COIN;
};
pos.Init("1000,50");
pos.StakeBlocks(5), SyncWithValidationInterfaceQueue();
CKey key; key.MakeNewKey(true);
const auto snodePubKey = key.GetPubKey();
const auto tier = sn::ServiceNode::Tier::SPV;
CBasicKeyStore keystore; // temp used to spend inputs
keystore.AddKey(pos.coinbaseKey);
// Spend inputs that would be used in snode collateral
{
std::vector<COutput> coins;
{
LOCK2(cs_main, pos.wallet->cs_wallet);
pos.wallet->AvailableCoins(*pos.locked_chain, coins, true, nullptr, 500 * COIN);
}
// Spend the first available input in "coins"
auto c = coins[0];
CMutableTransaction mtx;
mtx.vin.resize(1);
mtx.vin[0] = CTxIn(c.GetInputCoin().outpoint);
mtx.vout.resize(1);
mtx.vout[0].scriptPubKey = GetScriptForRawPubKey(snodePubKey);
mtx.vout[0].nValue = c.GetInputCoin().txout.nValue - CENT;
SignatureData sigdata = DataFromTransaction(mtx, 0, c.GetInputCoin().txout);
ProduceSignature(keystore, MutableTransactionSignatureCreator(&mtx, 0, c.GetInputCoin().txout.nValue, SIGHASH_ALL), c.GetInputCoin().txout.scriptPubKey, sigdata);
UpdateInput(mtx.vin[0], sigdata);
// Send transaction
uint256 txid; std::string errstr;
const TransactionError err = BroadcastTransaction(MakeTransactionRef(mtx), txid, errstr, 0);
BOOST_CHECK_MESSAGE(err == TransactionError::OK, strprintf("Failed to send snode collateral spent tx: %s", errstr));
pos.StakeBlocks(1), SyncWithValidationInterfaceQueue();
CBlock block;
BOOST_CHECK(ReadBlockFromDisk(block, chainActive.Tip(), params->GetConsensus()));
BOOST_CHECK_MESSAGE(block.vtx.size() >= 3 && block.vtx[2]->GetHash() == mtx.GetHash(), "Expected transaction to be included in latest block");
Coin cn;
BOOST_CHECK_MESSAGE(!pcoinsTip->GetCoin(c.GetInputCoin().outpoint, cn), "Coin should be spent here");
CAmount totalAmount{0};
std::vector<COutPoint> collateral;
for (int i = 0; i < coins.size(); ++i) {
const auto & coin = coins[i];
const auto txn = coin.tx->tx;
totalAmount += coin.GetInputCoin().txout.nValue;
collateral.emplace_back(txn->GetHash(), coin.i);
if (totalAmount >= sn::ServiceNode::COLLATERAL_SPV)
break;
}
// Generate the signature from sig hash
const auto & sighash = sn::ServiceNode::CreateSigHash(snodePubKey, tier, snodePubKey.GetID(), collateral, chainActive.Height(), chainActive.Tip()->GetBlockHash());
std::vector<unsigned char> sig;
BOOST_CHECK(pos.coinbaseKey.SignCompact(sighash, sig));
// Deserialize servicenode obj from network stream
sn::ServiceNode snode;
BOOST_CHECK_NO_THROW(snode = snodeNetwork(snodePubKey, tier, snodePubKey.GetID(), collateral, chainActive.Height(), chainActive.Tip()->GetBlockHash(), sig));
BOOST_CHECK_MESSAGE(!snode.isValid(GetTxFunc, IsServiceNodeBlockValidFunc), "Should fail on spent collateral");
cleanupSn();
}
// Check case where spent collateral is in mempool
{
std::vector<COutput> coins;
{
LOCK2(cs_main, pos.wallet->cs_wallet);
pos.wallet->AvailableCoins(*pos.locked_chain, coins, true, nullptr, 500 * COIN);
}
// Spend one of the collateral inputs (spend the 2nd coinbase input, b/c first was spent above)
COutput c = coins[0];
CMutableTransaction mtx;
mtx.vin.resize(1);
mtx.vin[0] = CTxIn(c.GetInputCoin().outpoint);
mtx.vout.resize(1);
mtx.vout[0].scriptPubKey = GetScriptForRawPubKey(snodePubKey);
mtx.vout[0].nValue = c.GetInputCoin().txout.nValue - CENT;
SignatureData sigdata = DataFromTransaction(mtx, 0, c.GetInputCoin().txout);
ProduceSignature(keystore, MutableTransactionSignatureCreator(&mtx, 0, c.GetInputCoin().txout.nValue, SIGHASH_ALL), c.GetInputCoin().txout.scriptPubKey, sigdata);
UpdateInput(mtx.vin[0], sigdata);
{
CValidationState state;
LOCK(cs_main);
BOOST_CHECK(AcceptToMemoryPool(mempool, state, MakeTransactionRef(mtx), nullptr, nullptr, false, 0));
}
CAmount totalAmount{0};
std::vector<COutPoint> collateral;
for (int i = 0; i < coins.size(); ++i) { // start at 1 (ignore first spent coinbase)
const auto & coin = coins[i];
const auto txn = coin.tx->tx;
totalAmount += coin.GetInputCoin().txout.nValue;
collateral.emplace_back(txn->GetHash(), coin.i);
if (totalAmount >= sn::ServiceNode::COLLATERAL_SPV)
break;
}
// Generate the signature from sig hash
const auto & sighash = sn::ServiceNode::CreateSigHash(snodePubKey, tier, snodePubKey.GetID(), collateral, chainActive.Height(), chainActive.Tip()->GetBlockHash());
std::vector<unsigned char> sig;
BOOST_CHECK(pos.coinbaseKey.SignCompact(sighash, sig));
// Deserialize servicenode obj from network stream
sn::ServiceNode snode;
BOOST_CHECK_NO_THROW(snode = snodeNetwork(snodePubKey, tier, snodePubKey.GetID(), collateral, chainActive.Height(), chainActive.Tip()->GetBlockHash(), sig));
BOOST_CHECK_MESSAGE(snode.isValid(GetTxFunc, IsServiceNodeBlockValidFunc), "Should not fail on spent collateral in mempool");
cleanupSn();
}
// Servicenode should be marked invalid if collateral is spent
{
std::vector<COutput> coins;
{
LOCK2(cs_main, pos.wallet->cs_wallet);
pos.wallet->AvailableCoins(*pos.locked_chain, coins, true, nullptr, 500 * COIN);
}
CAmount totalAmount{0};
std::vector<COutPoint> collateral;
for (int i = 1; i < coins.size(); ++i) { // start at 1 (ignore first spent coinbase)
const auto & coin = coins[i];
const auto txn = coin.tx->tx;
totalAmount += coin.GetInputCoin().txout.nValue;
collateral.emplace_back(txn->GetHash(), coin.i);
if (totalAmount >= sn::ServiceNode::COLLATERAL_SPV)
break;
}
// Generate the signature from sig hash
const auto & sighash = sn::ServiceNode::CreateSigHash(snodePubKey, tier, snodePubKey.GetID(), collateral, chainActive.Height(), chainActive.Tip()->GetBlockHash());
std::vector<unsigned char> sig;
BOOST_CHECK(pos.coinbaseKey.SignCompact(sighash, sig));
// Deserialize servicenode obj from network stream
sn::ServiceNode s;
BOOST_CHECK_NO_THROW(s = snodeNetwork(snodePubKey, tier, snodePubKey.GetID(), collateral, chainActive.Height(), chainActive.Tip()->GetBlockHash(), sig));
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << s;
sn::ServiceNode s2;
auto success = sn::ServiceNodeMgr::instance().processRegistration(ss, s2);
BOOST_CHECK_MESSAGE(success, "snode registration should succeed");
const auto snode = sn::ServiceNodeMgr::instance().getSn(snodePubKey);
BOOST_CHECK_MESSAGE(!snode.isNull(), "snode registration should succeed");
if (!snode.isNull()) {
RegisterValidationInterface(&sn::ServiceNodeMgr::instance());
const auto firstUtxo = snode.getCollateral().front();
CTransactionRef tx; uint256 hashBlock;
BOOST_CHECK_MESSAGE(GetTransaction(firstUtxo.hash, tx, Params().GetConsensus(), hashBlock), "failed to get snode collateral");
CMutableTransaction mtx;
mtx.vin.resize(1); mtx.vout.resize(1);
mtx.vin[0] = CTxIn(firstUtxo);
mtx.vout[0] = CTxOut(tx->vout[firstUtxo.n].nValue - CENT, tx->vout[firstUtxo.n].scriptPubKey);
SignatureData sigdata = DataFromTransaction(mtx, 0, tx->vout[firstUtxo.n]);
ProduceSignature(*pos.wallet, MutableTransactionSignatureCreator(&mtx, 0, tx->vout[firstUtxo.n].nValue, SIGHASH_ALL), tx->vout[firstUtxo.n].scriptPubKey, sigdata);
UpdateInput(mtx.vin[0], sigdata);
// Send transaction
uint256 txid; std::string errstr; const TransactionError err = BroadcastTransaction(MakeTransactionRef(mtx), txid, errstr, 0);
BOOST_CHECK_MESSAGE(err == TransactionError::OK, strprintf("Failed to spend snode collateral: %s", errstr));
pos.StakeBlocks(1), SyncWithValidationInterfaceQueue();
const auto checkSnode = sn::ServiceNodeMgr::instance().getSn(snodePubKey);
BOOST_CHECK_MESSAGE(checkSnode.isValid(GetTxFunc, IsServiceNodeBlockValidFunc), "snode should be valid because collateral was spent but we're still in grace period");
BOOST_CHECK_MESSAGE(checkSnode.getInvalid(), "snode should be marked invalid in the validation interface event (connect block)");
BOOST_CHECK_MESSAGE(checkSnode.getInvalidBlockNumber() == chainActive.Height(), "snode invalid block number should match chain tip");
pos.StakeBlocks(sn::ServiceNode::VALID_GRACEPERIOD_BLOCKS), SyncWithValidationInterfaceQueue(); // make sure snode grace period expires
BOOST_CHECK_MESSAGE(!checkSnode.isValid(GetTxFunc, IsServiceNodeBlockValidFunc), "snode should be invalid because collateral was spent and grace period expired");
UnregisterValidationInterface(&sn::ServiceNodeMgr::instance());
}
cleanupSn();
}
pos_ptr.reset();
}
/// Check case where servicenode is re-registered on spent collateral
BOOST_AUTO_TEST_CASE(servicenode_tests_reregister_onspend)
{
gArgs.SoftSetBoolArg("-servicenode", true);
auto pos_ptr = std::make_shared<TestChainPoS>(false);
auto & pos = *pos_ptr;
auto *params = (CChainParams*)&Params();
params->consensus.GetBlockSubsidy = [](const int & blockHeight, const Consensus::Params & consensusParams) {
if (blockHeight <= consensusParams.lastPOWBlock)
return 1000 * COIN;
return 50 * COIN;
};
params->consensus.coinMaturity = 10;
pos.Init("1000,50");
sn::ServiceNodeMgr::instance().reset();
RegisterValidationInterface(&sn::ServiceNodeMgr::instance());
CKey key; key.MakeNewKey(true);
const auto saddr = GetDestinationForKey(key.GetPubKey(), OutputType::LEGACY);
bool firstRun;
auto otherwallet = std::make_shared<CWallet>(*pos.chain, WalletLocation(), WalletDatabase::CreateMock());
otherwallet->LoadWallet(firstRun);
otherwallet->SetBroadcastTransactions(true);
AddKey(*otherwallet, key);
AddWallet(otherwallet); // add wallet to global mgr
RegisterValidationInterface(otherwallet.get());
CBasicKeyStore keystore; // temp used to spend inputs
keystore.AddKey(key);
keystore.AddKey(pos.coinbaseKey);
// Check that snode registration automatically happens after spent utxo detected
{
std::vector<COutput> coins;
{
LOCK2(cs_main, pos.wallet->cs_wallet);
pos.wallet->AvailableCoins(*pos.locked_chain, coins, true, nullptr, 1000 * COIN);
}
std::vector<COutPoint> collateral;
CAmount collateralTotal{0};
for (auto & c : coins) {
if (collateralTotal >= sn::ServiceNode::COLLATERAL_SPV)
break;
CMutableTransaction mtx;
mtx.vin.resize(1);
mtx.vin[0] = CTxIn(c.GetInputCoin().outpoint);
mtx.vout.resize(1);
mtx.vout[0].scriptPubKey = GetScriptForDestination(saddr);
mtx.vout[0].nValue = c.GetInputCoin().txout.nValue - CENT;
SignatureData sigdata = DataFromTransaction(mtx, 0, c.GetInputCoin().txout);
ProduceSignature(keystore, MutableTransactionSignatureCreator(&mtx, 0, c.GetInputCoin().txout.nValue, SIGHASH_ALL), c.GetInputCoin().txout.scriptPubKey, sigdata);
UpdateInput(mtx.vin[0], sigdata);
// Send transaction
uint256 txid; std::string errstr;
const TransactionError err = BroadcastTransaction(MakeTransactionRef(mtx), txid, errstr, 0);
BOOST_REQUIRE_MESSAGE(err == TransactionError::OK, strprintf("Failed to send snode collateral tx: %s", errstr));
collateral.emplace_back(mtx.GetHash(), 0);
collateralTotal += mtx.vout[0].nValue;
}
pos.StakeBlocks(params->GetConsensus().coinMaturity), SyncWithValidationInterfaceQueue();
rescanWallet(otherwallet.get());
// Setup snode
UniValue rpcparams = UniValue(UniValue::VARR);
rpcparams.push_backV({ EncodeDestination(saddr), "snode0" });
UniValue entry;
BOOST_CHECK_NO_THROW(entry = CallRPC2("servicenodesetup", rpcparams));
BOOST_CHECK_MESSAGE(entry.isObject(), "Service node entry expected");
rpcparams = UniValue(UniValue::VARR);
BOOST_CHECK_NO_THROW(CallRPC2("servicenoderegister", rpcparams));
const auto snodeEntry = sn::ServiceNodeMgr::instance().getActiveSn();
const auto snode = sn::ServiceNodeMgr::instance().getSn(snodeEntry.key.GetPubKey());
// Find collateral that is spendable
COutPoint selUtxo;
for (const auto & col : snode.getCollateral()) {
LOCK(cs_main);
Coin c;
if (pcoinsTip->GetCoin(col, c) && c.nHeight >= params->GetConsensus().coinMaturity) {
selUtxo = col;
break;
}
}
BOOST_REQUIRE_MESSAGE(!selUtxo.IsNull(), "Failed to find collateral utxo");
// Spend one of the collateral utxos
CTransactionRef tx; uint256 hashBlock;
BOOST_CHECK_MESSAGE(GetTransaction(selUtxo.hash, tx, Params().GetConsensus(), hashBlock), "failed to get snode collateral");
CMutableTransaction mtx;
mtx.vin.resize(1); mtx.vout.resize(1);
mtx.vin[0] = CTxIn(selUtxo);
mtx.vout[0] = CTxOut(tx->vout[selUtxo.n].nValue - CENT, tx->vout[selUtxo.n].scriptPubKey);
SignatureData sigdata = DataFromTransaction(mtx, 0, tx->vout[selUtxo.n]);
ProduceSignature(keystore, MutableTransactionSignatureCreator(&mtx, 0, tx->vout[selUtxo.n].nValue, SIGHASH_ALL), tx->vout[selUtxo.n].scriptPubKey, sigdata);
UpdateInput(mtx.vin[0], sigdata);
uint256 txid; std::string errstr; const TransactionError err = BroadcastTransaction(MakeTransactionRef(mtx), txid, errstr, 0);
BOOST_CHECK_MESSAGE(err == TransactionError::OK, strprintf("Failed to spend snode collateral: %s", errstr));
pos.StakeBlocks(2), SyncWithValidationInterfaceQueue();
const auto checkSnode = sn::ServiceNodeMgr::instance().getSn(snodeEntry.key.GetPubKey());
BOOST_CHECK_MESSAGE(checkSnode.isValid(GetTxFunc, IsServiceNodeBlockValidFunc), "snode should be auto-registered after spent utxo detected (2 confirmations)");
// make sure spent collateral not in the new registration
for (const auto & utxo : checkSnode.getCollateral())
BOOST_CHECK_MESSAGE(utxo != selUtxo, "snode spent utxo should not exist after new registration");
}
UnregisterValidationInterface(otherwallet.get());
RemoveWallet(otherwallet);
UnregisterValidationInterface(&sn::ServiceNodeMgr::instance());
gArgs.SoftSetBoolArg("-servicenode", false);
cleanupSn();
pos_ptr.reset();
}
/// Check case where servicenode is valid on reorg (block disconnect)
BOOST_AUTO_TEST_CASE(servicenode_tests_valid_onreorg)
{
gArgs.SoftSetBoolArg("-servicenode", true);
TestChainPoS pos(false);
auto *params = (CChainParams*)&Params();
params->consensus.GetBlockSubsidy = [](const int & blockHeight, const Consensus::Params & consensusParams) {
if (blockHeight <= consensusParams.lastPOWBlock)
return 1000 * COIN;
return 50 * COIN;
};
params->consensus.coinMaturity = 10;
pos.Init("1000,50");
sn::ServiceNodeMgr::instance().reset();
RegisterValidationInterface(&sn::ServiceNodeMgr::instance());
CKey key; key.MakeNewKey(true);
const auto saddr = GetDestinationForKey(key.GetPubKey(), OutputType::LEGACY);
bool firstRun;
auto otherwallet = std::make_shared<CWallet>(*pos.chain, WalletLocation(), WalletDatabase::CreateMock());
otherwallet->LoadWallet(firstRun);
otherwallet->SetBroadcastTransactions(true);
AddKey(*otherwallet, key);
AddWallet(otherwallet); // add wallet to global mgr
RegisterValidationInterface(otherwallet.get());
CBasicKeyStore keystore; // temp used to spend inputs
keystore.AddKey(key);
keystore.AddKey(pos.coinbaseKey);
// Check that snode is valid after spent collateral is orphaned
{
std::vector<COutput> coins;
{
LOCK2(cs_main, pos.wallet->cs_wallet);
pos.wallet->AvailableCoins(*pos.locked_chain, coins, true, nullptr, 1000 * COIN);
}
std::vector<COutPoint> collateral;
CAmount collateralTotal{0};
for (auto & c : coins) {
if (collateralTotal >= sn::ServiceNode::COLLATERAL_SPV)
break;
CMutableTransaction mtx;
mtx.vin.resize(1);
mtx.vin[0] = CTxIn(c.GetInputCoin().outpoint);
mtx.vout.resize(1);
mtx.vout[0].scriptPubKey = GetScriptForDestination(saddr);
mtx.vout[0].nValue = c.GetInputCoin().txout.nValue - CENT;
SignatureData sigdata = DataFromTransaction(mtx, 0, c.GetInputCoin().txout);
ProduceSignature(keystore, MutableTransactionSignatureCreator(&mtx, 0, c.GetInputCoin().txout.nValue, SIGHASH_ALL), c.GetInputCoin().txout.scriptPubKey, sigdata);
UpdateInput(mtx.vin[0], sigdata);
// Send transaction
uint256 txid; std::string errstr;
const TransactionError err = BroadcastTransaction(MakeTransactionRef(mtx), txid, errstr, 0);
BOOST_REQUIRE_MESSAGE(err == TransactionError::OK, strprintf("Failed to send snode collateral tx: %s", errstr));
collateral.emplace_back(mtx.GetHash(), 0);
collateralTotal += mtx.vout[0].nValue;
}
pos.StakeBlocks(params->GetConsensus().coinMaturity), SyncWithValidationInterfaceQueue();
rescanWallet(otherwallet.get());
// Setup snode
UniValue rpcparams = UniValue(UniValue::VARR);
rpcparams.push_backV({ EncodeDestination(saddr), "snode0" });
UniValue entry;
BOOST_CHECK_NO_THROW(entry = CallRPC2("servicenodesetup", rpcparams));
BOOST_CHECK_MESSAGE(entry.isObject(), "Service node entry expected");
rpcparams = UniValue(UniValue::VARR);
BOOST_CHECK_NO_THROW(CallRPC2("servicenoderegister", rpcparams));
const auto snodeEntry = sn::ServiceNodeMgr::instance().getActiveSn();
const auto snode = sn::ServiceNodeMgr::instance().getSn(snodeEntry.key.GetPubKey());
// Find collateral that is spendable
COutPoint selUtxo;
for (const auto & col : snode.getCollateral()) {
Coin c;
if (pcoinsTip->GetCoin(col, c) && c.nHeight >= params->GetConsensus().coinMaturity) {
selUtxo = col;
break;
}
}
BOOST_REQUIRE_MESSAGE(!selUtxo.IsNull(), "Failed to find collateral utxo");
// Simulate that the snode is someone elses, remove it from our local state
sn::ServiceNodeMgr::instance().removeSnEntry(snodeEntry);
auto ss = CDataStream(SER_NETWORK, PROTOCOL_VERSION);
ss << snode;
sn::ServiceNode snodetmp;
BOOST_CHECK_MESSAGE(sn::ServiceNodeMgr::instance().processRegistration(ss, snodetmp), "failed to process snode registration");
// Spend one of the collateral utxos
CTransactionRef tx; uint256 hashBlock;
BOOST_CHECK_MESSAGE(GetTransaction(selUtxo.hash, tx, params->GetConsensus(), hashBlock), "failed to get snode collateral");
CMutableTransaction mtx;
mtx.vin.resize(1); mtx.vout.resize(1);
mtx.vin[0] = CTxIn(selUtxo);
mtx.vout[0] = CTxOut(tx->vout[selUtxo.n].nValue - CENT, tx->vout[selUtxo.n].scriptPubKey);
SignatureData sigdata = DataFromTransaction(mtx, 0, tx->vout[selUtxo.n]);
ProduceSignature(keystore, MutableTransactionSignatureCreator(&mtx, 0, tx->vout[selUtxo.n].nValue, SIGHASH_ALL), tx->vout[selUtxo.n].scriptPubKey, sigdata);
UpdateInput(mtx.vin[0], sigdata);
uint256 txid; std::string errstr; const TransactionError err = BroadcastTransaction(MakeTransactionRef(mtx), txid, errstr, 0);
BOOST_CHECK_MESSAGE(err == TransactionError::OK, strprintf("Failed to spend snode collateral: %s", errstr));
pos.StakeBlocks(1), SyncWithValidationInterfaceQueue();
pos.StakeBlocks(sn::ServiceNode::VALID_GRACEPERIOD_BLOCKS), SyncWithValidationInterfaceQueue();
const auto checkSnode = sn::ServiceNodeMgr::instance().getSn(snodeEntry.key.GetPubKey());
BOOST_CHECK_MESSAGE(checkSnode.getInvalid(), "snode should be marked invalid since collateral was spent");
BOOST_CHECK_MESSAGE(!checkSnode.isValid(GetTxFunc, IsServiceNodeBlockValidFunc), "snode should be invalid");
// Now disconnect spent collateral blocks and verify that snode is still valid
CValidationState state;
for (int i = 0; i <= sn::ServiceNode::VALID_GRACEPERIOD_BLOCKS; ++i)
InvalidateBlock(state, *params, chainActive.Tip(), false);
SyncWithValidationInterfaceQueue();
const auto checkSnode2 = sn::ServiceNodeMgr::instance().getSn(snodeEntry.key.GetPubKey());
BOOST_CHECK_MESSAGE(checkSnode2.isValid(GetTxFunc, IsServiceNodeBlockValidFunc), "snode should still be valid after block disconnects");
}
UnregisterValidationInterface(otherwallet.get());
RemoveWallet(otherwallet);
UnregisterValidationInterface(&sn::ServiceNodeMgr::instance());
gArgs.SoftSetBoolArg("-servicenode", false);
cleanupSn();
}
/// Check case where collateral inputs are immature
BOOST_AUTO_TEST_CASE(servicenode_tests_immature_collateral)
{
auto pos_ptr = std::make_shared<TestChainPoS>(false);
auto & pos = *pos_ptr;
auto *params = (CChainParams*)&Params();
params->consensus.GetBlockSubsidy = [](const int & blockHeight, const Consensus::Params & consensusParams) {
if (blockHeight <= consensusParams.lastPOWBlock)
return 1000 * COIN;
return 50 * COIN;
};
params->consensus.coinMaturity = 10;
pos.Init("1000,50");
gArgs.SoftSetBoolArg("-servicenode", true);
CKey key; key.MakeNewKey(true);
const auto snodePubKey = key.GetPubKey();
const auto tier = sn::ServiceNode::Tier::SPV;
CTxDestination sdest = GetDestinationForKey(snodePubKey, OutputType::LEGACY);
CBasicKeyStore keystore; // temp used to spend inputs
keystore.AddKey(pos.coinbaseKey);
keystore.AddKey(key);
bool firstRun;
auto otherwallet = std::make_shared<CWallet>(*pos.chain, WalletLocation(), WalletDatabase::CreateMock());
otherwallet->LoadWallet(firstRun);
otherwallet->SetBroadcastTransactions(true);
AddKey(*otherwallet, key);
AddWallet(otherwallet); // add wallet to global mgr
RegisterValidationInterface(otherwallet.get());
// Test registering snode with immature inputs
{
std::vector<COutput> coins;
{
LOCK2(cs_main, pos.wallet->cs_wallet);
pos.wallet->AvailableCoins(*pos.locked_chain, coins, true, nullptr, 1000 * COIN);
}
std::vector<COutPoint> collateral;
CAmount collateralTotal{0};
for (auto & c : coins) {
if (collateralTotal >= sn::ServiceNode::COLLATERAL_SPV)
break;
CMutableTransaction mtx;
mtx.vin.resize(1);
mtx.vin[0] = CTxIn(c.GetInputCoin().outpoint);
mtx.vout.resize(1);
mtx.vout[0].scriptPubKey = GetScriptForDestination(sdest);
mtx.vout[0].nValue = c.GetInputCoin().txout.nValue - CENT;
SignatureData sigdata = DataFromTransaction(mtx, 0, c.GetInputCoin().txout);
ProduceSignature(keystore, MutableTransactionSignatureCreator(&mtx, 0, c.GetInputCoin().txout.nValue, SIGHASH_ALL), c.GetInputCoin().txout.scriptPubKey, sigdata);
UpdateInput(mtx.vin[0], sigdata);
// Send transaction
uint256 txid; std::string errstr;
const TransactionError err = BroadcastTransaction(MakeTransactionRef(mtx), txid, errstr, 0);
BOOST_CHECK_MESSAGE(err == TransactionError::OK, strprintf("Failed to send snode collateral tx: %s", errstr));
collateral.emplace_back(mtx.GetHash(), 0);
collateralTotal += mtx.vout[0].nValue;
}
// Stake 2 blocks since that's minimum snode collateral confirmations
pos.StakeBlocks(2), SyncWithValidationInterfaceQueue(), rescanWallet(otherwallet.get());
// Generate the signature from sig hash
const auto & sighash = sn::ServiceNode::CreateSigHash(snodePubKey, tier, snodePubKey.GetID(), collateral, chainActive.Height(), chainActive.Tip()->GetBlockHash());
std::vector<unsigned char> sig;
BOOST_CHECK(key.SignCompact(sighash, sig));
// Deserialize servicenode obj from network stream
sn::ServiceNode snode;
BOOST_CHECK_NO_THROW(snode = snodeNetwork(snodePubKey, tier, snodePubKey.GetID(), collateral, chainActive.Height(), chainActive.Tip()->GetBlockHash(), sig));
BOOST_CHECK_MESSAGE(snode.isValid(GetTxFunc, IsServiceNodeBlockValidFunc), "Service node should be valid with 1 confirmation on collateral");
// Register the snode
BOOST_CHECK_MESSAGE(sn::ServiceNodeMgr::instance().registerSn(key, sn::ServiceNode::SPV, EncodeDestination(sdest), g_connman.get(), {otherwallet}), "Service node should register on immature collateral");
sn::ServiceNodeConfigEntry entry("snode0", sn::ServiceNode::SPV, key, sdest);
sn::ServiceNodeMgr::writeSnConfig(std::vector<sn::ServiceNodeConfigEntry>{entry});
std::set<sn::ServiceNodeConfigEntry> entries;
sn::ServiceNodeMgr::instance().loadSnConfig(entries);
}
// Test that snode auto-registration occurs when one of the collateral inputs is spent/staked
{
// make sure coin isn't immature so we can spend it
pos.StakeBlocks(params->GetConsensus().coinMaturity), SyncWithValidationInterfaceQueue();
RegisterValidationInterface(&sn::ServiceNodeMgr::instance());
auto snode = sn::ServiceNodeMgr::instance().getSn(snodePubKey);
BOOST_CHECK_MESSAGE(!snode.isNull(), "Service node should not be null");
const auto collateral0 = snode.getCollateral()[0];
CTransactionRef tx; uint256 block;
BOOST_CHECK(GetTransaction(collateral0.hash, tx, params->GetConsensus(), block));
CMutableTransaction mtx;
mtx.vin.resize(1);
mtx.vin[0] = CTxIn(collateral0);
mtx.vout.resize(1);
mtx.vout[0].scriptPubKey = tx->vout[0].scriptPubKey; // must spend back to same snode collateral address
mtx.vout[0].nValue = tx->vout[0].nValue - CENT;
SignatureData sigdata = DataFromTransaction(mtx, 0, tx->vout[0]);
ProduceSignature(keystore, MutableTransactionSignatureCreator(&mtx, 0, tx->vout[0].nValue, SIGHASH_ALL), tx->vout[0].scriptPubKey, sigdata);
UpdateInput(mtx.vin[0], sigdata);
// Send transaction
uint256 txid; std::string errstr;
const TransactionError err = BroadcastTransaction(MakeTransactionRef(mtx), txid, errstr, 0);
BOOST_CHECK_MESSAGE(err == TransactionError::OK, strprintf("Failed to send snode collateral tx: %s", errstr));
pos.StakeBlocks(1), SyncWithValidationInterfaceQueue();
xbridge::App::instance().utAddXWallets({"BLOCK","BTC","LTC"});
const auto & jservices = xbridge::App::instance().myServicesJSON();
auto success = sn::ServiceNodeMgr::instance().sendPing(50, jservices, g_connman.get());
BOOST_CHECK_MESSAGE(success, "Refresh snode ping before running state check");
auto running = sn::ServiceNodeMgr::instance().getSn(snodePubKey).running();
BOOST_CHECK_MESSAGE(running, "Service node with recently spent collateral in grace period should still be in running state");
pos.StakeBlocks(sn::ServiceNode::VALID_GRACEPERIOD_BLOCKS), SyncWithValidationInterfaceQueue();
BOOST_CHECK_MESSAGE(sn::ServiceNodeMgr::instance().getSn(snodePubKey).isValid(GetTxFunc, IsServiceNodeBlockValidFunc), "Service node with recently staked collateral should be valid");
UnregisterValidationInterface(&sn::ServiceNodeMgr::instance());
}
UnregisterValidationInterface(otherwallet.get());
RemoveWallet(otherwallet);
cleanupSn();
gArgs.SoftSetBoolArg("-servicenode", false);
pos_ptr.reset();
}
/// Servicenode registration and ping tests
BOOST_AUTO_TEST_CASE(servicenode_tests_registration_pings)
{
gArgs.SoftSetBoolArg("-servicenode", true);
auto pos_ptr = std::make_shared<TestChainPoS>(false);
auto & pos = *pos_ptr;
auto *params = (CChainParams*)&Params();
params->consensus.GetBlockSubsidy = [](const int & blockHeight, const Consensus::Params & consensusParams) {
if (blockHeight <= consensusParams.lastPOWBlock)
return 1000 * COIN;
return 50 * COIN;
};
params->consensus.coinMaturity = 10;
pos.Init("1000,50");
CTxDestination dest(pos.coinbaseKey.GetPubKey().GetID());
auto & smgr = sn::ServiceNodeMgr::instance();
// Snode registration and ping w/ uncompressed key
{
CKey key; key.MakeNewKey(false);
BOOST_CHECK_MESSAGE(smgr.registerSn(key, sn::ServiceNode::SPV, EncodeDestination(dest), g_connman.get(), {pos.wallet}), "Register snode w/ uncompressed key");
// Snode ping w/ uncompressed key
sn::ServiceNodeConfigEntry entry("snode0", sn::ServiceNode::SPV, key, dest);
sn::ServiceNodeMgr::writeSnConfig(std::vector<sn::ServiceNodeConfigEntry>{entry});
std::set<sn::ServiceNodeConfigEntry> entries;
smgr.loadSnConfig(entries);
xbridge::App::instance().utAddXWallets({"BLOCK","BTC","LTC"});
const auto & jservices = xbridge::App::instance().myServicesJSON();
auto success = smgr.sendPing(50, jservices, g_connman.get());
BOOST_CHECK_MESSAGE(success, "Snode ping w/ uncompressed key");
BOOST_CHECK(smgr.list().size() == 1);
sn::ServiceNodeMgr::writeSnConfig(std::vector<sn::ServiceNodeConfigEntry>(), false); // reset
smgr.reset();
}
// Snode registration and ping w/ compressed key
{
CKey key; key.MakeNewKey(true);
BOOST_CHECK_MESSAGE(smgr.registerSn(key, sn::ServiceNode::SPV, EncodeDestination(dest), g_connman.get(), {pos.wallet}), "Register snode w/ compressed key");
// Snode ping w/ compressed key
sn::ServiceNodeConfigEntry entry("snode1", sn::ServiceNode::SPV, key, dest);
sn::ServiceNodeMgr::writeSnConfig(std::vector<sn::ServiceNodeConfigEntry>{entry});
std::set<sn::ServiceNodeConfigEntry> entries;
smgr.loadSnConfig(entries);
xbridge::App::instance().utAddXWallets({"BLOCK","BTC","LTC"});
const auto & jservices = xbridge::App::instance().myServicesJSON();
auto success = smgr.sendPing(50, jservices, g_connman.get());
BOOST_CHECK_MESSAGE(success, "Snode ping w/ compressed key");
BOOST_CHECK(smgr.list().size() == 1);
sn::ServiceNodeMgr::writeSnConfig(std::vector<sn::ServiceNodeConfigEntry>(), false); // reset
smgr.reset();
}
// Check servicenoderegister all rpc
{
const auto & saddr = EncodeDestination(GetDestinationForKey(pos.coinbaseKey.GetPubKey(), OutputType::LEGACY));
UniValue rpcparams(UniValue::VARR);
rpcparams.push_backV({ saddr, "snode0" });
UniValue entry;
BOOST_CHECK_NO_THROW(entry = CallRPC2("servicenodesetup", rpcparams));
BOOST_CHECK_MESSAGE(entry.isObject(), "Service node entry expected");
rpcparams = UniValue(UniValue::VARR);
BOOST_CHECK_NO_THROW(CallRPC2("servicenoderegister", rpcparams));
sn::ServiceNodeMgr::writeSnConfig(std::vector<sn::ServiceNodeConfigEntry>(), false); // reset
smgr.reset();
}
// Check servicenoderegister by alias rpc
{
const auto & saddr = EncodeDestination(GetDestinationForKey(pos.coinbaseKey.GetPubKey(), OutputType::LEGACY));
UniValue rpcparams(UniValue::VARR);
rpcparams.push_backV({ saddr, "snode1" });
UniValue entry;
BOOST_CHECK_NO_THROW(entry = CallRPC2("servicenodesetup", rpcparams));
BOOST_CHECK_MESSAGE(entry.isObject(), "Service node entry expected");
rpcparams = UniValue(UniValue::VARR);
rpcparams.push_backV({ "snode1" });
BOOST_CHECK_NO_THROW(CallRPC2("servicenoderegister", rpcparams));
sn::ServiceNodeMgr::writeSnConfig(std::vector<sn::ServiceNodeConfigEntry>(), false); // reset
smgr.reset();
}
// Check servicenoderegister rpc result data
{
const auto & saddr = EncodeDestination(GetDestinationForKey(pos.coinbaseKey.GetPubKey(), OutputType::LEGACY));
UniValue rpcparams(UniValue::VARR);
rpcparams.push_backV({ saddr, "snode1" });
UniValue entry;
BOOST_CHECK_NO_THROW(entry = CallRPC2("servicenodesetup", rpcparams));
BOOST_CHECK_MESSAGE(entry.isObject(), "Service node entry expected");
rpcparams = UniValue(UniValue::VARR);
try {
auto result = CallRPC2("servicenoderegister", rpcparams);
BOOST_CHECK_EQUAL(result.isArray(), true);
UniValue o = result[0];
BOOST_CHECK_EQUAL(find_value(o, "alias").get_str(), "snode1");
BOOST_CHECK_EQUAL(find_value(o, "tier").get_str(), sn::ServiceNodeMgr::tierString(sn::ServiceNode::SPV));
BOOST_CHECK_EQUAL(find_value(o, "snodekey").get_str().empty(), false); // check not empty
BOOST_CHECK_EQUAL(find_value(o, "snodeprivkey").get_str().empty(), false); // check not empty
BOOST_CHECK(DecodeSecret(find_value(o, "snodeprivkey").get_str()).IsValid()); // check validity
BOOST_CHECK_EQUAL(find_value(o, "address").get_str(), saddr);
} catch (std::exception & e) {
BOOST_CHECK_MESSAGE(false, strprintf("servicenoderegister failed: %s", e.what()));
}
sn::ServiceNodeMgr::writeSnConfig(std::vector<sn::ServiceNodeConfigEntry>(), false); // reset
smgr.reset();
}
// Check servicenoderegister bad alias
{
const auto & saddr = EncodeDestination(GetDestinationForKey(pos.coinbaseKey.GetPubKey(), OutputType::LEGACY));
UniValue rpcparams(UniValue::VARR);
rpcparams.push_backV({ saddr });
UniValue entry;
BOOST_CHECK_NO_THROW(entry = CallRPC2("servicenodesetup", rpcparams));
BOOST_CHECK_MESSAGE(entry.isObject(), "Service node entry expected");
rpcparams = UniValue(UniValue::VARR);
rpcparams.push_backV({ "bad_alias" });
BOOST_CHECK_THROW(CallRPC2("servicenoderegister", rpcparams), std::runtime_error);
sn::ServiceNodeMgr::writeSnConfig(std::vector<sn::ServiceNodeConfigEntry>(), false); // reset
smgr.reset();
}
// Check servicenoderegister no configs
{
const auto & saddr = EncodeDestination(GetDestinationForKey(pos.coinbaseKey.GetPubKey(), OutputType::LEGACY));
UniValue rpcparams(UniValue::VARR);
BOOST_CHECK_THROW(CallRPC2("servicenoderegister", rpcparams), std::runtime_error);
sn::ServiceNodeMgr::writeSnConfig(std::vector<sn::ServiceNodeConfigEntry>(), false); // reset
smgr.reset();
}
// Check valid snode ping
{
CKey key; key.MakeNewKey(true);
BOOST_CHECK_MESSAGE(smgr.registerSn(key, sn::ServiceNode::SPV, EncodeDestination(dest), g_connman.get(), {pos.wallet}), "Register SPV tier snode");
const auto bestBlock = chainActive.Height();
const auto bestBlockHash = chainActive[bestBlock]->GetBlockHash();
auto snode = smgr.getSn(key.GetPubKey());
sn::ServiceNodePing pingValid(key.GetPubKey(), bestBlock, bestBlockHash, static_cast<uint32_t>(GetTime()),
R"({"xbridgeversion":50,"xrouterversion":50,"xrouter":{"config":"[Main]\nwallets=\nplugins=CustomPlugin1,CustomPlugin2\nhost=127.0.0.1", "plugins":{"CustomPlugin1":"","CustomPlugin2":""}}})", snode);
pingValid.sign(key);
BOOST_CHECK_MESSAGE(pingValid.isValid(GetTxFunc, IsServiceNodeBlockValidFunc), "Service node ping should be valid for open tier xrs services");
sn::ServiceNodeMgr::writeSnConfig(std::vector<sn::ServiceNodeConfigEntry>(), false); // reset
smgr.reset();
}
// Check invalid snode ping (empty/missing config)
{
CKey key; key.MakeNewKey(true);
BOOST_CHECK_MESSAGE(smgr.registerSn(key, sn::ServiceNode::SPV, EncodeDestination(dest), g_connman.get(), {pos.wallet}), "Register SPV tier snode");
const auto bestBlock = chainActive.Height();
const auto bestBlockHash = chainActive[bestBlock]->GetBlockHash();
auto snode = smgr.getSn(key.GetPubKey());
sn::ServiceNodePing pingInvalid(key.GetPubKey(), bestBlock, bestBlockHash, static_cast<uint32_t>(GetTime()), "", snode);
pingInvalid.sign(key);
BOOST_CHECK_MESSAGE(!pingInvalid.isValid(GetTxFunc, IsServiceNodeBlockValidFunc), "Service node ping should be invalid for missing config");
sn::ServiceNodeMgr::writeSnConfig(std::vector<sn::ServiceNodeConfigEntry>(), false); // reset
smgr.reset();
}
// Check snode addping
{
CKey key; key.MakeNewKey(true);
BOOST_CHECK_MESSAGE(smgr.registerSn(key, sn::ServiceNode::SPV, EncodeDestination(dest), g_connman.get(), {pos.wallet}), "Register SPV tier snode");
const auto bestBlock = chainActive.Height();
const auto bestBlockHash = chainActive[bestBlock]->GetBlockHash();
auto snode = smgr.getSn(key.GetPubKey());
// Normal add ping should succeed
sn::ServiceNodePing ping(key.GetPubKey(), bestBlock, bestBlockHash, static_cast<uint32_t>(GetTime()),
R"({"xbridgeversion":50,"xrouterversion":50,"xrouter":{"config":"[Main]\nwallets=\nplugins=CustomPlugin1,CustomPlugin2\nhost=127.0.0.1", "plugins":{"CustomPlugin1":"","CustomPlugin2":""}}})", snode);
ping.sign(key);
BOOST_CHECK_MESSAGE(smgr.addPing(ping), "addPing should succeed");
// Ping in past should fail
sn::ServiceNodePing ping2(key.GetPubKey(), bestBlock, bestBlockHash, ping.getPingTime() - 1000,
R"({"xbridgeversion":50,"xrouterversion":50,"xrouter":{"config":"[Main]\nwallets=\nplugins=CustomPlugin1,CustomPlugin2\nhost=127.0.0.1", "plugins":{"CustomPlugin1":"","CustomPlugin2":""}}})", snode);
ping2.sign(key);
BOOST_CHECK_MESSAGE(!smgr.addPing(ping2), "addPing should fail on ping with time prior to latest known ping");
// Ping with future time should succeed
sn::ServiceNodePing ping3(key.GetPubKey(), bestBlock, bestBlockHash, ping.getPingTime() + 10000,
R"({"xbridgeversion":50,"xrouterversion":50,"xrouter":{"config":"[Main]\nwallets=\nplugins=CustomPlugin1,CustomPlugin2\nhost=127.0.0.1", "plugins":{"CustomPlugin1":"","CustomPlugin2":""}}})", snode);
ping3.sign(key);
BOOST_CHECK_MESSAGE(smgr.addPing(ping3), "addPing should succeed for a future time");
sn::ServiceNodeMgr::writeSnConfig(std::vector<sn::ServiceNodeConfigEntry>(), false); // reset
smgr.reset();
}
// Check snode processPing
{
CKey key; key.MakeNewKey(true);
BOOST_CHECK_MESSAGE(smgr.registerSn(key, sn::ServiceNode::SPV, EncodeDestination(dest), g_connman.get(), {pos.wallet}), "Register SPV tier snode");
const auto bestBlock = chainActive.Height();
const auto bestBlockHash = chainActive[bestBlock]->GetBlockHash();
auto snode = smgr.getSn(key.GetPubKey());
// Normal add ping should succeed
sn::ServiceNodePing ping(key.GetPubKey(), bestBlock, bestBlockHash, static_cast<uint32_t>(GetTime()),
R"({"xbridgeversion":50,"xrouterversion":50,"xrouter":{"config":"[Main]\nwallets=\nplugins=CustomPlugin1,CustomPlugin2\nhost=127.0.0.1", "plugins":{"CustomPlugin1":"","CustomPlugin2":""}}})", snode);
ping.sign(key);
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss << ping;
sn::ServiceNodePing pping;
BOOST_CHECK_MESSAGE(smgr.processPing(ss, pping), "processPing should succeed");
// Ping in past should fail
sn::ServiceNodePing ping2(key.GetPubKey(), bestBlock, bestBlockHash, ping.getPingTime() - 1000,
R"({"xbridgeversion":50,"xrouterversion":50,"xrouter":{"config":"[Main]\nwallets=\nplugins=CustomPlugin1,CustomPlugin2\nhost=127.0.0.1", "plugins":{"CustomPlugin1":"","CustomPlugin2":""}}})", snode);
ping2.sign(key);
CDataStream ss2(SER_NETWORK, PROTOCOL_VERSION); ss2 << ping2;
sn::ServiceNodePing pping2;
BOOST_CHECK_MESSAGE(!smgr.processPing(ss2, pping2), "processPing should fail on ping with time prior to latest known ping");
// Ping with future time should succeed
sn::ServiceNodePing ping3(key.GetPubKey(), bestBlock, bestBlockHash, ping.getPingTime() + 10000,
R"({"xbridgeversion":50,"xrouterversion":50,"xrouter":{"config":"[Main]\nwallets=\nplugins=CustomPlugin1,CustomPlugin2\nhost=127.0.0.1", "plugins":{"CustomPlugin1":"","CustomPlugin2":""}}})", snode);
ping3.sign(key);
CDataStream ss3(SER_NETWORK, PROTOCOL_VERSION); ss3 << ping3;
sn::ServiceNodePing pping3;
BOOST_CHECK_MESSAGE(smgr.processPing(ss3, pping3), "processPing should succeed for a future time");
sn::ServiceNodeMgr::writeSnConfig(std::vector<sn::ServiceNodeConfigEntry>(), false); // reset
smgr.reset();
}
// TODO Blocknet OPEN tier snodes, support non-SPV snode tiers (enable unit tests)
// // Snode ping should fail on open tier with xr:: namespace
// {
// CKey key; key.MakeNewKey(true);
// BOOST_CHECK_MESSAGE(smgr.registerSn(key, sn::ServiceNode::OPEN, EncodeDestination(dest), g_connman.get(), {}), "Register OPEN tier snode");
// const auto bestBlock = chainActive.Height();
// const auto bestBlockHash = chainActive[bestBlock]->GetBlockHash();
// auto snode = smgr.getSn(key.GetPubKey());
// sn::ServiceNodePing pingValid(key.GetPubKey(), bestBlock, bestBlockHash, static_cast<uint32_t>(GetTime()),
// R"({"xbridgeversion":50,"xrouterversion":50,"xrouter":{"config":"[Main]\nwallets=\nplugins=CustomPlugin1,CustomPlugin2\nhost=127.0.0.1", "plugins":{"CustomPlugin1":"","CustomPlugin2":""}}})", snode);
// pingValid.sign(key);
// BOOST_CHECK_MESSAGE(pingValid.isValid(GetTxFunc, IsServiceNodeBlockValidFunc), "Service node ping should be valid for open tier xrs services");
// sn::ServiceNodePing pingInvalid(key.GetPubKey(), bestBlock, bestBlockHash, static_cast<uint32_t>(GetTime()),
// R"({"xbridgeversion":50,"xrouterversion":50,"xrouter":{"config":"[Main]\nwallets=BLOCK,LTC\nplugins=CustomPlugin1,CustomPlugin2\nhost=127.0.0.1", "plugins":{"CustomPlugin1":"","CustomPlugin2":""}}})", snode);
// pingInvalid.sign(key);
// BOOST_CHECK_MESSAGE(!pingInvalid.isValid(GetTxFunc, IsServiceNodeBlockValidFunc), "Service node ping should be invalid for open tier non-xrs services");
// sn::ServiceNodeMgr::writeSnConfig(std::vector<sn::ServiceNodeConfigEntry>(), false); // reset
// }
gArgs.SoftSetBoolArg("-servicenode", false);
cleanupSn();
pos_ptr.reset();
}
/// Check misc cases
BOOST_AUTO_TEST_CASE(servicenode_tests_misc_checks)
{
auto pos_ptr = std::make_shared<TestChainPoS>(false);