-
Notifications
You must be signed in to change notification settings - Fork 12
/
pset.go
603 lines (522 loc) · 14.1 KB
/
pset.go
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
package psetv2
import (
"bytes"
"encoding/base64"
"encoding/hex"
"fmt"
"strings"
"github.com/vulpemventures/go-elements/address"
"github.com/vulpemventures/go-elements/elementsutil"
"github.com/vulpemventures/go-elements/internal/bufferutil"
"github.com/vulpemventures/go-elements/payment"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcd/btcec/v2/ecdsa"
"github.com/btcsuite/btcd/txscript"
"github.com/vulpemventures/go-elements/transaction"
)
const (
separator = 0x00
maxPsbtKeyLength = 10000
minTimeLockTime = 500000000
maxHeightLockTime = 499999999
PsetProprietary = 0xfc
)
var (
magicPrefix = []byte{0x70, 0x73, 0x65, 0x74}
magicPrefixWithSeparator = append(magicPrefix, 0xff)
ErrInvalidPsbtFormat = fmt.Errorf("invalid PSBT serialization format")
ErrNoMoreKeyPairs = fmt.Errorf("no more key-pairs")
ErrInvalidMagicBytes = fmt.Errorf("invalid magic bytes")
ErrPsetMissingBlindedOutput = fmt.Errorf(
"pset has blinded inputs, at least one output must be blinded",
)
ErrPsetInvalidGlobablModifiableState = fmt.Errorf(
"global modifiable flag must be unset for fully blinded pset",
)
ErrPsetForbiddenInputsModification = fmt.Errorf(
"pset locked for modifications on inputs",
)
ErrPsetForbiddenOutputsModification = fmt.Errorf(
"pset locked for modifications on outputs",
)
ErrPartialSignatureMissingPubKey = fmt.Errorf(
"input partial signature is missing pubkey",
)
)
// Pset - Partially Signed Elements Transaction
// Format:
// <pset> := <magic> <global-map> <input-map>* <output-map>*
// <magic> := 0x70 0x73 0x65 0x74 0xFF -> pset starts with magic bytes, after which goes global map
// followed by more input-map's and output-map's
// <global-map> := <keypair>* 0x00 -> there is one global-map, there can be many keypair's, global map ends with separator
// <input-map> := <keypair>* 0x00 -> there can be many input-map's, there can be many keypair's, input map ends with separator
// <output-map> := <keypair>* 0x00 -> there can be many output-map's, there can be many keypair's, output map ends with separator
// <keypair> := <key> <value>
// <key> := <keylen> <keytype> <keydata>
// <value> := <valuelen> <valuedata>
// Each map can contain ProprietaryData data and unknowns keypair's
// Full spec: https://github.com/ElementsProject/elements/blob/master/doc/pset.mediawiki
type Pset struct {
Global Global
Inputs []Input
Outputs []Output
}
func NewPsetFromBuffer(buf *bytes.Buffer) (*Pset, error) {
return deserialize(buf)
}
func NewPsetFromBase64(psetBase64 string) (*Pset, error) {
psetBytes, err := base64.StdEncoding.DecodeString(psetBase64)
if err != nil {
return nil, fmt.Errorf("failed to parse pset in base64 format: %s", err)
}
return deserialize(bytes.NewBuffer(psetBytes))
}
func (p *Pset) ToBase64() (string, error) {
buf, err := p.serialize()
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(buf), nil
}
func (p *Pset) Copy() *Pset {
return &Pset{
Global: p.Global,
Inputs: p.Inputs,
Outputs: p.Outputs,
}
}
func (p *Pset) InputsModifiable() bool {
if p.Global.TxModifiable != nil {
return p.Global.TxModifiable.Test(0)
}
return true
}
func (p *Pset) OutputsModifiable() bool {
if p.Global.TxModifiable != nil {
return p.Global.TxModifiable.Test(1)
}
return true
}
func (p *Pset) HasSighashSingle() bool {
if p.Global.TxModifiable == nil {
return false
}
return p.Global.TxModifiable.Test(2)
}
func (p *Pset) NeedsBlinding() bool {
for _, out := range p.Outputs {
if out.NeedsBlinding() && !out.IsFullyBlinded() {
return true
}
}
return false
}
func (p *Pset) IsFullyBlinded() bool {
if !p.NeedsBlinding() {
return false
}
for _, out := range p.Outputs {
if out.NeedsBlinding() && !out.IsFullyBlinded() {
return false
}
}
return true
}
func (p *Pset) IsComplete() bool {
for i := 0; i < len(p.Inputs); i++ {
if !isFinalized(p, i) {
return false
}
}
return true
}
func (p *Pset) Locktime() uint32 {
var heightLocktime, timeLocktime uint32
for _, v := range p.Inputs {
if v.RequiredTimeLocktime > 0 {
if v.RequiredTimeLocktime > timeLocktime {
timeLocktime = v.RequiredTimeLocktime
}
}
if v.RequiredHeightLocktime > 0 {
if v.RequiredHeightLocktime > heightLocktime {
heightLocktime = v.RequiredHeightLocktime
}
}
}
if heightLocktime > 0 {
return heightLocktime
}
if timeLocktime > 0 {
return timeLocktime
}
var locktime uint32
if p.Global.FallbackLocktime != nil {
locktime = *p.Global.FallbackLocktime
}
return locktime
}
func (p *Pset) SanityCheck() error {
var hasFullyBlindedOutput bool
for i, in := range p.Inputs {
if err := in.SanityCheck(); err != nil {
return fmt.Errorf("invalid input %d: %s", i, err)
}
}
for i, out := range p.Outputs {
if err := out.SanityCheck(); err != nil {
return fmt.Errorf("invalid output %d: %s", i, err)
}
if out.IsFullyBlinded() {
hasFullyBlindedOutput = true
}
}
if hasFullyBlindedOutput && len(p.Global.Scalars) == 0 && p.NeedsBlinding() {
return ErrPsetInvalidGlobablModifiableState
}
return nil
}
func (p *Pset) UnsignedTx() (*transaction.Transaction, error) {
tx := transaction.NewTx(int32(p.Global.TxVersion))
tx.Locktime = p.Locktime()
for _, in := range p.Inputs {
txIn := transaction.NewTxInput(in.PreviousTxid, in.PreviousTxIndex)
sequence := in.Sequence
if sequence == 0 {
sequence = transaction.DefaultSequence
}
txIn.Sequence = sequence
if in.IssuanceAssetEntropy != nil {
issuanceValue := in.IssuanceValueCommitment
if issuanceValue == nil {
issuanceValue, _ = elementsutil.ValueToBytes(in.IssuanceValue)
}
tokenValue := in.IssuanceInflationKeysCommitment
if tokenValue == nil {
if in.IssuanceInflationKeys > 0 {
tokenValue, _ = elementsutil.ValueToBytes(in.IssuanceInflationKeys)
} else {
tokenValue = []byte{0x00}
}
}
txIn.Issuance = &transaction.TxIssuance{
AssetEntropy: in.IssuanceAssetEntropy,
AssetBlindingNonce: in.IssuanceBlindingNonce,
AssetAmount: issuanceValue,
TokenAmount: tokenValue,
}
}
tx.AddInput(txIn)
}
for _, out := range p.Outputs {
value := out.ValueCommitment
if value == nil {
value, _ = elementsutil.ValueToBytes(out.Value)
}
asset := out.AssetCommitment
if asset == nil {
asset = append([]byte{0x01}, out.Asset...)
}
txOut := transaction.NewTxOutput(asset, value, out.Script)
txOut.Script = out.Script
txOut.RangeProof = out.ValueRangeproof
txOut.SurjectionProof = out.AssetSurjectionProof
if out.EcdhPubkey != nil {
txOut.Nonce = out.EcdhPubkey
}
tx.AddOutput(txOut)
}
return tx, nil
}
func (p *Pset) ValidateAllSignatures() (bool, error) {
for i := range p.Inputs {
valid, err := p.ValidateInputSignatures(i)
if err != nil {
return false, err
}
if !valid {
return false, nil
}
}
return true, nil
}
func (p *Pset) ValidateInputSignatures(
inputIndex int,
) (bool, error) {
if len(p.Inputs[inputIndex].PartialSigs) > 0 {
for _, partialSig := range p.Inputs[inputIndex].PartialSigs {
valid, err := p.validatePartialSignature(inputIndex, partialSig)
if err != nil {
return false, err
}
if !valid {
return false, nil
}
}
return true, nil
}
return false, nil
}
func (p *Pset) addInput(in Input) error {
if err := in.SanityCheck(); err != nil {
return err
}
if p.isDuplicateInput(in) {
return fmt.Errorf("input already existing")
}
if !p.InputsModifiable() {
return ErrPsetForbiddenInputsModification
}
if in.RequiredHeightLocktime != 0 || in.RequiredTimeLocktime != 0 {
oldLocktime := p.Locktime()
timeLocktime := in.RequiredTimeLocktime
heightLocktime := in.RequiredHeightLocktime
hasSigs := false
for _, i := range p.Inputs {
if i.RequiredTimeLocktime != 0 && i.RequiredHeightLocktime == 0 {
heightLocktime = 0
if timeLocktime == 0 {
return ErrInInvalidLocktime
}
}
if i.RequiredTimeLocktime == 0 && i.RequiredHeightLocktime != 0 {
timeLocktime = 0
if heightLocktime == 0 {
return ErrInInvalidLocktime
}
}
if i.RequiredTimeLocktime != 0 && timeLocktime != 0 {
timeLocktime = max(timeLocktime, i.RequiredTimeLocktime)
}
if i.RequiredHeightLocktime != 0 && heightLocktime != 0 {
heightLocktime = max(heightLocktime, i.RequiredHeightLocktime)
}
if len(i.PartialSigs) > 0 {
hasSigs = true
}
}
var newLocktime uint32
if p.Global.FallbackLocktime != nil {
newLocktime = *p.Global.FallbackLocktime
}
if timeLocktime != 0 {
newLocktime = timeLocktime
}
if heightLocktime != 0 {
newLocktime = heightLocktime
}
if hasSigs && oldLocktime != newLocktime {
return ErrInInvalidLocktime
}
}
p.Inputs = append(p.Inputs, in)
p.Global.InputCount++
return nil
}
func (p *Pset) addOutput(out Output) error {
if err := out.SanityCheck(); err != nil {
return err
}
if !p.OutputsModifiable() {
return ErrPsetForbiddenOutputsModification
}
p.Outputs = append(p.Outputs, out)
p.Global.OutputCount++
return nil
}
func (p *Pset) isDuplicateInput(in Input) bool {
for _, i := range p.Inputs {
if bytes.Equal(i.PreviousTxid, in.PreviousTxid) &&
i.PreviousTxIndex == in.PreviousTxIndex {
return true
}
}
return false
}
func (p *Pset) validatePartialSignature(
inputIndex int, partialSignature PartialSig,
) (bool, error) {
if len(partialSignature.PubKey) == 0 {
return false, ErrPartialSignatureMissingPubKey
}
signatureLen := len(partialSignature.Signature)
sigHashType := partialSignature.Signature[signatureLen-1]
signatureDer := partialSignature.Signature[:signatureLen-1]
sigHash, script, err := p.getHashAndScriptForSignature(
inputIndex, uint32(sigHashType),
)
if err != nil {
return false, err
}
valid, err := p.verifyScriptForPubKey(script, partialSignature.PubKey)
if err != nil {
return false, err
}
if !valid {
return false, nil
}
pSig, err := ecdsa.ParseDERSignature(signatureDer)
if err != nil {
return false, nil
}
pubKey, err := btcec.ParsePubKey(partialSignature.PubKey)
if err != nil {
return false, nil
}
return pSig.Verify(sigHash, pubKey), nil
}
func (p *Pset) getHashAndScriptForSignature(
inputIndex int, sigHashType uint32,
) ([]byte, []byte, error) {
var hash [32]byte
var script []byte
unsignedTx, err := p.UnsignedTx()
if err != nil {
return nil, nil, err
}
sighash := txscript.SigHashType(sigHashType)
input := p.Inputs[inputIndex]
if input.NonWitnessUtxo != nil {
prevoutHash := p.Inputs[inputIndex].PreviousTxid
utxoHash := input.NonWitnessUtxo.TxHash()
if !bytes.Equal(prevoutHash, utxoHash.CloneBytes()) {
return nil, nil, ErrInInvalidNonWitnessUtxo
}
prevoutIndex := p.Inputs[inputIndex].PreviousTxIndex
prevout := input.NonWitnessUtxo.Outputs[prevoutIndex]
if input.RedeemScript != nil {
script = input.RedeemScript
} else {
script = prevout.Script
}
switch address.GetScriptType(script) {
case address.P2WshScript:
if input.WitnessScript == nil {
return nil, nil, fmt.Errorf(
"segwit input needs witnessScript if not p2wpkh",
)
}
hash = unsignedTx.HashForWitnessV0(
inputIndex, input.WitnessScript, prevout.Value, sighash,
)
script = input.WitnessScript
case address.P2WpkhScript:
pay, err := payment.FromScript(script, nil, nil)
if err != nil {
return nil, nil, err
}
hash = unsignedTx.HashForWitnessV0(
inputIndex, pay.Script, input.WitnessUtxo.Value, sighash,
)
default:
var err error
hash, err = unsignedTx.HashForSignature(
inputIndex, script, sighash,
)
if err != nil {
return nil, nil, err
}
}
} else if input.WitnessUtxo != nil {
if input.RedeemScript != nil {
script = input.RedeemScript
} else {
script = input.WitnessUtxo.Script
}
switch address.GetScriptType(script) {
case address.P2WpkhScript:
pay, err := payment.FromScript(script, nil, nil)
if err != nil {
return nil, nil, err
}
hash = unsignedTx.HashForWitnessV0(
inputIndex, pay.Script, input.WitnessUtxo.Value, sighash,
)
case address.P2WshScript:
hash = unsignedTx.HashForWitnessV0(
inputIndex, input.WitnessScript, input.WitnessUtxo.Value, sighash,
)
script = input.WitnessScript
default:
return nil, nil, fmt.Errorf("input has witnessUtxo but non-segwit script")
}
} else {
return nil, nil, fmt.Errorf("need a utxo input item for signing")
}
return hash[:], script, nil
}
func (p *Pset) verifyScriptForPubKey(script, pubKey []byte) (bool, error) {
pk, err := btcec.ParsePubKey(pubKey)
if err != nil {
return false, err
}
pkHash := payment.Hash160(pubKey)
scriptAsm, err := txscript.DisasmString(script)
if err != nil {
return false, err
}
if strings.Contains(
scriptAsm, hex.EncodeToString(pk.SerializeCompressed()),
) || strings.Contains(
scriptAsm, hex.EncodeToString(pkHash),
) {
return true, nil
}
return false, nil
}
func (p *Pset) serialize() ([]byte, error) {
s := bufferutil.NewSerializer(nil)
if err := s.WriteSlice(magicPrefixWithSeparator); err != nil {
return nil, err
}
if err := p.Global.serialize(s); err != nil {
return nil, err
}
for _, v := range p.Inputs {
if err := v.serialize(s); err != nil {
return nil, err
}
}
for _, v := range p.Outputs {
if err := v.serialize(s); err != nil {
return nil, err
}
}
return s.Bytes(), nil
}
func deserialize(buf *bytes.Buffer) (*Pset, error) {
d := bufferutil.NewDeserializer(buf)
magic, err := d.ReadSlice(uint(len(magicPrefixWithSeparator)))
if err != nil {
return nil, err
}
if !bytes.Equal(magic, magicPrefixWithSeparator) {
return nil, ErrInvalidMagicBytes
}
global := Global{}
if err := global.deserialize(buf); err != nil {
return nil, err
}
inputs := make([]Input, 0)
for i := 0; i < int(global.InputCount); i++ {
input := Input{}
if err := input.deserialize(buf); err != nil {
return nil, err
}
inputs = append(inputs, input)
}
outputs := make([]Output, 0)
for i := 0; i < int(global.OutputCount); i++ {
output := Output{}
err := output.deserialize(buf)
if err != nil {
return nil, err
}
outputs = append(outputs, output)
}
newPset := &Pset{Global: global, Inputs: inputs, Outputs: outputs}
if err := newPset.SanityCheck(); err != nil {
return nil, err
}
return newPset, nil
}