forked from OpenBazaar/openbazaar-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
spend.go
226 lines (203 loc) · 6.25 KB
/
spend.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
package libbitcoin
import (
"net/http"
"encoding/json"
"errors"
"bytes"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcutil/coinset"
"github.com/OpenBazaar/openbazaar-go/bitcoin"
"github.com/tyler-smith/go-bip32"
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcwallet/wallet/txrules"
"github.com/btcsuite/btcwallet/wallet/txauthor"
"github.com/btcsuite/btcutil/txsort"
btc "github.com/btcsuite/btcutil"
"github.com/btcsuite/btcd/btcec"
"encoding/hex"
)
type Coin struct {
TxHash *wire.ShaHash
TxIndex uint32
TxValue btc.Amount
TxNumConfs int64
ScriptPubKey []byte
}
func (c *Coin) Hash() *wire.ShaHash { 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, _ := wire.NewShaHash(txid)
c := &Coin{
TxHash: shaTxid,
TxIndex: index,
TxValue: value,
TxNumConfs: numConfs,
ScriptPubKey: scriptPubKey,
}
return coinset.Coin(c)
}
func (w *LibbitcoinWallet) gatherCoins() map[coinset.Coin]*bip32.Key {
utxos := w.db.Coins().GetAll()
m := make(map[coinset.Coin]*bip32.Key)
for _, u := range(utxos) {
sha, _ := wire.NewShaHashFromStr(hex.EncodeToString(u.Txid))
c := NewCoin(sha.Bytes(), uint32(u.Index), btc.Amount(int64(u.Value)), 0, u.ScriptPubKey)
key, err := w.db.Keys().GetKeyForScript(u.ScriptPubKey)
if err != nil {
continue
}
m[c] = key
}
return m
}
func (w *LibbitcoinWallet) Spend(amount int64, addr btc.Address, feeLevel bitcoin.FeeLevel) error {
// Check for dust
script, _ := txscript.PayToAddrScript(addr)
if txrules.IsDustAmount(btc.Amount(amount), len(script), txrules.DefaultRelayFeePerKb) {
return errors.New("Amount is below dust threshold")
}
var additionalPrevScripts map[wire.OutPoint][]byte
var additionalKeysByAddress map[string]*btc.WIF
// 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, scripts [][]byte, err error) {
// TODO: maybe change the coin selection algorithm? We're using min coins right now because
// TODO: we don't know the number of confirmations on each coin without querying the libbitcoin server.
coinSelector := coinset.MinNumberCoinSelector{MaxInputs: 10000, MinChangeAmount: btc.Amount(10000)}
coins, err := coinSelector.CoinSelect(target, coins)
if err != nil {
return total, inputs, scripts, errors.New("insuffient funds")
}
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{})
in.Sequence = 0 // Opt-in RBF so we can bump fees
inputs = append(inputs, in)
additionalPrevScripts[*outpoint] = c.PkScript()
key := coinMap[c]
addr, _ := btc.NewAddressPubKey(key.PublicKey().Key, w.params)
pk, _ := btcec.PrivKeyFromBytes(btcec.S256(), key.Key)
wif, _ := btc.NewWIF(pk, w.params, true)
additionalKeysByAddress[addr.AddressPubKeyHash().EncodeAddress()] = wif
}
return total, inputs, 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.GetCurrentAddress(bitcoin.CHANGE)
script, err := txscript.PayToAddrScript(addr)
if err != nil {
return []byte{}, err
}
return script, nil
}
authoredTx, err := txauthor.NewUnsignedTransaction([]*wire.TxOut{out,}, btc.Amount(feePerKB), inputSource, changeSource)
if err != nil {
return 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 := txscript.SignTxOutput(w.params,
authoredTx.Tx, i, prevOutScript, txscript.SigHashAll, getKey,
getScript, txIn.SignatureScript)
if err != nil {
return errors.New("Failed to sign transaction")
}
txIn.SignatureScript = script
}
// Broadcast tx to bitcoin network
serializedTx := new(bytes.Buffer)
authoredTx.Tx.Serialize(serializedTx)
w.Client.Broadcast(serializedTx.Bytes(), func(i interface{}, err error){
if err == nil {
log.Infof("Broadcast tx %s to bitcoin network\n", authoredTx.Tx.TxSha().String())
} else {
log.Errorf("Failed to broadcast tx, reason: %s\n", err)
}
})
// Update the db
w.ProcessTransaction(btc.NewTx(authoredTx.Tx), 0)
return nil
}
func (w *LibbitcoinWallet) getFeePerByte(feeLevel bitcoin.FeeLevel) uint64 {
defaultFee := func() uint64 {
switch feeLevel {
case bitcoin.PRIOIRTY:
return w.priorityFee
case bitcoin.NORMAL:
return w.normalFee
case bitcoin.ECONOMIC:
return w.economicFee
default:
return w.normalFee
}
}
if w.feeAPI == "" {
return defaultFee()
}
resp, err := http.Get(w.feeAPI)
if err != nil {
return defaultFee()
}
defer resp.Body.Close()
type Fees struct {
FastestFee uint64
HalfHourFee uint64
HourFee uint64
}
fees := new(Fees)
err = json.NewDecoder(resp.Body).Decode(&fees)
if err != nil {
return defaultFee()
}
switch feeLevel {
case bitcoin.PRIOIRTY:
if fees.FastestFee > w.maxFee {
return w.maxFee
} else {
return fees.FastestFee
}
case bitcoin.NORMAL:
if fees.HalfHourFee > w.maxFee {
return w.maxFee
} else {
return fees.HalfHourFee
}
case bitcoin.ECONOMIC:
if fees.HourFee > w.maxFee {
return w.maxFee
} else {
return fees.HourFee
}
default:
return w.normalFee
}
}