-
Notifications
You must be signed in to change notification settings - Fork 1
/
esplora.go
74 lines (62 loc) · 1.5 KB
/
esplora.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
package opentimestamps
import (
"bytes"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"slices"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/wire"
)
func NewEsploraClient(url string) Bitcoin {
if strings.HasSuffix(url, "/") {
url = url[0 : len(url)-1]
}
return esplora{url}
}
type esplora struct{ baseurl string }
func (e esplora) GetBlockHash(height int64) (*chainhash.Hash, error) {
resp, err := http.Get(e.baseurl + "/block-height/" + strconv.FormatInt(height, 10))
if err != nil {
return nil, err
}
defer resp.Body.Close()
hexb, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
hash, err := hex.DecodeString(string(hexb))
if err != nil {
return nil, err
}
if len(hash) != chainhash.HashSize {
return nil, fmt.Errorf("got block hash (%x) of invalid size (expected %d)", hash, chainhash.HashSize)
}
slices.Reverse(hash)
var chash chainhash.Hash
copy(chash[:], hash)
return &chash, nil
}
func (e esplora) GetBlockHeader(hash *chainhash.Hash) (*wire.BlockHeader, error) {
resp, err := http.Get(fmt.Sprintf("%s/block/%s/header", e.baseurl, hash.String()))
if err != nil {
return nil, err
}
defer resp.Body.Close()
hexb, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
headerHash, err := hex.DecodeString(string(hexb))
if err != nil {
return nil, err
}
header := &wire.BlockHeader{}
if err := header.BtcDecode(bytes.NewBuffer(headerHash), 0, 0); err != nil {
return nil, err
}
return header, nil
}