Skip to content

Commit

Permalink
add new standard library value for revertibleRandom
Browse files Browse the repository at this point in the history
  • Loading branch information
Tarak Ben Youssef authored and SupunS committed Oct 30, 2023
1 parent a886ea3 commit 6321b64
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
1 change: 1 addition & 0 deletions runtime/stdlib/builtin.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ func DefaultStandardLibraryValues(handler StandardLibraryHandler) []StandardLibr
SignatureAlgorithmConstructor,
RLPContract,
NewLogFunction(handler),
NewRevertibleRandomFunction(handler),
NewUnsafeRandomFunction(handler),
NewGetBlockFunction(handler),
NewGetCurrentBlockFunction(handler),
Expand Down
34 changes: 32 additions & 2 deletions runtime/stdlib/random.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,15 @@ import (
"github.com/onflow/cadence/runtime/sema"
)

const unsafeRandomFunctionDocString = `
const revertibleRandomFunctionDocString = `
Returns a pseudo-random number.
NOTE: The use of this function is unsafe if not used correctly.
Follow best practices to prevent security issues when using this function
`

var unsafeRandomFunctionType = &sema.FunctionType{
var revertibleRandomFunctionType = &sema.FunctionType{
ReturnTypeAnnotation: sema.NewTypeAnnotation(
sema.UInt64Type,
),
Expand All @@ -45,6 +45,36 @@ type RandomGenerator interface {
ReadRandom([]byte) error
}

func NewRevertibleRandomFunction(generator RandomGenerator) StandardLibraryValue {
return NewStandardLibraryFunction(
"revertibleRandom",
revertibleRandomFunctionType,
revertibleRandomFunctionDocString,
func(invocation interpreter.Invocation) interpreter.Value {
return interpreter.NewUInt64Value(
invocation.Interpreter,
func() uint64 {
var buffer [8]byte
var err error
errors.WrapPanic(func() {
err = generator.ReadRandom(buffer[:])
})
if err != nil {
panic(interpreter.WrappedExternalError(err))
}
return binary.LittleEndian.Uint64(buffer[:])
},
)
},
)
}

// `unsafeRandom` related constants and functions will be deleted
// when the function is deprecated
const unsafeRandomFunctionDocString = revertibleRandomFunctionDocString

var unsafeRandomFunctionType = revertibleRandomFunctionType

func NewUnsafeRandomFunction(generator RandomGenerator) StandardLibraryValue {
return NewStandardLibraryFunction(
"unsafeRandom",
Expand Down

0 comments on commit 6321b64

Please sign in to comment.