This repository has been archived by the owner on Mar 28, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 285
/
wallet.go
758 lines (686 loc) · 19.9 KB
/
wallet.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
package bitcoind
import (
"bytes"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"github.com/OpenBazaar/spvwallet"
"github.com/btcsuite/btcd/blockchain"
"github.com/btcsuite/btcd/btcec"
"github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcrpcclient"
btc "github.com/btcsuite/btcutil"
hd "github.com/btcsuite/btcutil/hdkeychain"
"github.com/btcsuite/btcutil/txsort"
"github.com/btcsuite/btcwallet/wallet/txrules"
"github.com/op/go-logging"
b39 "github.com/tyler-smith/go-bip39"
"os/exec"
"strconv"
"strings"
"time"
)
var log = logging.MustGetLogger("bitcoind")
const (
Account = "OpenBazaar"
)
type BitcoindWallet struct {
params *chaincfg.Params
repoPath string
trustedPeer string
masterPrivateKey *hd.ExtendedKey
masterPublicKey *hd.ExtendedKey
listeners []func(spvwallet.TransactionCallback)
rpcClient *btcrpcclient.Client
binary string
controlPort int
useTor bool
}
var connCfg *btcrpcclient.ConnConfig = &btcrpcclient.ConnConfig{
Host: "localhost:8332",
HTTPPostMode: true, // Bitcoin core only supports HTTP POST mode
DisableTLS: true, // Bitcoin core does not provide TLS by default
DisableAutoReconnect: false,
DisableConnectOnNew: false,
}
func NewBitcoindWallet(mnemonic string, params *chaincfg.Params, repoPath string, trustedPeer string, binary string, username string, password string, useTor bool, torControlPort int) *BitcoindWallet {
seed := b39.NewSeed(mnemonic, "")
mPrivKey, _ := hd.NewMaster(seed, params)
mPubKey, _ := mPrivKey.Neuter()
if params.Name == chaincfg.TestNet3Params.Name || params.Name == chaincfg.RegressionNetParams.Name {
connCfg.Host = "localhost:18332"
}
connCfg.User = username
connCfg.Pass = password
if trustedPeer != "" {
trustedPeer = strings.Split(trustedPeer, ":")[0]
}
w := BitcoindWallet{
params: params,
repoPath: repoPath,
trustedPeer: trustedPeer,
masterPrivateKey: mPrivKey,
masterPublicKey: mPubKey,
binary: binary,
controlPort: torControlPort,
useTor: useTor,
}
return &w
}
func (w *BitcoindWallet) BuildArguments(rescan bool) []string {
notify := `curl -d %s http://localhost:8330/`
args := []string{"-walletnotify=" + notify, "-server"}
if rescan {
args = append(args, "-rescan")
}
args = append(args, "-torcontrol=127.0.0.1:"+strconv.Itoa(w.controlPort))
if w.params.Name == chaincfg.TestNet3Params.Name {
args = append(args, "-testnet")
} else if w.params.Name == chaincfg.RegressionNetParams.Name {
args = append(args, "-regtest")
}
if w.trustedPeer != "" {
args = append(args, "-connect="+w.trustedPeer)
}
if w.useTor {
socksPort := defaultSocksPort(w.controlPort)
args = append(args, "-listen", "-proxy:127.0.0.1:"+strconv.Itoa(socksPort), "-onlynet=onion")
}
return args
}
func (w *BitcoindWallet) Start() {
w.shutdownIfActive()
args := w.BuildArguments(false)
client, _ := btcrpcclient.New(connCfg, nil)
w.rpcClient = client
go startNotificationListener(client, w.listeners)
cmd := exec.Command(w.binary, args...)
cmd.Start()
ticker := time.NewTicker(time.Second * 30)
go func() {
for range ticker.C {
log.Fatal("Failed to connect to bitcoind")
}
}()
for {
_, err := client.GetBlockCount()
if err == nil {
break
}
time.Sleep(time.Second)
}
ticker.Stop()
log.Info("Connected to bitcoind")
}
// If bitcoind is already running let's shut it down so we restart it with our options
func (w *BitcoindWallet) shutdownIfActive() {
client, err := btcrpcclient.New(connCfg, nil)
if err != nil {
return
}
client.RawRequest("stop", []json.RawMessage{})
client.Shutdown()
time.Sleep(5 * time.Second)
}
func (w *BitcoindWallet) CurrencyCode() string {
if w.params.Name == chaincfg.MainNetParams.Name {
return "btc"
} else {
return "tbtc"
}
}
func (w *BitcoindWallet) IsDust(amount int64) bool {
return txrules.IsDustAmount(btc.Amount(amount), 25, txrules.DefaultRelayFeePerKb)
}
func (w *BitcoindWallet) MasterPrivateKey() *hd.ExtendedKey {
return w.masterPrivateKey
}
func (w *BitcoindWallet) MasterPublicKey() *hd.ExtendedKey {
return w.masterPublicKey
}
func (w *BitcoindWallet) CurrentAddress(purpose spvwallet.KeyPurpose) btc.Address {
addr, _ := w.rpcClient.GetAccountAddress(Account)
return addr
}
func (w *BitcoindWallet) NewAddress(purpose spvwallet.KeyPurpose) btc.Address {
addr, _ := w.rpcClient.GetNewAddress(Account)
return addr
}
func (w *BitcoindWallet) DecodeAddress(addr string) (btc.Address, error) {
return btc.DecodeAddress(addr, w.params)
}
func (w *BitcoindWallet) ScriptToAddress(script []byte) (btc.Address, error) {
_, addrs, _, err := txscript.ExtractPkScriptAddrs(script, w.params)
if err != nil {
return nil, err
}
if len(addrs) == 0 {
return nil, errors.New("unknown script")
}
return addrs[0], nil
}
func (w *BitcoindWallet) AddressToScript(addr btc.Address) ([]byte, error) {
return txscript.PayToAddrScript(addr)
}
func (w *BitcoindWallet) HasKey(addr btc.Address) bool {
_, err := w.rpcClient.DumpPrivKey(addr)
if err != nil {
return false
}
return true
}
func (w *BitcoindWallet) Balance() (confirmed, unconfirmed int64) {
resp, _ := w.rpcClient.RawRequest("getwalletinfo", []json.RawMessage{})
type walletInfo struct {
Balance float64 `json:"balance"`
Unconfirmed float64 `json:"unconfirmed_balance"`
}
respBytes, _ := resp.MarshalJSON()
i := new(walletInfo)
json.Unmarshal(respBytes, i)
c, _ := btc.NewAmount(i.Balance)
u, _ := btc.NewAmount(i.Unconfirmed)
return int64(c.ToUnit(btc.AmountSatoshi)), int64(u.ToUnit(btc.AmountSatoshi))
}
func (w *BitcoindWallet) Transactions() ([]spvwallet.Txn, error) {
var ret []spvwallet.Txn
resp, err := w.rpcClient.ListTransactions(Account)
if err != nil {
return ret, err
}
for _, r := range resp {
amt, err := btc.NewAmount(r.Amount)
if err != nil {
return ret, err
}
ts := time.Unix(r.TimeReceived, 0)
height := int32(0)
if r.BlockIndex != nil {
height = int32(*r.BlockIndex)
}
t := spvwallet.Txn{
Txid: r.TxID,
Value: int64(amt.ToUnit(btc.AmountSatoshi)),
Height: height,
Timestamp: ts,
}
ret = append(ret, t)
}
return ret, nil
}
func (w *BitcoindWallet) GetTransaction(txid chainhash.Hash) (spvwallet.Txn, error) {
includeWatchOnly := false
t := spvwallet.Txn{}
resp, err := w.rpcClient.GetTransaction(&txid, &includeWatchOnly)
if err != nil {
return t, err
}
t.Txid = resp.TxID
t.Value = int64(resp.Amount * 100000000)
t.Height = int32(resp.BlockIndex)
t.Timestamp = time.Unix(resp.TimeReceived, 0)
t.WatchOnly = false
return t, nil
}
func (w *BitcoindWallet) GetConfirmations(txid chainhash.Hash) (uint32, uint32, error) {
includeWatchOnly := true
resp, err := w.rpcClient.GetTransaction(&txid, &includeWatchOnly)
if err != nil {
return 0, 0, err
}
return uint32(resp.Confirmations), uint32(resp.BlockIndex), nil
}
func (w *BitcoindWallet) ChainTip() (uint32, chainhash.Hash) {
var ch chainhash.Hash
info, err := w.rpcClient.GetInfo()
if err != nil {
return uint32(0), ch
}
h, err := w.rpcClient.GetBestBlockHash()
if err != nil {
return uint32(0), ch
}
return uint32(info.Blocks), *h
}
func (w *BitcoindWallet) Spend(amount int64, addr btc.Address, feeLevel spvwallet.FeeLevel) (*chainhash.Hash, error) {
amt, err := btc.NewAmount(float64(amount) / 100000000)
if err != nil {
return nil, err
}
return w.rpcClient.SendFrom(Account, addr, amt)
}
func (w *BitcoindWallet) BumpFee(txid chainhash.Hash) (*chainhash.Hash, error) {
includeWatchOnly := false
tx, err := w.rpcClient.GetTransaction(&txid, &includeWatchOnly)
if err != nil {
return nil, err
}
if tx.Confirmations > 0 {
return nil, spvwallet.BumpFeeAlreadyConfirmedError
}
unspent, err := w.rpcClient.ListUnspent()
if err != nil {
return nil, err
}
for _, u := range unspent {
if u.TxID == txid.String() {
if u.Confirmations > 0 {
return nil, spvwallet.BumpFeeAlreadyConfirmedError
}
h, err := chainhash.NewHashFromStr(u.TxID)
if err != nil {
continue
}
op := wire.NewOutPoint(h, u.Vout)
script, err := hex.DecodeString(u.ScriptPubKey)
if err != nil {
continue
}
utxo := spvwallet.Utxo{
Op: *op,
Value: int64(u.Amount / 100000000),
ScriptPubkey: script,
}
addr, err := btc.DecodeAddress(u.Address, w.params)
if err != nil {
continue
}
key, err := w.rpcClient.DumpPrivKey(addr)
if err != nil {
continue
}
hdKey := hd.NewExtendedKey(w.Params().HDPrivateKeyID[:], key.PrivKey.Serialize(), make([]byte, 32), make([]byte, 4), 0, 0, true)
transactionID, err := w.SweepAddress([]spvwallet.Utxo{utxo}, nil, hdKey, nil, spvwallet.FEE_BUMP)
if err != nil {
return nil, err
}
return transactionID, nil
}
}
return nil, spvwallet.BumpFeeNotFoundError
}
func (w *BitcoindWallet) GetFeePerByte(feeLevel spvwallet.FeeLevel) uint64 {
defautlFee := uint64(50)
var nBlocks json.RawMessage
switch feeLevel {
case spvwallet.PRIOIRTY:
nBlocks = json.RawMessage([]byte(`1`))
case spvwallet.NORMAL:
nBlocks = json.RawMessage([]byte(`3`))
case spvwallet.ECONOMIC:
nBlocks = json.RawMessage([]byte(`6`))
default:
return defautlFee
}
resp, err := w.rpcClient.RawRequest("estimatefee", []json.RawMessage{nBlocks})
if err != nil {
return defautlFee
}
feePerKb, err := strconv.Atoi(string(resp))
if err != nil {
return defautlFee
}
if feePerKb <= 0 {
return defautlFee
}
fee := feePerKb / 1000
return uint64(fee)
}
func (w *BitcoindWallet) EstimateFee(ins []spvwallet.TransactionInput, outs []spvwallet.TransactionOutput, feePerByte uint64) uint64 {
tx := wire.NewMsgTx(wire.TxVersion)
for _, out := range outs {
output := wire.NewTxOut(out.Value, out.ScriptPubKey)
tx.TxOut = append(tx.TxOut, output)
}
estimatedSize := spvwallet.EstimateSerializeSize(len(ins), tx.TxOut, false, spvwallet.P2PKH)
fee := estimatedSize * int(feePerByte)
return uint64(fee)
}
func (w *BitcoindWallet) CreateMultisigSignature(ins []spvwallet.TransactionInput, outs []spvwallet.TransactionOutput, key *hd.ExtendedKey, redeemScript []byte, feePerByte uint64) ([]spvwallet.Signature, error) {
var sigs []spvwallet.Signature
tx := wire.NewMsgTx(wire.TxVersion)
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{})
tx.TxIn = append(tx.TxIn, input)
}
for _, out := range outs {
output := wire.NewTxOut(out.Value, out.ScriptPubKey)
tx.TxOut = append(tx.TxOut, output)
}
// Subtract fee
txType := spvwallet.P2SH_2of3_Multisig
_, err := spvwallet.LockTimeFromRedeemScript(redeemScript)
if err == nil {
txType = spvwallet.P2SH_Multisig_Timelock_2Sigs
}
estimatedSize := spvwallet.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 := txscript.RawTxInSignature(tx, i, redeemScript, txscript.SigHashAll, signingKey)
if err != nil {
continue
}
bs := spvwallet.Signature{InputIndex: uint32(i), Signature: sig}
sigs = append(sigs, bs)
}
return sigs, nil
}
func (w *BitcoindWallet) Multisign(ins []spvwallet.TransactionInput, outs []spvwallet.TransactionOutput, sigs1 []spvwallet.Signature, sigs2 []spvwallet.Signature, redeemScript []byte, feePerByte uint64, broadcast bool) ([]byte, error) {
tx := wire.NewMsgTx(wire.TxVersion)
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{})
tx.TxIn = append(tx.TxIn, input)
}
for _, out := range outs {
output := wire.NewTxOut(out.Value, out.ScriptPubKey)
tx.TxOut = append(tx.TxOut, output)
}
// Subtract fee
txType := spvwallet.P2SH_2of3_Multisig
_, err := spvwallet.LockTimeFromRedeemScript(redeemScript)
if err == nil {
txType = spvwallet.P2SH_Multisig_Timelock_2Sigs
}
estimatedSize := spvwallet.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)
tx.Version = 2
locktime, err := spvwallet.LockTimeFromRedeemScript(redeemScript)
if err != nil {
return nil, err
}
input.Sequence = locktime
}
builder.AddData(redeemScript)
scriptSig, err := builder.Script()
if err != nil {
return nil, err
}
input.SignatureScript = scriptSig
}
// Broadcast
if broadcast {
_, err := w.rpcClient.SendRawTransaction(tx, false)
if err != nil {
return nil, err
}
}
var buf bytes.Buffer
tx.BtcEncode(&buf, 1)
return buf.Bytes(), nil
}
func (w *BitcoindWallet) SweepAddress(utxos []spvwallet.Utxo, address *btc.Address, key *hd.ExtendedKey, redeemScript *[]byte, feeLevel spvwallet.FeeLevel) (*chainhash.Hash, error) {
var internalAddr btc.Address
if address != nil {
internalAddr = *address
} else {
internalAddr = w.CurrentAddress(spvwallet.INTERNAL)
}
script, err := txscript.PayToAddrScript(internalAddr)
if err != nil {
return nil, err
}
var val int64
var inputs []*wire.TxIn
additionalPrevScripts := make(map[wire.OutPoint][]byte)
for _, u := range utxos {
val += u.Value
in := wire.NewTxIn(&u.Op, []byte{})
inputs = append(inputs, in)
additionalPrevScripts[u.Op] = u.ScriptPubkey
}
out := wire.NewTxOut(val, script)
txType := spvwallet.P2PKH
if redeemScript != nil {
txType = spvwallet.P2SH_1of2_Multisig
_, err := spvwallet.LockTimeFromRedeemScript(*redeemScript)
if err == nil {
txType = spvwallet.P2SH_Multisig_Timelock_1Sig
}
}
estimatedSize := spvwallet.EstimateSerializeSize(len(utxos), []*wire.TxOut{out}, false, txType)
// Calculate the fee
b := json.RawMessage([]byte(`1`))
resp, err := w.rpcClient.RawRequest("estimatefee", []json.RawMessage{b})
if err != nil {
return nil, err
}
feePerKb, err := strconv.Atoi(string(resp))
if err != nil {
return nil, err
}
if feePerKb <= 0 {
feePerKb = 50000
}
fee := estimatedSize * (feePerKb / 1000)
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
getKey := txscript.KeyClosure(func(addr btc.Address) (*btcec.PrivateKey, bool, error) {
privKey, err := key.ECPrivKey()
if err != nil {
return nil, false, err
}
wif, err := btc.NewWIF(privKey, w.params, true)
if err != nil {
return nil, false, err
}
return wif.PrivKey, wif.CompressPubKey, nil
})
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
rs := *redeemScript
if redeemScript != nil && rs[0] == txscript.OP_IF {
timeLocked = true
}
for i, txIn := range tx.TxIn {
if !timeLocked {
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 {
priv, err := key.ECPrivKey()
if err != nil {
return nil, err
}
script, err := txscript.RawTxInSignature(tx, i, *redeemScript, txscript.SigHashAll, priv)
if err != nil {
return nil, err
}
builder := txscript.NewScriptBuilder().
AddData(script).
AddOp(txscript.OP_0).
AddData(*redeemScript)
scriptSig, _ := builder.Script()
txIn.SignatureScript = scriptSig
tx.Version = 2
locktime, err := spvwallet.LockTimeFromRedeemScript(*redeemScript)
if err != nil {
return nil, err
}
txIn.Sequence = locktime
}
}
// Broadcast
_, err = w.rpcClient.SendRawTransaction(tx, false)
if err != nil {
return nil, err
}
txid := tx.TxHash()
return &txid, nil
}
func (w *BitcoindWallet) Params() *chaincfg.Params {
return w.params
}
func (w *BitcoindWallet) AddTransactionListener(callback func(spvwallet.TransactionCallback)) {
w.listeners = append(w.listeners, callback)
}
func (w *BitcoindWallet) 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 = btc.NewAddressScriptHash(redeemScript, w.params)
if err != nil {
return nil, nil, err
}
return addr, redeemScript, nil
}
func (w *BitcoindWallet) AddWatchedScript(script []byte) error {
_, addrs, _, err := txscript.ExtractPkScriptAddrs(script, w.params)
if err != nil {
return err
}
return w.rpcClient.ImportAddress(addrs[0].EncodeAddress())
}
func (w *BitcoindWallet) ReSyncBlockchain(fromHeight int32) {
w.rpcClient.RawRequest("stop", []json.RawMessage{})
w.rpcClient.Shutdown()
time.Sleep(5 * time.Second)
args := w.BuildArguments(true)
cmd := exec.Command(w.binary, args...)
cmd.Start()
client, err := btcrpcclient.New(connCfg, nil)
if err != nil {
log.Error("Could not connect to bitcoind during rescan")
}
w.rpcClient = client
}
func (w *BitcoindWallet) Close() {
if w.rpcClient != nil {
w.rpcClient.RawRequest("stop", []json.RawMessage{})
w.rpcClient.Shutdown()
}
}
func defaultSocksPort(controlPort int) int {
socksPort := 9050
if controlPort == 9151 || controlPort == 9051 {
controlPort--
socksPort = controlPort
}
return socksPort
}