内置函数
策略中所有可用内置函数的完整参考
策略中仅启用以下内置函数。出于安全原因,此处未列出的函数被禁用。有关禁用函数的详细信息,请参阅限制。
字符串函数
用于操作和检查字符串值的函数。处理地址、方法名称和其他文本字段时必不可少。
contains
检查字符串是否包含子字符串。如果找到则返回 true,否则返回 false。
示例
# Block any method containing "sign"
deny if {
contains(input.rpc_method, "sign")
}startswith
检查字符串是否以前缀开头。用于匹配方法类别或地址模式。
示例
# Block debug methods
deny if {
startswith(input.rpc_method, "debug_")
}
# Block addresses starting with many zeros
deny if {
startswith(input.to_address, "0x00000000")
}endswith
检查字符串是否以后缀结尾。
示例
# Block addresses ending with specific pattern
deny if {
endswith(lower(input.to_address), "dead")
}lower
将字符串转换为小写。由于地址可能有混合大小写,这对于不区分大小写的地址比较至关重要。
示例
# Case-insensitive address check
blocked_addresses := {
"0x000000000000000000000000000000000000dead"
}
deny if {
lower(input.to_address) in blocked_addresses
}upper
将字符串转换为大写。
示例
# Normalize method names that might have inconsistent casing
deny if {
upper(input.rpc_method) == "ETH_SENDTRANSACTION"
input.usd_value > 10000
}concat
使用分隔符连接字符串数组。
示例
# Join values for logging or comparison
message := concat(", ", ["chain:", input.chain, "method:", input.rpc_method])split
使用分隔符将字符串拆分为数组。
示例
# Parse a method name
parts := split(input.rpc_method, "_")
deny if {
parts[0] == "debug"
}replace
将所有出现的子字符串替换为另一个字符串。
示例
# Normalize address format
normalized := replace(input.to_address, "0X", "0x")substring
通过起始位置和长度提取字符串的一部分。
示例
# Get method prefix (first 4 characters after "eth_")
deny if {
startswith(input.rpc_method, "eth_")
method_action := substring(input.rpc_method, 4, 4)
method_action == "send"
}sprintf
使用占位符格式化字符串。用于创建动态值。
| Placeholder | Type |
|---|---|
%s | String |
%d | Integer |
%f | Float |
%v | Any value |
示例
# Create formatted message
threshold := 10000
message := sprintf("Value %d exceeds limit of %d", [input.usd_value, threshold])trim
从字符串两端删除指定的字符。
示例
# Remove specific characters from both ends
cleaned := trim(input.rpc_method, "_")trim_space
从字符串两端删除空格。
示例
# Clean up input with extra spaces
clean_method := trim_space(input.rpc_method)trim_prefix
如果存在,则从字符串中删除前缀。
示例
# Remove common prefix to get the action name
method_name := trim_prefix(input.rpc_method, "eth_")
deny if {
method_name == "sendTransaction"
}trim_suffix
如果存在,则从字符串中删除后缀。
示例
# Remove suffix for comparison
base_method := trim_suffix(input.rpc_method, "_v2")indexof
查找子字符串首次出现的索引。如果未找到则返回 -1。
示例
# Check if underscore exists
deny if {
indexof(input.rpc_method, "_") == -1
}正则表达式函数
使用正则表达式进行模式匹配的函数。对于复杂模式,比字符串函数更强大。
regex.match
检查字符串是否匹配正则表达式模式。返回 true 或 false。
示例
# Block methods starting with debug_, admin_, or personal_
deny if {
regex.match("^(debug_|admin_|personal_)", input.rpc_method)
}
# Block addresses with many leading zeros
deny if {
regex.match("^0x0{10,}", input.to_address)
}regex.replace
将模式的所有匹配项替换为替换字符串。
示例
# Remove all non-alphanumeric characters
cleaned := regex.replace(input.rpc_method, "[^a-zA-Z0-9]", "")regex.split
通过正则表达式模式拆分字符串。
示例
# Split by multiple delimiters
parts := regex.split("[_.]", input.rpc_method)regex.find_n
在字符串中查找最多 n 个模式匹配项。
示例
# Find all hex sequences
hex_matches := regex.find_n("0x[a-fA-F0-9]+", input.raw_params[0].data, 10)
deny if {
count(hex_matches) > 5
}时间函数
用于处理时间的函数。所有时间值都是自 Unix 纪元以来的纳秒数。
time.now_ns
获取当前时间(纳秒)。将此作为基于时间的策略的基础。
示例
# Block high-value transactions during volatile market hours
deny if {
current := time.now_ns()
[hour, _, _] := time.clock(current)
hour >= 14 # After 2 PM UTC (US market open)
hour < 21 # Before 9 PM UTC (US market close)
input.usd_value > 50000
}time.clock
从时间戳中提取小时、分钟和秒。返回 [hour, minute, second]。
示例
# Block outside business hours (9 AM - 5 PM UTC)
deny if {
[hour, _, _] := time.clock(time.now_ns())
hour < 9
}
deny if {
[hour, _, _] := time.clock(time.now_ns())
hour >= 17
}time.weekday
从时间戳获取星期几。返回 0(星期日)到 6(星期六)。
示例
# Block on weekends
deny if {
day := time.weekday(time.now_ns())
day == 0 # Sunday
}
deny if {
day := time.weekday(time.now_ns())
day == 6 # Saturday
}time.date
从时间戳中提取年、月、日。返回 [year, month, day]。
示例
# Block on specific dates
deny if {
[year, month, day] := time.date(time.now_ns())
month == 12
day == 25 # Christmas
}time.parse_rfc3339_ns
将 RFC3339 格式的时间戳字符串解析为纳秒。
示例
# Compare against a specific date
cutoff := time.parse_rfc3339_ns("2024-12-31T23:59:59Z")
deny if {
time.now_ns() > cutoff
}time.add_date
向时间戳添加年、月和日。
示例
# Block transactions if we're within 7 days of year end
deny if {
year_end := time.parse_rfc3339_ns("2024-12-31T23:59:59Z")
week_before := time.add_date(year_end, 0, 0, -7)
time.now_ns() > week_before
input.usd_value > 10000
}time.diff
计算两个时间戳之间的差异。返回 [years, months, days, hours, minutes, seconds]。
示例
# Check if more than 1 hour has passed
start := time.parse_rfc3339_ns("2024-01-01T00:00:00Z")
[_, _, _, hours, _, _] := time.diff(time.now_ns(), start)
deny if {
hours > 1
}聚合函数
用于处理值集合的函数。
count
计算数组、集合或对象中的元素数。
示例
# Limit number of contracts in a request
deny if {
count(input.contract_addresses) > 5
}
# Ensure at least one address
deny if {
count(input.contract_addresses) == 0
}sum
计算数组中数字的总和。
示例
# Block if total gas across params exceeds limit
deny if {
gas_values := [to_number(p.gas) | some p in input.raw_params; p.gas != null]
sum(gas_values) > 5000000
}max
查找数组中的最大值。
示例
# Check against maximum in a set of thresholds
thresholds := [1000, 5000, 10000]
deny if {
input.usd_value > max(thresholds)
}min
查找数组中的最小值。
示例
# Ensure value meets minimum threshold
thresholds := [100, 500, 1000]
deny if {
input.usd_value < min(thresholds)
}sort
按升序对数组进行排序。
示例
# Check if smallest contract address looks suspicious (many leading zeros)
deny if {
count(input.contract_addresses) > 0
sorted_addrs := sort(input.contract_addresses)
startswith(sorted_addrs[0], "0x00000000")
}product
计算数组中数字的乘积。
示例
# Calculate combined risk score from multiple factors
deny if {
risk_factors := [2, 3] # High-value = 2x, Unknown sender = 3x
combined_risk := product(risk_factors)
combined_risk > 5
}类型函数
用于检查和处理数据类型的函数。对于安全处理可空字段很有用。
is_null
检查值是否为 null。对于处理可选输入字段至关重要。
示例
# Safely check nullable field
deny if {
not is_null(input.usd_value)
input.usd_value > 10000
}is_number
检查值是否为数字。
示例
# Validate before numeric comparison
deny if {
is_number(input.usd_value)
input.usd_value > 10000
}is_string
检查值是否为字符串。
示例
# Validate input type
deny if {
is_string(input.to_address)
startswith(input.to_address, "0x0000")
}is_array
检查值是否为数组。
示例
# Check before iterating
deny if {
is_array(input.contract_addresses)
count(input.contract_addresses) > 10
}is_boolean
检查值是否为布尔值(true 或 false)。
示例
# Verify a flag is actually a boolean before using it
deny if {
is_boolean(input.raw_params[0].enabled)
input.raw_params[0].enabled == false
}is_set
检查值是否为集合。
示例
# Validate collection type
deny if {
is_set(input.raw_params[0].addresses)
count(input.raw_params[0].addresses) > 100
}is_object
检查值是否为对象(键值映射)。
示例
# Ensure params is an object before accessing fields
deny if {
is_object(input.raw_params[0])
object.get(input.raw_params[0], "dangerous", false) == true
}type_name
将值的类型名称作为字符串获取。
示例
# Block if usd_value is not a number (unexpected type)
deny if {
input.usd_value != null
type_name(input.usd_value) != "number"
}数字函数
用于数值操作的函数。
abs
获取数字的绝对值。
示例
# Check magnitude regardless of sign
deny if {
abs(input.usd_value) > 10000
}round
将数字四舍五入到最接近的整数。
示例
# Round for comparison
deny if {
round(input.usd_value) > 10000
}ceil
将数字向上舍入到下一个整数。
示例
# Round up for conservative limit checking
deny if {
ceil(input.usd_value) > 10000
}floor
将数字向下舍入到前一个整数。
示例
# Block transactions over $10,000 (ignoring cents)
deny if {
floor(input.usd_value) >= 10000
}to_number
将字符串转换为数字。对十六进制字符串值很有用。
示例
# Convert hex gas values
deny if {
input.gas_limit != null
to_number(input.gas_limit) > 1000000
}numbers.range
生成从开始到结束(包括)的数字数组。
示例
# Allow transactions only during business hours (9 AM - 5 PM)
deny if {
[hour, _, _] := time.clock(time.now_ns())
business_hours := numbers.range(9, 17)
not hour in business_hours
}对象函数
用于处理对象(键值映射)的函数。
object.get
安全地从对象获取值,如果键不存在则使用默认值。
示例
# Safely access nested data
deny if {
params := input.raw_params[0]
data := object.get(params, "data", "0x")
startswith(data, "0xa9059cbb") # ERC-20 transfer
}object.keys
将对象的所有键作为数组获取。
示例
# Check which fields are present
params := input.raw_params[0]
keys := object.keys(params)
deny if {
"data" in keys
"value" in keys
}object.remove
创建删除指定键的新对象。
示例
# Block if params contain unexpected fields after removing known safe ones
deny if {
safe_fields := ["to", "from", "value", "gas", "data"]
remaining := object.remove(input.raw_params[0], safe_fields)
count(object.keys(remaining)) > 0
}object.union
合并两个对象。第二个对象的值会覆盖第一个。
示例
# Apply safe defaults and check resulting gas limit
deny if {
defaults := {"gas": "0x5208"}
params := object.union(defaults, input.raw_params[0])
to_number(params.gas) > 1000000
}数组函数
用于数组操作的函数。
array.concat
将两个数组连接成一个。
示例
# Combine address lists
all_addresses := array.concat(
input.contract_addresses,
[input.to_address]
)array.slice
通过起始和结束索引提取数组的一部分。
示例
# Only check first 5 contract addresses for blocked list
deny if {
first_five := array.slice(input.contract_addresses, 0, 5)
some addr in first_five
addr in {"0xbanned1...", "0xbanned2..."}
}array.reverse
反转数组中元素的顺序。
示例
# Check last contract address (most recent) for suspicious patterns
deny if {
count(input.contract_addresses) > 0
reversed := array.reverse(input.contract_addresses)
startswith(reversed[0], "0x00000000")
}集合函数
用于集合操作的函数。
intersection
获取两个集合中都存在的元素。
示例
# Check for any blocked address
blocked := {"0xdead...", "0xbad..."}
request_addrs := {lower(input.to_address)}
deny if {
count(intersection(blocked, request_addrs)) > 0
}union
将两个集合合并为一个包含所有唯一元素的集合。
示例
# Combine multiple blocklists
blocked_countries := union(
{"KP", "IR", "CU"},
{"SY", "RU"}
)
deny if {
input.source_country in blocked_countries
}编码函数
用于编码和解码数据的函数。
base64.encode
将字符串编码为 Base64 格式。
示例
# Check if method matches an encoded pattern
deny if {
encoded_method := base64.encode(input.rpc_method)
encoded_method == "ZXRoX3NlbmRUcmFuc2FjdGlvbg==" # eth_sendTransaction
}base64.decode
将 Base64 字符串解码回纯文本。
示例
# Decode base64 data from request
decoded := base64.decode("aGVsbG8=") # "hello"
deny if {
contains(decoded, "dangerous")
}base64url.encode
将字符串编码为 URL 安全的 Base64 格式。使用 - 和 _ 代替 + 和 /。
示例
# Create URL-safe identifier from address for comparison
deny if {
encoded_addr := base64url.encode(input.to_address)
encoded_addr in {"MHhkZWFk...", "MHhiYWQ..."}
}base64url.decode
将 URL 安全的 Base64 字符串解码回纯文本。
示例
# Decode and check URL-safe encoded data in params
deny if {
encoded_data := object.get(input.raw_params[0], "encoded", "")
decoded := base64url.decode(encoded_data)
contains(decoded, "malicious")
}hex.encode
将字符串编码为十六进制格式。
示例
# Encode method name to hex for pattern matching
deny if {
method_hex := hex.encode(input.rpc_method)
startswith(method_hex, "657468") # "eth" in hex
}hex.decode
将十六进制字符串解码回纯文本。
示例
# Decode hex-encoded data field and check contents
deny if {
data := object.get(input.raw_params[0], "data", "")
startswith(data, "0x")
decoded := hex.decode(substring(data, 2, 8))
contains(decoded, "admin")
}