-
Notifications
You must be signed in to change notification settings - Fork 0
/
fetcher.go
110 lines (99 loc) · 2.27 KB
/
fetcher.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
package main
import (
"bytes"
"encoding/hex"
"errors"
"fmt"
"io"
"log"
"net/http"
"github.com/boltdb/bolt"
"github.com/btcsuite/btcd/wire"
)
const dbName = "db"
const bucketName = "txs"
type fetcher struct {
db *bolt.DB
}
func NewFetcher() *fetcher {
db, err := bolt.Open(dbName, 0600, nil)
if err != nil {
log.Fatal(err)
}
return &fetcher{
db: db,
}
}
func (f *fetcher) Close() {
f.db.Close()
}
var (
bucketNotFoundError = errors.New("bucket not found")
notFoundError = errors.New("key not found")
)
func (f *fetcher) fetch(key string) (string, error) {
value := ""
err := f.db.View(func(tx *bolt.Tx) error {
bucket := tx.Bucket([]byte(bucketName))
if bucket == nil {
return bucketNotFoundError
}
value = string(bucket.Get([]byte(key)))
if value == "" {
return notFoundError
}
return nil
})
return value, err
}
func (f *fetcher) getTransaction(txid string) (*wire.MsgTx, error) {
txHex, err := f.fetch(txid)
if err != nil {
log.Printf("failed to fetch transaction from db %s: %v\n", txid, err)
}
if txHex == "" {
fmt.Printf("fetching transaction from api: %s\n", txid)
url := fmt.Sprintf("https://mempool.space/api/tx/%s/hex", txid)
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
txHexb, err := io.ReadAll(io.Reader(resp.Body))
if err != nil {
return nil, err
}
err = f.db.Update(func(tx *bolt.Tx) error {
b, err := tx.CreateBucketIfNotExists([]byte(bucketName))
if err != nil {
return err
}
return b.Put([]byte(txid), txHexb)
})
if err != nil {
return nil, err
}
txHex = string(txHexb)
}
txBytes, err := hex.DecodeString(txHex)
if err != nil {
return nil, err
}
msgTx := wire.NewMsgTx(wire.TxVersion)
err = msgTx.Deserialize(bytes.NewReader(txBytes))
if err != nil {
return nil, err
}
return msgTx, nil
}
// FetchPrevOutput attempts to fetch the previous output referenced by
// the passed outpoint. A nil value will be returned if the passed
// outpoint doesn't exist.
func (f *fetcher) FetchPrevOutput(outPoint wire.OutPoint) *wire.TxOut {
prevTx, err := f.getTransaction(outPoint.Hash.String())
if err != nil {
fmt.Printf("failed to get transaction %s: %v\n", outPoint.Hash.String(), err)
return nil
}
return prevTx.TxOut[outPoint.Index]
}