github.com/hyperledger/burrow@v0.34.5-0.20220512172541-77f09336001d/config/deployment/config.go (about) 1 package deployment 2 3 import ( 4 "bytes" 5 "encoding/base64" 6 "encoding/json" 7 "fmt" 8 "reflect" 9 "text/template" 10 11 "github.com/hyperledger/burrow/crypto" 12 "github.com/hyperledger/burrow/genesis" 13 "github.com/pkg/errors" 14 hex "github.com/tmthrgd/go-hex" 15 yaml "gopkg.in/yaml.v2" 16 ) 17 18 type Validator struct { 19 Name string 20 Address crypto.Address 21 NodeAddress crypto.Address 22 } 23 24 type Key struct { 25 Name string 26 Address crypto.Address 27 CurveType string 28 PublicKey []byte 29 PrivateKey []byte 30 KeyJSON json.RawMessage 31 } 32 33 type Config struct { 34 Keys map[crypto.Address]Key 35 Validators []Validator 36 *genesis.GenesisDoc 37 } 38 39 var templateFuncs template.FuncMap = map[string]interface{}{ 40 "base64": func(rv reflect.Value) string { 41 return encode(rv, base64.StdEncoding.EncodeToString) 42 }, 43 "hex": func(rv reflect.Value) string { 44 return encode(rv, hex.EncodeUpperToString) 45 }, 46 "yaml": func(rv interface{}) string { 47 a, _ := yaml.Marshal(rv) 48 return string(a) 49 }, 50 "json": func(rv interface{}) string { 51 b, _ := json.Marshal(rv) 52 return string(b) 53 }, 54 } 55 56 const DefaultKeysExportFormat = `{ 57 "CurveType": "{{ .CurveType }}", 58 "Address": "{{ .Address }}", 59 "PublicKey": "{{ hex .PublicKey }}", 60 "PrivateKey": "{{ hex .PrivateKey }}" 61 }` 62 63 var DefaultKeyExportTemplate = template.Must(template.New("KeysExport"). 64 Funcs(templateFuncs).Parse(DefaultKeysExportFormat)) 65 66 // Dump a configuration to a template 67 func (pkg *Config) Dump(templateName, templateData string) (string, error) { 68 tmpl, err := template.New(templateName).Funcs(templateFuncs).Parse(templateData) 69 if err != nil { 70 return "", errors.Wrap(err, "could not dump config to template") 71 } 72 buf := new(bytes.Buffer) 73 err = tmpl.Execute(buf, pkg) 74 if err != nil { 75 return "", err 76 } 77 return buf.String(), nil 78 } 79 80 // Dump a key file to a template 81 func (key *Key) Dump(templateData string) (string, error) { 82 tmpl, err := template.New("ExportKey").Funcs(templateFuncs).Parse(templateData) 83 if err != nil { 84 return "", errors.Wrap(err, "could not export key to template") 85 } 86 buf := new(bytes.Buffer) 87 err = tmpl.Execute(buf, key) 88 if err != nil { 89 return "", err 90 } 91 return buf.String(), nil 92 } 93 94 func encode(rv reflect.Value, encoder func([]byte) string) string { 95 switch rv.Kind() { 96 case reflect.Slice: 97 return encoder(rv.Bytes()) 98 case reflect.String: 99 return encoder([]byte(rv.String())) 100 default: 101 panic(fmt.Errorf("could not convert %#v to bytes to encode", rv)) 102 } 103 }