From 63575c2cd2a0203130b93884093d9d304db95db2 Mon Sep 17 00:00:00 2001 From: fudongbai <296179868@qq.com> Date: Wed, 15 Sep 2021 17:35:09 +0800 Subject: [PATCH] disable service when network is congest --- internal/ethapi/api.go | 32 +++++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/internal/ethapi/api.go b/internal/ethapi/api.go index b793537832..709db055fe 100644 --- a/internal/ethapi/api.go +++ b/internal/ethapi/api.go @@ -22,6 +22,7 @@ import ( "errors" "fmt" "math/big" + "sort" "strings" "time" @@ -55,6 +56,9 @@ const ( UnHealthyTimeout = 5 * time.Second MaxBundleBlockDelay = 1200 MaxBundleTimeDelay = 60 * 60 // second + MaxOracleBlocks = 21 + DropBlocks = 3 + MaxGasUsedRatio = 90 ) // PublicEthereumAPI provides an API to access Ethereum related information. @@ -2317,6 +2321,33 @@ func (s *PrivateTxBundleAPI) BundlePrice(ctx context.Context) (*big.Int, error) // SendBundle will add the signed transaction to the transaction pool. // The sender is responsible for signing the transaction and using the correct nonce and ensuring validity func (s *PrivateTxBundleAPI) SendBundle(ctx context.Context, args SendBundleArgs) (common.Hash, error) { + gasUsedRatio := make([]int, 0, MaxOracleBlocks) + block := s.b.CurrentBlock() + var err error + for i := 0; i < MaxOracleBlocks && block.NumberU64() > 1; i++ { + gasUsedRatio = append(gasUsedRatio, int(block.GasUsed()*100/block.GasLimit())) + block, err = s.b.BlockByHash(context.Background(), block.ParentHash()) + if err != nil { + break + } + } + sort.Ints(gasUsedRatio) + validGasUsedRatio := gasUsedRatio + if len(gasUsedRatio) > DropBlocks { + validGasUsedRatio = gasUsedRatio[DropBlocks:] + } + if len(validGasUsedRatio) == 0 { + return common.Hash{}, errors.New("no enough example ratio") + } + var totalRatio int + for _, ratio := range validGasUsedRatio { + totalRatio += ratio + } + averageRatio := totalRatio / len(validGasUsedRatio) + if averageRatio >= MaxGasUsedRatio { + return common.Hash{}, errors.New("the network is congested, please try later") + } + var txs types.Transactions if len(args.Txs) == 0 { return common.Hash{}, errors.New("bundle missing txs") @@ -2347,7 +2378,6 @@ func (s *PrivateTxBundleAPI) SendBundle(ctx context.Context, args SendBundleArgs } txs = append(txs, tx) } - var minTimestamp, maxTimestamp uint64 if args.MinTimestamp != nil { minTimestamp = *args.MinTimestamp