-
Notifications
You must be signed in to change notification settings - Fork 837
evm: add "count leading zeros" opcode example #4176
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
Merged
+73
−1
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
8ceb678
evm: add clz example script
cb41cc8
fix case description
6fb25ac
Add context to example
be35679
improve log output
d971432
rename file and move to opcodes subfolder
e2a793c
update examples runner script
d6fd7f3
make example logging style match other examples
02ecb92
Some systematic for renaming to stay a bit more future proof
holgerd77 9d4f4ef
Another small example name adjustment
holgerd77 58f5aee
Some small optimizations
holgerd77 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
72 changes: 72 additions & 0 deletions
72
packages/evm/examples/opcodes/0x1e-CLZ-count-leading-zeros.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,72 @@ | ||
| import { Common, Hardfork, Mainnet } from '@ethereumjs/common' | ||
| import { type EVM, createEVM } from '@ethereumjs/evm' | ||
| import { type PrefixedHexString, hexToBytes } from '@ethereumjs/util' | ||
|
|
||
| // CLZ (Count Leading Zeros) opcode (0x1e) | ||
| // Demonstrates the CLZ opcode introduced in https://eips.ethereum.org/EIPS/eip-7939 | ||
| // | ||
| // The CLZ opcode returns the number of zero bits before the most significant 1-bit in a 256-bit value. | ||
| // It enables efficient computation of bit length, log₂, and prefix comparisons directly in the EVM. | ||
| // | ||
| // Doing this in Solidity/Yul requires a loop or binary search using shifts and comparisons, | ||
| // which costs hundreds of gas and bloats bytecode. By replacing multi-step shift and branch logic | ||
| // with a single instruction, it reduces gas cost, bytecode size, and zk-proof complexity. | ||
|
|
||
| const common = new Common({ | ||
ScottyPoi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| chain: Mainnet, | ||
| hardfork: Hardfork.Osaka, | ||
| }) | ||
|
|
||
| const assembleCode = (x: Uint8Array) => { | ||
| if (x.length !== 32) { | ||
| throw new Error('x must be 32 bytes') | ||
| } | ||
|
|
||
| const code = new Uint8Array(35) // PUSH32 + 32-byte operand + CLZ + STOP | ||
| code[0] = 0x7f | ||
| code.set(x, 1) | ||
| code[33] = 0x1e | ||
| code[34] = 0x00 | ||
| return code | ||
| } | ||
|
|
||
| const runCase = async (evm: EVM, x: PrefixedHexString) => { | ||
| const code = assembleCode(hexToBytes(x)) | ||
|
|
||
| const res = await evm.runCode({ code }) | ||
|
|
||
| const stack = res.runState?.stack | ||
| if (!stack) { | ||
| throw new Error('Missing runState stack in result') | ||
| } | ||
|
|
||
| const [top] = stack.peek(1) | ||
| const hexValue = `0x${top.toString(16)}` | ||
| const gas = res.executionGasUsed | ||
| console.log('--------------------------------') | ||
| console.log(`input=${x}`) | ||
| console.log(`output=${hexValue} (leading zeros=${top})`) | ||
| console.log(`Gas used: ${gas}`) | ||
| } | ||
|
|
||
| const main = async () => { | ||
| const evm = await createEVM({ common }) | ||
|
|
||
| // Case 1: x == 0x00..00 -> expect 256 | ||
| await runCase(evm, `0x${'00'.repeat(32)}` as PrefixedHexString) | ||
|
|
||
| // Case 2: x == 0x0..01 -> MSB at bit 0 -> expect 255 | ||
| await runCase(evm, `0x${'00'.repeat(31)}01` as PrefixedHexString) | ||
|
|
||
| // Case 3: x == 0x40..00 -> MSB at bit 254 -> expect 1 | ||
| await runCase(evm, `0x40${'00'.repeat(31)}` as PrefixedHexString) | ||
|
|
||
| // Case 4: x == 0x80..00 -> MSB at bit 255 -> expect 0 | ||
| await runCase(evm, `0x80${'00'.repeat(31)}` as PrefixedHexString) | ||
| console.log('--------------------------------') | ||
| } | ||
|
|
||
| void main().catch((err) => { | ||
| console.error(err) | ||
| process.exitCode = 1 | ||
| }) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can we make the name of this file more expressive, so that people can spot what the example is about?
(clz might be in the head of people now, but will be forgotten soon).
So that would be
clz-opcode.tsor so.(simple solution)
I you want to go a little extra mile I would also be a fan of the a bit extended version, which would be to keep the name but do a subfolder
opcodes(likeprecompiles).I prepared for that to be possible (in the sense that the examples still run), this would need a slight addition to the
package.jsonexamplesscript (should be obvious).