Skip to content

Commit

Permalink
feat(noir-contracts): option<t> for get_notes
Browse files Browse the repository at this point in the history
  • Loading branch information
iAmMichaelConnor committed Jul 30, 2023
1 parent abcf81c commit 1530d57
Show file tree
Hide file tree
Showing 30 changed files with 466 additions and 269 deletions.
2 changes: 1 addition & 1 deletion build-system
38 changes: 35 additions & 3 deletions yarn-project/acir-simulator/src/client/client_execution_context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { CircuitsWasm, PrivateHistoricTreeRoots, ReadRequestMembershipWitness, T
import { computeCommitmentNonce } from '@aztec/circuits.js/abis';
import { AztecAddress } from '@aztec/foundation/aztec-address';
import { Fr, Point } from '@aztec/foundation/fields';
import { createDebugLogger } from '@aztec/foundation/log';

import {
ACVMField,
Expand Down Expand Up @@ -40,6 +41,8 @@ export class ClientTxExecutionContext {
/** The list of nullifiers created in this transaction. The commitment/note which is nullified
* might be pending or not (i.e., was generated in a previous transaction) */
private pendingNullifiers: Set<Fr> = new Set<Fr>(),

private log = createDebugLogger('aztec:simulator:client_execution_context'),
) {}

/**
Expand Down Expand Up @@ -136,8 +139,20 @@ export class ClientTxExecutionContext {
offset,
});

// TODO: notice, that if we don't have a note in our DB, we don't know how big the preimage needs to be, and so we don't actually know how many dummy notes to return, or big to make those dummy notes, or where to position `is_some` booleans to inform the noir program that _all_ the notes should be dummies.
// By a happy coincidence, a `0` field is interpreted as `is_none`, and since in this case (of an empty db) we'll return all zeros (paddedZeros), the noir program will treat the returned data as all dummies, but this is luck. Perhaps a preimage size should be conveyed by the get_notes noir oracle?
const preimageLength = notes?.[0]?.preimage.length ?? 0;
if (
!notes.every(({ preimage }) => {
return preimageLength === preimage.length;
})
)
throw new Error('Preimages for a particular note type should all be the same length');

// Combine pending and db preimages into a single flattened array.
const preimages = notes.flatMap(({ nonce, preimage }) => [nonce, ...preimage]);
const isSome = new Fr(1); // Boolean. Indicates whether the Noir Option<Note>::is_some();

const realNotePreimages = notes.flatMap(({ nonce, preimage }) => [nonce, isSome, ...preimage]);

// Add a partial witness for each note.
// It contains the note index for db notes. And flagged as transient for pending notes.
Expand All @@ -147,8 +162,25 @@ export class ClientTxExecutionContext {
);
});

const paddedZeros = Array(Math.max(0, returnSize - 2 - preimages.length)).fill(Fr.ZERO);
return [notes.length, contractAddress, ...preimages, ...paddedZeros].map(v => toACVMField(v));
const returnHeaderLength = 2; // is for the header values: `notes.length` and `contractAddress`.
const extraPreimageLength = 2; // is for the nonce and isSome fields.
const extendedPreimageLength = preimageLength + extraPreimageLength;
const numRealNotes = notes.length;
const numReturnNotes = Math.floor((returnSize - returnHeaderLength) / extendedPreimageLength);
const numDummyNotes = numReturnNotes - numRealNotes;

const dummyNotePreimage = Array(extendedPreimageLength).fill(Fr.ZERO);
const dummyNotePreimages = Array(numDummyNotes)
.fill(dummyNotePreimage)
.flatMap(note => note);

const paddedZeros = Array(
Math.max(0, returnSize - returnHeaderLength - realNotePreimages.length - dummyNotePreimages.length),
).fill(Fr.ZERO);

return [notes.length, contractAddress, ...realNotePreimages, ...dummyNotePreimages, ...paddedZeros].map(v =>
toACVMField(v),
);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ describe('Private Execution test suite', () => {

const buildNote = (amount: bigint, owner: AztecAddress, storageSlot = Fr.random()) => {
const nonce = new Fr(currentNoteIndex);
const preimage = [new Fr(amount), owner.toField(), Fr.random(), new Fr(1n)];
const preimage = [new Fr(amount), owner.toField(), Fr.random()];
return { contractAddress, storageSlot, index: currentNoteIndex++, nonce, nullifier: new Fr(0), preimage };
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ describe('Unconstrained Execution test suite', () => {
let owner: AztecAddress;

const buildNote = (amount: bigint, owner: AztecAddress) => {
return [new Fr(amount), owner, Fr.random(), new Fr(1n)];
return [new Fr(amount), owner, Fr.random()];
};

const calculateAddress = (privateKey: PrivateKey) => {
Expand Down Expand Up @@ -67,6 +67,7 @@ describe('Unconstrained Execution test suite', () => {
contractAddress,
storageSlot: Fr.random(),
nonce: Fr.random(),
isSome: new Fr(1),
preimage,
nullifier: Fr.random(),
index: BigInt(index),
Expand Down

Large diffs are not rendered by default.

Large diffs are not rendered by default.

Large diffs are not rendered by default.

Large diffs are not rendered by default.

Large diffs are not rendered by default.

Large diffs are not rendered by default.

16 changes: 8 additions & 8 deletions yarn-project/noir-contracts/src/artifacts/zk_token_contract.json

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -75,10 +75,6 @@ impl EcdsaPublicKeyNote {
header: NoteHeader::empty(),
}
}

fn is_dummy(self) -> bool {
(self.x == [0;32]) & (self.y == [0;32]) & (self.owner == 0)
}
}

fn deserialise(preimage: [Field; ECDSA_PUBLIC_KEY_NOTE_LEN]) -> EcdsaPublicKeyNote {
Expand Down Expand Up @@ -117,10 +113,6 @@ fn dummy() -> EcdsaPublicKeyNote {
EcdsaPublicKeyNote::dummy()
}

fn is_dummy(note: EcdsaPublicKeyNote) -> bool {
note.is_dummy()
}

fn get_header(note: EcdsaPublicKeyNote) -> NoteHeader {
note.header
}
Expand All @@ -135,7 +127,6 @@ global EcdsaPublicKeyNoteInterface = NoteInterface {
compute_note_hash,
compute_nullifier,
dummy,
is_dummy,
get_header,
set_header,
};
Original file line number Diff line number Diff line change
Expand Up @@ -68,15 +68,16 @@ contract PendingCommitments {

let options = NoteGetterOptions::with_filter(get_2_notes, 0);
// get note inserted above
let (context_tmp, got_notes) = owner_balance.get_notes(context, options);
let (context_tmp, maybe_notes) = owner_balance.get_notes(context, options);
context = context_tmp;

assert(note.value == got_notes[0].value);
assert(!got_notes[1].is_real);
let note0 = maybe_notes[0].unwrap();
assert(note.value == note0.value);
assert(maybe_notes[1].is_none());

context.return_values = context.return_values.push(got_notes[0].value);
context.return_values = context.return_values.push(note0.value);

context = owner_balance.remove(context, got_notes[0]);
context = owner_balance.remove(context, note0);

context.finish()
}
Expand All @@ -97,14 +98,13 @@ contract PendingCommitments {

let options = NoteGetterOptions::with_filter(get_2_notes, 0);
// get note (note inserted at bottom of function shouldn't exist yet)
let (context_tmp, got_notes) = owner_balance.get_notes(context, options);
let (context_tmp, maybe_notes) = owner_balance.get_notes(context, options);
context = context_tmp;

assert(!got_notes[0].is_real);
assert(got_notes[0].value == 0);
assert(!got_notes[1].is_real);
assert(maybe_notes[0].is_none());
assert(maybe_notes[1].is_none());

context.return_values = context.return_values.push(got_notes[0].value);
context.return_values = context.return_values.push(0);

// Insert note and emit encrypted note preimage via oracle call
let note = ValueNote::new(amount, owner);
Expand Down Expand Up @@ -149,15 +149,15 @@ contract PendingCommitments {
let owner_balance = storage.balances.at(owner);

let options = NoteGetterOptions::with_filter(get_2_notes, 0);
let (context_tmp, got_notes) = owner_balance.get_notes(context, options);
let (context_tmp, maybe_notes) = owner_balance.get_notes(context, options);
context = context_tmp;

assert(expected_value == got_notes[0].value);
assert(!got_notes[1].is_real);
assert(expected_value == maybe_notes[0].unwrap().value);
assert(maybe_notes[1].is_none());

context.return_values = context.return_values.push(got_notes[0].value);
context.return_values = context.return_values.push(expected_value);

context = owner_balance.remove(context, got_notes[0]);
context = owner_balance.remove(context, maybe_notes[0].unwrap_unchecked());

context.finish()
}
Expand All @@ -176,11 +176,11 @@ contract PendingCommitments {
let owner_balance = storage.balances.at(owner);

let options = NoteGetterOptions::with_filter(get_2_notes, 0);
let (context_tmp, got_notes) = owner_balance.get_notes(context, options);
let (context_tmp, maybe_notes) = owner_balance.get_notes(context, options);
context = context_tmp;

assert(!got_notes[0].is_real);
assert(!got_notes[1].is_real);
assert(maybe_notes[0].is_none());
assert(maybe_notes[1].is_none());

context.finish()
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,10 +47,6 @@ impl AddressNote {
header: NoteHeader::empty(),
}
}

fn is_dummy(self) -> bool {
self.address == 0
}
}

fn deserialise(preimage: [Field; ADDRESS_NOTE_LEN]) -> AddressNote {
Expand All @@ -76,10 +72,6 @@ fn dummy() -> AddressNote {
AddressNote::dummy()
}

fn is_dummy(note: AddressNote) -> bool {
note.is_dummy()
}

fn get_header(note: AddressNote) -> NoteHeader {
note.header
}
Expand All @@ -94,7 +86,6 @@ global AddressNoteInterface = NoteInterface {
compute_note_hash,
compute_nullifier,
dummy,
is_dummy,
get_header,
set_header,
};
Original file line number Diff line number Diff line change
Expand Up @@ -93,11 +93,13 @@ contract PokeableToken {
let sender_balance = storage.balances.at(sender.address);

let options = NoteGetterOptions::with_filter(get_2_notes, 0);
let (mut new_context, notes) = sender_balance.get_notes(context, options);
let (mut new_context, maybe_notes) = sender_balance.get_notes(context, options);
context = new_context;

let note1 = notes[0];
let note2 = notes[1];
// Note: dangerous to unwrap_unchecked. See zk_token_contract example for a safer implementation.
// TODO: any reason this doesn't use the 'spend_notes' util function?
let note1 = maybe_notes[0].unwrap_unchecked();
let note2 = maybe_notes[1].unwrap_unchecked();

let note_sum = note1.value + note2.value;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,6 @@ impl PublicKeyNote {
header: NoteHeader::empty(),
}
}

fn is_dummy(self) -> bool {
(self.x == 0) & (self.y == 0) & (self.owner == 0)
}
}

fn deserialise(preimage: [Field; PUBLIC_KEY_NOTE_LEN]) -> PublicKeyNote {
Expand Down Expand Up @@ -85,10 +81,6 @@ fn dummy() -> PublicKeyNote {
PublicKeyNote::dummy()
}

fn is_dummy(note: PublicKeyNote) -> bool {
note.is_dummy()
}

fn get_header(note: PublicKeyNote) -> NoteHeader {
note.header
}
Expand All @@ -103,7 +95,6 @@ global PublicKeyNoteInterface = NoteInterface {
compute_note_hash,
compute_nullifier,
dummy,
is_dummy,
get_header,
set_header,
};
Original file line number Diff line number Diff line change
Expand Up @@ -57,10 +57,6 @@ impl ClaimNote {
}
}

fn is_dummy(self) -> bool {
self.value == 0
}

fn set_header(mut self: Self, header: NoteHeader) -> Self {
self.header = header;
self
Expand All @@ -87,10 +83,6 @@ fn dummy() -> ClaimNote {
ClaimNote::dummy()
}

fn is_dummy(note: ClaimNote) -> bool {
note.is_dummy()
}

fn get_header(note: ClaimNote) -> NoteHeader {
note.header
}
Expand All @@ -105,7 +97,6 @@ global ClaimNoteInterface = NoteInterface {
compute_note_hash,
compute_nullifier,
dummy,
is_dummy,
get_header,
set_header,
};
43 changes: 23 additions & 20 deletions yarn-project/noir-libs/easy-private-state/src/easy_private_state.nr
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,10 @@ use dep::aztec::{
note::note_getter_options::NoteGetterOptions,
oracle::get_public_key::get_public_key,
state_vars::set::Set,
types::point::Point,
types::{
point::Point,
option::Option,
}
};

struct EasyPrivateUint {
Expand Down Expand Up @@ -68,38 +71,38 @@ impl EasyPrivateUint {
owner: Field,
) -> Context {
let options = NoteGetterOptions::with_filter(get_2_notes, 0);
let (mut new_context, notes) = self.set.get_notes(context, options);
let (mut new_context, maybe_notes) = self.set.get_notes(context, options);
context = new_context;
let note1 = notes[0];
let note2 = notes[1];

let note0 = maybe_notes[0].unwrap_or(ValueNote::dummy());
let note1 = maybe_notes[1].unwrap_or(ValueNote::dummy());

// Ensure the notes are actually owned by the owner (to prevent user from generating a valid proof while
// nullifying someone else's notes).
let validate = |note: ValueNote, owner: Field| {
let condition = (owner == note.owner);
assert((!note.is_real) | condition);
};

validate(note1, owner);
validate(note2, owner);
if maybe_notes[0].is_some() {
assert(owner == note0.owner);
// Removes the note from the owner's set of notes.
context = self.set.remove(context, note0);
}
if maybe_notes[1].is_some() {
assert(owner == note1.owner);
// Removes the note from the owner's set of notes.
context = self.set.remove(context, note1);
}

let note0_value: u120 = note0.value as u120;
let note1_value: u120 = note1.value as u120;
let note2_value: u120 = note2.value as u120;
let minuend = note1_value + note2_value;
let minuend = note0_value + note1_value;
assert(minuend >= subtrahend);

// Removes the 2 notes from the owner's set of notes.
context = self.set.remove(context, note1);
context = self.set.remove(context, note2);

// Creates change note for the owner.
let result = minuend - subtrahend;
let result_note = ValueNote::new(result as Field, owner);
let result_value = minuend - subtrahend;
let result_note = ValueNote::new(result_value as Field, owner);
context = self.set.insert(context, result_note);

// Emit the newly created encrypted note preimages via oracle calls.
let mut encrypted_data = [0; VALUE_NOTE_LEN];
if result_note.is_dummy() == false {
if result_value != 0 {
encrypted_data = result_note.serialise();
};

Expand Down
Loading

0 comments on commit 1530d57

Please sign in to comment.