-
-
Notifications
You must be signed in to change notification settings - Fork 356
/
Copy pathstate.cpp
1417 lines (1214 loc) · 46.6 KB
/
state.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "state.h"
#include "../validation.h"
#include "../batchproof_container.h"
namespace spark {
static CSparkState sparkState;
static bool CheckLTag(
CValidationState &state,
CSparkTxInfo *sparkTxInfo,
const GroupElement& lTag,
int nHeight,
bool fConnectTip) {
// check for Spark transaction in this block as well
if (sparkTxInfo &&
!sparkTxInfo->fInfoIsComplete &&
sparkTxInfo->spentLTags.find(lTag) != sparkTxInfo->spentLTags.end())
return state.DoS(0, error("CTransaction::CheckTransaction() : two or more spends with same linking tag in the same block"));
// check for used linking tags in state
if (sparkState.IsUsedLTag(lTag)) {
// Proceed with checks ONLY if we're accepting tx into the memory pool or connecting block to the existing blockchain
if (nHeight == INT_MAX || fConnectTip) {
return state.DoS(0, error("CTransaction::CheckTransaction() : The Spark coin has been used"));
}
}
return true;
}
bool BuildSparkStateFromIndex(CChain *chain) {
for (CBlockIndex *blockIndex = chain->Genesis(); blockIndex; blockIndex=chain->Next(blockIndex))
{
sparkState.AddBlock(blockIndex);
}
// DEBUG
LogPrintf(
"Latest ID for Spark coin group %d\n",
sparkState.GetLatestCoinID());
return true;
}
// CSparkTxInfo
void CSparkTxInfo::Complete() {
// We need to sort mints lexicographically by serialized value of pubCoin. That's the way old code
// works, we need to stick to it.
sort(mints.begin(), mints.end(),
[](decltype(mints)::const_reference m1, decltype(mints)::const_reference m2)->bool {
CDataStream ds1(SER_DISK, CLIENT_VERSION), ds2(SER_DISK, CLIENT_VERSION);
ds1 << m1;
ds2 << m2;
return ds1.str() < ds2.str();
});
// Mark this info as complete
fInfoIsComplete = true;
}
bool IsSparkAllowed()
{
LOCK(cs_main);
return IsSparkAllowed(chainActive.Height());
}
bool IsSparkAllowed(int height)
{
return height >= ::Params().GetConsensus().nSparkStartBlock;
}
unsigned char GetNetworkType() {
if (::Params().GetConsensus().IsMain())
return ADDRESS_NETWORK_MAINNET;
else if (::Params().GetConsensus().IsTestnet())
return ADDRESS_NETWORK_TESTNET;
else if (::Params().GetConsensus().IsDevnet())
return ADDRESS_NETWORK_DEVNET;
else
return ADDRESS_NETWORK_REGTEST;
}
/*
* Util funtions
*/
size_t CountCoinInBlock(CBlockIndex *index, int id) {
return index->sparkMintedCoins.count(id) > 0
? index->sparkMintedCoins[id].size() : 0;
}
std::vector<unsigned char> GetAnonymitySetHash(CBlockIndex *index, int group_id, bool generation = false) {
std::vector<unsigned char> out_hash;
CSparkState::SparkCoinGroupInfo coinGroup;
if (!sparkState.GetCoinGroupInfo(group_id, coinGroup))
return out_hash;
if ((coinGroup.firstBlock == coinGroup.lastBlock && generation) || (coinGroup.nCoins == 0))
return out_hash;
while (index != coinGroup.firstBlock) {
if (index->sparkSetHash.count(group_id) > 0) {
out_hash = index->sparkSetHash[group_id];
break;
}
index = index->pprev;
}
return out_hash;
}
void ParseSparkMintTransaction(const std::vector<CScript>& scripts, MintTransaction& mintTransaction)
{
std::vector<CDataStream> serializedCoins;
for (const auto& script : scripts) {
if (!script.IsSparkMint())
throw std::invalid_argument("Script is not a Spark mint");
std::vector<unsigned char> serialized(script.begin() + 1, script.end());
size_t size = spark::Coin::memoryRequired() + 8; // 8 is the size of uint64_t
if (serialized.size() < size) {
throw std::invalid_argument("Script is not a valid Spark mint");
}
CDataStream stream(
std::vector<unsigned char>(serialized.begin(), serialized.end()),
SER_NETWORK,
PROTOCOL_VERSION
);
serializedCoins.push_back(stream);
}
try {
mintTransaction.setMintTransaction(serializedCoins);
} catch (const std::exception &) {
throw std::invalid_argument("Unable to deserialize Spark mint transaction");
}
}
void ParseSparkMintCoin(const CScript& script, spark::Coin& txCoin)
{
if (!script.IsSparkMint() && !script.IsSparkSMint())
throw std::invalid_argument("Script is not a Spark mint");
if (script.size() < 213) {
throw std::invalid_argument("Script is not a valid Spark Mint");
}
std::vector<unsigned char> serialized(script.begin() + 1, script.end());
CDataStream stream(
std::vector<unsigned char>(serialized.begin(), serialized.end()),
SER_NETWORK,
PROTOCOL_VERSION
);
try {
stream >> txCoin;
} catch (const std::exception &) {
throw std::invalid_argument("Unable to deserialize Spark mint");
}
}
spark::SpendTransaction ParseSparkSpend(const CTransaction &tx)
{
if (tx.vin.size() != 1 || tx.vin[0].scriptSig.size() < 1) {
throw CBadTxIn();
}
CDataStream serialized(SER_NETWORK, PROTOCOL_VERSION);
if (tx.vin[0].scriptSig[0] == OP_SPARKSPEND && tx.nVersion >= 3 && tx.nType == TRANSACTION_SPARK) {
serialized.write((const char *)tx.vExtraPayload.data(), tx.vExtraPayload.size());
}
else {
throw CBadTxIn();
}
const spark::Params* params = spark::Params::get_default();
spark::SpendTransaction spendTransaction(params);
serialized >> spendTransaction;
return std::move(spendTransaction);
}
std::vector<GroupElement> GetSparkUsedTags(const CTransaction &tx)
{
const spark::Params* params = spark::Params::get_default();
spark::SpendTransaction spendTransaction(params);
try {
spendTransaction = ParseSparkSpend(tx);
} catch (const std::exception &) {
return std::vector<GroupElement>();
}
return spendTransaction.getUsedLTags();
}
std::vector<spark::Coin> GetSparkMintCoins(const CTransaction &tx)
{
std::vector<spark::Coin> result;
if (tx.IsSparkTransaction()) {
std::vector<unsigned char> serial_context = getSerialContext(tx);
for (const auto& vout : tx.vout) {
const auto& script = vout.scriptPubKey;
if (script.IsSparkMint() || script.IsSparkSMint()) {
try {
spark::Coin coin(Params::get_default());
ParseSparkMintCoin(script, coin);
coin.setSerialContext(serial_context);
result.push_back(coin);
} catch (const std::exception &) {
//Continue
}
}
}
}
return result;
}
size_t GetSpendInputs(const CTransaction &tx) {
return tx.IsSparkSpend() ?
GetSparkUsedTags(tx).size() : 0;
}
CAmount GetSpendTransparentAmount(const CTransaction& tx) {
CAmount result = 0;
if (!tx.IsSparkSpend())
return 0;
for (const CTxOut &txout : tx.vout)
result += txout.nValue;
return result;
}
/**
* Connect a new ZCblock to chainActive. pblock is either NULL or a pointer to a CBlock
* corresponding to pindexNew, to bypass loading it again from disk.
*/
bool ConnectBlockSpark(
CValidationState &state,
const CChainParams &chainparams,
CBlockIndex *pindexNew,
const CBlock *pblock,
bool fJustCheck) {
// Add spark transaction information to index
if (pblock && pblock->sparkTxInfo) {
if (!fJustCheck) {
pindexNew->sparkMintedCoins.clear();
pindexNew->spentLTags.clear();
pindexNew->sparkSetHash.clear();
}
if (!CheckSparkBlock(state, *pblock)) {
return false;
}
BOOST_FOREACH(auto& lTag, pblock->sparkTxInfo->spentLTags) {
if (!CheckLTag(
state,
pblock->sparkTxInfo.get(),
lTag.first,
pindexNew->nHeight,
true /* fConnectTip */
)) {
return false;
}
}
if (!fJustCheck) {
BOOST_FOREACH (auto& lTag, pblock->sparkTxInfo->spentLTags) {
pindexNew->spentLTags.insert(lTag);
sparkState.AddSpend(lTag.first, lTag.second);
}
if (GetBoolArg("-mobile", false)) {
BOOST_FOREACH (auto& lTag, pblock->sparkTxInfo->ltagTxhash) {
pindexNew->ltagTxhash.insert(lTag);
sparkState.AddLTagTxHash(lTag.first, lTag.second);
}
}
}
else {
return true;
}
const auto& params = ::Params().GetConsensus();
CHash256 hash;
bool updateHash = false;
if (!pblock->sparkTxInfo->mints.empty()) {
sparkState.AddMintsToStateAndBlockIndex(pindexNew, pblock);
int latestCoinId = sparkState.GetLatestCoinID();
// add coins into hasher, for generating set hash
updateHash = true;
// get previous hash of the set, if there is no such, don't write anything
std::vector<unsigned char> prev_hash = GetAnonymitySetHash(pindexNew->pprev, latestCoinId, true);
if (!prev_hash.empty())
hash.Write(prev_hash.data(), 32);
else {
if (latestCoinId > 1) {
prev_hash = GetAnonymitySetHash(pindexNew->pprev, latestCoinId - 1, true);
hash.Write(prev_hash.data(), 32);
}
}
for (auto &coin : pindexNew->sparkMintedCoins[latestCoinId]) {
CDataStream serializedCoin(SER_NETWORK, 0);
serializedCoin << coin;
std::vector<unsigned char> data(serializedCoin.begin(), serializedCoin.end());
hash.Write(data.data(), data.size());
}
}
// generate hash if we need it
if (updateHash) {
unsigned char hash_result[CSHA256::OUTPUT_SIZE];
hash.Finalize(hash_result);
auto &out_hash = pindexNew->sparkSetHash[sparkState.GetLatestCoinID()];
out_hash.clear();
out_hash.insert(out_hash.begin(), std::begin(hash_result), std::end(hash_result));
}
}
else if (!fJustCheck) {
sparkState.AddBlock(pindexNew);
}
return true;
}
void RemoveSpendReferencingBlock(CTxMemPool& pool, CBlockIndex* blockIndex) {
LOCK2(cs_main, pool.cs);
std::vector<CTransaction> txn_to_remove;
for (CTxMemPool::txiter mi = pool.mapTx.begin(); mi != pool.mapTx.end(); ++mi) {
const CTransaction& tx = mi->GetTx();
if (tx.IsSparkSpend()) {
// Run over all the inputs, check if their CoinGroup block hash is equal to
// block removed. If any one is equal, remove txn from mempool.
for (const CTxIn& txin : tx.vin) {
if (txin.scriptSig.IsSparkSpend()) {
std::unique_ptr<spark::SpendTransaction> sparkSpend;
try {
sparkSpend = std::make_unique<spark::SpendTransaction>(ParseSparkSpend(tx));
}
catch (const std::exception &) {
txn_to_remove.push_back(tx);
break;
}
const std::map<uint64_t, uint256>& coinGroupIdAndBlockHash = sparkSpend->getBlockHashes();
for(const auto& idAndHash : coinGroupIdAndBlockHash) {
if (idAndHash.second == blockIndex->GetBlockHash()) {
// Do not remove transaction immediately, that will invalidate iterator mi.
txn_to_remove.push_back(tx);
break;
}
}
}
}
}
}
for (const CTransaction& tx: txn_to_remove) {
// Remove txn from mempool.
pool.removeRecursive(tx);
LogPrintf("DisconnectTipSpark: removed spark spend which referenced a removed blockchain tip.");
}
}
void DisconnectTipSpark(CBlock& block, CBlockIndex *pindexDelete) {
sparkState.RemoveBlock(pindexDelete);
// Also remove from mempool spends that reference given block hash.
RemoveSpendReferencingBlock(mempool, pindexDelete);
RemoveSpendReferencingBlock(txpools.getStemTxPool(), pindexDelete);
}
bool CheckSparkBlock(CValidationState &state, const CBlock& block) {
auto& consensus = ::Params().GetConsensus();
size_t blockSpendsValue = 0;
for (const auto& tx : block.vtx) {
auto txSpendsValue = GetSpendTransparentAmount(*tx);
if (txSpendsValue > consensus.nMaxValueSparkSpendPerTransaction) {
return state.DoS(100, false, REJECT_INVALID,
"bad-txns-spark-spend-invalid");
}
blockSpendsValue += txSpendsValue;
}
if (blockSpendsValue > consensus.nMaxValueSparkSpendPerBlock) {
return state.DoS(100, false, REJECT_INVALID,
"bad-txns-spark-spend-invalid");
}
return true;
}
bool CheckSparkMintTransaction(
const std::vector<CTxOut>& txOuts,
CValidationState &state,
uint256 hashTx,
bool fStatefulSigmaCheck,
CSparkTxInfo* sparkTxInfo) {
LogPrintf("CheckSparkMintTransaction txHash = %s\n", hashTx.GetHex());
const spark::Params* params = spark::Params::get_default();
std::vector<CScript> scripts;
for (const auto& txOut : txOuts) {
scripts.push_back(txOut.scriptPubKey);
}
MintTransaction mintTransaction(params);
try {
ParseSparkMintTransaction(scripts, mintTransaction);
} catch (std::invalid_argument&) {
return state.DoS(100,
false,
PUBCOIN_NOT_VALIDATE,
"CTransaction::CheckTransaction() : SparkMint parsing failure.");
}
//checking whether MintTransaction is valid
if (!mintTransaction.verify()) {
return state.DoS(100,
false,
PUBCOIN_NOT_VALIDATE,
"CheckSparkMintTransaction : mintTransaction verification failed");
}
std::vector<Coin> coins;
mintTransaction.getCoins(coins);
if (coins.size() != txOuts.size())
return state.DoS(100,
false,
PUBCOIN_NOT_VALIDATE,
"CheckSparkMintTransaction : mintTransaction parsing failed");
for (size_t i = 0; i < coins.size(); i++) {
auto& coin = coins[i];
if (coin.v != txOuts[i].nValue)
return state.DoS(100,
false,
PUBCOIN_NOT_VALIDATE,
"CheckSparkMintTransaction : mintTransaction failed, wrong amount");
// if (coin.v > ::Params().GetConsensus().nMaxValueLelantusMint)
// return state.DoS(100,
// false,
// REJECT_INVALID,
// "CTransaction::CheckTransaction() : Spark Mint is out of limit.");
if (sparkTxInfo != NULL && !sparkTxInfo->fInfoIsComplete) {
// Update coin list in the info
sparkTxInfo->mints.push_back(coin);
sparkTxInfo->spTransactions.insert(hashTx);
}
}
return true;
}
bool CheckSparkSMintTransaction(
const std::vector<CTxOut>& vout,
CValidationState &state,
uint256 hashTx,
bool fStatefulSigmaCheck,
std::vector<Coin>& out_coins,
CSparkTxInfo* sparkTxInfo) {
LogPrintf("CheckSparkSMintTransaction txHash = %s\n", hashTx.ToString());
for (const auto& out : vout) {
const auto& script = out.scriptPubKey;
if (script.IsSparkSMint()) {
try {
spark::Coin coin(Params::get_default());
ParseSparkMintCoin(script, coin);
out_coins.emplace_back(coin);
} catch (const std::exception &) {
return state.DoS(100,
false,
REJECT_INVALID,
"CTransaction::CheckTransaction() : Spark Mint is invalid.");
}
}
}
for (auto& coin : out_coins) {
if (sparkTxInfo != NULL && !sparkTxInfo->fInfoIsComplete) {
// Update coin list in the info
sparkTxInfo->mints.push_back(coin);
}
}
return true;
}
bool CheckSparkSpendTransaction(
const CTransaction &tx,
CValidationState &state,
uint256 hashTx,
bool isVerifyDB,
int nHeight,
bool isCheckWallet,
bool fStatefulSigmaCheck,
CSparkTxInfo* sparkTxInfo) {
std::unordered_set<GroupElement, spark::CLTagHash> txLTags;
if (tx.vin.size() != 1 || !tx.vin[0].scriptSig.IsSparkSpend()) {
// mixing spark spend input with non-spark inputs is prohibited
return state.DoS(100, false,
REJECT_MALFORMED,
"CheckSparkSpendTransaction: can't mix spark spend input with other tx types or have more than one spend");
}
Consensus::Params const & params = ::Params().GetConsensus();
int height = nHeight == INT_MAX ? chainActive.Height()+1 : nHeight;
if (!isVerifyDB) {
if (height >= params.nSparkStartBlock) {
// data should be moved to v3 payload
if (tx.nVersion < 3 || tx.nType != TRANSACTION_SPARK)
return state.DoS(100, false, NSEQUENCE_INCORRECT,
"CheckSparkSpendTransaction: spark data should reside in transaction payload");
}
}
std::unique_ptr<spark::SpendTransaction> spend;
try {
spend = std::make_unique<spark::SpendTransaction>(ParseSparkSpend(tx));
}
catch (CBadTxIn&) {
return state.DoS(100,
false,
REJECT_MALFORMED,
"CheckSparkSpendTransaction: invalid spend transaction");
}
catch (const std::exception &) {
return state.DoS(100,
false,
REJECT_MALFORMED,
"CheckSparkSpendTransaction: failed to deserialize spend");
}
uint256 txHashForMetadata;
// Obtain the hash of the transaction sans the Spark part
CMutableTransaction txTemp = tx;
txTemp.vExtraPayload.clear();
for (auto itr = txTemp.vout.begin(); itr < txTemp.vout.end(); ++itr) {
if (itr->scriptPubKey.IsSparkSMint()) {
txTemp.vout.erase(itr);
--itr;
}
}
txHashForMetadata = txTemp.GetHash();
LogPrintf("CheckSparkSpendTransaction: tx metadata hash=%s\n", txHashForMetadata.ToString());
if (!fStatefulSigmaCheck) {
return true;
}
bool passVerify = false;
uint64_t Vout = 0;
std::size_t private_num = 0;
for (const CTxOut &txout : tx.vout) {
const auto& script = txout.scriptPubKey;
if (!script.empty() && script.IsSparkSMint()) {
private_num++;
} else if (script.IsSparkMint() ||
script.IsLelantusMint() ||
script.IsLelantusJMint() ||
script.IsSigmaMint()) {
return false;
} else {
Vout += txout.nValue;
}
}
if (private_num > ::Params().GetConsensus().nMaxSparkOutLimitPerTx)
return false;
std::vector<Coin> out_coins;
out_coins.reserve(private_num);
if (!CheckSparkSMintTransaction(tx.vout, state, hashTx, fStatefulSigmaCheck, out_coins, sparkTxInfo))
return false;
spend->setOutCoins(out_coins);
std::unordered_map<uint64_t, std::vector<Coin>> cover_sets;
std::unordered_map<uint64_t, CoverSetData> cover_set_data;
const auto idAndBlockHashes = spend->getBlockHashes();
BatchProofContainer* batchProofContainer = BatchProofContainer::get_instance();
bool useBatching = batchProofContainer->fCollectProofs && !isVerifyDB && !isCheckWallet && sparkTxInfo && !sparkTxInfo->fInfoIsComplete;
for (const auto& idAndHash : idAndBlockHashes) {
CSparkState::SparkCoinGroupInfo coinGroup;
if (!sparkState.GetCoinGroupInfo(idAndHash.first, coinGroup))
return state.DoS(100, false, NO_MINT_ZEROCOIN,
"CheckSparkSpendTransaction: Error: no coins were minted with such parameters");
CBlockIndex *index = coinGroup.lastBlock;
// find index for block with hash of accumulatorBlockHash or set index to the coinGroup.firstBlock if not found
while (index != coinGroup.firstBlock && index->GetBlockHash() != idAndHash.second)
index = index->pprev;
// take the hash from last block of anonymity set
std::vector<unsigned char> set_hash = GetAnonymitySetHash(index, idAndHash.first);
std::vector<Coin> cover_set;
cover_set.reserve(coinGroup.nCoins);
std::size_t set_size = 0;
// Build a vector with all the public coins with given id before
// the block on which the spend occurred.
// This list of public coins is required by function "Verify" of spend.
while (true) {
int id = 0;
if (CountCoinInBlock(index, idAndHash.first)) {
id = idAndHash.first;
} else if (CountCoinInBlock(index, idAndHash.first - 1)) {
id = idAndHash.first - 1;
}
if (id) {
if (index->sparkMintedCoins.count(id) > 0) {
BOOST_FOREACH(
const auto& coin,
index->sparkMintedCoins[id]) {
set_size++;
if (!useBatching)
cover_set.push_back(coin);
}
}
}
if (index == coinGroup.firstBlock)
break;
index = index->pprev;
}
CoverSetData setData;
setData.cover_set_size = set_size;
if (!set_hash.empty())
setData.cover_set_representation = set_hash;
setData.cover_set_representation.insert(setData.cover_set_representation.end(), txHashForMetadata.begin(), txHashForMetadata.end());
cover_sets[idAndHash.first] = std::move(cover_set);
cover_set_data [idAndHash.first] = setData;
}
spend->setCoverSets(cover_set_data);
spend->setVout(Vout);
const std::vector<uint64_t>& ids = spend->getCoinGroupIds();
for (const auto& id : ids) {
if (!cover_sets.count(id) || !cover_set_data.count(id))
return state.DoS(100,
error("CheckSparkSpendTransaction: No cover set found."));
}
// if we are collecting proofs, skip verification and collect proofs
// add proofs into container
if (useBatching) {
passVerify = true;
batchProofContainer->add(*spend);
} else {
try {
passVerify = spark::SpendTransaction::verify(*spend, cover_sets);
} catch (const std::exception &) {
passVerify = false;
}
}
if (passVerify) {
const std::vector<GroupElement>& lTags = spend->getUsedLTags();
if (lTags.size() != ids.size()) {
return state.DoS(100,
error("CheckSparkSpendTransaction: size of lTags and group ids don't match."));
}
// do not check for duplicates in case we've seen exact copy of this tx in this block before
if (!(sparkTxInfo && sparkTxInfo->spTransactions.count(hashTx) > 0)) {
for (size_t i = 0; i < lTags.size(); ++i) {
if (!CheckLTag(state, sparkTxInfo, lTags[i], nHeight, false)) {
LogPrintf("CheckSparkSpendTransaction: lTAg check failed, ltag=%s\n", lTags[i]);
return false;
}
}
}
// check duplicated linking tags in same transaction.
for (const auto &lTag : lTags) {
if (!txLTags.insert(lTag).second) {
return state.DoS(100,
error("CheckSparkSpendTransaction: two or more spends with same linking tag in the same transaction"));
}
}
if (!isVerifyDB && !isCheckWallet) {
// add spend information to the index
if (sparkTxInfo && !sparkTxInfo->fInfoIsComplete) {
for (size_t i = 0; i < lTags.size(); i++) {
sparkTxInfo->spentLTags.insert(std::make_pair(lTags[i], ids[i]));
if (GetBoolArg("-mobile", false)) {
sparkTxInfo->ltagTxhash.insert(std::make_pair(primitives::GetLTagHash(lTags[i]), hashTx));
}
}
}
}
}
else {
LogPrintf("CheckSparkSpendTransaction: verification failed at block %d\n", nHeight);
return false;
}
if (!isVerifyDB && !isCheckWallet) {
if (sparkTxInfo && !sparkTxInfo->fInfoIsComplete) {
sparkTxInfo->spTransactions.insert(hashTx);
}
}
return true;
}
bool CheckSparkTransaction(
const CTransaction &tx,
CValidationState &state,
uint256 hashTx,
bool isVerifyDB,
int nHeight,
bool isCheckWallet,
bool fStatefulSigmaCheck,
CSparkTxInfo* sparkTxInfo)
{
Consensus::Params const & consensus = ::Params().GetConsensus();
bool const allowSpark = IsSparkAllowed();
// Check Spark Mint Transaction
if (allowSpark && !isVerifyDB && tx.IsSparkMint()) {
std::vector<CTxOut> txOuts;
for (const CTxOut &txout : tx.vout) {
if (!txout.scriptPubKey.empty() && txout.scriptPubKey.IsSparkMint()) {
txOuts.push_back(txout);
}
}
if (!txOuts.empty()) {
try {
if (!CheckSparkMintTransaction(txOuts, state, hashTx, fStatefulSigmaCheck, sparkTxInfo)) {
LogPrintf("CheckSparkTransaction::Mint verification failed.\n");
return false;
}
}
catch (const std::exception &x) {
return state.Error(x.what());
}
} else {
return state.DoS(100, false,
REJECT_INVALID,
"bad-txns-mint-invalid");
}
}
// Check Spark Spend
if (tx.IsSparkSpend()) {
if (GetSpendTransparentAmount(tx) > consensus.nMaxValueSparkSpendPerTransaction) {
return state.DoS(100, false,
REJECT_INVALID,
"bad-txns-spend-invalid");
}
if (!isVerifyDB) {
try {
if (!CheckSparkSpendTransaction(
tx, state, hashTx, isVerifyDB, nHeight,
isCheckWallet, fStatefulSigmaCheck, sparkTxInfo)) {
return false;
}
}
catch (const std::exception &x) {
return state.Error(x.what());
}
}
}
return true;
}
uint256 GetTxHashFromCoin(const spark::Coin& coin) {
COutPoint outPoint;
GetOutPoint(outPoint, coin);
return outPoint.hash;
}
bool GetOutPoint(COutPoint& outPoint, const spark::Coin& coin)
{
spark::CSparkState *sparkState = spark::CSparkState::GetState();
auto mintedCoinHeightAndId = sparkState->GetMintedCoinHeightAndId(coin);
int mintHeight = mintedCoinHeightAndId.first;
int coinId = mintedCoinHeightAndId.second;
if (mintHeight==-1 && coinId==-1)
return false;
// get block containing mint
CBlockIndex *mintBlock = chainActive[mintHeight];
CBlock block;
//TODO levon, try to optimize this
if (!ReadBlockFromDisk(block, mintBlock, ::Params().GetConsensus())) {
LogPrintf("can't read block from disk.\n");
return false;
}
return GetOutPointFromBlock(outPoint, coin, block);
}
bool GetOutPoint(COutPoint& outPoint, const uint256& coinHash)
{
spark::Coin coin(Params::get_default());
spark::CSparkState *sparkState = spark::CSparkState::GetState();
if (!sparkState->HasCoinHash(coin, coinHash)) {
return false;
}
return GetOutPoint(outPoint, coin);
}
bool GetOutPointFromBlock(COutPoint& outPoint, const spark::Coin& coin, const CBlock &block) {
spark::Coin txCoin(coin.params);
// cycle transaction hashes, looking for this coin
for (CTransactionRef tx : block.vtx){
uint32_t nIndex = 0;
for (const CTxOut &txout : tx->vout) {
if (txout.scriptPubKey.IsSparkMint() || txout.scriptPubKey.IsSparkSMint()) {
try {
ParseSparkMintCoin(txout.scriptPubKey, txCoin);
}
catch (const std::exception &) {
continue;
}
if (coin == txCoin) {
outPoint = COutPoint(tx->GetHash(), nIndex);
return true;
}
}
nIndex++;
}
}
return false;
}
std::vector<unsigned char> getSerialContext(const CTransaction &tx) {
CDataStream serialContextStream(SER_NETWORK, PROTOCOL_VERSION);
if (tx.IsSparkSpend()) {
try {
spark::SpendTransaction spend = ParseSparkSpend(tx);
serialContextStream << spend.getUsedLTags();
} catch (const std::exception &) {
return std::vector<unsigned char>();
}
} else {
for (auto input: tx.vin) {
input.scriptSig.clear();
serialContextStream << input;
}
}
std::vector<unsigned char> serial_context(serialContextStream.begin(), serialContextStream.end());
return serial_context;
}
static bool CheckSparkSpendTAg(
CValidationState& state,
CSparkTxInfo* sparkTxInfo,
const GroupElement& tag,
int nHeight,
bool fConnectTip) {
// check for spark transaction in this block as well
if (sparkTxInfo &&
!sparkTxInfo->fInfoIsComplete &&
sparkTxInfo->spentLTags.find(tag) != sparkTxInfo->spentLTags.end())
return state.DoS(0, error("CTransaction::CheckTransaction() : two or more spark spends with same tag in the same block"));
// check for used tags in sparkState
if (sparkState.IsUsedLTag(tag)) {
// Proceed with checks ONLY if we're accepting tx into the memory pool or connecting block to the existing blockchain
if (nHeight == INT_MAX || fConnectTip) {
return state.DoS(0, error("CTransaction::CheckTransaction() : The Spark spend tag has been used"));
}
}
return true;
}
/******************************************************************************/
// CSparkState
/******************************************************************************/
CSparkState::CSparkState(
size_t maxCoinInGroup,
size_t startGroupSize)
:
maxCoinInGroup(maxCoinInGroup),
startGroupSize(startGroupSize)
{
Reset();
}
void CSparkState::Reset() {
coinGroups.clear();
latestCoinId = 0;
mintedCoins.clear();
usedLTags.clear();
mintMetaInfo.clear();
spendMetaInfo.clear();
}
std::pair<int, int> CSparkState::GetMintedCoinHeightAndId(const spark::Coin& coin) {
auto coinIt = mintedCoins.find(coin);
if (coinIt != mintedCoins.end()) {
return std::make_pair(coinIt->second.nHeight, coinIt->second.coinGroupId);
}
return std::make_pair(-1, -1);
}
bool CSparkState::HasCoin(const spark::Coin& coin) {
return mintedCoins.find(coin) != mintedCoins.end();
}
bool CSparkState::HasCoinHash(spark::Coin& coin, const uint256& coinHash) {
for (auto it = mintedCoins.begin(); it != mintedCoins.end(); ++it ){
const spark::Coin& coin_ = (*it).first;
if (primitives::GetSparkCoinHash(coin_) == coinHash) {
coin = coin_;
return true;
}
}
return false;
}
bool CSparkState::GetCoinGroupInfo(
int group_id,
SparkCoinGroupInfo& result) {
if (coinGroups.count(group_id) == 0)
return false;
result = coinGroups[group_id];
return true;
}
int CSparkState::GetLatestCoinID() const {
return latestCoinId;
}
bool CSparkState::IsUsedLTag(const GroupElement& lTag) {
return usedLTags.count(lTag) != 0;
}
bool CSparkState::IsUsedLTagHash(GroupElement& lTag, const uint256 &coinLTaglHash) {
for ( auto it = GetSpends().begin(); it != GetSpends().end(); ++it ) {
if (primitives::GetLTagHash(it->first) == coinLTaglHash) {
lTag = it->first;
return true;
}
}
return false;
}
bool CSparkState::CanAddSpendToMempool(const GroupElement& lTag) {
LOCK(mempool.cs);
return !IsUsedLTag(lTag) && !mempool.sparkState.HasLTag(lTag);
}
bool CSparkState::CanAddMintToMempool(const spark::Coin& coin){
LOCK(mempool.cs);
return !HasCoin(coin) && !mempool.sparkState.HasMint(coin);
}
void CSparkState::AddMint(const spark::Coin& coin, const CMintedCoinInfo& coinInfo) {
mintedCoins.insert(std::make_pair(coin, coinInfo));
mintMetaInfo[coinInfo.coinGroupId] += 1;
}
void CSparkState::RemoveMint(const spark::Coin& coin) {
auto iter = mintedCoins.find(coin);
if (iter != mintedCoins.end()) {
mintMetaInfo[iter->second.coinGroupId] -= 1;
mintedCoins.erase(iter);
}
}
void CSparkState::AddMintsToStateAndBlockIndex(
CBlockIndex *index,
const CBlock* pblock) {
std::vector<spark::Coin> blockMints = pblock->sparkTxInfo->mints;
latestCoinId = std::max(1, latestCoinId);
auto &coinGroup = coinGroups[latestCoinId];