-
Notifications
You must be signed in to change notification settings - Fork 17
/
grpc-server.go
623 lines (576 loc) · 19.2 KB
/
grpc-server.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
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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
package main
import (
"bufio"
"bytes"
"context"
"errors"
"fmt"
"io"
"net"
"runtime"
"sort"
"sync"
"time"
"github.com/gagliardetto/solana-go"
"github.com/ipfs/go-cid"
"github.com/ipld/go-car/util"
cidlink "github.com/ipld/go-ipld-prime/linking/cid"
"github.com/rpcpool/yellowstone-faithful/compactindexsized"
"github.com/rpcpool/yellowstone-faithful/ipld/ipldbindcode"
old_faithful_grpc "github.com/rpcpool/yellowstone-faithful/old-faithful-proto/old-faithful-grpc"
"golang.org/x/sync/errgroup"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
_ "google.golang.org/grpc/encoding/gzip" // Install the gzip compressor
"google.golang.org/grpc/status"
"k8s.io/klog/v2"
)
// ListeAndServe starts listening on the configured address and serves the RPC API.
func (me *MultiEpoch) ListenAndServeGRPC(ctx context.Context, listenOn string) error {
lis, err := net.Listen("tcp", listenOn)
if err != nil {
return fmt.Errorf("failed to create listener for gRPC server: %w", err)
}
grpcServer := grpc.NewServer()
old_faithful_grpc.RegisterOldFaithfulServer(grpcServer, me)
if err := grpcServer.Serve(lis); err != nil {
return fmt.Errorf("failed to serve gRPC server: %w", err)
}
return nil
}
func (me *MultiEpoch) GetVersion(context.Context, *old_faithful_grpc.VersionRequest) (*old_faithful_grpc.VersionResponse, error) {
// faithfulVersion["version"] = GitTag
// faithfulVersion["commit"] = GitCommit
// faithfulVersion["epochs"] = me.GetEpochNumbers()
resp := &old_faithful_grpc.VersionResponse{
Version: func() string {
if GitTag == "" {
return GitCommit
}
return GitTag
}(),
}
return resp, nil
}
func (multi *MultiEpoch) GetBlock(ctx context.Context, params *old_faithful_grpc.BlockRequest) (*old_faithful_grpc.BlockResponse, error) {
// find the epoch that contains the requested slot
slot := params.Slot
epochNumber := CalcEpochForSlot(slot)
epochHandler, err := multi.GetEpoch(epochNumber)
if err != nil {
return nil, status.Errorf(codes.NotFound, "Epoch %d is not available", epochNumber)
}
block, _, err := epochHandler.GetBlock(WithSubrapghPrefetch(ctx, true), slot)
if err != nil {
if errors.Is(err, compactindexsized.ErrNotFound) {
return nil, status.Errorf(codes.NotFound, "Slot %d was skipped, or missing in long-term storage", slot)
} else {
return nil, status.Errorf(codes.Internal, "Failed to get block: %v", err)
}
}
tim := newTimer(getRequestIDFromContext(ctx))
tim.time("GetBlock")
{
prefetcherFromCar := func() error {
parentIsInPreviousEpoch := CalcEpochForSlot(uint64(block.Meta.Parent_slot)) != CalcEpochForSlot(slot)
if slot == 0 {
parentIsInPreviousEpoch = true
}
if slot > 1 && block.Meta.Parent_slot == 0 {
parentIsInPreviousEpoch = true
}
var blockCid, parentBlockCid cid.Cid
wg := new(errgroup.Group)
wg.Go(func() (err error) {
blockCid, err = epochHandler.FindCidFromSlot(ctx, slot)
if err != nil {
return err
}
return nil
})
wg.Go(func() (err error) {
if parentIsInPreviousEpoch {
return nil
}
parentBlockCid, err = epochHandler.FindCidFromSlot(ctx, uint64(block.Meta.Parent_slot))
if err != nil {
return err
}
return nil
})
err = wg.Wait()
if err != nil {
return err
}
if slot == 0 {
klog.V(4).Infof("car start to slot(0)::%s", blockCid)
} else {
klog.V(4).Infof(
"slot(%d)::%s to slot(%d)::%s",
uint64(block.Meta.Parent_slot),
parentBlockCid,
slot,
blockCid,
)
}
{
var blockOffset, parentOffset uint64
wg := new(errgroup.Group)
wg.Go(func() (err error) {
offsetAndSize, err := epochHandler.FindOffsetAndSizeFromCid(ctx, blockCid)
if err != nil {
return err
}
blockOffset = offsetAndSize.Offset
return nil
})
wg.Go(func() (err error) {
if parentIsInPreviousEpoch {
// get car file header size
parentOffset = epochHandler.carHeaderSize
return nil
}
offsetAndSize, err := epochHandler.FindOffsetAndSizeFromCid(ctx, parentBlockCid)
if err != nil {
return err
}
parentOffset = offsetAndSize.Offset
return nil
})
err = wg.Wait()
if err != nil {
return err
}
length := blockOffset - parentOffset
MiB := uint64(1024 * 1024)
maxPrefetchSize := MiB * 10 // let's cap prefetching size
if length > maxPrefetchSize {
length = maxPrefetchSize
}
start := parentOffset
klog.V(4).Infof("prefetching CAR: start=%d length=%d (parent_offset=%d)", start, length, parentOffset)
carSection, err := epochHandler.ReadAtFromCar(ctx, start, length)
if err != nil {
return err
}
dr := bytes.NewReader(carSection)
br := bufio.NewReader(dr)
gotCid, data, err := util.ReadNode(br)
if err != nil {
return fmt.Errorf("failed to read first node: %w", err)
}
if !parentIsInPreviousEpoch && !gotCid.Equals(parentBlockCid) {
return fmt.Errorf("CID mismatch: expected %s, got %s", parentBlockCid, gotCid)
}
epochHandler.GetCache().PutRawCarObject(gotCid, data)
for {
gotCid, data, err = util.ReadNode(br)
if err != nil {
if errors.Is(err, io.EOF) {
break
}
return fmt.Errorf("failed to read node: %w", err)
}
if gotCid.Equals(blockCid) {
break
}
epochHandler.GetCache().PutRawCarObject(gotCid, data)
}
}
return nil
}
if epochHandler.lassieFetcher == nil {
err := prefetcherFromCar()
if err != nil {
klog.Errorf("failed to prefetch from car: %v", err)
}
}
}
allTransactionNodes := make([][]*ipldbindcode.Transaction, len(block.Entries))
mu := &sync.Mutex{}
var lastEntryHash solana.Hash
{
wg := new(errgroup.Group)
wg.SetLimit(runtime.NumCPU() * 2)
// get entries from the block
for entryIndex, entry := range block.Entries {
entryIndex := entryIndex
entryCid := entry.(cidlink.Link).Cid
wg.Go(func() error {
// get the entry by CID
entryNode, err := epochHandler.GetEntryByCid(ctx, entryCid)
if err != nil {
klog.Errorf("failed to decode Entry: %v", err)
return err
}
if entryIndex == len(block.Entries)-1 {
lastEntryHash = solana.HashFromBytes(entryNode.Hash)
}
twg := new(errgroup.Group)
twg.SetLimit(runtime.NumCPU())
// get the transactions from the entry
allTransactionNodes[entryIndex] = make([]*ipldbindcode.Transaction, len(entryNode.Transactions))
for txI := range entryNode.Transactions {
txI := txI
tx := entryNode.Transactions[txI]
twg.Go(func() error {
// get the transaction by CID
tcid := tx.(cidlink.Link).Cid
txNode, err := epochHandler.GetTransactionByCid(ctx, tcid)
if err != nil {
klog.Errorf("failed to decode Transaction %s: %v", tcid, err)
return nil
}
mu.Lock()
allTransactionNodes[entryIndex][txI] = txNode
mu.Unlock()
return nil
})
}
return twg.Wait()
})
}
err = wg.Wait()
if err != nil {
return nil, status.Errorf(codes.Internal, "Failed to get entries: %v", err)
}
}
tim.time("get entries")
resp := &old_faithful_grpc.BlockResponse{
Slot: uint64(block.Slot),
}
var allTransactions []*old_faithful_grpc.Transaction
hasRewards := !block.Rewards.(cidlink.Link).Cid.Equals(DummyCID)
if hasRewards {
rewardsNode, err := epochHandler.GetRewardsByCid(ctx, block.Rewards.(cidlink.Link).Cid)
if err != nil {
return nil, status.Errorf(codes.Internal, "Failed to get Rewards: %v", err)
}
rewardsBuf, err := loadDataFromDataFrames(&rewardsNode.Data, epochHandler.GetDataFrameByCid)
if err != nil {
return nil, status.Errorf(codes.Internal, "Failed to load Rewards dataFrames: %v", err)
}
uncompressedRawRewards, err := decompressZstd(rewardsBuf)
if err != nil {
return nil, status.Errorf(codes.Internal, "Failed to decompress Rewards: %v", err)
}
resp.Rewards = uncompressedRawRewards
}
tim.time("get rewards")
{
for _, transactionNode := range mergeTxNodeSlices(allTransactionNodes) {
txResp := new(old_faithful_grpc.Transaction)
// response.Slot = uint64(transactionNode.Slot)
// if blocktime != 0 {
// response.Blocktime = &blocktime
// }
{
pos, ok := transactionNode.GetPositionIndex()
if ok {
txResp.Index = ptrToUint64(uint64(pos))
}
txResp.Transaction, txResp.Meta, err = getTransactionAndMetaFromNode(transactionNode, epochHandler.GetDataFrameByCid)
if err != nil {
return nil, status.Errorf(codes.Internal, "Failed to get transaction: %v", err)
}
}
allTransactions = append(allTransactions, txResp)
}
}
sort.Slice(allTransactions, func(i, j int) bool {
if allTransactions[i].Index == nil || allTransactions[j].Index == nil {
return false
}
return *allTransactions[i].Index < *allTransactions[j].Index
})
tim.time("get transactions")
resp.Transactions = allTransactions
blocktime := uint64(block.Meta.Blocktime)
if blocktime != 0 {
resp.BlockTime = int64(blocktime)
}
resp.Blockhash = lastEntryHash[:]
resp.ParentSlot = uint64(block.Meta.Parent_slot)
if slot == 0 {
genesis := epochHandler.GetGenesis()
if genesis != nil {
blockZeroBlocktime := uint64(genesis.Config.CreationTime.Unix())
resp.BlockTime = int64(blockZeroBlocktime)
}
resp.ParentSlot = uint64(0)
zeroBlockHeight := uint64(0)
resp.BlockHeight = zeroBlockHeight
blockZeroBlockHash := lastEntryHash
resp.PreviousBlockhash = blockZeroBlockHash[:] // NOTE: this is what solana RPC does. Should it be nil instead? Or should it be the genesis hash?
}
{
blockHeight, ok := block.GetBlockHeight()
if ok {
resp.BlockHeight = blockHeight
}
}
{
// get parent slot
parentSlot := uint64(block.Meta.Parent_slot)
if (parentSlot != 0 || slot == 1) && CalcEpochForSlot(parentSlot) == epochNumber {
// NOTE: if the parent is in the same epoch, we can get it from the same epoch handler as the block;
// otherwise, we need to get it from the previous epoch (TODO: implement this)
parentBlock, _, err := epochHandler.GetBlock(WithSubrapghPrefetch(ctx, false), parentSlot)
if err != nil {
return nil, status.Errorf(codes.Internal, "Failed to get parent block: %v", err)
}
if len(parentBlock.Entries) > 0 {
lastEntryCidOfParent := parentBlock.Entries[len(parentBlock.Entries)-1]
parentEntryNode, err := epochHandler.GetEntryByCid(ctx, lastEntryCidOfParent.(cidlink.Link).Cid)
if err != nil {
return nil, status.Errorf(codes.Internal, "Failed to get parent entry: %v", err)
}
parentEntryHash := solana.HashFromBytes(parentEntryNode.Hash)
resp.PreviousBlockhash = parentEntryHash[:]
}
} else {
if slot != 0 {
klog.V(4).Infof("parent slot is in a different epoch, not implemented yet (can't get previousBlockhash)")
}
}
}
tim.time("get parent block")
return resp, nil
}
func (multi *MultiEpoch) GetTransaction(ctx context.Context, params *old_faithful_grpc.TransactionRequest) (*old_faithful_grpc.TransactionResponse, error) {
if multi.CountEpochs() == 0 {
return nil, status.Errorf(codes.Internal, "no epochs available")
}
sig := solana.SignatureFromBytes(params.Signature)
startedEpochLookupAt := time.Now()
epochNumber, err := multi.findEpochNumberFromSignature(ctx, sig)
if err != nil {
if errors.Is(err, ErrNotFound) {
// solana just returns null here in case of transaction not found: {"jsonrpc":"2.0","result":null,"id":1}
return nil, status.Errorf(codes.NotFound, "Transaction not found")
}
return nil, status.Errorf(codes.Internal, "Failed to get epoch for signature %s: %v", sig, err)
}
klog.V(4).Infof("Found signature %s in epoch %d in %s", sig, epochNumber, time.Since(startedEpochLookupAt))
epochHandler, err := multi.GetEpoch(uint64(epochNumber))
if err != nil {
return nil, status.Errorf(codes.NotFound, "Epoch %d is not available from this RPC", epochNumber)
}
transactionNode, _, err := epochHandler.GetTransaction(WithSubrapghPrefetch(ctx, true), sig)
if err != nil {
if errors.Is(err, compactindexsized.ErrNotFound) {
// NOTE: solana just returns null here in case of transaction not found: {"jsonrpc":"2.0","result":null,"id":1}
return nil, status.Errorf(codes.NotFound, "Transaction not found")
}
return nil, status.Errorf(codes.Internal, "Failed to get transaction: %v", err)
}
response := &old_faithful_grpc.TransactionResponse{
Transaction: &old_faithful_grpc.Transaction{},
}
response.Slot = uint64(transactionNode.Slot)
{
block, _, err := epochHandler.GetBlock(ctx, uint64(transactionNode.Slot))
if err != nil {
return nil, status.Errorf(codes.Internal, "Failed to get block: %v", err)
}
blocktime := uint64(block.Meta.Blocktime)
if blocktime != 0 {
response.BlockTime = int64(blocktime)
}
}
{
pos, ok := transactionNode.GetPositionIndex()
if ok {
response.Index = ptrToUint64(uint64(pos))
}
response.Transaction.Transaction, response.Transaction.Meta, err = getTransactionAndMetaFromNode(transactionNode, epochHandler.GetDataFrameByCid)
if err != nil {
return nil, status.Errorf(codes.Internal, "Failed to get transaction: %v", err)
}
}
return response, nil
}
func (multi *MultiEpoch) Get(ser old_faithful_grpc.OldFaithful_GetServer) error {
ctx := ser.Context()
for {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
req, err := ser.Recv()
if err != nil {
if errors.Is(err, io.EOF) {
return nil
}
return err
}
id := req.GetId()
switch req.Request.(type) {
case *old_faithful_grpc.GetRequest_Block:
params := req.GetBlock()
resp, err := multi.GetBlock(ctx, params)
if err != nil {
gerr, ok := status.FromError(err)
if ok {
err := ser.Send(&old_faithful_grpc.GetResponse{
Id: id,
Response: &old_faithful_grpc.GetResponse_Error{
Error: &old_faithful_grpc.GetResponseError{
Code: func() old_faithful_grpc.GetResponseErrorCode {
switch gerr.Code() {
case codes.NotFound:
return old_faithful_grpc.GetResponseErrorCode_NOT_FOUND
default:
return old_faithful_grpc.GetResponseErrorCode_INTERNAL
}
}(),
Message: gerr.Message(),
},
},
})
if err != nil {
return status.Errorf(codes.Internal, "request %d; failed to send block error response: %v", id, err)
}
continue
}
return status.Errorf(codes.Internal, "request %d; failed to get block: %v", id, err)
}
if err := ser.Send(&old_faithful_grpc.GetResponse{
Id: id,
Response: &old_faithful_grpc.GetResponse_Block{Block: resp},
}); err != nil {
return status.Errorf(codes.Internal, "request %d; failed to send block response: %v", id, err)
}
case *old_faithful_grpc.GetRequest_Transaction:
params := req.GetTransaction()
resp, err := multi.GetTransaction(ctx, params)
if err != nil {
gerr, ok := status.FromError(err)
if ok {
err := ser.Send(&old_faithful_grpc.GetResponse{
Id: id,
Response: &old_faithful_grpc.GetResponse_Error{
Error: &old_faithful_grpc.GetResponseError{
Code: func() old_faithful_grpc.GetResponseErrorCode {
switch gerr.Code() {
case codes.NotFound:
return old_faithful_grpc.GetResponseErrorCode_NOT_FOUND
default:
return old_faithful_grpc.GetResponseErrorCode_INTERNAL
}
}(),
Message: gerr.Message(),
},
},
})
if err != nil {
return status.Errorf(codes.Internal, "request %d; failed to send transaction error response: %v", id, err)
}
continue
}
return status.Errorf(codes.Internal, "request %d; failed to get transaction: %v", id, err)
}
if err := ser.Send(&old_faithful_grpc.GetResponse{
Id: id,
Response: &old_faithful_grpc.GetResponse_Transaction{Transaction: resp},
}); err != nil {
return status.Errorf(codes.Internal, "request %d; failed to send transaction response: %v", id, err)
}
case *old_faithful_grpc.GetRequest_Version:
params := req.GetVersion()
resp, err := multi.GetVersion(ctx, params)
if err != nil {
gerr, ok := status.FromError(err)
if ok {
err := ser.Send(&old_faithful_grpc.GetResponse{
Id: id,
Response: &old_faithful_grpc.GetResponse_Error{
Error: &old_faithful_grpc.GetResponseError{
Code: func() old_faithful_grpc.GetResponseErrorCode {
switch gerr.Code() {
case codes.NotFound:
return old_faithful_grpc.GetResponseErrorCode_NOT_FOUND
default:
return old_faithful_grpc.GetResponseErrorCode_INTERNAL
}
}(),
Message: gerr.Message(),
},
},
})
if err != nil {
return status.Errorf(codes.Internal, "request %d; failed to send version error response: %v", id, err)
}
continue
}
return status.Errorf(codes.Internal, "request %d; failed to get version: %v", id, err)
}
if err := ser.Send(&old_faithful_grpc.GetResponse{
Id: id,
Response: &old_faithful_grpc.GetResponse_Version{Version: resp},
}); err != nil {
return status.Errorf(codes.Internal, "request %d; failed to send version response: %v", id, err)
}
case *old_faithful_grpc.GetRequest_BlockTime:
params := req.GetBlockTime()
resp, err := multi.GetBlockTime(ctx, params)
if err != nil {
gerr, ok := status.FromError(err)
if ok {
err := ser.Send(&old_faithful_grpc.GetResponse{
Id: id,
Response: &old_faithful_grpc.GetResponse_Error{
Error: &old_faithful_grpc.GetResponseError{
Code: func() old_faithful_grpc.GetResponseErrorCode {
switch gerr.Code() {
case codes.NotFound:
return old_faithful_grpc.GetResponseErrorCode_NOT_FOUND
}
return old_faithful_grpc.GetResponseErrorCode_INTERNAL
}(),
Message: gerr.Message(),
},
},
})
if err != nil {
return status.Errorf(codes.Internal, "request %d; failed to send blocktime error response: %v", id, err)
}
continue
}
return status.Errorf(codes.Internal, "request %d; failed to get blocktime: %v", id, err)
}
if err := ser.Send(&old_faithful_grpc.GetResponse{
Id: id,
Response: &old_faithful_grpc.GetResponse_BlockTime{BlockTime: resp},
}); err != nil {
return status.Errorf(codes.Internal, "request %d; failed to send blocktime response: %v", id, err)
}
default:
return status.Errorf(codes.InvalidArgument, "unknown request type %T", req.Request)
}
}
}
func (multi *MultiEpoch) GetBlockTime(ctx context.Context, params *old_faithful_grpc.BlockTimeRequest) (*old_faithful_grpc.BlockTimeResponse, error) {
slot := params.Slot
epochNumber := CalcEpochForSlot(slot)
epochHandler, err := multi.GetEpoch(epochNumber)
if err != nil {
return nil, status.Errorf(codes.NotFound, "Epoch %d is not available", epochNumber)
}
block, _, err := epochHandler.GetBlock(WithSubrapghPrefetch(ctx, false), slot)
if err != nil {
if errors.Is(err, compactindexsized.ErrNotFound) {
return nil, status.Errorf(codes.NotFound, "Slot %d was skipped, or missing in long-term storage", slot)
} else {
return nil, status.Errorf(codes.Internal, "Failed to get block: %v", err)
}
}
blocktime := uint64(block.Meta.Blocktime)
if blocktime == 0 {
return nil, status.Errorf(codes.NotFound, "Blocktime for slot %d is not available", slot)
}
return &old_faithful_grpc.BlockTimeResponse{
BlockTime: int64(blocktime),
}, nil
}