Skip to content

Commit

Permalink
circuit: add bytes utils
Browse files Browse the repository at this point in the history
  • Loading branch information
saleel committed Mar 30, 2024
1 parent 85f95a6 commit 070bc4e
Show file tree
Hide file tree
Showing 4 changed files with 66 additions and 66 deletions.
41 changes: 0 additions & 41 deletions packages/circuits/helpers/utils/bytes2ints.circom

This file was deleted.

25 changes: 0 additions & 25 deletions packages/circuits/helpers/utils/constants.circom

This file was deleted.

52 changes: 52 additions & 0 deletions packages/circuits/utils/bytes.circom
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
pragma circom 2.1.5;

include "circomlib/circuits/bitify.circom";
include "circomlib/circuits/comparators.circom";
include "circomlib/circuits/poseidon.circom";
include "./constants.circom";


/// @title PackBytesToInts
/// @notice Converts a byte array into a 31-byte integer array (packing)
/// @param maxBytes: the maximum number of bytes in the input array
/// @input in: the input byte array
/// @output out: the output integer array
template PackBytesToInts(maxBytes) {
var packSize = MAX_BYTES_IN_FIELD();

// Calculate number of int chunks based in maxBytes
var remain = maxBytes % packSize;
var maxInts = (maxBytes - remain) / packSize;
if (remain > 0) {
maxInts += 1;
}

signal input in[maxBytes];
signal output out[maxInts];

signal intSums[maxInts][packSize];

for (var i = 0; i < maxInts; i++) {
for(var j=0; j < packSize; j++) {
var idx = packSize * i + j;

// Copy the previous value if we are out of bounds - we take last item as final result
if(idx >= maxBytes) {
intSums[i][j] <== intSums[i][j-1];
}
// First item of each chunk is the byte itself
else if (j == 0){
intSums[i][j] <== bytes[idx];
}
// Every other item is 256^j * byte
else {
intSums[i][j] <== intSums[i][j-1] + (1 << (8*j)) * bytes[idx];
}
}
}

// Last item of each chunk is the final sum
for (var i = 0; i < maxInts; i++) {
ints[i] <== intSums[i][packSize-1];
}
}
14 changes: 14 additions & 0 deletions packages/circuits/utils/constants.circom
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
pragma circom 2.1.5;

function EMAIL_ADDR_MAX_BYTES() {
return 256;
}

function DOMAIN_MAX_BYTES() {
return 255;
}

// Field support maximum of ~253 bit
function MAX_BYTES_IN_FIELD() {
return 31;
}

0 comments on commit 070bc4e

Please sign in to comment.