/
checkpoints.go
63 lines (60 loc) · 1.61 KB
/
checkpoints.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
package checkpoints
import (
"fmt"
"github.com/p9c/monorepo/pkg/chaincfg"
"github.com/p9c/monorepo/pkg/chainhash"
"strconv"
"strings"
)
// Parse checks the checkpoint strings for valid syntax ( '<height>:<hash>') and parses them to
// chaincfg.Checkpoint instances.
func Parse(checkpointStrings []string) ([]chaincfg.Checkpoint, error) {
if len(checkpointStrings) == 0 {
return nil, nil
}
checkpoints := make([]chaincfg.Checkpoint, len(checkpointStrings))
for i, cpString := range checkpointStrings {
checkpoint, e := newCheckpointFromStr(cpString)
if e != nil {
return nil, e
}
checkpoints[i] = checkpoint
}
return checkpoints, nil
}
// newCheckpointFromStr parses checkpoints in the '<height>:<hash>' format.
func newCheckpointFromStr(checkpoint string) (chaincfg.Checkpoint, error) {
parts := strings.Split(checkpoint, ":")
if len(parts) != 2 {
return chaincfg.Checkpoint{}, fmt.Errorf(
"unable to parse "+
"checkpoint %q -- use the syntax <height>:<hash>",
checkpoint,
)
}
height, e := strconv.ParseInt(parts[0], 10, 32)
if e != nil {
return chaincfg.Checkpoint{}, fmt.Errorf(
"unable to parse "+
"checkpoint %q due to malformed height", checkpoint,
)
}
if len(parts[1]) == 0 {
return chaincfg.Checkpoint{}, fmt.Errorf(
"unable to parse "+
"checkpoint %q due to missing hash", checkpoint,
)
}
hash, e := chainhash.NewHashFromStr(parts[1])
if e != nil {
return chaincfg.Checkpoint{}, fmt.Errorf(
"unable to parse "+
"checkpoint %q due to malformed hash", checkpoint,
)
}
return chaincfg.Checkpoint{
Height: int32(height),
Hash: hash,
},
nil
}