From 46ab97a79919ea0117ce39edc57a545e1b4093a7 Mon Sep 17 00:00:00 2001 From: aofengli <996177263@qq.com> Date: Tue, 14 Mar 2023 15:24:10 +0800 Subject: [PATCH] fix random bug --- modules/random/keeper/service.go | 13 +++++++++---- modules/random/types/rng.go | 6 ++++++ 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/modules/random/keeper/service.go b/modules/random/keeper/service.go index 4ec087f4..17e5bcf7 100644 --- a/modules/random/keeper/service.go +++ b/modules/random/keeper/service.go @@ -2,8 +2,6 @@ package keeper import ( "encoding/hex" - "math/rand" - "time" "github.com/tidwall/gjson" @@ -38,8 +36,15 @@ func (k Keeper) RequestService(ctx sdk.Context, consumer sdk.AccAddress, service return nil, sdkerrors.ErrInsufficientFee } - rand.Seed(time.Now().UnixNano()) - provider, _ := sdk.AccAddressFromBech32(bindings[rand.Intn(len(bindings))].Provider) + prng := types.MakePRNG( + ctx.BlockHeader().LastBlockId.Hash, + ctx.BlockHeader().Time.UnixNano(), + consumer, nil, true) + provider, err := sdk.AccAddressFromBech32(bindings[prng.Intn(len(bindings))].Provider) + if err != nil { + return nil, err + } + timeout := k.serviceKeeper.GetParams(ctx).MaxRequestTimeout return k.serviceKeeper.CreateRequestContext( diff --git a/modules/random/types/rng.go b/modules/random/types/rng.go index 82fdae22..9e73ba6a 100644 --- a/modules/random/types/rng.go +++ b/modules/random/types/rng.go @@ -3,6 +3,7 @@ package types import ( "crypto/sha256" "math/big" + "math/rand" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -59,6 +60,11 @@ func (p PRNG) GetRand() *big.Rat { return random } +func (p PRNG) Intn(n int) int { + rnd := rand.New(rand.NewSource(p.GetRand().Denom().Int64())) + return rnd.Intn(n) +} + // SHA256 wraps sha256.Sum256 with result converted to slice func SHA256(data []byte) []byte { sum := sha256.Sum256(data)