Skip to content

Commit

Permalink
Merge pull request #1441 from scrtlabs/ibc-input-light-client-validation
Browse files Browse the repository at this point in the history
Light client input validation (IBC Hooks + IBC contracts)
  • Loading branch information
assafmo authored Jun 5, 2023
2 parents 7845ab8 + dbc86c7 commit 9825f57
Show file tree
Hide file tree
Showing 75 changed files with 12,675 additions and 677 deletions.
9 changes: 5 additions & 4 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,20 +13,20 @@
"integration-tests/contract-v1/Cargo.toml",
"integration-tests/contract-v0.10/Cargo.toml",
"go-cosmwasm/Cargo.toml",
"integration-tests/contract-v0.10/Cargo.toml",
"check-hw/Cargo.toml"
"cosmwasm/enclaves/shared/cosmos-proto/Cargo.toml",
"cosmwasm/enclaves/shared/contract-engine/Cargo.toml"
],
"rust-analyzer.diagnostics.experimental.enable": true,
"rust-analyzer.rustfmt.rangeFormatting.enable": true,
"rust-analyzer.diagnostics.disabled": [
"unresolved-macro-call",
"unresolved-proc-macro"
],
"rust-analyzer.cargo.features": "all",
"[rust]": {
"editor.formatOnSave": true,
"editor.defaultFormatter": "rust-lang.rust-analyzer"
},

"go.testEnvVars": {
"SGX_MODE": "SW",
"RUST_BACKTRACE": "1"
Expand All @@ -40,5 +40,6 @@
"[go]": {
"editor.formatOnSave": true,
"editor.defaultFormatter": "golang.go"
}
},
"rust-analyzer.showUnlinkedFileNotification": false
}
97 changes: 51 additions & 46 deletions app/keepers/keepers.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,9 @@ import (
ibchost "github.com/cosmos/ibc-go/v4/modules/core/24-host"
ibckeeper "github.com/cosmos/ibc-go/v4/modules/core/keeper"
"github.com/scrtlabs/SecretNetwork/x/compute"
icaauth "github.com/scrtlabs/SecretNetwork/x/mauth"
icaauthkeeper "github.com/scrtlabs/SecretNetwork/x/mauth/keeper"
icaauthtypes "github.com/scrtlabs/SecretNetwork/x/mauth/types"
icaauth "github.com/scrtlabs/SecretNetwork/x/mauth"
reg "github.com/scrtlabs/SecretNetwork/x/registration"
ibcpacketforward "github.com/strangelove-ventures/packet-forward-middleware/v4/router"
ibcpacketforwardkeeper "github.com/strangelove-ventures/packet-forward-middleware/v4/router/keeper"
Expand All @@ -67,7 +67,7 @@ import (
ibcswitch "github.com/scrtlabs/SecretNetwork/x/emergencybutton"
ibcswitchtypes "github.com/scrtlabs/SecretNetwork/x/emergencybutton/types"

ibchooks "github.com/scrtlabs/SecretNetwork/x/ibc-hooks"
ibchooks "github.com/scrtlabs/SecretNetwork/x/ibc-hooks"
ibchookskeeper "github.com/scrtlabs/SecretNetwork/x/ibc-hooks/keeper"
ibchookstypes "github.com/scrtlabs/SecretNetwork/x/ibc-hooks/types"
)
Expand Down Expand Up @@ -296,62 +296,65 @@ func (ak *SecretAppKeepers) InitCustomKeepers(
// That means that whenever a packet is being send via Fee as an ics4wrapper, it will go through the switch middleware first (ref: https://github.com/cosmos/ibc-go/blob/v4.3.0/modules/apps/29-fee/keeper/relay.go#L15-L18).
// Then we'll pass Fee as an ics4wrapper to everything else.
//
// Compute: WASM Hooks -> Fee -> Switch
// Transfer: Packet Forward -> Fee -> Switch
// Compute send: Switch -> Fee -> Packet Forward -> WASM Hooks
// Compute receive: Switch -> Fee -> Packet Forward -> WASM Hooks
//
// Transfer send: Switch -> Fee -> Packet Forward -> WASM Hooks (WASM Hooks isn't necessary here, but we'll add it for consistency)
// Transfer receive: Switch -> Fee -> Packet Forward -> WASM Hooks
//
// Note: we need to make sure that every underlying IBC app/middleware that we're adding uses the ics4wrapper to send packets, and not the IBC channel keeper.

// Initialize channel for stacks that can turn off
// todo: verify that I don't have to create a new middleware instance for every different stack
ibcSwitchKeeper := ibcswitch.NewKeeper(
ak.IbcKeeper.ChannelKeeper,
ak.GetSubspace(ibcswitch.ModuleName),
// Setup the ICS4Wrapper used by the hooks middleware
// Configure the hooks keeper
ibcHooksKeeper := ibchookskeeper.NewKeeper(
ak.keys[ibchookstypes.StoreKey],
)
ak.IbcSwitchKeeper = &ibcSwitchKeeper
ak.IbcHooksKeeper = &ibcHooksKeeper

ak.IbcFeeKeeper = ibcfeekeeper.NewKeeper(
appCodec,
ak.keys[ibcfeetypes.StoreKey],
ak.GetSubspace(ibcfeetypes.ModuleName), // this isn't even used in the keeper but is required?
ak.IbcSwitchKeeper,
wasmHooks := ibchooks.NewWasmHooks(
&ibcHooksKeeper,
nil, // The compute keeper will be set later on
sdk.GetConfig().GetBech32AccountAddrPrefix(),
)
ibcHooksICS4Wrapper := ibchooks.NewICS4Middleware(
ak.IbcKeeper.ChannelKeeper,
&ak.IbcKeeper.PortKeeper,
ak.AccountKeeper,
ak.BankKeeper,
&wasmHooks,
)

// Initialize packet forward middleware router
// Initialize packet forward middleware
ak.PacketForwardKeeper = ibcpacketforwardkeeper.NewKeeper(
appCodec,
ak.keys[ibcpacketforwardtypes.StoreKey],
ak.GetSubspace(ibcpacketforwardtypes.ModuleName),
ak.TransferKeeper,
nil, // transfer keeper will be set later on
ak.IbcKeeper.ChannelKeeper,
ak.DistrKeeper,
ak.BankKeeper,
ak.IbcFeeKeeper,
ibcHooksICS4Wrapper,
)

// Setup the ICS4Wrapper used by the hooks middleware
// Configure the hooks keeper
hooksKeeper := ibchookskeeper.NewKeeper(
ak.keys[ibchookstypes.StoreKey],
ak.IbcFeeKeeper = ibcfeekeeper.NewKeeper(
appCodec,
ak.keys[ibcfeetypes.StoreKey],
ak.GetSubspace(ibcfeetypes.ModuleName),
ak.PacketForwardKeeper,
ak.IbcKeeper.ChannelKeeper,
&ak.IbcKeeper.PortKeeper,
ak.AccountKeeper,
ak.BankKeeper,
)
ak.IbcHooksKeeper = &hooksKeeper

// The compute keeper in wasmHooks will be set later on
wasmHooks := ibchooks.NewWasmHooks(&hooksKeeper, nil, sdk.GetConfig().GetBech32AccountAddrPrefix())
ibcHooksICS4Wrapper := ibchooks.NewICS4Middleware(
ibcSwitchKeeper := ibcswitch.NewKeeper(
ak.IbcFeeKeeper,
&wasmHooks,
ak.GetSubspace(ibcswitch.ModuleName),
)
ak.IbcSwitchKeeper = &ibcSwitchKeeper

icaControllerKeeper := icacontrollerkeeper.NewKeeper(
appCodec,
ak.keys[icacontrollertypes.StoreKey],
ak.GetSubspace(icacontrollertypes.SubModuleName),
// todo: how can this work if IbcFeeKeeper does not implement ics4Wrapper?? Juno seems to have a bug
ak.IbcFeeKeeper, // integrate fee channel with ica
ak.IbcSwitchKeeper,
ak.IbcKeeper.ChannelKeeper,
&ak.IbcKeeper.PortKeeper,
ak.ScopedICAControllerKeeper,
Expand All @@ -363,7 +366,6 @@ func (ak *SecretAppKeepers) InitCustomKeepers(
appCodec,
ak.keys[icahosttypes.StoreKey],
ak.GetSubspace(icahosttypes.SubModuleName),
// todo: maybe integrate feekeeper with ica host too
ak.IbcKeeper.ChannelKeeper,
&ak.IbcKeeper.PortKeeper,
ak.AccountKeeper,
Expand All @@ -384,10 +386,7 @@ func (ak *SecretAppKeepers) InitCustomKeepers(
appCodec,
ak.keys[ibctransfertypes.StoreKey],
ak.GetSubspace(ibctransfertypes.ModuleName),
// todo: verify the following: the transfer keeper does not need to know about packet forward keeper, because
// we don't want to go through forward module if the packets originated in this chain.
// todo: verify the following: we want fees for the transfer app (it previously didn't have)
ak.IbcFeeKeeper, // integrate fee channel with transfer
ak.IbcSwitchKeeper,
ak.IbcKeeper.ChannelKeeper,
&ak.IbcKeeper.PortKeeper,
ak.AccountKeeper,
Expand All @@ -398,19 +397,18 @@ func (ak *SecretAppKeepers) InitCustomKeepers(

ak.PacketForwardKeeper.SetTransferKeeper(ak.TransferKeeper)

// Transfer receive: Switch -> Fee -> Packet Forward -> WASM Hooks
var transferStack porttypes.IBCModule
transferStack = transfer.NewIBCModule(ak.TransferKeeper)
transferStack = ibchooks.NewIBCMiddleware(transferStack, &ibcHooksICS4Wrapper)
transferStack = ibcpacketforward.NewIBCMiddleware(
transferStack,
ak.PacketForwardKeeper,
0,
// 10 minutes
ibcpacketforwardkeeper.DefaultForwardTransferPacketTimeoutTimestamp,
// 28 days
ibcpacketforwardkeeper.DefaultRefundTransferPacketTimeoutTimestamp,
ibcpacketforwardkeeper.DefaultForwardTransferPacketTimeoutTimestamp, // 10 minutes
ibcpacketforwardkeeper.DefaultRefundTransferPacketTimeoutTimestamp, // 28 days
)
transferStack = ibcfee.NewIBCMiddleware(transferStack, ak.IbcFeeKeeper)
transferStack = ibchooks.NewIBCMiddleware(transferStack, &ibcHooksICS4Wrapper)
transferStack = ibcswitch.NewIBCMiddleware(transferStack, ak.IbcSwitchKeeper)

var icaHostStack porttypes.IBCModule
Expand Down Expand Up @@ -442,7 +440,7 @@ func (ak *SecretAppKeepers) InitCustomKeepers(
ak.IbcKeeper.PortKeeper,
ak.TransferKeeper,
ak.IbcKeeper.ChannelKeeper,
ibcHooksICS4Wrapper,
ak.IbcSwitchKeeper,
app.Router(),
app.MsgServiceRouter(),
app.GRPCQueryRouter(),
Expand All @@ -456,15 +454,22 @@ func (ak *SecretAppKeepers) InitCustomKeepers(
ak.ComputeKeeper = &computeKeeper
wasmHooks.ContractKeeper = ak.ComputeKeeper

// Create fee enabled wasm ibc Stack
// Compute receive: Switch -> Fee -> Packet Forward -> WASM Hooks
var computeStack porttypes.IBCModule
computeStack = compute.NewIBCHandler(ak.ComputeKeeper, ak.IbcKeeper.ChannelKeeper, ak.IbcFeeKeeper)
computeStack = ibchooks.NewIBCMiddleware(computeStack, &ibcHooksICS4Wrapper)
computeStack = ibcpacketforward.NewIBCMiddleware(
computeStack,
ak.PacketForwardKeeper,
0,
ibcpacketforwardkeeper.DefaultForwardTransferPacketTimeoutTimestamp, // 10 minutes
ibcpacketforwardkeeper.DefaultRefundTransferPacketTimeoutTimestamp, // 28 days
)
computeStack = ibcfee.NewIBCMiddleware(computeStack, ak.IbcFeeKeeper)
computeStack = ibcswitch.NewIBCMiddleware(computeStack, ak.IbcSwitchKeeper)

// Create static IBC router, add ibc-transfer module route, then set and seal it
ibcRouter := porttypes.NewRouter()
ibcRouter.
ibcRouter := porttypes.NewRouter().
AddRoute(ibctransfertypes.ModuleName, transferStack).
AddRoute(compute.ModuleName, computeStack).
AddRoute(icacontrollertypes.SubModuleName, icaControllerStack).
Expand Down
2 changes: 1 addition & 1 deletion app/legacy/v170/migrate.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (
v170registration "github.com/scrtlabs/SecretNetwork/x/registration/legacy/v170"
)

func Migrate(appState types.AppMap, clientCtx client.Context) types.AppMap {
func Migrate(appState types.AppMap, _ client.Context) types.AppMap {
legacyAminoCodec := codec.NewLegacyAmino()

if appState[v120registration.ModuleName] != nil {
Expand Down
2 changes: 1 addition & 1 deletion app/upgrades/v1.5/upgrade.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ var Upgrade = upgrades.Upgrade{
StoreUpgrades: store.StoreUpgrades{},
}

func createUpgradeHandler(mm *module.Manager, keepers *keepers.SecretAppKeepers, configurator module.Configurator,
func createUpgradeHandler(mm *module.Manager, _ *keepers.SecretAppKeepers, configurator module.Configurator,
) upgradetypes.UpgradeHandler {
return func(ctx sdk.Context, _ upgradetypes.Plan, vm module.VersionMap) (module.VersionMap, error) {
ctx.Logger().Info(` _ _ _____ _____ _____ _____ ______ `)
Expand Down
2 changes: 1 addition & 1 deletion app/upgrades/v1.6/upgrade.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ var Upgrade = upgrades.Upgrade{
StoreUpgrades: store.StoreUpgrades{},
}

func createUpgradeHandler(mm *module.Manager, keepers *keepers.SecretAppKeepers, configurator module.Configurator,
func createUpgradeHandler(mm *module.Manager, _ *keepers.SecretAppKeepers, configurator module.Configurator,
) upgradetypes.UpgradeHandler {
return func(ctx sdk.Context, _ upgradetypes.Plan, vm module.VersionMap) (module.VersionMap, error) {
ctx.Logger().Info(` _ _ _____ _____ _____ _____ ______ `)
Expand Down
3 changes: 2 additions & 1 deletion app/upgrades/v1.7/upgrade.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@ import (
"encoding/hex"
"encoding/json"
"fmt"
icacontrollertypes "github.com/cosmos/ibc-go/v4/modules/apps/27-interchain-accounts/controller/types"
"os"
"path/filepath"

icacontrollertypes "github.com/cosmos/ibc-go/v4/modules/apps/27-interchain-accounts/controller/types"

store "github.com/cosmos/cosmos-sdk/store/types"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/module"
Expand Down
2 changes: 1 addition & 1 deletion app/upgrades/v1.8/upgrade.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ var Upgrade = upgrades.Upgrade{
StoreUpgrades: store.StoreUpgrades{},
}

func createUpgradeHandler(mm *module.Manager, keepers *keepers.SecretAppKeepers, configurator module.Configurator,
func createUpgradeHandler(mm *module.Manager, keepers *keepers.SecretAppKeepers, configurator module.Configurator, //nolint:all
) upgradetypes.UpgradeHandler {
return func(ctx sdk.Context, _ upgradetypes.Plan, vm module.VersionMap) (module.VersionMap, error) {
ctx.Logger().Info(` _ _ _____ _____ _____ _____ ______ `)
Expand Down
4 changes: 2 additions & 2 deletions cmd/secretd/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,8 +107,8 @@ func InitCmd(mbm module.BasicManager, defaultNodeHome string) *cobra.Command {

// Get bip39 mnemonic
var mnemonic string
recover, _ := cmd.Flags().GetBool(FlagRecover)
if recover {
isRecover, _ := cmd.Flags().GetBool(FlagRecover)
if isRecover {
inBuf := bufio.NewReader(cmd.InOrStdin())
value, err := input.GetString("Enter your bip39 mnemonic", inBuf)
if err != nil {
Expand Down
9 changes: 3 additions & 6 deletions cmd/secretd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -286,7 +286,7 @@ func newApp(logger log.Logger, db dbm.DB, traceStore io.Writer, appOpts serverty

bootstrap := cast.ToBool(appOpts.Get("bootstrap"))

// fmt.Printf("bootstrap: %s", cast.ToString(bootstrap))
// fmt.Printf("bootstrap: %s\n", cast.ToString(bootstrap))

return app.NewSecretNetworkApp(logger, db, traceStore, true, skipUpgradeHeights,
cast.ToString(appOpts.Get(flags.FlagHome)),
Expand Down Expand Up @@ -348,11 +348,8 @@ func updateTmParamsAndInit(mbm module.BasicManager, defaultNodeHome string) *cob

serverconfig.WriteConfigFile(appConfigFilePath, appConf)

if err := originalFunc(cmd, args); err != nil {
return err
}

return nil
err := originalFunc(cmd, args)
return err
}

cmd.RunE = wrappedFunc
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ use cosmwasm_std::{
use cosmwasm_storage::PrefixedStorage;
use secp256k1::Secp256k1;

use crate::msg::{ExecuteMsg, ExternalMessages, InstantiateMsg, QueryMsg, QueryRes};
use crate::msg::{
ExecuteMsg, ExternalMessages, IBCLifecycleComplete, InstantiateMsg, QueryMsg, QueryRes,
};
use crate::state::{count, count_read, expiration, expiration_read, PREFIX_TEST, TEST_KEY};

#[entry_point]
Expand Down Expand Up @@ -1310,6 +1312,33 @@ pub fn execute(deps: DepsMut, env: Env, info: MessageInfo, msg: ExecuteMsg) -> S
})
.set_data(details[0].data.as_bytes()))
}
ExecuteMsg::IBCLifecycleComplete(IBCLifecycleComplete::IBCAck {
channel,
sequence,
ack,
success,
}) => Ok(Response::default().add_attributes(vec![
("ibc_lifecycle_complete.ibc_ack.channel", channel),
(
"ibc_lifecycle_complete.ibc_ack.sequence",
sequence.to_string(),
),
("ibc_lifecycle_complete.ibc_ack.ack", ack),
(
"ibc_lifecycle_complete.ibc_ack.success",
success.to_string(),
),
])),
ExecuteMsg::IBCLifecycleComplete(IBCLifecycleComplete::IBCTimeout {
channel,
sequence,
}) => Ok(Response::default().add_attributes(vec![
("ibc_lifecycle_complete.ibc_timeout.channel", channel),
(
"ibc_lifecycle_complete.ibc_timeout.sequence",
sequence.to_string(),
),
])),
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -422,6 +422,30 @@ pub enum ExecuteMsg {
ExecuteMultipleContracts {
details: Vec<ExecuteDetails>,
},
#[serde(rename = "ibc_lifecycle_complete")]
IBCLifecycleComplete(IBCLifecycleComplete),
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub enum IBCLifecycleComplete {
#[serde(rename = "ibc_ack")]
IBCAck {
/// The source channel (secret side) of the IBC packet
channel: String,
/// The sequence number that the packet was sent with
sequence: u64,
/// String encoded version of the ack as seen by OnAcknowledgementPacket(..)
ack: String,
/// Weather an ack is a success of failure according to the transfer spec
success: bool,
},
#[serde(rename = "ibc_timeout")]
IBCTimeout {
/// The source channel (secret side) of the IBC packet
channel: String,
/// The sequence number that the packet was sent with
sequence: u64,
},
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
Expand Down
Loading

0 comments on commit 9825f57

Please sign in to comment.