Skip to content

Commit

Permalink
feat: node-index, auth key interaction, and YAML support (#1044)
Browse files Browse the repository at this point in the history
* node-index and auth key interaction

* feat: yaml config support
  • Loading branch information
Reecepbcups authored Apr 18, 2024
1 parent 94f966a commit 97a1561
Show file tree
Hide file tree
Showing 14 changed files with 185 additions and 95 deletions.
33 changes: 33 additions & 0 deletions local-interchain/chains/hub.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
---
chains:
- name: gaia
chain_id: localcosmos-1
denom: uatom
binary: gaiad
bech32_prefix: cosmos
docker_image:
version: v10.0.1
gas_prices: 0%DENOM%
chain_type: cosmos
coin_type: 118
trusting_period: 112h
gas_adjustment: 2
number_vals: 1
number_node: 0
debugging: true
block_time: 500ms
genesis:
modify:
- key: app_state.gov.voting_params.voting_period
value: 15s
- key: app_state.gov.deposit_params.max_deposit_period
value: 15s
- key: app_state.gov.deposit_params.min_deposit.0.denom
value: uatom
accounts:
- name: acc0
address: cosmos1hj5fveer5cjtn4wd6wstzugjfdxzl0xpxvjjvr
amount: 10000000000%DENOM%
mnemonic: decorate bright ozone fork gallery riot bus exhaust worth way bone
indoor calm squirrel merry zero scheme cotton until shop any excess stage
laundry
4 changes: 2 additions & 2 deletions local-interchain/cmd/local-ic/chains.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,11 @@ import (
)

type chains struct {
Configs []string `json:"chain_configs"`
Configs []string `json:"chain_configs" yaml:"chain_configs"`
}

var chainsCmd = &cobra.Command{
Use: "chains [config.json]",
Use: "chains [config.(json|yaml)]",
Short: "List all current chains or outputs a current config information",
Args: cobra.RangeArgs(0, 1),
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
Expand Down
33 changes: 26 additions & 7 deletions local-interchain/cmd/local-ic/interaction.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,19 +14,22 @@ import (

const (
FlagAPIEndpoint = "api-endpoint"
FlagNodeIndex = "node-index"
)

func init() {
interactCmd.Flags().String(FlagAPIAddressOverride, "http://127.0.0.1:8080", "override the default API address")
interactCmd.Flags().String(FlagAuthKey, "a", "auth key to use")
interactCmd.Flags().IntP(FlagNodeIndex, "n", 0, "node index to interact with")
}

var interactCmd = &cobra.Command{
Use: "interact [chain_id] [interaction] [arguments...]",
Short: "Interact with a node",
Example: `local-ic interact localcosmos-1 bin 'status --node=%RPC%' --api-endpoint=http://127.0.0.1:8080
local-ic interact localcosmos-1 query bank balances cosmos1hj5fveer5cjtn4wd6wstzugjfdxzl0xpxvjjvr
local-ic interact localcosmos-1 get_channels
local-ic interact localcosmos-1 relayer-exec rly q channels localcosmos-1
Example: ` local-ic interact localcosmos-1 bin 'status --node=%RPC%' --api-endpoint=http://127.0.0.1:8080
local-ic interact localcosmos-1 query bank balances cosmos1hj5fveer5cjtn4wd6wstzugjfdxzl0xpxvjjvr
local-ic interact localcosmos-1 get_channels
local-ic interact localcosmos-1 relayer-exec rly q channels localcosmos-1
`,
Args: cobra.MinimumNArgs(2),
Aliases: []string{"i"},
Expand All @@ -35,7 +38,7 @@ local-ic interact localcosmos-1 relayer-exec rly q channels localcosmos-1
},
Run: func(cmd *cobra.Command, args []string) {

ah := handlers.ActionHandler{
ah := &handlers.ActionHandler{
ChainId: args[0],
Action: args[1],
}
Expand All @@ -44,14 +47,30 @@ local-ic interact localcosmos-1 relayer-exec rly q channels localcosmos-1
ah.Cmd = strings.Join(args[2:], " ")
}

apiAddr, _ := cmd.Flags().GetString(FlagAPIAddressOverride)
authKey, err := cmd.Flags().GetString(FlagAuthKey)
if err != nil {
panic(err)
}

nodeIdx, err := cmd.Flags().GetInt(FlagNodeIndex)
if err != nil {
panic(err)
}

ah.AuthKey = authKey
ah.NodeIndex = nodeIdx

apiAddr, err := cmd.Flags().GetString(FlagAPIAddressOverride)
if err != nil {
panic(err)
}

res := makeHttpReq(apiAddr, ah)
fmt.Println(res)
},
}

func makeHttpReq(apiEndpoint string, ah handlers.ActionHandler) string {
func makeHttpReq(apiEndpoint string, ah *handlers.ActionHandler) string {
client := &http.Client{}

// curl -X POST -H "Content-Type: application/json" -d '{
Expand Down
2 changes: 1 addition & 1 deletion local-interchain/cmd/local-ic/new_chain.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import (
var reader = bufio.NewReader(os.Stdin)

type Chains struct {
Chains []ictypes.Chain `json:"chains"`
Chains []ictypes.Chain `json:"chains" yaml:"chains"`
}

var newChainCmd = &cobra.Command{
Expand Down
34 changes: 29 additions & 5 deletions local-interchain/cmd/local-ic/start_chain.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package main

import (
"fmt"
"os"
"path"
"path/filepath"
"strings"
Expand Down Expand Up @@ -57,13 +59,14 @@ local-ic start https://pastebin.com/raw/Ummk4DTM
// last part of the URL to be the test name
configPath = configPath[strings.LastIndex(configPath, "/")+1:]
} else {
configPath, err = GetConfigWithExtension(parentDir, configPath)
if err != nil {
panic(err)
}

config, err = interchain.LoadConfig(parentDir, configPath)
if err != nil {
// try again with .json, then if it still fails - panic
config, err = interchain.LoadConfig(parentDir, configPath+".json")
if err != nil {
panic(err)
}
panic(err)
}
}

Expand Down Expand Up @@ -94,6 +97,27 @@ local-ic start https://pastebin.com/raw/Ummk4DTM
},
}

// GetConfigWithExtension returns the config with the file extension attached if one was not provided.
// If "hub" is passed it, it will search for hub.yaml, hub.yml, or hub.json.
// If an extension is already applied, it will use that.
func GetConfigWithExtension(parentDir, config string) (string, error) {
if path.Ext(config) != "" {
return config, nil
}

extensions := []string{".yaml", ".yml", ".json"}
for _, ext := range extensions {
fp := path.Join(parentDir, interchain.ChainDir, config+ext)
if _, err := os.Stat(fp); err != nil {
continue
}

return config + ext, nil
}

return "", fmt.Errorf("could not find a file with an accepted extension: %s. (%+v)", config, extensions)
}

func init() {
startCmd.Flags().String(FlagAPIAddressOverride, "127.0.0.1", "override the default API address")
startCmd.Flags().Uint16(FlagAPIPortOverride, 8080, "override the default API port")
Expand Down
24 changes: 16 additions & 8 deletions local-interchain/interchain/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package interchain
import (
"encoding/json"
"fmt"
"io/ioutil"
"io"
"log"
"net/http"
"os"
Expand All @@ -14,13 +14,16 @@ import (

types "github.com/strangelove-ventures/localinterchain/interchain/types"
"github.com/strangelove-ventures/localinterchain/interchain/util"
"gopkg.in/yaml.v3"

"github.com/strangelove-ventures/interchaintest/v8"
"github.com/strangelove-ventures/interchaintest/v8/chain/cosmos"
"github.com/strangelove-ventures/interchaintest/v8/ibc"
"github.com/strangelove-ventures/interchaintest/v8/testutil"
)

const ChainDir = "chains"

func LoadConfig(installDir, chainCfgFile string) (*types.Config, error) {
var config types.Config

Expand All @@ -29,18 +32,23 @@ func LoadConfig(installDir, chainCfgFile string) (*types.Config, error) {
configFile = chainCfgFile
}

// Chains Folder
chainsDir := filepath.Join(installDir, "chains")
// A nested "chains" dir is required within the parent you specify.
chainsDir := filepath.Join(installDir, ChainDir)
cfgFilePath := filepath.Join(chainsDir, configFile)

bytes, err := os.ReadFile(cfgFilePath)
bz, err := os.ReadFile(cfgFilePath)
if err != nil {
return nil, err
}

err = json.Unmarshal(bytes, &config)
if err != nil {
return nil, err
if strings.HasSuffix(chainCfgFile, ".json") {
if err = json.Unmarshal(bz, &config); err != nil {
return nil, fmt.Errorf("error unmarshalling json config: %w", err)
}
} else {
if err := yaml.Unmarshal(bz, &config); err != nil {
return nil, fmt.Errorf("error unmarshalling yaml config: %w", err)
}
}

log.Println("Using directory:", installDir)
Expand All @@ -56,7 +64,7 @@ func LoadConfigFromURL(url string) (*types.Config, error) {
}
defer resp.Body.Close()

body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatalln(err)
}
Expand Down
6 changes: 3 additions & 3 deletions local-interchain/interchain/handlers/info.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,9 @@ func NewInfo(
}

type GetInfo struct {
Logs types.MainLogs `json:"logs"`
Chains []types.Chain `json:"chains"`
Relay types.Relayer `json:"relayer"`
Logs types.MainLogs `json:"logs" yaml:"logs"`
Chains []types.Chain `json:"chains" yaml:"chains"`
Relay types.Relayer `json:"relayer" yaml:"relayer"`
}

func (i *info) GetInfo(w http.ResponseWriter, r *http.Request) {
Expand Down
20 changes: 10 additions & 10 deletions local-interchain/interchain/handlers/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,16 @@ import (
)

type IbcChainConfigAlias struct {
Type string `json:"type"`
Name string `json:"name"`
ChainID string `json:"chain_id"`
Bin string `json:"bin"`
Bech32Prefix string `json:"bech32_prefix"`
Denom string `json:"denom"`
CoinType string `json:"coin_type"`
GasPrices string `json:"gas_prices"`
GasAdjustment float64 `json:"gas_adjustment"`
TrustingPeriod string `json:"trusting_period"`
Type string `json:"type" yaml:"type"`
Name string `json:"name" yaml:"name"`
ChainID string `json:"chain_id" yaml:"chain_id"`
Bin string `json:"bin" yaml:"bin"`
Bech32Prefix string `json:"bech32_prefix" yaml:"bech32_prefix"`
Denom string `json:"denom" yaml:"denom"`
CoinType string `json:"coin_type" yaml:"coin_type"`
GasPrices string `json:"gas_prices" yaml:"gas_prices"`
GasAdjustment float64 `json:"gas_adjustment" yaml:"gas_adjustment"`
TrustingPeriod string `json:"trusting_period" yaml:"trusting_period"`
}

func (c *IbcChainConfigAlias) Marshal() ([]byte, error) {
Expand Down
4 changes: 2 additions & 2 deletions local-interchain/interchain/router/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ import (
)

type Route struct {
Path string `json:"path"`
Methods []string `json:"methods"`
Path string `json:"path" yaml:"path"`
Methods []string `json:"methods" yaml:"methods"`
}

func NewRouter(
Expand Down
21 changes: 16 additions & 5 deletions local-interchain/interchain/start.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"log"
"math"
"net/http"
"path"
"strings"

"github.com/strangelove-ventures/interchaintest/v8"
Expand Down Expand Up @@ -77,9 +78,9 @@ func StartChain(installDir, chainCfgFile string, ac *types.AppStartConfig) {
// Create chain factory for all the chains
cf := interchaintest.NewBuiltinChainFactory(logger, chainSpecs)

// Get chains from the chain factory
name := strings.ReplaceAll(chainCfgFile, ".json", "") + "ic"
chains, err := cf.Chains(name)
testName := GetTestName(chainCfgFile)

chains, err := cf.Chains(testName)
if err != nil {
log.Fatal("cf.Chains", err)
}
Expand All @@ -90,7 +91,7 @@ func StartChain(installDir, chainCfgFile string, ac *types.AppStartConfig) {
ic.AdditionalGenesisWallets = SetupGenesisWallets(config, chains)

fakeT := FakeTesting{
FakeName: name,
FakeName: testName,
}

// Base setup
Expand Down Expand Up @@ -125,7 +126,7 @@ func StartChain(installDir, chainCfgFile string, ac *types.AppStartConfig) {

// Build all chains & begin.
err = ic.Build(ctx, eRep, interchaintest.InterchainBuildOptions{
TestName: name,
TestName: testName,
Client: client,
NetworkID: network,
SkipPathCreation: false,
Expand Down Expand Up @@ -197,3 +198,13 @@ func StartChain(installDir, chainCfgFile string, ac *types.AppStartConfig) {
log.Fatal("WaitForBlocks StartChain: ", err)
}
}

func GetTestName(chainCfgFile string) string {
name := chainCfgFile
fExt := path.Ext(name)
if fExt != "" {
name = strings.ReplaceAll(chainCfgFile, fExt, "")
}

return name + "ic"
}
Loading

0 comments on commit 97a1561

Please sign in to comment.