Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Patch opinit bots flow #8

Merged
merged 8 commits into from
Dec 11, 2024
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion models/opinit_bots/bots.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
package opinit_bots

import (
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"

"github.com/initia-labs/weave/common"
)

const (
Expand Down Expand Up @@ -94,9 +99,17 @@ var BotInfos = []BotInfo{

// CheckIfKeysExist checks the output of `initiad keys list` and sets IsNotExist for missing keys
func CheckIfKeysExist(botInfos []BotInfo) []BotInfo {
cmd := exec.Command(AppName, "keys", "list", "weave-dummy")
userHome, err := os.UserHomeDir()
if err != nil {
panic(err)
}
binaryPath := filepath.Join(userHome, common.WeaveDataDirectory, fmt.Sprintf("opinitd@%s", OpinitBotBinaryVersion), AppName)
cmd := exec.Command(binaryPath, "keys", "list", "weave-dummy")
outputBytes, err := cmd.Output()
if err != nil {
for i := range botInfos {
botInfos[i].IsNotExist = true
}
Benzbeeb marked this conversation as resolved.
Show resolved Hide resolved
return botInfos
}
output := string(outputBytes)
Expand Down
51 changes: 31 additions & 20 deletions models/opinit_bots/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,13 @@ type NodeConfig struct {
}

type ChallengerConfig struct {
Version int `json:"version"`
ListenAddress string `json:"listen_address"`
L1Node NodeConfig `json:"l1_node"`
L2Node NodeConfig `json:"l2_node"`
L1StartHeight int `json:"l1_start_height"`
L2StartHeight int `json:"l2_start_height"`
DisableAutoSetL1Height bool `json:"disable_auto_set_l1_height"`
Version int `json:"version"`
Server ServerConfig `json:"server"`
L1Node NodeConfig `json:"l1_node"`
L2Node NodeConfig `json:"l2_node"`
L1StartHeight int `json:"l1_start_height"`
L2StartHeight int `json:"l2_start_height"`
DisableAutoSetL1Height bool `json:"disable_auto_set_l1_height"`
}

type NodeSettings struct {
Expand All @@ -25,18 +25,29 @@ type NodeSettings struct {
TxTimeout int `json:"tx_timeout"`
}

type ServerConfig struct {
Address string `json:"address"`
AllowOrigins string `json:"allow_origins"`
AllowHeaders string `json:"allow_headers"`
AllowMethods string `json:"allow_methods"`
}

type ExecutorConfig struct {
Version int `json:"version"`
ListenAddress string `json:"listen_address"`
L1Node NodeSettings `json:"l1_node"`
L2Node NodeSettings `json:"l2_node"`
DANode NodeSettings `json:"da_node"`
OutputSubmitter string `json:"output_submitter"`
BridgeExecutor string `json:"bridge_executor"`
BatchSubmitterEnabled bool `json:"enable_batch_submitter"`
MaxChunks int `json:"max_chunks"`
MaxChunkSize int `json:"max_chunk_size"`
MaxSubmissionTime int `json:"max_submission_time"`
L2StartHeight int `json:"l2_start_height"`
BatchStartHeight int `json:"batch_start_height"`
Version int `json:"version"`
Server ServerConfig `json:"server"`
L1Node NodeSettings `json:"l1_node"`
L2Node NodeSettings `json:"l2_node"`
DANode NodeSettings `json:"da_node"`
BridgeExecutor string `json:"bridge_executor"`
OracleBridgeExecutor string `json:"oracle_bridge_executor"`
DisableOutputSubmitter bool `json:"disable_output_submitter"`
DisableBatchSubmitter bool `json:"disable_batch_submitter"`
MaxChunks int `json:"max_chunks"`
MaxChunkSize int `json:"max_chunk_size"`
MaxSubmissionTime int `json:"max_submission_time"`
DisableAutoSetL1Height bool `json:"disable_auto_set_l1_height"`
L1StartHeight int `json:"l1_start_height"`
L2StartHeight int `json:"l2_start_height"`
BatchStartHeight int `json:"batch_start_height"`
DisableDeleteFutureWithdrawal bool `json:"disable_delete_future_withdrawal"`
}
182 changes: 166 additions & 16 deletions models/opinit_bots/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"fmt"
"github.com/initia-labs/weave/io"
"os"
"path/filepath"
"strings"
Expand All @@ -14,6 +13,8 @@ import (

"github.com/initia-labs/weave/common"
weavecontext "github.com/initia-labs/weave/context"
"github.com/initia-labs/weave/cosmosutils"
"github.com/initia-labs/weave/io"
"github.com/initia-labs/weave/registry"
"github.com/initia-labs/weave/service"
"github.com/initia-labs/weave/styles"
Expand Down Expand Up @@ -238,12 +239,55 @@ func (m *OPInitBotInitSelector) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
if selected != nil {
state := weavecontext.PushPageAndGetState[OPInitBotsState](m)
state.weave.PushPreviousResponse(styles.RenderPreviousResponse(styles.ArrowSeparator, m.GetQuestion(), []string{"bot"}, string(*selected)))
m.Ctx = weavecontext.SetCurrentState(m.Ctx, state)
switch *selected {
case ExecutorOPInitBotInitOption:
return OPInitBotInitSelectExecutor(m.Ctx), cmd
state.InitExecutorBot = true
keyNames := make(map[string]bool)
keyNames[BridgeExecutorKeyName] = true
keyNames[OutputSubmitterKeyName] = true
keyNames[BatchSubmitterKeyName] = true
keyNames[OracleBridgeExecutorKeyName] = true

finished := true

state.BotInfos = CheckIfKeysExist(BotInfos)
for idx, botInfo := range state.BotInfos {
if keyNames[botInfo.KeyName] && botInfo.IsNotExist {
state.BotInfos[idx].IsSetup = true
finished = false
} else {
state.BotInfos[idx].IsSetup = false
}
}
if finished {
return OPInitBotInitSelectExecutor(weavecontext.SetCurrentState(m.Ctx, state)), cmd
}

state.isSetupMissingKey = true
return NextUpdateOpinitBotKey(weavecontext.SetCurrentState(m.Ctx, state))
case ChallengerOPInitBotInitOption:
return OPInitBotInitSelectChallenger(m.Ctx), cmd
state.InitChallengerBot = true
keyNames := make(map[string]bool)
keyNames[ChallengerKeyName] = true

finished := true

state.BotInfos = CheckIfKeysExist(BotInfos)
for idx, botInfo := range state.BotInfos {
fmt.Println(botInfo.KeyName, keyNames[botInfo.KeyName], botInfo.IsNotExist)
if keyNames[botInfo.KeyName] && botInfo.IsNotExist {
state.BotInfos[idx].IsSetup = true
finished = false
} else {
state.BotInfos[idx].IsSetup = false
}
}
if finished {
return OPInitBotInitSelectChallenger(weavecontext.SetCurrentState(m.Ctx, state)), cmd
}

state.isSetupMissingKey = true
return NextUpdateOpinitBotKey(weavecontext.SetCurrentState(m.Ctx, state))
}
}
return m, cmd
Expand Down Expand Up @@ -754,8 +798,13 @@ func WaitStartingInitBot(ctx context.Context) tea.Cmd {
version := registry.MustGetOPInitBotsSpecVersion(state.botConfig["l1_node.chain_id"])

config := ExecutorConfig{
Version: version,
ListenAddress: configMap["listen_address"],
Version: version,
Server: ServerConfig{
Address: configMap["listen_address"],
AllowOrigins: "*",
AllowHeaders: "Origin, Content-Type, Accept",
AllowMethods: "GET",
},
Benzbeeb marked this conversation as resolved.
Show resolved Hide resolved
L1Node: NodeSettings{
ChainID: configMap["l1_node.chain_id"],
RPCAddress: configMap["l1_node.rpc_address"],
Expand All @@ -780,14 +829,17 @@ func WaitStartingInitBot(ctx context.Context) tea.Cmd {
GasAdjustment: 1.5,
TxTimeout: 60,
},
OutputSubmitter: OutputSubmitterKeyName,
BridgeExecutor: BridgeExecutorKeyName,
BatchSubmitterEnabled: true,
MaxChunks: 5000,
MaxChunkSize: 300000,
MaxSubmissionTime: 3600,
L2StartHeight: 0,
BatchStartHeight: 0,
BridgeExecutor: BridgeExecutorKeyName,
OracleBridgeExecutor: OracleBridgeExecutorKeyName,
MaxChunks: 5000,
MaxChunkSize: 300000,
MaxSubmissionTime: 3600,
L2StartHeight: 0,
BatchStartHeight: 0,
DisableDeleteFutureWithdrawal: false,
DisableAutoSetL1Height: false,
DisableBatchSubmitter: false,
DisableOutputSubmitter: false,
Benzbeeb marked this conversation as resolved.
Show resolved Hide resolved
}
configBz, err := json.MarshalIndent(config, "", " ")
if err != nil {
Expand All @@ -814,8 +866,13 @@ func WaitStartingInitBot(ctx context.Context) tea.Cmd {

version := registry.MustGetOPInitBotsSpecVersion(state.botConfig["l1_node.chain_id"])
config := ChallengerConfig{
Version: version,
ListenAddress: configMap["listen_address"],
Version: version,
Server: ServerConfig{
Address: configMap["listen_address"],
AllowOrigins: "*",
AllowHeaders: "Origin, Content-Type, Accept",
AllowMethods: "GET",
},
L1Node: NodeConfig{
ChainID: configMap["l1_node.chain_id"],
RPCAddress: configMap["l1_node.rpc_address"],
Expand Down Expand Up @@ -888,3 +945,96 @@ func (m *OPinitBotSuccessful) View() string {

return state.weave.Render() + styles.RenderPrompt(fmt.Sprintf("OPInit bot setup successfully. Config file is saved at %s. Feel free to modify it as needed.", filepath.Join(weavecontext.GetOPInitHome(m.Ctx), fmt.Sprintf("%s.json", botConfigFileName))), []string{}, styles.Completed) + "\n" + styles.RenderPrompt("You can start the bot by running `weave opinit-bots start "+botConfigFileName+"`", []string{}, styles.Completed) + "\n"
}

// SetupOPInitBotsMissingKey handles the loading and setup of OPInit bots
type SetupOPInitBotsMissingKey struct {
weavecontext.BaseModel
loading ui.Loading
}

// NewSetupOPInitBots initializes a new SetupOPInitBots with context
func NewSetupOPInitBotsMissingKey(ctx context.Context) *SetupOPInitBotsMissingKey {
return &SetupOPInitBotsMissingKey{
BaseModel: weavecontext.BaseModel{Ctx: ctx, CannotBack: true},
loading: ui.NewLoading("Downloading binary and adding keys...", WaitSetupOPInitBotsMissingKey(ctx)),
}
}

func (m *SetupOPInitBotsMissingKey) Init() tea.Cmd {
return m.loading.Init()
}

func (m *SetupOPInitBotsMissingKey) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
loader, cmd := m.loading.Update(msg)
m.loading = loader
if m.loading.Completing {
switch msg := msg.(type) {
case tea.KeyMsg:
if msg.String() == "enter" {
state := weavecontext.GetCurrentState[OPInitBotsState](m.loading.EndContext)
if state.InitExecutorBot {
return OPInitBotInitSelectExecutor(m.loading.EndContext), nil
} else if state.InitChallengerBot {
return OPInitBotInitSelectChallenger(m.loading.EndContext), nil
}
}
}
}
return m, cmd
}

func (m *SetupOPInitBotsMissingKey) View() string {
state := weavecontext.GetCurrentState[OPInitBotsState](m.Ctx)
if len(state.SetupOpinitResponses) > 0 {
mnemonicText := ""
for _, botName := range BotNames {
if res, ok := state.SetupOpinitResponses[botName]; ok {
keyInfo := strings.Split(res, "\n")
address := strings.Split(keyInfo[0], ": ")
mnemonicText += renderMnemonic(string(botName), address[1], keyInfo[1])
}
}
Benzbeeb marked this conversation as resolved.
Show resolved Hide resolved

return state.weave.Render() + "\n" + styles.BoldUnderlineText("Important", styles.Yellow) + "\n" +
styles.Text("Write down these mnemonic phrases and store them in a safe place. \nIt is the only way to recover your system keys.", styles.Yellow) + "\n\n" +
mnemonicText + "\nPress enter to go next step\n"
}
return state.weave.Render() + "\n"
}

func WaitSetupOPInitBotsMissingKey(ctx context.Context) tea.Cmd {
return func() tea.Msg {
state := weavecontext.GetCurrentState[OPInitBotsState](ctx)
userHome, err := os.UserHomeDir()
if err != nil {
return ui.ErrorLoading{Err: fmt.Errorf("failed to get user home directory: %v", err)}
}
Benzbeeb marked this conversation as resolved.
Show resolved Hide resolved

binaryPath := filepath.Join(userHome, common.WeaveDataDirectory, fmt.Sprintf("opinitd@%s", OpinitBotBinaryVersion), AppName)

opInitHome := weavecontext.GetOPInitHome(ctx)
for _, info := range state.BotInfos {
if info.Mnemonic != "" {
res, err := cosmosutils.OPInitRecoverKeyFromMnemonic(binaryPath, info.KeyName, info.Mnemonic, info.DALayer == string(CelestiaLayerOption), opInitHome)
if err != nil {
return ui.ErrorLoading{Err: fmt.Errorf("failed to recover key from mnemonic: %v", err)}
}
state.SetupOpinitResponses[info.BotName] = res
continue
}
if info.IsGenerateKey {
res, err := cosmosutils.OPInitAddOrReplace(binaryPath, info.KeyName, info.DALayer == string(CelestiaLayerOption), opInitHome)
if err != nil {
return ui.ErrorLoading{Err: fmt.Errorf("failed to add or replace key: %v", err)}

}
state.SetupOpinitResponses[info.BotName] = res
continue
}
}

return ui.EndLoading{
Ctx: ctx,
}
}
}
15 changes: 11 additions & 4 deletions models/opinit_bots/setup.go
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,11 @@ func NextUpdateOpinitBotKey(ctx context.Context) (tea.Model, tea.Cmd) {
return NewRecoverKeySelector(ctx, idx), nil
}
}
if state.isSetupMissingKey {
model := NewSetupOPInitBotsMissingKey(ctx)
return model, model.Init()
}

model := NewSetupOPInitBots(ctx)
return model, model.Init()
}
Expand Down Expand Up @@ -715,10 +720,12 @@ func (m *TerminalState) View() string {
state := weavecontext.GetCurrentState[OPInitBotsState](m.Ctx)
if len(state.SetupOpinitResponses) > 0 {
mnemonicText := ""
for botName, res := range state.SetupOpinitResponses {
keyInfo := strings.Split(res, "\n")
address := strings.Split(keyInfo[0], ": ")
mnemonicText += renderMnemonic(string(botName), address[1], keyInfo[1])
for _, botName := range BotNames {
if res, ok := state.SetupOpinitResponses[botName]; ok {
keyInfo := strings.Split(res, "\n")
address := strings.Split(keyInfo[0], ": ")
mnemonicText += renderMnemonic(string(botName), address[1], keyInfo[1])
}
}

return state.weave.Render() + "\n" + styles.RenderPrompt("Download binary and add keys successfully.", []string{}, styles.Completed) + "\n\n" +
Expand Down
Loading
Loading