Skip to content

Commit

Permalink
feat: add oracle for selector computation
Browse files Browse the repository at this point in the history
  • Loading branch information
LHerskind committed Sep 5, 2023
1 parent cd2990f commit c9c5369
Show file tree
Hide file tree
Showing 18 changed files with 94 additions and 83 deletions.
1 change: 1 addition & 0 deletions yarn-project/acir-simulator/src/acvm/acvm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ export const ONE_ACVM_FIELD: ACVMField = `0x${'00'.repeat(Fr.SIZE_IN_BYTES - 1)}
* The supported oracle names.
*/
type ORACLE_NAMES =
| 'computeSelector'
| 'packArguments'
| 'getSecretKey'
| 'getNote'
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { FunctionSelector } from '@aztec/circuits.js';

export const computeNoteHashAndNullifierSignature = 'compute_note_hash_and_nullifier(field,field,field,array)';
export const computeNoteHashAndNullifierSignature = 'compute_note_hash_and_nullifier(Field,Field,Field,[Field;3])';

export const computeNoteHashAndNullifierSelector = FunctionSelector.fromSignature(computeNoteHashAndNullifierSignature);
5 changes: 5 additions & 0 deletions yarn-project/acir-simulator/src/client/private_execution.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,11 @@ export class PrivateFunctionExecution {
acir,
initialWitness,
{
computeSelector: (...args) => {
const signature = oracleDebugCallToFormattedStr(args);
const returnValue = toACVMField(FunctionSelector.fromSignature(signature).toField());
return Promise.resolve(returnValue);
},
packArguments: async args => {
return toACVMField(await this.context.packedArgsCache.pack(args.map(fromACVMField)));
},
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { CallContext, FunctionData } from '@aztec/circuits.js';
import { DecodedReturn, decodeReturnValues } from '@aztec/foundation/abi';
import { DecodedReturn, FunctionSelector, decodeReturnValues } from '@aztec/foundation/abi';
import { AztecAddress } from '@aztec/foundation/aztec-address';
import { Fr } from '@aztec/foundation/fields';
import { createDebugLogger } from '@aztec/foundation/log';
Expand Down Expand Up @@ -43,6 +43,11 @@ export class UnconstrainedFunctionExecution {
acir,
initialWitness,
{
computeSelector: (...args) => {
const signature = oracleDebugCallToFormattedStr(args);
const returnValue = toACVMField(FunctionSelector.fromSignature(signature).toField());
return Promise.resolve(returnValue);
},
getSecretKey: ([ownerX], [ownerY]) => this.context.getSecretKey(this.contractAddress, ownerX, ownerY),
getPublicKey: async ([acvmAddress]) => {
const address = frToAztecAddress(fromACVMField(acvmAddress));
Expand Down
5 changes: 4 additions & 1 deletion yarn-project/acir-simulator/src/public/executor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,10 +68,13 @@ export class PublicExecutor {
// We use this cache to hold the packed arguments.
const packedArgs = await PackedArgsCache.create([]);
const { partialWitness } = await acvm(await AcirSimulator.getSolver(), acir, initialWitness, {
computeSelector: (...args) => {
const signature = oracleDebugCallToFormattedStr(args);
return Promise.resolve(toACVMField(FunctionSelector.fromSignature(signature).toField()));
},
packArguments: async args => {
return toACVMField(await packedArgs.pack(args.map(fromACVMField)));
},

debugLog: (...args) => {
this.log(oracleDebugCallToFormattedStr(args));
return Promise.resolve(ZERO_ACVM_FIELD);
Expand Down
7 changes: 5 additions & 2 deletions yarn-project/end-to-end/src/e2e_lending_contract.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { AztecNodeService } from '@aztec/aztec-node';
import { AztecRPCServer } from '@aztec/aztec-rpc';
import { AztecAddress, CheatCodes, Fr, Wallet, computeMessageSecretHash } from '@aztec/aztec.js';
import { AztecAddress, CheatCodes, Fr, Wallet, computeMessageSecretHash, sleep } from '@aztec/aztec.js';
import { CircuitsWasm, CompleteAddress } from '@aztec/circuits.js';
import { pedersenPlookupCommitInputs } from '@aztec/circuits.js/barretenberg';
import { DebugLogger } from '@aztec/foundation/log';
Expand Down Expand Up @@ -54,7 +54,7 @@ describe('e2e_lending_contract', () => {
logger(`Tx sent with hash ${await tx.getTxHash()}`);
const receipt = await tx.wait();
expect(receipt.status).toBe(TxStatus.MINED);
logger(`Debt asset deployed to ${receipt.contractAddress}`);
logger(`Stable coin asset deployed to ${receipt.contractAddress}`);
stableCoin = await NativeTokenContract.at(receipt.contractAddress!, wallet);
}

Expand Down Expand Up @@ -88,6 +88,7 @@ describe('e2e_lending_contract', () => {
stableCoin: NativeTokenContract,
account: Account,
) => {
await sleep(5000);
logger('Fetching storage snapshot 📸 ');
const accountKey = await account.key();

Expand Down Expand Up @@ -293,6 +294,7 @@ describe('e2e_lending_contract', () => {
const receipt3 = await tx3.wait();
expect(receipt3.status).toBe(TxStatus.MINED);

// At this point we should have some values!????
const tx4 = stableCoin.methods.redeemShield(shieldAmount, secret, recipient).send({ origin: recipient });
const receipt4 = await tx4.wait();
expect(receipt4.status).toBe(TxStatus.MINED);
Expand Down Expand Up @@ -411,6 +413,7 @@ describe('e2e_lending_contract', () => {
// - increase the private debt.

logger('Borrow 🥸 : 🏦 -> 🍌');
logger(`Addresses: ${stableCoin.address}, ${lendingContract.address}, ${collateralAsset.address}, ${recipient}`);
const tx = lendingContract.methods
.borrow_private(account.secret, account.address, borrowAmount)
.send({ origin: recipient });
Expand Down
5 changes: 4 additions & 1 deletion yarn-project/foundation/src/abi/function_selector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,10 @@ export class FunctionSelector {
*/
static fromNameAndParameters(name: string, parameters: ABIParameter[]) {
const signature = new FunctionSignatureDecoder(name, parameters).decode();
return FunctionSelector.fromSignature(signature);
const selector = FunctionSelector.fromSignature(signature);
// If you are debugging, can be useful to uncomment the following line.
// console.log(`Function selector for ${signature} is ${selector}`);
return selector;
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ mod storage;
// A contract used along with `Parent` contract to test nested calls.
contract Child {
use crate::storage::Storage;
use dep::aztec::oracle::logs::emit_unencrypted_log;
use dep::aztec::oracle::{logs::emit_unencrypted_log, compute_selector::compute_selector};
use dep::std::option::Option;

#[aztec(private)]
Expand All @@ -27,7 +27,7 @@ contract Child {
input + context.chain_id() + context.version()
}

// Returns base_value + 42.
// Returns base_value + chain_id + version + block_number + timestamp
#[aztec(public)]
fn pubGetValue(base_value: Field) -> Field {
let returnValue = base_value + context.chain_id() + context.version() + context.block_number() + context.timestamp();
Expand Down Expand Up @@ -70,7 +70,7 @@ contract Child {

#[aztec(public)]
fn setValueTwiceWithNestedFirst() {
let pubSetValueSelector = 0x5b0f91b0;
let pubSetValueSelector = compute_selector("pubSetValue(Field)");
let _ret = context.call_public_function(context.this_address(), pubSetValueSelector, [10]);

let storage = Storage::init(Option::none(), Option::some(&mut context));
Expand All @@ -84,7 +84,7 @@ contract Child {
storage.current_value.write(20);
let _hash = emit_unencrypted_log(20);

let pubSetValueSelector = 0x5b0f91b0;
let pubSetValueSelector = compute_selector("pubSetValue(Field)");
let _ret = context.call_public_function(context.this_address(), pubSetValueSelector, [10]);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use dep::aztec::context::{

use crate::storage::Asset;
use dep::aztec::constants_gen::RETURN_VALUES_LENGTH;
use dep::aztec::oracle::compute_selector::compute_selector;

struct PriceFeed {
address: Field,
Expand All @@ -20,7 +21,7 @@ impl PriceFeed {
fn get_price(self: Self, context: PublicContext) -> u120 {
let return_values = context.call_public_function(
self.address,
3359284436,
compute_selector("get_price(Field)"),
[0]
);

Expand All @@ -40,23 +41,23 @@ impl Token {
fn transfer_pub(self: Self, context: PublicContext, to: Field, amount: Field) {
let _transfer_return_values = context.call_public_function(
self.address,
1012824788,
compute_selector("transfer_pub(Field,Field)"),
[to, amount]
);
}

fn transfer_from_pub(self: Self, context: PublicContext, from: Field, to: Field, amount: Field) {
let _transfer_return_values = context.call_public_function(
self.address,
1602017294,
self.address,
compute_selector("transfer_from_pub(Field,Field,Field)"),
[from, to, amount]
);
}

fn owner_mint_pub(self: Self, context: PublicContext, to: Field, amount: Field) {
let _transfer_return_values = context.call_public_function(
self.address,
1071038680,
compute_selector("owner_mint_pub(Field,Field)"),
[to, amount]
);
}
Expand All @@ -65,7 +66,7 @@ impl Token {
fn unshield(self: Self, context: &mut PrivateContext, from: Field, to: Field, amount: Field) -> [Field; RETURN_VALUES_LENGTH] {
context.call_private_function(
self.address,
2423803924,
compute_selector("unshieldTokens(Field,Field,Field)"),
[from, to, amount]
)
}
Expand All @@ -82,8 +83,8 @@ impl Lending {

fn update_accumulator(self: Self, context: PublicContext) -> Asset {
let return_values = context.call_public_function_no_args(
self.address,
0x1873b536
self.address,
compute_selector("update_accumulator()"),
);

Asset {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ contract Lending {
use crate::interest_math::compute_multiplier;
use crate::helpers::{covered_by_collateral, DebtReturn, debt_updates, debt_value, compute_identifier};
use crate::interfaces::{Token, Lending, PriceFeed};
use dep::aztec::oracle::compute_selector::compute_selector;

struct Position {
collateral: Field,
Expand Down Expand Up @@ -59,7 +60,6 @@ contract Lending {
}

// Create a position.
// keccak256("update_accumulator()") >> 224 -> 0x1873b536
#[aztec(public)]
fn update_accumulator() -> Asset {
let storage = Storage::init(Option::none(), Option::some(&mut context));
Expand Down Expand Up @@ -98,7 +98,8 @@ contract Lending {
let on_behalf_of = compute_identifier(secret, on_behalf_of, context.msg_sender());
let _res = Token::at(collateral_asset).unshield(&mut context, asset_owner, context.this_address(), amount);
// _deposit(on_behalf_of, amount, collateral_asset)
let _callStackItem2 = context.call_public_function(context.this_address(), 0x08506e50,[on_behalf_of, amount, collateral_asset]);
let selector = compute_selector("_deposit(Field,Field,Field)");
let _callStackItem2 = context.call_public_function(context.this_address(), selector, [on_behalf_of, amount, collateral_asset]);
}

#[aztec(public)]
Expand All @@ -108,13 +109,13 @@ contract Lending {
collateral_asset: Field,
) -> Field {
Token::at(collateral_asset).transfer_from_pub(context, context.msg_sender(), context.this_address(), amount);
let return_values = context.call_public_function(context.this_address(), 0x08506e50, [owner, amount, collateral_asset]);
let selector = compute_selector("_deposit(Field,Field,Field)");
let return_values = context.call_public_function(context.this_address(), selector, [owner, amount, collateral_asset]);

return_values[0]
}

#[aztec(public)]
// keccak256("_deposit(field,field,field)") >> 224 -> 0x08506e50
internal fn _deposit(
owner: Field,
amount: Field,
Expand All @@ -140,21 +141,21 @@ contract Lending {
amount: Field
) {
let on_behalf_of = compute_identifier(secret, 0, context.msg_sender());
let _callStackItem = context.call_public_function(context.this_address(), 0x5af6f634, [on_behalf_of, to, amount]);
let selector = compute_selector("_withdraw(Field,Field,Field)");
let _callStackItem = context.call_public_function(context.this_address(), selector, [on_behalf_of, to, amount]);
}

#[aztec(public)]
fn withdraw_public(
to: Field,
amount: Field,
) -> Field {
// _withdraw(msg.sender, to, amount);
let return_values = context.call_public_function(context.this_address(), 0x5af6f634, [context.msg_sender(), to, amount]);
let selector = compute_selector("_withdraw(Field,Field,Field)");
let return_values = context.call_public_function(context.this_address(), selector, [context.msg_sender(), to, amount]);

return_values[0]
}

// keccak256("_withdraw(field,field,field)") >> 224 -> 0x5af6f634
#[aztec(public)]
internal fn _withdraw(
owner: Field,
Expand Down Expand Up @@ -195,22 +196,21 @@ contract Lending {
amount: Field
) {
let on_behalf_of = compute_identifier(secret, 0, context.msg_sender());
// _borrow(msg.sender, to, amount)
let _callStackItem = context.call_public_function(context.this_address(), 0xceffa31a, [on_behalf_of, to, amount]);
let selector = compute_selector("_borrow(Field,Field,Field)");
let _callStackItem = context.call_public_function(context.this_address(), selector, [on_behalf_of, to, amount]);
}

#[aztec(public)]
fn borrow_public(
to: Field,
amount: Field
) -> Field {
// _borrow(msg.sender, to, amount)
let return_values = context.call_public_function(context.this_address(), 0xceffa31a, [context.msg_sender(), to, amount]);
let selector = compute_selector("_borrow(Field,Field,Field)");
let return_values = context.call_public_function(context.this_address(), selector, [context.msg_sender(), to, amount]);

return_values[0]
}

// keccak256("_borrow(field,field,field)") >> 224 -> 0xceffa31a
#[aztec(public)]
internal fn _borrow(
owner: Field,
Expand Down Expand Up @@ -250,7 +250,8 @@ contract Lending {
) {
let on_behalf_of = compute_identifier(secret, on_behalf_of, context.msg_sender());
let _res = Token::at(stable_coin).unshield(&mut context, asset_owner, context.this_address(), amount);
let _callStackItem = context.call_public_function(context.this_address(), 0xfa94ab54, [on_behalf_of, amount, stable_coin]);
let selector = compute_selector("_repay(Field,Field,Field)");
let _callStackItem = context.call_public_function(context.this_address(), selector, [on_behalf_of, amount, stable_coin]);
}

#[aztec(public)]
Expand All @@ -261,12 +262,12 @@ contract Lending {
) -> Field {
// Should probably just burn the tokens actually :thinking:
Token::at(stable_coin).transfer_from_pub(context, context.msg_sender(), context.this_address(), amount);
let return_values = context.call_public_function(context.this_address(), 0xfa94ab54, [owner, amount, stable_coin]);
let selector = compute_selector("_repay(Field,Field,Field)");
let return_values = context.call_public_function(context.this_address(), selector, [owner, amount, stable_coin]);

return_values[0]
}

// keccak256("_repay(field,field,field)") >> 224 -> 0xfa94ab54
#[aztec(public)]
internal fn _repay(
owner: Field,
Expand Down
Loading

0 comments on commit c9c5369

Please sign in to comment.