-
Notifications
You must be signed in to change notification settings - Fork 1k
/
parse_graffiti.go
86 lines (75 loc) · 2.28 KB
/
parse_graffiti.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
package graffiti
import (
"encoding/hex"
"os"
"strings"
"github.com/pkg/errors"
"github.com/prysmaticlabs/prysm/v5/consensus-types/primitives"
"github.com/prysmaticlabs/prysm/v5/crypto/hash"
"gopkg.in/yaml.v2"
)
const (
hexGraffitiPrefix = "hex"
hex0xPrefix = "0x"
)
// Graffiti is a graffiti container.
type Graffiti struct {
Hash [32]byte
Default string `yaml:"default,omitempty"`
Ordered []string `yaml:"ordered,omitempty"`
Random []string `yaml:"random,omitempty"`
Specific map[primitives.ValidatorIndex]string `yaml:"specific,omitempty"`
}
// ParseGraffitiFile parses the graffiti file and returns the graffiti struct.
func ParseGraffitiFile(f string) (*Graffiti, error) {
yamlFile, err := os.ReadFile(f) // #nosec G304
if err != nil {
return nil, err
}
g := &Graffiti{}
if err := yaml.UnmarshalStrict(yamlFile, g); err != nil {
var typeError *yaml.TypeError
if !errors.As(err, &typeError) {
return nil, err
} else {
log.WithError(err).Error("There were some issues parsing graffiti from a yaml file.")
}
}
for i, o := range g.Specific {
g.Specific[i] = ParseHexGraffiti(o)
}
for i, v := range g.Ordered {
g.Ordered[i] = ParseHexGraffiti(v)
}
for i, v := range g.Random {
g.Random[i] = ParseHexGraffiti(v)
}
g.Default = ParseHexGraffiti(g.Default)
g.Hash = hash.Hash(yamlFile)
return g, nil
}
// ParseHexGraffiti checks if a graffiti input is being represented in hex and converts it to ASCII if so
func ParseHexGraffiti(rawGraffiti string) string {
splitGraffiti := strings.SplitN(rawGraffiti, ":", 2)
if strings.ToLower(splitGraffiti[0]) == hexGraffitiPrefix {
target := splitGraffiti[1]
if target == "" {
log.WithField("graffiti", rawGraffiti).Debug("Blank hex tag to be interpreted as itself")
return rawGraffiti
}
if len(target) > 3 && target[:2] == hex0xPrefix {
target = target[2:]
}
if target == "" {
log.WithField("graffiti", rawGraffiti).Debug("Nothing after 0x prefix, hex tag to be interpreted as itself")
return rawGraffiti
}
graffiti, err := hex.DecodeString(target)
if err != nil {
log.WithError(err).Debug("Error while decoding hex string")
return rawGraffiti
}
return string(graffiti)
}
return rawGraffiti
}