-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
listener_v2_types.go
324 lines (292 loc) · 10.1 KB
/
listener_v2_types.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
package v2
import (
"fmt"
"math/big"
"time"
"github.com/ethereum/go-ethereum/common"
heaps "github.com/theodesp/go-heaps"
txmgrcommon "github.com/smartcontractkit/chainlink/v2/common/txmgr"
"github.com/smartcontractkit/chainlink/v2/core/chains/evm/txmgr"
"github.com/smartcontractkit/chainlink/v2/core/logger"
"github.com/smartcontractkit/chainlink/v2/core/services/pg"
"github.com/smartcontractkit/chainlink/v2/core/services/pipeline"
"github.com/smartcontractkit/chainlink/v2/core/services/vrf/vrfcommon"
)
type errPossiblyInsufficientFunds struct{}
func (errPossiblyInsufficientFunds) Error() string {
return "Simulation errored, possibly insufficient funds. Request will remain unprocessed until funds are available"
}
type errBlockhashNotInStore struct{}
func (errBlockhashNotInStore) Error() string {
return "Blockhash not in store"
}
type errProofVerificationFailed struct{}
func (errProofVerificationFailed) Error() string {
return "Proof verification failed"
}
type fulfilledReqV2 struct {
blockNumber uint64
reqID string
}
func (a fulfilledReqV2) Compare(b heaps.Item) int {
a1 := a
a2 := b.(fulfilledReqV2)
switch {
case a1.blockNumber > a2.blockNumber:
return 1
case a1.blockNumber < a2.blockNumber:
return -1
default:
return 0
}
}
type pendingRequest struct {
confirmedAtBlock uint64
req RandomWordsRequested
utcTimestamp time.Time
// used for exponential backoff when retrying
attempts int
lastTry time.Time
}
type vrfPipelineResult struct {
err error
// maxFee indicates how much juels (link) or wei (ether) would be paid for the VRF request
// if it were to be fulfilled at the maximum gas price (i.e gas lane gas price).
maxFee *big.Int
// fundsNeeded indicates a "minimum balance" in juels or wei that must be held in the
// subscription's account in order to fulfill the request.
fundsNeeded *big.Int
run *pipeline.Run
payload string
gasLimit uint32
req pendingRequest
proof VRFProof
reqCommitment RequestCommitment
}
// batchFulfillment contains all the information needed in order to
// perform a batch fulfillment operation on the batch VRF coordinator.
type batchFulfillment struct {
proofs []VRFProof
commitments []RequestCommitment
totalGasLimit uint32
runs []*pipeline.Run
reqIDs []*big.Int
maxFees []*big.Int
txHashes []common.Hash
fromAddress common.Address
version vrfcommon.Version
}
func newBatchFulfillment(result vrfPipelineResult, fromAddress common.Address, version vrfcommon.Version) *batchFulfillment {
return &batchFulfillment{
proofs: []VRFProof{
result.proof,
},
commitments: []RequestCommitment{
result.reqCommitment,
},
totalGasLimit: result.gasLimit,
runs: []*pipeline.Run{
result.run,
},
reqIDs: []*big.Int{
result.req.req.RequestID(),
},
maxFees: []*big.Int{
result.maxFee,
},
txHashes: []common.Hash{
result.req.req.Raw().TxHash,
},
fromAddress: fromAddress,
version: version,
}
}
// batchFulfillments manages many batchFulfillment objects.
// It makes organizing many runs into batches that respect the
// batchGasLimit easy via the addRun method.
type batchFulfillments struct {
fulfillments []*batchFulfillment
batchGasLimit uint32
currIndex int
version vrfcommon.Version
}
func newBatchFulfillments(batchGasLimit uint32, version vrfcommon.Version) *batchFulfillments {
return &batchFulfillments{
fulfillments: []*batchFulfillment{},
batchGasLimit: batchGasLimit,
currIndex: 0,
version: version,
}
}
// addRun adds the given run to an existing batch, or creates a new
// batch if the batchGasLimit that has been configured was exceeded.
func (b *batchFulfillments) addRun(result vrfPipelineResult, fromAddress common.Address) {
if len(b.fulfillments) == 0 {
b.fulfillments = append(b.fulfillments, newBatchFulfillment(result, fromAddress, b.version))
} else {
currBatch := b.fulfillments[b.currIndex]
if (currBatch.totalGasLimit + result.gasLimit) >= b.batchGasLimit {
// don't add to curr batch, add new batch and increment index
b.fulfillments = append(b.fulfillments, newBatchFulfillment(result, fromAddress, b.version))
b.currIndex++
} else {
// we're okay on gas, add to current batch
currBatch.proofs = append(currBatch.proofs, result.proof)
currBatch.commitments = append(currBatch.commitments, result.reqCommitment)
currBatch.totalGasLimit += result.gasLimit
currBatch.runs = append(currBatch.runs, result.run)
currBatch.reqIDs = append(currBatch.reqIDs, result.req.req.RequestID())
currBatch.maxFees = append(currBatch.maxFees, result.maxFee)
currBatch.txHashes = append(currBatch.txHashes, result.req.req.Raw().TxHash)
}
}
}
func (lsn *listenerV2) processBatch(
l logger.Logger,
subID *big.Int,
startBalanceNoReserveLink *big.Int,
maxCallbackGasLimit uint32,
batch *batchFulfillment,
fromAddress common.Address,
) (processedRequestIDs []string) {
start := time.Now()
ctx, cancel := lsn.chStop.NewCtx()
defer cancel()
// Enqueue a single batch tx for requests that we're able to fulfill based on whether
// they passed simulation or not.
var (
payload []byte
err error
txMetaSubID *uint64
txMetaGlobalSubID *string
)
if batch.version == vrfcommon.V2 {
payload, err = batchCoordinatorV2ABI.Pack("fulfillRandomWords", ToV2Proofs(batch.proofs), ToV2Commitments(batch.commitments))
if err != nil {
// should never happen
l.Errorw("Failed to pack batch fulfillRandomWords payload",
"err", err, "proofs", batch.proofs, "commitments", batch.commitments)
return
}
txMetaSubID = ptr(subID.Uint64())
} else if batch.version == vrfcommon.V2Plus {
payload, err = batchCoordinatorV2PlusABI.Pack("fulfillRandomWords", ToV2PlusProofs(batch.proofs), ToV2PlusCommitments(batch.commitments))
if err != nil {
// should never happen
l.Errorw("Failed to pack batch fulfillRandomWords payload",
"err", err, "proofs", batch.proofs, "commitments", batch.commitments)
return
}
txMetaGlobalSubID = ptr(subID.String())
} else {
panic("batch version should be v2 or v2plus")
}
// Bump the total gas limit by a bit so that we account for the overhead of the batch
// contract's calling.
totalGasLimitBumped := batchFulfillmentGasEstimate(
uint64(len(batch.proofs)),
maxCallbackGasLimit,
float64(lsn.job.VRFSpec.BatchFulfillmentGasMultiplier),
)
ll := l.With("numRequestsInBatch", len(batch.reqIDs),
"requestIDs", batch.reqIDs,
"batchSumGasLimit", batch.totalGasLimit,
"fromAddress", fromAddress,
"linkBalance", startBalanceNoReserveLink,
"totalGasLimitBumped", totalGasLimitBumped,
"gasMultiplier", lsn.job.VRFSpec.BatchFulfillmentGasMultiplier,
)
ll.Info("Enqueuing batch fulfillment")
var ethTX txmgr.Tx
err = lsn.q.Transaction(func(tx pg.Queryer) error {
if err = lsn.pipelineRunner.InsertFinishedRuns(batch.runs, true, pg.WithQueryer(tx)); err != nil {
return fmt.Errorf("inserting finished pipeline runs: %w", err)
}
maxLink, maxEth := accumulateMaxLinkAndMaxEth(batch)
var (
txHashes []common.Hash
reqIDHashes []common.Hash
)
copy(txHashes, batch.txHashes)
for _, reqID := range batch.reqIDs {
reqIDHashes = append(reqIDHashes, common.BytesToHash(reqID.Bytes()))
}
ethTX, err = lsn.chain.TxManager().CreateTransaction(ctx, txmgr.TxRequest{
FromAddress: fromAddress,
ToAddress: lsn.batchCoordinator.Address(),
EncodedPayload: payload,
FeeLimit: totalGasLimitBumped,
Strategy: txmgrcommon.NewSendEveryStrategy(),
Meta: &txmgr.TxMeta{
RequestIDs: reqIDHashes,
MaxLink: &maxLink,
MaxEth: &maxEth,
SubID: txMetaSubID,
GlobalSubID: txMetaGlobalSubID,
RequestTxHashes: txHashes,
},
})
if err != nil {
return fmt.Errorf("create batch fulfillment eth transaction: %w", err)
}
return nil
})
if err != nil {
ll.Errorw("Error enqueuing batch fulfillments, requeuing requests", "err", err)
return
}
ll.Infow("Enqueued fulfillment", "ethTxID", ethTX.GetID())
// mark requests as processed since the fulfillment has been successfully enqueued
// to the txm.
for _, reqID := range batch.reqIDs {
processedRequestIDs = append(processedRequestIDs, reqID.String())
vrfcommon.IncProcessedReqs(lsn.job.Name.ValueOrZero(), lsn.job.ExternalJobID, vrfcommon.V2)
}
ll.Infow("Successfully enqueued batch", "duration", time.Since(start))
return
}
// getReadyAndExpired filters out requests that are expired from the given pendingRequest slice
// and returns requests that are ready for processing.
func (lsn *listenerV2) getReadyAndExpired(l logger.Logger, reqs []pendingRequest) (ready []pendingRequest, expired []string) {
for _, req := range reqs {
// Check if we can ignore the request due to its age.
if time.Now().UTC().Sub(req.utcTimestamp) >= lsn.job.VRFSpec.RequestTimeout {
l.Infow("Request too old, dropping it",
"reqID", req.req.RequestID().String(),
"txHash", req.req.Raw().TxHash)
expired = append(expired, req.req.RequestID().String())
vrfcommon.IncDroppedReqs(lsn.job.Name.ValueOrZero(), lsn.job.ExternalJobID, vrfcommon.V2, vrfcommon.ReasonAge)
continue
}
// we always check if the requests are already fulfilled prior to trying to fulfill them again
ready = append(ready, req)
}
return
}
func batchFulfillmentGasEstimate(
batchSize uint64,
maxCallbackGasLimit uint32,
gasMultiplier float64,
) uint32 {
return uint32(
gasMultiplier * float64((uint64(maxCallbackGasLimit)+400_000)+batchSize*BatchFulfillmentIterationGasCost),
)
}
func accumulateMaxLinkAndMaxEth(batch *batchFulfillment) (maxLinkStr string, maxEthStr string) {
maxLink := big.NewInt(0)
maxEth := big.NewInt(0)
for i := range batch.commitments {
if batch.commitments[i].VRFVersion == vrfcommon.V2 {
// v2 always bills in link
maxLink.Add(maxLink, batch.maxFees[i])
} else {
// v2plus can bill in link or eth, depending on the commitment
if batch.commitments[i].NativePayment() {
maxEth.Add(maxEth, batch.maxFees[i])
} else {
maxLink.Add(maxLink, batch.maxFees[i])
}
}
}
return maxLink.String(), maxEth.String()
}