Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,8 @@ jobs:
go-version: '1.23'

- name: Install syft for SBOM generation
uses: anchore/sbom-action/download-syft@v0
with:
syft-version: latest
run: |
curl -sSfL https://raw.githubusercontent.com/anchore/syft/main/install.sh | sh -s -- -b /usr/local/bin

- name: Run GoReleaser
uses: goreleaser/goreleaser-action@v5
Expand Down
148 changes: 91 additions & 57 deletions internal/engine/predicate.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ package engine

import (
"fmt"
"strconv"
"math/big"
"regexp"
"strings"
"time"
)
Expand Down Expand Up @@ -43,7 +44,7 @@ func compile(expr string) (Predicate, error) {
rawList := strings.Split(parts[1], ",")
values := make(map[string]struct{}, len(rawList))
for _, v := range rawList {
v = strings.TrimSpace(v)
v = normalizeString(unquote(strings.TrimSpace(v)))
if v == "" {
continue
}
Expand All @@ -54,8 +55,7 @@ func compile(expr string) (Predicate, error) {
if !ok {
return false, nil
}
s := fmt.Sprint(arg)
_, hit := values[s]
_, hit := values[normalizeString(fmt.Sprint(arg))]
return hit, nil
}, nil
}
Expand All @@ -66,7 +66,7 @@ func compile(expr string) (Predicate, error) {
return nil, fmt.Errorf("invalid contains expression: %s", expr)
}
field := strings.TrimSpace(parts[0])
needle := strings.TrimSpace(parts[1])
needle := unquote(strings.TrimSpace(parts[1]))
return func(args map[string]any) (bool, error) {
val, ok := args[field]
if !ok {
Expand Down Expand Up @@ -102,6 +102,7 @@ func compile(expr string) (Predicate, error) {
rhsRaw := strings.TrimSpace(parts[1])

numRHS, rhsIsNum := evaluateNumber(rhsRaw)
strRHS := normalizeString(unquote(rhsRaw))

return func(args map[string]any) (bool, error) {
val, ok := args[field]
Expand All @@ -114,102 +115,135 @@ func compile(expr string) (Predicate, error) {
if !ok {
return false, nil
}
c := lhs.Cmp(numRHS)
switch op {
case "==":
return lhs == numRHS, nil
return c == 0, nil
case "!=":
return lhs != numRHS, nil
return c != 0, nil
case ">":
return lhs > numRHS, nil
return c > 0, nil
case "<":
return lhs < numRHS, nil
return c < 0, nil
case ">=":
return lhs >= numRHS, nil
return c >= 0, nil
case "<=":
return lhs <= numRHS, nil
return c <= 0, nil
}
}

// String comparisons
lhs := fmt.Sprint(val)
lhs := normalizeString(fmt.Sprint(val))
switch op {
case "==":
return lhs == rhsRaw, nil
return lhs == strRHS, nil
case "!=":
return lhs != rhsRaw, nil
return lhs != strRHS, nil
default:
return false, nil
}
}, nil
}

// evaluateNumber evaluates a numeric expression, supporting:
// - Simple numbers: "100", "1e6", "1_000_000"
// decimalRe matches plain decimal literals (optionally with an exponent).
// Hex literals such as addresses are deliberately not numbers.
var decimalRe = regexp.MustCompile(`^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$`)

// evaluateNumber evaluates a numeric expression exactly, supporting:
// - Simple numbers: "100", "1e6", "1_000_000", "0.5"
// - Helper functions: "wei(1e18)", "microAlgos(1e6)"
// - Multiplication: "1_000_000 * 1e6"
func evaluateNumber(s string) (float64, bool) {
func evaluateNumber(s string) (*big.Rat, bool) {
s = strings.TrimSpace(s)
s = strings.ReplaceAll(s, "_", "")

// Handle multiplication
if strings.Contains(s, "*") {
parts := strings.Split(s, "*")
if len(parts) != 2 {
return 0, false
}
a, ok1 := evaluateNumber(strings.TrimSpace(parts[0]))
b, ok2 := evaluateNumber(strings.TrimSpace(parts[1]))
if !ok1 || !ok2 {
return 0, false
result := big.NewRat(1, 1)
for _, part := range strings.Split(s, "*") {
v, ok := evaluateNumber(part)
if !ok {
return nil, false
}
result.Mul(result, v)
}
return a * b, true
return result, true
}

// Check for helper functions: wei(value) or microAlgos(value)
if strings.HasPrefix(s, "wei(") && strings.HasSuffix(s, ")") {
inner := strings.TrimSpace(s[4 : len(s)-1])
v, ok := evaluateNumber(inner)
if !ok {
return 0, false
// Helper functions: wei(value) and microAlgos(value) are already base units.
for _, helper := range []string{"wei(", "microAlgos("} {
if strings.HasPrefix(s, helper) && strings.HasSuffix(s, ")") {
return evaluateNumber(s[len(helper) : len(s)-1])
}
return v, true // wei is already the base unit, no conversion needed
}
if strings.HasPrefix(s, "microAlgos(") && strings.HasSuffix(s, ")") {
inner := strings.TrimSpace(s[11 : len(s)-1])
v, ok := evaluateNumber(inner)
if !ok {
return 0, false
}
return v, true // microAlgos is already the base unit, no conversion needed
}

// Parse as a simple number
v, err := strconv.ParseFloat(s, 64)
return v, err == nil
}

// parseNumber is a simple wrapper for backward compatibility.
func parseNumber(s string) (float64, bool) {
return evaluateNumber(s)
if !decimalRe.MatchString(s) {
return nil, false
}
v, ok := new(big.Rat).SetString(s)
return v, ok
}

func toNumber(v any) (float64, bool) {
// toNumber converts a decoded event argument into an exact rational number.
// EVM uint256/int256 values arrive as *big.Int; Algorand amounts as uint64.
func toNumber(v any) (*big.Rat, bool) {
switch n := v.(type) {
case *big.Int:
if n == nil {
return nil, false
}
return new(big.Rat).SetInt(n), true
case big.Int:
return new(big.Rat).SetInt(&n), true
case int:
return float64(n), true
return new(big.Rat).SetInt64(int64(n)), true
case int8:
return new(big.Rat).SetInt64(int64(n)), true
case int16:
return new(big.Rat).SetInt64(int64(n)), true
case int32:
return new(big.Rat).SetInt64(int64(n)), true
case int64:
return float64(n), true
return new(big.Rat).SetInt64(n), true
case uint:
return new(big.Rat).SetUint64(uint64(n)), true
case uint8:
return new(big.Rat).SetUint64(uint64(n)), true
case uint16:
return new(big.Rat).SetUint64(uint64(n)), true
case uint32:
return new(big.Rat).SetUint64(uint64(n)), true
case uint64:
return float64(n), true
return new(big.Rat).SetUint64(n), true
case float64:
return n, true
r := new(big.Rat).SetFloat64(n)
return r, r != nil
case float32:
return float64(n), true
r := new(big.Rat).SetFloat64(float64(n))
return r, r != nil
case string:
return parseNumber(n)
return evaluateNumber(n)
default:
return 0, false
return nil, false
}
}

// unquote strips one pair of matching surrounding quotes, so that
// `sender == "0xabc"` compares against 0xabc.
func unquote(s string) string {
if len(s) >= 2 && (s[0] == '"' || s[0] == '\'') && s[len(s)-1] == s[0] {
return s[1 : len(s)-1]
}
return s
}

// normalizeString lowercases hex strings (addresses, hashes) so that
// checksummed and lowercase forms compare equal. Other strings are unchanged.
func normalizeString(s string) string {
if strings.HasPrefix(s, "0x") || strings.HasPrefix(s, "0X") {
return strings.ToLower(s)
}
return s
}

// TokenBucket is a simple per-rule rate limiter.
Expand Down
149 changes: 149 additions & 0 deletions internal/engine/predicate_bigint_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
package engine

import (
"math/big"
"testing"

"github.com/devblac/watch-tower/internal/config"
"github.com/devblac/watch-tower/internal/source/evm"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
)

func bigFromString(t *testing.T, s string) *big.Int {
t.Helper()
v, ok := new(big.Int).SetString(s, 10)
if !ok {
t.Fatalf("bad big int %q", s)
}
return v
}

func evalOne(t *testing.T, expr string, args map[string]any) bool {
t.Helper()
preds, err := CompilePredicates([]string{expr})
if err != nil {
t.Fatalf("compile %q: %v", expr, err)
}
ok, err := preds[0](args)
if err != nil {
t.Fatalf("eval %q: %v", expr, err)
}
return ok
}

func TestPredicates_BigIntValues(t *testing.T) {
oneMillionUSDC := big.NewInt(1_000_000_000_000)
tests := []struct {
name string
expr string
val any
want bool
}{
{"usdc_at_threshold", "value >= 1_000_000 * 1e6", oneMillionUSDC, true},
{"usdc_below_threshold", "value >= 1_000_000 * 1e6", big.NewInt(999_999_999_999), false},
{"wei_helper", "value >= wei(1e18)", bigFromString(t, "1000000000000000000"), true},
// float64 cannot tell these apart; exact comparison must.
{"exact_beyond_float_precision", "value > 1e24", bigFromString(t, "1000000000000000000000001"), true},
{"exact_eq_beyond_float_precision", "value == 1e24", bigFromString(t, "1000000000000000000000001"), false},
{"uint256_max", "value > 1e77", bigFromString(t, "115792089237316195423570985008687907853269984665640564039457584007913129639935"), true},
{"negative_int256", "value < 0", big.NewInt(-5), true},
{"uint8", "decimals == 6", uint8(6), true},
{"decimal_rhs", "value > 0.5", 1, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := evalOne(t, tt.expr, map[string]any{"value": tt.val, "decimals": tt.val}); got != tt.want {
t.Errorf("%q with %v = %v, want %v", tt.expr, tt.val, got, tt.want)
}
})
}
}

func TestPredicates_Addresses(t *testing.T) {
addr := common.HexToAddress("0xA0b86991c6218b36c1d19d4a2e9eb0ce3606eb48")
zero := common.Address{}
tests := []struct {
name string
expr string
val any
want bool
}{
{"quoted_lowercase_matches_checksummed", `sender == "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48"`, addr, true},
{"unquoted_matches", "sender == 0xA0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", addr, true},
{"zero_address_not_numeric", "sender != 0x0000000000000000000000000000000000000000", addr, true},
{"zero_address_excluded", "sender != 0x0000000000000000000000000000000000000000", zero, false},
{"in_list_mixed_case", "sender in 0x01,0xA0B86991C6218B36C1D19D4A2E9EB0CE3606EB48", addr, true},
{"quoted_contains", `memo contains "alert"`, "critical alert", true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := evalOne(t, tt.expr, map[string]any{"sender": tt.val, "memo": tt.val}); got != tt.want {
t.Errorf("%q with %v = %v, want %v", tt.expr, tt.val, got, tt.want)
}
})
}
}

// TestReadmeQuickstartRule runs the README's USDC whale rule (no abi_dirs)
// through the EVM matcher and the predicates, end to end.
func TestReadmeQuickstartRule(t *testing.T) {
const sig = "Transfer(address,address,uint256)"
rule := config.Rule{
ID: "large_transfer",
Source: "mainnet",
Match: config.MatchSpec{
Type: "log",
Contract: "0xA0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",
Event: sig,
Where: []string{
"value >= 1_000_000 * 1e6",
"to != 0x0000000000000000000000000000000000000000",
},
},
}
m, err := evm.NewRuleMatcher(rule, nil)
if err != nil {
t.Fatalf("new matcher: %v", err)
}
preds, err := CompilePredicates(rule.Match.Where)
if err != nil {
t.Fatalf("compile: %v", err)
}

topic := func(a common.Address) common.Hash { return common.BytesToHash(common.LeftPadBytes(a.Bytes(), 32)) }
transfer := func(to common.Address, amount int64) types.Log {
return types.Log{
Address: common.HexToAddress(rule.Match.Contract),
Topics: []common.Hash{crypto.Keccak256Hash([]byte(sig)), topic(common.HexToAddress("0x01")), topic(to)},
Data: common.LeftPadBytes(big.NewInt(amount).Bytes(), 32),
}
}

recipient := common.HexToAddress("0x00000000000000000000000000000000000000bb")
tests := []struct {
name string
log types.Log
want bool
}{
{"whale_transfer_alerts", transfer(recipient, 2_000_000_000_000), true},
{"small_transfer_ignored", transfer(recipient, 500_000_000), false},
{"burn_ignored", transfer(common.Address{}, 2_000_000_000_000), false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ev, ok, err := m.Match(tt.log)
if err != nil || !ok {
t.Fatalf("expected log to match, ok=%v err=%v", ok, err)
}
got, err := allPredicates(preds, ev.Args)
if err != nil {
t.Fatalf("predicates: %v", err)
}
if got != tt.want {
t.Errorf("alert = %v, want %v (args %v)", got, tt.want, ev.Args)
}
})
}
}
Loading
Loading