@@ -4,7 +4,10 @@ import (
44 "context"
55 "errors"
66 "fmt"
7+ "time"
78
9+ "github.com/ethereum/go-ethereum/common/hexutil"
10+ "github.com/ethereum/go-ethereum/eth/filters"
811 ethrpc "github.com/ethereum/go-ethereum/rpc"
912
1013 "github.com/sei-protocol/sei-chain/sei-db/ledger_db/receipt"
@@ -13,12 +16,142 @@ import (
1316 "github.com/sei-protocol/sei-chain/sei-tendermint/rpc/coretypes"
1417)
1518
19+ // logsRetryInterval is how long a logs subscription waits to poll again when an executed block's
20+ // receipts are not indexed yet.
21+ const logsRetryInterval = 100 * time .Millisecond
22+
1623type subscribeAPI struct {
1724 backend Backend
1825 store receipt.ReceiptStore
26+ logs * filterAPI
1927 limits * subscriptionLimiter
2028}
2129
30+ // logsErrorNotification is what a logs subscription pushes for a poll that failed. BlockNumber is
31+ // the block whose logs were skipped when the subscription continues past it.
32+ type logsErrorNotification struct {
33+ Error string `json:"error"`
34+ BlockNumber * hexutil.Uint64 `json:"blockNumber,omitempty"`
35+ }
36+
37+ // Logs serves eth_subscribe("logs"), pushing each log crit matches as blocks execute, polled
38+ // through the same cursor as eth_getFilterChanges. A failed poll pushes a logsErrorNotification;
39+ // the stream continues only past a block whose logs alone exceed the log caps.
40+ func (api * subscribeAPI ) Logs (ctx context.Context , crit * filters.FilterCriteria ) (* ethrpc.Subscription , error ) {
41+ notifier , ok := ethrpc .NotifierFromContext (ctx )
42+ if ! ok {
43+ return nil , ethrpc .ErrNotificationsUnsupported
44+ }
45+ criteria := subscriptionLogCriteria (crit )
46+ cursor , err := api .logs .pollStart (criteria )
47+ if err != nil {
48+ return nil , err
49+ }
50+ executed , err := api .backend .ExecutedBlocks ()
51+ if err != nil {
52+ return nil , err
53+ }
54+ connection := ethrpc .PeerInfoFromContext (ctx ).RemoteAddr
55+ if err := api .limits .acquireLogs (connection ); err != nil {
56+ return nil , err
57+ }
58+ rpcSub := notifier .CreateSubscription ()
59+ go func () {
60+ // The stream ends on eth_unsubscribe, when the connection drops, or once a bounded query
61+ // is delivered, and its slot frees with it.
62+ defer api .limits .releaseLogs (connection )
63+ api .streamLogs (context .WithoutCancel (ctx ), notifier , rpcSub , executed , criteria , cursor )
64+ }()
65+ return rpcSub , nil
66+ }
67+
68+ // subscriptionLogCriteria returns the criteria a logs subscription polls with. A fromBlock of 0
69+ // with a tag toBlock, which ethclient sends for an open-ended query, is treated as an omitted
70+ // fromBlock.
71+ func subscriptionLogCriteria (crit * filters.FilterCriteria ) filters.FilterCriteria {
72+ if crit == nil {
73+ return filters.FilterCriteria {}
74+ }
75+ if crit .FromBlock != nil && crit .FromBlock .Sign () == 0 && crit .ToBlock != nil && crit .ToBlock .Sign () < 0 {
76+ return filters.FilterCriteria {Addresses : crit .Addresses , Topics : crit .Topics }
77+ }
78+ return * crit
79+ }
80+
81+ func (api * subscribeAPI ) streamLogs (
82+ ctx context.Context ,
83+ notifier * ethrpc.Notifier ,
84+ rpcSub * ethrpc.Subscription ,
85+ executed utils.AtomicRecv [atypes.ExecutedBlocks ],
86+ crit filters.FilterCriteria ,
87+ cursor uint64 ,
88+ ) {
89+ // This goroutine is outside go-ethereum's per-call recovery, so a panic ends the subscription
90+ // rather than the node.
91+ defer func () {
92+ if r := recover (); r != nil {
93+ logger .Error ("logs: stream panicked" , "subscription" , rpcSub .ID , "panic" , r )
94+ }
95+ }()
96+ ctx , cancel := subscriptionContext (ctx , rpcSub .Err ())
97+ defer cancel ()
98+ for {
99+ if _ , err := executed .Wait (ctx , func (w atypes.ExecutedBlocks ) bool { return uint64 (w .Latest ().Number ) >= cursor }); err != nil {
100+ return
101+ }
102+ logs , next , err := api .logs .pollLogs (ctx , crit , cursor )
103+ if err != nil {
104+ if ctx .Err () != nil || notifier .Notify (rpcSub .ID , newLogsErrorNotification (err )) != nil {
105+ return
106+ }
107+ var oversized * oversizedBlockError
108+ if ! errors .As (err , & oversized ) {
109+ return
110+ }
111+ }
112+ for _ , lg := range logs {
113+ if err := notifier .Notify (rpcSub .ID , lg ); err != nil {
114+ return
115+ }
116+ }
117+ if logsExhausted (crit , next ) {
118+ return
119+ }
120+ if next == cursor {
121+ select {
122+ case <- ctx .Done ():
123+ return
124+ case <- time .After (logsRetryInterval ):
125+ }
126+ }
127+ cursor = next
128+ }
129+ }
130+
131+ // subscriptionContext returns a context derived from ctx that is cancelled once subErr closes,
132+ // which happens on eth_unsubscribe and when the connection drops, or once cancel is called.
133+ func subscriptionContext (ctx context.Context , subErr <- chan error ) (context.Context , context.CancelFunc ) {
134+ ctx , cancel := context .WithCancel (ctx )
135+ go func () {
136+ select {
137+ case <- subErr :
138+ cancel ()
139+ case <- ctx .Done ():
140+ }
141+ }()
142+ return ctx , cancel
143+ }
144+
145+ func newLogsErrorNotification (err error ) logsErrorNotification {
146+ notification := logsErrorNotification {Error : err .Error ()}
147+ var oversized * oversizedBlockError
148+ if errors .As (err , & oversized ) {
149+ height := hexutil .Uint64 (oversized .height )
150+ notification .BlockNumber = & height
151+ }
152+ return notification
153+ }
154+
22155// NewHeads serves eth_subscribe("newHeads"), pushing one Ethereum header per
23156// block executed after the subscription is created.
24157func (api * subscribeAPI ) NewHeads (ctx context.Context ) (* ethrpc.Subscription , error ) {
@@ -64,14 +197,8 @@ func (api *subscribeAPI) streamHeads(
64197 logger .Error ("newHeads: stream panicked" , "subscription" , rpcSub .ID , "panic" , r )
65198 }
66199 }()
67- ctx , cancel := context . WithCancel (ctx )
200+ ctx , cancel := subscriptionContext (ctx , rpcSub . Err () )
68201 defer cancel ()
69- go func () {
70- // Err closes on eth_unsubscribe and when the connection drops; that is
71- // the only way this stream ends.
72- <- rpcSub .Err ()
73- cancel ()
74- }()
75202 for next := last + 1 ; ; next ++ {
76203 window , err := executed .Wait (ctx , func (w atypes.ExecutedBlocks ) bool { return w .Latest ().Number >= next })
77204 if err != nil {
0 commit comments