-
Notifications
You must be signed in to change notification settings - Fork 0
/
sign.go
675 lines (611 loc) · 18.9 KB
/
sign.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
package litecoin
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"time"
"github.com/btcsuite/btcd/chaincfg"
"github.com/OpenBazaar/spvwallet"
wi "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/ltcsuite/ltcutil"
"github.com/ltcsuite/ltcwallet/wallet/txrules"
laddr "github.com/OpenBazaar/multiwallet/litecoin/address"
"github.com/OpenBazaar/multiwallet/util"
)
func (w *LitecoinWallet) buildTx(amount int64, addr btc.Address, feeLevel wi.FeeLevel, optionalOutput *wire.TxOut) (*wire.MsgTx, error) {
// Check for dust
script, _ := laddr.PayToAddrScript(addr)
if txrules.IsDustAmount(ltcutil.Amount(amount), len(script), txrules.DefaultRelayFeePerKb) {
return nil, wi.ErrorDustAmount
}
var additionalPrevScripts map[wire.OutPoint][]byte
var additionalKeysByAddress map[string]*btc.WIF
// Create input source
height, _ := w.ws.ChainTip()
utxos, err := w.db.Utxos().GetAll()
if err != nil {
return nil, err
}
coinMap := util.GatherCoins(height, utxos, w.ScriptToAddress, w.km.GetKeyForScript)
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, inputValues []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, inputValues, scripts, wi.ErrorInsuffientFunds
}
additionalPrevScripts = make(map[wire.OutPoint][]byte)
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{})
in.Sequence = 0 // Opt-in RBF so we can bump fees
inputs = append(inputs, in)
additionalPrevScripts[*outpoint] = c.PkScript()
key := coinMap[c]
addr, err := w.km.KeyToAddress(key)
if err != nil {
continue
}
privKey, err := key.ECPrivKey()
if err != nil {
continue
}
wif, _ := btc.NewWIF(privKey, w.params, true)
additionalKeysByAddress[addr.EncodeAddress()] = wif
}
return total, inputs, inputValues, 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(wi.INTERNAL)
script, err := laddr.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) {
a, err := laddr.NewAddressPubKeyHash(addr.ScriptAddress(), w.params)
if err != nil {
return nil, false, err
}
wif := additionalKeysByAddress[a.EncodeAddress()]
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 := txscript.SignTxOutput(w.params,
authoredTx.Tx, i, prevOutScript, txscript.SigHashAll, getKey,
getScript, txIn.SignatureScript)
if err != nil {
return nil, errors.New("Failed to sign transaction")
}
txIn.SignatureScript = script
}
return authoredTx.Tx, nil
}
func (w *LitecoinWallet) buildSpendAllTx(addr btc.Address, feeLevel wi.FeeLevel) (*wire.MsgTx, error) {
tx := wire.NewMsgTx(1)
height, _ := w.ws.ChainTip()
utxos, err := w.db.Utxos().GetAll()
if err != nil {
return nil, err
}
coinMap := util.GatherCoins(height, utxos, w.ScriptToAddress, w.km.GetKeyForScript)
totalIn, _, additionalPrevScripts, additionalKeysByAddress := util.LoadAllInputs(tx, coinMap, w.params)
// outputs
script, err := laddr.PayToAddrScript(addr)
if err != nil {
return nil, err
}
// Get the fee
feePerByte := int64(w.GetFeePerByte(feeLevel))
estimatedSize := EstimateSerializeSize(1, []*wire.TxOut{wire.NewTxOut(0, script)}, false, P2PKH)
fee := int64(estimatedSize) * feePerByte
// Check for dust output
if txrules.IsDustAmount(ltcutil.Amount(totalIn-fee), len(script), txrules.DefaultRelayFeePerKb) {
return nil, wi.ErrorDustAmount
}
// Build the output
out := wire.NewTxOut(totalIn-fee, script)
tx.TxOut = append(tx.TxOut, out)
// BIP 69 sorting
txsort.InPlaceSort(tx)
// Sign
getKey := txscript.KeyClosure(func(addr btc.Address) (*btcec.PrivateKey, bool, error) {
addrStr := addr.EncodeAddress()
wif, ok := additionalKeysByAddress[addrStr]
if !ok {
return nil, false, errors.New("key not found")
}
return wif.PrivKey, wif.CompressPubKey, nil
})
getScript := txscript.ScriptClosure(func(
addr btc.Address) ([]byte, error) {
return []byte{}, nil
})
for i, txIn := range tx.TxIn {
prevOutScript := additionalPrevScripts[txIn.PreviousOutPoint]
script, err := txscript.SignTxOutput(w.params,
tx, i, prevOutScript, txscript.SigHashAll, getKey,
getScript, txIn.SignatureScript)
if err != nil {
return nil, errors.New("failed to sign transaction")
}
txIn.SignatureScript = script
}
return 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(ltcutil.Amount(feePerKb), estimatedSize)
for {
inputAmount, inputs, _, scripts, err := fetchInputs(targetAmount + btc.Amount(targetFee))
if err != nil {
return nil, err
}
if inputAmount < targetAmount+btc.Amount(targetFee) {
return nil, errors.New("insufficient funds available to construct transaction")
}
maxSignedSize := EstimateSerializeSize(len(inputs), outputs, true, P2PKH)
maxRequiredFee := txrules.FeeForSerializeSize(ltcutil.Amount(feePerKb), maxSignedSize)
remainingAmount := inputAmount - targetAmount
if remainingAmount < btc.Amount(maxRequiredFee) {
targetFee = maxRequiredFee
continue
}
unsignedTransaction := &wire.MsgTx{
Version: wire.TxVersion,
TxIn: inputs,
TxOut: outputs,
LockTime: 0,
}
changeIndex := -1
changeAmount := inputAmount - targetAmount - btc.Amount(maxRequiredFee)
if changeAmount != 0 && !txrules.IsDustAmount(ltcutil.Amount(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 *LitecoinWallet) bumpFee(txid chainhash.Hash) (*chainhash.Hash, error) {
txn, err := w.db.Txns().Get(txid)
if err != nil {
return nil, err
}
if txn.Height > 0 {
return nil, spvwallet.BumpFeeAlreadyConfirmedError
}
if txn.Height < 0 {
return nil, spvwallet.BumpFeeTransactionDeadError
}
// Check utxos for CPFP
utxos, _ := w.db.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.km.GetKeyForScript(addr.ScriptAddress())
if err != nil {
return nil, err
}
h, err := hex.DecodeString(u.Op.Hash.String())
if err != nil {
return nil, err
}
in := wi.TransactionInput{
LinkedAddress: addr,
OutpointIndex: u.Op.Index,
OutpointHash: h,
Value: int64(u.Value),
}
transactionID, err := w.sweepAddress([]wi.TransactionInput{in}, nil, key, nil, wi.FEE_BUMP)
if err != nil {
return nil, err
}
return transactionID, nil
}
}
return nil, spvwallet.BumpFeeNotFoundError
}
func (w *LitecoinWallet) sweepAddress(ins []wi.TransactionInput, address *btc.Address, key *hd.ExtendedKey, redeemScript *[]byte, feeLevel wi.FeeLevel) (*chainhash.Hash, error) {
var internalAddr btc.Address
if address != nil {
internalAddr = *address
} else {
internalAddr = w.CurrentAddress(wi.INTERNAL)
}
script, err := laddr.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 := laddr.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 := spvwallet.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, fmt.Errorf("retrieving private key: %s", err.Error())
}
pk := privKey.PubKey().SerializeCompressed()
addressPub, err := btc.NewAddressPubKey(pk, w.params)
if err != nil {
return nil, fmt.Errorf("generating address pub key: %s", err.Error())
}
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 := spvwallet.LockTimeFromRedeemScript(*redeemScript)
if err != nil {
return nil, err
}
txIn.Sequence = locktime
}
}
}
hashes := txscript.NewTxSigHashes(tx)
for i, txIn := range tx.TxIn {
if redeemScript == nil {
prevOutScript := additionalPrevScripts[txIn.PreviousOutPoint]
script, err := txscript.SignTxOutput(w.params,
tx, i, prevOutScript, txscript.SigHashAll, getKey,
getScript, txIn.SignatureScript)
if err != nil {
return nil, errors.New("Failed to sign transaction")
}
txIn.SignatureScript = script
} else {
sig, err := txscript.RawTxInWitnessSignature(tx, hashes, i, ins[i].Value, *redeemScript, txscript.SigHashAll, privKey)
if err != nil {
return nil, err
}
var witness wire.TxWitness
if timeLocked {
witness = wire.TxWitness{sig, []byte{}}
} else {
witness = wire.TxWitness{[]byte{}, sig}
}
witness = append(witness, *redeemScript)
txIn.Witness = witness
}
}
// broadcast
if err := w.Broadcast(tx); err != nil {
return nil, err
}
txid := tx.TxHash()
return &txid, nil
}
func (w *LitecoinWallet) createMultisigSignature(ins []wi.TransactionInput, outs []wi.TransactionOutput, key *hd.ExtendedKey, redeemScript []byte, feePerByte uint64) ([]wi.Signature, error) {
var sigs []wi.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 := laddr.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 := spvwallet.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
}
hashes := txscript.NewTxSigHashes(tx)
for i := range tx.TxIn {
sig, err := txscript.RawTxInWitnessSignature(tx, hashes, i, ins[i].Value, redeemScript, txscript.SigHashAll, signingKey)
if err != nil {
continue
}
bs := wi.Signature{InputIndex: uint32(i), Signature: sig}
sigs = append(sigs, bs)
}
return sigs, nil
}
func (w *LitecoinWallet) multisign(ins []wi.TransactionInput, outs []wi.TransactionOutput, sigs1 []wi.Signature, sigs2 []wi.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 := laddr.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 := spvwallet.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
break
}
}
for _, sig := range sigs2 {
if int(sig.InputIndex) == i {
sig2 = sig.Signature
break
}
}
witness := wire.TxWitness{[]byte{}, sig1, sig2}
if timeLocked {
witness = append(witness, []byte{0x01})
}
witness = append(witness, redeemScript)
input.Witness = witness
}
// broadcast
if broadcast {
if err := w.Broadcast(tx); err != nil {
return nil, err
}
}
var buf bytes.Buffer
tx.BtcEncode(&buf, wire.ProtocolVersion, wire.WitnessEncoding)
return buf.Bytes(), nil
}
func (w *LitecoinWallet) 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
}
witnessProgram := sha256.Sum256(redeemScript)
addr, err = laddr.NewAddressWitnessScriptHash(witnessProgram[:], w.params)
if err != nil {
return nil, nil, err
}
return addr, redeemScript, nil
}
func (w *LitecoinWallet) estimateSpendFee(amount int64, feeLevel wi.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 := laddr.DecodeAddress("ltc1q65n2p3r4pwz4qppflml65en4xpdp6srjwultrun6hnddpzct5unsyyq4sf", &chaincfg.MainNetParams)
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.db.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
}