-
Notifications
You must be signed in to change notification settings - Fork 27
/
sortsignsend.go
795 lines (725 loc) · 22.1 KB
/
sortsignsend.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
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
// Copyright (C) 2015-2016 The Lightning Network Developers
// Copyright (c) 2016-2017 The OpenBazaar Developers
package bitcoincash
import (
"bytes"
"encoding/hex"
"errors"
"fmt"
"time"
"github.com/OpenBazaar/wallet-interface"
"github.com/btcsuite/btcd/blockchain"
"github.com/btcsuite/btcd/btcec"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
btc "github.com/btcsuite/btcutil"
"github.com/btcsuite/btcutil/coinset"
hd "github.com/btcsuite/btcutil/hdkeychain"
"github.com/btcsuite/btcutil/txsort"
"github.com/btcsuite/btcwallet/wallet/txauthor"
"github.com/btcsuite/btcwallet/wallet/txrules"
"github.com/cpacia/bchutil"
)
func (s *SPVWallet) Broadcast(tx *wire.MsgTx) error {
// Our own tx; don't keep track of false positives
_, err := s.txstore.Ingest(tx, 0, time.Now())
if err != nil {
return err
}
// make an inv message instead of a tx message to be polite
txid := tx.TxHash()
iv1 := wire.NewInvVect(wire.InvTypeTx, &txid)
invMsg := wire.NewMsgInv()
err = invMsg.AddInvVect(iv1)
if err != nil {
return err
}
s.wireService.MsgChan() <- updateFiltersMsg{}
log.Debugf("Broadcasting tx %s to peers", tx.TxHash().String())
for _, peer := range s.peerManager.ConnectedPeers() {
peer.QueueMessage(tx, nil)
}
return nil
}
type Coin struct {
TxHash *chainhash.Hash
TxIndex uint32
TxValue btc.Amount
TxNumConfs int64
ScriptPubKey []byte
}
func (c *Coin) Hash() *chainhash.Hash { return c.TxHash }
func (c *Coin) Index() uint32 { return c.TxIndex }
func (c *Coin) Value() btc.Amount { return c.TxValue }
func (c *Coin) PkScript() []byte { return c.ScriptPubKey }
func (c *Coin) NumConfs() int64 { return c.TxNumConfs }
func (c *Coin) ValueAge() int64 { return int64(c.TxValue) * c.TxNumConfs }
func NewCoin(txid []byte, index uint32, value btc.Amount, numConfs int64, scriptPubKey []byte) coinset.Coin {
shaTxid, _ := chainhash.NewHash(txid)
c := &Coin{
TxHash: shaTxid,
TxIndex: index,
TxValue: value,
TxNumConfs: numConfs,
ScriptPubKey: scriptPubKey,
}
return coinset.Coin(c)
}
func (w *SPVWallet) gatherCoins() map[coinset.Coin]*hd.ExtendedKey {
height, _ := w.blockchain.db.Height()
utxos, _ := w.txstore.Utxos().GetAll()
m := make(map[coinset.Coin]*hd.ExtendedKey)
for _, u := range utxos {
if u.WatchOnly {
continue
}
var confirmations int32
if u.AtHeight > 0 {
confirmations = int32(height) - u.AtHeight
}
c := NewCoin(u.Op.Hash.CloneBytes(), u.Op.Index, btc.Amount(u.Value), int64(confirmations), u.ScriptPubkey)
addr, err := w.ScriptToAddress(u.ScriptPubkey)
if err != nil {
continue
}
key, err := w.keyManager.GetKeyForScript(addr.ScriptAddress())
if err != nil {
continue
}
m[c] = key
}
return m
}
func (w *SPVWallet) Spend(amount int64, addr btc.Address, feeLevel wallet.FeeLevel, referenceID string) (*chainhash.Hash, error) {
tx, err := w.buildTx(amount, addr, feeLevel, nil)
if err != nil {
return nil, err
}
// Broadcast
err = w.Broadcast(tx)
if err != nil {
return nil, err
}
ch := tx.TxHash()
return &ch, nil
}
var BumpFeeAlreadyConfirmedError = errors.New("Transaction is confirmed, cannot bump fee")
var BumpFeeTransactionDeadError = errors.New("Cannot bump fee of dead transaction")
var BumpFeeNotFoundError = errors.New("Transaction either doesn't exist or has already been spent")
func (w *SPVWallet) BumpFee(txid chainhash.Hash) (*chainhash.Hash, error) {
txn, err := w.txstore.Txns().Get(txid)
if err != nil {
return nil, err
}
if txn.Height > 0 {
return nil, BumpFeeAlreadyConfirmedError
}
if txn.Height < 0 {
return nil, BumpFeeTransactionDeadError
}
// Check stxos for RBF opportunity
/*stxos, _ := w.txstore.Stxos().GetAll()
for _, s := range stxos {
if s.SpendTxid.IsEqual(&txid) {
r := bytes.NewReader(txn.Bytes)
msgTx := wire.NewMsgTx(1)
msgTx.BtcDecode(r, 1)
for i, output := range msgTx.TxOut {
key, err := w.txstore.GetKeyForScript(output.PkScript)
if key != nil && err == nil { // This is our change output
// Calculate change - additional fee
feePerByte := w.GetFeePerByte(PRIOIRTY)
estimatedSize := EstimateSerializeSize(len(msgTx.TxIn), msgTx.TxOut, false)
fee := estimatedSize * int(feePerByte)
newValue := output.Value - int64(fee)
// Check if still above dust value
if newValue <= 0 || txrules.IsDustAmount(btc.Amount(newValue), len(output.PkScript), txrules.DefaultRelayFeePerKb) {
msgTx.TxOut = append(msgTx.TxOut[:i], msgTx.TxOut[i+1:]...)
} else {
output.Value = newValue
}
// Bump sequence number
optInRBF := false
for _, input := range msgTx.TxIn {
if input.Sequence < 4294967294 {
input.Sequence++
optInRBF = true
}
}
if !optInRBF {
break
}
//TODO: Re-sign transaction
// Mark original tx as dead
if err = w.txstore.markAsDead(txid); err != nil {
return nil, err
}
// Broadcast new tx
if err := w.Broadcast(msgTx); err != nil {
return nil, err
}
newTxid := msgTx.TxHash()
return &newTxid, nil
}
}
}
}*/
// Check utxos for CPFP
utxos, _ := w.txstore.Utxos().GetAll()
for _, u := range utxos {
if u.Op.Hash.IsEqual(&txid) && u.AtHeight == 0 {
addr, err := w.ScriptToAddress(u.ScriptPubkey)
if err != nil {
return nil, err
}
key, err := w.keyManager.GetKeyForScript(addr.ScriptAddress())
if err != nil {
return nil, err
}
h, err := hex.DecodeString(u.Op.Hash.String())
if err != nil {
return nil, err
}
in := wallet.TransactionInput{
LinkedAddress: addr,
OutpointIndex: u.Op.Index,
OutpointHash: h,
Value: u.Value,
}
transactionID, err := w.SweepAddress([]wallet.TransactionInput{in}, nil, key, nil, wallet.FEE_BUMP)
if err != nil {
return nil, err
}
return transactionID, nil
}
}
return nil, BumpFeeNotFoundError
}
func (w *SPVWallet) EstimateFee(ins []wallet.TransactionInput, outs []wallet.TransactionOutput, feePerByte uint64) uint64 {
tx := wire.NewMsgTx(1)
for _, out := range outs {
scriptPubKey, _ := bchutil.PayToAddrScript(out.Address)
output := wire.NewTxOut(out.Value, scriptPubKey)
tx.TxOut = append(tx.TxOut, output)
}
estimatedSize := EstimateSerializeSize(len(ins), tx.TxOut, false, P2PKH)
fee := estimatedSize * int(feePerByte)
return uint64(fee)
}
// Build a spend transaction for the amount and return the transaction fee
func (w *SPVWallet) EstimateSpendFee(amount int64, feeLevel wallet.FeeLevel) (uint64, error) {
// Since this is an estimate we can use a dummy output address. Let's use a long one so we don't under estimate.
addr, err := btc.DecodeAddress("114K8nZhYcG1rsxcc1YGujFwWj5NLByc5v", w.params)
if err != nil {
return 0, err
}
tx, err := w.buildTx(amount, addr, feeLevel, nil)
if err != nil {
return 0, err
}
var outval int64
for _, output := range tx.TxOut {
outval += output.Value
}
var inval int64
utxos, err := w.txstore.Utxos().GetAll()
if err != nil {
return 0, err
}
for _, input := range tx.TxIn {
for _, utxo := range utxos {
if utxo.Op.Hash.IsEqual(&input.PreviousOutPoint.Hash) && utxo.Op.Index == input.PreviousOutPoint.Index {
inval += utxo.Value
break
}
}
}
if inval < outval {
return 0, errors.New("Error building transaction: inputs less than outputs")
}
return uint64(inval - outval), err
}
func (w *SPVWallet) GenerateMultisigScript(keys []hd.ExtendedKey, threshold int, timeout time.Duration, timeoutKey *hd.ExtendedKey) (addr btc.Address, redeemScript []byte, err error) {
if uint32(timeout.Hours()) > 0 && timeoutKey == nil {
return nil, nil, errors.New("Timeout key must be non nil when using an escrow timeout")
}
if len(keys) < threshold {
return nil, nil, fmt.Errorf("unable to generate multisig script with "+
"%d required signatures when there are only %d public "+
"keys available", threshold, len(keys))
}
var ecKeys []*btcec.PublicKey
for _, key := range keys {
ecKey, err := key.ECPubKey()
if err != nil {
return nil, nil, err
}
ecKeys = append(ecKeys, ecKey)
}
builder := txscript.NewScriptBuilder()
if uint32(timeout.Hours()) == 0 {
builder.AddInt64(int64(threshold))
for _, key := range ecKeys {
builder.AddData(key.SerializeCompressed())
}
builder.AddInt64(int64(len(ecKeys)))
builder.AddOp(txscript.OP_CHECKMULTISIG)
} else {
ecKey, err := timeoutKey.ECPubKey()
if err != nil {
return nil, nil, err
}
sequenceLock := blockchain.LockTimeToSequence(false, uint32(timeout.Hours()*6))
builder.AddOp(txscript.OP_IF)
builder.AddInt64(int64(threshold))
for _, key := range ecKeys {
builder.AddData(key.SerializeCompressed())
}
builder.AddInt64(int64(len(ecKeys)))
builder.AddOp(txscript.OP_CHECKMULTISIG)
builder.AddOp(txscript.OP_ELSE).
AddInt64(int64(sequenceLock)).
AddOp(txscript.OP_CHECKSEQUENCEVERIFY).
AddOp(txscript.OP_DROP).
AddData(ecKey.SerializeCompressed()).
AddOp(txscript.OP_CHECKSIG).
AddOp(txscript.OP_ENDIF)
}
redeemScript, err = builder.Script()
if err != nil {
return nil, nil, err
}
addr, err = bchutil.NewCashAddressScriptHash(redeemScript, w.params)
if err != nil {
return nil, nil, err
}
return addr, redeemScript, nil
}
func (w *SPVWallet) CreateMultisigSignature(ins []wallet.TransactionInput, outs []wallet.TransactionOutput, key *hd.ExtendedKey, redeemScript []byte, feePerByte uint64) ([]wallet.Signature, error) {
var sigs []wallet.Signature
tx := wire.NewMsgTx(1)
for _, in := range ins {
ch, err := chainhash.NewHashFromStr(hex.EncodeToString(in.OutpointHash))
if err != nil {
return sigs, err
}
outpoint := wire.NewOutPoint(ch, in.OutpointIndex)
input := wire.NewTxIn(outpoint, []byte{}, [][]byte{})
tx.TxIn = append(tx.TxIn, input)
}
for _, out := range outs {
scriptPubkey, err := bchutil.PayToAddrScript(out.Address)
if err != nil {
return sigs, err
}
output := wire.NewTxOut(out.Value, scriptPubkey)
tx.TxOut = append(tx.TxOut, output)
}
// Subtract fee
txType := P2SH_2of3_Multisig
_, err := LockTimeFromRedeemScript(redeemScript)
if err == nil {
txType = P2SH_Multisig_Timelock_2Sigs
}
estimatedSize := EstimateSerializeSize(len(ins), tx.TxOut, false, txType)
fee := estimatedSize * int(feePerByte)
if len(tx.TxOut) > 0 {
feePerOutput := fee / len(tx.TxOut)
for _, output := range tx.TxOut {
output.Value -= int64(feePerOutput)
}
}
// BIP 69 sorting
txsort.InPlaceSort(tx)
signingKey, err := key.ECPrivKey()
if err != nil {
return sigs, err
}
for i := range tx.TxIn {
sig, err := bchutil.RawTxInSignature(tx, i, redeemScript, txscript.SigHashAll, signingKey, ins[i].Value)
if err != nil {
continue
}
bs := wallet.Signature{InputIndex: uint32(i), Signature: sig}
sigs = append(sigs, bs)
}
return sigs, nil
}
func (w *SPVWallet) Multisign(ins []wallet.TransactionInput, outs []wallet.TransactionOutput, sigs1 []wallet.Signature, sigs2 []wallet.Signature, redeemScript []byte, feePerByte uint64, broadcast bool) ([]byte, error) {
tx := wire.NewMsgTx(1)
for _, in := range ins {
ch, err := chainhash.NewHashFromStr(hex.EncodeToString(in.OutpointHash))
if err != nil {
return nil, err
}
outpoint := wire.NewOutPoint(ch, in.OutpointIndex)
input := wire.NewTxIn(outpoint, []byte{}, [][]byte{})
tx.TxIn = append(tx.TxIn, input)
}
for _, out := range outs {
scriptPubkey, err := bchutil.PayToAddrScript(out.Address)
if err != nil {
return nil, err
}
output := wire.NewTxOut(out.Value, scriptPubkey)
tx.TxOut = append(tx.TxOut, output)
}
// Subtract fee
txType := P2SH_2of3_Multisig
_, err := LockTimeFromRedeemScript(redeemScript)
if err == nil {
txType = P2SH_Multisig_Timelock_2Sigs
}
estimatedSize := EstimateSerializeSize(len(ins), tx.TxOut, false, txType)
fee := estimatedSize * int(feePerByte)
if len(tx.TxOut) > 0 {
feePerOutput := fee / len(tx.TxOut)
for _, output := range tx.TxOut {
output.Value -= int64(feePerOutput)
}
}
// BIP 69 sorting
txsort.InPlaceSort(tx)
// Check if time locked
var timeLocked bool
if redeemScript[0] == txscript.OP_IF {
timeLocked = true
}
for i, input := range tx.TxIn {
var sig1 []byte
var sig2 []byte
for _, sig := range sigs1 {
if int(sig.InputIndex) == i {
sig1 = sig.Signature
}
}
for _, sig := range sigs2 {
if int(sig.InputIndex) == i {
sig2 = sig.Signature
}
}
builder := txscript.NewScriptBuilder()
builder.AddOp(txscript.OP_0)
builder.AddData(sig1)
builder.AddData(sig2)
if timeLocked {
builder.AddOp(txscript.OP_1)
}
builder.AddData(redeemScript)
scriptSig, err := builder.Script()
if err != nil {
return nil, err
}
input.SignatureScript = scriptSig
}
// broadcast
if broadcast {
w.Broadcast(tx)
}
var buf bytes.Buffer
tx.BtcEncode(&buf, 1, wire.BaseEncoding)
return buf.Bytes(), nil
}
func (w *SPVWallet) SweepAddress(ins []wallet.TransactionInput, address *btc.Address, key *hd.ExtendedKey, redeemScript *[]byte, feeLevel wallet.FeeLevel) (*chainhash.Hash, error) {
var internalAddr btc.Address
if address != nil {
internalAddr = *address
} else {
internalAddr = w.CurrentAddress(wallet.INTERNAL)
}
script, err := bchutil.PayToAddrScript(internalAddr)
if err != nil {
return nil, err
}
var val int64
var inputs []*wire.TxIn
additionalPrevScripts := make(map[wire.OutPoint][]byte)
for _, in := range ins {
val += in.Value
ch, err := chainhash.NewHashFromStr(hex.EncodeToString(in.OutpointHash))
if err != nil {
return nil, err
}
script, err := bchutil.PayToAddrScript(in.LinkedAddress)
if err != nil {
return nil, err
}
outpoint := wire.NewOutPoint(ch, in.OutpointIndex)
input := wire.NewTxIn(outpoint, []byte{}, [][]byte{})
inputs = append(inputs, input)
additionalPrevScripts[*outpoint] = script
}
out := wire.NewTxOut(val, script)
txType := P2PKH
if redeemScript != nil {
txType = P2SH_1of2_Multisig
_, err := LockTimeFromRedeemScript(*redeemScript)
if err == nil {
txType = P2SH_Multisig_Timelock_1Sig
}
}
estimatedSize := EstimateSerializeSize(len(ins), []*wire.TxOut{out}, false, txType)
// Calculate the fee
feePerByte := int(w.GetFeePerByte(feeLevel))
fee := estimatedSize * feePerByte
outVal := val - int64(fee)
if outVal < 0 {
outVal = 0
}
out.Value = outVal
tx := &wire.MsgTx{
Version: wire.TxVersion,
TxIn: inputs,
TxOut: []*wire.TxOut{out},
LockTime: 0,
}
// BIP 69 sorting
txsort.InPlaceSort(tx)
// Sign tx
privKey, err := key.ECPrivKey()
if err != nil {
return nil, err
}
pk := privKey.PubKey().SerializeCompressed()
addressPub, err := btc.NewAddressPubKey(pk, w.params)
getKey := txscript.KeyClosure(func(addr btc.Address) (*btcec.PrivateKey, bool, error) {
if addressPub.EncodeAddress() == addr.EncodeAddress() {
wif, err := btc.NewWIF(privKey, w.params, true)
if err != nil {
return nil, false, err
}
return wif.PrivKey, wif.CompressPubKey, nil
}
return nil, false, errors.New("Not found")
})
getScript := txscript.ScriptClosure(func(addr btc.Address) ([]byte, error) {
if redeemScript == nil {
return []byte{}, nil
}
return *redeemScript, nil
})
// Check if time locked
var timeLocked bool
if redeemScript != nil {
rs := *redeemScript
if rs[0] == txscript.OP_IF {
timeLocked = true
tx.Version = 2
for _, txIn := range tx.TxIn {
locktime, err := LockTimeFromRedeemScript(*redeemScript)
if err != nil {
return nil, err
}
txIn.Sequence = locktime
}
}
}
for i, txIn := range tx.TxIn {
if !timeLocked {
prevOutScript := additionalPrevScripts[txIn.PreviousOutPoint]
script, err := bchutil.SignTxOutput(w.params,
tx, i, prevOutScript, txscript.SigHashAll, getKey,
getScript, txIn.SignatureScript, ins[i].Value)
if err != nil {
return nil, errors.New("Failed to sign transaction")
}
txIn.SignatureScript = script
} else {
priv, err := key.ECPrivKey()
if err != nil {
return nil, err
}
script, err := bchutil.RawTxInSignature(tx, i, *redeemScript, txscript.SigHashAll, priv, ins[i].Value)
if err != nil {
return nil, err
}
builder := txscript.NewScriptBuilder().
AddData(script).
AddOp(txscript.OP_0).
AddData(*redeemScript)
scriptSig, _ := builder.Script()
txIn.SignatureScript = scriptSig
}
}
// broadcast
w.Broadcast(tx)
txid := tx.TxHash()
return &txid, nil
}
func (w *SPVWallet) buildTx(amount int64, addr btc.Address, feeLevel wallet.FeeLevel, optionalOutput *wire.TxOut) (*wire.MsgTx, error) {
// Check for dust
script, _ := bchutil.PayToAddrScript(addr)
if txrules.IsDustAmount(btc.Amount(amount), len(script), txrules.DefaultRelayFeePerKb) {
return nil, errors.New("Amount is below dust threshold")
}
var additionalPrevScripts map[wire.OutPoint][]byte
var additionalKeysByAddress map[string]*btc.WIF
var inVals map[wire.OutPoint]int64
// Create input source
coinMap := w.gatherCoins()
coins := make([]coinset.Coin, 0, len(coinMap))
for k := range coinMap {
coins = append(coins, k)
}
inputSource := func(target btc.Amount) (total btc.Amount, inputs []*wire.TxIn, amounts []btc.Amount, scripts [][]byte, err error) {
coinSelector := coinset.MaxValueAgeCoinSelector{MaxInputs: 10000, MinChangeAmount: btc.Amount(0)}
coins, err := coinSelector.CoinSelect(target, coins)
if err != nil {
return total, inputs, []btc.Amount{}, scripts, errors.New("insuffient funds")
}
additionalPrevScripts = make(map[wire.OutPoint][]byte)
inVals = make(map[wire.OutPoint]int64)
additionalKeysByAddress = make(map[string]*btc.WIF)
for _, c := range coins.Coins() {
total += c.Value()
outpoint := wire.NewOutPoint(c.Hash(), c.Index())
in := wire.NewTxIn(outpoint, []byte{}, [][]byte{})
inputs = append(inputs, in)
additionalPrevScripts[*outpoint] = c.PkScript()
key := coinMap[c]
addr, err := key.Address(w.params)
if err != nil {
continue
}
privKey, err := key.ECPrivKey()
if err != nil {
continue
}
wif, _ := btc.NewWIF(privKey, w.params, true)
additionalKeysByAddress[addr.EncodeAddress()] = wif
val := c.Value()
sat := val.ToUnit(btc.AmountSatoshi)
inVals[*outpoint] = int64(sat)
}
return total, inputs, []btc.Amount{}, scripts, nil
}
// Get the fee per kilobyte
feePerKB := int64(w.GetFeePerByte(feeLevel)) * 1000
// outputs
out := wire.NewTxOut(amount, script)
// Create change source
changeSource := func() ([]byte, error) {
addr := w.CurrentAddress(wallet.INTERNAL)
script, err := bchutil.PayToAddrScript(addr)
if err != nil {
return []byte{}, err
}
return script, nil
}
outputs := []*wire.TxOut{out}
if optionalOutput != nil {
outputs = append(outputs, optionalOutput)
}
authoredTx, err := NewUnsignedTransaction(outputs, btc.Amount(feePerKB), inputSource, changeSource)
if err != nil {
return nil, err
}
// BIP 69 sorting
txsort.InPlaceSort(authoredTx.Tx)
// Sign tx
getKey := txscript.KeyClosure(func(addr btc.Address) (*btcec.PrivateKey, bool, error) {
addrStr := addr.EncodeAddress()
wif := additionalKeysByAddress[addrStr]
return wif.PrivKey, wif.CompressPubKey, nil
})
getScript := txscript.ScriptClosure(func(
addr btc.Address) ([]byte, error) {
return []byte{}, nil
})
for i, txIn := range authoredTx.Tx.TxIn {
prevOutScript := additionalPrevScripts[txIn.PreviousOutPoint]
script, err := bchutil.SignTxOutput(w.params,
authoredTx.Tx, i, prevOutScript, txscript.SigHashAll, getKey,
getScript, txIn.SignatureScript, inVals[txIn.PreviousOutPoint])
if err != nil {
return nil, errors.New("Failed to sign transaction")
}
txIn.SignatureScript = script
}
return authoredTx.Tx, nil
}
func NewUnsignedTransaction(outputs []*wire.TxOut, feePerKb btc.Amount, fetchInputs txauthor.InputSource, fetchChange txauthor.ChangeSource) (*txauthor.AuthoredTx, error) {
var targetAmount btc.Amount
for _, txOut := range outputs {
targetAmount += btc.Amount(txOut.Value)
}
estimatedSize := EstimateSerializeSize(1, outputs, true, P2PKH)
targetFee := txrules.FeeForSerializeSize(feePerKb, estimatedSize)
for {
inputAmount, inputs, _, scripts, err := fetchInputs(targetAmount + targetFee)
if err != nil {
return nil, err
}
if inputAmount < targetAmount+targetFee {
return nil, errors.New("insufficient funds available to construct transaction")
}
maxSignedSize := EstimateSerializeSize(len(inputs), outputs, true, P2PKH)
maxRequiredFee := txrules.FeeForSerializeSize(feePerKb, maxSignedSize)
remainingAmount := inputAmount - targetAmount
if remainingAmount < maxRequiredFee {
targetFee = maxRequiredFee
continue
}
unsignedTransaction := &wire.MsgTx{
Version: wire.TxVersion,
TxIn: inputs,
TxOut: outputs,
LockTime: 0,
}
changeIndex := -1
changeAmount := inputAmount - targetAmount - maxRequiredFee
if changeAmount != 0 && !txrules.IsDustAmount(changeAmount,
P2PKHOutputSize, txrules.DefaultRelayFeePerKb) {
changeScript, err := fetchChange()
if err != nil {
return nil, err
}
if len(changeScript) > P2PKHPkScriptSize {
return nil, errors.New("fee estimation requires change " +
"scripts no larger than P2PKH output scripts")
}
change := wire.NewTxOut(int64(changeAmount), changeScript)
l := len(outputs)
unsignedTransaction.TxOut = append(outputs[:l:l], change)
changeIndex = l
}
return &txauthor.AuthoredTx{
Tx: unsignedTransaction,
PrevScripts: scripts,
TotalInput: inputAmount,
ChangeIndex: changeIndex,
}, nil
}
}
func (w *SPVWallet) GetFeePerByte(feeLevel wallet.FeeLevel) uint64 {
return w.feeProvider.GetFeePerByte(feeLevel)
}
func LockTimeFromRedeemScript(redeemScript []byte) (uint32, error) {
if len(redeemScript) < 113 {
return 0, errors.New("Redeem script invalid length")
}
if redeemScript[106] != 103 {
return 0, errors.New("Invalid redeem script")
}
if redeemScript[107] == 0 {
return 0, nil
}
if 81 <= redeemScript[107] && redeemScript[107] <= 96 {
return uint32((redeemScript[107] - 81) + 1), nil
}
var v []byte
op := redeemScript[107]
if 1 <= op && op <= 75 {
for i := 0; i < int(op); i++ {
v = append(v, []byte{redeemScript[108+i]}...)
}
} else {
return 0, errors.New("Too many bytes pushed for sequence")
}
var result int64
for i, val := range v {
result |= int64(val) << uint8(8*i)
}
return uint32(result), nil
}