Port "Refactor node creation"

Signed-off-by: Vasyl Gello <vasek.gello@gmail.com>
This commit is contained in:
Vasyl Gello 2023-11-15 18:58:02 +02:00
parent a0b3897278
commit 7b41cec27f
3 changed files with 435 additions and 232 deletions

View file

@ -33,6 +33,7 @@ import (
"time"
"github.com/hjson/hjson-go/v4"
"github.com/mitchellh/mapstructure"
"golang.org/x/text/encoding/unicode"
)
@ -89,6 +90,22 @@ func GenerateConfig() *NodeConfig {
return cfg
}
func GenerateConfigJSON(isjson bool) []byte {
// Generates a new configuration and returns it in HJSON or JSON format.
cfg := GenerateConfig()
var bs []byte
var err error
if isjson {
bs, err = json.MarshalIndent(cfg, "", " ")
} else {
bs, err = hjson.Marshal(cfg)
}
if err != nil {
panic(err)
}
return bs
}
func (cfg *NodeConfig) ReadFrom(r io.Reader) (int64, error) {
conf, err := io.ReadAll(r)
if err != nil {
@ -258,3 +275,68 @@ func (k *KeyBytes) UnmarshalJSON(b []byte) error {
*k, err = hex.DecodeString(s)
return err
}
func ReadConfig(conf []byte) *NodeConfig {
// Generate a new configuration - this gives us a set of sane defaults -
// then parse the configuration we loaded above on top of it. The effect
// of this is that any configuration item that is missing from the provided
// configuration will use a sane default.
cfg := GenerateConfig()
var dat map[string]interface{}
if err := hjson.Unmarshal(conf, &dat); err != nil {
panic(err)
}
// Check if we have old field names
if old, ok := dat["SigningPrivateKey"]; ok {
if _, ok := dat["PrivateKey"]; !ok {
if privstr, err := hex.DecodeString(old.(string)); err == nil {
priv := ed25519.PrivateKey(privstr)
pub := priv.Public().(ed25519.PublicKey)
dat["PrivateKey"] = hex.EncodeToString(priv[:])
dat["PublicKey"] = hex.EncodeToString(pub[:])
}
}
}
if oldmc, ok := dat["MulticastInterfaces"]; ok {
if oldmcvals, ok := oldmc.([]interface{}); ok {
var newmc []MulticastInterfaceConfig
for _, oldmcval := range oldmcvals {
if str, ok := oldmcval.(string); ok {
newmc = append(newmc, MulticastInterfaceConfig{
Regex: str,
Beacon: true,
Listen: true,
})
}
}
if newmc != nil {
if oldport, ok := dat["LinkLocalTCPPort"]; ok {
// numbers parse to float64 by default
if port, ok := oldport.(float64); ok {
for idx := range newmc {
newmc[idx].Port = uint16(port)
}
}
}
dat["MulticastInterfaces"] = newmc
}
}
}
// Sanitise the config
confJson, err := json.Marshal(dat)
if err != nil {
panic(err)
}
if err := json.Unmarshal(confJson, &cfg); err != nil {
panic(err)
}
// Overlay our newly mapped configuration onto the autoconf node config that
// we generated above.
if err = mapstructure.Decode(dat, &cfg); err != nil {
panic(err)
}
if err := cfg.postprocessConfig(); err != nil {
panic(err)
}
return cfg
}