github.com/fibonacci-chain/fbc@v0.0.0-20231124064014-c7636198c1e9/libs/cosmos-sdk/docs/architecture/adr-010-modular-antehandler.md (about)

     1  # ADR 010: Modular AnteHandler
     2  
     3  ## Changelog
     4  
     5  - 2019 Aug 31: Initial draft
     6  
     7  ## Context
     8  
     9  The current AnteHandler design allows users to either use the default AnteHandler provided in `x/auth` or to build their own AnteHandler from scratch. Ideally AnteHandler functionality is split into multiple, modular functions that can be chained together along with custom ante-functions so that users do not have to rewrite common antehandler logic when they want to implement custom behavior.
    10  
    11  For example, let's say a user wants to implement some custom signature verification logic. In the current codebase, the user would have to write their own Antehandler from scratch largely reimplementing much of the same code and then set their own custom, monolithic antehandler in the baseapp. Instead, we would like to allow users to specify custom behavior when necessary and combine them with default ante-handler functionality in a way that is as modular and flexible as possible.
    12  
    13  ## Proposals
    14  
    15  ### Per-Module AnteHandler
    16  
    17  One approach is to use the [ModuleManager](https://godoc.org/github.com/cosmos/cosmos-sdk/types/module) and have each module implement its own antehandler if it requires custom antehandler logic. The ModuleManager can then be passed in an AnteHandler order in the same way it has an order for BeginBlockers and EndBlockers. The ModuleManager returns a single AnteHandler function that will take in a tx and run each module's `AnteHandle` in the specified order. The module manager's AnteHandler is set as the baseapp's AnteHandler.
    18  
    19  Pros:
    20  1. Simple to implement
    21  2. Utilizes the existing ModuleManager architecture
    22  
    23  Cons:
    24  1. Improves granularity but still cannot get more granular than a per-module basis. e.g. If auth's `AnteHandle` function is in charge of validating memo and signatures, users cannot swap the signature-checking functionality while keeping the rest of auth's `AnteHandle` functionality.
    25  2. Module AnteHandler are run one after the other. There is no way for one AnteHandler to wrap or "decorate" another.
    26  
    27  ### Decorator Pattern
    28  
    29  The [weave project](https://github.com/iov-one/weave) achieves AnteHandler modularity through the use of a decorator pattern. The interface is designed as follows:
    30  
    31  ```go
    32  // Decorator wraps a Handler to provide common functionality
    33  // like authentication, or fee-handling, to many Handlers
    34  type Decorator interface {
    35  	Check(ctx Context, store KVStore, tx Tx, next Checker) (*CheckResult, error)
    36  	Deliver(ctx Context, store KVStore, tx Tx, next Deliverer) (*DeliverResult, error)
    37  }
    38  ```
    39  
    40  Each decorator works like a modularized SDK antehandler function, but it can take in a `next` argument that may be another decorator or a Handler (which does not take in a next argument). These decorators can be chained together, one decorator being passed in as the `next` argument of the previous decorator in the chain. The chain ends in a Router which can take a tx and route to the appropriate msg handler.
    41  
    42  A key benefit of this approach is that one Decorator can wrap its internal logic around the next Checker/Deliverer. A weave Decorator may do the following:
    43  
    44  ```go
    45  // Example Decorator's Deliver function
    46  func (example Decorator) Deliver(ctx Context, store KVStore, tx Tx, next Deliverer) {
    47      // Do some pre-processing logic
    48  
    49      res, err := next.Deliver(ctx, store, tx)
    50  
    51      // Do some post-processing logic given the result and error
    52  }
    53  ```
    54  
    55  Pros:
    56  1. Weave Decorators can wrap over the next decorator/handler in the chain. The ability to both pre-process and post-process may be useful in certain settings.
    57  2. Provides a nested modular structure that isn't possible in the solution above, while also allowing for a linear one-after-the-other structure like the solution above.
    58  
    59  Cons:
    60  1. It is hard to understand at first glance the state updates that would occur after a Decorator runs given the `ctx`, `store`, and `tx`. A Decorator can have an arbitrary number of nested Decorators being called within its function body, each possibly doing some pre- and post-processing before calling the next decorator on the chain. Thus to understand what a Decorator is doing, one must also understand what every other decorator further along the chain is also doing. This can get quite complicated to understand. A linear, one-after-the-other approach while less powerful, may be much easier to reason about.
    61  
    62  ### Chained Micro-Functions
    63  
    64  The benefit of Weave's approach is that the Decorators can be very concise, which when chained together allows for maximum customizability. However, the nested structure can get quite complex and thus hard to reason about.
    65  
    66  Another approach is to split the AnteHandler functionality into tightly scoped "micro-functions", while preserving the one-after-the-other ordering that would come from the ModuleManager approach.
    67  
    68  We can then have a way to chain these micro-functions so that they run one after the other. Modules may define multiple ante micro-functions and then also provide a default per-module AnteHandler that implements a default, suggested order for these micro-functions. 
    69  
    70  Users can order the AnteHandlers easily by simply using the ModuleManager. The ModuleManager will take in a list of AnteHandlers and return a single AnteHandler that runs each AnteHandler in the order of the list provided. If the user is comfortable with the default ordering of each module, this is as simple as providing a list with each module's antehandler (exactly the same as BeginBlocker and EndBlocker).
    71  
    72  If however, users wish to change the order or add, modify, or delete ante micro-functions in anyway; they can always define their own ante micro-functions and add them explicitly to the list that gets passed into module manager.
    73  
    74  #### Default Workflow:
    75  
    76  This is an example of a user's AnteHandler if they choose not to make any custom micro-functions.
    77  
    78  ##### SDK code:
    79  
    80  ```go
    81  // Chains together a list of AnteHandler micro-functions that get run one after the other.
    82  // Returned AnteHandler will abort on first error.
    83  func Chainer(order []AnteHandler) AnteHandler {
    84      return func(ctx Context, tx Tx, simulate bool) (newCtx Context, err error) {
    85          for _, ante := range order {
    86              ctx, err := ante(ctx, tx, simulate)
    87              if err != nil {
    88                  return ctx, err
    89              }
    90          }
    91          return ctx, err
    92      }
    93  }
    94  ```
    95  
    96  ```go
    97  // AnteHandler micro-function to verify signatures
    98  func VerifySignatures(ctx Context, tx Tx, simulate bool) (newCtx Context, err error) {
    99      // verify signatures
   100      // Returns InvalidSignature Result and abort=true if sigs invalid
   101      // Return OK result and abort=false if sigs are valid
   102  }
   103  
   104  // AnteHandler micro-function to validate memo
   105  func ValidateMemo(ctx Context, tx Tx, simulate bool) (newCtx Context, err error) {
   106      // validate memo
   107  }
   108  
   109  // Auth defines its own default ante-handler by chaining its micro-functions in a recommended order
   110  AuthModuleAnteHandler := Chainer([]AnteHandler{VerifySignatures, ValidateMemo})
   111  ```
   112  
   113  ```go
   114  // Distribution micro-function to deduct fees from tx
   115  func DeductFees(ctx Context, tx Tx, simulate bool) (newCtx Context, err error) {
   116      // Deduct fees from tx
   117      // Abort if insufficient funds in account to pay for fees
   118  }
   119  
   120  // Distribution micro-function to check if fees > mempool parameter
   121  func CheckMempoolFees(ctx Context, tx Tx, simulate bool) (newCtx Context, err error) {
   122      // If CheckTx: Abort if the fees are less than the mempool's minFee parameter
   123  }
   124  
   125  // Distribution defines its own default ante-handler by chaining its micro-functions in a recommended order
   126  DistrModuleAnteHandler := Chainer([]AnteHandler{CheckMempoolFees, DeductFees})
   127  ```
   128  
   129  ```go
   130  type ModuleManager struct {
   131      // other fields
   132      AnteHandlerOrder []AnteHandler
   133  }
   134  
   135  func (mm ModuleManager) GetAnteHandler() AnteHandler {
   136      retun Chainer(mm.AnteHandlerOrder)
   137  }
   138  ```
   139  
   140  ##### User Code:
   141  
   142  ```go
   143  // Note: Since user is not making any custom modifications, we can just SetAnteHandlerOrder with the default AnteHandlers provided by each module in our preferred order
   144  moduleManager.SetAnteHandlerOrder([]AnteHandler(AuthModuleAnteHandler, DistrModuleAnteHandler))
   145  
   146  app.SetAnteHandler(mm.GetAnteHandler())
   147  ```
   148  
   149  #### Custom Workflow
   150  
   151  This is an example workflow for a user that wants to implement custom antehandler logic. In this example, the user wants to implement custom signature verification and change the order of antehandler so that validate memo runs before signature verification.
   152  
   153  ##### User Code
   154  
   155  ```go
   156  // User can implement their own custom signature verification antehandler micro-function
   157  func CustomSigVerify(ctx Context, tx Tx, simulate bool) (newCtx Context, err error) {
   158      // do some custom signature verification logic
   159  }
   160  ```
   161  
   162  ```go
   163  // Micro-functions allow users to change order of when they get executed, and swap out default ante-functionality with their own custom logic.
   164  // Note that users can still chain the default distribution module handler, and auth micro-function along with their custom ante function
   165  moduleManager.SetAnteHandlerOrder([]AnteHandler(ValidateMemo, CustomSigVerify, DistrModuleAnteHandler))
   166  ```
   167  
   168  Pros:
   169  1. Allows for ante functionality to be as modular as possible.
   170  2. For users that do not need custom ante-functionality, there is little difference between how antehandlers work and how BeginBlock and EndBlock work in ModuleManager.
   171  3. Still easy to understand
   172  
   173  Cons:
   174  1. Cannot wrap antehandlers with decorators like you can with Weave.
   175  
   176  ### Simple Decorators
   177  
   178  This approach takes inspiration from Weave's decorator design while trying to minimize the number of breaking changes to the SDK and maximizing simplicity. Like Weave decorators, this approach allows one `AnteDecorator` to wrap the next AnteHandler to do pre- and post-processing on the result. This is useful since decorators can do defer/cleanups after an AnteHandler returns as well as perform some setup beforehand. Unlike Weave decorators, these `AnteDecorator` functions can only wrap over the AnteHandler rather than the entire handler execution path. This is deliberate as we want decorators from different modules to perform authentication/validation on a `tx`. However, we do not want decorators being capable of wrapping and modifying the results of a `MsgHandler`.
   179  
   180  In addition, this approach will not break any core SDK API's. Since we preserve the notion of an AnteHandler and still set a single AnteHandler in baseapp, the decorator is simply an additional approach available for users that desire more customization. The API of modules (namely `x/auth`) may break with this approach, but the core API remains untouched.
   181  
   182  Allow Decorator interface that can be chained together to create an SDK AnteHandler.
   183  
   184  This allows users to choose between implementing an AnteHandler by themselves and setting it in the baseapp, or use the decorator pattern to chain their custom decorators with SDK provided decorators in the order they wish.
   185  
   186  ```go
   187  // An AnteDecorator wraps an AnteHandler, and can do pre- and post-processing on the next AnteHandler
   188  type AnteDecorator interface {
   189      AnteHandle(ctx Context, tx Tx, simulate bool, next AnteHandler) (newCtx Context, err error)
   190  }
   191  ```
   192  
   193  ```go
   194  // ChainAnteDecorators will recursively link all of the AnteDecorators in the chain and return a final AnteHandler function
   195  // This is done to preserve the ability to set a single AnteHandler function in the baseapp.
   196  func ChainAnteDecorators(chain ...AnteDecorator) AnteHandler {
   197      if len(chain) == 1 {
   198          return func(ctx Context, tx Tx, simulate bool) {
   199              chain[0].AnteHandle(ctx, tx, simulate, nil)
   200          }
   201      }
   202      return func(ctx Context, tx Tx, simulate bool) {
   203          chain[0].AnteHandle(ctx, tx, simulate, ChainAnteDecorators(chain[1:]))
   204      }
   205  }
   206  ```
   207  
   208  #### Example Code
   209  
   210  Define AnteDecorator functions
   211  
   212  ```go
   213  // Setup GasMeter, catch OutOfGasPanic and handle appropriately
   214  type SetUpContextDecorator struct{}
   215  
   216  func (sud SetUpContextDecorator) AnteHandle(ctx Context, tx Tx, simulate bool, next AnteHandler) (newCtx Context, err error) {
   217      ctx.GasMeter = NewGasMeter(tx.Gas)
   218  
   219      defer func() {
   220          // recover from OutOfGas panic and handle appropriately
   221      }
   222  
   223      return next(ctx, tx, simulate)
   224  }
   225  
   226  // Signature Verification decorator. Verify Signatures and move on
   227  type SigVerifyDecorator struct{}
   228  
   229  func (svd SigVerifyDecorator) AnteHandle(ctx Context, tx Tx, simulate bool, next AnteHandler) (newCtx Context, err error) {
   230      // verify sigs. Return error if invalid
   231  
   232      // call next antehandler if sigs ok
   233      return next(ctx, tx, simulate)
   234  }
   235  
   236  // User-defined Decorator. Can choose to pre- and post-process on AnteHandler
   237  type UserDefinedDecorator struct{
   238      // custom fields
   239  }
   240  
   241  func (udd UserDefinedDecorator) AnteHandle(ctx Context, tx Tx, simulate bool, next AnteHandler) (newCtx Context, err error) {
   242      // pre-processing logic
   243  
   244      ctx, err = next(ctx, tx, simulate)
   245  
   246      // post-processing logic
   247  }
   248  ```
   249  
   250  Link AnteDecorators to create a final AnteHandler. Set this AnteHandler in baseapp.
   251  
   252  ```go
   253  // Create final antehandler by chaining the decorators together
   254  antehandler := ChainAnteDecorators(NewSetUpContextDecorator(), NewSigVerifyDecorator(), NewUserDefinedDecorator())
   255  
   256  // Set chained Antehandler in the baseapp
   257  bapp.SetAnteHandler(antehandler)
   258  ```
   259  
   260  Pros:
   261  
   262  1. Allows one decorator to pre- and post-process the next AnteHandler, similar to the Weave design.
   263  2. Do not need to break baseapp API. Users can still set a single AnteHandler if they choose.
   264  
   265  Cons:
   266  
   267  1. Decorator pattern may have a deeply nested structure that is hard to understand, this is mitigated by having the decorator order explicitly listed in the `ChainAnteDecorators` function.
   268  2. Does not make use of the ModuleManager design. Since this is already being used for BeginBlocker/EndBlocker, this proposal seems unaligned with that design pattern.
   269  
   270  ## Status
   271  
   272  > Accepted Simple Decorators approach
   273  
   274  ## Consequences
   275  
   276  Since pros and cons are written for each approach, it is omitted from this section
   277  
   278  ## References
   279  
   280  - [#4572](https://github.com/cosmos/cosmos-sdk/issues/4572):  Modular AnteHandler Issue
   281  - [#4582](https://github.com/cosmos/cosmos-sdk/pull/4583): Initial Implementation of Per-Module AnteHandler Approach
   282  - [Weave Decorator Code](https://github.com/iov-one/weave/blob/master/handler.go#L35)
   283  - [Weave Design Videos](https://vimeo.com/showcase/6189877)