-
Notifications
You must be signed in to change notification settings - Fork 2
/
blockchain.go
1315 lines (1162 loc) · 38.9 KB
/
blockchain.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 rpc
import (
"context"
"fmt"
"math/big"
"reflect"
"time"
"encoding/hex"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/rlp"
lru "github.com/hashicorp/golang-lru"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"golang.org/x/time/rate"
"github.com/PositionExchange/posichain/core/types"
internal_bls "github.com/PositionExchange/posichain/crypto/bls"
"github.com/PositionExchange/posichain/eth/rpc"
"github.com/PositionExchange/posichain/hmy"
"github.com/PositionExchange/posichain/internal/chain"
internal_common "github.com/PositionExchange/posichain/internal/common"
nodeconfig "github.com/PositionExchange/posichain/internal/configs/node"
"github.com/PositionExchange/posichain/internal/utils"
"github.com/PositionExchange/posichain/numeric"
rpc_common "github.com/PositionExchange/posichain/rpc/common"
eth "github.com/PositionExchange/posichain/rpc/eth"
v1 "github.com/PositionExchange/posichain/rpc/v1"
v2 "github.com/PositionExchange/posichain/rpc/v2"
"github.com/PositionExchange/posichain/shard"
stakingReward "github.com/PositionExchange/posichain/staking/reward"
)
// PublicBlockchainService provides an API to access the Harmony blockchain.
// It offers only methods that operate on public data that is freely available to anyone.
type PublicBlockchainService struct {
hmy *hmy.Harmony
version Version
limiter *rate.Limiter
rpcBlockFactory rpc_common.BlockFactory
helper *bcServiceHelper
// TEMP SOLUTION to rpc node spamming issue
limiterGetStakingNetworkInfo *rate.Limiter
limiterGetSuperCommittees *rate.Limiter
limiterGetCurrentUtilityMetrics *rate.Limiter
}
const (
DefaultRateLimiterWaitTimeout = 5 * time.Second
rpcGetBlocksLimit = 1024
)
// NewPublicBlockchainAPI creates a new API for the RPC interface
func NewPublicBlockchainAPI(hmy *hmy.Harmony, version Version, limiterEnable bool, limit int) rpc.API {
var limiter *rate.Limiter
if limiterEnable {
limiter = rate.NewLimiter(rate.Limit(limit), limit)
name := reflect.TypeOf(limiter).Elem().Name()
rpcRateLimitCounterVec.With(prometheus.Labels{
"limiter_name": name,
}).Add(float64(0))
}
s := &PublicBlockchainService{
hmy: hmy,
version: version,
limiter: limiter,
limiterGetStakingNetworkInfo: rate.NewLimiter(5, 10),
limiterGetSuperCommittees: rate.NewLimiter(5, 10),
limiterGetCurrentUtilityMetrics: rate.NewLimiter(5, 10),
}
s.helper = s.newHelper()
switch version {
case V1:
s.rpcBlockFactory = v1.NewBlockFactory(s.helper)
case V2:
s.rpcBlockFactory = v2.NewBlockFactory(s.helper)
case Eth:
s.rpcBlockFactory = eth.NewBlockFactory(s.helper)
default:
// This shall not happen for legitimate code.
}
return rpc.API{
Namespace: version.Namespace(),
Version: APIVersion,
Service: s,
Public: true,
}
}
// ChainId returns the chain id of the chain - required by MetaMask
func (s *PublicBlockchainService) ChainId(ctx context.Context) (interface{}, error) {
// Format return base on version
switch s.version {
case V1:
return hexutil.Uint64(s.hmy.ChainID), nil
case V2:
return s.hmy.ChainID, nil
case Eth:
ethChainID := nodeconfig.GetDefaultConfig().GetNetworkType().ChainConfig().EthCompatibleChainID
return hexutil.Uint64(ethChainID.Uint64()), nil
default:
return nil, ErrUnknownRPCVersion
}
}
// Accounts returns the collection of accounts this node manages
// While this JSON-RPC method is supported, it will not return any accounts.
// Similar to e.g. Infura "unlocking" accounts isn't supported.
// Instead, users should send already signed raw transactions using hmy_sendRawTransaction or eth_sendRawTransaction
func (s *PublicBlockchainService) Accounts() []common.Address {
return []common.Address{}
}
// getBalanceByBlockNumber returns balance by block number at given eth blockNum without checks
func (s *PublicBlockchainService) getBalanceByBlockNumber(
ctx context.Context, address string, blockNum rpc.BlockNumber,
) (*big.Int, error) {
addr, err := internal_common.ParseAddr(address)
if err != nil {
return nil, err
}
balance, err := s.hmy.GetBalance(ctx, addr, rpc.BlockNumberOrHashWithNumber(blockNum))
if err != nil {
return nil, err
}
return balance, nil
}
// BlockNumber returns the block number of the chain head.
func (s *PublicBlockchainService) BlockNumber(ctx context.Context) (interface{}, error) {
// Fetch latest header
header, err := s.hmy.HeaderByNumber(ctx, rpc.LatestBlockNumber)
if err != nil {
return nil, err
}
// Format return base on version
switch s.version {
case V1, Eth:
return hexutil.Uint64(header.Number().Uint64()), nil
case V2:
return header.Number().Uint64(), nil
default:
return nil, ErrUnknownRPCVersion
}
}
func (s *PublicBlockchainService) wait(limiter *rate.Limiter, ctx context.Context) error {
if limiter != nil {
deadlineCtx, cancel := context.WithTimeout(ctx, DefaultRateLimiterWaitTimeout)
defer cancel()
if !limiter.Allow() {
name := reflect.TypeOf(limiter).Elem().Name()
rpcRateLimitCounterVec.With(prometheus.Labels{
"limiter_name": name,
}).Inc()
}
return limiter.Wait(deadlineCtx)
}
return nil
}
// GetBlockByNumber returns the requested block. When blockNum is -1 the chain head is returned. When fullTx is true all
// transactions in the block are returned in full detail, otherwise only the transaction hash is returned.
// When withSigners in BlocksArgs is true it shows block signers for this block in list of one addresses.
func (s *PublicBlockchainService) GetBlockByNumber(
ctx context.Context, blockNumber BlockNumber, opts interface{},
) (response interface{}, err error) {
timer := DoMetricRPCRequest(GetBlockByNumber)
defer DoRPCRequestDuration(GetBlockByNumber, timer)
err = s.wait(s.limiter, ctx)
if err != nil {
DoMetricRPCQueryInfo(GetBlockByNumber, RateLimitedNumber)
return nil, err
}
// Process arguments based on version
blockArgs, err := s.getBlockOptions(opts)
if err != nil {
DoMetricRPCQueryInfo(GetBlockByNumber, FailedNumber)
return nil, err
}
if blockNumber.EthBlockNumber() == rpc.PendingBlockNumber {
return nil, errors.New("pending block number not implemented")
}
var blockNum uint64
if blockNumber.EthBlockNumber() == rpc.LatestBlockNumber {
blockNum = s.hmy.BlockChain.CurrentHeader().Number().Uint64()
} else {
blockNum = uint64(blockNumber.EthBlockNumber().Int64())
}
blk := s.hmy.BlockChain.GetBlockByNumber(blockNum)
// Some Ethereum tools (such as Truffle) rely on being able to query for future blocks without the chain returning errors.
// These tools implement retry mechanisms that will query & retry for a given block until it has been finalized.
// Throwing an error like "requested block number greater than current block number" breaks this retry functionality.
// Disable isBlockGreaterThanLatest checks for Ethereum RPC:s, but keep them in place for legacy hmy_ RPC:s for now to ensure backwards compatibility
if blk == nil {
DoMetricRPCQueryInfo(GetBlockByNumber, FailedNumber)
if s.version == Eth {
return nil, nil
}
return nil, ErrRequestedBlockTooHigh
}
// Format the response according to version
rpcBlock, err := s.rpcBlockFactory.NewBlock(blk, blockArgs)
if err != nil {
DoMetricRPCQueryInfo(GetBlockByNumber, FailedNumber)
return nil, err
}
return rpcBlock, err
}
// GetBlockByHash returns the requested block. When fullTx is true all transactions in the block are returned in full
// detail, otherwise only the transaction hash is returned. When withSigners in BlocksArgs is true
// it shows block signers for this block in list of one addresses.
func (s *PublicBlockchainService) GetBlockByHash(
ctx context.Context, blockHash common.Hash, opts interface{},
) (response interface{}, err error) {
timer := DoMetricRPCRequest(GetBlockByHash)
defer DoRPCRequestDuration(GetBlockByHash, timer)
err = s.wait(s.limiter, ctx)
if err != nil {
DoMetricRPCQueryInfo(GetBlockByHash, RateLimitedNumber)
return nil, err
}
// Process arguments based on version
blockArgs, err := s.getBlockOptions(opts)
if err != nil {
DoMetricRPCQueryInfo(GetBlockByHash, FailedNumber)
return nil, err
}
// Fetch the block
blk, err := s.hmy.GetBlock(ctx, blockHash)
if err != nil || blk == nil {
DoMetricRPCQueryInfo(GetBlockByHash, FailedNumber)
return nil, err
}
// Format the response according to version
rpcBlock, err := s.rpcBlockFactory.NewBlock(blk, blockArgs)
if err != nil {
DoMetricRPCQueryInfo(GetBlockByNumber, FailedNumber)
return nil, err
}
return rpcBlock, err
}
// GetBlockByNumberNew is an alias for GetBlockByNumber using rpc_common.BlockArgs
func (s *PublicBlockchainService) GetBlockByNumberNew(
ctx context.Context, blockNum BlockNumber, blockArgs *rpc_common.BlockArgs,
) (interface{}, error) {
timer := DoMetricRPCRequest(GetBlockByNumberNew)
defer DoRPCRequestDuration(GetBlockByNumberNew, timer)
res, err := s.GetBlockByNumber(ctx, blockNum, blockArgs)
if err != nil {
DoMetricRPCQueryInfo(GetBlockByNumberNew, FailedNumber)
}
return res, err
}
// GetBlockByHashNew is an alias for GetBlocksByHash using rpc_common.BlockArgs
func (s *PublicBlockchainService) GetBlockByHashNew(
ctx context.Context, blockHash common.Hash, blockArgs *rpc_common.BlockArgs,
) (interface{}, error) {
timer := DoMetricRPCRequest(GetBlockByHashNew)
defer DoRPCRequestDuration(GetBlockByHashNew, timer)
res, err := s.GetBlockByHash(ctx, blockHash, blockArgs)
if err != nil {
DoMetricRPCQueryInfo(GetBlockByHashNew, FailedNumber)
}
return res, err
}
// GetBlocks method returns blocks in range blockStart, blockEnd just like GetBlockByNumber but all at once.
func (s *PublicBlockchainService) GetBlocks(
ctx context.Context, blockNumberStart BlockNumber,
blockNumberEnd BlockNumber, blockArgs *rpc_common.BlockArgs,
) ([]interface{}, error) {
timer := DoMetricRPCRequest(GetBlocks)
defer DoRPCRequestDuration(GetBlocks, timer)
blockStart := blockNumberStart.Int64()
blockEnd := blockNumberEnd.Int64()
if blockNumberEnd.EthBlockNumber() == rpc.LatestBlockNumber {
blockEnd = s.hmy.BlockChain.CurrentHeader().Number().Int64()
}
if blockEnd >= blockStart && blockEnd-blockStart > rpcGetBlocksLimit {
return nil, fmt.Errorf("GetBlocks query must be smaller than size %v", rpcGetBlocksLimit)
}
// Fetch blocks within given range
result := make([]interface{}, 0)
for i := blockStart; i <= blockEnd; i++ {
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
}
blockNum := BlockNumber(i)
if blockNum.Int64() > s.hmy.CurrentBlock().Number().Int64() {
break
}
// rpcBlock is already formatted according to version
rpcBlock, err := s.GetBlockByNumber(ctx, blockNum, blockArgs)
if err != nil {
DoMetricRPCQueryInfo(GetBlockByNumber, FailedNumber)
utils.Logger().Warn().Err(err).Msg("RPC Get Blocks Error")
return nil, err
}
if rpcBlock != nil {
result = append(result, rpcBlock)
}
}
return result, nil
}
// IsLastBlock checks if block is last epoch block.
func (s *PublicBlockchainService) IsLastBlock(ctx context.Context, blockNum uint64) (bool, error) {
timer := DoMetricRPCRequest(IsLastBlock)
defer DoRPCRequestDuration(IsLastBlock, timer)
if !isBeaconShard(s.hmy) {
return false, ErrNotBeaconShard
}
return shard.Schedule.IsLastBlock(blockNum), nil
}
// EpochLastBlock returns epoch last block.
func (s *PublicBlockchainService) EpochLastBlock(ctx context.Context, epoch uint64) (uint64, error) {
timer := DoMetricRPCRequest(EpochLastBlock)
defer DoRPCRequestDuration(EpochLastBlock, timer)
if !isBeaconShard(s.hmy) {
return 0, ErrNotBeaconShard
}
return shard.Schedule.EpochLastBlock(epoch), nil
}
// GetBlockSigners returns signers for a particular block.
func (s *PublicBlockchainService) GetBlockSigners(
ctx context.Context, blockNumber BlockNumber,
) ([]string, error) {
timer := DoMetricRPCRequest(GetBlockSigners)
defer DoRPCRequestDuration(GetBlockSigners, timer)
// Process arguments based on version
blockNum := blockNumber.EthBlockNumber()
if blockNum == rpc.PendingBlockNumber {
return nil, errors.New("cannot get signer keys for pending blocks")
}
// Ensure correct block
if blockNum.Int64() == 0 || blockNum.Int64() >= s.hmy.CurrentBlock().Number().Int64() {
return []string{}, nil
}
if isBlockGreaterThanLatest(s.hmy, blockNum) {
return nil, ErrRequestedBlockTooHigh
}
var bn uint64
if blockNum == rpc.LatestBlockNumber {
bn = s.hmy.CurrentBlock().NumberU64()
} else {
bn = uint64(blockNum.Int64())
}
blk := s.hmy.BlockChain.GetBlockByNumber(bn)
if blk == nil {
return nil, errors.New("unknown block")
}
// Fetch signers
return s.helper.GetSigners(blk)
}
// GetBlockSignerKeys returns bls public keys that signed the block.
func (s *PublicBlockchainService) GetBlockSignerKeys(
ctx context.Context, blockNumber BlockNumber,
) ([]string, error) {
timer := DoMetricRPCRequest(GetBlockSignerKeys)
defer DoRPCRequestDuration(GetBlockSignerKeys, timer)
// Process arguments based on version
blockNum := blockNumber.EthBlockNumber()
if blockNum == rpc.PendingBlockNumber {
return nil, errors.New("cannot get signer keys for pending blocks")
}
// Ensure correct block
if blockNum.Int64() == 0 || blockNum.Int64() >= s.hmy.CurrentBlock().Number().Int64() {
return []string{}, nil
}
if isBlockGreaterThanLatest(s.hmy, blockNum) {
return nil, ErrRequestedBlockTooHigh
}
var bn uint64
if blockNum == rpc.LatestBlockNumber {
bn = s.hmy.CurrentBlock().NumberU64()
} else {
bn = uint64(blockNum.Int64())
}
// Fetch signers
return s.helper.GetBLSSigners(bn)
}
// GetBlockReceipts returns all transaction receipts for a particular block.
func (s *PublicBlockchainService) GetBlockReceipts(
ctx context.Context, blockHash common.Hash,
) ([]StructuredResponse, error) {
timer := DoMetricRPCRequest(GetBlockReceipts)
defer DoRPCRequestDuration(GetBlockReceipts, timer)
block, err := s.hmy.GetBlock(ctx, blockHash)
if err != nil {
return nil, err
}
receipts, err := s.hmy.GetReceipts(ctx, blockHash)
if err != nil {
return nil, err
}
rmap := make(map[common.Hash]*types.Receipt, len(receipts))
for _, r := range receipts {
rmap[r.TxHash] = r
}
txns := make([]types.CoreTransaction, 0,
block.Transactions().Len()+block.StakingTransactions().Len())
for _, tx := range block.Transactions() {
txns = append(txns, tx)
}
for _, tx := range block.StakingTransactions() {
txns = append(txns, tx)
}
if len(txns) != len(rmap) {
return nil, fmt.Errorf(
"transactions (%d) and receipts (%d) count mismatch",
len(txns), len(rmap))
}
rpcr := make([]StructuredResponse, 0, len(txns))
for i, tx := range txns {
index := uint64(i)
r, err := interface{}(nil), error(nil)
switch s.version {
case V1:
r, err = v1.NewReceipt(tx, blockHash, block.NumberU64(), index, rmap[tx.Hash()])
case V2:
r, err = v2.NewReceipt(tx, blockHash, block.NumberU64(), index, rmap[tx.Hash()])
case Eth:
if tx, ok := tx.(*types.Transaction); ok {
r, err = eth.NewReceipt(tx.ConvertToEth(), blockHash, block.NumberU64(), index, rmap[tx.Hash()])
}
default:
return nil, ErrUnknownRPCVersion
}
if err != nil {
return nil, err
}
sr, err := NewStructuredResponse(r)
if err != nil {
return nil, err
}
rpcr = append(rpcr, sr)
}
return rpcr, nil
}
// IsBlockSigner returns true if validator with address signed blockNum block.
func (s *PublicBlockchainService) IsBlockSigner(
ctx context.Context, blockNumber BlockNumber, address string,
) (bool, error) {
timer := DoMetricRPCRequest(IsBlockSigner)
defer DoRPCRequestDuration(IsBlockSigner, timer)
// Process arguments based on version
blockNum := blockNumber.EthBlockNumber()
// Ensure correct block
if blockNum.Int64() == 0 {
return false, nil
}
if isBlockGreaterThanLatest(s.hmy, blockNum) {
return false, ErrRequestedBlockTooHigh
}
var bn uint64
if blockNum == rpc.PendingBlockNumber {
return false, errors.New("no signing data for pending block number")
} else if blockNum == rpc.LatestBlockNumber {
bn = s.hmy.BlockChain.CurrentBlock().NumberU64()
} else {
bn = uint64(blockNum.Int64())
}
// Fetch signers
return s.helper.IsSigner(address, bn)
}
// GetSignedBlocks returns how many blocks a particular validator signed for
// last blocksPeriod (1 epoch's worth of blocks).
func (s *PublicBlockchainService) GetSignedBlocks(
ctx context.Context, address string,
) (interface{}, error) {
timer := DoMetricRPCRequest(GetSignedBlocks)
defer DoRPCRequestDuration(GetSignedBlocks, timer)
// Fetch the number of signed blocks within default period
curEpoch := s.hmy.CurrentBlock().Epoch()
var totalSigned uint64
if !s.hmy.ChainConfig().IsStaking(curEpoch) {
// calculate signed before staking epoch
totalSigned := uint64(0)
lastBlock := uint64(0)
blockHeight := s.hmy.CurrentBlock().Number().Uint64()
instance := shard.Schedule.InstanceForEpoch(s.hmy.CurrentBlock().Epoch())
if blockHeight >= instance.BlocksPerEpoch() {
lastBlock = blockHeight - instance.BlocksPerEpoch() + 1
}
for i := lastBlock; i <= blockHeight; i++ {
signed, err := s.IsBlockSigner(ctx, BlockNumber(i), address)
if err == nil && signed {
totalSigned++
}
}
} else {
ethAddr := common.HexToAddress(address)
curVal, err := s.hmy.BlockChain.ReadValidatorInformation(ethAddr)
if err != nil {
return nil, err
}
prevVal, err := s.hmy.BlockChain.ReadValidatorSnapshot(ethAddr)
if err != nil {
return nil, err
}
signedInEpoch := new(big.Int).Sub(curVal.Counters.NumBlocksSigned, prevVal.Validator.Counters.NumBlocksSigned)
if signedInEpoch.Cmp(common.Big0) < 0 {
return nil, errors.New("negative signed in epoch")
}
totalSigned = signedInEpoch.Uint64()
}
// Format the response according to the version
switch s.version {
case V1, Eth:
return hexutil.Uint64(totalSigned), nil
case V2:
return totalSigned, nil
default:
return nil, ErrUnknownRPCVersion
}
}
// GetEpoch returns current epoch.
func (s *PublicBlockchainService) GetEpoch(ctx context.Context) (interface{}, error) {
timer := DoMetricRPCRequest(GetEpoch)
defer DoRPCRequestDuration(GetEpoch, timer)
// Fetch Header
header, err := s.hmy.HeaderByNumber(ctx, rpc.LatestBlockNumber)
if err != nil {
return "", err
}
epoch := header.Epoch().Uint64()
// Format the response according to the version
switch s.version {
case V1, Eth:
return hexutil.Uint64(epoch), nil
case V2:
return epoch, nil
default:
return nil, ErrUnknownRPCVersion
}
}
// GetLeader returns current shard leader.
func (s *PublicBlockchainService) GetLeader(ctx context.Context) (string, error) {
timer := DoMetricRPCRequest(GetLeader)
defer DoRPCRequestDuration(GetLeader, timer)
// Fetch Header
blk := s.hmy.BlockChain.CurrentBlock()
// Response output is the same for all versions
leader := s.helper.GetLeader(blk)
return leader, nil
}
// GetShardingStructure returns an array of sharding structures.
func (s *PublicBlockchainService) GetShardingStructure(
ctx context.Context,
) ([]StructuredResponse, error) {
timer := DoMetricRPCRequest(GetShardingStructure)
defer DoRPCRequestDuration(GetShardingStructure, timer)
err := s.wait(s.limiter, ctx)
if err != nil {
DoMetricRPCQueryInfo(GetShardingStructure, RateLimitedNumber)
return nil, err
}
// Get header and number of shards.
epoch := s.hmy.CurrentBlock().Epoch()
numShard := shard.Schedule.InstanceForEpoch(epoch).NumShards()
// Return sharding structure for each case (response output is the same for all versions)
return shard.Schedule.GetShardingStructure(int(numShard), int(s.hmy.ShardID)), nil
}
// GetShardID returns shard ID of the requested node.
func (s *PublicBlockchainService) GetShardID(ctx context.Context) (int, error) {
// Response output is the same for all versions
return int(s.hmy.ShardID), nil
}
// GetBalanceByBlockNumber returns balance by block number
func (s *PublicBlockchainService) GetBalanceByBlockNumber(
ctx context.Context, address string, blockNumber BlockNumber,
) (interface{}, error) {
timer := DoMetricRPCRequest(GetBalanceByBlockNumber)
defer DoRPCRequestDuration(GetBalanceByBlockNumber, timer)
// Process number based on version
blockNum := blockNumber.EthBlockNumber()
// Fetch balance
if isBlockGreaterThanLatest(s.hmy, blockNum) {
DoMetricRPCQueryInfo(GetBalanceByBlockNumber, FailedNumber)
return nil, ErrRequestedBlockTooHigh
}
balance, err := s.getBalanceByBlockNumber(ctx, address, blockNum)
if err != nil {
DoMetricRPCQueryInfo(GetBalanceByBlockNumber, FailedNumber)
return nil, err
}
// Format return base on version
switch s.version {
case V1, Eth:
return (*hexutil.Big)(balance), nil
case V2:
return balance, nil
default:
return nil, ErrUnknownRPCVersion
}
}
// LatestHeader returns the latest header information
func (s *PublicBlockchainService) LatestHeader(ctx context.Context) (StructuredResponse, error) {
timer := DoMetricRPCRequest(LatestHeader)
defer DoRPCRequestDuration(LatestHeader, timer)
err := s.wait(s.limiter, ctx)
if err != nil {
DoMetricRPCQueryInfo(LatestHeader, RateLimitedNumber)
return nil, err
}
// Fetch Header
header, err := s.hmy.HeaderByNumber(ctx, rpc.LatestBlockNumber)
if err != nil {
DoMetricRPCQueryInfo(LatestHeader, FailedNumber)
return nil, err
}
// Response output is the same for all versions
leader := s.hmy.GetLeaderAddress(header.Coinbase(), header.Epoch())
return NewStructuredResponse(NewHeaderInformation(header, leader))
}
// GetLatestChainHeaders ..
func (s *PublicBlockchainService) GetLatestChainHeaders(
ctx context.Context,
) (StructuredResponse, error) {
// Response output is the same for all versions
timer := DoMetricRPCRequest(GetLatestChainHeaders)
defer DoRPCRequestDuration(GetLatestChainHeaders, timer)
return NewStructuredResponse(s.hmy.GetLatestChainHeaders())
}
// GetLastCrossLinks ..
func (s *PublicBlockchainService) GetLastCrossLinks(
ctx context.Context,
) ([]StructuredResponse, error) {
timer := DoMetricRPCRequest(GetLastCrossLinks)
defer DoRPCRequestDuration(GetLastCrossLinks, timer)
err := s.wait(s.limiter, ctx)
if err != nil {
DoMetricRPCQueryInfo(GetLastCrossLinks, RateLimitedNumber)
return nil, err
}
if !isBeaconShard(s.hmy) {
DoMetricRPCQueryInfo(GetLastCrossLinks, FailedNumber)
return nil, ErrNotBeaconShard
}
// Fetch crosslinks
crossLinks, err := s.hmy.GetLastCrossLinks()
if err != nil {
DoMetricRPCQueryInfo(GetLastCrossLinks, FailedNumber)
return nil, err
}
// Format response, all output is the same for all versions
responseSlice := []StructuredResponse{}
for _, el := range crossLinks {
response, err := NewStructuredResponse(el)
if err != nil {
DoMetricRPCQueryInfo(GetLastCrossLinks, FailedNumber)
return nil, err
}
responseSlice = append(responseSlice, response)
}
return responseSlice, nil
}
// GetHeaderByNumber returns block header at given number
func (s *PublicBlockchainService) GetHeaderByNumber(
ctx context.Context, blockNumber BlockNumber,
) (StructuredResponse, error) {
timer := DoMetricRPCRequest(GetHeaderByNumber)
defer DoRPCRequestDuration(GetHeaderByNumber, timer)
err := s.wait(s.limiter, ctx)
if err != nil {
DoMetricRPCQueryInfo(GetHeaderByNumber, RateLimitedNumber)
return nil, err
}
// Process number based on version
blockNum := blockNumber.EthBlockNumber()
// Ensure valid block number
if s.version != Eth && isBlockGreaterThanLatest(s.hmy, blockNum) {
DoMetricRPCQueryInfo(GetHeaderByNumber, FailedNumber)
return nil, ErrRequestedBlockTooHigh
}
// Fetch Header
header, err := s.hmy.HeaderByNumber(ctx, blockNum)
if header != nil && err == nil {
// Response output is the same for all versions
leader := s.hmy.GetLeaderAddress(header.Coinbase(), header.Epoch())
return NewStructuredResponse(NewHeaderInformation(header, leader))
}
return nil, err
}
// Result structs for GetProof
type AccountResult struct {
Address common.Address `json:"address"`
AccountProof []string `json:"accountProof"`
Balance *hexutil.Big `json:"balance"`
CodeHash common.Hash `json:"codeHash"`
Nonce hexutil.Uint64 `json:"nonce"`
StorageHash common.Hash `json:"storageHash"`
StorageProof []StorageResult `json:"storageProof"`
}
type StorageResult struct {
Key string `json:"key"`
Value *hexutil.Big `json:"value"`
Proof []string `json:"proof"`
}
// GetHeaderByNumberRLPHex returns block header at given number by `hex(rlp(header))`
func (s *PublicBlockchainService) GetProof(
ctx context.Context, address common.Address, storageKeys []string, blockNrOrHash rpc.BlockNumberOrHash) (ret *AccountResult, err error) {
timer := DoMetricRPCRequest(GetProof)
defer DoRPCRequestDuration(GetProof, timer)
defer func() {
if ret == nil || err != nil {
DoMetricRPCQueryInfo(GetProof, FailedNumber)
}
}()
err = s.wait(s.limiter, ctx)
if err != nil {
DoMetricRPCQueryInfo(GetProof, RateLimitedNumber)
return
}
state, _, err := s.hmy.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
if state == nil || err != nil {
return nil, err
}
storageTrie := state.StorageTrie(address)
storageHash := types.EmptyRootHash
codeHash := state.GetCodeHash(address)
storageProof := make([]StorageResult, len(storageKeys))
// if we have a storageTrie, (which means the account exists), we can update the storagehash
if storageTrie != nil {
storageHash = storageTrie.Hash()
} else {
// no storageTrie means the account does not exist, so the codeHash is the hash of an empty bytearray.
codeHash = crypto.Keccak256Hash(nil)
}
// create the proof for the storageKeys
for i, key := range storageKeys {
if storageTrie != nil {
proof, storageError := state.GetStorageProof(address, common.HexToHash(key))
if storageError != nil {
err = storageError
return
}
storageProof[i] = StorageResult{key, (*hexutil.Big)(state.GetState(address, common.HexToHash(key)).Big()), toHexSlice(proof)}
} else {
storageProof[i] = StorageResult{key, &hexutil.Big{}, []string{}}
}
}
// create the accountProof
accountProof, err := state.GetProof(address)
if err != nil {
return
}
ret, err = &AccountResult{
Address: address,
AccountProof: toHexSlice(accountProof),
Balance: (*hexutil.Big)(state.GetBalance(address)),
CodeHash: codeHash,
Nonce: hexutil.Uint64(state.GetNonce(address)),
StorageHash: storageHash,
StorageProof: storageProof,
}, state.Error()
return
}
// toHexSlice creates a slice of hex-strings based on []byte.
func toHexSlice(b [][]byte) []string {
r := make([]string, len(b))
for i := range b {
r[i] = hexutil.Encode(b[i])
}
return r
}
// GetHeaderByNumberRLPHex returns block header at given number by `hex(rlp(header))`
func (s *PublicBlockchainService) GetHeaderByNumberRLPHex(
ctx context.Context, blockNumber BlockNumber,
) (string, error) {
timer := DoMetricRPCRequest(GetHeaderByNumberRLPHex)
defer DoRPCRequestDuration(GetHeaderByNumberRLPHex, timer)
err := s.wait(s.limiter, ctx)
if err != nil {
DoMetricRPCQueryInfo(GetHeaderByNumberRLPHex, RateLimitedNumber)
return "", err
}
// Process number based on version
blockNum := blockNumber.EthBlockNumber()
// Ensure valid block number
if s.version != Eth && isBlockGreaterThanLatest(s.hmy, blockNum) {
DoMetricRPCQueryInfo(GetHeaderByNumberRLPHex, FailedNumber)
return "", ErrRequestedBlockTooHigh
}
// Fetch Header
header, err := s.hmy.HeaderByNumber(ctx, blockNum)
if header != nil && err == nil {
// Response output is the same for all versions
val, _ := rlp.EncodeToBytes(header)
return hex.EncodeToString(val), nil
}
return "", err
}
// GetCurrentUtilityMetrics ..
func (s *PublicBlockchainService) GetCurrentUtilityMetrics(
ctx context.Context,
) (StructuredResponse, error) {
timer := DoMetricRPCRequest(GetCurrentUtilityMetrics)
defer DoRPCRequestDuration(GetCurrentUtilityMetrics, timer)
err := s.wait(s.limiterGetCurrentUtilityMetrics, ctx)
if err != nil {
DoMetricRPCQueryInfo(GetCurrentUtilityMetrics, RateLimitedNumber)
return nil, err
}
if !isBeaconShard(s.hmy) {
DoMetricRPCQueryInfo(GetCurrentUtilityMetrics, FailedNumber)
return nil, ErrNotBeaconShard
}
// Fetch metrics
metrics, err := s.hmy.GetCurrentUtilityMetrics()
if err != nil {
DoMetricRPCQueryInfo(GetCurrentUtilityMetrics, FailedNumber)
return nil, err
}
// Response output is the same for all versions
return NewStructuredResponse(metrics)
}
// GetSuperCommittees ..
func (s *PublicBlockchainService) GetSuperCommittees(
ctx context.Context,
) (StructuredResponse, error) {
timer := DoMetricRPCRequest(GetSuperCommittees)
defer DoRPCRequestDuration(GetSuperCommittees, timer)
err := s.wait(s.limiterGetSuperCommittees, ctx)
if err != nil {
DoMetricRPCQueryInfo(GetSuperCommittees, RateLimitedNumber)
return nil, err
}
if !isBeaconShard(s.hmy) {
DoMetricRPCQueryInfo(GetSuperCommittees, FailedNumber)
return nil, ErrNotBeaconShard
}
// Fetch super committees
cmt, err := s.hmy.GetSuperCommittees()
if err != nil {
DoMetricRPCQueryInfo(GetSuperCommittees, FailedNumber)
return nil, err
}
// Response output is the same for all versions
return NewStructuredResponse(cmt)
}
// GetCurrentBadBlocks ..
func (s *PublicBlockchainService) GetCurrentBadBlocks(
ctx context.Context,
) ([]StructuredResponse, error) {
timer := DoMetricRPCRequest(GetCurrentBadBlocks)
defer DoRPCRequestDuration(GetCurrentBadBlocks, timer)
err := s.wait(s.limiter, ctx)
if err != nil {
DoMetricRPCQueryInfo(GetCurrentBadBlocks, RateLimitedNumber)
return nil, err
}
// Fetch bad blocks and format
badBlocks := []StructuredResponse{}
for _, blk := range s.hmy.GetCurrentBadBlocks() {
// Response output is the same for all versions
fmtBadBlock, err := NewStructuredResponse(blk)
if err != nil {
DoMetricRPCQueryInfo(GetCurrentBadBlocks, FailedNumber)
return nil, err
}
badBlocks = append(badBlocks, fmtBadBlock)
}
return badBlocks, nil
}
// GetTotalSupply ..
func (s *PublicBlockchainService) GetTotalSupply(
ctx context.Context,
) (numeric.Dec, error) {
timer := DoMetricRPCRequest(GetTotalSupply)
defer DoRPCRequestDuration(GetTotalSupply, timer)
return stakingReward.GetTotalTokens(s.hmy.BlockChain)
}
// GetCirculatingSupply ...
func (s *PublicBlockchainService) GetCirculatingSupply(
ctx context.Context,
) (numeric.Dec, error) {
timer := DoMetricRPCRequest(GetCirculatingSupply)
defer DoRPCRequestDuration(GetCirculatingSupply, timer)
return chain.GetCirculatingSupply(s.hmy.BlockChain)
}
// GetStakingNetworkInfo ..
func (s *PublicBlockchainService) GetStakingNetworkInfo(
ctx context.Context,