Skip to content

Commit

Permalink
[CT-1262] add e2e tests for permissioned keys success cases (#2479)
Browse files Browse the repository at this point in the history
  • Loading branch information
jayy04 authored Oct 22, 2024
1 parent bcd05e3 commit 9c214d0
Show file tree
Hide file tree
Showing 9 changed files with 939 additions and 59 deletions.
39 changes: 15 additions & 24 deletions protocol/app/ante.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,15 +124,22 @@ func NewAnteHandler(options HandlerOptions) (sdk.AnteHandler, error) {
),
sigVerification: accountplusante.NewCircuitBreakerDecorator(
options.Codec,
accountplusante.NewAuthenticatorDecorator(
options.Codec,
options.AccountplusKeeper,
options.AccountKeeper,
options.SignModeHandler,
sdk.ChainAnteDecorators(
customante.NewEmitPubKeyEventsDecorator(),
accountplusante.NewAuthenticatorDecorator(
options.Codec,
options.AccountplusKeeper,
options.AccountKeeper,
options.SignModeHandler,
),
),
customante.NewSigVerificationDecorator(
options.AccountKeeper,
options.SignModeHandler,
sdk.ChainAnteDecorators(
ante.NewSetPubKeyDecorator(options.AccountKeeper),
ante.NewSigGasConsumeDecorator(options.AccountKeeper, options.SigGasConsumer),
customante.NewSigVerificationDecorator(
options.AccountKeeper,
options.SignModeHandler,
),
),
),
consumeTxSizeGas: ante.NewConsumeGasForTxSizeDecorator(options.AccountKeeper),
Expand All @@ -142,8 +149,6 @@ func NewAnteHandler(options HandlerOptions) (sdk.AnteHandler, error) {
options.FeegrantKeeper,
options.TxFeeChecker,
),
setPubKey: ante.NewSetPubKeyDecorator(options.AccountKeeper),
sigGasConsume: ante.NewSigGasConsumeDecorator(options.AccountKeeper, options.SigGasConsumer),
clobRateLimit: clobante.NewRateLimitDecorator(options.ClobKeeper),
clob: clobante.NewClobDecorator(options.ClobKeeper),
marketUpdates: customante.NewValidateMarketUpdateDecorator(
Expand Down Expand Up @@ -175,8 +180,6 @@ type lockingAnteHandler struct {
sigVerification accountplusante.CircuitBreakerDecorator
consumeTxSizeGas ante.ConsumeTxSizeGasDecorator
deductFee ante.DeductFeeDecorator
setPubKey ante.SetPubKeyDecorator
sigGasConsume ante.SigGasConsumeDecorator
clobRateLimit clobante.ClobRateLimitDecorator
clob clobante.ClobDecorator
marketUpdates customante.ValidateMarketUpdateDecorator
Expand Down Expand Up @@ -252,15 +255,9 @@ func (h *lockingAnteHandler) clobAnteHandle(ctx sdk.Context, tx sdk.Tx, simulate
if ctx, err = h.consumeTxSizeGas.AnteHandle(ctx, tx, simulate, noOpAnteHandle); err != nil {
return ctx, err
}
if ctx, err = h.setPubKey.AnteHandle(ctx, tx, simulate, noOpAnteHandle); err != nil {
return ctx, err
}
if ctx, err = h.validateSigCount.AnteHandle(ctx, tx, simulate, noOpAnteHandle); err != nil {
return ctx, err
}
if ctx, err = h.sigGasConsume.AnteHandle(ctx, tx, simulate, noOpAnteHandle); err != nil {
return ctx, err
}
if ctx, err = h.replayProtection.AnteHandle(ctx, tx, simulate, noOpAnteHandle); err != nil {
return ctx, err
}
Expand Down Expand Up @@ -422,15 +419,9 @@ func (h *lockingAnteHandler) otherMsgAnteHandle(ctx sdk.Context, tx sdk.Tx, simu
if ctx, err = h.deductFee.AnteHandle(ctx, tx, simulate, noOpAnteHandle); err != nil {
return ctx, err
}
if ctx, err = h.setPubKey.AnteHandle(ctx, tx, simulate, noOpAnteHandle); err != nil {
return ctx, err
}
if ctx, err = h.validateSigCount.AnteHandle(ctx, tx, simulate, noOpAnteHandle); err != nil {
return ctx, err
}
if ctx, err = h.sigGasConsume.AnteHandle(ctx, tx, simulate, noOpAnteHandle); err != nil {
return ctx, err
}
if ctx, err = h.replayProtection.AnteHandle(ctx, tx, simulate, noOpAnteHandle); err != nil {
return ctx, err
}
Expand Down
110 changes: 110 additions & 0 deletions protocol/app/ante/pubkey.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
package ante

import (
"encoding/base64"
"fmt"

errorsmod "cosmossdk.io/errors"

cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/cosmos/cosmos-sdk/types/tx/signing"
authsigning "github.com/cosmos/cosmos-sdk/x/auth/signing"
)

// NewEmitPubKeyEventsDecorator emits events for each signer's public key.
// CONTRACT: Tx must implement SigVerifiableTx interface
type EmitPubKeyEventsDecorator struct{}

func NewEmitPubKeyEventsDecorator() EmitPubKeyEventsDecorator {
return EmitPubKeyEventsDecorator{}
}

func (eped EmitPubKeyEventsDecorator) AnteHandle(
ctx sdk.Context,
tx sdk.Tx,
simulate bool,
next sdk.AnteHandler,
) (sdk.Context, error) {
sigTx, ok := tx.(authsigning.SigVerifiableTx)
if !ok {
return ctx, errorsmod.Wrap(sdkerrors.ErrTxDecode, "invalid tx type")
}

signers, err := sigTx.GetSigners()
if err != nil {
return ctx, err
}

signerStrs := make([]string, len(signers))

// Also emit the following events, so that txs can be indexed by these
// indices:
// - signature (via `tx.signature='<sig_as_base64>'`),
// - concat(address,"/",sequence) (via `tx.acc_seq='cosmos1abc...def/42'`).
sigs, err := sigTx.GetSignaturesV2()
if err != nil {
return ctx, err
}

var events sdk.Events
for i, sig := range sigs {
events = append(events, sdk.NewEvent(sdk.EventTypeTx,
sdk.NewAttribute(sdk.AttributeKeyAccountSequence, fmt.Sprintf("%s/%d", signerStrs[i], sig.Sequence)),
))

sigBzs, err := signatureDataToBz(sig.Data)
if err != nil {
return ctx, err
}
for _, sigBz := range sigBzs {
events = append(events, sdk.NewEvent(sdk.EventTypeTx,
sdk.NewAttribute(sdk.AttributeKeySignature, base64.StdEncoding.EncodeToString(sigBz)),
))
}
}

ctx.EventManager().EmitEvents(events)

return next(ctx, tx, simulate)
}

// signatureDataToBz converts a SignatureData into raw bytes signature.
// For SingleSignatureData, it returns the signature raw bytes.
// For MultiSignatureData, it returns an array of all individual signatures,
// as well as the aggregated signature.
func signatureDataToBz(data signing.SignatureData) ([][]byte, error) {
if data == nil {
return nil, fmt.Errorf("got empty SignatureData")
}

switch data := data.(type) {
case *signing.SingleSignatureData:
return [][]byte{data.Signature}, nil
case *signing.MultiSignatureData:
sigs := [][]byte{}
var err error

for _, d := range data.Signatures {
nestedSigs, err := signatureDataToBz(d)
if err != nil {
return nil, err
}
sigs = append(sigs, nestedSigs...)
}

multiSignature := cryptotypes.MultiSignature{
Signatures: sigs,
}
aggregatedSig, err := multiSignature.Marshal()
if err != nil {
return nil, err
}
sigs = append(sigs, aggregatedSig)

return sigs, nil
default:
return nil, sdkerrors.ErrInvalidType.Wrapf("unexpected signature data type %T", data)
}
}
44 changes: 22 additions & 22 deletions protocol/app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -1113,6 +1113,28 @@ func New(
app.SubaccountsKeeper,
)

// Initialize authenticators
app.AuthenticatorManager = authenticator.NewAuthenticatorManager()
app.AuthenticatorManager.InitializeAuthenticators(
[]accountplusmoduletypes.Authenticator{
authenticator.NewAllOf(app.AuthenticatorManager),
authenticator.NewAnyOf(app.AuthenticatorManager),
authenticator.NewSignatureVerification(app.AccountKeeper),
authenticator.NewMessageFilter(),
authenticator.NewClobPairIdFilter(),
authenticator.NewSubaccountFilter(),
},
)
app.AccountPlusKeeper = *accountplusmodulekeeper.NewKeeper(
appCodec,
keys[accountplusmoduletypes.StoreKey],
app.AuthenticatorManager,
[]string{
lib.GovModuleAddress.String(),
},
)
accountplusModule := accountplusmodule.NewAppModule(appCodec, app.AccountPlusKeeper)

clobFlags := clobflags.GetClobFlagValuesFromOptions(appOpts)
logger.Info("Parsed CLOB flags", "Flags", clobFlags)

Expand Down Expand Up @@ -1232,28 +1254,6 @@ func New(
app.VaultKeeper,
)

// Initialize authenticators
app.AuthenticatorManager = authenticator.NewAuthenticatorManager()
app.AuthenticatorManager.InitializeAuthenticators(
[]accountplusmoduletypes.Authenticator{
authenticator.NewAllOf(app.AuthenticatorManager),
authenticator.NewAnyOf(app.AuthenticatorManager),
authenticator.NewSignatureVerification(app.AccountKeeper),
authenticator.NewMessageFilter(),
authenticator.NewClobPairIdFilter(),
authenticator.NewSubaccountFilter(),
},
)
app.AccountPlusKeeper = *accountplusmodulekeeper.NewKeeper(
appCodec,
keys[accountplusmoduletypes.StoreKey],
app.AuthenticatorManager,
[]string{
lib.GovModuleAddress.String(),
},
)
accountplusModule := accountplusmodule.NewAppModule(appCodec, app.AccountPlusKeeper)

/**** Module Options ****/

// NOTE: we may consider parsing `appOpts` inside module constructors. For the moment
Expand Down
12 changes: 12 additions & 0 deletions protocol/testutil/constants/stateful_orders.go
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,18 @@ var (
Subticks: 30,
GoodTilOneof: &clobtypes.Order_GoodTilBlockTime{GoodTilBlockTime: 10},
}
LongTermOrder_Bob_Num0_Id0_Clob1_Buy25_Price30_GTBT10 = clobtypes.Order{
OrderId: clobtypes.OrderId{
SubaccountId: Bob_Num0,
ClientId: 0,
OrderFlags: clobtypes.OrderIdFlags_LongTerm,
ClobPairId: 1,
},
Side: clobtypes.Order_SIDE_BUY,
Quantums: 25,
Subticks: 30,
GoodTilOneof: &clobtypes.Order_GoodTilBlockTime{GoodTilBlockTime: 10},
}
LongTermOrder_Bob_Num0_Id0_Clob0_Buy35_Price30_GTBT11 = clobtypes.Order{
OrderId: clobtypes.OrderId{
SubaccountId: Bob_Num0,
Expand Down
16 changes: 8 additions & 8 deletions protocol/x/accountplus/ante/circuit_breaker.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,20 +11,20 @@ import (
// the existence of `TxExtension`.
type CircuitBreakerDecorator struct {
cdc codec.BinaryCodec
authenticatorAnteHandlerFlow sdk.AnteDecorator
originalAnteHandlerFlow sdk.AnteDecorator
authenticatorAnteHandlerFlow sdk.AnteHandler
defaultAnteHandlerFlow sdk.AnteHandler
}

// NewCircuitBreakerDecorator creates a new instance of CircuitBreakerDecorator with the provided parameters.
func NewCircuitBreakerDecorator(
cdc codec.BinaryCodec,
auth sdk.AnteDecorator,
classic sdk.AnteDecorator,
authenticatorAnteHandlerFlow sdk.AnteHandler,
defaultAnteHandlerFlow sdk.AnteHandler,
) CircuitBreakerDecorator {
return CircuitBreakerDecorator{
cdc: cdc,
authenticatorAnteHandlerFlow: auth,
originalAnteHandlerFlow: classic,
authenticatorAnteHandlerFlow: authenticatorAnteHandlerFlow,
defaultAnteHandlerFlow: defaultAnteHandlerFlow,
}
}

Expand All @@ -44,9 +44,9 @@ func (ad CircuitBreakerDecorator) AnteHandle(
// Check that the authenticator flow is active
if specified, _ := lib.HasSelectedAuthenticatorTxExtensionSpecified(tx, ad.cdc); specified {
// Return and call the AnteHandle function on all the authenticator decorators.
return ad.authenticatorAnteHandlerFlow.AnteHandle(ctx, tx, simulate, next)
return ad.authenticatorAnteHandlerFlow(ctx, tx, simulate)
}

// Return and call the AnteHandle function on all the original decorators.
return ad.originalAnteHandlerFlow.AnteHandle(ctx, tx, simulate, next)
return ad.defaultAnteHandlerFlow(ctx, tx, simulate)
}
4 changes: 2 additions & 2 deletions protocol/x/accountplus/ante/circuit_breaker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -151,8 +151,8 @@ func (s *AuthenticatorCircuitBreakerAnteSuite) TestCircuitBreakerAnte() {
// Create a CircuitBreaker AnteDecorator
cbd := ante.NewCircuitBreakerDecorator(
s.tApp.App.AppCodec(),
mockTestAuthenticator,
mockTestClassic,
sdk.ChainAnteDecorators(mockTestAuthenticator),
sdk.ChainAnteDecorators(mockTestClassic),
)
anteHandler := sdk.ChainAnteDecorators(cbd)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,12 @@ func (sva SignatureVerification) Initialize(config []byte) (types.Authenticator,
// Authenticate takes a SignaturesVerificationData struct and validates
// each signer and signature using signature verification
func (sva SignatureVerification) Authenticate(ctx sdk.Context, request types.AuthenticationRequest) error {
// First consume gas for verifying the signature
params := sva.ak.GetParams(ctx)
// Signature verification only accepts secp256k1 signatures so consume static gas here.
ctx.GasMeter().ConsumeGas(params.SigVerifyCostSecp256k1, "secp256k1 signature verification")

// after gas consumption continue to verify signatures
if request.Simulate || ctx.IsReCheckTx() {
return nil
}
Expand Down
6 changes: 3 additions & 3 deletions protocol/x/affiliates/e2e/register_affiliate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,6 @@ import (
)

func TestRegisterAffiliateInvalidSigner(t *testing.T) {
tApp := testapp.NewTestAppBuilder(t).Build()
ctx := tApp.InitChain()

testCases := []struct {
name string
referee string
Expand Down Expand Up @@ -45,6 +42,9 @@ func TestRegisterAffiliateInvalidSigner(t *testing.T) {

for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
tApp := testapp.NewTestAppBuilder(t).Build()
ctx := tApp.InitChain()

msgRegisterAffiliate := types.MsgRegisterAffiliate{
Referee: tc.referee,
Affiliate: tc.affiliate,
Expand Down
Loading

0 comments on commit 9c214d0

Please sign in to comment.