Skip to content

Commit

Permalink
WIP
Browse files Browse the repository at this point in the history
  • Loading branch information
benesjan committed Jan 24, 2024
1 parent 2e47e23 commit fef1fbd
Show file tree
Hide file tree
Showing 43 changed files with 456 additions and 535 deletions.
30 changes: 8 additions & 22 deletions yarn-project/acir-simulator/src/acvm/deserialize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
ContractStorageRead,
ContractStorageUpdateRequest,
FunctionSelector,
HEADER_LENGTH,
Header,
MAX_NEW_COMMITMENTS_PER_CALL,
MAX_NEW_L2_TO_L1_MSGS_PER_CALL,
Expand Down Expand Up @@ -190,16 +191,8 @@ export function extractPrivateCircuitPublicInputs(
const encryptedLogPreimagesLength = witnessReader.readField();
const unencryptedLogPreimagesLength = witnessReader.readField();

const blockHeader = new Header(
witnessReader.readField(),
witnessReader.readField(),
witnessReader.readField(),
witnessReader.readField(),
witnessReader.readField(),
Fr.ZERO, // TODO(#3441)
witnessReader.readField(),
witnessReader.readField(),
);
const headerBuf = Buffer.concat(witnessReader.readFieldArray(HEADER_LENGTH).map(field => field.toBuffer()));
const header = Header.fromBuffer(headerBuf);

const contractDeploymentData = new ContractDeploymentData(
new Point(witnessReader.readField(), witnessReader.readField()),
Expand Down Expand Up @@ -227,7 +220,7 @@ export function extractPrivateCircuitPublicInputs(
unencryptedLogsHash,
encryptedLogPreimagesLength,
unencryptedLogPreimagesLength,
blockHeader,
header,
contractDeploymentData,
chainId,
version,
Expand Down Expand Up @@ -282,16 +275,9 @@ export function extractPublicCircuitPublicInputs(partialWitness: ACVMWitness, ac
const unencryptedLogsHash = witnessReader.readFieldArray(NUM_FIELDS_PER_SHA256);
const unencryptedLogPreimagesLength = witnessReader.readField();

const blockHeader = new BlockHeader(
witnessReader.readField(),
witnessReader.readField(),
witnessReader.readField(),
witnessReader.readField(),
witnessReader.readField(),
Fr.ZERO, // TODO(#3441)
witnessReader.readField(),
witnessReader.readField(),
);
const headerBuf = Buffer.concat(witnessReader.readFieldArray(HEADER_LENGTH).map(field => field.toBuffer()));
const header = Header.fromBuffer(headerBuf);

const proverAddress = AztecAddress.fromField(witnessReader.readField());

return new PublicCircuitPublicInputs(
Expand All @@ -309,7 +295,7 @@ export function extractPublicCircuitPublicInputs(partialWitness: ACVMWitness, ac
newL2ToL1Msgs,
unencryptedLogsHash,
unencryptedLogPreimagesLength,
blockHeader,
header,
proverAddress,
);
}
9 changes: 5 additions & 4 deletions yarn-project/acir-simulator/src/acvm/oracle/oracle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { ACVMField } from '../acvm_types.js';
import { frToNumber, fromACVMField } from '../deserialize.js';
import {
toACVMField,
toACVMHeader,
toAcvmCallPrivateStackItem,
toAcvmEnqueuePublicFunctionResult,
toAcvmL1ToL2MessageLoadOracleInputs,
Expand Down Expand Up @@ -124,14 +125,14 @@ export class Oracle {
return witness.toFieldArray().map(toACVMField);
}

async getBlockHeader([blockNumber]: ACVMField[]): Promise<ACVMField[]> {
async getHeader([blockNumber]: ACVMField[]): Promise<ACVMField[]> {
const parsedBlockNumber = frToNumber(fromACVMField(blockNumber));

const blockHeader = await this.typedOracle.getBlockHeader(parsedBlockNumber);
if (!blockHeader) {
const header = await this.typedOracle.getHeader(parsedBlockNumber);
if (!header) {
throw new Error(`Block header not found for block ${parsedBlockNumber}.`);
}
return blockHeader.toArray().map(toACVMField);
return toACVMHeader(header);
}

// TODO(#3564) - Nuke this oracle and inject the number directly to context
Expand Down
4 changes: 2 additions & 2 deletions yarn-project/acir-simulator/src/acvm/oracle/typed_oracle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
PublicKey,
UnencryptedL2Log,
} from '@aztec/circuit-types';
import { BlockHeader, GrumpkinPrivateKey, PrivateCallStackItem, PublicCallRequest } from '@aztec/circuits.js';
import { GrumpkinPrivateKey, Header, PrivateCallStackItem, PublicCallRequest } from '@aztec/circuits.js';
import { FunctionSelector } from '@aztec/foundation/abi';
import { AztecAddress } from '@aztec/foundation/aztec-address';
import { EthAddress } from '@aztec/foundation/eth-address';
Expand Down Expand Up @@ -121,7 +121,7 @@ export abstract class TypedOracle {
throw new Error('Not available.');
}

getBlockHeader(_blockNumber: number): Promise<BlockHeader | undefined> {
getHeader(_blockNumber: number): Promise<Header | undefined> {
throw new Error('Not available.');
}

Expand Down
27 changes: 14 additions & 13 deletions yarn-project/acir-simulator/src/acvm/serialize.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import {
BlockHeader,
CallContext,
ContractDeploymentData,
FunctionData,
GlobalVariables,
Header,
PrivateCallStackItem,
PrivateCircuitPublicInputs,
PublicCallRequest,
Expand Down Expand Up @@ -103,19 +103,20 @@ export function toACVMContractDeploymentData(contractDeploymentData: ContractDep

/**
* Converts a block header into ACVM fields.
* @param blockHeader - The block header object to convert.
* @param header - The block header object to convert.
* @returns The ACVM fields.
*/
export function toACVMBlockHeader(blockHeader: BlockHeader): ACVMField[] {
return [
toACVMField(blockHeader.noteHashTreeRoot),
toACVMField(blockHeader.nullifierTreeRoot),
toACVMField(blockHeader.contractTreeRoot),
toACVMField(blockHeader.l1ToL2MessageTreeRoot),
toACVMField(blockHeader.archiveRoot),
toACVMField(blockHeader.publicDataTreeRoot),
toACVMField(blockHeader.globalVariablesHash),
];
export function toACVMHeader(header: Header): ACVMField[] {
return toACVMFields(header.toBuffer());
}

export function toACVMFields(buf: Buffer): ACVMField[] {
// Ensure the buffer is a multiple of 32 bytes
if (buf.length % 32 !== 0) {
throw new Error('Buffer length must be a multiple of 32 bytes');
}
const chunks = buf.toString('hex').match(/.{1,64}/g);
return chunks!.map(chunk => `0x${chunk}`);
}

/**
Expand Down Expand Up @@ -156,7 +157,7 @@ export function toACVMPublicInputs(publicInputs: PrivateCircuitPublicInputs): AC
toACVMField(publicInputs.encryptedLogPreimagesLength),
toACVMField(publicInputs.unencryptedLogPreimagesLength),

...toACVMBlockHeader(publicInputs.blockHeader),
...toACVMHeader(publicInputs.header),

...toACVMContractDeploymentData(publicInputs.contractDeploymentData),

Expand Down
16 changes: 8 additions & 8 deletions yarn-project/acir-simulator/src/avm/avm_state_manager.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { BlockHeader } from '@aztec/circuits.js';
import { Header } from '@aztec/circuits.js';

import { AvmJournal, HostStorage } from './journal/index.js';

Expand All @@ -8,29 +8,29 @@ import { AvmJournal, HostStorage } from './journal/index.js';
*/
export class AvmStateManager {
/** - */
public readonly blockHeader: BlockHeader;
public readonly header: Header;

/**
* Journal keeps track of pending state changes
*/
public readonly journal: AvmJournal;

constructor(blockHeader: BlockHeader, journal: AvmJournal) {
this.blockHeader = blockHeader;
constructor(Header: Header, journal: AvmJournal) {
this.header = Header;
this.journal = journal;
}

/**
* Create a base state root manager
* - this should be created by the highest level item where the state
* can be reverted
* @param blockHeader -
* @param header -
* @param hostStorage - An immutable view into the node db
* @returns Avm State Manager
*/
public static rootStateManager(blockHeader: BlockHeader, hostStorage: HostStorage): AvmStateManager {
public static rootStateManager(header: Header, hostStorage: HostStorage): AvmStateManager {
const journal = AvmJournal.rootJournal(hostStorage);
return new AvmStateManager(blockHeader, journal);
return new AvmStateManager(header, journal);
}

/**
Expand All @@ -40,6 +40,6 @@ export class AvmStateManager {
*/
public static forkStateManager(parent: AvmStateManager): AvmStateManager {
const journal = AvmJournal.branchParent(parent.journal);
return new AvmStateManager(parent.blockHeader, journal);
return new AvmStateManager(parent.header, journal);
}
}
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { AuthWitness, FunctionL2Logs, L1NotePayload, Note, UnencryptedL2Log } from '@aztec/circuit-types';
import {
BlockHeader,
CallContext,
ContractDeploymentData,
FunctionData,
FunctionSelector,
Header,
PublicCallRequest,
ReadRequestMembershipWitness,
SideEffect,
Expand All @@ -19,9 +19,9 @@ import { createDebugLogger } from '@aztec/foundation/log';

import {
NoteData,
toACVMBlockHeader,
toACVMCallContext,
toACVMContractDeploymentData,
toACVMHeader,
toACVMWitness,
} from '../acvm/index.js';
import { PackedArgsCache } from '../common/packed_args_cache.js';
Expand Down Expand Up @@ -65,7 +65,7 @@ export class ClientExecutionContext extends ViewDataOracle {
private readonly txContext: TxContext,
private readonly callContext: CallContext,
/** Data required to reconstruct the block hash, it contains historical roots. */
protected readonly blockHeader: BlockHeader,
protected readonly header: Header,
/** List of transient auth witnesses to be used during this simulation */
protected readonly authWitnesses: AuthWitness[],
private readonly packedArgsCache: PackedArgsCache,
Expand All @@ -74,7 +74,7 @@ export class ClientExecutionContext extends ViewDataOracle {
private readonly curve: Grumpkin,
protected log = createDebugLogger('aztec:simulator:client_execution_context'),
) {
super(contractAddress, blockHeader, authWitnesses, db, undefined, log);
super(contractAddress, header, authWitnesses, db, undefined, log);
}

// We still need this function until we can get user-defined ordering of structs for fn arguments
Expand All @@ -97,7 +97,7 @@ export class ClientExecutionContext extends ViewDataOracle {

const fields = [
...toACVMCallContext(this.callContext),
...toACVMBlockHeader(this.blockHeader),
...toACVMHeader(this.header),
...toACVMContractDeploymentData(contractDeploymentData),

this.txContext.chainId,
Expand Down Expand Up @@ -337,7 +337,7 @@ export class ClientExecutionContext extends ViewDataOracle {
argsHash,
derivedTxContext,
derivedCallContext,
this.blockHeader,
this.header,
this.authWitnesses,
this.packedArgsCache,
this.noteCache,
Expand Down
6 changes: 3 additions & 3 deletions yarn-project/acir-simulator/src/client/db_oracle.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { L2Block, MerkleTreeId, NullifierMembershipWitness, PublicDataWitness } from '@aztec/circuit-types';
import { BlockHeader, CompleteAddress } from '@aztec/circuits.js';
import { CompleteAddress, Header } from '@aztec/circuits.js';
import { FunctionArtifactWithDebugMetadata, FunctionSelector } from '@aztec/foundation/abi';
import { AztecAddress } from '@aztec/foundation/aztec-address';
import { EthAddress } from '@aztec/foundation/eth-address';
Expand Down Expand Up @@ -111,9 +111,9 @@ export interface DBOracle extends CommitmentsDB {
* Retrieve the databases view of the Block Header object.
* This structure is fed into the circuits simulator and is used to prove against certain historical roots.
*
* @returns A Promise that resolves to a BlockHeader object.
* @returns A Promise that resolves to a Header object.
*/
getBlockHeader(): Promise<BlockHeader>;
getHeader(): Promise<Header>;

/**
* Fetch the index of the leaf in the respective tree
Expand Down
10 changes: 5 additions & 5 deletions yarn-project/acir-simulator/src/client/private_execution.test.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { Note, PackedArguments, TxExecutionRequest } from '@aztec/circuit-types';
import {
BlockHeader,
CallContext,
CompleteAddress,
ContractDeploymentData,
FunctionData,
Header,
L1_TO_L2_MSG_TREE_HEIGHT,
MAX_NEW_COMMITMENTS_PER_CALL,
NOTE_HASH_TREE_HEIGHT,
Expand Down Expand Up @@ -68,7 +68,7 @@ describe('Private Execution test suite', () => {
let oracle: MockProxy<DBOracle>;
let acirSimulator: AcirSimulator;

let blockHeader = BlockHeader.empty();
let header = Header.empty();
let logger: DebugLogger;

const defaultContractAddress = AztecAddress.random();
Expand Down Expand Up @@ -144,10 +144,10 @@ describe('Private Execution test suite', () => {

// Update root.
const newRoot = trees[name].getRoot(false);
const prevRoots = blockHeader.toBuffer();
const prevRoots = header.toBuffer();
const rootIndex = name === 'noteHash' ? 0 : 32 * 3;
const newRoots = Buffer.concat([prevRoots.subarray(0, rootIndex), newRoot, prevRoots.subarray(rootIndex + 32)]);
blockHeader = BlockHeader.fromBuffer(newRoots);
header = Header.fromBuffer(newRoots);

return trees[name];
};
Expand Down Expand Up @@ -193,7 +193,7 @@ describe('Private Execution test suite', () => {
}
throw new Error(`Unknown address ${accountAddress}`);
});
oracle.getBlockHeader.mockResolvedValue(blockHeader);
oracle.getHeader.mockResolvedValue(header);

acirSimulator = new AcirSimulator(oracle);
});
Expand Down
8 changes: 4 additions & 4 deletions yarn-project/acir-simulator/src/client/simulator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ export class AcirSimulator {

const curve = new Grumpkin();

const blockHeader = await this.db.getBlockHeader();
const header = await this.db.getHeader();
const callContext = new CallContext(
msgSender,
contractAddress,
Expand All @@ -101,7 +101,7 @@ export class AcirSimulator {
request.argsHash,
request.txContext,
callContext,
blockHeader,
header,
request.authWitnesses,
PackedArgsCache.create(request.packedArguments),
new ExecutionNoteCache(),
Expand Down Expand Up @@ -139,8 +139,8 @@ export class AcirSimulator {
throw new Error(`Cannot run ${entryPointArtifact.functionType} function as constrained`);
}

const blockHeader = await this.db.getBlockHeader();
const context = new ViewDataOracle(contractAddress, blockHeader, [], this.db, aztecNode);
const header = await this.db.getHeader();
const context = new ViewDataOracle(contractAddress, header, [], this.db, aztecNode);

try {
return await executeUnconstrainedFunction(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { FunctionCall, Note } from '@aztec/circuit-types';
import { BlockHeader, CompleteAddress, FunctionData } from '@aztec/circuits.js';
import { CompleteAddress, FunctionData, Header } from '@aztec/circuits.js';
import { FunctionSelector, encodeArguments } from '@aztec/foundation/abi';
import { AztecAddress } from '@aztec/foundation/aztec-address';
import { Fr, GrumpkinScalar } from '@aztec/foundation/fields';
Expand Down Expand Up @@ -46,7 +46,7 @@ describe('Unconstrained Execution test suite', () => {

const notes: Note[] = [...Array(5).fill(buildNote(1n, owner)), ...Array(2).fill(buildNote(2n, owner))];

oracle.getBlockHeader.mockResolvedValue(BlockHeader.empty());
oracle.getHeader.mockResolvedValue(Header.empty());
oracle.getNotes.mockResolvedValue(
notes.map((note, index) => ({
contractAddress,
Expand Down
Loading

0 comments on commit fef1fbd

Please sign in to comment.