*: make use of min/max where appropriate

Signed-off-by: Roman Khimov <roman@nspcc.ru>
This commit is contained in:
Roman Khimov 2024-08-23 22:09:20 +03:00
parent f21edef43b
commit 1c1d77c9b8
12 changed files with 26 additions and 82 deletions

View file

@ -64,8 +64,8 @@ func cancelTx(ctx *cli.Context) error {
if err != nil { if err != nil {
return err return err
} }
if mainTx != nil && t.NetworkFee < mainTx.NetworkFee+1 { if mainTx != nil {
t.NetworkFee = mainTx.NetworkFee + 1 t.NetworkFee = max(t.NetworkFee, mainTx.NetworkFee+1)
} }
t.NetworkFee += int64(flags.Fixed8FromContext(ctx, "gas")) t.NetworkFee += int64(flags.Fixed8FromContext(ctx, "gas"))
if mainTx != nil { if mainTx != nil {

View file

@ -118,9 +118,7 @@ func (c *codegen) traverseGlobals() bool {
var currMax int var currMax int
lastCnt, currMax = c.convertInitFuncs(f, pkg.Types, lastCnt) lastCnt, currMax = c.convertInitFuncs(f, pkg.Types, lastCnt)
if currMax > maxCnt { maxCnt = max(currMax, maxCnt)
maxCnt = currMax
}
} }
// because we reuse `convertFuncDecl` for init funcs, // because we reuse `convertFuncDecl` for init funcs,
// we need to clear scope, so that global variables // we need to clear scope, so that global variables
@ -128,9 +126,7 @@ func (c *codegen) traverseGlobals() bool {
c.scope = nil c.scope = nil
}) })
if c.globalInlineCount > maxCnt { maxCnt = max(c.globalInlineCount, maxCnt)
maxCnt = c.globalInlineCount
}
// Here we remove `INITSLOT` if no code was emitted for `init` function. // Here we remove `INITSLOT` if no code was emitted for `init` function.
// Note that the `INITSSLOT` must stay in place. // Note that the `INITSSLOT` must stay in place.

View file

@ -402,9 +402,7 @@ func (c *codegen) convertInitFuncs(f *ast.File, pkg *types.Package, lastCount in
f := c.convertFuncDecl(f, n, pkg) f := c.convertFuncDecl(f, n, pkg)
lastCount = f.vars.localsCnt lastCount = f.vars.localsCnt
if lastCount > maxCount { maxCount = max(lastCount, maxCount)
maxCount = lastCount
}
} }
case *ast.GenDecl: case *ast.GenDecl:
return false return false
@ -437,9 +435,7 @@ func (c *codegen) convertDeployFuncs() int {
f := c.convertFuncDecl(f, n, pkg) f := c.convertFuncDecl(f, n, pkg)
lastCount = f.vars.localsCnt lastCount = f.vars.localsCnt
if lastCount > maxCount { maxCount = max(lastCount, maxCount)
maxCount = lastCount
}
} }
case *ast.GenDecl: case *ast.GenDecl:
return false return false

View file

@ -47,9 +47,7 @@ func (c *codegen) inlineCall(f *funcScope, n *ast.CallExpr) {
c.scope = &funcScope{} c.scope = &funcScope{}
c.scope.vars.newScope() c.scope.vars.newScope()
defer func() { defer func() {
if cnt := c.scope.vars.localsCnt; cnt > c.globalInlineCount { c.globalInlineCount = max(c.globalInlineCount, c.scope.vars.localsCnt)
c.globalInlineCount = cnt
}
c.scope = nil c.scope = nil
}() }()
} }

View file

@ -634,9 +634,7 @@ func (s *service) processBlock(b dbft.Block[util.Uint256]) {
} }
func (s *service) postBlock(b *coreb.Block) { func (s *service) postBlock(b *coreb.Block) {
if s.lastTimestamp < b.Timestamp { s.lastTimestamp = max(s.lastTimestamp, b.Timestamp)
s.lastTimestamp = b.Timestamp
}
s.lastProposal = nil s.lastProposal = nil
} }

View file

@ -1115,9 +1115,7 @@ func (bc *Blockchain) Run() {
} }
nextSync = dur > persistInterval*2 nextSync = dur > persistInterval*2
interval := persistInterval - dur - gcDur interval := persistInterval - dur - gcDur
if interval <= 0 { interval = max(interval, time.Microsecond) // Reset doesn't work with zero or negative value.
interval = time.Microsecond // Reset doesn't work with zero value
}
persistTimer.Reset(interval) persistTimer.Reset(interval)
} }
} }
@ -1134,9 +1132,7 @@ func (bc *Blockchain) tryRunGC(oldHeight uint32) time.Duration {
syncP := newHeight / uint32(bc.config.StateSyncInterval) syncP := newHeight / uint32(bc.config.StateSyncInterval)
syncP-- syncP--
syncP *= uint32(bc.config.StateSyncInterval) syncP *= uint32(bc.config.StateSyncInterval)
if tgtBlock > int64(syncP) { tgtBlock = min(tgtBlock, int64(syncP))
tgtBlock = int64(syncP)
}
} }
// Always round to the GCP. // Always round to the GCP.
tgtBlock /= int64(bc.config.Ledger.GarbageCollectionPeriod) tgtBlock /= int64(bc.config.Ledger.GarbageCollectionPeriod)
@ -1619,9 +1615,7 @@ func (bc *Blockchain) storeBlock(block *block.Block, txpool *mempool.Pool) error
block.Index >= uint32(bc.config.StateSyncInterval)+bc.config.MaxTraceableBlocks && // check this in case if MaxTraceableBlocks>StateSyncInterval block.Index >= uint32(bc.config.StateSyncInterval)+bc.config.MaxTraceableBlocks && // check this in case if MaxTraceableBlocks>StateSyncInterval
int(block.Index)%bc.config.StateSyncInterval == 0 { int(block.Index)%bc.config.StateSyncInterval == 0 {
stop = block.Index - uint32(bc.config.StateSyncInterval) - bc.config.MaxTraceableBlocks stop = block.Index - uint32(bc.config.StateSyncInterval) - bc.config.MaxTraceableBlocks
if stop > uint32(bc.config.StateSyncInterval) { start = stop - min(stop, uint32(bc.config.StateSyncInterval))
start = stop - uint32(bc.config.StateSyncInterval)
}
} }
} else if block.Index > bc.config.MaxTraceableBlocks { } else if block.Index > bc.config.MaxTraceableBlocks {
start = block.Index - bc.config.MaxTraceableBlocks // is at least 1 start = block.Index - bc.config.MaxTraceableBlocks // is at least 1
@ -2954,10 +2948,7 @@ func (bc *Blockchain) VerifyWitness(h util.Uint160, c hash.Hashable, w *transact
// verifyHashAgainstScript verifies given hash against the given witness and returns the amount of GAS consumed. // verifyHashAgainstScript verifies given hash against the given witness and returns the amount of GAS consumed.
func (bc *Blockchain) verifyHashAgainstScript(hash util.Uint160, witness *transaction.Witness, interopCtx *interop.Context, gas int64) (int64, error) { func (bc *Blockchain) verifyHashAgainstScript(hash util.Uint160, witness *transaction.Witness, interopCtx *interop.Context, gas int64) (int64, error) {
gasPolicy := bc.contracts.Policy.GetMaxVerificationGas(interopCtx.DAO) gas = min(gas, bc.contracts.Policy.GetMaxVerificationGas(interopCtx.DAO))
if gas > gasPolicy {
gas = gasPolicy
}
vm := interopCtx.SpawnVM() vm := interopCtx.SpawnVM()
vm.GasLimit = gas vm.GasLimit = gas

View file

@ -475,11 +475,7 @@ func (s *Server) run() {
} else if s.MinPeers > 0 && loopCnt%s.MinPeers == 0 && optimalN > peerN && optimalN < s.MaxPeers && optimalN < netSize { } else if s.MinPeers > 0 && loopCnt%s.MinPeers == 0 && optimalN > peerN && optimalN < s.MaxPeers && optimalN < netSize {
// Having some number of peers, but probably can get some more, the network is big. // Having some number of peers, but probably can get some more, the network is big.
// It also allows to start picking up new peers proactively, before we suddenly have <s.MinPeers of them. // It also allows to start picking up new peers proactively, before we suddenly have <s.MinPeers of them.
var connN = s.AttemptConnPeers s.discovery.RequestRemote(min(s.AttemptConnPeers, optimalN-peerN))
if connN > optimalN-peerN {
connN = optimalN - peerN
}
s.discovery.RequestRemote(connN)
} }
if addrCheckTimeout || s.discovery.PoolCount() < s.AttemptConnPeers { if addrCheckTimeout || s.discovery.PoolCount() < s.AttemptConnPeers {
@ -1509,9 +1505,7 @@ func (s *Server) RequestTx(hashes ...util.Uint256) {
for i := 0; i <= len(hashes)/payload.MaxHashesCount; i++ { for i := 0; i <= len(hashes)/payload.MaxHashesCount; i++ {
start := i * payload.MaxHashesCount start := i * payload.MaxHashesCount
stop := (i + 1) * payload.MaxHashesCount stop := (i + 1) * payload.MaxHashesCount
if stop > len(hashes) { stop = min(stop, len(hashes))
stop = len(hashes)
}
if start == stop { if start == stop {
break break
} }
@ -1660,9 +1654,7 @@ func (s *Server) initStaleMemPools() {
threshold := 5 threshold := 5
// Not perfect, can change over time, but should be sufficient. // Not perfect, can change over time, but should be sufficient.
numOfCNs := s.config.GetNumOfCNs(s.chain.BlockHeight()) numOfCNs := s.config.GetNumOfCNs(s.chain.BlockHeight())
if numOfCNs*2 > threshold { threshold = max(threshold, numOfCNs*2)
threshold = numOfCNs * 2
}
s.mempool.SetResendThreshold(uint32(threshold), s.broadcastTX) s.mempool.SetResendThreshold(uint32(threshold), s.broadcastTX)
if s.chain.P2PSigExtensionsEnabled() { if s.chain.P2PSigExtensionsEnabled() {
@ -1769,12 +1761,5 @@ func (s *Server) Port(localAddr net.Addr) (uint16, error) {
func optimalNumOfThreads() int { func optimalNumOfThreads() int {
// Doing more won't help, mempool is still a contention point. // Doing more won't help, mempool is still a contention point.
const maxThreads = 16 const maxThreads = 16
var threads = runtime.GOMAXPROCS(0) return min(runtime.GOMAXPROCS(0), runtime.NumCPU(), maxThreads)
if threads > runtime.NumCPU() {
threads = runtime.NumCPU()
}
if threads > maxThreads {
threads = maxThreads
}
return threads
} }

View file

@ -229,9 +229,7 @@ func iterateNext(rpc RPCSessions, sessionID uuid.UUID, iterator *result.Iterator
if iterator.ID != nil { if iterator.ID != nil {
return rpc.TraverseIterator(sessionID, *iterator.ID, num) return rpc.TraverseIterator(sessionID, *iterator.ID, num)
} }
if num > len(iterator.Values) { num = min(num, len(iterator.Values))
num = len(iterator.Values)
}
items := iterator.Values[:num] items := iterator.Values[:num]
iterator.Values = iterator.Values[num:] iterator.Values = iterator.Values[num:]

View file

@ -265,9 +265,7 @@ func (n *Notary) OnNewRequest(payload *payload.P2PNotaryRequest) {
return // then we already have processed this request return // then we already have processed this request
} }
} }
if nvbFallback < r.minNotValidBefore { r.minNotValidBefore = min(r.minNotValidBefore, nvbFallback)
r.minNotValidBefore = nvbFallback
}
} else { } else {
// Avoid changes in the main transaction witnesses got from the notary request pool to // Avoid changes in the main transaction witnesses got from the notary request pool to
// keep the pooled tx valid. We will update its copy => the copy's size will be changed. // keep the pooled tx valid. We will update its copy => the copy's size will be changed.

View file

@ -449,9 +449,7 @@ func (p *pathParser) descendByRange(objs []any, start, end int) ([]any, bool) {
subEnd += len(arr) subEnd += len(arr)
} }
if subEnd > len(arr) { subEnd = min(subEnd, len(arr))
subEnd = len(arr)
}
if subEnd <= subStart { if subEnd <= subStart {
continue continue

View file

@ -273,10 +273,7 @@ func New(chain Ledger, conf config.RPC, coreServer *network.Server,
protoCfg := chain.GetConfig().ProtocolConfiguration protoCfg := chain.GetConfig().ProtocolConfiguration
if conf.SessionEnabled { if conf.SessionEnabled {
if conf.SessionExpirationTime <= 0 { if conf.SessionExpirationTime <= 0 {
conf.SessionExpirationTime = int(protoCfg.TimePerBlock / time.Second) conf.SessionExpirationTime = max(int(protoCfg.TimePerBlock/time.Second), 5)
if conf.SessionExpirationTime < 5 {
conf.SessionExpirationTime = 5
}
log.Info("SessionExpirationTime is not set or wrong, setting default value", zap.Int("SessionExpirationTime", conf.SessionExpirationTime)) log.Info("SessionExpirationTime is not set or wrong, setting default value", zap.Int("SessionExpirationTime", conf.SessionExpirationTime))
} }
if conf.SessionPoolSize <= 0 { if conf.SessionPoolSize <= 0 {
@ -958,13 +955,9 @@ func (s *Server) calculateNetworkFee(reqParams params.Params) (any, *neorpc.Erro
size := len(hashablePart) + io.GetVarSize(len(tx.Signers)) size := len(hashablePart) + io.GetVarSize(len(tx.Signers))
var ( var (
netFee int64 netFee int64
// Verification GAS cost can't exceed this policy. // Verification GAS cost can't exceed chin policy, but RPC config can limit it further.
gasLimit = s.chain.GetMaxVerificationGAS() gasLimit = min(s.chain.GetMaxVerificationGAS(), int64(s.config.MaxGasInvoke))
) )
if gasLimit > int64(s.config.MaxGasInvoke) {
// But we honor instance configuration as well.
gasLimit = int64(s.config.MaxGasInvoke)
}
for i, signer := range tx.Signers { for i, signer := range tx.Signers {
w := tx.Scripts[i] w := tx.Scripts[i]
if len(w.InvocationScript) == 0 { // No invocation provided, try to infer one. if len(w.InvocationScript) == 0 { // No invocation provided, try to infer one.
@ -1683,9 +1676,7 @@ func (s *Server) findStates(ps params.Params) (any, *neorpc.Error) {
if err != nil { if err != nil {
return nil, neorpc.WrapErrorWithData(neorpc.ErrInvalidParams, fmt.Sprintf("invalid count: %s", err)) return nil, neorpc.WrapErrorWithData(neorpc.ErrInvalidParams, fmt.Sprintf("invalid count: %s", err))
} }
if count > s.config.MaxFindResultItems { count = min(count, s.config.MaxFindResultItems)
count = s.config.MaxFindResultItems
}
} }
cs, respErr := s.getHistoricalContractState(root, csHash) cs, respErr := s.getHistoricalContractState(root, csHash)
if respErr != nil { if respErr != nil {
@ -2379,10 +2370,7 @@ func (s *Server) prepareInvocationContext(t trigger.Type, script []byte, contrac
if t == trigger.Verification { if t == trigger.Verification {
// We need this special case because witnesses verification is not the simple System.Contract.Call, // We need this special case because witnesses verification is not the simple System.Contract.Call,
// and we need to define exactly the amount of gas consumed for a contract witness verification. // and we need to define exactly the amount of gas consumed for a contract witness verification.
gasPolicy := s.chain.GetMaxVerificationGAS() ic.VM.GasLimit = min(ic.VM.GasLimit, s.chain.GetMaxVerificationGAS())
if ic.VM.GasLimit > gasPolicy {
ic.VM.GasLimit = gasPolicy
}
err = s.chain.InitVerificationContext(ic, contractScriptHash, &transaction.Witness{InvocationScript: script, VerificationScript: []byte{}}) err = s.chain.InitVerificationContext(ic, contractScriptHash, &transaction.Witness{InvocationScript: script, VerificationScript: []byte{}})
if err != nil { if err != nil {

View file

@ -676,11 +676,9 @@ func (i *ByteArray) equalsLimited(s Item, limit *int) bool {
if !ok { if !ok {
return false return false
} }
comparedSize = lCurr
lOther := len(*val) lOther := len(*val)
if lOther > comparedSize { comparedSize = max(lCurr, lOther)
comparedSize = lOther
}
if i == val { if i == val {
return true return true
} }