Skip to content

Commit

Permalink
l2chess state transition
Browse files Browse the repository at this point in the history
  • Loading branch information
tj327 committed Aug 14, 2024
1 parent fca12eb commit ce60ae1
Show file tree
Hide file tree
Showing 15 changed files with 497 additions and 45 deletions.
95 changes: 95 additions & 0 deletions common/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import (
tmjson "github.com/cometbft/cometbft/libs/json"
tmTypes "github.com/cometbft/cometbft/rpc/core/types"
tmJsonRPCTypes "github.com/cometbft/cometbft/rpc/jsonrpc/types"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
)
Expand Down Expand Up @@ -125,6 +126,62 @@ func GetAccountBalances(gwCosmosmux *runtime.ServeMux, r *http.Request, bech32ad
return result.Balances
}

type DappSession struct {
Leader string `protobuf:"bytes,1,opt,name=leader,proto3" json:"leader,omitempty"`
Start string `protobuf:"varint,2,opt,name=start,proto3" json:"start,omitempty"`
StatusHash string `protobuf:"bytes,3,opt,name=status_hash,json=statusHash,proto3" json:"statusHash,omitempty"`
Status string `protobuf:"varint,4,opt,name=status,proto3,enum=kira.layer2.SessionStatus" json:"status,omitempty"`
Gateway string `protobuf:"bytes,5,opt,name=gateway,proto3" json:"gateway,omitempty"`
OnchainMessages []*codectypes.Any `protobuf:"bytes,6,rep,name=onchain_messages,json=onchainMessages,proto3" json:"onchainMessages,omitempty"`
}

type ExecutionRegistrar struct {
DappName string `protobuf:"bytes,1,opt,name=dapp_name,json=dappName,proto3" json:"dappName,omitempty"`
PrevSession *DappSession `protobuf:"bytes,2,opt,name=prev_session,json=prevSession,proto3" json:"prevSession,omitempty"`
CurrSession *DappSession `protobuf:"bytes,3,opt,name=curr_session,json=currSession,proto3" json:"currSession,omitempty"`
NextSession *DappSession `protobuf:"bytes,4,opt,name=next_session,json=nextSession,proto3" json:"nextSession,omitempty"`
}

type DappOperator struct {
DappName string `protobuf:"bytes,1,opt,name=dapp_name,json=dappName,proto3" json:"dappName,omitempty"`
Operator string `protobuf:"bytes,2,opt,name=operator,proto3" json:"operator,omitempty"`
Executor bool `protobuf:"varint,3,opt,name=executor,proto3" json:"executor,omitempty"`
Verifier bool `protobuf:"varint,4,opt,name=verifier,proto3" json:"verifier,omitempty"`
Interx string `protobuf:"bytes,5,opt,name=interx,proto3" json:"interx,omitempty"`
Status string `protobuf:"varint,6,opt,name=status,proto3,enum=kira.layer2.OperatorStatus" json:"status,omitempty"`
Rank string `protobuf:"varint,7,opt,name=rank,proto3" json:"rank,omitempty"`
Streak string `protobuf:"varint,8,opt,name=streak,proto3" json:"streak,omitempty"`
Mischance string `protobuf:"varint,9,opt,name=mischance,proto3" json:"mischance,omitempty"`
VerifiedSessions string `protobuf:"varint,10,opt,name=verified_sessions,json=verifiedSessions,proto3" json:"verifiedSessions,omitempty"`
MissedSessions string `protobuf:"varint,11,opt,name=missed_sessions,json=missedSessions,proto3" json:"missedSessions,omitempty"`
BondedLpAmount string `protobuf:"bytes,12,opt,name=bonded_lp_amount,json=bondedLpAmount,proto3" json:"bondedLpAmount"`
}

type QueryExecutionRegistrarResponse struct {
Dapp interface{} `protobuf:"bytes,1,opt,name=dapp,proto3" json:"dapp,omitempty"`
ExecutionRegistrar *ExecutionRegistrar `json:"executionRegistrar,omitempty"`
Operators []DappOperator `protobuf:"bytes,3,rep,name=operators,proto3" json:"operators"`
}

func GetExecutionRegistrar(gwCosmosmux *runtime.ServeMux, r *http.Request, appName string) QueryExecutionRegistrarResponse {
r.URL.Path = fmt.Sprintf("/kira/layer2/execution_registrar/%s", appName)
r.URL.RawQuery = ""
r.Method = "GET"

recorder := httptest.NewRecorder()
gwCosmosmux.ServeHTTP(recorder, r)
resp := recorder.Result()

result := QueryExecutionRegistrarResponse{}

err := json.NewDecoder(resp.Body).Decode(&result)
if err != nil {
GetLogger().Error("[grpc-call] Unable to decode response: ", err)
}

return result
}

// GetAccountNumberSequence is a function to get AccountNumber and Sequence
func GetAccountNumberSequence(gwCosmosmux *runtime.ServeMux, r *http.Request, bech32addr string) (uint64, uint64) {
_, err := sdk.AccAddressFromBech32(bech32addr)
Expand Down Expand Up @@ -163,6 +220,44 @@ func GetAccountNumberSequence(gwCosmosmux *runtime.ServeMux, r *http.Request, be
return uint64(accountNumber), uint64(sequence)
}

func BroadcastTransactionSync(rpcAddr string, txBytes []byte) (string, error) {
endpoint := fmt.Sprintf("%s/broadcast_tx_sync?tx=0x%X", rpcAddr, txBytes)
GetLogger().Info("[rpc-call] Entering rpc call: ", endpoint)

resp, err := http.Get(endpoint)
if err != nil {
GetLogger().Error("[rpc-call] Unable to connect to ", endpoint)
return "", err
}
defer resp.Body.Close()

type RPCTempResponse struct {
Jsonrpc string `json:"jsonrpc"`
ID int `json:"id"`
Result struct {
Height string `json:"height"`
Hash string `json:"hash"`
} `json:"result,omitempty"`
Error struct {
Message string `json:"message"`
} `json:"error,omitempty"`
}

result := new(RPCTempResponse)
err = json.NewDecoder(resp.Body).Decode(result)
if err != nil {
GetLogger().Error("[rpc-call] Unable to decode response: ", err)
return "", err
}

if resp.StatusCode != http.StatusOK {
GetLogger().Error("[rpc-call] Unable to broadcast transaction: ", result.Error.Message)
return "", errors.New(result.Error.Message)
}

return result.Result.Hash, nil
}

// BroadcastTransaction is a function to post transaction, returns txHash
func BroadcastTransaction(rpcAddr string, txBytes []byte) (string, error) {
endpoint := fmt.Sprintf("%s/broadcast_tx_async?tx=0x%X", rpcAddr, txBytes)
Expand Down
2 changes: 2 additions & 0 deletions common/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,3 +78,5 @@ func IsCacheExpired(result types.InterxResponse) bool {

return isBlockExpire || isTimestampExpire
}

var Layer2Status map[string]string
5 changes: 4 additions & 1 deletion config/constants.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package config

const (
InterxVersion = "v0.4.48"
SekaiVersion = "v0.3.42"
SekaiVersion = "v0.4.0"
CosmosVersion = "v0.47.6"

QueryDashboard = "/api/dashboard"
Expand Down Expand Up @@ -76,6 +76,8 @@ const (
QueryAddrBook = "/api/addrbook"
QueryNetInfo = "/api/net_info"

QueryLayer2Status = "/api/layer2/{appName}/status"

Download = "/download"
AppDownload = "/app/download"
DataReferenceRegistry = "DRR"
Expand Down Expand Up @@ -183,3 +185,4 @@ var MsgTypes = map[string]string{
}
var SupportedEVMChains = [1]string{"goerli"}
var SupportedBitcoinChains = [1]string{"testnet"}
var SupportedLayer2Apps = [1]string{"l2chess"}
9 changes: 9 additions & 0 deletions config/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,15 @@ func defaultConfig() InterxConfigFromFile {

configFromFile.CachingBin = false

configFromFile.Layer2 = make(map[string]Layer2Config)
for _, item := range SupportedLayer2Apps {
layer2Config := Layer2Config{
RPC: "http://127.0.0.1:9000",
Fee: "300ukex",
}
configFromFile.Layer2[item] = layer2Config
}

return configFromFile
}

Expand Down
9 changes: 5 additions & 4 deletions config/load.go
Original file line number Diff line number Diff line change
Expand Up @@ -145,9 +145,9 @@ func LoadAddressAndDenom(configFilePath string, gwCosmosmux *runtime.ServeMux, r
panic("Invalid Interx Mnemonic")
}

privKey := ConvMnemonic2PrivKey(Config.Mnemonic)
privKey1 := ConvMnemonic2PrivKey(Config.Mnemonic)

Config.PrivKey = &privKey
Config.PrivKey = &privKey1
Config.PubKey = Config.PrivKey.PubKey()
Config.Address = sdk.MustBech32ifyAddressBytes(sdk.GetConfig().GetBech32AccountAddrPrefix(), Config.PubKey.Address())

Expand Down Expand Up @@ -193,9 +193,9 @@ func LoadAddressAndDenom(configFilePath string, gwCosmosmux *runtime.ServeMux, r
panic("Invalid Faucet Mnemonic")
}

privKey = ConvMnemonic2PrivKey(Config.Faucet.Mnemonic)
privKey2 := ConvMnemonic2PrivKey(Config.Faucet.Mnemonic)

Config.Faucet.PrivKey = &privKey
Config.Faucet.PrivKey = &privKey2
Config.Faucet.PubKey = Config.Faucet.PrivKey.PubKey()
Config.Faucet.Address = sdk.MustBech32ifyAddressBytes(sdk.GetConfig().GetBech32AccountAddrPrefix(), Config.Faucet.PubKey.Address())

Expand Down Expand Up @@ -333,6 +333,7 @@ func LoadConfig(configFilePath string) {

Config.Evm = configFromFile.Evm
Config.Bitcoin = configFromFile.Bitcoin
Config.Layer2 = configFromFile.Layer2

Config.SnapshotInterval = configFromFile.SnapshotInterval
Config.CachingBin = configFromFile.CachingBin
Expand Down
7 changes: 7 additions & 0 deletions config/type.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,11 @@ type BitcoinConfig struct {
BTC_FAUCET string `json:"btc_faucet"`
}

type Layer2Config struct {
RPC string `json:"rpc"`
Fee string `json:"fee"`
}

type AppSettingConfig struct {
AppMode int `json:"app_mode"`
AppMock bool `json:"app_mock"`
Expand Down Expand Up @@ -121,6 +126,7 @@ type InterxConfig struct {
RPCMethods RPCConfig `json:"rpc_methods"`
Evm map[string]EVMConfig `json:"evm"`
Bitcoin map[string]BitcoinConfig `json:"bitcoin"`
Layer2 map[string]Layer2Config `json:"layer2"`
SnapshotInterval uint64 `json:"snapshot_interval"`
AppSetting AppSettingConfig `json:"app_setting"`
CachingBin bool `json:"caching_bin"`
Expand Down Expand Up @@ -154,6 +160,7 @@ type InterxConfigFromFile struct {
} `json:"faucet"`
Evm map[string]EVMConfig `json:"evm"`
Bitcoin map[string]BitcoinConfig `json:"bitcoin"`
Layer2 map[string]Layer2Config `json:"layer2"`
SnapshotInterval uint64 `json:"snapshot_interval"`
AppSetting AppSettingConfig `json:"app_setting"`
CachingBin bool `json:"caching_bin"`
Expand Down
81 changes: 81 additions & 0 deletions database/layer2.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
package database

import (
"github.com/KiraCore/interx/config"
"github.com/sonyarouje/simdb/db"
)

// Layer2Data is a struct for layer2 details.
type Layer2Data struct {
Id string `json:"id"`
Data string `json:"data"`
}

// ID is a field for facuet claim struct.
func (c Layer2Data) ID() (jsonField string, value interface{}) {
value = c.Id
jsonField = "id"
return
}

func LoadLayer2DbDriver() {
DisableStdout()
driver, _ := db.New(config.GetDbCacheDir() + "/layer2")
EnableStdout()

layer2Db = driver
}

// GetLayer2State is a function to get layer2 app state stored
func GetLayer2State(id string) (string, error) {
if layer2Db == nil {
panic("cache dir not set")
}

data := Layer2Data{}

DisableStdout()
err := layer2Db.Open(Layer2Data{}).Where("id", "=", id).First().AsEntity(&data)
EnableStdout()

if err != nil {
return "", err
}

return data.Data, nil
}

// GetAllLayer2s is a function to get all layer2Times
func GetAllLayer2s() []interface{} {
if layer2Db == nil {
panic("cache dir not set")
}

DisableStdout()
rawData := layer2Db.Open(Layer2Data{}).RawArray()
EnableStdout()

return rawData
}

// SetLayer2State is a function to set layer2 app status
func SetLayer2State(id string, data string) {
if layer2Db == nil {
panic("cache dir not set")
}

DisableStdout()
err := layer2Db.Open(Layer2Data{}).Insert(Layer2Data{
Id: id,
Data: data,
})
EnableStdout()

if err != nil {
panic(err)
}
}

var (
layer2Db *db.Driver
)
2 changes: 1 addition & 1 deletion functions/interx.go
Original file line number Diff line number Diff line change
Expand Up @@ -1028,7 +1028,7 @@ func RegisterInterxFunctions() {
"type": "string",
"description": "This is an option to query only nodes by app_name or app_id.",
"optional": true
},
}
},
"response": {
"last_update": {
Expand Down
34 changes: 0 additions & 34 deletions gateway/application_check.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,8 @@ package gateway

import (
"encoding/json"
"errors"
"net/http"

"github.com/KiraCore/interx/common"
"github.com/KiraCore/interx/config"
layer2types "github.com/KiraCore/sekai/x/layer2/types"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
)

func ToString(data interface{}) string {
Expand Down Expand Up @@ -48,32 +43,3 @@ func NodeSyncState(rpcAddr string) bool {

return !result.SyncInfo.CatchingUp
}

func CheckApplicationState(gwCosmosmux *runtime.ServeMux, gatewayAddr string) error {
if config.Config.AppSetting.AppMock {
return nil
}

result := layer2types.QueryExecutionRegistrarResponse{}
appstateQueryRequest, _ := http.NewRequest("GET", "http://"+gatewayAddr+"/kira/layer2/execution_registrar/"+config.Config.AppSetting.AppName, nil)

appstateQueryResponse, failure, _ := common.ServeGRPC(appstateQueryRequest, gwCosmosmux)

if appstateQueryResponse == nil {
return errors.New(ToString(failure))
}

byteData, err := json.Marshal(appstateQueryResponse)
if err != nil {
return err
}

err = json.Unmarshal(byteData, &result)
if err != nil {
return err
}

// TODO : check if config.appmode is not same with appmode in result
// result.Dapp.verifier
return nil
}
11 changes: 11 additions & 0 deletions gateway/layer2/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package layer2

import (
"github.com/gorilla/mux"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
)

// RegisterRequest is a function to register requests.
func RegisterRequest(router *mux.Router, gwCosmosmux *runtime.ServeMux, rpcAddr string) {
RegisterStatusRoutes(router, gwCosmosmux, rpcAddr)
}
Loading

0 comments on commit ce60ae1

Please sign in to comment.