Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

feat(accounts): re-introduce bundler #21562

Open
wants to merge 19 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view

Large diffs are not rendered by default.

660 changes: 523 additions & 137 deletions api/cosmos/accounts/v1/tx.pulsar.go

Large diffs are not rendered by default.

359 changes: 336 additions & 23 deletions x/accounts/interfaces/account_abstraction/v1/interface.pb.go

Large diffs are not rendered by default.

34 changes: 33 additions & 1 deletion x/accounts/keeper.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"errors"
"fmt"

txdecode "cosmossdk.io/x/tx/decode"
gogoproto "github.com/cosmos/gogoproto/proto"

"cosmossdk.io/collections"
Expand Down Expand Up @@ -78,6 +79,7 @@ func NewKeeper(
type Keeper struct {
appmodule.Environment

txDecoder *txdecode.Decoder
addressCodec address.Codec
codec codec.Codec
makeSendCoinsMsg coinsTransferMsgFunc
Expand Down Expand Up @@ -339,7 +341,6 @@ func (k Keeper) makeAccountContext(ctx context.Context, accountNumber uint64, ac

// sendAnyMessages it a helper function that executes untyped codectypes.Any messages
// The messages must all belong to a module.
// nolint: unused // TODO: remove nolint when we bring back bundler payments
func (k Keeper) sendAnyMessages(ctx context.Context, sender []byte, anyMessages []*implementation.Any) ([]*implementation.Any, error) {
anyResponses := make([]*implementation.Any, len(anyMessages))
for i := range anyMessages {
Expand All @@ -360,6 +361,37 @@ func (k Keeper) sendAnyMessages(ctx context.Context, sender []byte, anyMessages
return anyResponses, nil
}

func (k Keeper) sendManyMessagesReturnAnys(ctx context.Context, sender []byte, msgs []transaction.Msg) ([]*implementation.Any, error) {
resp, err := k.sendManyMessages(ctx, sender, msgs)
if err != nil {
return nil, err
}
anys := make([]*implementation.Any, len(resp))
for i := range resp {
anypb, err := implementation.PackAny(resp[i])
if err != nil {
return nil, err
}
anys[i] = anypb
}
return anys, nil
}

// sendManyMessages is a helper function that sends many untyped messages on behalf of the sender
// then returns the respective results. Since the function calls into SendModuleMessage
// it is guaranteed to disallow impersonation attacks from the sender.
func (k Keeper) sendManyMessages(ctx context.Context, sender []byte, msgs []transaction.Msg) ([]transaction.Msg, error) {
resps := make([]transaction.Msg, len(msgs))
for i, msg := range msgs {
resp, err := k.SendModuleMessage(ctx, sender, msg)
if err != nil {
return nil, fmt.Errorf("failed to execute message %d: %s", i, err.Error())
}
resps[i] = resp
}
return resps, nil
}

// SendModuleMessage can be used to send a message towards a module.
// It should be used when the response type is not known by the caller.
func (k Keeper) SendModuleMessage(ctx context.Context, sender []byte, msg transaction.Msg) (transaction.Msg, error) {
Expand Down
154 changes: 154 additions & 0 deletions x/accounts/keeper_account_abstraction.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,15 @@ import (
"context"
"errors"
"fmt"
"strings"
"time"

"cosmossdk.io/collections"
aa_interface_v1 "cosmossdk.io/x/accounts/interfaces/account_abstraction/v1"
"cosmossdk.io/x/accounts/internal/implementation"
v1 "cosmossdk.io/x/accounts/v1"
txdecode "cosmossdk.io/x/tx/decode"
gogoproto "github.com/cosmos/gogoproto/proto"

"github.com/cosmos/cosmos-sdk/types/address"
"github.com/cosmos/cosmos-sdk/types/tx"
Expand Down Expand Up @@ -38,6 +44,7 @@ func (k Keeper) IsAbstractedAccount(ctx context.Context, addr []byte) (bool, err
return impl.HasExec(&aa_interface_v1.MsgAuthenticate{}), nil
}

// AuthenticateAccount runs the authentication flow of an account.
func (k Keeper) AuthenticateAccount(ctx context.Context, signer []byte, bundler string, rawTx *tx.TxRaw, protoTx *tx.Tx, signIndex uint32) error {
msg := &aa_interface_v1.MsgAuthenticate{
Bundler: bundler,
Expand All @@ -51,3 +58,150 @@ func (k Keeper) AuthenticateAccount(ctx context.Context, signer []byte, bundler
}
return nil
}

// ExecuteBundledTx will execute the single bundled tx.
func (k Keeper) ExecuteBundledTx(ctx context.Context, bundler string, txBytes []byte) *v1.BundledTxResponse {
resp, err := k.executeBundledTx(ctx, bundler, txBytes)
if err != nil {
if resp == nil {
return &v1.BundledTxResponse{
Error: err.Error(),
}
}
// ensure partial information is not discarded
resp.Error = err.Error()
return resp
}
return resp
}

func (k Keeper) executeBundledTx(ctx context.Context, bundler string, txBytes []byte) (*v1.BundledTxResponse, error) {
bundledTx, err := k.txDecoder.Decode(txBytes)
if err != nil {
return nil, fmt.Errorf("invalid tx bytes: %w", err)
}
blockInfo := k.HeaderService.HeaderInfo(ctx)
xt, err := verifyAndExtractAaXtFromTx(bundledTx, uint64(blockInfo.Height), blockInfo.Time)
if err != nil {
return nil, fmt.Errorf("tx failed validation check: %w", err)
}

resp := new(v1.BundledTxResponse)
// to execute a bundled tx the first step is authentication.
signer := bundledTx.Signers[0]
authGasUsed, err := k.BranchService.ExecuteWithGasLimit(ctx, xt.AuthenticationGasLimit, func(ctx context.Context) error {
return k.AuthenticateAccount(ctx, signer, bundler, protov2TxRawToProtoV1(bundledTx.TxRaw), protoV2TxToProtoV1(bundledTx.Tx), 0)
})
resp.AuthenticationGasUsed = authGasUsed // set independently of outcome
if err != nil {
return nil, err
}

// after authentication, we execute the bundler messages.
if len(xt.BundlerPaymentMessages) != 0 {
var paymentMsgResp []*implementation.Any
bundlerPaymentGasUsed, err := k.BranchService.ExecuteWithGasLimit(ctx, xt.BundlerPaymentGasLimit, func(ctx context.Context) error {
responses, err := k.sendAnyMessages(ctx, signer, xt.BundlerPaymentMessages)
if err != nil {
return err
}
paymentMsgResp = responses
return nil
})
resp.BundlerPaymentGasUsed = bundlerPaymentGasUsed // set independently of outcome
if err != nil {
return nil, fmt.Errorf("%w: %w", ErrBundlerPayment, err)
}
resp.BundlerPaymentResponses = paymentMsgResp
}

// finally execute the real messages
var execResponses []*implementation.Any
execGasUsed, err := k.BranchService.ExecuteWithGasLimit(ctx, xt.ExecutionGasLimit, func(ctx context.Context) error {
responses, err := k.sendManyMessagesReturnAnys(ctx, signer, bundledTx.Messages)
if err != nil {
return err
}
execResponses = responses
return nil
})
resp.ExecutionGasUsed = execGasUsed // set independently of outcome
if err != nil {
return nil, fmt.Errorf("%w: %w", ErrExecution, err)
}
resp.ExecutionResponses = execResponses

return resp, nil
}

var aaXtName = gogoproto.MessageName(&aa_interface_v1.MsgAuthenticate{})

func verifyAndExtractAaXtFromTx(bundledTx *txdecode.DecodedTx, currentBlock uint64, currentTime time.Time) (*aa_interface_v1.TxExtension, error) {
// some basic things: we do not allow multi addresses in the bundled tx
// rationale: the bundler could simply bundle multiple txs in the same bundle
// with other accounts.
if len(bundledTx.Signers) != 1 {
return nil, fmt.Errorf("account abstraction bundled txs can only have one signer, got: %d", len(bundledTx.Signers))
}
// do not allow sign modes different from single
if len(bundledTx.Tx.AuthInfo.SignerInfos) != 1 {
return nil, fmt.Errorf("account abstraction tx must have one signer info")
}

// check sign mode is valid
if bundledTx.Tx.AuthInfo.SignerInfos[0].ModeInfo.GetSingle() == nil {
return nil, fmt.Errorf("account abstraction mode info must be single")
}

// we do not want the tx to have any fees set.
if bundledTx.Tx.AuthInfo.Fee != nil {
return nil, fmt.Errorf("account abstraction tx must not have the Fee field set")
}

// check timeouts TODO: do not like this much since it feels like we are adding repetition of logic.
if bundledTx.Tx.Body.TimeoutTimestamp != nil && currentTime.After(bundledTx.Tx.Body.TimeoutTimestamp.AsTime()) {
return nil, fmt.Errorf("block time is after tx timeout timestamp")
}
if bundledTx.Tx.Body.TimeoutHeight != 0 && currentBlock >= bundledTx.Tx.Body.TimeoutHeight {
return nil, fmt.Errorf("block height is after tx timeout height")
}
Comment on lines +164 to +170
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Refactor timeout checks to reduce code duplication

The timeout checks for TimeoutTimestamp and TimeoutHeight are similar and could be refactored into a helper function to improve code readability and maintainability.

Would you like assistance in implementing this refactoring? Here's a suggested approach:

+func isTimeoutExceeded(bundledTx *txdecode.DecodedTx, currentBlock uint64, currentTime time.Time) error {
+	if bundledTx.Tx.Body.TimeoutTimestamp != nil && currentTime.After(bundledTx.Tx.Body.TimeoutTimestamp.AsTime()) {
+		return fmt.Errorf("block time is after tx timeout timestamp")
+	}
+	if bundledTx.Tx.Body.TimeoutHeight != 0 && currentBlock >= bundledTx.Tx.Body.TimeoutHeight {
+		return fmt.Errorf("block height is after tx timeout height")
+	}
+	return nil
+}

 func verifyAndExtractAaXtFromTx(bundledTx *txdecode.DecodedTx, currentBlock uint64, currentTime time.Time) (*aa_interface_v1.TxExtension, error) {
 	// ...

-	// check timeouts TODO: do not like this much since it feels like we are adding repetition of logic.
-	if bundledTx.Tx.Body.TimeoutTimestamp != nil && currentTime.After(bundledTx.Tx.Body.TimeoutTimestamp.AsTime()) {
-		return nil, fmt.Errorf("block time is after tx timeout timestamp")
-	}
-	if bundledTx.Tx.Body.TimeoutHeight != 0 && currentBlock >= bundledTx.Tx.Body.TimeoutHeight {
-		return nil, fmt.Errorf("block height is after tx timeout height")
-	}
+	// Check timeouts
+	if err := isTimeoutExceeded(bundledTx, currentBlock, currentTime); err != nil {
+		return nil, err
+	}
 
 	// extract extension
 	// ...
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// check timeouts TODO: do not like this much since it feels like we are adding repetition of logic.
if bundledTx.Tx.Body.TimeoutTimestamp != nil && currentTime.After(bundledTx.Tx.Body.TimeoutTimestamp.AsTime()) {
return nil, fmt.Errorf("block time is after tx timeout timestamp")
}
if bundledTx.Tx.Body.TimeoutHeight != 0 && currentBlock >= bundledTx.Tx.Body.TimeoutHeight {
return nil, fmt.Errorf("block height is after tx timeout height")
}
func isTimeoutExceeded(bundledTx *txdecode.DecodedTx, currentBlock uint64, currentTime time.Time) error {
if bundledTx.Tx.Body.TimeoutTimestamp != nil && currentTime.After(bundledTx.Tx.Body.TimeoutTimestamp.AsTime()) {
return fmt.Errorf("block time is after tx timeout timestamp")
}
if bundledTx.Tx.Body.TimeoutHeight != 0 && currentBlock >= bundledTx.Tx.Body.TimeoutHeight {
return fmt.Errorf("block height is after tx timeout height")
}
return nil
}
func verifyAndExtractAaXtFromTx(bundledTx *txdecode.DecodedTx, currentBlock uint64, currentTime time.Time) (*aa_interface_v1.TxExtension, error) {
// ...
// Check timeouts
if err := isTimeoutExceeded(bundledTx, currentBlock, currentTime); err != nil {
return nil, err
}
// extract extension
// ...


// extract extension
found := false
xt := new(aa_interface_v1.TxExtension)
for i, anyPb := range bundledTx.Tx.Body.ExtensionOptions {
if nameFromTypeURL(anyPb.TypeUrl) == aaXtName {
if found {
return nil, fmt.Errorf("multiple aa extensions on the same tx")
}
found = true
// unwrap
err := xt.Unmarshal(anyPb.Value)
if err != nil {
return nil, fmt.Errorf("unable to unmarshal tx extension at index %d: %w", i, err)
}
}
}
if !found {
return nil, fmt.Errorf("%w: did not have AA extension %s", ErrAuthentication, aaXtName)
}

err := verifyAaXt(xt)
if err != nil {
return nil, fmt.Errorf("invalid account abstraction tx extension: %w", err)
}

return xt, nil
}

func verifyAaXt(_ *aa_interface_v1.TxExtension) error {
return nil
}

func nameFromTypeURL(url string) string {
name := url
if i := strings.LastIndexByte(url, '/'); i >= 0 {
name = name[i+len("/"):]
}
return name
}
Loading
Loading