Skip to content

Commit

Permalink
Adding config for the mainnet with an example (#308)
Browse files Browse the repository at this point in the history
* Adding config for the mainnet with an example

* Fixed fomartting issue

* Update config_test.go for windows

Co-authored-by: Mantre <[email protected]>
  • Loading branch information
vlasfama and themantre authored Apr 27, 2022
1 parent 5001c88 commit f414ed6
Show file tree
Hide file tree
Showing 35 changed files with 541 additions and 249 deletions.
2 changes: 1 addition & 1 deletion .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,4 @@ indent_size = 4
indent_style = tab

[Makefile]
indent_style = tab
indent_style = tab
46 changes: 30 additions & 16 deletions cmd/daemon/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,11 @@ func Init() func(c *cli.Cmd) {
Desc: "Initialize working directory for joining the testnet",
Value: false,
})
localnetOpt := c.Bool(cli.BoolOpt{
Name: "localnet",
Desc: "Initialize working directory for localnet (for developers)",
Value: false,
})

c.LongDesc = "Initializing the working directory by new validator's private key and genesis file."
c.Before = func() { fmt.Println(cmd.ZARB) }
Expand Down Expand Up @@ -82,17 +87,17 @@ func Init() func(c *cli.Cmd) {
}

var gen *genesis.Genesis
conf := config.DefaultConfig()
confFile := cmd.ZarbConfigPath(workingDir)

if *testnetOpt {
gen = genesis.Testnet()

conf.Network.Name = "perdana-testnet"
conf.Network.Bootstrap.Addresses = []string{"/ip4/172.104.169.94/tcp/21777/p2p/12D3KooWNYD4bB82YZRXv6oNyYPwc5ozabx2epv75ATV3D8VD3Mq"}
conf.Network.Bootstrap.MinThreshold = 4
conf.Network.Bootstrap.MaxThreshold = 8
conf.State.RewardAddress = rewardAddrStr
} else {
// Save config for testnet
if err := config.SaveTestnetConfig(confFile, rewardAddrStr); err != nil {
cmd.PrintErrorMsg("Failed to write config file: %v", err)
return
}
} else if *localnetOpt {
valPubStr, err := wallet.PublicKey("", valAddrStr)
if err != nil {
cmd.PrintErrorMsg("Failed to get validator public key: %v", err)
Expand All @@ -105,28 +110,37 @@ func Init() func(c *cli.Cmd) {
}

gen = makeLocalGenesis(valPub)
conf.Network.Name = "local-test"

// Save config for localnet
if err := config.SaveLocalnetConfig(confFile, rewardAddrStr); err != nil {
cmd.PrintErrorMsg("Failed to write config file: %v", err)
return
}
} else {
panic("not yet!")
// gen = genesis.Mainnet()

// // Save config for mainnet
// if err := config.SaveMainnetConfig(confFile, rewardAddrStr); err != nil {
// cmd.PrintErrorMsg("Failed to write config file: %v", err)
// return
// }
}

// Save genesis file to file system
// Save genesis file
genFile := cmd.ZarbGenesisPath(workingDir)
if err := gen.SaveToFile(genFile); err != nil {
cmd.PrintErrorMsg("Failed to write genesis file: %v", err)
return
}

// Save config file to file system
confFile := cmd.ZarbConfigPath(workingDir)
if err := conf.SaveToFile(confFile); err != nil {
cmd.PrintErrorMsg("Failed to write config file: %v", err)
return
}

err = wallet.UpdatePassword("", password)
if err != nil {
cmd.PrintErrorMsg("Failed to update wallet password: %v", err)
return
}

// Save wallet
err = wallet.Save()
if err != nil {
cmd.PrintErrorMsg("Failed to save wallet: %v", err)
Expand Down
42 changes: 31 additions & 11 deletions cmd/gtk/startup_assistant.go
Original file line number Diff line number Diff line change
Expand Up @@ -317,25 +317,45 @@ Now you are ready to start the node!`
rewardAddr, err := defaultWallet.MakeNewAddress("", "Reward address")
errorCheck(err)

var gen *genesis.Genesis
confFile := cmd.ZarbConfigPath(workingDir)

if testnet {
gen = genesis.Testnet()

// Save config for testnet
if err := config.SaveTestnetConfig(confFile, rewardAddr); err != nil {
cmd.PrintErrorMsg("Failed to write config file: %v", err)
return
}
} else {
panic("not yet!")
// gen = genesis.Mainnet()

// // Save config for mainnet
// if err := config.SaveMainnetConfig(confFile, rewardAddr); err != nil {
// cmd.PrintErrorMsg("Failed to write config file: %v", err)
// return
// }
}

// Save genesis file
genFile := cmd.ZarbGenesisPath(workingDir)
err = gen.SaveToFile(genFile)
errorCheck(err)

// To make process faster we set password after generating addresses
walletPassword, err := passwordEntry.GetText()
errorCheck(err)

err = defaultWallet.UpdatePassword("", walletPassword)
errorCheck(err)
err = defaultWallet.Save()
errorCheck(err)
err = genesis.Testnet().SaveToFile(cmd.ZarbGenesisPath(workingDir))
errorCheck(err)

conf := config.DefaultConfig()
conf.Network.Name = "perdana-testnet"
conf.Network.Bootstrap.Addresses = []string{"/ip4/172.104.169.94/tcp/21777/p2p/12D3KooWNYD4bB82YZRXv6oNyYPwc5ozabx2epv75ATV3D8VD3Mq"}
conf.Network.Bootstrap.MinThreshold = 4
conf.Network.Bootstrap.MaxThreshold = 8
conf.State.RewardAddress = rewardAddr
err = conf.SaveToFile(cmd.ZarbConfigPath(workingDir))
// Save wallet
err = defaultWallet.Save()
errorCheck(err)

// Done! showing the node information
successful = true
nodeInfo := fmt.Sprintf("Working directory:\n %s\n\n", workingDir)
nodeInfo += fmt.Sprintf("Validator address:\n %s\n\n", valAddr)
Expand Down
129 changes: 75 additions & 54 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@ package config

import (
"bytes"
"encoding/json"
_ "embed"
"fmt"
"io/ioutil"
"strings"

toml "github.com/pelletier/go-toml"
"github.com/zarbchain/zarb-go/consensus"
"github.com/zarbchain/zarb-go/errors"
"github.com/zarbchain/zarb-go/logger"
"github.com/zarbchain/zarb-go/network"
"github.com/zarbchain/zarb-go/state"
Expand All @@ -21,93 +21,114 @@ import (
"github.com/zarbchain/zarb-go/www/http"
)

//go:embed example_config.toml
var exampleConfigBytes []byte

type Config struct {
State *state.Config `toml:"" comment:"State contains the state of the blockchain."`
Store *store.Config `toml:"" comment:"Store which write and store the blockchin data using golevel db. "`
TxPool *txpool.Config `toml:"" comment:"TxPool is pool of unconfirmed transaction."`
Consensus *consensus.Config `toml:"" comment:"Consensus configuration."`
Network *network.Config `toml:"" comment:"Network contains all details of network configuration. Zarb uses lip2p protocol."`
Logger *logger.Config `toml:"" comment:"Logger contains Output level for logging."`
Sync *sync.Config `toml:"" comment:"Sync is used for peer to peer connection and synchronizing blockchain and it also contains monkier and its details."`
Capnp *capnp.Config `toml:"" comment:"Cap’n Proto is an insanely fast data interchange format and capability-based RPC system."`
HTTP *http.Config `toml:"" comment:"Http configuration."`
GRPC *grpc.Config `toml:"" comment:"GRPC configuration."`
State *state.Config `toml:"state"`
Store *store.Config `toml:"store"`
Network *network.Config `toml:"network"`
Sync *sync.Config `toml:"sync"`
TxPool *txpool.Config `toml:"tx_pool"`
Consensus *consensus.Config `toml:"consensus"`
Logger *logger.Config `toml:"logger"`
GRPC *grpc.Config `toml:"grpc"`
Capnp *capnp.Config `toml:"capnp"`
HTTP *http.Config `toml:"http"`
}

func DefaultConfig() *Config {
conf := &Config{
State: state.DefaultConfig(),
Store: store.DefaultConfig(),
TxPool: txpool.DefaultConfig(),
Consensus: consensus.DefaultConfig(),
Network: network.DefaultConfig(),
Sync: sync.DefaultConfig(),
TxPool: txpool.DefaultConfig(),
Consensus: consensus.DefaultConfig(),
Logger: logger.DefaultConfig(),
GRPC: grpc.DefaultConfig(),
Capnp: capnp.DefaultConfig(),
HTTP: http.DefaultConfig(),
GRPC: grpc.DefaultConfig(),
}

return conf
}

func FromTOML(t string) (*Config, error) {
func SaveMainnetConfig(path, rewardAddr string) error {
exampleConfig := string(exampleConfigBytes)

exampleConfig = strings.Replace(exampleConfig, "## reward_address = \"\"",
fmt.Sprintf(" reward_address = \"%s\"", rewardAddr), 1)

return util.WriteFile(path, []byte(exampleConfig))
}

func SaveTestnetConfig(path, rewardAddr string) error {
conf := DefaultConfig()
conf.Network.Name = "zarb-testnet"
conf.Network.Listens = []string{"/ip4/0.0.0.0/tcp/21777", "/ip6/::/tcp/21777"}
conf.Network.Bootstrap.Addresses = []string{"/ip4/172.104.169.94/tcp/21777/p2p/12D3KooWNYD4bB82YZRXv6oNyYPwc5ozabx2epv75ATV3D8VD3Mq"}
conf.Network.Bootstrap.MinThreshold = 4
conf.Network.Bootstrap.MaxThreshold = 8
conf.GRPC.Enable = true
conf.GRPC.Listen = "[::]:9090"
conf.GRPC.Gateway.Enable = true
conf.GRPC.Gateway.Listen = "[::]:80"
conf.Capnp.Enable = true
conf.Capnp.Listen = "[::]:37621"
conf.HTTP.Enable = true
conf.HTTP.Listen = "[::]:8080"
conf.State.RewardAddress = rewardAddr

return util.WriteFile(path, conf.toTOML())
}

if err := toml.Unmarshal([]byte(t), conf); err != nil {
return nil, err
}
return conf, nil
func SaveLocalnetConfig(path, rewardAddr string) error {
conf := DefaultConfig()
conf.Network.Name = "zarb-localnet"
conf.Network.Listens = []string{}
conf.Network.Bootstrap.Addresses = []string{}
conf.Network.Bootstrap.MinThreshold = 4
conf.Network.Bootstrap.MaxThreshold = 8
conf.GRPC.Enable = true
conf.GRPC.Listen = "[::]:9090"
conf.GRPC.Gateway.Enable = true
conf.GRPC.Gateway.Listen = "[::]:8080"
conf.Capnp.Enable = true
conf.Capnp.Listen = "[::]:37621"
conf.HTTP.Enable = true
conf.HTTP.Listen = "[::]:8081"
conf.State.RewardAddress = rewardAddr

return util.WriteFile(path, conf.toTOML())
}

func (conf *Config) ToTOML() ([]byte, error) {
func (conf *Config) toTOML() []byte {
buf := new(bytes.Buffer)
encoder := toml.NewEncoder(buf)
encoder.Order(toml.OrderPreserve)
err := encoder.Encode(conf)
if err != nil {
return nil, err
}

return buf.Bytes(), nil
}

func FromJSON(t string) (*Config, error) {
conf := DefaultConfig()
if err := json.Unmarshal([]byte(t), conf); err != nil {
return nil, err
panic(err)
}
return conf, nil
}

func (conf *Config) ToJSON() ([]byte, error) {
return json.MarshalIndent(conf, "", " ")
return buf.Bytes()
}

func LoadFromFile(file string) (*Config, error) {
dat, err := ioutil.ReadFile(file)
data, err := ioutil.ReadFile(file)
if err != nil {
return nil, err
}

if strings.HasSuffix(file, "toml") {
return FromTOML(string(dat))
} else if strings.HasSuffix(file, "json") {
return FromJSON(string(dat))
}

return nil, errors.Errorf(errors.ErrInvalidConfig, "invalid suffix for the config file")
}

func (conf *Config) SaveToFile(file string) error {
var dat []byte
if strings.HasSuffix(file, "toml") {
dat, _ = conf.ToTOML()
} else if strings.HasSuffix(file, "json") {
dat, _ = conf.ToJSON()
} else {
return errors.Errorf(errors.ErrInvalidConfig, "invalid suffix for the config file")
conf := DefaultConfig()
buf := bytes.NewBuffer(data)
decoder := toml.NewDecoder(buf)
decoder.Strict(true)
if err := decoder.Decode(conf); err != nil {
return nil, err
}
return util.WriteFile(file, dat)
return conf, nil
}

func (conf *Config) SanityCheck() error {
Expand Down
Loading

0 comments on commit f414ed6

Please sign in to comment.