forked from etotheipi/BitcoinArmory
/
Signer.cpp
4794 lines (3947 loc) · 128 KB
/
Signer.cpp
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) 2016-2022, goatpig //
// Distributed under the MIT license //
// See LICENSE-MIT or https://opensource.org/licenses/MIT //
// //
////////////////////////////////////////////////////////////////////////////////
#include "Signer.h"
#include "Script.h"
#include "LegacySigner.h"
#include "Transactions.h"
#include "BIP32_Node.h"
#include "Assets.h"
#include "Addresses.h"
#include "../TxOutScrRef.h"
#include "../BitcoinSettings.h"
using namespace std;
using namespace Armory::Signer;
using namespace Armory::Assets;
using namespace Armory::Wallets;
#define TXSIGCOLLECT_VER_LEGACY 1
#define USTXI_VER_LEGACY 1
#define USTXO_VER_LEGACY 1
#define TXSIGCOLLECT_VER_MODERN 2
#define TXSIGCOLLECT_WIDTH 64
#define TXSIGCOLLECT_HEADER "=====TXSIGCOLLECT-"
#define TXIN_EXT_P2SHSCRIPT 0x10
StackItem::~StackItem()
{}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//// ScriptSpender
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
const UTXO& ScriptSpender::getUtxo() const
{
if (!utxo_.isInitialized())
{
if (!haveSupportingTx())
throw SpenderException("missing both utxo & supporting tx");
utxo_.txHash_ = getOutputHash();
utxo_.txOutIndex_ = getOutputIndex();
const auto& supportingTx = getSupportingTx();
auto opId = getOutputIndex();
auto txOutCopy = supportingTx.getTxOutCopy(opId);
utxo_.unserializeRaw(txOutCopy.serializeRef());
}
return utxo_;
}
////////////////////////////////////////////////////////////////////////////////
BinaryDataRef ScriptSpender::getOutputScript() const
{
const auto& utxo = getUtxo();
return utxo.getScript();
}
////////////////////////////////////////////////////////////////////////////////
BinaryDataRef ScriptSpender::getOutputHash() const
{
if (utxo_.isInitialized())
return utxo_.getTxHash();
if (outpoint_.getSize() != 36)
throw SpenderException("missing utxo");
BinaryRefReader brr(outpoint_);
return brr.get_BinaryDataRef(32);
}
////////////////////////////////////////////////////////////////////////////////
unsigned ScriptSpender::getOutputIndex() const
{
if (utxo_.isInitialized())
return utxo_.getTxOutIndex();
if (outpoint_.getSize() != 36)
throw SpenderException("missing utxo");
BinaryRefReader brr(outpoint_);
brr.advance(32);
return brr.get_uint32_t();
}
////////////////////////////////////////////////////////////////////////////////
BinaryDataRef ScriptSpender::getOutpoint() const
{
if (outpoint_.getSize() == 0)
{
BinaryWriter bw;
bw.put_BinaryDataRef(getOutputHash());
bw.put_uint32_t(getOutputIndex());
outpoint_ = bw.getData();
}
return outpoint_.getRef();
}
////////////////////////////////////////////////////////////////////////////////
BinaryData ScriptSpender::serializeScript(
const vector<shared_ptr<StackItem>>& stack, bool no_throw)
{
BinaryWriter bwStack;
for (auto& stackItem : stack)
{
switch (stackItem->type_)
{
case StackItemType_PushData:
{
auto stackItem_pushdata =
dynamic_pointer_cast<StackItem_PushData>(stackItem);
if (stackItem_pushdata == nullptr)
{
if (!no_throw)
throw ScriptException("unexpected StackItem type");
bwStack.put_uint8_t(0);
break;
}
bwStack.put_BinaryData(
BtcUtils::getPushDataHeader(stackItem_pushdata->data_));
bwStack.put_BinaryData(stackItem_pushdata->data_);
break;
}
case StackItemType_SerializedScript:
{
auto stackItem_ss =
dynamic_pointer_cast<StackItem_SerializedScript>(stackItem);
if (stackItem_ss == nullptr)
{
if (!no_throw)
throw ScriptException("unexpected StackItem type");
break;
}
bwStack.put_BinaryData(stackItem_ss->data_);
break;
}
case StackItemType_Sig:
{
auto stackItem_sig =
dynamic_pointer_cast<StackItem_Sig>(stackItem);
if (stackItem_sig == nullptr)
{
if (!no_throw)
throw ScriptException("unexpected StackItem type");
bwStack.put_uint8_t(0);
break;
}
bwStack.put_BinaryData(
BtcUtils::getPushDataHeader(stackItem_sig->sig_));
bwStack.put_BinaryData(stackItem_sig->sig_);
break;
}
case StackItemType_MultiSig:
{
auto stackItem_sig =
dynamic_pointer_cast<StackItem_MultiSig>(stackItem);
if (stackItem_sig == nullptr)
{
if (!no_throw)
throw ScriptException("unexpected StackItem type");
bwStack.put_uint8_t(0);
break;
}
if (stackItem_sig->sigs_.size() < stackItem_sig->m_)
{
if (!no_throw)
throw ScriptException("missing sigs for ms script");
}
for (auto& sigpair : stackItem_sig->sigs_)
{
bwStack.put_BinaryData(
BtcUtils::getPushDataHeader(sigpair.second));
bwStack.put_BinaryData(sigpair.second);
}
break;
}
case StackItemType_OpCode:
{
auto stackItem_opcode =
dynamic_pointer_cast<StackItem_OpCode>(stackItem);
if (stackItem_opcode == nullptr)
{
if (no_throw)
throw ScriptException("unexpected StackItem type");
bwStack.put_uint8_t(0);
break;
}
bwStack.put_uint8_t(stackItem_opcode->opcode_);
break;
}
default:
if (!no_throw)
throw ScriptException("unexpected StackItem type");
}
}
return bwStack.getData();
}
////////////////////////////////////////////////////////////////////////////////
BinaryData ScriptSpender::serializeWitnessData(
const vector<shared_ptr<StackItem>>& stack,
unsigned &itemCount, bool no_throw)
{
itemCount = 0;
BinaryWriter bwStack;
for (auto& stackItem : stack)
{
switch (stackItem->type_)
{
case StackItemType_PushData:
{
++itemCount;
auto stackItem_pushdata =
dynamic_pointer_cast<StackItem_PushData>(stackItem);
if (stackItem_pushdata == nullptr)
{
if (!no_throw)
throw ScriptException("unexpected StackItem type");
bwStack.put_uint8_t(0);
break;
}
bwStack.put_var_int(stackItem_pushdata->data_.getSize());
bwStack.put_BinaryData(stackItem_pushdata->data_);
break;
}
case StackItemType_SerializedScript:
{
auto stackItem_ss =
dynamic_pointer_cast<StackItem_SerializedScript>(stackItem);
if (stackItem_ss == nullptr)
{
if (!no_throw)
throw ScriptException("unexpected StackItem type");
break;
}
bwStack.put_BinaryData(stackItem_ss->data_);
++itemCount;
break;
}
case StackItemType_Sig:
{
++itemCount;
auto stackItem_sig =
dynamic_pointer_cast<StackItem_Sig>(stackItem);
if (stackItem_sig == nullptr)
{
if (!no_throw)
throw ScriptException("unexpected StackItem type");
bwStack.put_uint8_t(0);
break;
}
bwStack.put_var_int(stackItem_sig->sig_.getSize());
bwStack.put_BinaryData(stackItem_sig->sig_);
break;
}
case StackItemType_MultiSig:
{
auto stackItem_sig =
dynamic_pointer_cast<StackItem_MultiSig>(stackItem);
if (stackItem_sig == nullptr)
{
if (!no_throw)
throw ScriptException("unexpected StackItem type");
bwStack.put_uint8_t(0);
break;
}
if (stackItem_sig->sigs_.size() < stackItem_sig->m_)
{
if (!no_throw)
throw ScriptException("missing sigs for ms script");
}
for (auto& sigpair : stackItem_sig->sigs_)
{
bwStack.put_BinaryData(
BtcUtils::getPushDataHeader(sigpair.second));
bwStack.put_BinaryData(sigpair.second);
++itemCount;
}
break;
}
case StackItemType_OpCode:
{
++itemCount;
auto stackItem_opcode =
dynamic_pointer_cast<StackItem_OpCode>(stackItem);
if (stackItem_opcode == nullptr)
{
if (!no_throw)
throw ScriptException("unexpected StackItem type");
bwStack.put_uint8_t(0);
break;
}
bwStack.put_uint8_t(stackItem_opcode->opcode_);
break;
}
default:
if (!no_throw)
throw ScriptException("unexpected StackItem type");
}
}
return bwStack.getData();
}
////////////////////////////////////////////////////////////////////////////////
bool ScriptSpender::isResolved() const
{
if (!canBeResolved())
return false;
if (!isSegWit())
{
if (legacyStatus_ >= SpenderStatus::Resolved)
return true;
}
else
{
//If this spender is SW, only emtpy (native sw) and resolved (nested sw)
//states are valid. The SW stack should not be empty for a SW input
if ((legacyStatus_ == SpenderStatus::Empty ||
legacyStatus_ == SpenderStatus::Resolved) &&
segwitStatus_ >= SpenderStatus::Resolved)
{
return true;
}
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
bool ScriptSpender::isSigned() const
{
/*
Valid combos are:
legacy: Signed, SW: empty
legacy: empty, SW: signed
legacy: resolved, SW: signed
*/
if (!canBeResolved())
return false;
if (!isSegWit())
{
if (legacyStatus_ == SpenderStatus::Signed &&
segwitStatus_ == SpenderStatus::Empty)
{
return true;
}
}
else
{
if (segwitStatus_ == SpenderStatus::Signed)
{
if (legacyStatus_ == SpenderStatus::Empty ||
legacyStatus_ == SpenderStatus::Resolved)
{
return true;
}
}
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
BinaryData ScriptSpender::getSerializedOutpoint() const
{
if (utxo_.isInitialized())
{
BinaryWriter bw;
bw.put_BinaryData(utxo_.getTxHash());
bw.put_uint32_t(utxo_.getTxOutIndex());
return bw.getData();
}
if (outpoint_.getSize() != 36)
throw SpenderException("missing outpoint");
return outpoint_;
}
////////////////////////////////////////////////////////////////////////////////
BinaryData ScriptSpender::getAvailableInputScript() const
{
//if we have a serialized script already, return that
if (!finalInputScript_.empty())
return finalInputScript_;
//otherwise, serialize it from the stack
vector<shared_ptr<StackItem>> stack;
for (auto& stack_item : legacyStack_)
stack.push_back(stack_item.second);
return serializeScript(stack, true);
}
////////////////////////////////////////////////////////////////////////////////
BinaryData ScriptSpender::getSerializedInput(bool withSig, bool loose) const
{
if (legacyStatus_ == SpenderStatus::Unknown && !loose)
{
throw SpenderException("unresolved spender");
}
if (withSig)
{
if (!isSegWit())
{
if (legacyStatus_ != SpenderStatus::Signed)
throw SpenderException("spender is missing sigs");
}
else
{
if (legacyStatus_ != SpenderStatus::Empty &&
legacyStatus_ != SpenderStatus::Resolved)
{
throw SpenderException("invalid legacy state for sw spender");
}
}
}
auto serializedScript = getAvailableInputScript();
BinaryWriter bw;
bw.put_BinaryData(getSerializedOutpoint());
bw.put_var_int(serializedScript.getSize());
bw.put_BinaryData(serializedScript);
bw.put_uint32_t(sequence_);
return bw.getData();
}
////////////////////////////////////////////////////////////////////////////////
BinaryData ScriptSpender::getEmptySerializedInput() const
{
BinaryWriter bw;
bw.put_BinaryData(getSerializedOutpoint());
bw.put_uint8_t(0);
bw.put_uint32_t(sequence_);
return bw.getData();
}
////////////////////////////////////////////////////////////////////////////////
BinaryDataRef ScriptSpender::getFinalizedWitnessData(void) const
{
if (isSegWit())
{
if(segwitStatus_ != SpenderStatus::Signed)
throw runtime_error("witness data missing signature");
}
else if (segwitStatus_ != SpenderStatus::Empty)
{
throw runtime_error("unresolved witness");
}
return finalWitnessData_.getRef();
}
////////////////////////////////////////////////////////////////////////////////
BinaryData ScriptSpender::serializeAvailableWitnessData(void) const
{
try
{
return getFinalizedWitnessData();
}
catch (exception&)
{}
vector<shared_ptr<StackItem>> stack;
for (auto& stack_item : witnessStack_)
stack.push_back(stack_item.second);
//serialize and get item count
unsigned itemCount = 0;
auto&& data = serializeWitnessData(stack, itemCount, true);
//put stack item count
BinaryWriter bw;
bw.put_var_int(itemCount);
//put serialized stack
bw.put_BinaryData(data);
return bw.getData();
}
////////////////////////////////////////////////////////////////////////////////
void ScriptSpender::setWitnessData(const vector<shared_ptr<StackItem>>& stack)
{
//serialize to get item count
unsigned itemCount = 0;
auto&& data = serializeWitnessData(stack, itemCount);
//put stack item count
BinaryWriter bw;
bw.put_var_int(itemCount);
//put serialized stack
bw.put_BinaryData(data);
finalWitnessData_ = bw.getData();
}
////////////////////////////////////////////////////////////////////////////////
void ScriptSpender::updateStack(map<unsigned, shared_ptr<StackItem>>& stackMap,
const vector<shared_ptr<StackItem>>& stackVec)
{
for (auto& stack_item : stackVec)
{
auto iter_pair = stackMap.insert(
make_pair(stack_item->getId(), stack_item));
if (iter_pair.second == true)
continue;
//already have a stack item for this id, let's compare them
if (iter_pair.first->second->isSame(stack_item.get()))
continue;
//stack items differ, are they multisig items?
switch (iter_pair.first->second->type_)
{
case StackItemType_PushData:
{
if (!iter_pair.first->second->isValid())
iter_pair.first->second = stack_item;
else if (stack_item->isValid())
throw ScriptException("invalid push_data");
break;
}
case StackItemType_MultiSig:
{
auto stack_item_ms =
dynamic_pointer_cast<StackItem_MultiSig>(iter_pair.first->second);
stack_item_ms->merge(stack_item.get());
break;
}
case StackItemType_Sig:
{
auto stack_item_sig =
dynamic_pointer_cast<StackItem_Sig>(iter_pair.first->second);
stack_item_sig->merge(stack_item.get());
break;
}
default:
throw ScriptException("unexpected StackItem type inequality");
}
}
}
////////////////////////////////////////////////////////////////////////////////
void ScriptSpender::processStacks()
{
/*
Process the respective stacks, set the serialized input scripts if the
stacks carry enough data and clear the stacks. Otherwise, leave the
input/witness script empty and preserve the stack as is.
*/
auto parseStack = [](
const map<unsigned, shared_ptr<StackItem>>& stack)
->SpenderStatus
{
SpenderStatus stackState = SpenderStatus::Resolved;
for (auto& item_pair : stack)
{
auto& stack_item = item_pair.second;
switch (stack_item->type_)
{
case StackItemType_MultiSig:
{
if (stack_item->isValid())
{
stackState = SpenderStatus::Signed;
break;
}
auto stack_item_ms = dynamic_pointer_cast<StackItem_MultiSig>(
stack_item);
if (stack_item_ms == nullptr)
throw runtime_error("unexpected stack item type");
if (stack_item_ms->sigs_.size() > 0)
stackState = SpenderStatus::PartiallySigned;
break;
}
case StackItemType_Sig:
{
if (stack_item->isValid())
stackState = SpenderStatus::Signed;
break;
}
default:
{
if (!stack_item->isValid())
return SpenderStatus::Unknown;
}
}
}
return stackState;
};
auto updateState = [parseStack](
map<unsigned, shared_ptr<StackItem>>& stack,
SpenderStatus& spenderState,
const function<void(const vector<shared_ptr<StackItem>>&)>& setScript)
->void
{
auto stackState = parseStack(stack);
if (stackState >= spenderState)
{
switch (stackState)
{
case SpenderStatus::Resolved:
case SpenderStatus::PartiallySigned:
{
//do not set the script, keep the stack
break;
}
case SpenderStatus::Signed:
{
//set the script, clear the stack
vector<shared_ptr<StackItem>> stack_vec;
for (auto& item_pair : stack)
stack_vec.push_back(item_pair.second);
setScript(stack_vec);
stack.clear();
break;
}
default:
//do not set the script, keep the stack
break;
}
spenderState = stackState;
}
};
if (legacyStack_.size() > 0)
{
updateState(legacyStack_, legacyStatus_, [this](
const vector<shared_ptr<StackItem>>& stackVec)
{ finalInputScript_ = move(serializeScript(stackVec)); }
);
}
if (witnessStack_.size() > 0)
{
updateState(witnessStack_, segwitStatus_, [this](
const vector<shared_ptr<StackItem>>& stackVec)
{ this->setWitnessData(stackVec); }
);
}
}
////////////////////////////////////////////////////////////////////////////////
void ScriptSpender::serializeStateHeader(
Codec_SignerState::ScriptSpenderState& protoMsg) const
{
protoMsg.set_version_max(SCRIPT_SPENDER_VERSION_MAX);
protoMsg.set_version_min(SCRIPT_SPENDER_VERSION_MIN);
protoMsg.set_legacy_status((uint8_t)legacyStatus_);
protoMsg.set_segwit_status((uint8_t)segwitStatus_);
protoMsg.set_sighash_type((uint8_t)sigHashType_);
protoMsg.set_sequence(sequence_);
protoMsg.set_is_p2sh(isP2SH_);
protoMsg.set_is_csv(isCSV_);
protoMsg.set_is_cltv(isCLTV_);
}
////////////////////////////////////////////////////////////////////////////////
void ScriptSpender::serializeStateUtxo(
Codec_SignerState::ScriptSpenderState& protoMsg) const
{
if (utxo_.isInitialized())
{
auto utxoEntry = protoMsg.mutable_utxo();
utxo_.toProtobuf(*utxoEntry);
}
else
{
auto outpoint = protoMsg.mutable_outpoint();
auto outputHashRef = getOutputHash();
outpoint->set_txhash(outputHashRef.getPtr(), outputHashRef.getSize());
outpoint->set_txoutindex(getOutputIndex());
outpoint->set_value(UINT64_MAX);
outpoint->set_isspent(false);
}
}
////////////////////////////////////////////////////////////////////////////////
void ScriptSpender::serializeLegacyState(
Codec_SignerState::ScriptSpenderState& protoMsg) const
{
if (legacyStatus_ == SpenderStatus::Signed)
{
//put resolved script
protoMsg.set_sig_script(
finalInputScript_.getPtr(), finalInputScript_.getSize());
}
else if (legacyStatus_ >= SpenderStatus::Resolved)
{
//put legacy stack
for (auto stackItem : legacyStack_)
{
auto stackEntry = protoMsg.add_legacy_stack();
stackItem.second->serialize(*stackEntry);
}
}
}
////////////////////////////////////////////////////////////////////////////////
void ScriptSpender::serializeSegwitState(
Codec_SignerState::ScriptSpenderState& protoMsg) const
{
if (segwitStatus_ == SpenderStatus::Signed)
{
//put resolved witness data
protoMsg.set_witness_data(
finalWitnessData_.getPtr(), finalWitnessData_.getSize());
}
else if (segwitStatus_ >= SpenderStatus::Resolved)
{
//put witness stack
for (auto stackItem : witnessStack_)
{
auto stackEntry = protoMsg.add_witness_stack();
stackItem.second->serialize(*stackEntry);
}
}
}
////////////////////////////////////////////////////////////////////////////////
void ScriptSpender::serializePathData(
Codec_SignerState::ScriptSpenderState& protoMsg) const
{
for (auto bip32Path : bip32Paths_)
{
auto pathEntry = protoMsg.add_bip32paths();
bip32Path.second.toProtobuf(*pathEntry);
}
}
////////////////////////////////////////////////////////////////////////////////
void ScriptSpender::serializeState(
Codec_SignerState::ScriptSpenderState& protoMsg) const
{
serializeStateHeader(protoMsg);
serializeStateUtxo(protoMsg);
serializeLegacyState(protoMsg);
serializeSegwitState(protoMsg);
serializePathData(protoMsg);
}
////////////////////////////////////////////////////////////////////////////////
shared_ptr<ScriptSpender> ScriptSpender::deserializeState(
const Codec_SignerState::ScriptSpenderState& protoMsg)
{
auto maxVer = protoMsg.version_max();
auto minVer = protoMsg.version_min();
if (maxVer != SCRIPT_SPENDER_VERSION_MAX ||
minVer != SCRIPT_SPENDER_VERSION_MIN)
{
throw SignerDeserializationError("serialized spender version mismatch");
}
shared_ptr<ScriptSpender> resultPtr;
if (protoMsg.has_utxo())
{
auto&& utxo = UTXO::fromProtobuf(protoMsg.utxo());
resultPtr = make_shared<ScriptSpender>(utxo);
}
else if (protoMsg.has_outpoint())
{
const auto& outpoint = protoMsg.outpoint();
auto outpointHash = BinaryDataRef::fromString(outpoint.txhash());
if (outpointHash.getSize() != 32)
throw SignerDeserializationError("invalid outpoint hash");
resultPtr = make_shared<ScriptSpender>(
outpointHash, outpoint.txoutindex());
}
else
{
throw SignerDeserializationError("missing utxo/outpoint");
}
resultPtr->legacyStatus_ = (SpenderStatus)protoMsg.legacy_status();
resultPtr->segwitStatus_ = (SpenderStatus)protoMsg.segwit_status();
resultPtr->isP2SH_ = protoMsg.is_p2sh();
resultPtr->isCSV_ = protoMsg.is_csv();
resultPtr->isCLTV_ = protoMsg.is_cltv();
resultPtr->sequence_ = protoMsg.sequence();
resultPtr->sigHashType_ = (SIGHASH_TYPE)protoMsg.sighash_type();
if (protoMsg.has_sig_script())
{
resultPtr->finalInputScript_ = BinaryData::fromString(protoMsg.sig_script());
}
for (int i=0; i<protoMsg.legacy_stack_size(); i++)
{
const auto& stackItem = protoMsg.legacy_stack(i);
auto stackObjPtr = StackItem::deserialize(stackItem);
resultPtr->legacyStack_.emplace(stackObjPtr->getId(), stackObjPtr);
}
if (protoMsg.has_witness_data())
{
resultPtr->finalWitnessData_ = BinaryData::fromString(protoMsg.witness_data());
}
for (int i=0; i<protoMsg.witness_stack_size(); i++)
{
const auto& stackItem = protoMsg.witness_stack(i);
auto stackObjPtr = StackItem::deserialize(stackItem);
resultPtr->witnessStack_.emplace(stackObjPtr->getId(), stackObjPtr);
}
for (int i=0; i<protoMsg.bip32paths_size(); i++)
{
auto pathObj = BIP32_AssetPath::fromProtobuf(protoMsg.bip32paths(i));
resultPtr->bip32Paths_.emplace(pathObj.getPublicKey(), move(pathObj));
}
return resultPtr;
}
////////////////////////////////////////////////////////////////////////////////
void ScriptSpender::merge(const ScriptSpender& obj)
{
/*
Do not tolerate sequence mismatch. Sequence should be updated explicitly
if the transaction scheme calls for it.
*/
if (sequence_ != obj.sequence_)
throw runtime_error("sequence mismatch");
//nothing to merge if the spender is already signed
if (isSigned())
return;
//do we have supporting data?
{
//sanity check on obj
BinaryDataRef objOpHash;
uint64_t objOpVal;
try
{
objOpHash = obj.getOutputHash();
objOpVal = obj.getValue();
}
catch (const exception&)
{
//obj has no supporting data, it doesn't carry anything to merge
return;
}
try
{
if (getOutputHash() != objOpHash)
throw runtime_error("spender output hash mismatch");
if (getOutputIndex() != obj.getOutputIndex())
throw runtime_error("spender output index mismatch");
if (getValue() != objOpVal)
throw runtime_error("spender output value mismatch");
}
catch (const SpenderException&)
{
//missing supporting data, get it from obj
if (obj.utxo_.isInitialized())
utxo_ = obj.utxo_;
else if (!obj.outpoint_.empty())
outpoint_ = obj.outpoint_;
else
throw runtime_error("impossible condition, how did we get here??");
}
}
isP2SH_ |= obj.isP2SH_;
isCLTV_ |= obj.isCLTV_;
isCSV_ |= obj.isCSV_;
//legacy stack
if (legacyStatus_ != SpenderStatus::Signed)
{
switch (obj.legacyStatus_)
{
case SpenderStatus::Resolved:
case SpenderStatus::PartiallySigned:
{
//merge the stacks
vector<shared_ptr<StackItem>> objStackVec;
for (auto& stackItemPtr : obj.legacyStack_)
objStackVec.emplace_back(stackItemPtr.second);
updateStack(legacyStack_, objStackVec);
processStacks();
/*
processStacks will set the relevant legacy status,
therefor we break out of the switch scope so as to not overwrite
the status unnecessarely
*/
break;
}
case SpenderStatus::Signed:
{
finalInputScript_ = obj.finalInputScript_;
[[fallthrough]];
}
default:
//set the legacy status
if (obj.legacyStatus_ > legacyStatus_)
legacyStatus_ = obj.legacyStatus_;
}
}