forked from coinbase/chainstorage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler.go
1395 lines (1175 loc) · 43 KB
/
handler.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
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package server
import (
"context"
"fmt"
"net"
"regexp"
"strconv"
"strings"
"sync"
"time"
"unicode"
grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
"google.golang.org/grpc/reflection"
"github.com/cenkalti/backoff"
"github.com/uber-go/tally/v4"
"go.uber.org/fx"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"golang.org/x/exp/maps"
"golang.org/x/xerrors"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/keepalive"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"github.com/coinbase/chainstorage/internal/blockchain/client"
"github.com/coinbase/chainstorage/internal/blockchain/parser"
"github.com/coinbase/chainstorage/internal/config"
"github.com/coinbase/chainstorage/internal/gateway"
"github.com/coinbase/chainstorage/internal/s3"
"github.com/coinbase/chainstorage/internal/storage"
"github.com/coinbase/chainstorage/internal/storage/blobstorage"
"github.com/coinbase/chainstorage/internal/storage/metastorage"
"github.com/coinbase/chainstorage/internal/storage/metastorage/model"
storage_utils "github.com/coinbase/chainstorage/internal/storage/utils"
"github.com/coinbase/chainstorage/internal/utils/consts"
"github.com/coinbase/chainstorage/internal/utils/fxparams"
"github.com/coinbase/chainstorage/internal/utils/log"
"github.com/coinbase/chainstorage/internal/utils/syncgroup"
"github.com/coinbase/chainstorage/internal/utils/utils"
api "github.com/coinbase/chainstorage/protos/coinbase/chainstorage"
"github.com/coinbase/chainstorage/sdk/services"
)
type (
Server struct {
config *config.Config
logger *zap.Logger
metaStorage metastorage.MetaStorage
blobStorage blobstorage.BlobStorage
transactionStorage metastorage.TransactionStorage
blockchainClient client.Client
parser parser.Parser
metrics *serverMetrics
streamDone chan struct{}
maxNoEventTime time.Duration
authorizedClients map[string]*config.AuthClient // Token => AuthClient
throttler *Throttler
}
ServerParams struct {
fx.In
fxparams.Params
MetaStorage metastorage.MetaStorage
BlobStorage blobstorage.BlobStorage
TransactionStorage metastorage.TransactionStorage
S3Client s3.Client
BlockchainClient client.Client `name:"slave"`
Parser parser.Parser
Lifecycle fx.Lifecycle
}
RegisterParams struct {
fx.In
fxparams.Params
Manager services.SystemManager
Server *Server
}
serverMetrics struct {
scope tally.Scope
}
requestByRange interface {
GetTag() uint32
GetStartHeight() uint64
GetEndHeight() uint64
}
requestByID interface {
GetTag() uint32
GetHeight() uint64
GetHash() string
}
parseChainEventsRequestInput interface {
// Deprecated: Use GetSequenceNum instead.
GetSequence() string
GetSequenceNum() int64
GetInitialPositionInStream() string
}
contextKey string
)
const (
// Custom interceptors
errorInterceptorID = "xerror"
requestInterceptorID = "xrequest"
statsdInterceptorID = "xstatsd"
rateLimitInterceptorID = "xratelimit"
keepAliveTime = 5 * time.Second
keepAliveTimeout = 5 * time.Second
)
const (
scopeName = "server"
blocksServedCounter = "blocks_served"
formatTag = "format"
formatFile = "file"
formatRaw = "raw"
formatNative = "native"
formatRosetta = "rosetta"
eventsServedCounter = "events_served"
eventTypeTag = "event_type"
eventTypeBlockAdded = "block_added"
eventTypeBlockRemoved = "block_removed"
metricEventTag = "event_tag"
transactionsServedCounter = "transactions_served"
accountStateServedCounter = "account_state_served"
errorCounter = "error"
serviceTag = "service"
methodTag = "method"
statusTag = "status"
requestCounter = "request"
clientIDTag = "clientID"
// If the client ID is not set, set it as unknown.
unknownClientID = "unknown"
// Client ID is cached in context.Context for quick access.
contextKeyClientID = contextKey("client_id")
)
const (
streamingShortWaitTime = time.Millisecond * 10
streamingBackoffMaxInterval = time.Minute
streamingBackoffMultiplier = 1.5
streamingBackoffRandomizationFactor = 0.5
streamingBackoffStop = backoff.Stop
)
var (
InitialPositionLatest = api.InitialPosition_LATEST.String()
InitialPositionEarliest = api.InitialPosition_EARLIEST.String()
errServerShutDown = xerrors.New("sever is shutting down")
errNoNewEventForTooLong = xerrors.New("there was no new event for quite a while")
errNotImplemented = xerrors.New("handler method not implemented")
// The method the interceptor is given is of the form /coinbase.chainstorage.ChainStorage/GetNativeBlock
// This regex matches that and extracts the service and method name into
// separate capture groups.
methodRegex = regexp.MustCompile(`\/(.+)\/(.+)$`)
)
var registerServerOnce sync.Once
var registerServerError error
// RCU stands for Read Capacity Unit, which is similar to the concept in DynamoDB.
// Each request consumes 1 RCU unless it is explicitly defined below.
// When the total RCUs exceed the rate limit, the request would be rejected.
var rcuByMethod = map[string]int{
"GetRawBlock": 10,
"GetRawBlocksByRange": 50,
"GetNativeBlock": 10,
"GetNativeBlocksByRange": 50,
"GetRosettaBlock": 10,
"GetRosettaBlocksByRange": 50,
"GetNativeTransaction": 10,
"GetVerifiedAccountState": 10,
}
func NewServer(params ServerParams) *Server {
cfg := params.Config
s := &Server{
config: cfg,
logger: log.WithPackage(params.Logger),
metaStorage: params.MetaStorage,
blobStorage: params.BlobStorage,
transactionStorage: params.TransactionStorage,
blockchainClient: params.BlockchainClient,
parser: params.Parser,
metrics: newServerMetrics(params.Metrics),
streamDone: make(chan struct{}),
maxNoEventTime: cfg.Api.StreamingMaxNoEventTime,
authorizedClients: cfg.Api.Auth.AsMap(),
throttler: NewThrottler(&cfg.Api),
}
params.Lifecycle.Append(fx.Hook{
OnStart: s.onStart,
OnStop: s.onStop,
})
return s
}
func newServerMetrics(scope tally.Scope) *serverMetrics {
scope = scope.SubScope(scopeName)
return &serverMetrics{
scope: scope,
}
}
func Register(params RegisterParams) error {
registerServerOnce.Do(func() {
manager := params.Manager
server := params.Server
config := params.Config
unaryInterceptor := grpc.ChainUnaryInterceptor(
// XXX: Add your own interceptors here.
server.unaryRequestInterceptor,
server.unaryErrorInterceptor,
server.unaryRateLimitInterceptor,
)
streamInterceptr := grpc.ChainStreamInterceptor(
// XXX: Add your own interceptors here.
server.streamRequestInterceptor,
server.streamErrorInterceptor,
server.streamRateLimitInterceptor,
)
gs := grpc.NewServer(
unaryInterceptor,
streamInterceptr,
grpc.KeepaliveParams(keepalive.ServerParameters{
Time: keepAliveTime,
Timeout: keepAliveTimeout,
}),
)
api.RegisterChainStorageServer(gs, server)
reflection.Register(gs)
daemonizeServer(manager, gs, config)
})
return registerServerError
}
func daemonizeServer(
manager services.SystemManager,
gs *grpc.Server,
cfg *config.Config,
) {
bindAddress := cfg.Server.BindAddress
runGRPCServer := func(ctx context.Context) (services.ShutdownFunction, chan error) {
return startServer(manager.Logger(), bindAddress, gs)
}
manager.ServiceWaitGroup().Add(1)
go func() {
defer manager.ServiceWaitGroup().Done()
services.Daemonize(manager, runGRPCServer, "GRPC Server")
}()
}
func startServer(
logger *zap.Logger,
bindAddress string,
gs *grpc.Server,
) (services.ShutdownFunction, chan error) {
errorChannel := make(chan error)
done := make(chan struct{})
go func() {
defer close(done)
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered", r)
}
}()
logger.Info("Listening", zap.String("bindAddress", bindAddress))
listener, err := net.Listen("tcp", bindAddress)
if err != nil {
logger.Error("Failed to listen", zap.Error(err))
errorChannel <- err
return
}
if err := gs.Serve(listener); err != nil {
logger.Error("Failed to serve", zap.Error(err))
errorChannel <- err
return
}
}()
return func(_ context.Context) error {
gs.GracefulStop()
<-done
return nil
}, errorChannel
}
func (s *Server) emitBlocksMetric(format string, clientID string, count int64) {
s.metrics.scope.Tagged(map[string]string{formatTag: format, clientIDTag: clientID}).Counter(blocksServedCounter).Inc(count)
}
func (s *Server) emitEventsMetric(eventType string, clientID string, eventTag string, count int64) {
s.metrics.scope.Tagged(map[string]string{eventTypeTag: eventType, clientIDTag: clientID, metricEventTag: eventTag}).Counter(eventsServedCounter).Inc(count)
}
func (s *Server) emitTransactionsMetric(format string, clientID string, count int64) {
s.metrics.scope.Tagged(map[string]string{formatTag: format, clientIDTag: clientID}).Counter(transactionsServedCounter).Inc(count)
}
func (s *Server) emitAccountStateMetric(clientID string, count int64) {
s.metrics.scope.Tagged(map[string]string{clientIDTag: clientID}).Counter(accountStateServedCounter).Inc(count)
}
func (s *Server) GetLatestBlock(ctx context.Context, req *api.GetLatestBlockRequest) (*api.GetLatestBlockResponse, error) {
tag := s.config.GetEffectiveBlockTag(req.GetTag())
if err := s.validateTag(tag); err != nil {
return nil, xerrors.Errorf("failed to validate tag: %w", err)
}
block, err := s.metaStorage.GetLatestBlock(ctx, tag)
if err != nil {
return nil, xerrors.Errorf("failed to get latest block: %w", err)
}
return &api.GetLatestBlockResponse{
Tag: block.Tag,
Hash: block.Hash,
ParentHash: block.ParentHash,
Height: block.Height,
Timestamp: block.Timestamp,
}, nil
}
func (s *Server) GetBlockFile(ctx context.Context, req *api.GetBlockFileRequest) (*api.GetBlockFileResponse, error) {
clientID := getClientID(ctx)
block, err := s.getBlockFromMetaStorage(ctx, req)
if err != nil {
return nil, xerrors.Errorf("failed to get block from meta storage: %w", err)
}
blockFile, err := s.newBlockFile(block)
if err != nil {
return nil, xerrors.Errorf("failed to prepare block file: %w", err)
}
s.emitBlocksMetric(formatFile, clientID, 1)
return &api.GetBlockFileResponse{
File: blockFile,
}, nil
}
func (s *Server) GetBlockFilesByRange(ctx context.Context, req *api.GetBlockFilesByRangeRequest) (*api.GetBlockFilesByRangeResponse, error) {
clientID := getClientID(ctx)
blocks, err := s.getBlocksFromMetaStorage(ctx, req, s.config.Api.MaxNumBlockFiles)
if err != nil {
return nil, xerrors.Errorf("failed to get blocks from meta storage: %w", err)
}
blockFiles := make([]*api.BlockFile, len(blocks))
for i := 0; i < len(blocks); i++ {
blockFile, err := s.newBlockFile(blocks[i])
if err != nil {
return nil, xerrors.Errorf("newBlockFile error: %w", err)
}
blockFiles[i] = blockFile
}
s.emitBlocksMetric(formatFile, clientID, int64(len(blockFiles)))
return &api.GetBlockFilesByRangeResponse{Files: blockFiles}, nil
}
func (s *Server) GetRawBlock(ctx context.Context, req *api.GetRawBlockRequest) (*api.GetRawBlockResponse, error) {
clientID := getClientID(ctx)
block, err := s.getBlockFromMetaStorage(ctx, req)
if err != nil {
return nil, xerrors.Errorf("failed to get block from meta storage: %w", err)
}
rawBlock, err := s.getBlockFromBlobStorage(ctx, block)
if err != nil {
return nil, xerrors.Errorf("failed to get raw blocks: %w", err)
}
s.emitBlocksMetric(formatRaw, clientID, 1)
return &api.GetRawBlockResponse{
Block: rawBlock,
}, nil
}
func (s *Server) GetRawBlocksByRange(ctx context.Context, req *api.GetRawBlocksByRangeRequest) (*api.GetRawBlocksByRangeResponse, error) {
clientID := getClientID(ctx)
blocks, err := s.getBlocksFromMetaStorage(ctx, req, s.config.Api.MaxNumBlocks)
if err != nil {
return nil, xerrors.Errorf("failed to get blocks from meta storage: %w", err)
}
rawBlocks, err := s.getBlocksFromBlobStorage(ctx, blocks)
if err != nil {
return nil, xerrors.Errorf("failed to get raw blocks: %w", err)
}
s.emitBlocksMetric(formatRaw, clientID, int64(len(rawBlocks)))
return &api.GetRawBlocksByRangeResponse{
Blocks: rawBlocks,
}, nil
}
func (s *Server) GetNativeBlock(ctx context.Context, req *api.GetNativeBlockRequest) (*api.GetNativeBlockResponse, error) {
clientID := getClientID(ctx)
block, err := s.getBlockFromMetaStorage(ctx, req)
if err != nil {
return nil, xerrors.Errorf("failed to get block from meta storage: %w", err)
}
rawBlock, err := s.getBlockFromBlobStorage(ctx, block)
if err != nil {
return nil, xerrors.Errorf("failed to get raw blocks: %w", err)
}
nativeBlock, err := s.parser.ParseNativeBlock(ctx, rawBlock)
if err != nil {
return nil, xerrors.Errorf("failed to parse block: %w", err)
}
s.emitBlocksMetric(formatNative, clientID, 1)
return &api.GetNativeBlockResponse{
Block: nativeBlock,
}, nil
}
func (s *Server) GetNativeBlocksByRange(ctx context.Context, req *api.GetNativeBlocksByRangeRequest) (*api.GetNativeBlocksByRangeResponse, error) {
clientID := getClientID(ctx)
blocks, err := s.getBlocksFromMetaStorage(ctx, req, s.config.Api.MaxNumBlocks)
if err != nil {
return nil, xerrors.Errorf("failed to get blocks from meta storage: %w", err)
}
rawBlocks, err := s.getBlocksFromBlobStorage(ctx, blocks)
if err != nil {
return nil, xerrors.Errorf("failed to get raw blocks: %w", err)
}
nativeBlocks := make([]*api.NativeBlock, len(rawBlocks))
for i := 0; i < len(nativeBlocks); i++ {
nativeBlock, err := s.parser.ParseNativeBlock(ctx, rawBlocks[i])
if err != nil {
return nil, xerrors.Errorf("failed to parse block: %w", err)
}
nativeBlocks[i] = nativeBlock
}
s.emitBlocksMetric(formatNative, clientID, int64(len(nativeBlocks)))
return &api.GetNativeBlocksByRangeResponse{
Blocks: nativeBlocks,
}, nil
}
func (s *Server) GetRosettaBlock(ctx context.Context, req *api.GetRosettaBlockRequest) (*api.GetRosettaBlockResponse, error) {
// TODO: short-circuit fetching block from blob-storage if RosettaParser is not implemented for chain
clientID := getClientID(ctx)
block, err := s.getBlockFromMetaStorage(ctx, req)
if err != nil {
return nil, xerrors.Errorf("failed to get block from meta storage: %w", err)
}
rawBlock, err := s.getBlockFromBlobStorage(ctx, block)
if err != nil {
return nil, xerrors.Errorf("failed to get raw blocks: %w", err)
}
rosettaBlock, err := s.parser.ParseRosettaBlock(ctx, rawBlock)
if err != nil {
return nil, xerrors.Errorf("failed to parse block: %w", err)
}
s.emitBlocksMetric(formatRosetta, clientID, 1)
return &api.GetRosettaBlockResponse{
Block: rosettaBlock,
}, nil
}
func (s *Server) GetRosettaBlocksByRange(ctx context.Context, req *api.GetRosettaBlocksByRangeRequest) (*api.GetRosettaBlocksByRangeResponse, error) {
clientID := getClientID(ctx)
blocks, err := s.getBlocksFromMetaStorage(ctx, req, s.config.Api.MaxNumBlocks)
if err != nil {
return nil, xerrors.Errorf("failed to get blocks from meta storage: %w", err)
}
rawBlocks, err := s.getBlocksFromBlobStorage(ctx, blocks)
if err != nil {
return nil, xerrors.Errorf("failed to get raw blocks: %w", err)
}
rosettaBlocks := make([]*api.RosettaBlock, len(rawBlocks))
for i := 0; i < len(rosettaBlocks); i++ {
rosettaBlock, err := s.parser.ParseRosettaBlock(ctx, rawBlocks[i])
if err != nil {
return nil, xerrors.Errorf("failed to parse block: %w", err)
}
rosettaBlocks[i] = rosettaBlock
}
s.emitBlocksMetric(formatRosetta, clientID, int64(len(rosettaBlocks)))
return &api.GetRosettaBlocksByRangeResponse{
Blocks: rosettaBlocks,
}, nil
}
func (s *Server) GetBlockByTransaction(ctx context.Context, req *api.GetBlockByTransactionRequest) (*api.GetBlockByTransactionResponse, error) {
if !s.config.Chain.Feature.TransactionIndexing {
return nil, errNotImplemented
}
blocks, err := s.getBlocksFromTransactionStorage(ctx, req.GetTag(), req.GetTransactionHash())
if err != nil {
return nil, xerrors.Errorf("failed to get blocks from transaction storage: %w", err)
}
results := make([]*api.BlockIdentifier, len(blocks))
for i, block := range blocks {
results[i] = &api.BlockIdentifier{
Hash: block.GetHash(),
Height: block.GetHeight(),
Tag: block.GetTag(),
Skipped: block.GetSkipped(),
Timestamp: block.GetTimestamp(),
}
}
clientID := getClientID(ctx)
s.emitTransactionsMetric(formatRaw, clientID, 1)
return &api.GetBlockByTransactionResponse{
Blocks: results,
}, nil
}
func (s *Server) GetNativeTransaction(ctx context.Context, req *api.GetNativeTransactionRequest) (*api.GetNativeTransactionResponse, error) {
if !s.config.Chain.Feature.TransactionIndexing {
return nil, errNotImplemented
}
blocks, err := s.getBlocksFromTransactionStorage(ctx, req.GetTag(), req.GetTransactionHash())
if err != nil {
return nil, xerrors.Errorf("failed to get blocks from transaction storage: %w", err)
}
rawBlocks, err := s.getBlocksFromBlobStorage(ctx, blocks)
if err != nil {
return nil, xerrors.Errorf("failed to get raw blocks: %w", err)
}
nativeTransactions := make([]*api.NativeTransaction, len(rawBlocks))
for i := 0; i < len(nativeTransactions); i++ {
nativeBlock, err := s.parser.ParseNativeBlock(ctx, rawBlocks[i])
if err != nil {
return nil, xerrors.Errorf("failed to parse block: %w", err)
}
nativeTransaction, err := s.parser.GetNativeTransaction(ctx, nativeBlock, req.GetTransactionHash())
if err != nil {
return nil, xerrors.Errorf("failed to extract transaction from block: %w", err)
}
nativeTransactions[i] = nativeTransaction
}
clientID := getClientID(ctx)
s.emitTransactionsMetric(formatNative, clientID, 1)
return &api.GetNativeTransactionResponse{
Transactions: nativeTransactions,
}, nil
}
func (s *Server) GetVerifiedAccountState(ctx context.Context, req *api.GetVerifiedAccountStateRequest) (*api.GetVerifiedAccountStateResponse, error) {
if !s.config.Chain.Feature.VerifiedAccountStateEnabled {
return nil, errNotImplemented
}
// First, use the tag, height, and hash to get the native block
block, err := s.getBlockFromMetaStorage(ctx, req.Req)
if err != nil {
return nil, xerrors.Errorf("failed to get block from meta storage: %w", err)
}
rawBlock, err := s.getBlockFromBlobStorage(ctx, block)
if err != nil {
return nil, xerrors.Errorf("failed to get raw blocks: %w", err)
}
nativeBlock, err := s.parser.ParseNativeBlock(ctx, rawBlock)
if err != nil {
return nil, xerrors.Errorf("failed to parse block: %w", err)
}
// Second, call eth_getProof to fetch the account proof for the target account and block
accountProof, err := s.blockchainClient.GetAccountProof(ctx, req)
if err != nil {
return nil, xerrors.Errorf("failed to call client.GetAccountProof: %w", err)
}
// Finally, verify the account state with parser.VerifyAccountState
request := &api.ValidateAccountStateRequest{
AccountReq: req.Req,
Block: nativeBlock,
AccountProof: accountProof,
}
accountResult, err := s.parser.ValidateAccountState(ctx, request)
if err != nil {
return nil, xerrors.Errorf("failed to ValidateAccountState: %w", err)
}
clientID := getClientID(ctx)
s.emitAccountStateMetric(clientID, 1)
return &api.GetVerifiedAccountStateResponse{
Response: accountResult,
}, nil
}
// getBlocksFromTransactionStorage returns the blocks associated with the transaction.
// If the transaction is not found, storage.ErrItemNotFound is returned.
func (s *Server) getBlocksFromTransactionStorage(ctx context.Context, tag uint32, transactionHash string) ([]*api.BlockMetadata, error) {
tag = s.config.GetEffectiveBlockTag(tag)
if err := s.validateTag(tag); err != nil {
return nil, err
}
txs, err := s.transactionStorage.GetTransaction(ctx, tag, transactionHash)
if err != nil {
return nil, xerrors.Errorf("failed to get transaction from transaction storage: %w", err)
}
// use map to dedup in blockNums
blockNumberToMetadataMap := make(map[uint64]*api.BlockMetadata)
for _, tx := range txs {
blockNumberToMetadataMap[tx.BlockNumber] = nil
}
// query blockMetadata for blocks
blockNums := maps.Keys(blockNumberToMetadataMap)
blocksMetadata, err := s.metaStorage.GetBlocksByHeights(ctx, tag, blockNums)
if err != nil {
return nil, xerrors.Errorf("failed to get blockMetadata for blocks=%v: %w", blockNums, err)
}
for _, blockMetadata := range blocksMetadata {
blockNumberToMetadataMap[blockMetadata.Height] = blockMetadata
}
var results []*api.BlockMetadata
for _, tx := range txs {
canonicalBlock, ok := blockNumberToMetadataMap[tx.BlockNumber]
if !ok {
// this should not happen
continue
}
if canonicalBlock == nil || canonicalBlock.Hash != tx.BlockHash {
// tx.BlockHash got reorged
continue
}
results = append(results, canonicalBlock)
}
return results, nil
}
func (s *Server) newBlockFile(block *api.BlockMetadata) (*api.BlockFile, error) {
if block.Skipped {
return &api.BlockFile{
Tag: block.Tag,
Height: block.Height,
Skipped: true,
}, nil
}
key := block.GetObjectKeyMain()
compression := storage_utils.GetCompressionType(key)
fileUrl, err := s.blobStorage.PreSign(context.Background(), key)
if err != nil {
s.logger.Error("block file s3 presign error", zap.String("key", key), zap.Error(err))
return nil, status.Errorf(codes.Internal, "internal block file url generation error: %+v", err)
}
return &api.BlockFile{
Tag: block.Tag,
Hash: block.Hash,
ParentHash: block.ParentHash,
Height: block.Height,
ParentHeight: block.ParentHeight,
FileUrl: fileUrl,
Compression: compression,
}, nil
}
func (s *Server) validateTag(tag uint32) error {
if latestTag := s.config.GetLatestBlockTag(); tag > latestTag {
return status.Errorf(codes.InvalidArgument, "requested tag is unavailable: latest tag is %v", latestTag)
}
return nil
}
func (s *Server) validateBlockRange(startHeight uint64, endHeight uint64, maxNumBlocks uint64) error {
if startHeight >= endHeight {
return status.Error(codes.InvalidArgument, "invalid range: start_height must be less than end_height")
}
if numBlocks := endHeight - startHeight; numBlocks > maxNumBlocks {
return status.Errorf(codes.InvalidArgument, "block range size exceeded limit of %d", maxNumBlocks)
}
return nil
}
func (s *Server) getBlockFromMetaStorage(ctx context.Context, req requestByID) (*api.BlockMetadata, error) {
tag := s.config.GetEffectiveBlockTag(req.GetTag())
height := req.GetHeight()
hash := req.GetHash()
if err := s.validateTag(tag); err != nil {
return nil, err
}
block, err := s.metaStorage.GetBlockByHash(ctx, tag, height, hash)
if err != nil {
return nil, xerrors.Errorf("failed to get block by hash (tag=%v, height=%v, hash=%v): %w", tag, height, hash, err)
}
return block, nil
}
func (s *Server) getBlocksFromMetaStorage(ctx context.Context, req requestByRange, maxNumBlocks uint64) ([]*api.BlockMetadata, error) {
tag := s.config.GetEffectiveBlockTag(req.GetTag())
startHeight := req.GetStartHeight()
endHeight := req.GetEndHeight()
if endHeight == 0 {
endHeight = startHeight + 1
}
if err := s.validateTag(tag); err != nil {
return nil, err
}
if err := s.validateBlockRange(startHeight, endHeight, maxNumBlocks); err != nil {
return nil, err
}
blocks, err := s.metaStorage.GetBlocksByHeightRange(ctx, tag, startHeight, endHeight)
if err != nil {
return nil, xerrors.Errorf("internal meta storage error: %w", err)
}
// A chain reorg may happen after calling GetBlocksByHeightRange
// Validate requests do not go beyond the latest watermark
latestBlock, err := s.metaStorage.GetLatestBlock(ctx, tag)
if err != nil {
return nil, xerrors.Errorf("internal meta storage error: %w", err)
}
latest := latestBlock.Height
if endHeight-1 > latest {
// Possibly caused by chain reorg.
// Return a special error code so that client can retry the request.
return nil, status.Errorf(codes.FailedPrecondition, "block end height exceeded latest watermark %d", latest)
}
return blocks, nil
}
func (s *Server) getBlockFromBlobStorage(ctx context.Context, block *api.BlockMetadata) (*api.Block, error) {
output, err := s.blobStorage.Download(ctx, block)
if err != nil {
return nil, xerrors.Errorf("failed to download from blob storage (input={%+v}): %w", block, err)
}
return output, nil
}
func (s *Server) getBlocksFromBlobStorage(ctx context.Context, blocks []*api.BlockMetadata) ([]*api.Block, error) {
result := make([]*api.Block, len(blocks))
group, ctx := syncgroup.New(ctx, syncgroup.WithThrottling(int(s.config.Api.NumWorkers)))
for i := range blocks {
i := i
group.Go(func() error {
input := blocks[i]
output, err := s.blobStorage.Download(ctx, input)
if err != nil {
return xerrors.Errorf("failed to download from blob storage (input={%+v}): %w", input, err)
}
result[i] = output
return nil
})
}
if err := group.Wait(); err != nil {
return nil, xerrors.Errorf("failed to download blocks from blob storage: %w", err)
}
return result, nil
}
func (s *Server) newAuthContext(ctx context.Context) context.Context {
// Client ID is optional. Set it to "unknown" by default.
clientID := unknownClientID
if md, ok := metadata.FromIncomingContext(ctx); ok {
// Use "x-client-id" if available.
if v := md.Get(consts.ClientIDHeader); len(v) > 0 {
clientID = v[0]
}
// Remove non-printable characters.
clientID = sanitizeClientID(clientID)
}
// Cache clientID for quick access.
return context.WithValue(ctx, contextKeyClientID, clientID)
}
func sanitizeClientID(s string) string {
s = strings.TrimSpace(s)
s = strings.Split(s, ":")[0]
if s == "" {
return unknownClientID
}
return strings.Map(func(r rune) rune {
if unicode.IsSpace(r) {
return '_'
} else if unicode.IsLetter(r) {
return unicode.ToLower(r)
} else if unicode.IsNumber(r) || r == '_' || r == '-' || r == '/' {
return r
}
return -1
}, s)
}
func getClientID(ctx context.Context) string {
// Client ID should already be cached by newAuthContext.
clientID, ok := ctx.Value(contextKeyClientID).(string)
if !ok {
// Client ID not set - set it to unknown to avoid a panic.
return unknownClientID
}
return clientID
}
// getServiceAndMethod extracts the service and method name.
func getServiceAndMethod(fullMethod string) (service, method string) {
methodParts := methodRegex.FindStringSubmatch(fullMethod)
if len(methodParts) > 0 {
service = methodParts[1]
method = methodParts[2]
} else {
method = fullMethod
}
return
}
func (s *Server) unaryRequestInterceptor(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
service, method := getServiceAndMethod(info.FullMethod)
ctx = s.newAuthContext(ctx)
clientID := getClientID(ctx)
resp, err := handler(ctx, req)
status := status.Convert(err).Code().String()
s.metrics.scope.Tagged(map[string]string{
serviceTag: service,
methodTag: method,
clientIDTag: clientID,
statusTag: status,
}).Counter(requestCounter).Inc(1)
s.logger.Debug(
"handler.request",
zap.String(methodTag, method),
zap.String(clientIDTag, clientID),
zap.String(statusTag, status),
)
return resp, err
}
func (s *Server) streamRequestInterceptor(srv any, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
service, method := getServiceAndMethod(info.FullMethod)
ctx := s.newAuthContext(stream.Context())
clientID := getClientID(ctx)
stream = &grpc_middleware.WrappedServerStream{
ServerStream: stream,
WrappedContext: ctx,
}
err := handler(srv, stream)
status := status.Convert(err).Code().String()
s.metrics.scope.Tagged(map[string]string{
serviceTag: service,
methodTag: method,
clientIDTag: clientID,
statusTag: status,
}).Counter(requestCounter).Inc(1)
s.logger.Debug(
"handler.stream.request",
zap.String(serviceTag, service),
zap.String(methodTag, method),
zap.String(clientIDTag, clientID),
zap.String(statusTag, status),
)
return err
}
// unaryErrorInterceptor is responsible for instrumenting the errors returned by unary methods.
func (s *Server) unaryErrorInterceptor(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
resp, err := handler(ctx, req)
return resp, s.mapToGrpcError(err, info.FullMethod, req)
}
// streamErrorInterceptor is responsible for instrumenting the errors returned by stream methods.
func (s *Server) streamErrorInterceptor(srv any, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
err := handler(srv, stream)
return s.mapToGrpcError(err, info.FullMethod, nil)
}
func (s *Server) unaryRateLimitInterceptor(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
service, method := getServiceAndMethod(info.FullMethod)
if service == consts.FullServiceName {
clientID := getClientID(ctx)
rcu := s.getRCUByMethod(method)
if !s.throttler.AllowN(clientID, rcu) {
return nil, status.Error(codes.ResourceExhausted, "rate limit exceeded")
}
}
return handler(ctx, req)
}
func (s *Server) streamRateLimitInterceptor(srv any, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
service, method := getServiceAndMethod(info.FullMethod)
if service == consts.FullServiceName {
clientID := getClientID(stream.Context())
rcu := s.getRCUByMethod(method)
if !s.throttler.AllowN(clientID, rcu) {
return status.Error(codes.ResourceExhausted, "rate limit exceeded")
}
}
return handler(srv, stream)
}
func (s *Server) getRCUByMethod(method string) int {
rcu, ok := rcuByMethod[method]
if !ok {
return 1
}
return rcu
}