-
Notifications
You must be signed in to change notification settings - Fork 40
/
bdf.go
231 lines (207 loc) · 4.66 KB
/
bdf.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
// Copyright (c) 2024 Hemi Labs, Inc.
// Use of this source code is governed by the MIT License,
// which can be found in the LICENSE file.
package bdf
import (
"bytes"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"sync"
"github.com/btcsuite/btcd/wire"
"github.com/juju/loggo"
)
// XXX add tests
var (
log = loggo.GetLogger("bdf")
dfm sync.RWMutex
)
const (
DefaultNet = "testnet"
HeightFilename = "height"
)
var DefaultDataDir = filepath.Join(DefaultNet, "bitcoin_headers")
type LastHeight struct {
Height int `json:"height"`
Hash string `json:"hash"`
}
type Header struct {
Height int `json:"height"`
Header string `json:"header"`
}
func ReadHeight(filename string) (int, string, error) {
dfm.RLock()
defer dfm.RUnlock()
f, err := os.Open(filename)
if err != nil {
return 0, "", err
}
d := json.NewDecoder(f)
var lh LastHeight
err = d.Decode(&lh)
if err != nil {
f.Close()
return 0, "", err
}
err = f.Close()
if err != nil {
return 0, "", err
}
return lh.Height, lh.Hash, nil
}
func ReadHeader(filename string) (*wire.BlockHeader, int, error) {
dfm.RLock()
defer dfm.RUnlock()
f, err := os.Open(filename)
if err != nil {
return nil, 0, err
}
d := json.NewDecoder(f)
var h Header
err = d.Decode(&h)
if err != nil {
f.Close()
return nil, 0, err
}
err = f.Close()
if err != nil {
return nil, 0, err
}
dh, err := hex.DecodeString(h.Header)
if err != nil {
return nil, 0, err
}
if len(dh) != 80 {
return nil, 0, err
}
var wbh wire.BlockHeader
err = wbh.Deserialize(bytes.NewReader(dh))
if err != nil {
return nil, 0, err
}
return &wbh, h.Height, nil
}
func Header2Bytes(wbh *wire.BlockHeader) ([]byte, error) {
var b bytes.Buffer
err := wbh.Serialize(&b)
if err != nil {
return nil, err
}
return b.Bytes(), nil
}
func Header2ExactBytes(wbh *wire.BlockHeader, header *[80]byte) error {
b, err := Header2Bytes(wbh)
if err != nil {
return err
}
if len(b) != 80 {
return fmt.Errorf("should not happen length %v", len(b))
}
copy(header[:], b)
return nil
}
func Header2Hex(wbh *wire.BlockHeader) (string, error) {
b, err := Header2Bytes(wbh)
if err != nil {
return "", err
}
return hex.EncodeToString(b), nil
}
func Hex2Header(header string) (*wire.BlockHeader, error) {
blockHeader, err := hex.DecodeString(header)
if err != nil {
return nil, fmt.Errorf("decode string: %w", err)
}
var bh wire.BlockHeader
err = bh.Deserialize(bytes.NewReader(blockHeader))
if err != nil {
return nil, fmt.Errorf("deserialize block header: %w", err)
}
return &bh, nil
}
// writeHeight reads the latest height and overwrites it if the provided height
// is higher. Poor mans for resolution :-)
func writeHeight(height int, hash, dir string) error {
log.Tracef("WriteHeight %v %v", height, hash)
defer log.Tracef("WriteHeight exit")
var lh LastHeight
filename := filepath.Join(dir, HeightFilename)
f, err := os.Open(filename)
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
// do nothing
defer f.Close()
} else {
return fmt.Errorf("open file: %w", err)
}
} else {
defer f.Close()
d := json.NewDecoder(f)
err = d.Decode(&lh)
if err != nil {
return fmt.Errorf("%v corrupt: %w", filename, err)
}
}
if lh.Height > height {
log.Tracef("not overwriting height: %v > %v", lh.Height, height)
return nil
}
fw, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600)
if err != nil {
return fmt.Errorf("open file: %w", err)
}
e := json.NewEncoder(fw)
lh.Height = height
lh.Hash = hash
err = e.Encode(lh)
if err != nil {
return fmt.Errorf("encode: %w", err)
}
return fw.Close()
}
// writeHeader writes a header. We pass the hash to verify that the header is correct.
func writeHeader(height int, hash, header, dir string) error {
filename := filepath.Join(dir, hash)
overwrite := false
if !overwrite {
_, err := os.Stat(filename)
if err == nil {
return fmt.Errorf("caught up at height: %v", height)
}
}
f, err := os.Create(filename)
if err != nil {
return fmt.Errorf("create file: %w", err)
}
e := json.NewEncoder(f)
err = e.Encode(Header{
Height: height,
Header: header,
})
if err != nil {
f.Close()
return fmt.Errorf("encode json: %w", err)
}
return f.Close()
}
func WriteHeader(height int, header, dir string) error {
bh, err := Hex2Header(header)
if err != nil {
return fmt.Errorf("convert hex to header: %w", err)
}
dfm.Lock()
defer dfm.Unlock()
err = writeHeader(height, bh.BlockHash().String(), header, dir)
if err != nil {
return fmt.Errorf("write header: %w", err)
}
err = writeHeight(height, bh.BlockHash().String(), dir)
if err != nil {
return fmt.Errorf("write height: %w", err)
}
return nil
}