additions

This commit is contained in:
Federico Kunze
2021-04-18 17:54:18 +02:00
parent 5a3d514ba0
commit 614e62fb7e
138 changed files with 11348 additions and 2906 deletions
-22
View File
@@ -61,25 +61,3 @@ func ValidateChainID(baseCmd *cobra.Command) *cobra.Command {
baseCmd.RunE = validateFn
return baseCmd
}
// GenerateChainID wraps a cobra command with a RunE function with base 10 integer chain-id random generation
// when a chain-id is not provided.
func GenerateChainID(baseCmd *cobra.Command) *cobra.Command {
// Copy base run command to be used after chain verification
baseRunE := baseCmd.RunE
// Function to replace command's RunE function
generateFn := func(cmd *cobra.Command, args []string) error {
chainID, _ := cmd.Flags().GetString(flags.FlagChainID)
if chainID == "" {
if err := cmd.Flags().Set(flags.FlagChainID, ethermint.GenerateRandomChainID()); err != nil {
return fmt.Errorf("could not set random chain-id: %v", err)
}
}
return baseRunE(cmd, args)
}
baseCmd.RunE = generateFn
return baseCmd
}
+6 -8
View File
@@ -5,17 +5,15 @@ import (
"fmt"
"strings"
"github.com/spf13/cobra"
"github.com/ethereum/go-ethereum/common/hexutil"
ethcrypto "github.com/ethereum/go-ethereum/crypto"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client/input"
"github.com/cosmos/cosmos-sdk/crypto"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/ethereum/go-ethereum/common/hexutil"
ethcrypto "github.com/ethereum/go-ethereum/crypto"
"github.com/spf13/cobra"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
"github.com/cosmos/ethermint/crypto/ethsecp256k1"
"github.com/cosmos/ethermint/crypto/hd"
)
@@ -77,13 +75,13 @@ func UnsafeExportEthKeyCommand() *cobra.Command {
}
// Converts key to Ethermint secp256 implementation
ethermintPrivKey, ok := privKey.(*ethsecp256k1.PrivKey)
ethPrivKey, ok := privKey.(*ethsecp256k1.PrivKey)
if !ok {
return fmt.Errorf("invalid private key type %T, expected %T", privKey, &ethsecp256k1.PrivKey{})
}
// Formats key for output
privB := ethcrypto.FromECDSA(ethermintPrivKey.ToECDSA())
privB := ethcrypto.FromECDSA(ethPrivKey.ToECDSA())
keyS := strings.ToUpper(hexutil.Encode(privB)[2:])
fmt.Println(keyS)
+58
View File
@@ -0,0 +1,58 @@
package client
import (
"bufio"
"github.com/spf13/cobra"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client/input"
"github.com/cosmos/cosmos-sdk/crypto"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/ethermint/crypto/ethsecp256k1"
"github.com/ethereum/go-ethereum/common"
"github.com/cosmos/ethermint/crypto/hd"
)
// UnsafeImportKeyCommand imports private keys from a keyfile.
func UnsafeImportKeyCommand() *cobra.Command {
return &cobra.Command{
Use: "unsafe-import-eth-key <name> <pk>",
Short: "**UNSAFE** Import Ethereum private keys into the local keybase",
Long: "**UNSAFE** Import a hex-encoded Ethereum private key into the local keybase.",
Args: cobra.ExactArgs(2),
RunE: runImportCmd,
}
}
func runImportCmd(cmd *cobra.Command, args []string) error {
inBuf := bufio.NewReader(cmd.InOrStdin())
keyringBackend, _ := cmd.Flags().GetString(flags.FlagKeyringBackend)
rootDir, _ := cmd.Flags().GetString(flags.FlagHome)
kb, err := keyring.New(
sdk.KeyringServiceName(),
keyringBackend,
rootDir,
inBuf,
hd.EthSecp256k1Option(),
)
if err != nil {
return err
}
passphrase, err := input.GetPassword("Enter passphrase to encrypt your key:", inBuf)
if err != nil {
return err
}
privKey := &ethsecp256k1.PrivKey{
Key: common.FromHex(args[1]),
}
armor := crypto.EncryptArmorPrivKey(privKey, passphrase, "eth_secp256k1")
return kb.ImportPrivKey(args[0], armor, passphrase)
}
+109
View File
@@ -0,0 +1,109 @@
package client
import (
"bufio"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client/keys"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/spf13/cobra"
"github.com/tendermint/tendermint/libs/cli"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
"github.com/cosmos/ethermint/crypto/hd"
)
const (
flagDryRun = "dry-run"
)
// KeyCommands registers a sub-tree of commands to interact with
// local private key storage.
func KeyCommands(defaultNodeHome string) *cobra.Command {
cmd := &cobra.Command{
Use: "keys",
Short: "Manage your application's keys",
Long: `Keyring management commands. These keys may be in any format supported by the
Tendermint crypto library and can be used by light-clients, full nodes, or any other application
that needs to sign with a private key.
The keyring supports the following backends:
os Uses the operating system's default credentials store.
file Uses encrypted file-based keystore within the app's configuration directory.
This keyring will request a password each time it is accessed, which may occur
multiple times in a single command resulting in repeated password prompts.
kwallet Uses KDE Wallet Manager as a credentials management application.
pass Uses the pass command line utility to store and retrieve keys.
test Stores keys insecurely to disk. It does not prompt for a password to be unlocked
and it should be use only for testing purposes.
kwallet and pass backends depend on external tools. Refer to their respective documentation for more
information:
KWallet https://github.com/KDE/kwallet
pass https://www.passwordstore.org/
The pass backend requires GnuPG: https://gnupg.org/
`,
}
// support adding Ethereum supported keys
addCmd := keys.AddKeyCommand()
// update the default signing algorithm value to "eth_secp256k1"
algoFlag := addCmd.Flag("algo")
algoFlag.DefValue = string(hd.EthSecp256k1Type)
err := algoFlag.Value.Set(string(hd.EthSecp256k1Type))
if err != nil {
panic(err)
}
addCmd.RunE = runAddCmd
cmd.AddCommand(
keys.MnemonicKeyCommand(),
addCmd,
keys.ExportKeyCommand(),
keys.ImportKeyCommand(),
keys.ListKeysCmd(),
keys.ShowKeysCmd(),
flags.LineBreak,
keys.DeleteKeyCommand(),
keys.ParseKeyStringCommand(),
keys.MigrateCommand(),
flags.LineBreak,
UnsafeExportEthKeyCommand(),
UnsafeImportKeyCommand(),
)
cmd.PersistentFlags().String(flags.FlagHome, defaultNodeHome, "The application home directory")
cmd.PersistentFlags().String(flags.FlagKeyringDir, "", "The client Keyring directory; if omitted, the default 'home' directory will be used")
cmd.PersistentFlags().String(flags.FlagKeyringBackend, keyring.BackendFile, "Select keyring's backend (os|file|test)")
cmd.PersistentFlags().String(cli.OutputFlag, "text", "Output format (text|json)")
return cmd
}
func runAddCmd(cmd *cobra.Command, args []string) error {
buf := bufio.NewReader(cmd.InOrStdin())
clientCtx := client.GetClientContextFromCmd(cmd)
var (
kr keyring.Keyring
err error
)
dryRun, _ := cmd.Flags().GetBool(flags.FlagDryRun)
if dryRun {
kr, err = keyring.New(sdk.KeyringServiceName(), keyring.BackendMemory, clientCtx.KeyringDir, buf, hd.EthSecp256k1Option())
} else {
backend, _ := cmd.Flags().GetString(flags.FlagKeyringBackend)
kr, err = keyring.New(sdk.KeyringServiceName(), backend, clientCtx.KeyringDir, buf, hd.EthSecp256k1Option())
}
if err != nil {
return err
}
return keys.RunAddCmd(cmd, args, kr, buf)
}
+90 -15
View File
@@ -4,13 +4,20 @@ package client
import (
"bufio"
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net"
"os"
"path/filepath"
"strings"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
ethcrypto "github.com/ethereum/go-ethereum/crypto"
"github.com/spf13/cobra"
tmconfig "github.com/tendermint/tendermint/config"
@@ -22,8 +29,6 @@ import (
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client/tx"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
"github.com/cosmos/cosmos-sdk/server"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/module"
@@ -36,12 +41,14 @@ import (
mintypes "github.com/cosmos/cosmos-sdk/x/mint/types"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
ethcrypto "github.com/ethereum/go-ethereum/crypto"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
"github.com/cosmos/ethermint/crypto/hd"
srvconfig "github.com/cosmos/ethermint/server/config"
ethermint "github.com/cosmos/ethermint/types"
chaintypes "github.com/cosmos/ethermint/types"
evmtypes "github.com/cosmos/ethermint/x/evm/types"
"github.com/cosmos/ethermint/cmd/injectived/config"
"github.com/cosmos/ethermint/crypto/ethsecp256k1"
"github.com/ethereum/go-ethereum/common"
)
var (
@@ -67,7 +74,7 @@ necessary files (private validator, genesis, config, etc.).
Note, strict routability for addresses is turned off in the config file.`,
Example: "ethermintd testnet --v 4 --keyring-backend test --output-dir ./output --ip-addresses 192.168.10.2",
Example: "injectived testnet --v 4 --keyring-backend test --output-dir ./output --ip-addresses 192.168.10.2",
RunE: func(cmd *cobra.Command, _ []string) error {
clientCtx := client.GetClientContextFromCmd(cmd)
@@ -99,13 +106,13 @@ Note, strict routability for addresses is turned off in the config file.`,
cmd.Flags().Int(flagNumValidators, 4, "Number of validators to initialize the testnet with")
cmd.Flags().StringP(flagOutputDir, "o", "./mytestnet", "Directory to store initialization data for the testnet")
cmd.Flags().String(flagNodeDirPrefix, "node", "Prefix the directory name for each node with (node results in node0, node1, ...)")
cmd.Flags().String(flagNodeDaemonHome, "simd", "Home directory of the node's daemon configuration")
cmd.Flags().String(flagNodeDaemonHome, "injectived", "Home directory of the node's daemon configuration")
cmd.Flags().StringSlice(flagIPAddrs, []string{"192.168.0.1"}, "List of IP addresses to use (i.e. `192.168.0.1,172.168.0.1` results in persistent peers list ID0@192.168.0.1:46656, ID1@172.168.0.1)")
cmd.Flags().String(flags.FlagChainID, "", "genesis file chain-id, if left blank will be randomly created")
cmd.Flags().String(server.FlagMinGasPrices, fmt.Sprintf("0.000006%s", ethermint.AttoPhoton), "Minimum gas prices to accept for transactions; All fees in a tx must meet this minimum (e.g. 0.01aphoton,0.001stake)")
cmd.Flags().String(server.FlagMinGasPrices, "", "Minimum gas prices to accept for transactions; All fees in a tx must meet this minimum (e.g. 0.01inj,0.001stake)")
cmd.Flags().String(flags.FlagKeyringBackend, flags.DefaultKeyringBackend, "Select keyring's backend (os|file|test)")
cmd.Flags().String(flags.FlagKeyAlgorithm, string(hd.EthSecp256k1Type), "Key signing algorithm to generate keys for")
cmd.Flags().String(flagCoinDenom, ethermint.AttoPhoton, "Coin denomination used for staking, governance, mint, crisis and evm parameters")
cmd.Flags().String(flagCoinDenom, chaintypes.InjectiveCoin, "Coin denomination used for staking, governance, mint, crisis and evm parameters")
return cmd
}
@@ -129,10 +136,10 @@ func InitTestnet(
) error {
if chainID == "" {
chainID = fmt.Sprintf("ethermint-%d", tmrand.Int63n(9999999999999)+1)
chainID = fmt.Sprintf("injective-%d", tmrand.Int63n(9999999999999)+1)
}
if !ethermint.IsValidChainID(chainID) {
if !chaintypes.IsValidChainID(chainID) {
return fmt.Errorf("invalid chain-id: %s", chainID)
}
@@ -147,7 +154,7 @@ func InitTestnet(
nodeIDs := make([]string, numValidators)
valPubKeys := make([]cryptotypes.PubKey, numValidators)
appConfig := srvconfig.DefaultConfig()
appConfig := config.DefaultConfig()
appConfig.MinGasPrices = minGasPrices
appConfig.API.Enable = true
appConfig.Telemetry.Enabled = true
@@ -243,7 +250,7 @@ func InitTestnet(
)
genBalances = append(genBalances, banktypes.Balance{Address: addr.String(), Coins: coins})
genAccounts = append(genAccounts, &ethermint.EthAccount{
genAccounts = append(genAccounts, &chaintypes.EthAccount{
BaseAccount: authtypes.NewBaseAccount(addr, nil, 0, 0),
CodeHash: ethcrypto.Keccak256(nil),
})
@@ -289,7 +296,10 @@ func InitTestnet(
return err
}
srvconfig.WriteConfigFile(filepath.Join(nodeDir, "config/app.toml"), appConfig)
config.WriteConfigFile(filepath.Join(nodeDir, "config/app.toml"), appConfig)
ethPrivKey, err := keyring.NewUnsafe(kb).UnsafeExportPrivKeyHex(nodeDirName)
initPeggo(outputDir, nodeDirName, []byte(strings.ToUpper(ethPrivKey)))
}
if err := initGenFiles(clientCtx, mbm, chainID, coinDenom, genAccounts, genBalances, genFiles, numValidators); err != nil {
@@ -308,6 +318,32 @@ func InitTestnet(
return nil
}
func initPeggo(outputDir string, nodeDirName string, privKey []byte) {
peggoDir := filepath.Join(outputDir, nodeDirName, "peggo")
if envdata, _ := ioutil.ReadFile("./templates/peggo_config.template"); len(envdata) > 0 {
s := bufio.NewScanner(bytes.NewReader(envdata))
for s.Scan() {
parts := strings.Split(s.Text(), "=")
if len(parts) != 2 {
continue
} else {
content := []byte(s.Text())
if parts[0] == "PEGGY_COSMOS_PRIVKEY" {
content = append([]byte(parts[0]+"="), privKey...)
} else if parts[0] == "PEGGY_ETH_PRIVATE_KEY" {
newPrivkey, _ := ethsecp256k1.GenerateKey()
privKeyStr := common.Bytes2Hex(newPrivkey.GetKey())
privKeyBytes := []byte(strings.ToUpper(privKeyStr))
content = append([]byte(parts[0]+"="), privKeyBytes...)
}
if err := appendToFile(fmt.Sprintf("config.env"), peggoDir, content); err != nil {
fmt.Println("Error writing peggo config", "error", err)
}
}
}
}
}
func initGenFiles(
clientCtx client.Context,
mbm module.BasicManager,
@@ -476,3 +512,42 @@ func writeFile(name string, dir string, contents []byte) error {
return nil
}
func appendToFile(name string, dir string, contents []byte) error {
writePath := filepath.Join(dir)
file := filepath.Join(writePath, name)
err := tmos.EnsureDir(writePath, 0755)
if err != nil {
return err
}
if _, err = os.Stat(file); err == nil {
err = os.Chmod(file, 0777)
if err != nil {
fmt.Println(err)
return err
}
}
f, err := os.OpenFile(file, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Println(err)
return err
}
defer f.Close()
_, err = f.Write(contents)
if err != nil {
log.Println(err)
return err
}
f.Write([]byte("\n"))
if err != nil {
log.Println(err)
return err
}
return nil
}