Skip to content

Commit

Permalink
feat: ts pedersen commit with offset (#7699)
Browse files Browse the repository at this point in the history
  • Loading branch information
IlyasRidhuan authored Jul 31, 2024
1 parent 43a83ae commit b2224b4
Show file tree
Hide file tree
Showing 11 changed files with 61 additions and 63 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,15 @@

using namespace bb;

WASM_EXPORT void pedersen_commit(fr::vec_in_buf inputs_buffer, grumpkin::g1::affine_element::out_buf output)
WASM_EXPORT void pedersen_commit(fr::vec_in_buf inputs_buffer,
uint32_t const* ctx_index,
grumpkin::g1::affine_element::out_buf output)
{
std::vector<grumpkin::fq> to_commit;
read(inputs_buffer, to_commit);
grumpkin::g1::affine_element pedersen_commitment = crypto::pedersen_commitment::commit_native(to_commit);
crypto::GeneratorContext<curve::Grumpkin> ctx;
ctx.offset = static_cast<size_t>(ntohl(*ctx_index));
grumpkin::g1::affine_element pedersen_commitment = crypto::pedersen_commitment::commit_native(to_commit, ctx);

write(output, pedersen_commitment);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,7 @@ extern "C" {
using namespace bb;
using affine_element = grumpkin::g1::affine_element;

WASM_EXPORT void pedersen_commit(fr::vec_in_buf inputs_buffer, affine_element::out_buf output);
}
WASM_EXPORT void pedersen_commit(fr::vec_in_buf inputs_buffer,
uint32_t const* ctx_index,
affine_element::out_buf output);
}
23 changes: 4 additions & 19 deletions barretenberg/exports.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@
{
"name": "inputs_buffer",
"type": "fr::vec_in_buf"
},
{
"name": "ctx_index",
"type": "const uint32_t *"
}
],
"outArgs": [
Expand Down Expand Up @@ -549,25 +553,6 @@
"outArgs": [],
"isAsync": false
},
{
"functionName": "acir_create_circuit",
"inArgs": [
{
"name": "acir_composer_ptr",
"type": "in_ptr"
},
{
"name": "constraint_system_buf",
"type": "const uint8_t *"
},
{
"name": "size_hint",
"type": "const uint32_t *"
}
],
"outArgs": [],
"isAsync": false
},
{
"functionName": "acir_init_proving_key",
"inArgs": [
Expand Down
5 changes: 3 additions & 2 deletions barretenberg/scripts/bindgen.sh
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
#!/usr/bin/env bash
# Run from aztec-packages/barretenberg.
set -eu

if ! dpkg -l python3-clang-18 &> /dev/null; then
echo "You need to install python clang 18 e.g.: apt install python3-clang-18"
exit 1
fi

#find ./cpp/src -type f -name "c_bind*.hpp" | ./scripts/decls_json.py > exports.json
#find ./cpp/src -type f -name "c_bind*.hpp" > ./scripts/c_bind_files.txt
cat ./scripts/c_bind_files.txt | ./scripts/decls_json.py > exports.json
(
cd ./ts && \
yarn install && \
yarn node --loader ts-node/esm ./src/bindgen/index.ts ../exports.json > ./src/barretenberg_api/index.ts && \
yarn prettier -w ./src/barretenberg_api/index.ts
)
)
4 changes: 2 additions & 2 deletions barretenberg/ts/src/barretenberg/pedersen.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ describe('pedersen sync', () => {
});

it('pedersenCommit', () => {
const result = api.pedersenCommit([new Fr(4n), new Fr(8n), new Fr(12n)]);
const result = api.pedersenCommit([new Fr(4n), new Fr(8n), new Fr(12n)], 0);
expect(result).toMatchSnapshot();
});

Expand All @@ -55,7 +55,7 @@ describe('pedersen sync', () => {
const fields = Array.from({ length: loops * 2 }).map(() => Fr.random());
const t = new Timer();
for (let i = 0; i < loops; ++i) {
api.pedersenCommit([fields[i * 2], fields[i * 2 + 1]]);
api.pedersenCommit([fields[i * 2], fields[i * 2 + 1]], 0);
}
console.log(t.us() / loops);
});
Expand Down
32 changes: 4 additions & 28 deletions barretenberg/ts/src/barretenberg_api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ import { Fr, Fq, Point, Buffer32, Buffer128, Ptr } from '../types/index.js';
export class BarretenbergApi {
constructor(protected wasm: BarretenbergWasmWorker) {}

async pedersenCommit(inputsBuffer: Fr[]): Promise<Point> {
const inArgs = [inputsBuffer].map(serializeBufferable);
async pedersenCommit(inputsBuffer: Fr[], ctxIndex: number): Promise<Point> {
const inArgs = [inputsBuffer, ctxIndex].map(serializeBufferable);
const outTypes: OutputType[] = [Point];
const result = await this.wasm.callWasmExport(
'pedersen_commit',
Expand Down Expand Up @@ -367,18 +367,6 @@ export class BarretenbergApi {
return;
}

async acirCreateCircuit(acirComposerPtr: Ptr, constraintSystemBuf: Uint8Array, sizeHint: number): Promise<void> {
const inArgs = [acirComposerPtr, constraintSystemBuf, sizeHint].map(serializeBufferable);
const outTypes: OutputType[] = [];
const result = await this.wasm.callWasmExport(
'acir_create_circuit',
inArgs,
outTypes.map(t => t.SIZE_IN_BYTES),
);
const out = result.map((r, i) => outTypes[i].fromBuffer(r));
return;
}

async acirInitProvingKey(acirComposerPtr: Ptr, constraintSystemBuf: Uint8Array): Promise<void> {
const inArgs = [acirComposerPtr, constraintSystemBuf].map(serializeBufferable);
const outTypes: OutputType[] = [];
Expand Down Expand Up @@ -606,8 +594,8 @@ export class BarretenbergApi {
export class BarretenbergApiSync {
constructor(protected wasm: BarretenbergWasm) {}

pedersenCommit(inputsBuffer: Fr[]): Point {
const inArgs = [inputsBuffer].map(serializeBufferable);
pedersenCommit(inputsBuffer: Fr[], ctxIndex: number): Point {
const inArgs = [inputsBuffer, ctxIndex].map(serializeBufferable);
const outTypes: OutputType[] = [Point];
const result = this.wasm.callWasmExport(
'pedersen_commit',
Expand Down Expand Up @@ -955,18 +943,6 @@ export class BarretenbergApiSync {
return;
}

acirCreateCircuit(acirComposerPtr: Ptr, constraintSystemBuf: Uint8Array, sizeHint: number): void {
const inArgs = [acirComposerPtr, constraintSystemBuf, sizeHint].map(serializeBufferable);
const outTypes: OutputType[] = [];
const result = this.wasm.callWasmExport(
'acir_create_circuit',
inArgs,
outTypes.map(t => t.SIZE_IN_BYTES),
);
const out = result.map((r, i) => outTypes[i].fromBuffer(r));
return;
}

acirInitProvingKey(acirComposerPtr: Ptr, constraintSystemBuf: Uint8Array): void {
const inArgs = [acirComposerPtr, constraintSystemBuf].map(serializeBufferable);
const outTypes: OutputType[] = [];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ contract AvmTest {

#[aztec(public)]
fn pedersen_commit(x: Field, y: Field) -> EmbeddedCurvePoint {
let commitment = dep::std::hash::pedersen_commitment([x, y]);
let commitment = dep::std::hash::pedersen_commitment_with_separator([x, y], 20);
commitment
}

Expand Down
7 changes: 5 additions & 2 deletions yarn-project/foundation/src/crypto/pedersen/pedersen.wasm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,15 @@ import { type Fieldable, serializeToFields } from '../../serialize/serialize.js'
* Create a pedersen commitment (point) from an array of input fields.
* Left pads any inputs less than 32 bytes.
*/
export function pedersenCommit(input: Buffer[]) {
export function pedersenCommit(input: Buffer[], offset = 0) {
if (!input.every(i => i.length <= 32)) {
throw new Error('All Pedersen Commit input buffers must be <= 32 bytes.');
}
input = input.map(i => (i.length < 32 ? Buffer.concat([Buffer.alloc(32 - i.length, 0), i]) : i));
const point = BarretenbergSync.getSingleton().pedersenCommit(input.map(i => new FrBarretenberg(i)));
const point = BarretenbergSync.getSingleton().pedersenCommit(
input.map(i => new FrBarretenberg(i)),
offset,
);
// toBuffer returns Uint8Arrays (browser/worker-boundary friendly).
// TODO: rename toTypedArray()?
return [Buffer.from(point.x.toBuffer()), Buffer.from(point.y.toBuffer())];
Expand Down
2 changes: 1 addition & 1 deletion yarn-project/simulator/src/avm/avm_simulator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ describe('AVM simulator: transpiled Noir contracts', () => {

expect(results.reverted).toBe(false);
// This doesnt include infinites
const expectedResult = pedersenCommit([Buffer.from([100]), Buffer.from([1])]).map(f => new Fr(f));
const expectedResult = pedersenCommit([Buffer.from([100]), Buffer.from([1])], 20).map(f => new Fr(f));
// TODO: Come back to the handling of infinities when we confirm how they're handled in bb
const isInf = expectedResult[0] === new Fr(0) && expectedResult[1] === new Fr(0);
expectedResult.push(new Fr(isInf));
Expand Down
27 changes: 27 additions & 0 deletions yarn-project/simulator/src/avm/opcodes/commitment.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,33 @@ describe('Commitment Opcode', () => {
expect(0).toEqual(context.machineState.memory.get(outputOffset + 2).toNumber());
});

it('Should commit correctly with a different gen - direct', async () => {
const args = randomMemoryFields(10);
const inputOffset = 0;
const inputSizeOffset = 20;
const outputOffset = 50;
const indirect = 0;
const generatorIndex = 40;
const generatorIndexOffset = 100;

context.machineState.memory.setSlice(inputOffset, args);
context.machineState.memory.set(inputSizeOffset, new Uint32(args.length));
context.machineState.memory.set(generatorIndexOffset, new Uint32(generatorIndex));

const expectedCommitment = pedersenCommit(
args.map(f => f.toBuffer()),
generatorIndex,
).map(f => new Field(f));
await new PedersenCommitment(indirect, inputOffset, outputOffset, inputSizeOffset, generatorIndexOffset).execute(
context,
);

const result = context.machineState.memory.getSlice(outputOffset, 2);
expect(result).toEqual(expectedCommitment);
// Check Inf
expect(0).toEqual(context.machineState.memory.get(outputOffset + 2).toNumber());
});

it('Should commit correctly - indirect', async () => {
const args = randomMemoryFields(10);
const indirect = new Addressing([
Expand Down
6 changes: 3 additions & 3 deletions yarn-project/simulator/src/avm/opcodes/commitment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,15 +43,15 @@ export class PedersenCommitment extends Instruction {
const inputs = memory.getSlice(inputOffset, inputSize);
memory.checkTagsRange(TypeTag.FIELD, inputOffset, inputSize);

// Generator index not used for now since we dont utilise it in the pedersenCommit function
const generatorIndex = memory.get(genIndexOffset).toNumber();
memory.checkTag(TypeTag.UINT32, genIndexOffset);

const memoryOperations = { reads: inputSize + 1, writes: 3, indirect: this.indirect };
const memoryOperations = { reads: inputSize + 2, writes: 3, indirect: this.indirect };
context.machineState.consumeGas(this.gasCost(memoryOperations));

const inputBuffer: Buffer[] = inputs.map(input => input.toBuffer());
// TODO: Add the generate index to the pedersenCommit function
const commitment = pedersenCommit(inputBuffer).map(f => new Field(f));
const commitment = pedersenCommit(inputBuffer, generatorIndex).map(f => new Field(f));
// The function doesnt include a flag if the output point is infinity, come back to this
// for now we just check if theyre zero - until we know how bb encodes them
const isInfinity = commitment[0].equals(new Field(0)) && commitment[1].equals(new Field(0));
Expand Down

0 comments on commit b2224b4

Please sign in to comment.