From 390f8009797ceb9560500c58adcd9008d2478ead Mon Sep 17 00:00:00 2001 From: ragnarok87 Date: Wed, 24 May 2023 19:19:29 +0800 Subject: [PATCH] fix: defining ChainType in genesis to detect the type of network --- INSTALL.md | 9 ---- cmd/cmd.go | 50 ++++++++++++---------- cmd/daemon/init.go | 9 +++- cmd/daemon/start.go | 11 +---- cmd/gtk/assets/ui/widget_node.ui | 48 +++++++++++++++++---- cmd/gtk/main.go | 62 +++++++++------------------- cmd/gtk/main_window.go | 5 +-- cmd/gtk/startup_assistant.go | 11 ++--- cmd/gtk/widget_node.go | 6 ++- cmd/wallet/create.go | 5 ++- config/config.go | 20 --------- config/config_test.go | 11 ----- genesis/genesis.go | 33 ++++++++++++++- genesis/genesis_test.go | 2 +- genesis/testnet.go | 2 +- node/node.go | 6 ++- state/facade.go | 3 +- state/mock.go | 9 ++-- state/state.go | 4 +- state/state_test.go | 2 +- sync/firewall/firewall.go | 18 +++++--- sync/firewall/firewall_test.go | 29 ++++++++----- sync/handler_blocks_request_test.go | 2 +- sync/handler_blocks_response_test.go | 1 - sync/handler_hello.go | 4 +- sync/handler_hello_test.go | 8 ++-- sync/sync.go | 13 +++--- sync/sync_test.go | 2 +- types/param/param.go | 8 ---- wallet/store.go | 15 +++---- wallet/wallet.go | 31 +++++++------- wallet/wallet_test.go | 9 ++-- www/grpc/server.go | 8 +--- www/grpc/wallet.go | 5 ++- 34 files changed, 239 insertions(+), 222 deletions(-) diff --git a/INSTALL.md b/INSTALL.md index 4f5eadb9f..e94c2cf2c 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -59,15 +59,6 @@ and then start the node: ./pactus-daemon start -w= ``` -### Local net - -You can create a local node with one validator to test Pactus on your machine: - - ```text - ./pactus-daemon init -w= --localnet - ./pactus-daemon start -w= - ``` - ## What is pactus-wallet? Pactus wallet is a native wallet in the Pactus blockchain that lets users easily manage diff --git a/cmd/cmd.go b/cmd/cmd.go index 3418f0dc3..19ca44b27 100644 --- a/cmd/cmd.go +++ b/cmd/cmd.go @@ -17,6 +17,7 @@ import ( "github.com/pactus-project/pactus/config" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/genesis" + "github.com/pactus-project/pactus/node" "github.com/pactus-project/pactus/wallet" ) @@ -253,16 +254,12 @@ func TrapSignal(cleanupFunc func()) { }() } -func CreateNode(numValidators int, testnet bool, workingDir string, +func CreateNode(numValidators int, chain genesis.ChainType, workingDir string, mnemonic string, walletPassword string) ( validatorAddrs []string, rewardAddrs []string, err error) { // To make process faster, we update the password after creating the addresses - network := wallet.NetworkMainNet - if testnet { - network = wallet.NetworkTestNet - } walletPath := PactusDefaultWalletPath(workingDir) - wallet, err := wallet.Create(walletPath, mnemonic, "", network) + wallet, err := wallet.Create(walletPath, mnemonic, "", chain) if err != nil { return nil, nil, err } @@ -286,8 +283,9 @@ func CreateNode(numValidators int, testnet bool, workingDir string, confPath := PactusConfigPath(workingDir) genPath := PactusGenesisPath(workingDir) - if testnet { - err = genesis.Testnet().SaveToFile(genPath) + switch chain { + case genesis.Testnet: + err = genesis.TestnetGenesis().SaveToFile(genPath) if err != nil { return nil, nil, err } @@ -296,7 +294,7 @@ func CreateNode(numValidators int, testnet bool, workingDir string, if err != nil { return nil, nil, err } - } else { + case genesis.Mainnet: panic("not yet!") } @@ -313,14 +311,14 @@ func CreateNode(numValidators int, testnet bool, workingDir string, return validatorAddrs, rewardAddrs, nil } -func GetKeys(workingDir string, passwordFetcher func(*wallet.Wallet) (string, bool)) ( - *genesis.Genesis, *config.Config, []crypto.Signer, []crypto.Address, *wallet.Wallet, error) { +func StartNode(workingDir string, passwordFetcher func(*wallet.Wallet) (string, bool)) ( + *node.Node, *wallet.Wallet, error) { gen, err := genesis.LoadFromFile(PactusGenesisPath(workingDir)) if err != nil { - return nil, nil, nil, nil, nil, err + return nil, nil, err } - if gen.Params().IsTestnet() { + if gen.ChainType().IsTestnet() { crypto.AddressHRP = "tpc" crypto.PublicKeyHRP = "tpublic" crypto.PrivateKeyHRP = "tsecret" @@ -330,24 +328,24 @@ func GetKeys(workingDir string, passwordFetcher func(*wallet.Wallet) (string, bo conf, err := config.LoadFromFile(PactusConfigPath(workingDir)) if err != nil { - return nil, nil, nil, nil, nil, err + return nil, nil, err } err = conf.SanityCheck() if err != nil { - return nil, nil, nil, nil, nil, err + return nil, nil, err } walletPath := PactusDefaultWalletPath(workingDir) wallet, err := wallet.Open(walletPath, true) if err != nil { - return nil, nil, nil, nil, nil, err + return nil, nil, err } addrLabels := wallet.AddressLabels() // Create signers if len(addrLabels) < conf.Node.NumValidators { - return nil, nil, nil, nil, nil, fmt.Errorf("not enough addresses in wallet") + return nil, nil, fmt.Errorf("not enough addresses in wallet") } validatorAddrs := make([]string, conf.Node.NumValidators) for i := 0; i < conf.Node.NumValidators; i++ { @@ -356,11 +354,11 @@ func GetKeys(workingDir string, passwordFetcher func(*wallet.Wallet) (string, bo signers := make([]crypto.Signer, conf.Node.NumValidators) password, ok := passwordFetcher(wallet) if !ok { - return nil, nil, nil, nil, nil, fmt.Errorf("aborted") + return nil, nil, fmt.Errorf("aborted") } prvKeys, err := wallet.PrivateKeys(password, validatorAddrs) if err != nil { - return nil, nil, nil, nil, nil, err + return nil, nil, err } for i, key := range prvKeys { signers[i] = crypto.NewSigner(key) @@ -374,7 +372,7 @@ func GetKeys(workingDir string, passwordFetcher func(*wallet.Wallet) (string, bo } } else { if len(addrLabels) < 2*conf.Node.NumValidators { - return nil, nil, nil, nil, nil, fmt.Errorf("not enough addresses in wallet") + return nil, nil, fmt.Errorf("not enough addresses in wallet") } for i := 0; i < conf.Node.NumValidators; i++ { rewardAddrs[i], _ = @@ -382,5 +380,15 @@ func GetKeys(workingDir string, passwordFetcher func(*wallet.Wallet) (string, bo } } - return gen, conf, signers, rewardAddrs, wallet, nil + node, err := node.NewNode(gen, conf, signers, rewardAddrs) + if err != nil { + return nil, nil, err + } + + err = node.Start() + if err != nil { + return nil, nil, err + } + + return node, wallet, nil } diff --git a/cmd/daemon/init.go b/cmd/daemon/init.go index 45b294e4e..07f98b596 100644 --- a/cmd/daemon/init.go +++ b/cmd/daemon/init.go @@ -6,6 +6,7 @@ import ( cli "github.com/jawher/mow.cli" "github.com/pactus-project/pactus/cmd" + "github.com/pactus-project/pactus/genesis" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/wallet" ) @@ -54,7 +55,11 @@ func Init() func(c *cli.Cmd) { cmd.PrintInfoMsg("You can define validators based on the amount of coins you want to stake.") numValidators := cmd.PromptInputWithRange("Number of Validators", 7, 1, 32) - validatorAddrs, rewardAddrs, err := cmd.CreateNode(numValidators, *testnetOpt, workingDir, mnemonic, password) + network := genesis.Mainnet + if *testnetOpt { + network = genesis.Testnet + } + validatorAddrs, rewardAddrs, err := cmd.CreateNode(numValidators, network, workingDir, mnemonic, password) cmd.FatalErrorCheck(err) cmd.PrintLine() @@ -69,6 +74,8 @@ func Init() func(c *cli.Cmd) { cmd.PrintInfoMsg("%v- %s", i+1, addr) } + cmd.PrintLine() + cmd.PrintInfoMsgBold("Network: %v", network.String()) cmd.PrintLine() cmd.PrintSuccessMsg("A pactus node is successfully initialized at %v", workingDir) cmd.PrintLine() diff --git a/cmd/daemon/start.go b/cmd/daemon/start.go index e310b876b..4bfdbf25b 100644 --- a/cmd/daemon/start.go +++ b/cmd/daemon/start.go @@ -10,7 +10,6 @@ import ( cli "github.com/jawher/mow.cli" "github.com/pactus-project/pactus/cmd" - "github.com/pactus-project/pactus/node" "github.com/pactus-project/pactus/wallet" ) @@ -70,18 +69,10 @@ func Start() func(c *cli.Cmd) { } return password, true } - gen, conf, signers, rewardAddrs, _, err := cmd.GetKeys( + node, _, err := cmd.StartNode( workingDir, passwordFetcher) cmd.FatalErrorCheck(err) - cmd.PrintLine() - - node, err := node.NewNode(gen, conf, signers, rewardAddrs) - cmd.FatalErrorCheck(err) - - err = node.Start() - cmd.FatalErrorCheck(err) - cmd.TrapSignal(func() { node.Stop() cmd.PrintInfoMsg("Exiting ...") diff --git a/cmd/gtk/assets/ui/widget_node.ui b/cmd/gtk/assets/ui/widget_node.ui index 9a7eb96e6..509f4e0c3 100644 --- a/cmd/gtk/assets/ui/widget_node.ui +++ b/cmd/gtk/assets/ui/widget_node.ui @@ -48,7 +48,7 @@ 0.019999999552965164 in - + 400 True @@ -104,7 +104,7 @@ 0 - 1 + 2 @@ -118,7 +118,7 @@ 1 - 1 + 2 @@ -133,7 +133,7 @@ 0 - 2 + 3 @@ -147,7 +147,7 @@ 1 - 2 + 3 @@ -162,7 +162,7 @@ 0 - 3 + 4 @@ -176,7 +176,7 @@ 1 - 3 + 4 @@ -191,7 +191,7 @@ 0 - 4 + 5 @@ -204,7 +204,37 @@ 1 - 4 + 5 + + + + + True + False + start + start + True + True + Netwotk: + + + 0 + 1 + + + + + True + False + start + start + True + True + True + + + 1 + 1 diff --git a/cmd/gtk/main.go b/cmd/gtk/main.go index 1ff3070b8..120260e02 100644 --- a/cmd/gtk/main.go +++ b/cmd/gtk/main.go @@ -4,16 +4,15 @@ package main import ( "flag" + "fmt" "log" "os" "path/filepath" - "time" "github.com/gotk3/gotk3/glib" "github.com/gotk3/gotk3/gtk" "github.com/pactus-project/pactus/cmd" - "github.com/pactus-project/pactus/config" - "github.com/pactus-project/pactus/node" + "github.com/pactus-project/pactus/genesis" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/wallet" ) @@ -45,8 +44,12 @@ func main() { } // If node is not initialized yet - if !util.PathExists(cmd.PactusDefaultWalletPath(workingDir)) { - if !startupAssistant(workingDir, *testnetOpt) { + if !util.PathExists(workingDir) { + network := genesis.Mainnet + if *testnetOpt { + network = genesis.Testnet + } + if !startupAssistant(workingDir, network) { return } } @@ -76,34 +79,6 @@ func main() { os.Exit(app.Run(nil)) } -func startingNode(workingDir string) (*node.Node, *config.Config, *time.Time, *wallet.Wallet, error) { - passwordFetcher := func(wallet *wallet.Wallet) (string, bool) { - if *passwordOpt != "" { - return *passwordOpt, true - } - return getWalletPassword(wallet) - } - - gen, conf, signers, rewardAddrs, wallet, err := cmd.GetKeys(workingDir, passwordFetcher) - if err != nil { - return nil, nil, nil, nil, err - } - - node, err := node.NewNode(gen, conf, signers, rewardAddrs) - if err != nil { - return nil, nil, nil, nil, err - } - //TODO: log to file - - err = node.Start() - if err != nil { - return nil, nil, nil, nil, err - } - - genTime := gen.GenesisTime() - return node, conf, &genTime, wallet, nil -} - func start(workingDir string, app *gtk.Application) { // change working directory if err := os.Chdir(workingDir); err != nil { @@ -111,24 +86,27 @@ func start(workingDir string, app *gtk.Application) { return } - // TODO: Get genTime from the node or state - node, conf, genTime, wallet, err := startingNode(workingDir) + passwordFetcher := func(wallet *wallet.Wallet) (string, bool) { + if *passwordOpt != "" { + return *passwordOpt, true + } + return getWalletPassword(wallet) + } + + node, wallet, err := cmd.StartNode(workingDir, passwordFetcher) fatalErrorCheck(err) - // TODO - // No showing the main window - if err != nil { - return - } + grpcAddr := node.GRPC().Address() + fmt.Printf("connect wallet to grpc server: %s\n", grpcAddr) - err = wallet.Connect(conf.GRPC.Listen) + err = wallet.Connect(grpcAddr) fatalErrorCheck(err) nodeModel := newNodeModel(node) walletModel := newWalletModel(wallet) // building main window - win := buildMainWindow(nodeModel, walletModel, *genTime) + win := buildMainWindow(nodeModel, walletModel) // Show the Window and all of its components. win.Show() diff --git a/cmd/gtk/main_window.go b/cmd/gtk/main_window.go index 2f9506fef..785557e3b 100644 --- a/cmd/gtk/main_window.go +++ b/cmd/gtk/main_window.go @@ -4,7 +4,6 @@ package main import ( _ "embed" - "time" "github.com/gotk3/gotk3/gtk" ) @@ -19,7 +18,7 @@ type mainWindow struct { widgetWallet *widgetWallet } -func buildMainWindow(nodeModel *nodeModel, walletModel *walletModel, genesisTime time.Time) *mainWindow { +func buildMainWindow(nodeModel *nodeModel, walletModel *walletModel) *mainWindow { // Get the GtkBuilder UI definition in the glade file. builder, err := gtk.BuilderNewFromString(string(uiMainWindow)) fatalErrorCheck(err) @@ -28,7 +27,7 @@ func buildMainWindow(nodeModel *nodeModel, walletModel *walletModel, genesisTime boxNode := getBoxObj(builder, "id_box_node") boxDefaultWallet := getBoxObj(builder, "id_box_default_wallet") - widgetNode, err := buildWidgetNode(nodeModel, genesisTime) + widgetNode, err := buildWidgetNode(nodeModel) fatalErrorCheck(err) widgetWallet, err := buildWidgetWallet(walletModel) diff --git a/cmd/gtk/startup_assistant.go b/cmd/gtk/startup_assistant.go index 227fc2763..ae89518f4 100644 --- a/cmd/gtk/startup_assistant.go +++ b/cmd/gtk/startup_assistant.go @@ -11,6 +11,7 @@ import ( "github.com/gotk3/gotk3/glib" "github.com/gotk3/gotk3/gtk" "github.com/pactus-project/pactus/cmd" + "github.com/pactus-project/pactus/genesis" "github.com/pactus-project/pactus/wallet" ) @@ -21,7 +22,7 @@ func setMargin(widget gtk.IWidget, top, bottom, start, end int) { widget.ToWidget().SetMarginEnd(end) } -func startupAssistant(workingDir string, testnet bool) bool { +func startupAssistant(workingDir string, chain genesis.ChainType) bool { successful := false createPage := func(assistant *gtk.Assistant, content gtk.IWidget, name, title, subject, desc string) *gtk.Widget { @@ -382,17 +383,13 @@ Now you are ready to start the node!` walletPassword, err := entryPassword.GetText() fatalErrorCheck(err) - validatorAddrs, rewardAddrs, err := cmd.CreateNode(numValidators, testnet, workingDir, mnemonic, walletPassword) + validatorAddrs, rewardAddrs, err := cmd.CreateNode(numValidators, chain, workingDir, mnemonic, walletPassword) fatalErrorCheck(err) // Done! showing the node information successful = true nodeInfo := fmt.Sprintf("Working directory: %s\n", workingDir) - if testnet { - nodeInfo += "Network: Testnet\n" - } else { - nodeInfo += "Network: Mainnet\n" - } + nodeInfo += fmt.Sprintf("Network: %s\n", chain.String()) nodeInfo += "\nValidator addresses:\n" for i, addr := range validatorAddrs { nodeInfo += fmt.Sprintf("%v- %s\n", i+1, addr) diff --git a/cmd/gtk/widget_node.go b/cmd/gtk/widget_node.go index 667b959c1..fbf5c2541 100644 --- a/cmd/gtk/widget_node.go +++ b/cmd/gtk/widget_node.go @@ -32,7 +32,7 @@ type widgetNode struct { progressBarSynced *gtk.ProgressBar } -func buildWidgetNode(model *nodeModel, genesisTime time.Time) (*widgetNode, error) { +func buildWidgetNode(model *nodeModel) (*widgetNode, error) { builder, err := gtk.BuilderNewFromString(string(uiWidgetNode)) if err != nil { return nil, err @@ -40,17 +40,19 @@ func buildWidgetNode(model *nodeModel, genesisTime time.Time) (*widgetNode, erro box := getBoxObj(builder, "id_box_node") labelLocation := getLabelObj(builder, "id_label_working_directory") + labelNetwork := getLabelObj(builder, "id_label_network") cwd, err := os.Getwd() if err != nil { return nil, err } labelLocation.SetText(cwd) + labelNetwork.SetText(model.node.State().Genesis().ChainType().String()) w := &widgetNode{ Box: box, model: model, - genesisTime: genesisTime, + genesisTime: model.node.State().Genesis().GenesisTime(), labelLastBlockTime: getLabelObj(builder, "id_label_last_block_time"), labelLastBlockHeight: getLabelObj(builder, "id_label_last_block_height"), labelBlocksLeft: getLabelObj(builder, "id_label_blocks_left"), diff --git a/cmd/wallet/create.go b/cmd/wallet/create.go index 081a7cdd3..e80abe0bb 100644 --- a/cmd/wallet/create.go +++ b/cmd/wallet/create.go @@ -3,6 +3,7 @@ package main import ( cli "github.com/jawher/mow.cli" "github.com/pactus-project/pactus/cmd" + "github.com/pactus-project/pactus/genesis" "github.com/pactus-project/pactus/wallet" ) @@ -26,9 +27,9 @@ func Generate() func(c *cli.Cmd) { password := cmd.PromptPassword("Password", true) mnemonic := wallet.GenerateMnemonic(*entropyOpt) - network := wallet.NetworkMainNet + network := genesis.Mainnet if *testnetOpt { - network = wallet.NetworkTestNet + network = genesis.Testnet } wallet, err := wallet.Create(*pathArg, mnemonic, password, network) cmd.FatalErrorCheck(err) diff --git a/config/config.go b/config/config.go index 545c7fef1..0f6ebc339 100644 --- a/config/config.go +++ b/config/config.go @@ -115,26 +115,6 @@ func SaveTestnetConfig(path string, numValidators int) error { return util.WriteFile(path, conf.toTOML()) } -func SaveLocalnetConfig(path string) error { - conf := DefaultConfig() - conf.Node.NumValidators = 1 - conf.Network.Name = "pactus-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.HTTP.Enable = true - conf.HTTP.Listen = "[::]:8081" - conf.Nanomsg.Enable = true - conf.Nanomsg.Listen = "tcp://127.0.0.1:40899" - - return util.WriteFile(path, conf.toTOML()) -} - func (conf *Config) toTOML() []byte { buf := new(bytes.Buffer) encoder := toml.NewEncoder(buf) diff --git a/config/config_test.go b/config/config_test.go index 305d4e4d8..330617c20 100644 --- a/config/config_test.go +++ b/config/config_test.go @@ -31,17 +31,6 @@ func TestSaveTestnetConfig(t *testing.T) { assert.Equal(t, conf.Network.Name, "pactus-testnet") } -func TestSaveLocalnetConfig(t *testing.T) { - path := util.TempFilePath() - assert.NoError(t, SaveLocalnetConfig(path)) - - conf, err := LoadFromFile(path) - assert.NoError(t, err) - - assert.NoError(t, conf.SanityCheck()) - assert.Equal(t, conf.Network.Name, "pactus-localnet") -} - func TestLoadFromFile(t *testing.T) { path := util.TempFilePath() _, err := LoadFromFile(path) diff --git a/genesis/genesis.go b/genesis/genesis.go index 9ae86f16f..55199a49e 100644 --- a/genesis/genesis.go +++ b/genesis/genesis.go @@ -16,6 +16,29 @@ import ( "github.com/pactus-project/pactus/util" ) +type ChainType uint8 + +const ( + Unknown ChainType = 0xff + Mainnet ChainType = 0 + Testnet ChainType = 1 +) + +func (n ChainType) IsTestnet() bool { + return n == Testnet +} + +func (n ChainType) String() string { + switch n { + case Mainnet: + return "Mainnet" + case Testnet: + return "Testnet" + default: + return "Unknown" + } +} + type genAccount struct { Address string `cbor:"1,keyasint"` Balance int64 `cbor:"2,keyasint"` @@ -134,7 +157,7 @@ func LoadFromFile(file string) (*Genesis, error) { return &gen, nil } -// SaveToFile saves the genesis info a JSON file. +// SaveToFile saves the genesis into a JSON file. func (gen *Genesis) SaveToFile(file string) error { json, err := gen.MarshalJSON() if err != nil { @@ -144,3 +167,11 @@ func (gen *Genesis) SaveToFile(file string) error { // write dataContent to file return util.WriteFile(file, json) } + +func (gen *Genesis) ChainType() ChainType { + if gen.Hash() == TestnetGenesis().Hash() { + return Testnet + } + + return Unknown +} diff --git a/genesis/genesis_test.go b/genesis/genesis_test.go index 72a610153..f38e4da3f 100644 --- a/genesis/genesis_test.go +++ b/genesis/genesis_test.go @@ -45,7 +45,7 @@ func TestMarshaling(t *testing.T) { } func TestGenesisTestNet(t *testing.T) { - g := Testnet() + g := TestnetGenesis() assert.Equal(t, len(g.Validators()), 4) assert.Equal(t, len(g.Accounts()), 1) diff --git a/genesis/testnet.go b/genesis/testnet.go index 389af4d3c..bab0477a4 100644 --- a/genesis/testnet.go +++ b/genesis/testnet.go @@ -8,7 +8,7 @@ import ( //go:embed testnet.json var testnetJSON []byte -func Testnet() *Genesis { +func TestnetGenesis() *Genesis { var gen Genesis if err := json.Unmarshal(testnetJSON, &gen); err != nil { panic(err) diff --git a/node/node.go b/node/node.go index 372cef32a..db3c3b752 100644 --- a/node/node.go +++ b/node/node.go @@ -43,7 +43,8 @@ func NewNode(genDoc *genesis.Genesis, conf *config.Config, logger.InitLogger(conf.Logger) logger.Info("You are running a pactus block chain", - "version", version.Version()) + "version", version.Version(), + "network", genDoc.ChainType()) network, err := network.NewNetwork(conf.Network) if err != nil { @@ -159,3 +160,6 @@ func (n *Node) Sync() sync.Synchronizer { func (n *Node) State() state.Facade { return n.state } +func (n *Node) GRPC() *grpc.Server { + return n.grpc +} diff --git a/state/facade.go b/state/facade.go index 593795e72..0b6f1b62c 100644 --- a/state/facade.go +++ b/state/facade.go @@ -5,6 +5,7 @@ import ( "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/hash" + "github.com/pactus-project/pactus/genesis" "github.com/pactus-project/pactus/store" "github.com/pactus-project/pactus/types/account" "github.com/pactus-project/pactus/types/block" @@ -14,7 +15,7 @@ import ( ) type Facade interface { - GenesisHash() hash.Hash + Genesis() *genesis.Genesis LastBlockHeight() uint32 LastBlockHash() hash.Hash LastBlockTime() time.Time diff --git a/state/mock.go b/state/mock.go index 0898dc472..622acb00e 100644 --- a/state/mock.go +++ b/state/mock.go @@ -8,6 +8,7 @@ import ( "github.com/pactus-project/pactus/committee" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/hash" + "github.com/pactus-project/pactus/genesis" "github.com/pactus-project/pactus/store" "github.com/pactus-project/pactus/txpool" "github.com/pactus-project/pactus/types/account" @@ -25,7 +26,7 @@ type MockState struct { // This locks prevents the Data Race in tests lk sync.RWMutex - TestGenHash hash.Hash + TestGenesis *genesis.Genesis TestStore *store.MockStore TestPool *txpool.MockTxPool TestCommittee committee.Committee @@ -35,7 +36,7 @@ type MockState struct { func MockingState() *MockState { committee, _ := committee.GenerateTestCommittee(21) return &MockState{ - TestGenHash: hash.GenerateTestHash(), + TestGenesis: genesis.TestnetGenesis(), // TODO: replace me with the Mainnet genesis TestStore: store.MockingStore(), TestPool: txpool.MockingTxPool(), TestCommittee: committee, @@ -58,8 +59,8 @@ func (m *MockState) LastBlockHeight() uint32 { return m.TestStore.LastHeight } -func (m *MockState) GenesisHash() hash.Hash { - return m.TestGenHash +func (m *MockState) Genesis() *genesis.Genesis { + return m.TestGenesis } func (m *MockState) LastBlockHash() hash.Hash { m.lk.RLock() diff --git a/state/state.go b/state/state.go index 8a731b653..39f302a06 100644 --- a/state/state.go +++ b/state/state.go @@ -207,11 +207,11 @@ func (st *state) Close() error { return st.store.Close() } -func (st *state) GenesisHash() hash.Hash { +func (st *state) Genesis() *genesis.Genesis { st.lk.RLock() defer st.lk.RUnlock() - return st.genDoc.Hash() + return st.genDoc } func (st *state) LastBlockHeight() uint32 { diff --git a/state/state_test.go b/state/state_test.go index 12f7dbceb..8c747755c 100644 --- a/state/state_test.go +++ b/state/state_test.go @@ -197,7 +197,7 @@ func TestCommitBlocks(t *testing.T) { assert.Equal(t, tState1.LastBlockTime(), b1.Header().Time()) assert.Equal(t, tState1.LastCertificate().Hash(), c1.Hash()) assert.Equal(t, tState1.LastBlockHeight(), uint32(1)) - assert.Equal(t, tState1.GenesisHash(), tState2.GenesisHash()) + assert.Equal(t, tState1.Genesis().Hash(), tState2.Genesis().Hash()) } func TestCommitSandbox(t *testing.T) { diff --git a/sync/firewall/firewall.go b/sync/firewall/firewall.go index d6fb4f712..d916b913a 100644 --- a/sync/firewall/firewall.go +++ b/sync/firewall/firewall.go @@ -5,11 +5,11 @@ import ( "io" "github.com/libp2p/go-libp2p/core/peer" + "github.com/pactus-project/pactus/genesis" "github.com/pactus-project/pactus/network" "github.com/pactus-project/pactus/state" "github.com/pactus-project/pactus/sync/bundle" "github.com/pactus-project/pactus/sync/peerset" - "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/errors" "github.com/pactus-project/pactus/util/logger" ) @@ -116,18 +116,24 @@ func (f *Firewall) checkBundle(bdl *bundle.Bundle, pid peer.ID) error { "source is not same as initiator. source: %v, initiator: %v", pid, bdl.Initiator) } - if f.state.Params().IsMainnet() { - if !util.IsFlagSet(bdl.Flags, bundle.BundleFlagNetworkMainnet) { + switch f.state.Genesis().ChainType() { + case genesis.Mainnet: + if bdl.Flags&0x3 != bundle.BundleFlagNetworkMainnet { return errors.Errorf(errors.ErrInvalidMessage, "bundle is not for the mainnet") } - } - if f.state.Params().IsTestnet() { - if !util.IsFlagSet(bdl.Flags, bundle.BundleFlagNetworkTestnet) { + case genesis.Testnet: + if bdl.Flags&0x3 != bundle.BundleFlagNetworkTestnet { return errors.Errorf(errors.ErrInvalidMessage, "bundle is not for the testnet") } + + default: + if bdl.Flags&0x3 != 0 { + return errors.Errorf(errors.ErrInvalidMessage, + "bundle is not for the localnet") + } } return nil diff --git a/sync/firewall/firewall_test.go b/sync/firewall/firewall_test.go index 6ef3f80c7..f452cc5a9 100644 --- a/sync/firewall/firewall_test.go +++ b/sync/firewall/firewall_test.go @@ -51,12 +51,12 @@ func TestInvalidBundlesCounter(t *testing.T) { assert.Nil(t, tFirewall.OpenGossipBundle(nil, tUnknownPeerID, tUnknownPeerID)) bdl := bundle.NewBundle(tUnknownPeerID, message.NewQueryProposalMessage(0, -1)) - bdl.Flags = util.SetFlag(bdl.Flags, bundle.BundleFlagNetworkMainnet) + bdl.Flags = util.SetFlag(bdl.Flags, bundle.BundleFlagNetworkTestnet) d, _ := bdl.Encode() assert.Nil(t, tFirewall.OpenGossipBundle(d, tUnknownPeerID, tUnknownPeerID)) bdl = bundle.NewBundle(tBadPeerID, message.NewQueryProposalMessage(0, 1)) - bdl.Flags = util.SetFlag(bdl.Flags, bundle.BundleFlagNetworkMainnet) + bdl.Flags = util.SetFlag(bdl.Flags, bundle.BundleFlagNetworkTestnet) d, _ = bdl.Encode() assert.Nil(t, tFirewall.OpenGossipBundle(d, tUnknownPeerID, tUnknownPeerID)) @@ -69,7 +69,7 @@ func TestGossipMessage(t *testing.T) { setup(t) bdl := bundle.NewBundle(tUnknownPeerID, message.NewQueryProposalMessage(100, 1)) - bdl.Flags = util.SetFlag(bdl.Flags, bundle.BundleFlagNetworkMainnet) + bdl.Flags = util.SetFlag(bdl.Flags, bundle.BundleFlagNetworkTestnet) d, _ := bdl.Encode() assert.False(t, tNetwork.IsClosed(tBadPeerID)) @@ -81,7 +81,7 @@ func TestGossipMessage(t *testing.T) { setup(t) bdl := bundle.NewBundle(tBadPeerID, message.NewQueryProposalMessage(100, 1)) - bdl.Flags = util.SetFlag(bdl.Flags, bundle.BundleFlagNetworkMainnet) + bdl.Flags = util.SetFlag(bdl.Flags, bundle.BundleFlagNetworkTestnet) d, _ := bdl.Encode() assert.False(t, tNetwork.IsClosed(tBadPeerID)) @@ -93,7 +93,7 @@ func TestGossipMessage(t *testing.T) { setup(t) bdl := bundle.NewBundle(tBadPeerID, message.NewQueryProposalMessage(100, 1)) - bdl.Flags = util.SetFlag(bdl.Flags, bundle.BundleFlagNetworkMainnet) + bdl.Flags = util.SetFlag(bdl.Flags, bundle.BundleFlagNetworkTestnet) d, _ := bdl.Encode() assert.Nil(t, tFirewall.OpenGossipBundle(d, tUnknownPeerID, tUnknownPeerID)) @@ -104,7 +104,7 @@ func TestGossipMessage(t *testing.T) { setup(t) bdl := bundle.NewBundle(tGoodPeerID, message.NewQueryProposalMessage(100, 1)) - bdl.Flags = util.SetFlag(bdl.Flags, bundle.BundleFlagNetworkMainnet) + bdl.Flags = util.SetFlag(bdl.Flags, bundle.BundleFlagNetworkTestnet) d, _ := bdl.Encode() assert.False(t, tNetwork.IsClosed(tGoodPeerID)) @@ -118,7 +118,7 @@ func TestStreamMessage(t *testing.T) { setup(t) bdl := bundle.NewBundle(tBadPeerID, message.NewBlocksRequestMessage(int(util.RandInt32(0)), 1, 100)) - bdl.Flags = util.SetFlag(bdl.Flags, bundle.BundleFlagNetworkMainnet) + bdl.Flags = util.SetFlag(bdl.Flags, bundle.BundleFlagNetworkTestnet) d, _ := bdl.Encode() assert.False(t, tNetwork.IsClosed(tBadPeerID)) @@ -130,7 +130,7 @@ func TestStreamMessage(t *testing.T) { setup(t) bdl := bundle.NewBundle(tGoodPeerID, message.NewBlocksRequestMessage(int(util.RandInt32(0)), 1, 100)) - bdl.Flags = util.SetFlag(bdl.Flags, bundle.BundleFlagNetworkMainnet) + bdl.Flags = util.SetFlag(bdl.Flags, bundle.BundleFlagNetworkTestnet) d, _ := bdl.Encode() assert.False(t, tNetwork.IsClosed(tGoodPeerID)) @@ -143,7 +143,7 @@ func TestDisabledFirewall(t *testing.T) { setup(t) bdl := bundle.NewBundle(tGoodPeerID, message.NewQueryProposalMessage(0, -1)) - bdl.Flags = util.SetFlag(bdl.Flags, bundle.BundleFlagNetworkMainnet) + bdl.Flags = util.SetFlag(bdl.Flags, bundle.BundleFlagNetworkTestnet) d, _ := bdl.Encode() tFirewall.config.Enabled = false @@ -155,7 +155,7 @@ func TestUpdateLastSeen(t *testing.T) { setup(t) bdl := bundle.NewBundle(tGoodPeerID, message.NewQueryProposalMessage(100, 1)) - bdl.Flags = util.SetFlag(bdl.Flags, bundle.BundleFlagNetworkMainnet) + bdl.Flags = util.SetFlag(bdl.Flags, bundle.BundleFlagNetworkTestnet) d, _ := bdl.Encode() now := time.Now().UnixNano() assert.Nil(t, tFirewall.OpenGossipBundle(d, tUnknownPeerID, tGoodPeerID)) @@ -167,8 +167,15 @@ func TestUpdateLastSeen(t *testing.T) { func TestNetworkFlags(t *testing.T) { setup(t) + // TODO: add tests for Mainnet and Testnet flags bdl := bundle.NewBundle(tGoodPeerID, message.NewQueryProposalMessage(100, 1)) - bdl.Flags = util.UnsetFlag(bdl.Flags, bundle.BundleFlagNetworkMainnet) + bdl.Flags = util.SetFlag(bdl.Flags, bundle.BundleFlagNetworkTestnet) + assert.NoError(t, tFirewall.checkBundle(bdl, tGoodPeerID)) + + bdl.Flags = util.SetFlag(bdl.Flags, bundle.BundleFlagNetworkMainnet) + assert.Error(t, tFirewall.checkBundle(bdl, tGoodPeerID)) + + bdl.Flags = 0 assert.Error(t, tFirewall.checkBundle(bdl, tGoodPeerID)) tState.TestParams.BlockVersion = 0x3f diff --git a/sync/handler_blocks_request_test.go b/sync/handler_blocks_request_test.go index 382900e87..8afffab9f 100644 --- a/sync/handler_blocks_request_test.go +++ b/sync/handler_blocks_request_test.go @@ -20,7 +20,7 @@ func TestSessionTimeout(t *testing.T) { signer := bls.GenerateTestSigner() pid := network.TestRandomPeerID() claimedHeight := uint32(6666) - msg := message.NewHelloMessage(pid, "Oscar", claimedHeight, message.FlagNodeNetwork, tState.GenesisHash()) + msg := message.NewHelloMessage(pid, "Oscar", claimedHeight, message.FlagNodeNetwork, tState.Genesis().Hash()) signer.SignMsg(msg) assert.NoError(t, testReceivingNewMessage(tSync, msg, pid)) diff --git a/sync/handler_blocks_response_test.go b/sync/handler_blocks_response_test.go index 9d6217214..668a41679 100644 --- a/sync/handler_blocks_response_test.go +++ b/sync/handler_blocks_response_test.go @@ -77,7 +77,6 @@ func TestSyncing(t *testing.T) { configBob.NodeNetwork = true networkAlice.AddAnotherNetwork(networkBob) networkBob.AddAnotherNetwork(networkAlice) - stateBob.TestGenHash = stateAlice.GenesisHash() testAddBlocks(t, stateBob, 100) sync1, err := NewSynchronizer(configAlice, diff --git a/sync/handler_hello.go b/sync/handler_hello.go index 8be7b779f..1c6333639 100644 --- a/sync/handler_hello.go +++ b/sync/handler_hello.go @@ -30,11 +30,11 @@ func (handler *helloHandler) ParsMessage(m message.Message, initiator peer.ID) e msg.PeerID, initiator) } - if !msg.GenesisHash.EqualsTo(handler.state.GenesisHash()) { + if !msg.GenesisHash.EqualsTo(handler.state.Genesis().Hash()) { handler.peerSet.UpdateStatus(initiator, peerset.StatusCodeBanned) return errors.Errorf(errors.ErrInvalidMessage, "received a message from different chain, expected: %v, got: %v", - handler.state.GenesisHash(), msg.GenesisHash) + handler.state.Genesis().Hash(), msg.GenesisHash) } handler.logger.Debug("updating peer info", diff --git a/sync/handler_hello_test.go b/sync/handler_hello_test.go index 329dfe55e..007bc0ae2 100644 --- a/sync/handler_hello_test.go +++ b/sync/handler_hello_test.go @@ -22,7 +22,7 @@ func TestParsingHelloMessages(t *testing.T) { signer := bls.GenerateTestSigner() pid := network.TestRandomPeerID() initiator := network.TestRandomPeerID() - msg := message.NewHelloMessage(pid, "bad-genesis", 0, 0, tState.GenesisHash()) + msg := message.NewHelloMessage(pid, "bad-genesis", 0, 0, tState.Genesis().Hash()) signer.SignMsg(msg) assert.True(t, msg.PublicKey.EqualsTo(signer.PublicKey())) @@ -49,7 +49,7 @@ func TestParsingHelloMessages(t *testing.T) { signer := bls.GenerateTestSigner() height := util.RandUint32(tState.LastBlockHeight()) pid := network.TestRandomPeerID() - msg := message.NewHelloMessage(pid, "kitty", height, message.FlagNodeNetwork, tState.GenesisHash()) + msg := message.NewHelloMessage(pid, "kitty", height, message.FlagNodeNetwork, tState.Genesis().Hash()) signer.SignMsg(msg) assert.NoError(t, testReceivingNewMessage(tSync, msg, pid)) @@ -75,7 +75,7 @@ func TestParsingHelloMessages(t *testing.T) { signer := bls.GenerateTestSigner() height := util.RandUint32(tState.LastBlockHeight()) pid := network.TestRandomPeerID() - msg := message.NewHelloMessage(pid, "kitty", height, message.FlagHelloAck, tState.GenesisHash()) + msg := message.NewHelloMessage(pid, "kitty", height, message.FlagHelloAck, tState.Genesis().Hash()) signer.SignMsg(msg) assert.NoError(t, testReceivingNewMessage(tSync, msg, pid)) @@ -93,7 +93,7 @@ func TestParsingHelloMessages(t *testing.T) { signer := bls.GenerateTestSigner() claimedHeight := tState.LastBlockHeight() + 5 pid := network.TestRandomPeerID() - msg := message.NewHelloMessage(pid, "kitty", claimedHeight, message.FlagHelloAck, tState.GenesisHash()) + msg := message.NewHelloMessage(pid, "kitty", claimedHeight, message.FlagHelloAck, tState.Genesis().Hash()) signer.SignMsg(msg) assert.NoError(t, testReceivingNewMessage(tSync, msg, pid)) diff --git a/sync/sync.go b/sync/sync.go index ac8b0f070..1995bdfa0 100644 --- a/sync/sync.go +++ b/sync/sync.go @@ -8,6 +8,7 @@ import ( "github.com/libp2p/go-libp2p/core/peer" "github.com/pactus-project/pactus/consensus" "github.com/pactus-project/pactus/crypto" + "github.com/pactus-project/pactus/genesis" "github.com/pactus-project/pactus/network" "github.com/pactus-project/pactus/state" "github.com/pactus-project/pactus/sync/bundle" @@ -170,7 +171,7 @@ func (sync *synchronizer) sayHello(helloAck bool) { sync.SelfID(), sync.config.Moniker, sync.state.LastBlockHeight(), - flags, sync.state.GenesisHash()) + flags, sync.state.Genesis().Hash()) for _, signer := range sync.signers { signer.SignMsg(msg) @@ -282,13 +283,15 @@ func (sync *synchronizer) prepareBundle(msg message.Message) *bundle.Bundle { // In future we might support other libraries. bdl.Flags = util.SetFlag(bdl.Flags, bundle.BundleFlagCarrierLibP2P) - if sync.state.Params().IsMainnet() { + switch sync.state.Genesis().ChainType() { + case genesis.Mainnet: bdl.Flags = util.SetFlag(bdl.Flags, bundle.BundleFlagNetworkMainnet) - } - - if sync.state.Params().IsTestnet() { + case genesis.Testnet: bdl.Flags = util.SetFlag(bdl.Flags, bundle.BundleFlagNetworkTestnet) + default: + // It's localnet and for testing purpose only } + return bdl } return nil diff --git a/sync/sync_test.go b/sync/sync_test.go index 37c5345e9..cf6085716 100644 --- a/sync/sync_test.go +++ b/sync/sync_test.go @@ -108,7 +108,7 @@ func shouldPublishMessageWithThisType(t *testing.T, net *network.MockNetwork, ms // ----------- // Check flags require.True(t, util.IsFlagSet(bdl.Flags, bundle.BundleFlagCarrierLibP2P), "invalid flag: %v", bdl) - require.True(t, util.IsFlagSet(bdl.Flags, bundle.BundleFlagNetworkMainnet), "invalid flag: %v", bdl) + require.True(t, util.IsFlagSet(bdl.Flags, bundle.BundleFlagNetworkTestnet), "invalid flag: %v", bdl) if b.Target == nil { require.True(t, util.IsFlagSet(bdl.Flags, bundle.BundleFlagBroadcasted), "invalid flag: %v", bdl) diff --git a/types/param/param.go b/types/param/param.go index 6afc83379..36b4be57e 100644 --- a/types/param/param.go +++ b/types/param/param.go @@ -37,11 +37,3 @@ func DefaultParams() Params { func (p Params) BlockTime() time.Duration { return time.Duration(p.BlockTimeInSecond) * time.Second } - -func (p Params) IsMainnet() bool { - return p.BlockVersion == 0x01 -} - -func (p Params) IsTestnet() bool { - return p.BlockVersion == 0x3f // 63 -} diff --git a/wallet/store.go b/wallet/store.go index 2b654dc35..24eff06f0 100644 --- a/wallet/store.go +++ b/wallet/store.go @@ -6,17 +6,18 @@ import ( "time" "github.com/google/uuid" + "github.com/pactus-project/pactus/genesis" "github.com/pactus-project/pactus/wallet/vault" ) type store struct { - Version int `json:"version"` - UUID uuid.UUID `json:"uuid"` - CreatedAt time.Time `json:"created_at"` - Network Network `json:"network"` - VaultCRC uint32 `json:"crc"` - Vault *vault.Vault `json:"vault"` - History history `json:"history"` + Version int `json:"version"` + UUID uuid.UUID `json:"uuid"` + CreatedAt time.Time `json:"created_at"` + Network genesis.ChainType `json:"network"` + VaultCRC uint32 `json:"crc"` + Vault *vault.Vault `json:"vault"` + History history `json:"history"` } func (s *store) Load() ([]byte, error) { diff --git a/wallet/wallet.go b/wallet/wallet.go index acea47398..9e7194d5a 100644 --- a/wallet/wallet.go +++ b/wallet/wallet.go @@ -10,6 +10,7 @@ import ( "github.com/google/uuid" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/bls" + "github.com/pactus-project/pactus/genesis" "github.com/pactus-project/pactus/types/param" "github.com/pactus-project/pactus/types/tx" "github.com/pactus-project/pactus/types/tx/payload" @@ -18,13 +19,6 @@ import ( pactus "github.com/pactus-project/pactus/www/grpc/gen/go" ) -type Network uint8 - -const ( - NetworkMainNet = Network(0) - NetworkTestNet = Network(1) -) - type Wallet struct { store *store path string @@ -67,20 +61,27 @@ func Open(path string, offline bool) (*Wallet, error) { // Create creates a wallet from mnemonic (seed phrase) and save it at the // given path. -func Create(path, mnemonic, password string, net Network) (*Wallet, error) { +func Create(path, mnemonic, password string, chain genesis.ChainType) (*Wallet, error) { path = util.MakeAbs(path) if util.PathExists(path) { return nil, NewErrWalletExits(path) } - coinType := uint32(21888) - if net == NetworkTestNet { - coinType = uint32(21777) + + coinType := uint32(0) + switch chain { + case genesis.Mainnet: + coinType = 21888 + case genesis.Testnet: + coinType = 21777 + default: + return nil, ErrInvalidNetwork } + store := &store{ Version: 1, UUID: uuid.New(), CreatedAt: time.Now().Round(time.Second).UTC(), - Network: net, + Network: chain, Vault: nil, } wallet, err := newWallet(path, store, true) @@ -101,7 +102,7 @@ func Create(path, mnemonic, password string, net Network) (*Wallet, error) { } func newWallet(path string, store *store, offline bool) (*Wallet, error) { - if store.Network == NetworkTestNet { + if store.Network.IsTestnet() { crypto.AddressHRP = "tpc" crypto.PublicKeyHRP = "tpublic" crypto.PrivateKeyHRP = "tsecret" @@ -161,11 +162,11 @@ func (w *Wallet) connectToRandomServer() error { var netServers []serverInfo switch w.store.Network { - case NetworkMainNet: + case genesis.Mainnet: { // mainnet netServers = serversInfo["mainnet"] } - case NetworkTestNet: + case genesis.Testnet: { // testnet netServers = serversInfo["testnet"] } diff --git a/wallet/wallet_test.go b/wallet/wallet_test.go index de1b30c14..a8e0b5496 100644 --- a/wallet/wallet_test.go +++ b/wallet/wallet_test.go @@ -11,6 +11,7 @@ import ( "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/crypto/hash" + "github.com/pactus-project/pactus/genesis" "github.com/pactus-project/pactus/types/tx/payload" "github.com/pactus-project/pactus/util" pactus "github.com/pactus-project/pactus/www/grpc/gen/go" @@ -51,7 +52,7 @@ func setup(t *testing.T) { tPassword := "" walletPath := util.TempFilePath() mnemonic := GenerateMnemonic(128) - w, err := Create(walletPath, mnemonic, tPassword, NetworkMainNet) + w, err := Create(walletPath, mnemonic, tPassword, genesis.Mainnet) assert.NoError(t, err) assert.False(t, w.IsEncrypted()) assert.Equal(t, w.Path(), walletPath) @@ -129,7 +130,7 @@ func TestRecoverWallet(t *testing.T) { t.Run("Ok", func(t *testing.T) { path := util.TempFilePath() - recovered, err := Create(path, mnemonic, password, NetworkMainNet) + recovered, err := Create(path, mnemonic, password, genesis.Mainnet) assert.NoError(t, err) addr1, err := recovered.DeriveNewAddress("addr-1") @@ -172,13 +173,13 @@ func TestImportPrivateKey(t *testing.T) { func TestTestKeyInfo(t *testing.T) { mnemonic := GenerateMnemonic(128) w1, err := Create(util.TempFilePath(), mnemonic, tPassword, - NetworkMainNet) + genesis.Mainnet) assert.NoError(t, err) addrStr1, _ := w1.DeriveNewAddress("") prv1, _ := w1.PrivateKey("", addrStr1) w2, err := Create(util.TempFilePath(), mnemonic, tPassword, - NetworkTestNet) + genesis.Testnet) assert.NoError(t, err) addrStr2, _ := w2.DeriveNewAddress("") prv2, _ := w2.PrivateKey("", addrStr2) diff --git a/www/grpc/server.go b/www/grpc/server.go index 99fb6f3e9..7480a8ed4 100644 --- a/www/grpc/server.go +++ b/www/grpc/server.go @@ -8,7 +8,6 @@ import ( "github.com/pactus-project/pactus/state" "github.com/pactus-project/pactus/sync" "github.com/pactus-project/pactus/util/logger" - "github.com/pactus-project/pactus/wallet" pactus "github.com/pactus-project/pactus/www/grpc/gen/go" "google.golang.org/grpc" ) @@ -60,13 +59,10 @@ func (s *Server) StartServer() error { sync: s.sync, logger: s.logger, } - network := wallet.NetworkMainNet - if s.state.Params().IsTestnet() { - network = wallet.NetworkTestNet - } + network := s.state.Genesis().ChainType() walletServer := &walletServer{ wallets: make(map[string]*loadedWallet), - network: network, + chain: network, logger: s.logger, } pactus.RegisterBlockchainServer(grpc, blockchainServer) diff --git a/www/grpc/wallet.go b/www/grpc/wallet.go index 62b67ed4b..afacbb9bd 100644 --- a/www/grpc/wallet.go +++ b/www/grpc/wallet.go @@ -5,6 +5,7 @@ import ( "fmt" "os" + "github.com/pactus-project/pactus/genesis" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/logger" "github.com/pactus-project/pactus/wallet" @@ -19,7 +20,7 @@ type loadedWallet struct { type walletServer struct { wallets map[string]*loadedWallet - network wallet.Network + chain genesis.ChainType logger *logger.Logger } @@ -34,7 +35,7 @@ func (s *walletServer) CreateWallet(_ context.Context, } path := walletPath(req.Name) - w, err := wallet.Create(path, req.Mnemonic, req.Language, s.network) + w, err := wallet.Create(path, req.Mnemonic, req.Language, s.chain) if err != nil { return nil, err }