/
delegate.go
409 lines (366 loc) · 12.6 KB
/
delegate.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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
package directrequest
import (
"context"
"fmt"
"reflect"
"sync"
"github.com/ethereum/go-ethereum/common"
"github.com/pkg/errors"
"github.com/smartcontractkit/chainlink/core/assets"
"github.com/smartcontractkit/chainlink/core/chains/evm"
"github.com/smartcontractkit/chainlink/core/chains/evm/log"
evmtypes "github.com/smartcontractkit/chainlink/core/chains/evm/types"
"github.com/smartcontractkit/chainlink/core/gethwrappers/generated/operator_wrapper"
"github.com/smartcontractkit/chainlink/core/logger"
"github.com/smartcontractkit/chainlink/core/services"
"github.com/smartcontractkit/chainlink/core/services/job"
"github.com/smartcontractkit/chainlink/core/services/pg"
"github.com/smartcontractkit/chainlink/core/services/pipeline"
"github.com/smartcontractkit/chainlink/core/store/models"
"github.com/smartcontractkit/chainlink/core/utils"
)
type (
Delegate struct {
logger logger.Logger
pipelineRunner pipeline.Runner
pipelineORM pipeline.ORM
chHeads chan *evmtypes.Head
chainSet evm.ChainSet
mailMon *utils.MailboxMonitor
}
Config interface {
MinIncomingConfirmations() uint32
MinimumContractPayment() *assets.Link
}
)
var _ job.Delegate = (*Delegate)(nil)
func NewDelegate(
logger logger.Logger,
pipelineRunner pipeline.Runner,
pipelineORM pipeline.ORM,
chainSet evm.ChainSet,
mailMon *utils.MailboxMonitor,
) *Delegate {
return &Delegate{
logger.Named("DirectRequest"),
pipelineRunner,
pipelineORM,
make(chan *evmtypes.Head, 1),
chainSet,
mailMon,
}
}
func (d *Delegate) JobType() job.Type {
return job.DirectRequest
}
func (d *Delegate) BeforeJobCreated(spec job.Job) {}
func (d *Delegate) AfterJobCreated(spec job.Job) {}
func (d *Delegate) BeforeJobDeleted(spec job.Job) {}
// ServicesForSpec returns the log listener service for a direct request job
func (d *Delegate) ServicesForSpec(jb job.Job) ([]job.ServiceCtx, error) {
if jb.DirectRequestSpec == nil {
return nil, errors.Errorf("DirectRequest: directrequest.Delegate expects a *job.DirectRequestSpec to be present, got %v", jb)
}
chain, err := d.chainSet.Get(jb.DirectRequestSpec.EVMChainID.ToInt())
if err != nil {
return nil, err
}
concreteSpec := job.LoadEnvConfigVarsDR(chain.Config(), *jb.DirectRequestSpec)
oracle, err := operator_wrapper.NewOperator(concreteSpec.ContractAddress.Address(), chain.Client())
if err != nil {
return nil, errors.Wrapf(err, "DirectRequest: failed to create an operator wrapper for address: %v", concreteSpec.ContractAddress.Address().String())
}
svcLogger := d.logger.
With(
"contract", concreteSpec.ContractAddress.Address().String(),
"jobName", jb.PipelineSpec.JobName,
"jobID", jb.PipelineSpec.JobID,
"externalJobID", jb.ExternalJobID,
)
logListener := &listener{
logger: svcLogger.Named("DirectRequest"),
config: chain.Config(),
logBroadcaster: chain.LogBroadcaster(),
oracle: oracle,
pipelineRunner: d.pipelineRunner,
pipelineORM: d.pipelineORM,
mailMon: d.mailMon,
job: jb,
mbOracleRequests: utils.NewHighCapacityMailbox[log.Broadcast](),
mbOracleCancelRequests: utils.NewHighCapacityMailbox[log.Broadcast](),
minIncomingConfirmations: concreteSpec.MinIncomingConfirmations.Uint32,
requesters: concreteSpec.Requesters,
minContractPayment: concreteSpec.MinContractPayment,
chStop: make(chan struct{}),
}
var services []job.ServiceCtx
services = append(services, logListener)
return services, nil
}
var (
_ log.Listener = &listener{}
_ job.ServiceCtx = &listener{}
)
type listener struct {
logger logger.Logger
config Config
logBroadcaster log.Broadcaster
oracle operator_wrapper.OperatorInterface
pipelineRunner pipeline.Runner
pipelineORM pipeline.ORM
mailMon *utils.MailboxMonitor
job job.Job
runs sync.Map
shutdownWaitGroup sync.WaitGroup
mbOracleRequests *utils.Mailbox[log.Broadcast]
mbOracleCancelRequests *utils.Mailbox[log.Broadcast]
minIncomingConfirmations uint32
requesters models.AddressCollection
minContractPayment *assets.Link
chStop chan struct{}
utils.StartStopOnce
}
// Start complies with job.Service
func (l *listener) Start(context.Context) error {
return l.StartOnce("DirectRequestListener", func() error {
unsubscribeLogs := l.logBroadcaster.Register(l, log.ListenerOpts{
Contract: l.oracle.Address(),
ParseLog: l.oracle.ParseLog,
LogsWithTopics: map[common.Hash][][]log.Topic{
operator_wrapper.OperatorOracleRequest{}.Topic(): {{log.Topic(l.job.ExternalIDEncodeBytesToTopic()), log.Topic(l.job.ExternalIDEncodeStringToTopic())}},
operator_wrapper.OperatorCancelOracleRequest{}.Topic(): {{log.Topic(l.job.ExternalIDEncodeBytesToTopic()), log.Topic(l.job.ExternalIDEncodeStringToTopic())}},
},
MinIncomingConfirmations: l.minIncomingConfirmations,
})
l.shutdownWaitGroup.Add(3)
go l.processOracleRequests()
go l.processCancelOracleRequests()
go func() {
<-l.chStop
unsubscribeLogs()
l.shutdownWaitGroup.Done()
}()
l.mailMon.Monitor(l.mbOracleRequests, "DirectRequest", "Requests", fmt.Sprint(l.job.PipelineSpec.JobID))
l.mailMon.Monitor(l.mbOracleCancelRequests, "DirectRequest", "Cancel", fmt.Sprint(l.job.PipelineSpec.JobID))
return nil
})
}
// Close complies with job.Service
func (l *listener) Close() error {
return l.StopOnce("DirectRequestListener", func() error {
l.runs.Range(func(key, runCloserChannelIf interface{}) bool {
runCloserChannel, _ := runCloserChannelIf.(chan struct{})
close(runCloserChannel)
return true
})
l.runs = sync.Map{}
close(l.chStop)
l.shutdownWaitGroup.Wait()
return services.MultiClose{l.mbOracleRequests, l.mbOracleCancelRequests}.Close()
})
}
func (l *listener) HandleLog(lb log.Broadcast) {
log := lb.DecodedLog()
if log == nil || reflect.ValueOf(log).IsNil() {
l.logger.Error("HandleLog: ignoring nil value")
return
}
switch log := log.(type) {
case *operator_wrapper.OperatorOracleRequest:
wasOverCapacity := l.mbOracleRequests.Deliver(lb)
if wasOverCapacity {
l.logger.Error("OracleRequest log mailbox is over capacity - dropped the oldest log")
}
case *operator_wrapper.OperatorCancelOracleRequest:
wasOverCapacity := l.mbOracleCancelRequests.Deliver(lb)
if wasOverCapacity {
l.logger.Error("CancelOracleRequest log mailbox is over capacity - dropped the oldest log")
}
default:
l.logger.Warnf("Unexpected log type %T", log)
}
}
func (l *listener) processOracleRequests() {
for {
select {
case <-l.chStop:
l.shutdownWaitGroup.Done()
return
case <-l.mbOracleRequests.Notify():
l.handleReceivedLogs(l.mbOracleRequests)
}
}
}
func (l *listener) processCancelOracleRequests() {
for {
select {
case <-l.chStop:
l.shutdownWaitGroup.Done()
return
case <-l.mbOracleCancelRequests.Notify():
l.handleReceivedLogs(l.mbOracleCancelRequests)
}
}
}
func (l *listener) handleReceivedLogs(mailbox *utils.Mailbox[log.Broadcast]) {
for {
select {
case <-l.chStop:
return
default:
}
lb, exists := mailbox.Retrieve()
if !exists {
return
}
was, err := l.logBroadcaster.WasAlreadyConsumed(lb)
if err != nil {
l.logger.Errorw("Could not determine if log was already consumed", "error", err)
continue
} else if was {
continue
}
logJobSpecID := lb.RawLog().Topics[1]
if logJobSpecID == (common.Hash{}) || (logJobSpecID != l.job.ExternalIDEncodeStringToTopic() && logJobSpecID != l.job.ExternalIDEncodeBytesToTopic()) {
l.logger.Debugw("Skipping Run for Log with wrong Job ID", "logJobSpecID", logJobSpecID)
l.markLogConsumed(lb)
continue
}
log := lb.DecodedLog()
if log == nil || reflect.ValueOf(log).IsNil() {
l.logger.Error("HandleLog: ignoring nil value")
continue
}
switch log := log.(type) {
case *operator_wrapper.OperatorOracleRequest:
l.handleOracleRequest(log, lb)
case *operator_wrapper.OperatorCancelOracleRequest:
l.handleCancelOracleRequest(log, lb)
default:
l.logger.Warnf("Unexpected log type %T", log)
}
}
}
func oracleRequestToMap(request *operator_wrapper.OperatorOracleRequest) map[string]interface{} {
result := make(map[string]interface{})
result["specId"] = fmt.Sprintf("0x%x", request.SpecId)
result["requester"] = request.Requester.Hex()
result["requestId"] = formatRequestId(request.RequestId)
result["payment"] = fmt.Sprintf("%v", request.Payment)
result["callbackAddr"] = request.CallbackAddr.Hex()
result["callbackFunctionId"] = fmt.Sprintf("0x%x", request.CallbackFunctionId)
result["cancelExpiration"] = fmt.Sprintf("%v", request.CancelExpiration)
result["dataVersion"] = fmt.Sprintf("%v", request.DataVersion)
result["data"] = fmt.Sprintf("0x%x", request.Data)
return result
}
func (l *listener) handleOracleRequest(request *operator_wrapper.OperatorOracleRequest, lb log.Broadcast) {
l.logger.Infow("Oracle request received",
"specId", fmt.Sprintf("%0x", request.SpecId),
"requester", request.Requester,
"requestId", fmt.Sprintf("%0x", request.RequestId),
"payment", request.Payment,
"callbackAddr", request.CallbackAddr,
"callbackFunctionId", fmt.Sprintf("%0x", request.CallbackFunctionId),
"cancelExpiration", request.CancelExpiration,
"dataVersion", request.DataVersion,
"data", fmt.Sprintf("%0x", request.Data),
)
if !l.allowRequester(request.Requester) {
l.logger.Infow("Rejected run for invalid requester",
"requester", request.Requester,
"allowedRequesters", l.requesters.ToStrings(),
)
l.markLogConsumed(lb)
return
}
var minContractPayment *assets.Link
if l.minContractPayment != nil {
minContractPayment = l.minContractPayment
} else {
minContractPayment = l.config.MinimumContractPayment()
}
if minContractPayment != nil && request.Payment != nil {
requestPayment := assets.Link(*request.Payment)
if minContractPayment.Cmp(&requestPayment) > 0 {
l.logger.Warnw("Rejected run for insufficient payment",
"minContractPayment", minContractPayment.String(),
"requestPayment", requestPayment.String(),
)
l.markLogConsumed(lb)
return
}
}
meta := make(map[string]interface{})
meta["oracleRequest"] = oracleRequestToMap(request)
runCloserChannel := make(chan struct{})
runCloserChannelIf, loaded := l.runs.LoadOrStore(formatRequestId(request.RequestId), runCloserChannel)
if loaded {
runCloserChannel, _ = runCloserChannelIf.(chan struct{})
}
ctx, cancel := utils.ContextFromChan(runCloserChannel)
defer cancel()
vars := pipeline.NewVarsFrom(map[string]interface{}{
"jobSpec": map[string]interface{}{
"databaseID": l.job.ID,
"externalJobID": l.job.ExternalJobID,
"name": l.job.Name.ValueOrZero(),
"pipelineSpec": &pipeline.Spec{
ForwardingAllowed: l.job.ForwardingAllowed,
},
},
"jobRun": map[string]interface{}{
"meta": meta,
"logBlockHash": request.Raw.BlockHash,
"logBlockNumber": request.Raw.BlockNumber,
"logTxHash": request.Raw.TxHash,
"logAddress": request.Raw.Address,
"logTopics": request.Raw.Topics,
"logData": request.Raw.Data,
"blockReceiptsRoot": lb.ReceiptsRoot(),
"blockTransactionsRoot": lb.TransactionsRoot(),
"blockStateRoot": lb.StateRoot(),
},
})
run := pipeline.NewRun(*l.job.PipelineSpec, vars)
_, err := l.pipelineRunner.Run(ctx, &run, l.logger, true, func(tx pg.Queryer) error {
l.markLogConsumed(lb, pg.WithQueryer(tx))
return nil
})
if ctx.Err() != nil {
return
} else if err != nil {
l.logger.Errorw("Failed executing run", "err", err)
}
}
func (l *listener) allowRequester(requester common.Address) bool {
if len(l.requesters) == 0 {
return true
}
for _, addr := range l.requesters {
if addr == requester {
return true
}
}
return false
}
// Cancels runs that haven't been started yet, with the given request ID
func (l *listener) handleCancelOracleRequest(request *operator_wrapper.OperatorCancelOracleRequest, lb log.Broadcast) {
runCloserChannelIf, loaded := l.runs.LoadAndDelete(formatRequestId(request.RequestId))
if loaded {
close(runCloserChannelIf.(chan struct{}))
}
l.markLogConsumed(lb)
}
func (l *listener) markLogConsumed(lb log.Broadcast, qopts ...pg.QOpt) {
if err := l.logBroadcaster.MarkConsumed(lb, qopts...); err != nil {
l.logger.Errorw("Unable to mark log consumed", "err", err, "log", lb.String())
}
}
// JobID - Job complies with log.Listener
func (l *listener) JobID() int32 {
return l.job.ID
}
func formatRequestId(requestId [32]byte) string {
return fmt.Sprintf("0x%x", requestId)
}