-
Notifications
You must be signed in to change notification settings - Fork 107
Expand file tree
/
Copy pathblockstream.go
More file actions
247 lines (213 loc) · 6.74 KB
/
Copy pathblockstream.go
File metadata and controls
247 lines (213 loc) · 6.74 KB
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
// Copyright (c) 2025-2026 Hemi Labs, Inc.
// Use of this source code is governed by the MIT License,
// which can be found in the LICENSE file.
// Package blockstream implements [gozer.Gozer] and retrieves Bitcoin data from
// Blockstream (https://blockstream.info/).
package blockstream
import (
"bytes"
"context"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"slices"
"strings"
"time"
"github.com/btcsuite/btcd/btcutil"
"github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/wire"
"github.com/hemilabs/heminetwork/v2/api"
"github.com/hemilabs/heminetwork/v2/api/protocol"
"github.com/hemilabs/heminetwork/v2/api/tbcapi"
"github.com/hemilabs/heminetwork/v2/bitcoin/wallet/gozer"
"github.com/hemilabs/heminetwork/v2/cmd/btctool/httpclient"
)
var (
bsMainnetURL = "https://blockstream.info/api"
bsTestne3tURL = "https://blockstream.info/testnet/api"
)
// blockstreamGozer implements [gozer.Gozer] and retrieves Bitcoin data from
// Blockstream.
type blockstreamGozer struct {
url string
}
var _ gozer.Gozer = (*blockstreamGozer)(nil)
func (bs *blockstreamGozer) Connected() bool {
return true // XXX should we try to connect first?
}
func (bs *blockstreamGozer) BestHeightHashTime(ctx context.Context) (uint64, *chainhash.Hash, time.Time, error) {
var timestamp time.Time
u := fmt.Sprintf("%v/blocks/tip/hash", bs.url)
rawHash, err := httpclient.Request(ctx, "GET", u, nil)
if err != nil {
return 0, nil, timestamp, fmt.Errorf("request: %w", err)
}
hash, err := chainhash.NewHashFromStr(string(rawHash))
if err != nil {
return 0, nil, timestamp, err
}
u = fmt.Sprintf("%v/block/%v", bs.url, hash)
blockInfo, err := httpclient.Request(ctx, "GET", u, nil)
if err != nil {
return 0, nil, timestamp, fmt.Errorf("request: %w", err)
}
var bi map[string]any
err = json.Unmarshal(blockInfo, &bi)
if err != nil {
return 0, nil, timestamp, err
}
if t, ok := bi["timestamp"]; ok {
if ts, ok := t.(float64); ok && ts > 0 {
timestamp = time.Unix(int64(ts), 0)
} else {
return 0, nil, timestamp, errors.New("invalid timestamp")
}
} else {
return 0, nil, timestamp, errors.New("invalid timestamp")
}
if h, ok := bi["height"]; ok {
if height, ok := h.(float64); ok && height >= 0 {
return uint64(height), hash, timestamp, nil
}
}
return 0, nil, time.Time{}, errors.New("invalid height")
}
func (bs *blockstreamGozer) FeeEstimates(ctx context.Context) ([]*tbcapi.FeeEstimate, error) {
u := fmt.Sprintf("%v/fee-estimates", bs.url)
feeEstimates, err := httpclient.Request(ctx, "GET", u, nil)
if err != nil {
return nil, fmt.Errorf("request: %w", err)
}
fm := make(map[uint]float64, len(u))
err = json.Unmarshal(feeEstimates, &fm)
if err != nil {
return nil, err
}
frv := make([]*tbcapi.FeeEstimate, 0, len(fm))
for k, v := range fm {
frv = append(frv, &tbcapi.FeeEstimate{Blocks: k, SatsPerByte: v})
}
return frv, nil
}
func (bs *blockstreamGozer) BroadcastTx(ctx context.Context, tx *wire.MsgTx) (*chainhash.Hash, error) {
u := fmt.Sprintf("%v/tx", bs.url)
var buf bytes.Buffer
if err := tx.Serialize(&buf); err != nil {
return nil, err
}
hexTx := hex.EncodeToString(buf.Bytes())
client := &http.Client{}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, u,
strings.NewReader(hexTx))
if err != nil {
return nil, err
}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("request: %v %v",
resp.StatusCode, http.StatusText(resp.StatusCode))
}
respb, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
txidBytes, err := hex.DecodeString(string(respb))
if err != nil {
return nil, err
}
slices.Reverse(txidBytes)
txidHash, err := chainhash.NewHash(txidBytes)
if err != nil {
return nil, err
}
return txidHash, nil
}
func (bs *blockstreamGozer) UtxosByAddress(ctx context.Context, _ bool, addr btcutil.Address, _, _ uint) ([]*tbcapi.UTXO, error) {
u := fmt.Sprintf("%v/address/%v/utxo", bs.url, addr)
utxos, err := httpclient.Request(ctx, "GET", u, nil)
if err != nil {
return nil, fmt.Errorf("request: %w", err)
}
// XXX figure out if we need to set or do something with filterMempool here
type statusJSON struct {
Confirmed bool `json:"confirmed"`
BlockHeight uint64 `json:"block_height"`
BlockHash chainhash.Hash `json:"block_hash"`
BlockTime int64 `json:"block_time"`
}
type utxosJSON struct {
TxID chainhash.Hash `json:"txid"`
Vout uint32 `json:"vout"`
Value btcutil.Amount `json:"value"`
Status statusJSON `json:"status"`
}
var uj []utxosJSON
err = json.Unmarshal(utxos, &uj)
if err != nil {
return nil, err
}
urv := make([]*tbcapi.UTXO, 0, len(uj))
for _, v := range uj {
if !v.Status.Confirmed {
continue
}
urv = append(urv, &tbcapi.UTXO{
TxID: v.TxID,
OutIndex: v.Vout,
Value: v.Value,
})
}
return urv, nil
}
// MempoolUtxos is not supported by the Blockstream backend.
func (bs *blockstreamGozer) MempoolUtxos(_ context.Context, _ []api.ByteSlice) (*tbcapi.MempoolUtxosResponse, error) {
return nil, errors.New("mempool utxos not supported by blockstream")
}
func (bs *blockstreamGozer) BlocksByL2AbrevHashes(_ context.Context, _ []chainhash.Hash) *gozer.BlocksByL2AbrevHashesResponse {
return &gozer.BlocksByL2AbrevHashesResponse{
Error: protocol.Errorf("not supported yet"),
}
}
func (bs *blockstreamGozer) KeystonesByHeight(_ context.Context, _ uint32, _ int) (*gozer.KeystonesByHeightResponse, error) {
err := errors.New("not supported yet")
return &gozer.KeystonesByHeightResponse{
Error: protocol.Errorf("%v", err),
}, err
}
// TxByID is not yet implemented for Blockstream.
// TxByID is a stub — blockstream support for transaction lookup is
// not yet implemented. The only consumer today is ectoplasm which
// uses tbcGozer.
func (bs *blockstreamGozer) TxByID(_ context.Context, _ *chainhash.Hash) (*tbcapi.Tx, error) {
// Blockstream exposes GET /tx/{txid}/hex and GET /tx/{txid},
// either of which could be mapped onto *tbcapi.Tx. Left as
// a stub here because the only consumer today is ectoplasm
// which uses tbcGozer; fill this in when blockstream-backed
// deployments need the ordinal viewer.
return nil, errors.New("not supported yet")
}
func (bs *blockstreamGozer) Run(_ context.Context, _ func()) error {
return nil
}
// New returns a new Blockstream Gozer.
func New(params *chaincfg.Params) (gozer.Gozer, error) {
bs := &blockstreamGozer{}
switch params {
case &chaincfg.MainNetParams:
bs.url = bsMainnetURL
case &chaincfg.TestNet3Params:
bs.url = bsTestne3tURL
default:
// XXX blockstream does not currently support testnet4
return nil, errors.New("invalid net")
}
return bs, nil
}