This repository was archived by the owner on Feb 15, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathprovider.go
80 lines (69 loc) · 1.79 KB
/
provider.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
package backend
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"strconv"
"time"
"google.golang.org/appengine/urlfetch"
"golang.org/x/net/context"
)
// Package specific errors
var (
ErrBlockNotFound = errors.New("no block found")
)
// Provider provides Blockhain info
type Provider interface {
// Fetch fetches a block at the given height
Fetch(int) (Block, error)
}
// Blockcypher is a Blockchain info provider hosted at blockcypher.com
type Blockcypher struct {
ctx context.Context
}
// Fetch fetches a Block at the given height
func (bc *Blockcypher) Fetch(h int) (Block, error) {
client := urlfetch.Client(bc.ctx)
// get block
res, err := client.Get("https://api.blockcypher.com/v1/btc/main/blocks/" + strconv.Itoa(h) + "?txstart=0&limit=1")
if err != nil {
return Block{}, err
}
if res.StatusCode == http.StatusNotFound {
return Block{}, ErrBlockNotFound
}
br := struct {
Version int `json:"ver"`
Height int `json:"height"`
Hash string `json:"hash"`
Timestamp time.Time `json:"time"`
TxURL string `json:"tx_url"`
TxIDs []string `json:"txids"`
}{}
err = json.NewDecoder(res.Body).Decode(&br)
if err != nil {
return Block{}, fmt.Errorf("could not parse body: %v", err)
}
// get first tx
res, err = client.Get(br.TxURL + "/" + br.TxIDs[0])
if res.StatusCode == http.StatusNotFound {
return Block{}, fmt.Errorf("could not find first transaction: %v", err)
}
tr := struct {
Inputs []struct {
Script string `json:"script"`
} `json:"inputs"`
}{}
err = json.NewDecoder(res.Body).Decode(&tr)
if err != nil {
return Block{}, fmt.Errorf("could not parse body: %v", err)
}
b := Block{}
b.Script = tr.Inputs[0].Script
b.Hash = br.Hash
b.Height = br.Height
b.Timestamp = br.Timestamp
b.Version = br.Version
return b, nil
}