Skip to content

Commit

Permalink
add option for console
Browse files Browse the repository at this point in the history
  • Loading branch information
bxq2011hust committed Jan 4, 2024
1 parent 5e335e5 commit 58b4802
Show file tree
Hide file tree
Showing 19 changed files with 607 additions and 93 deletions.
8 changes: 4 additions & 4 deletions .ci/hello/HelloWorld.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 4 additions & 4 deletions .ci/store/Store.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,7 @@ cp .ci/hello/HelloWorld.sol ./hello

```bash
# 国密请使用 ./abigen --bin ./hello/HelloWorld.bin --abi ./hello/HelloWorld.abi --pkg hello --type HelloWorld --out ./hello/HelloWorld.go --smcrypto=true
# 注意:国密模式,请使用国密solc编译得到bin
./abigen --bin ./hello/HelloWorld.bin --abi ./hello/HelloWorld.abi --pkg hello --type HelloWorld --out ./hello/HelloWorld.go
```

Expand Down Expand Up @@ -243,7 +244,12 @@ func main() {
return
}
done := make(chan bool)
_, err = helloSession.WatchAllSetValue(nil, func(ret int, logs []types.Log) {
currentBlock, err := client.GetBlockNumber(context.Background())
if err != nil {
fmt.Printf("GetBlockNumber() failed: %v", err)
return
}
_, err = helloSession.WatchAllSetValue(&currentBlock, func(ret int, logs []types.Log) {
fmt.Printf("WatchAllSetValue receive statud: %d, logs: %v\n", ret, logs)
setValue, err := helloSession.ParseSetValue(logs[0])
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion v3/abi/bind/base.go
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ func (c *BoundContract) asyncTransact(opts *TransactOpts, contract *common.Addre

// WatchLogs filters subscribes to contract logs for future blocks, returning a
// subscription object that can be used to tear down the watcher.
func (c *BoundContract) WatchLogs(fromBlock *uint64, handler func(int, []types.Log), name string, query ...interface{}) (string, error) {
func (c *BoundContract) WatchLogs(fromBlock *int64, handler func(int, []types.Log), name string, query ...interface{}) (string, error) {
from := int64(1)
to := int64(-1)
// Don't crash on a lazy user
Expand Down
8 changes: 4 additions & 4 deletions v3/abi/bind/template.go
Original file line number Diff line number Diff line change
Expand Up @@ -400,11 +400,11 @@ var (
// Watch{{.Normalized.Name}} is a free log subscription operation binding the contract event 0x{{printf "%x" .Original.ID}}.
//
// Solidity: {{formatevent .Original $structs}}
func (_{{$contract.Type}} *{{$contract.Type}}Filterer) Watch{{.Normalized.Name}}(fromBlock *uint64, handler func(int, []types.Log){{range .Normalized.Inputs}}{{if .Indexed}}, {{.Name}} {{bindtype .Type $structs}}{{end}}{{end}}) (string, error) {
func (_{{$contract.Type}} *{{$contract.Type}}Filterer) Watch{{.Normalized.Name}}(fromBlock *int64, handler func(int, []types.Log){{range .Normalized.Inputs}}{{if .Indexed}}, {{.Name}} {{bindtype .Type $structs}}{{end}}{{end}}) (string, error) {
return _{{$contract.Type}}.contract.WatchLogs(fromBlock, handler, "{{.Original.Name}}"{{range .Normalized.Inputs}}{{if .Indexed}}, {{.Name}}{{end}}{{end}})
}
func (_{{$contract.Type}} *{{$contract.Type}}Filterer) WatchAll{{.Normalized.Name}}(fromBlock *uint64, handler func(int, []types.Log)) (string, error) {
func (_{{$contract.Type}} *{{$contract.Type}}Filterer) WatchAll{{.Normalized.Name}}(fromBlock *int64, handler func(int, []types.Log)) (string, error) {
return _{{$contract.Type}}.contract.WatchLogs(fromBlock, handler, "{{.Original.Name}}")
}
Expand All @@ -422,11 +422,11 @@ var (
// Watch{{.Normalized.Name}} is a free log subscription operation binding the contract event 0x{{printf "%x" .Original.ID}}.
//
// Solidity: {{formatevent .Original $structs}}
func (_{{$contract.Type}} *{{$contract.Type}}Session) Watch{{.Normalized.Name}}(fromBlock *uint64, handler func(int, []types.Log){{range .Normalized.Inputs}}{{if .Indexed}}, {{.Name}} {{bindtype .Type $structs}}{{end}}{{end}}) (string, error) {
func (_{{$contract.Type}} *{{$contract.Type}}Session) Watch{{.Normalized.Name}}(fromBlock *int64, handler func(int, []types.Log){{range .Normalized.Inputs}}{{if .Indexed}}, {{.Name}} {{bindtype .Type $structs}}{{end}}{{end}}) (string, error) {
return _{{$contract.Type}}.Contract.Watch{{.Normalized.Name}}(fromBlock, handler {{range .Normalized.Inputs}}{{if .Indexed}}, {{.Name}}{{end}}{{end}})
}
func (_{{$contract.Type}} *{{$contract.Type}}Session) WatchAll{{.Normalized.Name}}(fromBlock *uint64, handler func(int, []types.Log)) (string, error) {
func (_{{$contract.Type}} *{{$contract.Type}}Session) WatchAll{{.Normalized.Name}}(fromBlock *int64, handler func(int, []types.Log)) (string, error) {
return _{{$contract.Type}}.Contract.WatchAll{{.Normalized.Name}}(fromBlock, handler)
}
Expand Down
8 changes: 4 additions & 4 deletions v3/client/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,11 @@ func ParseConfigOptions(caFile string, key string, cert, keyFile string, groupId
if err != nil {
return nil, fmt.Errorf("parse private key failed, err: %v", err)
}
if config.IsSMCrypto && curve != sm2p256v1 {
return nil, fmt.Errorf("smcrypto must use sm2p256v1 private key, but found %s", curve)
if config.IsSMCrypto && curve != Sm2p256v1 {
return nil, fmt.Errorf("smcrypto should use sm2p256v1 private key, but found %s", curve)

Check warning on line 41 in v3/client/config.go

View check run for this annotation

Codecov / codecov/patch

v3/client/config.go#L40-L41

Added lines #L40 - L41 were not covered by tests
}
if !config.IsSMCrypto && curve != secp256k1 {
return nil, fmt.Errorf("must use secp256k1 private key, but found %s", curve)
if !config.IsSMCrypto && curve != Secp256k1 {
return nil, fmt.Errorf("must should secp256k1 private key, but found %s", curve)

Check warning on line 44 in v3/client/config.go

View check run for this annotation

Codecov / codecov/patch

v3/client/config.go#L43-L44

Added lines #L43 - L44 were not covered by tests
}
config.PrivateKey = keyBytes
return &config, nil
Expand Down
4 changes: 2 additions & 2 deletions v3/client/parse_pem.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ import (
)

const (
secp256k1 = "secp256k1"
sm2p256v1 = "sm2p256v1"
Secp256k1 = "secp256k1"
Sm2p256v1 = "sm2p256v1"
)

var (
Expand Down
30 changes: 15 additions & 15 deletions v3/cmd/commandline/commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ const (
// and reset your terminal to use autocompletion.`,
// Run: func(cmd *cobra.Command, args []string) {
// rootCmd.GenZshCompletionFile("_console");
// fmt.Println("zsh file _console had created on your current diretory successfully.")
// fmt.Println("zsh file _console had created on your current directory successfully.")
// },
// }

Expand Down Expand Up @@ -89,8 +89,8 @@ The block height is encoded in hex`,
},
}

var getPbftViewCmd = &cobra.Command{
Use: "getPbftView",
var getPBFTViewCmd = &cobra.Command{
Use: "getPBFTView",
Short: " Get the latest PBFT view(PBFT consensus only)",
Long: `Returns the latest PBFT view in the specified group where the node is located.
The PBFT view is encoded in hex`,
Expand Down Expand Up @@ -376,7 +376,7 @@ For more information please refer:
fmt.Printf("block not found: %v\n", err)
return
}
js, err := json.MarshalIndent(block, "", indent)
js, _ := json.MarshalIndent(block, "", indent)
fmt.Printf("Block: \n%s\n", js)
},
}
Expand Down Expand Up @@ -658,7 +658,7 @@ func init() {
// add common command
rootCmd.AddCommand(completionCmd)
// add node command
rootCmd.AddCommand(getGroupIDCmd, getBlockNumberCmd, getPbftViewCmd, getSealerListCmd)
rootCmd.AddCommand(getGroupIDCmd, getBlockNumberCmd, getPBFTViewCmd, getSealerListCmd)
rootCmd.AddCommand(getObserverListCmd, getConsensusStatusCmd, getSyncStatusCmd, getPeersCmd, getGroupPeersCmd)
rootCmd.AddCommand(getNodeIDListCmd, getGroupListCmd, getNodeInfoCmd, getGroupInfoCmd, getGroupInfoListCmd)
// add block access command
Expand All @@ -671,33 +671,33 @@ func init() {

// cobra.OnInitialize(initConfig)

// FIXME: add a custom help command or find a way to make help command work without network

// Here you will define your flags and configuration settings.
// Cobra supports persistent flags, which, if defined here,
// will be global for your application.

rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is the project directory ./config.ini)")

// Cobra also supports local flags, which will only run
// when this action is called directly.
// rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
// rootCmd.PersistentFlags().StringVarP(&cfgFile, "config", "c", "", "config file (default is the project directory ./config.ini)")
rootCmd.Flags().StringVarP(&cfgFile, "privateKeyPath", "p", "", "private key file path of pem format")
rootCmd.Flags().BoolVarP(&smCrypto, "smCrypto", "s", false, "use smCrypto or not, default is false")
rootCmd.Flags().BoolVarP(&disableSsl, "disableSsl", "d", false, "switch off ssl or not, default use ssl")
rootCmd.PersistentFlags().StringVarP(&groupID, "groupID", "g", "group0", "groupID of FISCO BCOS chain")
rootCmd.PersistentFlags().StringVarP(&nodeEndpoint, "nodeEndpoint", "n", "127.0.0.1:20200", "node endpoint, default is 127.0.0.1:20200")
rootCmd.PersistentFlags().StringVarP(&certPath, "certPath", "c", "./conf", "cert path, default is ./conf, should contain ca.crt, sdk.crt, sdk.key")
}

func isValidHex(str string) (bool, error) {
// starts with "0x"
if strings.HasPrefix(str, "0x") {
if len(str) == 2 {
return false, fmt.Errorf("not a valid hex string: arguments error: please check your inpunt: %s%s", str, info)
return false, fmt.Errorf("not a valid hex string: arguments error: please check your input: %s%s", str, info)
}
// is hex string
_, err := hexutil.Decode(str)
if err != nil {
return false, fmt.Errorf("not a valid hex string: arguments error: please check your inpunt: %s%s: %v", str, info, err)
return false, fmt.Errorf("not a valid hex string: arguments error: please check your input: %s%s: %v", str, info, err)
}
return true, nil
}
return false, fmt.Errorf("arguments error: Not a valid hex string, please check your inpunt: %s%s", str, info)
return false, fmt.Errorf("arguments error: Not a valid hex string, please check your input: %s%s", str, info)
}

func isBlockNumberOutOfRange(blockNumber int64) (bool, error) {
Expand Down
20 changes: 4 additions & 16 deletions v3/cmd/commandline/kvTable.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (

var createTable = &cobra.Command{
Use: "createTable",
Short: "[tableName] [keyName] [valueName] create table",
Short: "<tableName> <keyName> <valueName>",
Long: `createTable.
Arguments:
[tableName]: string
Expand All @@ -18,11 +18,7 @@ Arguments:
For example:
[createTable] [table1] [key1] [value1]
For more information please refer:
https://fisco-bcos-documentation.readthedocs.io/zh_CN/latest/docs/manual/console.html#addobserver`,
createTable table1 key1 value1`,
Args: cobra.ExactArgs(3),
Run: func(cmd *cobra.Command, args []string) {
tableName := args[0]
Expand Down Expand Up @@ -60,11 +56,7 @@ Arguments:
For example:
[set] [table1] [key1] [value1]
For more information please refer:
https://fisco-bcos-documentation.readthedocs.io/zh_CN/latest/docs/manual/console.html#addsealer`,
set table1 key1 value1`,
Args: cobra.ExactArgs(3),
Run: func(cmd *cobra.Command, args []string) {
tableName := args[0]
Expand Down Expand Up @@ -104,11 +96,7 @@ Arguments:
For example:
[get] [tableName] [key1]
For more information please refer:
https://fisco-bcos-documentation.readthedocs.io/zh_CN/latest/docs/manual/console.html#removenode`,
[get] [tableName] [key1]`,
Args: cobra.ExactArgs(2),
Run: func(cmd *cobra.Command, args []string) {
tableName := args[0]
Expand Down
49 changes: 36 additions & 13 deletions v3/cmd/commandline/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,25 +5,24 @@ import (
"encoding/hex"
"fmt"
"os"
"strconv"
"strings"

"github.com/FISCO-BCOS/go-sdk/v3/client"
"github.com/spf13/cobra"
)

var cfgFile string
var privateKeyFilePath string
var smCrypto bool
var disableSsl bool
var nodeEndpoint string
var groupID string
var certPath string

// RPC is the client connected to the blockchain
var RPC *client.Client

// GroupID default
var GroupID uint

// ChainID default
var ChainID int64

// URL default
var URL string

// GetClient is used for test, it will be init by a config file later.
func getClient(config *client.Config) *client.Client {
// RPC API
Expand All @@ -39,7 +38,7 @@ func getClient(config *client.Config) *client.Client {
var rootCmd = &cobra.Command{
Use: "console",
Short: "console is a command line tool for FISCO BCOS 3.0.0",
Version: "0.10.0",
Version: "3.0.0",
Long: `console is a Golang client for FISCO BCOS 3.0.0 and it supports the JSON-RPC
service and the contract operations(e.g. deploying && writing contracts).
Expand Down Expand Up @@ -71,8 +70,32 @@ func Execute() {

// initConfig reads in config file and ENV variables if set.
func initConfig() {
privateKey, _ := hex.DecodeString("145e247e170ba3afd6ae97e88f00dbc976c2345d511b0f6713355d19d8b80b58")
config := &client.Config{IsSMCrypto: false, GroupID: "group0",
PrivateKey: privateKey, Host: "127.0.0.1", Port: 20200, TLSCaFile: "./ca.crt", TLSKeyFile: "./sdk.key", TLSCertFile: "./sdk.crt"}
var privateKey []byte
if len(privateKeyFilePath) != 0 {
_, err := os.Stat(privateKeyFilePath)
if err != nil && os.IsNotExist(err) {
fmt.Println("private key file set but not exist, use default private key")
}
key, curve, err := client.LoadECPrivateKeyFromPEM(privateKeyFilePath)
if err != nil {
fmt.Printf("parse private key failed, err: %v\n", err)
return
}
if smCrypto && curve != client.Sm2p256v1 {
fmt.Printf("smCrypto should use sm2p256v1 private key, but found %s\n", curve)
return
}
if !smCrypto && curve != client.Secp256k1 {
fmt.Printf("should use secp256k1 private key, but found %s\n", curve)
}
privateKey = key
} else {
privateKey, _ = hex.DecodeString("145e247e170ba3afd6ae97e88f00dbc976c2345d511b0f6713355d19d8b80b58")
}
ret := strings.Split(nodeEndpoint, ":")
host := ret[0]
port, _ := strconv.Atoi(ret[1])
config := &client.Config{IsSMCrypto: smCrypto, GroupID: groupID, DisableSsl: disableSsl,
PrivateKey: privateKey, Host: host, Port: port, TLSCaFile: certPath + "/ca.crt", TLSKeyFile: certPath + "/sdk.key", TLSCertFile: certPath + "/sdk.crt"}
RPC = getClient(config)
}
6 changes: 1 addition & 5 deletions v3/cmd/commandline/system_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,7 @@ Arguments:
For example:
[setSystemConfigByKey] [tx_count_limit] 10000
For more information please refer:
https://fisco-bcos-documentation.readthedocs.io/zh_CN/latest/docs/api.html#`,
[setSystemConfigByKey] [tx_count_limit] 10000`,
Args: cobra.ExactArgs(2),
Run: func(cmd *cobra.Command, args []string) {
//configMap := make(map[string]struct{})
Expand Down
8 changes: 4 additions & 4 deletions v3/examples/KVTableTest.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit 58b4802

Please sign in to comment.