2023-30-10 Audit - Fee Abstraction Module by Notional
Security Audit Report
Fee Abstraction Module by Notional
Authors: Aleksandar Ljahovic, Ivan Golubovic
Last revised 30 October, 2023 © 2023 Informal Systems Fee Abstraction Module by Notional
Table of Contents Audit overview............................................................................................................. 1 The Project 1 Scope of this audit 1 Conducted work 1 Conclusions 1 Audit dashboard.......................................................................................................... 2 Target Summary 2 Engagement Summary 2 Severity Summary 2 System overview ......................................................................................................... 3 Introduction 3 Key design features 3 Conclusion 6 Threat inspection ........................................................................................................ 7 Threat Model Entry: Network Congestion and Transaction Failures in Fee Abstraction Module 7 Threat Model Entry: Fee Deduction and Transaction Validation in Customized AnteHandler 9 Threat Model Entry: Oracle (TWAP) Manipulation in Fee Abstraction Module 12 Threat Model Entry: Insufficient Liquidity in Osmosis Pools Affecting Fee Abstraction Module 14 Findings ..................................................................................................................... 16 Critical Risk of Non-Uniqueness in KVStore Keys 18 Outdated Exchange Rate Risk Due to Potential IBC Relayer Delays 20 Lack of Frozen Status Check in Cross-chain Swap Execution 22 Missing Frozen Host Zone Checks in AnteHandles 24 Unvalidated External Exchange Rate Data Usage 26 Unnecessary Host Zone Freezing Due to Lack of Granular Error Handling 28 Unspecified recovery address for Crosschain-swaps IBC transfer 30 Missing Fee Collector Account Check in abstractionDeductFeeHandler 32 Inaccurate Time Calculation for ICQ TWAP Request 34 Optimization Opportunities in KVStore Calls 37 Optimize Fee Calculation Process 39 © 2023 Informal Systems Fee Abstraction Module by Notional
Minor Code Improvements 41 Code Quality and Naming Improvements 45 Appendix: Vulnerability Classification ..................................................................... 47 Impact Score 47 Exploitability Score 47 Severity Score 48 Disclaimer.................................................................................................................. 50 © 2023 Informal Systems Fee Abstraction Module by Notional
Audit overview The Project In collaboration with Osmosis team, Notional developed Fee Abstraction Module as a tool available to other chains to facilitate transaction fee payments in IBC tokens. This module can be integrated to a chain, and this chain then communicated with Osmosis chain to be able to obtain all the required data to make IBC tokens eligible for fee payments. The core mechanism of the module derives the exchange rate (Time-Weighted Average Price or TWAP) from Osmosis, facilitating the conversion of IBC tokens to native tokens for fee calculation. To kickstart this operation, the module is endowed with a foundational token fund. Moreover, it leverages Osmosis' smart contracts to exchange its accumulated IBC tokens for native tokens, replenishing the token pool needed for fee transactions.
A crucial aspect of this project was the customization of AnteHandle functions, which play an important role in the transaction validation process. Additionally, IBC transfers are identified as valuable components for the seamless operation of this module. Through this audit, we inspected the Fee Abstraction Module, aiming to ensure its robustness, accuracy, and security in handling transaction fees, while enabling interaction with the Osmosis chain.
Scope of this audit The audit was scheduled from October 2, 2023, to October 27, 2023. The audit team consisted of the following personnel: • Aleksandar Ljahovic • Ivan Golubovic
Conducted work The audit project encompassed the following activities: • Manual code inspection of the Fee Abstraction Module. We conducted a thorough examination of the codebase, documenting our insights in the "System Overview" section. The manual code inspection revealed the majority of the findings presented in this report. • Thread modeling and inspection is documented in “Threat Inspection” chapter, giving the detailed insight in conducted work, identified threats and code snippets of interest etc. • Where possible, we attempted to reproduce the findings using end-to-end test suite, as well as try to use the environment to test edge cases.
Conclusions Overall, we found the codebase to exhibit quality, characterized by well-structured and comprehensible code. The comprehensive test suite includes unit, and valuable end-to-end testing environment. During the audit, we identified 1 critical, 4 high and 2 medium severity findings, while others were of low and informational severity. Our collaboration with the Osmosis/Notional team was exemplary, significantly enhancing the quality of work executed within the audit's timeframe.
Audit overview 1 © 2023 Informal Systems Fee Abstraction Module by Notional
Audit dashboard Target Summary • Type: Specification and Implementation • Platform: Go • Artifacts: • Commit hash: 3ef7b78d034d93632fa363519da9b77ff59c9805
Engagement Summary • Dates: 02.10.2023. to 27.10.2023 • Method: Manual code review, protocol analysis, design analysis, testing • Employees Engaged: 2
Severity Summary Finding Severity #
Critical 1
High 4
Medium 2
Low 2
Informational 4
Total 13
Audit dashboard 2 © 2023 Informal Systems Fee Abstraction Module by Notional
System overview Introduction In this audit, we are evaluating the implementation and security of the Fee Abstraction Module developed by the Notional team for the Cosmos ecosystem, specifically in conjunction with the Osmosis decentralized exchange. This module is designed to offer unique functionalities that enhance the flexibility of transaction fee payments through the innovative use of Inter-Blockchain Communication (IBC) tokens. Fee Abstraction Module empowers customer chains to execute fee payments using any IBC token available on Osmosis. The ibc tokens are exchanged for the native tokens held in module’s account. This is achieved by integrating oracle Time-Weighted Average Price (TWAP) data from Osmosis, ensuring real-time and accurate conversion rates. Users on customer chains that integrate this module can pay transaction fees in IBC tokens, with the conversion rates determined by Osmosis’ TWAP oracles. The second feature of the module, on the other hand, utilizes packet forward middleware and Crosschain Swaps smart contract to enable an automated process where accumulated fees in IBC tokens are swapped for the native tokens using Osmosis. This not only simplifies the fee collection process for the customer chains but also potentially boosts the trading volume on Osmosis, given the automated token swap mechanism. This audit will provide a comprehensive analysis of the Fee Abstraction Module’s security, efficiency, and operational integrity. We will evaluate the technical implementation, the reliability of the TWAP data integration, the effectiveness of the cross-chain token swapping, and the overall impact on the transaction fee payment ecosystem within the Cosmos network. Each aspect will be scrutinized to ensure that the module not only enhances transaction fee payment flexibility but also adheres to the highest standards of security and efficiency.
Key design features
Decorators One of the key design approaches here is the customization of MempoolFeeDecorator . More precisely, decorators are used to modify the AnteHandler, a crucial component in the Cosmos SDK that handles the processing of transaction fees. The decorators, specifically FeeAbstractionDeductFeeDecorate and FeeAbstrationMempoolFeeDecorator , are customized to facilitate fee payment using IBC tokens.
FeeAbstractionDeductFeeDecorate This decorator is responsible for handling the deduction of transaction fees. It is initialized with keepers for account, bank, fee abstraction, and fee grant. The AnteHandle function is the core, checking if the transaction is a FeeTx and then proceeding to handle the fee deduction based on the transaction's characteristics.
• If the transaction does not involve IBC tokens or the host chain configuration is not set for the fee's denomination, it calls the normalDeductFeeAnteHandle method. This method deducts the fee from the fee payer or fee granter's account and ensures that the fee collector module account is set. • If the transaction involves IBC tokens and the host chain configuration is set, it calls the abstractionDeductFeeHandler method. This method calculates the equivalent native tokens from IBC tokens and deducts the fees accordingly.
System overview 3 © 2023 Informal Systems Fee Abstraction Module by Notional
FeeAbstrationMempoolFeeDecorator This decorator checks if the transaction's fee meets the local validator's minimum gas fee during the transaction's inclusion in the mempool. It ensures that the fee is sufficient, and if not, the transaction is rejected from the mempool. • It calculates the required fee based on the transaction's gas limit and the minimum gas prices. If the fee is insufficient, an error is returned, and the transaction is not processed. • Special conditions like bypassing the minimum fee requirement or handling global fees are also considered. Transactions that meet these conditions are processed without the minimum fee check. These two customizations are illutrated in the following diagram:
Epochs and IBC In the context of the fee abstraction module, Inter-Blockchain Communication (IBC) and epochs are combined to facilitate automated interactions with the Osmosis chain for querying TWAP and executing cross-chain swaps. This is achieved using epoch mechanism, which triggers specific IBC operations at the end of each epoch.
The AfterEpochEnd function serves as the routing point where epochs and IBC intersect. At the end of each epoch, identified by the epoch identifier, this function is invoked to initiate either a TWAP query or a cross-chain swap on the Osmosis chain.
TWAP Query
The executeAllHostChainTWAPQuery function is called, which internally invokes the handleOsmosisIbcQuery function to manage the IBC query to Osmosis. This ensures that the TWAP is queried from the Osmosis chain at the end of each specific epoch, facilitating real-time and automated retrieval of TWAP data.
Cross-Chain Swap To be able to support these ibc token paid transactions, the fee abstraction module has a designated account to store native tokens. Initial fund is needed after the launch, but the swapping using Osmosis liquidity pools is the mechanism to keep this account in operation.
System overview 4 © 2023 Informal Systems Fee Abstraction Module by Notional
For the swap, the executeAllHostChainSwap function is invoked, iterating through all host zones and executing the swap over the chain. This automated process ensures that cross-chain swaps are performed at the end of each designated epoch, enabling automated liquidity management and token swaps between chains. Osmosis’ specific Crosschain Swaps and Swaprouter smart contract are utilized to perform this operation.
Transactions through ABCI functions. The diagram below shows the processes that are called in the ABCI functions (CheckTx, BeginBlock, DeliverTx) in the fee abstraction module. It shows the calls to KVStores and the initiation of sending packages via IBC:
System overview 5 © 2023 Informal Systems Fee Abstraction Module by Notional
Conclusion This system ensures that users on the Cosmos network can seamlessly pay transaction fees using IBC tokens. By leveraging the Osmosis chain for real-time exchange rates and token swaps, the system is both user-friendly and adaptable to future changes and improvements. The use of decorators and the IBCModule ensures that the process is secure, efficient, and seamless for all users.
System overview 6 © 2023 Informal Systems Fee Abstraction Module by Notional
Threat inspection Threat Model Entry: Network Congestion and Transaction Failures in Fee Abstraction Module
System Component: IBC Communication and Transaction Processing
Description: The Fee Abstraction Module in the Cosmos ecosystem is heavily reliant on Inter-Blockchain Communication (IBC) for various operations, including querying TWAP prices from Osmosis, performing token swaps, and unwinding IBC denoms. Network congestion or relayer failures could lead to delayed or failed transactions, impacting the module's ability to calculate fees or perform swaps efficiently.
Potential Threat: Network congestion or a halt in the relayer's operation could lead to a backlog of transactions, resulting in delayed or failed transactions. This could impact users attempting to pay fees with IBC tokens, leading to transaction failures or significant delays, affecting the overall user experience and system performance.
Attack Vector: • Network Congestion: An unusually high volume of transactions could overload the network, leading to delayed processing of transactions related to fee payments in IBC tokens. • Relayer Halt: If the relayer stops functioning, IBC transactions could be stuck, leading to failed or delayed transactions. • Failed Transactions: In scenarios of network congestion or relayer halts, transactions could fail, and it needs to be inspected if recovery systems are in place to handle such scenarios.
Code to Focus on for this Threat:
- Sending Interchain Query: _, err := k.SendInterchainQuery(ctx, icqReqs, sourcePort, sourceChannel) • Observation: The module sends interchain queries to Osmosis. The handling of errors and the efficiency of this process during network congestion should be inspected.
- Handling Acknowledgement Packet: func (k Keeper) OnAcknowledgementPacket(ctx sdk.Context, ack channeltypes.Acknowledgement, icqReqs []abci.RequestQuery) error • Observation: The handling of acknowledgements and errors is crucial. The system’s response to errors and its ability to recover or retry transactions should be evaluated.
- Timeout Handling: func (k Keeper) OnTimeoutPacket(ctx sdk.Context) error • Observation: The system's response to timeouts is essential, especially during network congestion. The mechanism to retry or handle timed-out transactions should be robust.
- IBC Token Transfer: func (k Keeper) transferOsmosisCrosschainSwap(ctx sdk.Context, hostChainConfig types.HostChainFeeAbsConfig) error • Observation: The transfer of IBC tokens, especially during the swap process, should be efficient and error-resistant to ensure that network congestion doesn’t lead to failed swaps.
Threat inspection 7 © 2023 Informal Systems Fee Abstraction Module by Notional
Important Requirements: • The system should be equipped to handle a high volume of transactions efficiently to mitigate the impact of network congestion. • The error handling and recovery mechanisms should be robust to ensure that the system can recover from failed transactions or timeouts effectively. • The use of Interchain Queries from Strangelove should be evaluated to understand its efficiency and reliability during network congestion.
Example of Impact: In a scenario where the network is congested, users attempting to pay transaction fees with IBC tokens could experience significant delays or transaction failures. This could lead to a poor user experience and could potentially impact the integrity of the transaction processing system if not handled efficiently. The system's ability to recover from such scenarios, handle transaction timeouts, and process a backlog of transactions efficiently is crucial to mitigate the impact of this threat.
Threat Inspection Results: The Fee Abstraction Module's dependency on Inter-Blockchain Communication (IBC) for various operations, particularly interchain queries and cross-chain swaps on the Osmosis chain, was closely examined. The inspection primarily focused on the code contained in ibc.go , with special attention given to the OnAcknowledgementPacket and OnTimeoutPacket functions, alongside the helper functions invoked from them, namely handleOsmosisIbcQuery and transferOsmosisCrosschainSwap .
Cross-Chain Swaps Execution: The code leverages built-in IBC features and Osmosis' smart contract designs (Crosschain Swaps and Swap Router) for handling errors and timeouts during cross-chain swaps. Specifically, the executeTransferMsg function relies on the built-in transferKeeper to facilitate the token transfer over IBC.
func (k Keeper) executeTransferMsg(ctx sdk.Context, transferMsg *transfertypes.MsgTransfer) (*transfertypes.MsgTransferResponse, error) { if err := transferMsg.ValidateBasic(); err != nil { return nil, fmt.Errorf("bad msg %v", err.Error()) } return k.transferKeeper.Transfer(sdk.WrapSDKContext(ctx), transferMsg) }
This mechanism appears sufficiently robust to mitigate the potential threats of network congestion, relayer halts, and transaction failures as outlined in the threat model.
Interchain Queries Execution: The handling of interchain queries exhibits a higher level of customization, particularly within the OnAcknowledgementPacket and OnTimeoutPacket functions. The code contained is considered less successful in handling network congestion or delayed transactions.
func (k Keeper) OnAcknowledgementPacket(ctx sdk.Context, ack channeltypes.Acknowledgement, icqReqs []abci.RequestQuery) error { // ... case *channeltypes.Acknowledgement_Error:
Threat inspection 8 © 2023 Informal Systems Fee Abstraction Module by Notional
k.IterateHostZone(ctx, func(hostZoneConfig types.HostChainFeeAbsConfig) (stop bool) { err := k.FrozenHostZoneByIBCDenom(ctx, hostZoneConfig.IbcDenom) // ... }) // ... }
In the event of an error acknowledgment, the current implementation opts to freeze all host zones, which could lead to an entire feature shutdown due to an error in a single host zone. This approach may not be the most optimal for ensuring system resilience in the face of network congestion or relayer reliability issues concerning timely transfer deliveries.
Dependency on External Systems: The dependency of the external system (TWAP from Osmosis) has to be better handled in case of timed out transfers as described in one of the findings. The value obtained from Osmosis (exchange rate) is used in token amount calculations which makes it particularly important to keep it up to date. Outdated values could lead to serious consequences for the user or the system itself. The findings that came out of this threat inspection are:
- Outdated Exchange Rate Risk Due to Potential IBC Relayer Delays
- Unnecessary Host Zone Freezing Due to Lack of Granular Error Handling
Threat Model Entry: Fee Deduction and Transaction Validation in Customized AnteHandler
System Component: Customized AnteHandler for Transaction Pre-processing
Description: The customized AnteHandler in the Fee Abstraction Module is a critical component within the Cosmos ecosystem. It is responsible for the pre-processing of transactions before they enter the mempool, focusing on transactions paid with IBC tokens. The AnteHandler inspects transactions to ensure they meet the minimum fee requirements and calculates the appropriate fees using the Osmosis price oracle.
Potential Threat: There could be vulnerabilities in the transaction inspection process, allowing invalid transactions to pass through or enabling front-running attacks. Errors in fee deduction, especially in the conversion and calculation of fees paid with IBC tokens, could lead to incorrect fee deductions, impacting the network's financial integrity.
Attack Vector:
- Transaction Inspection Weaknesses: Flaws in the transaction inspection process that might allow invalid transactions to pass or be susceptible to front-running attacks.
- Fee Deduction
Excerpt (19999 of 87676 characters). Read the whole page on informalsystems/audits ↗