Repository navigation
Expand file tree
/
Copy pathbundle_manager.cpp
More file actions
2813 lines (2429 loc) · 114 KB
/
Copy pathbundle_manager.cpp
File metadata and controls
2813 lines (2429 loc) · 114 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) 2024 The DigiByte Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <oracle/bundle_manager.h>
#include <algorithm>
#include <cassert>
#include <chrono>
#include <limits>
#include <chainparams.h>
#include <common/args.h>
#include <consensus/consensus.h>
#include <consensus/digidollar.h>
#include <consensus/volatility.h>
#include <digidollar/digidollar.h>
#include <kernel/chainparams.h>
#include <logging.h>
#include <net.h>
#include <netmessagemaker.h>
#include <oracle/mock_oracle.h>
#include <oracle/musig2_aggregator.h>
#include <oracle/musig2_orchestrator.h>
#include <oracle/musig2_messages.h>
#include <oracle/signing_orchestrator.h>
#include <oracle/musig2_session.h>
#include <oracle/node.h>
#include <primitives/block.h>
#include <primitives/oracle.h>
#include <primitives/transaction.h>
#include <protocol.h>
#include <script/script.h>
#include <script/standard.h>
#include <secp256k1.h>
#include <secp256k1_schnorrsig.h>
#include <util/time.h>
#include <validation.h>
// Forward declaration for missing functions
extern int32_t GetBestHeight();
// MuSig2 global signing session store (defined in musig2_session.cpp)
extern std::map<int32_t, MuSig2SigningSession> g_oracle_signing_sessions;
extern Mutex g_oracle_signing_sessions_mutex;
// Get current chain height - used by oracle bundle manager
int32_t GetBestHeight() {
// TODO: Wire up to ChainstateManager properly
// For now, return 0 if we can't determine height
return 0;
}
namespace {
bool IsFreshLiveOracleTimestamp(int64_t timestamp, int64_t now)
{
return timestamp > 0 &&
timestamp <= now + 60 &&
now - timestamp <= ORACLE_MAX_AGE_SECONDS;
}
bool IsConsensusMuSig2OracleId(uint32_t oracle_id, const Consensus::Params& params)
{
return params.nOraclePubkeyCount > 0 &&
oracle_id < static_cast<uint32_t>(params.nOraclePubkeyCount);
}
bool IsActiveConsensusOracle(uint32_t oracle_id)
{
const CChainParams& params = Params();
if (!IsConsensusMuSig2OracleId(oracle_id, params.GetConsensus())) return false;
const OracleNodeInfo* oracle_config = params.GetOracleNode(oracle_id);
return oracle_config && oracle_config->is_active;
}
bool IsCompleteMuSig2Bundle(const COracleBundle& bundle)
{
return bundle.IsMuSig2() &&
bundle.aggregate_sig.size() == 64 &&
!bundle.participation_bitmap.empty() &&
bundle.median_price_micro_usd > 0 &&
bundle.timestamp > 0;
}
bool HasMuSig2Quorum(const COracleBundle& bundle, const Consensus::Params& params)
{
if (!IsCompleteMuSig2Bundle(bundle)) return false;
const std::vector<uint8_t> oracle_ids = MuSig2OracleAggregator::DecodeBitmap(
bundle.participation_bitmap, static_cast<uint16_t>(params.nOracleTotalOracles));
if (static_cast<int>(oracle_ids.size()) < params.nOracleConsensusRequired) return false;
for (uint8_t oracle_id : oracle_ids) {
if (static_cast<int>(oracle_id) >= params.nOraclePubkeyCount) return false;
}
return true;
}
bool BlockTouchesDigiDollar(const CBlock& block)
{
for (size_t i = 1; i < block.vtx.size(); ++i) {
if (DigiDollar::HasDigiDollarMarker(*block.vtx[i])) {
return true;
}
}
return false;
}
bool BlockNeedsOraclePrice(const CBlock& block)
{
for (size_t i = 1; i < block.vtx.size(); ++i) {
const CTransaction& tx = *block.vtx[i];
if (!DigiDollar::HasDigiDollarMarker(tx)) continue;
const DigiDollar::DigiDollarTxType tx_type = DigiDollar::GetDigiDollarTxType(tx);
if (tx_type == DigiDollar::DD_TX_MINT || tx_type == DigiDollar::DD_TX_REDEEM) {
return true;
}
}
return false;
}
bool BlockHasDigiDollarMint(const CBlock& block)
{
for (size_t i = 1; i < block.vtx.size(); ++i) {
const CTransaction& tx = *block.vtx[i];
if (DigiDollar::HasDigiDollarMarker(tx) &&
DigiDollar::GetDigiDollarTxType(tx) == DigiDollar::DD_TX_MINT) {
return true;
}
}
return false;
}
} // namespace
//! Global oracle bundle manager instance
std::unique_ptr<OracleBundleManager> g_oracle_bundle_manager;
/**
* OracleBundleManager Implementation
*/
OracleBundleManager::OracleBundleManager()
{
const int64_t configured_wait_ms = std::max<int64_t>(0, gArgs.GetIntArg("-oraclebundlewaitms", 2000));
const int64_t configured_poll_ms = std::max<int64_t>(1, gArgs.GetIntArg("-oraclebundlewaitpollms", 200));
near_quorum_wait_timeout = std::chrono::milliseconds(configured_wait_ms);
near_quorum_wait_poll_interval = std::chrono::milliseconds(configured_poll_ms);
if (near_quorum_wait_timeout.count() > 0 && near_quorum_wait_poll_interval > near_quorum_wait_timeout) {
near_quorum_wait_poll_interval = near_quorum_wait_timeout;
}
LogPrintf("Oracle: Initializing Oracle Bundle Manager\n");
LogPrintf("Oracle: Near-quorum wait config: timeout=%lldms poll=%lldms\n",
static_cast<long long>(near_quorum_wait_timeout.count()),
static_cast<long long>(near_quorum_wait_poll_interval.count()));
}
OracleBundleManager::~OracleBundleManager()
{
LogPrintf("Oracle: Shutting down Oracle Bundle Manager\n");
}
bool OracleBundleManager::AddOracleMessage(const COraclePriceMessage& message)
{
std::lock_guard<std::recursive_mutex> lock(mtx_messages);
LogPrint(BCLog::DIGIDOLLAR, "Oracle: AddOracleMessage called for oracle_id=%d, price=%llu, timestamp=%d, enabled=%d\n",
message.oracle_id, message.price_micro_usd, message.timestamp, enabled);
if (!enabled) {
LogPrint(BCLog::DIGIDOLLAR, "Oracle: Manager not enabled, rejecting message\n");
return false;
}
if (!IsValidOracleMessage(message)) {
LogPrintf("Oracle: Invalid oracle message from oracle %d\n", message.oracle_id);
return false;
}
LogPrint(BCLog::DIGIDOLLAR, "Oracle: Message passed IsValidOracleMessage check\n");
// Purge stale messages from pending_messages.
// Messages older than ORACLE_MAX_AGE_SECONDS are from oracles that may no
// longer be active. Without this cleanup, oracle nodes accumulate entries
// from briefly-running oracles, inflating the consensus count (e.g. showing
// "7-of-5" instead of "5-of-5").
{
int64_t now = GetTime();
auto stale_it = pending_messages.begin();
while (stale_it != pending_messages.end()) {
if (!IsFreshLiveOracleTimestamp(stale_it->second.timestamp, now)) {
LogPrint(BCLog::DIGIDOLLAR, "Oracle: Purging stale/future message from oracle %d (age %lld seconds)\n",
stale_it->first, now - stale_it->second.timestamp);
stale_it = pending_messages.erase(stale_it);
} else {
++stale_it;
}
}
}
// Periodic cleanup of seen message hashes to prevent deadlock.
// When the oracle consensus round stalls (e.g., due to rapid block production
// or network partition), messages with the same attestation hash keep getting
// rejected as duplicates, preventing recovery. Clearing the set periodically
// allows fresh consensus rounds to form. The 300-second interval is shorter
// than the 40-block (~600s) DigiDollar oracle epoch, ensuring at least one
// cleanup per epoch. The pending_messages map (keyed by oracle_id)
// provides the authoritative dedup; seen_message_hashes is best-effort P2P
// optimization only.
{
static int64_t last_seen_cleanup = 0;
int64_t now_cleanup = GetTime();
if (now_cleanup - last_seen_cleanup > 300) {
size_t old_size = seen_message_hashes.size();
seen_message_hashes.clear();
last_seen_cleanup = now_cleanup;
if (old_size > 0) {
LogPrint(BCLog::DIGIDOLLAR, "Oracle: Periodic cleanup cleared %zu seen message hashes\n", old_size);
}
}
}
// Calculate message hash for duplicate detection.
// Use the attestation hash (oracle_id + price + timestamp) for compact
// off-chain oracle messages. GetSignatureHash() includes block_height+nonce,
// which are not covered by attestations; letting peers mutate those fields
// would bypass deduplication.
uint256 msg_hash = (!message.schnorr_sig.empty())
? message.GetAttestationSignatureHash()
: message.GetSignatureHash();
// Check if we've already seen this exact message
if (seen_message_hashes.count(msg_hash) > 0) {
LogPrint(BCLog::DIGIDOLLAR, "Oracle: Ignoring duplicate message from oracle %d\n", message.oracle_id);
return false;
}
// Add to seen set
seen_message_hashes.insert(msg_hash);
// Cap seen_message_hashes to prevent unbounded growth.
// Each oracle re-broadcasts every ~60 seconds with a new timestamp, adding a
// new hash each time. With 8 oracles broadcasting for hours, the set can
// grow very large. Keep only the most recent hashes; old hashes are no
// longer needed because the corresponding messages have already expired
// from pending_messages (purged above) and from the P2P relay window.
static constexpr size_t MAX_SEEN_HASHES = 2048;
if (seen_message_hashes.size() > MAX_SEEN_HASHES) {
// std::set iteration is ordered; erasing from begin() removes the
// "smallest" hashes which, being random SHA-256 digests, are
// effectively arbitrary. This is acceptable because the set is only
// a best-effort duplicate filter — true dedup is enforced by the
// pending_messages oracle_id key.
auto erase_end = seen_message_hashes.begin();
std::advance(erase_end, seen_message_hashes.size() - MAX_SEEN_HASHES);
seen_message_hashes.erase(seen_message_hashes.begin(), erase_end);
}
// Check if we already have a message from this oracle for current epoch
auto it = pending_messages.find(message.oracle_id);
if (it != pending_messages.end()) {
// Replace if new message is more recent
if (message.timestamp > it->second.timestamp) {
it->second = message;
LogPrint(BCLog::DIGIDOLLAR, "Oracle: Updated message from oracle %d with newer timestamp\n", message.oracle_id);
} else {
LogPrint(BCLog::DIGIDOLLAR, "Oracle: Ignoring older message from oracle %d\n", message.oracle_id);
return false;
}
} else {
// Add new message
pending_messages[message.oracle_id] = message;
LogPrint(BCLog::DIGIDOLLAR, "Oracle: Added new message from oracle %d: price=%llu micro-USD, timestamp=%d\n",
message.oracle_id, message.price_micro_usd, message.timestamp);
}
// Note: Bundle creation happens in AddOracleBundleToBlock() or when explicitly requested
// Don't auto-create here to avoid epoch mismatch issues
// Individual P2P messages may coordinate MuSig2 signing, but they do not
// update the canonical price cache. V1 cache updates come only from a
// validated on-chain MuSig2 bundle after block validation succeeds.
{
std::lock_guard<std::recursive_mutex> pending_lock(mtx_messages);
const int64_t now = GetTime();
COracleBundle temp;
temp.messages.reserve(pending_messages.size());
for (const auto& [id, m] : pending_messages) {
if (IsActiveConsensusOracle(id) &&
IsFreshLiveOracleTimestamp(m.timestamp, now)) {
temp.messages.push_back(m);
}
}
int fresh_count = static_cast<int>(temp.messages.size());
if (fresh_count >= min_oracle_count) {
const Consensus::Params& cparams = Params().GetConsensus();
const CAmount consensus_price = CalculateConsensusPrice(temp, cparams);
if (consensus_price <= 0) {
LogPrint(BCLog::DIGIDOLLAR, "Oracle: %d fresh messages reached threshold but no valid consensus price was calculated\n",
fresh_count);
m_messages_updated_cv.notify_all();
return true;
}
LogPrint(BCLog::DIGIDOLLAR,
"Oracle: %d/%d individual messages reached off-chain consensus (min %d required); waiting for MuSig2 on-chain bundle before updating price cache\n",
fresh_count, (int)pending_messages.size(), min_oracle_count);
// T5-03: When consensus is reached from individual messages, try to generate
// consensus attestations from local oracle nodes. Each oracle signs
// H(oracle_id, consensus_price, consensus_timestamp) so the signature verifies
// when stored on-chain with the consensus values.
if (min_oracle_count > 1) {
uint64_t att_consensus_price = static_cast<uint64_t>(consensus_price);
int64_t att_consensus_timestamp = 0;
// Compute consensus values (median price + median timestamp)
{
std::vector<int64_t> ts;
for (const auto& m : temp.messages) ts.push_back(m.timestamp);
std::sort(ts.begin(), ts.end());
size_t tmid = ts.size() / 2;
att_consensus_timestamp = (ts.size() % 2 == 0) ?
(ts[tmid - 1] + ts[tmid]) / 2 : ts[tmid];
// Proactive broadcast: send consensus proposal when quorum is reached
// This ensures remote oracles get the proposal BEFORE any block template is needed
// Use cached_epoch, or fallback to a conservative estimate if not set
int32_t epoch_for_broadcast;
{
std::lock_guard<std::mutex> bundles_lock(mtx_bundles);
epoch_for_broadcast = (cached_epoch >= 0) ? cached_epoch :
static_cast<int32_t>(GetTime() / (1440 * 15)); // 1440 blocks * 15 seconds/block
}
BroadcastConsensusProposal(epoch_for_broadcast, att_consensus_price, att_consensus_timestamp);
// Ask local oracle nodes to sign consensus values
OracleManager& om = OracleManager::GetInstance();
for (const auto& [oid, omsg] : pending_messages) {
if (!IsActiveConsensusOracle(oid)) continue;
if (pending_attestations.count(oid)) continue; // Already have attestation
OracleNode* node = om.GetOracleNode(oid);
if (node) {
COraclePriceMessage att = node->CreateConsensusAttestation(
att_consensus_price, att_consensus_timestamp);
if (!att.schnorr_sig.empty() && att.VerifyAttestation()) {
pending_attestations[oid] = att;
LogPrint(BCLog::DIGIDOLLAR,
"Oracle: Auto-generated consensus attestation for local oracle %d\n", oid);
}
}
}
}
}
} else {
LogPrint(BCLog::DIGIDOLLAR, "Oracle: %d fresh messages, need %d for consensus - cached price unchanged\n",
fresh_count, min_oracle_count);
}
}
m_messages_updated_cv.notify_all();
return true;
}
bool OracleBundleManager::RemoveOracleMessage(uint32_t oracle_id)
{
std::lock_guard<std::recursive_mutex> lock(mtx_messages);
auto it = pending_messages.find(oracle_id);
if (it != pending_messages.end()) {
pending_messages.erase(it);
LogPrint(BCLog::DIGIDOLLAR, "Oracle: Removed message from oracle %d\n", oracle_id);
return true;
}
return false;
}
std::vector<COraclePriceMessage> OracleBundleManager::GetPendingMessages() const
{
std::lock_guard<std::recursive_mutex> lock(mtx_messages);
LogPrint(BCLog::DIGIDOLLAR, "Oracle: GetPendingMessages called, pending_messages.size()=%zu\n", pending_messages.size());
std::vector<COraclePriceMessage> messages;
messages.reserve(pending_messages.size());
for (const auto& [oracle_id, message] : pending_messages) {
LogPrint(BCLog::DIGIDOLLAR, "Oracle: GetPendingMessages - oracle_id=%d, price=%llu, timestamp=%d\n",
oracle_id, message.price_micro_usd, message.timestamp);
messages.push_back(message);
}
LogPrint(BCLog::DIGIDOLLAR, "Oracle: GetPendingMessages returning %zu messages\n", messages.size());
return messages;
}
size_t OracleBundleManager::GetPendingMessageCount() const
{
std::lock_guard<std::recursive_mutex> lock(mtx_messages);
return pending_messages.size();
}
void OracleBundleManager::ClearPendingMessages()
{
std::lock_guard<std::recursive_mutex> lock(mtx_messages);
pending_messages.clear();
pending_attestations.clear();
seen_message_hashes.clear();
seen_attestation_hashes.clear();
LogPrintf("Oracle: Manually cleared all pending messages and attestations\n");
m_messages_updated_cv.notify_all();
}
void OracleBundleManager::InjectTestMessage(const COraclePriceMessage& message)
{
std::lock_guard<std::recursive_mutex> lock(mtx_messages);
pending_messages[message.oracle_id] = message;
LogPrint(BCLog::DIGIDOLLAR, "Oracle: Injected test message for oracle %d, price=%llu\n",
message.oracle_id, message.price_micro_usd);
m_messages_updated_cv.notify_all();
}
bool OracleBundleManager::AddConsensusAttestation(const COraclePriceMessage& attestation)
{
std::lock_guard<std::recursive_mutex> lock(mtx_messages);
// Consensus attestations are off-chain inputs to the MuSig2 signing round.
// They must be signed, but they are never accepted as on-chain oracle bundles.
if (attestation.schnorr_sig.empty() || attestation.schnorr_sig.size() != 64) {
LogPrintf("Oracle: Rejecting consensus attestation from oracle %d: missing/invalid signature\n",
attestation.oracle_id);
return false;
}
if (!IsActiveConsensusOracle(attestation.oracle_id)) {
LogPrintf("Oracle: Rejecting consensus attestation from oracle %d: outside active MuSig2 consensus keyset\n",
attestation.oracle_id);
return false;
}
// Price range check
if (attestation.price_micro_usd < ORACLE_MIN_PRICE_MICRO_USD ||
attestation.price_micro_usd > ORACLE_MAX_PRICE_MICRO_USD) {
LogPrintf("Oracle: Rejecting consensus attestation from oracle %d: price out of range\n",
attestation.oracle_id);
return false;
}
const int64_t now = GetTime();
if (!IsFreshLiveOracleTimestamp(attestation.timestamp, now)) {
LogPrintf("Oracle: Rejecting consensus attestation from oracle %d: stale/future timestamp=%lld now=%lld\n",
attestation.oracle_id, attestation.timestamp, now);
return false;
}
// Verify compact attestation signature over the consensus values.
if (!attestation.VerifyAttestation()) {
// Also try with chainparams pubkey binding
const CChainParams& params = Params();
const OracleNodeInfo* oracle_config = params.GetOracleNode(attestation.oracle_id);
if (oracle_config) {
COraclePriceMessage bound = attestation;
bound.oracle_pubkey = XOnlyPubKey(oracle_config->pubkey);
if (!bound.VerifyAttestation()) {
LogPrintf("Oracle: Rejecting consensus attestation from oracle %d: invalid signature\n",
attestation.oracle_id);
return false;
}
// Store with chainparams-bound pubkey
pending_attestations[attestation.oracle_id] = bound;
} else {
// In regtest, chainparams may not have this oracle — accept with original pubkey
if (Params().GetChainType() == ChainType::REGTEST) {
pending_attestations[attestation.oracle_id] = attestation;
} else {
LogPrintf("Oracle: Rejecting consensus attestation from oracle %d: unknown oracle\n",
attestation.oracle_id);
return false;
}
}
} else {
pending_attestations[attestation.oracle_id] = attestation;
}
LogPrint(BCLog::DIGIDOLLAR, "Oracle: Added consensus attestation from oracle %d: price=%llu, timestamp=%lld\n",
attestation.oracle_id, attestation.price_micro_usd, attestation.timestamp);
m_messages_updated_cv.notify_all();
return true;
}
std::vector<COraclePriceMessage> OracleBundleManager::GetPendingAttestations() const
{
std::lock_guard<std::recursive_mutex> lock(mtx_messages);
std::vector<COraclePriceMessage> attestations;
attestations.reserve(pending_attestations.size());
for (const auto& [id, msg] : pending_attestations) {
attestations.push_back(msg);
}
return attestations;
}
size_t OracleBundleManager::GetPendingAttestationCount() const
{
std::lock_guard<std::recursive_mutex> lock(mtx_messages);
return pending_attestations.size();
}
void OracleBundleManager::ClearPendingAttestations()
{
std::lock_guard<std::recursive_mutex> lock(mtx_messages);
pending_attestations.clear();
m_messages_updated_cv.notify_all();
}
bool OracleBundleManager::ComputeConsensusValues(uint64_t& consensus_price, int64_t& consensus_timestamp) const
{
std::lock_guard<std::recursive_mutex> lock(mtx_messages);
const int64_t now = GetTime();
COracleBundle temp;
for (const auto& [id, msg] : pending_messages) {
if (IsActiveConsensusOracle(id) &&
IsFreshLiveOracleTimestamp(msg.timestamp, now)) {
temp.messages.push_back(msg);
}
}
if (static_cast<int>(temp.messages.size()) < min_oracle_count) {
return false;
}
const Consensus::Params& cparams = Params().GetConsensus();
CAmount price = CalculateConsensusPrice(temp, cparams);
if (price <= 0) return false;
consensus_price = static_cast<uint64_t>(price);
// Compute consensus timestamp as the median of individual message timestamps
std::vector<int64_t> timestamps;
for (const auto& msg : temp.messages) {
timestamps.push_back(msg.timestamp);
}
std::sort(timestamps.begin(), timestamps.end());
size_t mid = timestamps.size() / 2;
if (timestamps.size() % 2 == 0) {
consensus_timestamp = (timestamps[mid - 1] + timestamps[mid]) / 2;
} else {
consensus_timestamp = timestamps[mid];
}
return true;
}
bool OracleBundleManager::ComputeConsensusValuesForOracles(const std::vector<uint8_t>& oracle_ids,
uint64_t& consensus_price,
int64_t& consensus_timestamp) const
{
std::lock_guard<std::recursive_mutex> lock(mtx_messages);
if (static_cast<int>(oracle_ids.size()) < min_oracle_count) return false;
const int64_t now = GetTime();
COracleBundle temp;
temp.messages.reserve(oracle_ids.size());
std::set<uint8_t> seen;
for (uint8_t id : oracle_ids) {
if (!seen.insert(id).second) return false;
if (!IsActiveConsensusOracle(id)) {
LogPrint(BCLog::DIGIDOLLAR,
"Oracle: Signing context cannot compute consensus: oracle %u outside active keyset\n",
id);
return false;
}
auto it = pending_messages.find(id);
if (it == pending_messages.end()) {
LogPrint(BCLog::DIGIDOLLAR,
"Oracle: Signing context waiting for price message from oracle %u\n",
id);
return false;
}
if (!IsFreshLiveOracleTimestamp(it->second.timestamp, now)) {
LogPrint(BCLog::DIGIDOLLAR,
"Oracle: Signing context price from oracle %u is stale/future timestamp=%lld now=%lld\n",
id, static_cast<long long>(it->second.timestamp), static_cast<long long>(now));
return false;
}
temp.messages.push_back(it->second);
}
if (static_cast<int>(temp.messages.size()) < min_oracle_count) return false;
const Consensus::Params& cparams = Params().GetConsensus();
const CAmount price = CalculateConsensusPrice(temp, cparams);
if (price <= 0) return false;
consensus_price = static_cast<uint64_t>(price);
std::vector<int64_t> timestamps;
timestamps.reserve(temp.messages.size());
for (const auto& msg : temp.messages) {
timestamps.push_back(msg.timestamp);
}
std::sort(timestamps.begin(), timestamps.end());
const size_t mid = timestamps.size() / 2;
consensus_timestamp = (timestamps.size() % 2 == 0) ?
(timestamps[mid - 1] + timestamps[mid]) / 2 : timestamps[mid];
return true;
}
bool OracleBundleManager::ValidateConsensusProposal(uint64_t consensus_price, int64_t consensus_timestamp) const
{
if (consensus_price < ORACLE_MIN_PRICE_MICRO_USD ||
consensus_price > ORACLE_MAX_PRICE_MICRO_USD) {
LogPrint(BCLog::DIGIDOLLAR,
"Oracle: Rejecting consensus proposal with out-of-range price=%llu\n",
consensus_price);
return false;
}
uint64_t local_price = 0;
int64_t local_timestamp = 0;
if (!ComputeConsensusValues(local_price, local_timestamp)) {
LogPrint(BCLog::DIGIDOLLAR,
"Oracle: Rejecting consensus proposal price=%llu timestamp=%lld: no local quorum\n",
consensus_price, consensus_timestamp);
return false;
}
if (local_price != consensus_price || local_timestamp != consensus_timestamp) {
LogPrint(BCLog::DIGIDOLLAR,
"Oracle: Rejecting consensus proposal price=%llu timestamp=%lld: local price=%llu timestamp=%lld\n",
consensus_price, consensus_timestamp, local_price, local_timestamp);
return false;
}
return true;
}
COracleBundle OracleBundleManager::GetCurrentBundle(int32_t epoch) const
{
std::lock_guard<std::mutex> lock(mtx_bundles);
auto it = epoch_bundles.find(epoch);
if (it != epoch_bundles.end()) {
return it->second;
}
// Return empty bundle if not found
return COracleBundle(epoch);
}
bool OracleBundleManager::UpdateBundle(const COracleBundle& bundle)
{
if (!IsEnabled()) {
return false;
}
std::lock_guard<std::mutex> lock(mtx_bundles);
epoch_bundles[bundle.epoch] = bundle;
const int32_t newest_epoch = std::max_element(
epoch_bundles.begin(), epoch_bundles.end(),
[](const auto& a, const auto& b) { return a.first < b.first; })->first;
for (auto it = epoch_bundles.begin(); it != epoch_bundles.end(); ) {
if (it->first < newest_epoch - 1) {
LogPrint(BCLog::DIGIDOLLAR, "Oracle: Pruning stale bundle for epoch %d after update\n", it->first);
it = epoch_bundles.erase(it);
} else {
++it;
}
}
LogPrint(BCLog::DIGIDOLLAR, "Oracle: Updated bundle for epoch %d with %d messages\n",
bundle.epoch, bundle.messages.size());
// Only complete MuSig2 bundles may update the latest price cache. Off-chain
// individual-message consensus can coordinate signing but is not canonical.
if (HasMuSig2Quorum(bundle, Params().GetConsensus()) && bundle.epoch >= cached_epoch) {
cached_price = static_cast<CAmount>(bundle.median_price_micro_usd);
cached_epoch = bundle.epoch;
last_update_time = GetTime();
}
return true;
}
bool OracleBundleManager::HasValidBundle(int32_t epoch) const
{
std::lock_guard<std::mutex> lock(mtx_bundles);
auto it = epoch_bundles.find(epoch);
return it != epoch_bundles.end() && HasMuSig2Quorum(it->second, Params().GetConsensus());
}
void OracleBundleManager::CleanupOldBundles(int32_t current_epoch)
{
std::lock_guard<std::mutex> lock(mtx_bundles);
// Keep bundles for current and previous epoch only
auto it = epoch_bundles.begin();
while (it != epoch_bundles.end()) {
if (it->first < current_epoch - 1) {
LogPrint(BCLog::DIGIDOLLAR, "Oracle: Cleaning up old bundle for epoch %d\n", it->first);
it = epoch_bundles.erase(it);
} else {
++it;
}
}
}
bool OracleBundleManager::AddOracleBundleToBlock(CBlock& block, int32_t block_height)
{
const bool block_touches_dd = BlockTouchesDigiDollar(block);
const bool block_needs_oracle_price = BlockNeedsOraclePrice(block);
LogPrint(BCLog::DIGIDOLLAR, "Oracle: AddOracleBundleToBlock called for height %d, enabled=%d, min_oracle_count=%d\n",
block_height, IsEnabled(), GetMinOracleCount());
if (!IsEnabled()) {
if (block_needs_oracle_price) {
LogPrintf("Oracle: price-dependent DD block at height %d requires a MuSig2 bundle, but oracles are disabled\n",
block_height);
} else {
LogPrint(BCLog::DIGIDOLLAR, "Oracle: Oracles disabled, no bundle available for block %d\n", block_height);
}
return false;
}
int32_t epoch = GetCurrentEpoch(block_height);
LogPrint(BCLog::DIGIDOLLAR, "Oracle: Current epoch=%d for height %d\n", epoch, block_height);
// Cleanup stale MuSig2 sessions at epoch boundary (keep current epoch only).
// This prevents unbounded growth of the global session map when epoch advances.
{
LOCK(g_oracle_signing_sessions_mutex);
auto it = g_oracle_signing_sessions.begin();
while (it != g_oracle_signing_sessions.end()) {
if (it->first < epoch) {
LogPrint(BCLog::DIGIDOLLAR, "Oracle: Pruning stale MuSig2 session for epoch %d (current epoch=%d)\n",
it->first, epoch);
it = g_oracle_signing_sessions.erase(it);
} else {
++it;
}
}
}
auto bundle_is_fresh = [&](const COracleBundle& bundle) -> bool {
// Mine only bundles that will still be fresh against the candidate block
// timestamp. Functional tests and real miners can advance mock/adjusted
// time beyond wall-clock GetTime(); using wall time here allowed stale
// cached bundles into templates that TestBlockValidity then rejected.
const int64_t now = std::max<int64_t>(GetTime(), block.nTime);
if (bundle.timestamp <= 0 || bundle.timestamp > now + 60 ||
now - bundle.timestamp > ORACLE_MAX_AGE_SECONDS) {
LogPrintf("Oracle: Refusing stale/future MuSig2 bundle for block %d: timestamp=%lld now=%lld age=%lld max=%d\n",
block_height,
static_cast<long long>(bundle.timestamp),
static_cast<long long>(now),
static_cast<long long>(now - bundle.timestamp),
ORACLE_MAX_AGE_SECONDS);
return false;
}
return true;
};
auto add_bundle_to_coinbase = [&](const COracleBundle& bundle) -> bool {
CScript oracle_script = CreateOracleScript(bundle);
if (oracle_script.empty()) {
return false;
}
CMutableTransaction coinbase_tx(*block.vtx[0]);
CTxOut oracle_output;
oracle_output.nValue = 0;
oracle_output.scriptPubKey = oracle_script;
coinbase_tx.vout.push_back(oracle_output);
block.vtx[0] = MakeTransactionRef(std::move(coinbase_tx));
return true;
};
// V1 is MuSig2-only. The OracleSigningOrchestrator drives the
// MuSig2 protocol asynchronously via BlockConnected callbacks.
// AddOracleBundleToBlock only *queries* for a completed session.
if (g_signing_orchestrator) {
COracleBundle bundle(epoch);
bundle.version = 3;
uint64_t signed_price = 0;
int64_t signed_timestamp = 0;
bool session_ready = g_signing_orchestrator->GetCompletedSession(
epoch, bundle.aggregate_sig, bundle.participation_bitmap,
signed_price, signed_timestamp);
if (session_ready) {
LogPrint(BCLog::DIGIDOLLAR, "Oracle: MuSig2 session for epoch %d is COMPLETE, sig=%zu bytes, bitmap=%zu bytes\n",
epoch, bundle.aggregate_sig.size(), bundle.participation_bitmap.size());
// Use the EXACT values signed by the MuSig2 ceremony
bundle.median_price_micro_usd = signed_price;
bundle.timestamp = signed_timestamp;
std::string error;
if (ValidateMuSig2Bundle(bundle, block_height, Params().GetConsensus(), error) &&
bundle_is_fresh(bundle) &&
add_bundle_to_coinbase(bundle)) {
LogPrint(BCLog::DIGIDOLLAR, "Oracle: Added MuSig2 v0x03 bundle to block %d (epoch %d)\n",
block_height, epoch);
return true;
}
LogPrintf("Oracle: Completed MuSig2 session for epoch %d failed bundle validation: %s\n",
epoch, error);
}
}
COracleBundle cached_bundle = GetCurrentBundle(epoch);
std::string error;
if (ValidateMuSig2Bundle(cached_bundle, block_height, Params().GetConsensus(), error) &&
bundle_is_fresh(cached_bundle) &&
add_bundle_to_coinbase(cached_bundle)) {
LogPrint(BCLog::DIGIDOLLAR, "Oracle: Added cached MuSig2 v0x03 bundle to block %d (epoch %d)\n",
block_height, epoch);
return true;
}
if (block_needs_oracle_price) {
LogPrintf("Oracle: No valid MuSig2 bundle ready for price-dependent DD block %d (epoch %d): %s\n",
block_height, epoch, error);
return false;
}
if (block_touches_dd) {
LogPrint(BCLog::DIGIDOLLAR, "Oracle: MuSig2 not ready/fresh for transfer-only DD block %d (epoch %d); no oracle data added\n",
block_height, epoch);
} else {
LogPrint(BCLog::DIGIDOLLAR, "Oracle: MuSig2 not ready/fresh for epoch %d; no oracle data added to block template\n", epoch);
}
return true;
}
CScript OracleBundleManager::CreateOracleScript(const COracleBundle& bundle) const
{
// MuSig2 v0x03: aggregate signature + participation bitmap
// Format: OP_RETURN OP_ORACLE <version=0x03> <v03_data>
// v03_data: bitmap_len(1) + bitmap(var) + price(8) + timestamp(8) + aggregate_sig(64)
if (bundle.version == 3) {
if (bundle.aggregate_sig.size() != 64) {
LogPrintf("Oracle: CreateOracleScript v0x03 error: aggregate_sig size %zu != 64\n",
bundle.aggregate_sig.size());
return CScript();
}
if (bundle.participation_bitmap.empty()) {
LogPrintf("Oracle: CreateOracleScript v0x03 error: empty participation_bitmap\n");
return CScript();
}
const Consensus::Params& cparams = Params().GetConsensus();
const uint16_t total_oracles = static_cast<uint16_t>(std::max(1, cparams.nOracleTotalOracles));
const std::vector<uint8_t> participants = MuSig2OracleAggregator::DecodeBitmap(
bundle.participation_bitmap, total_oracles);
if (participants.empty()) {
LogPrintf("Oracle: CreateOracleScript v0x03 error: malformed participation_bitmap size=%zu for total_oracles=%u\n",
bundle.participation_bitmap.size(), total_oracles);
return CScript();
}
const int required = std::max(1, cparams.nOracleConsensusRequired);
if (static_cast<int>(participants.size()) < required) {
LogPrintf("Oracle: CreateOracleScript v0x03 error: participation count %zu below threshold %d\n",
participants.size(), required);
return CScript();
}
std::vector<unsigned char> v03_data = bundle.SerializeV03Data();
if (v03_data.empty()) {
LogPrintf("Oracle: CreateOracleScript v0x03 error: SerializeV03Data failed\n");
return CScript();
}
CScript script;
script << OP_RETURN << OP_ORACLE;
script << std::vector<unsigned char>{0x03};
script << v03_data;
LogPrint(BCLog::DIGIDOLLAR, "Oracle: Created MuSig2 v0x03 script with bitmap_bytes=%zu, payload=%zu, price=%llu\n",
bundle.participation_bitmap.size(),
v03_data.size(),
static_cast<unsigned long long>(bundle.median_price_micro_usd));
return script;
}
return CScript();
}
bool OracleBundleManager::ExtractOracleBundle(const CTransaction& coinbase_tx, COracleBundle& bundle) const
{
int oracle_output_count = 0;
for (const auto& output : coinbase_tx.vout) {
if (output.scriptPubKey.size() >= 2 &&
output.scriptPubKey[0] == OP_RETURN &&
output.scriptPubKey[1] == OP_ORACLE) {
++oracle_output_count;
}
}
if (oracle_output_count > 1) {
LogPrintf("Oracle: Rejecting transaction with %d oracle outputs (expected at most 1)\n",
oracle_output_count);
return false;
}
// Look for OP_RETURN output with OP_ORACLE marker
for (const auto& output : coinbase_tx.vout) {
if (output.scriptPubKey.size() > 2 && output.scriptPubKey[0] == OP_RETURN) {
// Check for OP_ORACLE opcode at byte 1
if (output.scriptPubKey.size() >= 4 &&
output.scriptPubKey[1] == OP_ORACLE) {
try {
// Extract data chunks
std::vector<unsigned char> data;
auto script_it = output.scriptPubKey.begin() + 2; // Skip OP_RETURN + OP_ORACLE
while (script_it < output.scriptPubKey.end()) {
if (*script_it <= 75) { // Direct push (1-75 bytes)
unsigned char chunk_size = *script_it;
++script_it;
if (script_it + chunk_size <= output.scriptPubKey.end()) {
data.insert(data.end(), script_it, script_it + chunk_size);
script_it += chunk_size;
} else {
return false;
}
} else if (*script_it == 0x4c) { // OP_PUSHDATA1: next byte is length
++script_it;
if (script_it >= output.scriptPubKey.end()) return false;
unsigned int chunk_size = *script_it;
++script_it;
if (script_it + chunk_size <= output.scriptPubKey.end()) {
data.insert(data.end(), script_it, script_it + chunk_size);
script_it += chunk_size;
} else {
return false;
}
} else if (*script_it == 0x4d) { // OP_PUSHDATA2: next 2 bytes are length (LE)
++script_it;
if (script_it + 2 > output.scriptPubKey.end()) return false;
unsigned int chunk_size = *script_it | (*(script_it + 1) << 8);
script_it += 2;
if (script_it + chunk_size <= output.scriptPubKey.end()) {
data.insert(data.end(), script_it, script_it + chunk_size);
script_it += chunk_size;
} else {
return false;
}
} else {
return false;
}
}
if (data.empty()) {
return false;
}
// Check version byte
if (data[0] == 0x03) {
// v0x03 MuSig2 format: aggregate sig + participation bitmap (RC30)
// Data layout (after version byte):
// bitmap_len(1) + bitmap(variable) + epoch(4) + price(8) + timestamp(8) + aggregate_sig(64)
std::vector<unsigned char> v03_data(data.begin() + 1, data.end());
if (!COracleBundle::DeserializeV03Data(v03_data, bundle)) {
LogPrintf("Oracle: Failed to deserialize v0x03 MuSig2 bundle data (%zu bytes)\n",
v03_data.size());
return false;
}
bundle.version = 3;
// RC30: bundle.epoch is now parsed from the on-chain payload by
// DeserializeV03Data — do NOT zero it here. The validator binds
// the epoch to the current block height in ValidateMuSig2Bundle.
// Wave 3: decode participation bitmap into synthetic oracle messages.
// v0x03 stores one aggregate signature, so per-oracle schnorr_sig is empty.
bundle.messages.clear();
const Consensus::Params& params = Params().GetConsensus();
const uint16_t total_oracles = static_cast<uint16_t>(std::max(1, params.nOracleTotalOracles));
std::vector<uint8_t> oracle_ids = MuSig2OracleAggregator::DecodeBitmap(
bundle.participation_bitmap, total_oracles);
if (oracle_ids.empty()) {
LogPrintf("Oracle: Rejecting v0x03 MuSig2 bundle with malformed participation bitmap (bytes=%zu, total_oracles=%u)\n",
bundle.participation_bitmap.size(), total_oracles);
return false;
}
const CChainParams& chainparams = Params();
for (uint8_t oracle_id : oracle_ids) {
COraclePriceMessage msg;