Compare commits

..

1 Commits

Author SHA1 Message Date
5560c59614
Prevent dice overflow
rand.Int() would panic when the max value is <= 0, which happens when
big.NewInt() was fed with a too large number. Avoid this by validating
the big.NewInt() return beforehand. Add error handling to all callers to
both gracefully return to IRC and to log an error message.
Rename the shadowed "max" variable whilst at it to avoid confusion.

Signed-off-by: Georg Pfuetzenreuter <mail@georg-pfuetzenreuter.net>
2024-10-10 02:41:46 +02:00

View File

@ -2,7 +2,6 @@ package wat
import (
"crypto/rand"
"errors"
"fmt"
"math/big"
"strconv"
@ -122,11 +121,11 @@ func (g *WatGame) help() string {
return ret
}
func (g *WatGame) RandInt(max int64) (uint64, error) {
bi := big.NewInt(max)
func (g *WatGame) RandInt(maxx int64) (uint64, error) {
bi := big.NewInt(maxx)
// prevent panic of rand.Int on big numbers
if bi.BitLen() < 2 {
return 0, errors.New("overflow")
return 0, fmt.Errorf("overflow, got %d", bi)
}
i, err := rand.Int(rand.Reader, bi)
if err != nil {