Skip to content

Commit

Permalink
overflow check
Browse files Browse the repository at this point in the history
  • Loading branch information
envestcc committed Nov 3, 2023
1 parent ef356cc commit b547d27
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 5 deletions.
8 changes: 7 additions & 1 deletion pkg/util/blockutil/block_time_calculator.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package blockutil

import (
"errors"
"math"
"time"
)

Expand Down Expand Up @@ -47,9 +48,14 @@ func (btc *BlockTimeCalculator) CalculateBlockTime(height uint64) (time.Time, er
}

// predict block time according to tip block time and interval
blockInterval := btc.getBlockInterval(tipHeight)
blockNumer := time.Duration(height - tipHeight)
if blockNumer > math.MaxInt64/blockInterval {
return time.Time{}, errors.New("height overflow")
}
tipBlockTime, err := btc.getHistoryBlockTime(tipHeight)
if err != nil {
return time.Time{}, err
}
return tipBlockTime.Add(time.Duration(height-tipHeight) * btc.getBlockInterval(tipHeight)), nil
return tipBlockTime.Add(blockNumer * blockInterval), nil
}
15 changes: 11 additions & 4 deletions pkg/util/blockutil/block_time_calculator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,16 +30,23 @@ func TestBlockTimeCalculator_CalculateBlockTime(t *testing.T) {
name string
height uint64
want time.Time
errMsg string
}{
{"height is in the past", tipHeight - 1, historyWrapper(tipHeight - 1)},
{"height is in the past I", tipHeight, historyWrapper(tipHeight)},
{"height is in the future", tipHeight + 1, historyWrapper(tipHeight).Add(interval)},
{"height is in the future I", tipHeight + 2, historyWrapper(tipHeight).Add(2 * interval)},
{"height is in the past", tipHeight - 1, historyWrapper(tipHeight - 1), ""},
{"height is in the past I", tipHeight, historyWrapper(tipHeight), ""},
{"height is in the future", tipHeight + 1, historyWrapper(tipHeight).Add(interval), ""},
{"height is in the future I", tipHeight + 2, historyWrapper(tipHeight).Add(2 * interval), ""},
{"height is not overflow", tipHeight + (1<<63-1)/uint64(interval), historyWrapper(tipHeight).Add((1<<63 - 1) / interval * interval), ""},
{"height is overflow", tipHeight + (1<<63-1)/uint64(interval) + 1, time.Time{}, "height overflow"},
}

for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
got, err := btc.CalculateBlockTime(c.height)
if c.errMsg != "" {
r.ErrorContains(err, c.errMsg)
return
}
r.NoError(err)
r.Equal(c.want, got)
})
Expand Down

0 comments on commit b547d27

Please sign in to comment.