mirror of
https://github.com/logos-messaging/go-zerokit-rln.git
synced 2026-01-02 13:13:11 +00:00
chore: add Bytes32ToBigInt
This commit is contained in:
parent
3b5c0bbefb
commit
1ccba817b5
25
rln/utils.go
25
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
|
||||
}
|
||||
|
||||
21
rln/utils_test.go
Normal file
21
rln/utils_test.go
Normal file
@ -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()))
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user