-
Notifications
You must be signed in to change notification settings - Fork 31
/
filter_api.go
235 lines (200 loc) · 6.7 KB
/
filter_api.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
package rpcapi
import (
"context"
"fmt"
"sync/atomic"
"time"
"github.com/ethereum/go-ethereum/log"
subscriptioncommon "github.com/ten-protocol/go-ten/go/common/subscription"
tenrpc "github.com/ten-protocol/go-ten/go/rpc"
gethcommon "github.com/ethereum/go-ethereum/common"
"github.com/ten-protocol/go-ten/go/common"
wecommon "github.com/ten-protocol/go-ten/tools/walletextension/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ten-protocol/go-ten/lib/gethfork/rpc"
)
type FilterAPI struct {
we *Services
logger log.Logger
}
func NewFilterAPI(we *Services) *FilterAPI {
return &FilterAPI{
we: we,
logger: we.logger,
}
}
func (api *FilterAPI) NewPendingTransactionFilter(_ *bool) rpc.ID {
return "not supported"
}
func (api *FilterAPI) NewPendingTransactions(ctx context.Context, fullTx *bool) (*rpc.Subscription, error) {
return nil, fmt.Errorf("not supported")
}
func (api *FilterAPI) NewBlockFilter() rpc.ID {
// not implemented
return ""
}
func (api *FilterAPI) NewHeads(ctx context.Context) (*rpc.Subscription, error) {
notifier, supported := rpc.NotifierFromContext(ctx)
if !supported {
return nil, fmt.Errorf("creation of subscriptions is not supported")
}
subscription := notifier.CreateSubscription()
api.we.NewHeadsService.RegisterNotifier(notifier, subscription)
return subscription, nil
}
func (api *FilterAPI) Logs(ctx context.Context, crit common.FilterCriteria) (*rpc.Subscription, error) {
audit(api.we, "start Logs subscription %v", crit)
subNotifier, user, err := getUserAndNotifier(ctx, api)
if err != nil {
return nil, err
}
// determine the accounts to use for the backend subscriptions
candidateAddresses := user.GetAllAddresses()
if len(candidateAddresses) > 1 {
candidateAddresses = searchForAddressInFilterCriteria(crit, user.GetAllAddresses())
// when we can't determine which addresses to use based on the criteria, use all of them
if len(candidateAddresses) == 0 {
candidateAddresses = user.GetAllAddresses()
}
}
backendWSConnections := make([]*tenrpc.EncRPCClient, 0)
inputChannels := make([]chan types.Log, 0)
errorChannels := make([]<-chan error, 0)
backendSubscriptions := make([]*rpc.ClientSubscription, 0)
for _, address := range candidateAddresses {
rpcWSClient, err := connectWS(ctx, user.accounts[*address], api.we.Logger())
if err != nil {
return nil, err
}
backendWSConnections = append(backendWSConnections, rpcWSClient)
inCh := make(chan types.Log)
backendSubscription, err := rpcWSClient.Subscribe(ctx, "eth", inCh, "logs", crit)
if err != nil {
fmt.Printf("could not connect to backend %s", err)
return nil, err
}
inputChannels = append(inputChannels, inCh)
errorChannels = append(errorChannels, backendSubscription.Err())
backendSubscriptions = append(backendSubscriptions, backendSubscription)
}
dedupeBuffer := NewCircularBuffer(wecommon.DeduplicationBufferSize)
subscription := subNotifier.CreateSubscription()
unsubscribedByClient := atomic.Bool{}
unsubscribedByBackend := atomic.Bool{}
go subscriptioncommon.ForwardFromChannels(
inputChannels,
func(log types.Log) error {
uniqueLogKey := LogKey{
BlockHash: log.BlockHash,
TxHash: log.TxHash,
Index: log.Index,
}
if !dedupeBuffer.Contains(uniqueLogKey) {
dedupeBuffer.Push(uniqueLogKey)
return subNotifier.Notify(subscription.ID, log)
}
return nil
},
func() {
// release resources
api.closeConnections(backendSubscriptions, backendWSConnections)
}, // todo - we can implement reconnect logic here
&unsubscribedByBackend,
&unsubscribedByClient,
12*time.Hour,
api.logger,
)
// handles any of the backend connections being closed
go subscriptioncommon.HandleUnsubscribeErrChan(errorChannels, func() {
unsubscribedByBackend.Store(true)
})
// handles "unsubscribe" from the user
go subscriptioncommon.HandleUnsubscribe(subscription, func() {
unsubscribedByClient.Store(true)
api.closeConnections(backendSubscriptions, backendWSConnections)
})
return subscription, err
}
func (api *FilterAPI) closeConnections(backendSubscriptions []*rpc.ClientSubscription, backendWSConnections []*tenrpc.EncRPCClient) {
for _, backendSub := range backendSubscriptions {
backendSub.Unsubscribe()
}
for _, connection := range backendWSConnections {
_ = returnConn(api.we.rpcWSConnPool, connection.BackingClient(), api.logger)
}
}
func getUserAndNotifier(ctx context.Context, api *FilterAPI) (*rpc.Notifier, *GWUser, error) {
subNotifier, supported := rpc.NotifierFromContext(ctx)
if !supported {
return nil, nil, fmt.Errorf("creation of subscriptions is not supported")
}
// todo - we might want to allow access to public logs
if len(subNotifier.UserID) == 0 {
return nil, nil, fmt.Errorf("illegal access")
}
user, err := getUser(subNotifier.UserID, api.we)
if err != nil {
return nil, nil, fmt.Errorf("illegal access: %s, %w", subNotifier.UserID, err)
}
return subNotifier, user, nil
}
func searchForAddressInFilterCriteria(filterCriteria common.FilterCriteria, possibleAddresses []*gethcommon.Address) []*gethcommon.Address {
result := make([]*gethcommon.Address, 0)
addrMap := toMap(possibleAddresses)
for _, topicCondition := range filterCriteria.Topics {
for _, topic := range topicCondition {
potentialAddr := common.ExtractPotentialAddress(topic)
if potentialAddr != nil && addrMap[*potentialAddr] != nil {
result = append(result, potentialAddr)
}
}
}
return result
}
func (api *FilterAPI) NewFilter(crit common.FilterCriteria) (rpc.ID, error) {
return rpc.NewID(), rpcNotImplemented
}
func (api *FilterAPI) GetLogs(ctx context.Context, crit common.FilterCriteria) ([]*types.Log, error) {
logs, err := ExecAuthRPC[[]*types.Log](
ctx,
api.we,
&ExecCfg{
cacheCfg: &CacheCfg{
CacheTypeDynamic: func() CacheStrategy {
// when the toBlock is not specified, the request is open-ended
if crit.ToBlock != nil && crit.ToBlock.Int64() > 0 {
return LongLiving
}
return LatestBatch
},
},
tryUntilAuthorised: true,
adjustArgs: func(acct *GWAccount) []any {
// convert to something serializable
return []any{common.FromCriteria(crit)}
},
},
"eth_getLogs",
crit,
)
if logs != nil {
return *logs, err
}
return nil, err
}
func (api *FilterAPI) UninstallFilter(id rpc.ID) bool {
// not implemented
return false
}
func (api *FilterAPI) GetFilterLogs(ctx context.Context, id rpc.ID) ([]*types.Log, error) {
//txRec, err := ExecAuthRPC[[]*types.Log](ctx, api.we, "GetFilterLogs", ExecCfg{account: args.From}, id)
//if txRec != nil {
// return *txRec, err
//}
//return common.Hash{}, err
// not implemented
return nil, nil
}
func (api *FilterAPI) GetFilterChanges(id rpc.ID) (interface{}, error) {
return nil, rpcNotImplemented
}