-
Notifications
You must be signed in to change notification settings - Fork 129
Expand file tree
/
Copy pathmn_checks.cpp
More file actions
1585 lines (1391 loc) · 63.2 KB
/
Copy pathmn_checks.cpp
File metadata and controls
1585 lines (1391 loc) · 63.2 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) DeFi Blockchain Developers
// Distributed under the MIT software license, see the accompanying
// file LICENSE or http://www.opensource.org/licenses/mit-license.php.
#include <dfi/accountshistory.h>
#include <dfi/consensus/accounts.h>
#include <dfi/consensus/governance.h>
#include <dfi/consensus/icxorders.h>
#include <dfi/consensus/loans.h>
#include <dfi/consensus/masternodes.h>
#include <dfi/consensus/oracles.h>
#include <dfi/consensus/poolpairs.h>
#include <dfi/consensus/proposals.h>
#include <dfi/consensus/smartcontracts.h>
#include <dfi/consensus/tokens.h>
#include <dfi/consensus/vaults.h>
#include <dfi/consensus/xvm.h>
#include <dfi/govvariables/attributes.h>
#include <dfi/mn_checks.h>
#include <dfi/vaulthistory.h>
#include <ffi/ffihelpers.h>
#include <ain_rs_exports.h>
#include <core_io.h>
#include <ffi/cxx.h>
#include <index/txindex.h>
#include <txmempool.h>
#include <validation.h>
#include <algorithm>
CCustomTxMessage customTypeToMessage(CustomTxType txType) {
switch (txType) {
case CustomTxType::CreateMasternode:
return CCreateMasterNodeMessage{};
case CustomTxType::ResignMasternode:
return CResignMasterNodeMessage{};
case CustomTxType::UpdateMasternode:
return CUpdateMasterNodeMessage{};
case CustomTxType::CreateToken:
return CCreateTokenMessage{};
case CustomTxType::UpdateToken:
return CUpdateTokenPreAMKMessage{};
case CustomTxType::UpdateTokenAny:
return CUpdateTokenMessage{};
case CustomTxType::MintToken:
return CMintTokensMessage{};
case CustomTxType::BurnToken:
return CBurnTokensMessage{};
case CustomTxType::CreatePoolPair:
return CCreatePoolPairMessage{};
case CustomTxType::UpdatePoolPair:
return CUpdatePoolPairMessage{};
case CustomTxType::PoolSwap:
return CPoolSwapMessage{};
case CustomTxType::PoolSwapV2:
return CPoolSwapMessageV2{};
case CustomTxType::AddPoolLiquidity:
return CLiquidityMessage{};
case CustomTxType::RemovePoolLiquidity:
return CRemoveLiquidityMessage{};
case CustomTxType::UtxosToAccount:
return CUtxosToAccountMessage{};
case CustomTxType::AccountToUtxos:
return CAccountToUtxosMessage{};
case CustomTxType::AccountToAccount:
return CAccountToAccountMessage{};
case CustomTxType::AnyAccountsToAccounts:
return CAnyAccountsToAccountsMessage{};
case CustomTxType::SmartContract:
return CSmartContractMessage{};
case CustomTxType::FutureSwap:
return CFutureSwapMessage{};
case CustomTxType::SetGovVariable:
return CGovernanceMessage{};
case CustomTxType::SetGovVariableHeight:
return CGovernanceHeightMessage{};
case CustomTxType::AppointOracle:
return CAppointOracleMessage{};
case CustomTxType::RemoveOracleAppoint:
return CRemoveOracleAppointMessage{};
case CustomTxType::UpdateOracleAppoint:
return CUpdateOracleAppointMessage{};
case CustomTxType::SetOracleData:
return CSetOracleDataMessage{};
case CustomTxType::AutoAuthPrep:
return CCustomTxMessageNone{};
case CustomTxType::ICXCreateOrder:
return CICXCreateOrderMessage{};
case CustomTxType::ICXMakeOffer:
return CICXMakeOfferMessage{};
case CustomTxType::ICXSubmitDFCHTLC:
return CICXSubmitDFCHTLCMessage{};
case CustomTxType::ICXSubmitEXTHTLC:
return CICXSubmitEXTHTLCMessage{};
case CustomTxType::ICXClaimDFCHTLC:
return CICXClaimDFCHTLCMessage{};
case CustomTxType::ICXCloseOrder:
return CICXCloseOrderMessage{};
case CustomTxType::ICXCloseOffer:
return CICXCloseOfferMessage{};
case CustomTxType::SetLoanCollateralToken:
return CLoanSetCollateralTokenMessage{};
case CustomTxType::SetLoanToken:
return CLoanSetLoanTokenMessage{};
case CustomTxType::UpdateLoanToken:
return CLoanUpdateLoanTokenMessage{};
case CustomTxType::LoanScheme:
return CLoanSchemeMessage{};
case CustomTxType::DefaultLoanScheme:
return CDefaultLoanSchemeMessage{};
case CustomTxType::DestroyLoanScheme:
return CDestroyLoanSchemeMessage{};
case CustomTxType::Vault:
return CVaultMessage{};
case CustomTxType::CloseVault:
return CCloseVaultMessage{};
case CustomTxType::UpdateVault:
return CUpdateVaultMessage{};
case CustomTxType::DepositToVault:
return CDepositToVaultMessage{};
case CustomTxType::WithdrawFromVault:
return CWithdrawFromVaultMessage{};
case CustomTxType::PaybackWithCollateral:
return CPaybackWithCollateralMessage{};
case CustomTxType::TakeLoan:
return CLoanTakeLoanMessage{};
case CustomTxType::PaybackLoan:
return CLoanPaybackLoanMessage{};
case CustomTxType::PaybackLoanV2:
return CLoanPaybackLoanV2Message{};
case CustomTxType::AuctionBid:
return CAuctionBidMessage{};
case CustomTxType::FutureSwapExecution:
return CCustomTxMessageNone{};
case CustomTxType::FutureSwapRefund:
return CCustomTxMessageNone{};
case CustomTxType::TokenSplit:
return CCustomTxMessageNone{};
case CustomTxType::Reject:
return CCustomTxMessageNone{};
case CustomTxType::CreateCfp:
return CCreateProposalMessage{};
case CustomTxType::CreateVoc:
return CCreateProposalMessage{};
case CustomTxType::Vote:
return CProposalVoteMessage{};
case CustomTxType::ProposalFeeRedistribution:
return CCustomTxMessageNone{};
case CustomTxType::UnsetGovVariable:
return CGovernanceUnsetMessage{};
case CustomTxType::TransferDomain:
return CTransferDomainMessage{};
case CustomTxType::EvmTx:
return CEvmTxMessage{};
case CustomTxType::None:
return CCustomTxMessageNone{};
}
return CCustomTxMessageNone{};
}
template <typename... T>
constexpr bool FalseType = false;
template <typename T>
constexpr bool IsOneOf() {
return false;
}
template <typename T, typename T1, typename... Args>
constexpr bool IsOneOf() {
return std::is_same_v<T, T1> || IsOneOf<T, Args...>();
}
class CCustomMetadataParseVisitor {
uint32_t height;
const Consensus::Params &consensus;
const std::vector<unsigned char> &metadata;
Res IsHardforkEnabled(const uint32_t startHeight) const {
const std::unordered_map<int, std::string> hardforks = {
{consensus.DF1AMKHeight, "called before AMK height" },
{consensus.DF2BayfrontHeight, "called before Bayfront height" },
{consensus.DF4BayfrontGardensHeight, "called before Bayfront Gardens height" },
{consensus.DF8EunosHeight, "called before Eunos height" },
{consensus.DF10EunosPayaHeight, "called before EunosPaya height" },
{consensus.DF11FortCanningHeight, "called before FortCanning height" },
{consensus.DF14FortCanningHillHeight, "called before FortCanningHill height" },
{consensus.DF15FortCanningRoadHeight, "called before FortCanningRoad height" },
{consensus.DF19FortCanningEpilogueHeight, "called before FortCanningEpilogue height"},
{consensus.DF20GrandCentralHeight, "called before GrandCentral height" },
{consensus.DF22MetachainHeight, "called before Metachain height" },
};
if (startHeight && height < startHeight) {
auto it = hardforks.find(startHeight);
assert(it != hardforks.end());
return Res::Err(it->second);
}
return Res::Ok();
}
public:
CCustomMetadataParseVisitor(uint32_t height,
const Consensus::Params &consensus,
const std::vector<unsigned char> &metadata)
: height(height),
consensus(consensus),
metadata(metadata) {}
template <typename T>
Res EnabledAfter() const {
if constexpr (IsOneOf<T,
CCreateTokenMessage,
CUpdateTokenPreAMKMessage,
CUtxosToAccountMessage,
CAccountToUtxosMessage,
CAccountToAccountMessage,
CMintTokensMessage>()) {
return IsHardforkEnabled(consensus.DF1AMKHeight);
} else if constexpr (IsOneOf<T,
CUpdateTokenMessage,
CPoolSwapMessage,
CLiquidityMessage,
CRemoveLiquidityMessage,
CCreatePoolPairMessage,
CUpdatePoolPairMessage,
CGovernanceMessage>()) {
return IsHardforkEnabled(consensus.DF2BayfrontHeight);
} else if constexpr (IsOneOf<T,
CAppointOracleMessage,
CRemoveOracleAppointMessage,
CUpdateOracleAppointMessage,
CSetOracleDataMessage,
CICXCreateOrderMessage,
CICXMakeOfferMessage,
CICXSubmitDFCHTLCMessage,
CICXSubmitEXTHTLCMessage,
CICXClaimDFCHTLCMessage,
CICXCloseOrderMessage,
CICXCloseOfferMessage>()) {
return IsHardforkEnabled(consensus.DF8EunosHeight);
} else if constexpr (IsOneOf<T,
CPoolSwapMessageV2,
CLoanSetCollateralTokenMessage,
CLoanSetLoanTokenMessage,
CLoanUpdateLoanTokenMessage,
CLoanSchemeMessage,
CDefaultLoanSchemeMessage,
CDestroyLoanSchemeMessage,
CVaultMessage,
CCloseVaultMessage,
CUpdateVaultMessage,
CDepositToVaultMessage,
CWithdrawFromVaultMessage,
CLoanTakeLoanMessage,
CLoanPaybackLoanMessage,
CAuctionBidMessage,
CGovernanceHeightMessage>()) {
return IsHardforkEnabled(consensus.DF11FortCanningHeight);
} else if constexpr (IsOneOf<T, CAnyAccountsToAccountsMessage>()) {
return IsHardforkEnabled(consensus.DF4BayfrontGardensHeight);
} else if constexpr (IsOneOf<T, CSmartContractMessage>()) {
return IsHardforkEnabled(consensus.DF14FortCanningHillHeight);
} else if constexpr (IsOneOf<T, CLoanPaybackLoanV2Message, CFutureSwapMessage>()) {
return IsHardforkEnabled(consensus.DF15FortCanningRoadHeight);
} else if constexpr (IsOneOf<T, CPaybackWithCollateralMessage>()) {
return IsHardforkEnabled(consensus.DF19FortCanningEpilogueHeight);
} else if constexpr (IsOneOf<T,
CUpdateMasterNodeMessage,
CBurnTokensMessage,
CCreateProposalMessage,
CProposalVoteMessage,
CGovernanceUnsetMessage>()) {
return IsHardforkEnabled(consensus.DF20GrandCentralHeight);
} else if constexpr (IsOneOf<T, CTransferDomainMessage, CEvmTxMessage>()) {
return IsHardforkEnabled(consensus.DF22MetachainHeight);
} else if constexpr (IsOneOf<T, CCreateMasterNodeMessage, CResignMasterNodeMessage>()) {
return Res::Ok();
} else {
static_assert(FalseType<T>, "Unhandled type");
}
}
template <typename T>
Res DisabledAfter() const {
if constexpr (IsOneOf<T, CUpdateTokenPreAMKMessage>()) {
return IsHardforkEnabled(consensus.DF2BayfrontHeight) ? Res::Err("called after Bayfront height")
: Res::Ok();
}
return Res::Ok();
}
template <typename T>
Res operator()(T &obj) const {
auto res = EnabledAfter<T>();
if (!res) {
return res;
}
res = DisabledAfter<T>();
if (!res) {
return res;
}
CDataStream ss(metadata, SER_NETWORK, PROTOCOL_VERSION);
ss >> obj;
if (!ss.empty()) {
return Res::Err("deserialization failed: excess %d bytes", ss.size());
}
return Res::Ok();
}
Res operator()(CCustomTxMessageNone &) const { return Res::Ok(); }
};
// -- -- -- -- -- -- -- -DONE
class CCustomTxApplyVisitor {
BlockContext &blockCtx;
const TransactionContext &txCtx;
template <typename T, typename T1, typename... Args>
Res ConsensusHandler(const T &obj) const {
static_assert(std::is_base_of_v<CCustomTxVisitor, T1>, "CCustomTxVisitor base required");
if constexpr (std::is_invocable_v<T1, T>) {
return T1{blockCtx, txCtx}(obj);
} else if constexpr (sizeof...(Args) != 0) {
return ConsensusHandler<T, Args...>(obj);
} else {
static_assert(FalseType<T>, "Unhandled type");
}
return Res::Err("(%s): Unhandled type", __func__);
}
public:
CCustomTxApplyVisitor(BlockContext &blockCtx, const TransactionContext &txCtx)
: blockCtx(blockCtx),
txCtx(txCtx) {}
template <typename T>
Res operator()(const T &obj) const {
return ConsensusHandler<T,
CAccountsConsensus,
CGovernanceConsensus,
CICXOrdersConsensus,
CLoansConsensus,
CMasternodesConsensus,
COraclesConsensus,
CPoolPairsConsensus,
CProposalsConsensus,
CSmartContractsConsensus,
CTokensConsensus,
CVaultsConsensus,
CXVMConsensus>(obj);
}
Res operator()(const CCustomTxMessageNone &) const { return Res::Ok(); }
};
Res CustomMetadataParse(uint32_t height,
const Consensus::Params &consensus,
const std::vector<unsigned char> &metadata,
CCustomTxMessage &txMessage) {
try {
return std::visit(CCustomMetadataParseVisitor(height, consensus, metadata), txMessage);
} catch (const std::exception &e) {
return Res::Err(e.what());
} catch (...) {
return Res::Err("%s unexpected error", __func__);
}
}
bool IsDisabledTx(uint32_t height, CustomTxType type, const Consensus::Params &consensus) {
// All the heights that are involved in disabled Txs
auto fortCanningParkHeight = static_cast<uint32_t>(consensus.DF13FortCanningParkHeight);
auto fortCanningHillHeight = static_cast<uint32_t>(consensus.DF14FortCanningHillHeight);
if (height < fortCanningParkHeight) {
return false;
}
// For additional safety, since some APIs do block + 1 calc
if (height == fortCanningHillHeight || height == fortCanningHillHeight - 1) {
switch (type) {
case CustomTxType::TakeLoan:
case CustomTxType::PaybackLoan:
case CustomTxType::DepositToVault:
case CustomTxType::WithdrawFromVault:
case CustomTxType::UpdateVault:
return true;
default:
break;
}
}
return false;
}
bool IsDisabledTx(uint32_t height, const CTransaction &tx, const Consensus::Params &consensus) {
TBytes dummy;
auto txType = GuessCustomTxType(tx, dummy);
return IsDisabledTx(height, txType, consensus);
}
Res CustomTxVisit(const CCustomTxMessage &txMessage, BlockContext &blockCtx, const TransactionContext &txCtx) {
const auto &consensus = txCtx.GetConsensus();
const auto height = txCtx.GetHeight();
const auto time = txCtx.GetTime();
const auto &tx = txCtx.GetTransaction();
if (IsDisabledTx(height, tx, consensus)) {
return Res::ErrCode(CustomTxErrCodes::Fatal, "Disabled custom transaction");
}
const auto isEvmEnabledForBlock = blockCtx.GetEVMEnabledForBlock();
const auto &evmTemplate = blockCtx.GetEVMTemplate();
if (!evmTemplate && isEvmEnabledForBlock) {
std::string minerAddress{};
blockCtx.SetEVMTemplate(CScopedTemplate::Create(height, minerAddress, 0u, time, 0));
if (!evmTemplate) {
return Res::Err("Failed to create queue");
}
}
try {
auto res = std::visit(CCustomTxApplyVisitor(blockCtx, txCtx), txMessage);
return res;
} catch (const std::bad_variant_access &e) {
return Res::Err(e.what());
} catch (...) {
return Res::Err("%s unexpected error", __func__);
}
}
bool ShouldReturnNonFatalError(const CTransaction &tx, uint32_t height) {
static const std::map<uint32_t, uint256> skippedTx = {
{471222, uint256S("0ab0b76352e2d865761f4c53037041f33e1200183d55cdf6b09500d6f16b7329")},
};
auto it = skippedTx.find(height);
return it != skippedTx.end() && it->second == tx.GetHash();
}
void PopulateVaultHistoryData(CHistoryWriters &writers,
CAccountsHistoryWriter &view,
const CCustomTxMessage &txMessage,
const CustomTxType txType,
const TransactionContext &txCtx) {
const auto height = txCtx.GetHeight();
const auto &txid = txCtx.GetTransaction().GetHash();
const auto txn = txCtx.GetTxn();
if (txType == CustomTxType::Vault) {
auto obj = std::get<CVaultMessage>(txMessage);
writers.schemeID = obj.schemeId;
view.vaultID = txid;
} else if (txType == CustomTxType::CloseVault) {
auto obj = std::get<CCloseVaultMessage>(txMessage);
view.vaultID = obj.vaultId;
} else if (txType == CustomTxType::UpdateVault) {
auto obj = std::get<CUpdateVaultMessage>(txMessage);
view.vaultID = obj.vaultId;
if (!obj.schemeId.empty()) {
writers.schemeID = obj.schemeId;
}
} else if (txType == CustomTxType::DepositToVault) {
auto obj = std::get<CDepositToVaultMessage>(txMessage);
view.vaultID = obj.vaultId;
} else if (txType == CustomTxType::WithdrawFromVault) {
auto obj = std::get<CWithdrawFromVaultMessage>(txMessage);
view.vaultID = obj.vaultId;
} else if (txType == CustomTxType::PaybackWithCollateral) {
auto obj = std::get<CPaybackWithCollateralMessage>(txMessage);
view.vaultID = obj.vaultId;
} else if (txType == CustomTxType::TakeLoan) {
auto obj = std::get<CLoanTakeLoanMessage>(txMessage);
view.vaultID = obj.vaultId;
} else if (txType == CustomTxType::PaybackLoan) {
auto obj = std::get<CLoanPaybackLoanMessage>(txMessage);
view.vaultID = obj.vaultId;
} else if (txType == CustomTxType::PaybackLoanV2) {
auto obj = std::get<CLoanPaybackLoanV2Message>(txMessage);
view.vaultID = obj.vaultId;
} else if (txType == CustomTxType::AuctionBid) {
auto obj = std::get<CAuctionBidMessage>(txMessage);
view.vaultID = obj.vaultId;
} else if (txType == CustomTxType::LoanScheme) {
auto obj = std::get<CLoanSchemeMessage>(txMessage);
writers.globalLoanScheme.identifier = obj.identifier;
writers.globalLoanScheme.ratio = obj.ratio;
writers.globalLoanScheme.rate = obj.rate;
if (!obj.updateHeight) {
writers.globalLoanScheme.schemeCreationTxid = txid;
} else {
writers.GetVaultView()->ForEachGlobalScheme(
[&writers](const VaultGlobalSchemeKey &key, CLazySerialize<VaultGlobalSchemeValue> value) {
if (value.get().loanScheme.identifier != writers.globalLoanScheme.identifier) {
return true;
}
writers.globalLoanScheme.schemeCreationTxid = key.schemeCreationTxid;
return false;
},
{height, txn, {}});
}
}
}
Res ApplyCustomTx(BlockContext &blockCtx, TransactionContext &txCtx, uint256 *canSpend) {
auto &mnview = blockCtx.GetView();
const auto isEvmEnabledForBlock = blockCtx.GetEVMEnabledForBlock();
const auto &consensus = txCtx.GetConsensus();
const auto height = txCtx.GetHeight();
const auto metadataValidation = txCtx.GetMetadataValidation();
const auto &tx = txCtx.GetTransaction();
const auto &txn = txCtx.GetTxn();
auto r = Res::Ok();
if (tx.IsCoinBase() && height > 0) { // genesis contains custom coinbase txs
return r;
}
const auto txType = txCtx.GetTxType();
auto attributes = mnview.GetAttributes();
if ((txType == CustomTxType::EvmTx || txType == CustomTxType::TransferDomain) && !isEvmEnabledForBlock) {
return Res::ErrCode(CustomTxErrCodes::Fatal, "EVM is not enabled on this block");
}
// Check OP_RETURN sizes
const auto opReturnLimits = OpReturnLimits::From(height, consensus, *attributes);
if (opReturnLimits.shouldEnforce) {
if (r = opReturnLimits.Validate(tx, txType); !r) {
return r;
}
}
if (txType == CustomTxType::None) {
return r;
}
if (metadataValidation && txType == CustomTxType::Reject) {
return Res::ErrCode(CustomTxErrCodes::Fatal, "Invalid custom transaction");
}
CAccountsHistoryWriter view(mnview, height, txn, tx.GetHash(), uint8_t(txType));
auto &[res, txMessage] = txCtx.GetTxMessage();
if (res) {
if (mnview.GetHistoryWriters().GetVaultView()) {
PopulateVaultHistoryData(mnview.GetHistoryWriters(), view, txMessage, txType, txCtx);
}
// TX changes are applied on a different view which
// is then used to create the TX undo based on the
// difference between the original and the copy.
auto blockCtxTxView{blockCtx};
blockCtxTxView.SetView(view);
res = CustomTxVisit(txMessage, blockCtxTxView, txCtx);
if (res) {
if (canSpend && txType == CustomTxType::UpdateMasternode) {
auto obj = std::get<CUpdateMasterNodeMessage>(txMessage);
for (const auto &item : obj.updates) {
if (item.first == static_cast<uint8_t>(UpdateMasternodeType::OwnerAddress)) {
if (const auto node = mnview.GetMasternode(obj.mnId)) {
*canSpend = node->collateralTx.IsNull() ? obj.mnId : node->collateralTx;
}
break;
}
}
}
// Track burn fee
if (txType == CustomTxType::CreateToken || txType == CustomTxType::CreateMasternode) {
mnview.GetHistoryWriters().AddFeeBurn(tx.vout[0].scriptPubKey, tx.vout[0].nValue);
}
if (txType == CustomTxType::CreateCfp || txType == CustomTxType::CreateVoc) {
// burn fee_burn_pct of creation fee, the rest is distributed among voting masternodes
CDataStructureV0 burnPctKey{
AttributeTypes::Governance, GovernanceIDs::Proposals, GovernanceKeys::FeeBurnPct};
auto attributes = view.GetAttributes();
auto burnFee = MultiplyAmounts(tx.vout[0].nValue, attributes->GetValue(burnPctKey, COIN / 2));
mnview.GetHistoryWriters().AddFeeBurn(tx.vout[0].scriptPubKey, burnFee);
}
if (txType == CustomTxType::Vault) {
// burn the half, the rest is returned on close vault
auto burnFee = tx.vout[0].nValue / 2;
mnview.GetHistoryWriters().AddFeeBurn(tx.vout[0].scriptPubKey, burnFee);
}
}
}
// list of transactions which aren't allowed to fail:
if (!res) {
res.msg = strprintf("%sTx: %s", ToString(txType), res.msg);
if (height >= static_cast<uint32_t>(consensus.DF6DakotaHeight)) {
res.code |= CustomTxErrCodes::Fatal;
return res;
}
// Below DF6, only the following are fatal:
// - mint
// - account to utxo
// - explicit skip lists
if (IsBelowDF6MintTokenOrAccountToUtxos(txType, height)) {
if (ShouldReturnNonFatalError(tx, height)) {
return res;
}
res.code |= CustomTxErrCodes::Fatal;
}
return res;
}
// construct undo
auto &flushable = view.GetStorage();
auto undo = CUndo::Construct(mnview.GetStorage(), flushable.GetRaw());
// flush changes
view.Flush();
// write undo
if (!undo.before.empty()) {
mnview.SetUndo(UndoKey{height, tx.GetHash()}, undo);
}
return res;
}
ResVal<uint256> ApplyAnchorRewardTx(CCustomCSView &mnview,
const CTransaction &tx,
int height,
const uint256 &prevStakeModifier,
const std::vector<unsigned char> &metadata,
const Consensus::Params &consensusParams) {
if (height >= consensusParams.DF6DakotaHeight) {
return Res::Err("Old anchor TX type after Dakota fork. Height %d", height);
}
CDataStream ss(metadata, SER_NETWORK, PROTOCOL_VERSION);
CAnchorFinalizationMessage finMsg;
ss >> finMsg;
auto rewardTx = mnview.GetRewardForAnchor(finMsg.btcTxHash);
if (rewardTx) {
return Res::ErrDbg("bad-ar-exists",
"reward for anchor %s already exists (tx: %s)",
finMsg.btcTxHash.ToString(),
(*rewardTx).ToString());
}
if (!finMsg.CheckConfirmSigs()) {
return Res::ErrDbg("bad-ar-sigs", "anchor signatures are incorrect");
}
if (finMsg.sigs.size() < GetMinAnchorQuorum(finMsg.currentTeam)) {
return Res::ErrDbg("bad-ar-sigs-quorum",
"anchor sigs (%d) < min quorum (%) ",
finMsg.sigs.size(),
GetMinAnchorQuorum(finMsg.currentTeam));
}
// check reward sum
if (height >= consensusParams.DF1AMKHeight) {
const auto cbValues = tx.GetValuesOut();
if (cbValues.size() != 1 || cbValues.begin()->first != DCT_ID{0}) {
return Res::ErrDbg("bad-ar-wrong-tokens", "anchor reward should be payed only in Defi coins");
}
const auto anchorReward = mnview.GetCommunityBalance(CommunityAccountType::AnchorReward);
if (cbValues.begin()->second != anchorReward) {
return Res::ErrDbg("bad-ar-amount",
"anchor pays wrong amount (actual=%d vs expected=%d)",
cbValues.begin()->second,
anchorReward);
}
} else { // pre-AMK logic
auto anchorReward = GetAnchorSubsidy(finMsg.anchorHeight, finMsg.prevAnchorHeight, consensusParams);
if (tx.GetValueOut() > anchorReward) {
return Res::ErrDbg(
"bad-ar-amount", "anchor pays too much (actual=%d vs limit=%d)", tx.GetValueOut(), anchorReward);
}
}
CTxDestination destination = FromOrDefaultKeyIDToDestination(
finMsg.rewardKeyID, TxDestTypeToKeyType(finMsg.rewardKeyType), KeyType::MNOwnerKeyType);
if (!IsValidDestination(destination) || tx.vout[1].scriptPubKey != GetScriptForDestination(destination)) {
return Res::ErrDbg("bad-ar-dest", "anchor pay destination is incorrect");
}
if (finMsg.currentTeam != mnview.GetCurrentTeam()) {
return Res::ErrDbg("bad-ar-curteam", "anchor wrong current team");
}
if (finMsg.nextTeam != mnview.CalcNextTeam(height, prevStakeModifier)) {
return Res::ErrDbg("bad-ar-nextteam", "anchor wrong next team");
}
mnview.SetTeam(finMsg.nextTeam);
if (height >= consensusParams.DF1AMKHeight) {
LogPrint(BCLog::ACCOUNTCHANGE,
"AccountChange: hash=%s fund=%s change=%s\n",
tx.GetHash().ToString(),
GetCommunityAccountName(CommunityAccountType::AnchorReward),
(CBalances{{{{0}, -mnview.GetCommunityBalance(CommunityAccountType::AnchorReward)}}}.ToString()));
mnview.SetCommunityBalance(CommunityAccountType::AnchorReward, 0); // just reset
} else {
mnview.SetFoundationsDebt(mnview.GetFoundationsDebt() + tx.GetValueOut());
}
return {finMsg.btcTxHash, Res::Ok()};
}
ResVal<uint256> ApplyAnchorRewardTxPlus(CCustomCSView &mnview,
const CTransaction &tx,
int height,
const std::vector<unsigned char> &metadata,
const Consensus::Params &consensusParams) {
if (height < consensusParams.DF6DakotaHeight) {
return Res::Err("New anchor TX type before Dakota fork. Height %d", height);
}
CDataStream ss(metadata, SER_NETWORK, PROTOCOL_VERSION);
CAnchorFinalizationMessagePlus finMsg;
ss >> finMsg;
auto rewardTx = mnview.GetRewardForAnchor(finMsg.btcTxHash);
if (rewardTx) {
return Res::ErrDbg("bad-ar-exists",
"reward for anchor %s already exists (tx: %s)",
finMsg.btcTxHash.ToString(),
(*rewardTx).ToString());
}
// Miner used confirm team at chain height when creating this TX, this is height - 1.
int anchorHeight = height - 1;
auto uniqueKeys = finMsg.CheckConfirmSigs(anchorHeight);
if (!uniqueKeys) {
return Res::ErrDbg("bad-ar-sigs", "anchor signatures are incorrect");
}
auto team = mnview.GetConfirmTeam(anchorHeight);
if (!team) {
return Res::ErrDbg("bad-ar-team", "could not get confirm team for height: %d", anchorHeight);
}
auto quorum = GetMinAnchorQuorum(*team);
if (finMsg.sigs.size() < quorum) {
return Res::Err("anchor sigs (%d) < min quorum (%) ", finMsg.sigs.size(), quorum);
}
if (uniqueKeys < quorum) {
return Res::Err("anchor unique keys (%d) < min quorum (%) ", uniqueKeys, quorum);
}
// Make sure anchor block height and hash exist in chain.
auto *anchorIndex = ::ChainActive()[finMsg.anchorHeight];
if (!anchorIndex) {
return Res::Err("Active chain does not contain block height %d. Chain height %d",
finMsg.anchorHeight,
::ChainActive().Height());
}
if (anchorIndex->GetBlockHash() != finMsg.dfiBlockHash) {
return Res::Err("Anchor and blockchain mismatch at height %d. Expected %s found %s",
finMsg.anchorHeight,
anchorIndex->GetBlockHash().ToString(),
finMsg.dfiBlockHash.ToString());
}
// check reward sum
const auto cbValues = tx.GetValuesOut();
if (cbValues.size() != 1 || cbValues.begin()->first != DCT_ID{0}) {
return Res::Err("anchor reward should be paid in DFI only");
}
const auto anchorReward = mnview.GetCommunityBalance(CommunityAccountType::AnchorReward);
if (cbValues.begin()->second != anchorReward) {
return Res::Err("anchor pays wrong amount (actual=%d vs expected=%d)", cbValues.begin()->second, anchorReward);
}
CTxDestination destination;
if (height < consensusParams.DF22MetachainHeight) {
destination = FromOrDefaultKeyIDToDestination(
finMsg.rewardKeyID, TxDestTypeToKeyType(finMsg.rewardKeyType), KeyType::MNOwnerKeyType);
} else {
destination = FromOrDefaultKeyIDToDestination(
finMsg.rewardKeyID, TxDestTypeToKeyType(finMsg.rewardKeyType), KeyType::MNRewardKeyType);
}
if (!IsValidDestination(destination) || tx.vout[1].scriptPubKey != GetScriptForDestination(destination)) {
return Res::ErrDbg("bad-ar-dest", "anchor pay destination is incorrect");
}
LogPrint(BCLog::ACCOUNTCHANGE,
"AccountChange: hash=%s fund=%s change=%s\n",
tx.GetHash().ToString(),
GetCommunityAccountName(CommunityAccountType::AnchorReward),
(CBalances{{{{0}, -mnview.GetCommunityBalance(CommunityAccountType::AnchorReward)}}}.ToString()));
mnview.SetCommunityBalance(CommunityAccountType::AnchorReward, 0); // just reset
mnview.AddRewardForAnchor(finMsg.btcTxHash, tx.GetHash());
// Store reward data for RPC info
mnview.AddAnchorConfirmData(CAnchorConfirmDataPlus{finMsg});
return {finMsg.btcTxHash, Res::Ok()};
}
bool IsMempooledCustomTxCreate(const CTxMemPool &pool, const uint256 &txid) {
CTransactionRef ptx = pool.get(txid);
if (ptx) {
std::vector<unsigned char> dummy;
CustomTxType txType = GuessCustomTxType(*ptx, dummy);
return txType == CustomTxType::CreateMasternode || txType == CustomTxType::CreateToken;
}
return false;
}
std::vector<DCT_ID> CPoolSwap::CalculateSwaps(CCustomCSView &view, const Consensus::Params &consensus, bool testOnly) {
std::vector<std::vector<DCT_ID> > poolPaths = CalculatePoolPaths(view);
// Record best pair
std::pair<std::vector<DCT_ID>, CAmount> bestPair{{}, -1};
// Loop through all common pairs
for (const auto &path : poolPaths) {
// Test on copy of view
CCustomCSView dummy(view);
// Execute pool path
auto res = ExecuteSwap(dummy, path, consensus, testOnly);
// Add error for RPC user feedback
if (!res) {
const auto token = dummy.GetToken(currentID);
if (token) {
errors.emplace_back(token->symbol, res.msg);
}
}
// Record amount if more than previous or default value
if (res && result > bestPair.second) {
bestPair = {path, result};
}
}
return bestPair.first;
}
std::vector<std::vector<DCT_ID> > CPoolSwap::CalculatePoolPaths(CCustomCSView &view) {
std::vector<std::vector<DCT_ID> > poolPaths;
// For tokens to be traded get all pairs and pool IDs
std::multimap<uint32_t, DCT_ID> fromPoolsID, toPoolsID;
view.ForEachPoolPair(
[&](DCT_ID const &id, const CPoolPair &pool) {
if ((obj.idTokenFrom == pool.idTokenA && obj.idTokenTo == pool.idTokenB) ||
(obj.idTokenTo == pool.idTokenA && obj.idTokenFrom == pool.idTokenB)) {
// Push poolId when direct path
poolPaths.push_back({{id}});
}
if (pool.idTokenA == obj.idTokenFrom) {
fromPoolsID.emplace(pool.idTokenB.v, id);
} else if (pool.idTokenB == obj.idTokenFrom) {
fromPoolsID.emplace(pool.idTokenA.v, id);
}
if (pool.idTokenA == obj.idTokenTo) {
toPoolsID.emplace(pool.idTokenB.v, id);
} else if (pool.idTokenB == obj.idTokenTo) {
toPoolsID.emplace(pool.idTokenA.v, id);
}
return true;
},
{0});
if (fromPoolsID.empty() || toPoolsID.empty()) {
return {};
}
// Find intersection on key
std::map<uint32_t, DCT_ID> commonPairs;
set_intersection(fromPoolsID.begin(),
fromPoolsID.end(),
toPoolsID.begin(),
toPoolsID.end(),
std::inserter(commonPairs, commonPairs.begin()),
[](std::pair<uint32_t, DCT_ID> a, std::pair<uint32_t, DCT_ID> b) { return a.first < b.first; });
// Loop through all common pairs and record direct pool to pool swaps
for (const auto &item : commonPairs) {
// Loop through all source/intermediate pools matching common pairs
const auto poolFromIDs = fromPoolsID.equal_range(item.first);
for (auto fromID = poolFromIDs.first; fromID != poolFromIDs.second; ++fromID) {
// Loop through all destination pools matching common pairs
const auto poolToIDs = toPoolsID.equal_range(item.first);
for (auto toID = poolToIDs.first; toID != poolToIDs.second; ++toID) {
// Add to pool paths
poolPaths.push_back({fromID->second, toID->second});
}
}
}
// Look for pools that bridges token. Might be in addition to common token pairs paths.
view.ForEachPoolPair(
[&](DCT_ID const &id, const CPoolPair &pool) {
// Loop through from pool multimap on unique keys only
for (auto fromIt = fromPoolsID.begin(); fromIt != fromPoolsID.end();
fromIt = fromPoolsID.equal_range(fromIt->first).second) {
// Loop through to pool multimap on unique keys only
for (auto toIt = toPoolsID.begin(); toIt != toPoolsID.end();
toIt = toPoolsID.equal_range(toIt->first).second) {
// If a pool pairs matches from pair and to pair add it to the pool paths
if ((fromIt->first == pool.idTokenA.v && toIt->first == pool.idTokenB.v) ||
(fromIt->first == pool.idTokenB.v && toIt->first == pool.idTokenA.v)) {
poolPaths.push_back({fromIt->second, id, toIt->second});
}
}
}
return true;
},
{0});
// return pool paths
return poolPaths;
}
// Note: `testOnly` doesn't update views, and as such can result in a previous price calculations
// for a pool, if used multiple times (or duplicated pool IDs) with the same view.
// testOnly is only meant for one-off tests per well defined view.
Res CPoolSwap::ExecuteSwap(CCustomCSView &view,
std::vector<DCT_ID> poolIDs,
const Consensus::Params &consensus,
bool testOnly) {
Res poolResult = Res::Ok();
// No composite swap allowed before Fort Canning
if (height < static_cast<uint32_t>(consensus.DF11FortCanningHeight) && !poolIDs.empty()) {
poolIDs.clear();
}
if (obj.amountFrom <= 0) {
return Res::Err("Input amount should be positive");
}
if (height >= static_cast<uint32_t>(consensus.DF14FortCanningHillHeight) && poolIDs.size() > MAX_POOL_SWAPS) {
return Res::Err(
strprintf("Too many pool IDs provided, max %d allowed, %d provided", MAX_POOL_SWAPS, poolIDs.size()));
}
// Single swap if no pool IDs provided
auto poolPrice = PoolPrice::getMaxValid();
std::optional<std::pair<DCT_ID, CPoolPair> > poolPair;
if (poolIDs.empty()) {
poolPair = view.GetPoolPair(obj.idTokenFrom, obj.idTokenTo);
if (!poolPair) {
return Res::Err("Cannot find the pool pair.");
}
// Add single swap pool to vector for loop
poolIDs.push_back(poolPair->first);
// Get legacy max price
poolPrice = obj.maxPrice;
}
if (!testOnly) {
CCustomCSView mnview(view);
mnview.CalculateOwnerRewards(obj.from, height);
mnview.CalculateOwnerRewards(obj.to, height);
mnview.Flush();
}
auto attributes = view.GetAttributes();
CDataStructureV0 dexKey{AttributeTypes::Live, ParamIDs::Economy, EconomyKeys::DexTokens};
auto dexBalances = attributes->GetValue(dexKey, CDexBalances{});
// Set amount to be swapped in pool
CTokenAmount swapAmountResult{obj.idTokenFrom, obj.amountFrom};
struct PoolSwapResult {
int64_t toAmount;
uint32_t poolId;
};
PoolSwapResult finalSwapAmount;
for (size_t i{0}; i < poolIDs.size(); ++i) {
// Also used to generate pool specific error messages for RPC users
currentID = poolIDs[i];
// Use single swap pool if already found
std::optional<CPoolPair> pool;
if (poolPair) {
pool = poolPair->second;
} else // Or get pools from IDs provided for composite swap