-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
367 lines (327 loc) · 10.7 KB
/
client.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
package libbtc
import (
"context"
"encoding/hex"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
"time"
"github.com/btcsuite/btcd/chaincfg"
)
type PreviousOut struct {
TransactionHash string `json:"hash"`
Value uint64 `json:"value"`
TransactionIndex uint64 `json:"tx_index"`
VoutNumber uint8 `json:"n"`
Address string `json:"addr"`
}
type Input struct {
PrevOut PreviousOut `json:"prev_out"`
Script string `json:"script"`
}
type Output struct {
Value uint64 `json:"value"`
TransactionHash string `json:"hash"`
Script string `json:"script"`
}
type Transaction struct {
TransactionHash string `json:"hash"`
Version uint8 `json:"ver"`
VinSize uint32 `json:"vin_sz"`
VoutSize uint32 `json:"vout_sz"`
Size int64 `json:"size"`
RelayedBy string `json:"relayed_by"`
BlockHeight int64 `json:"block_height"`
TransactionIndex uint64 `json:"tx_index"`
Inputs []Input `json:"inputs"`
Outputs []Output `json:"out"`
}
type Block struct {
BlockHash string `json:"hash"`
Version uint8 `json:"ver"`
PreviousBlockHash string `json:"prev_block"`
MerkleRoot string `json:"mrkl_root"`
Time int64 `json:"time"`
Bits int64 `json:"bits"`
Nonce int64 `json:"nonce"`
TransactionCount int `json:"n_tx"`
Size int64 `json:"size"`
BlockIndex uint64 `json:"block_index"`
MainChain bool `json:"main_chain"`
Height int64 `json:"height"`
ReceivedTime int64 `json:"received_time"`
RelayedBy string `json:"relayed_by"`
Transactions []Transaction `json:"tx"`
}
type Blocks struct {
Blocks []Block `json:"block"`
}
type SingleAddress struct {
PublicKeyHash string `json:"hash160"`
Address string `json:"address"`
TransactionCount int64 `json:"n_tx"`
UnredeemedTransactionCount int64 `json:"n_unredeemed"`
Received int64 `json:"total_received"`
Sent int64 `json:"total_sent"`
Balance int64 `json:"final_balance"`
Transactions []Transaction `json:"txs"`
}
type Address struct {
PublicKeyHash string `json:"hash160"`
Address string `json:"address"`
TransactionCount int64 `json:"n_tx"`
Received int64 `json:"total_received"`
Sent int64 `json:"total_sent"`
Balance int64 `json:"final_balance"`
}
type MultiAddress struct {
Addresses []Address `json:"addresses"`
Transactions []Transaction `json:"txs"`
}
type UnspentOutput struct {
TransactionAge string `json:"tx_age"`
TransactionHash string `json:"tx_hash"`
TransactionIndex uint32 `json:"tx_index"`
TransactionOutputNumber uint32 `json:"tx_output_n"`
ScriptPubKey string `json:"script"`
Amount int64 `json:"value"`
}
type Unspent struct {
Outputs []UnspentOutput `json:"unspent_outputs"`
}
type LatestBlock struct {
Hash string `json:"hash"`
Time int64 `json:"time"`
BlockIndex int64 `json:"block_index"`
Height int64 `json:"height"`
}
type client struct {
URL string
Params *chaincfg.Params
}
type Client interface {
// NetworkParams should return the network parameters of the underlying
// Bitcoin blockchain.
NetworkParams() *chaincfg.Params
GetUnspentOutputs(ctx context.Context, address string, limit, confitmations int64) (Unspent, error)
GetRawTransaction(ctx context.Context, txhash string) (Transaction, error)
GetRawAddressInformation(ctx context.Context, addr string) (SingleAddress, error)
// PublishTransaction should publish a signed transaction to the Bitcoin
// blockchain.
PublishTransaction(ctx context.Context, signedTransaction []byte) error
// Balance of the given address on Bitcoin blockchain.
Balance(ctx context.Context, address string, confirmations int64) (int64, error)
// ScriptSpent checks whether a script is spent.
ScriptSpent(ctx context.Context, address string) (bool, error)
// ScriptFunded checks whether a script is funded.
ScriptFunded(ctx context.Context, address string, value int64) (bool, int64, error)
ScriptRedeemed(ctx context.Context, address string, value int64) (bool, int64, error)
GetScriptFromSpentP2SH(ctx context.Context, address string) ([]byte, error)
Confirmations(ctx context.Context, txHash string) (int64, error)
// FormatTransactionView formats the message and txhash into a user friendly
// message.
FormatTransactionView(msg, txhash string) string
}
func NewBlockchainInfoClient(network string) Client {
network = strings.ToLower(network)
switch network {
case "mainnet":
return &client{
URL: "https://blockchain.info",
Params: &chaincfg.MainNetParams,
}
case "testnet", "testnet3", "":
return &client{
URL: "https://testnet.blockchain.info",
Params: &chaincfg.TestNet3Params,
}
default:
panic(NewErrUnsupportedNetwork(network))
}
}
func (client *client) GetUnspentOutputs(ctx context.Context, address string, limit, confitmations int64) (Unspent, error) {
if limit == 0 {
limit = 250
}
utxos := Unspent{}
err := backoff(ctx, func() error {
resp, err := http.Get(fmt.Sprintf("%s/unspent?active=%s&confirmations=%d&limit=%d", client.URL, address, confitmations, limit))
if err != nil {
return err
}
defer resp.Body.Close()
respBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
if string(respBytes) == "No free outputs to spend" {
return nil
}
return json.Unmarshal(respBytes, &utxos)
})
return utxos, err
}
func (client *client) GetRawTransaction(ctx context.Context, txhash string) (Transaction, error) {
transaction := Transaction{}
err := backoff(ctx, func() error {
resp, err := http.Get(fmt.Sprintf("%s/rawtx/%s", client.URL, txhash))
if err != nil {
return err
}
defer resp.Body.Close()
txBytes, err := ioutil.ReadAll(resp.Body)
return json.Unmarshal(txBytes, &transaction)
})
return transaction, err
}
func (client *client) Confirmations(ctx context.Context, txhash string) (int64, error) {
tx, err := client.GetRawTransaction(ctx, txhash)
if err != nil {
return 0, err
}
if tx.BlockHeight != 0 {
latest, err := client.LatestBlock(ctx)
if err != nil {
return 0, err
}
return 1 + (latest.Height - tx.BlockHeight), nil
}
return 0, nil
}
func (client *client) GetRawAddressInformation(ctx context.Context, addr string) (SingleAddress, error) {
addressInfo := SingleAddress{}
err := backoff(ctx, func() error {
resp, err := http.Get(fmt.Sprintf("%s/rawaddr/%s", client.URL, addr))
if err != nil {
return err
}
defer resp.Body.Close()
addrBytes, err := ioutil.ReadAll(resp.Body)
return json.Unmarshal(addrBytes, &addressInfo)
})
return addressInfo, err
}
func (client *client) LatestBlock(ctx context.Context) (LatestBlock, error) {
latestBlock := LatestBlock{}
err := backoff(ctx, func() error {
resp, err := http.Get(fmt.Sprintf("%s/latestblock", client.URL))
if err != nil {
return err
}
defer resp.Body.Close()
latestBlockBytes, err := ioutil.ReadAll(resp.Body)
return json.Unmarshal(latestBlockBytes, &latestBlock)
})
return latestBlock, err
}
func (client *client) PublishTransaction(ctx context.Context, signedTransaction []byte) error {
data := url.Values{}
data.Set("tx", hex.EncodeToString(signedTransaction))
err := backoff(ctx, func() error {
httpClient := &http.Client{}
r, err := http.NewRequest("POST", fmt.Sprintf("%s/pushtx", client.URL), strings.NewReader(data.Encode())) // URL-encoded payload
if err != nil {
return err
}
r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
resp, err := httpClient.Do(r)
if err != nil {
return err
}
defer resp.Body.Close()
stxResultBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
stxResult := string(stxResultBytes)
if !strings.Contains(stxResult, "Transaction Submitted") {
return NewErrBitcoinSubmitTx(stxResult)
}
return nil
})
return err
}
func (client *client) GetScriptFromSpentP2SH(ctx context.Context, address string) ([]byte, error) {
for {
addrInfo, err := client.GetRawAddressInformation(ctx, address)
if err != nil {
return nil, err
}
if addrInfo.Sent > 0 {
break
}
}
addrInfo, err := client.GetRawAddressInformation(ctx, address)
if err != nil {
return nil, err
}
for _, tx := range addrInfo.Transactions {
for i := range tx.Inputs {
if tx.Inputs[i].PrevOut.Address == addrInfo.Address {
return hex.DecodeString(tx.Inputs[i].Script)
}
}
}
return nil, ErrNoSpendingTransactions
}
func (client *client) Balance(ctx context.Context, address string, confirmations int64) (balance int64, err error) {
unspent, err := client.GetUnspentOutputs(ctx, address, 1000, confirmations)
for _, utxo := range unspent.Outputs {
balance = balance + utxo.Amount
}
return
}
func (client *client) ScriptSpent(ctx context.Context, address string) (bool, error) {
rawAddress, err := client.GetRawAddressInformation(ctx, address)
if err != nil {
return false, err
}
return rawAddress.Sent > 0, nil
}
func (client *client) ScriptFunded(ctx context.Context, address string, value int64) (bool, int64, error) {
rawAddress, err := client.GetRawAddressInformation(ctx, address)
if err != nil {
return false, 0, err
}
return rawAddress.Received >= value, rawAddress.Received, nil
}
func (client *client) ScriptRedeemed(ctx context.Context, address string, value int64) (bool, int64, error) {
rawAddress, err := client.GetRawAddressInformation(ctx, address)
if err != nil {
return false, 0, err
}
return rawAddress.Received >= value && rawAddress.Balance == 0, rawAddress.Balance, nil
}
func (client *client) NetworkParams() *chaincfg.Params {
return client.Params
}
func (client *client) FormatTransactionView(msg, txhash string) string {
switch client.NetworkParams().Name {
case "mainnet":
return fmt.Sprintf("%s, transaction can be viewed at https://live.blockcypher.com/btc/tx/%s", msg, txhash)
case "testnet3":
return fmt.Sprintf("%s, transaction can be viewed at https://live.blockcypher.com/btc-testnet/tx/%s", msg, txhash)
default:
panic(NewErrUnsupportedNetwork(client.NetworkParams().Name))
}
}
func backoff(ctx context.Context, f func() error) error {
duration := time.Duration(1000)
for {
select {
case <-ctx.Done():
return ErrTimedOut
default:
err := f()
if err == nil {
return nil
}
fmt.Printf("Error: %v, will try again in %d sec\n", err, duration)
time.Sleep(duration * time.Millisecond)
duration = time.Duration(float64(duration) * 1.6)
}
}
}