Repository navigation
Expand file tree
/
Copy pathdigidollar.cpp
More file actions
7099 lines (6514 loc) · 392 KB
/
Copy pathdigidollar.cpp
File metadata and controls
7099 lines (6514 loc) · 392 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) 2025 The DigiByte Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include <config/digibyte-config.h>
#endif
#include <rpc/server.h>
#include <rpc/util.h>
#include <rpc/server_util.h>
#include <rpc/blockchain.h>
#include <rpc/digidollar_transactions.h>
#include <random.h>
#include <oracle/bundle_manager.h>
#include <primitives/oracle.h>
#include <oracle/node.h>
#include <oracle/mock_oracle.h>
#include <oracle/signing_orchestrator.h>
#include <oracle/musig2_aggregator.h>
#include <consensus/digidollar.h>
#include <consensus/dca.h>
#include <consensus/merkle.h>
#include <consensus/err.h>
#include <consensus/volatility.h>
#include <digidollar/amount.h>
#include <digidollar/digidollar.h>
#include <digidollar/health.h>
#include <index/digidollarstatsindex.h>
#include <chainparams.h>
#include <clientversion.h>
#include <kernel/chainparams.h>
#include <logging.h>
#include <node/context.h>
#include <core_io.h>
#include <util/signalinterrupt.h>
#include <util/strencodings.h>
#include <validation.h>
#include <versionbits.h>
#include <cmath>
#ifdef ENABLE_WALLET
#include <util/any.h>
#include <wallet/wallet.h>
#include <wallet/receive.h>
#include <wallet/context.h>
#include <wallet/rpc/util.h>
#include <wallet/spend.h>
#include <wallet/coincontrol.h>
#include <wallet/coinselection.h>
#include <wallet/digidollarwallet.h>
#include <wallet/digidollarmintcapability.h>
#include <wallet/digidollarmintconsolidation.h>
#include <wallet/walletdb.h>
#include <wallet/scriptpubkeyman.h>
#include <interfaces/wallet.h>
#endif
#include <digidollar/txbuilder.h>
#include <node/transaction.h>
#include <base58.h>
#include <script/standard.h>
#include <script/signingprovider.h>
#include <rpc/protocol.h>
#include <oracle/musig2_messages.h>
#include <versionbits.h>
#include <deploymentstatus.h>
#include <key_io.h>
#include <policy/policy.h>
#include <version.h>
#include <util/time.h>
#include <univalue.h>
#include <algorithm>
#include <cmath>
#include <limits>
#include <set>
using namespace DigiDollar;
using namespace DigiDollar::DCA;
// Mock utility functions for RPC-only implementation
namespace {
// Aligned with consensus/digidollar.h (10 tiers, 0-9)
int GetLockDaysForTier(uint32_t tier) {
switch (tier) {
case 0: return 0; // Special: 1 hour (240 blocks) - handled separately
case 1: return 30; // 30 days
case 2: return 90; // 90 days (3 months)
case 3: return 180; // 180 days (6 months)
case 4: return 365; // 1 year
case 5: return 730; // 2 years
case 6: return 1095; // 3 years
case 7: return 1825; // 5 years
case 8: return 2555; // 7 years
case 9: return 3650; // 10 years
default: return 0;
}
}
int GetMinCollateralRatio(uint32_t tier) {
const int lock_days = GetLockDaysForTier(tier);
const int64_t lock_blocks = DigiDollar::LockDaysToBlocks(lock_days);
const int ratio = DigiDollar::GetCollateralRatioForLockTime(lock_blocks, Params().GetDigiDollarParams());
return ratio > 0 ? ratio : 0;
}
#ifdef ENABLE_WALLET
bool HasPendingDigiDollarRedeem(const wallet::CWallet& wallet, const uint256& position_id)
{
const auto* dd_wallet = wallet.GetDDWallet();
COutPoint collateral_outpoint;
// Legacy mints can place ordinary change before the collateral.
if (!dd_wallet || !dd_wallet->GetMintCollateralOutpoint(position_id, collateral_outpoint)) return false;
for (const auto& wallet_entry : wallet.mapWallet) {
const wallet::CWalletTx& wtx = wallet_entry.second;
if (!wtx.tx || ::GetDigiDollarTxType(*wtx.tx) != ::DD_TX_REDEEM) continue;
if (wtx.isAbandoned()) continue;
if (wallet.GetTxDepthInMainChain(wtx) != 0 || !wtx.isUnconfirmed()) continue;
for (const auto& txin : wtx.tx->vin) {
if (txin.prevout == collateral_outpoint) {
return true;
}
}
}
return false;
}
#endif
#ifdef ENABLE_WALLET
bool TryParseOraclePrivateKey(const std::string& private_key_hex, CKey& key_out, std::string& error_out)
{
if (!IsHex(private_key_hex)) {
error_out = "private key is not valid hex";
return false;
}
auto key_data_opt = TryParseHex<unsigned char>(private_key_hex);
if (!key_data_opt || key_data_opt->size() != 32) {
error_out = "private key must be 32 bytes";
return false;
}
CKey key;
key.Set(key_data_opt->begin(), key_data_opt->end(), true);
if (!key.IsValid()) {
error_out = "private key is invalid";
return false;
}
key_out = key;
return true;
}
uint32_t ParseConfiguredOracleId(const JSONRPCRequest& request, size_t param_index)
{
const int oracle_id_signed = request.params[param_index].getInt<int>();
if (oracle_id_signed < 0 || oracle_id_signed >= ORACLE_TOTAL_COUNT) {
throw JSONRPCError(RPC_INVALID_PARAMETER,
strprintf("Invalid oracle ID %d. Must be between 0 and %d",
oracle_id_signed, ORACLE_TOTAL_COUNT - 1));
}
if (Params().GetOracleNode(static_cast<uint32_t>(oracle_id_signed)) == nullptr) {
throw JSONRPCError(RPC_INVALID_PARAMETER,
strprintf("Oracle ID %d not found in chain parameters", oracle_id_signed));
}
return static_cast<uint32_t>(oracle_id_signed);
}
void EnsureOracleWalletCanUsePrivateKeys(const wallet::CWallet& wallet)
{
if (wallet.IsWalletFlagSet(wallet::WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
throw JSONRPCError(RPC_WALLET_ERROR, "Error: Private keys are disabled for this wallet");
}
}
void EnsureOracleWalletUnlocked(const wallet::CWallet& wallet, const std::string& action)
{
if (wallet.IsLocked()) {
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED,
strprintf("DigiDollar oracle key %s requires the wallet to be unlocked. "
"Error: Please enter the wallet passphrase with walletpassphrase first.",
action));
}
}
bool OraclePubKeyMatchesChainparams(uint32_t oracle_id, const CPubKey& pubkey, std::string& message_out)
{
const OracleNodeInfo* oracle_config = Params().GetOracleNode(oracle_id);
if (!oracle_config) {
message_out = strprintf("Oracle ID %u not found in chain parameters", oracle_id);
return false;
}
if (pubkey != oracle_config->pubkey) {
message_out = strprintf(
"Oracle key is configured but is not authorized for oracle ID %u: wallet/public key mismatch (wallet pubkey %s, chainparams pubkey %s)",
oracle_id, HexStr(pubkey), HexStr(oracle_config->pubkey));
return false;
}
return true;
}
bool OraclePrivateKeyMatchesChainparams(uint32_t oracle_id, const std::string& private_key_hex, std::string& message_out)
{
CKey key;
std::string parse_error;
if (!TryParseOraclePrivateKey(private_key_hex, key, parse_error)) {
message_out = strprintf("Oracle private key is invalid: %s", parse_error);
return false;
}
return OraclePubKeyMatchesChainparams(oracle_id, key.GetPubKey(), message_out);
}
bool TryStartOracleFromPrivateKey(OracleManager& oracle_manager, uint32_t oracle_id, const std::string& private_key_hex, const std::string& key_source, bool allow_initialized_without_running, std::string& status_message, bool* initialized_out = nullptr)
{
if (initialized_out) *initialized_out = false;
if (!OraclePrivateKeyMatchesChainparams(oracle_id, private_key_hex, status_message)) {
status_message = strprintf("%s from %s", status_message, key_source);
return false;
}
bool initialized = false;
OracleNode* oracle = oracle_manager.GetOracleNode(oracle_id);
if (!oracle) {
if (!oracle_manager.AddOracleNode(oracle_id, private_key_hex)) {
status_message = strprintf("Failed to initialize oracle with %s", key_source);
return false;
}
initialized = true;
oracle_manager.EnableOracle(oracle_id, true);
oracle = oracle_manager.GetOracleNode(oracle_id);
if (!oracle) {
status_message = strprintf("Oracle initialized with %s but manager returned no oracle instance", key_source);
if (initialized_out) *initialized_out = initialized;
return false;
}
} else {
initialized = true;
oracle_manager.EnableOracle(oracle_id, true);
}
if (initialized_out) *initialized_out = initialized;
oracle->Start();
if (oracle->IsRunning()) {
status_message = strprintf("Oracle started with %s", key_source);
return true;
}
if (allow_initialized_without_running) {
status_message = strprintf("Oracle initialized with %s (price fetcher is not running)", key_source);
return false;
}
status_message = strprintf("Oracle initialized with %s but failed to start price thread", key_source);
return false;
}
#endif
std::string OracleDisplayName(uint32_t oracle_id)
{
const auto* oracle = Params().GetOracleNode(oracle_id);
return oracle && !oracle->display_name.empty() ? oracle->display_name : strprintf("Oracle %u", oracle_id);
}
#ifdef ENABLE_WALLET
struct WalletOracleKeyLookup {
bool wallet_resolved{false};
bool key_found{false};
bool selection_error{false};
RPCErrorCode error_code{RPC_WALLET_ERROR};
std::string error_message;
std::string wallet_name;
CPubKey pubkey;
};
WalletOracleKeyLookup LookupWalletOraclePubKey(const JSONRPCRequest& request, uint32_t oracle_id)
{
WalletOracleKeyLookup lookup;
std::shared_ptr<wallet::CWallet> pwallet;
if (util::AnyPtr<wallet::WalletContext>(request.context)) {
try {
pwallet = wallet::GetWalletForJSONRPCRequest(request);
} catch (const UniValue& e) {
lookup.selection_error = true;
lookup.error_code = static_cast<RPCErrorCode>(e["code"].getInt<int>());
lookup.error_message = e["message"].get_str();
return lookup;
}
} else {
node::NodeContext* node_ctx = util::AnyPtr<node::NodeContext>(request.context);
wallet::WalletContext* wallet_ctx = node_ctx && node_ctx->wallet_loader ? node_ctx->wallet_loader->context() : nullptr;
if (!wallet_ctx) {
lookup.selection_error = true;
lookup.error_code = RPC_WALLET_NOT_FOUND;
lookup.error_message = "Wallet context not found; request this RPC through /wallet/<wallet_name> to inspect wallet-stored oracle keys";
return lookup;
}
std::string wallet_name;
if (wallet::GetWalletNameFromJSONRPCRequest(request, wallet_name)) {
pwallet = wallet::GetWallet(*wallet_ctx, wallet_name);
if (!pwallet) {
lookup.selection_error = true;
lookup.error_code = RPC_WALLET_NOT_FOUND;
lookup.error_message = strprintf("Requested wallet '%s' does not exist or is not loaded", wallet_name);
return lookup;
}
} else {
size_t wallet_count{0};
pwallet = wallet::GetDefaultWallet(*wallet_ctx, wallet_count);
if (!pwallet) {
lookup.selection_error = true;
if (wallet_count == 0) {
lookup.error_code = RPC_WALLET_NOT_FOUND;
lookup.error_message = "No wallet is loaded. Load a wallet or request /wallet/<wallet_name> to inspect wallet-stored oracle keys";
} else {
lookup.error_code = RPC_WALLET_NOT_SPECIFIED;
lookup.error_message = "Wallet file not specified; multiple wallets are loaded, so request /wallet/<wallet_name> to inspect wallet-stored oracle keys";
}
return lookup;
}
}
}
if (!pwallet) {
lookup.selection_error = true;
lookup.error_code = RPC_WALLET_NOT_FOUND;
lookup.error_message = "No wallet is selected";
return lookup;
}
lookup.wallet_resolved = true;
lookup.wallet_name = pwallet->GetName();
lookup.key_found = pwallet->GetOraclePubKey(oracle_id, lookup.pubkey);
return lookup;
}
#endif
void PushWalletOraclePubKeyResult(UniValue& result, uint32_t oracle_id, const CPubKey& pubkey, const std::string& wallet_name, bool is_running)
{
XOnlyPubKey xonly_pubkey(pubkey);
const OracleNodeInfo* oracle_config = Params().GetOracleNode(oracle_id);
const bool authorized = oracle_config && pubkey == oracle_config->pubkey;
result.pushKV("oracle_id", static_cast<int>(oracle_id));
result.pushKV("pubkey", HexStr(xonly_pubkey));
result.pushKV("pubkey_xonly", HexStr(xonly_pubkey));
result.pushKV("pubkey_full", HexStr(pubkey));
result.pushKV("valid", xonly_pubkey.IsFullyValid());
result.pushKV("authorized", authorized);
result.pushKV("is_running", is_running);
result.pushKV("configured_in_wallet", true);
result.pushKV("source", is_running ? "running_oracle" : "wallet");
result.pushKV("wallet_name", wallet_name);
if (!is_running) {
result.pushKV("message", strprintf(
"Oracle key is configured in wallet '%s' but the oracle is not running. Use 'startoracle %u' to start it.",
wallet_name, oracle_id));
}
}
void PublishRegtestMockMuSig2Quote(int32_t quote_height)
{
COracleBundle bundle = MockOracleManager::GetInstance().CreateMockMuSig2Bundle(quote_height, GetTime());
std::string error;
if (!OracleBundleManager::ValidateMuSig2Bundle(bundle, quote_height, Params().GetConsensus(), error)) {
throw JSONRPCError(RPC_MISC_ERROR,
strprintf("Failed to create regtest MuSig2 oracle quote: %s", error));
}
if (!OracleBundleManager::GetInstance().UpdateBundle(bundle)) {
throw JSONRPCError(RPC_MISC_ERROR,
"Failed to publish regtest MuSig2 oracle quote");
}
}
#ifdef ENABLE_WALLET
void RefreshRegtestMockMuSig2QuoteForMempool(const wallet::CWallet& wallet)
{
if (Params().GetChainType() != ChainType::REGTEST) return;
if (!MockOracleManager::GetInstance().IsEnabled()) return;
if (MockOracleManager::GetInstance().GetCurrentPrice() <= 0) return;
node::NodeContext* node_ctx = wallet.chain().context();
if (!node_ctx || !node_ctx->chainman) {
throw JSONRPCError(RPC_INTERNAL_ERROR, "Node context unavailable");
}
const int current_height = WITH_LOCK(cs_main, {
const CBlockIndex* tip = node_ctx->chainman->ActiveChain().Tip();
return tip ? tip->nHeight : 0;
});
PublishRegtestMockMuSig2Quote(current_height + 1);
}
#endif
struct CandidateHealthQuote {
bool active{false};
bool ready{false};
int height{0};
int health{-1};
CAmount price{0};
ChainstateHealth canonical;
std::string error;
};
CandidateHealthQuote GetCandidateHealthQuote(ChainstateManager& chainman)
{
LOCK(cs_main);
CandidateHealthQuote result;
const CBlockIndex* parent = chainman.ActiveChain().Tip();
result.height = parent ? parent->nHeight + 1 : 0;
result.active = IsThawDayActive(chainman.GetConsensus(), result.height);
if (!result.active) return result;
result.ready = GetNextBlockOracleQuote(parent, chainman.GetConsensus(), chainman.m_blockman,
result.price, result.error) &&
GetChainstateHealthForNextBlock(parent, chainman.GetConsensus(), chainman.m_blockman,
chainman.ActiveChainstate().CoinsTip(), result.price,
result.health, result.canonical, result.error,
[&chainman] { return bool(chainman.m_interrupt); });
return result;
}
void RequireCandidateHealth(const CandidateHealthQuote& candidate)
{
if (candidate.active && !candidate.ready) {
throw JSONRPCError(RPC_MISC_ERROR, candidate.price <= 0 ?
"Waiting for a valid signed oracle quote for the next block. "
"Retry after oracle data is available; see getdigidollarstats.next_block_health.data_error for details." :
"DigiDollar health state is not ready. "
"Check getdigidollarstats.next_block_health.data_error before retrying.");
}
}
/**
* Held for the whole of a mint or a redemption, so only one of them builds
* and sends a transaction from a wallet at a time.
*
* The wallet locks used to do this job. They were taken before the coins
* were chosen and kept until the finished transaction had been handed to
* the wallet, and while they were held no other worker could choose the
* same coins. They cannot do it any more, because they are let go for a
* moment further down so the chain can be asked whether it has moved. In
* that moment the coins this transaction spends still look unspent to
* everyone else, because the transaction has not reached the wallet yet.
* Two mints sent at the same instant chose the same coins and the second
* one came back "txn-mempool-conflict".
*
* This lock is taken before any wallet lock and the chain never takes it,
* so asking the chain while holding it cannot leave the node stuck. One
* lock is shared by every loaded wallet. A mint and a redemption are rare,
* deliberate actions, so waiting behind one on another wallet costs far
* less than keeping a separate lock alive for each wallet would.
*/
GlobalMutex g_digidollar_spend_mutex;
/**
* Stop the node at once, naming the lock and the line that took it, if a
* wallet lock is held where the chain is about to be asked a question.
*
* The chain takes its own lock and then calls into the wallet. So a thread
* that holds a wallet lock and then waits for the chain, running against a
* thread going the other way, leaves the node stuck with no way out. This
* turns that into an immediate, named stop while a build with lock checking
* is under test. It does nothing in a release build.
*
* It is a plain function rather than the AssertLockNotHeld macro so that a
* compiler which tracks locks does not object to checking a lock it
* believes is held, which is exactly the case worth checking.
*/
void RequireNoWalletLockForChainQuery(const char* lock_name, RecursiveMutex& cs, const char* file, int line)
{
AssertLockNotHeldInternal(lock_name, file, line, &cs);
}
void RecheckCandidateHealth(ChainstateManager& chainman, const CandidateHealthQuote& previous)
{
if (!previous.active) return;
const auto current = GetCandidateHealthQuote(chainman);
RequireCandidateHealth(current);
if (current.height != previous.height || current.price != previous.price ||
current.canonical != previous.canonical) {
throw JSONRPCError(RPC_MISC_ERROR,
"Candidate chain state or oracle quote changed; retry transaction construction with the current collateral and burn requirements");
}
}
UniValue CanonicalHealthJSON(const std::optional<ChainstateHealth>& state, bool ready)
{
UniValue result(UniValue::VOBJ);
result.pushKV("ready", ready);
if (state) {
result.pushKV("format_version", state->format_version);
result.pushKV("rules_version", state->rules_version);
result.pushKV("activation_height", state->activation_height);
result.pushKV("digidollar_height", state->digidollar_height);
result.pushKV("genesis_hash", state->genesis_hash.GetHex());
result.pushKV("block_hash", state->best_block.GetHex());
result.pushKV("open_vault_principal", int64_t{state->open_vault_principal});
result.pushKV("collateral", int64_t{state->collateral});
result.pushKV("active_vaults", state->active_vaults);
result.pushKV("history_checked", state->history_checked);
}
return result;
}
UniValue NextBlockHealthJSON(ChainstateManager& chainman, int legacy_health,
CAmount legacy_supply, CAmount legacy_price,
const CandidateHealthQuote* snapshot = nullptr)
{
const auto candidate = snapshot ? *snapshot : GetCandidateHealthQuote(chainman);
UniValue result(UniValue::VOBJ);
result.pushKV("candidate_height", candidate.height);
result.pushKV("rule_version", candidate.active ? 1 : 0);
result.pushKV("ready", candidate.active ? candidate.ready : legacy_price > 0);
result.pushKV("selected_health_denominator", candidate.active ? "open_vault_principal" : "legacy_supply");
result.pushKV("health_denominator_cents", candidate.active ?
(candidate.ready ? UniValue(candidate.canonical.open_vault_principal) : UniValue()) : (legacy_supply < 0 ? UniValue() : UniValue(legacy_supply)));
result.pushKV("health_percentage", candidate.active ? candidate.health : legacy_health);
result.pushKV("oracle_price_micro_usd", int64_t{candidate.active ? candidate.price : legacy_price});
result.pushKV("oracle_price_source", candidate.active ? "next_block_signed_bundle" : "legacy_display_quote");
result.pushKV("minting_restricted", candidate.active ? (!candidate.ready || candidate.health < 100) :
(legacy_price <= 0 || legacy_health < 100));
result.pushKV("rejection_reason", candidate.active && !candidate.ready ? "health_state_not_ready" :
(candidate.active && candidate.health < 100 ? "err_active" : "none"));
result.pushKV("data_error", candidate.error);
result.pushKV("canonical_health", CanonicalHealthJSON(candidate.ready ?
std::optional<ChainstateHealth>{candidate.canonical} : std::nullopt, candidate.ready));
return result;
}
void AddHealthReporting(UniValue& result, ChainstateManager& chainman,
int legacy_health, CAmount legacy_supply, CAmount legacy_price,
const CandidateHealthQuote* snapshot = nullptr)
{
LOCK(cs_main);
const auto* tip = chainman.ActiveChain().Tip();
const bool active = tip && IsThawDayActive(chainman.GetConsensus(), tip->nHeight);
const auto state = chainman.ActiveChainstate().CoinsTip().GetDigiDollarState();
const bool ready = tip && state && state->Matches(chainman.GetConsensus().hashGenesisBlock, tip->GetBlockHash(),
chainman.GetConsensus().nDDThawDayHeight, chainman.GetConsensus().DigiDollarHeight) &&
(!active || state->history_checked);
result.pushKV("canonical_health", CanonicalHealthJSON(state, ready));
result.pushKV("selected_health_denominator", active ? "open_vault_principal" : "legacy_supply");
result.pushKV("health_denominator_cents", active ?
(ready ? UniValue(state->open_vault_principal) : UniValue()) : UniValue(legacy_supply));
result.pushKV("health_rule_height", tip ? tip->nHeight : 0);
result.pushKV("health_oracle_price_source", "latest_display_quote");
result.pushKV("next_block_health", NextBlockHealthJSON(chainman, legacy_health, legacy_supply, legacy_price, snapshot));
}
struct DigiDollarRpcTotals {
CAmount total_collateral{0};
CAmount total_dd{0};
};
DigiDollarRpcTotals GetDigiDollarRpcTotals(const JSONRPCRequest& request)
{
DigiDollarRpcTotals totals;
const node::NodeContext& node = EnsureAnyNodeContext(request.context);
ChainstateManager& chainman = EnsureChainman(node);
{
LOCK(cs_main);
struct CompletedSupply {
const Chainstate* chainstate;
const CCoinsViewCache* coins;
fs::path datadir;
ChainstateHealth canonical;
CAmount supply;
};
// Retain only a completed snapshot; every request rechecks its chain
// identity and canonical readiness while holding the chain lock.
static std::optional<CompletedSupply> cached_supply GUARDED_BY(cs_main);
const CBlockIndex* tip = chainman.ActiveChain().Tip();
if (tip && IsThawDayActive(chainman.GetConsensus(), tip->nHeight)) {
auto& chainstate = chainman.ActiveChainstate();
const auto& coins = chainstate.CoinsTip();
const auto state = coins.GetDigiDollarState();
if (!state || !state->Matches(chainman.GetConsensus().hashGenesisBlock, tip->GetBlockHash(),
chainman.GetConsensus().nDDThawDayHeight, chainman.GetConsensus().DigiDollarHeight) ||
!state->history_checked || coins.GetBestBlock() != tip->GetBlockHash()) {
cached_supply.reset();
throw JSONRPCError(RPC_MISC_ERROR, "DigiDollar canonical health state not ready");
}
if (cached_supply && (cached_supply->chainstate != &chainstate || cached_supply->coins != &coins ||
cached_supply->datadir != chainman.m_options.datadir || cached_supply->canonical != *state)) {
cached_supply.reset();
}
totals.total_collateral = state->collateral;
if (g_digidollar_stats_index) {
const auto stats = g_digidollar_stats_index->LookUpStats(*tip);
if (stats) { totals.total_dd = stats->total_dd_supply; return totals; }
}
if (cached_supply) {
totals.total_dd = cached_supply->supply;
return totals;
}
std::map<uint32_t, CBlock> blocks;
const auto lookup = [&](const uint256& txid, uint32_t height, CTransactionRef& tx) {
auto found = blocks.find(height);
if (found == blocks.end()) {
const auto* ancestor = tip->GetAncestor(height);
CBlock block;
if (!ancestor || !chainman.m_blockman.ReadBlockFromDisk(block, *ancestor) ||
block.GetHash() != ancestor->GetBlockHash()) return false;
bool mutated{false};
if (BlockMerkleRoot(block, &mutated) != block.hashMerkleRoot || mutated) return false;
// Limit retained block bodies while visiting UTXOs from arbitrary heights.
static constexpr size_t MAX_LOOKUP_BLOCKS{8};
if (blocks.size() >= MAX_LOOKUP_BLOCKS) blocks.erase(blocks.begin());
found = blocks.emplace(height, std::move(block)).first;
}
for (const auto& candidate : found->second.vtx) {
if (candidate->GetHash() == txid) { tx = candidate; return true; }
}
return false;
};
ChainstateHealth rebuilt;
std::string error;
if (!ReconstructChainstateHealth(coins, chainman.GetConsensus(), lookup, rebuilt, error,
[&chainman] { return bool(chainman.m_interrupt); }, &totals.total_dd)) {
throw JSONRPCError(RPC_MISC_ERROR, error);
}
cached_supply = CompletedSupply{&chainstate, &coins, chainman.m_options.datadir, *state, totals.total_dd};
LogPrint(BCLog::DIGIDOLLAR, "DigiDollar stats: reconstructed circulating supply at %s\n", tip->GetBlockHash().ToString());
return totals;
}
cached_supply.reset();
}
if (g_digidollar_stats_index) {
if (!g_digidollar_stats_index->BlockUntilSyncedToCurrentChain()) {
const IndexSummary summary{g_digidollar_stats_index->GetSummary()};
throw JSONRPCError(RPC_INTERNAL_ERROR,
strprintf("DigiDollar stats index is syncing. Current height: %d", summary.best_block_height));
}
const CBlockIndex* pindex = WITH_LOCK(cs_main, return chainman.ActiveChain().Tip());
if (pindex) {
auto stats = g_digidollar_stats_index->LookUpStats(*pindex);
if (!stats) throw JSONRPCError(RPC_MISC_ERROR, "DigiDollar circulating supply is unavailable from retained metadata");
if (stats) {
totals.total_dd = stats->total_dd_supply;
totals.total_collateral = stats->total_collateral;
}
}
} else {
const SystemMetrics cached_metrics = DigiDollar::SystemHealthMonitor::GetCachedMetrics();
const int chain_height = WITH_LOCK(cs_main, return chainman.ActiveChain().Height());
if (chain_height <= 0 &&
cached_metrics.hasCanonicalHealth &&
cached_metrics.totalDDSupply > 0 &&
cached_metrics.totalCollateral > 0) {
totals.total_dd = cached_metrics.totalDDSupply;
totals.total_collateral = cached_metrics.totalCollateral;
return totals;
}
Chainstate& active_chainstate = chainman.ActiveChainstate();
active_chainstate.ForceFlushStateToDisk();
{
LOCK(::cs_main);
CCoinsView* coins_view = &active_chainstate.CoinsDB();
node::BlockManager* blockman = &active_chainstate.m_blockman;
const CTxMemPool* mempool = node.mempool.get();
if (!DigiDollar::SystemHealthMonitor::ScanUTXOSet(
coins_view, &active_chainstate.CoinsTip(), blockman, mempool,
&active_chainstate.m_chain, &Params().GetConsensus())) {
throw JSONRPCError(RPC_MISC_ERROR,
"DigiDollar-era block data is incomplete or unreadable; restart with -reindex");
}
}
DigiDollar::SystemMetrics metrics = DigiDollar::SystemHealthMonitor::GetSystemMetrics();
totals.total_collateral = metrics.totalCollateral;
totals.total_dd = metrics.totalDDSupply;
}
return totals;
}
#ifdef ENABLE_WALLET
std::vector<COutPoint> ParseDigiDollarSelectedInputs(const UniValue& inputs)
{
std::vector<COutPoint> outpoints;
for (const UniValue& input : inputs.get_array().getValues()) {
const UniValue& obj = input.get_obj();
const UniValue& txid_value = obj.find_value("txid");
const UniValue& vout_value = obj.find_value("vout");
if (txid_value.isNull() || vout_value.isNull()) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Each selected DigiDollar input must include txid and vout");
}
uint256 hash;
const std::string txid = txid_value.get_str();
if (!IsHex(txid) || txid.size() != 64) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid selected DigiDollar input txid");
}
hash.SetHex(txid);
const int vout = vout_value.getInt<int>();
if (vout < 0) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Selected DigiDollar input vout must be non-negative");
}
outpoints.emplace_back(hash, static_cast<uint32_t>(vout));
}
return outpoints;
}
#endif
int GetDigiDollarRpcSystemHealth(const JSONRPCRequest& request,
CAmount& oracle_price_micro_usd,
int empty_supply_health)
{
auto& chainman = EnsureAnyChainman(request.context);
const auto candidate = GetCandidateHealthQuote(chainman);
if (candidate.active) {
RequireCandidateHealth(candidate);
oracle_price_micro_usd = candidate.price;
return candidate.health;
}
DigiDollarRpcTotals totals = GetDigiDollarRpcTotals(request);
if (totals.total_dd == 0) {
return empty_supply_health;
}
const CAmount oracle_price_millicents = oracle_price_micro_usd / 10;
return DynamicCollateralAdjustment::CalculateSystemHealth(
totals.total_collateral, totals.total_dd, oracle_price_millicents);
}
bool OptionalParamIsSet(const JSONRPCRequest& request, size_t index)
{
return request.params.size() > index && !request.params[index].isNull();
}
#ifdef ENABLE_WALLET
// The largest DigiDollar amount a single senddigidollar request, a single
// sendmanydigidollar recipient, or a redeemdigidollar principal may name:
// 10,000,000 cents = $100,000.00. Checked before any coin selection or
// transaction construction. It is the per-output transfer consensus limit
// and the mainnet maximum mint, so no legitimate send or full vault
// redemption is ever blocked by it. It exists to stop a typo from moving
// far more than intended.
using DigiDollar::MAX_DD_RPC_AMOUNT_CENTS;
/** Help text for the amount_unit argument, identical on every RPC that takes one. */
const char* const DD_AMOUNT_UNIT_HELP{
"How to read the amount: \"cents\" (an integer, 10000 = $100.00) or \"dollars\" "
"(at most two decimals, 100.00 = $100.00). If omitted, the amount must be a whole "
"number of cents; an amount written with a decimal point is refused rather than guessed."};
const char* const DD_AMOUNT_UNIT_BAD{"amount_unit must be \"cents\" or \"dollars\""};
// Reads the optional amount_unit argument at the given position. An
// absent argument means the caller said nothing, and then only a whole
// number of cents is accepted.
DigiDollar::DDAmountUnit ParseDigiDollarRpcAmountUnit(const JSONRPCRequest& request, size_t index)
{
if (!OptionalParamIsSet(request, index)) return DigiDollar::DDAmountUnit::UNSPECIFIED;
if (!request.params[index].isStr()) {
throw JSONRPCError(RPC_INVALID_PARAMETER, DD_AMOUNT_UNIT_BAD);
}
const std::optional<DigiDollar::DDAmountUnit> unit =
DigiDollar::ParseDDAmountUnit(request.params[index].get_str());
if (!unit.has_value()) {
throw JSONRPCError(RPC_INVALID_PARAMETER, DD_AMOUNT_UNIT_BAD);
}
return unit.value();
}
// Turns a caller's amount into cents. The unit is never guessed from the
// shape of the number: "10000" is 10,000 cents, and "10000.00" is only
// read as $10,000.00 when the caller passed amount_unit=dollars.
// `context` is appended to any refusal so a caller with many amounts in
// one request (sendmanydigidollar) is told which one was wrong. The
// parser itself is not given the $100,000 cap, so an over-cap amount
// still reaches each RPC's own cap message.
CAmount ParseDigiDollarRpcAmount(const UniValue& amount_param,
DigiDollar::DDAmountUnit unit,
const std::string& context = "")
{
if (!amount_param.isStr() && !amount_param.isNum()) {
throw JSONRPCError(RPC_INVALID_PARAMETER,
"Amount must be a number (integer cents, or dollars with amount_unit=dollars)" + context);
}
const DigiDollar::DDAmountParseResult parsed =
DigiDollar::ParseDDAmount(amount_param.getValStr(), unit, DigiDollar::DD_AMOUNT_NO_CAP);
if (!parsed.ok()) {
throw JSONRPCError(RPC_INVALID_PARAMETER, parsed.message + context);
}
return parsed.cents;
}
#endif
bool IsFreshOracleTimestamp(int64_t timestamp, int64_t now)
{
return timestamp > 0 &&
timestamp <= now + 60 &&
now - timestamp <= ORACLE_MAX_AGE_SECONDS;
}
int LatestFreshOracleBundleHeight(const ChainstateManager& chainman, const OracleBundleManager& oracle_manager, int current_height)
{
LOCK(cs_main);
const int64_t now = GetTime();
for (int h = current_height; h >= std::max(0, current_height - 20); --h) {
const CBlockIndex* pindex = chainman.ActiveChain()[h];
if (!pindex) continue;
CBlock block;
if (!chainman.m_blockman.ReadBlockFromDisk(block, *pindex)) continue;
if (block.vtx.empty()) continue;
COracleBundle bundle;
if (oracle_manager.ExtractOracleBundle(*block.vtx[0], bundle) &&
IsFreshOracleTimestamp(bundle.timestamp, now)) {
return h;
}
}
return 0;
}
std::string ExpectedDigiDollarAddressPrefix()
{
switch (Params().GetChainType()) {
case ChainType::REGTEST:
return "RD";
case ChainType::TESTNET:
return "TD";
case ChainType::MAIN:
case ChainType::SIGNET:
return "DD";
}
return "DD";
}
std::string DigiDollarAddressNetworkForPrefix(const std::string& prefix)
{
if (prefix == "DD") return "mainnet";
if (prefix == "TD") return "testnet";
if (prefix == "RD") return "regtest";
return "unknown";
}
bool ValidateDigiDollarAddressForCurrentNetwork(const std::string& address, std::string& error)
{
CDigiDollarAddress dd_address(address);
if (!dd_address.IsValid()) {
error = "Invalid DigiDollar address";
return false;
}
const std::string prefix = address.substr(0, 2);
const std::string expected = ExpectedDigiDollarAddressPrefix();
if (prefix != expected) {
error = strprintf("DigiDollar address is for %s network (%s prefix), but this node expects %s prefix",
DigiDollarAddressNetworkForPrefix(prefix), prefix, expected);
return false;
}
return true;
}
}
static RPCResult CanonicalHealthResult()
{
return {RPCResult::Type::OBJ, "canonical_health", "State tied to the current chain; amounts are available only when ready", {
{RPCResult::Type::BOOL, "ready", "Whether the state identity and history proof are usable"},
{RPCResult::Type::NUM, "format_version", true, "Storage format version"},
{RPCResult::Type::NUM, "rules_version", true, "Accounting rules version"},
{RPCResult::Type::NUM, "activation_height", true, "Thaw Day height bound into the record"},
{RPCResult::Type::NUM, "digidollar_height", true, "DigiDollar height bound into the record"},
{RPCResult::Type::STR_HEX, "genesis_hash", true, "Network identity"},
{RPCResult::Type::STR_HEX, "block_hash", true, "Matching UTXO block"},
{RPCResult::Type::NUM, "open_vault_principal", true, "Original cents attached to open vaults"},
{RPCResult::Type::NUM, "collateral", true, "Satoshis locked in those vaults"},
{RPCResult::Type::NUM, "active_vaults", true, "Number of open vaults"},
{RPCResult::Type::BOOL, "history_checked", true, "Whether activated history has been checked"},
}};
}
static RPCResult NextBlockHealthResult()
{
return {RPCResult::Type::OBJ, "next_block_health", "Health for next-block construction, separate from tip display health", {
{RPCResult::Type::NUM, "candidate_height", "Candidate height"},
{RPCResult::Type::NUM, "rule_version", "0 legacy or 1 canonical accounting"},
{RPCResult::Type::BOOL, "ready", "Whether state and a quote are available"},
{RPCResult::Type::STR, "selected_health_denominator", "open_vault_principal or legacy_supply"},
{RPCResult::Type::NUM, "health_denominator_cents", "Selected liability amount, or null if unavailable", {}, true},
{RPCResult::Type::NUM, "health_percentage", "Candidate health, or -1 if unavailable"},
{RPCResult::Type::NUM, "oracle_price_micro_usd", "Quote used for this candidate"},
{RPCResult::Type::STR, "oracle_price_source", "next_block_signed_bundle or legacy_display_quote"},
{RPCResult::Type::BOOL, "minting_restricted", "Whether oracle readiness or emergency health blocks minting"},
{RPCResult::Type::STR, "rejection_reason", "Health restriction reason"},
{RPCResult::Type::STR, "data_error", "Readiness or recovery detail"},
CanonicalHealthResult(),
}};
}
static RPCResult MintVolatilityResult(const std::string& name)
{
return {RPCResult::Type::OBJ, name, "Next-block mint volatility eligibility; other mint requirements still apply", {
{RPCResult::Type::NUM, "tip_height", "Current tip height"},
{RPCResult::Type::NUM, "candidate_height", "Next-block candidate height"},
{RPCResult::Type::NUM, "activation_height", "Thaw Day height, or null when disabled", {}, true},
{RPCResult::Type::BOOL, "tip_active", "Whether Thaw Day rules apply to the tip"},
{RPCResult::Type::BOOL, "next_block_active", "Whether Thaw Day rules apply to the next block"},
{RPCResult::Type::NUM, "rule_version", "0 legacy, 1 ancestor-derived mint-only rule"},
{RPCResult::Type::BOOL, "quote_available", "Whether a checked quote is available for the candidate"},
{RPCResult::Type::NUM, "candidate_price_micro_usd", "Price used for this evaluation"},
{RPCResult::Type::BOOL, "ready", "Whether required reference data is available"},
{RPCResult::Type::NUM, "reference_price_micro_usd", "Lower median reference, zero for an empty window"},
{RPCResult::Type::NUM, "sample_count", "Qualifying ancestor blocks selected"},
{RPCResult::Type::NUM, "window_start_height", "Oldest height in the reference window"},
{RPCResult::Type::NUM, "window_end_height", "Newest height in the reference window"},
{RPCResult::Type::NUM, "deviation_bps", "Absolute deviation in basis points, rounded down for display"},
{RPCResult::Type::BOOL, "minting_restricted", "Whether volatility restricts this candidate mint"},
{RPCResult::Type::BOOL, "all_operations_restricted", "Always false under the mint-only rule"},
{RPCResult::Type::STR, "rejection_reason", "none, oracle_unavailable, volatility_state_not_ready, volatility_pause, or legacy_volatility_freeze"},
{RPCResult::Type::STR, "data_error", "Local data or quote availability detail"},
{RPCResult::Type::BOOL, "protection_active", "Whether volatility restricts an operation"},
{RPCResult::Type::NUM, "current_volatility", "Candidate deviation percent, or legacy monitor volatility"},
{RPCResult::Type::NUM, "protection_threshold", "Mint volatility threshold percent"},
}};
}
static UniValue GetMintVolatilityRPC(const ChainstateManager& chainman, CAmount legacy_price = 0,
const CandidateHealthQuote* snapshot = nullptr)
{
LOCK(cs_main);
const CBlockIndex* parent = chainman.ActiveChain().Tip();
const auto& params = chainman.GetConsensus();
const int tip_height = parent ? parent->nHeight : -1;
const int height = tip_height + 1;
const bool active = DigiDollar::IsThawDayActive(params, height);
Volatility::MintReference reference;
Volatility::MintPriceStatus status;
CAmount price = legacy_price;
std::string data_error;
bool all_restricted{false};
double current_volatility{0};
if (active) {
if (snapshot) {
price = snapshot->price;
if (price <= 0) data_error = snapshot->error;
} else {
DigiDollar::GetNextBlockOracleQuote(parent, params, chainman.m_blockman, price, data_error);
}
reference = DigiDollar::GetMintVolatilityReference(parent, params, chainman.m_blockman);
status = Volatility::EvaluateMintPrice(price, reference);
if (!reference.ready) data_error = reference.error;
current_volatility = status.deviation_bps / 100.0;
} else {
const auto legacy = Volatility::VolatilityMonitor::GetCurrentState();
status.ready = true;
status.quote_available = price > 0;
all_restricted = Volatility::VolatilityMonitor::ShouldFreezeAll();
status.restricted = all_restricted || Volatility::VolatilityMonitor::ShouldFreezeMinting() ||
Volatility::VolatilityMonitor::WouldCandidateFreezeMinting(price);
status.reason = !status.quote_available ? "oracle_unavailable" :
(status.restricted ? "legacy_volatility_freeze" : "none");
current_volatility = std::max({legacy.hourlyVolatility, legacy.dailyVolatility, legacy.weeklyVolatility});
}
UniValue result(UniValue::VOBJ);
result.pushKV("tip_height", tip_height);
result.pushKV("candidate_height", height);
result.pushKV("activation_height", DigiDollar::IsThawDayScheduled(params) ? UniValue(params.nDDThawDayHeight) : UniValue());
result.pushKV("tip_active", DigiDollar::IsThawDayActive(params, tip_height));
result.pushKV("next_block_active", active);
result.pushKV("rule_version", active ? Volatility::MINT_REFERENCE_RULE_VERSION : 0);
result.pushKV("quote_available", status.quote_available);
result.pushKV("candidate_price_micro_usd", int64_t{price});
result.pushKV("ready", status.ready);
result.pushKV("reference_price_micro_usd", int64_t{reference.price_micro_usd});
result.pushKV("sample_count", static_cast<int>(reference.sample_count));
result.pushKV("window_start_height", active ? reference.window_start_height : 0);
result.pushKV("window_end_height", active ? reference.window_end_height : -1);
result.pushKV("deviation_bps", status.deviation_bps);
result.pushKV("minting_restricted", status.restricted);
result.pushKV("all_operations_restricted", all_restricted);
result.pushKV("rejection_reason", status.reason);
result.pushKV("data_error", data_error);
result.pushKV("protection_active", status.restricted || all_restricted);
result.pushKV("current_volatility", current_volatility);
result.pushKV("protection_threshold", 20);
return result;
}
RPCHelpMan getdigidollarstats()
{
return RPCHelpMan{"getdigidollarstats",
"\nGet current DigiDollar system health information.\n"
"Returns the overall health of the DigiDollar stablecoin system,\n"
"including collateralization ratio and DCA tier status.\n",
{},
RPCResult{
RPCResult::Type::OBJ, "", "",
{
{RPCResult::Type::NUM, "health_percentage", "System health as percentage (e.g., 150 = 150% collateralized)"},
{RPCResult::Type::STR, "health_status", "Health tier status: healthy, warning, critical, or emergency"},
{RPCResult::Type::NUM, "total_collateral_dgb", "Total DGB locked as collateral"},
{RPCResult::Type::NUM, "total_dd_supply", "Total DigiDollar supply in circulation (in cents)"},
{RPCResult::Type::NUM, "oracle_price_cents", "Current DGB/USD price from oracle (in cents per DGB)"},
{RPCResult::Type::NUM, "oracle_price_micro_usd", "Current DGB/USD price from oracle in micro-USD (1,000,000 = $1.00)"},
{RPCResult::Type::BOOL, "oracle_available", "True when a live oracle price is available"},