diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index e1a0766..2d8a343 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -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 diff --git a/internal/engine/predicate.go b/internal/engine/predicate.go index 3ca1ce0..5435d97 100644 --- a/internal/engine/predicate.go +++ b/internal/engine/predicate.go @@ -2,7 +2,8 @@ package engine import ( "fmt" - "strconv" + "math/big" + "regexp" "strings" "time" ) @@ -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 } @@ -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 } @@ -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 { @@ -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] @@ -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. diff --git a/internal/engine/predicate_bigint_test.go b/internal/engine/predicate_bigint_test.go new file mode 100644 index 0000000..0171588 --- /dev/null +++ b/internal/engine/predicate_bigint_test.go @@ -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) + } + }) + } +} diff --git a/internal/source/evm/matcher.go b/internal/source/evm/matcher.go index f5e05b1..999f40c 100644 --- a/internal/source/evm/matcher.go +++ b/internal/source/evm/matcher.go @@ -17,6 +17,9 @@ type RuleMatcher struct { address common.Address topic0 common.Hash event *abi.Event + // synthetic is set when no ABI was found and the event was built from the + // signature alone; indexed args and names are then resolved per log. + synthetic bool } // NewRuleMatcher builds a matcher for a log rule using available ABIs. Supports only log rules. @@ -28,21 +31,29 @@ func NewRuleMatcher(rule config.Rule, abis map[string]*abi.ABI) (*RuleMatcher, e return nil, fmt.Errorf("rule %s: contract and event are required", rule.ID) } - evName := eventName(rule.Match.Event) + signature := canonicalSignature(rule.Match.Event) + evName := eventName(signature) var ev *abi.Event + isSynthetic := false if found, ok := FindEvent(abis, evName); ok { ev = found - } else if synthetic, err := syntheticEvent(rule.Match.Event); err == nil { + } else { + synthetic, err := syntheticEvent(signature) + if err != nil { + return nil, fmt.Errorf("rule %s: %w", rule.ID, err) + } ev = synthetic + isSynthetic = true } - topic := crypto.Keccak256Hash([]byte(rule.Match.Event)) + topic := crypto.Keccak256Hash([]byte(signature)) return &RuleMatcher{ - rule: rule, - address: common.HexToAddress(rule.Match.Contract), - topic0: topic, - event: ev, + rule: rule, + address: common.HexToAddress(rule.Match.Contract), + topic0: topic, + event: ev, + synthetic: isSynthetic, }, nil } @@ -57,7 +68,15 @@ func (m *RuleMatcher) Match(log types.Log) (*NormalizedEvent, bool, error) { args := map[string]any{} if m.event != nil { - indexed, nonIndexed := splitIndexed(m.event.Inputs) + inputs := m.event.Inputs + if m.synthetic { + resolved, err := resolveSyntheticInputs(m.event, len(log.Topics)-1) + if err != nil { + return nil, false, err + } + inputs = resolved + } + indexed, nonIndexed := splitIndexed(inputs) if err := abi.ParseTopicsIntoMap(args, indexed, log.Topics[1:]); err != nil { return nil, false, fmt.Errorf("parse topics: %w", err) } @@ -84,8 +103,15 @@ func eventName(signature string) string { return signature } +// canonicalSignature strips whitespace so "Transfer(address, address, uint256)" +// hashes to the same topic as "Transfer(address,address,uint256)". +func canonicalSignature(signature string) string { + return strings.Join(strings.Fields(signature), "") +} + // syntheticEvent builds a minimal ABI Event from a signature like Transfer(address,address,uint256). -// Indexed fields are not inferred; all arguments are treated as non-indexed. +// Which arguments are indexed is not known from the signature; resolveSyntheticInputs +// decides that per log from the number of topics. func syntheticEvent(signature string) (*abi.Event, error) { l := strings.Index(signature, "(") r := strings.LastIndex(signature, ")") @@ -108,11 +134,55 @@ func syntheticEvent(signature string) (*abi.Event, error) { } return &abi.Event{ Name: name, + RawName: name, Inputs: args, Anonymous: false, + Sig: signature, }, nil } +// wellKnownArgNames gives argument names for common token events, keyed by +// canonical signature and then by number of indexed arguments. ERC-20 and +// ERC-721 share the Transfer/Approval signatures and differ only in indexing. +var wellKnownArgNames = map[string]map[int][]string{ + "Transfer(address,address,uint256)": { + 2: {"from", "to", "value"}, // ERC-20 + 3: {"from", "to", "tokenId"}, // ERC-721 + }, + "Approval(address,address,uint256)": { + 2: {"owner", "spender", "value"}, + 3: {"owner", "approved", "tokenId"}, + }, + "ApprovalForAll(address,address,bool)": { + 2: {"owner", "operator", "approved"}, + }, + "TransferSingle(address,address,address,uint256,uint256)": { + 3: {"operator", "from", "to", "id", "value"}, + }, +} + +// resolveSyntheticInputs marks the first indexedCount arguments as indexed +// (the usual Solidity layout) and names every argument, using well-known names +// when available and arg0, arg1, ... otherwise. Events whose indexed +// arguments are not leading need an ABI file in abi_dirs. +func resolveSyntheticInputs(ev *abi.Event, indexedCount int) (abi.Arguments, error) { + if indexedCount < 0 || indexedCount > len(ev.Inputs) { + return nil, fmt.Errorf("event %s: log has %d indexed topics but signature has %d arguments", ev.Sig, indexedCount, len(ev.Inputs)) + } + names := wellKnownArgNames[ev.Sig][indexedCount] + out := make(abi.Arguments, len(ev.Inputs)) + for i, in := range ev.Inputs { + in.Indexed = i < indexedCount + if len(names) == len(ev.Inputs) { + in.Name = names[i] + } else { + in.Name = fmt.Sprintf("arg%d", i) + } + out[i] = in + } + return out, nil +} + func splitIndexed(args abi.Arguments) (indexed abi.Arguments, nonIndexed abi.Arguments) { for _, a := range args { if a.Indexed { diff --git a/internal/source/evm/matcher_synthetic_test.go b/internal/source/evm/matcher_synthetic_test.go new file mode 100644 index 0000000..e3322de --- /dev/null +++ b/internal/source/evm/matcher_synthetic_test.go @@ -0,0 +1,130 @@ +package evm + +import ( + "math/big" + "testing" + + "github.com/devblac/watch-tower/internal/config" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/crypto" +) + +const usdc = "0xA0b86991c6218b36c1d19d4a2e9eb0ce3606eb48" + +func logRule(event string) config.Rule { + return config.Rule{ + ID: "r", + Source: "evm_main", + Match: config.MatchSpec{Type: "log", Contract: usdc, Event: event}, + } +} + +func TestRuleMatcher_NoABI_ERC20Transfer(t *testing.T) { + m, err := NewRuleMatcher(logRule("Transfer(address,address,uint256)"), nil) + if err != nil { + t.Fatalf("new matcher: %v", err) + } + + from := common.HexToAddress("0x00000000000000000000000000000000000000aa") + to := common.HexToAddress("0x00000000000000000000000000000000000000bb") + value := new(big.Int).Mul(big.NewInt(2_000_000), big.NewInt(1_000_000)) + log := types.Log{ + Address: common.HexToAddress(usdc), + Topics: []common.Hash{crypto.Keccak256Hash([]byte("Transfer(address,address,uint256)")), addrTopic(from), addrTopic(to)}, + Data: common.LeftPadBytes(value.Bytes(), 32), + } + + ev, ok, err := m.Match(log) + if err != nil || !ok { + t.Fatalf("expected match, ok=%v err=%v", ok, err) + } + if got := ev.Args["from"]; got != from { + t.Errorf("from = %v, want %v", got, from) + } + if got := ev.Args["to"]; got != to { + t.Errorf("to = %v, want %v", got, to) + } + if got, _ := ev.Args["value"].(*big.Int); got == nil || got.Cmp(value) != 0 { + t.Errorf("value = %v, want %v", ev.Args["value"], value) + } +} + +func TestRuleMatcher_NoABI_ERC721Transfer(t *testing.T) { + m, err := NewRuleMatcher(logRule("Transfer(address,address,uint256)"), nil) + if err != nil { + t.Fatalf("new matcher: %v", err) + } + tokenID := common.BigToHash(big.NewInt(42)) + log := types.Log{ + Address: common.HexToAddress(usdc), + Topics: []common.Hash{ + crypto.Keccak256Hash([]byte("Transfer(address,address,uint256)")), + addrTopic(common.HexToAddress("0x01")), + addrTopic(common.HexToAddress("0x02")), + tokenID, + }, + } + ev, ok, err := m.Match(log) + if err != nil || !ok { + t.Fatalf("expected match, ok=%v err=%v", ok, err) + } + if got, _ := ev.Args["tokenId"].(*big.Int); got == nil || got.Int64() != 42 { + t.Errorf("tokenId = %v, want 42", ev.Args["tokenId"]) + } +} + +func TestRuleMatcher_NoABI_UnknownEventUsesPositionalNames(t *testing.T) { + sig := "Swap(address,uint256,uint256)" + m, err := NewRuleMatcher(logRule(sig), nil) + if err != nil { + t.Fatalf("new matcher: %v", err) + } + data := append(common.LeftPadBytes(big.NewInt(7).Bytes(), 32), common.LeftPadBytes(big.NewInt(9).Bytes(), 32)...) + log := types.Log{ + Address: common.HexToAddress(usdc), + Topics: []common.Hash{crypto.Keccak256Hash([]byte(sig)), addrTopic(common.HexToAddress("0x03"))}, + Data: data, + } + ev, ok, err := m.Match(log) + if err != nil || !ok { + t.Fatalf("expected match, ok=%v err=%v", ok, err) + } + if got := ev.Args["arg0"]; got != common.HexToAddress("0x03") { + t.Errorf("arg0 = %v", got) + } + if got, _ := ev.Args["arg2"].(*big.Int); got == nil || got.Int64() != 9 { + t.Errorf("arg2 = %v, want 9", ev.Args["arg2"]) + } +} + +func TestRuleMatcher_SignatureWhitespaceIgnored(t *testing.T) { + m, err := NewRuleMatcher(logRule("Transfer(address, address, uint256)"), nil) + if err != nil { + t.Fatalf("new matcher: %v", err) + } + if want := crypto.Keccak256Hash([]byte("Transfer(address,address,uint256)")); m.topic0 != want { + t.Fatalf("topic0 = %s, want %s", m.topic0, want) + } +} + +func TestRuleMatcher_NoABI_TooManyTopics(t *testing.T) { + sig := "Ping(uint256)" + m, err := NewRuleMatcher(logRule(sig), nil) + if err != nil { + t.Fatalf("new matcher: %v", err) + } + log := types.Log{ + Address: common.HexToAddress(usdc), + Topics: []common.Hash{crypto.Keccak256Hash([]byte(sig)), {}, {}}, + } + if _, _, err := m.Match(log); err == nil { + t.Fatalf("expected error for more indexed topics than arguments") + } +} + +func TestNewRuleMatcher_InvalidSignature(t *testing.T) { + if _, err := NewRuleMatcher(logRule("Transfer"), nil); err == nil { + t.Fatalf("expected error for signature without parentheses") + } +}