Skip to content

fix(exchange): reject int64 overflow in order cost and average price - #1341

Open
vipwzw wants to merge 1 commit into
masterfrom
fix-exchange-cost-overflow
Open

vipwzw wants to merge 1 commit into
masterfrom
fix-exchange-cost-overflow

Conversation

@vipwzw

@vipwzw vipwzw commented Oct 19, 2026

Copy link
Copy Markdown
Collaborator

问题

SafeMul 用 big.Int 计算后再 Int64() 截断,结果超出 int64 时静默回绕(可能变成一个小正数)且上层不感知。

攻击:挂一笔被动买单,Amount=28999941890838049、Price=1e16(均在 CheckAmount/CheckPrice 允许范围),名义成本约为 2.9e24,截断后恰好为 256,买单只冻结 256 个单位。taker 卖单卖出数量不小于该挂单数量时,matchModel 用 SafeMul(matched, 1e16, 1e8) 计算付款同样回绕成 256,卖方交出大量 token 只收到 0.00000256 枚。caclAVGPrice 也会同样截断,损坏订单均价/市场深度。

修复

  • SafeMul、caclAVGPrice 改为返回 (int64, error),!IsInt64() 时返回 ErrOverflow。
  • 新增 ForkFixSafeMulOverflow,在下单余额检查、撤单、未成交冻结、撮合付款、均价计算所有路径分叉后拒绝溢出;分叉前仍沿用旧的截断值,保证历史区块可重放。
  • 同步修改测试中的 CalcActualCost 调用,并新增 TestSafeMul 溢出用例。

验证

  • go build ./plugin/dapp/exchange/... 通过
  • go test ./plugin/dapp/exchange/executor/ -count=1 通过

SafeMul and caclAVGPrice compute with big.Int and then silently truncate the
result with Int64(). For a large amount/price combination the wrapped value can
be a small positive number, so a malicious passive buy order only freezes a
tiny amount and the matching engine pays the taker seller the wrapped value
while transferring the full token amount. The average price bookkeeping is
corrupted the same way.

- SafeMul/caclAVGPrice now return ErrOverflow when the result does not fit in
  int64.
- Order creation, frozen remainder, matching settlement and average-price
  updates reject the overflow behind ForkFixSafeMulOverflow.
- Pre-fork behavior is unchanged (the truncated value is still used) so the
  fix can be activated at a fork height.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant