90 lines
2.2 KiB
Nim
Raw Normal View History

2024-01-15 21:47:06 -06:00
## Nim-Codex
## Copyright (c) 2024 Status Research & Development GmbH
## Licensed under either of
## * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE))
## * MIT license ([LICENSE-MIT](LICENSE-MIT))
## at your option.
## This file may not be copied, modified, or distributed except according to
## those terms.
import std/sugar
import std/bitops
import pkg/poseidon2
import pkg/poseidon2/io
import pkg/constantine/math/arithmetic
2024-01-15 13:59:55 -06:00
2024-01-15 21:47:06 -06:00
import ../../merkletree
func extractLowBits*[n: static int](elm: BigInt[n], k: int): uint64 =
2024-01-15 21:47:06 -06:00
assert( k > 0 and k <= 64 )
var r = 0'u64
for i in 0..<k:
let b = bit[n](elm, i)
2024-01-15 13:59:55 -06:00
let y = uint64(b)
if (y != 0):
2024-01-15 21:47:06 -06:00
r = bitor( r, 1'u64 shl i )
r
2024-01-15 13:59:55 -06:00
2024-01-15 21:47:06 -06:00
func extractLowBits(fld: Poseidon2Hash, k: int): uint64 =
let elm : BigInt[254] = fld.toBig()
return extractLowBits(elm, k);
func floorLog2*(x : int) : int =
2024-01-15 13:59:55 -06:00
var k = -1
var y = x
while (y > 0):
k += 1
y = y shr 1
return k
2024-01-15 21:47:06 -06:00
func ceilingLog2*(x : int) : int =
if (x == 0):
2024-01-15 13:59:55 -06:00
return -1
else:
return (floorLog2(x-1) + 1)
2024-01-15 21:47:06 -06:00
func toBlockIdx*(cell: Natural, numCells: Natural): Natural =
2024-01-15 21:47:06 -06:00
let log2 = ceilingLog2(numCells)
doAssert( 1 shl log2 == numCells , "`numCells` is assumed to be a power of two" )
return cell div numCells
2024-01-15 21:47:06 -06:00
func toBlockCellIdx*(cell: Natural, numCells: Natural): Natural =
2024-01-15 21:47:06 -06:00
let log2 = ceilingLog2(numCells)
doAssert( 1 shl log2 == numCells , "`numCells` is assumed to be a power of two" )
return cell mod numCells
2024-01-15 21:47:06 -06:00
func cellIndex*(
entropy: Poseidon2Hash,
slotRoot: Poseidon2Hash,
numCells: Natural,
counter: Natural): Natural =
2024-01-15 21:47:06 -06:00
let log2 = ceilingLog2(numCells)
doAssert( 1 shl log2 == numCells , "`numCells` is assumed to be a power of two" )
let
hash = Sponge.digest( @[ slotRoot, entropy, counter.toF ], rate = 2 )
2024-01-15 21:47:06 -06:00
extractLowBits(hash, log2)
2024-01-15 21:47:06 -06:00
func cellIndices*(
entropy: Poseidon2Hash,
slotRoot: Poseidon2Hash,
slotIndicies: seq[int],
cellsPerBlock: Natural,
numCells: Natural,
nSamples: Natural): seq[Natural] =
var
indices: seq[Natural]
counter = 1
2024-01-15 21:47:06 -06:00
while (indices.len < nSamples):
let idx = cellIndex(entropy, slotRoot, numCells, counter)
if idx.toBlockIdx(cellsPerBlock) in slotIndicies and idx notin indices:
indices.add(idx.Natural)
counter.inc
2024-01-16 13:36:34 +01:00
indices