Skip to content

Commit

Permalink
Merge pull request #48 from aquarius-kuchain/features/build-scripts
Browse files Browse the repository at this point in the history
Add Supports for boot chain
  • Loading branch information
aquarius-kuchain authored Sep 14, 2020
2 parents d0823a8 + 865e550 commit f3c3194
Show file tree
Hide file tree
Showing 9 changed files with 205 additions and 44 deletions.
22 changes: 19 additions & 3 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,17 @@ endif
ldflags += $(LDFLAGS)
ldflags := $(strip $(ldflags))

BUILD_FLAGS := -tags "$(build_tags)" -ldflags '$(ldflags)' -trimpath
OS_NAME := $(shell uname -s | tr A-Z a-z)/$(shell uname -m)

os:
@echo $(OS_NAME)

BUILD_FLAGS := -tags "$(build_tags)" -ldflags '$(ldflags)'

BUILD_OS := -osarch="linux/arm linux/amd64 windows/amd64"
ifneq ($(OS_NAME), darwin/x86_64)
BUILD_OS = -osarch="linux/arm linux/amd64 windows/amd64 darwin/amd64"
endif

all: clear-build build

Expand All @@ -87,8 +97,14 @@ else
go build -mod=readonly $(BUILD_FLAGS) -o build/kucli ./cmd/kucli
endif

build-linux: go.sum
LEDGER_ENABLED=false GOOS=linux GOARCH=amd64 $(MAKE) build
build-gox: go.sum
gox $(BUILD_FLAGS) $(BUILD_OS) -output "build/kucd_{{.OS}}_{{.Arch}}" ./cmd/kucd
gox $(BUILD_FLAGS) $(BUILD_OS) -output "build/kucli_{{.OS}}_{{.Arch}}" ./cmd/kucli

ifeq ($(OS_NAME), darwin/x86_64)
go build -mod=readonly $(BUILD_FLAGS) -o build/kucd_darwin_amd64 ./cmd/kucd
go build -mod=readonly $(BUILD_FLAGS) -o build/kucli_darwin_amd64 ./cmd/kucli
endif

install: go.sum
go install -mod=readonly $(BUILD_FLAGS) ./cmd/kucd
Expand Down
3 changes: 2 additions & 1 deletion chain/ante/sigverify.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,8 @@ func (svd SigVerificationDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simul

// verify signature
if !simulate && !pubKey.VerifyBytes(signBytes, sig.Signature) {
return ctx, sdkerrors.Wrap(sdkerrors.ErrUnauthorized, "signature verification failed; verify correct account sequence and chain-id")
return ctx, sdkerrors.Wrapf(sdkerrors.ErrUnauthorized,
"signature verification failed; verify correct account sequence and chain-id: %s, seq: %d, num: %d.", ctx.ChainID(), seq, num)
}
}

Expand Down
141 changes: 141 additions & 0 deletions chain/client/keys/parse.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
package keys

import (
"encoding/hex"
"errors"
"fmt"
"strings"

"github.com/spf13/cobra"
"github.com/spf13/viper"
yaml "gopkg.in/yaml.v2"

"github.com/tendermint/tendermint/libs/bech32"
"github.com/tendermint/tendermint/libs/cli"

"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client/keys"
sdk "github.com/cosmos/cosmos-sdk/types"
)

type hexOutput struct {
Human string `json:"human"`
Bytes string `json:"bytes"`
}

func (ho hexOutput) String() string {
return fmt.Sprintf("Human readable part: %v\nBytes (hex): %s", ho.Human, ho.Bytes)
}

func newHexOutput(human string, bs []byte) hexOutput {
return hexOutput{Human: human, Bytes: fmt.Sprintf("%X", bs)}
}

type bech32Output struct {
Formats []string `json:"formats"`
}

func newBech32Output(bs []byte) bech32Output {
var config = sdk.GetConfig()
var bech32Prefixes = []string{
config.GetBech32AccountAddrPrefix(),
config.GetBech32AccountPubPrefix(),
config.GetBech32ValidatorAddrPrefix(),
config.GetBech32ValidatorPubPrefix(),
config.GetBech32ConsensusAddrPrefix(),
config.GetBech32ConsensusPubPrefix(),
}

out := bech32Output{Formats: make([]string, len(bech32Prefixes))}
for i, prefix := range bech32Prefixes {
bech32Addr, err := bech32.ConvertAndEncode(prefix, bs)
if err != nil {
panic(err)
}
out.Formats[i] = bech32Addr
}

return out
}

func (bo bech32Output) String() string {
out := make([]string, len(bo.Formats))

for i, format := range bo.Formats {
out[i] = fmt.Sprintf(" - %s", format)
}

return fmt.Sprintf("Bech32 Formats:\n%s", strings.Join(out, "\n"))
}

// ParseKeyStringCommand parses an address from hex to bech32 and vice versa.
func ParseKeyStringCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "parse <hex-or-bech32-address>",
Short: "Parse address from hex to bech32 and vice versa",
Long: `Convert and print to stdout key addresses and fingerprints from
hexadecimal into bech32 cosmos prefixed format and vice versa.
`,
Args: cobra.ExactArgs(1),
RunE: parseKey,
}
cmd.Flags().Bool(flags.FlagIndentResponse, false, "Indent JSON output")

return cmd
}

func parseKey(_ *cobra.Command, args []string) error {
addr := strings.TrimSpace(args[0])
if len(addr) == 0 {
return errors.New("couldn't parse empty input")
}
if !(runFromBech32(addr) || runFromHex(addr)) {
return errors.New("couldn't find valid bech32 nor hex data")
}
return nil
}

// print info from bech32
func runFromBech32(bech32str string) bool {
hrp, bz, err := bech32.DecodeAndConvert(bech32str)
if err != nil {
return false
}
displayParseKeyInfo(newHexOutput(hrp, bz))
return true
}

// print info from hex
func runFromHex(hexstr string) bool {
bz, err := hex.DecodeString(hexstr)
if err != nil {
return false
}
displayParseKeyInfo(newBech32Output(bz))
return true
}

func displayParseKeyInfo(stringer fmt.Stringer) {
var out []byte
var err error

switch viper.Get(cli.OutputFlag) {
case keys.OutputFormatText:
out, err = yaml.Marshal(&stringer)

case keys.OutputFormatJSON:

if viper.GetBool(flags.FlagIndentResponse) {
out, err = keys.KeysCdc.MarshalJSONIndent(stringer, "", " ")
} else {
out = keys.KeysCdc.MustMarshalJSON(stringer)
}

}

if err != nil {
panic(err)
}

fmt.Println(string(out))
}
11 changes: 11 additions & 0 deletions chain/client/txutil/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,22 @@ func NewKuCLICtx(ctx context.CLIContext) KuCLIContext {
}.WithFromAccount(types.NewAccountIDFromAccAdd(ctx.GetFromAddress()))
}

func NewKuCLICtxNoFrom(ctx context.CLIContext) KuCLIContext {
return KuCLIContext{
CLIContext: ctx,
}
}

// NewKuCLICtxByBuf creates a new KuCLIContext with cmd
func NewKuCLICtxByBuf(cdc *codec.Codec, inBuf io.Reader) KuCLIContext {
return NewKuCLICtx(context.NewCLIContextWithInput(inBuf).WithCodec(cdc))
}

func NewKuCLICtxByBufNoFrom(cdc *codec.Codec, inBuf io.Reader) KuCLIContext {
ctx := context.NewCLIContextWithInput(inBuf).WithCodec(cdc)
return NewKuCLICtxNoFrom(ctx)
}

// WithFromAccount with account from accountID
func (k KuCLIContext) WithFromAccount(from AccountID) KuCLIContext {
k.FromAccount = from
Expand Down
10 changes: 7 additions & 3 deletions cmd/kucli/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (

"github.com/KuChainNetwork/kuchain/app"
blockrest "github.com/KuChainNetwork/kuchain/chain/client/blockutil/client/rest"
kuKeys "github.com/KuChainNetwork/kuchain/chain/client/keys"
txcmd "github.com/KuChainNetwork/kuchain/chain/client/txutil/client/cli"
txrest "github.com/KuChainNetwork/kuchain/chain/client/txutil/client/rest"
chainCfg "github.com/KuChainNetwork/kuchain/chain/config"
Expand All @@ -30,13 +31,15 @@ var (
cdc = app.MakeCodec()
)

func init() {
// Read in the configuration file for the sdk
chainCfg.SealChainConfig()
}

func main() {
// Configure cobra to sort commands
cobra.EnableCommandSorting = false

// Read in the configuration file for the sdk
chainCfg.SealChainConfig()

// TODO: setup keybase, viper object, etc. to be passed into
// the below functions and eliminate global vars, like we do
// with the cdc
Expand Down Expand Up @@ -65,6 +68,7 @@ func main() {
flags.LineBreak,
version.Cmd,
flags.NewCompletionCmd(rootCmd, true),
kuKeys.ParseKeyStringCommand(),
)

// Add flags and prefix all env exposed with GA
Expand Down
39 changes: 14 additions & 25 deletions x/genutil/client/cli/gentx.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
chainTypes "github.com/KuChainNetwork/kuchain/chain/types"
"github.com/KuChainNetwork/kuchain/x/genutil"
"github.com/KuChainNetwork/kuchain/x/genutil/types"
"github.com/cosmos/cosmos-sdk/client/context"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/crypto/keys"
Expand All @@ -36,7 +37,7 @@ type StakingMsgBuildingHelpers interface {
PrepareFlagsForTxCreateValidator(config *cfg.Config, nodeID, chainID string, valPubKey crypto.PubKey)

BuildCreateValidatorMsg(cliCtx txutil.KuCLIContext, txBldr txutil.TxBuilder, operAccountID chainTypes.AccountID, authAddress sdk.AccAddress) (txutil.TxBuilder, sdk.Msg, error)
BuildDelegateMsg(cliCtx txutil.KuCLIContext, txBldr txutil.TxBuilder, delAccountID chainTypes.AccountID, valAccountID chainTypes.AccountID) (txutil.TxBuilder, sdk.Msg, error)
BuildDelegateMsg(cliCtx txutil.KuCLIContext, txBldr txutil.TxBuilder, authAddress chainTypes.AccAddress, delAccountID chainTypes.AccountID, valAccountID chainTypes.AccountID) (txutil.TxBuilder, sdk.Msg, error)
}

// GenTxCmd builds the application's gentx command.
Expand All @@ -48,9 +49,9 @@ func GenTxCmd(ctx *server.Context, cdc *codec.Codec, mbm module.BasicManager, sm
fsCreateValidator, flagNodeID, flagPubKey, _, defaultsDesc := smbh.CreateValidatorMsgHelpers(ipDefault)

cmd := &cobra.Command{
Use: "gentx [validator-operator-account]",
Use: "gentx [validator-operator-account] [validator-account-auth-address]",
Short: "Generate a genesis tx carrying a self delegation",
Args: cobra.ExactArgs(1),
Args: cobra.ExactArgs(2),
Long: fmt.Sprintf(`This command is an alias of the 'tx create-validator' command'.
It creates a genesis transaction to create a validator.
Expand All @@ -69,6 +70,7 @@ func GenTxCmd(ctx *server.Context, cdc *codec.Codec, mbm module.BasicManager, sm
if nodeIDString := viper.GetString(flagNodeID); nodeIDString != "" {
nodeID = nodeIDString
}

// Read --pubkey, if empty take it from priv_validator.json
if valPubKeyString := viper.GetString(flagPubKey); valPubKeyString != "" {
valPubKey, err = sdk.GetPubKeyFromBech32(sdk.Bech32PubKeyTypeConsPub, valPubKeyString)
Expand All @@ -92,30 +94,28 @@ func GenTxCmd(ctx *server.Context, cdc *codec.Codec, mbm module.BasicManager, sm
}

inBuf := bufio.NewReader(cmd.InOrStdin())
kb, err := keys.NewKeyring(sdk.KeyringServiceName(),
_, err = keys.NewKeyring(sdk.KeyringServiceName(),
viper.GetString(flags.FlagKeyringBackend), viper.GetString(flagClientHome), inBuf)
if err != nil {
return errors.Wrap(err, "failed to initialize keybase")
}

name := viper.GetString(flags.FlagName)
key, err := kb.Get(name)
if err != nil {
return errors.Wrap(err, "failed to read from keybase")
}

authAccAddress := key.GetAddress()
authAccAddress := chainTypes.MustAccAddressFromBech32(args[1])

// Set flags for creating gentx
viper.Set(flags.FlagHome, viper.GetString(flagClientHome))
smbh.PrepareFlagsForTxCreateValidator(config, nodeID, genDoc.ChainID, valPubKey)

txBldr := txutil.NewTxBuilderFromCLI(inBuf).WithTxEncoder(txutil.GetTxEncoder(cdc))
cliCtx := txutil.NewKuCLICtxByBuf(cdc, inBuf)

// Set the generate-only flag here after the CLI context has
// been created. This allows the from name/key to be correctly populated.
viper.Set(flags.FlagGenerateOnly, true)
viper.Set(flags.FlagFrom, args[1])

ctxCli := context.NewCLIContextWithInput(inBuf).WithCodec(cdc)
cliCtx := txutil.NewKuCLICtxNoFrom(ctxCli)

valAccountID, err := chainTypes.NewAccountIDFromStr(args[0])
if err != nil {
return errors.Wrap(err, "Invalid validator account ID")
Expand All @@ -126,19 +126,14 @@ func GenTxCmd(ctx *server.Context, cdc *codec.Codec, mbm module.BasicManager, sm
return errors.Wrap(err, "failed to build create-validator message")
}

txBldr, msgdelegator, err := smbh.BuildDelegateMsg(cliCtx, txBldr, valAccountID, valAccountID)
txBldr, msgdelegator, err := smbh.BuildDelegateMsg(cliCtx, txBldr, authAccAddress, valAccountID, valAccountID)
if err != nil {
return errors.Wrap(err, "failed to build create-validator message")
}

// set payer in gentx
txBldr = txBldr.WithPayer(args[0])

if key.GetType() == keys.TypeOffline || key.GetType() == keys.TypeMulti {
fmt.Println("Offline key passed in. Use `tx sign` command to sign:")
return txutil.PrintUnsignedStdTx(txBldr, cliCtx, []sdk.Msg{msg, msgdelegator})
}

// write the unsigned transaction to the buffer
w := bytes.NewBuffer([]byte{})
cliCtx = cliCtx.WithOutput(w)
Expand All @@ -153,12 +148,6 @@ func GenTxCmd(ctx *server.Context, cdc *codec.Codec, mbm module.BasicManager, sm
return errors.Wrap(err, "failed to read unsigned gen tx file")
}

// sign the transaction and write it to the output file
signedTx, err := txutil.SignStdTx(txBldr, cliCtx, name, stdTx, false, true)
if err != nil {
return errors.Wrap(err, "failed to sign std tx")
}

// Fetch output file name
outputDocument := viper.GetString(flags.FlagOutputDocument)
if outputDocument == "" {
Expand All @@ -168,7 +157,7 @@ func GenTxCmd(ctx *server.Context, cdc *codec.Codec, mbm module.BasicManager, sm
}
}

if err := writeSignedGenTx(cdc, outputDocument, signedTx); err != nil {
if err := writeSignedGenTx(cdc, outputDocument, stdTx); err != nil {
return errors.Wrap(err, "failed to write signed gen tx")
}

Expand Down
7 changes: 4 additions & 3 deletions x/genutil/gentx_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ package genutil_test
import (
"bufio"
"encoding/json"
"os"
"testing"

"github.com/KuChainNetwork/kuchain/chain/client/txutil"
"github.com/KuChainNetwork/kuchain/chain/types"
"github.com/KuChainNetwork/kuchain/test/simapp"
Expand All @@ -19,8 +22,6 @@ import (
"github.com/spf13/viper"
tcmd "github.com/tendermint/tendermint/cmd/tendermint/commands"
"github.com/tendermint/tendermint/libs/cli"
"os"
"testing"
)

var smbh = staking.AppModuleBasic{}
Expand All @@ -47,7 +48,7 @@ func TestSetGenTxsInAppGenesisState(t *testing.T) {
txBldr, msg, err := smbh.BuildCreateValidatorMsg(cliCtx, txBldr, valAccountID, auth)
So(err, ShouldBeNil)

txBldr, msgdelegator, err := smbh.BuildDelegateMsg(cliCtx, txBldr, valAccountID, valAccountID)
txBldr, msgdelegator, err := smbh.BuildDelegateMsg(cliCtx, txBldr, auth, valAccountID, valAccountID)
So(err, ShouldBeNil)

stdSignMsg, err := txBldr.BuildSignMsg([]sdk.Msg{msg, msgdelegator})
Expand Down
Loading

0 comments on commit f3c3194

Please sign in to comment.