Repository navigation
Expand file tree
/
Copy pathmnsharesession.cpp
More file actions
1643 lines (1536 loc) · 77.6 KB
/
Copy pathmnsharesession.cpp
File metadata and controls
1643 lines (1536 loc) · 77.6 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) 2026 The Dash Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <qt/mnsharesession.h>
#include <addresstype.h>
#include <chainparams.h>
#include <consensus/validation.h>
#include <core_io.h>
#include <crypto/sha256.h>
#include <evo/dmn_types.h>
#include <evo/netinfo.h>
#include <evo/providertx.h>
#include <evo/sharedcollateral.h>
#include <evo/specialtx.h>
#include <key_io.h>
#include <messagesigner.h>
#include <primitives/transaction.h>
#include <random.h>
#include <uint256.h>
#include <util/strencodings.h>
#include <QCoreApplication>
#include <QRegularExpression>
#include <algorithm>
#include <limits>
#include <optional>
#include <utility>
#include <variant>
namespace {
constexpr const char* ENVELOPE_TYPE{"dash-shared-mn-session"};
constexpr int ENVELOPE_VERSION{1};
constexpr const char* FINGERPRINT_KEY{"fingerprint"};
//! A participant funds their share from a handful of coins; a transaction with
//! thousands of inputs could never be relayed anyway, and every one of them is
//! rendered and re-checked on the GUI thread
constexpr size_t MAX_CONTRIBUTION_INPUTS{64};
//! The engine has no options model, so its own messages quote plain DASH
constexpr BitcoinUnits::Unit kEngineUnit{BitcoinUnits::Unit::DASH};
//! Copy of `json` with any "fingerprint" key removed, preserving key order
UniValue WithoutFingerprint(const UniValue& json)
{
if (!json.isObject()) return json;
UniValue ret(UniValue::VOBJ);
const std::vector<std::string>& keys{json.getKeys()};
const std::vector<UniValue>& values{json.getValues()};
for (size_t i = 0; i < keys.size(); ++i) {
if (keys[i] == FINGERPRINT_KEY) continue;
ret.pushKV(keys[i], values[i]);
}
return ret;
}
//! Untranslated stage keys used in the envelope JSON
const char* StageKey(MnShareSession::Stage stage)
{
switch (stage) {
case MnShareSession::Stage::Draft: return "draft";
case MnShareSession::Stage::Frozen: return "frozen";
case MnShareSession::Stage::Signing: return "signing";
case MnShareSession::Stage::Combined: return "combined";
case MnShareSession::Stage::FundingSigned: return "fundingSigned";
case MnShareSession::Stage::Broadcast: return "broadcast";
}
return "draft";
}
std::optional<MnShareSession::Stage> StageFromKey(const std::string& key)
{
for (const auto stage : {MnShareSession::Stage::Draft, MnShareSession::Stage::Frozen,
MnShareSession::Stage::Signing, MnShareSession::Stage::Combined,
MnShareSession::Stage::FundingSigned, MnShareSession::Stage::Broadcast}) {
if (key == StageKey(stage)) return stage;
}
return std::nullopt;
}
//! Display name of share `index`: its label, or "Share k" when unnamed
QString ShareName(const std::vector<MnShareSession::Share>& shares, size_t index)
{
if (index < shares.size() && !shares[index].label.isEmpty()) return shares[index].label;
return QCoreApplication::translate("MnShareSession", "Share %1").arg(index + 1);
}
//! Index of the share named `label`, or shares.size() when no share matches
size_t ShareIndexOfLabel(const std::vector<MnShareSession::Share>& shares, const QString& label)
{
for (size_t i = 0; i < shares.size(); ++i) {
if (shares[i].label == label) return i;
}
return shares.size();
}
//! Same consensus content. Labels are local annotations, not terms, and are
//! ignored.
bool SameShare(const MnShareSession::Share& a, const MnShareSession::Share& b)
{
return a.amount == b.amount && a.ownerAddress == b.ownerAddress && a.refundAddress == b.refundAddress &&
a.rewardAddress == b.rewardAddress;
}
bool IsTxidHex(const QString& txid)
{
return txid.size() == 64 && IsHex(txid.toStdString());
}
//! The inputs and change outputs `contributions` describe, in the order the
//! funding transaction uses: every contribution's inputs first, then one change
//! output per contribution that has one. `error` names the contribution at
//! fault when an input id or a change address is malformed.
bool BuildFundingParts(const std::vector<MnShareSession::Contribution>& contributions, std::vector<CTxIn>& vin,
std::vector<CTxOut>& vout, QString& error)
{
for (const auto& contribution : contributions) {
for (const auto& input : contribution.inputs) {
if (!IsTxidHex(input.txid)) {
error = QCoreApplication::translate("MnShareSession",
"Contribution \"%1\" has a malformed input transaction id.")
.arg(contribution.label);
return false;
}
vin.emplace_back(COutPoint(uint256S(input.txid.toStdString()), input.vout), CScript(), input.sequence);
}
}
for (const auto& contribution : contributions) {
if (!contribution.hasChange) continue;
const CTxDestination dest{DecodeDestination(contribution.changeAddress.toStdString())};
if (!IsValidDestination(dest)) {
error = QCoreApplication::translate("MnShareSession", "Contribution \"%1\" has an invalid change address.")
.arg(contribution.label);
return false;
}
vout.emplace_back(contribution.changeAmount, GetScriptForDestination(dest));
}
return true;
}
//! True when `payload` registers exactly the service addresses `addrs` (the
//! comma-joined list the envelope displays) would register. Both sides are run
//! through NetInfoInterface::AddEntry, so the comparison is between canonical
//! forms rather than between strings.
bool NetInfoMatches(const CProRegTx& payload, const QString& addrs)
{
if (!payload.netInfo) return false;
const auto expected{NetInfoInterface::MakeNetInfo(payload.nVersion)};
if (!expected) return false;
static const QRegularExpression separator{QStringLiteral("[,\\s]+")};
for (const QString& entry : addrs.split(separator, Qt::SkipEmptyParts)) {
if (expected->AddEntry(NetInfoPurpose::CORE_P2P, entry.toStdString()) != NetInfoStatus::Success) return false;
}
return *payload.netInfo == *expected;
}
//! Decode a frozen shared registration (funding tx + CProRegTx payload with a
//! share table) from the envelope's protx hex
bool DecodeSharedProTx(const QString& protx_hex, CMutableTransaction& tx, CProRegTx& payload, QString& error)
{
if (!DecodeHexTx(tx, protx_hex.toStdString())) {
error = QCoreApplication::translate("MnShareSession",
"The session's prepared transaction is not valid transaction hex.");
return false;
}
// assert_type=false: a malformed file must produce an error, not a debug abort
auto opt_payload = GetTxPayload<CProRegTx>(tx, /*assert_type=*/false);
if (!opt_payload || !opt_payload->IsShared()) {
error = QCoreApplication::translate("MnShareSession", "The session's prepared transaction is not a shared "
"masternode registration.");
return false;
}
payload = std::move(*opt_payload);
return true;
}
} // anonymous namespace
bool MnShareSession::SameContribution(const Contribution& a, const Contribution& b)
{
if (a.inputs.size() != b.inputs.size() || a.hasChange != b.hasChange) return false;
if (a.hasChange && (a.changeAddress != b.changeAddress || a.changeAmount != b.changeAmount)) return false;
for (size_t i = 0; i < a.inputs.size(); ++i) {
if (a.inputs[i].txid.compare(b.inputs[i].txid, Qt::CaseInsensitive) != 0 ||
a.inputs[i].vout != b.inputs[i].vout || a.inputs[i].sequence != b.inputs[i].sequence) {
return false;
}
}
return true;
}
namespace {
//! U+202F NARROW NO-BREAK SPACE. BitcoinUnits groups thousands with a plain
//! thin space, which a layout may break a number across.
constexpr char16_t NARROW_NO_BREAK_SPACE{0x202F};
} // anonymous namespace
QString SharedMnFormatAmount(BitcoinUnits::Unit unit, CAmount amount)
{
// Eight fixed decimals on a 1000 DASH collateral are noise the reader has
// to count through to compare two rows, so a whole-coin amount is shown as
// one. Both separators are made non-breaking: a collateral that wraps as
// "1" / "000.00000000" / "tDASH" across three lines is unreadable, and one
// confirmation dialog did exactly that.
QString number{BitcoinUnits::format(unit, amount, /*plussign=*/false, BitcoinUnits::SeparatorStyle::ALWAYS)};
if (const int point{number.indexOf(QLatin1Char('.'))}; point >= 0) {
int end{number.size()};
while (end > point + 1 && number.at(end - 1) == QLatin1Char('0')) {
--end;
}
number.truncate(end == point + 1 ? point : end);
}
number.replace(QChar(THIN_SP_CP), QChar(NARROW_NO_BREAK_SPACE));
return number + QChar(QChar::Nbsp) + BitcoinUnits::name(unit);
}
QString SharedMnPlural(qint64 count, const char* singular, const char* plural)
{
return count == 1 ? QCoreApplication::translate("MnShareSession", singular)
: QCoreApplication::translate("MnShareSession", plural).arg(count);
}
QString shared_mn::EnvelopeFingerprint(const UniValue& json)
{
const std::string text{WithoutFingerprint(json).write(/*prettyIndent=*/2)};
unsigned char digest[CSHA256::OUTPUT_SIZE];
CSHA256().Write(reinterpret_cast<const unsigned char*>(text.data()), text.size()).Finalize(digest);
const QString hex{QString::fromStdString(HexStr(Span<const unsigned char>(digest, 4))).toUpper()};
return hex.left(4) + QLatin1Char('-') + hex.mid(4);
}
void shared_mn::AppendFingerprint(UniValue& json)
{
json.pushKV(FINGERPRINT_KEY, EnvelopeFingerprint(json).toStdString());
}
bool shared_mn::CheckFingerprint(const UniValue& json, QString& warning)
{
if (!json.isObject()) return true;
const UniValue& stamped{json.find_value(FINGERPRINT_KEY)};
if (!stamped.isStr()) return true;
if (QString::fromStdString(stamped.get_str()).compare(EnvelopeFingerprint(json), Qt::CaseInsensitive) == 0) {
return true;
}
warning = QCoreApplication::translate("MnShareSession", "This message was edited after it was copied.");
return false;
}
MnShareSession::MnShareSession()
: m_network{QString::fromStdString(Params().GetChainTypeString())},
m_session_id{QString::fromStdString(GetRandHash().ToString())}
{
}
QString MnShareSession::StageName(Stage stage)
{
switch (stage) {
case Stage::Draft:
return QCoreApplication::translate("MnShareSession", "Draft");
case Stage::Frozen:
return QCoreApplication::translate("MnShareSession", "Terms locked");
case Stage::Signing:
return QCoreApplication::translate("MnShareSession", "Collecting approvals");
case Stage::Combined:
return QCoreApplication::translate("MnShareSession", "Approvals combined");
case Stage::FundingSigned:
return QCoreApplication::translate("MnShareSession", "Contributions signed");
case Stage::Broadcast:
return QCoreApplication::translate("MnShareSession", "Broadcast");
}
return {};
}
UniValue MnShareSession::toJsonBody() const
{
UniValue ret(UniValue::VOBJ);
ret.pushKV("type", ENVELOPE_TYPE);
ret.pushKV("version", ENVELOPE_VERSION);
ret.pushKV("network", m_network.toStdString());
ret.pushKV("sessionId", m_session_id.toStdString());
ret.pushKV("revision", m_revision);
ret.pushKV("stage", StageKey(m_stage));
ret.pushKV("fundingTx", m_funding_tx.toStdString());
UniValue shares(UniValue::VARR);
for (const auto& share : m_shares) {
UniValue entry(UniValue::VOBJ);
entry.pushKV("label", share.label.toStdString());
entry.pushKV("amount", share.amount);
entry.pushKV("ownerAddress", share.ownerAddress.toStdString());
entry.pushKV("refundAddress", share.refundAddress.toStdString());
entry.pushKV("rewardAddress", share.rewardAddress.toStdString());
shares.push_back(entry);
}
ret.pushKV("shares", shares);
UniValue terms(UniValue::VOBJ);
terms.pushKV("coreP2PAddrs", m_terms.coreP2PAddrs.toStdString());
terms.pushKV("operatorPubKey", m_terms.operatorPubKey.toStdString());
terms.pushKV("votingAddress", m_terms.votingAddress.toStdString());
terms.pushKV("operatorReward", m_terms.operatorReward);
terms.pushKV("earlyPeriodBlocks", static_cast<int64_t>(m_terms.earlyPeriodBlocks));
terms.pushKV("earlyPenalty", m_terms.earlyPenalty);
ret.pushKV("terms", terms);
UniValue contributions(UniValue::VARR);
for (const auto& contribution : m_contributions) {
UniValue entry(UniValue::VOBJ);
entry.pushKV("label", contribution.label.toStdString());
UniValue inputs(UniValue::VARR);
for (const auto& input : contribution.inputs) {
UniValue in(UniValue::VOBJ);
in.pushKV("txid", input.txid.toStdString());
in.pushKV("vout", static_cast<int64_t>(input.vout));
in.pushKV("sequence", static_cast<int64_t>(input.sequence));
inputs.push_back(in);
}
entry.pushKV("inputs", inputs);
if (contribution.hasChange) {
UniValue change(UniValue::VOBJ);
change.pushKV("address", contribution.changeAddress.toStdString());
change.pushKV("amount", contribution.changeAmount);
entry.pushKV("change", change);
}
entry.pushKV("changeIndex", contribution.changeIndex);
contributions.push_back(entry);
}
ret.pushKV("contributions", contributions);
ret.pushKV("protx", m_protx.toStdString());
ret.pushKV("consentHash", m_consent_hash.toStdString());
ret.pushKV("collateralIndex", m_collateral_index);
ret.pushKV("sigs", signaturesJson());
ret.pushKV("prepareWallet", m_prepare_wallet.toStdString());
ret.pushKV("operatorSecretHolder", m_operator_secret_holder.toStdString());
ret.pushKV("coordinatorLabel", m_coordinator_label.toStdString());
return ret;
}
UniValue MnShareSession::toJson() const
{
UniValue ret{toJsonBody()};
shared_mn::AppendFingerprint(ret);
return ret;
}
QString MnShareSession::fingerprint() const
{
return shared_mn::EnvelopeFingerprint(toJsonBody());
}
QString MnShareSession::toJsonString() const
{
return QString::fromStdString(toJson().write(/*prettyIndent=*/2));
}
bool MnShareSession::fromJson(const std::string& text, QString& error)
{
UniValue json;
if (!json.read(text)) {
error = QCoreApplication::translate("MnShareSession", "The file is not valid JSON.");
return false;
}
return fromJson(json, error);
}
bool MnShareSession::fromJson(const UniValue& json, QString& error)
{
try {
if (!json.isObject()) {
error = QCoreApplication::translate("MnShareSession", "The file is not a shared masternode session file.");
return false;
}
const UniValue& type{json.find_value("type")};
if (!type.isStr() || type.get_str() != ENVELOPE_TYPE) {
error = QCoreApplication::translate("MnShareSession", "The file is not a shared masternode session file.");
return false;
}
const UniValue& version{json.find_value("version")};
if (!version.isNum() || version.getInt<int>() != ENVELOPE_VERSION) {
error = QCoreApplication::translate("MnShareSession", "The session file uses an unsupported format "
"version. Update Dash Core to open it.");
return false;
}
const UniValue& network{json.find_value("network")};
const std::string our_network{Params().GetChainTypeString()};
if (!network.isStr() || network.get_str() != our_network) {
error = QCoreApplication::translate("MnShareSession", "The session file is for the \"%1\" network but this "
"node runs \"%2\". It cannot be used here.")
.arg(network.isStr() ? QString::fromStdString(network.get_str())
: QCoreApplication::translate("MnShareSession", "unknown"),
QString::fromStdString(our_network));
return false;
}
const UniValue& session_id{json.find_value("sessionId")};
if (!session_id.isStr() || session_id.get_str().empty()) {
error = QCoreApplication::translate("MnShareSession", "The session file has no session id.");
return false;
}
const UniValue& revision{json.find_value("revision")};
if (!revision.isNum() || revision.getInt<int>() < 1) {
error = QCoreApplication::translate("MnShareSession", "The session file has an invalid revision.");
return false;
}
const UniValue& stage_value{json.find_value("stage")};
if (!stage_value.isStr()) {
error = QCoreApplication::translate("MnShareSession", "The session file has no stage.");
return false;
}
const auto stage{StageFromKey(stage_value.get_str())};
if (!stage) {
error = QCoreApplication::translate("MnShareSession", "The session file is at the unknown stage \"%1\". It "
"was probably created by a newer Dash Core.")
.arg(QString::fromStdString(stage_value.get_str()));
return false;
}
MnShareSession parsed;
// A mismatch means the text was altered between copy and paste. That is
// not fatal on its own — every consensus-relevant field is re-validated
// below — so parsing continues and the caller surfaces the warning.
shared_mn::CheckFingerprint(json, parsed.m_import_warning);
parsed.m_network = QString::fromStdString(network.get_str());
parsed.m_session_id = QString::fromStdString(session_id.get_str());
parsed.m_revision = revision.getInt<int>();
parsed.m_stage = *stage;
if (const UniValue& v{json.find_value("fundingTx")}; v.isStr()) {
parsed.m_funding_tx = QString::fromStdString(v.get_str());
}
if (const UniValue& shares{json.find_value("shares")}; shares.isArray()) {
// Refuse an oversized table before allocating anything for it: the
// dialog builds three widgets and a radio button per share row on
// the GUI thread, and consensus caps the table anyway
if (shares.size() > CProRegTx::MAX_SHARES) {
error = QCoreApplication::translate("MnShareSession",
"The session file lists %1 shares; a shared masternode can have "
"at most %2.")
.arg(shares.size())
.arg(CProRegTx::MAX_SHARES);
return false;
}
for (size_t i = 0; i < shares.size(); ++i) {
const UniValue& entry{shares[i]};
const bool well_formed{entry.isObject() && entry.find_value("amount").isNum() &&
entry.find_value("ownerAddress").isStr() &&
entry.find_value("refundAddress").isStr()};
if (!well_formed) {
error = QCoreApplication::translate("MnShareSession",
"Share entry %1 in the session file is malformed.")
.arg(i + 1);
return false;
}
Share share;
if (const UniValue& v{entry.find_value("label")}; v.isStr()) share.label = QString::fromStdString(v.get_str());
share.amount = entry.find_value("amount").getInt<int64_t>();
if (!MoneyRange(share.amount)) {
error = QCoreApplication::translate("MnShareSession",
"Share entry %1 in the session file is malformed.")
.arg(i + 1);
return false;
}
share.ownerAddress = QString::fromStdString(entry.find_value("ownerAddress").get_str());
share.refundAddress = QString::fromStdString(entry.find_value("refundAddress").get_str());
if (const UniValue& v{entry.find_value("rewardAddress")}; v.isStr()) {
share.rewardAddress = QString::fromStdString(v.get_str());
}
parsed.m_shares.push_back(share);
}
}
if (const UniValue& terms{json.find_value("terms")}; terms.isObject()) {
if (const UniValue& v{terms.find_value("coreP2PAddrs")}; v.isStr()) parsed.m_terms.coreP2PAddrs = QString::fromStdString(v.get_str());
if (const UniValue& v{terms.find_value("operatorPubKey")}; v.isStr()) parsed.m_terms.operatorPubKey = QString::fromStdString(v.get_str());
if (const UniValue& v{terms.find_value("votingAddress")}; v.isStr()) parsed.m_terms.votingAddress = QString::fromStdString(v.get_str());
if (const UniValue& v{terms.find_value("operatorReward")}; v.isNum()) parsed.m_terms.operatorReward = v.getInt<int>();
if (const UniValue& v{terms.find_value("earlyPeriodBlocks")}; v.isNum()) {
const int64_t blocks{v.getInt<int64_t>()};
if (blocks < 0 || blocks > std::numeric_limits<uint32_t>::max()) {
error = QCoreApplication::translate("MnShareSession",
"The session file has an invalid early period.");
return false;
}
parsed.m_terms.earlyPeriodBlocks = static_cast<uint32_t>(blocks);
}
if (const UniValue& v{terms.find_value("earlyPenalty")}; v.isNum()) {
parsed.m_terms.earlyPenalty = v.getInt<int64_t>();
if (!MoneyRange(parsed.m_terms.earlyPenalty)) {
error = QCoreApplication::translate("MnShareSession",
"The session file has an invalid early-exit penalty.");
return false;
}
}
}
if (const UniValue& contributions{json.find_value("contributions")}; contributions.isArray()) {
if (contributions.size() > CProRegTx::MAX_SHARES) {
error = QCoreApplication::translate("MnShareSession",
"The session file lists %1 contributions; there can be at most "
"one per share, and at most %2 shares.")
.arg(contributions.size())
.arg(CProRegTx::MAX_SHARES);
return false;
}
const auto malformed = [&error](size_t i) {
error = QCoreApplication::translate("MnShareSession",
"Contribution entry %1 in the session file is malformed.")
.arg(i + 1);
return false;
};
for (size_t i = 0; i < contributions.size(); ++i) {
const UniValue& entry{contributions[i]};
if (!entry.isObject() || !entry.find_value("label").isStr() || !entry.find_value("inputs").isArray()) {
return malformed(i);
}
Contribution contribution;
contribution.label = QString::fromStdString(entry.find_value("label").get_str());
const UniValue& inputs{entry.find_value("inputs")};
if (inputs.size() > MAX_CONTRIBUTION_INPUTS) {
error = QCoreApplication::translate("MnShareSession",
"Contribution entry %1 in the session file has %2 inputs; at "
"most %3 can be funded in one contribution.")
.arg(i + 1)
.arg(inputs.size())
.arg(MAX_CONTRIBUTION_INPUTS);
return false;
}
for (size_t j = 0; j < inputs.size(); ++j) {
const UniValue& in{inputs[j]};
const bool well_formed{in.isObject() && in.find_value("txid").isStr() &&
in.find_value("vout").isNum() && in.find_value("sequence").isNum()};
if (!well_formed) {
return malformed(i);
}
const int64_t vout{in.find_value("vout").getInt<int64_t>()};
const int64_t sequence{in.find_value("sequence").getInt<int64_t>()};
if (vout < 0 || vout > std::numeric_limits<uint32_t>::max() ||
sequence < 0 || sequence > std::numeric_limits<uint32_t>::max()) {
return malformed(i);
}
Input input;
input.txid = QString::fromStdString(in.find_value("txid").get_str());
input.vout = static_cast<uint32_t>(vout);
input.sequence = static_cast<uint32_t>(sequence);
if (!IsTxidHex(input.txid)) {
return malformed(i);
}
contribution.inputs.push_back(input);
}
if (const UniValue& change{entry.find_value("change")}; change.isObject()) {
if (!change.find_value("address").isStr() || !change.find_value("amount").isNum()) {
return malformed(i);
}
contribution.hasChange = true;
contribution.changeAddress = QString::fromStdString(change.find_value("address").get_str());
contribution.changeAmount = change.find_value("amount").getInt<int64_t>();
if (!MoneyRange(contribution.changeAmount)) {
return malformed(i);
}
}
if (const UniValue& v{entry.find_value("changeIndex")}; v.isNum()) contribution.changeIndex = v.getInt<int>();
parsed.m_contributions.push_back(contribution);
}
}
if (const UniValue& v{json.find_value("protx")}; v.isStr()) parsed.m_protx = QString::fromStdString(v.get_str());
if (const UniValue& v{json.find_value("consentHash")}; v.isStr()) {
const std::string& hash{v.get_str()};
if (!hash.empty() && !(hash.size() == 64 && IsHex(hash))) {
error = QCoreApplication::translate("MnShareSession", "The session file has a malformed consent hash.");
return false;
}
parsed.m_consent_hash = QString::fromStdString(hash).toLower();
}
if (const UniValue& v{json.find_value("collateralIndex")}; v.isNum()) parsed.m_collateral_index = v.getInt<int>();
if (const UniValue& sigs{json.find_value("sigs")}; sigs.isArray()) {
for (size_t i = 0; i < sigs.size(); ++i) {
const UniValue& entry{sigs[i]};
if (!entry.isObject() || !entry.find_value("shareIndex").isNum() || !entry.find_value("signature").isStr()) {
error = QCoreApplication::translate("MnShareSession",
"Signature entry %1 in the session file is malformed.")
.arg(i + 1);
return false;
}
Signature sig;
sig.shareIndex = entry.find_value("shareIndex").getInt<int>();
sig.signatureB64 = QString::fromStdString(entry.find_value("signature").get_str());
if (std::any_of(parsed.m_sigs.begin(), parsed.m_sigs.end(),
[&](const Signature& s) { return s.shareIndex == sig.shareIndex; })) {
error = QCoreApplication::translate("MnShareSession",
"The session file lists more than one signature for share %1.")
.arg(sig.shareIndex + 1);
return false;
}
parsed.m_sigs.push_back(sig);
}
}
if (const UniValue& v{json.find_value("prepareWallet")}; v.isStr()) parsed.m_prepare_wallet = QString::fromStdString(v.get_str());
if (const UniValue& v{json.find_value("operatorSecretHolder")}; v.isStr()) parsed.m_operator_secret_holder = QString::fromStdString(v.get_str());
if (const UniValue& v{json.find_value("coordinatorLabel")}; v.isStr()) parsed.m_coordinator_label = QString::fromStdString(v.get_str());
if (parsed.m_stage != Stage::Draft) {
if (parsed.m_protx.isEmpty() || parsed.m_consent_hash.isEmpty()) {
error = QCoreApplication::translate("MnShareSession", "The session file is marked \"%1\" but is "
"missing its frozen transaction or consent hash.")
.arg(StageName(parsed.m_stage));
return false;
}
// A frozen file must register exactly the shares/terms it displays,
// and its prepared transaction must match its consent hash
CMutableTransaction frozen_tx;
CProRegTx frozen_payload;
if (!parsed.decodeFrozen(parsed.m_protx, frozen_tx, frozen_payload, error)) return false;
if (!parsed.payloadMatchesEnvelope(error)) return false;
for (const auto& sig : parsed.m_sigs) {
if (sig.shareIndex < 0 || static_cast<size_t>(sig.shareIndex) >= parsed.m_shares.size()) {
error = QCoreApplication::translate("MnShareSession", "The session file has a signature for a "
"share that does not exist.");
return false;
}
}
if (parsed.m_stage >= Stage::Combined &&
parsed.signedCount() != static_cast<int>(parsed.m_shares.size())) {
error = QCoreApplication::translate("MnShareSession", "The session file claims the approvals are "
"combined, but not every share has an approval.");
return false;
}
if (parsed.m_stage >= Stage::Combined) {
for (const auto& sig : parsed.m_sigs) {
QString sig_error;
if (!parsed.verifySignature(sig.shareIndex, sig.signatureB64, sig_error)) {
error = QCoreApplication::translate("MnShareSession",
"The session file claims the approvals are combined, but "
"an approval is invalid: %1")
.arg(sig_error);
return false;
}
}
}
if (parsed.m_stage >= Stage::FundingSigned &&
std::any_of(frozen_tx.vin.begin(), frozen_tx.vin.end(),
[](const CTxIn& input) { return input.scriptSig.empty(); })) {
error = QCoreApplication::translate("MnShareSession", "The session file claims every contribution is "
"signed, but one or more funding inputs "
"are unsigned.");
return false;
}
}
*this = std::move(parsed);
return true;
} catch (const std::exception& e) {
error = QCoreApplication::translate("MnShareSession", "The session file could not be parsed: %1")
.arg(QString::fromUtf8(e.what()));
return false;
}
}
QString MnShareSession::ShareListErrorText(const std::string& reject_reason, BitcoinUnits::Unit unit,
CAmount min_share_amount, uint32_t early_period_blocks)
{
const CAmount required_collateral{GetMnType(MnType::Regular).collat_amount};
if (reject_reason == "bad-protx-shares-count") {
return QCoreApplication::translate("MnShareSession", "A shared masternode needs between %1 and %2 shares.")
.arg(CProRegTx::MIN_SHARES)
.arg(CProRegTx::MAX_SHARES);
}
if (reject_reason == "bad-protx-shares-early-period") {
return QCoreApplication::translate("MnShareSession",
"The early period must be at most %1 blocks (about two years).")
.arg(CProRegTx::MAX_EARLY_PERIOD_BLOCKS);
}
if (reject_reason == "bad-protx-shares-amount") {
return QCoreApplication::translate("MnShareSession", "Every share amount must be between %1 and %2.")
.arg(SharedMnFormatAmount(unit, CCollateralShare::MIN_AMOUNT),
SharedMnFormatAmount(unit, required_collateral));
}
if (reject_reason == "bad-protx-shares-amount-sum") {
return QCoreApplication::translate("MnShareSession", "The share amounts must sum to exactly %1.")
.arg(SharedMnFormatAmount(unit, required_collateral));
}
if (reject_reason == "bad-protx-shares-key-null" || reject_reason == "bad-protx-shares-dup-key") {
return QCoreApplication::translate("MnShareSession", "Every share needs its own, non-empty owner address.");
}
if (reject_reason == "bad-protx-shares-dup-refund") {
return QCoreApplication::translate("MnShareSession", "Every refund address must be unique.");
}
if (reject_reason == "bad-protx-shares-payee" || reject_reason == "bad-protx-shares-payee-dest") {
return QCoreApplication::translate("MnShareSession",
"Every refund and reward address must be a valid P2PKH or P2SH address.");
}
if (reject_reason == "bad-protx-shares-payee-reuse") {
return QCoreApplication::translate("MnShareSession", "A refund or reward address must not be the voting "
"address or any share's owner address.");
}
if (reject_reason == "bad-protx-shares-penalty") {
if (early_period_blocks == 0) {
return QCoreApplication::translate("MnShareSession",
"Set the early penalty to 0 when there is no early period.");
}
return QCoreApplication::translate("MnShareSession",
"The early penalty must be below the smallest share amount (%1).")
.arg(SharedMnFormatAmount(unit, min_share_amount));
}
return QCoreApplication::translate("MnShareSession", "The share table is not valid (%1).")
.arg(QString::fromStdString(reject_reason));
}
QString MnShareSession::CheckEarlyPenalty(const std::vector<CAmount>& share_amounts, BitcoinUnits::Unit unit,
uint32_t early_period_blocks, CAmount early_penalty)
{
CAmount smallest{GetMnType(MnType::Regular).collat_amount};
for (const CAmount amount : share_amounts) {
if (amount > 0) smallest = std::min(smallest, amount);
}
TxValidationState state;
if (IsEarlyPenaltyValid(early_period_blocks, early_penalty, smallest, state)) return {};
return ShareListErrorText(state.GetRejectReason(), unit, smallest, early_period_blocks);
}
QString MnShareSession::CheckShareAmounts(const std::vector<CAmount>& share_amounts, BitcoinUnits::Unit unit)
{
TxValidationState state;
if (AreShareAmountsValid(share_amounts, GetMnType(MnType::Regular).collat_amount, state)) return {};
return ShareListErrorText(state.GetRejectReason(), unit, CCollateralShare::MIN_AMOUNT, /*early_period_blocks=*/0);
}
QStringList MnShareSession::validateShares() const
{
QStringList errors;
// What consensus cannot see: whether each address string decodes to a destination of the right type
CollateralShares shares;
CKeyID voting_key_id;
if (CTxDestination dest{DecodeDestination(m_terms.votingAddress.toStdString())}; const auto* pkhash = std::get_if<PKHash>(&dest)) {
voting_key_id = ToKeyID(*pkhash);
} else {
errors << QCoreApplication::translate("MnShareSession", "The voting address must be a valid P2PKH address.");
}
for (size_t i = 0; i < m_shares.size(); ++i) {
const Share& share{m_shares[i]};
const QString row{QCoreApplication::translate("MnShareSession", "Share %1:").arg(i + 1)};
const auto row_error{[&](const QString& text) { errors << row + QLatin1Char(' ') + text; }};
CKeyID owner_key_id;
if (CTxDestination dest{DecodeDestination(share.ownerAddress.toStdString())}; const auto* pkhash = std::get_if<PKHash>(&dest)) {
owner_key_id = ToKeyID(*pkhash);
} else {
row_error(QCoreApplication::translate("MnShareSession", "the owner address must be a valid P2PKH address."));
}
CScript scripts[2];
const std::pair<const QString*, QString> payout_addrs[]{
{&share.refundAddress, QCoreApplication::translate("MnShareSession", "refund")},
{&share.rewardAddress, QCoreApplication::translate("MnShareSession", "reward")},
};
for (size_t j = 0; j < std::size(payout_addrs); ++j) {
const auto& [addr, kind] = payout_addrs[j];
if (addr == &share.rewardAddress && addr->isEmpty()) continue; // empty reward = fall back to refund
const CTxDestination dest{DecodeDestination(addr->toStdString())};
if (!std::holds_alternative<PKHash>(dest) && !std::holds_alternative<ScriptHash>(dest)) {
row_error(QCoreApplication::translate("MnShareSession",
"the %1 address must be a valid P2PKH or P2SH address.")
.arg(kind));
continue;
}
scripts[j] = GetScriptForDestination(dest);
}
shares.emplace_back(share.amount, scripts[0], scripts[1], owner_key_id);
}
if (!errors.isEmpty()) return errors;
TxValidationState state;
if (!IsShareListTriviallyValid(shares, m_terms.earlyPeriodBlocks, m_terms.earlyPenalty,
GetMnType(MnType::Regular).collat_amount, voting_key_id, state)) {
CAmount min_amount{std::numeric_limits<CAmount>::max()};
for (const auto& share : shares) min_amount = std::min(min_amount, share.amount);
errors << ShareListErrorText(state.GetRejectReason(), kEngineUnit, min_amount, m_terms.earlyPeriodBlocks);
}
return errors;
}
void MnShareSession::noteDraftChange()
{
if (m_stage == Stage::Draft) ++m_revision;
}
bool MnShareSession::rebuildFundingTx(QString& error)
{
CMutableTransaction tx;
tx.nVersion = 2;
if (!BuildFundingParts(m_contributions, tx.vin, tx.vout, error)) return false;
int change_index{0};
for (auto& contribution : m_contributions) {
contribution.changeIndex = contribution.hasChange ? change_index++ : -1;
}
m_funding_tx = QString::fromStdString(EncodeHexTx(CTransaction(tx)));
return true;
}
bool MnShareSession::addContribution(const Contribution& contribution, QString& error)
{
if (m_stage != Stage::Draft) {
error = QCoreApplication::translate("MnShareSession", "Funding can only be changed while the session is "
"editable. Unlock the terms first (this discards "
"all collected approvals).");
return false;
}
if (contribution.label.isEmpty()) {
error = QCoreApplication::translate("MnShareSession", "The contribution needs a participant label.");
return false;
}
if (contribution.inputs.empty()) {
error = QCoreApplication::translate("MnShareSession", "The contribution has no funding inputs.");
return false;
}
for (const auto& existing : m_contributions) {
if (existing.label == contribution.label) {
error = QCoreApplication::translate("MnShareSession", "\"%1\" has already contributed. Remove the existing "
"contribution first.")
.arg(contribution.label);
return false;
}
for (const auto& in : existing.inputs) {
for (const auto& new_in : contribution.inputs) {
if (in.txid.compare(new_in.txid, Qt::CaseInsensitive) == 0 && in.vout == new_in.vout) {
error = QCoreApplication::translate("MnShareSession",
"Input %1:%2 is already contributed by \"%3\".")
.arg(new_in.txid)
.arg(new_in.vout)
.arg(existing.label);
return false;
}
}
}
}
if (contribution.hasChange && contribution.changeAmount <= 0) {
error = QCoreApplication::translate("MnShareSession", "The change amount must be positive.");
return false;
}
m_contributions.push_back(contribution);
if (!rebuildFundingTx(error)) {
m_contributions.pop_back();
return false;
}
++m_revision;
return true;
}
bool MnShareSession::removeContribution(const QString& label, QString& error)
{
if (m_stage != Stage::Draft) {
error = QCoreApplication::translate("MnShareSession", "Funding can only be changed while the session is "
"editable. Unlock the terms first (this discards "
"all collected approvals).");
return false;
}
for (auto it = m_contributions.begin(); it != m_contributions.end(); ++it) {
if (it->label == label) {
m_contributions.erase(it);
if (!rebuildFundingTx(error)) return false;
++m_revision;
return true;
}
}
error = QCoreApplication::translate("MnShareSession", "No contribution from \"%1\" was found.").arg(label);
return false;
}
bool MnShareSession::freeze(const QString& protx_hex, const QString& consent_hash_hex, int collateral_index, QString& error)
{
if (m_stage != Stage::Draft) {
error = QCoreApplication::translate("MnShareSession", "Only an editable session can be locked.");
return false;
}
CMutableTransaction tx;
CProRegTx payload;
if (!DecodeSharedProTx(protx_hex, tx, payload, error)) return false;
if (!(consent_hash_hex.size() == 64 && IsHex(consent_hash_hex.toStdString()))) {
error = QCoreApplication::translate("MnShareSession", "The consent hash is malformed.");
return false;
}
const uint256 recomputed{payload.MakeSharedRegConsentHash(CTransaction(tx))};
if (recomputed != uint256S(consent_hash_hex.toStdString())) {
error = QCoreApplication::translate("MnShareSession",
"The consent hash does not match the prepared transaction. Do not sign; "
"restart the preparation step.");
return false;
}
if (collateral_index < 0 || payload.collateralOutpoint.n != static_cast<uint32_t>(collateral_index)) {
error = QCoreApplication::translate("MnShareSession",
"The collateral output index does not match the prepared transaction.");
return false;
}
// The share table and terms the user reviewed must be exactly what the
// prepared transaction registers, otherwise the displayed session lies
m_protx = protx_hex;
m_collateral_index = collateral_index;
if (!payloadMatchesEnvelope(error)) {
m_protx.clear();
m_collateral_index = -1;
return false;
}
m_consent_hash = consent_hash_hex.toLower();
m_sigs.clear();
m_stage = Stage::Frozen;
return true;
}
void MnShareSession::unfreeze()
{
m_protx.clear();
m_consent_hash.clear();
m_collateral_index = -1;
m_sigs.clear();
m_stage = Stage::Draft;
// Signatures collected for the old consent hash can never apply to the
// reworked session; a new revision makes every circulating copy stale
++m_revision;
}
bool MnShareSession::verifySignature(int share_index, const QString& sig_b64, QString& error) const
{
if (m_protx.isEmpty() || m_consent_hash.isEmpty()) {
error = QCoreApplication::translate("MnShareSession",
"The terms are not locked yet; there is nothing to approve.");
return false;
}
CMutableTransaction tx;
CProRegTx payload;
if (!decodeFrozen(m_protx, tx, payload, error)) return false;
if (share_index < 0 || static_cast<size_t>(share_index) >= payload.shares.size()) {
error = QCoreApplication::translate("MnShareSession", "Share %1 of %2 does not exist.")
.arg(share_index + 1)
.arg(payload.shares.size());
return false;
}
const uint256 consent_hash{uint256S(m_consent_hash.toStdString())};
// A signature over the payload digest is meaningless if the payload is not
// the share table the participant reviewed
if (!payloadMatchesEnvelope(error)) return false;
const auto sig{DecodeBase64(sig_b64.toStdString())};
if (!sig) {
error = QCoreApplication::translate("MnShareSession", "The signature is not valid base64.");
return false;
}
const QString label{ShareName(m_shares, static_cast<size_t>(share_index))};
if (std::string str_error; !CHashSigner::VerifyHashCanonical(consent_hash, payload.shares[share_index].keyIDOwner, *sig, str_error)) {
error = QCoreApplication::translate("MnShareSession",
"The signature from %1 does not verify against the current terms. It was "
"most likely made for an older version of this session — ask %1 to re-sign "
"the current version.")
.arg(label);
return false;
}
return true;
}
const MnShareSession::Signature* MnShareSession::findSignature(int share_index) const
{
for (const auto& sig : m_sigs) {
if (sig.shareIndex == share_index) return &sig;
}
return nullptr;
}
bool MnShareSession::payloadMatchesEnvelope(QString& error) const
{
CMutableTransaction tx;
CProRegTx payload;
if (!DecodeSharedProTx(m_protx, tx, payload, error)) return false;
if (payload.shares.size() != m_shares.size()) {
error = QCoreApplication::translate("MnShareSession",
"The session file's share table does not match its prepared transaction. "
"Do not sign; request a fresh copy.");
return false;
}
for (size_t i = 0; i < m_shares.size(); ++i) {
const Share& share{m_shares[i]};
const CCollateralShare& signed_share{payload.shares[i]};
const CTxDestination owner{DecodeDestination(share.ownerAddress.toStdString())};
const auto* owner_pkhash{std::get_if<PKHash>(&owner)};
if (!owner_pkhash || ToKeyID(*owner_pkhash) != signed_share.keyIDOwner ||
share.amount != signed_share.amount ||
GetScriptForDestination(DecodeDestination(share.refundAddress.toStdString())) != signed_share.scriptRefund) {
error = QCoreApplication::translate("MnShareSession",
"Share %1 in the session file does not match its prepared transaction. "
"Do not sign; request a fresh copy.")
.arg(i + 1);