forked from digibyte/digibyte
-
Notifications
You must be signed in to change notification settings - Fork 96
Expand file tree
/
Copy pathdigidollarwallet.cpp
More file actions
8351 lines (7115 loc) · 370 KB
/
Copy pathdigidollarwallet.cpp
File metadata and controls
8351 lines (7115 loc) · 370 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 <wallet/digidollarwallet.h>
#include <wallet/wallet.h>
#include <wallet/crypter.h>
#include <wallet/spend.h>
#include <wallet/receive.h>
#include <wallet/coincontrol.h>
#include <wallet/scriptpubkeyman.h>
#include <common/args.h>
#include <interfaces/chain.h>
#include <digidollar/txbuilder.h>
#include <digidollar/validation.h>
#include <digidollar/scripts.h>
#include <util/strencodings.h>
#include <logging.h>
#include <util/time.h>
#include <kernel/chainparams.h>
#include <chainparams.h>
#include <crypto/common.h>
#include <streams.h>
#include <script/sign.h>
#include <script/signingprovider.h>
#include <script/interpreter.h>
#include <random.h>
#include <key_io.h>
#include <oracle/mock_oracle.h>
#include <oracle/bundle_manager.h>
#include <coins.h>
#include <policy/policy.h>
#include <algorithm>
#include <limits>
#include <map>
#include <regex>
#include <set>
namespace {
static constexpr CAmount MIN_DD_TRANSFER_FEE_RATE{35000000}; // 0.35 DGB/kB
static constexpr CAmount MIN_DD_TRANSFER_FEE{10000000}; // 0.1 DGB
static constexpr CAmount TRANSFER_BUILDER_PRICE_UNUSED{1}; // Transfers are price-independent.
CScript BuildDDTransferMetadataScript(const std::vector<CAmount>& amounts)
{
CScript metadata;
metadata << OP_RETURN << std::vector<unsigned char>{'D', 'D'} << CScriptNum(2);
for (const CAmount amount : amounts) metadata << CScriptNum(amount);
return metadata;
}
bool PreflightDDTransferCapacity(const DigiDollar::TxBuilderTransferParams& params,
CAmount selected_dd_total,
CAmount total_dd_out,
std::string& error,
size_t* projected_vsize = nullptr,
CAmount* projected_fee = nullptr)
{
std::vector<CAmount> dd_output_amounts;
dd_output_amounts.reserve(params.recipients.size() + 1);
for (const auto& [address, amount] : params.recipients) dd_output_amounts.push_back(amount);
const CAmount dd_change = selected_dd_total - total_dd_out;
if (dd_change > 0) dd_output_amounts.push_back(dd_change);
const CScript metadata = BuildDDTransferMetadataScript(dd_output_amounts);
if (metadata.size() > MAX_OP_RETURN_RELAY) {
error = strprintf("Too many DigiDollar outputs for one transaction: metadata is %u bytes, standard relay limit is %u bytes. Reduce recipients or split into multiple sendmanydigidollar calls.",
static_cast<unsigned>(metadata.size()), MAX_OP_RETURN_RELAY);
return false;
}
CMutableTransaction projected;
projected.SetDigiDollarType(::DD_TX_TRANSFER);
for (const auto& utxo : params.ddUtxos) projected.vin.push_back(CTxIn(utxo));
for (const auto& utxo : params.feeUtxos) projected.vin.push_back(CTxIn(utxo));
for (const auto& [address, amount] : params.recipients) {
CTxDestination dest = DecodeDigiDollarAddress(address);
const auto* taproot = std::get_if<WitnessV1Taproot>(&dest);
if (!taproot) {
error = "Invalid DigiDollar recipient address during capacity preflight";
return false;
}
CScript dd_script;
dd_script << OP_1 << ToByteVector(*taproot);
projected.vout.push_back(CTxOut(0, dd_script));
}
if (dd_change > 0) {
CScript change_script;
change_script << OP_1 << std::vector<unsigned char>(32, 0);
projected.vout.push_back(CTxOut(0, change_script));
}
// Worst-case DGB fee change output; including it makes the preflight deterministic and conservative.
projected.vout.push_back(CTxOut(1, CScript() << OP_0 << std::vector<unsigned char>(20, 0)));
projected.vout.push_back(CTxOut(0, metadata));
const size_t vsize = DigiDollar::EstimateTransactionVSize(projected);
const int64_t weight = static_cast<int64_t>(vsize) * WITNESS_SCALE_FACTOR;
if (weight > MAX_STANDARD_TX_WEIGHT) {
error = strprintf("Projected DigiDollar transaction is too large: %d weight units (%u vB), standard limit is %d WU. Reduce recipients or consolidate DD/DGB UTXOs first.",
weight, static_cast<unsigned>(vsize), MAX_STANDARD_TX_WEIGHT);
return false;
}
const CAmount fee = std::max<CAmount>((static_cast<CAmount>(vsize) * MIN_DD_TRANSFER_FEE_RATE) / 1000, MIN_DD_TRANSFER_FEE);
if (projected_vsize) *projected_vsize = vsize;
if (projected_fee) *projected_fee = fee;
return true;
}
} // namespace
static bool DDChangeIsStandard(CAmount selected_total, CAmount target_amount)
{
if (selected_total < target_amount) return false;
const CAmount change = selected_total - target_amount;
return change == 0 || change >= Params().GetDigiDollarParams().minOutputAmount;
}
static std::string DDChangePolicyError(CAmount selected_total, CAmount target_amount)
{
if (selected_total < target_amount) {
return strprintf("Insufficient selected DD input amount. Selected: %lld cents, Required: %lld cents",
static_cast<long long>(selected_total), static_cast<long long>(target_amount));
}
const CAmount change = selected_total - target_amount;
return strprintf("Selected DD input change is below minimum DigiDollar output. Change: %lld cents, Minimum: %lld cents",
static_cast<long long>(change),
static_cast<long long>(Params().GetDigiDollarParams().minOutputAmount));
}
static bool IsStandardDDTokenOutput(const CTxOut& txout)
{
int witness_version = -1;
std::vector<unsigned char> witness_program;
return txout.nValue == 0 &&
txout.scriptPubKey.IsWitnessProgram(witness_version, witness_program) &&
witness_version == 1 &&
witness_program.size() == WITNESS_V1_TAPROOT_SIZE;
}
static bool IsCanonicalP2TROutput(const CScript& script)
{
int witness_version = -1;
std::vector<unsigned char> witness_program;
return script.IsWitnessProgram(witness_version, witness_program) &&
witness_version == 1 &&
witness_program.size() == WITNESS_V1_TAPROOT_SIZE;
}
struct MintOutputIndexes {
uint32_t collateral_index{std::numeric_limits<uint32_t>::max()};
uint32_t dd_token_index{std::numeric_limits<uint32_t>::max()};
CAmount collateral_amount{0};
};
static bool FindMintOutputIndexes(const CTransaction& tx, MintOutputIndexes& indexes)
{
indexes = {};
if (DigiDollar::GetDigiDollarTxType(tx) != DigiDollar::DD_TX_MINT) {
return false;
}
int collateral_count = 0;
int dd_token_count = 0;
for (uint32_t i = 0; i < tx.vout.size(); ++i) {
const CTxOut& txout = tx.vout[i];
if (!IsCanonicalP2TROutput(txout.scriptPubKey)) {
continue;
}
if (txout.nValue > 0) {
++collateral_count;
indexes.collateral_index = i;
indexes.collateral_amount = txout.nValue;
} else if (txout.nValue == 0) {
++dd_token_count;
indexes.dd_token_index = i;
}
}
return collateral_count == 1 &&
dd_token_count == 1 &&
indexes.collateral_amount > 0;
}
static std::vector<CAmount> ExtractDDMetadataAmounts(const CTransaction& tx, int expected_type)
{
std::vector<CAmount> amounts;
for (const CTxOut& txout : tx.vout) {
const CScript& script = txout.scriptPubKey;
if (script.empty() || script[0] != OP_RETURN) continue;
auto pc = script.begin();
opcodetype opcode;
std::vector<unsigned char> data;
if (!script.GetOp(pc, opcode, data) || opcode != OP_RETURN) continue;
if (!script.GetOp(pc, opcode, data)) continue;
if (data.size() != 2 || data[0] != 'D' || data[1] != 'D') continue;
if (!script.GetOp(pc, opcode, data)) continue;
try {
CScriptNum tx_type(data, true);
if (tx_type.getint() != expected_type) return {};
while (script.GetOp(pc, opcode, data)) {
if (data.empty()) continue;
CScriptNum amount(data, true, 8);
const CAmount value = amount.GetInt64();
if (value > 0) amounts.push_back(value);
}
} catch (const scriptnum_error&) {
return {};
}
break;
}
return amounts;
}
// CDigiDollarAddress is defined in base58.h - no need to redefine
// =============================================================================
// DDTransaction Implementation
// =============================================================================
DDTransaction::DDTransaction()
: amount(0), timestamp(0), confirmations(0), incoming(false), category("unknown"),
blockheight(-1), blockhash(""), fee(0), comment(""), abandoned(false), lock_tier(-1),
in_mempool(false), is_local(false) {}
// =============================================================================
// DigiDollarWallet Implementation
// =============================================================================
DigiDollarWallet::DigiDollarWallet() : mockBalance(0), total_dd_balance(0), locked_collateral(0), m_wallet(nullptr) {
// Initialize with some test data for development
LogPrintf("DigiDollar: Wallet initialized\n");
}
DigiDollarWallet::DigiDollarWallet(wallet::CWallet* wallet) : mockBalance(0), total_dd_balance(0), locked_collateral(0), m_wallet(wallet) {
LogPrintf("DigiDollar: Wallet initialized with CWallet pointer\n");
// Load existing DigiDollar data from database
if (m_wallet) {
size_t loaded = LoadFromDatabase();
LogPrintf("DigiDollarWallet: Initialized with %d items from database\n", loaded);
}
}
size_t DigiDollarWallet::LoadFromDatabase()
{
LOCK(cs_dd_wallet);
if (!m_wallet) {
LogPrint(BCLog::WALLETDB, "DigiDollarWallet::LoadFromDatabase - No wallet pointer\n");
return 0;
}
LogPrint(BCLog::WALLETDB, "DigiDollarWallet: Loading data from database...\n");
size_t positions_loaded = LoadPositionsFromDatabase();
size_t balances_loaded = LoadBalancesFromDatabase();
size_t txs_loaded = LoadTransactionsFromDatabase();
// FIX #1: Load DD UTXOs from database
size_t utxos_loaded = 0;
wallet::WalletBatch batch(m_wallet->GetDatabase());
dd_utxos.clear();
std::unique_ptr<wallet::DatabaseCursor> cursor = batch.GetNewCursor();
if (cursor) {
wallet::DatabaseCursor::Status status = wallet::DatabaseCursor::Status::MORE;
while (status == wallet::DatabaseCursor::Status::MORE) {
DataStream key{};
DataStream value{};
status = cursor->Next(key, value);
if (status != wallet::DatabaseCursor::Status::MORE) break;
std::string key_type;
key >> key_type;
if (key_type == wallet::DBKeys::DD_OUTPUT) {
COutPoint outpoint;
key >> outpoint;
CAmount dd_amount;
value >> dd_amount;
dd_utxos[outpoint] = dd_amount;
utxos_loaded++;
LogPrint(BCLog::WALLETDB, "DigiDollarWallet: Loaded DD UTXO %s:%u (%lld cents)\n",
outpoint.hash.ToString(), outpoint.n, static_cast<long long>(dd_amount));
}
}
}
// Load DD address keys for received tokens (FIX for wallet restart key loss)
size_t addr_keys_loaded = LoadDDAddressKeys();
// Load DD owner keys for minted tokens (FIX for vault redemption after restart)
size_t owner_keys_loaded = LoadDDOwnerKeys();
size_t total = positions_loaded + balances_loaded + txs_loaded + utxos_loaded + addr_keys_loaded + owner_keys_loaded;
LogPrintf("DigiDollarWallet: Loaded %zu positions, %zu balances, %zu transactions, %zu DD UTXOs, %zu DD address keys, %zu DD owner keys\n",
positions_loaded, balances_loaded, txs_loaded, utxos_loaded, addr_keys_loaded, owner_keys_loaded);
// CRITICAL FIX: Lock collateral UTXOs for all active DD positions
// This ensures the wallet's regular DGB coin selection never picks
// collateral UTXOs after a restart. Without this, the wallet could
// create transactions that try to spend time-locked collateral,
// causing them to get stuck as unconfirmed.
size_t locked_count = 0;
if (m_wallet) {
wallet::WalletBatch lock_batch(m_wallet->GetDatabase());
for (const auto& [pos_id, pos] : collateral_positions) {
if (pos.is_active) {
COutPoint collateralOutpoint(pos.dd_timelock_id, 0);
COutPoint ddTokenOutpoint(pos.dd_timelock_id, 1);
auto tx_it = m_wallet->mapWallet.find(pos.dd_timelock_id);
if (tx_it != m_wallet->mapWallet.end() && tx_it->second.tx) {
MintOutputIndexes mint_outputs;
if (FindMintOutputIndexes(*tx_it->second.tx, mint_outputs)) {
collateralOutpoint = COutPoint(pos.dd_timelock_id, mint_outputs.collateral_index);
ddTokenOutpoint = COutPoint(pos.dd_timelock_id, mint_outputs.dd_token_index);
}
}
if (!m_wallet->IsLockedCoin(collateralOutpoint)) {
if (m_wallet->LockCoin(collateralOutpoint, &lock_batch)) {
locked_count++;
}
}
if (!m_wallet->IsLockedCoin(ddTokenOutpoint)) {
if (m_wallet->LockCoin(ddTokenOutpoint, &lock_batch)) {
locked_count++;
}
}
}
}
if (locked_count > 0) {
LogPrintf("DigiDollarWallet: Locked %zu collateral/DD-token UTXOs from %zu active positions\n",
locked_count, collateral_positions.size());
}
}
// Recalculate totals
RecalculateTotals();
return total;
}
size_t DigiDollarWallet::LoadPositionsFromDatabase()
{
LOCK(cs_dd_wallet);
wallet::WalletBatch batch(m_wallet->GetDatabase());
size_t count = 0;
// Clear in-memory positions
collateral_positions.clear();
// Iterate through database using cursor
std::unique_ptr<wallet::DatabaseCursor> cursor = batch.GetNewCursor();
if (!cursor) {
LogPrint(BCLog::WALLETDB, "DigiDollarWallet: Failed to get database cursor\n");
return 0;
}
wallet::DatabaseCursor::Status status = wallet::DatabaseCursor::Status::MORE;
while (status == wallet::DatabaseCursor::Status::MORE) {
DataStream key{};
DataStream value{};
status = cursor->Next(key, value);
if (status != wallet::DatabaseCursor::Status::MORE) break;
// Check if this is a position entry
std::string key_type;
key >> key_type;
if (key_type == wallet::DBKeys::DD_POSITION) {
uint256 dd_timelock_id;
key >> dd_timelock_id;
WalletCollateralPosition position;
value >> position;
collateral_positions[dd_timelock_id] = position;
count++;
LogPrint(BCLog::WALLETDB, "DigiDollarWallet: Loaded position %s\n",
dd_timelock_id.ToString());
}
}
return count;
}
size_t DigiDollarWallet::LoadBalancesFromDatabase()
{
LOCK(cs_dd_wallet);
wallet::WalletBatch batch(m_wallet->GetDatabase());
size_t count = 0;
dd_balances.clear();
std::unique_ptr<wallet::DatabaseCursor> cursor = batch.GetNewCursor();
if (!cursor) return 0;
wallet::DatabaseCursor::Status status = wallet::DatabaseCursor::Status::MORE;
while (status == wallet::DatabaseCursor::Status::MORE) {
DataStream key{};
DataStream value{};
status = cursor->Next(key, value);
if (status != wallet::DatabaseCursor::Status::MORE) break;
std::string key_type;
key >> key_type;
if (key_type == wallet::DBKeys::DD_BALANCE) {
std::string address;
key >> address;
WalletDDBalance balance;
value >> balance;
dd_balances[address] = balance;
count++;
LogPrint(BCLog::WALLETDB, "DigiDollarWallet: Loaded balance for %s\n", address);
}
}
return count;
}
size_t DigiDollarWallet::LoadTransactionsFromDatabase()
{
LOCK(cs_dd_wallet);
wallet::WalletBatch batch(m_wallet->GetDatabase());
size_t count = 0;
transaction_history.clear();
std::unique_ptr<wallet::DatabaseCursor> cursor = batch.GetNewCursor();
if (!cursor) return 0;
wallet::DatabaseCursor::Status status = wallet::DatabaseCursor::Status::MORE;
while (status == wallet::DatabaseCursor::Status::MORE) {
DataStream key{};
DataStream value{};
status = cursor->Next(key, value);
if (status != wallet::DatabaseCursor::Status::MORE) break;
std::string key_type;
key >> key_type;
if (key_type == wallet::DBKeys::DD_TRANSACTION) {
uint256 txid;
key >> txid;
DDTransaction ddtx;
value >> ddtx;
transaction_history.push_back(ddtx);
count++;
LogPrint(BCLog::WALLETDB, "DigiDollarWallet: Loaded transaction %s\n", ddtx.txid);
}
}
return count;
}
void DigiDollarWallet::RecalculateTotals()
{
LOCK(cs_dd_wallet);
// Recalculate total DD balance
total_dd_balance = 0;
for (const auto& [addr, bal] : dd_balances) {
total_dd_balance += bal.balance;
}
// Recalculate locked collateral
locked_collateral = 0;
for (const auto& [id, pos] : collateral_positions) {
if (pos.is_active) {
locked_collateral += pos.dgb_collateral;
}
}
LogPrint(BCLog::WALLETDB, "DigiDollarWallet: Totals - DD Balance: %lld, Locked: %lld\n",
static_cast<long long>(total_dd_balance), static_cast<long long>(locked_collateral));
}
// =============================================================================
// T4-03a: Encrypt existing DD keys when wallet encryption is enabled
// =============================================================================
bool DigiDollarWallet::EncryptDDKeys(const wallet::CKeyingMaterial& vMasterKey, wallet::WalletBatch* encrypted_batch)
{
LOCK(cs_dd_wallet);
LogPrintf("DigiDollarWallet: Encrypting %zu owner keys and %zu address keys\n",
dd_owner_keys.size(), dd_address_keys.size());
bool use_external_batch = (encrypted_batch != nullptr);
// Encrypt all plaintext owner keys
for (const auto& [timelock_id, key] : dd_owner_keys) {
CPubKey pubkey = key.GetPubKey();
wallet::CKeyingMaterial vchSecret(key.begin(), key.end());
std::vector<unsigned char> vchCryptedSecret;
if (!wallet::EncryptSecret(vMasterKey, vchSecret, pubkey.GetHash(), vchCryptedSecret)) {
LogPrintf("DigiDollarWallet: ERROR - Failed to encrypt DD owner key for timelock %s\n",
timelock_id.ToString());
return false;
}
dd_crypted_owner_keys[timelock_id] = std::make_pair(pubkey, vchCryptedSecret);
// Persist to database
if (use_external_batch) {
if (!encrypted_batch->WriteCryptedDDOwnerKey(timelock_id, pubkey, vchCryptedSecret)) {
LogPrintf("DigiDollarWallet: ERROR - Failed to write encrypted DD owner key to database\n");
return false;
}
} else if (m_wallet) {
wallet::WalletBatch batch(m_wallet->GetDatabase());
if (!batch.WriteCryptedDDOwnerKey(timelock_id, pubkey, vchCryptedSecret)) {
LogPrintf("DigiDollarWallet: ERROR - Failed to write encrypted DD owner key to database\n");
return false;
}
}
}
// Encrypt all plaintext address keys
for (const auto& [key_bytes, key] : dd_address_keys) {
CPubKey pubkey = key.GetPubKey();
wallet::CKeyingMaterial vchSecret(key.begin(), key.end());
std::vector<unsigned char> vchCryptedSecret;
if (!wallet::EncryptSecret(vMasterKey, vchSecret, pubkey.GetHash(), vchCryptedSecret)) {
LogPrintf("DigiDollarWallet: ERROR - Failed to encrypt DD address key %s\n",
HexStr(key_bytes));
return false;
}
dd_crypted_address_keys[key_bytes] = std::make_pair(pubkey, vchCryptedSecret);
// Persist to database
if (use_external_batch) {
if (!encrypted_batch->WriteCryptedDDAddressKey(key_bytes, pubkey, vchCryptedSecret)) {
LogPrintf("DigiDollarWallet: ERROR - Failed to write encrypted DD address key to database\n");
return false;
}
} else if (m_wallet) {
wallet::WalletBatch batch(m_wallet->GetDatabase());
if (!batch.WriteCryptedDDAddressKey(key_bytes, pubkey, vchCryptedSecret)) {
LogPrintf("DigiDollarWallet: ERROR - Failed to write encrypted DD address key to database\n");
return false;
}
}
}
// Erase plaintext keys from the DATABASE before clearing memory.
// Without this, a forensic attacker could read wallet.dat and find
// plaintext DD_OWNER_KEY / DD_ADDRESS_KEY entries alongside encrypted ones.
if (m_wallet) {
wallet::WalletBatch* erase_batch = use_external_batch ? encrypted_batch : nullptr;
std::unique_ptr<wallet::WalletBatch> local_batch;
if (!erase_batch) {
local_batch = std::make_unique<wallet::WalletBatch>(m_wallet->GetDatabase());
erase_batch = local_batch.get();
}
for (const auto& [timelock_id, key] : dd_owner_keys) {
if (!erase_batch->EraseDDOwnerKey(timelock_id)) {
LogPrintf("DigiDollarWallet: WARNING - Failed to erase plaintext DD owner key %s from database\n",
timelock_id.ToString());
}
}
for (const auto& [key_bytes, key] : dd_address_keys) {
if (!erase_batch->EraseDDAddressKey(key_bytes)) {
LogPrintf("DigiDollarWallet: WARNING - Failed to erase plaintext DD address key %s from database\n",
HexStr(key_bytes));
}
}
}
// Clear plaintext keys from memory — they are now encrypted
dd_owner_keys.clear();
dd_address_keys.clear();
dd_foreign_output_keys.clear();
LogPrintf("DigiDollarWallet: Successfully encrypted %zu owner keys and %zu address keys\n",
dd_crypted_owner_keys.size(), dd_crypted_address_keys.size());
return true;
}
void DigiDollarWallet::StoreAddressKey(const XOnlyPubKey& output_key, const CKey& key)
{
LOCK(cs_dd_wallet);
std::array<unsigned char, 32> key_bytes;
std::copy(output_key.begin(), output_key.end(), key_bytes.begin());
dd_foreign_output_keys.erase(key_bytes);
LogPrintf("DigiDollarWallet: Storing DD address key for output key %s\n",
HexStr(output_key));
// If wallet is encrypted, encrypt the key before storage (T4-03a)
if (m_wallet && m_wallet->IsCrypted()) {
CPubKey pubkey = key.GetPubKey();
wallet::CKeyingMaterial vchSecret(key.begin(), key.end());
std::vector<unsigned char> vchCryptedSecret;
if (!wallet::EncryptSecret(m_wallet->GetEncryptionKey(), vchSecret, pubkey.GetHash(), vchCryptedSecret)) {
LogPrintf("DigiDollarWallet: ERROR - Failed to encrypt DD address key\n");
return;
}
// Store encrypted in memory
dd_crypted_address_keys[key_bytes] = std::make_pair(pubkey, vchCryptedSecret);
// Remove any plaintext version from memory
dd_address_keys.erase(key_bytes);
// Persist encrypted to database
if (m_wallet) {
wallet::WalletBatch batch(m_wallet->GetDatabase());
if (!batch.WriteCryptedDDAddressKey(key_bytes, pubkey, vchCryptedSecret)) {
LogPrintf("DigiDollarWallet: WARNING - Failed to persist encrypted DD address key to database\n");
} else {
LogPrintf("DigiDollarWallet: Persisted encrypted DD address key to database\n");
}
}
} else {
// Store plaintext in memory
dd_address_keys[key_bytes] = key;
// Persist plaintext to wallet database
if (m_wallet) {
wallet::WalletBatch batch(m_wallet->GetDatabase());
if (!batch.WriteDDAddressKey(key_bytes, key)) {
LogPrintf("DigiDollarWallet: WARNING - Failed to persist DD address key to database\n");
} else {
LogPrintf("DigiDollarWallet: Persisted DD address key to database\n");
}
}
}
}
size_t DigiDollarWallet::LoadDDAddressKeys()
{
LOCK(cs_dd_wallet);
if (!m_wallet) {
LogPrint(BCLog::WALLETDB, "DigiDollarWallet::LoadDDAddressKeys - No wallet pointer\n");
return 0;
}
wallet::WalletBatch batch(m_wallet->GetDatabase());
size_t count = 0;
// Clear in-memory maps before loading
dd_address_keys.clear();
dd_crypted_address_keys.clear();
dd_foreign_output_keys.clear();
// Iterate through database to find DD address keys (both plaintext and encrypted)
std::unique_ptr<wallet::DatabaseCursor> cursor = batch.GetNewCursor();
if (cursor) {
wallet::DatabaseCursor::Status status = wallet::DatabaseCursor::Status::MORE;
while (status == wallet::DatabaseCursor::Status::MORE) {
DataStream key_stream{};
DataStream value_stream{};
status = cursor->Next(key_stream, value_stream);
if (status != wallet::DatabaseCursor::Status::MORE) break;
std::string key_type;
key_stream >> key_type;
if (key_type == wallet::DBKeys::DD_ADDRESS_KEY) {
// Plaintext DD address key (unencrypted wallet)
std::array<unsigned char, 32> output_key_bytes;
key_stream >> output_key_bytes;
CPrivKey privkey;
value_stream >> privkey;
std::array<unsigned char, CPubKey::COMPRESSED_SIZE> compressed_dummy{};
compressed_dummy[0] = 0x02;
CPubKey dummy_pubkey(compressed_dummy.begin(), compressed_dummy.end());
CKey key;
if (key.Load(privkey, dummy_pubkey, /*fSkipCheck=*/true)) {
dd_address_keys[output_key_bytes] = key;
count++;
LogPrint(BCLog::WALLETDB, "DigiDollarWallet: Loaded plaintext DD address key %s\n",
HexStr(output_key_bytes));
} else {
LogPrintf("DigiDollarWallet: WARNING - Failed to load DD address key from database\n");
}
} else if (key_type == wallet::DBKeys::DD_CRYPTED_ADDRESS_KEY) {
// Encrypted DD address key (T4-03a: encrypted wallet)
std::array<unsigned char, 32> output_key_bytes;
key_stream >> output_key_bytes;
std::pair<CPubKey, std::vector<unsigned char>> val;
value_stream >> val;
dd_crypted_address_keys[output_key_bytes] = val;
count++;
LogPrint(BCLog::WALLETDB, "DigiDollarWallet: Loaded encrypted DD address key %s\n",
HexStr(output_key_bytes));
}
}
}
LogPrintf("DigiDollarWallet: Loaded %zu DD address keys (%zu plaintext, %zu encrypted) from database\n",
count, dd_address_keys.size(), dd_crypted_address_keys.size());
return count;
}
bool DigiDollarWallet::IsDDOutputMine(const CTxOut& txout, const uint256& txid) const
{
auto locks = LockDDWallet();
// First check if this is a DD output (P2TR with value=0)
if (txout.nValue != 0 || txout.scriptPubKey.size() != 34 || txout.scriptPubKey[0] != OP_1) {
return false;
}
// Try standard wallet IsMine first — require SPENDABLE to exclude watch-only
// SECURITY [T4-04]: Using ISMINE_SPENDABLE prevents watch-only DD balance contamination
if (m_wallet && (m_wallet->IsMine(txout) & wallet::ISMINE_SPENDABLE)) {
return true;
}
// Check if this is a MINT output that we've already identified as ours
// This handles the case where dd_owner_keys is empty (e.g., after wallet restore)
// but we've already processed the MINT tx and added it to collateral_positions
if (collateral_positions.count(txid) > 0) {
// This txid is a MINT we own, so its canonical DD token output is ours.
return true;
}
// Extract the P2TR output key from the scriptPubKey
// P2TR scripts are: OP_1 <32-byte-output-key>
std::vector<unsigned char> output_key_bytes(txout.scriptPubKey.begin() + 2, txout.scriptPubKey.end());
std::array<unsigned char, 32> output_key_array;
std::copy(output_key_bytes.begin(), output_key_bytes.end(), output_key_array.begin());
// Check dd_owner_keys - first try the specific txid, then check ALL owner keys
// This is needed because TRANSFER change outputs use the owner key from the original
// MINT (stored under MINT txid), not the TRANSFER txid.
CKey owner_key;
if (GetOwnerKey(txid, owner_key)) {
// Compute what the tweaked key should be from this owner_key
XOnlyPubKey owner_xonly(owner_key.GetPubKey());
auto tweaked = owner_xonly.CreateTapTweak(nullptr);
if (tweaked) {
// Check if tweaked key matches output key
if (std::equal(output_key_bytes.begin(), output_key_bytes.end(),
tweaked->first.begin())) {
return true;
}
}
}
// Check ALL owner keys - necessary for TRANSFER change outputs where the key
// is from the original MINT but we're checking with the TRANSFER's txid
for (const auto& [key_txid, key] : dd_owner_keys) {
if (key_txid == txid) continue; // Already checked above
XOnlyPubKey owner_xonly(key.GetPubKey());
auto tweaked = owner_xonly.CreateTapTweak(nullptr);
if (tweaked) {
if (std::equal(output_key_bytes.begin(), output_key_bytes.end(),
tweaked->first.begin())) {
return true;
}
}
}
// T4-03a: Also check encrypted owner keys. We can check pubkey-derived
// tweaked keys without decrypting the secret, which lets locked encrypted
// wallets recognize their own DD outputs during rescan without exposing keys.
for (const auto& [key_txid, crypted_pair] : dd_crypted_owner_keys) {
const CPubKey& pubkey = crypted_pair.first;
XOnlyPubKey owner_xonly(pubkey);
auto tweaked = owner_xonly.CreateTapTweak(nullptr);
if (tweaked) {
if (std::equal(output_key_bytes.begin(), output_key_bytes.end(),
tweaked->first.begin())) {
return true;
}
}
}
// Check dd_address_keys (for DD addresses generated via getdigidollaraddress)
XOnlyPubKey output_key(output_key_bytes);
CKey address_key;
if (GetAddressKey(output_key, address_key)) {
return true;
}
if (dd_foreign_output_keys.count(output_key_array) > 0) {
LogPrint(BCLog::DIGIDOLLAR, "DigiDollar: IsDDOutputMine - cached foreign output_key=%s\n",
HexStr(output_key_bytes));
return false;
}
// WALLET RESTORE FIX: After descriptor import, dd_address_keys may be
// only partially rebuilt. DD addresses are created by taking a wallet key
// and applying TapTweak(nullptr). The wallet has the base keys from
// descriptors, but not necessarily every DD-tweaked output cached yet.
// Try to find a wallet key that, when DD-tweaked, matches this output key.
if (m_wallet) {
LogPrint(BCLog::DIGIDOLLAR, "DigiDollar: IsDDOutputMine: trying descriptor key derivation for output_key=%s\n",
HexStr(output_key_bytes));
LOCK(m_wallet->cs_wallet);
int spk_man_count = 0;
int p2tr_script_count = 0;
int provider_count = 0;
int spenddata_count = 0;
int key_count = 0;
bool found_target_in_scripts = false;
// Enumerate ALL P2TR scripts from all descriptor managers
// This includes keys that were reserved via GetNewDestination but not used in transactions
for (auto* spk_man : m_wallet->GetAllScriptPubKeyMans()) {
auto* desc_spk = dynamic_cast<wallet::DescriptorScriptPubKeyMan*>(spk_man);
if (!desc_spk) continue;
spk_man_count++;
// Get all scripts this descriptor knows about
auto scripts = desc_spk->GetScriptPubKeys();
for (const auto& script : scripts) {
// Skip non-P2TR scripts
if (script.size() != 34 || script[0] != OP_1) {
continue;
}
p2tr_script_count++;
// Extract the output key from this script (bytes 2-33)
std::vector<unsigned char> script_output_key(script.begin() + 2, script.end());
// Check if THIS script has our target output_key (direct match - no tweak needed)
if (std::equal(output_key_bytes.begin(), output_key_bytes.end(), script_output_key.begin())) {
found_target_in_scripts = true;
LogPrint(BCLog::DIGIDOLLAR, "DigiDollar: IsDDOutputMine - output_key found directly in descriptor script\n");
// Get signing provider with keys for this script
auto provider = desc_spk->GetSigningProviderWithKeys(script);
if (provider) {
CTxDestination dest;
if (ExtractDestination(script, dest)) {
auto* taproot_dest = std::get_if<WitnessV1Taproot>(&dest);
if (taproot_dest) {
TaprootSpendData spenddata;
if (provider->GetTaprootSpendData(XOnlyPubKey(*taproot_dest), spenddata)) {
CKey internal_key;
if (provider->GetKeyByXOnly(spenddata.internal_key, internal_key)) {
// Store the internal key for this DD output
LogPrint(BCLog::DIGIDOLLAR, "DigiDollar: IsDDOutputMine - direct descriptor match, storing internal key\n");
const_cast<DigiDollarWallet*>(this)->StoreAddressKey(output_key, internal_key);
return true;
}
}
}
}
}
LogPrint(BCLog::DIGIDOLLAR, "DigiDollar: IsDDOutputMine - descriptor script matched but key extraction failed\n");
}
// Get signing provider with keys for this script
auto provider = desc_spk->GetSigningProviderWithKeys(script);
if (!provider) continue;
provider_count++;
// Extract destination and get Taproot spend data
CTxDestination dest;
if (!ExtractDestination(script, dest)) {
continue;
}
auto* taproot_dest = std::get_if<WitnessV1Taproot>(&dest);
if (!taproot_dest) {
continue;
}
TaprootSpendData spenddata;
if (!provider->GetTaprootSpendData(XOnlyPubKey(*taproot_dest), spenddata)) {
continue;
}
spenddata_count++;
if (!spenddata.internal_key.IsFullyValid()) {
continue;
}
CKey test_key;
if (!provider->GetKeyByXOnly(spenddata.internal_key, test_key)) {
continue;
}
key_count++;
// Apply DD tweak (nullptr merkle root) and check if it matches
XOnlyPubKey test_xonly(test_key.GetPubKey());
auto tweaked = test_xonly.CreateTapTweak(nullptr);
// Debug: Log first few computed DD output keys
if (key_count <= 3) {
LogPrint(BCLog::DIGIDOLLAR, "DigiDollar: IsDDOutputMine - key %d: internal=%s, pubkey=%s, dd_tweaked=%s\n",
key_count,
HexStr(Span<const unsigned char>(spenddata.internal_key.begin(), spenddata.internal_key.end())),
HexStr(Span<const unsigned char>(test_xonly.begin(), test_xonly.end())),
tweaked ? HexStr(Span<const unsigned char>(tweaked->first.begin(), tweaked->first.end())) : "FAILED");
}
if (tweaked && std::equal(output_key_bytes.begin(), output_key_bytes.end(),
tweaked->first.begin())) {
// Found a match! Cache it in dd_address_keys for future lookups
LogPrint(BCLog::DIGIDOLLAR, "DigiDollar: IsDDOutputMine - found key via descriptor scan, caching DD address key\n");
const_cast<DigiDollarWallet*>(this)->StoreAddressKey(output_key, test_key);
return true;
}
}
}
LogPrint(BCLog::DIGIDOLLAR, "DigiDollar: IsDDOutputMine - no match found. Stats: spk_mans=%d, p2tr_scripts=%d, providers=%d, spenddata=%d, keys=%d, target_in_scripts=%d\n",
spk_man_count, p2tr_script_count, provider_count, spenddata_count, key_count, found_target_in_scripts);
dd_foreign_output_keys.insert(output_key_array);
}
return false;
}
bool DigiDollarWallet::IsDDOutputMine(const COutPoint& outpoint) const
{
auto locks = LockDDWallet();
// PRIMARY CHECK: If it's in dd_utxos, we own it
// This is the source of truth for DD ownership (like mapWallet for DGB)
// CRITICAL for detecting TRANSFER change outputs after wallet restore,
// where dd_owner_keys is empty and IsDDOutputMine(txout, txid) would fail.
if (dd_utxos.find(outpoint) != dd_utxos.end()) {
LogPrint(BCLog::DIGIDOLLAR, "IsDDOutputMine(COutPoint): %s:%u found in dd_utxos - returning true\n",
outpoint.hash.GetHex(), outpoint.n);
return true;
}
// SECONDARY CHECK: Fall back to txout-based check for new outputs
// This handles outputs we haven't yet added to dd_utxos
if (m_wallet) {
LOCK(m_wallet->cs_wallet);
auto it = m_wallet->mapWallet.find(outpoint.hash);
if (it != m_wallet->mapWallet.end() && outpoint.n < it->second.tx->vout.size()) {
return IsDDOutputMine(it->second.tx->vout[outpoint.n], outpoint.hash);
}
}
return false;
}
bool DigiDollarWallet::IsMyDDAddress(const std::string& addrStr) const
{
auto locks = LockDDWallet();
// Check dd_balances (addresses that have received DD)
if (dd_balances.count(addrStr) > 0) return true;
// Check dd_address_keys via output_key from DD address
CDigiDollarAddress dd_addr(addrStr);
if (dd_addr.IsValid()) {
CTxDestination dest = dd_addr.GetDigiDollarDestination();
if (auto* tr = std::get_if<WitnessV1Taproot>(&dest)) {
std::array<unsigned char, 32> key_bytes;
std::copy(tr->begin(), tr->end(), key_bytes.begin());
if (dd_address_keys.count(key_bytes) > 0) return true;
}
// Fallback: standard wallet IsMine
if (m_wallet) {
LOCK(m_wallet->cs_wallet);
if (m_wallet->IsMine(dest) & wallet::ISMINE_SPENDABLE) return true;
}
}
return false;
}
std::vector<std::string> DigiDollarWallet::GetKnownDDAddresses() const
{
LOCK(cs_dd_wallet);
std::set<std::string> addresses;
for (const auto& [addr, balance] : dd_balances) {
if (addr == "total" || addr.rfind("test_addr_", 0) == 0) continue;
CDigiDollarAddress dd_addr(addr);