nim-poseidon2/poseidon2.nim

54 lines
1.1 KiB
Nim
Raw Normal View History

import std/sequtils
2023-11-07 11:58:15 +01:00
import constantine/math/arithmetic
2023-10-24 13:57:47 +02:00
import poseidon2/types
2023-11-08 13:08:33 +01:00
import poseidon2/permutation
import poseidon2/io
2023-11-08 13:08:33 +01:00
import poseidon2/sponge
2023-11-08 13:08:33 +01:00
export sponge
export toBytes
export elements
export types
2023-11-07 11:58:15 +01:00
#-------------------------------------------------------------------------------
# 2-to-1 compression
func compress*(a, b : F) : F =
var x = a
var y = b
var z : F ; setZero(z)
2023-10-24 14:16:54 +02:00
permInplace(x, y, z)
return x
func merkleRoot*(xs: openArray[F]) : F =
let a = low(xs)
let b = high(xs)
let m = b-a+1
if m==1:
return xs[a]
else:
let halfn : int = m div 2
let n : int = 2*halfn
2023-10-24 14:16:54 +02:00
let isOdd : bool = (n != m)
2023-10-24 13:55:04 +02:00
var ys : seq[F]
2023-10-24 14:16:54 +02:00
if not isOdd:
ys = newSeq[F](halfn)
else:
ys = newSeq[F](halfn+1)
for i in 0..<halfn:
ys[i] = compress( xs[a+2*i], xs[a+2*i+1] )
if isOdd:
ys[halfn] = compress( xs[n], zero )
2023-10-24 14:16:54 +02:00
return merkleRoot(ys)
func merkleRoot*(bytes: openArray[byte]): F =
merkleRoot(toSeq bytes.elements(F))
2023-11-07 11:58:15 +01:00
#-------------------------------------------------------------------------------