-
Notifications
You must be signed in to change notification settings - Fork 1
/
Psbt.scala
2175 lines (2096 loc) · 72.8 KB
/
Psbt.scala
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
package scoin
import java.io.{
ByteArrayInputStream,
ByteArrayOutputStream,
InputStream,
OutputStream
}
import java.nio.ByteOrder
import scala.annotation.tailrec
import scala.util.{Failure, Success, Try}
import scala.language.postfixOps
import scodec.bits.ByteVector
import scoin.Crypto.{PrivateKey, PublicKey}
import scoin.DeterministicWallet.{ExtendedPublicKey, KeyPath}
/** A partially signed bitcoin transaction: see
* https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki.
*
* @param global
* global psbt data containing the transaction to be signed.
* @param inputs
* signing data for each input of the transaction to be signed (order matches
* the unsigned tx).
* @param outputs
* signing data for each output of the transaction to be signed (order
* matches the unsigned tx).
*/
case class Psbt(
global: Psbt.Global,
inputs: Seq[Psbt.Input],
outputs: Seq[Psbt.Output]
) {
import Psbt._
require(
global.tx.txIn.length == inputs.length,
"there must be one partially signed input per input of the unsigned tx"
)
require(
global.tx.txOut.length == outputs.length,
"there must be one partially signed output per output of the unsigned tx"
)
/** Implements the PSBT updater role; adds information about a given segwit
* utxo. When you have access to the complete input transaction, you should
* prefer [[updateWitnessInputTx]].
*
* @param outPoint
* utxo being spent.
* @param txOut
* transaction output for the provided outPoint.
* @param redeemScript
* redeem script if known and applicable (when using p2sh-embedded segwit).
* @param witnessScript
* witness script if known and applicable (when using p2wsh).
* @param sighashType
* sighash type if one should be specified.
* @param derivationPaths
* derivation paths for keys used by this utxo.
* @return
* psbt with the matching input updated.
*/
def updateWitnessInput(
outPoint: OutPoint,
txOut: TxOut,
redeemScript: Option[Seq[ScriptElt]] = None,
witnessScript: Option[Seq[ScriptElt]] = None,
sighashType: Option[Int] = None,
derivationPaths: Map[PublicKey, KeyPathWithMaster] = Map.empty
): Try[Psbt] = Try {
val inputIndex = global.tx.txIn.indexWhere(_.outPoint == outPoint)
require(
inputIndex >= 0,
"psbt transaction does not spend the provided outpoint"
)
val updatedInput = inputs(inputIndex) match {
case input: PartiallySignedInputWithoutUtxo =>
PartiallySignedWitnessInput(
txOut,
None,
sighashType.orElse(input.sighashType),
Map.empty,
derivationPaths ++ input.derivationPaths,
redeemScript,
witnessScript,
input.ripemd160,
input.sha256,
input.hash160,
input.hash256,
input.unknown
)
case input: PartiallySignedWitnessInput =>
input.copy(
txOut = txOut,
redeemScript = redeemScript.orElse(input.redeemScript),
witnessScript = witnessScript.orElse(input.witnessScript),
sighashType = sighashType.orElse(input.sighashType),
derivationPaths = input.derivationPaths ++ derivationPaths
)
case _: PartiallySignedNonWitnessInput =>
return Failure(
new IllegalArgumentException(
"cannot update segwit input: it has already been updated with non-segwit data"
)
)
case _: FinalizedInput =>
return Failure(
new IllegalArgumentException(
"cannot update segwit input: it has already been finalized"
)
)
}
this.copy(inputs = inputs.updated(inputIndex, updatedInput))
}
/** Implements the PSBT updater role; adds information about a given segwit
* utxo. Note that we always fill the nonWitnessUtxo (see
* https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki#cite_note-7).
*
* @param inputTx
* transaction containing the utxo.
* @param outputIndex
* index of the utxo in the inputTx.
* @param redeemScript
* redeem script if known and applicable (when using p2sh-embedded segwit).
* @param witnessScript
* witness script if known and applicable (when using p2wsh).
* @param sighashType
* sighash type if one should be specified.
* @param derivationPaths
* derivation paths for keys used by this utxo.
* @return
* psbt with the matching input updated.
*/
def updateWitnessInputTx(
inputTx: Transaction,
outputIndex: Int,
redeemScript: Option[Seq[ScriptElt]] = None,
witnessScript: Option[Seq[ScriptElt]] = None,
sighashType: Option[Int] = None,
derivationPaths: Map[PublicKey, KeyPathWithMaster] = Map.empty
): Try[Psbt] = Try {
require(
outputIndex < inputTx.txOut.size,
"output index must exist in the input tx"
)
val outpoint = OutPoint(inputTx, outputIndex)
val inputIndex = global.tx.txIn.indexWhere(_.outPoint == outpoint)
require(
inputIndex >= 0,
"psbt transaction does not spend the provided outpoint"
)
val updatedInput = inputs(inputIndex) match {
case input: PartiallySignedInputWithoutUtxo =>
PartiallySignedWitnessInput(
inputTx.txOut(outputIndex),
Some(inputTx),
sighashType.orElse(input.sighashType),
Map.empty,
derivationPaths ++ input.derivationPaths,
redeemScript,
witnessScript,
input.ripemd160,
input.sha256,
input.hash160,
input.hash256,
input.unknown
)
case input: PartiallySignedWitnessInput =>
input.copy(
txOut = inputTx.txOut(outputIndex),
nonWitnessUtxo = Some(inputTx),
redeemScript = redeemScript.orElse(input.redeemScript),
witnessScript = witnessScript.orElse(input.witnessScript),
sighashType = sighashType.orElse(input.sighashType),
derivationPaths = input.derivationPaths ++ derivationPaths
)
case _: PartiallySignedNonWitnessInput =>
return Failure(
new IllegalArgumentException(
"cannot update segwit input: it has already been updated with non-segwit data"
)
)
case _: FinalizedInput =>
return Failure(
new IllegalArgumentException(
"cannot update segwit input: it has already been finalized"
)
)
}
this.copy(inputs = inputs.updated(inputIndex, updatedInput))
}
/** Implements the PSBT updater role; adds information about a given
* non-segwit utxo.
*
* @param inputTx
* transaction containing the utxo.
* @param outputIndex
* index of the utxo in the inputTx.
* @param redeemScript
* redeem script if known and applicable (when using p2sh).
* @param sighashType
* sighash type if one should be specified.
* @param derivationPaths
* derivation paths for keys used by this utxo.
* @return
* psbt with the matching input updated.
*/
def updateNonWitnessInput(
inputTx: Transaction,
outputIndex: Int,
redeemScript: Option[Seq[ScriptElt]] = None,
sighashType: Option[Int] = None,
derivationPaths: Map[PublicKey, KeyPathWithMaster] = Map.empty
): Try[Psbt] = Try {
require(
outputIndex < inputTx.txOut.size,
"output index must exist in the input tx"
)
val outpoint = OutPoint(inputTx, outputIndex)
val inputIndex = global.tx.txIn.indexWhere(_.outPoint == outpoint)
require(
inputIndex >= 0,
"psbt transaction does not spend the provided outpoint"
)
val updatedInput = inputs(inputIndex) match {
case input: PartiallySignedInputWithoutUtxo =>
PartiallySignedNonWitnessInput(
inputTx,
outputIndex,
sighashType.orElse(input.sighashType),
Map.empty,
derivationPaths ++ input.derivationPaths,
redeemScript,
input.ripemd160,
input.sha256,
input.hash160,
input.hash256,
input.unknown
)
case input: PartiallySignedNonWitnessInput =>
input.copy(
inputTx = inputTx,
outputIndex = outputIndex,
redeemScript = redeemScript.orElse(input.redeemScript),
sighashType = sighashType.orElse(input.sighashType),
derivationPaths = input.derivationPaths ++ derivationPaths
)
case _: PartiallySignedWitnessInput =>
return Failure(
new IllegalArgumentException(
"cannot update non-segwit input: it has already been updated with segwit data"
)
)
case _: FinalizedInput =>
return Failure(
new IllegalArgumentException(
"cannot update non-segwit input: it has already been finalized"
)
)
}
this.copy(inputs = inputs.updated(inputIndex, updatedInput))
}
def updatePreimageChallenges(
outPoint: OutPoint,
ripemd160: Set[ByteVector],
sha256: Set[ByteVector],
hash160: Set[ByteVector],
hash256: Set[ByteVector]
): Try[Psbt] = {
val inputIndex = global.tx.txIn.indexWhere(_.outPoint == outPoint)
require(
inputIndex >= 0,
"psbt transaction does not spend the provided outpoint"
)
updatePreimageChallenges(inputIndex, ripemd160, sha256, hash160, hash256)
}
def updatePreimageChallenges(
inputIndex: Int,
ripemd160: Set[ByteVector],
sha256: Set[ByteVector],
hash160: Set[ByteVector],
hash256: Set[ByteVector]
): Try[Psbt] = Try {
require(inputIndex < inputs.length, "input must exist in the global tx")
val updatedInput = inputs(inputIndex) match {
case input: PartiallySignedInputWithoutUtxo =>
input.copy(
ripemd160 = ripemd160 ++ input.ripemd160,
sha256 = sha256 ++ input.sha256,
hash160 = hash160 ++ input.hash160,
hash256 = hash256 ++ input.hash256
)
case input: PartiallySignedWitnessInput =>
input.copy(
ripemd160 = ripemd160 ++ input.ripemd160,
sha256 = sha256 ++ input.sha256,
hash160 = hash160 ++ input.hash160,
hash256 = hash256 ++ input.hash256
)
case input: PartiallySignedNonWitnessInput =>
input.copy(
ripemd160 = ripemd160 ++ input.ripemd160,
sha256 = sha256 ++ input.sha256,
hash160 = hash160 ++ input.hash160,
hash256 = hash256 ++ input.hash256
)
case input: FinalizedWitnessInput =>
input.copy(
ripemd160 = ripemd160 ++ input.ripemd160,
sha256 = sha256 ++ input.sha256,
hash160 = hash160 ++ input.hash160,
hash256 = hash256 ++ input.hash256
)
case input: FinalizedNonWitnessInput =>
input.copy(
ripemd160 = ripemd160 ++ input.ripemd160,
sha256 = sha256 ++ input.sha256,
hash160 = hash160 ++ input.hash160,
hash256 = hash256 ++ input.hash256
)
case input: FinalizedInputWithoutUtxo =>
input.copy(
ripemd160 = ripemd160 ++ input.ripemd160,
sha256 = sha256 ++ input.sha256,
hash160 = hash160 ++ input.hash160,
hash256 = hash256 ++ input.hash256
)
}
this.copy(inputs = inputs.updated(inputIndex, updatedInput))
}
/** Add details for a segwit output.
*
* @param outputIndex
* index of the output in the psbt.
* @param witnessScript
* witness script if known and applicable (when using p2wsh).
* @param redeemScript
* redeem script if known and applicable (when using p2sh-embedded segwit).
* @param derivationPaths
* derivation paths for keys used by this output.
* @return
* psbt with the matching output updated.
*/
def updateWitnessOutput(
outputIndex: Int,
witnessScript: Option[Seq[ScriptElt]] = None,
redeemScript: Option[Seq[ScriptElt]] = None,
derivationPaths: Map[PublicKey, KeyPathWithMaster] = Map.empty
): Try[Psbt] = Try {
require(
outputIndex < global.tx.txOut.size,
"output index must exist in the global tx"
)
val updatedOutput = outputs(outputIndex) match {
case _: NonWitnessOutput =>
return Failure(
new IllegalArgumentException(
"cannot update segwit output: it has already been updated with non-segwit data"
)
)
case output: WitnessOutput =>
output.copy(
witnessScript = witnessScript.orElse(output.witnessScript),
redeemScript = redeemScript.orElse(output.redeemScript),
derivationPaths = derivationPaths ++ output.derivationPaths
)
case output: UnspecifiedOutput =>
WitnessOutput(
witnessScript,
redeemScript,
derivationPaths ++ output.derivationPaths,
output.unknown
)
}
this.copy(outputs = outputs.updated(outputIndex, updatedOutput))
}
/** Add details for a non-segwit output.
*
* @param outputIndex
* index of the output in the psbt.
* @param redeemScript
* redeem script if known and applicable (when using p2sh).
* @param derivationPaths
* derivation paths for keys used by this output.
* @return
* psbt with the matching output updated.
*/
def updateNonWitnessOutput(
outputIndex: Int,
redeemScript: Option[Seq[ScriptElt]] = None,
derivationPaths: Map[PublicKey, KeyPathWithMaster] = Map.empty
): Try[Psbt] = Try {
require(
outputIndex < global.tx.txOut.size,
"output index must exist in the global tx"
)
val updatedOutput = outputs(outputIndex) match {
case output: NonWitnessOutput =>
output.copy(
redeemScript = redeemScript.orElse(output.redeemScript),
derivationPaths = derivationPaths ++ output.derivationPaths
)
case _: WitnessOutput =>
return Failure(
new IllegalArgumentException(
"cannot update non-segwit output: it has already been updated with segwit data"
)
)
case output: UnspecifiedOutput =>
NonWitnessOutput(
redeemScript,
derivationPaths ++ output.derivationPaths,
output.unknown
)
}
this.copy(outputs = outputs.updated(outputIndex, updatedOutput))
}
/** Implements the PSBT signer role: sign a given input. The caller needs to
* carefully verify that it wants to spend that input, and that the unsigned
* transaction matches what it expects.
*
* @param priv
* private key used to sign the input.
* @param outPoint
* input that should be signed.
* @return
* the psbt with a partial signature added (other inputs will not be
* modified).
*/
def sign(priv: PrivateKey, outPoint: OutPoint): Try[SignPsbtResult] = {
val inputIndex = global.tx.txIn.indexWhere(_.outPoint == outPoint)
require(
inputIndex >= 0,
"psbt transaction does not spend the provided outpoint"
)
sign(priv, inputIndex)
}
/** Implements the PSBT signer role: sign a given input. The caller needs to
* carefully verify that it wants to spend that input, and that the unsigned
* transaction matches what it expects.
*
* @param priv
* private key used to sign the input.
* @param inputIndex
* index of the input that should be signed.
* @return
* the psbt with a partial signature added (other inputs will not be
* modified).
*/
def sign(priv: PrivateKey, inputIndex: Int): Try[SignPsbtResult] = Try {
require(
inputIndex < inputs.length,
"input index must exist in the input tx"
)
val input = inputs(inputIndex)
Psbt.sign(priv, inputIndex, input, global) match {
case Success((signedInput, sig)) =>
SignPsbtResult(
this.copy(inputs = inputs.updated(inputIndex, signedInput)),
sig
)
case Failure(ex) => return Failure(ex)
}
}
/** Implements the PSBT finalizer role: finalizes a given segwit input. This
* will clear all fields from the input except the utxo, scriptSig,
* scriptWitness and unknown entries.
*
* @param outPoint
* input that should be finalized.
* @param scriptWitness
* witness script.
* @return
* a psbt with the given input finalized.
*/
def finalizeWitnessInput(
outPoint: OutPoint,
scriptWitness: ScriptWitness
): Try[Psbt] = {
val inputIndex = global.tx.txIn.indexWhere(_.outPoint == outPoint)
require(
inputIndex >= 0,
"psbt transaction does not spend the provided outpoint"
)
finalizeWitnessInput(inputIndex, scriptWitness)
}
/** Implements the PSBT finalizer role: finalizes a given segwit input. This
* will clear all fields from the input except the utxo, scriptSig,
* scriptWitness and unknown entries.
*
* @param inputIndex
* index of the input that should be finalized.
* @param scriptWitness
* witness script.
* @return
* a psbt with the given input finalized.
*/
def finalizeWitnessInput(
inputIndex: Int,
scriptWitness: ScriptWitness
): Try[Psbt] = {
if (inputIndex >= inputs.length) {
Failure(
new IllegalArgumentException("input index must exist in the input tx")
)
} else {
inputs(inputIndex) match {
case _: PartiallySignedInputWithoutUtxo =>
Failure(
new IllegalArgumentException(
"cannot finalize: input is missing utxo details"
)
)
case _: PartiallySignedNonWitnessInput =>
Failure(
new IllegalArgumentException(
"cannot finalize: input is a non-segwit input"
)
)
case input: PartiallySignedWitnessInput =>
val scriptSig = input.redeemScript.map(script =>
OP_PUSHDATA(Script.write(script)) :: Nil
) // p2sh-embedded segwit
val finalizedInput = FinalizedWitnessInput(
input.txOut,
input.nonWitnessUtxo,
scriptWitness,
scriptSig,
input.ripemd160,
input.sha256,
input.hash160,
input.hash256,
input.unknown
)
Success(
this.copy(inputs = this.inputs.updated(inputIndex, finalizedInput))
)
case _: FinalizedInput =>
Failure(
new IllegalArgumentException(
"cannot finalize: input has already been finalized"
)
)
}
}
}
/** Implements the PSBT finalizer role: finalizes a given non-segwit input.
* This will clear all fields from the input except the utxo, scriptSig and
* unknown entries.
*
* @param outPoint
* input that should be finalized.
* @param scriptSig
* signature script.
* @return
* a psbt with the given input finalized.
*/
def finalizeNonWitnessInput(
outPoint: OutPoint,
scriptSig: Seq[ScriptElt]
): Try[Psbt] = {
val inputIndex = global.tx.txIn.indexWhere(_.outPoint == outPoint)
require(
inputIndex >= 0,
"psbt transaction does not spend the provided outpoint"
)
finalizeNonWitnessInput(inputIndex, scriptSig)
}
/** Implements the PSBT finalizer role: finalizes a given non-segwit input.
* This will clear all fields from the input except the utxo, scriptSig and
* unknown entries.
*
* @param inputIndex
* index of the input that should be finalized.
* @param scriptSig
* signature script.
* @return
* a psbt with the given input finalized.
*/
def finalizeNonWitnessInput(
inputIndex: Int,
scriptSig: Seq[ScriptElt]
): Try[Psbt] = {
if (inputIndex >= inputs.length) {
Failure(
new IllegalArgumentException("input index must exist in the input tx")
)
} else {
inputs(inputIndex) match {
case _: PartiallySignedInputWithoutUtxo =>
Failure(
new IllegalArgumentException(
"cannot finalize: input is missing utxo details"
)
)
case _: PartiallySignedWitnessInput =>
Failure(
new IllegalArgumentException(
"cannot finalize: input is a segwit input"
)
)
case input: PartiallySignedNonWitnessInput =>
val finalizedInput = FinalizedNonWitnessInput(
input.inputTx,
input.outputIndex,
scriptSig,
input.ripemd160,
input.sha256,
input.hash160,
input.hash256,
input.unknown
)
Success(
this.copy(inputs = this.inputs.updated(inputIndex, finalizedInput))
)
case _: FinalizedInput =>
Failure(
new IllegalArgumentException(
"cannot finalize: input has already been finalized"
)
)
}
}
}
/** Implements the PSBT extractor role: extracts a valid transaction from the
* psbt data.
*
* @return
* a fully signed, ready-to-broadcast transaction.
*/
def extract(): Try[Transaction] = {
val (finalTxsIn, utxos) = global.tx.txIn
.zip(inputs)
.map { case (txIn, input) =>
val finalTxIn = txIn.copy(
witness = input.scriptWitness.getOrElse(ScriptWitness.empty),
signatureScript =
input.scriptSig.map(Script.write).getOrElse(ByteVector.empty)
)
val utxo = input match {
case input: FinalizedNonWitnessInput
if input.inputTx.txid != txIn.outPoint.txid =>
return Failure(
new IllegalArgumentException(
"cannot extract transaction: non-witness utxo does not match unsigned tx input"
)
)
case input: FinalizedNonWitnessInput
if input.inputTx.txOut.length <= txIn.outPoint.index =>
return Failure(
new IllegalArgumentException(
"cannot extract transaction: non-witness utxo index out of bounds"
)
)
case input: FinalizedNonWitnessInput =>
input.inputTx.txOut(txIn.outPoint.index.toInt)
case input: FinalizedWitnessInput => input.txOut
case _ =>
return Failure(
new IllegalArgumentException(
"cannot extract transaction: some inputs are not finalized or are missing utxo data"
)
)
}
(finalTxIn, txIn.outPoint -> utxo)
}
.unzip
val finalTx = global.tx.copy(txIn = finalTxsIn)
Try {
Transaction.correctlySpends(
finalTx,
utxos.toMap,
ScriptFlags.STANDARD_SCRIPT_VERIFY_FLAGS
)
}.map(_ => finalTx)
}
/** Compute the fees paid by the PSBT. Note that if some inputs have not been
* updated yet, the fee cannot be computed.
*/
def computeFees(): Try[Satoshi] = {
val amountOut = global.tx.txOut match {
case Nil => 0 sat
case txOut => txOut.map(_.amount).sum
}
val amountIn = inputs.foldLeft(Success(0 sat): Try[Satoshi]) {
case (Failure(ex), _) => Failure(ex)
case (Success(amount), input: WitnessInput) =>
Success(amount + input.amount)
case (Success(amount), input: NonWitnessInput) =>
Success(amount + input.amount)
case _ =>
Failure(
new IllegalArgumentException(
s"some inputs are missing utxo details: amount unknown"
)
)
}
amountIn.map(_ - amountOut)
}
def getInput(outPoint: OutPoint): Option[Input] = {
val inputIndex = global.tx.txIn.indexWhere(_.outPoint == outPoint)
if (inputIndex >= 0) Some(inputs(inputIndex)) else None
}
def getInput(inputIndex: Int): Option[Input] = {
if (0 <= inputIndex && inputIndex < inputs.size) Some(inputs(inputIndex))
else None
}
}
/** Partially signed bitcoin transactions: see
* https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki
*/
object Psbt {
/** Only version 0 is supported for now. */
val Version: Long = 0
/** @param prefix
* extended public key version bytes.
* @param masterKeyFingerprint
* fingerprint of the master key.
* @param extendedPublicKey
* BIP32 extended public key.
*/
case class ExtendedPublicKeyWithMaster(
prefix: Long,
masterKeyFingerprint: Long,
extendedPublicKey: ExtendedPublicKey
)
/** @param masterKeyFingerprint
* fingerprint of the master key.
* @param keyPath
* bip 32 derivation path.
*/
case class KeyPathWithMaster(masterKeyFingerprint: Long, keyPath: KeyPath)
case class SignPsbtResult(psbt: Psbt, sig: ByteVector)
case class DataEntry(key: ByteVector, value: ByteVector)
/** A PSBT is a collection of key-value maps. */
sealed trait DataMap {
/** Unknown key-value pairs should be ignored but included in the PSBT. */
def unknown: Seq[DataEntry]
}
/** Global data for the PSBT.
*
* @param version
* psbt version.
* @param tx
* partially signed transaction.
* @param extendedPublicKeys
* (optional) extended public keys used when signing inputs and producing
* outputs.
* @param unknown
* (optional) unknown global entries.
*/
case class Global(
version: Long,
tx: Transaction,
extendedPublicKeys: Seq[ExtendedPublicKeyWithMaster],
unknown: Seq[DataEntry]
) extends DataMap
/** A PSBT input. A valid PSBT must contain one such input per input of the
* [[Global.tx]].
*/
sealed trait Input extends DataMap {
// @formatter:off
/** Non-witness utxo, used when spending non-segwit outputs (may also be included when spending segwit outputs). */
def nonWitnessUtxo: Option[Transaction]
/** Witness utxo, used when spending segwit outputs. */
def witnessUtxo: Option[TxOut]
/** Sighash type to be used when producing signatures for this output. */
def sighashType: Option[Int]
/** Signatures as would be pushed to the stack from a scriptSig or witness. */
def partialSigs: Map[PublicKey, ByteVector]
/** Derivation paths used for the signatures. */
def derivationPaths: Map[PublicKey, KeyPathWithMaster]
/** Redeem script for this input (when using p2sh). */
def redeemScript: Option[Seq[ScriptElt]]
/** Witness script for this input (when using p2wsh). */
def witnessScript: Option[Seq[ScriptElt]]
/** Fully constructed scriptSig with signatures and any other scripts necessary for the input to pass validation. */
def scriptSig: Option[Seq[ScriptElt]]
/** Fully constructed scriptWitness with signatures and any other scripts necessary for the input to pass validation. */
def scriptWitness: Option[ScriptWitness]
/** RipeMD160 preimages (e.g. for miniscript hash challenges). */
def ripemd160: Set[ByteVector]
/** Sha256 preimages (e.g. for miniscript hash challenges). */
def sha256: Set[ByteVector]
/** Hash160 preimages (e.g. for miniscript hash challenges). */
def hash160: Set[ByteVector]
/** Hash256 preimages (e.g. for miniscript hash challenges). */
def hash256: Set[ByteVector]
/** (optional) Unknown global entries. */
def unknown: Seq[DataEntry]
// @formatter:on
}
/** An input spending a segwit output. */
sealed trait WitnessInput extends Input {
// @formatter:off
def txOut: TxOut
def amount: Satoshi = txOut.amount
override val witnessUtxo: Option[TxOut] = Some(txOut)
// @formatter:on
}
/** An input spending a non-segwit output. */
sealed trait NonWitnessInput extends Input {
// @formatter:off
def inputTx: Transaction
def outputIndex: Int
def amount: Satoshi = inputTx.txOut(outputIndex).amount
override val nonWitnessUtxo: Option[Transaction] = Some(inputTx)
// The following fields should only be present for inputs which spend segwit outputs (including P2SH embedded ones).
override val witnessUtxo: Option[TxOut] = None
override val witnessScript: Option[Seq[ScriptElt]] = None
// @formatter:on
}
/** A partially signed input. More signatures may need to be added before it
* can be finalized.
*/
sealed trait PartiallySignedInput extends Input {
override val scriptSig: Option[Seq[ScriptElt]] = None
override val scriptWitness: Option[ScriptWitness] = None
}
case class PartiallySignedInputWithoutUtxo(
sighashType: Option[Int],
derivationPaths: Map[PublicKey, KeyPathWithMaster],
ripemd160: Set[ByteVector],
sha256: Set[ByteVector],
hash160: Set[ByteVector],
hash256: Set[ByteVector],
unknown: Seq[DataEntry]
) extends PartiallySignedInput {
override val nonWitnessUtxo: Option[Transaction] = None
override val witnessUtxo: Option[TxOut] = None
override val redeemScript: Option[Seq[ScriptElt]] = None
override val witnessScript: Option[Seq[ScriptElt]] = None
override val partialSigs: Map[PublicKey, ByteVector] = Map.empty
}
case class PartiallySignedWitnessInput(
txOut: TxOut,
nonWitnessUtxo: Option[Transaction],
sighashType: Option[Int],
partialSigs: Map[PublicKey, ByteVector],
derivationPaths: Map[PublicKey, KeyPathWithMaster],
redeemScript: Option[Seq[ScriptElt]],
witnessScript: Option[Seq[ScriptElt]],
ripemd160: Set[ByteVector],
sha256: Set[ByteVector],
hash160: Set[ByteVector],
hash256: Set[ByteVector],
unknown: Seq[DataEntry]
) extends PartiallySignedInput
with WitnessInput
case class PartiallySignedNonWitnessInput(
inputTx: Transaction,
outputIndex: Int,
sighashType: Option[Int],
partialSigs: Map[PublicKey, ByteVector],
derivationPaths: Map[PublicKey, KeyPathWithMaster],
redeemScript: Option[Seq[ScriptElt]],
ripemd160: Set[ByteVector],
sha256: Set[ByteVector],
hash160: Set[ByteVector],
hash256: Set[ByteVector],
unknown: Seq[DataEntry]
) extends PartiallySignedInput
with NonWitnessInput
/** A fully signed input. */
sealed trait FinalizedInput extends Input {
override val sighashType: Option[Int] = None
override val partialSigs: Map[PublicKey, ByteVector] = Map.empty
override val derivationPaths: Map[PublicKey, KeyPathWithMaster] = Map.empty
override val redeemScript: Option[Seq[ScriptElt]] = None
override val witnessScript: Option[Seq[ScriptElt]] = None
}
case class FinalizedWitnessInput(
txOut: TxOut,
nonWitnessUtxo: Option[Transaction],
finalScriptWitness: ScriptWitness,
scriptSig: Option[Seq[ScriptElt]],
ripemd160: Set[ByteVector],
sha256: Set[ByteVector],
hash160: Set[ByteVector],
hash256: Set[ByteVector],
unknown: Seq[DataEntry]
) extends FinalizedInput
with WitnessInput {
override val scriptWitness: Option[ScriptWitness] = Some(finalScriptWitness)
}
case class FinalizedNonWitnessInput(
inputTx: Transaction,
outputIndex: Int,
finalScriptSig: Seq[ScriptElt],
ripemd160: Set[ByteVector],
sha256: Set[ByteVector],
hash160: Set[ByteVector],
hash256: Set[ByteVector],
unknown: Seq[DataEntry]
) extends FinalizedInput
with NonWitnessInput {
override val scriptSig: Option[Seq[ScriptElt]] = Some(finalScriptSig)
override val scriptWitness: Option[ScriptWitness] = None
}
/** Input finalizers should keep the utxo to allow transaction extractors to
* verify the final network serialized transaction, but it's not mandatory so
* we may not have it available when parsing psbt inputs.
*/
case class FinalizedInputWithoutUtxo(
scriptWitness: Option[ScriptWitness],
scriptSig: Option[Seq[ScriptElt]],
ripemd160: Set[ByteVector],
sha256: Set[ByteVector],
hash160: Set[ByteVector],
hash256: Set[ByteVector],
unknown: Seq[DataEntry]
) extends FinalizedInput {
override val nonWitnessUtxo: Option[Transaction] = None
override val witnessUtxo: Option[TxOut] = None
}
/** A PSBT output. A valid PSBT must contain one such output per output of the
* [[Global.tx]].
*/
sealed trait Output extends DataMap {
// @formatter:off
/** Redeem script for this output (when using p2sh). */
def redeemScript: Option[Seq[ScriptElt]]
/** Witness script for this output (when using p2wsh). */
def witnessScript: Option[Seq[ScriptElt]]
/** Derivation paths used to produce the public keys associated to this output. */
def derivationPaths: Map[PublicKey, KeyPathWithMaster]
/** (optional) Unknown global entries. */
def unknown: Seq[DataEntry]
// @formatter:on
}
/** A non-segwit output. */
case class NonWitnessOutput(
redeemScript: Option[Seq[ScriptElt]],
derivationPaths: Map[PublicKey, KeyPathWithMaster],
unknown: Seq[DataEntry]
) extends Output {
override val witnessScript: Option[Seq[ScriptElt]] = None
}
/** A segwit output. */
case class WitnessOutput(
witnessScript: Option[Seq[ScriptElt]],
redeemScript: Option[Seq[ScriptElt]],
derivationPaths: Map[PublicKey, KeyPathWithMaster],
unknown: Seq[DataEntry]
) extends Output
/** An output for which usage of segwit is currently unknown. */
case class UnspecifiedOutput(
derivationPaths: Map[PublicKey, KeyPathWithMaster],
unknown: Seq[DataEntry]
) extends Output {
override val redeemScript: Option[Seq[ScriptElt]] = None
override val witnessScript: Option[Seq[ScriptElt]] = None
}
/** Implements the PSBT creator role; initializes a PSBT for the given
* unsigned transaction.