限制与最佳实践

编写有效策略的安全限制和最佳实践

出于安全考虑,策略在受限环境中运行。本页面记录了不允许的操作,并提供了编写有效策略的最佳实践。

策略限制

策略长度限制为 2,048 个字符。这鼓励简洁、集中的规则,并确保快速的评估时间。


平台级限制

以下 RPC 方法在平台级别被阻止,任何策略都无法启用:

CategoryMethods
Debug & Tracedebug_*, trace_*
Legacy Filterseth_newFilter, eth_newBlockFilter, eth_newPendingTransactionFilter, eth_getFilterChanges, eth_getFilterLogs, eth_uninstallFilter

这些限制适用于所有请求,无论组织或端点策略如何。


eth_getLogs 限制

eth_getLogs 方法仅限于单区块查询。您必须指定以下之一:

  • block_hash:从特定区块哈希查询日志
  • block_number:从特定区块号查询日志(十六进制格式如 0x100 或标签如 latest

不支持使用 fromBlocktoBlock 的区块范围查询。此限制适用于 RPC 和 MCP 请求。


禁止的关键字

以下模式在策略中不允许使用:

PatternReason
import ...Cannot import external modules
package ...Cannot declare packages
default ...Cannot override default values
data.*Cannot reference external data

尝试使用这些模式的策略将无法通过验证。


禁用的内置函数

这些内置函数类别已禁用,将被拒绝

PatternError Message
http.send"http.send is disabled"
crypto.*"Crypto functions are disabled"
io.jwt.*"JWT functions are disabled"
yaml.*"YAML functions are disabled"
uuid.*"UUID functions are disabled"
glob.*"Glob functions are disabled"
semver.*"Semver functions are disabled"
json.schema*"JSON schema functions are disabled"
graphql.*"GraphQL functions are disabled"
net.cidr*"Net CIDR functions are disabled"
opa.runtime*"OPA runtime functions are disabled"
rego.metadata*"Rego metadata functions are disabled"

使用禁用的内置函数的策略将无法通过验证,并显示清晰的错误消息,指示不允许使用哪个函数。


验证错误

当策略验证失败时,您将收到如下错误:

ErrorCause
"Import statements are not allowed"Policy contains import
"Package declarations are not allowed"Policy contains package
"Default statements are not allowed"Policy contains default
"Data references are not allowed"Policy contains data.

当由于无效的 Rego 语法导致编译失败时,您将收到来自编译器的行号和错误消息。


最佳实践

小写地址

始终使用 lower() 进行不区分大小写的地址匹配:

# Good: Normalized comparison
deny if {
    lower(input.to_address) == "0xdead..."
}
 
# Bad: May miss matches due to case differences
deny if {
    input.to_address == "0xDead..."
}

处理可空字段

某些输入字段可以为 null。请妥善处理:

# Good: Check for null before comparison
deny if {
    input.usd_value != null
    input.usd_value > 10000
}
 
# Alternative: Use type checking
deny if {
    is_number(input.usd_value)
    input.usd_value > 10000
}

彻底测试

在将策略部署到生产环境之前:

  1. 使用各种输入组合进行测试
  2. 验证允许和拒绝的情况
  3. 检查边缘情况(null 值、空数组)
  4. 针对实际交易数据进行验证

记录您的规则

使用注释解释复杂的逻辑:

# Block high-value transactions during off-hours
# Business hours are 9 AM - 5 PM UTC, Monday-Friday
deny if {
    [hour, _, _] := time.clock(time.now_ns())
    hour < 9
    input.usd_value > 1000
}

使用有意义的变量名

使用局部变量时,选择描述性名称:

# Good: Clear variable names
deny if {
    high_risk_threshold := 10000
    input.usd_value > high_risk_threshold
}
 
# Avoid: Cryptic names
deny if {
    x := 10000
    input.usd_value > x
}
限制与最佳实践 | 256 Blocks