-
Notifications
You must be signed in to change notification settings - Fork 0
/
headers.go
427 lines (392 loc) · 11.9 KB
/
headers.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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
// Copyright 2018 Shift Devices AG
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package headers
import (
"bytes"
"errors"
"fmt"
"math/big"
"time"
btcdBlockchain "github.com/btcsuite/btcd/blockchain"
"github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/wire"
"github.com/digitalbitbox/bitbox-wallet-app/backend/coins/btc/blockchain"
"github.com/digitalbitbox/bitbox-wallet-app/backend/coins/ltc"
"github.com/digitalbitbox/bitbox-wallet-app/util/errp"
"github.com/digitalbitbox/bitbox-wallet-app/util/locker"
"github.com/sirupsen/logrus"
"golang.org/x/crypto/scrypt"
)
const reorgLimit = 100
// Event instances are sent to the onEvent callback.
type Event string
const (
// EventSyncing is fired when the headers are syncing (a batch was downloaded but more are
// coming). At the end, EventSynced is fired.
EventSyncing Event = "syncing"
// EventSynced is fired when the headers finished syncing.
EventSynced Event = "synced"
// EventNewTip is fired when a new tip is known.
EventNewTip Event = "newTip"
)
// Interface represents the public API of this package.
//go:generate mockery -name Interface
type Interface interface {
Initialize()
SubscribeEvent(f func(Event)) func()
HeaderByHeight(int) (*wire.BlockHeader, error)
TipHeight() int
Status() (*Status, error)
}
// Headers manages syncing blockchain headers.
type Headers struct {
log *logrus.Entry
net *chaincfg.Params
db DBInterface
blockchain blockchain.Interface
headersPerBatch int
lock locker.Locker
// targetHeight is the potential tip height we are syncing up to.
targetHeight int
// tipAtInitTime is the tip at init time, i.e. the last tip known, loaded from the DB. It is
// used to show the sync progress since the last time (catch up).
tipAtInitTime int
kickChan chan struct{}
eventCallbacks []func(Event)
events chan Event
}
// Status represents the syncing status.
type Status struct {
TipAtInitTime int `json:"tipAtInitTime"`
Tip int `json:"tip"`
// Only well defined if Tip >= 0
TipHashHex blockchain.TXHash `json:"tipHashHex"`
TargetHeight int `json:"targetHeight"`
}
// NewHeaders creates a new Headers instance.
func NewHeaders(
net *chaincfg.Params,
db DBInterface,
blockchain blockchain.Interface,
log *logrus.Entry) *Headers {
return &Headers{
log: log,
net: net,
db: db,
blockchain: blockchain,
// We start with a small batch size and increase to the maximum allowed one with the first
// response.
headersPerBatch: 10,
targetHeight: 0,
tipAtInitTime: 0,
kickChan: make(chan struct{}, 1),
eventCallbacks: []func(Event){},
events: make(chan Event),
}
}
// SubscribeEvent subscribes to header events. The provided callback will be notified of events. The
// returned function unsubscribes.
// FIXME: not thread-safe
func (headers *Headers) SubscribeEvent(f func(event Event)) func() {
headers.eventCallbacks = append(headers.eventCallbacks, f)
index := len(headers.eventCallbacks) - 1
return func() {
headers.eventCallbacks[index] = nil
}
}
// TipHeight returns the height of the tip.
func (headers *Headers) TipHeight() int {
return headers.targetHeight
}
// Initialize starts the syncing process.
func (headers *Headers) Initialize() {
headers.tipAtInitTime = headers.tip()
headers.log.Infof("last tip loaded: %d", headers.tipAtInitTime)
go headers.download()
headers.blockchain.HeadersSubscribe(
nil,
func(header *blockchain.Header) error {
return headers.update(header.BlockHeight)
},
)
headers.kickChan <- struct{}{}
}
type batchInfo struct {
blockHeaders []*wire.BlockHeader
max int
}
func (headers *Headers) download() {
for range headers.kickChan {
func() {
defer headers.lock.Lock()()
dbTx, err := headers.db.Begin()
if err != nil {
// TODO
panic(err)
}
defer func() {
_ = dbTx.Commit()
}()
tip, err := dbTx.Tip()
if err != nil {
// TODO
panic(err)
}
batchChan := make(chan batchInfo)
headers.blockchain.Headers(
tip+1, headers.headersPerBatch,
func(blockHeaders []*wire.BlockHeader, max int) error {
batchChan <- batchInfo{blockHeaders, max}
return nil
}, func(error) {})
batch := <-batchChan
if err := headers.processBatch(dbTx, tip, batch.blockHeaders, batch.max); err != nil {
headers.log.WithError(err).Panic("processBatch")
}
}()
}
}
var errPrevHash = errors.New("header prevhash does not match")
func (headers *Headers) getTarget(dbTx DBTxInterface, index int) (*big.Int, error) {
targetTimespan := int64(headers.net.TargetTimespan / time.Second)
targetTimePerBlock := int64(headers.net.TargetTimePerBlock / time.Second)
blocksPerRetarget := int(targetTimespan / targetTimePerBlock)
chunkIndex := (index / blocksPerRetarget) - 1
if chunkIndex == -1 {
return btcdBlockchain.CompactToBig(headers.net.GenesisBlock.Header.Bits), nil
}
firstIndex := chunkIndex * blocksPerRetarget
if headers.net.Net == ltc.MainNetParams.Net && chunkIndex > 0 {
// Litecoin includes the last block of the previous window to fix a time warp attack:
// https://litecoin.info/index.php/Time_warp_attack#cite_note-2
firstIndex--
}
first, err := dbTx.HeaderByHeight(firstIndex)
if err != nil {
return nil, err
}
last, err := dbTx.HeaderByHeight((chunkIndex+1)*blocksPerRetarget - 1)
if err != nil {
return nil, err
}
lastTarget := btcdBlockchain.CompactToBig(last.Bits)
timespan := last.Timestamp.Unix() - first.Timestamp.Unix()
minRetargetTimespan := targetTimespan / headers.net.RetargetAdjustmentFactor
maxRetargetTimespan := targetTimespan * headers.net.RetargetAdjustmentFactor
if timespan < minRetargetTimespan {
timespan = minRetargetTimespan
} else if timespan > maxRetargetTimespan {
timespan = maxRetargetTimespan
}
newTarget := new(big.Int).Mul(lastTarget, big.NewInt(timespan))
newTarget.Div(newTarget, big.NewInt(targetTimespan))
if newTarget.Cmp(headers.net.PowLimit) > 0 {
newTarget.Set(headers.net.PowLimit)
}
return newTarget, nil
}
func (headers *Headers) powHash(msg []byte) chainhash.Hash {
switch headers.net.Net {
case chaincfg.MainNetParams.Net:
return chainhash.DoubleHashH(msg)
case ltc.MainNetParams.Net:
const (
N = 1024
r = 1
p = 1
)
hashBytes, err := scrypt.Key(msg, msg, N, r, p, 32)
if err != nil {
panic(errp.WithStack(err))
}
hash := chainhash.Hash{}
if err := hash.SetBytes(hashBytes); err != nil {
panic(errp.WithStack(err))
}
return hash
default:
panic("unsupported coin")
}
}
func (headers *Headers) canConnect(dbTx DBTxInterface, tip int, header *wire.BlockHeader) error {
if tip == 0 {
if header.BlockHash() != *headers.net.GenesisHash {
return errp.Newf("wrong genesis hash, got %s, expected %s",
header.BlockHash(), *headers.net.GenesisHash)
}
} else {
previousHeader, err := dbTx.HeaderByHeight(tip - 1)
if err != nil {
return err
}
prevBlock := previousHeader.BlockHash()
if header.PrevBlock != prevBlock {
return errp.Wrap(errPrevHash,
fmt.Sprintf("%s (%d) does not connect to %s (%d)",
header.PrevBlock, tip, prevBlock, tip-1))
}
lastCheckpoint := headers.net.Checkpoints[len(headers.net.Checkpoints)-1]
if tip == int(lastCheckpoint.Height) {
if *lastCheckpoint.Hash != header.BlockHash() {
return errp.Newf("checkpoint mismatch at %d. Expected %s, got %s",
tip, lastCheckpoint.Hash, header.BlockHash())
}
headers.log.Infof("checkpoint at %d matches", tip)
}
// Check Difficulty, PoW.
if headers.net.Net == chaincfg.MainNetParams.Net || headers.net.Net == ltc.MainNetParams.Net {
newTarget, err := headers.getTarget(dbTx, tip)
if err != nil {
return err
}
if header.Bits != btcdBlockchain.BigToCompact(newTarget) {
return errp.Newf("header %d has an unexpected difficulty", tip)
}
headerSerialized := &bytes.Buffer{}
if err := header.BtcEncode(headerSerialized, 0, wire.BaseEncoding); err != nil {
panic(errp.WithStack(err))
}
// Skip PoW check before the checkpoint for performance.
if tip > int(lastCheckpoint.Height) {
powHash := headers.powHash(headerSerialized.Bytes())
proofOfWork := btcdBlockchain.HashToBig(&powHash)
if proofOfWork.Cmp(newTarget) > 0 {
return errp.Newf("header %d, %s has insufficient proof of work.", tip, powHash)
}
}
}
}
return nil
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
func (headers *Headers) reorg(dbTx DBTxInterface, tip int) {
// Simple reorg method: re-fetch headers up to the maximum reorg limit. The server can shorten
// our chain by sending a fake header and set us back by `reorgLimit` blocks, but it needs to
// contain the correct PoW to do so.
newTip := tip - reorgLimit
if newTip < -1 {
newTip = -1
}
if err := dbTx.PutTip(newTip); err != nil {
panic(err)
}
headers.kick()
}
func (headers *Headers) notifyEvent(event Event) {
for _, f := range headers.eventCallbacks {
if f != nil {
go f(event)
}
}
}
func (headers *Headers) processBatch(
dbTx DBTxInterface, tip int, blockHeaders []*wire.BlockHeader, max int) error {
for _, header := range blockHeaders {
err := headers.canConnect(dbTx, tip+1, header)
if errp.Cause(err) == errPrevHash {
headers.log.WithError(err).Infof("Reorg detected at height %d", tip+1)
headers.reorg(dbTx, tip)
return nil
}
if err != nil {
return errp.WithMessage(err, "can't connect header, unexpected blockchain reply")
}
tip++
if err := dbTx.PutHeader(tip, header); err != nil {
return err
}
}
if len(blockHeaders) == min(max, headers.headersPerBatch) {
// Received max number of headers per batch, so there might be more.
headers.kick()
headers.log.Debugf("Syncing headers; tip: %d", tip)
headers.notifyEvent(EventSyncing)
} else if len(blockHeaders) != 0 {
headers.log.Debugf("Synced headers; tip: %d", tip)
headers.notifyEvent(EventSynced)
}
headers.headersPerBatch = max
return nil
}
// HeaderByHeight returns the header at the given height. Returns nil if the headers are not synced
// up to this height yet.
func (headers *Headers) HeaderByHeight(height int) (*wire.BlockHeader, error) {
defer headers.lock.RLock()()
dbTx, err := headers.db.Begin()
if err != nil {
return nil, err
}
defer dbTx.Rollback()
return dbTx.HeaderByHeight(height)
}
func (headers *Headers) kick() {
select {
case headers.kickChan <- struct{}{}:
default:
}
}
// update should be called when there is a new header.
func (headers *Headers) update(blockHeight int) error {
headers.log.Debugf("new target %d", blockHeight)
headers.kick()
headers.targetHeight = blockHeight
headers.notifyEvent(EventNewTip)
return nil
}
func (headers *Headers) tip() int {
defer headers.lock.RLock()()
dbTx, err := headers.db.Begin()
if err != nil {
panic(err)
}
defer dbTx.Rollback()
tip, err := dbTx.Tip()
if err != nil {
panic(err)
}
return tip
}
// Status returns the current sync status.
func (headers *Headers) Status() (*Status, error) {
defer headers.lock.RLock()()
dbTx, err := headers.db.Begin()
if err != nil {
return nil, err
}
defer dbTx.Rollback()
tip, err := dbTx.Tip()
if err != nil {
return nil, err
}
header, err := dbTx.HeaderByHeight(tip)
if err != nil {
return nil, err
}
var tipHashHex blockchain.TXHash
if header != nil {
tipHashHex = blockchain.TXHash(header.BlockHash())
}
return &Status{
TipAtInitTime: headers.tipAtInitTime,
Tip: tip,
TargetHeight: headers.targetHeight,
TipHashHex: tipHashHex,
}, nil
}