mirror of
https://github.com/codex-storage/nim-poseidon2.git
synced 2025-02-23 00:08:05 +00:00
Adds method for converting 32 bytes to field element
This commit is contained in:
parent
aceccb2367
commit
fbf95e21b8
@ -1,8 +1,9 @@
|
||||
import ./types
|
||||
import std/options
|
||||
import constantine/math/arithmetic
|
||||
import constantine/math/io/io_bigints
|
||||
import constantine/math/io/io_fields
|
||||
import constantine/math/config/curves
|
||||
import ./types
|
||||
|
||||
export curves
|
||||
|
||||
@ -14,6 +15,13 @@ func fromBytes*(_: type F, bytes: array[31, byte]): F =
|
||||
## canonical little-endian big integer.
|
||||
F.fromOpenArray(bytes)
|
||||
|
||||
func fromBytes*(_: type F, bytes: array[32, byte]): Option[F] =
|
||||
## Converts bytes into a field element. The byte array is interpreted as a
|
||||
## canonical little-endian big integer.
|
||||
let big = B.unmarshal(bytes, littleEndian)
|
||||
if big < F.fieldMod():
|
||||
return some(F.fromBig(big))
|
||||
|
||||
func toBytes*(element: F): array[32, byte] =
|
||||
## Converts a field element into its canonical representation in little-endian
|
||||
## byte order. Uses at most 254 bits, the remaining most-significant bits are
|
||||
|
@ -18,6 +18,18 @@ suite "conversion to/from bytes":
|
||||
let unmarshalled = F.fromBytes(bytes)
|
||||
check bool(unmarshalled == expected)
|
||||
|
||||
test "converts 32 little endian bytes into a field elements":
|
||||
let bytes = toArray toSeq 1'u8..32'u8
|
||||
let expected = F.fromBig(B.unmarshal(bytes, littleEndian))
|
||||
let unmarshalled = F.fromBytes(bytes).get()
|
||||
check bool(unmarshalled == expected)
|
||||
|
||||
test "convert fails for 32 little endian bytes larger than the prime field":
|
||||
let bytes = toArray toSeq(255'u8).repeat(32)
|
||||
let expected = F.fromBig(B.unmarshal(bytes, littleEndian))
|
||||
let unmarshalled = F.fromBytes(bytes)
|
||||
check not unmarshalled.isSome()
|
||||
|
||||
test "converts every 31 bytes into a field element":
|
||||
let bytes = toSeq 1'u8..62'u8
|
||||
let expected1 = F.fromBytes(bytes[0..<31].toArray)
|
||||
|
Loading…
x
Reference in New Issue
Block a user