forked from miketout/BitGoJS
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathtransaction_builder.js
948 lines (783 loc) · 30 KB
/
transaction_builder.js
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
var Buffer = require('safe-buffer').Buffer
var baddress = require('./address')
var bcrypto = require('./crypto')
var bscript = require('./script')
var btemplates = require('./templates')
var coins = require('./coins')
var networks = require('./networks')
var ops = require('bitcoin-ops')
var typeforce = require('typeforce')
var types = require('./types')
var scriptTypes = btemplates.types
var SIGNABLE = [
btemplates.types.P2PKH,
btemplates.types.P2PK,
btemplates.types.MULTISIG,
btemplates.types.SMART_TRANSACTION
]
var P2SH = SIGNABLE.concat([btemplates.types.P2WPKH, btemplates.types.P2WSH])
var ECPair = require('./ecpair')
var ECSignature = require('./ecsignature')
var Transaction = require('./transaction')
var SmartTransactionSignatures = require('./smart_transaction_signatures')
var SmartTransactionSignature = require('./smart_transaction_signature')
const { getMainnet } = require('./coins')
var debug = require('debug')('bitgo:utxolib:txbuilder')
function supportedType (type) {
return SIGNABLE.indexOf(type) !== -1
}
function supportedP2SHType (type) {
return P2SH.indexOf(type) !== -1
}
function extractChunks (type, chunks, script) {
var pubKeys = []
var signatures = []
switch (type) {
case scriptTypes.P2PKH:
// if (redeemScript) throw new Error('Nonstandard... P2SH(P2PKH)')
pubKeys = chunks.slice(1)
signatures = chunks.slice(0, 1)
break
case scriptTypes.SMART_TRANSACTION:
signatures = [chunks[0]]
break
case scriptTypes.P2PK:
pubKeys[0] = script ? btemplates.pubKey.output.decode(script) : undefined
signatures = chunks.slice(0, 1)
break
case scriptTypes.MULTISIG:
if (script) {
var multisig = btemplates.multisig.output.decode(script)
pubKeys = multisig.pubKeys
}
signatures = chunks.slice(1).map(function (chunk) {
return chunk.length === 0 ? undefined : chunk
})
break
}
return {
pubKeys: pubKeys,
signatures: signatures
}
}
function expandInput (scriptSig, witnessStack) {
if (scriptSig.length === 0 && witnessStack.length === 0) return {}
var prevOutScript
var prevOutType
var scriptType
var script
var redeemScript
var witnessScript
var witnessScriptType
var redeemScriptType
var witness = false
var p2wsh = false
var p2sh = false
var witnessProgram
var chunks
var scriptSigChunks = bscript.decompile(scriptSig)
var sigType = btemplates.classifyInput(scriptSigChunks, true)
if (sigType === scriptTypes.P2SH) {
p2sh = true
redeemScript = scriptSigChunks[scriptSigChunks.length - 1]
redeemScriptType = btemplates.classifyOutput(redeemScript)
prevOutScript = btemplates.scriptHash.output.encode(bcrypto.hash160(redeemScript))
prevOutType = scriptTypes.P2SH
script = redeemScript
}
var classifyWitness = btemplates.classifyWitness(witnessStack, true)
if (classifyWitness === scriptTypes.P2WSH) {
witnessScript = witnessStack[witnessStack.length - 1]
witnessScriptType = btemplates.classifyOutput(witnessScript)
p2wsh = true
witness = true
if (scriptSig.length === 0) {
prevOutScript = btemplates.witnessScriptHash.output.encode(bcrypto.sha256(witnessScript))
prevOutType = scriptTypes.P2WSH
if (redeemScript !== undefined) {
throw new Error('Redeem script given when unnecessary')
}
// bare witness
} else {
if (!redeemScript) {
throw new Error('No redeemScript provided for P2WSH, but scriptSig non-empty')
}
witnessProgram = btemplates.witnessScriptHash.output.encode(bcrypto.sha256(witnessScript))
if (!redeemScript.equals(witnessProgram)) {
throw new Error('Redeem script didn\'t match witnessScript')
}
}
if (!supportedType(btemplates.classifyOutput(witnessScript))) {
throw new Error('unsupported witness script')
}
script = witnessScript
scriptType = witnessScriptType
chunks = witnessStack.slice(0, -1)
} else if (classifyWitness === scriptTypes.P2WPKH) {
witness = true
var key = witnessStack[witnessStack.length - 1]
var keyHash = bcrypto.hash160(key)
if (scriptSig.length === 0) {
prevOutScript = btemplates.witnessPubKeyHash.output.encode(keyHash)
prevOutType = scriptTypes.P2WPKH
if (typeof redeemScript !== 'undefined') {
throw new Error('Redeem script given when unnecessary')
}
} else {
if (!redeemScript) {
throw new Error('No redeemScript provided for P2WPKH, but scriptSig wasn\'t empty')
}
witnessProgram = btemplates.witnessPubKeyHash.output.encode(keyHash)
if (!redeemScript.equals(witnessProgram)) {
throw new Error('Redeem script did not have the right witness program')
}
}
scriptType = scriptTypes.P2PKH
chunks = witnessStack
} else if (redeemScript) {
if (!supportedP2SHType(redeemScriptType)) {
throw new Error('Bad redeemscript!')
}
script = redeemScript
scriptType = redeemScriptType
chunks = scriptSigChunks.slice(0, -1)
} else {
prevOutType = scriptType = btemplates.classifyInput(scriptSig)
chunks = scriptSigChunks
}
var expanded = extractChunks(scriptType, chunks, script)
var result = {
pubKeys: expanded.pubKeys,
signatures: expanded.signatures,
prevOutScript: prevOutScript,
prevOutType: prevOutType,
signType: scriptType,
signScript: script,
witness: Boolean(witness)
}
if (p2sh) {
result.redeemScript = redeemScript
result.redeemScriptType = redeemScriptType
}
if (p2wsh) {
result.witnessScript = witnessScript
result.witnessScriptType = witnessScriptType
}
return result
}
// could be done in expandInput, but requires the original Transaction for hashForSignature
function fixMultisigOrder (input, transaction, vin, value, network) {
if (input.redeemScriptType !== scriptTypes.MULTISIG || !input.redeemScript) return
if (input.pubKeys.length === input.signatures.length) return
network = network || networks.bitcoin
var unmatched = input.signatures.concat()
input.signatures = input.pubKeys.map(function (pubKey) {
var keyPair = ECPair.fromPublicKeyBuffer(pubKey)
var match
// check for a signature
unmatched.some(function (signature, i) {
// skip if undefined || OP_0
if (!signature) return false
if (coins.isZcash(network) && value === undefined) {
return false
}
// TODO: avoid O(n) hashForSignature
var parsed = ECSignature.parseScriptSignature(signature)
var hash = transaction.hashForSignatureByNetwork(
vin,
input.signScript,
value,
parsed.hashType,
!!input.witness,
)
// skip if signature does not match pubKey
if (!keyPair.verify(hash, parsed.signature)) return false
// remove matched signature from unmatched
unmatched[i] = undefined
match = signature
return true
})
return match
})
}
function expandOutput (script, scriptType, ourPubKey) {
typeforce(types.Buffer, script)
var scriptChunks = bscript.decompile(script)
if (!scriptType) {
scriptType = btemplates.classifyOutput(script)
}
var pubKeys = []
switch (scriptType) {
// does our hash160(pubKey) match the output scripts?
case scriptTypes.P2PKH:
if (!ourPubKey) break
var pkh1 = scriptChunks[2]
var pkh2 = bcrypto.hash160(ourPubKey)
if (pkh1.equals(pkh2)) pubKeys = [ourPubKey]
break
// does our hash160(pubKey) match the output scripts?
case scriptTypes.P2WPKH:
if (!ourPubKey) break
var wpkh1 = scriptChunks[1]
var wpkh2 = bcrypto.hash160(ourPubKey)
if (wpkh1.equals(wpkh2)) pubKeys = [ourPubKey]
break
case scriptTypes.SMART_TRANSACTION:
if (!ourPubKey) break
pubKeys = [ourPubKey]
break
case scriptTypes.P2PK:
pubKeys = scriptChunks.slice(0, 1)
break
case scriptTypes.MULTISIG:
pubKeys = scriptChunks.slice(1, -2)
break
default: return { scriptType: scriptType }
}
return {
pubKeys: pubKeys,
scriptType: scriptType,
signatures: pubKeys.map(function () { return undefined })
}
}
function checkP2SHInput (input, redeemScriptHash) {
if (input.prevOutType) {
if (input.prevOutType !== scriptTypes.P2SH) throw new Error('PrevOutScript must be P2SH')
var prevOutScriptScriptHash = bscript.decompile(input.prevOutScript)[1]
if (!prevOutScriptScriptHash.equals(redeemScriptHash)) throw new Error('Inconsistent hash160(RedeemScript)')
}
}
function checkP2WSHInput (input, witnessScriptHash) {
if (input.prevOutType) {
if (input.prevOutType !== scriptTypes.P2WSH) throw new Error('PrevOutScript must be P2WSH')
var scriptHash = bscript.decompile(input.prevOutScript)[1]
if (!scriptHash.equals(witnessScriptHash)) throw new Error('Inconsistent sha25(WitnessScript)')
}
}
function prepareInput (input, kpPubKey, redeemScript, witnessValue, witnessScript) {
var expanded
var prevOutType
var prevOutScript
var p2sh = false
var p2shType
var redeemScriptHash
var witness = false
var p2wsh = false
var witnessType
var witnessScriptHash
var signType
var signScript
if (redeemScript && witnessScript) {
redeemScriptHash = bcrypto.hash160(redeemScript)
witnessScriptHash = bcrypto.sha256(witnessScript)
checkP2SHInput(input, redeemScriptHash)
if (!redeemScript.equals(btemplates.witnessScriptHash.output.encode(witnessScriptHash))) throw new Error('Witness script inconsistent with redeem script')
expanded = expandOutput(witnessScript, undefined, kpPubKey)
if (!expanded.pubKeys) throw new Error('WitnessScript not supported "' + bscript.toASM(redeemScript) + '"')
prevOutType = btemplates.types.P2SH
prevOutScript = btemplates.scriptHash.output.encode(redeemScriptHash)
p2sh = witness = p2wsh = true
p2shType = btemplates.types.P2WSH
signType = witnessType = expanded.scriptType
signScript = witnessScript
} else if (redeemScript) {
redeemScriptHash = bcrypto.hash160(redeemScript)
checkP2SHInput(input, redeemScriptHash)
expanded = expandOutput(redeemScript, undefined, kpPubKey)
if (!expanded.pubKeys) throw new Error('RedeemScript not supported "' + bscript.toASM(redeemScript) + '"')
prevOutType = btemplates.types.P2SH
prevOutScript = btemplates.scriptHash.output.encode(redeemScriptHash)
p2sh = true
signType = p2shType = expanded.scriptType
signScript = redeemScript
witness = signType === btemplates.types.P2WPKH
} else if (witnessScript) {
witnessScriptHash = bcrypto.sha256(witnessScript)
checkP2WSHInput(input, witnessScriptHash)
expanded = expandOutput(witnessScript, undefined, kpPubKey)
if (!expanded.pubKeys) throw new Error('WitnessScript not supported "' + bscript.toASM(redeemScript) + '"')
prevOutType = btemplates.types.P2WSH
prevOutScript = btemplates.witnessScriptHash.output.encode(witnessScriptHash)
witness = p2wsh = true
signType = witnessType = expanded.scriptType
signScript = witnessScript
} else if (input.prevOutType) {
// embedded scripts are not possible without a redeemScript
if (input.prevOutType === scriptTypes.P2SH ||
input.prevOutType === scriptTypes.P2WSH) {
throw new Error('PrevOutScript is ' + input.prevOutType + ', requires redeemScript')
}
prevOutType = input.prevOutType
prevOutScript = input.prevOutScript
expanded = expandOutput(input.prevOutScript, input.prevOutType, kpPubKey)
if (!expanded.pubKeys) return
witness = (input.prevOutType === scriptTypes.P2WPKH)
signType = prevOutType
signScript = prevOutScript
} else {
prevOutScript = btemplates.pubKeyHash.output.encode(bcrypto.hash160(kpPubKey))
expanded = expandOutput(prevOutScript, scriptTypes.P2PKH, kpPubKey)
prevOutType = scriptTypes.P2PKH
witness = false
signType = prevOutType
signScript = prevOutScript
}
if (signType === scriptTypes.P2WPKH) {
signScript = btemplates.pubKeyHash.output.encode(btemplates.witnessPubKeyHash.output.decode(signScript))
}
if (p2sh) {
input.redeemScript = redeemScript
input.redeemScriptType = p2shType
}
if (p2wsh) {
input.witnessScript = witnessScript
input.witnessScriptType = witnessType
}
input.pubKeys = expanded.pubKeys
input.signatures = expanded.signatures
input.signScript = signScript
input.signType = signType
input.prevOutScript = prevOutScript
input.prevOutType = prevOutType
input.witness = witness
}
function buildStack (type, signatures, pubKeys, allowIncomplete) {
if (type === scriptTypes.P2PKH) {
if (signatures.length === 1 && Buffer.isBuffer(signatures[0]) && pubKeys.length === 1) return btemplates.pubKeyHash.input.encodeStack(signatures[0], pubKeys[0])
} else if (type === scriptTypes.SMART_TRANSACTION) {
if (signatures.length === 1 && Buffer.isBuffer(signatures[0])) return btemplates.smartTransaction.input.encodeStack(signatures[0])
} else if (type === scriptTypes.P2PK) {
if (signatures.length === 1 && Buffer.isBuffer(signatures[0])) return btemplates.pubKey.input.encodeStack(signatures[0])
} else if (type === scriptTypes.MULTISIG) {
if (signatures.length > 0) {
signatures = signatures.map(function (signature) {
return signature || ops.OP_0
})
if (!allowIncomplete) {
// remove blank signatures
signatures = signatures.filter(function (x) { return x !== ops.OP_0 })
}
return btemplates.multisig.input.encodeStack(signatures)
}
} else {
throw new Error('Not yet supported')
}
if (!allowIncomplete) throw new Error('Not enough signatures provided')
return []
}
function buildInput (input, allowIncomplete) {
var scriptType = input.prevOutType
var sig = []
var witness = []
if (supportedType(scriptType)) {
sig = buildStack(scriptType, input.signatures, input.pubKeys, allowIncomplete)
}
var p2sh = false
if (scriptType === btemplates.types.P2SH) {
// We can remove this error later when we have a guarantee prepareInput
// rejects unsignable scripts - it MUST be signable at this point.
if (!allowIncomplete && !supportedP2SHType(input.redeemScriptType)) {
throw new Error('Impossible to sign this type')
}
if (supportedType(input.redeemScriptType)) {
sig = buildStack(input.redeemScriptType, input.signatures, input.pubKeys, allowIncomplete)
}
// If it wasn't SIGNABLE, it's witness, defer to that
if (input.redeemScriptType) {
p2sh = true
scriptType = input.redeemScriptType
}
}
switch (scriptType) {
// P2WPKH is a special case of P2PKH
case btemplates.types.P2WPKH:
witness = buildStack(btemplates.types.P2PKH, input.signatures, input.pubKeys, allowIncomplete)
break
case btemplates.types.P2WSH:
// We can remove this check later
if (!allowIncomplete && !supportedType(input.witnessScriptType)) {
throw new Error('Impossible to sign this type')
}
if (supportedType(input.witnessScriptType)) {
witness = buildStack(input.witnessScriptType, input.signatures, input.pubKeys, allowIncomplete)
witness.push(input.witnessScript)
scriptType = input.witnessScriptType
}
break
}
// append redeemScript if necessary
if (p2sh) {
sig.push(input.redeemScript)
}
return {
type: scriptType,
script: bscript.compile(sig),
witness: witness
}
}
// By default, assume is a bitcoin transaction
function TransactionBuilder (network, maximumFeeRate) {
this.prevTxMap = {}
this.network = network || networks.bitcoin
// WARNING: This is __NOT__ to be relied on, its just another potential safety mechanism (safety in-depth)
this.maximumFeeRate = maximumFeeRate || 2500
this.inputs = []
this.tx = new Transaction(this.network)
}
TransactionBuilder.prototype.setLockTime = function (locktime) {
typeforce(types.UInt32, locktime)
// if any signatures exist, throw
if (this.inputs.some(function (input) {
if (!input.signatures) return false
return input.signatures.some(function (s) { return s })
})) {
throw new Error('No, this would invalidate signatures')
}
this.tx.locktime = locktime
}
TransactionBuilder.prototype.setVersion = function (version, overwinter = true) {
typeforce(types.UInt32, version)
if (coins.isZcashCompatible(this.network)) {
if (!this.network.consensusBranchId.hasOwnProperty(this.tx.version)) {
/* istanbul ignore next */
throw new Error('Unsupported Zcash transaction')
}
this.tx.overwintered = (overwinter ? 1 : 0)
this.tx.consensusBranchId = this.network.consensusBranchId[version]
}
this.tx.version = version
}
TransactionBuilder.prototype.setConsensusBranchId = function (consensusBranchId) {
if (!coins.isZcashCompatible(this.network)) {
throw new Error('consensusBranchId can only be set for Zcash or compatible transactions')
}
if (!this.inputs.every(function (input) {
if (input.prevOutType === scriptTypes.SMART_TRANSACTION) {
if (input.signatures === undefined || input.signatures.length === 0) return true
const smartTxSigs = SmartTransactionSignatures.fromChunk(bscript.decompile(input.signatures)[0])
if (
smartTxSigs.error != null ||
smartTxSigs.signatures.length === 0 ||
smartTxSigs.signatures.every((sig) => sig.oneSignature.length === 0)
) {
return true
}
}
return input.signatures === undefined
})) {
/* istanbul ignore next */
throw new Error('Changing the consensusBranchId for a partially signed transaction would invalidate signatures')
}
typeforce(types.UInt32, consensusBranchId)
this.tx.consensusBranchId = consensusBranchId
}
TransactionBuilder.prototype.setVersionGroupId = function (versionGroupId) {
if (!(coins.isZcashCompatible(this.network) && this.tx.isOverwinterCompatible())) {
throw new Error('expiryHeight can only be set for Zcash starting at overwinter version. Current network coin: ' +
this.network.coin + ', version: ' + this.tx.version)
}
typeforce(types.UInt32, versionGroupId)
this.tx.versionGroupId = versionGroupId
}
TransactionBuilder.prototype.setExpiryHeight = function (expiryHeight) {
if (!(coins.isZcashCompatible(this.network) && this.tx.isOverwinterCompatible())) {
throw new Error('expiryHeight can only be set for Zcash or compatible networks starting at overwinter version. Current network coin: ' +
this.network.coin + ', version: ' + this.tx.version)
}
typeforce(types.UInt32, expiryHeight)
this.tx.expiryHeight = expiryHeight
}
TransactionBuilder.prototype.setJoinSplits = function (transaction) {
if (!(coins.isZcashCompatible(this.network) && this.tx.supportsJoinSplits())) {
throw new Error('joinsplits can only be set for Zcash or compatible networks starting at version 2. Current network coin: ' +
this.network.coin + ', version: ' + this.tx.version)
}
if (transaction && transaction.joinsplits) {
this.tx.joinsplits = transaction.joinsplits.map(function (txJoinsplit) {
return {
vpubOld: txJoinsplit.vpubOld,
vpubNew: txJoinsplit.vpubNew,
anchor: txJoinsplit.anchor,
nullifiers: txJoinsplit.nullifiers,
commitments: txJoinsplit.commitments,
ephemeralKey: txJoinsplit.ephemeralKey,
randomSeed: txJoinsplit.randomSeed,
macs: txJoinsplit.macs,
zproof: txJoinsplit.zproof,
ciphertexts: txJoinsplit.ciphertexts
}
})
this.tx.joinsplitPubkey = transaction.joinsplitPubkey
this.tx.joinsplitSig = transaction.joinsplitSig
return
}
throw new Error('Invalid transaction with joinsplits')
}
TransactionBuilder.fromTransaction = function (transaction, network) {
var txbNetwork = network || networks.bitcoin
var txb = new TransactionBuilder(txbNetwork)
if (getMainnet(txb.network) !== getMainnet(transaction.network)) {
throw new Error('This transaction is incompatible with the transaction builder')
}
// Copy transaction fields
txb.setVersion(transaction.version, transaction.overwintered)
txb.setLockTime(transaction.locktime)
if (coins.isZcashCompatible(txbNetwork)) {
// Copy Zcash overwinter fields. Omitted if the transaction builder is not for Zcash.
if (txb.tx.isOverwinterCompatible()) {
txb.setVersionGroupId(transaction.versionGroupId)
txb.setExpiryHeight(transaction.expiryHeight)
}
txb.setConsensusBranchId(transaction.consensusBranchId)
}
// Copy Dash special transaction fields. Omitted if the transaction builder is not for Dash.
if (coins.isDash(txbNetwork)) {
typeforce(types.UInt16, transaction.type)
txb.tx.type = transaction.type
if (txb.tx.versionSupportsDashSpecialTransactions()) {
typeforce(types.Buffer, transaction.extraPayload)
txb.tx.extraPayload = transaction.extraPayload
}
}
// Copy outputs (done first to avoid signature invalidation)
transaction.outs.forEach(function (txOut) {
txb.addOutput(txOut.script, txOut.value)
})
// Copy inputs
transaction.ins.forEach(function (txIn) {
txb.__addInputUnsafe(txIn.hash, txIn.index, {
sequence: txIn.sequence,
script: txIn.script,
witness: txIn.witness,
value: txIn.value
})
})
// fix some things not possible through the public API
txb.inputs.forEach(function (input, i) {
fixMultisigOrder(input, transaction, i, input.value, txbNetwork)
})
return txb
}
TransactionBuilder.prototype.addInput = function (txHash, vout, sequence, prevOutScript) {
if (!this.__canModifyInputs()) {
throw new Error('No, this would invalidate signatures')
}
var value
// is it a hex string?
if (typeof txHash === 'string') {
// transaction hashs's are displayed in reverse order, un-reverse it
txHash = Buffer.from(txHash, 'hex').reverse()
// is it a Transaction object?
} else if (txHash instanceof Transaction) {
var txOut = txHash.outs[vout]
prevOutScript = txOut.script
value = txOut.value
txHash = txHash.getHash()
}
return this.__addInputUnsafe(txHash, vout, {
sequence: sequence,
prevOutScript: prevOutScript,
value: value
})
}
TransactionBuilder.prototype.__addInputUnsafe = function (txHash, vout, options) {
if (Transaction.isCoinbaseHash(txHash)) {
throw new Error('coinbase inputs not supported')
}
var prevTxOut = txHash.toString('hex') + ':' + vout
if (this.prevTxMap[prevTxOut] !== undefined) throw new Error('Duplicate TxOut: ' + prevTxOut)
var input = {}
// derive what we can from the scriptSig
if (options.script !== undefined) {
input = expandInput(options.script, options.witness || [])
}
// if an input value was given, retain it
if (options.value !== undefined) {
input.value = options.value
}
// derive what we can from the previous transactions output script
if (!input.prevOutScript && options.prevOutScript) {
var prevOutType
if (!input.pubKeys && !input.signatures) {
var expanded = expandOutput(options.prevOutScript)
if (expanded.pubKeys) {
input.pubKeys = expanded.pubKeys
input.signatures = expanded.signatures
}
prevOutType = expanded.scriptType
}
input.prevOutScript = options.prevOutScript
input.prevOutType = prevOutType || btemplates.classifyOutput(options.prevOutScript)
}
var vin = this.tx.addInput(txHash, vout, options.sequence, options.script)
this.inputs[vin] = input
this.prevTxMap[prevTxOut] = vin
return vin
}
TransactionBuilder.prototype.addOutput = function (scriptPubKey, value) {
if (!this.__canModifyOutputs()) {
throw new Error('No, this would invalidate signatures')
}
// Attempt to get a script if it's a base58 address string
if (typeof scriptPubKey === 'string') {
scriptPubKey = baddress.toOutputScript(scriptPubKey, this.network)
}
return this.tx.addOutput(scriptPubKey, value)
}
TransactionBuilder.prototype.build = function () {
return this.__build(false)
}
TransactionBuilder.prototype.buildIncomplete = function () {
return this.__build(true)
}
TransactionBuilder.prototype.__build = function (allowIncomplete) {
if (!allowIncomplete) {
if (!this.tx.ins.length) throw new Error('Transaction has no inputs')
if (!this.tx.outs.length) throw new Error('Transaction has no outputs')
}
var tx = this.tx.clone()
// Create script signatures from inputs
this.inputs.forEach(function (input, i) {
var scriptType = input.witnessScriptType || input.redeemScriptType || input.prevOutType
if (!scriptType && !allowIncomplete) throw new Error('Transaction is not complete')
var result = buildInput(input, allowIncomplete)
// skip if no result
if (!allowIncomplete) {
if (!supportedType(result.type) && result.type !== btemplates.types.P2WPKH) {
throw new Error(result.type + ' not supported')
}
}
tx.setInputScript(i, result.script)
tx.setWitness(i, result.witness)
})
if (!allowIncomplete) {
// do not rely on this, its merely a last resort
if (this.__overMaximumFees(tx.virtualSize())) {
throw new Error('Transaction has absurd fees')
}
}
return tx
}
function canSign (input) {
return (
input.prevOutScript !== undefined &&
input.signScript !== undefined &&
input.pubKeys !== undefined &&
input.signatures !== undefined &&
input.signatures.length === input.pubKeys.length &&
input.pubKeys.length > 0 &&
(input.witness === false || (input.witness === true && input.value !== undefined))
)
}
TransactionBuilder.prototype.sign = function (vin, keyPair, redeemScript, hashType, witnessValue, witnessScript) {
debug('Signing transaction: (input: %d, hashType: %d, witnessVal: %s, witnessScript: %j)', vin, hashType, witnessValue, witnessScript)
debug('Transaction Builder network: %j', this.network)
// TODO: remove keyPair.network matching in 4.0.0
if (keyPair.network && keyPair.network !== this.network) throw new TypeError('Inconsistent network')
if (!this.inputs[vin]) throw new Error('No input at index: ' + vin)
hashType = hashType || Transaction.SIGHASH_ALL
var input = this.inputs[vin]
// if redeemScript was previously provided, enforce consistency
if (input.redeemScript !== undefined &&
redeemScript &&
!input.redeemScript.equals(redeemScript)) {
throw new Error('Inconsistent redeemScript')
}
var kpPubKey = keyPair.publicKey || keyPair.getPublicKeyBuffer()
if (!canSign(input)) {
if (witnessValue !== undefined) {
if (input.value !== undefined && input.value !== witnessValue) throw new Error('Input didn\'t match witnessValue')
typeforce(types.Satoshi, witnessValue)
input.value = witnessValue
}
debug('Preparing input %d for signing', vin)
if (!canSign(input)) prepareInput(input, kpPubKey, redeemScript, witnessValue, witnessScript)
if (!canSign(input)) throw Error(input.prevOutType + ' not supported')
}
// ready to sign
var signatureHash = this.tx.hashForSignatureByNetwork(
vin,
input.signScript,
witnessValue,
hashType,
!!input.witness
)
// enforce in order signing of public keys
var signed = input.pubKeys.some(function (pubKey, i) {
if (!kpPubKey.equals(pubKey)) return false
if (input.signatures[i]) throw new Error('Signature already exists')
if (kpPubKey.length !== 33 &&
input.signType === scriptTypes.P2WPKH) throw new Error('BIP143 rejects uncompressed public keys in P2WPKH or P2WSH')
var signature = keyPair.sign(signatureHash)
if (Buffer.isBuffer(signature)) signature = ECSignature.fromRSBuffer(signature)
debug('Produced signature (r: %s, s: %s)', signature.r, signature.s)
if (input.signType === scriptTypes.SMART_TRANSACTION) {
input.signatures[i] = new SmartTransactionSignatures(1, 1, [
new SmartTransactionSignature(
1,
1,
pubKey,
signature.toCompact().slice(1)
)
]).toChunk()
} else input.signatures[i] = signature.toScriptSignature(hashType)
return true
})
if (!signed) throw new Error('Key pair cannot sign for this input')
}
function signatureHashType (buffer) {
return buffer.readUInt8(buffer.length - 1)
}
TransactionBuilder.prototype.__canModifyInputs = function () {
return this.inputs.every(function (input) {
// any signatures?
if (input.signatures === undefined) return true
return input.signatures.every(function (signature) {
if (!signature) return true
var hashType = signatureHashType(signature)
// if SIGHASH_ANYONECANPAY is set, signatures would not
// be invalidated by more inputs
return hashType & Transaction.SIGHASH_ANYONECANPAY
})
})
}
TransactionBuilder.prototype.__canModifyOutputs = function () {
var nInputs = this.tx.ins.length
var nOutputs = this.tx.outs.length
return this.inputs.every(function (input) {
if (input.signatures === undefined) return true
if (input.signType === scriptTypes.SMART_TRANSACTION) {
const smartTxSigs = SmartTransactionSignatures.fromChunk(bscript.decompile(input.signatures)[0])
if (
smartTxSigs.error != null ||
smartTxSigs.signatures.length === 0 ||
smartTxSigs.signatures.every((sig) => sig.oneSignature.length === 0)
) {
return true
}
}
return input.signatures.every(function (signature) {
if (!signature) return true
var hashType = signatureHashType(signature)
var hashTypeMod = hashType & 0x1f
if (hashTypeMod === Transaction.SIGHASH_NONE) return true
if (hashTypeMod === Transaction.SIGHASH_SINGLE) {
// if SIGHASH_SINGLE is set, and nInputs > nOutputs
// some signatures would be invalidated by the addition
// of more outputs
return nInputs <= nOutputs
}
})
})
}
TransactionBuilder.prototype.__overMaximumFees = function (bytes) {
// not all inputs will have .value defined
var incoming = this.inputs.reduce(function (a, x) { return a + (x.value >>> 0) }, 0)
// but all outputs do, and if we have any input value
// we can immediately determine if the outputs are too small
var outgoing = this.tx.outs.reduce(function (a, x) { return a + x.value }, 0)
var fee = incoming - outgoing
var feeRate = fee / bytes
return feeRate > this.maximumFeeRate
}
module.exports = TransactionBuilder