智能合约与以太坊 / 系统课时

校验预言机报价的时效和精度

校验预言机报价的时效和精度

智能合约读取到的预言机价格不一定可以直接用于清算、借贷或兑换。本课使用 Solidity 实现一套报价校验逻辑,检查时间戳、价格正值和小数精度,再用 Foundry 模拟过期、零值、负值及未来时间戳,验证异常报价能否被正确拒绝。

学习目标

  • 理解 latestRoundData() 的返回字段及报价过期判定方法。
  • 实现正值、时间戳和 decimals 校验,并将价格统一为 18 位精度。
  • 使用 Foundry 编写正常报价与异常报价测试,确认拒绝行为。

识别预言机报价中的风险字段

以 Chainlink Data Feeds 的 AggregatorV3Interface 为例,latestRoundData() 返回五个字段:

字段 类型 安全检查重点
roundId uint80 报价轮次标识
answer int256 必须大于 0
startedAt uint256 本轮开始时间,通常不用于新鲜度判定
updatedAt uint256 必须有效、不能来自未来、不能过期
answeredInRound uint80 兼容字段,现代 Chainlink 接口中已弃用其历史轮次语义

报价的单位由 decimals() 决定。例如 ETH/USD 报价为 2500 美元,且返回精度为 8,则原始 answer 为 250000000000。

不能直接把这个整数作为 18 位精度的美元价格,否则会发生数量级错误。还必须检查报价的计价方向,例如 ETH/USD 与 USD/ETH 不能互换使用。

时间戳边界

假设当前区块时间戳为 1800000000,业务允许报价最大年龄为 3600 秒。

updatedAt 年龄 结果
1799999940 60 秒 允许
1799996400 3600 秒 允许,恰好达到边界
1799996399 3601 秒 拒绝,报价过期
0 无有效更新时间 拒绝
1800000001 来自未来 拒绝

判断顺序不能颠倒。先拒绝 updatedAt == 0 和未来时间戳,再计算 block.timestamp - updatedAt,可避免异常数据导致减法下溢。

编写安全报价读取合约

下面使用 Solidity 0.8.24 和 Chainlink AggregatorV3Interface 的标准接口签名。示例将返回价格统一放大到 18 位小数,同时拒绝不符合预期的精度。

在 Foundry 项目的 src/SafePriceReader.sol 中编写完整代码:

solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

interface AggregatorV3Interface {
    function decimals() external view returns (uint8);

    function latestRoundData() external view returns (
        uint80 roundId,
        int256 answer,
        uint256 startedAt,
        uint256 updatedAt,
        uint80 answeredInRound
    );
}

contract SafePriceReader {
    AggregatorV3Interface public immutable feed;
    uint256 public immutable maxAge;
    uint8 public immutable feedDecimals;

    error InvalidConfig();
    error InvalidPrice();
    error InvalidTimestamp();
    error StalePrice();
    error InvalidDecimals();

    constructor(address feedAddress, uint256 age) {
        if (feedAddress == address(0) || age == 0) {
            revert InvalidConfig();
        }

        feed = AggregatorV3Interface(feedAddress);
        maxAge = age;

        uint8 decimalsValue = feed.decimals();
        if (decimalsValue > 18) revert InvalidDecimals();
        feedDecimals = decimalsValue;
    }

    function getPrice18() external view returns (uint256) {
        (, int256 answer, , uint256 updatedAt, ) =
            feed.latestRoundData();

        // 必须先排除无效及未来时间戳,再计算数据年龄。
        if (updatedAt == 0 || updatedAt > block.timestamp) {
            revert InvalidTimestamp();
        }
        if (block.timestamp - updatedAt > maxAge) {
            revert StalePrice();
        }
        if (answer <= 0) revert InvalidPrice();

        // 检测报价源在部署后发生的小数位变化。
        if (feed.decimals() != feedDecimals) {
            revert InvalidDecimals();
        }

        uint256 scale = 10 ** uint256(18 - feedDecimals);
        uint256 price = uint256(answer);
        if (price > type(uint256).max / scale) {
            revert InvalidPrice();
        }
        return price * scale;
    }
}

这段实现具有几个明确的边界:

  1. age 必须大于 0,避免错误配置成仅接受与当前区块同一秒更新的价格。
  2. answer 是有符号整数,因此先判断正值,再转换成 uint256。
  3. feedDecimals 在部署时记录,读取时再次检查,防止代理升级后精度变化被静默忽略。
  4. 只支持 decimals <= 18 的报价源,避免不受控的除法截断;需要更高精度时应另外设计缩放规则。
  5. 缩放乘法前检查溢出,确保即使报价源返回极大整数也会明确拒绝。

预期结果:当 answer = 250000000000、decimals = 8 且时间戳有效时,getPrice18() 返回 2500000000000000000000,表示采用 18 位精度的 2500。异常报价将以对应自定义错误回滚。

使用 Foundry 验证拒绝行为

下面用 Mock 模拟预言机,测试无需依赖真实 RPC 或链上报价变化。测试环境为 Solidity 0.8.24,并要求 Foundry 工程已有 forge-std 依赖。

创建 test/SafePriceReader.t.sol,代码中的 Mock 实现与生产接口具有相同的调用签名。

solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {Test} from "forge-std/Test.sol";
import {SafePriceReader} from "../src/SafePriceReader.sol";

contract MockFeed {
    int256 public answer;
    uint256 public updatedAt;
    uint8 public decimalsValue = 8;

    function setData(int256 price, uint256 timestamp) external {
        answer = price;
        updatedAt = timestamp;
    }

    function setDecimals(uint8 value) external {
        decimalsValue = value;
    }

    function decimals() external view returns (uint8) {
        return decimalsValue;
    }

    function latestRoundData() external view returns (
        uint80, int256, uint256, uint256, uint80
    ) {
        return (1, answer, updatedAt, updatedAt, 1);
    }
}

contract SafePriceReaderTest is Test {
    MockFeed feed;
    SafePriceReader reader;

    function setUp() public {
        vm.warp(1_800_000_000);
        feed = new MockFeed();
        reader = new SafePriceReader(address(feed), 3600);
    }

    function testValidPrice() public {
        feed.setData(2500 * 1e8, block.timestamp - 60);
        assertEq(reader.getPrice18(), 2500 * 1e18);
    }

    function testExactlyMaxAge() public {
        feed.setData(2500 * 1e8, block.timestamp - 3600);
        assertEq(reader.getPrice18(), 2500 * 1e18);
    }

    function testStalePrice() public {
        feed.setData(2500 * 1e8, block.timestamp - 3601);
        vm.expectRevert(SafePriceReader.StalePrice.selector);
        reader.getPrice18();
    }

    function testZeroTimestamp() public {
        feed.setData(2500 * 1e8, 0);
        vm.expectRevert(SafePriceReader.InvalidTimestamp.selector);
        reader.getPrice18();
    }

    function testFutureTimestamp() public {
        feed.setData(2500 * 1e8, block.timestamp + 1);
        vm.expectRevert(SafePriceReader.InvalidTimestamp.selector);
        reader.getPrice18();
    }

    function testZeroPrice() public {
        feed.setData(0, block.timestamp);
        vm.expectRevert(SafePriceReader.InvalidPrice.selector);
        reader.getPrice18();
    }

    function testNegativePrice() public {
        feed.setData(-1, block.timestamp);
        vm.expectRevert(SafePriceReader.InvalidPrice.selector);
        reader.getPrice18();
    }

    function testDecimalsChanged() public {
        feed.setData(2500 * 1e8, block.timestamp);
        feed.setDecimals(18);
        vm.expectRevert(SafePriceReader.InvalidDecimals.selector);
        reader.getPrice18();
    }

    function testUnsupportedDecimals() public {
        feed.setDecimals(19);
        vm.expectRevert(SafePriceReader.InvalidDecimals.selector);
        new SafePriceReader(address(feed), 3600);
    }
}

测试通过 vm.warp() 固定区块时间,通过 vm.expectRevert() 精确验证自定义错误。特别注意:预期回滚本身就是测试成功的条件,不表示用例失败。

在 Foundry 项目根目录运行:

bash
forge test --match-contract SafePriceReaderTest

预期输出(展示汇总,实际耗时和 Gas 数值因环境而异):

text
Ran 9 tests for test/SafePriceReader.t.sol:SafePriceReaderTest
[PASS] testDecimalsChanged()
[PASS] testExactlyMaxAge()
[PASS] testFutureTimestamp()
[PASS] testNegativePrice()
[PASS] testStalePrice()
[PASS] testUnsupportedDecimals()
[PASS] testValidPrice()
[PASS] testZeroPrice()
[PASS] testZeroTimestamp()
Suite result: ok. 9 passed; 0 failed

如果出现编译错误,应首先检查 src/SafePriceReader.sol 是否存在、Solidity 编译版本是否兼容,以及 forge-std 是否已正确安装。预期结果是全部九个测试通过,而不是仅观察到合约可以编译。

设置真实业务中的有效期和精度

通过单元测试并不意味着任意报价源都可以直接接入。部署前还需要为具体资产与网络建立配置清单。

假设某个报价源经查证使用 8 位小数、heartbeat 为 3600 秒,业务决定额外容忍 300 秒延迟,可以把 maxAge 配置为 3900 秒。这个数值仅是配置计算示例,应当结合实际预言机文档和业务可接受的最大数据延迟确定。

检查项 示例配置或条件 不满足时的动作
报价源地址 经验证的目标链代理合约地址 禁止部署或暂停使用
资产与方向 ETH/USD,以 USD 计价 拒绝错误资产对
maxAge 3900 秒(示例) 超时回滚
answer 大于 0 回滚
decimals 部署时与读取时一致,且不大于 18 回滚
updatedAt 大于 0 且不晚于当前区块时间 回滚

另外需要注意:updatedAt 新鲜并不必然意味着价格合理。例如极端行情下,报价仍可能与特定交易市场存在明显偏差。对于抵押借贷或自动清算,应在此基础上增加价格上下界、市场偏差检测或暂停机制。

不要在主预言机过期时无条件复用缓存旧价,也不要直接把另一个不同计价单位的报价源作为替代。降级方案必须分别验证资产对、精度、时效与安全边界。

审计时如何检查这段逻辑

审计同类报价读取代码时,可以按下面的顺序核查:

  1. 搜索所有 latestRoundData() 调用位置,确认没有遗漏直接消费 answer 的路径。
  2. 检查是否验证 answer > 0,尤其关注有符号整数到无符号整数的转换时机。
  3. 检查 updatedAt 是否排除了零值、未来值以及超过 maxAge 的值。
  4. 检查所有精度转换,确认乘法、除法、溢出和舍入规则符合业务要求。
  5. 核对每个预言机的实际资产对、网络、heartbeat 和代理配置,不要默认所有报价都是 8 位小数。
  6. 检查异常报价是否阻止后续敏感业务操作,而不是仅记录错误后继续清算或借款。

一个典型高危错误是先把未经检查的 answer 用于计算抵押物价值,之后才检查报价是否过期。此时如果后续出现不安全的外部调用或状态更新,风险可能已经进入业务流程。正确做法是在计算和状态变更之前完成报价验证,并让不合格报价导致整个调用回滚。

对于不同的 Chainlink 数据源,还应区分标准 Data Feeds 与其他产品的返回语义,不要把本示例的时间戳规则机械应用到所有预言机。标准接口的字段定义可参照 Chainlink Data Feeds API Reference,报价更新策略可参照 Data Feeds Overview。

当正常报价、过期边界、时间戳异常、非正价格和精度变化均有自动化测试覆盖后,这个价格读取模块才具备可重复检查的基本安全行为。

按自己的节奏,确认真正理解。

目录与阅读设置

阅读设置

17

记录一个想法

校验预言机报价的时效和精度

0 / 10000 · 笔记保存到账号。未提交的修改会在关闭、离开或刷新后丢失。

登录哪都通