Add usage example to Readme

- unit test that example code works
- fixes for said unit test
This commit is contained in:
Mark Spanbroek 2023-11-09 14:44:38 +01:00 committed by markspanbroek
parent 70c03b834f
commit 457b8623be
6 changed files with 44 additions and 2 deletions

View File

@ -16,6 +16,29 @@ project. Add the following to its .nimble file:
requires "poseidon2 >= 0.1.0 & < 0.2.0"
```
Usage
-----
Hashing bytes into a field element with the sponge construction:
```nim
import poseidon2
let input = [1'u8, 2'u8, 3'u8] # some bytes that you want to hash
let digest: F = Sponge.digest(input) # a field element
```
Converting a field element into bytes:
```nim
let output: array[32, byte] = digest.toBytes
```
Combining field elements, useful for constructing a binary Merkle tree:
```nim
let left = Sponge.digest([1'u8, 2'u8, 3'u8])
let right = Sponge.digest([4'u8, 5'u8, 6'u8])
let combination = compress(left, right)
```
[1]: https://eprint.iacr.org/2023/323.pdf
[2]: https://github.com/mratsim/constantine
[3]: https://github.com/nim-lang/nimble

View File

@ -9,6 +9,7 @@ import poseidon2/sponge
export sponge
export toBytes
export elements
export types
#-------------------------------------------------------------------------------

View File

@ -1,6 +1,9 @@
import ./types
import constantine/math/arithmetic
import constantine/math/io/io_bigints
import constantine/math/config/curves
export curves
func fromOpenArray(_: type F, bytes: openArray[byte]): F =
F.fromBig(B.unmarshal(bytes, littleEndian))

View File

@ -60,13 +60,13 @@ func init*(_: type Sponge, rate: static int = 2): Sponge[rate] =
{.error: "only rate 1 and 2 are supported".}
result.init
func digest*(_: type Sponge, elements: openArray[F], rate: static int): F =
func digest*(_: type Sponge, elements: openArray[F], rate: static int = 2): F =
var sponge = Sponge.init(rate)
for element in elements:
sponge.update(element)
return sponge.finish()
func digest*(_: type Sponge, bytes: openArray[byte], rate: static int): F =
func digest*(_: type Sponge, bytes: openArray[byte], rate: static int = 2): F =
var sponge = Sponge.init(rate)
for element in bytes.elements(F):
sponge.update(element)

View File

@ -0,0 +1,14 @@
# Test that the example code from the Readme.md compiles
{.hint[XDeclaredButNotUsed]: off.}
import poseidon2
let input = [1'u8, 2'u8, 3'u8] # some bytes that you want to hash
let digest: F = Sponge.digest(input) # a field element
let output: array[32, byte] = digest.toBytes
let left = Sponge.digest([1'u8, 2'u8, 3'u8])
let right = Sponge.digest([4'u8, 5'u8, 6'u8])
let combination = compress(left, right)

View File

@ -2,5 +2,6 @@ import ./poseidon2/testPermutation
import ./poseidon2/testSponge
import ./poseidon2/testPoseidon2
import ./poseidon2/testIo
import ./poseidon2/testReadme
{.warning[UnusedImport]: off.}