Skip to content

Commit

Permalink
refactor: representing TxHash as Fr (#10954)
Browse files Browse the repository at this point in the history
  • Loading branch information
benesjan authored Jan 6, 2025
1 parent f35094f commit 84e67ac
Show file tree
Hide file tree
Showing 40 changed files with 144 additions and 104 deletions.
1 change: 1 addition & 0 deletions cspell.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"auditability",
"authwit",
"authwits",
"authwitness",
"Automine",
"autonat",
"autorun",
Expand Down
2 changes: 1 addition & 1 deletion l1-contracts/src/core/libraries/RollupLibs/ProposeLib.sol
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,6 @@ struct ProposeArgs {

library ProposeLib {
function digest(ProposeArgs memory _args) internal pure returns (bytes32) {
return keccak256(abi.encode(SignatureLib.SignatureDomainSeperator.blockAttestation, _args));
return keccak256(abi.encode(SignatureLib.SignatureDomainSeparator.blockAttestation, _args));
}
}
4 changes: 2 additions & 2 deletions l1-contracts/src/core/libraries/crypto/SignatureLib.sol
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ struct Signature {

library SignatureLib {
/**
* @notice The domain seperator for the signatures
* @notice The domain separator for the signatures
*/
enum SignatureDomainSeperator {
enum SignatureDomainSeparator {
blockProposal,
blockAttestation
}
Expand Down
2 changes: 1 addition & 1 deletion noir-projects/aztec-nr/aztec/src/keys/secret_derivation.nr
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ pub fn derive_aes_secret(secret: Scalar, point: Point) -> [u8; 32] {
}

shared_secret_bytes_with_separator[32] = GENERATOR_INDEX__SYMMETRIC_KEY;

// TODO(https://github.com/AztecProtocol/aztec-packages/issues/10537): Replace use of sha256
sha256(shared_secret_bytes_with_separator)
}

Expand Down
4 changes: 2 additions & 2 deletions noir-projects/aztec-nr/aztec/src/macros/notes/mod.nr
Original file line number Diff line number Diff line change
Expand Up @@ -441,7 +441,7 @@ comptime fn generate_setup_payload(
+ 2 /* log_plaintext_length */
+ 14 /* AES padding */;
// Each field contains 31 bytes so the length in fields is computed as ceil(encrypted_log_byte_length / 31)
// --> we achieve rouding by adding 30 and then dividing without remainder
// --> we achieve rounding by adding 30 and then dividing without remainder
let encrypted_log_field_length = (encrypted_log_byte_length + 30) / 31;

(
Expand Down Expand Up @@ -661,7 +661,7 @@ comptime fn generate_finalization_payload(
+ 2 /* log_plaintext_length */
+ 14 /* AES padding */;
// Each field contains 31 bytes so the length in fields is computed as ceil(setup_log_byte_length / 31)
// --> we achieve rouding by adding 30 and then dividing without remainder
// --> we achieve rounding by adding 30 and then dividing without remainder
let setup_log_field_length = (setup_log_byte_length + 30) / 31;
let public_values_field_length = public_values_length * 32;
let finalization_log_byte_length =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@ contract AMM {
let sender = context.msg_sender();

// Liquidity tokens are burned when liquidity is removed in order to reduce the total supply. However, we lack
// a function to privately burn, so we instead transfer the tokens into the AMM's public balance, and them have
// a function to privately burn, so we instead transfer the tokens into the AMM's public balance, and then have
// the AMM publicly burn its own tokens.
// TODO(#10287): consider adding a private burn
liquidity_token.transfer_to_public(sender, context.this_address(), liquidity, nonce).call(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,6 @@ contract TokenBridge {
/// Claims the bridged tokens and makes them accessible in private. Note that recipient's address is not revealed
/// but the amount is. Hence it's most likely possible to determine to which L1 deposit this claim corresponds to
/// (unless there are multiple pending deposits of the same amount).
/// TODO(#8416): Consider creating a truly private claim flow.
#[private]
fn claim_private(
recipient: AztecAddress, // recipient of the bridged tokens
Expand Down
3 changes: 2 additions & 1 deletion noir-projects/noir-protocol-circuits/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ Verifier.toml
target
crates/autogenerated
/Nargo.toml
/private_kernel_reset_dimensions.json
/private_kernel_reset_dimensions.json
install-state.gz
Binary file not shown.
3 changes: 2 additions & 1 deletion noir-projects/noir-protocol-circuits/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,6 @@
"main": "index.js",
"dependencies": {
"@iarna/toml": "^2.2.5"
}
},
"packageManager": "yarn@4.5.2+sha512.570504f67349ef26d2d86a768dc5ec976ead977aa086b0bb4237e97d5db7ae5c620f9f0e0edf3ea5047205063faff102bf2a2d778664a94eaaa1085ad483fe2e"
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import {
makeUnconstrainedFunctionWithMembershipProof,
} from '@aztec/circuits.js/testing';
import { times } from '@aztec/foundation/collection';
import { randomBytes, randomInt } from '@aztec/foundation/crypto';
import { randomInt } from '@aztec/foundation/crypto';

import { type ArchiverDataStore, type ArchiverL1SynchPoint } from './archiver_store.js';
import { type L1Published } from './structs/published.js';
Expand Down Expand Up @@ -223,7 +223,7 @@ export function describeArchiverDataStore(testName: string, getStore: () => Arch
});

it('returns undefined if tx is not found', async () => {
await expect(store.getTxEffect(new TxHash(Fr.random().toBuffer()))).resolves.toBeUndefined();
await expect(store.getTxEffect(TxHash.random())).resolves.toBeUndefined();
});

it.each([
Expand All @@ -241,7 +241,7 @@ export function describeArchiverDataStore(testName: string, getStore: () => Arch
});

it('returns undefined if tx is not found', async () => {
await expect(store.getTxEffect(new TxHash(Fr.random().toBuffer()))).resolves.toBeUndefined();
await expect(store.getTxEffect(TxHash.random())).resolves.toBeUndefined();
});
});

Expand Down Expand Up @@ -645,7 +645,7 @@ export function describeArchiverDataStore(testName: string, getStore: () => Arch

it('"txHash" filter param is ignored when "afterLog" is set', async () => {
// Get random txHash
const txHash = new TxHash(randomBytes(TxHash.SIZE));
const txHash = TxHash.random();
const afterLog = new LogId(1, 0, 0);

const response = await store.getUnencryptedLogs({ txHash, afterLog });
Expand Down
3 changes: 2 additions & 1 deletion yarn-project/aztec.js/src/contract/sent_tx.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { type PXE, TxHash, type TxReceipt, TxStatus } from '@aztec/circuit-types';
import { Fr } from '@aztec/circuits.js';

import { type MockProxy, mock } from 'jest-mock-extended';

Expand All @@ -12,7 +13,7 @@ describe('SentTx', () => {

beforeEach(() => {
pxe = mock();
txHashPromise = Promise.resolve(TxHash.fromBigInt(1n));
txHashPromise = Promise.resolve(new TxHash(new Fr(1n)));
sentTx = new SentTx(pxe, txHashPromise);
});

Expand Down
1 change: 1 addition & 0 deletions yarn-project/aztec/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"build": "yarn clean && tsc -b",
"start": "node --no-warnings ./dest/bin",
"start:debug": "node --inspect=0.0.0.0:9221 --no-warnings ./dest/bin",
"start:sandbox": "ETHEREUM_HOST=http://0.0.0.0:8545/ && yarn start start --sandbox",
"clean": "rm -rf ./dest .tsbuildinfo",
"formatting": "run -T prettier --check ./src && run -T eslint ./src",
"formatting:fix": "run -T eslint --fix ./src && run -T prettier -w ./src",
Expand Down
4 changes: 2 additions & 2 deletions yarn-project/circuit-types/src/interfaces/archiver.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,12 +100,12 @@ describe('ArchiverApiSchema', () => {
});

it('getTxEffect', async () => {
const result = await context.client.getTxEffect(new TxHash(Buffer.alloc(32, 1)));
const result = await context.client.getTxEffect(TxHash.fromBuffer(Buffer.alloc(32, 1)));
expect(result!.data).toBeInstanceOf(TxEffect);
});

it('getSettledTxReceipt', async () => {
const result = await context.client.getSettledTxReceipt(new TxHash(Buffer.alloc(32, 1)));
const result = await context.client.getSettledTxReceipt(TxHash.fromBuffer(Buffer.alloc(32, 1)));
expect(result).toBeInstanceOf(TxReceipt);
});

Expand Down
2 changes: 1 addition & 1 deletion yarn-project/circuit-types/src/logs/get_logs_response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ export class TxScopedL2Log {
static fromBuffer(buffer: Buffer) {
const reader = BufferReader.asReader(buffer);
return new TxScopedL2Log(
TxHash.fromField(reader.readObject(Fr)),
reader.readObject(TxHash),
reader.readNumber(),
reader.readNumber(),
reader.readBoolean(),
Expand Down
2 changes: 1 addition & 1 deletion yarn-project/circuit-types/src/mocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ import { PublicExecutionRequest } from './public_execution_request.js';
import { PublicSimulationOutput, Tx, TxHash, TxSimulationResult, accumulatePrivateReturnValues } from './tx/index.js';
import { TxEffect } from './tx_effect.js';

export const randomTxHash = (): TxHash => new TxHash(randomBytes(32));
export const randomTxHash = (): TxHash => TxHash.random();

export const mockPrivateExecutionResult = (
seed = 1,
Expand Down
54 changes: 27 additions & 27 deletions yarn-project/circuit-types/src/notes/extended_note.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { AztecAddress, Fr } from '@aztec/circuits.js';
import { NoteSelector } from '@aztec/foundation/abi';
import { schemas } from '@aztec/foundation/schemas';
import { BufferReader } from '@aztec/foundation/serialize';
import { BufferReader, serializeToBuffer } from '@aztec/foundation/serialize';
import { bufferToHex, hexToBuffer } from '@aztec/foundation/string';

import { z } from 'zod';
Expand Down Expand Up @@ -29,25 +29,25 @@ export class ExtendedNote {
) {}

toBuffer(): Buffer {
return Buffer.concat([
this.note.toBuffer(),
this.owner.toBuffer(),
this.contractAddress.toBuffer(),
this.storageSlot.toBuffer(),
this.noteTypeId.toBuffer(),
this.txHash.buffer,
return serializeToBuffer([
this.note,
this.owner,
this.contractAddress,
this.storageSlot,
this.noteTypeId,
this.txHash,
]);
}

static fromBuffer(buffer: Buffer | BufferReader) {
const reader = BufferReader.asReader(buffer);

const note = Note.fromBuffer(reader);
const owner = AztecAddress.fromBuffer(reader);
const contractAddress = AztecAddress.fromBuffer(reader);
const storageSlot = Fr.fromBuffer(reader);
const note = reader.readObject(Note);
const owner = reader.readObject(AztecAddress);
const contractAddress = reader.readObject(AztecAddress);
const storageSlot = reader.readObject(Fr);
const noteTypeId = reader.readObject(NoteSelector);
const txHash = new TxHash(reader.readBytes(TxHash.SIZE));
const txHash = reader.readObject(TxHash);

return new this(note, owner, contractAddress, storageSlot, noteTypeId, txHash);
}
Expand Down Expand Up @@ -124,14 +124,14 @@ export class UniqueNote extends ExtendedNote {
}

override toBuffer(): Buffer {
return Buffer.concat([
this.note.toBuffer(),
this.owner.toBuffer(),
this.contractAddress.toBuffer(),
this.storageSlot.toBuffer(),
this.noteTypeId.toBuffer(),
this.txHash.buffer,
this.nonce.toBuffer(),
return serializeToBuffer([
this.note,
this.owner,
this.contractAddress,
this.storageSlot,
this.noteTypeId,
this.txHash,
this.nonce,
]);
}

Expand All @@ -150,13 +150,13 @@ export class UniqueNote extends ExtendedNote {
static override fromBuffer(buffer: Buffer | BufferReader) {
const reader = BufferReader.asReader(buffer);

const note = Note.fromBuffer(reader);
const owner = AztecAddress.fromBuffer(reader);
const contractAddress = AztecAddress.fromBuffer(reader);
const storageSlot = Fr.fromBuffer(reader);
const note = reader.readObject(Note);
const owner = reader.readObject(AztecAddress);
const contractAddress = reader.readObject(AztecAddress);
const storageSlot = reader.readObject(Fr);
const noteTypeId = reader.readObject(NoteSelector);
const txHash = new TxHash(reader.readBytes(TxHash.SIZE));
const nonce = Fr.fromBuffer(reader);
const txHash = reader.readObject(TxHash);
const nonce = reader.readObject(Fr);

return new this(note, owner, contractAddress, storageSlot, noteTypeId, txHash, nonce);
}
Expand Down
6 changes: 3 additions & 3 deletions yarn-project/circuit-types/src/p2p/block_attestation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { z } from 'zod';

import { ConsensusPayload } from './consensus_payload.js';
import { Gossipable } from './gossipable.js';
import { SignatureDomainSeperator, getHashedSignaturePayloadEthSignedMessage } from './signature_utils.js';
import { SignatureDomainSeparator, getHashedSignaturePayloadEthSignedMessage } from './signature_utils.js';
import { TopicType, createTopicString } from './topic_type.js';

export class BlockAttestationHash extends Buffer32 {
Expand Down Expand Up @@ -65,7 +65,7 @@ export class BlockAttestation extends Gossipable {
getSender() {
if (!this.sender) {
// Recover the sender from the attestation
const hashed = getHashedSignaturePayloadEthSignedMessage(this.payload, SignatureDomainSeperator.blockAttestation);
const hashed = getHashedSignaturePayloadEthSignedMessage(this.payload, SignatureDomainSeparator.blockAttestation);
// Cache the sender for later use
this.sender = recoverAddress(hashed, this.signature);
}
Expand All @@ -74,7 +74,7 @@ export class BlockAttestation extends Gossipable {
}

getPayload(): Buffer {
return this.payload.getPayloadToSign(SignatureDomainSeperator.blockAttestation);
return this.payload.getPayloadToSign(SignatureDomainSeparator.blockAttestation);
}

toBuffer(): Buffer {
Expand Down
8 changes: 4 additions & 4 deletions yarn-project/circuit-types/src/p2p/block_proposal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { BufferReader, serializeToBuffer } from '@aztec/foundation/serialize';
import { ConsensusPayload } from './consensus_payload.js';
import { Gossipable } from './gossipable.js';
import {
SignatureDomainSeperator,
SignatureDomainSeparator,
getHashedSignaturePayload,
getHashedSignaturePayloadEthSignedMessage,
} from './signature_utils.js';
Expand Down Expand Up @@ -57,7 +57,7 @@ export class BlockProposal extends Gossipable {
payload: ConsensusPayload,
payloadSigner: (payload: Buffer32) => Promise<Signature>,
) {
const hashed = getHashedSignaturePayload(payload, SignatureDomainSeperator.blockProposal);
const hashed = getHashedSignaturePayload(payload, SignatureDomainSeparator.blockProposal);
const sig = await payloadSigner(hashed);

return new BlockProposal(payload, sig);
Expand All @@ -68,7 +68,7 @@ export class BlockProposal extends Gossipable {
*/
getSender() {
if (!this.sender) {
const hashed = getHashedSignaturePayloadEthSignedMessage(this.payload, SignatureDomainSeperator.blockProposal);
const hashed = getHashedSignaturePayloadEthSignedMessage(this.payload, SignatureDomainSeparator.blockProposal);
// Cache the sender for later use
this.sender = recoverAddress(hashed, this.signature);
}
Expand All @@ -77,7 +77,7 @@ export class BlockProposal extends Gossipable {
}

getPayload() {
return this.payload.getPayloadToSign(SignatureDomainSeperator.blockProposal);
return this.payload.getPayloadToSign(SignatureDomainSeparator.blockProposal);
}

toBuffer(): Buffer {
Expand Down
6 changes: 3 additions & 3 deletions yarn-project/circuit-types/src/p2p/consensus_payload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { encodeAbiParameters, parseAbiParameters } from 'viem';
import { z } from 'zod';

import { TxHash } from '../tx/tx_hash.js';
import { type Signable, type SignatureDomainSeperator } from './signature_utils.js';
import { type Signable, type SignatureDomainSeparator } from './signature_utils.js';

export class ConsensusPayload implements Signable {
private size: number | undefined;
Expand Down Expand Up @@ -36,11 +36,11 @@ export class ConsensusPayload implements Signable {
return [fields.header, fields.archive, fields.txHashes] as const;
}

getPayloadToSign(domainSeperator: SignatureDomainSeperator): Buffer {
getPayloadToSign(domainSeparator: SignatureDomainSeparator): Buffer {
const abi = parseAbiParameters('uint8, (bytes32, bytes32, (uint256, uint256), bytes, bytes32[])');
const txArray = this.txHashes.map(tx => tx.toString());
const encodedData = encodeAbiParameters(abi, [
domainSeperator,
domainSeparator,
[
this.archive.toString(),
this.header.hash().toString(),
Expand Down
10 changes: 5 additions & 5 deletions yarn-project/circuit-types/src/p2p/mocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { TxHash } from '../tx/tx_hash.js';
import { BlockAttestation } from './block_attestation.js';
import { BlockProposal } from './block_proposal.js';
import { ConsensusPayload } from './consensus_payload.js';
import { SignatureDomainSeperator, getHashedSignaturePayloadEthSignedMessage } from './signature_utils.js';
import { SignatureDomainSeparator, getHashedSignaturePayloadEthSignedMessage } from './signature_utils.js';

export interface MakeConsensusPayloadOptions {
signer?: Secp256k1Signer;
Expand All @@ -17,7 +17,7 @@ export interface MakeConsensusPayloadOptions {
}

const makeAndSignConsensusPayload = (
domainSeperator: SignatureDomainSeperator,
domainSeparator: SignatureDomainSeparator,
options?: MakeConsensusPayloadOptions,
) => {
const {
Expand All @@ -33,19 +33,19 @@ const makeAndSignConsensusPayload = (
txHashes,
});

const hash = getHashedSignaturePayloadEthSignedMessage(payload, domainSeperator);
const hash = getHashedSignaturePayloadEthSignedMessage(payload, domainSeparator);
const signature = signer.sign(hash);

return { payload, signature };
};

export const makeBlockProposal = (options?: MakeConsensusPayloadOptions): BlockProposal => {
const { payload, signature } = makeAndSignConsensusPayload(SignatureDomainSeperator.blockProposal, options);
const { payload, signature } = makeAndSignConsensusPayload(SignatureDomainSeparator.blockProposal, options);
return new BlockProposal(payload, signature);
};

// TODO(https://github.com/AztecProtocol/aztec-packages/issues/8028)
export const makeBlockAttestation = (options?: MakeConsensusPayloadOptions): BlockAttestation => {
const { payload, signature } = makeAndSignConsensusPayload(SignatureDomainSeperator.blockAttestation, options);
const { payload, signature } = makeAndSignConsensusPayload(SignatureDomainSeparator.blockAttestation, options);
return new BlockAttestation(payload, signature);
};
Loading

0 comments on commit 84e67ac

Please sign in to comment.