-
Notifications
You must be signed in to change notification settings - Fork 324
/
coreservice.go
1990 lines (1852 loc) · 64.9 KB
/
coreservice.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
// Copyright (c) 2022 IoTeX Foundation
// This source code is provided 'as is' and no warranties are given as to title or non-infringement, merchantability
// or fitness for purpose and, to the extent permitted by law, all liability for your use of the code is disclaimed.
// This source code is governed by Apache License 2.0 that can be found in the LICENSE file.
package api
import (
"bytes"
"context"
"encoding/hex"
"fmt"
"math"
"math/big"
"strconv"
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/eth/tracers"
// Force-load the tracer engines to trigger registration
_ "github.com/ethereum/go-ethereum/eth/tracers/js"
_ "github.com/ethereum/go-ethereum/eth/tracers/native"
"github.com/ethereum/go-ethereum/eth/tracers/logger"
"github.com/pkg/errors"
"go.uber.org/zap"
"golang.org/x/sync/errgroup"
"google.golang.org/genproto/googleapis/rpc/errdetails"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/durationpb"
"google.golang.org/protobuf/types/known/timestamppb"
"github.com/iotexproject/go-pkgs/hash"
"github.com/iotexproject/go-pkgs/util"
"github.com/iotexproject/iotex-address/address"
"github.com/iotexproject/iotex-election/committee"
"github.com/iotexproject/iotex-proto/golang/iotexapi"
"github.com/iotexproject/iotex-proto/golang/iotextypes"
"github.com/iotexproject/iotex-core/v2/action"
"github.com/iotexproject/iotex-core/v2/action/protocol"
accountutil "github.com/iotexproject/iotex-core/v2/action/protocol/account/util"
"github.com/iotexproject/iotex-core/v2/action/protocol/execution/evm"
"github.com/iotexproject/iotex-core/v2/action/protocol/poll"
"github.com/iotexproject/iotex-core/v2/action/protocol/rewarding"
"github.com/iotexproject/iotex-core/v2/action/protocol/rolldpos"
"github.com/iotexproject/iotex-core/v2/action/protocol/staking"
"github.com/iotexproject/iotex-core/v2/actpool"
logfilter "github.com/iotexproject/iotex-core/v2/api/logfilter"
apitypes "github.com/iotexproject/iotex-core/v2/api/types"
"github.com/iotexproject/iotex-core/v2/blockchain"
"github.com/iotexproject/iotex-core/v2/blockchain/block"
"github.com/iotexproject/iotex-core/v2/blockchain/blockdao"
"github.com/iotexproject/iotex-core/v2/blockchain/filedao"
"github.com/iotexproject/iotex-core/v2/blockchain/genesis"
"github.com/iotexproject/iotex-core/v2/blockindex"
"github.com/iotexproject/iotex-core/v2/blocksync"
"github.com/iotexproject/iotex-core/v2/db"
"github.com/iotexproject/iotex-core/v2/gasstation"
"github.com/iotexproject/iotex-core/v2/pkg/log"
batch "github.com/iotexproject/iotex-core/v2/pkg/messagebatcher"
"github.com/iotexproject/iotex-core/v2/pkg/tracer"
"github.com/iotexproject/iotex-core/v2/pkg/unit"
"github.com/iotexproject/iotex-core/v2/pkg/version"
"github.com/iotexproject/iotex-core/v2/server/itx/nodestats"
"github.com/iotexproject/iotex-core/v2/state"
"github.com/iotexproject/iotex-core/v2/state/factory"
)
const _workerNumbers int = 5
const (
// defaultTraceTimeout is the amount of time a single transaction can execute
// by default before being forcefully aborted.
defaultTraceTimeout = 5 * time.Second
)
type (
// CoreService provides api interface for user to interact with blockchain data
CoreService interface {
// Account returns the metadata of an account
Account(addr address.Address) (*iotextypes.AccountMeta, *iotextypes.BlockIdentifier, error)
// ChainMeta returns blockchain metadata
ChainMeta() (*iotextypes.ChainMeta, string, error)
// ServerMeta gets the server metadata
ServerMeta() (packageVersion string, packageCommitID string, gitStatus string, goVersion string, buildTime string)
// SendAction is the API to send an action to blockchain.
SendAction(ctx context.Context, in *iotextypes.Action) (string, error)
// ReadContract reads the state in a contract address specified by the slot
ReadContract(ctx context.Context, callerAddr address.Address, sc action.Envelope) (string, *iotextypes.Receipt, error)
// ReadState reads state on blockchain
ReadState(protocolID string, height string, methodName []byte, arguments [][]byte) (*iotexapi.ReadStateResponse, error)
// SuggestGasPrice suggests gas price
SuggestGasPrice() (uint64, error)
// SuggestGasTipCap suggests gas tip cap
SuggestGasTipCap() (*big.Int, error)
// EstimateGasForAction estimates gas for action
EstimateGasForAction(ctx context.Context, in *iotextypes.Action) (uint64, error)
// EpochMeta gets epoch metadata
EpochMeta(epochNum uint64) (*iotextypes.EpochData, uint64, []*iotexapi.BlockProducerInfo, error)
// RawBlocks gets raw block data
RawBlocks(startHeight uint64, count uint64, withReceipts bool, withTransactionLogs bool) ([]*iotexapi.BlockInfo, error)
// ElectionBuckets returns the native election buckets.
ElectionBuckets(epochNum uint64) ([]*iotextypes.ElectionBucket, error)
// ReceiptByActionHash returns receipt by action hash
ReceiptByActionHash(h hash.Hash256) (*action.Receipt, error)
// TransactionLogByActionHash returns transaction log by action hash
TransactionLogByActionHash(actHash string) (*iotextypes.TransactionLog, error)
// TransactionLogByBlockHeight returns transaction log by block height
TransactionLogByBlockHeight(blockHeight uint64) (*iotextypes.BlockIdentifier, *iotextypes.TransactionLogs, error)
// Start starts the API server
Start(ctx context.Context) error
// Stop stops the API server
Stop(ctx context.Context) error
// Actions returns actions within the range
Actions(start uint64, count uint64) ([]*iotexapi.ActionInfo, error)
// TODO: unify the three get action by hash methods: Action, ActionByActionHash, PendingActionByActionHash
// Action returns action by action hash
Action(actionHash string, checkPending bool) (*iotexapi.ActionInfo, error)
// ActionsByAddress returns all actions associated with an address
ActionsByAddress(addr address.Address, start uint64, count uint64) ([]*iotexapi.ActionInfo, error)
// ActionByActionHash returns action by action hash
ActionByActionHash(h hash.Hash256) (*action.SealedEnvelope, *block.Block, uint32, error)
// PendingActionByActionHash returns action by action hash
PendingActionByActionHash(h hash.Hash256) (*action.SealedEnvelope, error)
// ActPoolActions returns the all Transaction Identifiers in the actpool
ActionsInActPool(actHashes []string) ([]*action.SealedEnvelope, error)
// BlockByHeightRange returns blocks within the height range
BlockByHeightRange(uint64, uint64) ([]*apitypes.BlockWithReceipts, error)
// BlockByHeight returns the block and its receipt from block height
BlockByHeight(uint64) (*apitypes.BlockWithReceipts, error)
// BlockByHash returns the block and its receipt
BlockByHash(string) (*apitypes.BlockWithReceipts, error)
// UnconfirmedActionsByAddress returns all unconfirmed actions in actpool associated with an address
UnconfirmedActionsByAddress(address string, start uint64, count uint64) ([]*iotexapi.ActionInfo, error)
// EstimateMigrateStakeGasConsumption estimates gas for migrate stake
EstimateMigrateStakeGasConsumption(context.Context, *action.MigrateStake, address.Address) (uint64, error)
// EstimateGasForNonExecution estimates action gas except execution
EstimateGasForNonExecution(action.Action) (uint64, error)
// EstimateExecutionGasConsumption estimate gas consumption for execution action
EstimateExecutionGasConsumption(ctx context.Context, sc action.Envelope, callerAddr address.Address, opts ...protocol.SimulateOption) (uint64, error)
// LogsInBlockByHash filter logs in the block by hash
LogsInBlockByHash(filter *logfilter.LogFilter, blockHash hash.Hash256) ([]*action.Log, error)
// LogsInRange filter logs among [start, end] blocks
LogsInRange(filter *logfilter.LogFilter, start, end, paginationSize uint64) ([]*action.Log, []hash.Hash256, error)
// Genesis returns the genesis of the chain
Genesis() genesis.Genesis
// EVMNetworkID returns the network id of evm
EVMNetworkID() uint32
// ChainID returns the chain id of evm
ChainID() uint32
// ReadContractStorage reads contract's storage
ReadContractStorage(ctx context.Context, addr address.Address, key []byte) ([]byte, error)
// ChainListener returns the instance of Listener
ChainListener() apitypes.Listener
// SimulateExecution simulates execution
SimulateExecution(context.Context, address.Address, action.Envelope) ([]byte, *action.Receipt, error)
// SyncingProgress returns the syncing status of node
SyncingProgress() (uint64, uint64, uint64)
// TipHeight returns the tip of the chain
TipHeight() uint64
// PendingNonce returns the pending nonce of an account
PendingNonce(address.Address) (uint64, error)
// ReceiveBlock broadcasts the block to api subscribers
ReceiveBlock(blk *block.Block) error
// BlockHashByBlockHeight returns block hash by block height
BlockHashByBlockHeight(blkHeight uint64) (hash.Hash256, error)
// TraceTransaction returns the trace result of a transaction
TraceTransaction(ctx context.Context, actHash string, config *tracers.TraceConfig) ([]byte, *action.Receipt, any, error)
// TraceCall returns the trace result of a call
TraceCall(ctx context.Context,
callerAddr address.Address,
blkNumOrHash any,
contractAddress string,
nonce uint64,
amount *big.Int,
gasLimit uint64,
data []byte,
config *tracers.TraceConfig) ([]byte, *action.Receipt, any, error)
// Track tracks the api call
Track(ctx context.Context, start time.Time, method string, size int64, success bool)
// BlobSidecarsByHeight returns blob sidecars by height
BlobSidecarsByHeight(height uint64) ([]*apitypes.BlobSidecarResult, error)
}
// coreService implements the CoreService interface
coreService struct {
bc blockchain.Blockchain
bs blocksync.BlockSync
sf factory.Factory
dao blockdao.BlockDAO
indexer blockindex.Indexer
bfIndexer blockindex.BloomFilterIndexer
ap actpool.ActPool
gs *gasstation.GasStation
broadcastHandler BroadcastOutbound
cfg Config
registry *protocol.Registry
chainListener apitypes.Listener
electionCommittee committee.Committee
readCache *ReadCache
messageBatcher *batch.Manager
apiStats *nodestats.APILocalStats
getBlockTime evm.GetBlockTime
}
// jobDesc provides a struct to get and store logs in core.LogsInRange
jobDesc struct {
idx int
blkNum uint64
}
)
// Option is the option to override the api config
type Option func(cfg *coreService)
// BroadcastOutbound sends a broadcast message to the whole network
type BroadcastOutbound func(ctx context.Context, chainID uint32, msg proto.Message) error
// WithBroadcastOutbound is the option to broadcast msg outbound
func WithBroadcastOutbound(broadcastHandler BroadcastOutbound) Option {
return func(svr *coreService) {
svr.broadcastHandler = broadcastHandler
}
}
// WithNativeElection is the option to return native election data through API.
func WithNativeElection(committee committee.Committee) Option {
return func(svr *coreService) {
svr.electionCommittee = committee
}
}
// WithAPIStats is the option to return RPC stats through API.
func WithAPIStats(stats *nodestats.APILocalStats) Option {
return func(svr *coreService) {
svr.apiStats = stats
}
}
type intrinsicGasCalculator interface {
IntrinsicGas() (uint64, error)
}
var (
// ErrNotFound indicates the record isn't found
ErrNotFound = errors.New("not found")
)
// newcoreService creates a api server that contains major blockchain components
func newCoreService(
cfg Config,
chain blockchain.Blockchain,
bs blocksync.BlockSync,
sf factory.Factory,
dao blockdao.BlockDAO,
indexer blockindex.Indexer,
bfIndexer blockindex.BloomFilterIndexer,
actPool actpool.ActPool,
registry *protocol.Registry,
getBlockTime evm.GetBlockTime,
opts ...Option,
) (CoreService, error) {
if cfg == (Config{}) {
log.L().Warn("API server is not configured.")
cfg = DefaultConfig
}
if cfg.RangeQueryLimit < uint64(cfg.TpsWindow) {
return nil, errors.New("range query upper limit cannot be less than tps window")
}
core := coreService{
bc: chain,
bs: bs,
sf: sf,
dao: dao,
indexer: indexer,
bfIndexer: bfIndexer,
ap: actPool,
cfg: cfg,
registry: registry,
chainListener: NewChainListener(cfg.ListenerLimit),
gs: gasstation.NewGasStation(chain, dao, cfg.GasStation),
readCache: NewReadCache(),
getBlockTime: getBlockTime,
}
for _, opt := range opts {
opt(&core)
}
if core.broadcastHandler != nil {
core.messageBatcher = batch.NewManager(func(msg *batch.Message) error {
return core.broadcastHandler(context.Background(), core.bc.ChainID(), msg.Data)
})
}
return &core, nil
}
// Account returns the metadata of an account
func (core *coreService) Account(addr address.Address) (*iotextypes.AccountMeta, *iotextypes.BlockIdentifier, error) {
ctx, span := tracer.NewSpan(context.Background(), "coreService.Account")
defer span.End()
addrStr := addr.String()
if addrStr == address.RewardingPoolAddr || addrStr == address.StakingBucketPoolAddr {
return core.getProtocolAccount(ctx, addrStr)
}
span.AddEvent("accountutil.AccountStateWithHeight")
ctx = genesis.WithGenesisContext(ctx, core.bc.Genesis())
state, tipHeight, err := accountutil.AccountStateWithHeight(ctx, core.sf, addr)
if err != nil {
return nil, nil, status.Error(codes.NotFound, err.Error())
}
span.AddEvent("ap.GetPendingNonce")
pendingNonce, err := core.ap.GetPendingNonce(addrStr)
if err != nil {
return nil, nil, status.Error(codes.Internal, err.Error())
}
if core.indexer == nil {
return nil, nil, status.Error(codes.NotFound, blockindex.ErrActionIndexNA.Error())
}
span.AddEvent("indexer.GetActionCount")
numActions, err := core.indexer.GetActionCountByAddress(hash.BytesToHash160(addr.Bytes()))
if err != nil {
return nil, nil, status.Error(codes.NotFound, err.Error())
}
// TODO: deprecate nonce field in account meta
accountMeta := &iotextypes.AccountMeta{
Address: addrStr,
Balance: state.Balance.String(),
PendingNonce: pendingNonce,
NumActions: numActions,
IsContract: state.IsContract(),
}
if state.IsContract() {
var code protocol.SerializableBytes
_, err = core.sf.State(&code, protocol.NamespaceOption(evm.CodeKVNameSpace), protocol.KeyOption(state.CodeHash))
if err != nil {
return nil, nil, status.Error(codes.NotFound, err.Error())
}
accountMeta.ContractByteCode = code
}
span.AddEvent("bc.BlockHeaderByHeight")
header, err := core.bc.BlockHeaderByHeight(tipHeight)
if err != nil {
return nil, nil, status.Error(codes.NotFound, err.Error())
}
hash := header.HashBlock()
span.AddEvent("coreService.Account.End")
return accountMeta, &iotextypes.BlockIdentifier{
Hash: hex.EncodeToString(hash[:]),
Height: tipHeight,
}, nil
}
// ChainMeta returns blockchain metadata
func (core *coreService) ChainMeta() (*iotextypes.ChainMeta, string, error) {
tipHeight := core.bc.TipHeight()
if tipHeight == 0 {
return &iotextypes.ChainMeta{
Epoch: &iotextypes.EpochData{},
ChainID: core.bc.ChainID(),
}, "", nil
}
syncStatus := ""
if core.bs != nil {
_, _, _, syncStatus = core.bs.SyncStatus()
}
chainMeta := &iotextypes.ChainMeta{
Height: tipHeight,
ChainID: core.bc.ChainID(),
}
if core.indexer == nil {
return chainMeta, syncStatus, nil
}
totalActions, err := core.indexer.GetTotalActions()
if err != nil {
return nil, "", status.Error(codes.Internal, err.Error())
}
blockLimit := int64(core.cfg.TpsWindow)
if blockLimit <= 0 {
return nil, "", status.Errorf(codes.Internal, "block limit is %d", blockLimit)
}
// avoid genesis block
if int64(tipHeight) < blockLimit {
blockLimit = int64(tipHeight)
}
blkStores, err := core.BlockByHeightRange(tipHeight-uint64(blockLimit)+1, uint64(blockLimit))
if err != nil {
return nil, "", status.Error(codes.NotFound, err.Error())
}
if len(blkStores) == 0 {
return nil, "", status.Error(codes.NotFound, "get 0 blocks! not able to calculate aps")
}
var numActions uint64
for _, blkStore := range blkStores {
numActions += uint64(len(blkStore.Block.Actions))
}
t1 := blkStores[0].Block.Timestamp()
t2 := blkStores[len(blkStores)-1].Block.Timestamp()
// duration of time difference in milli-seconds
// TODO: use config.Genesis.BlockInterval after PR1289 merges
timeDiff := (t2.Sub(t1) + 10*time.Second) / time.Millisecond
tps := float32(numActions*1000) / float32(timeDiff)
chainMeta.NumActions = int64(totalActions)
chainMeta.Tps = int64(math.Ceil(float64(tps)))
chainMeta.TpsFloat = tps
rp := rolldpos.FindProtocol(core.registry)
if rp != nil {
epochNum := rp.GetEpochNum(tipHeight)
epochHeight := rp.GetEpochHeight(epochNum)
gravityChainStartHeight, err := core.getGravityChainStartHeight(epochHeight)
if err != nil {
return nil, "", status.Error(codes.NotFound, err.Error())
}
chainMeta.Epoch = &iotextypes.EpochData{
Num: epochNum,
Height: epochHeight,
GravityChainStartHeight: gravityChainStartHeight,
}
}
return chainMeta, syncStatus, nil
}
// ServerMeta gets the server metadata
func (core *coreService) ServerMeta() (packageVersion string, packageCommitID string, gitStatus string, goVersion string, buildTime string) {
packageVersion = version.PackageVersion
packageCommitID = version.PackageCommitID
gitStatus = version.GitStatus
goVersion = version.GoVersion
buildTime = version.BuildTime
return
}
// SendAction is the API to send an action to blockchain.
func (core *coreService) SendAction(ctx context.Context, in *iotextypes.Action) (string, error) {
log.Logger("api").Debug("receive send action request")
selp, err := (&action.Deserializer{}).SetEvmNetworkID(core.EVMNetworkID()).ActionToSealedEnvelope(in)
if err != nil {
return "", status.Error(codes.InvalidArgument, err.Error())
}
// reject action if chainID is not matched at KamchatkaHeight
if err := core.validateChainID(in.GetCore().GetChainID()); err != nil {
return "", err
}
// reject action if a replay tx is not whitelisted
var (
g = core.Genesis()
deployer = selp.SenderAddress()
)
if selp.Encoding() == uint32(iotextypes.Encoding_ETHEREUM_UNPROTECTED) && !g.IsDeployerWhitelisted(deployer) {
return "", status.Errorf(codes.InvalidArgument, "replay deployer %v not whitelisted", deployer.Hex())
}
// Add to local actpool
ctx = protocol.WithRegistry(ctx, core.registry)
hash, err := selp.Hash()
if err != nil {
return "", err
}
l := log.Logger("api").With(zap.String("actionHash", hex.EncodeToString(hash[:])))
if err = core.ap.Add(ctx, selp); err != nil {
txBytes, serErr := proto.Marshal(in)
if serErr != nil {
l.Error("Data corruption", zap.Error(serErr))
} else {
l.With(zap.String("txBytes", hex.EncodeToString(txBytes))).Debug("Failed to accept action", zap.Error(err))
}
st := status.New(codes.Internal, err.Error())
br := &errdetails.BadRequest{
FieldViolations: []*errdetails.BadRequest_FieldViolation{
{
Field: "Action rejected",
Description: action.LoadErrorDescription(err),
},
},
}
st, err := st.WithDetails(br)
if err != nil {
log.Logger("api").Panic("Unexpected error attaching metadata", zap.Error(err))
}
return "", st.Err()
}
// If there is no error putting into local actpool, broadcast it to the network
// broadcast action hash if it's blobTx
hasSidecar := selp.BlobTxSidecar() != nil
out := proto.Message(in)
if hasSidecar {
out = &iotextypes.ActionHash{
Hash: hash[:],
}
}
if core.messageBatcher != nil && !hasSidecar {
// TODO: batch blobTx
err = core.messageBatcher.Put(&batch.Message{
ChainID: core.bc.ChainID(),
Target: nil,
Data: out,
})
} else {
err = core.broadcastHandler(ctx, core.bc.ChainID(), out)
}
if err != nil {
l.Warn("Failed to broadcast SendAction request.", zap.Error(err))
}
return hex.EncodeToString(hash[:]), nil
}
func (core *coreService) PendingNonce(addr address.Address) (uint64, error) {
return core.ap.GetPendingNonce(addr.String())
}
func (core *coreService) validateChainID(chainID uint32) error {
ge := core.bc.Genesis()
if ge.IsQuebec(core.bc.TipHeight()) && chainID != core.bc.ChainID() {
return status.Errorf(codes.InvalidArgument, "ChainID does not match, expecting %d, got %d", core.bc.ChainID(), chainID)
}
if ge.IsMidway(core.bc.TipHeight()) && chainID != core.bc.ChainID() && chainID != 0 {
return status.Errorf(codes.InvalidArgument, "ChainID does not match, expecting %d, got %d", core.bc.ChainID(), chainID)
}
return nil
}
// ReadContract reads the state in a contract address specified by the slot
func (core *coreService) ReadContract(ctx context.Context, callerAddr address.Address, elp action.Envelope) (string, *iotextypes.Receipt, error) {
log.Logger("api").Debug("receive read smart contract request")
exec, ok := elp.Action().(*action.Execution)
if !ok {
return "", nil, status.Error(codes.InvalidArgument, "expecting action.Execution")
}
key := hash.Hash160b(append([]byte(exec.Contract()), exec.Data()...))
// TODO: either moving readcache into the upper layer or change the storage format
if d, ok := core.readCache.Get(key); ok {
res := iotexapi.ReadContractResponse{}
if err := proto.Unmarshal(d, &res); err == nil {
return res.Data, res.Receipt, nil
}
}
var (
g = core.bc.Genesis()
blockGasLimit = g.BlockGasLimitByHeight(core.bc.TipHeight())
)
if elp.Gas() == 0 || blockGasLimit < elp.Gas() {
elp.SetGas(blockGasLimit)
}
retval, receipt, err := core.simulateExecution(ctx, callerAddr, elp)
if err != nil {
return "", nil, status.Error(codes.Internal, err.Error())
}
res := iotexapi.ReadContractResponse{
Data: hex.EncodeToString(retval),
Receipt: receipt.ConvertToReceiptPb(),
}
if d, err := proto.Marshal(&res); err == nil {
core.readCache.Put(key, d)
}
return res.Data, res.Receipt, nil
}
// ReadState reads state on blockchain
func (core *coreService) ReadState(protocolID string, height string, methodName []byte, arguments [][]byte) (*iotexapi.ReadStateResponse, error) {
p, ok := core.registry.Find(protocolID)
if !ok {
return nil, status.Errorf(codes.Internal, "protocol %s isn't registered", protocolID)
}
data, readStateHeight, err := core.readState(context.Background(), p, height, methodName, arguments...)
if err != nil {
return nil, status.Error(codes.NotFound, err.Error())
}
blkHash, err := core.dao.GetBlockHash(readStateHeight)
if err != nil {
if errors.Cause(err) == db.ErrNotExist {
return nil, status.Error(codes.NotFound, err.Error())
}
return nil, status.Error(codes.Internal, err.Error())
}
return &iotexapi.ReadStateResponse{
Data: data,
BlockIdentifier: &iotextypes.BlockIdentifier{
Height: readStateHeight,
Hash: hex.EncodeToString(blkHash[:]),
},
}, nil
}
// SuggestGasPrice suggests gas price
func (core *coreService) SuggestGasPrice() (uint64, error) {
return core.gs.SuggestGasPrice()
}
func (core *coreService) SuggestGasTipCap() (*big.Int, error) {
sp, err := core.SuggestGasPrice()
if err != nil {
return nil, err
}
price := big.NewInt(0).SetUint64(sp)
header, err := core.bc.BlockHeaderByHeight(core.bc.TipHeight())
if err != nil {
return nil, err
}
if header.BaseFee() == nil {
// eip-1559 is not enabled yet
return price, nil
}
fee := big.NewInt(0).Sub(price, header.BaseFee())
minFee := big.NewInt(unit.Qev) // TODO: use a better value
if fee.Cmp(minFee) < 0 {
fee = minFee
}
return fee, nil
}
// EstimateGasForAction estimates gas for action
func (core *coreService) EstimateGasForAction(ctx context.Context, in *iotextypes.Action) (uint64, error) {
selp, err := (&action.Deserializer{}).SetEvmNetworkID(core.EVMNetworkID()).ActionToSealedEnvelope(in)
if err != nil {
return 0, status.Error(codes.Internal, err.Error())
}
if _, ok := selp.Action().(*action.Execution); !ok {
gas, err := selp.IntrinsicGas()
if err != nil {
return 0, status.Error(codes.Internal, err.Error())
}
return gas, nil
}
callerAddr := selp.SenderAddress()
if callerAddr == nil {
return 0, status.Error(codes.Internal, "failed to get address")
}
_, receipt, err := core.SimulateExecution(ctx, callerAddr, selp.Envelope)
if err != nil {
return 0, status.Error(codes.Internal, err.Error())
}
return receipt.GasConsumed, nil
}
// EpochMeta gets epoch metadata
func (core *coreService) EpochMeta(epochNum uint64) (*iotextypes.EpochData, uint64, []*iotexapi.BlockProducerInfo, error) {
rp := rolldpos.FindProtocol(core.registry)
if rp == nil {
return nil, 0, nil, nil
}
if epochNum < 1 {
return nil, 0, nil, status.Error(codes.InvalidArgument, "epoch number cannot be less than one")
}
epochHeight := rp.GetEpochHeight(epochNum)
gravityChainStartHeight, err := core.getGravityChainStartHeight(epochHeight)
if err != nil {
return nil, 0, nil, status.Error(codes.NotFound, err.Error())
}
epochData := &iotextypes.EpochData{
Num: epochNum,
Height: epochHeight,
GravityChainStartHeight: gravityChainStartHeight,
}
pp := poll.FindProtocol(core.registry)
if pp == nil {
return nil, 0, nil, status.Error(codes.Internal, "poll protocol is not registered")
}
methodName := []byte("ActiveBlockProducersByEpoch")
arguments := [][]byte{[]byte(strconv.FormatUint(epochNum, 10))}
height := strconv.FormatUint(epochHeight, 10)
data, _, err := core.readState(context.Background(), pp, height, methodName, arguments...)
if err != nil {
return nil, 0, nil, status.Error(codes.NotFound, err.Error())
}
var activeConsensusBlockProducers state.CandidateList
if err := activeConsensusBlockProducers.Deserialize(data); err != nil {
return nil, 0, nil, status.Error(codes.Internal, err.Error())
}
numBlks, produce, err := core.getProductivityByEpoch(rp, epochNum, core.bc.TipHeight(), activeConsensusBlockProducers)
if err != nil {
return nil, 0, nil, status.Error(codes.NotFound, err.Error())
}
methodName = []byte("BlockProducersByEpoch")
data, _, err = core.readState(context.Background(), pp, height, methodName, arguments...)
if err != nil {
return nil, 0, nil, status.Error(codes.NotFound, err.Error())
}
var BlockProducers state.CandidateList
if err := BlockProducers.Deserialize(data); err != nil {
return nil, 0, nil, status.Error(codes.Internal, err.Error())
}
var blockProducersInfo []*iotexapi.BlockProducerInfo
for _, bp := range BlockProducers {
var active bool
var blockProduction uint64
if production, ok := produce[bp.Address]; ok {
active = true
blockProduction = production
}
blockProducersInfo = append(blockProducersInfo, &iotexapi.BlockProducerInfo{
Address: bp.Address,
Votes: bp.Votes.String(),
Active: active,
Production: blockProduction,
})
}
return epochData, numBlks, blockProducersInfo, nil
}
// RawBlocks gets raw block data
func (core *coreService) RawBlocks(startHeight uint64, count uint64, withReceipts bool, withTransactionLogs bool) ([]*iotexapi.BlockInfo, error) {
if count == 0 || count > core.cfg.RangeQueryLimit {
return nil, status.Error(codes.InvalidArgument, "range exceeds the limit")
}
tipHeight := core.bc.TipHeight()
if startHeight > tipHeight {
return nil, status.Error(codes.InvalidArgument, "start height should not exceed tip height")
}
endHeight := startHeight + count - 1
if endHeight > tipHeight {
endHeight = tipHeight
}
var res []*iotexapi.BlockInfo
for height := startHeight; height <= endHeight; height++ {
blk, err := core.dao.GetBlockByHeight(height)
if err != nil {
return nil, status.Error(codes.NotFound, err.Error())
}
var receiptsPb []*iotextypes.Receipt
if withReceipts && height > 0 {
receipts, err := core.dao.GetReceipts(height)
if err != nil {
return nil, status.Error(codes.NotFound, err.Error())
}
for _, receipt := range receipts {
receiptsPb = append(receiptsPb, receipt.ConvertToReceiptPb())
}
}
var transactionLogs *iotextypes.TransactionLogs
if withTransactionLogs {
if transactionLogs, err = core.dao.TransactionLogs(height); err != nil {
return nil, status.Error(codes.NotFound, err.Error())
}
}
res = append(res, &iotexapi.BlockInfo{
Block: blk.ConvertToBlockPb(),
Receipts: receiptsPb,
TransactionLogs: transactionLogs,
})
}
return res, nil
}
// ChainListener returns the instance of Listener
func (core *coreService) ChainListener() apitypes.Listener {
return core.chainListener
}
// ElectionBuckets returns the native election buckets.
func (core *coreService) ElectionBuckets(epochNum uint64) ([]*iotextypes.ElectionBucket, error) {
if core.electionCommittee == nil {
return nil, status.Error(codes.Unavailable, "Native election no supported")
}
buckets, err := core.electionCommittee.NativeBucketsByEpoch(epochNum)
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
re := make([]*iotextypes.ElectionBucket, len(buckets))
for i, b := range buckets {
startTime := timestamppb.New(b.StartTime())
re[i] = &iotextypes.ElectionBucket{
Voter: b.Voter(),
Candidate: b.Candidate(),
Amount: b.Amount().Bytes(),
StartTime: startTime,
Duration: durationpb.New(b.Duration()),
Decay: b.Decay(),
}
}
return re, nil
}
// ReceiptByActionHash returns receipt by action hash
func (core *coreService) ReceiptByActionHash(h hash.Hash256) (*action.Receipt, error) {
if core.indexer == nil {
return nil, status.Error(codes.NotFound, blockindex.ErrActionIndexNA.Error())
}
actIndex, err := core.indexer.GetActionIndex(h[:])
if err != nil {
return nil, errors.Wrap(ErrNotFound, err.Error())
}
receipts, err := core.dao.GetReceipts(actIndex.BlockHeight())
if err != nil {
return nil, err
}
if receipt := filterReceipts(receipts, h); receipt != nil {
return receipt, nil
}
return nil, errors.Wrapf(ErrNotFound, "failed to find receipt for action %x", h)
}
// TransactionLogByActionHash returns transaction log by action hash
func (core *coreService) TransactionLogByActionHash(actHash string) (*iotextypes.TransactionLog, error) {
if core.indexer == nil {
return nil, status.Error(codes.Unimplemented, blockindex.ErrActionIndexNA.Error())
}
if !core.dao.ContainsTransactionLog() {
return nil, status.Error(codes.Unimplemented, filedao.ErrNotSupported.Error())
}
h, err := hex.DecodeString(actHash)
if err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}
actIndex, err := core.indexer.GetActionIndex(h)
if err != nil {
if errors.Cause(err) == db.ErrNotExist {
return nil, status.Error(codes.NotFound, err.Error())
}
return nil, status.Error(codes.Internal, err.Error())
}
sysLog, err := core.dao.TransactionLogs(actIndex.BlockHeight())
if err != nil {
if errors.Cause(err) == db.ErrNotExist {
return nil, status.Error(codes.NotFound, err.Error())
}
return nil, status.Error(codes.Internal, err.Error())
}
for _, log := range sysLog.Logs {
if bytes.Equal(h, log.ActionHash) {
return log, nil
}
}
return nil, status.Errorf(codes.NotFound, "transaction log not found for action %s", actHash)
}
// TransactionLogByBlockHeight returns transaction log by block height
func (core *coreService) TransactionLogByBlockHeight(blockHeight uint64) (*iotextypes.BlockIdentifier, *iotextypes.TransactionLogs, error) {
if !core.dao.ContainsTransactionLog() {
return nil, nil, status.Error(codes.Unimplemented, filedao.ErrNotSupported.Error())
}
tip, err := core.dao.Height()
if err != nil {
return nil, nil, status.Error(codes.Internal, err.Error())
}
if blockHeight < 1 || blockHeight > tip {
return nil, nil, status.Errorf(codes.InvalidArgument, "invalid block height = %d", blockHeight)
}
h, err := core.dao.GetBlockHash(blockHeight)
if err != nil {
if errors.Cause(err) == db.ErrNotExist {
return nil, nil, status.Error(codes.NotFound, err.Error())
}
return nil, nil, status.Error(codes.Internal, err.Error())
}
blockIdentifier := &iotextypes.BlockIdentifier{
Hash: hex.EncodeToString(h[:]),
Height: blockHeight,
}
sysLog, err := core.dao.TransactionLogs(blockHeight)
if err != nil {
if errors.Cause(err) == db.ErrNotExist {
// should return empty, no transaction happened in block
return blockIdentifier, nil, nil
}
return nil, nil, status.Error(codes.Internal, err.Error())
}
return blockIdentifier, sysLog, nil
}
func (core *coreService) TipHeight() uint64 {
return core.bc.TipHeight()
}
// Start starts the API server
func (core *coreService) Start(_ context.Context) error {
if err := core.chainListener.Start(); err != nil {
return errors.Wrap(err, "failed to start blockchain listener")
}
if core.messageBatcher != nil {
if err := core.messageBatcher.Start(); err != nil {
return errors.Wrap(err, "failed to start message batcher")
}
}
return nil
}
// Stop stops the API server
func (core *coreService) Stop(_ context.Context) error {
if core.messageBatcher != nil {
if err := core.messageBatcher.Stop(); err != nil {
return errors.Wrap(err, "failed to stop message batcher")
}
}
return core.chainListener.Stop()
}
func (core *coreService) readState(ctx context.Context, p protocol.Protocol, height string, methodName []byte, arguments ...[]byte) ([]byte, uint64, error) {
key := ReadKey{
Name: p.Name(),
Height: height,
Method: methodName,
Args: arguments,
}
tipHeight := core.bc.TipHeight()
if height == "" {
key.Height = strconv.FormatUint(tipHeight, 10)
}
if d, ok := core.readCache.Get(key.Hash()); ok {
h := tipHeight
if height != "" {
h, _ = strconv.ParseUint(height, 0, 64)
}
return d, h, nil
}
// TODO: need to complete the context
ctx = protocol.WithBlockCtx(ctx, protocol.BlockCtx{
BlockHeight: tipHeight,
})
ctx = genesis.WithGenesisContext(
protocol.WithRegistry(ctx, core.registry),
core.bc.Genesis(),
)
ctx = protocol.WithFeatureCtx(protocol.WithFeatureWithHeightCtx(ctx))
if height != "" {
inputHeight, err := strconv.ParseUint(height, 0, 64)
if err != nil {
return nil, uint64(0), err
}
rp := rolldpos.FindProtocol(core.registry)
if rp != nil {
tipEpochNum := rp.GetEpochNum(tipHeight)
inputEpochNum := rp.GetEpochNum(inputHeight)
if inputEpochNum < tipEpochNum {
inputHeight = rp.GetEpochHeight(inputEpochNum)
}
}
if inputHeight < tipHeight {
// old data, wrap to history state reader
d, h, err := p.ReadState(ctx, factory.NewHistoryStateReader(core.sf, inputHeight), methodName, arguments...)
if err == nil {
key.Height = strconv.FormatUint(h, 10)
core.readCache.Put(key.Hash(), d)
}
return d, h, err
}
}
// TODO: need to distinguish user error and system error
d, h, err := p.ReadState(ctx, core.sf, methodName, arguments...)
if err == nil {
key.Height = strconv.FormatUint(h, 10)
core.readCache.Put(key.Hash(), d)
}
return d, h, err
}
func (core *coreService) getActionsFromIndex(start, count uint64) ([]*iotexapi.ActionInfo, error) {
hashes, err := core.indexer.GetActionHashFromIndex(start, count)
if err != nil {
return nil, status.Error(codes.Unavailable, err.Error())
}
var actionInfo []*iotexapi.ActionInfo
for i := range hashes {
act, err := core.getAction(hash.BytesToHash256(hashes[i]), false)
if err != nil {
return nil, status.Error(codes.Unavailable, err.Error())
}
actionInfo = append(actionInfo, act)
}
return actionInfo, nil
}
// Actions returns actions within the range
func (core *coreService) Actions(start uint64, count uint64) ([]*iotexapi.ActionInfo, error) {
if err := core.checkActionIndex(); err != nil {
return nil, err