diff --git a/app/app.go b/app/app.go index 4e03cd0..9579490 100644 --- a/app/app.go +++ b/app/app.go @@ -639,7 +639,8 @@ func NewSimApp( // domain := uint32(12345) app.IgpKeeper = igpkeeper.NewKeeper(appCodec, keys[igptypes.StoreKey], app.BankKeeper.(bankkeeper.SendKeeper), app.StakingKeeper, "") app.IsmKeeper = ismkeeper.NewKeeper(appCodec, keys[ismtypes.StoreKey], authtypes.NewModuleAddress(govtypes.ModuleName).String()) - app.MailboxKeeper = mailboxkeeper.NewKeeper(appCodec, keys[mailboxtypes.StoreKey], &app.WasmKeeper, &app.IsmKeeper) + app.MailboxKeeper = mailboxkeeper.NewKeeper(appCodec, keys[mailboxtypes.StoreKey], &app.IsmKeeper) + app.MailboxKeeper.AddWasmReceiver(&app.WasmKeeper) app.AnnounceKeeper = announcekeeper.NewKeeper(appCodec, keys[announcetypes.StoreKey], app.MailboxKeeper) // app.MailboxKeeper.SetDomain(domain) diff --git a/contracts/interface-test/src/contract.rs b/contracts/interface-test/src/contract.rs index 6a32859..5e8eb23 100644 --- a/contracts/interface-test/src/contract.rs +++ b/contracts/interface-test/src/contract.rs @@ -1,7 +1,9 @@ use crate::{ error::ContractError, msg::{ExecuteMsg, InstantiateMsg, MigrateMsg, QueryMsg}, - state::OWNER, + state::{ + OWNER, ISM, + }, execute, queries, hyperlane_bindings::HyperlaneMsg, }; @@ -19,6 +21,7 @@ pub fn instantiate( _msg: InstantiateMsg, ) -> Result { OWNER.save(deps.storage, &info.sender)?; + ISM.save(deps.storage, &0)?; Ok(Response::new() .add_event(Event::new("hyperlane_init").add_attribute("attr", "value")) @@ -53,6 +56,9 @@ pub fn execute( ExecuteMsg::ChangeContractOwner { new_owner } => { execute::change_contract_owner(deps, info, new_owner) } + ExecuteMsg::SetIsmId { ism_id } => { + execute::set_ism(deps, info, ism_id) + } } } @@ -61,5 +67,6 @@ pub fn execute( pub fn query(deps: Deps, _env: Env, msg: QueryMsg) -> StdResult { match msg { QueryMsg::Owner {} => to_binary(&queries::query_owner(deps)?), + QueryMsg::Ism {} => to_binary(&queries::query_ism(deps)?), } } diff --git a/contracts/interface-test/src/execute.rs b/contracts/interface-test/src/execute.rs index 37a72d6..d529cdf 100644 --- a/contracts/interface-test/src/execute.rs +++ b/contracts/interface-test/src/execute.rs @@ -1,6 +1,6 @@ use crate::{ error::ContractError, - state::OWNER, + state::{OWNER, ISM}, hyperlane_bindings::HyperlaneMsg, }; use cosmwasm_std::{Addr, Deps, DepsMut, MessageInfo, Response, CosmosMsg}; @@ -75,4 +75,21 @@ pub fn check_is_contract_owner(deps: Deps, sender: Addr) -> Result<(), ContractE } else { Ok(()) } +} + +pub fn set_ism( + deps: DepsMut, + info: MessageInfo, + ism_id: u32, +) -> Result, ContractError> { + // Only allow current contract owner to change owner + check_is_contract_owner(deps.as_ref(), info.sender)?; + + // update ism id + ISM.save(deps.storage, &ism_id)?; + + // return OK + Ok(Response::new() + .add_attribute("action", "set_ism") + .add_attribute("ism_id", ism_id.to_string())) } \ No newline at end of file diff --git a/contracts/interface-test/src/msg.rs b/contracts/interface-test/src/msg.rs index 538c5c0..c8c3362 100644 --- a/contracts/interface-test/src/msg.rs +++ b/contracts/interface-test/src/msg.rs @@ -21,6 +21,9 @@ pub enum ExecuteMsg { ChangeContractOwner { new_owner: String, }, + SetIsmId { + ism_id: u32, + } } #[cw_serde] @@ -29,9 +32,16 @@ pub enum QueryMsg { /// Owner returns the owner of the contract. Response: OwnerResponse #[returns(OwnerResponse)] Owner {}, + #[returns(IsmResponse)] + Ism {}, } #[cw_serde] pub struct OwnerResponse { pub address: String, } + +#[cw_serde] +pub struct IsmResponse { + pub ism_id: u32, +} \ No newline at end of file diff --git a/contracts/interface-test/src/queries.rs b/contracts/interface-test/src/queries.rs index 82b7448..e3d4bc3 100644 --- a/contracts/interface-test/src/queries.rs +++ b/contracts/interface-test/src/queries.rs @@ -1,6 +1,6 @@ use crate::{ - msg::OwnerResponse, - state::OWNER, + msg::{IsmResponse, OwnerResponse}, + state::{ISM, OWNER}, }; use cosmwasm_std::{Deps, StdResult}; @@ -9,4 +9,9 @@ pub fn query_owner(deps: Deps) -> StdResult { Ok(OwnerResponse { address: owner.to_string(), }) +} + +pub fn query_ism(deps: Deps) -> StdResult { + let ism = ISM.load(deps.storage)?; + Ok(IsmResponse { ism_id: ism }) } \ No newline at end of file diff --git a/contracts/interface-test/src/state.rs b/contracts/interface-test/src/state.rs index d7ecf6b..bfb57ac 100644 --- a/contracts/interface-test/src/state.rs +++ b/contracts/interface-test/src/state.rs @@ -1,4 +1,5 @@ use cosmwasm_std::Addr; use cw_storage_plus::Item; -pub const OWNER: Item = Item::new("owner"); \ No newline at end of file +pub const OWNER: Item = Item::new("owner"); +pub const ISM: Item = Item::new("ism"); \ No newline at end of file diff --git a/interchaintest/contracts/hyperlane.wasm b/interchaintest/contracts/hyperlane.wasm index 9b38bab..78a36b4 100755 Binary files a/interchaintest/contracts/hyperlane.wasm and b/interchaintest/contracts/hyperlane.wasm differ diff --git a/interchaintest/counterchain/counter_chain.go b/interchaintest/counterchain/counter_chain.go index 2cc91d2..c66dacf 100644 --- a/interchaintest/counterchain/counter_chain.go +++ b/interchaintest/counterchain/counter_chain.go @@ -10,14 +10,18 @@ import ( "github.com/strangelove-ventures/hyperlane-cosmos/imt" common "github.com/strangelove-ventures/hyperlane-cosmos/x/common" + ismtypes "github.com/strangelove-ventures/hyperlane-cosmos/x/ism/types" + "github.com/strangelove-ventures/hyperlane-cosmos/x/ism/types/legacy_multisig" + "github.com/strangelove-ventures/hyperlane-cosmos/x/ism/types/merkle_root_multisig" + "github.com/strangelove-ventures/hyperlane-cosmos/x/ism/types/message_id_multisig" ) const MAX_MESSAGE_BODY_BYTES = 2_000 var ( - LEGACY_MULTISIG = "legacy_multisig" - MERKLE_ROOT_MULTISIG = "merkle_root_multisig" - MESSAGE_ID_MULTISIG = "message_id_multisig" + LEGACY_MULTISIG = "LegacyMultiSig" + MERKLE_ROOT_MULTISIG = "MerkleRootMultiSig" + MESSAGE_ID_MULTISIG = "MessageIdMultiSig" ) type CounterChain struct { @@ -113,3 +117,43 @@ func (c *CounterChain) CreateMessage(sender string, originDomain uint32, destDom return message, proof } + +func (c *CounterChain) VerifyAbstractIsm(ism ismtypes.AbstractIsm) bool { + switch c.IsmType { + case LEGACY_MULTISIG: + lms := ism.(*legacy_multisig.LegacyMultiSig) + if lms.Threshold == uint32(c.ValSet.Threshold) { + for i, val := range c.ValSet.Vals { + if val.Addr != lms.ValidatorPubKeys[i] { + return false + } + } + return true + } + + case MESSAGE_ID_MULTISIG: + mims := ism.(*message_id_multisig.MessageIdMultiSig) + if mims.Threshold == uint32(c.ValSet.Threshold) { + for i, val := range c.ValSet.Vals { + if val.Addr != mims.ValidatorPubKeys[i] { + return false + } + } + return true + } + + case MERKLE_ROOT_MULTISIG: + mrms := ism.(*merkle_root_multisig.MerkleRootMultiSig) + if mrms.Threshold == uint32(c.ValSet.Threshold) { + for i, val := range c.ValSet.Vals { + if val.Addr != mrms.ValidatorPubKeys[i] { + return false + } + } + return true + } + + } + + return false +} diff --git a/interchaintest/helpers/cosmwasm.go b/interchaintest/helpers/cosmwasm.go index eb31530..6baa965 100644 --- a/interchaintest/helpers/cosmwasm.go +++ b/interchaintest/helpers/cosmwasm.go @@ -2,9 +2,11 @@ package helpers import ( "context" + "encoding/json" "testing" "github.com/strangelove-ventures/interchaintest/v7/chain/cosmos" + "github.com/strangelove-ventures/interchaintest/v7/ibc" "github.com/stretchr/testify/require" ) @@ -17,3 +19,15 @@ func SetupContract(t *testing.T, ctx context.Context, chain *cosmos.CosmosChain, return codeId, contractAddr } + +func SetContractsIsm(t *testing.T, ctx context.Context, chain *cosmos.CosmosChain, user ibc.Wallet, contractAddr string, ismId uint32) { + setIsmMsg := ExecuteMsg{ + SetIsmId: &SetIsmId{ + IsmId: ismId, + }, + } + setIsmMsgBz, err := json.Marshal(setIsmMsg) + require.NoError(t, err) + _, err = chain.ExecuteContract(ctx, user.KeyName(), contractAddr, string(setIsmMsgBz)) + require.NoError(t, err) +} diff --git a/interchaintest/helpers/ism.go b/interchaintest/helpers/ism.go index bdfb12c..00b4195 100644 --- a/interchaintest/helpers/ism.go +++ b/interchaintest/helpers/ism.go @@ -3,9 +3,11 @@ package helpers import ( "context" "fmt" + "strconv" "testing" codectypes "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/cosmos/cosmos-sdk/crypto/keyring" sdk "github.com/cosmos/cosmos-sdk/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" @@ -92,6 +94,68 @@ func SetDefaultIsm(t *testing.T, ctx context.Context, chain *cosmos.CosmosChain, require.NoError(t, err) } +func CreateCustomIsm(t *testing.T, ctx context.Context, chain *cosmos.CosmosChain, keyName string, counterChain *counterchain.CounterChain) uint32 { + var valSet []string + for _, val := range counterChain.ValSet.Vals { + valSet = append(valSet, val.Addr) + } + + var ism ismtypes.AbstractIsm + switch counterChain.IsmType { + case counterchain.LEGACY_MULTISIG: + ism = &legacy_multisig.LegacyMultiSig{ + Threshold: uint32(counterChain.ValSet.Threshold), + ValidatorPubKeys: valSet, + } + case counterchain.MERKLE_ROOT_MULTISIG: + ism = &merkle_root_multisig.MerkleRootMultiSig{ + Threshold: uint32(counterChain.ValSet.Threshold), + ValidatorPubKeys: valSet, + } + case counterchain.MESSAGE_ID_MULTISIG: + ism = &message_id_multisig.MessageIdMultiSig{ + Threshold: uint32(counterChain.ValSet.Threshold), + ValidatorPubKeys: valSet, + } + } + + msgBz, err := chain.Config().EncodingConfig.Codec.MarshalJSON(ism) + fmt.Println("Msg: ", string(msgBz)) + require.NoError(t, err) + + cmd := []string{ + "simd", "tx", "hyperlane-ism", "create-multisig-ism", counterChain.IsmType, + string(msgBz), + "--node", chain.GetRPCAddress(), + "--home", chain.HomeDir(), + "--chain-id", chain.Config().ChainID, + "--from", keyName, + "--gas", "2500000", + "--gas-adjustment", "2.0", + "--keyring-dir", chain.HomeDir(), + "--keyring-backend", keyring.BackendTest, + "-y", + } + stdout, stderr, err := chain.Exec(ctx, cmd, nil) + require.NoError(t, err) + + fmt.Println("CreateCustomIsm stdout: ", string(stdout)) + fmt.Println("CreateCustomIsm stderr: ", string(stderr)) + + err = testutil.WaitForBlocks(ctx, 2, chain) + require.NoError(t, err) + + ismTxHash := ParseTxHash(string(stdout)) + + events, err := GetEvents(chain, ismTxHash) + require.NoError(t, err) + ismId, found := GetEventAttribute(events, ismtypes.EventTypeCreateCustomIsm, ismtypes.AttributeKeyIndex) + require.True(t, found) + ismId32, err := strconv.ParseUint(ismId, 10, 32) + require.NoError(t, err) + return uint32(ismId32) +} + func QueryAllDefaultIsms(t *testing.T, ctx context.Context, chain *cosmos.CosmosChain) *ismtypes.QueryAllDefaultIsmsResponse { grpcAddress := chain.GetHostGRPCAddress() conn, err := grpc.Dial(grpcAddress, grpc.WithInsecure()) @@ -104,3 +168,29 @@ func QueryAllDefaultIsms(t *testing.T, ctx context.Context, chain *cosmos.Cosmos return res } + +func QueryCustomIsm(t *testing.T, ctx context.Context, chain *cosmos.CosmosChain, ismId uint32) *ismtypes.QueryCustomIsmResponse { + grpcAddress := chain.GetHostGRPCAddress() + conn, err := grpc.Dial(grpcAddress, grpc.WithInsecure()) + require.NoError(t, err) + defer conn.Close() + + queryClient := ismtypes.NewQueryClient(conn) + res, err := queryClient.CustomIsm(ctx, &ismtypes.QueryCustomIsmRequest{IsmId: ismId}) + require.NoError(t, err) + + return res +} + +func QueryAllCustomIsms(t *testing.T, ctx context.Context, chain *cosmos.CosmosChain) *ismtypes.QueryAllCustomIsmsResponse { + grpcAddress := chain.GetHostGRPCAddress() + conn, err := grpc.Dial(grpcAddress, grpc.WithInsecure()) + require.NoError(t, err) + defer conn.Close() + + queryClient := ismtypes.NewQueryClient(conn) + res, err := queryClient.AllCustomIsms(ctx, &ismtypes.QueryAllCustomIsmsRequest{}) + require.NoError(t, err) + + return res +} diff --git a/interchaintest/helpers/mailbox.go b/interchaintest/helpers/mailbox.go index a4e9a85..07216fa 100644 --- a/interchaintest/helpers/mailbox.go +++ b/interchaintest/helpers/mailbox.go @@ -13,10 +13,12 @@ import ( mbtypes "github.com/strangelove-ventures/hyperlane-cosmos/x/mailbox/types" "github.com/cosmos/cosmos-sdk/crypto/keyring" + sdk "github.com/cosmos/cosmos-sdk/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/strangelove-ventures/interchaintest/v7/chain/cosmos" "github.com/strangelove-ventures/interchaintest/v7/testutil" "github.com/stretchr/testify/require" + "google.golang.org/grpc" ) // simd tx hyperlane-mailbox process @@ -246,3 +248,18 @@ func GetMailboxAddress() (string, []byte) { mailboxAddrBytes, _ := hex.DecodeString(mailboxAddr) return mailboxAddr, mailboxAddrBytes } + +func QueryRecipientsIsmId(t *testing.T, ctx context.Context, chain *cosmos.CosmosChain, recipient string) uint32 { + grpcAddress := chain.GetHostGRPCAddress() + conn, err := grpc.Dial(grpcAddress, grpc.WithInsecure()) + require.NoError(t, err) + defer conn.Close() + + queryClient := mbtypes.NewQueryClient(conn) + recipientBz, err := sdk.AccAddressFromBech32(recipient) + require.NoError(t, err) + res, err := queryClient.RecipientsIsmId(ctx, &mbtypes.QueryRecipientsIsmIdRequest{Recipient: recipientBz}) + require.NoError(t, err) + + return res.IsmId +} diff --git a/interchaintest/helpers/types.go b/interchaintest/helpers/types.go index 746b8f4..961ba99 100644 --- a/interchaintest/helpers/types.go +++ b/interchaintest/helpers/types.go @@ -22,6 +22,7 @@ type ExecuteMsg struct { DispatchMsg *DispatchMsg `json:"dispatch_msg,omitempty"` ProcessMsg *ProcessMsg `json:"process_msg,omitempty"` ChangeContractOwner *ChangeContractOwner `json:"change_contract_owner,omitempty"` + SetIsmId *SetIsmId `json:"set_ism_id,omitempty"` } type ExecuteRsp struct{} @@ -39,3 +40,7 @@ type ProcessMsg struct { type ChangeContractOwner struct { NewOwner string `json:"new_owner"` } + +type SetIsmId struct { + IsmId uint32 `json:"ism_id"` +} diff --git a/interchaintest/tests/announcement_test.go b/interchaintest/tests/announcement_test.go index 952cb5a..b843c9c 100644 --- a/interchaintest/tests/announcement_test.go +++ b/interchaintest/tests/announcement_test.go @@ -114,9 +114,6 @@ func TestAnnounce(t *testing.T) { _, contract2 := helpers.SetupContract(t, ctx, simd2, userSimd2.KeyName(), "../contracts/hyperlane.wasm", msg) logger.Info("simd2 contract", zap.String("address", contract2)) - verifyContractEntryPoints(t, ctx, simd1, userSimd, contract) - verifyContractEntryPoints(t, ctx, simd2, userSimd2, contract2) - // Create counter chain 1 with val set signing legacy multisig // The private key used here MUST be the one from the validator config file. TODO: cleanup this test to read it from the file. simd1IsmValidator := counterchain.CreateEmperorValidator(t, uint32(simdDomain), counterchain.LEGACY_MULTISIG, valSimd1PrivKey) @@ -271,7 +268,6 @@ func TestHyperlaneAnnounceWithValidator(t *testing.T) { msg := `{}` _, contract := helpers.SetupContract(t, ctx, simd1, userSimd.KeyName(), "../contracts/hyperlane.wasm", msg) logger.Info("simd1 contract", zap.String("address", contract)) - verifyContractEntryPoints(t, ctx, simd1, userSimd, contract) // Create counter chain with val set signing legacy multisig // The private key used here MUST be the one from the validator config file. TODO: cleanup this test to read it from the file. diff --git a/interchaintest/tests/cosmos_e2e_test.go b/interchaintest/tests/cosmos_e2e_test.go index d2e353c..ec10e4c 100644 --- a/interchaintest/tests/cosmos_e2e_test.go +++ b/interchaintest/tests/cosmos_e2e_test.go @@ -146,9 +146,6 @@ func TestHyperlaneCosmosE2E(t *testing.T) { _, contract2 := helpers.SetupContract(t, ctx, simd2, userSimd2.KeyName(), "../contracts/hyperlane.wasm", msg) logger.Info("simd2 contract", zap.String("address", contract2)) - verifyContractEntryPoints(t, ctx, simd1, userSimd1, contract) - verifyContractEntryPoints(t, ctx, simd2, userSimd2, contract2) - // Create counter chain 1 with val set signing legacy multisig. // The private key used here MUST be the one from the validator config file. simd1IsmValidator := counterchain.CreateEmperorValidator(t, simd1Domain, counterchain.LEGACY_MULTISIG, valSimd1PrivKey) @@ -156,9 +153,16 @@ func TestHyperlaneCosmosE2E(t *testing.T) { simd2IsmValidator := counterchain.CreateEmperorValidator(t, simd2Domain, counterchain.LEGACY_MULTISIG, valSimd2PrivKey) // Set default isms for counter chains for SIMD - helpers.SetDefaultIsm(t, ctx, simd1, userSimd1.KeyName(), simd2IsmValidator) + //helpers.SetDefaultIsm(t, ctx, simd1, userSimd1.KeyName(), simd2IsmValidator) // Set default isms for counter chains for SIMD2 - helpers.SetDefaultIsm(t, ctx, simd2, userSimd2.KeyName(), simd1IsmValidator) + //helpers.SetDefaultIsm(t, ctx, simd2, userSimd2.KeyName(), simd1IsmValidator) + + // Set custom isms for counter chains + ismIdForSimd1 := helpers.CreateCustomIsm(t, ctx, simd1, userSimd1.KeyName(), simd2IsmValidator) + ismIdForSimd2 := helpers.CreateCustomIsm(t, ctx, simd2, userSimd2.KeyName(), simd1IsmValidator) + + helpers.SetContractsIsm(t, ctx, simd1, userSimd1, contract, ismIdForSimd1) + helpers.SetContractsIsm(t, ctx, simd2, userSimd2, contract2, ismIdForSimd2) recipientAccAddr := sdk.MustAccAddressFromBech32(contract2).Bytes() recipientDispatch := hexutil.Encode([]byte(recipientAccAddr)) @@ -245,8 +249,8 @@ func TestHyperlaneCosmosE2E(t *testing.T) { // ***************** IGP setup, copied from *************************************** exchangeRate := math.NewInt(1e10) gasPrice := math.NewInt(1) - testGasAmount := math.NewInt(100_000) - quoteExpected := math.NewInt(100_000) + testGasAmount := math.NewInt(200_000) + quoteExpected := math.NewInt(200_000) beneficiary := "cosmos12aqqagjkk3y7mtgkgy5fuun3j84zr3c6e0zr6n" // This should be IGP 0, which we will ignore and not use for anything @@ -423,9 +427,6 @@ func TestHyperlaneCosmosMultiMessageE2E(t *testing.T) { _, contract2 := helpers.SetupContract(t, ctx, simd2, userSimd2.KeyName(), "../contracts/hyperlane.wasm", msg) logger.Info("simd2 contract", zap.String("address", contract2)) - verifyContractEntryPoints(t, ctx, simd1, userSimd, contract) - verifyContractEntryPoints(t, ctx, simd2, userSimd2, contract2) - // Create counter chain 1 with val set signing legacy multisig. // The private key used here MUST be the one from the validator config file. simd1IsmValidator := counterchain.CreateEmperorValidator(t, simd1Domain, counterchain.LEGACY_MULTISIG, valSimd1PrivKey) @@ -679,9 +680,6 @@ func TestHyperlaneCosmosValidator(t *testing.T) { _, contract2 := helpers.SetupContract(t, ctx, simd2, userSimd2.KeyName(), "../contracts/hyperlane.wasm", msg) logger.Info("simd2 contract", zap.String("address", contract2)) - verifyContractEntryPoints(t, ctx, simd1, userSimd, contract) - verifyContractEntryPoints(t, ctx, simd2, userSimd2, contract2) - // Create counter chain 1 with val set signing legacy multisig // The private key used here MUST be the one from the validator config file. TODO: cleanup this test to read it from the file. simd1IsmValidator := counterchain.CreateEmperorValidator(t, uint32(simdDomain), counterchain.LEGACY_MULTISIG, valSimd1PrivKey) diff --git a/interchaintest/tests/module_mailbox_test.go b/interchaintest/tests/module_mailbox_test.go index e06925e..c56d53d 100644 --- a/interchaintest/tests/module_mailbox_test.go +++ b/interchaintest/tests/module_mailbox_test.go @@ -51,8 +51,6 @@ func TestHyperlaneMailbox(t *testing.T) { _, contract := helpers.SetupContract(t, ctx, simd, user.KeyName(), "../contracts/hyperlane.wasm", msg) t.Log("coreContract", contract) - verifyContractEntryPoints(t, ctx, simd, user, contract) - // Create counter chain 1, with origin 1, with val set signing legacy multisig counterChain1 := counterchain.CreateCounterChain(t, 1, counterchain.LEGACY_MULTISIG) counterChain2 := counterchain.CreateCounterChain(t, 2, counterchain.MESSAGE_ID_MULTISIG) @@ -120,6 +118,135 @@ func TestHyperlaneMailbox(t *testing.T) { require.NoError(t, err) } +// TestHyperlaneMailboxWithCustomISM ensures the mailbox module & bindings work properly with a custom ISM. +func TestHyperlaneMailboxWithCustomISM(t *testing.T) { + t.Parallel() + + // Base setup + chains := CreateSingleHyperlaneSimd(t) + ctx := BuildInitialChain(t, chains) + + // Chains + simd := chains[0].(*cosmos.CosmosChain) + t.Log("simd.GetHostRPCAddress()", simd.GetHostRPCAddress()) + t.Log("simd.GetHostGRPCAddress()", simd.GetHostGRPCAddress()) + + users := icv7.GetAndFundTestUsers(t, ctx, "default", int64(10_000_000_000), simd) + user := users[0] + + msg := fmt.Sprintf(`{}`) + _, contract := helpers.SetupContract(t, ctx, simd, user.KeyName(), "../contracts/hyperlane.wasm", msg) + t.Log("coreContract", contract) + + // Create counter chain 1, with origin 1, with val set signing legacy multisig + counterChain1 := counterchain.CreateCounterChain(t, 1, counterchain.LEGACY_MULTISIG) + counterChain2 := counterchain.CreateCounterChain(t, 2, counterchain.MESSAGE_ID_MULTISIG) + counterChain3 := counterchain.CreateCounterChain(t, 3, counterchain.MERKLE_ROOT_MULTISIG) + + // Set custom isms for counter chains + ismId1 := helpers.CreateCustomIsm(t, ctx, simd, user.KeyName(), counterChain1) + ismId2 := helpers.CreateCustomIsm(t, ctx, simd, user.KeyName(), counterChain2) + ismId3 := helpers.CreateCustomIsm(t, ctx, simd, user.KeyName(), counterChain3) + + // Query custom ISM 1 + customIsmResp1 := helpers.QueryCustomIsm(t, ctx, simd, ismId1) + var abstractIsm1 ismtypes.AbstractIsm + err := simd.Config().EncodingConfig.InterfaceRegistry.UnpackAny(customIsmResp1.CustomIsm, &abstractIsm1) + require.NoError(t, err) + require.True(t, counterChain1.VerifyAbstractIsm(abstractIsm1)) + + // Query custom ISM 2 + customIsmResp2 := helpers.QueryCustomIsm(t, ctx, simd, ismId2) + var abstractIsm2 ismtypes.AbstractIsm + err = simd.Config().EncodingConfig.InterfaceRegistry.UnpackAny(customIsmResp2.CustomIsm, &abstractIsm2) + require.NoError(t, err) + require.True(t, counterChain2.VerifyAbstractIsm(abstractIsm2)) + + // Query custom ISM 3 + customIsmResp3 := helpers.QueryCustomIsm(t, ctx, simd, ismId3) + var abstractIsm3 ismtypes.AbstractIsm + err = simd.Config().EncodingConfig.InterfaceRegistry.UnpackAny(customIsmResp3.CustomIsm, &abstractIsm3) + require.NoError(t, err) + require.True(t, counterChain3.VerifyAbstractIsm(abstractIsm3)) + + // Query all custom ISMs + allCustomIsms := helpers.QueryAllCustomIsms(t, ctx, simd) + require.Equal(t, customIsmResp1.CustomIsm.TypeUrl, allCustomIsms.CustomIsms[0].AbstractIsm.TypeUrl) + require.Equal(t, customIsmResp1.CustomIsm.Value, allCustomIsms.CustomIsms[0].AbstractIsm.Value) + require.Equal(t, customIsmResp2.CustomIsm.TypeUrl, allCustomIsms.CustomIsms[1].AbstractIsm.TypeUrl) + require.Equal(t, customIsmResp2.CustomIsm.Value, allCustomIsms.CustomIsms[1].AbstractIsm.Value) + require.Equal(t, customIsmResp3.CustomIsm.TypeUrl, allCustomIsms.CustomIsms[2].AbstractIsm.TypeUrl) + require.Equal(t, customIsmResp3.CustomIsm.Value, allCustomIsms.CustomIsms[2].AbstractIsm.Value) + + sender := "0xbcb815f38D481a5EBA4D7ac4c9E74D9D0FC2A7e7" + destDomain := uint32(12345) + + // Update contract to use Legacy MultiSig ISM + helpers.SetContractsIsm(t, ctx, simd, user, contract, ismId1) + contractsIsmId := helpers.QueryRecipientsIsmId(t, ctx, simd, contract) + require.Equal(t, ismId1, contractsIsmId) + + // Create first legacy multisig message from counter chain 1 + message1, proof1 := counterChain1.CreateMessage(sender, 1, destDomain, contract, "Legacy Multisig 1") + metadata1 := counterChain1.CreateLegacyMetadata(message1, proof1) + msgId1 := hexutil.Encode(common.Id(message1)) + delivered := helpers.QueryMsgDelivered(t, ctx, simd, msgId1) + require.False(t, delivered) + helpers.CallProcessMsg(t, ctx, simd, user.KeyName(), hexutil.Encode(metadata1), hexutil.Encode(message1)) + delivered = helpers.QueryMsgDelivered(t, ctx, simd, msgId1) + require.True(t, delivered) + + // Create second legacy multisig message from counter chain 1 + message2, proof2 := counterChain1.CreateMessage(sender, 1, destDomain, contract, "Legacy Multisig 2") + metadata2 := counterChain1.CreateLegacyMetadata(message2, proof2) + msgId2 := hexutil.Encode(common.Id(message2)) + delivered = helpers.QueryMsgDelivered(t, ctx, simd, msgId2) + require.False(t, delivered) + helpers.CallProcessMsg(t, ctx, simd, user.KeyName(), hexutil.Encode(metadata2), hexutil.Encode(message2)) + delivered = helpers.QueryMsgDelivered(t, ctx, simd, msgId2) + require.True(t, delivered) + + // Create third legacy multisig message from counter chain 1 + message3, proof3 := counterChain1.CreateMessage(sender, 1, destDomain, contract, "Legacy Multisig 3") + metadata3 := counterChain1.CreateLegacyMetadata(message3, proof3) + msgId3 := hexutil.Encode(common.Id(message3)) + delivered = helpers.QueryMsgDelivered(t, ctx, simd, msgId3) + require.False(t, delivered) + helpers.CallProcessMsg(t, ctx, simd, user.KeyName(), hexutil.Encode(metadata3), hexutil.Encode(message3)) + delivered = helpers.QueryMsgDelivered(t, ctx, simd, msgId3) + require.True(t, delivered) + + // Update contract to use Message ID MultiSig ISM + helpers.SetContractsIsm(t, ctx, simd, user, contract, ismId2) + contractsIsmId = helpers.QueryRecipientsIsmId(t, ctx, simd, contract) + require.Equal(t, ismId2, contractsIsmId) + + // Create first message id multisig message from counter chain 2 + message4, _ := counterChain2.CreateMessage(sender, 2, destDomain, contract, "Message Id Multisig 1") + metadata4 := counterChain2.CreateMessageIdMetadata(message4) + msgId4 := hexutil.Encode(common.Id(message4)) + delivered = helpers.QueryMsgDelivered(t, ctx, simd, msgId4) + require.False(t, delivered) + helpers.CallProcessMsg(t, ctx, simd, user.KeyName(), hexutil.Encode(metadata4), hexutil.Encode(message4)) + delivered = helpers.QueryMsgDelivered(t, ctx, simd, msgId4) + require.True(t, delivered) + + // Update contract to use Merkle Root MultiSig ISM + helpers.SetContractsIsm(t, ctx, simd, user, contract, ismId3) + contractsIsmId = helpers.QueryRecipientsIsmId(t, ctx, simd, contract) + require.Equal(t, ismId3, contractsIsmId) + + // Create first merkle root multisig message from counter chain 3 + message5, proof5 := counterChain3.CreateMessage(sender, 3, destDomain, contract, "Merkle Root Multisig 1") + metadata5 := counterChain3.CreateMerkleRootMetadata(message5, proof5) + msgId5 := hexutil.Encode(common.Id(message5)) + delivered = helpers.QueryMsgDelivered(t, ctx, simd, msgId5) + require.False(t, delivered) + helpers.CallProcessMsg(t, ctx, simd, user.KeyName(), hexutil.Encode(metadata5), hexutil.Encode(message5)) + delivered = helpers.QueryMsgDelivered(t, ctx, simd, msgId5) + require.True(t, delivered) +} + func TestHyperlaneIgp(t *testing.T) { t.Parallel() @@ -178,9 +305,6 @@ func TestHyperlaneIgp(t *testing.T) { _, contract2 := helpers.SetupContract(t, ctx, simd2, userSimd2.KeyName(), "../contracts/hyperlane.wasm", msg) t.Log("coreContract", contract2) - verifyContractEntryPoints(t, ctx, simd, userSimd, contract) - verifyContractEntryPoints(t, ctx, simd2, userSimd2, contract2) - // Create counter chain 1 with val set signing legacy multisig simdIsmValidator := counterchain.CreateCounterChain(t, uint32(simdDomain), counterchain.LEGACY_MULTISIG) // Create counter chain 2 with val set signing legacy multisig @@ -378,25 +502,3 @@ func GetQueryContext() (context.Context, context.CancelFunc) { // ctx = metadata.AppendToOutgoingContext(ctx, grpctypes.GRPCBlockHeightHeader, height) return ctx, cancel } - -func verifyContractEntryPoints(t *testing.T, ctx context.Context, simd *cosmos.CosmosChain, user ibc.Wallet, contract string) { - queryMsg := helpers.QueryMsg{Owner: &struct{}{}} - var queryRsp helpers.QueryRsp - err := simd.QueryContract(ctx, contract, queryMsg, &queryRsp) - require.NoError(t, err) - require.Equal(t, user.FormattedAddress(), queryRsp.Data.Address) - - randomAddr := "cosmos10qa7yajp3fp869mdegtpap5zg056exja3chkw5" - newContractOwnerStruct := helpers.ExecuteMsg{ - ChangeContractOwner: &helpers.ChangeContractOwner{ - NewOwner: randomAddr, - }, - } - newContractOwner, err := json.Marshal(newContractOwnerStruct) - require.NoError(t, err) - simd.ExecuteContract(ctx, user.KeyName(), contract, string(newContractOwner)) - - err = simd.QueryContract(ctx, contract, queryMsg, &queryRsp) - require.NoError(t, err) - require.Equal(t, randomAddr, queryRsp.Data.Address) -} diff --git a/proto/hyperlane/mailbox/v1/query.proto b/proto/hyperlane/mailbox/v1/query.proto index 99c0079..702f17f 100644 --- a/proto/hyperlane/mailbox/v1/query.proto +++ b/proto/hyperlane/mailbox/v1/query.proto @@ -28,6 +28,12 @@ service Query { returns (QueryMsgDeliveredResponse) { option (google.api.http).get = "/hyperlane/mailbox/v1/delivered"; } + + // Query ISM ID from recipient + rpc RecipientsIsmId(QueryRecipientsIsmIdRequest) + returns (QueryRecipientsIsmIdResponse) { + option (google.api.http).get = "/hyperlane/mailbox/v1/recipients_ism_id"; + } } // QueryCurrentTreeMetadataRequest is the request type for the Query/Tree @@ -63,3 +69,9 @@ message QueryMsgDeliveredRequest { bytes message_id = 1; } // QueryMsgDeliveredResponse is the response type if message was delivered message QueryMsgDeliveredResponse { bool delivered = 1; } + +// QueryRecipientsIsmIdRequest is the request type to get the ISM ID +message QueryRecipientsIsmIdRequest { bytes recipient = 1; } + +// QueryRecipientsIsmIdResponse is the response type containing the ISM ID +message QueryRecipientsIsmIdResponse { uint32 ism_id = 1; } \ No newline at end of file diff --git a/x/ism/client/cli/cli.go b/x/ism/client/cli/cli.go index 62776b7..baf2678 100644 --- a/x/ism/client/cli/cli.go +++ b/x/ism/client/cli/cli.go @@ -20,6 +20,8 @@ func GetQueryCmd() *cobra.Command { queryCmd.AddCommand( getOriginsDefaultIsmCmd(), getAllDefaultIsmsCmd(), + getCustomIsmCmd(), + getAllCustomIsmsCmd(), ) return queryCmd @@ -37,6 +39,7 @@ func NewTxCmd() *cobra.Command { txCmd.AddCommand( setDefaultIsmCmd(), + createMultiSigIsmCmd(), ) return txCmd diff --git a/x/ism/client/cli/query.go b/x/ism/client/cli/query.go index 453d8e3..d08a6cc 100644 --- a/x/ism/client/cli/query.go +++ b/x/ism/client/cli/query.go @@ -81,3 +81,72 @@ func getAllDefaultIsmsCmd() *cobra.Command { return cmd } + +// getCustomIsmCmd defines the command to query a custom ISM +func getCustomIsmCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: "custom-ism [ism-id]", + Short: "Query custom ISM", + Long: "Query custom ISM given an ism-id", + Example: fmt.Sprintf("%s query %s custom-ism [ism-id]", version.AppName, types.ModuleName), + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.GetClientQueryContext(cmd) + if err != nil { + return err + } + queryClient := types.NewQueryClient(clientCtx) + + ismId, err := strconv.ParseUint(args[0], 10, 32) + if err != nil { + return err + } + + req := types.QueryCustomIsmRequest{ + IsmId: uint32(ismId), + } + + res, err := queryClient.CustomIsm(context.Background(), &req) + if err != nil { + return err + } + + return clientCtx.PrintProto(res) + }, + } + + flags.AddQueryFlagsToCmd(cmd) + + return cmd +} + +// getAllCustomIsmsCmd defines the command to query all custom ISMs +func getAllCustomIsmsCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: "all-custom-isms", + Short: "Query all custom ISMs", + Long: "Query all custom ISMs", + Example: fmt.Sprintf("%s query %s all-custom-isms", version.AppName, types.ModuleName), + Args: cobra.ExactArgs(0), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.GetClientQueryContext(cmd) + if err != nil { + return err + } + queryClient := types.NewQueryClient(clientCtx) + + req := types.QueryAllCustomIsmsRequest{} + + res, err := queryClient.AllCustomIsms(context.Background(), &req) + if err != nil { + return err + } + + return clientCtx.PrintProto(res) + }, + } + + flags.AddQueryFlagsToCmd(cmd) + + return cmd +} diff --git a/x/ism/client/cli/tx.go b/x/ism/client/cli/tx.go index 4a0055c..2d769ad 100644 --- a/x/ism/client/cli/tx.go +++ b/x/ism/client/cli/tx.go @@ -13,9 +13,12 @@ import ( "github.com/spf13/cobra" "github.com/strangelove-ventures/hyperlane-cosmos/x/ism/types" + "github.com/strangelove-ventures/hyperlane-cosmos/x/ism/types/legacy_multisig" + "github.com/strangelove-ventures/hyperlane-cosmos/x/ism/types/merkle_root_multisig" + "github.com/strangelove-ventures/hyperlane-cosmos/x/ism/types/message_id_multisig" ) -// newStoreCodeCmd returns the command to create a MsgStoreCode transaction +// setDefaultIsmCmd returns the command to set default ISM(s) func setDefaultIsmCmd() *cobra.Command { cmd := &cobra.Command{ Use: "set-default-ism [path/to/ism.json]", @@ -27,13 +30,14 @@ Example: $ %s tx %s set-default-ism [path/to/ism.json] Where ism.json contains: - { - isms: + "@type":""/hyperlane.ism.v1.MsgSetDefaultIsm", + "isms": [ { "origin": 1, - "ism": { + "abstract_ism": { + "@type":"/hyperlane.ism.v1.LegacyMultiSig", "validator_pub_keys": [ "0x123456789", "0x234567890", @@ -44,7 +48,8 @@ Where ism.json contains: }, { "origin": 2, - "ism": { + "abstract_ism": { + "@type":"/hyperlane.ism.v1.MerkleRootMultiSig", "validator_pub_keys": [ "0x123456789", "0x234567890", @@ -56,7 +61,7 @@ Where ism.json contains: ... ] } `, version.AppName, types.ModuleName)), - Example: fmt.Sprintf("%s tx %s set-default-ism [ism-hash]", version.AppName, types.ModuleName), + Example: fmt.Sprintf("%s tx %s set-default-ism [path/to/ism.json]", version.AppName, types.ModuleName), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { clientCtx, err := client.GetClientTxContext(cmd) @@ -89,3 +94,71 @@ Where ism.json contains: return cmd } + +// createIsmCmd returns the command to create a MsgCreateIsm transaction +func createMultiSigIsmCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: "create-multisig-ism [type] [ism-json-string]", + Short: "Create a new multisig ISM", + Long: strings.TrimSpace( + fmt.Sprintf(`Create a new LegacyMultiSig ISM. +Example: +$ %s tx %s create-ism LegacyMultiSig +{"validator_pub_keys":["0x123456789...","0x234567890...","0x345678901..."],"threshold":2}`, version.AppName, types.ModuleName)), + Example: fmt.Sprintf("%s tx %s create-ism [type] [ism-json-string]", version.AppName, types.ModuleName), + Args: cobra.ExactArgs(2), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.GetClientTxContext(cmd) + if err != nil { + return err + } + + contents := []byte(args[1]) + + var ism types.AbstractIsm + switch args[0] { + case "LegacyMultiSig": + var lms legacy_multisig.LegacyMultiSig + err = json.Unmarshal(contents, &lms) + if err != nil { + return err + } + ism = &lms + case "MerkleRootMultiSig": + var mrms merkle_root_multisig.MerkleRootMultiSig + err = json.Unmarshal(contents, &mrms) + if err != nil { + return err + } + ism = &mrms + case "MessageIdMultiSig": + var mims message_id_multisig.MessageIdMultiSig + err = json.Unmarshal(contents, &mims) + if err != nil { + return err + } + ism = &mims + } + + ismAny, err := types.PackAbstractIsm(ism) + if err != nil { + return err + } + + msg := types.MsgCreateIsm{ + Signer: clientCtx.GetFromAddress().String(), + Ism: ismAny, + } + + if err := msg.ValidateBasic(); err != nil { + return err + } + + return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) + }, + } + + flags.AddTxFlagsToCmd(cmd) + + return cmd +} diff --git a/x/ism/keeper/genesis.go b/x/ism/keeper/genesis.go index f8a541e..84da09d 100644 --- a/x/ism/keeper/genesis.go +++ b/x/ism/keeper/genesis.go @@ -40,7 +40,7 @@ func (k Keeper) InitGenesis(ctx sdk.Context, gs types.GenesisState) error { func (k Keeper) ExportGenesis(ctx sdk.Context) types.GenesisState { return types.GenesisState{ DefaultIsm: k.ExportDefaultIsms(ctx), - CustomIsm: k.ExportCustomIsms(ctx), + CustomIsm: k.ExportCustomIsms(ctx), } } @@ -98,10 +98,10 @@ func (k Keeper) ExportCustomIsms(ctx sdk.Context) []types.CustomIsm { panic(err) } customIsms = append(customIsms, types.CustomIsm{ - Index: uint32(index), + Index: uint32(index), AbstractIsm: ismAny, }) } return customIsms -} \ No newline at end of file +} diff --git a/x/ism/keeper/genesis_test.go b/x/ism/keeper/genesis_test.go index 54e275f..20031bf 100644 --- a/x/ism/keeper/genesis_test.go +++ b/x/ism/keeper/genesis_test.go @@ -34,7 +34,7 @@ func (suite *KeeperTestSuite) TestGenesis() { actualDefaultIsm := types.MustUnpackAbstractIsm(gs.DefaultIsm[i].AbstractIsm) suite.Require().Equal(defaultIsms[i].Origin, gs.DefaultIsm[i].Origin) suite.Require().Equal(expectedIsm, actualDefaultIsm) - + actualCustomIsm := types.MustUnpackAbstractIsm(gs.CustomIsm[i].AbstractIsm) suite.Require().Equal(uint32(i+1), gs.CustomIsm[i].Index) suite.Require().Equal(expectedIsm, actualCustomIsm) @@ -46,14 +46,14 @@ func (suite *KeeperTestSuite) TestGenesis() { suite.Require().NoError(err) metadata, err := hex.DecodeString(metadatas[0]) suite.Require().NoError(err) - pass, err := suite.keeper.Verify(suite.ctx, metadata, message) + pass, err := suite.keeper.Verify(suite.ctx, metadata, message, 0) suite.Require().Error(err) suite.Require().False(pass) err = suite.keeper.InitGenesis(suite.ctx, gs) suite.Require().NoError(err) - pass, err = suite.keeper.Verify(suite.ctx, metadata, message) + pass, err = suite.keeper.Verify(suite.ctx, metadata, message, 0) suite.Require().NoError(err) suite.Require().True(pass) @@ -68,9 +68,9 @@ func (suite *KeeperTestSuite) TestGenesis() { actualDefaultIsm := types.MustUnpackAbstractIsm(defaultIsmResp.DefaultIsm) suite.Require().Equal(defaultIsms[i].Origin, gs.DefaultIsm[i].Origin) suite.Require().Equal(expectedIsm, actualDefaultIsm) - + customIsmReq := types.QueryCustomIsmRequest{ - IsmId: uint32(i+1), + IsmId: uint32(i + 1), } customIsmResp, err := suite.queryClient.CustomIsm(suite.ctx, &customIsmReq) suite.Require().NoError(err) diff --git a/x/ism/keeper/grpc_query.go b/x/ism/keeper/grpc_query.go index 748d52d..11527f7 100644 --- a/x/ism/keeper/grpc_query.go +++ b/x/ism/keeper/grpc_query.go @@ -5,7 +5,7 @@ import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/status" - + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/strangelove-ventures/hyperlane-cosmos/x/ism/types" diff --git a/x/ism/keeper/grpc_query_test.go b/x/ism/keeper/grpc_query_test.go index c475ce3..f234de3 100644 --- a/x/ism/keeper/grpc_query_test.go +++ b/x/ism/keeper/grpc_query_test.go @@ -121,13 +121,12 @@ func (suite *KeeperTestSuite) TestQueryAllDefaultIsms() { } } - func (suite *KeeperTestSuite) TestQueryCustomIsm() { var req *types.QueryCustomIsmRequest var index uint32 signer := authtypes.NewModuleAddress(govtypes.ModuleName).String() - + testCases := []struct { name string malleate func() @@ -185,7 +184,6 @@ func (suite *KeeperTestSuite) TestQueryCustomIsm() { for _, tc := range testCases { suite.Run(tc.name, func() { - tc.malleate() res, err := suite.queryClient.CustomIsm(suite.ctx, req) @@ -223,7 +221,7 @@ func (suite *KeeperTestSuite) TestQueryAllCustomIsms() { suite.SetupTest() signer := authtypes.NewModuleAddress(govtypes.ModuleName).String() - + msg := types.NewMsgCreateIsm(signer, defaultIsms[0].AbstractIsm) resp1, err := suite.keeper.CreateIsm(suite.ctx, msg) suite.Require().NoError(err) @@ -259,4 +257,3 @@ func (suite *KeeperTestSuite) TestQueryAllCustomIsms() { }) } } - diff --git a/x/ism/keeper/keeper.go b/x/ism/keeper/keeper.go index a077329..ba4ffba 100644 --- a/x/ism/keeper/keeper.go +++ b/x/ism/keeper/keeper.go @@ -4,8 +4,8 @@ import ( "context" "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" storetypes "github.com/cosmos/cosmos-sdk/store/types" + sdk "github.com/cosmos/cosmos-sdk/types" common "github.com/strangelove-ventures/hyperlane-cosmos/x/common" "github.com/strangelove-ventures/hyperlane-cosmos/x/ism/types" @@ -15,24 +15,24 @@ type Keeper struct { // implements gRPC QueryServer interface types.QueryServer - storeKey storetypes.StoreKey - cdc codec.BinaryCodec - authority string + storeKey storetypes.StoreKey + cdc codec.BinaryCodec + authority string } func NewKeeper(cdc codec.BinaryCodec, key storetypes.StoreKey, authority string) Keeper { return Keeper{ - cdc: cdc, - storeKey: key, - authority: authority, + cdc: cdc, + storeKey: key, + authority: authority, } } -func (k Keeper) Verify(goCtx context.Context, metadata, message []byte) (bool, error) { +func (k Keeper) Verify(goCtx context.Context, metadata, message []byte, ismId uint32) (bool, error) { ctx := sdk.UnwrapSDKContext(goCtx) msgOrigin := common.Origin(message) - // Look up recipient contract's ISM, if 0, use default multi sig (just use default for now) - ism, err := k.getDefaultIsm(ctx, msgOrigin) + + ism, err := k.getIsm(ctx, ismId, msgOrigin) if err != nil { return false, err } diff --git a/x/ism/keeper/keeper_test.go b/x/ism/keeper/keeper_test.go index ca4d6f1..4bd7157 100644 --- a/x/ism/keeper/keeper_test.go +++ b/x/ism/keeper/keeper_test.go @@ -108,7 +108,7 @@ func (suite *KeeperTestSuite) TestVerify() { _, err := suite.msgServer.SetDefaultIsm(suite.ctx, msg) suite.Require().NoError(err) - pass, err := suite.keeper.Verify(suite.ctx, tc.metadata, tc.message) + pass, err := suite.keeper.Verify(suite.ctx, tc.metadata, tc.message, 0) if tc.expPass { suite.Require().True(pass) diff --git a/x/ism/keeper/msg_server.go b/x/ism/keeper/msg_server.go index dbe8656..a6a295e 100644 --- a/x/ism/keeper/msg_server.go +++ b/x/ism/keeper/msg_server.go @@ -4,7 +4,7 @@ import ( "context" sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + sdkerrors "cosmossdk.io/errors" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/strangelove-ventures/hyperlane-cosmos/x/ism/types" @@ -36,10 +36,10 @@ func (k Keeper) SetDefaultIsm(goCtx context.Context, msg *types.MsgSetDefaultIsm return &types.MsgSetDefaultIsmResponse{}, err } - events.AppendEvent(ism.DefaultIsmEvent(originIsm.Origin)) + events = events.AppendEvent(ism.DefaultIsmEvent(originIsm.Origin)) } - events.AppendEvent(sdk.NewEvent( + events = events.AppendEvent(sdk.NewEvent( sdk.EventTypeMessage, sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName), )) @@ -68,9 +68,9 @@ func (k Keeper) CreateIsm(goCtx context.Context, msg *types.MsgCreateIsm) (*type } events := sdk.Events{} - events.AppendEvent(ism.CustomIsmEvent(ismId)) + events = events.AppendEvent(ism.CustomIsmEvent(ismId)) - events.AppendEvent(sdk.NewEvent( + events = events.AppendEvent(sdk.NewEvent( sdk.EventTypeMessage, sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName), )) diff --git a/x/ism/keeper/msg_server_test.go b/x/ism/keeper/msg_server_test.go index 8e08fce..f56c7b4 100644 --- a/x/ism/keeper/msg_server_test.go +++ b/x/ism/keeper/msg_server_test.go @@ -134,4 +134,4 @@ func (suite *KeeperTestSuite) TestMsgCreateIsm() { } }) } -} \ No newline at end of file +} diff --git a/x/ism/keeper/store.go b/x/ism/keeper/store.go index 09468f0..573f091 100644 --- a/x/ism/keeper/store.go +++ b/x/ism/keeper/store.go @@ -10,6 +10,13 @@ import ( "github.com/strangelove-ventures/hyperlane-cosmos/x/ism/types" ) +func (k Keeper) getIsm(ctx sdk.Context, ismId, origin uint32) (types.AbstractIsm, error) { + if ismId == 0 { + return k.getDefaultIsm(ctx, origin) + } + return k.getCustomIsm(ctx, ismId) +} + // getDefaultIsm returns the default ISM func (k Keeper) getDefaultIsm(ctx sdk.Context, origin uint32) (types.AbstractIsm, error) { store := ctx.KVStore(k.storeKey) @@ -37,20 +44,20 @@ func (k Keeper) getAllDefaultIsms(ctx sdk.Context) ([]*types.DefaultIsm, error) if err != nil { return nil, err } - + var ism types.AbstractIsm err = k.cdc.UnmarshalInterface(iterator.Value(), &ism) if err != nil { return nil, err } - + ismAny, err := types.PackAbstractIsm(ism) if err != nil { return nil, err } defaultIsms = append(defaultIsms, &types.DefaultIsm{ - Origin: uint32(origin64), + Origin: uint32(origin64), AbstractIsm: ismAny, }) } @@ -98,20 +105,20 @@ func (k Keeper) getAllCustomIsms(ctx sdk.Context) ([]*types.CustomIsm, error) { if err != nil { return nil, err } - + var ism types.AbstractIsm err = k.cdc.UnmarshalInterface(iterator.Value(), &ism) if err != nil { return nil, err } - + ismAny, err := types.PackAbstractIsm(ism) if err != nil { return nil, err } customIsms = append(customIsms, &types.CustomIsm{ - Index: uint32(index64), + Index: uint32(index64), AbstractIsm: ismAny, }) } @@ -150,4 +157,4 @@ func (k Keeper) getNextCustomIsmIndex(ctx sdk.Context) (uint32, error) { } return index, nil -} \ No newline at end of file +} diff --git a/x/ism/module.go b/x/ism/module.go index ce3903a..14682d5 100644 --- a/x/ism/module.go +++ b/x/ism/module.go @@ -27,9 +27,7 @@ var ( _ module.AppModuleBasic = (*AppModule)(nil) ) -// AppModuleBasic defines the basic application module used by the hyperlane mailbox. -// Only the RegisterInterfaces function needs to be implemented. All other function perform -// a no-op. +// AppModuleBasic defines the basic application module used by the hyperlane ISM. type AppModuleBasic struct{} // Name returns the hyperlane ISM module name. @@ -52,7 +50,7 @@ func (AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { return cdc.MustMarshalJSON(&types.GenesisState{ DefaultIsm: []types.DefaultIsm{}, - CustomIsm: []types.CustomIsm{}, + CustomIsm: []types.CustomIsm{}, }) } diff --git a/x/ism/types/codec.go b/x/ism/types/codec.go index 9610e42..890e869 100644 --- a/x/ism/types/codec.go +++ b/x/ism/types/codec.go @@ -1,10 +1,9 @@ package types import ( - "fmt" codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + sdkerrors "cosmossdk.io/errors" "github.com/cosmos/cosmos-sdk/types/msgservice" proto "github.com/cosmos/gogoproto/proto" ) @@ -49,13 +48,11 @@ func MustPackAbstractIsm(ism AbstractIsm) *codectypes.Any { func UnpackAbstractIsm(any *codectypes.Any) (AbstractIsm, error) { if any == nil { - fmt.Println("Panic2") return nil, sdkerrors.Wrap(ErrUnpackAny, "protobuf Any message cannot be nil") } ism, ok := any.GetCachedValue().(AbstractIsm) if !ok { - fmt.Println("Panic3") return nil, sdkerrors.Wrapf(ErrUnpackAny, "cannot unpack Any into Ism %T", any) } @@ -65,7 +62,6 @@ func UnpackAbstractIsm(any *codectypes.Any) (AbstractIsm, error) { func MustUnpackAbstractIsm(any *codectypes.Any) AbstractIsm { ism, err := UnpackAbstractIsm(any) if err != nil { - fmt.Println("Panic1") panic(err) } return ism diff --git a/x/ism/types/events.go b/x/ism/types/events.go index 3012cf5..88ed401 100644 --- a/x/ism/types/events.go +++ b/x/ism/types/events.go @@ -8,8 +8,8 @@ const ( // Hyperlane ISM attribute keys const ( - AttributeKeyOrigin = "origin" - AttributeKeyIndex = "index" - AttributeKeyThreshold = "threshold" - AttributeKeyValidator = "validator" + AttributeKeyOrigin = "origin" + AttributeKeyIndex = "index" + AttributeKeyThreshold = "threshold" + AttributeKeyValidator = "validator" ) diff --git a/x/ism/types/legacy_multisig/codec.go b/x/ism/types/legacy_multisig/codec.go index 5644298..02e4b4b 100644 --- a/x/ism/types/legacy_multisig/codec.go +++ b/x/ism/types/legacy_multisig/codec.go @@ -6,7 +6,7 @@ import ( "github.com/strangelove-ventures/hyperlane-cosmos/x/ism/types" ) -// RegisterInterfaces registers the hyperlane mailbox +// RegisterInterfaces registers the LegacyMultiSig // implementations and interfaces. func RegisterInterfaces(registry codectypes.InterfaceRegistry) { registry.RegisterImplementations( diff --git a/x/ism/types/legacy_multisig/legacy_multisig.go b/x/ism/types/legacy_multisig/legacy_multisig.go index 959b147..c69129c 100644 --- a/x/ism/types/legacy_multisig/legacy_multisig.go +++ b/x/ism/types/legacy_multisig/legacy_multisig.go @@ -92,7 +92,6 @@ func (i *LegacyMultiSig) VerifyValidatorSignatures(metadata []byte, message []by if err != nil { return false } - // fmt.Println("Signer: ", hex.EncodeToString(signer)) signerAddress := crypto.PubkeyToAddress(*signer) // Loop through remaining validators until we find a match for validatorIndex < validatorCount { diff --git a/x/ism/types/merkle_root_multisig/merkle_root_multisig.go b/x/ism/types/merkle_root_multisig/merkle_root_multisig.go index e15388c..9284110 100644 --- a/x/ism/types/merkle_root_multisig/merkle_root_multisig.go +++ b/x/ism/types/merkle_root_multisig/merkle_root_multisig.go @@ -103,7 +103,6 @@ func (i *MerkleRootMultiSig) VerifyValidatorSignatures(metadata []byte, message if err != nil { return false } - // fmt.Println("Signer: ", hex.EncodeToString(signer)) signerAddress := crypto.PubkeyToAddress(*signer) // Loop through remaining validators until we find a match for validatorIndex < validatorCount { diff --git a/x/ism/types/message_id_multisig/message_id_mulitsig.go b/x/ism/types/message_id_multisig/message_id_mulitsig.go index ea03b0d..34e9867 100644 --- a/x/ism/types/message_id_multisig/message_id_mulitsig.go +++ b/x/ism/types/message_id_multisig/message_id_mulitsig.go @@ -89,7 +89,6 @@ func (i *MessageIdMultiSig) VerifyValidatorSignatures(metadata []byte, message [ if err != nil { return false } - // fmt.Println("Signer: ", hex.EncodeToString(signer)) signerAddress := crypto.PubkeyToAddress(*signer) // Loop through remaining validators until we find a match for validatorIndex < validatorCount { diff --git a/x/ism/types/msgs.go b/x/ism/types/msgs.go index c372a93..9538ff1 100644 --- a/x/ism/types/msgs.go +++ b/x/ism/types/msgs.go @@ -58,7 +58,6 @@ func (m MsgSetDefaultIsm) UnpackInterfaces(unpacker codectypes.AnyUnpacker) erro return nil } - var ( _ sdk.Msg = (*MsgCreateIsm)(nil) _ codectypes.UnpackInterfacesMessage = (*MsgCreateIsm)(nil) @@ -68,7 +67,7 @@ var ( func NewMsgCreateIsm(signer string, ism *codectypes.Any) *MsgCreateIsm { return &MsgCreateIsm{ Signer: signer, - Ism: ism, + Ism: ism, } } @@ -101,11 +100,10 @@ func (m MsgCreateIsm) GetSigners() []sdk.AccAddress { func (m MsgCreateIsm) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { var ism AbstractIsm - + err := unpacker.UnpackAny(m.Ism, &ism) if err != nil { return err } return nil } - diff --git a/x/ism/types/query.go b/x/ism/types/query.go index 31205c9..a7c744f 100644 --- a/x/ism/types/query.go +++ b/x/ism/types/query.go @@ -53,4 +53,4 @@ func (r QueryAllCustomIsmsResponse) UnpackInterfaces(unpacker codectypes.AnyUnpa } } return nil -} \ No newline at end of file +} diff --git a/x/mailbox/client/cli/cli.go b/x/mailbox/client/cli/cli.go index d831371..c8ed5a0 100644 --- a/x/mailbox/client/cli/cli.go +++ b/x/mailbox/client/cli/cli.go @@ -22,6 +22,7 @@ func GetQueryCmd() *cobra.Command { getCurrentTreeCmd(), getDomainCmd(), getMsgDeliveredCmd(), + getRecipientsIsmIdCmd(), ) return queryCmd diff --git a/x/mailbox/client/cli/query.go b/x/mailbox/client/cli/query.go index 2d4a55d..9b5244e 100644 --- a/x/mailbox/client/cli/query.go +++ b/x/mailbox/client/cli/query.go @@ -6,6 +6,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/version" "github.com/ethereum/go-ethereum/common/hexutil" "github.com/spf13/cobra" @@ -143,3 +144,41 @@ func getMsgDeliveredCmd() *cobra.Command { return cmd } + +// getRecipientsIsmIdCmd defines the command to query a recipient's ISM ID +func getRecipientsIsmIdCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: "recipients-ism-id [bech32 address]", + Short: "Query recipients ISM ID", + Long: "Query recipients ISM ID", + Example: fmt.Sprintf("%s query %s recipients-ism-id [bech32 address]", version.AppName, types.ModuleName), + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.GetClientQueryContext(cmd) + if err != nil { + return err + } + queryClient := types.NewQueryClient(clientCtx) + + recipientBz, err := sdk.AccAddressFromBech32(args[0]) + if err != nil { + return err + } + + req := types.QueryRecipientsIsmIdRequest{ + Recipient: recipientBz, + } + + res, err := queryClient.RecipientsIsmId(context.Background(), &req) + if err != nil { + return err + } + + return clientCtx.PrintProto(res) + }, + } + + flags.AddQueryFlagsToCmd(cmd) + + return cmd +} diff --git a/x/mailbox/keeper/grpc_query.go b/x/mailbox/keeper/grpc_query.go index f19e8d7..ea212b5 100644 --- a/x/mailbox/keeper/grpc_query.go +++ b/x/mailbox/keeper/grpc_query.go @@ -77,3 +77,22 @@ func (k Keeper) MsgDelivered(c context.Context, req *types.QueryMsgDeliveredRequ Delivered: delivered, }, nil } + +// RecipientsIsmId implements to Query/RecipientsIsmId gRPC method +func (k Keeper) RecipientsIsmId(c context.Context, req *types.QueryRecipientsIsmIdRequest) (*types.QueryRecipientsIsmIdResponse, error) { + if req == nil { + return nil, status.Error(codes.InvalidArgument, "empty request") + } + + ctx := sdk.UnwrapSDKContext(c) + + recipient := sdk.MustBech32ifyAddressBytes(sdk.GetConfig().GetBech32AccountAddrPrefix(), req.Recipient) + ismId, err := k.getReceiversIsm(ctx, recipient) + if err != nil { + return nil, err + } + + return &types.QueryRecipientsIsmIdResponse{ + IsmId: ismId, + }, nil +} \ No newline at end of file diff --git a/x/mailbox/keeper/keeper.go b/x/mailbox/keeper/keeper.go index db78c7f..abed8e5 100644 --- a/x/mailbox/keeper/keeper.go +++ b/x/mailbox/keeper/keeper.go @@ -16,6 +16,7 @@ import ( "github.com/strangelove-ventures/hyperlane-cosmos/imt" common "github.com/strangelove-ventures/hyperlane-cosmos/x/common" ismkeeper "github.com/strangelove-ventures/hyperlane-cosmos/x/ism/keeper" + "github.com/strangelove-ventures/hyperlane-cosmos/x/mailbox/receiver" "github.com/strangelove-ventures/hyperlane-cosmos/x/mailbox/types" ) @@ -33,6 +34,8 @@ type Keeper struct { authority string mailboxAddr sdk.AccAddress version byte + + receivers []receiver.Receiver } type ReadOnlyMailboxKeeper interface { @@ -50,22 +53,31 @@ func (k Keeper) GetMailboxAddress() []byte { return mailboxAddr } -func NewKeeper(cdc codec.BinaryCodec, key storetypes.StoreKey, cwKeeper *cosmwasm.Keeper, ismKeeper *ismkeeper.Keeper) Keeper { +func NewKeeper(cdc codec.BinaryCodec, key storetypes.StoreKey, ismKeeper *ismkeeper.Keeper) Keeper { // governance authority authority := authtypes.NewModuleAddress(govtypes.ModuleName) return Keeper{ cdc: cdc, storeKey: key, - cwKeeper: cwKeeper, ismKeeper: ismKeeper, authority: authority.String(), mailboxAddr: authtypes.NewModuleAddress(types.ModuleName), version: 0, - pcwKeeper: cosmwasm.NewDefaultPermissionKeeper(cwKeeper), + pcwKeeper: nil, + receivers: []receiver.Receiver{}, } } +func (k *Keeper) AddReceiver(receiver *receiver.Receiver) { + k.receivers = append(k.receivers, *receiver) +} + +func (k *Keeper) AddWasmReceiver(cwKeeper *cosmwasm.Keeper) { + k.cwKeeper = cwKeeper + k.pcwKeeper = cosmwasm.NewDefaultPermissionKeeper(cwKeeper) +} + func (k *Keeper) SetDomain(c context.Context, domain uint32) { ctx := sdk.UnwrapSDKContext(c) store := ctx.KVStore(k.storeKey) diff --git a/x/mailbox/keeper/keeper_test.go b/x/mailbox/keeper/keeper_test.go index 39aa4d1..ef0767d 100644 --- a/x/mailbox/keeper/keeper_test.go +++ b/x/mailbox/keeper/keeper_test.go @@ -44,7 +44,6 @@ func (suite *KeeperTestSuite) SetupTest() { encCfg.Codec, key, nil, - nil, ) suite.keeper.SetDomain(ctx, testOriginDomain) diff --git a/x/mailbox/keeper/msg_server.go b/x/mailbox/keeper/msg_server.go index 6d39b05..209a1b7 100644 --- a/x/mailbox/keeper/msg_server.go +++ b/x/mailbox/keeper/msg_server.go @@ -3,12 +3,10 @@ package keeper import ( "context" "encoding/binary" - "encoding/json" "fmt" "strconv" sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/ethereum/go-ethereum/common/hexutil" @@ -20,23 +18,11 @@ var _ types.MsgServer = (*Keeper)(nil) const MAX_MESSAGE_BODY_BYTES = 2_000 -type ContractMsg struct { - ContractProcessMsg ContractProcessMsg `json:"process_msg,omitempty"` -} - -type ContractProcessMsg struct { - Origin uint32 `json:"origin"` - Sender string `json:"sender"` - Msg string `json:"msg"` -} - // NewMsgServerImpl return an implementation of the mailbox MsgServer interface for the provided keeper func NewMsgServerImpl(keeper Keeper) types.MsgServer { return keeper } -// func (k Keeper) CreateIsm(goCtx context.Context, msg *types.) - // Dispatch defines a rpc handler method for MsgDispatch func (k Keeper) Dispatch(goCtx context.Context, msg *types.MsgDispatch) (*types.MsgDispatchResponse, error) { tree := k.GetImtTree(goCtx) @@ -149,8 +135,18 @@ func (k Keeper) Process(goCtx context.Context, msg *types.MsgProcess) (*types.Ms metadataBytes := hexutil.MustDecode(msg.Metadata) + // Parse the recipient and get the contract address + recipientBytes := common.Recipient(messageBytes) + recipient := sdk.MustBech32ifyAddressBytes(sdk.GetConfig().GetBech32AccountAddrPrefix(), recipientBytes) + + // Get receiver's ISM ID + ismId, err := k.getReceiversIsm(ctx, recipient) + if err != nil { + return nil, err + } + // Verify message signatures - verified, err := k.ismKeeper.Verify(goCtx, metadataBytes, messageBytes) + verified, err := k.ismKeeper.Verify(goCtx, metadataBytes, messageBytes, ismId) if err != nil { return nil, err } @@ -161,35 +157,14 @@ func (k Keeper) Process(goCtx context.Context, msg *types.MsgProcess) (*types.Ms } fmt.Println("ISM verify succeeded") // TODO: remove, debug only - // Parse the recipient and get the contract address - recipientBytes := common.Recipient(messageBytes) - recipient := sdk.MustBech32ifyAddressBytes(sdk.GetConfig().GetBech32AccountAddrPrefix(), recipientBytes) - contractAddr, err := sdk.AccAddressFromBech32(recipient) - if err != nil { - return nil, sdkerrors.Wrap(err, "contract") - } - // Parse origin, sender, and body for the contract msg origin := common.Origin(messageBytes) senderBytes := common.Sender(messageBytes) senderHex := hexutil.Encode(senderBytes) body := common.Body(messageBytes) - contractMsg := ContractMsg{ - ContractProcessMsg: ContractProcessMsg{ - Origin: origin, - Sender: senderHex, - Msg: string(body), - }, - } - encodedMsg, err := json.Marshal(contractMsg) - if err != nil { - return nil, err - } - // Call the recipient contract - _, err = k.pcwKeeper.Execute(ctx, contractAddr, k.mailboxAddr, encodedMsg, sdk.NewCoins()) + err = k.processMsg(ctx, recipient, origin, senderHex, string(body)) if err != nil { - fmt.Println("Contract err: ", err) // TODO: remove, debug only return nil, err } diff --git a/x/mailbox/keeper/msg_server_test.go b/x/mailbox/keeper/msg_server_test.go index 903583e..12bdb93 100644 --- a/x/mailbox/keeper/msg_server_test.go +++ b/x/mailbox/keeper/msg_server_test.go @@ -2,7 +2,6 @@ package keeper_test import ( "encoding/binary" - "fmt" "strconv" sdk "github.com/cosmos/cosmos-sdk/types" @@ -175,8 +174,6 @@ func (suite *KeeperTestSuite) TestDispatch() { suite.Require().NoError(err) suite.Require().NotNil(res) - fmt.Println("ID: ", res.MessageId) - // zero-pad the sender w/ appropriate hyperlane byte length senderB, _ := hexutil.Decode(senderHex) for len(senderB) < (common.DESTINATION_OFFSET - common.SENDER_OFFSET) { diff --git a/x/mailbox/keeper/receivers.go b/x/mailbox/keeper/receivers.go new file mode 100644 index 0000000..745383a --- /dev/null +++ b/x/mailbox/keeper/receivers.go @@ -0,0 +1,109 @@ +package keeper + +import ( + "encoding/json" + + sdk "github.com/cosmos/cosmos-sdk/types" + errorsmod "cosmossdk.io/errors" + + "github.com/strangelove-ventures/hyperlane-cosmos/x/mailbox/types" +) + +type QueryMsg struct { + QueryIsmMsg *QueryIsmMsg `json:"ism,omitempty"` +} + +type QueryIsmMsg struct{} + +type QueryIsmResponse struct { + IsmId uint32 `json:"ism_id,omitempty"` +} + +type ContractMsg struct { + ContractProcessMsg ContractProcessMsg `json:"process_msg,omitempty"` +} + +type ContractProcessMsg struct { + Origin uint32 `json:"origin"` + Sender string `json:"sender"` + Msg string `json:"msg"` +} + +func (k Keeper) getReceiversIsm(ctx sdk.Context, recipient string) (uint32, error) { + // Iterate through all receivers + for _, receiver := range k.receivers { + // If recipient matches the receiver address, query its ISM + if recipient == receiver.Address() { + return receiver.QueryIsm(), nil + } + } + + // If x/wasm is supported and no receivers match the recipient, query the contract + if k.cwKeeper != nil { + recipientBz, err := sdk.AccAddressFromBech32(recipient) + if err != nil { + return 0, err + } + + req := QueryMsg{QueryIsmMsg: &QueryIsmMsg{}} + reqBz, err := json.Marshal(req) + if err != nil { + return 0, err + } + resp, err := k.cwKeeper.QuerySmart(ctx, recipientBz, reqBz) + if err != nil { + return 0, err + } + + var ismResp QueryIsmResponse + err = json.Unmarshal(resp, &ismResp) + if err != nil { + return 0, err + } + + return ismResp.IsmId, nil + } + + return 0, types.ErrInvalidRecipient +} + +func (k Keeper) processMsg(ctx sdk.Context, recipient string, origin uint32, sender string, msg string) error { + // Iterate through all receivers + for _, receiver := range k.receivers { + // If recipient matches the receiver address, process the message + if recipient == receiver.Address() { + err := receiver.Process(origin, sender, msg) + return err + } + } + + // If x/wasm is supported and no receivers match the recipient, call the contract's process + if k.cwKeeper != nil { + contractMsg := ContractMsg{ + ContractProcessMsg: ContractProcessMsg{ + Origin: origin, + Sender: sender, + Msg: msg, + }, + } + encodedMsg, err := json.Marshal(contractMsg) + if err != nil { + return err + } + + receiverAddr, err := sdk.AccAddressFromBech32(recipient) + if err != nil { + return errorsmod.Wrap(err, "invalid bech32 recipient") + } + + // Call the recipient contract + _, err = k.pcwKeeper.Execute(ctx, receiverAddr, k.mailboxAddr, encodedMsg, sdk.NewCoins()) + if err != nil { + return err + } + + return nil + } + + return types.ErrInvalidRecipient +} diff --git a/x/mailbox/receiver/receiver.go b/x/mailbox/receiver/receiver.go new file mode 100644 index 0000000..b88ff88 --- /dev/null +++ b/x/mailbox/receiver/receiver.go @@ -0,0 +1,10 @@ +package receiver + +type Receiver interface { + // Address() returns the bech32 address of module + Address() string + // QueryIsm returns a custom ism id or 0 for default + QueryIsm() uint32 + // Process() will process the message, sender is in hex + Process(origin uint32, sender, msg string) error +} diff --git a/x/mailbox/types/errors.go b/x/mailbox/types/errors.go index 307f185..f759258 100644 --- a/x/mailbox/types/errors.go +++ b/x/mailbox/types/errors.go @@ -17,4 +17,5 @@ var ( ErrMsgProcessInvalidSender = sdkerrors.Register(ModuleName, 12, "invalid sender in msg process") ErrMsgProcessInvalidMetadata = sdkerrors.Register(ModuleName, 13, "invalid metadata in msg process") ErrMsgProcessInvalidMessage = sdkerrors.Register(ModuleName, 14, "invalid message in msg process") + ErrInvalidRecipient = sdkerrors.Register(ModuleName, 15, "invalid recipient") ) diff --git a/x/mailbox/types/query.pb.go b/x/mailbox/types/query.pb.go index 38a5957..b181319 100644 --- a/x/mailbox/types/query.pb.go +++ b/x/mailbox/types/query.pb.go @@ -424,6 +424,106 @@ func (m *QueryMsgDeliveredResponse) GetDelivered() bool { return false } +// QueryRecipientsIsmIdRequest is the request type to get the ISM ID +type QueryRecipientsIsmIdRequest struct { + Recipient []byte `protobuf:"bytes,1,opt,name=recipient,proto3" json:"recipient,omitempty"` +} + +func (m *QueryRecipientsIsmIdRequest) Reset() { *m = QueryRecipientsIsmIdRequest{} } +func (m *QueryRecipientsIsmIdRequest) String() string { return proto.CompactTextString(m) } +func (*QueryRecipientsIsmIdRequest) ProtoMessage() {} +func (*QueryRecipientsIsmIdRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_567dd9a34f8715cd, []int{8} +} + +func (m *QueryRecipientsIsmIdRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} + +func (m *QueryRecipientsIsmIdRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryRecipientsIsmIdRequest.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} + +func (m *QueryRecipientsIsmIdRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryRecipientsIsmIdRequest.Merge(m, src) +} + +func (m *QueryRecipientsIsmIdRequest) XXX_Size() int { + return m.Size() +} + +func (m *QueryRecipientsIsmIdRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryRecipientsIsmIdRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryRecipientsIsmIdRequest proto.InternalMessageInfo + +func (m *QueryRecipientsIsmIdRequest) GetRecipient() []byte { + if m != nil { + return m.Recipient + } + return nil +} + +// QueryRecipientsIsmIdResponse is the response type containing the ISM ID +type QueryRecipientsIsmIdResponse struct { + IsmId uint32 `protobuf:"varint,1,opt,name=ism_id,json=ismId,proto3" json:"ism_id,omitempty"` +} + +func (m *QueryRecipientsIsmIdResponse) Reset() { *m = QueryRecipientsIsmIdResponse{} } +func (m *QueryRecipientsIsmIdResponse) String() string { return proto.CompactTextString(m) } +func (*QueryRecipientsIsmIdResponse) ProtoMessage() {} +func (*QueryRecipientsIsmIdResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_567dd9a34f8715cd, []int{9} +} + +func (m *QueryRecipientsIsmIdResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} + +func (m *QueryRecipientsIsmIdResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryRecipientsIsmIdResponse.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} + +func (m *QueryRecipientsIsmIdResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryRecipientsIsmIdResponse.Merge(m, src) +} + +func (m *QueryRecipientsIsmIdResponse) XXX_Size() int { + return m.Size() +} + +func (m *QueryRecipientsIsmIdResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryRecipientsIsmIdResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryRecipientsIsmIdResponse proto.InternalMessageInfo + +func (m *QueryRecipientsIsmIdResponse) GetIsmId() uint32 { + if m != nil { + return m.IsmId + } + return 0 +} + func init() { proto.RegisterType((*QueryCurrentTreeMetadataRequest)(nil), "hyperlane.mailbox.v1.QueryCurrentTreeMetadataRequest") proto.RegisterType((*QueryCurrentTreeMetadataResponse)(nil), "hyperlane.mailbox.v1.QueryCurrentTreeMetadataResponse") @@ -433,44 +533,51 @@ func init() { proto.RegisterType((*QueryDomainResponse)(nil), "hyperlane.mailbox.v1.QueryDomainResponse") proto.RegisterType((*QueryMsgDeliveredRequest)(nil), "hyperlane.mailbox.v1.QueryMsgDeliveredRequest") proto.RegisterType((*QueryMsgDeliveredResponse)(nil), "hyperlane.mailbox.v1.QueryMsgDeliveredResponse") + proto.RegisterType((*QueryRecipientsIsmIdRequest)(nil), "hyperlane.mailbox.v1.QueryRecipientsIsmIdRequest") + proto.RegisterType((*QueryRecipientsIsmIdResponse)(nil), "hyperlane.mailbox.v1.QueryRecipientsIsmIdResponse") } func init() { proto.RegisterFile("hyperlane/mailbox/v1/query.proto", fileDescriptor_567dd9a34f8715cd) } var fileDescriptor_567dd9a34f8715cd = []byte{ - // 504 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x54, 0xbf, 0x6e, 0xd3, 0x40, - 0x18, 0xcf, 0x95, 0x36, 0x6a, 0x8f, 0x74, 0xb9, 0x46, 0x90, 0x5a, 0xc1, 0x75, 0x0d, 0x88, 0x20, - 0x14, 0x5b, 0x05, 0x81, 0xd4, 0x0d, 0x41, 0x17, 0x24, 0x3a, 0x60, 0x31, 0x75, 0xa9, 0x2e, 0xf1, - 0x27, 0xc7, 0x92, 0x7d, 0xe7, 0xde, 0x9d, 0xad, 0x66, 0x85, 0x17, 0xa8, 0xc4, 0xc2, 0x6b, 0xf0, - 0x16, 0x8c, 0x95, 0x58, 0x18, 0x51, 0xc2, 0xce, 0x2b, 0x20, 0xce, 0xe7, 0xa4, 0x05, 0x27, 0xa4, - 0x5b, 0xee, 0xcb, 0xef, 0xdf, 0xf7, 0x47, 0xc6, 0xce, 0x68, 0x9c, 0x81, 0x48, 0x28, 0x03, 0x3f, - 0xa5, 0x71, 0x32, 0xe0, 0xe7, 0x7e, 0x71, 0xe0, 0x9f, 0xe5, 0x20, 0xc6, 0x5e, 0x26, 0xb8, 0xe2, - 0xa4, 0x3d, 0x43, 0x78, 0x06, 0xe1, 0x15, 0x07, 0x56, 0x37, 0xe2, 0x3c, 0x4a, 0xc0, 0xa7, 0x59, - 0xec, 0x53, 0xc6, 0xb8, 0xa2, 0x2a, 0xe6, 0x4c, 0x96, 0x1c, 0x77, 0x1f, 0xef, 0xbd, 0xfb, 0x23, - 0xf1, 0x3a, 0x17, 0x02, 0x98, 0x7a, 0x2f, 0x00, 0x8e, 0x41, 0xd1, 0x90, 0x2a, 0x1a, 0xc0, 0x59, - 0x0e, 0x52, 0xb9, 0x6f, 0xb1, 0xb3, 0x18, 0x22, 0x33, 0xce, 0x24, 0x10, 0x82, 0xd7, 0x05, 0xe7, - 0xaa, 0x83, 0x1c, 0xd4, 0x6b, 0x05, 0xfa, 0x37, 0x69, 0xe3, 0x8d, 0x21, 0xcf, 0x99, 0xea, 0xac, - 0x39, 0xa8, 0xb7, 0x1d, 0x94, 0x0f, 0x77, 0x17, 0xdf, 0xfd, 0x5b, 0x6d, 0x6e, 0xd4, 0xf9, 0xf7, - 0x2f, 0x63, 0x60, 0xe1, 0xcd, 0x81, 0xa0, 0x6c, 0x38, 0x02, 0xd9, 0x41, 0xce, 0xad, 0x5e, 0x2b, - 0x98, 0xbd, 0x17, 0x18, 0xb5, 0x31, 0xd1, 0x6a, 0x47, 0x3c, 0xa5, 0x31, 0xab, 0x3c, 0xfa, 0x78, - 0xe7, 0x5a, 0xd5, 0xc8, 0xdf, 0xc1, 0xcd, 0x50, 0x57, 0x74, 0x07, 0xdb, 0x81, 0x79, 0xb9, 0x87, - 0x26, 0xd2, 0xb1, 0x8c, 0x8e, 0x20, 0x89, 0x0b, 0x10, 0x10, 0x1a, 0x29, 0x72, 0x0f, 0xe3, 0x14, - 0xa4, 0xa4, 0x11, 0x9c, 0xc6, 0xa1, 0xe9, 0x7c, 0xcb, 0x54, 0xde, 0x84, 0xee, 0x21, 0xde, 0xad, - 0xa1, 0x1a, 0xbf, 0x2e, 0xde, 0x0a, 0xab, 0xa2, 0xa6, 0x6e, 0x06, 0xf3, 0xc2, 0xd3, 0x5f, 0xeb, - 0x78, 0x43, 0x73, 0xc9, 0x17, 0x84, 0x77, 0x6a, 0xe6, 0x4e, 0x9e, 0x7b, 0x75, 0xbb, 0xf6, 0xfe, - 0xb3, 0x4a, 0xeb, 0xc5, 0x4d, 0x69, 0x65, 0x5c, 0xf7, 0xc9, 0x87, 0x6f, 0x3f, 0x3f, 0xad, 0x3d, - 0x24, 0xf7, 0xfd, 0xda, 0x23, 0x54, 0x02, 0xe0, 0x34, 0xad, 0xb2, 0x7d, 0x44, 0xb8, 0x59, 0x8e, - 0x97, 0xf4, 0x96, 0xf8, 0x5d, 0xdb, 0x8b, 0xf5, 0x78, 0x05, 0xa4, 0x09, 0xf3, 0x40, 0x87, 0xb1, - 0x49, 0xb7, 0x3e, 0x4c, 0xb9, 0x39, 0x72, 0x81, 0xf0, 0xed, 0x2b, 0x2d, 0x91, 0xfe, 0x6a, 0xad, - 0x57, 0x79, 0xbc, 0x55, 0xe1, 0x26, 0x94, 0xab, 0x43, 0x75, 0x89, 0xb5, 0x78, 0x42, 0xe4, 0x33, - 0xc2, 0xad, 0xab, 0xd7, 0x40, 0x96, 0x99, 0xd4, 0x5c, 0x9c, 0xe5, 0xaf, 0x8c, 0x37, 0xa9, 0x1e, - 0xe9, 0x54, 0xfb, 0x64, 0x6f, 0xc1, 0xa8, 0x2a, 0xc2, 0xab, 0x93, 0xaf, 0x13, 0x1b, 0x5d, 0x4e, - 0x6c, 0xf4, 0x63, 0x62, 0xa3, 0x8b, 0xa9, 0xdd, 0xb8, 0x9c, 0xda, 0x8d, 0xef, 0x53, 0xbb, 0x71, - 0xf2, 0x32, 0x8a, 0xd5, 0x28, 0x1f, 0x78, 0x43, 0x9e, 0xfa, 0x52, 0x09, 0xca, 0x22, 0x48, 0x78, - 0x01, 0xfd, 0x02, 0x98, 0xca, 0x05, 0xc8, 0xb9, 0x72, 0x7f, 0xc8, 0x65, 0xca, 0xa5, 0x7f, 0x3e, - 0xb3, 0x50, 0xe3, 0x0c, 0xe4, 0xa0, 0xa9, 0xbf, 0x34, 0xcf, 0x7e, 0x07, 0x00, 0x00, 0xff, 0xff, - 0xdf, 0x4e, 0x60, 0xd4, 0xc1, 0x04, 0x00, 0x00, + // 589 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x94, 0x4f, 0x4f, 0xd4, 0x4e, + 0x18, 0xc7, 0x19, 0x7e, 0x3f, 0x36, 0xf0, 0x08, 0x31, 0x19, 0x50, 0x97, 0xba, 0x96, 0xa5, 0x6a, + 0x58, 0x62, 0xb6, 0x0d, 0x18, 0x4c, 0x88, 0x17, 0xa3, 0x5c, 0x48, 0xe4, 0x60, 0xe3, 0x89, 0x0b, + 0x99, 0xdd, 0x3e, 0x29, 0x4d, 0xb6, 0x33, 0x65, 0x66, 0xba, 0x81, 0xab, 0xbe, 0x01, 0x12, 0x2f, + 0x26, 0xbe, 0x02, 0x8f, 0xbe, 0x0b, 0x8f, 0x24, 0x5e, 0x3c, 0x1a, 0xf0, 0x85, 0x18, 0xa6, 0xd3, + 0xf2, 0xc7, 0x2e, 0x2e, 0xb7, 0x9d, 0x67, 0x9e, 0xef, 0xf3, 0xfd, 0x4c, 0xe7, 0x3b, 0x0b, 0xed, + 0xfd, 0xa3, 0x0c, 0xe5, 0x80, 0x71, 0x0c, 0x52, 0x96, 0x0c, 0x7a, 0xe2, 0x30, 0x18, 0xae, 0x05, + 0x07, 0x39, 0xca, 0x23, 0x3f, 0x93, 0x42, 0x0b, 0xba, 0x50, 0x75, 0xf8, 0xb6, 0xc3, 0x1f, 0xae, + 0x39, 0xad, 0x58, 0x88, 0x78, 0x80, 0x01, 0xcb, 0x92, 0x80, 0x71, 0x2e, 0x34, 0xd3, 0x89, 0xe0, + 0xaa, 0xd0, 0x78, 0xcb, 0xb0, 0xf4, 0xee, 0x7c, 0xc4, 0x9b, 0x5c, 0x4a, 0xe4, 0xfa, 0xbd, 0x44, + 0xdc, 0x41, 0xcd, 0x22, 0xa6, 0x59, 0x88, 0x07, 0x39, 0x2a, 0xed, 0xbd, 0x85, 0xf6, 0xe8, 0x16, + 0x95, 0x09, 0xae, 0x90, 0x52, 0xf8, 0x5f, 0x0a, 0xa1, 0x9b, 0xa4, 0x4d, 0x3a, 0xb3, 0xa1, 0xf9, + 0x4d, 0x17, 0x60, 0xaa, 0x2f, 0x72, 0xae, 0x9b, 0x93, 0x6d, 0xd2, 0x99, 0x0b, 0x8b, 0x85, 0xb7, + 0x08, 0x0f, 0xae, 0x4f, 0xbb, 0x30, 0x6a, 0xfe, 0xbd, 0x65, 0x0d, 0x1c, 0x98, 0xee, 0x49, 0xc6, + 0xfb, 0xfb, 0xa8, 0x9a, 0xa4, 0xfd, 0x5f, 0x67, 0x36, 0xac, 0xd6, 0x23, 0x8c, 0x16, 0x80, 0x9a, + 0x69, 0x5b, 0x22, 0x65, 0x09, 0x2f, 0x3d, 0xba, 0x30, 0x7f, 0xa5, 0x6a, 0xc7, 0xdf, 0x87, 0x46, + 0x64, 0x2a, 0xe6, 0x04, 0x73, 0xa1, 0x5d, 0x79, 0x9b, 0x16, 0x69, 0x47, 0xc5, 0x5b, 0x38, 0x48, + 0x86, 0x28, 0x31, 0xb2, 0xa3, 0xe8, 0x23, 0x80, 0x14, 0x95, 0x62, 0x31, 0xee, 0x25, 0x91, 0x3d, + 0xf9, 0x8c, 0xad, 0x6c, 0x47, 0xde, 0x26, 0x2c, 0xd6, 0x48, 0xad, 0x5f, 0x0b, 0x66, 0xa2, 0xb2, + 0x68, 0xa4, 0xd3, 0xe1, 0x45, 0xc1, 0x7b, 0x09, 0x0f, 0x8d, 0x34, 0xc4, 0x7e, 0x92, 0x25, 0xc8, + 0xb5, 0xda, 0x56, 0xe9, 0x76, 0x65, 0xdc, 0x82, 0x19, 0x59, 0xee, 0x94, 0xbe, 0x55, 0xc1, 0xdb, + 0x80, 0x56, 0xbd, 0xd8, 0x5a, 0xdf, 0x83, 0x46, 0xa2, 0xd2, 0x12, 0x79, 0x2e, 0x9c, 0x4a, 0xce, + 0xb7, 0xd7, 0xbf, 0x34, 0x60, 0xca, 0xe8, 0xe8, 0x37, 0x02, 0xf3, 0x35, 0x77, 0x4d, 0x37, 0xfc, + 0xba, 0x7c, 0xf9, 0xff, 0x88, 0x8f, 0xf3, 0xe2, 0xb6, 0xb2, 0x82, 0xd3, 0x7b, 0xf6, 0xe1, 0xc7, + 0xef, 0x4f, 0x93, 0x4f, 0xe9, 0xe3, 0xa0, 0x36, 0xf8, 0x5a, 0x22, 0xee, 0xa5, 0x25, 0xdb, 0x47, + 0x02, 0x8d, 0xe2, 0x4a, 0x69, 0xe7, 0x06, 0xbf, 0x2b, 0x59, 0x70, 0x56, 0xc7, 0xe8, 0xb4, 0x30, + 0x4f, 0x0c, 0x8c, 0x4b, 0x5b, 0xf5, 0x30, 0x45, 0x5a, 0xe8, 0x31, 0x81, 0x3b, 0x97, 0x8e, 0x44, + 0xbb, 0xe3, 0x1d, 0xbd, 0xe4, 0xf1, 0xc7, 0x6d, 0xb7, 0x50, 0x9e, 0x81, 0x6a, 0x51, 0x67, 0xf4, + 0x17, 0xa2, 0x9f, 0x09, 0xcc, 0x5e, 0x4e, 0x20, 0xbd, 0xc9, 0xa4, 0x26, 0xe5, 0x4e, 0x30, 0x76, + 0xbf, 0xa5, 0x5a, 0x31, 0x54, 0xcb, 0x74, 0x69, 0xc4, 0xa7, 0xaa, 0x48, 0xbe, 0x12, 0xb8, 0x7b, + 0x2d, 0xa4, 0x74, 0xed, 0x06, 0xb7, 0xfa, 0xd7, 0xe0, 0xac, 0xdf, 0x46, 0x62, 0x19, 0x03, 0xc3, + 0xb8, 0x4a, 0x57, 0xea, 0x19, 0xab, 0xc7, 0xa4, 0xf6, 0x8a, 0xa7, 0xf2, 0x7a, 0xf7, 0xfb, 0xa9, + 0x4b, 0x4e, 0x4e, 0x5d, 0xf2, 0xeb, 0xd4, 0x25, 0xc7, 0x67, 0xee, 0xc4, 0xc9, 0x99, 0x3b, 0xf1, + 0xf3, 0xcc, 0x9d, 0xd8, 0x7d, 0x15, 0x27, 0x7a, 0x3f, 0xef, 0xf9, 0x7d, 0x91, 0x06, 0x4a, 0x4b, + 0xc6, 0x63, 0x1c, 0x88, 0x21, 0x76, 0x87, 0xc8, 0x75, 0x2e, 0x51, 0x5d, 0x38, 0x74, 0xfb, 0x42, + 0xa5, 0x42, 0x05, 0x87, 0x95, 0x95, 0x3e, 0xca, 0x50, 0xf5, 0x1a, 0xe6, 0x9f, 0xf8, 0xf9, 0x9f, + 0x00, 0x00, 0x00, 0xff, 0xff, 0xa2, 0x1a, 0xdf, 0x2d, 0xe1, 0x05, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. @@ -495,6 +602,8 @@ type QueryClient interface { CurrentTree(ctx context.Context, in *QueryCurrentTreeRequest, opts ...grpc.CallOption) (*QueryCurrentTreeResponse, error) // Check if message was delivered MsgDelivered(ctx context.Context, in *QueryMsgDeliveredRequest, opts ...grpc.CallOption) (*QueryMsgDeliveredResponse, error) + // Query ISM ID from recipient + RecipientsIsmId(ctx context.Context, in *QueryRecipientsIsmIdRequest, opts ...grpc.CallOption) (*QueryRecipientsIsmIdResponse, error) } type queryClient struct { @@ -541,6 +650,15 @@ func (c *queryClient) MsgDelivered(ctx context.Context, in *QueryMsgDeliveredReq return out, nil } +func (c *queryClient) RecipientsIsmId(ctx context.Context, in *QueryRecipientsIsmIdRequest, opts ...grpc.CallOption) (*QueryRecipientsIsmIdResponse, error) { + out := new(QueryRecipientsIsmIdResponse) + err := c.cc.Invoke(ctx, "/hyperlane.mailbox.v1.Query/RecipientsIsmId", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + // QueryServer is the server API for Query service. type QueryServer interface { // Get current tree metadata @@ -551,6 +669,8 @@ type QueryServer interface { CurrentTree(context.Context, *QueryCurrentTreeRequest) (*QueryCurrentTreeResponse, error) // Check if message was delivered MsgDelivered(context.Context, *QueryMsgDeliveredRequest) (*QueryMsgDeliveredResponse, error) + // Query ISM ID from recipient + RecipientsIsmId(context.Context, *QueryRecipientsIsmIdRequest) (*QueryRecipientsIsmIdResponse, error) } // UnimplementedQueryServer can be embedded to have forward compatible implementations. @@ -572,6 +692,10 @@ func (*UnimplementedQueryServer) MsgDelivered(ctx context.Context, req *QueryMsg return nil, status.Errorf(codes.Unimplemented, "method MsgDelivered not implemented") } +func (*UnimplementedQueryServer) RecipientsIsmId(ctx context.Context, req *QueryRecipientsIsmIdRequest) (*QueryRecipientsIsmIdResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method RecipientsIsmId not implemented") +} + func RegisterQueryServer(s grpc1.Server, srv QueryServer) { s.RegisterService(&_Query_serviceDesc, srv) } @@ -648,6 +772,24 @@ func _Query_MsgDelivered_Handler(srv interface{}, ctx context.Context, dec func( return interceptor(ctx, in, info, handler) } +func _Query_RecipientsIsmId_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryRecipientsIsmIdRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).RecipientsIsmId(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/hyperlane.mailbox.v1.Query/RecipientsIsmId", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).RecipientsIsmId(ctx, req.(*QueryRecipientsIsmIdRequest)) + } + return interceptor(ctx, in, info, handler) +} + var _Query_serviceDesc = grpc.ServiceDesc{ ServiceName: "hyperlane.mailbox.v1.Query", HandlerType: (*QueryServer)(nil), @@ -668,6 +810,10 @@ var _Query_serviceDesc = grpc.ServiceDesc{ MethodName: "MsgDelivered", Handler: _Query_MsgDelivered_Handler, }, + { + MethodName: "RecipientsIsmId", + Handler: _Query_RecipientsIsmId_Handler, + }, }, Streams: []grpc.StreamDesc{}, Metadata: "hyperlane/mailbox/v1/query.proto", @@ -905,6 +1051,64 @@ func (m *QueryMsgDeliveredResponse) MarshalToSizedBuffer(dAtA []byte) (int, erro return len(dAtA) - i, nil } +func (m *QueryRecipientsIsmIdRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryRecipientsIsmIdRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryRecipientsIsmIdRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Recipient) > 0 { + i -= len(m.Recipient) + copy(dAtA[i:], m.Recipient) + i = encodeVarintQuery(dAtA, i, uint64(len(m.Recipient))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *QueryRecipientsIsmIdResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryRecipientsIsmIdResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryRecipientsIsmIdResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.IsmId != 0 { + i = encodeVarintQuery(dAtA, i, uint64(m.IsmId)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + func encodeVarintQuery(dAtA []byte, offset int, v uint64) int { offset -= sovQuery(v) base := offset @@ -1015,6 +1219,31 @@ func (m *QueryMsgDeliveredResponse) Size() (n int) { return n } +func (m *QueryRecipientsIsmIdRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Recipient) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func (m *QueryRecipientsIsmIdResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.IsmId != 0 { + n += 1 + sovQuery(uint64(m.IsmId)) + } + return n +} + func sovQuery(x uint64) (n int) { return (math_bits.Len64(x|1) + 6) / 7 } @@ -1608,6 +1837,161 @@ func (m *QueryMsgDeliveredResponse) Unmarshal(dAtA []byte) error { return nil } +func (m *QueryRecipientsIsmIdRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryRecipientsIsmIdRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryRecipientsIsmIdRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Recipient", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Recipient = append(m.Recipient[:0], dAtA[iNdEx:postIndex]...) + if m.Recipient == nil { + m.Recipient = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} + +func (m *QueryRecipientsIsmIdResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryRecipientsIsmIdResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryRecipientsIsmIdResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field IsmId", wireType) + } + m.IsmId = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.IsmId |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} + func skipQuery(dAtA []byte) (n int, err error) { l := len(dAtA) iNdEx := 0 diff --git a/x/mailbox/types/query.pb.gw.go b/x/mailbox/types/query.pb.gw.go index 638f248..dc7892f 100644 --- a/x/mailbox/types/query.pb.gw.go +++ b/x/mailbox/types/query.pb.gw.go @@ -115,6 +115,38 @@ func local_request_Query_MsgDelivered_0(ctx context.Context, marshaler runtime.M return msg, metadata, err } +var filter_Query_RecipientsIsmId_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} + +func request_Query_RecipientsIsmId_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryRecipientsIsmIdRequest + var metadata runtime.ServerMetadata + + if err := req.ParseForm(); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_RecipientsIsmId_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := client.RecipientsIsmId(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err +} + +func local_request_Query_RecipientsIsmId_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryRecipientsIsmIdRequest + var metadata runtime.ServerMetadata + + if err := req.ParseForm(); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_RecipientsIsmId_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := server.RecipientsIsmId(ctx, &protoReq) + return msg, metadata, err +} + // RegisterQueryHandlerServer registers the http handlers for service Query to "mux". // UnaryRPC :call QueryServer directly. // StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. @@ -208,6 +240,28 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv forward_Query_MsgDelivered_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) + mux.Handle("GET", pattern_Query_RecipientsIsmId_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_Query_RecipientsIsmId_0(rctx, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_RecipientsIsmId_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + }) + return nil } @@ -324,6 +378,25 @@ func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, clie forward_Query_MsgDelivered_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) + mux.Handle("GET", pattern_Query_RecipientsIsmId_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_Query_RecipientsIsmId_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_RecipientsIsmId_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + }) + return nil } @@ -335,6 +408,8 @@ var ( pattern_Query_CurrentTree_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"hyperlane", "mailbox", "v1", "tree"}, "", runtime.AssumeColonVerbOpt(false))) pattern_Query_MsgDelivered_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"hyperlane", "mailbox", "v1", "delivered"}, "", runtime.AssumeColonVerbOpt(false))) + + pattern_Query_RecipientsIsmId_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"hyperlane", "mailbox", "v1", "recipients_ism_id"}, "", runtime.AssumeColonVerbOpt(false))) ) var ( @@ -345,4 +420,6 @@ var ( forward_Query_CurrentTree_0 = runtime.ForwardResponseMessage forward_Query_MsgDelivered_0 = runtime.ForwardResponseMessage + + forward_Query_RecipientsIsmId_0 = runtime.ForwardResponseMessage )