Resources

People often ask me "How did you learn how to hack?" The answer: by reading. This page is a collection of the blog posts and other articles that I have accumulated over the years of my journey. Enjoy!

Issues in Certain Forks of Gains Network- 1398

ZellicPosted 1 Year Ago
  • Gains is a leverage-trading platform. In particular, users can provide small amount of funds yet still gain high exposure to a given asset. The leverage portion allows for gains or losses of multiple times. There are two special types of orders: stop loss and take profit. Stop loss will remove the current position after an X% decrease in price while the take profit will cash out once a specific price point has been hit.
  • On Gains, regardless if it's a long or short, there are three types of orders:
    • Market: Open a trade immediately.
    • Limit: Go long on a lower price than present or reversed for short.
    • Stop Limit: Go long on a higher price than present or reversed for short.
  • The trade struct has several fields, including tp for take-profit and sl for stop loss profit. If the price was 1K with a 5x leverage and the SL was 900 with a price below that, then the return would be -50. All of this is standard to the protocol.
  • In the function that does the calculations above, there is some logic for figuring out payouts which deals with negative numbers. If the field t.openPrice is t.sl, then the current pricing model breaks. As a result, if the token drops on a long then we'd gain unintended profit. By setting up parameters for the trade in a very specific way, including specific order types, it was possible to trigger this condition.
  • After finding this bug they kept looking and found another one! The function _currentPercentProfit casts currentPrice (which is included by end users) from an unsigned integer to a signed integer. By specifying the price to be extremely large, it would underflow to a negative value! Since we're dealing with shorts and longs, it was
  • After doing both of these tricks, the position could be immediately closed for a 900% profit. Crazily enough, the profit didn't depend on the movement of the token because of the confusion between the different types.
  • To fix both of the bugs, an invariant check no sl/tp to be within the proper bounds was done. I'm hopeful they introduced more patches than just invariant checks but invariant checks are amazing for killing exploit paths like this one.
  • With my inexperience with leveraged trading and the Gains network logic, I found the first bug to understand. However, it seems like it was just a logic flaw that broke an invariant of the protocol. To me, it was interesting to see can we make the value greater than this other value because it would be bad which led them to the bugs in the end. Good finds!