Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: contract class must be registered before deployment #10949

Merged
merged 25 commits into from
Jan 10, 2025
Merged
Show file tree
Hide file tree
Changes from 21 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -210,4 +210,9 @@ contract ContractClassRegisterer {
LogHash { value: log_hash, counter, length: 40 + (N as Field) * 32 },
);
}

#[private]
fn assert_class_id_is_registered(contract_class_id: ContractClassId) {
context.push_nullifier_read_request(contract_class_id.to_field());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ type = "contract"

[dependencies]
aztec = { path = "../../../aztec-nr/aztec" }
contract_class_registerer = { path = "../contract_class_registerer_contract" }
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,13 @@ contract ContractInstanceDeployer {
use dep::aztec::macros::{events::event, functions::private};
use dep::aztec::protocol_types::{
address::{AztecAddress, PartialAddress},
constants::DEPLOYER_CONTRACT_INSTANCE_DEPLOYED_MAGIC_VALUE,
constants::{DEPLOYER_CONTRACT_INSTANCE_DEPLOYED_MAGIC_VALUE, REGISTERER_CONTRACT_ADDRESS},
contract_class_id::ContractClassId,
public_keys::PublicKeys,
traits::Serialize,
utils::arrays::array_concat,
};
use dep::contract_class_registerer::ContractClassRegisterer;
use std::meta::derive;

#[derive(Serialize)]
Expand Down Expand Up @@ -85,7 +86,11 @@ contract ContractInstanceDeployer {
public_keys: PublicKeys,
universal_deploy: bool,
) {
// TODO(@spalladino): assert nullifier_exists silo(contract_class_id, ContractClassRegisterer)
// contract class must be registered to deploy an instance
ContractClassRegisterer::at(REGISTERER_CONTRACT_ADDRESS)
.assert_class_id_is_registered(contract_class_id)
.call(&mut context);

let deployer = if universal_deploy {
AztecAddress::zero()
} else {
Expand Down
14 changes: 12 additions & 2 deletions yarn-project/accounts/src/testing/create_account.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,23 @@ export async function createAccounts(

// Prepare deployments
const accountsAndDeployments = await Promise.all(
secrets.map(async secret => {
secrets.map(async (secret, index) => {
const signingKey = deriveSigningKey(secret);
const account = getSchnorrAccount(pxe, secret, signingKey);

// only register the contract class once
let skipClassRegistration = true;
if (index === 0) {
// for the first account, check if the contract class is already registered, otherwise we should register now
if (!(await pxe.isContractClassPubliclyRegistered(account.getInstance().contractClassId))) {
skipClassRegistration = false;
}
}

const deployMethod = await account.getDeployMethod();
const provenTx = await deployMethod.prove({
contractAddressSalt: account.salt,
skipClassRegistration: true,
skipClassRegistration,
skipPublicDeployment: true,
universalDeploy: true,
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { type TokenContract } from '@aztec/noir-contracts.js/Token';
import { TokenBlacklistContract } from '@aztec/noir-contracts.js/TokenBlacklist';

import { jest } from '@jest/globals';
import { strict as assert } from 'assert';

import {
type ISnapshotManager,
Expand Down Expand Up @@ -94,10 +95,20 @@ export class BlacklistTokenContractTest {
await this.snapshotManager.snapshot('3_accounts', addAccounts(3, this.logger), async ({ accountKeys }, { pxe }) => {
const accountManagers = accountKeys.map(ak => getSchnorrAccount(pxe, ak[0], ak[1], 1));
this.wallets = await Promise.all(accountManagers.map(a => a.getWallet()));
this.admin = this.wallets[0];
this.other = this.wallets[1];
this.blacklisted = this.wallets[2];
this.accounts = await pxe.getRegisteredAccounts();

// This Map and loop ensure that this.accounts has the same order as this.wallets and this.keys
const registeredAccounts: Map<string, CompleteAddress> = new Map(
(await pxe.getRegisteredAccounts()).map(acc => [acc.address.toString(), acc]),
);
for (let i = 0; i < this.wallets.length; i++) {
const wallet = this.wallets[i];
const walletAddr = wallet.getAddress().toString();
assert(
registeredAccounts.has(walletAddr),
`Test account ${walletAddr} not registered, but it should have been`,
);
this.accounts.push(registeredAccounts.get(walletAddr)!);
}
});

await this.snapshotManager.snapshot(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,15 @@ describe('e2e_deploy_contract deploy method', () => {

afterAll(() => t.teardown());

it('refused to deploy a contract instance whose contract class is not yet registered', async () => {
const owner = wallet.getAddress();
const opts = { skipClassRegistration: true };
logger.debug(`Trying to deploy contract instance without registering its contract class`);
await expect(StatefulTestContract.deploy(wallet, owner, owner, 42).send(opts).wait()).rejects.toThrow(
/Cannot find the leaf for nullifier/,
);
});

it('publicly deploys and initializes a contract', async () => {
const owner = wallet.getAddress();
logger.debug(`Deploying stateful test contract`);
Expand Down
16 changes: 15 additions & 1 deletion yarn-project/end-to-end/src/e2e_prover/e2e_prover_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import { type ProverNode, type ProverNodeConfig, createProverNode } from '@aztec
import { type PXEService } from '@aztec/pxe';
import { NoopTelemetryClient } from '@aztec/telemetry-client/noop';

import { strict as assert } from 'assert';
// TODO(#7373): Deploy honk solidity verifier
// @ts-expect-error solc-js doesn't publish its types https://github.com/ethereum/solc-js/issues/689
import solc from 'solc';
Expand Down Expand Up @@ -115,7 +116,20 @@ export class FullProverTest {
this.keys = accountKeys;
const accountManagers = accountKeys.map(ak => getSchnorrAccount(pxe, ak[0], ak[1], SALT));
this.wallets = await Promise.all(accountManagers.map(a => a.getWallet()));
this.accounts = await pxe.getRegisteredAccounts();

// This Map and loop ensure that this.accounts has the same order as this.wallets and this.keys
const registeredAccounts: Map<string, CompleteAddress> = new Map(
(await pxe.getRegisteredAccounts()).map(acc => [acc.address.toString(), acc]),
);
for (let i = 0; i < this.wallets.length; i++) {
const wallet = this.wallets[i];
const walletAddr = wallet.getAddress().toString();
assert(
registeredAccounts.has(walletAddr),
`Test account ${walletAddr} not registered, but it should have been`,
);
this.accounts.push(registeredAccounts.get(walletAddr)!);
}
this.wallets.forEach((w, i) => this.logger.verbose(`Wallet ${i} address: ${w.getAddress()}`));
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I had to do something like this instead of what I had done here dcb4cb4 because it is later assumed that this.wallets and this.accounts are in the same order as this.keys. @spalladino there are many places throughout our tests where we do this

this.wallets = await Promise.all(accountManagers.map(a => a.getWallet()));
this.accounts = await pxe.getRegisteredAccounts();

Even if all tests pass, I wouldn't be surprised if we run into issues/flakes down the line because of ordering mismatches in other tests. So, my questions are:

  1. Why did this just start happening now? I guess before this PR, pxe.getRegisteredAccounts() was always matching the order of the account keys as returned from addAccounts. It's not clear to me why pxe.getRegisteredAccounts() order would no longer match after my changeset.
  2. Should something change in the PXE/elsewhere to make sure that these orders match? Or should I just create a test helper function for this?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

moved it into a helper for now

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can't think of a reason why this is happening now. But I think the easiest thing is to not get the registered accounts from the pxe but from the account managers themselves, so we ensure the order is the same. WDYT?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll try that!

});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { DocsExampleContract } from '@aztec/noir-contracts.js/DocsExample';
import { TokenContract } from '@aztec/noir-contracts.js/Token';

import { jest } from '@jest/globals';
import { strict as assert } from 'assert';

import {
type ISnapshotManager,
Expand Down Expand Up @@ -48,7 +49,20 @@ export class TokenContractTest {
await this.snapshotManager.snapshot('3_accounts', addAccounts(3, this.logger), async ({ accountKeys }, { pxe }) => {
const accountManagers = accountKeys.map(ak => getSchnorrAccount(pxe, ak[0], ak[1], 1));
this.wallets = await Promise.all(accountManagers.map(a => a.getWallet()));
this.accounts = await pxe.getRegisteredAccounts();

// This Map and loop ensure that this.accounts has the same order as this.wallets and this.keys
const registeredAccounts: Map<string, CompleteAddress> = new Map(
(await pxe.getRegisteredAccounts()).map(acc => [acc.address.toString(), acc]),
);
for (let i = 0; i < this.wallets.length; i++) {
const wallet = this.wallets[i];
const walletAddr = wallet.getAddress().toString();
assert(
registeredAccounts.has(walletAddr),
`Test account ${walletAddr} not registered, but it should have been`,
);
this.accounts.push(registeredAccounts.get(walletAddr)!);
}
});

await this.snapshotManager.snapshot(
Expand Down
32 changes: 25 additions & 7 deletions yarn-project/end-to-end/src/fixtures/snapshot_manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,12 @@ import {
type CompleteAddress,
type DeployL1Contracts,
Fr,
type FunctionCall,
GrumpkinScalar,
type Logger,
type PXE,
type Wallet,
getContractClassFromArtifact,
} from '@aztec/aztec.js';
import { deployInstance, registerContractClass } from '@aztec/aztec.js/deployment';
import { type BlobSinkServer, createBlobSinkServer } from '@aztec/blob-sink/server';
Expand Down Expand Up @@ -550,13 +552,22 @@ export const addAccounts =

logger.verbose('Simulating account deployment...');
const provenTxs = await Promise.all(
accountKeys.map(async ([secretKey, signPk]) => {
accountKeys.map(async ([secretKey, signPk], index) => {
const account = getSchnorrAccount(pxe, secretKey, signPk, 1);
const deployMethod = await account.getDeployMethod();

// only register the contract class once
let skipClassRegistration = true;
if (index === 0) {
// for the first account, check if the contract class is already registered, otherwise we should register now
if (!(await pxe.isContractClassPubliclyRegistered(account.getInstance().contractClassId))) {
skipClassRegistration = false;
}
}

const deployMethod = await account.getDeployMethod();
const provenTx = await deployMethod.prove({
contractAddressSalt: account.salt,
skipClassRegistration: true,
skipClassRegistration,
skipPublicDeployment: true,
universalDeploy: true,
});
Expand Down Expand Up @@ -589,9 +600,16 @@ export async function publicDeployAccounts(
) {
const accountAddressesToDeploy = accountsToDeploy.map(a => ('address' in a ? a.address : a));
const instances = await Promise.all(accountAddressesToDeploy.map(account => sender.getContractInstance(account)));
const batch = new BatchCall(sender, [
(await registerContractClass(sender, SchnorrAccountContractArtifact)).request(),
...instances.map(instance => deployInstance(sender, instance!).request()),
]);

const contractClass = getContractClassFromArtifact(SchnorrAccountContractArtifact);
const alreadyRegistered = await sender.isContractClassPubliclyRegistered(contractClass.id);

const calls: FunctionCall[] = [];
if (!alreadyRegistered) {
calls.push((await registerContractClass(sender, SchnorrAccountContractArtifact)).request());
}
calls.push(...instances.map(instance => deployInstance(sender, instance!).request()));

const batch = new BatchCall(sender, calls);
Comment on lines -592 to +613
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't batch a call to register the class if it is already registered

await batch.send().wait({ proven: waitUntilProven });
}
Loading