/
chain_id.go
69 lines (58 loc) · 1.54 KB
/
chain_id.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
package types
import (
"encoding/json"
"errors"
"fmt"
"io"
"strings"
"github.com/cometbft/cometbft/types"
)
const ChainIDFieldName = "chain_id"
// ParseChainIDFromGenesis parses the `chain_id` from a genesis JSON file, aborting early after finding the `chain_id`.
// For efficiency, it's recommended to place the `chain_id` field before any large entries in the JSON file.
// Returns an error if the `chain_id` field is not found.
func ParseChainIDFromGenesis(r io.Reader) (string, error) {
dec := json.NewDecoder(r)
t, err := dec.Token()
if err != nil {
return "", err
}
if t != json.Delim('{') {
return "", fmt.Errorf("expected {, got %s", t)
}
for dec.More() {
t, err = dec.Token()
if err != nil {
return "", err
}
key, ok := t.(string)
if !ok {
return "", fmt.Errorf("expected string for the key type, got %s", t)
}
if key == ChainIDFieldName {
var chainID string
if err := dec.Decode(&chainID); err != nil {
return "", err
}
if err := validateChainID(chainID); err != nil {
return "", err
}
return chainID, nil
}
// skip the value
var value json.RawMessage
if err := dec.Decode(&value); err != nil {
return "", err
}
}
return "", errors.New("missing chain-id in genesis file")
}
func validateChainID(chainID string) error {
if strings.TrimSpace(chainID) == "" {
return errors.New("genesis doc must include non-empty chain_id")
}
if len(chainID) > types.MaxChainIDLen {
return fmt.Errorf("chain_id in genesis doc is too long (max: %d)", types.MaxChainIDLen)
}
return nil
}