From 1ccba817b5853a368c6edbfdf8f744281f813e5b Mon Sep 17 00:00:00 2001 From: Richard Ramos Date: Thu, 17 Aug 2023 18:19:53 -0400 Subject: [PATCH] chore: add Bytes32ToBigInt --- rln/utils.go | 25 ++++++++++++++++++++++--- rln/utils_test.go | 21 +++++++++++++++++++++ 2 files changed, 43 insertions(+), 3 deletions(-) create mode 100644 rln/utils_test.go diff --git a/rln/utils.go b/rln/utils.go index d4a12ea..42e767d 100644 --- a/rln/utils.go +++ b/rln/utils.go @@ -71,11 +71,30 @@ func ToBytes32LE(hexStr string) ([32]byte, error) { return Bytes32(b), nil } -func BigIntToBytes32(value *big.Int) [32]byte { - b := value.Bytes() +func revert(b []byte) []byte { bLen := len(b) for i := 0; i < bLen/2; i++ { b[i], b[bLen-i-1] = b[bLen-i-1], b[i] } - return Bytes32(b) + return b +} + +// BigIntToBytes32 takes a *big.Int (which uses big endian) and converts it into a little endian 32 byte array +// Notice that is the *big.Int value contains an integer <= 2^248 - 1 (a 7 bytes value with all bits on), it will right-pad the result with 0s until +// the result has 32 bytes, i.e.: +// for a some bigInt whose `Bytes()` are {0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF}, using this function will return +// {0xEF, 0xCD, 0xAB, 0x90, 0x78, 0x56, 0x34, 0x12, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0} +func BigIntToBytes32(value *big.Int) [32]byte { + b := revert(value.Bytes()) + tmp := make([]byte, 32) + copy(tmp[0:len(b)], b) + return Bytes32(tmp) +} + +// Bytes32ToBigInt takes a little endian 32 byte array and returns a *big.Int (which uses big endian) +func Bytes32ToBigInt(value [32]byte) *big.Int { + b := revert(value[:]) + result := new(big.Int) + result.SetBytes(b) + return result } diff --git a/rln/utils_test.go b/rln/utils_test.go new file mode 100644 index 0000000..f44440e --- /dev/null +++ b/rln/utils_test.go @@ -0,0 +1,21 @@ +package rln + +import ( + "bytes" + "math/big" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestBigInt(t *testing.T) { + base := big.NewInt(2) + value := base.Exp(base, big.NewInt(248), nil) + value = value.Sub(value, big.NewInt(1)) // 2^248 - 1 + + b32Value := BigIntToBytes32(value) + require.True(t, bytes.Equal(b32Value[:], []byte{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0})) + + newValue := Bytes32ToBigInt(b32Value) + require.True(t, bytes.Equal(newValue.Bytes(), value.Bytes())) +}