Skip to content
Merged
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
25 changes: 24 additions & 1 deletion bridgetracker/activity.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ import (
// compile-time check: ActivityCache fulfils ActivityRegistry
var _ ActivityRegistry = (*ActivityCache)(nil)

// compile-time check: ActivityCache serves the per-address revision
var _ domain.ActivityRevisionReader = (*ActivityCache)(nil)

// DefaultMaxActivityAddresses bounds how many distinct from_addresses ActivityCache accepts
// before refusing new ones (see ActivityCache.register), mirroring DefaultMaxTrackedBridges'
// DoS-protection reasoning for the tracker's own registry
Expand All @@ -38,6 +41,11 @@ type activityAddrCache struct {
// overwritten every call rather than accumulated, so a recovered network's warning clears
// promptly
warnings []domain.ActivityWarning
// revision accumulates the hash of every entry of the address (see domain.ActivityRevision,
// domain.HashActivityEntry, domain.ActivityRevisionReader). Its zero value is the empty
// activity, which is all it holds until the follow-up that maintains it as entries are
// added, removed or changed lands (agglayer/aggkit#1968, #1969)
revision domain.ActivityRevision
// waiters holds one channel per RegisterAndAwait call currently blocked on this address's
// next refresh; closed and cleared by RefreshAddress once it completes
waiters map[chan struct{}]struct{}
Expand Down Expand Up @@ -320,6 +328,21 @@ func (a *ActivityCache) GetActivity(
return out, cache.warnings, nil
}

// GetActivityRevision implements domain.ActivityRevisionReader: the address's current revision
// (activityAddrCache.revision), domain.EmptyActivityRevision for an address with nothing cached.
// It does not count as an access (unlike GetActivity, it does not touch lastAccess): the caller
// reads the entries right after, through GetActivity
func (a *ActivityCache) GetActivityRevision(_ context.Context, fromAddress common.Address) (string, error) {
a.mu.Lock()
defer a.mu.Unlock()

cache, ok := a.byAddr[fromAddress]
if !ok {
return domain.EmptyActivityRevision, nil
}
return cache.revision.String(), nil
}

// FlushActivity implements domain.ActivityQuerier: it discards fromAddress's whole per-address
// cache, if any β€” every cached bridge (settled or not) is forgotten, so the next background
// refresh for fromAddress rescans and rechecks everything from scratch, exactly as if it had
Expand Down Expand Up @@ -364,7 +387,7 @@ func (a *ActivityCache) upsert(
func matchesFilter(entry *domain.ActivityEntry, filter types.ActivityFilter) bool {
switch filter {
case types.ActivityFilterClaimed:
return entry.TrackerClaimStatus == types.TrackerClaimStatusClaimed
return entry.TrackerClaimStatus.IsClaimed()
case types.ActivityFilterPending:
return entry.TrackerClaimStatus == types.TrackerClaimStatusPending
case types.ActivityFilterReadyToClaim:
Expand Down
80 changes: 80 additions & 0 deletions bridgetracker/activity_finality_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
package bridgetracker

import (
"testing"
"time"

bridgeservicetypes "github.com/agglayer/aggkit/bridgeservice/types"
"github.com/agglayer/aggkit/bridgetracker/domain"
"github.com/agglayer/aggkit/bridgetracker/types"
"github.com/ethereum/go-ethereum/common"
"github.com/stretchr/testify/require"
)

// TestActivityCache_GetActivityRevision verifies the per-address revision ActivityCache serves:
// the empty-activity value for an address with nothing cached, and whatever the address's cache
// holds otherwise (the follow-up issues are the ones that maintain it)
func TestActivityCache_GetActivityRevision(t *testing.T) {
cache := NewActivityCache(nil, nil, nil, nil)

revision, err := cache.GetActivityRevision(t.Context(), testFromAddress)
require.NoError(t, err)
require.Equal(t, domain.EmptyActivityRevision, revision, "an address with nothing cached is empty")

_, err = cache.RegisterAndAwait(testFromAddress, false, 0)
require.NoError(t, err)
revision, err = cache.GetActivityRevision(t.Context(), testFromAddress)
require.NoError(t, err)
require.Equal(t, domain.EmptyActivityRevision, revision)

entryHash := domain.HashActivityEntry(&domain.ActivityEntry{
Bridge: &bridgeservicetypes.BridgeResponse{GlobalIndex: "1", TxHash: "0xaa", BlockNum: 7},
})
cache.mu.Lock()
cache.byAddr[testFromAddress].revision = cache.byAddr[testFromAddress].revision.Add(entryHash)
want := cache.byAddr[testFromAddress].revision.String()
cache.mu.Unlock()
revision, err = cache.GetActivityRevision(t.Context(), testFromAddress)
require.NoError(t, err)
require.Equal(t, want, revision)
require.NotEqual(t, domain.EmptyActivityRevision, revision)

revision, err = cache.GetActivityRevision(t.Context(), common.HexToAddress("0x2222222222222222222222222222222222222222"))
require.NoError(t, err)
require.Equal(t, domain.EmptyActivityRevision, revision, "the revision is per address")
}

// TestActivityCache_GetActivityRevisionIsNotAnAccess verifies reading the revision does not
// refresh the address's lastAccess: only the GetActivity read that follows it counts
func TestActivityCache_GetActivityRevisionIsNotAnAccess(t *testing.T) {
cache := NewActivityCache(nil, nil, nil, nil)
start := time.Unix(1_700_000_000, 0)
cache.now = func() time.Time { return start }
_, err := cache.RegisterAndAwait(testFromAddress, false, 0)
require.NoError(t, err)

cache.now = func() time.Time { return start.Add(time.Hour) }
_, err = cache.GetActivityRevision(t.Context(), testFromAddress)
require.NoError(t, err)

cache.mu.Lock()
defer cache.mu.Unlock()
require.Equal(t, start, cache.byAddr[testFromAddress].lastAccess)
}

// TestMatchesFilter_ClaimedIncludesClaimedFinalized verifies filterBridges=claimed keeps matching
// every claimed bridge now that "claimed_finalized" exists, and that no other filter matches it
func TestMatchesFilter_ClaimedIncludesClaimedFinalized(t *testing.T) {
entry := func(status types.TrackerClaimStatus) *domain.ActivityEntry {
return &domain.ActivityEntry{TrackerClaimStatus: status}
}

require.True(t, matchesFilter(entry(types.TrackerClaimStatusClaimed), types.ActivityFilterClaimed))
require.True(t, matchesFilter(entry(types.TrackerClaimStatusClaimedFinalized), types.ActivityFilterClaimed))
require.True(t, matchesFilter(entry(types.TrackerClaimStatusClaimedFinalized), types.ActivityFilterAll))
for _, filter := range []types.ActivityFilter{
types.ActivityFilterPending, types.ActivityFilterReadyToClaim, types.ActivityFilterError,
} {
require.False(t, matchesFilter(entry(types.TrackerClaimStatusClaimedFinalized), filter), filter.String())
}
}
64 changes: 55 additions & 9 deletions bridgetracker/api/activity_command.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package api

import (
"context"
"encoding/json"
"errors"
"fmt"
Expand Down Expand Up @@ -70,14 +71,22 @@ type ActivityItem struct {
// not indexed this bridge yet, or could not be reached β€” see domain.ActivitySourceKind)
Source string `json:"source"`
// ClaimStatus is a simplified claim-readiness summary, one of "pending", "readyToClaim",
// "claimed" or "error" β€” the same vocabulary and field name as TrackingData.ClaimStatus (see
// domain.TrackingData.ClaimStatus for exactly how it is derived). "error" reports the
// destination bridge contract's isClaimed() call itself failing (e.g. no bridge contract
// address configured for the destination network) β€” callers must not read it as "pending".
// While unclaimed, "readyToClaim" vs "pending" is resolved from the tracker's own snapshot
// when Tracking is present, or directly against the bridge-service endpoints otherwise (see
// domain.ActivityClaimChecker.IsReadyToClaim)
ClaimStatus string `json:"claim_status"`
// "claimed", "claimed_finalized" or "error" β€” the same vocabulary and field name as
// TrackingData.ClaimStatus (see domain.TrackingData.ClaimStatus for exactly how it is
// derived). "claimed_finalized" is the only final state: "claimed" can still go back to
// "readyToClaim" or "pending" if a reorg removes the claim. "error" reports the destination
// bridge contract's isClaimed() call itself failing (e.g. no bridge contract address
// configured for the destination network) β€” callers must not read it as "pending". While
// unclaimed, "readyToClaim" vs "pending" is resolved from the tracker's own snapshot when
// Tracking is present, or directly against the bridge-service endpoints otherwise (see
// domain.ActivityClaimChecker.IsReadyToClaim). "claimed_finalized" is not produced yet (see
// Finalized)
ClaimStatus string `json:"claim_status" enums:"pending,readyToClaim,claimed,claimed_finalized,error"`
// Finalized is true when this item can no longer be changed by a reorg: its bridge is final
// and, if it is claimed, its claim is final too. Always serialized. It is false for every
// item until the activity finality follow-ups populate it (agglayer/aggkit#1968, #1969).
// Going from false to true does not change the response's Revision
Finalized bool `json:"finalized"`
// ClaimNetworkID is the network whose bridge service reported Claim (the bridge's
// destination network); only present alongside Claim
ClaimNetworkID uint32 `json:"claim_network_id,omitempty"`
Expand Down Expand Up @@ -155,6 +164,18 @@ type ActivityResponse struct {
// Count is how many bridges matched filterBridges in total, across every page β€” not just
// len(Bridges) β€” mirroring bridgeservice's BridgesResult/ClaimsResult "count" field
Count int `json:"count"`
// Revision is FromAddress's revision (see domain.ActivityRevisionReader), an opaque string
// that is a hash of the address's activity (e.g. "v1:" followed by hex), present in every
// response whatever filterBridges/page_number/page_size say: it covers all of the address's
// bridges, not just this page. It changes when a bridge is added or removed, changes
// claim_status or is corrected after a reorg β€” wherever it sits in the sorted result β€” and it
// does NOT change when an item only goes from finalized=false to finalized=true. It is the
// same after a restart and on every instance holding the same data. A client polls it with a
// cheap request (page_size=1), reloads the pages it has loaded when it differs from the one
// it holds, and checks it again after the last page; compare it for equality only. Always
// serialized; until the follow-up that computes it lands (agglayer/aggkit#1968, #1969) it is
// the empty-activity value "v1:" followed by 64 zeros
Revision string `json:"revision" example:"v1:0000000000000000000000000000000000000000000000000000000000000000"`
// Warnings lists every network whose bridge service could not be scanned this call; absent
// when every configured network was scanned successfully. Bridges may be incomplete for the
// networks listed here, but is still valid for every other network
Expand Down Expand Up @@ -207,7 +228,13 @@ type ActivityResponse struct {
// @Description whole request. Bridges are sorted most recent first and paginated via
// @Description page_number/page_size (same names and 1-based numbering as the bridge service's
// @Description own paginated endpoints); "count" reports how many bridges matched in total,
// @Description across every page.
// @Description across every page. "revision" is an opaque string, a hash of the address's
// @Description activity: it changes when a bridge is added or removed, changes claim_status or is
// @Description corrected after a reorg, wherever it sits in the sorted result, and does not change
// @Description when an item only becomes finalized. It is the same after a restart and on every
// @Description instance holding the same data. Poll it with a cheap request (page_size=1), reload
// @Description the loaded pages when it changed, and check it again after the last page. Compare
// @Description it only for equality.
// @Tags bridge-tracker
// @Produce json
// @Param from_address path string true "Address that sent the bridges to look up"
Expand Down Expand Up @@ -276,6 +303,13 @@ func (cmd *activityCommand) Execute(c *gin.Context) (int, any, *types.ErrorData)
}
}

// the revision is read BEFORE the entries (see domain.ActivityRevisionReader): a refresh landing
// in between can only make the entries newer than the revision reported, never older
revision, err := cmd.activityRevision(c.Request.Context(), fromAddress)
if err != nil {
return 0, nil, &types.ErrorData{Code: http.StatusInternalServerError, Message: aggkitcommon.RedactError(err)}
}

entries, warnings, err := cmd.registry.GetActivity(c.Request.Context(), fromAddress, includeTracking, filter)
if err != nil {
return 0, nil, &types.ErrorData{Code: http.StatusInternalServerError, Message: aggkitcommon.RedactError(err)}
Expand All @@ -285,10 +319,21 @@ func (cmd *activityCommand) Execute(c *gin.Context) (int, any, *types.ErrorData)
FromAddress: fromAddress,
Bridges: newActivityItems(paginateActivityEntries(entries, pageNumber, pageSize)),
Count: len(entries),
Revision: revision,
Warnings: newActivityWarningItems(warnings),
}, nil
}

// activityRevision is fromAddress's revision as served by the registry when it implements
// domain.ActivityRevisionReader, and domain.EmptyActivityRevision when it does not
func (cmd *activityCommand) activityRevision(ctx context.Context, fromAddress common.Address) (string, error) {
reader, ok := cmd.registry.(domain.ActivityRevisionReader)
if !ok {
return domain.EmptyActivityRevision, nil
}
return reader.GetActivityRevision(ctx, fromAddress)
}

// parseActivityPageParams parses and validates the activity endpoint's page_number/page_size
// query parameters, same names, defaults and bounds as the bridge service's own paginated
// endpoints (see bridgeservice.parseUintQuery/validatePaginationParams): page_number defaults to
Expand Down Expand Up @@ -384,6 +429,7 @@ func newActivityItems(entries []*domain.ActivityEntry) []ActivityItem {
BridgeNetworkID: e.BridgeNetworkID,
Source: string(e.Source),
ClaimStatus: e.TrackerClaimStatus.String(),
Finalized: e.Finalized,
Errors: e.Errors,
CreationTimestamp: uint64(e.CreatedAt.Unix()),
LastUpdatedTimestamp: uint64(e.UpdatedAt.Unix()),
Expand Down
Loading
Loading