-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdirect.go
More file actions
495 lines (435 loc) · 12.5 KB
/
direct.go
File metadata and controls
495 lines (435 loc) · 12.5 KB
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
package submit
import (
"context"
"errors"
"fmt"
"strconv"
"strings"
"sync"
"time"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/anypb"
)
const (
defaultFeeDenom = "utia"
defaultPollInterval = time.Second
maxSequenceRetryRounds = 2
)
var (
errSequenceMismatch = errors.New("account sequence mismatch")
errTooManyInFlight = errors.New("too many in-flight submissions")
)
// DirectConfig contains the fixed submission settings Apex owns for direct
// celestia-app writes.
type DirectConfig struct {
ChainID string
GasPrice float64
MaxGasPrice float64
ConfirmationTimeout time.Duration
}
// DirectSubmitter signs and submits Celestia BlobTx payloads directly to
// celestia-app over Cosmos SDK gRPC.
type DirectSubmitter struct {
app AppClient
signer *Signer
chainID string
gasPrice float64
maxGasPrice float64
confirmationTimeout time.Duration
pollInterval time.Duration
feeDenom string
mu sync.Mutex
inFlight int
accountNumber uint64
nextSequence uint64
sequenceReady bool
pendingSequences map[string]uint64
maxInFlight int
}
// NewDirectSubmitter builds a concrete single-account submitter.
func NewDirectSubmitter(app AppClient, signer *Signer, cfg DirectConfig) (*DirectSubmitter, error) {
if app == nil {
return nil, errors.New("submission app client is required")
}
if signer == nil {
return nil, errors.New("submission signer is required")
}
if cfg.ChainID == "" {
return nil, errors.New("submission chain id is required")
}
if cfg.ConfirmationTimeout <= 0 {
return nil, errors.New("submission confirmation timeout must be positive")
}
if cfg.GasPrice < 0 {
return nil, errors.New("submission gas price must be non-negative")
}
if cfg.MaxGasPrice < 0 {
return nil, errors.New("submission max gas price must be non-negative")
}
if cfg.MaxGasPrice > 0 && cfg.GasPrice > cfg.MaxGasPrice {
return nil, errors.New("submission gas price must not exceed the max gas price")
}
return &DirectSubmitter{
app: app,
signer: signer,
chainID: cfg.ChainID,
gasPrice: cfg.GasPrice,
maxGasPrice: cfg.MaxGasPrice,
confirmationTimeout: cfg.ConfirmationTimeout,
pollInterval: defaultPollInterval,
feeDenom: defaultFeeDenom,
pendingSequences: make(map[string]uint64),
}, nil
}
func (s *DirectSubmitter) Close() error {
if s == nil || s.app == nil {
return nil
}
return s.app.Close()
}
// Submit serializes sequence reservation and broadcast for the configured
// signer, then waits for confirmation without blocking the next nonce.
func (s *DirectSubmitter) Submit(ctx context.Context, req *Request) (*Result, error) {
if err := validateSubmitRequest(req); err != nil {
return nil, err
}
if err := s.startSubmission(); err != nil {
return nil, err
}
defer s.finishSubmission()
broadcast, err := s.broadcastTx(ctx, req)
if err != nil {
return nil, err
}
return s.waitForConfirmation(ctx, broadcast.Hash)
}
func validateSubmitRequest(req *Request) error {
if req == nil {
return errors.New("submission request is required")
}
if len(req.Blobs) == 0 {
return errors.New("at least one blob is required")
}
for i := range req.Blobs {
if _, err := convertSquareBlob(req.Blobs[i]); err != nil {
return fmt.Errorf("validate submission blob %d: %w", i, err)
}
}
return nil
}
func (s *DirectSubmitter) broadcastTx(ctx context.Context, req *Request) (*TxStatus, error) {
s.mu.Lock()
defer s.mu.Unlock()
var lastErr error
for range maxSequenceRetryRounds {
account, err := s.nextAccountLocked(ctx)
if err != nil {
return nil, err
}
txBytes, err := s.buildBlobTx(req, account)
if err != nil {
return nil, err
}
broadcast, err := s.app.BroadcastTx(ctx, txBytes)
if err != nil {
if isSequenceMismatchText(err.Error()) {
s.recoverSequenceLocked(account, err.Error())
lastErr = fmt.Errorf("%w: %w", errSequenceMismatch, err)
continue
}
return nil, fmt.Errorf("broadcast blob tx: %w", err)
}
if err := checkTxStatus("broadcast", broadcast); err != nil {
if errors.Is(err, errSequenceMismatch) {
s.recoverSequenceLocked(account, err.Error())
lastErr = err
continue
}
return nil, err
}
if broadcast.Hash != "" {
s.rememberPendingLocked(broadcast.Hash, account.Sequence)
}
s.nextSequence = account.Sequence + 1
s.sequenceReady = true
return broadcast, nil
}
return nil, lastErr
}
func (s *DirectSubmitter) nextAccountLocked(ctx context.Context) (*AccountInfo, error) {
if !s.sequenceReady {
account, err := s.app.AccountInfo(ctx, s.signer.Address())
if err != nil {
return nil, fmt.Errorf("query submission account: %w", err)
}
if account == nil {
return nil, errors.New("query submission account: empty response")
}
s.accountNumber = account.AccountNumber
s.nextSequence = account.Sequence
s.sequenceReady = true
if err := s.reconcilePendingLocked(ctx); err != nil {
return nil, err
}
}
return &AccountInfo{
Address: s.signer.Address(),
AccountNumber: s.accountNumber,
Sequence: s.nextSequence,
}, nil
}
func (s *DirectSubmitter) invalidateSequenceLocked() {
s.accountNumber = 0
s.nextSequence = 0
s.sequenceReady = false
}
func (s *DirectSubmitter) startSubmission() error {
s.mu.Lock()
defer s.mu.Unlock()
if s.maxInFlight > 0 && s.inFlight >= s.maxInFlight {
return errTooManyInFlight
}
s.inFlight++
return nil
}
func (s *DirectSubmitter) finishSubmission() {
s.mu.Lock()
defer s.mu.Unlock()
if s.inFlight > 0 {
s.inFlight--
}
}
func (s *DirectSubmitter) recoverSequenceLocked(account *AccountInfo, errText string) {
expected, ok := expectedSequenceFromMismatchText(errText)
if !ok {
s.invalidateSequenceLocked()
return
}
s.accountNumber = account.AccountNumber
s.nextSequence = expected
s.sequenceReady = true
}
func (s *DirectSubmitter) reconcilePendingLocked(ctx context.Context) error {
if len(s.pendingSequences) == 0 {
return nil
}
nextSequence := s.nextSequence
for hash, sequence := range s.pendingSequences {
_, err := s.app.GetTx(ctx, hash)
if err == nil {
delete(s.pendingSequences, hash)
continue
}
if isTxNotFound(err) {
if sequence >= nextSequence {
nextSequence = sequence + 1
}
continue
}
return fmt.Errorf("reconcile pending blob tx %s: %w", hash, err)
}
s.nextSequence = nextSequence
return nil
}
func (s *DirectSubmitter) rememberPendingLocked(hash string, sequence uint64) {
if hash == "" {
return
}
s.pendingSequences[hash] = sequence
}
func (s *DirectSubmitter) clearPending(hash string) {
if hash == "" {
return
}
s.mu.Lock()
defer s.mu.Unlock()
delete(s.pendingSequences, hash)
}
func (s *DirectSubmitter) buildBlobTx(req *Request, account *AccountInfo) ([]byte, error) {
pfb, err := BuildMsgPayForBlobs(s.signer.Address(), req.Blobs)
if err != nil {
return nil, fmt.Errorf("build pay-for-blobs message: %w", err)
}
msg, err := MarshalMsgPayForBlobsAny(pfb)
if err != nil {
return nil, err
}
gasLimit, gasPrice, err := s.resolveFees(req.Blobs, req.Options, account.Sequence)
if err != nil {
return nil, err
}
feeAmount, err := FeeAmountFromGasPrice(gasLimit, gasPrice)
if err != nil {
return nil, err
}
signerInfo, err := BuildSignerInfo(s.signer.PublicKey(), account.Sequence)
if err != nil {
return nil, err
}
authInfo, err := BuildAuthInfo(signerInfo, s.feeDenom, feeAmount, gasLimit, "", feeGranter(req.Options))
if err != nil {
return nil, err
}
authInfoBytes, err := MarshalAuthInfo(authInfo)
if err != nil {
return nil, err
}
bodyBytes, err := MarshalTxBody([]*anypb.Any{msg}, "", 0)
if err != nil {
return nil, err
}
signDocBytes, err := BuildSignDoc(bodyBytes, authInfoBytes, s.chainID, account.AccountNumber)
if err != nil {
return nil, err
}
signature, err := s.signer.Sign(signDocBytes)
if err != nil {
return nil, fmt.Errorf("sign pay-for-blobs tx: %w", err)
}
innerTx, err := MarshalTxRaw(bodyBytes, authInfoBytes, signature)
if err != nil {
return nil, err
}
return MarshalBlobTx(innerTx, req.Blobs)
}
func (s *DirectSubmitter) resolveFees(blobs []Blob, opts *TxConfig, sequence uint64) (uint64, float64, error) {
if err := s.validateOptions(opts); err != nil {
return 0, 0, err
}
gasPrice, err := resolveGasPrice(s.gasPrice, opts)
if err != nil {
return 0, 0, err
}
effectiveMaxGasPrice, err := resolveMaxGasPrice(s.maxGasPrice, opts)
if err != nil {
return 0, 0, err
}
if effectiveMaxGasPrice > 0 && gasPrice > effectiveMaxGasPrice {
return 0, 0, fmt.Errorf("submission gas price %.6f exceeds the max gas price %.6f", gasPrice, effectiveMaxGasPrice)
}
if opts != nil && opts.Gas > 0 {
return opts.Gas, gasPrice, nil
}
gasLimit, err := EstimateGas(blobs, sequence)
if err != nil {
return 0, 0, err
}
return gasLimit, gasPrice, nil
}
func (s *DirectSubmitter) validateOptions(opts *TxConfig) error {
if opts == nil {
return nil
}
if opts.KeyName != "" {
return errors.New("submission tx option key_name is not supported by the direct submitter")
}
if opts.TxPriority != 0 {
return errors.New("submission tx option tx_priority is not supported by the direct submitter")
}
if opts.SignerAddress != "" && opts.SignerAddress != s.signer.Address() {
return fmt.Errorf("submission signer_address %q does not match configured signer %q", opts.SignerAddress, s.signer.Address())
}
return nil
}
func resolveGasPrice(defaultGasPrice float64, opts *TxConfig) (float64, error) {
gasPrice := defaultGasPrice
if opts != nil && (opts.IsGasPriceSet || opts.GasPrice > 0) {
gasPrice = opts.GasPrice
}
if gasPrice <= 0 {
return 0, errors.New("submission gas price must be configured or provided per request")
}
return gasPrice, nil
}
func resolveMaxGasPrice(defaultMaxGasPrice float64, opts *TxConfig) (float64, error) {
effectiveMaxGasPrice := defaultMaxGasPrice
if opts == nil {
return effectiveMaxGasPrice, nil
}
if opts.MaxGasPrice < 0 {
return 0, errors.New("submission tx option max_gas_price must be non-negative")
}
if opts.MaxGasPrice > 0 && (effectiveMaxGasPrice == 0 || opts.MaxGasPrice < effectiveMaxGasPrice) {
effectiveMaxGasPrice = opts.MaxGasPrice
}
return effectiveMaxGasPrice, nil
}
func feeGranter(opts *TxConfig) string {
if opts == nil {
return ""
}
return opts.FeeGranterAddress
}
func (s *DirectSubmitter) waitForConfirmation(parent context.Context, hash string) (*Result, error) {
if hash == "" {
return nil, errors.New("broadcast returned an empty tx hash")
}
ctx, cancel := context.WithTimeout(parent, s.confirmationTimeout)
defer cancel()
ticker := time.NewTicker(s.pollInterval)
defer ticker.Stop()
for {
tx, err := s.app.GetTx(ctx, hash)
if err == nil {
s.clearPending(hash)
if err := checkTxStatus("confirm", tx); err != nil {
return nil, err
}
if tx.Height <= 0 {
return nil, fmt.Errorf("confirm tx %s returned an invalid height %d", hash, tx.Height)
}
return &Result{Height: uint64(tx.Height)}, nil
}
if !isTxNotFound(err) {
return nil, fmt.Errorf("confirm blob tx %s: %w", hash, err)
}
select {
case <-ctx.Done():
return nil, fmt.Errorf("confirm blob tx %s: %w", hash, ctx.Err())
case <-ticker.C:
}
}
}
func checkTxStatus(stage string, tx *TxStatus) error {
if tx == nil {
return fmt.Errorf("%s blob tx returned an empty response", stage)
}
if tx.Code == 0 {
return nil
}
if isSequenceMismatchText(tx.RawLog) {
return fmt.Errorf("%w: %s", errSequenceMismatch, tx.RawLog)
}
if tx.Codespace != "" {
return fmt.Errorf("%s blob tx failed with code %d (%s): %s", stage, tx.Code, tx.Codespace, tx.RawLog)
}
return fmt.Errorf("%s blob tx failed with code %d: %s", stage, tx.Code, tx.RawLog)
}
func isSequenceMismatchText(text string) bool {
text = strings.ToLower(text)
return strings.Contains(text, "account sequence mismatch") || strings.Contains(text, "incorrect account sequence")
}
func expectedSequenceFromMismatchText(text string) (uint64, bool) {
lower := strings.ToLower(text)
idx := strings.Index(lower, "expected ")
if idx < 0 {
return 0, false
}
start := idx + len("expected ")
end := start
for end < len(lower) && lower[end] >= '0' && lower[end] <= '9' {
end++
}
if end == start {
return 0, false
}
sequence, err := strconv.ParseUint(lower[start:end], 10, 64)
if err != nil {
return 0, false
}
return sequence, true
}
func isTxNotFound(err error) bool {
return status.Code(err) == codes.NotFound
}