Skip to content

Commit

Permalink
feat(sync): adding remote address to the peer info
Browse files Browse the repository at this point in the history
  • Loading branch information
themantre committed Nov 8, 2023
1 parent d2c7b65 commit afe1286
Show file tree
Hide file tree
Showing 30 changed files with 431 additions and 193 deletions.
16 changes: 13 additions & 3 deletions cmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -340,14 +340,24 @@ func StartNode(workingDir string, passwordFetcher func(*wallet.Wallet) (string,
crypto.XPrivateKeyHRP = "txsecret"
}

var defConf *config.Config
switch gen.ChainType() {
case genesis.Mainnet:
panic("not yet implemented!")
case genesis.Testnet:
defConf = config.DefaultConfigTestnet()
case genesis.Localnet:
defConf = config.DefaultConfigLocalnet()
}

confPath := PactusConfigPath(workingDir)
conf, err := config.LoadFromFile(confPath, true)
conf, err := config.LoadFromFile(confPath, true, defConf)
if err != nil {
PrintWarnMsgf("Unable to load the config: %s", err)
PrintInfoMsgf("Attempting to restore the config to the default values...")

// First, try to open the old config file in non-strict mode
confBack, err := config.LoadFromFile(confPath, false)
confBack, err := config.LoadFromFile(confPath, false, defConf)
if err != nil {
return nil, nil, err
}
Expand Down Expand Up @@ -381,7 +391,7 @@ func StartNode(workingDir string, passwordFetcher func(*wallet.Wallet) (string,
}

PrintSuccessMsgf("Config restored to the default values")
conf, _ = config.LoadFromFile(confPath, true) // This time it should be OK
conf, _ = config.LoadFromFile(confPath, true, defConf) // This time it should be OK
}

err = conf.BasicCheck()
Expand Down
60 changes: 40 additions & 20 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ func (conf *NodeConfig) BasicCheck() error {
return nil
}

func DefaultConfig() *Config {
func defaultConfig() *Config {
conf := &Config{
Node: DefaultNodeConfig(),
Store: store.DefaultConfig(),
Expand All @@ -91,18 +91,15 @@ func DefaultConfig() *Config {
return conf
}

func SaveMainnetConfig(path string, numValidators int) error {
conf := string(exampleConfigBytes)
conf = strings.Replace(conf, "%num_validators%",
fmt.Sprintf("%v", numValidators), 1)

return util.WriteFile(path, []byte(conf))
func DefaultConfigMainnet() *Config {
conf := defaultConfig()
// TO BE DEFINED
return conf
}

//nolint:lll // long multi-address
func SaveTestnetConfig(path string, numValidators int) error {
conf := DefaultConfig()
conf.Node.NumValidators = numValidators
func DefaultConfigTestnet() *Config {
conf := defaultConfig()
conf.Network.ListenAddrStrings = []string{
"/ip4/0.0.0.0/tcp/21777", "/ip4/0.0.0.0/udp/21777/quic-v1",
"/ip6/::/tcp/21777", "/ip6/::/udp/21777/quic-v1",
Expand All @@ -119,14 +116,16 @@ func SaveTestnetConfig(path string, numValidators int) error {
"/dns/pactus.nodesync.top/tcp/21777/p2p/12D3KooWP25ejVsd7cL5DvWAPwEu4JTUwnPniHBf4w93tgSezVt8", // NodeSync.Top ([email protected])
"/ip4/95.217.89.202/tcp/21777/p2p/12D3KooWMsi5oYkbbpyyXctmPXzF8UZu2pCvKPRZGyvymhN9BzTD", // CodeBlockLabs ([email protected])
}
conf.Network.MinConns = 16
conf.Network.MaxConns = 32
conf.Network.EnableNAT = false
conf.Network.EnableRelay = false
conf.Network.RelayAddrStrings = []string{
"/ip4/139.162.153.10/tcp/4002/p2p/12D3KooWNR79jqHVVNhNVrqnDbxbJJze4VjbEsBjZhz6mkvinHAN",
"/ip4/188.121.102.178/tcp/4002/p2p/12D3KooWCRHn8vjrKNBEQcut8uVCYX5q77RKidPaE6iMK31qEVHb",
}
conf.Network.MinConns = 16
conf.Network.MaxConns = 32
conf.Network.EnableNAT = false
conf.Network.EnableRelay = true
conf.Network.NetworkName = "pactus-testnet"
conf.Network.DefaultPort = 21777
conf.GRPC.Enable = true
conf.GRPC.Listen = "[::]:50052"
conf.GRPC.Gateway.Enable = true
Expand All @@ -136,18 +135,19 @@ func SaveTestnetConfig(path string, numValidators int) error {
conf.Nanomsg.Enable = false
conf.Nanomsg.Listen = "tcp://127.0.0.1:40799"

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

func SaveLocalnetConfig(path string, numValidators int) error {
conf := DefaultConfig()
conf.Node.NumValidators = numValidators
func DefaultConfigLocalnet() *Config {
conf := defaultConfig()
conf.Network.ListenAddrStrings = []string{}
conf.Network.EnableRelay = false
conf.Network.EnableNAT = false
conf.Network.BootstrapAddrStrings = []string{}
conf.Network.MinConns = 0
conf.Network.MaxConns = 0
conf.Network.NetworkName = "pactus-localnet"
conf.Network.DefaultPort = 21666
conf.GRPC.Enable = true
conf.GRPC.Listen = "[::]:0"
conf.GRPC.Gateway.Enable = true
Expand All @@ -157,6 +157,26 @@ func SaveLocalnetConfig(path string, numValidators int) error {
conf.Nanomsg.Enable = true
conf.Nanomsg.Listen = "tcp://127.0.0.1:0"

return conf
}

func SaveMainnetConfig(path string, numValidators int) error {
conf := string(exampleConfigBytes)
conf = strings.Replace(conf, "%num_validators%",
fmt.Sprintf("%v", numValidators), 1)

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

func SaveTestnetConfig(path string, numValidators int) error {
conf := DefaultConfigTestnet()
conf.Node.NumValidators = numValidators
return util.WriteFile(path, conf.toTOML())
}

func SaveLocalnetConfig(path string, numValidators int) error {
conf := DefaultConfigLocalnet()
conf.Node.NumValidators = numValidators
return util.WriteFile(path, conf.toTOML())
}

Expand All @@ -172,13 +192,13 @@ func (conf *Config) toTOML() []byte {
return buf.Bytes()
}

func LoadFromFile(file string, strict bool) (*Config, error) {
func LoadFromFile(file string, strict bool, defaultConfig *Config) (*Config, error) {
data, err := os.ReadFile(file)
if err != nil {
return nil, err
}

conf := DefaultConfig()
conf := defaultConfig
buf := bytes.NewBuffer(data)
decoder := toml.NewDecoder(buf)
decoder.Strict(strict)
Expand Down
24 changes: 16 additions & 8 deletions config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ func TestSaveMainnetConfig(t *testing.T) {
path := util.TempFilePath()
assert.NoError(t, SaveMainnetConfig(path, 7))

conf, err := LoadFromFile(path, true)
defConf := DefaultConfigMainnet()
conf, err := LoadFromFile(path, true, defConf)
assert.NoError(t, err)

assert.NoError(t, conf.BasicCheck())
Expand All @@ -23,37 +24,44 @@ func TestSaveTestnetConfig(t *testing.T) {
path := util.TempFilePath()
assert.NoError(t, SaveTestnetConfig(path, 7))

conf, err := LoadFromFile(path, true)
defConf := DefaultConfigTestnet()
conf, err := LoadFromFile(path, true, defConf)
assert.NoError(t, err)

assert.NoError(t, conf.BasicCheck())
assert.Equal(t, conf.Network.NetworkName, "pactus-testnet")
assert.Equal(t, conf.Network.DefaultPort, 21777)
}

func TestSaveLocalnetConfig(t *testing.T) {
path := util.TempFilePath()
assert.NoError(t, SaveLocalnetConfig(path, 4))

conf, err := LoadFromFile(path, true)
defConf := DefaultConfigLocalnet()
conf, err := LoadFromFile(path, true, defConf)
assert.NoError(t, err)

assert.NoError(t, conf.BasicCheck())
assert.Empty(t, conf.Network.ListenAddrStrings)
assert.Empty(t, conf.Network.RelayAddrStrings)
assert.Equal(t, conf.Network.DefaultPort, 21777)
assert.Equal(t, conf.Network.NetworkName, "pactus-localnet")
assert.Equal(t, conf.Network.DefaultPort, 21666)
}

func TestLoadFromFile(t *testing.T) {
path := util.TempFilePath()
_, err := LoadFromFile(path, true)
defConf := DefaultConfigTestnet()

_, err := LoadFromFile(path, true, defConf)
assert.Error(t, err, "not exists")

assert.NoError(t, util.WriteFile(path, []byte(`foo = "bar"`)))
_, err = LoadFromFile(path, true)
_, err = LoadFromFile(path, true, defConf)
assert.Error(t, err, "unknown field")

_, err = LoadFromFile(path, false)
conf, err := LoadFromFile(path, false, defConf)
assert.NoError(t, err)
assert.Equal(t, conf, defConf)
}

func TestExampleConfig(t *testing.T) {
Expand All @@ -69,7 +77,7 @@ func TestExampleConfig(t *testing.T) {
}
}

defaultConf := DefaultConfig()
defaultConf := DefaultConfigMainnet()
defaultToml := string(defaultConf.toTOML())

exampleToml = strings.ReplaceAll(exampleToml, "%num_validators%", "7")
Expand Down
4 changes: 2 additions & 2 deletions config/example_config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,15 @@
## public_addr = ""

# `listen_addrs` specifies the addresses and ports where the node will listen for incoming connections from other nodes.
## listen_addrs = ["/ip4/0.0.0.0/tcp/21888", "/ip6/::/tcp/21888", "/ip4/0.0.0.0/udp/21888/quic-v1", "/ip6/::/udp/21888/quic-v1"]
## listen_addrs = []

# `relay_addrs` provides the necessary relay addresses. These should be specified if 'enable_relay' is 'true'.
# Note: this parameter will be ignored if 'enable_relay' is 'false'.
## relay_addrs = []

# `bootstrap_addrs` is a list of peer addresses needed for peer discovery.
# These addresses are used by the Pactus node to discover and connect to other peers on the network.
## bootstrap_addrs = ["/ip4/172.104.46.145/tcp/21777/p2p/12D3KooWNYD4bB82YZRXv6oNyYPwc5ozabx2epv75ATV3D8VD3Mq"]
## bootstrap_addrs = []

# `min_connections` is the minimum number of connections that the Pactus node should maintain.
# Default is 16
Expand Down
26 changes: 0 additions & 26 deletions genesis/genesis.go
Original file line number Diff line number Diff line change
Expand Up @@ -187,29 +187,3 @@ func (gen *Genesis) ChainType() ChainType {

return Localnet
}

func (gen *Genesis) NetworkName() string {
switch gen.ChainType() {
case Mainnet:
return "pactus"
case Testnet:
return "pactus-testnet"
case Localnet:
return "pactus-localnet"
default:
return "unknown"
}
}

func (gen *Genesis) DefaultPort() int {
switch gen.ChainType() {
case Mainnet:
return 21888
case Testnet:
return 21777
case Localnet:
return 21666
default:
return 0
}
}
5 changes: 0 additions & 5 deletions genesis/genesis_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,6 @@ func TestGenesisTestNet(t *testing.T) {
assert.Equal(t, gen.Params().BondInterval, uint32(120))
assert.Equal(t, gen.ChainType(), genesis.Testnet)
assert.Equal(t, gen.TotalSupply(), int64(42*1e15))
assert.Equal(t, gen.NetworkName(), "pactus-testnet")
assert.Equal(t, gen.DefaultPort(), 21777)
}

func TestCheckGenesisAccountAndValidator(t *testing.T) {
Expand All @@ -87,7 +85,4 @@ func TestCheckGenesisAccountAndValidator(t *testing.T) {
for i, val := range gen.Validators() {
assert.Equal(t, val.Hash(), vals[i].Hash())
}

assert.Equal(t, gen.NetworkName(), "pactus-localnet")
assert.Equal(t, gen.DefaultPort(), 21666)
}
38 changes: 9 additions & 29 deletions network/config.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
package network

import (
"fmt"

lp2ppeer "github.com/libp2p/go-libp2p/core/peer"
"github.com/multiformats/go-multiaddr"
"github.com/pactus-project/pactus/util/errors"
Expand All @@ -22,37 +20,19 @@ type Config struct {
EnableMetrics bool `toml:"enable_metrics"`
ForcePrivateNetwork bool `toml:"force_private_network"`
Bootstrapper bool `toml:"bootstrapper"` // TODO: detect it automatically
DefaultPort int `toml:"-"`

// Private configs
NetworkName string `toml:"-"`
DefaultPort int `toml:"-"`
}

func DefaultConfig() *Config {
nodes := []struct {
ip string
port string
id string
}{
{
ip: "172.104.46.145",
port: "21777",
id: "12D3KooWNYD4bB82YZRXv6oNyYPwc5ozabx2epv75ATV3D8VD3Mq",
},
}

bootstrapAddrs := []string{}
for _, n := range nodes {
bootstrapAddrs = append(bootstrapAddrs,
fmt.Sprintf("/ip4/%s/tcp/%s/p2p/%s", n.ip, n.port, n.id))
}

return &Config{
NetworkKey: "network_key",
PublicAddrString: "",
ListenAddrStrings: []string{
"/ip4/0.0.0.0/tcp/21888", "/ip6/::/tcp/21888",
"/ip4/0.0.0.0/udp/21888/quic-v1", "/ip6/::/udp/21888/quic-v1",
},
NetworkKey: "network_key",
PublicAddrString: "",
ListenAddrStrings: []string{},
RelayAddrStrings: []string{},
BootstrapAddrStrings: bootstrapAddrs,
BootstrapAddrStrings: []string{},
MinConns: 16,
MaxConns: 32,
EnableNAT: false,
Expand All @@ -61,7 +41,7 @@ func DefaultConfig() *Config {
EnableMetrics: false,
ForcePrivateNetwork: false,
Bootstrapper: false,
DefaultPort: 21777,
DefaultPort: 21888,
}
}

Expand Down
2 changes: 1 addition & 1 deletion network/gossip_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ func TestJoinConsensusTopic(t *testing.T) {
}

func TestInvalidTopic(t *testing.T) {
net, err := NewNetwork("test", testConfig())
net, err := NewNetwork(testConfig())
assert.NoError(t, err)

msg := []byte("test-invalid-topic")
Expand Down
4 changes: 3 additions & 1 deletion network/interface.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,9 @@ func (*StreamMessage) Type() EventType {

// ConnectEvent represents a peer connection event.
type ConnectEvent struct {
PeerID lp2pcore.PeerID
PeerID lp2pcore.PeerID
RemoteAddress string
SupportStream bool
}

func (*ConnectEvent) Type() EventType {
Expand Down
Loading

0 comments on commit afe1286

Please sign in to comment.