diff --git a/commands/box/common/common.go b/commands/box/common/common.go index 23b92bfe..b5fb339d 100644 --- a/commands/box/common/common.go +++ b/commands/box/common/common.go @@ -6,10 +6,10 @@ package common import ( "bytes" - "encoding/hex" "fmt" "io/ioutil" "net" + "os" "path" "strconv" @@ -51,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 } @@ -125,14 +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 -} diff --git a/commands/box/contract/contract.go b/commands/box/contract/contract.go index 0d596bd1..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") @@ -154,12 +156,17 @@ func init() { Short: "view contract details", Run: detailAbi, }, - &cobra.Command{ - Use: "compile [sol_file_path] [optional|ouput_file_path]", + ) + 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) { @@ -238,9 +245,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)}) } } @@ -1105,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) @@ -1113,26 +1118,29 @@ 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") } } } } else { - if !common.IsHexFormat(data) { + if _, err := hex.DecodeString(data); err != nil { return "", "", err } bytecode = data @@ -1140,7 +1148,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 +1158,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 @@ -1216,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) @@ -1291,25 +1287,31 @@ 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(inFilePath) == 0 { + fmt.Println("please input the path of peer.key") + return + } + if _, err := os.Stat(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 - } + var ( + outputDir string + filepath = inFilePath + ) + currentFilePath, err := os.Getwd() + if err != nil { + fmt.Println(err) + return + } + if outFilePath == currentFilePath { outputDir = currentFilePath + "/" - } else if len(args) == 2 { - outputDir = args[1] + "/" + } else { + outputDir = outFilePath + "/" if _, err := os.Stat(outputDir); err != nil { fmt.Printf("output dir %s error: %s\n", outputDir, err) return @@ -1323,14 +1325,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/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 1c3123e7..28d6622a 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" @@ -35,6 +36,11 @@ var rootCmd = &cobra.Command{ // Run: func(cmd *cobra.Command, args []string) { }, } +var ( + inFilePath string + outFilePath string +) + // Init adds the sub command to the root command. func init() { root.RootCmd.AddCommand(rootCmd) @@ -70,16 +76,30 @@ func init() { Run: makeP2PKHAddress, }, &cobra.Command{ - Use: "peerid [optional|peerkey_path, peerkey]", - Short: "conversion peer key to peer ID", - Run: peerID, + Use: "test [pubkey]", + Short: "test", + Run: test, }, - &cobra.Command{ - Use: "createpeerid [optional|peerkey_path]", + ) + 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, - }, + } ) + 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) { @@ -250,27 +270,32 @@ 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) { - 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]) +func showPeerID(cmd *cobra.Command, args []string) { + var data string + switch len(args) { + case 0: + if len(inFilePath) == 0 { + fmt.Println("please input the path of peer.key") + return + } + if _, err := os.Stat(inFilePath); err != nil { + fmt.Println(err) + return + } + dataByte, err := ioutil.ReadFile(inFilePath) if err != nil { fmt.Printf("read data from %s error: %s\n", args[0], err) return } data = string(dataByte) - } else if _, err := libcrypto.ConfigDecodeKey(args[0]); err == nil { + case 1: + if _, err := libcrypto.ConfigDecodeKey(args[0]); err != nil { + fmt.Printf("read data from %s, error: %s.", args[0], err) + return + } data = args[0] - } else { - fmt.Println("invailb argument:", args[0]) + default: + fmt.Println(cmd.Use) return } decodeData, err := base64.StdEncoding.DecodeString(data) @@ -292,27 +317,34 @@ 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 + defaultFile = outFilePath + "/peer.key" ) - if len(args) == 0 { - peerKeyPath, err = os.Getwd() - if err != nil { - fmt.Println(err) + _, 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 += "/peer.key" - } else if len(args) == 1 { - if err = util.FileExists(args[0]); err != nil { - fmt.Println(err) + } else { + if !util.Isfile(outFilePath) { + if _, err := os.Stat(defaultFile); err != nil { + peerKeyPath = defaultFile + } else { + fmt.Printf("%s has already existed.\n", defaultFile) + return + } + } else { + fmt.Printf("%s has already existed.\n", outFilePath) return } - peerKeyPath = args[0] + "/peer.key" } key, _, err := libcrypto.GenerateEd25519Key(rand.Reader) if err != nil { @@ -331,4 +363,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()) } 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 }