github.com/prysmaticlabs/prysm@v1.4.4/validator/graffiti/parse_graffiti.go (about)

     1  package graffiti
     2  
     3  import (
     4  	"encoding/hex"
     5  	"io/ioutil"
     6  	"strings"
     7  
     8  	types "github.com/prysmaticlabs/eth2-types"
     9  	"github.com/prysmaticlabs/prysm/shared/hashutil"
    10  	"gopkg.in/yaml.v2"
    11  )
    12  
    13  const (
    14  	hexGraffitiPrefix = "hex"
    15  	hex0xPrefix       = "0x"
    16  )
    17  
    18  // Graffiti is a graffiti container.
    19  type Graffiti struct {
    20  	Hash     [32]byte
    21  	Default  string                          `yaml:"default,omitempty"`
    22  	Ordered  []string                        `yaml:"ordered,omitempty"`
    23  	Random   []string                        `yaml:"random,omitempty"`
    24  	Specific map[types.ValidatorIndex]string `yaml:"specific,omitempty"`
    25  }
    26  
    27  // ParseGraffitiFile parses the graffiti file and returns the graffiti struct.
    28  func ParseGraffitiFile(f string) (*Graffiti, error) {
    29  	yamlFile, err := ioutil.ReadFile(f)
    30  	if err != nil {
    31  		return nil, err
    32  	}
    33  	g := &Graffiti{}
    34  	if err := yaml.Unmarshal(yamlFile, g); err != nil {
    35  		return nil, err
    36  	}
    37  
    38  	for i, o := range g.Specific {
    39  		g.Specific[types.ValidatorIndex(i)] = ParseHexGraffiti(o)
    40  	}
    41  
    42  	for i, v := range g.Ordered {
    43  		g.Ordered[i] = ParseHexGraffiti(v)
    44  	}
    45  
    46  	for i, v := range g.Random {
    47  		g.Random[i] = ParseHexGraffiti(v)
    48  	}
    49  
    50  	g.Default = ParseHexGraffiti(g.Default)
    51  	g.Hash = hashutil.Hash(yamlFile)
    52  
    53  	return g, nil
    54  }
    55  
    56  // ParseHexGraffiti checks if a graffiti input is being represented in hex and converts it to ASCII if so
    57  func ParseHexGraffiti(rawGraffiti string) string {
    58  	splitGraffiti := strings.SplitN(rawGraffiti, ":", 2)
    59  	if strings.ToLower(splitGraffiti[0]) == hexGraffitiPrefix {
    60  		target := splitGraffiti[1]
    61  		if target == "" {
    62  			log.WithField("graffiti", rawGraffiti).Debug("Blank hex tag to be interpreted as itself")
    63  			return rawGraffiti
    64  		}
    65  		if len(target) > 3 && target[:2] == hex0xPrefix {
    66  			target = target[2:]
    67  		}
    68  		if target == "" {
    69  			log.WithField("graffiti", rawGraffiti).Debug("Nothing after 0x prefix, hex tag to be interpreted as itself")
    70  			return rawGraffiti
    71  		}
    72  		graffiti, err := hex.DecodeString(target)
    73  		if err != nil {
    74  			log.WithError(err).Debug("Error while decoding hex string")
    75  			return rawGraffiti
    76  		}
    77  		return string(graffiti)
    78  	}
    79  	return rawGraffiti
    80  }