Skip to content

Commit

Permalink
Merge pull request #3 from bianjieai/shedlon/fix-random
Browse files Browse the repository at this point in the history
fix random bug
  • Loading branch information
taramakage authored Mar 15, 2023
2 parents c835543 + 46ab97a commit 651b50b
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 4 deletions.
13 changes: 9 additions & 4 deletions modules/random/keeper/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@ package keeper

import (
"encoding/hex"
"math/rand"
"time"

"github.com/tidwall/gjson"

Expand Down Expand Up @@ -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(
Expand Down
6 changes: 6 additions & 0 deletions modules/random/types/rng.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package types
import (
"crypto/sha256"
"math/big"
"math/rand"

sdk "github.com/cosmos/cosmos-sdk/types"
)
Expand Down Expand Up @@ -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)
Expand Down

0 comments on commit 651b50b

Please sign in to comment.