2023-11-08 13:25:23 +01:00
|
|
|
import std/sequtils
|
2023-11-07 11:58:15 +01:00
|
|
|
import constantine/math/arithmetic
|
2023-07-28 22:10:14 +02:00
|
|
|
|
2023-10-24 13:57:47 +02:00
|
|
|
import poseidon2/types
|
2023-11-08 13:08:33 +01:00
|
|
|
import poseidon2/permutation
|
2023-10-31 13:40:07 +01:00
|
|
|
import poseidon2/io
|
2023-11-08 13:08:33 +01:00
|
|
|
import poseidon2/sponge
|
2023-11-13 11:57:55 +01:00
|
|
|
import poseidon2/compress
|
2023-07-28 22:10:14 +02:00
|
|
|
|
2023-11-08 13:08:33 +01:00
|
|
|
export sponge
|
2023-11-13 11:57:55 +01:00
|
|
|
export compress
|
2023-11-02 10:31:26 +01:00
|
|
|
export toBytes
|
2023-11-08 13:25:23 +01:00
|
|
|
export elements
|
2023-11-09 14:44:38 +01:00
|
|
|
export types
|
2023-11-07 11:58:15 +01:00
|
|
|
|
|
|
|
#-------------------------------------------------------------------------------
|
|
|
|
|
2023-11-01 10:34:55 +01:00
|
|
|
func merkleRoot*(xs: openArray[F]) : F =
|
2023-07-28 22:10:14 +02:00
|
|
|
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
|
|
|
|
2023-11-09 10:20:10 +01:00
|
|
|
var ys : seq[F]
|
2023-10-24 14:16:54 +02:00
|
|
|
if not isOdd:
|
2023-11-09 10:20:10 +01:00
|
|
|
ys = newSeq[F](halfn)
|
2023-07-28 22:10:14 +02:00
|
|
|
else:
|
2023-11-09 10:20:10 +01:00
|
|
|
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-07-28 22:10:14 +02:00
|
|
|
|
2023-10-24 14:16:54 +02:00
|
|
|
return merkleRoot(ys)
|
2023-07-28 22:10:14 +02:00
|
|
|
|
2023-11-01 10:34:55 +01:00
|
|
|
func merkleRoot*(bytes: openArray[byte]): F =
|
2023-11-08 13:25:23 +01:00
|
|
|
merkleRoot(toSeq bytes.elements(F))
|
2023-11-07 11:58:15 +01:00
|
|
|
|
|
|
|
#-------------------------------------------------------------------------------
|