forked from blocknetdx/blocknet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgovernance_tests.cpp
More file actions
3536 lines (3265 loc) · 197 KB
/
governance_tests.cpp
File metadata and controls
3536 lines (3265 loc) · 197 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) 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 <consensus/tx_verify.h>
#include <consensus/merkle.h>
#include <governance/governancewallet.h>
#include <net.h>
#include <node/transaction.h>
#include <wallet/coincontrol.h>
#include <boost/test/test_tools.hpp>
bool GovernanceSetupFixtureSetup{false};
struct GovernanceSetupFixture {
explicit GovernanceSetupFixture() {
if (GovernanceSetupFixtureSetup) return; GovernanceSetupFixtureSetup = true;
chain_100_40001_50();
chain_200_40001_50();
}
void chain_100_40001_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 100 * COIN;
else if (blockHeight % consensusParams.superblock == 0)
return 40001 * COIN;
return 50 * COIN;
};
pos->Init("100,40001,50");
pos.reset();
}
void chain_200_40001_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 200 * COIN;
else if (blockHeight % consensusParams.superblock == 0)
return 40001 * COIN;
return 50 * COIN;
};
pos->Init("200,40001,50");
pos.reset();
}
};
BOOST_FIXTURE_TEST_SUITE(governance_tests, GovernanceSetupFixture)
int nextSuperblock(const int & block, const int & superblock) {
return block + (superblock - block % superblock);
}
bool sendToRecipients(CWallet *wallet, const std::vector<CRecipient> & recipients, CTransactionRef & tx, std::vector<std::pair<CTxOut,COutPoint>> *recvouts=nullptr) {
// Create and send the transaction
CReserveKey reservekey(wallet);
CAmount nFeeRequired;
std::string strError;
int nChangePosRet = -1;
CCoinControl cc;
auto locked_chain = wallet->chain().lock();
if (!wallet->CreateTransaction(*locked_chain, recipients, tx, reservekey, nFeeRequired, nChangePosRet, strError, cc))
return false;
if (recvouts) { // ensure vouts in order of recipients
std::set<COutPoint> used;
for (int i = 0; i < recipients.size(); ++i) {
auto & rec = recipients[i];
for (int j = 0; j < tx->vout.size(); ++j) {
auto vout = tx->vout[j];
if (used.count({tx->GetHash(), (uint32_t)j}))
continue;
if (vout.scriptPubKey == rec.scriptPubKey && vout.nValue == rec.nAmount) {
recvouts->emplace_back(vout, COutPoint(tx->GetHash(), j));
used.insert({tx->GetHash(), (uint32_t)j});
break;
}
}
}
}
CValidationState state;
auto sent = wallet->CommitTransaction(tx, {}, {}, reservekey, g_connman.get(), state);
BOOST_CHECK_MESSAGE(state.IsValid(), state.GetRejectReason());
return sent && state.IsValid();
}
bool newWalletAddress(CWallet *wallet, CTxDestination & dest) {
wallet->TopUpKeyPool();
CPubKey newKey;
if (!wallet->GetKeyFromPool(newKey))
return false;
wallet->LearnRelatedScripts(newKey, OutputType::LEGACY);
dest = GetDestinationForKey(newKey, OutputType::LEGACY);
return true;
}
bool sendProposal(gov::Proposal & proposal, CTransactionRef & tx, TestChainPoS *testChainPoS, const CChainParams & params) {
// Check that proposal block was accepted with proposal tx in it
const int blockHeight = chainActive.Height();
testChainPoS->StakeBlocks(1), SyncWithValidationInterfaceQueue();
BOOST_CHECK_EQUAL(blockHeight+1, chainActive.Height());
CBlock proposalBlock;
BOOST_CHECK(ReadBlockFromDisk(proposalBlock, chainActive.Tip(), params.GetConsensus()));
bool found{false};
for (const auto & txn : proposalBlock.vtx) {
if (txn->GetHash() == tx->GetHash()) {
found = true;
break;
}
}
BOOST_CHECK_MESSAGE(found, "Proposal tx output was not found in the chain tip");
bool govHasProp = gov::Governance::instance().hasProposal(proposal.getHash());
BOOST_CHECK_MESSAGE(govHasProp, "Failed to add proposal to the governance proposal list");
return found && govHasProp;
}
bool createUtxos(const CAmount & targetAmount, const CAmount & utxoAmount, TestChainPoS *testChainPoS) {
CWallet *wallet = testChainPoS->wallet.get();
std::vector<COutput> coins;
{
LOCK2(cs_main, wallet->cs_wallet);
wallet->AvailableCoins(*testChainPoS->locked_chain, coins);
}
std::sort(coins.begin(), coins.end(), [](const COutput & a, const COutput & b) {
return a.GetInputCoin().txout.nValue > b.GetInputCoin().txout.nValue;
});
const CAmount feeAmount = 1 * COIN;
CAmount runningAmount{0};
CMutableTransaction mtx;
int pos{0};
while (runningAmount < targetAmount - feeAmount) {
mtx.vin.emplace_back(coins[pos].GetInputCoin().outpoint);
// slice vouts
for (CAmount i = 0; i < coins[pos].GetInputCoin().txout.nValue; i += utxoAmount)
mtx.vout.emplace_back(utxoAmount, coins[pos].GetInputCoin().txout.scriptPubKey);
runningAmount += coins[pos].GetInputCoin().txout.nValue;
++pos;
}
// Cover fee
mtx.vin.emplace_back(coins[pos].GetInputCoin().outpoint);
mtx.vout.emplace_back(coins[pos].GetInputCoin().txout.nValue - feeAmount, coins[pos].GetInputCoin().txout.scriptPubKey);
// Sign the tx inputs
const auto scriptPubKey = coins[0].GetInputCoin().txout.scriptPubKey;
for (int i = 0; i < (int)mtx.vin.size(); ++i) {
auto & vin = mtx.vin[i];
SignatureData sigdata = DataFromTransaction(mtx, i, coins[i].GetInputCoin().txout);
BOOST_CHECK(ProduceSignature(*wallet, MutableTransactionSignatureCreator(&mtx, i, coins[i].GetInputCoin().txout.nValue, SIGHASH_ALL), scriptPubKey, sigdata));
UpdateInput(vin, sigdata);
}
// Send transaction
CReserveKey reservekey(wallet);
CValidationState state;
return wallet->CommitTransaction(MakeTransactionRef(mtx), {}, {}, reservekey, g_connman.get(), state);
}
bool applySuperblockPayees(TestChainPoS & pos, CBlockTemplate *blocktemplate, const StakeMgr::StakeCoin & stake,
const std::vector<CTxOut> & payees, const Consensus::Params & consensus, const CAmount addStakeSubsidy=0)
{
CBlock *pblock = &blocktemplate->block;
const int nHeight = chainActive.Height() + 1;
// Create coinstake transaction
CMutableTransaction coinstakeTx;
coinstakeTx.vin.resize(1);
coinstakeTx.vin[0] = CTxIn(stake.coin->outpoint);
coinstakeTx.vout.resize(2); // coinstake + stake payment
coinstakeTx.vout[0].SetNull(); // coinstake
coinstakeTx.vout[0].nValue = 0;
coinstakeTx.vout.resize(2 + payees.size()); // coinstake + stake payment + payees
for (int i = 0; i < static_cast<int>(payees.size()); ++i)
coinstakeTx.vout[2 + i] = payees[i];
const bool feesEnabled = IsNetworkFeesEnabled(chainActive.Tip(), consensus);
// Can't claim any part of the superblock amount as stake reward
const auto stakeSubsidy = GetBlockSubsidy(nHeight, consensus) -
(gov::Governance::isSuperblock(nHeight, consensus) ? consensus.proposalMaxAmount : 0);
const auto stakeAmount = (feesEnabled ? blocktemplate->vTxFees[0] : 0) + stakeSubsidy + addStakeSubsidy;
// Find pubkey of stake input
CTxDestination stakeInputDest;
if (!ExtractDestination(stake.coin->txout.scriptPubKey, stakeInputDest))
return false;
const auto keyid = GetKeyForDestination(*pos.wallet.get(), stakeInputDest);
if (keyid.IsNull())
return false;
CScript paymentScript;
if (VersionBitsState(chainActive.Tip(), consensus, Consensus::DEPLOYMENT_STAKEP2PKH, versionbitscache) == ThresholdState::ACTIVE) { // Stake to p2pkh
paymentScript = GetScriptForDestination(keyid);
} else { // stake to p2pk
CPubKey paymentPubKey;
if (!pos.wallet->GetPubKey(keyid, paymentPubKey))
throw std::runtime_error(strprintf("%s: Failed to find staked input pubkey", __func__));
paymentScript = CScript() << ToByteVector(paymentPubKey) << OP_CHECKSIG;
}
// stake amount and payment script
coinstakeTx.vout[1] = CTxOut(stake.coin->txout.nValue + stakeAmount, paymentScript); // staker payment
// Sign stake input w/ keystore
auto signInput = [](CMutableTransaction & tx, CWallet *keystore) -> bool {
SignatureData empty; // clean script sig on all inputs
for (auto & txin : tx.vin)
UpdateInput(txin, empty);
auto locked_chain = keystore->chain().lock();
LOCK(keystore->cs_wallet);
if (!keystore->SignTransaction(tx))
return false;
return true;
};
// Calculate network fee for coinbase/coinstake txs
if (!signInput(coinstakeTx, pos.wallet.get()))
return false;
const auto coinbaseBytes = ::GetSerializeSize(pblock->vtx[0], PROTOCOL_VERSION);
const auto coinstakeBytes = ::GetSerializeSize(coinstakeTx, PROTOCOL_VERSION);
CAmount estimatedNetworkFee = static_cast<CAmount>(::minRelayTxFee.GetFee(coinbaseBytes) + ::minRelayTxFee.GetFee(coinstakeBytes));
coinstakeTx.vout[1] = CTxOut(stake.coin->txout.nValue + stakeAmount - estimatedNetworkFee, paymentScript); // staker payment w/ network fee taken out
if (!signInput(coinstakeTx, pos.wallet.get())) // resign with correct fee estimation
return false;
// Assign coinstake tx
pblock->vtx[1] = MakeTransactionRef(std::move(coinstakeTx));
blocktemplate->vchCoinbaseCommitment = GenerateCoinbaseCommitment(*pblock, chainActive.Tip(), consensus);
pblock->hashMerkleRoot = BlockMerkleRoot(*pblock);
blocktemplate->vTxSigOpsCost[0] = WITNESS_SCALE_FACTOR * GetLegacySigOpCount(*pblock->vtx[0]);
return SignBlock(*pblock, stake.coin->txout.scriptPubKey, *pos.wallet);
}
bool stakeWallet(std::shared_ptr<CWallet> & wallet, StakeMgr & staker, const COutPoint & stakeInput, const int & tryiter) {
const CChainParams & params = Params();
int tries{0};
int64_t tipBlockTime{0};
const int currentBlockHeight = chainActive.Height();
while (chainActive.Height() < currentBlockHeight + 1) {
try {
CBlockIndex *tip = nullptr;
CBlockIndex *stakeIndex = nullptr;
std::shared_ptr<COutput> output = nullptr;
CTransactionRef tx;
uint256 block;
{
LOCK(cs_main);
tip = chainActive.Tip();
tipBlockTime = tip->GetBlockTime();
if (!GetTransaction(stakeInput.hash, tx, params.GetConsensus(), block))
return false;
stakeIndex = LookupBlockIndex(block);
if (!stakeIndex)
return false;
{
LOCK(wallet->cs_wallet);
const CWalletTx *wtx = wallet->GetWalletTx(tx->GetHash());
output = std::make_shared<COutput>(wtx, stakeInput.n, tip->nHeight - stakeIndex->nHeight, true, true, true);
}
}
const auto adjustedTime = GetAdjustedTime();
const auto fromTime = std::max(tip->GetBlockTime()+1, adjustedTime);
const auto blockTime = fromTime;
const auto toTime = fromTime + params.GetConsensus().PoSFutureBlockTimeLimit(blockTime);
std::map<int64_t, std::vector<StakeMgr::StakeCoin>> stakes;
if (staker.GetStakesMeetingTarget(output, wallet, tip, adjustedTime, blockTime, fromTime, toTime,
stakes, params.GetConsensus())) {
for (auto & item : stakes) {
for (auto & sc : item.second) {
if (staker.StakeBlock(sc, params))
return true;
}
}
}
} catch (std::exception & e) {
LogPrintf("Staker ran into an exception: %s\n", e.what());
throw e;
} catch (...) {
throw std::runtime_error("Staker unknown error");
}
if (++tries > tryiter)
throw std::runtime_error("Staker failed to find stake");
SetMockTime(GetAdjustedTime() + params.GetConsensus().PoSFutureBlockTimeLimit(tipBlockTime));
}
return false;
}
bool isTxInBlock(const CBlockIndex *blockhash, const uint256 & txhash, const Consensus::Params & consensus) {
CBlock block;
ReadBlockFromDisk(block, blockhash, consensus);
bool txInBlock{false};
for (auto & vtx : block.vtx) {
if (vtx->GetHash() == txhash) {
txInBlock = true;
break;
}
}
return txInBlock;
}
bool cleanup(int blockCount, CWallet *wallet=nullptr) {
const auto & params = Params();
{
LOCK2(cs_main, mempool.cs);
mempool.clear();
}
CValidationState state;
while (chainActive.Height() > blockCount)
InvalidateBlock(state, params, chainActive.Tip(), false);
ActivateBestChain(state, params); SyncWithValidationInterfaceQueue();
gArgs.ForceSetArg("-proposaladdress", "");
gArgs.ForceSetArg("-maxtxfee", "");
removeGovernanceDBFiles();
gov::Governance::instance().reset();
if (wallet) {
std::vector<CWalletTx> wtx;
wallet->ZapWalletTx(wtx);
WalletRescanReserver reserver(wallet);
reserver.reserve();
wallet->ScanForWalletTransactions(chainActive.Genesis()->GetBlockHash(), {}, reserver, true);
}
return true;
}
BOOST_FIXTURE_TEST_CASE(governance_tests_proposals, TestChainPoS)
{
RegisterValidationInterface(&gov::Governance::instance());
const auto & params = Params();
const auto & consensus = params.GetConsensus();
CTxDestination dest(coinbaseKey.GetPubKey().GetID());
// Check vote copy constructor
{
gov::Vote vote1(COutPoint{m_coinbase_txns[5]->vin[0].prevout});
gov::Vote vote2;
vote2 = vote1;
BOOST_CHECK_MESSAGE(vote1 == vote2, "Vote copy constructor should work");
}
// Check proposal copy constructor
{
gov::Proposal proposal1("Test proposal-1", nextSuperblock(chainActive.Height(), consensus.superblock), 3000*COIN,
EncodeDestination(dest), "https://forum.blocknet.co", "Short description");
gov::Proposal proposal2;
proposal2 = proposal1;
BOOST_CHECK_MESSAGE(proposal1 == proposal2, "Proposal copy constructor should work");
}
// Check normal proposal
gov::Proposal p1("Test proposal-1", nextSuperblock(chainActive.Height(), consensus.superblock), 3000*COIN,
EncodeDestination(dest), "https://forum.blocknet.co", "Short description");
BOOST_CHECK_MESSAGE(p1.isValid(consensus), "Basic proposal should be valid");
// Proposal with underscores should pass
gov::Proposal p2("Test proposal_2", nextSuperblock(chainActive.Height(), consensus.superblock), 3000*COIN,
EncodeDestination(dest), "https://forum.blocknet.co", "Short description");
BOOST_CHECK_MESSAGE(p2.isValid(consensus), "Basic proposal should be valid");
// Proposal with empty description should pass
gov::Proposal p2a("Test proposal 2", nextSuperblock(chainActive.Height(), consensus.superblock), 3000*COIN,
EncodeDestination(dest), "https://forum.blocknet.co", "");
BOOST_CHECK_MESSAGE(p2a.isValid(consensus), "Proposal should be valid with empty description");
// Proposal with empty url should pass
gov::Proposal p2b("Test proposal 2", nextSuperblock(chainActive.Height(), consensus.superblock), 3000*COIN,
EncodeDestination(dest), "", "Short description");
BOOST_CHECK_MESSAGE(p2b.isValid(consensus), "Proposal should be valid with empty url");
// Proposal with empty name should fail
gov::Proposal p2c("", nextSuperblock(chainActive.Height(), consensus.superblock), 3000*COIN,
EncodeDestination(dest), "https://forum.blocknet.co", "Short description");
BOOST_CHECK_MESSAGE(!p2c.isValid(consensus), "Proposal should fail with empty name");
// Proposal with minimum size name should pass
gov::Proposal p2d("ab", nextSuperblock(chainActive.Height(), consensus.superblock), 3000*COIN,
EncodeDestination(dest), "https://forum.blocknet.co", "Short description");
BOOST_CHECK_MESSAGE(p2d.isValid(consensus), "Proposal should be valid with minimal name");
// Proposal with maxed out size should pass (157 bytes is the max size of a proposal)
gov::Proposal p2m("Test proposal max", nextSuperblock(chainActive.Height(), consensus.superblock), 3000*COIN,
EncodeDestination(dest), "https://forum.blocknet.co", "This description is the maximum allowed for this particular prp");
BOOST_CHECK_MESSAGE(p2m.isValid(consensus), "Proposal at max description should pass");
// Proposal with maxed out size + 1 should fail
gov::Proposal p2n("Test proposal max", nextSuperblock(chainActive.Height(), consensus.superblock), 3000*COIN,
EncodeDestination(dest), "https://forum.blocknet.co", p2m.getDescription() + "1");
BOOST_CHECK_MESSAGE(!p2n.isValid(consensus), "Proposal with max description + 1 should fail");
// Proposal should fail if description is too long
gov::Proposal p3("Test proposal-3", nextSuperblock(chainActive.Height(), consensus.superblock), 3000*COIN,
EncodeDestination(dest), "https://forum.blocknet.co", "This is a long description that causes the proposal to fail. Proposals are limited by the OP_RETURN size");
BOOST_CHECK_MESSAGE(!p3.isValid(consensus), "Proposal should fail if its serialized size is too large");
// Should fail if amount is too high
gov::Proposal p4("Test proposal", nextSuperblock(chainActive.Height(), consensus.superblock), 100000*COIN,
EncodeDestination(dest), "https://forum.blocknet.co", "Short description");
BOOST_CHECK_MESSAGE(!p4.isValid(consensus), "Proposal should fail if amount is too large");
// Should fail if amount is too low
gov::Proposal p4a("Test proposal", nextSuperblock(chainActive.Height(), consensus.superblock), consensus.proposalMinAmount-1,
EncodeDestination(dest), "https://forum.blocknet.co", "Short description");
BOOST_CHECK_MESSAGE(!p4a.isValid(consensus), "Proposal should fail if amount is too small");
// Should fail if proposal address is bad
gov::Proposal p5("Test proposal", nextSuperblock(chainActive.Height(), consensus.superblock), 3000*COIN,
"fjdskjfksdafjksdajfkdsajfkasjdfk", "https://forum.blocknet.co", "Short description");
BOOST_CHECK_MESSAGE(!p5.isValid(consensus), "Proposal should fail on bad proposal address");
// Should fail on bad superblock height
gov::Proposal p6("Test proposal", 17, 3000*COIN,
EncodeDestination(dest), "https://forum.blocknet.co", "Short description");
BOOST_CHECK_MESSAGE(!p6.isValid(consensus), "Proposal should fail on bad superblock height");
// Should fail on bad proposal name (special chars)
gov::Proposal p7("Test $proposal", nextSuperblock(chainActive.Height(), consensus.superblock), 3000*COIN,
EncodeDestination(dest), "https://forum.blocknet.co", "Short description");
BOOST_CHECK_MESSAGE(!p7.isValid(consensus), "Proposal should fail on bad proposal name (special chars)");
// Should fail on bad proposal name (starts with spaces)
gov::Proposal p8(" Test proposal", nextSuperblock(chainActive.Height(), consensus.superblock), 3000*COIN,
EncodeDestination(dest), "https://forum.blocknet.co", "Short description");
BOOST_CHECK_MESSAGE(!p8.isValid(consensus), "Proposal should be invalid if name starts with whitespace");
// Should fail on bad proposal name (ends with spaces)
gov::Proposal p9("Test proposal ", nextSuperblock(chainActive.Height(), consensus.superblock), 3000*COIN,
EncodeDestination(dest), "https://forum.blocknet.co", "Short description");
BOOST_CHECK_MESSAGE(!p9.isValid(consensus), "Proposal should be invalid if name ends with whitespace");
// Check that proposal submission tx is added to mempool
{
const auto resetBlocks = chainActive.Height();
gov::Proposal psubmit("Test proposal", nextSuperblock(chainActive.Height(), consensus.superblock), 3000*COIN,
EncodeDestination(dest), "https://forum.blocknet.co", "Short description");
CTransactionRef tx = nullptr;
std::string failReason;
auto success = gov::SubmitProposal(psubmit, {wallet}, consensus, tx, g_connman.get(), &failReason);
BOOST_REQUIRE_MESSAGE(success, strprintf("Proposal submission failed: %s", failReason));
BOOST_CHECK_MESSAGE(tx != nullptr, "Proposal tx should be valid");
BOOST_CHECK_MESSAGE(mempool.exists(tx->GetHash()), "Proposal submission tx should be in the mempool");
CDataStream ss(SER_NETWORK, GOV_PROTOCOL_VERSION);
ss << psubmit;
bool found{false};
for (const auto & out : tx->vout) {
if (out.scriptPubKey[0] == OP_RETURN) {
BOOST_CHECK_EQUAL(consensus.proposalFee, out.nValue);
BOOST_CHECK_MESSAGE((CScript() << OP_RETURN << ToByteVector(ss)) == out.scriptPubKey, "Proposal submission OP_RETURN script in tx should match expected");
found = true;
}
}
BOOST_CHECK_MESSAGE(found, "Proposal submission tx must contain an OP_RETURN");
cleanup(resetBlocks, wallet.get());
ReloadWallet();
}
// Check proposal that is under the pushdata1 requirements should be properly processed
{
const auto resetBlocks = chainActive.Height();
gov::Proposal psubmit("tt", nextSuperblock(chainActive.Height(), consensus.superblock), 3000*COIN,
EncodeDestination(dest), "", "");
CTransactionRef tx = nullptr;
std::string failReason;
auto success = gov::SubmitProposal(psubmit, {wallet}, consensus, tx, g_connman.get(), &failReason);
BOOST_REQUIRE_MESSAGE(success, strprintf("Proposal submission failed: %s", failReason));
BOOST_CHECK_MESSAGE(tx != nullptr, "Proposal tx should be valid");
BOOST_CHECK_MESSAGE(mempool.exists(tx->GetHash()), "Proposal submission tx should be in the mempool");
StakeBlocks(1), SyncWithValidationInterfaceQueue();
BOOST_CHECK_MESSAGE(!gov::Governance::instance().getProposal(psubmit.getHash()).isNull(), "Very small proposal should exist");
cleanup(resetBlocks, wallet.get());
ReloadWallet();
}
// Check -proposaladdress config option
{
const auto resetBlocks = chainActive.Height();
CTxDestination newDest;
BOOST_CHECK(newWalletAddress(wallet.get(), newDest));
gArgs.ForceSetArg("-proposaladdress", EncodeDestination(newDest));
// Send coin to the proposal address
CTransactionRef tx;
bool accepted = sendToAddress(wallet.get(), newDest, 50 * COIN, tx);
if (!accepted) cleanup(resetBlocks);
BOOST_REQUIRE_MESSAGE(accepted, "Proposal fee account should confirm to the network before continuing");
StakeBlocks(1), SyncWithValidationInterfaceQueue();
// Create and submit proposal
gov::Proposal pp1("Test -proposaladdress", nextSuperblock(chainActive.Height(), consensus.superblock), 3000*COIN,
EncodeDestination(dest), "https://forum.blocknet.co", "Short description");
CTransactionRef pp1_tx = nullptr;
std::string failReason;
auto success = gov::SubmitProposal(pp1, {wallet}, consensus, pp1_tx, g_connman.get(), &failReason);
BOOST_REQUIRE_MESSAGE(success, strprintf("Proposal submission failed: %s", failReason));
BOOST_CHECK_MESSAGE(failReason.empty(), strprintf("Failed to submit proposal: %s", failReason));
// Check that proposal tx was accepted
accepted = pp1_tx != nullptr && sendProposal(pp1, pp1_tx, this, params);
if (!accepted) cleanup(resetBlocks);
BOOST_REQUIRE_MESSAGE(accepted, "Proposal tx should confirm to the network before continuing");
// Check that proposal tx pays change to -proposaladdress
uint256 block;
CTransactionRef txPrev;
BOOST_CHECK_MESSAGE(GetTransaction(pp1_tx->vin[0].prevout.hash, txPrev, params.GetConsensus(), block), "Failed to find vin transaction");
const auto & prevOut = txPrev->vout[pp1_tx->vin[0].prevout.n];
const auto & inAmount = prevOut.nValue;
const auto & inAddress = prevOut.scriptPubKey;
CTxDestination extractAddr;
BOOST_CHECK_MESSAGE(ExtractDestination(inAddress, extractAddr), "Failed to extract payment address from proposaladdress vin");
BOOST_CHECK_MESSAGE(newDest == extractAddr, "Address vin should match -proposaladdress config flag");
bool foundOpReturn{false};
bool foundChangeAddress{false};
for (const auto & out : pp1_tx->vout) {
if (out.scriptPubKey[0] == OP_RETURN && out.nValue == consensus.proposalFee)
foundOpReturn = true;
if (out.scriptPubKey == GetScriptForDestination(extractAddr)) {
const auto fee = inAmount - pp1_tx->GetValueOut();
BOOST_CHECK_MESSAGE(fee > 0, "Proposal tx must account for network fee");
foundChangeAddress = out.nValue == inAmount - consensus.proposalFee - fee;
}
}
BOOST_CHECK_MESSAGE(foundOpReturn, "Failed to find proposal fee payment");
BOOST_CHECK_MESSAGE(foundChangeAddress, "Failed to find proposal change address payment");
cleanup(resetBlocks, wallet.get());
ReloadWallet();
}
UnregisterValidationInterface(&gov::Governance::instance());
cleanup(chainActive.Height(), wallet.get());
ReloadWallet();
}
BOOST_FIXTURE_TEST_CASE(governance_tests_votes, TestChainPoS)
{
RegisterValidationInterface(&gov::Governance::instance());
auto *params = (CChainParams*)&Params();
params->consensus.voteMinUtxoAmount = 20*COIN;
params->consensus.voteBalance = 1000*COIN;
const auto & consensus = params->GetConsensus();
CTxDestination dest(coinbaseKey.GetPubKey().GetID());
std::vector<COutput> coins;
{
LOCK2(cs_main, wallet->cs_wallet);
wallet->AvailableCoins(*locked_chain, coins);
}
BOOST_CHECK_MESSAGE(!coins.empty(), "Vote tests require available coins");
const gov::VinHash & vinHash = gov::makeVinHash(coins.front().GetInputCoin().outpoint);
std::set<gov::VinHash> vinHashes{vinHash};
// Check normal proposal
gov::Proposal proposal("Test proposal", nextSuperblock(chainActive.Height(), consensus.superblock), 3000*COIN,
EncodeDestination(dest), "https://forum.blocknet.co", "Short description");
BOOST_CHECK_MESSAGE(proposal.isValid(consensus), "Basic proposal should be valid");
// Check YES vote is valid
{
gov::Vote vote(proposal.getHash(), gov::YES, coins.begin()->GetInputCoin().outpoint, vinHash);
BOOST_CHECK_MESSAGE(vote.sign(coinbaseKey), "Vote YES signing should succeed");
BOOST_CHECK_MESSAGE(vote.isValid(vinHashes, consensus), "Vote YES should be valid upon signing");
}
// Check NO vote is valid
{
gov::Vote vote(proposal.getHash(), gov::NO, coins.begin()->GetInputCoin().outpoint, vinHash);
BOOST_CHECK_MESSAGE(vote.sign(coinbaseKey), "Vote NO signing should succeed");
BOOST_CHECK_MESSAGE(vote.isValid(vinHashes, consensus), "Vote NO should be valid upon signing");
}
// Check ABSTAIN vote is valid
{
gov::Vote vote(proposal.getHash(), gov::ABSTAIN, coins.begin()->GetInputCoin().outpoint, vinHash);
BOOST_CHECK_MESSAGE(vote.sign(coinbaseKey), "Vote ABSTAIN signing should succeed");
BOOST_CHECK_MESSAGE(vote.isValid(vinHashes, consensus), "Vote ABSTAIN should be valid upon signing");
}
// Bad vote type should fail
{
gov::Vote vote(proposal.getHash(), (gov::VoteType)99, coins.begin()->GetInputCoin().outpoint, vinHash);
BOOST_CHECK_MESSAGE(vote.sign(coinbaseKey), "Vote signing should succeed");
BOOST_CHECK_MESSAGE(!vote.isValid(vinHashes, consensus), "Vote with invalid type should fail");
}
// Signing with key not matching utxo should fail
{
CKey key; key.MakeNewKey(true);
gov::Vote vote(proposal.getHash(), gov::YES, coins.begin()->GetInputCoin().outpoint, vinHash);
BOOST_CHECK_MESSAGE(vote.sign(key), "Vote signing should succeed");
BOOST_CHECK_MESSAGE(!vote.isValid(vinHashes, consensus), "Vote with bad signing key should fail");
}
// Vote with utxo from a non-owned address in mempool should fail
{
const auto resetBlocks = chainActive.Height();
CKey key; key.MakeNewKey(true);
const auto & newDest = GetDestinationForKey(key.GetPubKey(), OutputType::LEGACY);
CTransactionRef tx;
BOOST_CHECK(sendToAddress(wallet.get(), newDest, 50 * COIN, tx));
// find n pos
COutPoint outpoint;
for (int i = 0; i < static_cast<int>(tx->vout.size()); ++i) {
const auto & out = tx->vout[i];
CTxDestination destination;
ExtractDestination(out.scriptPubKey, destination);
if (newDest == destination) {
outpoint = {tx->GetHash(), static_cast<uint32_t>(i)};
break;
}
}
BOOST_CHECK_MESSAGE(!outpoint.IsNull(), "Vote utxo should not be null in non-owned address check");
gov::Vote vote(proposal.getHash(), gov::YES, outpoint, vinHash);
BOOST_CHECK_MESSAGE(vote.sign(coinbaseKey), "Vote signing should succeed");
BOOST_CHECK_MESSAGE(!vote.isValid(vinHashes, consensus), "Vote with bad utxo should fail");
// clean up
cleanup(resetBlocks);
}
// Vote with utxo from a non-owned address should fail
{
const auto resetBlocks = chainActive.Height();
CKey key; key.MakeNewKey(true);
const auto & newDest = GetDestinationForKey(key.GetPubKey(), OutputType::LEGACY);
CTransactionRef tx;
bool sent = sendToAddress(wallet.get(), newDest, 50 * COIN, tx);
BOOST_CHECK_MESSAGE(sent, "Send to another address failed");
if (sent) StakeBlocks(1), SyncWithValidationInterfaceQueue();
// find n pos
COutPoint outpoint;
for (int i = 0; i < static_cast<int>(tx->vout.size()); ++i) {
const auto & out = tx->vout[i];
CTxDestination destination;
ExtractDestination(out.scriptPubKey, destination);
if (newDest == destination) {
outpoint = {tx->GetHash(), static_cast<uint32_t>(i)};
break;
}
}
BOOST_CHECK_MESSAGE(!outpoint.IsNull(), "Vote utxo should not be null in non-owned address check");
gov::Vote vote(proposal.getHash(), gov::YES, outpoint, vinHash);
BOOST_CHECK_MESSAGE(vote.sign(coinbaseKey), "Vote signing should succeed");
BOOST_CHECK_MESSAGE(!vote.isValid(vinHashes, consensus), "Vote with bad utxo should fail");
// Clean up
cleanup(resetBlocks);
}
// Voting with spent utxo should fail
{
const auto resetBlocks = chainActive.Height();
CKey key; key.MakeNewKey(true);
const auto & newDest = GetDestinationForKey(key.GetPubKey(), OutputType::LEGACY);
CTransactionRef tx;
CTransactionRef txVoteInput;
bool sent = sendToAddress(wallet.get(), newDest, 200 * COIN, tx)
&& sendToAddress(wallet.get(), newDest, 1 * COIN, txVoteInput);
BOOST_CHECK_MESSAGE(sent, "Send to another address failed");
CTransactionRef ptx; // proposal tx
std::string failReason;
gov::SubmitProposal(proposal, {wallet}, consensus, ptx, g_connman.get(), &failReason);
if (sent) StakeBlocks(1), SyncWithValidationInterfaceQueue();
COutPoint outpoint;
CTxOut txout;
for (int i = 0; i < static_cast<int>(tx->vout.size()); ++i) {
const auto & out = tx->vout[i];
CTxDestination destination;
ExtractDestination(out.scriptPubKey, destination);
if (newDest == destination) {
outpoint = {tx->GetHash(), static_cast<uint32_t>(i)};
txout = out;
break;
}
}
BOOST_CHECK_MESSAGE(!outpoint.IsNull(), "Vote utxo should not be null");
// Submit the vote with spent utxo
CBasicKeyStore keystore;
keystore.AddKey(key);
// Vote should not be accepted since the input is being spent in the voting tx's itself
{
gov::VinHash voteVinHash = gov::makeVinHash(outpoint);
gov::Vote vote(proposal.getHash(), gov::YES, outpoint, voteVinHash);
BOOST_CHECK_MESSAGE(vote.sign(key), "Vote signing should succeed");
BOOST_CHECK_MESSAGE(vote.isValid(std::set<gov::VinHash>{voteVinHash}, consensus), "Vote should be valid");
CMutableTransaction mtx;
mtx.vin.resize(1);
mtx.vin[0] = CTxIn(outpoint);
CDataStream ss(SER_NETWORK, GOV_PROTOCOL_VERSION);
ss << vote;
auto voteScript = CScript() << OP_RETURN << ToByteVector(ss);
mtx.vout.resize(2);
mtx.vout[0] = CTxOut(0, voteScript); // vote here w/ spent utxo
mtx.vout[1] = CTxOut(200 * COIN - COIN, txout.scriptPubKey);
SignatureData sigdata = DataFromTransaction(mtx, 0, txout);
ProduceSignature(keystore, MutableTransactionSignatureCreator(&mtx, 0, txout.nValue, SIGHASH_ALL),
txout.scriptPubKey, sigdata);
UpdateInput(mtx.vin[0], sigdata);
// Send transaction
uint256 txid;
std::string errstr;
const TransactionError err = BroadcastTransaction(MakeTransactionRef(mtx), txid, errstr, 100 * COIN);
BOOST_CHECK_MESSAGE(err == TransactionError::OK, strprintf("Failed to send vote transaction: %s", errstr));
StakeBlocks(1), SyncWithValidationInterfaceQueue();
BOOST_CHECK_MESSAGE(!gov::Governance::instance().hasVote(vote.getHash()), "Vote should not be accepted since its input was spent in mempool");
// update outpoint with latest utxo
outpoint = {mtx.GetHash(), 1};
txout = mtx.vout[1];
}
// Vote should not be accepted since it was spent in the last block
// Spend a utxo and then attempt to vote with that spent utxo
{
CMutableTransaction mtx1;
mtx1.vin.resize(1);
mtx1.vin[0] = CTxIn(outpoint);
mtx1.vout.resize(1);
mtx1.vout[0] = CTxOut(txout.nValue - COIN, txout.scriptPubKey);
{
SignatureData sigdata = DataFromTransaction(mtx1, 0, txout);
ProduceSignature(keystore, MutableTransactionSignatureCreator(&mtx1, 0, txout.nValue, SIGHASH_ALL),
txout.scriptPubKey, sigdata);
UpdateInput(mtx1.vin[0], sigdata);
// Send transaction
uint256 txid;
std::string errstr;
const TransactionError err = BroadcastTransaction(MakeTransactionRef(mtx1), txid, errstr, 100 * COIN);
BOOST_CHECK_MESSAGE(err == TransactionError::OK, strprintf("Failed to send vote transaction: %s", errstr));
StakeBlocks(1), SyncWithValidationInterfaceQueue();
}
// Obtain valid utxo to use in submitting the vote
COutPoint prevout;
CTxOut prevtxout;
for (int i = 0; i < static_cast<int>(txVoteInput->vout.size()); ++i) {
const auto & out = txVoteInput->vout[i];
CTxDestination destination;
ExtractDestination(out.scriptPubKey, destination);
if (newDest == destination) {
prevout = {txVoteInput->GetHash(), static_cast<uint32_t>(i)};
prevtxout = out;
break;
}
}
COutPoint voteOutpoint = outpoint; // reference the spent utxo
gov::VinHash voteVinHash = gov::makeVinHash(prevout); // valid prevout to submit the vote with
gov::Vote vote(proposal.getHash(), gov::YES, voteOutpoint, voteVinHash);
BOOST_CHECK_MESSAGE(vote.sign(key), "Vote signing should succeed");
BOOST_CHECK_MESSAGE(vote.isValid(std::set<gov::VinHash>{voteVinHash}, consensus), "Vote should be valid");
// Create voting transaction, make sure the vote is referencing the spent utxo
// but is being submitted by a valid unspent vin
CMutableTransaction mtx2;
mtx2.vin.resize(1);
mtx2.vin[0] = CTxIn(prevout);
CDataStream ss(SER_NETWORK, GOV_PROTOCOL_VERSION);
ss << vote;
auto voteScript = CScript() << OP_RETURN << ToByteVector(ss);
mtx2.vout.resize(2);
mtx2.vout[0] = CTxOut(0, voteScript); // vote here w/ spent utxo
mtx2.vout[1] = CTxOut(prevtxout.nValue - 10000, prevtxout.scriptPubKey);
{
SignatureData sigdata = DataFromTransaction(mtx2, 0, prevtxout);
ProduceSignature(keystore, MutableTransactionSignatureCreator(&mtx2, 0, prevtxout.nValue, SIGHASH_ALL),
prevtxout.scriptPubKey, sigdata);
UpdateInput(mtx2.vin[0], sigdata);
// Send transaction
uint256 txid;
std::string errstr;
const TransactionError err = BroadcastTransaction(MakeTransactionRef(mtx2), txid, errstr, 100 * COIN);
BOOST_CHECK_MESSAGE(err == TransactionError::OK, strprintf("Failed to send vote transaction: %s", errstr));
StakeBlocks(1), SyncWithValidationInterfaceQueue();
BOOST_CHECK_MESSAGE(!gov::Governance::instance().hasVote(vote.getHash()), "Vote should not be accepted since its input was spent in previous block");
}
}
// Clean up
cleanup(resetBlocks, wallet.get());
ReloadWallet();
}
UnregisterValidationInterface(&gov::Governance::instance());
cleanup(chainActive.Height(), wallet.get());
ReloadWallet();
}
BOOST_FIXTURE_TEST_CASE(governance_tests_votes_undo, TestChainPoS)
{
gArgs.ForceSetArg("-maxtxfee", "500000000");
RegisterValidationInterface(&gov::Governance::instance());
auto *params = (CChainParams*)&Params();
params->consensus.voteMinUtxoAmount = 20*COIN;
params->consensus.voteBalance = 200*COIN;
const auto & consensus = params->GetConsensus();
CTxDestination dest(coinbaseKey.GetPubKey().GetID());
std::vector<COutput> coins;
{
LOCK2(cs_main, wallet->cs_wallet);
wallet->AvailableCoins(*locked_chain, coins);
}
BOOST_CHECK_MESSAGE(!coins.empty(), "Vote tests require available coins");
const gov::VinHash & vinHash = gov::makeVinHash(coins.front().GetInputCoin().outpoint);
std::set<gov::VinHash> vinHashes{vinHash};
// Check normal proposal
gov::Proposal proposal("Test proposal", nextSuperblock(chainActive.Height(), consensus.superblock), 3000*COIN,
EncodeDestination(dest), "https://forum.blocknet.co", "Short description");
BOOST_CHECK_MESSAGE(proposal.isValid(consensus), "Basic proposal should be valid");
// Voting with spent utxo should fail
{
const auto resetBlocks = chainActive.Height();
CKey key; key.MakeNewKey(true);
const auto & newDest = GetDestinationForKey(key.GetPubKey(), OutputType::LEGACY);
// Submit the vote with spent utxo
bool firstRun;
auto otherwallet = std::make_shared<CWallet>(*chain, WalletLocation(), WalletDatabase::CreateMock());
otherwallet->LoadWallet(firstRun);
AddKey(*otherwallet, key);
otherwallet->SetBroadcastTransactions(true);
rescanWallet(otherwallet.get());
RegisterValidationInterface(otherwallet.get());
// Vote inputs
{
CTransactionRef tx;
CTransactionRef txVoteInput;
bool sent = sendToAddress(wallet.get(), newDest, 200 * COIN, tx)
&& sendToAddress(wallet.get(), newDest, 3 * COIN, txVoteInput);
BOOST_CHECK_MESSAGE(sent, "Send to another address failed");
}
// Create proposal
{
CTransactionRef ptx; // proposal tx
std::string failReason;
gov::SubmitProposal(proposal, {wallet}, consensus, ptx, g_connman.get(), &failReason);
StakeBlocks(1), SyncWithValidationInterfaceQueue();
}
// 1) Vote on a proposal
{
gov::ProposalVote proposalVote{proposal, gov::YES};
std::vector<CTransactionRef> txs;
std::string failReason;
bool success = gov::SubmitVotes(std::vector<gov::ProposalVote>{proposalVote}, {otherwallet}, consensus, txs, g_connman.get(), &failReason);
BOOST_REQUIRE_MESSAGE(success, strprintf("Submit votes failed: %s", failReason));
StakeBlocks(1), SyncWithValidationInterfaceQueue();
auto vs = gov::Governance::instance().getVotes(proposal.getHash());
BOOST_CHECK_MESSAGE(vs.size() == 1, strprintf("Expecting 1 vote, found %u", vs.size()));
}
// 2) Spend vote
{
CTransactionRef tx;
bool sent = sendToAddress(otherwallet.get(), newDest, otherwallet->GetBalance()-COIN, tx);
BOOST_CHECK_MESSAGE(sent, "Spending vote utxos failed");
StakeBlocks(1), SyncWithValidationInterfaceQueue();
auto vs = gov::Governance::instance().getVotes(proposal.getHash());
BOOST_CHECK_MESSAGE(vs.empty(), strprintf("Expecting 0 votes, found %u", vs.size()));
auto pvs = gov::Governance::instance().getVotes(proposal.getHash(), true);
BOOST_CHECK_MESSAGE(pvs.size() == 1 && pvs[0].spent(), "Expecting 1 spent vote");
}
// 3) Simulate block invalidation/disconnect and make sure votes are properly unspent
{
CValidationState state;
BOOST_CHECK_MESSAGE(InvalidateBlock(state, *params, chainActive.Tip(), false), "Failed to invalidate the block with spent vote");
ActivateBestChain(state, *params); SyncWithValidationInterfaceQueue();
auto vs = gov::Governance::instance().getVotes(proposal.getHash());
BOOST_CHECK_MESSAGE(vs.size() == 1, strprintf("Expecting 1 vote, found %u", vs.size()));
auto pvs = gov::Governance::instance().getVotes(proposal.getHash());
BOOST_CHECK_MESSAGE(pvs.size() == 1 && !pvs[0].spent(), "Expecting 1 unspent vote");
}
// 4) Check vote is valid after new block
{
StakeBlocks(1), SyncWithValidationInterfaceQueue();
auto vs = gov::Governance::instance().getVotes(proposal.getHash());
BOOST_CHECK_MESSAGE(vs.size() == 1, strprintf("Expecting 1 vote, found %u", vs.size()));
auto pvs = gov::Governance::instance().getVotes(proposal.getHash());
BOOST_CHECK_MESSAGE(pvs.size() == 1 && !pvs[0].spent(), "Expecting 1 unspent vote");
}
// Clean up
UnregisterValidationInterface(otherwallet.get());
otherwallet.reset();
cleanup(resetBlocks, wallet.get());
ReloadWallet();
}
UnregisterValidationInterface(&gov::Governance::instance());
cleanup(chainActive.Height(), wallet.get());
ReloadWallet();
}
BOOST_FIXTURE_TEST_CASE(governance_tests_votes_changescutoff, TestChainPoS)
{
gArgs.ForceSetArg("-maxtxfee", "500000000");
RegisterValidationInterface(&gov::Governance::instance());
auto *params = (CChainParams*)&Params();
params->consensus.voteMinUtxoAmount = 20*COIN;
params->consensus.voteBalance = 200*COIN;
const auto & consensus = params->GetConsensus();
CTxDestination dest(coinbaseKey.GetPubKey().GetID());
std::vector<COutput> coins;
{
LOCK2(cs_main, wallet->cs_wallet);
wallet->AvailableCoins(*locked_chain, coins);
}
BOOST_CHECK_MESSAGE(!coins.empty(), "Vote tests require available coins");
const gov::VinHash & vinHash = gov::makeVinHash(coins.front().GetInputCoin().outpoint);
std::set<gov::VinHash> vinHashes{vinHash};
// Check normal proposal
gov::Proposal proposal("Test proposal", nextSuperblock(chainActive.Height(), consensus.superblock), 3000*COIN,
EncodeDestination(dest), "https://forum.blocknet.co", "Short description");
BOOST_CHECK_MESSAGE(proposal.isValid(consensus), "Basic proposal should be valid");
// Casting change votes inside voting cutoff period should not influence the tally
{
const auto resetBlocks = chainActive.Height();
CKey key; key.MakeNewKey(true);
const auto & newDest = GetDestinationForKey(key.GetPubKey(), OutputType::LEGACY);
bool firstRun;
auto otherwallet = std::make_shared<CWallet>(*chain, WalletLocation(), WalletDatabase::CreateMock());
otherwallet->LoadWallet(firstRun);
AddKey(*otherwallet, key);
otherwallet->SetBroadcastTransactions(true);
rescanWallet(otherwallet.get());
RegisterValidationInterface(otherwallet.get());
// Vote inputs
{
CTransactionRef tx;
CTransactionRef txVoteInput;
bool sent = sendToAddress(wallet.get(), newDest, 200 * COIN, tx)
&& sendToAddress(wallet.get(), newDest, 3 * COIN, txVoteInput);
BOOST_CHECK_MESSAGE(sent, "Send to another address failed");
}
// Create proposal
{
CTransactionRef ptx; // proposal tx
std::string failReason;
gov::SubmitProposal(proposal, {wallet}, consensus, ptx, g_connman.get(), &failReason);
StakeBlocks(1), SyncWithValidationInterfaceQueue();
}
// 1) Vote on a proposal
gov::ProposalVote proposalVoteYes{proposal, gov::YES};
{
std::vector<CTransactionRef> txs;
std::string failReason;
bool success = gov::SubmitVotes(std::vector<gov::ProposalVote>{proposalVoteYes}, {otherwallet}, consensus, txs, g_connman.get(), &failReason);
BOOST_REQUIRE_MESSAGE(success, strprintf("Submit votes failed: %s", failReason));
StakeBlocks(1), SyncWithValidationInterfaceQueue();
auto vs = gov::Governance::instance().getVotes(proposal.getHash());
BOOST_CHECK_MESSAGE(vs.size() == 1, strprintf("Expecting 1 vote, found %u", vs.size()));
}
// 2) Stake to cutoff period
StakeBlocks(gov::NextSuperblock(consensus, chainActive.Height()) - consensus.votingCutoff), SyncWithValidationInterfaceQueue();
// 3) Attempt to change vote
{
gov::ProposalVote proposalVoteNo{proposal, gov::NO};
std::vector<CTransactionRef> txs;
std::string failReason;
bool success = gov::SubmitVotes(std::vector<gov::ProposalVote>{proposalVoteNo}, {otherwallet}, consensus, txs, g_connman.get(), &failReason);
BOOST_REQUIRE_MESSAGE(success, strprintf("Change vote failed: %s", failReason));
StakeBlocks(1), SyncWithValidationInterfaceQueue();
auto vs = gov::Governance::instance().getVotes(proposal.getHash());
BOOST_REQUIRE_MESSAGE(vs.size() == 1, strprintf("Expecting 1 vote, found %u", vs.size()));
BOOST_CHECK_MESSAGE(vs[0].getVote() == proposalVoteYes.vote, strprintf("Expecting vote to remain unchanged in cutoff period"));
}
// Clean up
UnregisterValidationInterface(otherwallet.get());
otherwallet.reset();
cleanup(resetBlocks, wallet.get());
ReloadWallet();
}
UnregisterValidationInterface(&gov::Governance::instance());
cleanup(chainActive.Height(), wallet.get());
ReloadWallet();
}
BOOST_FIXTURE_TEST_CASE(governance_tests_undo_submissions, TestChainPoS)
{
gArgs.ForceSetArg("-maxtxfee", "500000000");
RegisterValidationInterface(&gov::Governance::instance());
auto *params = (CChainParams*)&Params();
params->consensus.voteMinUtxoAmount = 20*COIN;
params->consensus.voteBalance = 200*COIN;
const auto & consensus = params->GetConsensus();
CTxDestination dest(coinbaseKey.GetPubKey().GetID());
std::string failReason;
// Check normal proposal
gov::Proposal proposal("Test Proposal Undo", nextSuperblock(chainActive.Height(), consensus.superblock), 3000*COIN,
EncodeDestination(dest), "https://forum.blocknet.co", "");
BOOST_REQUIRE_MESSAGE(proposal.isValid(consensus), "Proposal should be valid");
CTransactionRef ptx; // proposal tx
gov::SubmitProposal(proposal, {wallet}, consensus, ptx, g_connman.get(), &failReason);
StakeBlocks(1), SyncWithValidationInterfaceQueue();
BOOST_REQUIRE_MESSAGE(gov::Governance::instance().getProposal(proposal.getHash()).isValid(consensus), "Proposal should be valid");
// Setup other wallet to cast votes from
CKey key; key.MakeNewKey(true);
const auto & voteDest = GetDestinationForKey(key.GetPubKey(), OutputType::LEGACY);
// Submit the vote with spent utxo
auto otherwallet = std::make_shared<CWallet>(*chain, WalletLocation(), WalletDatabase::CreateMock());
bool firstRun; otherwallet->LoadWallet(firstRun);
AddKey(*otherwallet, key);
otherwallet->SetBroadcastTransactions(true);
rescanWallet(otherwallet.get());
RegisterValidationInterface(otherwallet.get());
std::vector<std::pair<CTxOut,COutPoint>> recvouts;
// Send vote coin to otherwallet
{
CTransactionRef sendtx;
auto recipients = std::vector<CRecipient>{