package main import "C" import ( // std "encoding/base64" "encoding/json" "fmt" "os" "sync" "time" // helpers _ "github.com/gogo/protobuf/gogoproto" proto "github.com/gogo/protobuf/proto" "github.com/pkg/errors" // tendermint abci "github.com/tendermint/tendermint/abci/types" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" // cosmos sdk codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" sdk "github.com/cosmos/cosmos-sdk/types" banktest "github.com/cosmos/cosmos-sdk/x/bank/testutil" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" // wasmd wasmtypes "github.com/CosmWasm/wasmd/x/wasm/types" // cosmwasm-testing "github.com/classic-terra/test-tube/classic-test-tube/result" "github.com/classic-terra/test-tube/classic-test-tube/testenv" // terra apptesting "github.com/classic-terra/core/v2/app/testing" coretypes "github.com/classic-terra/core/v2/types" ) var ( envCounter uint64 = 0 envRegister = sync.Map{} mu sync.Mutex ) //export InitTestEnv func InitTestEnv() uint64 { // Temp fix for concurrency issue mu.Lock() defer mu.Unlock() sdkConfig := sdk.GetConfig() sdkConfig.SetCoinType(coretypes.CoinType) sdkConfig.SetPurpose(coretypes.Purpose) sdkConfig.SetBech32PrefixForAccount(coretypes.Bech32PrefixAccAddr, coretypes.Bech32PrefixAccPub) sdkConfig.SetBech32PrefixForValidator(coretypes.Bech32PrefixValAddr, coretypes.Bech32PrefixValPub) sdkConfig.SetBech32PrefixForConsensusNode(coretypes.Bech32PrefixConsAddr, coretypes.Bech32PrefixConsPub) sdkConfig.SetAddressVerifier(wasmtypes.VerifyAddressLen()) env := new(testenv.TestEnv) nodeHome, err := os.MkdirTemp("", "mytestnet") if err != nil { panic(err) } env.App = testenv.SetupTerraApp(nodeHome) env.NodeHome = nodeHome env.ParamTypesRegistry = *testenv.NewParamTypeRegistry() env.SetupParamTypes() // Allow testing unoptimized contract wasmtypes.MaxWasmSize = 1024 * 1024 * 1024 * 1024 * 1024 env.Ctx = env.App.BaseApp.NewContext(false, tmproto.Header{Height: env.App.LastBlockHeight(), ChainID: apptesting.SimAppChainID, Time: time.Now().UTC()}) env.BeginNewBlock(false, 5) reqEndBlock := abci.RequestEndBlock{Height: env.Ctx.BlockHeight()} env.App.EndBlock(reqEndBlock) env.App.Commit() envCounter += 1 id := envCounter envRegister.Store(id, *env) return id } //export CleanUp func CleanUp(envId uint64) { env := loadEnv(envId) err := os.RemoveAll(env.NodeHome) if err != nil { panic(err) } envRegister.Delete(envId) } //export InitAccount func InitAccount(envId uint64, coinsJson string) *C.char { env := loadEnv(envId) var coins sdk.Coins if err := json.Unmarshal([]byte(coinsJson), &coins); err != nil { panic(err) } priv := secp256k1.GenPrivKey() accAddr := sdk.AccAddress(priv.PubKey().Address()) for _, coin := range coins { // create denom if not exist _, hasDenomMetaData := env.App.BankKeeper.GetDenomMetaData(env.Ctx, coin.Denom) if !hasDenomMetaData { denomMetaData := banktypes.Metadata{ DenomUnits: []*banktypes.DenomUnit{{ Denom: coin.Denom, Exponent: 0, }}, Base: coin.Denom, } env.App.BankKeeper.SetDenomMetaData(env.Ctx, denomMetaData) } } err := banktest.FundAccount(env.App.BankKeeper, env.Ctx, accAddr, coins) if err != nil { panic(errors.Wrapf(err, "Failed to fund account")) } base64Priv := base64.StdEncoding.EncodeToString(priv.Bytes()) envRegister.Store(envId, env) return C.CString(base64Priv) } //export IncreaseTime func IncreaseTime(envId uint64, seconds uint64) { env := loadEnv(envId) env.BeginNewBlock(false, seconds) envRegister.Store(envId, env) EndBlock(envId) } //export BeginBlock func BeginBlock(envId uint64) { env := loadEnv(envId) env.BeginNewBlock(false, 5) envRegister.Store(envId, env) } //export EndBlock func EndBlock(envId uint64) { env := loadEnv(envId) reqEndBlock := abci.RequestEndBlock{Height: env.Ctx.BlockHeight()} env.App.EndBlock(reqEndBlock) env.App.Commit() envRegister.Store(envId, env) } //export Execute func Execute(envId uint64, base64ReqDeliverTx string) *C.char { env := loadEnv(envId) // Temp fix for concurrency issue mu.Lock() defer mu.Unlock() reqDeliverTxBytes, err := base64.StdEncoding.DecodeString(base64ReqDeliverTx) if err != nil { panic(err) } reqDeliverTx := abci.RequestDeliverTx{} err = proto.Unmarshal(reqDeliverTxBytes, &reqDeliverTx) if err != nil { return encodeErrToResultBytes(result.ExecuteError, err) } resDeliverTx := env.App.DeliverTx(reqDeliverTx) bz, err := proto.Marshal(&resDeliverTx) if err != nil { panic(err) } envRegister.Store(envId, env) return encodeBytesResultBytes(bz) } //export Query func Query(envId uint64, path, base64QueryMsgBytes string) *C.char { env := loadEnv(envId) queryMsgBytes, err := base64.StdEncoding.DecodeString(base64QueryMsgBytes) if err != nil { panic(err) } req := abci.RequestQuery{} req.Data = queryMsgBytes route := env.App.GRPCQueryRouter().Route(path) if route == nil { err := errors.New("No route found for `" + path + "`") return encodeErrToResultBytes(result.QueryError, err) } res, err := route(env.Ctx, req) if err != nil { return encodeErrToResultBytes(result.QueryError, err) } return encodeBytesResultBytes(res.Value) } //export GetBlockTime func GetBlockTime(envId uint64) int64 { env := loadEnv(envId) return env.Ctx.BlockTime().UnixNano() } //export GetBlockHeight func GetBlockHeight(envId uint64) int64 { env := loadEnv(envId) return env.Ctx.BlockHeight() } //export AccountSequence func AccountSequence(envId uint64, bech32Address string) uint64 { env := loadEnv(envId) addr, err := sdk.AccAddressFromBech32(bech32Address) if err != nil { panic(err) } seq, err := env.App.AppKeepers.AccountKeeper.GetSequence(env.Ctx, addr) if err != nil { panic(err) } return seq } //export AccountNumber func AccountNumber(envId uint64, bech32Address string) uint64 { env := loadEnv(envId) addr, err := sdk.AccAddressFromBech32(bech32Address) if err != nil { panic(err) } acc := env.App.AppKeepers.AccountKeeper.GetAccount(env.Ctx, addr) return acc.GetAccountNumber() } //export Simulate func Simulate(envId uint64, base64TxBytes string) *C.char { // => base64GasInfo env := loadEnv(envId) // Temp fix for concurrency issue mu.Lock() defer mu.Unlock() txBytes, err := base64.StdEncoding.DecodeString(base64TxBytes) if err != nil { panic(err) } gasInfo, _, err := env.App.Simulate(txBytes) if err != nil { return encodeErrToResultBytes(result.ExecuteError, err) } bz, err := proto.Marshal(&gasInfo) if err != nil { panic(err) } return encodeBytesResultBytes(bz) } //export SetParamSet func SetParamSet(envId uint64, subspaceName, base64ParamSetBytes string) *C.char { env := loadEnv(envId) // Temp fix for concurrency issue mu.Lock() defer mu.Unlock() paramSetBytes, err := base64.StdEncoding.DecodeString(base64ParamSetBytes) if err != nil { panic(err) } subspace, ok := env.App.ParamsKeeper.GetSubspace(subspaceName) if !ok { err := errors.New("No subspace found for `" + subspaceName + "`") return encodeErrToResultBytes(result.ExecuteError, err) } pReg := env.ParamTypesRegistry any := codectypes.Any{} err = proto.Unmarshal(paramSetBytes, &any) if err != nil { return encodeErrToResultBytes(result.ExecuteError, err) } pset, err := pReg.UnpackAny(&any) if err != nil { return encodeErrToResultBytes(result.ExecuteError, err) } subspace.SetParamSet(env.Ctx, pset) // return empty bytes if no error return encodeBytesResultBytes([]byte{}) } //export GetParamSet func GetParamSet(envId uint64, subspaceName, typeUrl string) *C.char { env := loadEnv(envId) subspace, ok := env.App.ParamsKeeper.GetSubspace(subspaceName) if !ok { err := errors.New("No subspace found for `" + subspaceName + "`") return encodeErrToResultBytes(result.ExecuteError, err) } pReg := env.ParamTypesRegistry pset, ok := pReg.GetEmptyParamsSet(typeUrl) if !ok { err := errors.New("No param set found for `" + typeUrl + "`") return encodeErrToResultBytes(result.ExecuteError, err) } subspace.GetParamSet(env.Ctx, pset) bz, err := proto.Marshal(pset) if err != nil { panic(err) } return encodeBytesResultBytes(bz) } //export GetValidatorAddress func GetValidatorAddress(envId uint64, n int32) *C.char { env := loadEnv(envId) return C.CString(env.GetValidatorAddresses()[n]) } //export GetValidatorPrivateKey func GetValidatorPrivateKey(envId uint64, n int32) *C.char { env := loadEnv(envId) priv := env.ValPrivs[n].Key base64Priv := base64.StdEncoding.EncodeToString(priv) return C.CString(base64Priv) } // ========= utils ========= func loadEnv(envId uint64) testenv.TestEnv { item, ok := envRegister.Load(envId) env := testenv.TestEnv(item.(testenv.TestEnv)) if !ok { panic(fmt.Sprintf("env not found: %d", envId)) } return env } func encodeErrToResultBytes(code byte, err error) *C.char { return C.CString(result.EncodeResultFromError(code, err)) } func encodeBytesResultBytes(bytes []byte) *C.char { return C.CString(result.EncodeResultFromOk(bytes)) } // must define main for ffi build func main() {}