From 4f03fdaf2bbd419e7f9999b7c7f1ed3853214f44 Mon Sep 17 00:00:00 2001 From: "shuyi.yu" Date: Tue, 26 Nov 2019 11:49:10 +0800 Subject: [PATCH 1/3] refine the command about createpeerid and compiling sol file --- commands/box/contract/contract.go | 41 ++++++++++++------------------- commands/box/util/root.go | 29 +++++++++++++++++++--- 2 files changed, 41 insertions(+), 29 deletions(-) diff --git a/commands/box/contract/contract.go b/commands/box/contract/contract.go index 0d596bd1..01afcc93 100644 --- a/commands/box/contract/contract.go +++ b/commands/box/contract/contract.go @@ -1113,19 +1113,22 @@ func parseContractData(data string) (bytecode string, abi string, err error) { return "", "", err } if len(binData) == 1 { - bytecode = binData[0] - abi = abiData[0] + bytecode = string(binData[0]) + abi = string(abiData[0]) } else if len(binData) > 1 { - fmt.Printf("%v\n", solName) + for i, v := range solName { + fmt.Printf("%d:%s\n", i, v) + } fmt.Println("Which one do you want to deploy?") var input string fmt.Scanf("%s", &input) for i, v := range solName { - if input == v { - bytecode = binData[i] - abi = abiData[i] + if input == v || input == strconv.Itoa(i) { + bytecode = string(binData[i]) + abi = string(abiData[i]) } } + //if len(bytecode) == 0, there is no match in compiling sol file if len(bytecode) == 0 { return "", "", errors.New("Please make sure your input is correct") } @@ -1140,7 +1143,7 @@ func parseContractData(data string) (bytecode string, abi string, err error) { return bytecode, abi, nil } -func compileSol(filepath string) (binData []string, abiData []string, solName []string, err error) { +func compileSol(filepath string) (binData [][]byte, abiData [][]byte, solName []string, err error) { cmd := exec.Command("solc", filepath, "--bin", "--abi") //CombinedOutput runs the command and returns its combined standard output and standard error. output, err := cmd.CombinedOutput() @@ -1150,30 +1153,18 @@ func compileSol(filepath string) (binData []string, abiData []string, solName [] } binMatches := solcBinReg.FindAllSubmatch(output, -1) for _, v := range binMatches { - for i, k := range v { - if (i+1)%2 == 0 { - binData = append(binData, string(k)) - } - } + binData = append(binData, v[1]) } abiMathes := solcAbiReg.FindAllSubmatch(output, -1) for _, v := range abiMathes { - for i, k := range v { - if (i+1)%2 == 0 { - abiData = append(abiData, string(k)) - } - } + abiData = append(abiData, v[1]) } solFilePath = filepath nameMatches := solNameReg.FindAllSubmatch(output, -1) for _, v := range nameMatches { - for i, k := range v { - if (i+1)%2 == 0 { - solName = append(solName, string(k)) - } - } + solName = append(solName, string(v[1])) } - if len(abiData) == 0 && len(binData) == 0 && len(solName) == 0 { + if len(abiData) == 0 || len(binData) == 0 || len(solName) == 0 { return nil, nil, nil, errors.New("no matche in sol file") } return binData, abiData, solName, nil @@ -1323,14 +1314,14 @@ func compile(cmd *cobra.Command, args []string) { for i := 0; i < len(binData); i++ { binFile := outputDir + solName[i] + ".bin" // write bin data to file - if err := ioutil.WriteFile(binFile, []byte(binData[i]), 0644); err != nil { + if err := ioutil.WriteFile(binFile, binData[i], 0644); err != nil { fmt.Println(err) return } fmt.Println("generate bin file:", binFile) abiFile := outputDir + solName[i] + ".abi" // write abi data to file - if err := ioutil.WriteFile(abiFile, []byte(abiData[i]), 0644); err != nil { + if err := ioutil.WriteFile(abiFile, abiData[i], 0644); err != nil { fmt.Println(err) return } diff --git a/commands/box/util/root.go b/commands/box/util/root.go index 1c3123e7..10c8ccad 100644 --- a/commands/box/util/root.go +++ b/commands/box/util/root.go @@ -12,6 +12,7 @@ import ( "io/ioutil" "math" "os" + "path/filepath" "strconv" root "github.com/BOXFoundation/boxd/commands/box/root" @@ -267,6 +268,10 @@ func peerID(cmd *cobra.Command, args []string) { return } data = string(dataByte) + if _, err := libcrypto.ConfigDecodeKey(data); err != nil { + fmt.Printf("read data from %s, error: %s", args[0], err) + return + } } else if _, err := libcrypto.ConfigDecodeKey(args[0]); err == nil { data = args[0] } else { @@ -308,11 +313,21 @@ func createPeerID(cmd *cobra.Command, args []string) { } peerKeyPath += "/peer.key" } else if len(args) == 1 { - if err = util.FileExists(args[0]); err != nil { - fmt.Println(err) - return + if fileInfo, err := os.Stat(args[0]); err == nil { + if fileInfo.IsDir() { + peerKeyPath = args[0] + "/peer.key" + } else { + fmt.Printf("%s has already existed.\n", args[0]) + return + } + } else { + if _, err := os.Stat(filepath.Dir(args[0])); err == nil { + peerKeyPath = args[0] + } else { + fmt.Println(err) + return + } } - peerKeyPath = args[0] + "/peer.key" } key, _, err := libcrypto.GenerateEd25519Key(rand.Reader) if err != nil { @@ -331,4 +346,10 @@ func createPeerID(cmd *cobra.Command, args []string) { return } fmt.Println("generate peer key:", peerKeyPath) + peerID, err := peer.IDFromPublicKey(key.GetPublic()) + if err != nil { + fmt.Println("get peer ID from public key error:", err) + return + } + fmt.Println("peer ID:", peerID.Pretty()) } From cf2a59bac6512646c212392cf32b1449a05f056e Mon Sep 17 00:00:00 2001 From: "shuyi.yu" Date: Thu, 28 Nov 2019 17:54:40 +0800 Subject: [PATCH 2/3] add a flage about file --- commands/box/common/common.go | 19 ++++++ commands/box/contract/contract.go | 46 ++++++++------- commands/box/util/root.go | 98 +++++++++++++++++++------------ 3 files changed, 103 insertions(+), 60 deletions(-) diff --git a/commands/box/common/common.go b/commands/box/common/common.go index 23b92bfe..900c95d7 100644 --- a/commands/box/common/common.go +++ b/commands/box/common/common.go @@ -10,6 +10,7 @@ import ( "fmt" "io/ioutil" "net" + "os" "path" "strconv" @@ -22,6 +23,7 @@ import ( "github.com/BOXFoundation/boxd/util" "github.com/BOXFoundation/boxd/wallet" "github.com/BOXFoundation/boxd/wallet/account" + "github.com/spf13/cobra" "github.com/spf13/viper" ) @@ -36,6 +38,8 @@ const ( // var ( DefaultWalletDir = path.Join(util.HomeDir(), ".box_keystore") + OutFilePath string + InFilePath string ) // GetRPCAddr gets rpc addr @@ -136,3 +140,18 @@ func IsHexFormat(str string) bool { } return true } + +// GetCurrentFilePath returns a rooted path name corresponding to the current directory. +func GetCurrentFilePath() string { + filePath, err := os.Getwd() + if err != nil { + return "" + } + return filePath +} + +//SetFlag set a flage to flag the file +func SetFlag(cmd *cobra.Command) { + cmd.PersistentFlags().StringVar(&OutFilePath, "o", GetCurrentFilePath(), "output file path, default current directory") + cmd.PersistentFlags().StringVar(&InFilePath, "i", "", "input file path, default nil") +} diff --git a/commands/box/contract/contract.go b/commands/box/contract/contract.go index 01afcc93..8d686570 100644 --- a/commands/box/contract/contract.go +++ b/commands/box/contract/contract.go @@ -98,6 +98,14 @@ var rootCmd = &cobra.Command{ `, } +var ( + compileCmd = &cobra.Command{ + Use: "compile", + Short: "Compile contract source file", + Run: compile, + } +) + func init() { root.RootCmd.AddCommand(rootCmd) rootCmd.AddCommand( @@ -154,12 +162,9 @@ func init() { Short: "view contract details", Run: detailAbi, }, - &cobra.Command{ - Use: "compile [sol_file_path] [optional|ouput_file_path]", - Short: "Compile contract source file", - Run: compile, - }, + compileCmd, ) + common.SetFlag(compileCmd) } func importAbi(cmd *cobra.Command, args []string) { @@ -238,9 +243,7 @@ func importAbi(cmd *cobra.Command, args []string) { fmt.Printf("Would you want to change current index into %d. [Y/n]\n", max+1) var input string fmt.Scanf("%s", &input) - switch { - case input == "n" || input == "N": - default: + if input != "n" && input != "N" { setabi(&cobra.Command{}, []string{strconv.Itoa(max + 1)}) } } @@ -1282,25 +1285,26 @@ func detailAbi(cmd *cobra.Command, args []string) { } func compile(cmd *cobra.Command, args []string) { - if len(args) == 0 || len(args) > 2 { + if len(args) != 0 { fmt.Println(cmd.Use) return } - filepath := args[0] - if err := util.FileExists(filepath); err != nil { + if len(common.InFilePath) == 0 { + fmt.Println("please input the path of peer.key") + return + } + if err := util.FileExists(common.InFilePath); err != nil { fmt.Println(err) return } - var outputDir string - if len(args) == 1 { - currentFilePath, err := os.Getwd() - if err != nil { - fmt.Println(err) - return - } - outputDir = currentFilePath + "/" - } else if len(args) == 2 { - outputDir = args[1] + "/" + var ( + outputDir string + filepath = common.InFilePath + ) + if common.OutFilePath == common.GetCurrentFilePath() { + outputDir = common.GetCurrentFilePath() + "/" + } else { + outputDir = common.OutFilePath + "/" if _, err := os.Stat(outputDir); err != nil { fmt.Printf("output dir %s error: %s\n", outputDir, err) return diff --git a/commands/box/util/root.go b/commands/box/util/root.go index 10c8ccad..9d0da0b8 100644 --- a/commands/box/util/root.go +++ b/commands/box/util/root.go @@ -15,6 +15,7 @@ import ( "path/filepath" "strconv" + "github.com/BOXFoundation/boxd/commands/box/common" root "github.com/BOXFoundation/boxd/commands/box/root" "github.com/BOXFoundation/boxd/core/txlogic" "github.com/BOXFoundation/boxd/core/types" @@ -36,6 +37,19 @@ var rootCmd = &cobra.Command{ // Run: func(cmd *cobra.Command, args []string) { }, } +var ( + peerIDCmd = &cobra.Command{ + Use: "peerid [optional|peerkey]", + Short: "conversion peer key to peer ID", + Run: peerID, + } + createPeerIDCmd = &cobra.Command{ + Use: "createpeerid ", + Short: "create peer key", + Run: createPeerID, + } +) + // Init adds the sub command to the root command. func init() { root.RootCmd.AddCommand(rootCmd) @@ -70,17 +84,11 @@ func init() { Short: "creat p2pKH address", Run: makeP2PKHAddress, }, - &cobra.Command{ - Use: "peerid [optional|peerkey_path, peerkey]", - Short: "conversion peer key to peer ID", - Run: peerID, - }, - &cobra.Command{ - Use: "createpeerid [optional|peerkey_path]", - Short: "create peer key", - Run: createPeerID, - }, + peerIDCmd, + createPeerIDCmd, ) + common.SetFlag(peerIDCmd) + common.SetFlag(createPeerIDCmd) } func encode(cmd *cobra.Command, args []string) { @@ -252,30 +260,31 @@ func makeP2PKHAddress(cmd *cobra.Command, args []string) { } func peerID(cmd *cobra.Command, args []string) { - if len(args) != 1 { - fmt.Println(cmd.Use) - return - } - var ( - data string - err error - dataByte []byte - ) - if err := util.FileExists(args[0]); err == nil { - dataByte, err = ioutil.ReadFile(args[0]) + var data string + switch len(args) { + case 0: + if len(common.InFilePath) == 0 { + fmt.Println("please input the path of peer.key") + return + } + if err := util.FileExists(common.InFilePath); err != nil { + fmt.Println(err) + return + } + dataByte, err := ioutil.ReadFile(common.InFilePath) if err != nil { fmt.Printf("read data from %s error: %s\n", args[0], err) return } data = string(dataByte) - if _, err := libcrypto.ConfigDecodeKey(data); err != nil { - fmt.Printf("read data from %s, error: %s", args[0], err) + case 1: + if _, err := libcrypto.ConfigDecodeKey(args[0]); err != nil { + fmt.Printf("read data from %s, error: %s.", args[0], err) return } - } else if _, err := libcrypto.ConfigDecodeKey(args[0]); err == nil { data = args[0] - } else { - fmt.Println("invailb argument:", args[0]) + default: + fmt.Println(cmd.Use) return } decodeData, err := base64.StdEncoding.DecodeString(data) @@ -297,32 +306,43 @@ func peerID(cmd *cobra.Command, args []string) { } func createPeerID(cmd *cobra.Command, args []string) { - if len(args) > 1 { + if len(args) != 0 { fmt.Println(cmd.Use) return } var ( peerKeyPath string - err error + sameFile = common.OutFilePath + "/peer.key" ) - if len(args) == 0 { - peerKeyPath, err = os.Getwd() - if err != nil { - fmt.Println(err) + //case 1: check whether peer.key exists. If it doesn't exist, it will generate peer.key. Otherwise, it will return + if common.OutFilePath == common.GetCurrentFilePath() { + if err := util.FileExists(sameFile); err == nil { + fmt.Printf("%s has already existed.\n", sameFile) return } - peerKeyPath += "/peer.key" - } else if len(args) == 1 { - if fileInfo, err := os.Stat(args[0]); err == nil { + peerKeyPath = common.OutFilePath + "/peer.key" + } else { + //case 2: setting the path of output file, the path has already existed. + //case 2.1:if you input a directory, it will check whether the peer.key exits. + //if it doesn't exit, it will generate. Otherwise, it will return + //case 2.2:if you input a file path, it will return. And tell you the file has already existed. + if fileInfo, err := os.Stat(common.OutFilePath); err == nil { if fileInfo.IsDir() { - peerKeyPath = args[0] + "/peer.key" + if err := util.FileExists(sameFile); err == nil { + fmt.Printf("%s has already existed.\n", sameFile) + return + } + peerKeyPath = common.OutFilePath + "/peer.key" } else { - fmt.Printf("%s has already existed.\n", args[0]) + fmt.Printf("%s has already existed.\n", common.OutFilePath) return } } else { - if _, err := os.Stat(filepath.Dir(args[0])); err == nil { - peerKeyPath = args[0] + //case 3: setting the path of output file, the path doesn't exist. Check the directory of the file whether it exists. + //case 3.1: If it doesnit exist, it will return + //case 3.2:If it exists, it will generate a file to save the peerID + if _, err := os.Stat(filepath.Dir(common.OutFilePath)); err == nil { + peerKeyPath = common.OutFilePath } else { fmt.Println(err) return From 21f7e5fa7ca951bc681b8322df4b038b95bf268e Mon Sep 17 00:00:00 2001 From: "shuyi.yu" Date: Tue, 3 Dec 2019 11:24:36 +0800 Subject: [PATCH 3/3] refine the createpeerid and add a func to check file whether it is a file --- commands/box/common/common.go | 32 +---------- commands/box/contract/contract.go | 45 +++++++++------- commands/box/root/root.go | 3 +- commands/box/util/root.go | 89 +++++++++++++++---------------- util/util.go | 16 +++--- 5 files changed, 77 insertions(+), 108 deletions(-) diff --git a/commands/box/common/common.go b/commands/box/common/common.go index 900c95d7..b5fb339d 100644 --- a/commands/box/common/common.go +++ b/commands/box/common/common.go @@ -6,7 +6,6 @@ package common import ( "bytes" - "encoding/hex" "fmt" "io/ioutil" "net" @@ -23,7 +22,6 @@ import ( "github.com/BOXFoundation/boxd/util" "github.com/BOXFoundation/boxd/wallet" "github.com/BOXFoundation/boxd/wallet/account" - "github.com/spf13/cobra" "github.com/spf13/viper" ) @@ -38,8 +36,6 @@ const ( // var ( DefaultWalletDir = path.Join(util.HomeDir(), ".box_keystore") - OutFilePath string - InFilePath string ) // GetRPCAddr gets rpc addr @@ -55,7 +51,7 @@ func GetRPCAddr() string { ) switch { case rpcAddr == nilIP && rpcPort == nilGRPCPort: - if err := util.FileExists(ConnAddrFile); err != nil { + if _, err := os.Stat(ConnAddrFile); err != nil { connAddr = "127.0.0.1:19191" return connAddr } @@ -129,29 +125,3 @@ func SignAndSendTx( } return sendResp.GetHash(), nil } - -//IsHexFormat judge whether str is hex code -func IsHexFormat(str string) bool { - if len(str) == 0 { - return false - } - if _, err := hex.DecodeString(str); err != nil { - return false - } - return true -} - -// GetCurrentFilePath returns a rooted path name corresponding to the current directory. -func GetCurrentFilePath() string { - filePath, err := os.Getwd() - if err != nil { - return "" - } - return filePath -} - -//SetFlag set a flage to flag the file -func SetFlag(cmd *cobra.Command) { - cmd.PersistentFlags().StringVar(&OutFilePath, "o", GetCurrentFilePath(), "output file path, default current directory") - cmd.PersistentFlags().StringVar(&InFilePath, "i", "", "input file path, default nil") -} diff --git a/commands/box/contract/contract.go b/commands/box/contract/contract.go index 8d686570..387e2734 100644 --- a/commands/box/contract/contract.go +++ b/commands/box/contract/contract.go @@ -46,6 +46,8 @@ const ( var ( walletDir string solFilePath string + inFilePath string + outFilePath string solcBinReg = regexp.MustCompile("Binary:\\s?\n([0-9a-f]+)\\s") solcAbiReg = regexp.MustCompile("ABI\\s?\n([\\pP0-9a-zA-Z]+)\\s") solNameReg = regexp.MustCompile(solFilePath + ":([0-9a-zA-Z_]+)\\s") @@ -98,14 +100,6 @@ var rootCmd = &cobra.Command{ `, } -var ( - compileCmd = &cobra.Command{ - Use: "compile", - Short: "Compile contract source file", - Run: compile, - } -) - func init() { root.RootCmd.AddCommand(rootCmd) rootCmd.AddCommand( @@ -162,9 +156,17 @@ func init() { Short: "view contract details", Run: detailAbi, }, - compileCmd, ) - common.SetFlag(compileCmd) + var ( + compileCmd = &cobra.Command{ + Use: "compile", + Short: "Compile contract source file", + Run: compile, + } + ) + rootCmd.AddCommand(compileCmd) + compileCmd.PersistentFlags().StringVar(&inFilePath, "i", "", "input file path, default nil") + compileCmd.PersistentFlags().StringVar(&outFilePath, "o", ".", "output file path, default current directory") } func importAbi(cmd *cobra.Command, args []string) { @@ -1108,7 +1110,7 @@ func parseContractData(data string) (bytecode string, abi string, err error) { return "", "", err } bytesStr := strings.TrimSpace(string(bytes)) - if common.IsHexFormat(bytesStr) { + if _, err := hex.DecodeString(bytesStr); err == nil { bytecode = bytesStr } else { binData, abiData, solName, err := compileSol(data) @@ -1138,7 +1140,7 @@ func parseContractData(data string) (bytecode string, abi string, err error) { } } } else { - if !common.IsHexFormat(data) { + if _, err := hex.DecodeString(data); err != nil { return "", "", err } bytecode = data @@ -1210,7 +1212,7 @@ func detailAbi(cmd *cobra.Command, args []string) { } if len(args) == 1 { fileName := args[0] - if err := util.FileExists(fileName); err == nil { + if _, err := os.Stat(fileName); err == nil { abiObj, err = newAbiObjFromFile(fileName) if err != nil { fmt.Printf("new abi object from file %s error:%s\n", fileName, err) @@ -1289,22 +1291,27 @@ func compile(cmd *cobra.Command, args []string) { fmt.Println(cmd.Use) return } - if len(common.InFilePath) == 0 { + if len(inFilePath) == 0 { fmt.Println("please input the path of peer.key") return } - if err := util.FileExists(common.InFilePath); err != nil { + if _, err := os.Stat(inFilePath); err != nil { fmt.Println(err) return } var ( outputDir string - filepath = common.InFilePath + filepath = inFilePath ) - if common.OutFilePath == common.GetCurrentFilePath() { - outputDir = common.GetCurrentFilePath() + "/" + currentFilePath, err := os.Getwd() + if err != nil { + fmt.Println(err) + return + } + if outFilePath == currentFilePath { + outputDir = currentFilePath + "/" } else { - outputDir = common.OutFilePath + "/" + outputDir = outFilePath + "/" if _, err := os.Stat(outputDir); err != nil { fmt.Printf("output dir %s error: %s\n", outputDir, err) return diff --git a/commands/box/root/root.go b/commands/box/root/root.go index 8df75e59..47e081e7 100644 --- a/commands/box/root/root.go +++ b/commands/box/root/root.go @@ -15,7 +15,6 @@ import ( "github.com/BOXFoundation/boxd/commands/box/common" "github.com/BOXFoundation/boxd/config" "github.com/BOXFoundation/boxd/log" - "github.com/BOXFoundation/boxd/util" homedir "github.com/mitchellh/go-homedir" "github.com/spf13/cobra" "github.com/spf13/viper" @@ -170,7 +169,7 @@ func resetConn(cmd *cobra.Command, args []string) { fmt.Println(cmd.Use) return } - if err := util.FileExists(common.ConnAddrFile); err != nil { + if _, err := os.Stat(common.ConnAddrFile); err != nil { return } if err := os.Remove(common.ConnAddrFile); err != nil { diff --git a/commands/box/util/root.go b/commands/box/util/root.go index 9d0da0b8..28d6622a 100644 --- a/commands/box/util/root.go +++ b/commands/box/util/root.go @@ -15,7 +15,6 @@ import ( "path/filepath" "strconv" - "github.com/BOXFoundation/boxd/commands/box/common" root "github.com/BOXFoundation/boxd/commands/box/root" "github.com/BOXFoundation/boxd/core/txlogic" "github.com/BOXFoundation/boxd/core/types" @@ -38,16 +37,8 @@ var rootCmd = &cobra.Command{ } var ( - peerIDCmd = &cobra.Command{ - Use: "peerid [optional|peerkey]", - Short: "conversion peer key to peer ID", - Run: peerID, - } - createPeerIDCmd = &cobra.Command{ - Use: "createpeerid ", - Short: "create peer key", - Run: createPeerID, - } + inFilePath string + outFilePath string ) // Init adds the sub command to the root command. @@ -84,11 +75,31 @@ func init() { Short: "creat p2pKH address", Run: makeP2PKHAddress, }, - peerIDCmd, - createPeerIDCmd, + &cobra.Command{ + Use: "test [pubkey]", + Short: "test", + Run: test, + }, + ) + var ( + showPeerIDCmd = &cobra.Command{ + Use: "showpeerid [optional|peerkey]", + Short: "conversion peer key to peer ID", + Run: showPeerID, + } + createPeerIDCmd = &cobra.Command{ + Use: "createpeerid ", + Short: "create peer key", + Run: createPeerID, + } ) - common.SetFlag(peerIDCmd) - common.SetFlag(createPeerIDCmd) + rootCmd.AddCommand(showPeerIDCmd, createPeerIDCmd) + showPeerIDCmd.PersistentFlags().StringVar(&inFilePath, "i", "", "input file path, default nil") + createPeerIDCmd.PersistentFlags().StringVar(&outFilePath, "o", ".", "output file path, default current directory") +} + +func test(cmd *cobra.Command, args []string) { + util.Isfile(args[0]) } func encode(cmd *cobra.Command, args []string) { @@ -259,19 +270,19 @@ func makeP2PKHAddress(cmd *cobra.Command, args []string) { fmt.Printf("address: %s, address hash: %x\n", addr, addr.Hash160()[:]) } -func peerID(cmd *cobra.Command, args []string) { +func showPeerID(cmd *cobra.Command, args []string) { var data string switch len(args) { case 0: - if len(common.InFilePath) == 0 { + if len(inFilePath) == 0 { fmt.Println("please input the path of peer.key") return } - if err := util.FileExists(common.InFilePath); err != nil { + if _, err := os.Stat(inFilePath); err != nil { fmt.Println(err) return } - dataByte, err := ioutil.ReadFile(common.InFilePath) + dataByte, err := ioutil.ReadFile(inFilePath) if err != nil { fmt.Printf("read data from %s error: %s\n", args[0], err) return @@ -312,41 +323,27 @@ func createPeerID(cmd *cobra.Command, args []string) { } var ( peerKeyPath string - sameFile = common.OutFilePath + "/peer.key" + defaultFile = outFilePath + "/peer.key" ) - //case 1: check whether peer.key exists. If it doesn't exist, it will generate peer.key. Otherwise, it will return - if common.OutFilePath == common.GetCurrentFilePath() { - if err := util.FileExists(sameFile); err == nil { - fmt.Printf("%s has already existed.\n", sameFile) + _, err := os.Stat(outFilePath) + if err != nil { + if _, err := os.Stat(filepath.Dir(outFilePath)); err == nil { + peerKeyPath = outFilePath + } else { + fmt.Printf("%s doesn't exist.\n", outFilePath) return } - peerKeyPath = common.OutFilePath + "/peer.key" } else { - //case 2: setting the path of output file, the path has already existed. - //case 2.1:if you input a directory, it will check whether the peer.key exits. - //if it doesn't exit, it will generate. Otherwise, it will return - //case 2.2:if you input a file path, it will return. And tell you the file has already existed. - if fileInfo, err := os.Stat(common.OutFilePath); err == nil { - if fileInfo.IsDir() { - if err := util.FileExists(sameFile); err == nil { - fmt.Printf("%s has already existed.\n", sameFile) - return - } - peerKeyPath = common.OutFilePath + "/peer.key" + if !util.Isfile(outFilePath) { + if _, err := os.Stat(defaultFile); err != nil { + peerKeyPath = defaultFile } else { - fmt.Printf("%s has already existed.\n", common.OutFilePath) + fmt.Printf("%s has already existed.\n", defaultFile) return } } else { - //case 3: setting the path of output file, the path doesn't exist. Check the directory of the file whether it exists. - //case 3.1: If it doesnit exist, it will return - //case 3.2:If it exists, it will generate a file to save the peerID - if _, err := os.Stat(filepath.Dir(common.OutFilePath)); err == nil { - peerKeyPath = common.OutFilePath - } else { - fmt.Println(err) - return - } + fmt.Printf("%s has already existed.\n", outFilePath) + return } } key, _, err := libcrypto.GenerateEd25519Key(rand.Reader) diff --git a/util/util.go b/util/util.go index 7c3e876b..816d532f 100644 --- a/util/util.go +++ b/util/util.go @@ -6,8 +6,6 @@ package util import ( "bytes" - "errors" - "fmt" "os" "os/user" "reflect" @@ -90,13 +88,11 @@ func MkDir(filename string) error { } } -//FileExists check whether a file exists -func FileExists(filename string) error { - if _, err := os.Stat(filename); err != nil { - if os.IsNotExist(err) { - return errors.New("file is not exists") - } - return fmt.Errorf("file status error: %s", err) +//Isfile check a path whether it is a file +func Isfile(filePath string) bool { + fileInfo, _ := os.Stat(filePath) + if fileInfo.IsDir() { + return false } - return nil + return true }