Skip to content

Commit

Permalink
from2Fields func
Browse files Browse the repository at this point in the history
  • Loading branch information
benesjan committed Jan 12, 2024
1 parent 0acf208 commit f63a8cb
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
18 changes: 18 additions & 0 deletions yarn-project/foundation/src/serialize/free_funcs.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { randomBytes } from '../crypto/index.js';
import { from2Fields, to2Fields } from './free_funcs.js';

describe('buffer to fields and back', () => {
it('should correctly serialize and deserialize a buffer', () => {
// Generate a random 32-byte buffer
const originalBuffer = randomBytes(32);

// Serialize the buffer to two fields
const [field1, field2] = to2Fields(originalBuffer);

// Deserialize the fields back to a buffer
const reconstructedBuffer = from2Fields(field1, field2);

// Check if the original buffer and reconstructed buffer are identical
expect(reconstructedBuffer).toEqual(originalBuffer);
});
});
19 changes: 19 additions & 0 deletions yarn-project/foundation/src/serialize/free_funcs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,3 +126,22 @@ export function to2Fields(buf: Buffer): [Fr, Fr] {

return [Fr.fromBuffer(buf1), Fr.fromBuffer(buf2)];
}

/**
* Reconstructs the original 32 bytes of data from 2 field elements.
* @param field1 - First field element
* @param field2 - Second field element
* @returns 32 bytes of data as a Buffer
*/
export function from2Fields(field1: Fr, field2: Fr): Buffer {
// Convert the field elements back to buffers
const buf1 = field1.toBuffer();
const buf2 = field2.toBuffer();

// Remove the padding (first 16 bytes) from each buffer
const originalPart1 = buf1.slice(16, 32);
const originalPart2 = buf2.slice(16, 32);

// Concatenate the two parts to form the original buffer
return Buffer.concat([originalPart1, originalPart2]);
}

0 comments on commit f63a8cb

Please sign in to comment.