---
lang: zh-tw
tags: NTHU, Notes, Cryptocurrency
date: 20210308
robots: noindex, nofollow
license: GPL-3.0
---
Oracles (Uniswap V2)
===
- Reference:https://uniswap.org/docs/v2/core-concepts/oracles/
Introduction
---
- A price oracle is any **tool** used to **view price information** about a given asset.
- 許多基於 Ethereum 的專案,其 price oracle 都是特別訂製的,所以很多駭客以思考如何攻擊 price oracle 當起手式
- 相關討論:https://samczsun.com/taking-undercollateralized-loans-for-fun-and-for-profit/
- Uniswap V2 希望可以創造出高度去中心化、可抵抗被惡意操弄的 price oracle
Uniswap V2 Solution (本文主軸)
---
- Uniswap V2 採用許多改進方法來創造可抵抗被惡意操弄 price oracle
1. 在開始任何交易之前,先「測量」(measure) 每個貨幣對 (pair) 的市場價格
- 測量代表只是暫訂的價格,不一定等於最後執行 contract 用到的價格
- 如此一來
- 該「測量價格」來自於前一個 block 的 last TX (new block 尚未生成,市場流通的價格即來自 previous block)
- 駭客操弄價格的成本很高
- 駭客無法利用 flash loan 在同一個 block 內操弄價格,攻擊失敗就 reverse TX 回來
- 駭客首先要在 previous block 的 last TX 做很虧錢的交易以偏離市場正常價格,緊接著必須在下一個 block 趕緊完成攻擊&做反向交易沖掉先前的損失
- 以上方法唯一的可能就是駭客必須同時挖兩個 block,目前尚未觀察到此種攻擊
2. Time-Weighted Average Price (TWAP)
- 計算 Cumulative Price (CP):Uniswap V2 把 block end 的 price 乘以其存續時間秒數 (i.e., 直到下一個 new block 生成前時間長度) 進行連續累加,詳細見下圖
<img src="https://i.imgur.com/fRoZfj4.jpg" width="500"/>
- 計算 Time-Weighted Average Price:透過「讀取」一個所需時間區間的 CP 之後,把頭尾的 CP 相減再除以流逝的時間總長度,就等於 TWAP
<img src="https://uniswap.org/static/f134d0d4763a11354a400c3c944aecad/c6f3b/v2_twap.png" width="500"/>
- TWAP 可以直接拿來用,或是當作稍後計算 moving average 的資料來源
- 其他注意事項
- For a 10-minute TWAP, sample once every 10 minutes. For a 1-week TWAP, sample once every week.
- For a simple TWAP, the cost of manipulation increases (approx. linear) with liquidity on Uniswap, as well as (approx. linear) with the length of time over which you average.
- The Cost of an attack is relatively simple to estimate. Moving the price 5% on a 1-hour TWAP is approximately equal to the amount lost to arbitrage and fees for moving the price 5% every block for 1 hour.
- 如果要拿 Uniswap V2 當作 price oracle 還需要注意一些小細節,請見:https://uniswap.org/whitepaper.pdf
- Uniswap V2 24H TWAP 程式範例:https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/examples/ExampleOracleSimple.sol
Manipulation Resistance
---
- 惡意操弄價格的攻擊成本,可以粗估為:在指定時間內,每一個 block 的套利損失和手續費的總和
> The cost of manipulating the price for a specific time period can be roughly estimated as the amount lost to arbitrage and fees every block for the entire period.
- 對於流動性很大的交易池來說,發動攻擊會非常不切實際
- 關於更多 Uniswap V2 price oracle 的安全議題
- https://uniswap.org/audit.html#org87c8b91
如何建造基於 Uniswap V2 的 Price Oracle
---
- https://uniswap.org/docs/v2/smart-contract-integration/building-an-oracle/
- 一些實作的細節與注意事項,跟原理比較沒關係