Skip to content

Commit

Permalink
init
Browse files Browse the repository at this point in the history
  • Loading branch information
sklppy88 committed Oct 18, 2024
1 parent 5b8d888 commit 9424c07
Show file tree
Hide file tree
Showing 12 changed files with 165 additions and 48 deletions.
2 changes: 1 addition & 1 deletion noir-projects/aztec-nr/aztec/src/encrypted_logs/payload.nr
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ pub fn compute_encrypted_log<let P: u32, let M: u32>(

let header = EncryptedLogHeader::new(contract_address);

let incoming_header_ciphertext: [u8; 48] = header.compute_ciphertext(eph_sk, ivpk);
let incoming_header_ciphertext: [u8; 48] = header.compute_ciphertext(eph_sk, recipient);
let outgoing_header_ciphertext: [u8; 48] = header.compute_ciphertext(eph_sk, ovpk);
let incoming_body_ciphertext = compute_incoming_body_ciphertext(plaintext, eph_sk, ivpk);
let outgoing_body_ciphertext: [u8; 144] = compute_outgoing_body_ciphertext(recipient, ivpk, fr_to_fq(ovsk_app), eph_sk, eph_pk);
Expand Down
2 changes: 1 addition & 1 deletion noir-projects/aztec-nr/aztec/src/utils/point.nr
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use dep::protocol_types::point::Point;

// I am storing the modulus divided by 2 plus 1 here because full modulus would throw "String literal too large" error
// I am storing the modulus minus 1 divided by 2 here because full modulus would throw "String literal too large" error
// Full modulus is 21888242871839275222246405745257275088548364400416034343698204186575808495617
global BN254_FR_MODULUS_DIV_2: Field = 10944121435919637611123202872628637544274182200208017171849102093287904247808;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,25 @@ use crate::{
partial_address::PartialAddress, public_keys_hash::PublicKeysHash,
salted_initialization_hash::SaltedInitializationHash
},
constants::{AZTEC_ADDRESS_LENGTH, FUNCTION_TREE_HEIGHT, GENERATOR_INDEX__CONTRACT_ADDRESS_V1},
constants::{AZTEC_ADDRESS_LENGTH, FUNCTION_TREE_HEIGHT, GENERATOR_INDEX__PUBLIC_KEYS_HASH, GENERATOR_INDEX__CONTRACT_ADDRESS_V1},
contract_class_id::ContractClassId,
hash::{poseidon2_hash_with_separator, private_functions_root_from_siblings},
merkle_tree::membership::MembershipWitness,
traits::{Empty, FromField, ToField, Serialize, Deserialize}, utils
};

global BN254_FR_MODULUS_DIV_2: Field = 10944121435919637611123202872628637544274182200208017171849102093287904247808;

// We do below because `use crate::point::Point;` does not work
use dep::std::embedded_curve_ops::EmbeddedCurvePoint as Point;

use std::{
ec::{sqrt, pow},
embedded_curve_ops::{fixed_base_scalar_mul as derive_public_key, EmbeddedCurveScalar}
};
use crate::public_keys::ToPoint;
use crate::public_keys::PublicKeys;

// Aztec address
pub struct AztecAddress {
inner : Field
Expand Down Expand Up @@ -52,6 +64,31 @@ impl Deserialize<AZTEC_ADDRESS_LENGTH> for AztecAddress {
}
}

impl ToPoint for AztecAddress {
pub fn to_point(self) -> Point {
// Calculate y^2 = x^3 - 17
let y_squared = pow(self.inner, 3) - 17;

// We can see if y is square first, or we can soft fail with just sqrt(y_squared);
// If y is not square, the x-coordinate is not on the curve
// Do we throw here or soft continue ?
// let y_is_square = is_square(y_squared);
// assert(y_is_square);

let mut y = sqrt(y_squared);

// We can NOT do a check like the below. We do not have access to the sign, and this derivation produces "both" points
// assert(y.lt(BN254_FR_MODULUS_DIV_2) | y.eq(BN254_FR_MODULUS_DIV_2));

// If we get a negative y coordinate, we pin it to the positive one by subtracting it from the Field modulus
if (!(y.lt(BN254_FR_MODULUS_DIV_2) | y.eq(BN254_FR_MODULUS_DIV_2))) {
y = (BN254_FR_MODULUS_DIV_2 + BN254_FR_MODULUS_DIV_2 + 1) - y;
}

Point { x: self.inner, y, is_infinite: false }
}
}

impl AztecAddress {
pub fn zero() -> Self {
Self { inner: 0 }
Expand All @@ -66,6 +103,18 @@ impl AztecAddress {
)
}

pub fn compute_from_public_keys(public_keys: PublicKeys, partial_address: PartialAddress) -> AztecAddress {
let public_keys_hash = public_keys.hash();

let pre_address = poseidon2_hash_with_separator(
[public_keys_hash.to_field(), partial_address.to_field()],
GENERATOR_INDEX__CONTRACT_ADDRESS_V1
);

let address_point = derive_public_key(EmbeddedCurveScalar::from_field(pre_address)).add(public_keys.ivpk_m.to_point());
AztecAddress::from_field(address_point.x)
}

pub fn compute_from_private_function(
function_selector: FunctionSelector,
functino_vk_hash: Field,
Expand Down
40 changes: 16 additions & 24 deletions yarn-project/aztec.js/src/account_manager/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,26 +35,29 @@ export class AccountManager {
public readonly salt: Fr;

// TODO(@spalladino): Does it make sense to have both completeAddress and instance?
private completeAddress?: CompleteAddress;
private instance?: ContractInstanceWithAddress;
private publicKeys?: PublicKeys;
private completeAddress: CompleteAddress;
private instance: ContractInstanceWithAddress;

constructor(private pxe: PXE, private secretKey: Fr, private accountContract: AccountContract, salt?: Salt) {
this.salt = salt !== undefined ? new Fr(salt) : Fr.random();
}

protected getPublicKeysHash() {
if (!this.publicKeys) {
this.publicKeys = deriveKeys(this.secretKey).publicKeys;
}
return this.publicKeys.hash();
const { publicKeys } = deriveKeys(secretKey);

this.instance = getContractInstanceFromDeployParams(this.accountContract.getContractArtifact(), {
constructorArgs: this.accountContract.getDeploymentArgs(),
salt: this.salt,
publicKeys,
});

this.completeAddress = CompleteAddress.fromSecretKeyAndInstance(this.secretKey, this.instance);
}

protected getPublicKeys() {
if (!this.publicKeys) {
this.publicKeys = deriveKeys(this.secretKey).publicKeys;
}
return this.publicKeys;
return this.instance.publicKeys;
}

protected getPublicKeysHash() {
return this.getPublicKeys().hash();
}

/**
Expand All @@ -73,10 +76,6 @@ export class AccountManager {
* @returns The address, partial address, and encryption public key.
*/
public getCompleteAddress(): CompleteAddress {
if (!this.completeAddress) {
const instance = this.getInstance();
this.completeAddress = CompleteAddress.fromSecretKeyAndInstance(this.secretKey, instance);
}
return this.completeAddress;
}

Expand All @@ -95,13 +94,6 @@ export class AccountManager {
* @returns ContractInstance instance.
*/
public getInstance(): ContractInstanceWithAddress {
if (!this.instance) {
this.instance = getContractInstanceFromDeployParams(this.accountContract.getContractArtifact(), {
constructorArgs: this.accountContract.getDeploymentArgs(),
salt: this.salt,
publicKeys: this.getPublicKeys(),
});
}
return this.instance;
}

Expand Down
11 changes: 10 additions & 1 deletion yarn-project/circuits.js/src/contract/contract_address.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { Fr } from '@aztec/foundation/fields';

import { GeneratorIndex } from '../constants.gen.js';
import { computeVarArgsHash } from '../hash/hash.js';
import { computeAddress } from '../keys/index.js';
import { computeAddress, computeNewAddress } from '../keys/index.js';
import { type ContractInstance } from './interfaces/contract_instance.js';

// TODO(@spalladino): Review all generator indices in this file
Expand All @@ -29,6 +29,15 @@ export function computeContractAddressFromInstance(
return computeAddress(publicKeysHash, partialAddress);
}

export function computeContractAddressFromInstanceNew(
instance:
| ContractInstance
| ({ contractClassId: Fr; saltedInitializationHash: Fr } & Pick<ContractInstance, 'publicKeys'>),
): AztecAddress {
const partialAddress = computePartialAddress(instance);
return computeNewAddress(instance.publicKeys, partialAddress);
}

/**
* Computes the partial address defined as the hash of the contract class id and salted initialization hash.
* @param instance - Contract instance for which to calculate the partial address.
Expand Down
3 changes: 2 additions & 1 deletion yarn-project/circuits.js/src/contract/contract_instance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { computeContractClassId } from '../contract/contract_class_id.js';
import { PublicKeys } from '../types/public_keys.js';
import {
computeContractAddressFromInstance,
computeContractAddressFromInstanceNew,
computeInitializationHash,
computeInitializationHashFromEncodedArgs,
} from './contract_address.js';
Expand Down Expand Up @@ -133,7 +134,7 @@ export function getContractInstanceFromDeployParams(
version: 1,
};

return { ...instance, address: computeContractAddressFromInstance(instance) };
return { ...instance, address: computeContractAddressFromInstanceNew(instance) };
}

function getConstructorArtifact(
Expand Down
33 changes: 32 additions & 1 deletion yarn-project/circuits.js/src/keys/derivation.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { AztecAddress } from '@aztec/foundation/aztec-address';
import { poseidon2HashWithSeparator, sha512ToGrumpkinScalar } from '@aztec/foundation/crypto';
import { type Fq, type Fr, GrumpkinScalar } from '@aztec/foundation/fields';
import { Fq, Fr, GrumpkinScalar, type Point } from '@aztec/foundation/fields';

import { Grumpkin } from '../barretenberg/crypto/grumpkin/index.js';
import { GeneratorIndex } from '../constants.gen.js';
Expand Down Expand Up @@ -46,6 +46,37 @@ export function computeAddress(publicKeysHash: Fr, partialAddress: Fr) {
return AztecAddress.fromField(addressFr);
}

export function computeNewAddress(publicKeys: PublicKeys, partialAddress: Fr) {
const preaddress = poseidon2HashWithSeparator([publicKeys.hash(), partialAddress], GeneratorIndex.CONTRACT_ADDRESS_V1);
const address = computeAddressFromPreaddressAndIvpkM(preaddress, publicKeys.masterIncomingViewingPublicKey);

return address;
}

export function computeAddressFromPreaddressAndIvpkM(preaddress: Fr, ivpkM: Point) {
const addressPoint = computeAddressPointFromPreaddressAndIvpkM(preaddress, ivpkM);

return AztecAddress.fromField(addressPoint.x);
}

export function computeAddressPointFromPreaddressAndIvpkM(preaddress: Fr, ivpkM: Point) {
const preaddressPoint = derivePublicKeyFromSecretKey(new Fq(preaddress.toBigInt()));
const addressPoint = new Grumpkin().add(preaddressPoint, ivpkM);

return addressPoint;
}

export function computeAddressSecret(preaddress: Fr, ivsk: Fq) {
const addressSecretCandidate = ivsk.add(new Fq(preaddress.toBigInt()));
const addressPointCandidate = derivePublicKeyFromSecretKey(addressSecretCandidate);

if (!addressPointCandidate.y.lt(new Fr((Fr.MODULUS - 1n)/ 2n))) {
return new Fq(Fq.MODULUS - addressSecretCandidate.toBigInt());
}

return addressSecretCandidate;
}

export function derivePublicKeyFromSecretKey(secretKey: Fq) {
const curve = new Grumpkin();
return curve.mul(curve.generator(), secretKey);
Expand Down
28 changes: 21 additions & 7 deletions yarn-project/circuits.js/src/structs/complete_address.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { AztecAddress } from '@aztec/foundation/aztec-address';
import { Fr } from '@aztec/foundation/fields';
import { Fq, Fr } from '@aztec/foundation/fields';
import { BufferReader, serializeToBuffer } from '@aztec/foundation/serialize';

import { computePartialAddress } from '../contract/contract_address.js';
import { computeAddress, deriveKeys } from '../keys/index.js';
import { computeAddress, deriveKeys, derivePublicKeyFromSecretKey } from '../keys/index.js';
import { type PartialAddress } from '../types/partial_address.js';
import { PublicKeys } from '../types/public_keys.js';
import { Grumpkin } from '../barretenberg/index.js';

/**
* A complete address is a combination of an Aztec address, a public key and a partial address.
Expand Down Expand Up @@ -35,9 +36,18 @@ export class CompleteAddress {
}

static fromSecretKeyAndPartialAddress(secretKey: Fr, partialAddress: Fr): CompleteAddress {
const { publicKeys } = deriveKeys(secretKey);
const address = computeAddress(publicKeys.hash(), partialAddress);
return new CompleteAddress(address, publicKeys, partialAddress);
const { publicKeys, masterIncomingViewingSecretKey } = deriveKeys(secretKey);
const preaddress = computeAddress(publicKeys.hash(), partialAddress);

const combined = masterIncomingViewingSecretKey.add(new Fq(preaddress.toBigInt()));

const addressPoint = derivePublicKeyFromSecretKey(combined);

return new CompleteAddress(AztecAddress.fromField(addressPoint.x), publicKeys, partialAddress);
}

getPreAddress() {
return computeAddress(this.publicKeys.hash(), this.partialAddress);
}

static fromSecretKeyAndInstance(
Expand All @@ -50,8 +60,12 @@ export class CompleteAddress {

/** Throws if the address is not correctly derived from the public key and partial address.*/
public validate() {
const expectedAddress = computeAddress(this.publicKeys.hash(), this.partialAddress);
if (!expectedAddress.equals(this.address)) {
const expectedPreAddress = computeAddress(this.publicKeys.hash(), this.partialAddress);
const expectedPreAddressPoint = derivePublicKeyFromSecretKey(new Fq(expectedPreAddress.toBigInt()));

const expectedAddress = new Grumpkin().add(expectedPreAddressPoint, this.publicKeys.masterIncomingViewingPublicKey);

if (!AztecAddress.fromField(expectedAddress.x).equals(this.address)) {
throw new Error(
`Address cannot be derived from public keys and partial address (received ${this.address.toString()}, derived ${expectedAddress.toString()})`,
);
Expand Down
4 changes: 4 additions & 0 deletions yarn-project/foundation/src/fields/fields.ts
Original file line number Diff line number Diff line change
Expand Up @@ -381,6 +381,10 @@ export class Fq extends BaseField {
return new Fq((high.toBigInt() << Fq.HIGH_SHIFT) + low.toBigInt());
}

add(rhs: Fq) {
return new Fq((this.toBigInt() + rhs.toBigInt()) % Fq.MODULUS);
}

toJSON() {
return {
type: 'Fq',
Expand Down
22 changes: 19 additions & 3 deletions yarn-project/key-store/src/key_store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,8 @@ export class KeyStore {
publicKeys,
} = deriveKeys(sk);

const publicKeysHash = publicKeys.hash();
const account = computeAddress(publicKeysHash, partialAddress);
const completeAddress = CompleteAddress.fromSecretKeyAndPartialAddress(sk, partialAddress);
const { address: account } = completeAddress;

// Naming of keys is as follows ${account}-${n/iv/ov/t}${sk/pk}_m
await this.#keys.set(`${account.toString()}-ivsk_m`, masterIncomingViewingSecretKey.toBuffer());
Expand All @@ -82,7 +82,7 @@ export class KeyStore {
await this.#keys.set(`${account.toString()}-tpk_m_hash`, publicKeys.masterTaggingPublicKey.hash().toBuffer());

// At last, we return the newly derived account address
return Promise.resolve(new CompleteAddress(account, publicKeys, partialAddress));
return Promise.resolve(completeAddress);
}

/**
Expand Down Expand Up @@ -141,6 +141,22 @@ export class KeyStore {
return Promise.resolve(new KeyValidationRequest(pkM, skApp));
}

/**
* Gets the master nullifier public key for a given account.
* @throws If the account does not exist in the key store.
* @param account - The account address for which to retrieve the master nullifier public key.
* @returns The master nullifier public key for the account.
*/
public async getMasterNullifierPublicKey(account: AztecAddress): Promise<PublicKey> {
const masterNullifierPublicKeyBuffer = this.#keys.get(`${account.toString()}-npk_m`);
if (!masterNullifierPublicKeyBuffer) {
throw new Error(
`Account ${account.toString()} does not exist. Registered accounts: ${await this.getAccounts()}.`,
);
}
return Promise.resolve(Point.fromBuffer(masterNullifierPublicKeyBuffer));
}

/**
* Gets the master incoming viewing public key for a given account.
* @throws If the account does not exist in the key store.
Expand Down
5 changes: 3 additions & 2 deletions yarn-project/pxe/src/note_processor/note_processor.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { type AztecNode, L1NotePayload, type L2Block } from '@aztec/circuit-types';
import { type NoteProcessorStats } from '@aztec/circuit-types/stats';
import { type CompleteAddress, INITIAL_L2_BLOCK_NUM, MAX_NOTE_HASHES_PER_TX, type PublicKey } from '@aztec/circuits.js';
import { type CompleteAddress, computeAddressSecret, INITIAL_L2_BLOCK_NUM, MAX_NOTE_HASHES_PER_TX, type PublicKey } from '@aztec/circuits.js';
import { type Fr } from '@aztec/foundation/fields';
import { type Logger, createDebugLogger } from '@aztec/foundation/log';
import { Timer } from '@aztec/foundation/timer';
Expand Down Expand Up @@ -115,6 +115,7 @@ export class NoteProcessor {
const deferredOutgoingNotes: DeferredNoteDao[] = [];

const ivskM = await this.keyStore.getMasterSecretKey(this.ivpkM);
const addressSecret = computeAddressSecret(this.account.getPreAddress(), ivskM);
const ovskM = await this.keyStore.getMasterSecretKey(this.ovpkM);

// Iterate over both blocks and encrypted logs.
Expand Down Expand Up @@ -142,7 +143,7 @@ export class NoteProcessor {
for (const functionLogs of txFunctionLogs) {
for (const log of functionLogs.logs) {
this.stats.seen++;
const incomingNotePayload = L1NotePayload.decryptAsIncoming(log, ivskM);
const incomingNotePayload = L1NotePayload.decryptAsIncoming(log, addressSecret);
const outgoingNotePayload = L1NotePayload.decryptAsOutgoing(log, ovskM);

if (incomingNotePayload || outgoingNotePayload) {
Expand Down
Loading

0 comments on commit 9424c07

Please sign in to comment.