17 Commits
Author SHA1 Message Date
navelbuffle 39de432af4 completed positive unit test coverage for available bool opcodes 2025-01-05 08:46:39 +03:00
navelbuffle c86111206f implemented and tested majority of bool opcodes 2025-01-05 04:28:48 +03:00
navelbuffle 818f702b32 basic bool operations implementation 2025-01-04 19:33:28 +03:00
navelbuffle dfb7b933cc more clear offset values 2025-01-04 19:09:34 +03:00
navelbuffle 2e214f95d3 fix adapter unit tests 2025-01-04 17:59:31 +03:00
navelbuffle 18063377fb fix interpeter unit tests 2025-01-04 17:54:07 +03:00
navelbuffle 79c8b3bd6d add bool stack into adapter 2025-01-04 16:27:21 +03:00
navelbuffle e220ff39fc add bool stack return and fix adapter 2025-01-04 16:20:00 +03:00
navelbuffle 7f259c8a07 fix opcode offsets in runInterpreter 2025-01-04 16:13:38 +03:00
navelbuffle 3d7cf54723 added error ReadUintOutOfRange 2025-01-04 16:01:04 +03:00
navelbuffle ead3797ea0 refactor helper read funcs and add instruction into parseSublist 2025-01-04 15:54:11 +03:00
navelbuffle 68d9076424 return to: all opcode implementations inline 2025-01-04 15:12:22 +03:00
navelbuffle 9c657167a8 refactored into ordered CodeTag and OpCode (same keys in a code) 2025-01-03 21:04:03 +03:00
navelbuffle 0be8408a3a extend helper reads with a boolean type 2025-01-03 10:51:45 +03:00
navelbuffle d38937095e extend Descriptor with a boolean type 2025-01-03 09:21:57 +03:00
navelbuffle 7d74d84717 extend CodeTag and OpCode enums with a boolean type 2025-01-03 08:34:30 +03:00
navelbuffle ce1cc8adad extend gitignore 2024-12-31 02:41:28 +03:00
27 changed files with 1581 additions and 1950 deletions
+2 -1
View File
@@ -3,4 +3,5 @@ onchain/out/
offchain/target/ offchain/target/
.direnv .direnv
.env
+123 -127
View File
@@ -70,9 +70,9 @@ dependencies = [
[[package]] [[package]]
name = "alloy-primitives" name = "alloy-primitives"
version = "0.8.18" version = "0.8.15"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "788bb18e8f61d5d9340b52143f27771daf7e1dccbaf2741621d2493f9debf52e" checksum = "6259a506ab13e1d658796c31e6e39d2e2ee89243bcc505ddc613b35732e0a430"
dependencies = [ dependencies = [
"alloy-rlp", "alloy-rlp",
"bytes", "bytes",
@@ -81,6 +81,7 @@ dependencies = [
"derive_more", "derive_more",
"foldhash", "foldhash",
"hashbrown", "hashbrown",
"hex-literal",
"indexmap", "indexmap",
"itoa", "itoa",
"k256", "k256",
@@ -114,7 +115,7 @@ checksum = "5a833d97bf8a5f0f878daf2c8451fff7de7f9de38baa5a45d936ec718d81255a"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.96", "syn 2.0.91",
] ]
[[package]] [[package]]
@@ -264,13 +265,13 @@ dependencies = [
[[package]] [[package]]
name = "async-trait" name = "async-trait"
version = "0.1.85" version = "0.1.83"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f934833b4b7233644e5848f235df3f57ed8c80f1528a26c3dfa13d2147fa056" checksum = "721cae7de5c34fbb2acd27e21e6d2cf7b886dce0c27388d46c4e6c47ea4318dd"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.96", "syn 2.0.91",
] ]
[[package]] [[package]]
@@ -302,7 +303,7 @@ checksum = "3c87f3f15e7794432337fc718554eaa4dc8f04c9677a950ffe366f20a162ae42"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.96", "syn 2.0.91",
] ]
[[package]] [[package]]
@@ -379,9 +380,9 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
[[package]] [[package]]
name = "bitflags" name = "bitflags"
version = "2.7.0" version = "2.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1be3f42a67d6d345ecd59f675f3f012d6974981560836e938c22b424b85ce1be" checksum = "b048fb63fd8b5923fc5aa7b340d8e156aec7ec02f0c78fa8a6ddc2613f6f71de"
[[package]] [[package]]
name = "bitvec" name = "bitvec"
@@ -523,9 +524,9 @@ dependencies = [
[[package]] [[package]]
name = "cc" name = "cc"
version = "1.2.9" version = "1.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c8293772165d9345bdaaa39b45b2109591e63fe5e6fbc23c6ff930a048aa310b" checksum = "c31a0499c1dc64f458ad13872de75c0eb7e3fdb0e67964610c914b034fc5956e"
dependencies = [ dependencies = [
"jobserver", "jobserver",
"libc", "libc",
@@ -774,7 +775,7 @@ checksum = "62d671cc41a825ebabc75757b62d3d168c577f9149b2d49ece1dad1f72119d25"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.96", "syn 2.0.91",
] ]
[[package]] [[package]]
@@ -794,7 +795,7 @@ checksum = "cb7330aeadfbe296029522e6c40f315320aba36fc43a5b3632f3795348f3bd22"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.96", "syn 2.0.91",
"unicode-xid", "unicode-xid",
] ]
@@ -869,7 +870,7 @@ checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.96", "syn 2.0.91",
] ]
[[package]] [[package]]
@@ -961,7 +962,7 @@ checksum = "2f9ed6b3789237c8a0c1c505af1c7eb2c560df6186f01b098c3a1064ea532f38"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.96", "syn 2.0.91",
] ]
[[package]] [[package]]
@@ -1116,7 +1117,7 @@ dependencies = [
"reqwest", "reqwest",
"serde", "serde",
"serde_json", "serde_json",
"syn 2.0.96", "syn 2.0.91",
"toml", "toml",
"walkdir", "walkdir",
] ]
@@ -1134,7 +1135,7 @@ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"serde_json", "serde_json",
"syn 2.0.96", "syn 2.0.91",
] ]
[[package]] [[package]]
@@ -1160,7 +1161,7 @@ dependencies = [
"serde", "serde",
"serde_json", "serde_json",
"strum", "strum",
"syn 2.0.96", "syn 2.0.91",
"tempfile", "tempfile",
"thiserror 1.0.69", "thiserror 1.0.69",
"tiny-keccak", "tiny-keccak",
@@ -1477,7 +1478,7 @@ checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.96", "syn 2.0.91",
] ]
[[package]] [[package]]
@@ -1559,9 +1560,9 @@ checksum = "07e28edb80900c19c28f1072f2e8aeca7fa06b23cd4169cefe1af5aa3260783f"
[[package]] [[package]]
name = "glob" name = "glob"
version = "0.3.2" version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a8d1add55171497b4705a648c6b583acafb01d58050a51727785f0b2c8e0a2b2" checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b"
[[package]] [[package]]
name = "gloo-timers" name = "gloo-timers"
@@ -1641,6 +1642,12 @@ version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
[[package]]
name = "hex-literal"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6fe2267d4ed49bc07b63801559be28c718ea06c4738b7a03c94df7386d2cde46"
[[package]] [[package]]
name = "hmac" name = "hmac"
version = "0.12.1" version = "0.12.1"
@@ -1846,7 +1853,7 @@ checksum = "1ec89e9337638ecdc08744df490b221a7399bf8d164eb52a665454e60e075ad6"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.96", "syn 2.0.91",
] ]
[[package]] [[package]]
@@ -1905,7 +1912,7 @@ checksum = "a0eb5a3343abf848c0984fe4604b2b105da9539376e24fc0a3b0007411ae4fd9"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.96", "syn 2.0.91",
] ]
[[package]] [[package]]
@@ -1983,9 +1990,9 @@ dependencies = [
[[package]] [[package]]
name = "js-sys" name = "js-sys"
version = "0.3.77" version = "0.3.76"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1cfaf33c695fc6e08064efbc1f72ec937429614f25eef83af942d0e227c3a28f" checksum = "6717b6b5b077764fb5966237269cb3c64edddde4b14ce42647430a78ced9e7b7"
dependencies = [ dependencies = [
"once_cell", "once_cell",
"wasm-bindgen", "wasm-bindgen",
@@ -2095,15 +2102,15 @@ version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c0ff37bd590ca25063e35af745c343cb7a0271906fb7b37e4813e8f79f00268d" checksum = "c0ff37bd590ca25063e35af745c343cb7a0271906fb7b37e4813e8f79f00268d"
dependencies = [ dependencies = [
"bitflags 2.7.0", "bitflags 2.6.0",
"libc", "libc",
] ]
[[package]] [[package]]
name = "linux-raw-sys" name = "linux-raw-sys"
version = "0.4.15" version = "0.4.14"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" checksum = "78b3ae25bc7c8c38cec158d1f2757ee79e9b3740fbc7ccf0e59e4b08d793fa89"
[[package]] [[package]]
name = "litemap" name = "litemap"
@@ -2283,7 +2290,7 @@ dependencies = [
"proc-macro-crate", "proc-macro-crate",
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.96", "syn 2.0.91",
] ]
[[package]] [[package]]
@@ -2462,7 +2469,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b7cafe60d6cf8e62e1b9b2ea516a089c008945bb5a275416789e7db0bc199dc" checksum = "8b7cafe60d6cf8e62e1b9b2ea516a089c008945bb5a275416789e7db0bc199dc"
dependencies = [ dependencies = [
"memchr", "memchr",
"thiserror 2.0.11", "thiserror 2.0.9",
"ucd-trie", "ucd-trie",
] ]
@@ -2488,35 +2495,35 @@ dependencies = [
[[package]] [[package]]
name = "phf" name = "phf"
version = "0.11.3" version = "0.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078" checksum = "ade2d8b8f33c7333b51bcf0428d37e217e9f32192ae4772156f65063b8ce03dc"
dependencies = [ dependencies = [
"phf_macros", "phf_macros",
"phf_shared 0.11.3", "phf_shared 0.11.2",
] ]
[[package]] [[package]]
name = "phf_generator" name = "phf_generator"
version = "0.11.3" version = "0.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d" checksum = "48e4cc64c2ad9ebe670cb8fd69dd50ae301650392e81c05f9bfcb2d5bdbc24b0"
dependencies = [ dependencies = [
"phf_shared 0.11.3", "phf_shared 0.11.2",
"rand", "rand",
] ]
[[package]] [[package]]
name = "phf_macros" name = "phf_macros"
version = "0.11.3" version = "0.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f84ac04429c13a7ff43785d75ad27569f2951ce0ffd30a3321230db2fc727216" checksum = "3444646e286606587e49f3bcf1679b8cef1dc2c5ecc29ddacaffc305180d464b"
dependencies = [ dependencies = [
"phf_generator", "phf_generator",
"phf_shared 0.11.3", "phf_shared 0.11.2",
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.96", "syn 2.0.91",
] ]
[[package]] [[package]]
@@ -2525,43 +2532,43 @@ version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6796ad771acdc0123d2a88dc428b5e38ef24456743ddb1744ed628f9815c096" checksum = "b6796ad771acdc0123d2a88dc428b5e38ef24456743ddb1744ed628f9815c096"
dependencies = [ dependencies = [
"siphasher 0.3.11", "siphasher",
] ]
[[package]] [[package]]
name = "phf_shared" name = "phf_shared"
version = "0.11.3" version = "0.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67eabc2ef2a60eb7faa00097bd1ffdb5bd28e62bf39990626a582201b7a754e5" checksum = "90fcb95eef784c2ac79119d1dd819e162b5da872ce6f3c3abe1e8ca1c082f72b"
dependencies = [ dependencies = [
"siphasher 1.0.1", "siphasher",
] ]
[[package]] [[package]]
name = "pin-project" name = "pin-project"
version = "1.1.8" version = "1.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e2ec53ad785f4d35dac0adea7f7dc6f1bb277ad84a680c7afefeae05d1f5916" checksum = "be57f64e946e500c8ee36ef6331845d40a93055567ec57e8fae13efd33759b95"
dependencies = [ dependencies = [
"pin-project-internal", "pin-project-internal",
] ]
[[package]] [[package]]
name = "pin-project-internal" name = "pin-project-internal"
version = "1.1.8" version = "1.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d56a66c0c55993aa927429d0f8a0abfd74f084e4d9c192cffed01e418d83eefb" checksum = "3c0f5fad0874fc7abcd4d750e76917eaebbecaa2c20bde22e1dbeeba8beb758c"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.96", "syn 2.0.91",
] ]
[[package]] [[package]]
name = "pin-project-lite" name = "pin-project-lite"
version = "0.2.16" version = "0.2.15"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b" checksum = "915a1e146535de9163f3987b8944ed8cf49a18bb0056bcebcdcece385cece4ff"
[[package]] [[package]]
name = "pin-utils" name = "pin-utils"
@@ -2608,12 +2615,12 @@ checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c"
[[package]] [[package]]
name = "prettyplease" name = "prettyplease"
version = "0.2.29" version = "0.2.25"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6924ced06e1f7dfe3fa48d57b9f74f55d8915f5036121bef647ef4b204895fac" checksum = "64d1ec885c64d0457d564db4ec299b2dae3f9c02808b8ad9c3a089c591b18033"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"syn 2.0.96", "syn 2.0.91",
] ]
[[package]] [[package]]
@@ -2641,9 +2648,9 @@ dependencies = [
[[package]] [[package]]
name = "proc-macro2" name = "proc-macro2"
version = "1.0.93" version = "1.0.92"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "60946a68e5f9d28b0dc1c21bb8a97ee7d018a8b322fa57838ba31cc878e22d99" checksum = "37d3544b3f2748c54e147655edb5025752e2303145b5aefb3c3ea2c78b973bb0"
dependencies = [ dependencies = [
"unicode-ident", "unicode-ident",
] ]
@@ -2656,7 +2663,7 @@ checksum = "b4c2511913b88df1637da85cc8d96ec8e43a3f8bb8ccb71ee1ac240d6f3df58d"
dependencies = [ dependencies = [
"bit-set", "bit-set",
"bit-vec", "bit-vec",
"bitflags 2.7.0", "bitflags 2.6.0",
"lazy_static", "lazy_static",
"num-traits", "num-traits",
"rand", "rand",
@@ -2676,9 +2683,9 @@ checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0"
[[package]] [[package]]
name = "quote" name = "quote"
version = "1.0.38" version = "1.0.37"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0e4dccaaaf89514f546c693ddc140f729f958c247918a13380cccc6078391acc" checksum = "b5b9d34b8991d19d98081b46eacdd8eb58c6f2b201139f7c5f643cc155a633af"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
] ]
@@ -2754,7 +2761,7 @@ version = "0.5.8"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "03a862b389f93e68874fbf580b9de08dd02facb9a788ebadaf4a3fd33cf58834" checksum = "03a862b389f93e68874fbf580b9de08dd02facb9a788ebadaf4a3fd33cf58834"
dependencies = [ dependencies = [
"bitflags 2.7.0", "bitflags 2.6.0",
] ]
[[package]] [[package]]
@@ -3001,7 +3008,7 @@ name = "revm-state"
version = "1.0.0" version = "1.0.0"
source = "git+https://github.com/bluealloy/revm.git?rev=03ea24bd9550e93b08f343e0b410725557c1adb4#03ea24bd9550e93b08f343e0b410725557c1adb4" source = "git+https://github.com/bluealloy/revm.git?rev=03ea24bd9550e93b08f343e0b410725557c1adb4#03ea24bd9550e93b08f343e0b410725557c1adb4"
dependencies = [ dependencies = [
"bitflags 2.7.0", "bitflags 2.6.0",
"revm-bytecode", "revm-bytecode",
"revm-primitives", "revm-primitives",
"revm-specification", "revm-specification",
@@ -3148,11 +3155,11 @@ dependencies = [
[[package]] [[package]]
name = "rustix" name = "rustix"
version = "0.38.43" version = "0.38.42"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a78891ee6bf2340288408954ac787aa063d8e8817e9f53abb37c695c6d834ef6" checksum = "f93dc38ecbab2eb790ff964bb77fa94faf256fd3e73285fd7ba0903b76bedb85"
dependencies = [ dependencies = [
"bitflags 2.7.0", "bitflags 2.6.0",
"errno", "errno",
"libc", "libc",
"linux-raw-sys", "linux-raw-sys",
@@ -3192,9 +3199,9 @@ dependencies = [
[[package]] [[package]]
name = "rustversion" name = "rustversion"
version = "1.0.19" version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f7c45b9784283f1b2e7fb61b42047c2fd678ef0960d4f6f1eba131594cc369d4" checksum = "0e819f2bc632f285be6d7cd36e25940d45b2391dd6d9b939e79de557f7014248"
[[package]] [[package]]
name = "rusty-fork" name = "rusty-fork"
@@ -3253,7 +3260,7 @@ dependencies = [
"proc-macro-crate", "proc-macro-crate",
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.96", "syn 2.0.91",
] ]
[[package]] [[package]]
@@ -3358,29 +3365,29 @@ checksum = "cd0b0ec5f1c1ca621c432a25813d8d60c88abe6d3e08a3eb9cf37d97a0fe3d73"
[[package]] [[package]]
name = "serde" name = "serde"
version = "1.0.217" version = "1.0.216"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02fc4265df13d6fa1d00ecff087228cc0a2b5f3c0e87e258d8b94a156e984c70" checksum = "0b9781016e935a97e8beecf0c933758c97a5520d32930e460142b4cd80c6338e"
dependencies = [ dependencies = [
"serde_derive", "serde_derive",
] ]
[[package]] [[package]]
name = "serde_derive" name = "serde_derive"
version = "1.0.217" version = "1.0.216"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a9bf7cf98d04a2b28aead066b7496853d4779c9cc183c440dbac457641e19a0" checksum = "46f859dbbf73865c6627ed570e78961cd3ac92407a2d117204c49232485da55e"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.96", "syn 2.0.91",
] ]
[[package]] [[package]]
name = "serde_json" name = "serde_json"
version = "1.0.135" version = "1.0.134"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b0d7ba2887406110130a978386c4e1befb98c674b4fba677954e4db976630d9" checksum = "d00f4175c42ee48b15416f6193a959ba3a0d67fc699a0db9ad12df9f83991c7d"
dependencies = [ dependencies = [
"itoa", "itoa",
"memchr", "memchr",
@@ -3469,13 +3476,13 @@ dependencies = [
[[package]] [[package]]
name = "simple_asn1" name = "simple_asn1"
version = "0.6.3" version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "297f631f50729c8c99b84667867963997ec0b50f32b2a7dbcab828ef0541e8bb" checksum = "adc4e5204eb1910f40f9cfa375f6f05b68c3abac4b6fd879c8ff5e7ae8a0a085"
dependencies = [ dependencies = [
"num-bigint", "num-bigint",
"num-traits", "num-traits",
"thiserror 2.0.11", "thiserror 1.0.69",
"time", "time",
] ]
@@ -3485,12 +3492,6 @@ version = "0.3.11"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "38b58827f4464d87d377d175e90bf58eb00fd8716ff0a62f80356b5e61555d0d" checksum = "38b58827f4464d87d377d175e90bf58eb00fd8716ff0a62f80356b5e61555d0d"
[[package]]
name = "siphasher"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "56199f7ddabf13fe5074ce809e7d3f42b42ae711800501b5b16ea82ad029c39d"
[[package]] [[package]]
name = "slab" name = "slab"
version = "0.4.9" version = "0.4.9"
@@ -3596,7 +3597,7 @@ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"rustversion", "rustversion",
"syn 2.0.96", "syn 2.0.91",
] ]
[[package]] [[package]]
@@ -3651,9 +3652,9 @@ dependencies = [
[[package]] [[package]]
name = "syn" name = "syn"
version = "2.0.96" version = "2.0.91"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d5d0adab1ae378d7f53bdebc67a39f1f151407ef230f0ce2883572f5d8985c80" checksum = "d53cbcb5a243bd33b7858b1d7f4aca2153490815872d86d955d6ea29f743c035"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
@@ -3674,7 +3675,7 @@ checksum = "c8af7666ab7b6390ab78131fb5b0fce11d6b7a6951602017c35fa82800708971"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.96", "syn 2.0.91",
] ]
[[package]] [[package]]
@@ -3706,13 +3707,12 @@ checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369"
[[package]] [[package]]
name = "tempfile" name = "tempfile"
version = "3.15.0" version = "3.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a8a559c81686f576e8cd0290cd2a24a2a9ad80c98b3478856500fcbd7acd704" checksum = "28cce251fcbc87fac86a866eeb0d6c2d536fc16d06f184bb61aeae11aa4cee0c"
dependencies = [ dependencies = [
"cfg-if", "cfg-if",
"fastrand", "fastrand",
"getrandom",
"once_cell", "once_cell",
"rustix", "rustix",
"windows-sys 0.59.0", "windows-sys 0.59.0",
@@ -3740,11 +3740,11 @@ dependencies = [
[[package]] [[package]]
name = "thiserror" name = "thiserror"
version = "2.0.11" version = "2.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d452f284b73e6d76dd36758a0c8684b1d5be31f92b89d07fd5822175732206fc" checksum = "f072643fd0190df67a8bab670c20ef5d8737177d6ac6b2e9a236cb096206b2cc"
dependencies = [ dependencies = [
"thiserror-impl 2.0.11", "thiserror-impl 2.0.9",
] ]
[[package]] [[package]]
@@ -3755,18 +3755,18 @@ checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.96", "syn 2.0.91",
] ]
[[package]] [[package]]
name = "thiserror-impl" name = "thiserror-impl"
version = "2.0.11" version = "2.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "26afc1baea8a989337eeb52b6e72a039780ce45c3edfcc9c5b9d112feeb173c2" checksum = "7b50fa271071aae2e6ee85f842e2e28ba8cd2c5fb67f11fcb1fd70b276f9e7d4"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.96", "syn 2.0.91",
] ]
[[package]] [[package]]
@@ -3845,9 +3845,9 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
[[package]] [[package]]
name = "tokio" name = "tokio"
version = "1.43.0" version = "1.42.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d61fa4ffa3de412bfea335c6ecff681de2b609ba3c77ef3e00e521813a9ed9e" checksum = "5cec9b21b0450273377fc97bd4c33a8acffc8c996c987a7c5b319a0083707551"
dependencies = [ dependencies = [
"backtrace", "backtrace",
"bytes", "bytes",
@@ -3955,7 +3955,7 @@ checksum = "395ae124c09f9e6918a2310af6038fba074bcf474ac352496d5910dd59a2226d"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.96", "syn 2.0.91",
] ]
[[package]] [[package]]
@@ -4144,35 +4144,34 @@ checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
[[package]] [[package]]
name = "wasm-bindgen" name = "wasm-bindgen"
version = "0.2.100" version = "0.2.99"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1edc8929d7499fc4e8f0be2262a241556cfc54a0bea223790e71446f2aab1ef5" checksum = "a474f6281d1d70c17ae7aa6a613c87fce69a127e2624002df63dcb39d6cf6396"
dependencies = [ dependencies = [
"cfg-if", "cfg-if",
"once_cell", "once_cell",
"rustversion",
"wasm-bindgen-macro", "wasm-bindgen-macro",
] ]
[[package]] [[package]]
name = "wasm-bindgen-backend" name = "wasm-bindgen-backend"
version = "0.2.100" version = "0.2.99"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2f0a0651a5c2bc21487bde11ee802ccaf4c51935d0d3d42a6101f98161700bc6" checksum = "5f89bb38646b4f81674e8f5c3fb81b562be1fd936d84320f3264486418519c79"
dependencies = [ dependencies = [
"bumpalo", "bumpalo",
"log", "log",
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.96", "syn 2.0.91",
"wasm-bindgen-shared", "wasm-bindgen-shared",
] ]
[[package]] [[package]]
name = "wasm-bindgen-futures" name = "wasm-bindgen-futures"
version = "0.4.50" version = "0.4.49"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "555d470ec0bc3bb57890405e5d4322cc9ea83cebb085523ced7be4144dac1e61" checksum = "38176d9b44ea84e9184eff0bc34cc167ed044f816accfe5922e54d84cf48eca2"
dependencies = [ dependencies = [
"cfg-if", "cfg-if",
"js-sys", "js-sys",
@@ -4183,9 +4182,9 @@ dependencies = [
[[package]] [[package]]
name = "wasm-bindgen-macro" name = "wasm-bindgen-macro"
version = "0.2.100" version = "0.2.99"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7fe63fc6d09ed3792bd0897b314f53de8e16568c2b3f7982f468c0bf9bd0b407" checksum = "2cc6181fd9a7492eef6fef1f33961e3695e4579b9872a6f7c83aee556666d4fe"
dependencies = [ dependencies = [
"quote", "quote",
"wasm-bindgen-macro-support", "wasm-bindgen-macro-support",
@@ -4193,31 +4192,28 @@ dependencies = [
[[package]] [[package]]
name = "wasm-bindgen-macro-support" name = "wasm-bindgen-macro-support"
version = "0.2.100" version = "0.2.99"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ae87ea40c9f689fc23f209965b6fb8a99ad69aeeb0231408be24920604395de" checksum = "30d7a95b763d3c45903ed6c81f156801839e5ee968bb07e534c44df0fcd330c2"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.96", "syn 2.0.91",
"wasm-bindgen-backend", "wasm-bindgen-backend",
"wasm-bindgen-shared", "wasm-bindgen-shared",
] ]
[[package]] [[package]]
name = "wasm-bindgen-shared" name = "wasm-bindgen-shared"
version = "0.2.100" version = "0.2.99"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1a05d73b933a847d6cccdda8f838a22ff101ad9bf93e33684f39c1f5f0eece3d" checksum = "943aab3fdaaa029a6e0271b35ea10b72b943135afe9bffca82384098ad0e06a6"
dependencies = [
"unicode-ident",
]
[[package]] [[package]]
name = "web-sys" name = "web-sys"
version = "0.3.77" version = "0.3.76"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "33b6dd2ef9186f1f2072e409e99cd22a975331a6b3591b12c764e0e55c60d5d2" checksum = "04dd7223427d52553d3702c004d3b2fe07c148165faa56313cb00211e31c12bc"
dependencies = [ dependencies = [
"js-sys", "js-sys",
"wasm-bindgen", "wasm-bindgen",
@@ -4410,9 +4406,9 @@ checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
[[package]] [[package]]
name = "winnow" name = "winnow"
version = "0.6.24" version = "0.6.20"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c8d71a593cc5c42ad7876e2c1fda56f314f3754c084128833e64f1345ff8a03a" checksum = "36c1fec1a2bb5866f07c25f68c26e565c4c200aebb96d7e55710c19d3e8ac49b"
dependencies = [ dependencies = [
"memchr", "memchr",
] ]
@@ -4493,7 +4489,7 @@ checksum = "2380878cad4ac9aac1e2435f3eb4020e8374b5f13c296cb75b4620ff8e229154"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.96", "syn 2.0.91",
"synstructure", "synstructure",
] ]
@@ -4515,7 +4511,7 @@ checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.96", "syn 2.0.91",
] ]
[[package]] [[package]]
@@ -4535,7 +4531,7 @@ checksum = "595eed982f7d355beb85837f651fa22e90b3c044842dc7f2c2842c086f295808"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.96", "syn 2.0.91",
"synstructure", "synstructure",
] ]
@@ -4556,7 +4552,7 @@ checksum = "ce36e65b0d2999d2aafac989fb249189a141aee1f53c612c1f37d72631959f69"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.96", "syn 2.0.91",
] ]
[[package]] [[package]]
@@ -4578,7 +4574,7 @@ checksum = "6eafa6dfb17584ea3e2bd6e76e0cc15ad7af12b09abdd1ca55961bed9b1063c6"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.96", "syn 2.0.91",
] ]
[[package]] [[package]]
-16
View File
@@ -3,22 +3,6 @@ name = "offchain"
version = "0.1.0" version = "0.1.0"
edition = "2021" edition = "2021"
[[bin]]
name = "gp_tester"
path = "src/bin/gp_tester.rs"
[[bin]]
name = "gp_spec_tester"
path = "src/bin/gp_spec_tester.rs"
[[bin]]
name = "symreg_experiment"
path = "src/bin/symreg_experiment.rs"
[[bin]]
name = "symreg_experiment_local"
path = "src/bin/symreg_experiment_local.rs"
[dependencies] [dependencies]
serde = { version = "1.0", features = ["derive"] } serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0" serde_json = "1.0"
-36
View File
@@ -1,36 +0,0 @@
use anyhow::Result;
use rand::thread_rng;
use rand::Rng;
// Suppose you have these in your library:
use offchain::gp::generate_spec::ranmdom_code_fixed;
use offchain::gp::mutation::mutate_by_index;
use offchain::compiler::ast::UntypedAst;
fn main() -> Result<()> {
let mut rng = thread_rng();
// We'll produce, say, 3 random ASTs ("subjects").
let num_subjects = 3;
let max_points = 6;
for i in 0..num_subjects {
// Generate a random AST
let original = ranmdom_code_fixed(&mut rng, max_points);
println!("=== Subject #{} ===", i);
println!("Original AST:\n{:#?}", original);
// Let's do 2 successive mutations on it
let mut prev = original.clone();
for mut_idx in 0..2 {
let mutated = mutate_by_index(&prev, &mut rng, max_points);
println!("Mutation #{} result:\n{:#?}", mut_idx, mutated);
prev = mutated; // so the next iteration mutates from the last result
}
println!("=== End of Subject #{} ===\n", i);
}
println!("Done generating & mutating random ASTs!");
Ok(())
}
-91
View File
@@ -1,91 +0,0 @@
// src/bin/gp_tester.rs
use anyhow::{anyhow, bail, Result};
use rand::{thread_rng, Rng};
// 1) We'll use the helper that reads creation code from a JSON artifact
use offchain::helpers::artifact::get_creation_code;
// 2) EvmRunner to deploy & run the interpreter
use offchain::runner::revm_runner::EvmRunner;
// 3) AST generation & mutation
use offchain::gp::generate::random_ast;
use offchain::gp::genetic_ops::mutated_ast;
use offchain::compiler::ast::UntypedAst;
fn main() -> Result<()> {
// ----------------------------------------------------------------------
// 1) Read the creation code (Push3Interpreter) using our helper function
// ----------------------------------------------------------------------
let creation_hex_filename = "../onchain/out/Push3Interpreter.sol/Push3Interpreter.json";
let creation_bytes = get_creation_code(creation_hex_filename)?;
println!(
"Loaded creation code from {} ({} bytes)",
creation_hex_filename,
creation_bytes.len()
);
// 2) Create the ephemeral EVM (deploy the contract)
let mut runner = EvmRunner::new(creation_bytes)?;
println!("Deployed test interpreter at: 0x{:x}\n", runner.interpreter_addr);
// 3) We'll generate random ASTs & mutate them
let number_of_programs = 3; // how many random ASTs to try
let max_depth = 4; // max AST depth
let mut rng = thread_rng();
for i in 0..number_of_programs {
// a) Generate a random AST
let ast: UntypedAst = random_ast(&mut rng, 0, max_depth);
println!("=== Program {} ===", i);
println!("Random AST:\n{:#?}", ast);
// b) Run the original AST
match runner.run_ast(&ast) {
Ok(outputs) => {
println!("Original AST ran successfully!");
println!("Final CODE stack: {:?}", outputs.final_code_stack);
println!("Final EXEC stack: {:?}", outputs.final_exec_stack);
println!("Final INT stack: {:?}", outputs.final_int_stack);
// c) Mutate it a few times
let mutated1 = mutated_ast(&ast, &mut rng, 0, max_depth);
println!("\n-- MUTATED 1 --\n{:#?}", mutated1);
match runner.run_ast(&mutated1) {
Ok(m1_out) => {
println!("MUTATED 1 ran successfully!");
println!("Final INT stack: {:?}", m1_out.final_int_stack);
}
Err(e) => {
println!("MUTATED 1 error: {}", e);
}
}
let mutated2 = mutated_ast(&ast, &mut rng, 0, max_depth);
println!("\n-- MUTATED 2 --\n{:#?}", mutated2);
match runner.run_ast(&mutated2) {
Ok(m2_out) => {
println!("MUTATED 2 ran successfully!");
println!("Final INT stack: {:?}", m2_out.final_int_stack);
}
Err(e) => {
println!("MUTATED 2 error: {}", e);
}
}
}
Err(e) => {
// If the original fails, we won't bother mutating it
println!("Original AST error: {}", e);
}
}
println!("=== End of Program {} ===\n", i);
}
println!("Finished running & mutating {} random programs.", number_of_programs);
Ok(())
}
-223
View File
@@ -1,223 +0,0 @@
// src/bin/symreg_experiment.rs
use anyhow::Result;
use rand::{thread_rng, Rng};
// Our GP + compiler modules (adjust paths as needed)
use offchain::compiler::ast::{UntypedAst, Push3Ast};
use offchain::helpers::artifact::get_creation_code;
use offchain::runner::revm_runner::{
EvmRunner,
Push3InterpreterInputs,
};
use offchain::compiler::push3_describtor::make_sublist_descriptor;
// Our GP operators
use offchain::gp::generate_spec::ranmdom_code_fixed;
use offchain::gp::mutation::{mutate_by_index, crossover_by_index};
// Ethers + ABI
use ethers::types::U256;
use ethers::abi::{encode, Token};
/// 1) Generate (x, y) samples for f(x)=3x^2 + x + 3
fn generate_samples() -> Vec<(i32, i32)> {
let mut samples = Vec::new();
for x in -5..=5 {
let y = 3 * x * x + x + 3;
samples.push((x, y));
}
samples
}
/// 2) Evaluate a single AST on a single input `x` by
/// pushing `x` onto the int stack, running in EVM,
/// and reading the final top of the int stack.
fn evaluate_ast_on_x(
runner: &mut EvmRunner,
ast: &UntypedAst,
x: i32,
) -> i32 {
// a) Convert AST => push3 bytecode
let code_bytes = ast.to_bytecode();
let code_len = code_bytes.len() as u32;
// b) Build a sublist descriptor
let descriptor = make_sublist_descriptor(0, code_len);
// c) Provide x in `init_int_stack`
let inputs = Push3InterpreterInputs {
code: code_bytes,
init_code_stack: Vec::new(),
init_exec_stack: vec![descriptor],
init_int_stack: vec![x as i128],
};
// d) Actually run the interpreter
let outputs = match runner.run_interpreter(&inputs) {
Ok(o) => o,
Err(_) => {
// If the call fails or reverts, return 0
return 0;
}
};
// e) If final_int_stack is empty => 0, else top item
if outputs.final_int_stack.is_empty() {
i32::MAX
} else {
*outputs.final_int_stack.last().unwrap() as i32
}
}
/// 3) Evaluate an AST on all (x, y) samples => compute MSE
fn evaluate_fitness(
runner: &mut EvmRunner,
ast: &UntypedAst,
samples: &[(i32, i32)]
) -> f64 {
let mut error_sum = 0.0;
for &(x, target_y32) in samples {
// cast to i64
let target_y = target_y32 as i64;
// evaluate in i64 as well
let predicted_i64 = evaluate_ast_on_x(runner, ast, x) as i64;
let diff = predicted_i64.wrapping_sub(target_y);
// or you could saturating_sub if you prefer
error_sum += (diff as f64) * (diff as f64);
}
error_sum / samples.len() as f64
}
fn main() -> Result<()> {
// 1) Generate samples for f(x)=3x^2 + x + 3
let samples = generate_samples();
// 2) Create ephemeral EVM runner for the interpreter
let creation_hex_filename = "../onchain/out/Push3Interpreter.sol/Push3Interpreter.json";
let creation_bytes = get_creation_code(creation_hex_filename)?;
let mut runner = EvmRunner::new(creation_bytes)?;
// 3) GP parameters
let pop_size = 4000; // must be divisible by 4 for our scheme
let generations = 100;
let early_stop_threshold = 1.0;
let max_points = 20;
assert_eq!(pop_size % 4, 0, "pop_size must be multiple of 4 for our scheme");
let quarter = pop_size / 4;
let mut rng = thread_rng();
// 4) Initialize population (random)
let mut population: Vec<UntypedAst> = (0..pop_size)
.map(|_| ranmdom_code_fixed(&mut rng, max_points))
.collect();
// 5) Main GP loop
for gen in 0..generations {
// (a) Evaluate
let mut scored: Vec<(UntypedAst, f64)> = population.into_iter()
.map(|ast| {
let err = evaluate_fitness(&mut runner, &ast, &samples);
(ast, err)
})
.collect();
// (b) Sort ascending by error
scored.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap());
// (c) Print generation summary
let best_err = scored[0].1;
println!("\n=== Generation {gen} ===");
println!("Best error = {best_err}");
// Print top 5 subjects in pretty format
// let top_n = 5.min(scored.len());
// println!("Top {top_n} subjects:");
// for i in 0..top_n {
// println!(
// " #{i}, err={}, AST:\n{:#?}",
// scored[i].1,
// scored[i].0
// );
// }
// early stop?
if best_err < early_stop_threshold {
println!("Best error < {early_stop_threshold}, stopping early!");
// we can keep 'scored' for final if we want
population = scored.into_iter().map(|(a, _)| a).collect();
break;
}
// (d) Reproduction => build new population
let mut new_pop = Vec::with_capacity(pop_size);
// keep best quarter
for i in 0..quarter {
new_pop.push(scored[i].0.clone());
}
// add random quarter
for _ in 0..quarter {
let fresh = ranmdom_code_fixed(&mut rng, max_points);
new_pop.push(fresh);
}
// crossover quarter
let top_half_count = scored.len() / 2;
let crossover_pairs = quarter / 2; // each yields 2 kids => quarter total
for _ in 0..crossover_pairs {
let idx1 = rng.gen_range(0..top_half_count);
let idx2 = rng.gen_range(0..top_half_count);
let (child1, child2) = crossover_by_index(
&scored[idx1].0,
&scored[idx2].0,
&mut rng
);
new_pop.push(child1);
new_pop.push(child2);
}
// mutate quarter
while new_pop.len() < pop_size {
let idx = rng.gen_range(0..top_half_count);
let mutated = mutate_by_index(&scored[idx].0, &mut rng, max_points);
new_pop.push(mutated);
}
population = new_pop;
}
// 6) Final population => evaluate & sort, then print only top 10
println!("\n=== Final Population (Top 10) ===");
// a) Evaluate each item in the final population
let mut final_scored: Vec<(UntypedAst, f64)> = population
.into_iter()
.map(|ast| {
let err = evaluate_fitness(&mut runner, &ast, &samples);
(ast, err)
})
.collect();
// b) Sort ascending by error
final_scored.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap());
// c) Print the top 10 (or fewer if the population is smaller)
let top_n = 10.min(final_scored.len());
for i in 0..top_n {
let (ref ast, err) = final_scored[i];
println!(
"Subject #{i}, err={err}, AST:\n{:#?}",
ast
);
}
Ok(())
}
-202
View File
@@ -1,202 +0,0 @@
// src/bin/symreg_experiment_local.rs
use anyhow::Result;
use rand::{thread_rng, Rng};
// Our GP + compiler modules (adjust paths if needed)
use offchain::compiler::ast::{UntypedAst, Push3Ast};
use offchain::helpers::artifact::get_creation_code;
use offchain::runner::revm_runner::{EvmRunner, Push3InterpreterInputs};
use offchain::compiler::push3_describtor::make_sublist_descriptor;
// Our random code and local mutation
use offchain::gp::generate_spec::ranmdom_code_fixed;
use offchain::gp::local_mutation::local_mutation_fixed;
// Ethers + ABI
use ethers::types::U256;
use ethers::abi::{encode, Token};
/// 1) Generate (x, y) samples for f(x) = 3x^2 + x + 3
fn generate_samples() -> Vec<(i32, i32)> {
let mut samples = Vec::new();
for x in -5..=5 {
let y = 3 * x * x + x + 3;
samples.push((x, y));
}
samples
}
/// 2) Evaluate a single AST on a single input `x`, returning the final top of the int stack.
fn evaluate_ast_on_x(
runner: &mut EvmRunner,
ast: &UntypedAst,
x: i32,
) -> i32 {
// Convert AST => push3 bytecode
let code_bytes = ast.to_bytecode();
let code_len = code_bytes.len() as u32;
// Build a sublist descriptor
let descriptor = make_sublist_descriptor(0, code_len);
// Provide x in `init_int_stack`
let inputs = Push3InterpreterInputs {
code: code_bytes,
init_code_stack: Vec::new(),
init_exec_stack: vec![descriptor],
init_int_stack: vec![x as i128],
};
// Run
let outputs = match runner.run_interpreter(&inputs) {
Ok(o) => o,
Err(_) => {
// If revert => 0
return 0;
}
};
if outputs.final_int_stack.is_empty() {
i32::MAX // or 0, or i32::MAX to strongly penalize weird runs
} else {
*outputs.final_int_stack.last().unwrap() as i32
}
}
/// 3) Evaluate an AST on all samples => compute MSE
fn evaluate_fitness(
runner: &mut EvmRunner,
ast: &UntypedAst,
samples: &[(i32, i32)]
) -> f64 {
let mut error_sum = 0.0;
for &(x, target_y32) in samples {
// cast to i64
let target_y = target_y32 as i64;
// evaluate in i64
let predicted_i64 = evaluate_ast_on_x(runner, ast, x) as i64;
// wrapping_sub to avoid panic
let diff = predicted_i64.wrapping_sub(target_y);
error_sum += (diff as f64) * (diff as f64);
}
error_sum / samples.len() as f64
}
fn main() -> Result<()> {
// 1) Generate samples
let samples = generate_samples();
// 2) Setup ephemeral EVM runner
let creation_hex_filename = "../onchain/out/Push3Interpreter.sol/Push3Interpreter.json";
let creation_bytes = get_creation_code(creation_hex_filename)?;
let mut runner = EvmRunner::new(creation_bytes)?;
// 3) GP parameters
let pop_size = 3600; // must be multiple of 3 for our scheme
let generations = 100;
let early_stop_threshold = 1.0;
let max_points = 12; // random code size limit
// Ensure pop_size is multiple of 3
assert_eq!(pop_size % 3, 0, "pop_size must be multiple of 3 for our scheme");
let third = pop_size / 3;
let mut rng = thread_rng();
// 4) Initialize random population
let mut population: Vec<UntypedAst> = (0..pop_size)
.map(|_| ranmdom_code_fixed(&mut rng, max_points))
.collect();
// 5) Main loop
for gen in 0..generations {
// a) Evaluate
let mut scored: Vec<(UntypedAst, f64)> = population.into_iter()
.map(|ast| {
let err = evaluate_fitness(&mut runner, &ast, &samples);
(ast, err)
})
.collect();
// b) Sort ascending by error
scored.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap());
let best_err = scored[0].1;
println!("\n=== Generation {gen} ===");
println!("Best error = {best_err}");
// (Optionally) Print top 5 in pretty format
let top_n = 5.min(scored.len());
println!("Top {top_n} subjects:");
for i in 0..top_n {
println!(
" #{i}, err={}, AST:\n{:#?}",
scored[i].1,
scored[i].0
);
}
// check early stop
if best_err < early_stop_threshold {
println!("Best error < {early_stop_threshold}, stopping early!");
population = scored.into_iter().map(|(a, _)| a).collect();
break;
}
// c) Build new population:
// - 1/3 = best survivors
// - 1/3 = fresh random
// - 1/3 = local mutation
let mut new_pop = Vec::with_capacity(pop_size);
// keep best third
for i in 0..third {
new_pop.push(scored[i].0.clone());
}
// random third
for _ in 0..third {
let fresh = ranmdom_code_fixed(&mut rng, max_points);
new_pop.push(fresh);
}
// local mutation third
let top_half_count = scored.len() / 2;
// we'll pick parents from top half for local mutation
while new_pop.len() < pop_size {
let idx = rng.gen_range(0..top_half_count);
// we assume you have local_mutation_fixed
// if you prefer passing a custom InstructionSet, do local_mutation(..., &instr_set)
let mutated = offchain::gp::local_mutation::local_mutation_fixed(
&scored[idx].0,
&mut rng
);
new_pop.push(mutated);
}
// store for next generation
population = new_pop;
}
// 6) Final => evaluate & sort => top 10
println!("\n=== Final Population (Top 10) ===");
let mut final_scored: Vec<(UntypedAst, f64)> = population
.into_iter()
.map(|ast| {
let err = evaluate_fitness(&mut runner, &ast, &samples);
(ast, err)
})
.collect();
final_scored.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap());
let top_n = 10.min(final_scored.len());
for i in 0..top_n {
let (ref ast, err) = final_scored[i];
println!("Subject #{i}, err={err}, AST:\n{:#?}", ast);
}
Ok(())
}
+394 -137
View File
@@ -1,50 +1,375 @@
//! src/compiler/ast.rs // pub trait Push3Ast {
//! // /// Convert this AST into a bytecode array (Push3 tokens).
//! This module defines an **abstract** untyped AST for our Push3-like language, // fn to_bytecode(&self) -> Vec<u8>;
//! plus a mapping for how to encode opcodes as bytes. We do *not* hardcode numeric
//! values in the `OpCode` enum. Instead, we provide a trait that can map // // Parse an AST from bytecode (the "decompiler"), if possible.
//! opcodes to bytes. This allows us to expand or change instructions easily // // Possibly returns a Result in case of partial/invalid parse.
//! (e.g., when the on-chain interpreter adds new opcodes or changes their IDs). // // fn from_bytecode(data: &[u8]) -> Self
// // where
// // Self: Sized;
// // Randomly mutate this AST in-place (GP mutation).
// // fn mutate(&mut self, rng: &mut impl rand::Rng);
// // Possibly a "crossover" method, or we do it externally.
// // fn crossover(&self, other: &Self, rng: &mut impl rand::Rng) -> Self;
// // Evaluate the AST with some input(s).
// // Optionally do we want this or do we always run in EVM?
// // We can stub it or do an interpret approach for local test.
// // fn interpret_locally(&self, inputs: &[i32]) -> Vec<i32>;
// }
// #[derive(Debug, Clone)]
// pub enum TypedAst {
// IntLiteral(i32),
// Instruction(InstructionKind),
// }
// #[derive(Debug, Clone)]
// pub enum InstructionKind {
// Plus(Box<TypedAst>, Box<TypedAst>),
// Minus(Box<TypedAst>, Box<TypedAst>),
// Mult(Box<TypedAst>, Box<TypedAst>),
// Dup, // 0 children
// Pop, // 0 children
// }
// impl Push3Ast for TypedAst {
// fn to_bytecode(&self) -> Vec<u8> {
// // do typed encoding:
// // - for Plus(e1, e2): e1 -> bytecode, e2 -> bytecode, then PLUS opcode
// unimplemented!()
// }
// // fn from_bytecode(data: &[u8]) -> Self {
// // // parse in a strictly typed manner; might fail or panic
// // // if the code doesn't line up properly
// // unimplemented!()
// // }
// // fn mutate(&mut self, rng: &mut impl rand::Rng) {
// // // e.g. randomly pick a node, replace it with something
// // // that respects the typed structure
// // unimplemented!()
// // }
// // fn interpret_locally(&self, inputs: &[i32]) -> Vec<i32> {
// // // do a normal expression evaluation. If a node is "Plus(a,b)",
// // // interpret (a) + interpret(b).
// // unimplemented!()
// // }
// }
// #[derive(Debug, Clone)]
// pub enum UntypedAst {
// /// A single token in a list-based approach, e.g. "Integer literal"
// IntLiteral(i32),
// /// "Instruction" might be a simple variant with no children,
// /// because the stack-based evaluation decides how many arguments it consumes.
// Instruction(OpCode),
// /// A sublist of tokens, e.g. "( 2 3 DUP + )"
// Sublist(Vec<UntypedAst>),
// }
// /// Possibly an enum for OpCode:
// #[derive(Debug, Clone)]
// pub enum OpCode {
// Noop,
// Plus,
// Minus,
// Mult,
// Dup,
// Pop,
// // maybe Unknown => treat as no-op
// }
// // impl Push3Ast for UntypedAst {
// // fn to_bytecode(&self) -> Vec<u8> {
// // // flatten out sublists vs instructions
// // unimplemented!()
// // }
// // // fn from_bytecode(data: &[u8]) -> Self {
// // // // parse "0x02 => INT_LITERAL => read next 4 bytes"
// // // // instructions might have no subchildren
// // // unimplemented!()
// // // }
// // // fn mutate(&mut self, rng: &mut impl rand::Rng) {
// // // // can randomly insert unknown tokens, reorder sublists, etc.
// // // // possibly produce "invalid ops => noops"
// // // unimplemented!()
// // // }
// // // fn interpret_locally(&self, inputs: &[i32]) -> Vec<i32> {
// // // // push-based interpretation:
// // // // sublist => interpret each item in sequence
// // // // if an instruction sees insufficient args => no-op
// // // unimplemented!()
// // // }
// // }
// use crate::compiler::ast::Push3Ast;
// /// An untyped AST node, matching your Push3 structure.
// #[derive(Debug, Clone)]
// pub enum UntypedAst {
// /// A single integer literal.
// IntLiteral(i32),
// /// A single push instruction (no subchildren).
// Instruction(OpCode),
// /// A sublist of items, each of which is another UntypedAst.
// Sublist(Vec<UntypedAst>),
// }
// /// Your Push3 opcodes in an untyped form.
// #[derive(Debug, Clone)]
// pub enum OpCode {
// Noop,
// Plus,
// Minus,
// Mult,
// Dup,
// Pop,
// }
// /// Implementation of `Push3Ast` for `UntypedAst`.
// ///
// /// This will produce **bytecode** compatible with your Solidity `Push3Interpreter`:
// ///
// /// - `0x00` => NOOP
// /// - `0x01` => INTEGER_PLUS
// /// - `0x02` => INT_LITERAL => next 4 bytes (little-endian i32)
// /// - `0x03` => SUBLIST => next 2 bytes (big-endian `u16` length), then the sublist contents
// /// - `0x04` => INTEGER_MINUS
// /// - `0x05` => INTEGER_MULT
// /// - `0x06` => INTEGER_DUP
// /// - `0x07` => INTEGER_POP
// ///
// /// In the Solidity parser, `SUBLIST (0x03)` consumes two bytes to determine
// /// how many bytes of tokens to read in that sublist.
// impl Push3Ast for UntypedAst {
// /// Convert this untyped AST into a flattened push3 bytecode sequence.
// fn to_bytecode(&self) -> Vec<u8> {
// match self {
// UntypedAst::IntLiteral(val) => {
// // 0x02 followed by 4 bytes of i32 (little-endian)
// let mut bytes = Vec::with_capacity(1 + 4);
// bytes.push(0x02);
// bytes.extend_from_slice(&val.to_le_bytes());
// bytes
// }
// UntypedAst::Instruction(op) => {
// // Single opcode byte
// let opcode_byte = match op {
// OpCode::Noop => 0x00,
// OpCode::Plus => 0x01,
// OpCode::Minus => 0x04,
// OpCode::Mult => 0x05,
// OpCode::Dup => 0x06,
// OpCode::Pop => 0x07,
// };
// vec![opcode_byte]
// }
// UntypedAst::Sublist(children) => {
// // 0x03 => SUBLIST
// // Then 2 bytes for length (big-endian u16),
// // Then the concatenated bytecode for all children.
// let mut payload = Vec::new();
// for child in children {
// let child_bytes = child.to_bytecode();
// payload.extend_from_slice(&child_bytes);
// }
// let sub_len = payload.len() as u16; // assume it fits in 65535
// let mut bytes = Vec::with_capacity(1 + 2 + payload.len());
// bytes.push(0x03);
// // Store the sublist length as big-endian, because readUint16 in solidity
// // does `val = uint16(word >> 240)` (effectively big-endian).
// bytes.extend_from_slice(&sub_len.to_be_bytes());
// // Then the actual sublist payload
// bytes.extend_from_slice(&payload);
// bytes
// }
// }
// }
// }
// #[derive(Debug, Clone, PartialEq)]
// pub enum SExpr {
// Atom(String), // e.g. "3", "DUP", "+"
// List(Vec<SExpr>), // e.g. (3 5 +)
// }
// fn tokenize(s: &str) -> Vec<String> {
// let mut tokens = Vec::new();
// let mut current = String::new();
// for c in s.chars() {
// match c {
// '(' | ')' => {
// // If we were building up an atom, push it first
// if !current.trim().is_empty() {
// tokens.push(current.trim().to_string());
// }
// current.clear();
// // Then push the single-char token
// tokens.push(c.to_string());
// }
// ' ' | '\t' | '\n' | '\r' => {
// // Whitespace => if we have an atom, finish it
// if !current.trim().is_empty() {
// tokens.push(current.trim().to_string());
// current.clear();
// }
// }
// _ => {
// // Part of an atom
// current.push(c);
// }
// }
// }
// // If something is left in 'current' at the end
// if !current.trim().is_empty() {
// tokens.push(current.trim().to_string());
// }
// tokens
// }
// fn parse_sexpr(tokens: &[String], pos: &mut usize) -> Result<SExpr, String> {
// // If we’re out of tokens, error
// if *pos >= tokens.len() {
// return Err("Unexpected end of tokens".into());
// }
// let token = &tokens[*pos];
// match token.as_str() {
// "(" => {
// // Parse a list
// *pos += 1; // consume '('
// let mut list_items = Vec::new();
// while *pos < tokens.len() && tokens[*pos] != ")" {
// let expr = parse_sexpr(tokens, pos)?;
// list_items.push(expr);
// }
// if *pos >= tokens.len() {
// return Err("Missing closing parenthesis".into());
// }
// // consume ")"
// *pos += 1;
// Ok(SExpr::List(list_items))
// }
// ")" => {
// // Should never parse_sexpr starting with ')'
// Err("Unexpected ')'".into())
// }
// _ => {
// // Atom
// let atom_str = token.clone();
// *pos += 1;
// Ok(SExpr::Atom(atom_str))
// }
// }
// }
// /// Parse an entire string into a single top-level `SExpr`.
// fn parse_string_to_sexpr(s: &str) -> Result<SExpr, String> {
// let tokens = tokenize(s);
// let mut pos = 0;
// let expr = parse_sexpr(&tokens, &mut pos)?;
// // If there's leftover tokens, optionally check
// if pos < tokens.len() {
// return Err(format!("Extra tokens after parse: {:?}", &tokens[pos..]));
// }
// Ok(expr)
// }
// fn sexpr_to_untyped(expr: &SExpr) -> Result<UntypedAst, String> {
// match expr {
// SExpr::Atom(text) => {
// // 1) try to parse as i32
// if let Ok(val) = text.parse::<i32>() {
// Ok(UntypedAst::IntLiteral(val))
// } else {
// // 2) otherwise parse as OpCode symbol
// match text.to_uppercase().as_str() {
// "+" => Ok(UntypedAst::Instruction(OpCode::Plus)),
// "-" => Ok(UntypedAst::Instruction(OpCode::Minus)),
// "*" => Ok(UntypedAst::Instruction(OpCode::Mult)),
// "DUP" => Ok(UntypedAst::Instruction(OpCode::Dup)),
// "POP" => Ok(UntypedAst::Instruction(OpCode::Pop)),
// // more opcodes ...
// _ => Ok(UntypedAst::Instruction(OpCode::Noop))
// }
// }
// }
// SExpr::List(list) => {
// // parse each child into UntypedAst
// let mut result = Vec::new();
// for child in list {
// result.push(sexpr_to_untyped(child)?);
// }
// Ok(UntypedAst::Sublist(result))
// }
// }
// }
// src/compiler/ast.rs
/// A trait describing how to convert an AST into Push3 bytecode.
///
/// This is deliberately minimal for now. In the future, we could add more methods
/// (like parsing from bytecode or AST mutation).
pub trait Push3Ast { pub trait Push3Ast {
/// Convert this AST into a bytecode vector that the on-chain interpreter /// Convert this AST into a bytecode array (Push3 tokens).
/// can parse and execute.
fn to_bytecode(&self) -> Vec<u8>; fn to_bytecode(&self) -> Vec<u8>;
} }
/// A trait that **maps** each [`OpCode`] variant to its **single-byte** representation. /* --------------------------------------------
/// 1) TypedAst stubs (optional)
/// By centralizing this, we can easily add or reorder instructions without rewriting -------------------------------------------- */
/// big chunks of code everywhere. For example, if we add `OpCode::MyNewOp`, we just
/// update this trait’s logic.
pub trait OpCodeMapping {
/// Given an `OpCode` enum variant, return the corresponding single `u8`
/// that the interpreter expects.
fn opcode_byte(&self, op: &OpCode) -> u8;
// If you need reverse-lookup (byte => OpCode), you could add a method like: #[derive(Debug, Clone)]
// fn from_byte(&self, b: u8) -> Option<OpCode>; pub enum TypedAst {
// for now, we omit it since we only do forward mapping in this file. IntLiteral(i32),
Instruction(InstructionKind),
} }
/// Our untyped AST node: #[derive(Debug, Clone)]
/// - `IntLiteral(i32)` holds a literal integer, pub enum InstructionKind {
/// - `Instruction(OpCode)` holds one opcode, Plus(Box<TypedAst>, Box<TypedAst>),
/// - `Sublist(Vec<UntypedAst>)` holds a collection of nested AST nodes. Minus(Box<TypedAst>, Box<TypedAst>),
#[derive(Debug, Clone, PartialEq)] Mult(Box<TypedAst>, Box<TypedAst>),
Dup,
Pop,
}
// Example stub; not fully implemented
impl Push3Ast for TypedAst {
fn to_bytecode(&self) -> Vec<u8> {
unimplemented!("TypedAst::to_bytecode not yet implemented");
}
}
/* --------------------------------------------
2) UntypedAst + OpCode
-------------------------------------------- */
#[derive(Debug, Clone)]
pub enum UntypedAst { pub enum UntypedAst {
IntLiteral(i32), IntLiteral(i32),
Instruction(OpCode), Instruction(OpCode),
Sublist(Vec<UntypedAst>), Sublist(Vec<UntypedAst>),
} }
/// An **abstract** set of opcodes. We do *not* assign numeric values here. #[derive(Debug, Clone)]
/// Instead, see [`OpCodeMapping::opcode_byte`] for how we convert them to bytes.
#[derive(Debug, Clone, PartialEq)]
pub enum OpCode { pub enum OpCode {
Noop, Noop,
Plus, Plus,
@@ -52,91 +377,57 @@ pub enum OpCode {
Mult, Mult,
Dup, Dup,
Pop, Pop,
// Add new instructions here as needed. E.g.:
// MyNewOp, etc.
} }
impl UntypedAst { /// Implementation of `Push3Ast` for `UntypedAst`.
/// Encode this AST into bytecode, using a provided [`OpCodeMapping`]. /// Matches the Solidity-based Push3Interpreter token IDs.
/// impl Push3Ast for UntypedAst {
/// This method is more flexible than `to_bytecode()`, because you can pass in fn to_bytecode(&self) -> Vec<u8> {
/// *any* mapping if needed. The method used by the trait’s `to_bytecode()`
/// relies on the global `DEFAULT_OP_MAPPING`.
pub fn to_bytecode_with_mapping<M: OpCodeMapping>(&self, mapping: &M) -> Vec<u8> {
match self { match self {
// For an integer literal, we write the “tag byte” for int-literal, then 4 bytes (LE).
UntypedAst::IntLiteral(val) => { UntypedAst::IntLiteral(val) => {
// Hardcode 0x02 => INT_LITERAL. // 0x02 => INT_LITERAL => next 4 bytes (little-endian i32)
// You *could* put that in the mapping if you want to make that flexible, too.
let mut bytes = Vec::with_capacity(1 + 4); let mut bytes = Vec::with_capacity(1 + 4);
bytes.push(0x02); bytes.push(0x02);
bytes.extend_from_slice(&val.to_be_bytes()); bytes.extend_from_slice(&val.to_be_bytes());
bytes bytes
} }
UntypedAst::Instruction(op) => { UntypedAst::Instruction(op) => {
// Use the mapping to find the correct opcode byte: let opcode_byte = match op {
let b = mapping.opcode_byte(op); OpCode::Noop => 0x00,
vec![b] OpCode::Plus => 0x01,
OpCode::Minus => 0x04,
OpCode::Mult => 0x05,
OpCode::Dup => 0x06,
OpCode::Pop => 0x07,
};
vec![opcode_byte]
} }
UntypedAst::Sublist(children) => { UntypedAst::Sublist(children) => {
// Hardcode 0x03 => SUBLIST, then big-endian length, then child payload // 0x03 => SUBLIST => next 2 bytes = big-endian length, then sub-payload
let mut payload = Vec::new(); let mut payload = Vec::new();
for child in children { for child in children {
let child_bytes = child.to_bytecode_with_mapping(mapping); payload.extend(child.to_bytecode());
payload.extend(child_bytes);
} }
let sub_len = payload.len() as u16; let sub_len = payload.len() as u16;
let mut bytes = Vec::with_capacity(1 + 2 + payload.len()); let mut bytes = Vec::with_capacity(1 + 2 + payload.len());
bytes.push(0x03); bytes.push(0x03);
bytes.extend_from_slice(&sub_len.to_be_bytes()); // big-endian length bytes.extend_from_slice(&sub_len.to_be_bytes()); // big-endian
bytes.extend(payload); bytes.extend_from_slice(&payload);
bytes bytes
} }
} }
} }
} }
/// For convenience, we implement `Push3Ast` using a *default* mapping. /* --------------------------------------------
impl Push3Ast for UntypedAst { 3) S-expression parsing helpers
fn to_bytecode(&self) -> Vec<u8> { -------------------------------------------- */
self.to_bytecode_with_mapping(&DEFAULT_OP_MAPPING)
}
}
/// A default mapping that corresponds to your current on-chain byte definitions.
///
/// This way, if your interpreter changes (e.g., `Minus` becomes 0x0A),
/// you just update this mapping.
pub struct DefaultOpCodeMapping;
impl OpCodeMapping for DefaultOpCodeMapping {
fn opcode_byte(&self, op: &OpCode) -> u8 {
match op {
OpCode::Noop => 0x00, // 0x00 => NOOP
OpCode::Plus => 0x01, // 0x01 => INTEGER_PLUS
OpCode::Minus => 0x04, // 0x04 => INTEGER_MINUS
OpCode::Mult => 0x05, // 0x05 => INTEGER_MULT
OpCode::Dup => 0x06, // 0x06 => INTEGER_DUP
OpCode::Pop => 0x07, // 0x07 => INTEGER_POP
}
}
}
/// A convenient global `const` or `static` for quick usage.
pub const DEFAULT_OP_MAPPING: DefaultOpCodeMapping = DefaultOpCodeMapping;
// ----------------------------------------------------------------------------
// S-Expression Parsing Helpers
// ----------------------------------------------------------------------------
/// A simple S-expression tree for textual representation: either an `Atom` or a `List`.
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]
pub enum SExpr { pub enum SExpr {
Atom(String), Atom(String),
List(Vec<SExpr>), List(Vec<SExpr>),
} }
/// Tokenize a string into parentheses and symbols (atoms).
pub fn tokenize(s: &str) -> Vec<String> { pub fn tokenize(s: &str) -> Vec<String> {
let mut tokens = Vec::new(); let mut tokens = Vec::new();
let mut current = String::new(); let mut current = String::new();
@@ -169,10 +460,9 @@ pub fn tokenize(s: &str) -> Vec<String> {
tokens tokens
} }
/// Recursive helper to parse a single S-expression from a list of tokens, advancing `pos`.
fn parse_sexpr_internal(tokens: &[String], pos: &mut usize) -> Result<SExpr, String> { fn parse_sexpr_internal(tokens: &[String], pos: &mut usize) -> Result<SExpr, String> {
if *pos >= tokens.len() { if *pos >= tokens.len() {
return Err("Unexpected end of tokens".to_string()); return Err("Unexpected end of tokens".into());
} }
let token = &tokens[*pos]; let token = &tokens[*pos];
@@ -185,52 +475,47 @@ fn parse_sexpr_internal(tokens: &[String], pos: &mut usize) -> Result<SExpr, Str
items.push(expr); items.push(expr);
} }
if *pos >= tokens.len() { if *pos >= tokens.len() {
return Err("Missing closing parenthesis".to_string()); return Err("Missing closing parenthesis".into());
} }
*pos += 1; // consume ')' *pos += 1; // consume ')'
Ok(SExpr::List(items)) Ok(SExpr::List(items))
} }
")" => Err("Unexpected ')'".to_string()), ")" => {
Err("Unexpected ')'".into())
}
_ => { _ => {
let atom_str = token.clone(); let atom = token.clone();
*pos += 1; *pos += 1;
Ok(SExpr::Atom(atom_str)) Ok(SExpr::Atom(atom))
} }
} }
} }
/// Parse a full string into a single top-level `SExpr`, assuming balanced parentheses. /// Parse an entire string into a single top-level `SExpr`.
pub fn parse_string_to_sexpr(s: &str) -> Result<SExpr, String> { pub fn parse_string_to_sexpr(s: &str) -> Result<SExpr, String> {
let tokens = tokenize(s); let tokens = tokenize(s);
let mut pos = 0; let mut pos = 0;
let expr = parse_sexpr_internal(&tokens, &mut pos)?; let expr = parse_sexpr_internal(&tokens, &mut pos)?;
if pos < tokens.len() { if pos < tokens.len() {
Err(format!( return Err(format!("Extra tokens after parse: {:?}", &tokens[pos..]));
"Extra tokens after parse: {:?}",
&tokens[pos..]
))
} else {
Ok(expr)
} }
Ok(expr)
} }
/// Convert an S-expression to an **untyped** AST node. /// Convert an SExpr => UntypedAst
pub fn sexpr_to_untyped(expr: &SExpr) -> Result<UntypedAst, String> { pub fn sexpr_to_untyped(expr: &SExpr) -> Result<UntypedAst, String> {
match expr { match expr {
SExpr::Atom(text) => { SExpr::Atom(text) => {
// 1) Try parse as integer
if let Ok(val) = text.parse::<i32>() { if let Ok(val) = text.parse::<i32>() {
Ok(UntypedAst::IntLiteral(val)) Ok(UntypedAst::IntLiteral(val))
} else { } else {
// 2) Otherwise interpret as an opcode
match text.to_uppercase().as_str() { match text.to_uppercase().as_str() {
"+" => Ok(UntypedAst::Instruction(OpCode::Plus)), "+" => Ok(UntypedAst::Instruction(OpCode::Plus)),
"-" => Ok(UntypedAst::Instruction(OpCode::Minus)), "-" => Ok(UntypedAst::Instruction(OpCode::Minus)),
"*" => Ok(UntypedAst::Instruction(OpCode::Mult)), "*" => Ok(UntypedAst::Instruction(OpCode::Mult)),
"DUP" => Ok(UntypedAst::Instruction(OpCode::Dup)), "DUP" => Ok(UntypedAst::Instruction(OpCode::Dup)),
"POP" => Ok(UntypedAst::Instruction(OpCode::Pop)), "POP" => Ok(UntypedAst::Instruction(OpCode::Pop)),
// unknown => treat as Noop _ => Ok(UntypedAst::Instruction(OpCode::Noop)),
_ => Ok(UntypedAst::Instruction(OpCode::Noop)),
} }
} }
} }
@@ -243,31 +528,3 @@ pub fn sexpr_to_untyped(expr: &SExpr) -> Result<UntypedAst, String> {
} }
} }
} }
// ----------------------------------------------------------------------------
// (Optional) Placeholder for a future typed AST
// ----------------------------------------------------------------------------
// /// In the future, we plan to define a `TypedAst` enum that ensures each operation
// /// has the correct number of typed children. We might also handle errors
// /// if an operation expects two integer children, but the user tries to attach
// /// a sublist or zero children, etc.
// ///
// /// For now, the untyped AST suffices for quick prototyping, but typed checks
// /// will be crucial in more advanced genetic programming or static analysis scenarios.
// #[derive(Debug, Clone)]
// pub enum TypedAst {
// // e.g. IntLiteral(i32),
// // Instruction(InstructionKind),
// }
// #[derive(Debug, Clone)]
// pub enum InstructionKind {
// // e.g. Plus(Box<TypedAst>, Box<TypedAst>),
// // Minus(Box<TypedAst>, Box<TypedAst>),
// // Mult(Box<TypedAst>, Box<TypedAst>),
// // Dup,
// // Pop,
// }
// // etc.
-1
View File
@@ -1,2 +1 @@
pub mod ast; pub mod ast;
pub mod push3_describtor;
-67
View File
@@ -1,67 +0,0 @@
//! src/compiler/push3_descriptor.rs
//!
//! A small module of helper functions to construct or interpret the 256-bit descriptors
//! used by our on-chain `Push3Interpreter`. Each descriptor encodes a tag, an offset,
//! a length, and any leftover bits (e.g., immediate data).
use ethers::types::U256;
/// The 256-bit descriptor layout is as follows:
/// [ 8 bits: tag | 32 bits: offset | 32 bits: length | 184 bits: leftover ]
///
/// We'll define small helper functions to build or parse these.
/// Our `make_sublist_descriptor` is an example for tag=3 (SUBLIST).
/// Tag constants, if you want them:
pub const TAG_SUBLIST: u8 = 3;
pub const TAG_INT_LITERAL: u8 = 2;
pub const TAG_INSTRUCTION: u8 = 1;
pub const TAG_NONE: u8 = 0;
/// A small helper to shift the tag into the top 8 bits.
#[inline]
fn tag_bits(tag: u8) -> U256 {
U256::from(tag) << 248
}
/// Build a descriptor for a SUBLIST with the given offset and length (in bytes),
/// leftover=0.
///
/// # Example
/// ```
/// let desc = make_sublist_descriptor(0, code_bytes.len() as u32);
/// // pass `desc` into the interpreter's exec stack
/// ```
pub fn make_sublist_descriptor(offset: u32, length: u32) -> U256 {
tag_bits(TAG_SUBLIST as u8)
| (U256::from(offset) << 216)
| (U256::from(length) << 184)
| U256::zero() // leftover
}
/// Possibly you want a more general helper that builds any descriptor:
/// If you have other uses for leftover bits, you can pass that in:
pub fn make_descriptor(tag: u8, offset: u32, length: u32, leftover: U256) -> U256 {
tag_bits(tag)
| (U256::from(offset) << 216)
| (U256::from(length) << 184)
| leftover
}
/// If you want to parse a descriptor, you can define getTag, getOffset, getLength, etc:
pub fn get_tag(desc: U256) -> u8 {
// top 8 bits => shift right 248
(desc >> 248).as_u32() as u8
}
pub fn get_offset(desc: U256) -> u32 {
((desc >> 216) & U256::from(u32::MAX)).as_u32()
}
pub fn get_length(desc: U256) -> u32 {
((desc >> 184) & U256::from(u32::MAX)).as_u32()
}
pub fn get_low_184(desc: U256) -> U256 {
desc & ((U256::from(1u64) << 184) - 1)
}
-79
View File
@@ -1,79 +0,0 @@
use rand::Rng;
use crate::compiler::ast::{UntypedAst, OpCode};
pub fn random_sublist_ast(rng: &mut impl Rng, max_depth: usize) -> UntypedAst {
// 1) Choose how many children the top-level `Sublist` will have.
let len = rng.gen_range(1..=3);
// 2) Build a vector of sub-ASTs by calling `random_ast` for each child
let mut children = Vec::with_capacity(len);
for _ in 0..len {
// We start at `depth=1` because the top-level sublist itself is `depth=0`.
children.push(random_ast(rng, 1, max_depth));
}
// 3) Return a `Sublist` as the root node
UntypedAst::Sublist(children)
}
/// Generate a random `UntypedAst` by recursively building sub-trees,
/// int literals, or instructions.
///
/// - `depth` tracks how deep we are in the tree.
/// - `max_depth` is the maximum allowed depth to prevent infinite recursion.
pub fn random_ast(rng: &mut impl Rng, depth: usize, max_depth: usize) -> UntypedAst {
if depth >= max_depth {
// Return something "terminal,"
// e.g. an IntLiteral or a single Instruction
random_terminal(rng)
} else {
// Weighted choice:
// 0 => IntLiteral,
// 1 => single Instruction,
// 2 => Sublist with children
let choice = rng.gen_range(0..3);
match choice {
0 => UntypedAst::IntLiteral(rng.gen_range(-10..10)),
1 => UntypedAst::Instruction(random_opcode(rng)),
2 => {
// Make a sublist with 1..=3 children
let len = rng.gen_range(1..=3);
let mut children = Vec::with_capacity(len);
for _ in 0..len {
children.push(random_ast(rng, depth + 1, max_depth));
}
UntypedAst::Sublist(children)
}
_ => unreachable!(),
}
}
}
/// Generate a random "terminal" node.
/// Typically either an int literal or a single instruction.
fn random_terminal(rng: &mut impl Rng) -> UntypedAst {
// Weighted choice:
// 0 => IntLiteral
// 1 => single Instruction
let choice = rng.gen_range(0..2);
match choice {
0 => UntypedAst::IntLiteral(rng.gen_range(-10..10)),
1 => UntypedAst::Instruction(random_opcode(rng)),
_ => unreachable!(),
}
}
/// Generate a random `OpCode` from your known set of instructions.
pub fn random_opcode(rng: &mut impl Rng) -> OpCode {
let choice = rng.gen_range(0..6);
// because we have 6 variants: Noop, Plus, Minus, Mult, Dup, Pop
match choice {
0 => OpCode::Noop,
1 => OpCode::Plus,
2 => OpCode::Minus,
3 => OpCode::Mult,
4 => OpCode::Dup,
5 => OpCode::Pop,
_ => unreachable!(),
}
}
-121
View File
@@ -1,121 +0,0 @@
use crate::compiler::ast::{UntypedAst, OpCode};
use rand::Rng;
use rand::prelude::SliceRandom;
#[derive(Clone, Debug)]
pub enum InstructionAtom {
/// A normal opcode, e.g. `Plus`, `Minus`, `Dup`, etc.
Opcode(OpCode),
/// An ephemeral random constant placeholder.
/// If chosen, we generate a random literal on the spot.
EphemeralInt,
// If you want ephemeral floats, booleans, etc., add more variants
}
/// A small struct to hold our entire “instruction set.”
#[derive(Clone, Debug)]
pub struct InstructionSet {
pub atoms: Vec<InstructionAtom>,
}
impl InstructionSet {
pub fn new_default() -> Self {
// Example: Some opcodes + ephemeral constant
// Tweak as you like
use InstructionAtom::*;
use OpCode::*;
Self {
atoms: vec![
Opcode(Noop),
Opcode(Plus),
Opcode(Minus),
Opcode(Mult),
Opcode(Dup),
Opcode(Pop),
EphemeralInt,
],
}
}
/// Pick a random atom from this set.
/// If it's `EphemeralInt`, we produce `UntypedAst::IntLiteral(...)`.
/// If it's `Opcode(...)`, we produce `UntypedAst::Instruction(...)`.
pub fn random_atom_as_ast(&self, rng: &mut impl Rng) -> UntypedAst {
let idx = rng.gen_range(0..self.atoms.len());
match &self.atoms[idx] {
InstructionAtom::Opcode(op) => UntypedAst::Instruction(op.clone()),
InstructionAtom::EphemeralInt => {
// For ephemeral int, produce a random literal in some range
let val = rng.gen_range(-30..30);
UntypedAst::IntLiteral(val)
}
}
}
}
pub fn ranmdom_code_fixed(rng: &mut impl Rng, max_points: usize) -> UntypedAst {
let instr_set = InstructionSet::new_default();
return random_code(rng, &instr_set, max_points);
}
/// The "entry point": random_code(max_points).
/// 1) Choose actual_points in [1..=max_points].
/// 2) Return the result of random_code_with_size.
pub fn random_code(rng: &mut impl Rng, instr_set: &InstructionSet, max_points: usize) -> UntypedAst {
let actual_points = rng.gen_range(1..=max_points);
random_code_with_size(rng, instr_set, actual_points)
}
/// The main logic:
/// If points == 1 => pick a single instruction/ephemeral
/// Else =>
/// - We "decompose" (points - 1) among sub-codes
/// - For each sub-points, we recursively call random_code_with_size
/// - We return a Sublist of those children, possibly in random order
pub fn random_code_with_size(
rng: &mut impl Rng,
instr_set: &InstructionSet,
points: usize,
) -> UntypedAst {
use UntypedAst::*;
// Base case
if points == 1 {
// Choose a random "atom" from instr_set
return instr_set.random_atom_as_ast(rng);
}
// If `points > 1`, let's produce a Sublist
// We'll break (points - 1) into sub-points via `decompose`
let subpoints_list = decompose(rng, points - 1, points - 1);
// subpoints_list is e.g. [2, 3, 5] and sums to (points-1)
// Then for each "subpoints", we do random_code_with_size
let mut sub_asts: Vec<UntypedAst> = subpoints_list
.into_iter()
.map(|sp| random_code_with_size(rng, instr_set, sp))
.collect();
// The spec says "Return a list containing the results, in random order"
// so let's shuffle sub_asts
sub_asts.shuffle(rng);
Sublist(sub_asts)
}
/// Decompose a number into random parts.
///
/// - If number is 1 or max_parts is 1 => return [number].
/// - Otherwise pick a random split "this_part" and recurse on the remainder.
fn decompose(rng: &mut impl Rng, number: usize, max_parts: usize) -> Vec<usize> {
if number == 1 || max_parts == 1 {
return vec![number];
}
// pick a random "this_part" in [1 .. (number-1)]
let this_part = rng.gen_range(1..number);
let mut remainder = decompose(rng, number - this_part, max_parts - 1);
let mut result = vec![this_part];
result.append(&mut remainder);
result
}
+8 -62
View File
@@ -1,64 +1,10 @@
use rand::Rng; // use crate::compiler::ast::{Expr};
use crate::compiler::ast::{UntypedAst, OpCode};
use crate::gp::generate::{random_ast, random_opcode};
/// Returns a new `UntypedAst` that is a mutated version of `original`. // pub fn crossover(a: &Expr, b: &Expr) -> (Expr, Expr) {
/// We do not modify `original`; we clone or build new pieces as needed. // // stub
/// // (a.clone(), b.clone())
/// - `depth`: current depth of this node, // }
/// - `max_depth`: max allowed depth (to prevent infinite recursion).
pub fn mutated_ast(original: &UntypedAst, rng: &mut impl Rng, depth: usize, max_depth: usize) -> UntypedAst {
// 10% chance: completely replace this node with a fresh random subtree
if rng.gen_range(0..100) < 10 {
return random_ast(rng, depth, max_depth);
}
match original { // pub fn mutate(expr: &mut Expr) {
UntypedAst::IntLiteral(val) => { // // stub
// Another small chance to replace the entire node with random subtree // }
if rng.gen_range(0..100) < 10 {
return random_ast(rng, depth, max_depth);
}
// Otherwise, "tweak" the int by a small offset
let delta = rng.gen_range(-2..=2);
let new_val = val.saturating_add(delta);
UntypedAst::IntLiteral(new_val)
}
UntypedAst::Instruction(op) => {
// 10% chance to replace node
if rng.gen_range(0..100) < 10 {
return random_ast(rng, depth, max_depth);
}
// 50% chance to pick a new opcode
// or else keep the same
if rng.gen_bool(0.5) {
UntypedAst::Instruction(random_opcode(rng))
} else {
// Just clone the original
UntypedAst::Instruction(op.clone())
}
}
UntypedAst::Sublist(children) => {
// 10% chance to replace this sublist entirely
if rng.gen_range(0..100) < 10 {
return random_ast(rng, depth, max_depth);
}
// Otherwise, mutate zero or more children
let mut new_children = children.clone();
if !new_children.is_empty() {
// Choose how many kids to mutate:
// e.g., 1..=min(2, children.len())
let mut_count = rng.gen_range(1..=new_children.len().min(2));
for _ in 0..mut_count {
let idx = rng.gen_range(0..new_children.len());
new_children[idx] = mutated_ast(&new_children[idx], rng, depth+1, max_depth);
}
}
UntypedAst::Sublist(new_children)
}
}
}
-114
View File
@@ -1,114 +0,0 @@
//! src/gp/local_mutation.rs
//! A localized mutation operator that makes small tweaks depending on node type.
use rand::Rng;
use crate::compiler::ast::{UntypedAst, OpCode};
use crate::gp::mutation::{
enum_nodes_dfs, get_subtree, replace_subtree,
};
use crate::gp::generate_spec::{
InstructionAtom, InstructionSet,
};
/// A top-level function to perform a localized mutation with a chosen `InstructionSet`.
pub fn local_mutation(
original: &UntypedAst,
rng: &mut impl Rng,
instr_set: &InstructionSet,
) -> UntypedAst {
let all_paths = enum_nodes_dfs(original);
let idx = rng.gen_range(0..all_paths.len());
let chosen_path = &all_paths[idx];
let old_subtree = get_subtree(original, chosen_path);
let new_subtree = local_mutation_node(&old_subtree, rng, instr_set);
replace_subtree(original, chosen_path, new_subtree)
}
/// A convenience wrapper that always uses `InstructionSet::new_default()`.
pub fn local_mutation_fixed(
original: &UntypedAst,
rng: &mut impl Rng,
) -> UntypedAst {
let instr_set = InstructionSet::new_default();
local_mutation(original, rng, &instr_set)
}
fn local_mutation_node(
subtree: &UntypedAst,
rng: &mut impl Rng,
instr_set: &InstructionSet,
) -> UntypedAst {
match subtree {
UntypedAst::IntLiteral(val) => {
let delta = rng.gen_range(-5..=5);
let new_val = val.saturating_add(delta);
UntypedAst::IntLiteral(new_val)
}
UntypedAst::Instruction(op) => {
let mut new_op = pick_random_opcode(rng, instr_set);
for _ in 0..3 {
if &new_op != op {
break;
}
new_op = pick_random_opcode(rng, instr_set);
}
UntypedAst::Instruction(new_op)
}
UntypedAst::Sublist(children) => {
let choice = rng.gen_range(0..3);
let mut new_children = children.clone();
match choice {
0 => {
// remove one child if possible
if !new_children.is_empty() {
let i = rng.gen_range(0..new_children.len());
new_children.remove(i);
}
}
1 => {
// insert a new small node
let i = rng.gen_range(0..=new_children.len());
let node = create_small_node(rng, instr_set);
new_children.insert(i, node);
}
2 => {
// reorder two children
if new_children.len() > 1 {
let i = rng.gen_range(0..new_children.len());
let j = rng.gen_range(0..new_children.len());
new_children.swap(i, j);
}
}
_ => {}
}
UntypedAst::Sublist(new_children)
}
}
}
fn pick_random_opcode(rng: &mut impl Rng, instr_set: &InstructionSet) -> OpCode {
use crate::compiler::ast::OpCode;
let mut opcode_list: Vec<&OpCode> = Vec::new();
for atom in &instr_set.atoms {
if let InstructionAtom::Opcode(ref op) = atom {
opcode_list.push(op);
}
}
if opcode_list.is_empty() {
// fallback => default to Noop
return OpCode::Noop;
}
let i = rng.gen_range(0..opcode_list.len());
opcode_list[i].clone()
}
fn create_small_node(
rng: &mut impl Rng,
instr_set: &InstructionSet,
) -> UntypedAst {
instr_set.random_atom_as_ast(rng)
}
+11 -4
View File
@@ -1,6 +1,13 @@
pub mod population; pub mod population;
pub mod genetic_ops; pub mod genetic_ops;
pub mod generate; // pub mod fitness;
pub mod generate_spec;
pub mod mutation; #[cfg(test)]
pub mod local_mutation; mod tests {
use super::*;
#[test]
fn test_dummy() {
assert_eq!(2+2, 4);
}
}
-147
View File
@@ -1,147 +0,0 @@
use rand::Rng;
use crate::compiler::ast::UntypedAst;
use crate::gp::generate_spec::ranmdom_code_fixed; // or push3-based generator
/// A "path" is a list of indices leading from the root to a child.
/// For example, [] is the root, [0] is the root's first child, [0,1] is that child's second child, etc.
pub type Path = Vec<usize>;
/// Enumerate all nodes in a DFS order (root first).
/// For each node, we store the `Path` (list of child indices).
pub fn enum_nodes_dfs(ast: &UntypedAst) -> Vec<Path> {
let mut paths = Vec::new();
dfs_helper(ast, &mut paths, &mut vec![]);
paths
}
/// Recursive helper: `current_path` is a stack we push child indices onto.
/// `paths` is the global list of final results.
fn dfs_helper(ast: &UntypedAst, paths: &mut Vec<Path>, current_path: &mut Vec<usize>) {
// Record the current path as a valid node
paths.push(current_path.clone());
match ast {
UntypedAst::Sublist(children) => {
// For each child, push its index, recurse, then pop
for (i, child) in children.iter().enumerate() {
current_path.push(i);
dfs_helper(child, paths, current_path);
current_path.pop();
}
}
UntypedAst::IntLiteral(_) | UntypedAst::Instruction(_) => {
// Leaf node => no children
}
}
}
/// Replace the node at `path` in `original` with `replacement`, returning a new AST.
/// If `path` is empty => we replace the root entirely.
pub fn replace_subtree(
original: &UntypedAst,
path: &[usize],
replacement: UntypedAst
) -> UntypedAst {
if path.is_empty() {
// means we’re replacing the root
return replacement;
}
// otherwise, we need to walk the sublist chain
match original {
UntypedAst::Sublist(children) => {
// let path_head = path[0], path_tail = path[1..]
let (first_idx, tail_path) = (path[0], &path[1..]);
let mut new_children = children.clone();
new_children[first_idx] = replace_subtree(&children[first_idx], tail_path, replacement);
UntypedAst::Sublist(new_children)
}
// If the path is not empty but we’re not in a Sublist => error or do nothing
UntypedAst::IntLiteral(_) | UntypedAst::Instruction(_) => {
// Possibly, if the path is invalid, we ignore. Or we treat it as "replace anyway."
// Here, we might treat it as an error or a no-op.
original.clone()
}
}
}
/// Produces a new AST by choosing exactly one node in `original` at random
/// (by enumerating them), and replacing it with a new random subtree.
pub fn mutate_by_index(
original: &UntypedAst,
rng: &mut impl Rng,
max_points: usize,
) -> UntypedAst {
// 1) Enumerate all nodes => get a vector of `Path`
let all_paths = enum_nodes_dfs(original);
// pick a random path
let idx = rng.gen_range(0..all_paths.len());
let chosen_path = &all_paths[idx];
// 2) Generate a new subtree with our "fixed" random code generator
let new_subtree = ranmdom_code_fixed(rng, max_points);
// 3) Replace the subtree at `chosen_path` in `original` with `new_subtree`
replace_subtree(original, chosen_path, new_subtree)
}
/// Return the subtree of `original` at `path`,
/// cloning it as a `UntypedAst`.
/// If `path` is empty => returns the entire `original`.
pub fn get_subtree(original: &UntypedAst, path: &[usize]) -> UntypedAst {
if path.is_empty() {
// The entire AST is the subtree
return original.clone();
}
match original {
UntypedAst::Sublist(children) => {
let (first_idx, tail_path) = (path[0], &path[1..]);
if first_idx >= children.len() {
// If path index is out of range, just clone the entire AST or
// do something fallback
return original.clone();
}
get_subtree(&children[first_idx], tail_path)
}
UntypedAst::IntLiteral(_) | UntypedAst::Instruction(_) => {
// If path is non-empty but this is a leaf,
// fallback: just return the leaf.
original.clone()
}
}
}
/// Perform a subtree crossover between two ASTs.
/// 1) We pick a random node in `a` and a random node in `b`,
/// 2) We swap those subtrees,
/// 3) Return the two new ASTs.
///
/// Example usage:
/// ```rust
/// let (childA, childB) = crossover_by_index(&parentA, &parentB, &mut rng);
/// ```
pub fn crossover_by_index(
a: &UntypedAst,
b: &UntypedAst,
rng: &mut impl Rng,
) -> (UntypedAst, UntypedAst) {
// 1) enumerate nodes in a
let paths_a = enum_nodes_dfs(a);
let idx_a = rng.gen_range(0..paths_a.len());
let chosen_a = &paths_a[idx_a];
// 2) enumerate nodes in b
let paths_b = enum_nodes_dfs(b);
let idx_b = rng.gen_range(0..paths_b.len());
let chosen_b = &paths_b[idx_b];
// 3) get subtree from a, from b
let subtree_a = get_subtree(a, chosen_a);
let subtree_b = get_subtree(b, chosen_b);
// 4) replace them
let new_a = replace_subtree(a, chosen_a, subtree_b);
let new_b = replace_subtree(b, chosen_b, subtree_a);
(new_a, new_b)
}
-41
View File
@@ -1,41 +0,0 @@
//! src/helpers/artifact.rs
//! A small helper module to read a Forge artifact JSON and extract the creation code.
use anyhow::{anyhow, bail, Result};
use serde::Deserialize;
use std::fs;
/// This mirrors the JSON structure: "bytecode": { "object": "...hex..." }
#[derive(Debug, Deserialize)]
struct BytecodeObject {
object: String,
}
/// The top-level artifact with a "bytecode" field.
#[derive(Debug, Deserialize)]
struct MyContractArtifact {
bytecode: BytecodeObject,
}
/// Reads the given JSON file (a Forge artifact) and returns the raw creation code bytes.
///
/// * `filename`: path to the artifact JSON (e.g. `../onchain/out/Push3Interpreter.sol/Push3Interpreter.json`)
pub fn get_creation_code(filename: &str) -> Result<Vec<u8>> {
// 1) Read the JSON file
let creation_json = fs::read_to_string(filename)
.map_err(|e| anyhow!("Failed to read JSON file {}: {}", filename, e))?;
// 2) Parse
let contract_artifact: MyContractArtifact = serde_json::from_str(&creation_json)
.map_err(|e| anyhow!("Failed to parse JSON artifact: {}", e))?;
// 3) Extract the hex code
let raw_hex = &contract_artifact.bytecode.object;
let stripped_hex = raw_hex.trim_start_matches("0x");
// 4) Convert from hex => bytes
match hex::decode(stripped_hex) {
Ok(bytes) => Ok(bytes),
Err(e) => bail!("Invalid hex for creation code: {e}"),
}
}
-1
View File
@@ -1 +0,0 @@
pub mod artifact;
-4
View File
@@ -1,4 +0,0 @@
pub mod compiler;
pub mod runner;
pub mod gp;
pub mod helpers;
+133 -75
View File
File diff suppressed because one or more lines are too long
-232
View File
@@ -1,232 +0,0 @@
//! src/evm_integration/revm_runner.rs
//!
//! This module provides a thin wrapper around REVM to deploy a Push3Interpreter
//! contract, then call its `runInterpreter(...)` function with flexible inputs/outputs,
//! using the same style (Context::builder(), .modify_tx_chained, etc.) you had in your main.
use anyhow::{anyhow, bail, Result};
use ethers::abi::{encode, decode, Token, ParamType};
use ethers::types::U256;
use ethers::utils;
use database::CacheDB;
use revm::{
context::Context,
context::{BlockEnv, TxEnv, CfgEnv},
context_interface::result::{ExecutionResult, Output},
database_interface::EmptyDB,
handler::EthHandler,
primitives::{Bytes, TxKind}, // 4 generics
EvmCommit,
MainEvm,
};
// We import your AST definitions so we can call `ast.to_bytecode()`.
use crate::compiler::ast::{UntypedAst, Push3Ast};
// If you have a descriptor helper (like make_sublist_descriptor), bring it in:
use crate::compiler::push3_describtor::make_sublist_descriptor;
/// The input parameters for `runInterpreter(...)`: four fields (code, codeStack, execStack, intStack).
pub struct Push3InterpreterInputs {
pub code: Vec<u8>,
pub init_code_stack: Vec<U256>,
pub init_exec_stack: Vec<U256>,
pub init_int_stack: Vec<i128>,
}
/// The outputs from `runInterpreter(...)`: three arrays for code/exec/int stacks.
pub struct Push3InterpreterOutputs {
pub final_code_stack: Vec<U256>,
pub final_exec_stack: Vec<U256>,
pub final_int_stack: Vec<i128>,
}
/// A thin wrapper around REVM, parameterized by the 4 generics (DB, BLOCK, TX, CFG).
/// - We store the ephemeral EVM instance,
/// - We store the deployed address of your `Push3Interpreter`,
/// - We provide `run_interpreter` and `run_ast`.
pub struct EvmRunner {
/// The 4-parameter MainEvm:
/// DB = CacheDB<EmptyDB>,
/// BLOCK = BlockEnv,
/// TX = TxEnv,
/// CFG = CfgEnv
pub evm: MainEvm<CacheDB<EmptyDB>, BlockEnv, TxEnv, CfgEnv>,
/// The address where Push3Interpreter was deployed.
pub interpreter_addr: revm::primitives::Address,
}
impl EvmRunner {
/// Deploy a new ephemeral EVM with a "Create" transaction for the given `creation_code`.
///
/// This matches your older style of:
/// `MainEvm::new(Context::builder()... .with_db(...), EthHandler::default())`
pub fn new(creation_code: Vec<u8>) -> Result<Self> {
// 1) Create the EVM using your old style: `Context::builder()...`
// Then pass to MainEvm::new(...).
// The difference is that we explicitly say MainEvm<DB,BLOCK,TX,CFG>.
let mut evm = MainEvm::new(
// a) Prepare context with a chained transaction to CREATE
Context::builder()
.modify_tx_chained(|tx| {
tx.transact_to = TxKind::Create;
tx.data = Bytes::from(creation_code.clone());
})
// b) Provide ephemeral DB
.with_db(CacheDB::<EmptyDB>::default()),
// c) The EthHandler for block/tx environment logic
EthHandler::default(),
);
// 2) Execute the CREATE transaction
let creation_result = evm.exec_commit()?;
let ExecutionResult::Success {
output: Output::Create(_, Some(deployed_addr)),
..
} = creation_result
else {
bail!("Interpreter deployment failed or no address returned: {creation_result:#?}");
};
// 3) Return the EvmRunner
Ok(Self {
evm,
interpreter_addr: deployed_addr,
})
}
/// Call `runInterpreter(bytes,uint256[],uint256[],int256[])` on the deployed contract,
/// returning the final code/exec/int stacks.
pub fn run_interpreter(
&mut self,
inputs: &Push3InterpreterInputs
) -> Result<Push3InterpreterOutputs> {
// 1) Build function selector
let func_selector = &utils::id("runInterpreter(bytes,uint256[],uint256[],int256[])")[0..4];
// 2) Convert each field to `ethers::abi::Token`
let code_token = Token::Bytes(inputs.code.clone());
let init_code_stack = Token::Array(
inputs.init_code_stack
.iter()
.map(|&u| Token::Uint(u))
.collect()
);
let init_exec_stack = Token::Array(
inputs.init_exec_stack
.iter()
.map(|&u| Token::Uint(u))
.collect()
);
let init_int_stack = Token::Array(
inputs.init_int_stack
.iter()
.map(|&val_i128| {
// store i128 as a U256. If you need negative values, do a two’s complement approach.
let as_u128 = val_i128 as u128;
Token::Int(U256::from(as_u128))
})
.collect()
);
// 3) Encode
let encoded_args = encode(&[
code_token,
init_code_stack,
init_exec_stack,
init_int_stack,
]);
// 4) Build final call data
let mut call_data = Vec::from(func_selector);
call_data.extend_from_slice(&encoded_args);
// 5) Modify the transaction to CALL the deployed interpreter
self.evm.context.modify_tx(|tx| {
tx.transact_to = TxKind::Call(self.interpreter_addr);
tx.data = Bytes::from(call_data);
tx.nonce = 1; // increment nonce to avoid reuse
});
// 6) Execute the call
let call_result = self.evm.transact()?;
match &call_result.result {
ExecutionResult::Success {
output: Output::Call(return_data),
..
} => {
// 7) Decode (uint256[], uint256[], int256[])
let param_types = &[
ParamType::Array(Box::new(ParamType::Uint(256))), // finalCodeStack
ParamType::Array(Box::new(ParamType::Uint(256))), // finalExecStack
ParamType::Array(Box::new(ParamType::Int(256))), // finalIntStack
];
let decoded = decode(param_types, return_data)
.map_err(|e| anyhow!("Failed to decode return data: {e}"))?;
// parse each array
let final_code_stack = match &decoded[0] {
Token::Array(arr) => arr.iter().filter_map(|t| {
if let Token::Uint(u) = t { Some(*u) } else { None }
}).collect(),
_ => Vec::new(),
};
let final_exec_stack = match &decoded[1] {
Token::Array(arr) => arr.iter().filter_map(|t| {
if let Token::Uint(u) = t { Some(*u) } else { None }
}).collect(),
_ => Vec::new(),
};
let final_int_stack = match &decoded[2] {
Token::Array(arr) => arr.iter().filter_map(|t| {
if let Token::Int(u256_val) = t {
// read only the lower 128 bits => ignoring sign extension
let lo = u256_val.low_u128();
Some(lo as i128)
} else {
None
}
}).collect(),
_ => Vec::new(),
};
Ok(Push3InterpreterOutputs {
final_code_stack,
final_exec_stack,
final_int_stack,
})
}
ExecutionResult::Revert { gas_used, output } => {
bail!("Call reverted: gas used={gas_used:?}, output={output:?}")
}
other => {
bail!("Call failed: {other:?}")
}
}
}
/// A convenience method to run an `UntypedAst`:
/// - Convert AST => push3 code,
/// - Build a sublist descriptor in the exec stack,
/// - Call `run_interpreter`.
pub fn run_ast(&mut self, ast: &UntypedAst) -> Result<Push3InterpreterOutputs> {
// 1) Convert AST => push3 bytecode
let code_bytes = ast.to_bytecode();
let code_len = code_bytes.len() as u32;
// 2) Build a sublist descriptor
let descriptor = make_sublist_descriptor(0, code_len);
// 3) Put code in `code` and sublist descriptor in `execStack`
let inputs = Push3InterpreterInputs {
code: code_bytes,
init_code_stack: Vec::new(),
init_exec_stack: vec![descriptor],
init_int_stack: Vec::new(),
};
// 4) Run interpreter
self.run_interpreter(&inputs)
}
}
+21 -13
View File
@@ -28,9 +28,9 @@ contract Push3IntAdapter {
view view
returns (uint256) returns (uint256)
{ {
// CodeTag.SUBLIST is typically enum = 3, but // CodeTag.SUBLIST is typically enum = 4, but
// let's fetch it via // let's fetch it via
// (uint8)Push3Interpreter.CodeTag.SUBLIST // (uint8)Push3Interpreter.CodeTag.SUBLIST
// or we can directly pass 3 if we know the numeric value. // or we can directly pass 3 if we know the numeric value.
// We'll do: // We'll do:
@@ -69,9 +69,12 @@ contract Push3IntAdapter {
int256[] memory initIntStack = new int256[](1); int256[] memory initIntStack = new int256[](1);
initIntStack[0] = in1; initIntStack[0] = in1;
// No bool stack
bool[] memory initBoolStack = new bool[](0);
// 4) Run // 4) Run
(, , int256[] memory finalIntStack) = (, , int256[] memory finalIntStack,) =
interpreter.runInterpreter(code, initCodeStack, initExecStack, initIntStack); interpreter.runInterpreter(code, initCodeStack, initExecStack, initIntStack, initBoolStack);
// 5) Return top of final int stack // 5) Return top of final int stack
require(finalIntStack.length > 0, "No integer output produced"); require(finalIntStack.length > 0, "No integer output produced");
@@ -96,11 +99,13 @@ contract Push3IntAdapter {
initIntStack[0] = in1; initIntStack[0] = in1;
initIntStack[1] = in2; initIntStack[1] = in2;
(, , int256[] memory finalIntStack) = bool[] memory initBoolStack = new bool[](0);
interpreter.runInterpreter(code, initCodeStack, initExecStack, initIntStack);
(, , int256[] memory finalIntStack,) =
interpreter.runInterpreter(code, initCodeStack, initExecStack, initIntStack, initBoolStack);
require(finalIntStack.length > 0, "No integer output"); require(finalIntStack.length > 0, "No integer output");
out1 = finalIntStack[finalIntStack.length - 1]; out1 = finalIntStack[finalIntStack.length - 1];
} }
@@ -121,8 +126,10 @@ contract Push3IntAdapter {
int256[] memory initIntStack = new int256[](1); int256[] memory initIntStack = new int256[](1);
initIntStack[0] = in1; initIntStack[0] = in1;
(, , int256[] memory finalIntStack) = bool[] memory initBoolStack = new bool[](0);
interpreter.runInterpreter(code, initCodeStack, initExecStack, initIntStack);
(, , int256[] memory finalIntStack,) =
interpreter.runInterpreter(code, initCodeStack, initExecStack, initIntStack, initBoolStack);
require(finalIntStack.length >= 2, "Not enough outputs"); require(finalIntStack.length >= 2, "Not enough outputs");
out1 = finalIntStack[finalIntStack.length - 1]; out1 = finalIntStack[finalIntStack.length - 1];
@@ -130,7 +137,7 @@ contract Push3IntAdapter {
} }
/** /**
* @notice Zero int input, returns entire final int stack * @notice Zero int input, returns entire final int stack
*/ */
function run0InNOut(bytes calldata code) function run0InNOut(bytes calldata code)
external external
@@ -143,9 +150,10 @@ contract Push3IntAdapter {
uint256[] memory initCodeStack = new uint256[](0); uint256[] memory initCodeStack = new uint256[](0);
int256[] memory initIntStack = new int256[](0); int256[] memory initIntStack = new int256[](0);
bool[] memory initBoolStack = new bool[](0);
(, , int256[] memory finalIntStack) = (, , int256[] memory finalIntStack,) =
interpreter.runInterpreter(code, initCodeStack, initExecStack, initIntStack); interpreter.runInterpreter(code, initCodeStack, initExecStack, initIntStack, initBoolStack);
return finalIntStack; return finalIntStack;
} }
+296 -94
View File
@@ -9,6 +9,15 @@ import "forge-std/console.sol";
* a token-based bytecode approach. * a token-based bytecode approach.
*/ */
contract Push3Interpreter { contract Push3Interpreter {
// ReadUint`numBits` out of the code range.
error ReadUintOutOfRange(uint256 numBits);
// -----------------------------------------------------
// 0. CONSTANTS
// -----------------------------------------------------
uint8 internal constant OPCODE_INTEGER_OFFSET = uint8(OpCode.INTEGER_PLUS);
uint8 internal constant OPCODE_BOOL_OFFSET = uint8(OpCode.BOOL_DUP);
uint8 internal constant OPCODE_LAST = uint8(OpCode.BOOL_RAND);
// ----------------------------------------------------- // -----------------------------------------------------
// 1. ENUMS // 1. ENUMS
// ----------------------------------------------------- // -----------------------------------------------------
@@ -16,16 +25,38 @@ contract Push3Interpreter {
NO_TAG, // 0 NO_TAG, // 0
INSTRUCTION, // 1 INSTRUCTION, // 1
INT_LITERAL, // 2 INT_LITERAL, // 2
SUBLIST // 3 BOOL_LITERAL, // 3
SUBLIST // 4
} }
enum OpCode { enum OpCode {
NOOP, // 0 NOOP, // 0
INTEGER_PLUS, // 1 NOOP_1, // 1 - empty for INSTRUCTION
INTEGER_MINUS, // 2 NOOP_2, // 2 - empty for INT_LITERAL
INTEGER_MULT, // 3 NOOP_3, // 3 - empty for BOOL_LITERAL
INTEGER_DUP, // 4 NOOP_4, // 4 - empty for SUBLIST
INTEGER_POP // 5 INTEGER_PLUS, // 5 - OPCODE_INTEGER_OFFSET
INTEGER_MINUS, // OPCODE_INTEGER_OFFSET + 1
INTEGER_MULT, // OPCODE_INTEGER_OFFSET + 2
INTEGER_DUP, // OPCODE_INTEGER_OFFSET + 3
INTEGER_POP, // OPCODE_INTEGER_OFFSET + 4
BOOL_DUP, // 10 - OPCODE_BOOL_OFFSET
BOOL_POP, // OPCODE_BOOL_OFFSET + 1
BOOL_SWAP, // OPCODE_BOOL_OFFSET + 2
BOOL_FLUSH, // OPCODE_BOOL_OFFSET + 3
BOOL_STACKDEPTH, // OPCODE_BOOL_OFFSET + 4
BOOL_NOT, // OPCODE_BOOL_OFFSET + 5
BOOL_AND, // OPCODE_BOOL_OFFSET + 6
BOOL_OR, // OPCODE_BOOL_OFFSET + 7
BOOL_EQ, // OPCODE_BOOL_OFFSET + 8
BOOL_FROMFLOAT, // OPCODE_BOOL_OFFSET + 9
BOOL_FROMINTEGER,// OPCODE_BOOL_OFFSET + 10
BOOL_ROT, // OPCODE_BOOL_OFFSET + 11
BOOL_SHOVE, // OPCODE_BOOL_OFFSET + 12
BOOL_YANK, // OPCODE_BOOL_OFFSET + 13
BOOL_YANKDUP, // OPCODE_BOOL_OFFSET + 14
BOOL_DEFINE, // OPCODE_BOOL_OFFSET + 15
BOOL_RAND // OPCODE_BOOL_OFFSET + 16
} }
// ----------------------------------------------------- // -----------------------------------------------------
@@ -85,56 +116,81 @@ contract Push3Interpreter {
return makeDescriptor(CodeTag.INT_LITERAL, 0, 0, masked); return makeDescriptor(CodeTag.INT_LITERAL, 0, 0, masked);
} }
function makeBoolLiteral(bool val) internal pure returns (uint256) {
uint256 masked;
if (val) masked = uint256(1);
return makeDescriptor(CodeTag.BOOL_LITERAL, 0, 0, masked);
}
function extractInt32(uint256 desc) internal pure returns (int32) { function extractInt32(uint256 desc) internal pure returns (int32) {
// read the low 32 bits // read the low 32 bits
return int32(uint32(getLow184(desc))); return int32(uint32(getLow184(desc)));
} }
function extractBool(uint256 desc) internal pure returns (bool) {
return desc & 1 == 1;
}
// ----------------------------------------------------- // -----------------------------------------------------
// 3. HELPER READS // 3. HELPER READS
// ----------------------------------------------------- // -----------------------------------------------------
/**
* @dev Read `x` bytes from `code` at `start` as uint.
*/
function readUint(bytes calldata code, uint32 start, uint256 numBytes) internal pure returns (uint256 word) {
uint256 numBits = numBytes * 8;
if (start + numBytes > code.length) revert ReadUintOutOfRange(numBits);
assembly {
let buf := mload(0x40) // free memory
// copy exactly x bytes from code into buf
calldatacopy(buf, add(code.offset, start), numBytes)
word := mload(buf)
}
word >>= 256 - numBits;
}
/** /**
* @dev Read 4 bytes from `code` at `start` as uint32. * @dev Read 4 bytes from `code` at `start` as uint32.
*/ */
function readUint32(bytes calldata code, uint32 start) internal pure returns (uint32 val) { function readUint32(bytes calldata code, uint32 start) internal pure returns (uint32 val) {
require(start + 4 <= code.length, "readUint32 out of range"); val = uint32(readUint(code, start, 4));
uint256 word;
assembly {
let buf := mload(0x40) // free memory
// copy exactly 4 bytes from code into buf
calldatacopy(buf, add(code.offset, start), 4)
word := mload(buf)
}
val = uint32(word >> 224);
} }
/** /**
* @dev Read 2 bytes from `code` at `start` as uint16. * @dev Read 2 bytes from `code` at `start` as uint16.
*/ */
function readUint16(bytes calldata code, uint32 start) internal pure returns (uint16 val) { function readUint16(bytes calldata code, uint32 start) internal pure returns (uint16 val) {
require(start + 2 <= code.length, "readUint16 out of range"); val = uint16(readUint(code, start, 2));
uint256 word; }
assembly {
let buf := mload(0x40) /**
calldatacopy(buf, add(code.offset, start), 2) * @dev Read 1 byte from `code` at `start` as uint8.
word := mload(buf) */
val := and(word, 0xffff) function readUint8(bytes calldata code, uint32 start) internal pure returns (uint8 val) {
} val = uint8(readUint(code, start, 1));
// Not sure this is correct }
val = uint16(word >> 240);
/**
* @dev Read 1 byte from `code` at `start` as bool.
*/
function readBool(bytes calldata code, uint32 start) internal pure returns (bool val) {
val = readUint(code, start, 1) & 1 == 1;
} }
// ----------------------------------------------------- // -----------------------------------------------------
// 4. SUBLIST PARSING // 4. SUBLIST PARSING
// ----------------------------------------------------- // -----------------------------------------------------
/** /**
* Token format: * Token format is combination of ordered CodeTag and OpCode:
* 0x00 => NOOP * 0x00 => NOOP/NO_TAG
* 0x01 => INTEGER_PLUS * 0x01 => INSTRUCTION => read next 1 byte => OpCode
* 0x02 => INT_LITERAL => read next 4 bytes => int32 * 0x02 => INT_LITERAL => read next 4 bytes => int32
* 0x03 => SUBLIST => read next 2 bytes => subLen => parse that * 0x03 => BOOL_LITERAL => read next 1 byte => bool
* 0x04 => INTEGER_MINUS * 0x04 => SUBLIST => read next 2 bytes => subLen => parse that
* 0x05 => INTEGER_PLUS
* 0x06 => INTEGER_MINUS
* ... opcode list with type offsets
*/ */
function parseSublist(bytes calldata code, uint32 off, uint32 len) function parseSublist(bytes calldata code, uint32 off, uint32 len)
internal internal
@@ -160,9 +216,15 @@ contract Push3Interpreter {
count++; count++;
} }
else if (tokenType == 0x01) { else if (tokenType == 0x01) {
// INTEGER_PLUS // INSTRUCTION
temp[count] = makeInstruction(OpCode.INTEGER_PLUS); if (cur + 1 <= endPos && (cur + 1) <= code.length) {
count++; uint8 opcode = readUint8(code,cur);
if (opcode < OPCODE_INTEGER_OFFSET || opcode > OPCODE_LAST) opcode = uint8(0); // NOOP
temp[count] = makeInstruction(OpCode(opcode));
count++;
} else {
break;
}
} }
else if (tokenType == 0x02) { else if (tokenType == 0x02) {
// INT_LITERAL => 4 bytes // INT_LITERAL => 4 bytes
@@ -177,6 +239,17 @@ contract Push3Interpreter {
} }
} }
else if (tokenType == 0x03) { else if (tokenType == 0x03) {
// BOOL_LITERAL
if (cur + 1 <= endPos && (cur + 1) <= code.length) {
bool val = readBool(code, cur);
cur += 1;
temp[count] = makeBoolLiteral(val);
count++;
} else {
break;
}
}
else if (tokenType == 0x04) {
// SUBLIST => read 2 bytes => length // SUBLIST => read 2 bytes => length
if (cur + 2 <= endPos && (cur + 2) <= code.length) { if (cur + 2 <= endPos && (cur + 2) <= code.length) {
uint16 subLen = readUint16(code, cur); uint16 subLen = readUint16(code, cur);
@@ -194,22 +267,9 @@ contract Push3Interpreter {
break; break;
} }
} }
else if (tokenType == 0x04) { else if (tokenType <= OPCODE_LAST) {
// INTEGER_PLUS // OPCODE
temp[count] = makeInstruction(OpCode.INTEGER_MINUS); temp[count] = makeInstruction(OpCode(tokenType));
count++;
}
else if (tokenType == 0x05) {
// INTEGER_PLUS
temp[count] = makeInstruction(OpCode.INTEGER_MULT);
count++;
}
else if (tokenType == 0x06) {
temp[count] = makeInstruction(OpCode.INTEGER_DUP);
count++;
}
else if (tokenType == 0x07) {
temp[count] = makeInstruction(OpCode.INTEGER_POP);
count++; count++;
} }
else { else {
@@ -229,17 +289,19 @@ contract Push3Interpreter {
// 5. MAIN INTERPRETER // 5. MAIN INTERPRETER
// ----------------------------------------------------- // -----------------------------------------------------
function runInterpreter( function runInterpreter(
bytes calldata code, bytes calldata code, // non-empty - genetic agent (DNA)
uint256[] calldata initCodeStack, uint256[] calldata initCodeStack, // empty
uint256[] calldata initExecStack, uint256[] calldata initExecStack, // descriptors
int256[] calldata initIntStack int256[] calldata initIntStack, // 32bit word
bool[] calldata initBoolStack // bool array
) )
external external
pure view
returns ( returns (
uint256[] memory finalCodeStack, uint256[] memory finalCodeStack,
uint256[] memory finalExecStack, uint256[] memory finalExecStack,
int256[] memory finalIntStack int256[] memory finalIntStack,
bool[] memory finalBoolStack
) )
{ {
// A) CODE STACK // A) CODE STACK
@@ -263,6 +325,13 @@ contract Push3Interpreter {
intStack[k] = initIntStack[k]; intStack[k] = initIntStack[k];
} }
// D) BOOL STACK
bool[] memory boolStack = new bool[](initBoolStack.length + 256);
uint256 boolTop = initBoolStack.length;
for (uint256 k = 0; k < initBoolStack.length; k++) {
boolStack[k] = initBoolStack[k];
}
// D) MAIN LOOP // D) MAIN LOOP
while (execTop > 0) { while (execTop > 0) {
uint256 topDesc = execStack[execTop - 1]; uint256 topDesc = execStack[execTop - 1];
@@ -272,49 +341,172 @@ contract Push3Interpreter {
if (tag == CodeTag.INSTRUCTION) { if (tag == CodeTag.INSTRUCTION) {
OpCode op = getOpCode(topDesc); OpCode op = getOpCode(topDesc);
if (op == OpCode.NOOP) { if (uint8(op) < OPCODE_INTEGER_OFFSET) {
// do nothing // NOOP, do nothing
} }
else if (op == OpCode.INTEGER_PLUS) { else if (uint8(op) < OPCODE_BOOL_OFFSET) {
// pop top 2 => sum // INTEGER OPCODES
if (intTop >= 2) { if (op == OpCode.INTEGER_PLUS) {
int256 a = intStack[intTop - 1]; // pop top 2 => sum
int256 b = intStack[intTop - 2]; if (intTop >= 2) {
intTop -= 2; int256 a = intStack[intTop - 1];
intStack[intTop] = b + a; int256 b = intStack[intTop - 2];
intTop++; intTop -= 2;
intStack[intTop] = b + a;
intTop++;
}
}
else if (op == OpCode.INTEGER_MINUS) {
// pop top 2 => minus
if (intTop >= 2) {
int256 a = intStack[intTop - 1];
int256 b = intStack[intTop - 2];
intTop -= 2;
intStack[intTop] = b - a;
intTop++;
}
}
else if (op == OpCode.INTEGER_MULT) {
// pop top 2 => minus
if (intTop >= 2) {
int256 a = intStack[intTop - 1];
int256 b = intStack[intTop - 2];
intTop -= 2;
intStack[intTop] = b * a;
intTop++;
}
}
else if (op == OpCode.INTEGER_DUP) {
if (intTop >= 1) {
int256 a = intStack[intTop - 1];
intStack[intTop] = a;
intTop++;
}
}
else if (op == OpCode.INTEGER_POP) {
if (intTop >= 1) {
intTop -= 1;
}
} }
} }
else if (op == OpCode.INTEGER_MINUS) { else if (uint8(op) <= OPCODE_LAST) {
// pop top 2 => minus // BOOL OPCODES
if (intTop >= 2) { if (op == OpCode.BOOL_DUP) {
int256 a = intStack[intTop - 1]; // dup top
int256 b = intStack[intTop - 2]; if (boolTop > 0) {
intTop -= 2; boolStack[boolTop] = boolStack[boolTop - 1];
intStack[intTop] = b - a; boolTop++;
}
}
else if (op == OpCode.BOOL_POP) {
// pop top
if (boolTop > 0) {
boolTop--;
}
}
else if (op == OpCode.BOOL_SWAP) {
// swap top 2
if (boolTop > 1) {
(boolStack[boolTop - 1], boolStack[boolTop - 2]) = (boolStack[boolTop - 2], boolStack[boolTop - 1]);
}
}
else if (op == OpCode.BOOL_FLUSH) {
// empty stack
boolTop = 0;
}
else if (op == OpCode.BOOL_STACKDEPTH) {
// push bool depth onto int stack
intStack[intTop] = int256(boolTop);
intTop++; intTop++;
} }
} else if (op == OpCode.BOOL_NOT) {
else if (op == OpCode.INTEGER_MULT) { // push NOT of top
// pop top 2 => minus if (boolTop > 0) {
if (intTop >= 2) { boolStack[boolTop - 1] = !boolStack[boolTop - 1];
int256 a = intStack[intTop - 1]; }
int256 b = intStack[intTop - 2];
intTop -= 2;
intStack[intTop] = b * a;
intTop++;
} }
} else if (op == OpCode.BOOL_AND) {
else if (op == OpCode.INTEGER_DUP) { // push AND of top 2
if (intTop >= 1) { if (boolTop > 1) {
int256 a = intStack[intTop - 1]; boolStack[boolTop - 2] = boolStack[boolTop - 1] && boolStack[boolTop - 2];
intStack[intTop] = a; boolTop--;
intTop++; }
} }
} else if (op == OpCode.BOOL_OR) {
else if (op == OpCode.INTEGER_POP) { // push OR of top 2
if (intTop >= 1) { if (boolTop > 1) {
intTop -= 1; boolStack[boolTop - 2] = boolStack[boolTop - 1] || boolStack[boolTop - 2];
boolTop--;
}
}
else if (op == OpCode.BOOL_EQ) {
// push True if top 2 equal
if (boolTop > 1) {
boolStack[boolTop - 2] = boolStack[boolTop - 1] == boolStack[boolTop - 2];
boolTop--;
}
}
else if (op == OpCode.BOOL_FROMFLOAT) {
// FLOAT is not implemented yet
}
else if (op == OpCode.BOOL_FROMINTEGER) {
// push True if top int not eq 0
if (intTop > 0) {
boolStack[boolTop] = intStack[intTop - 1] != int256(0);
boolTop++;
intTop--;
}
}
else if (op == OpCode.BOOL_ROT) {
// rotate [top - 3, top - 2, top - 1] into -> [top - 2, top - 1, top - 3]
if (boolTop > 2) {
(boolStack[boolTop - 1], boolStack[boolTop - 2], boolStack[boolTop - 3]) = (boolStack[boolTop - 3], boolStack[boolTop - 1], boolStack[boolTop - 2]);
}
}
else if (op == OpCode.BOOL_SHOVE) {
// Task: Inserts the top BOOLEAN "deep" in the stack, at the position indexed by the top INTEGER.
// Questions: what does "inserts" mean? does it mean that we pop top value and then insert it
// at index? does it mean that array size does not change?
// what happens with the previous element at this index?
// is it correct that this element stays in array?
// should it be moved in top or bottom direction from index (index + || -)?
// does it mean that we need to reindex the whole stack?
// is the simplest solution to reindex to iterate through the whole stack?
// do we really want have such loops?
}
else if (op == OpCode.BOOL_YANK) {
// Task: Removes an indexed item from "deep" in the stack and pushes it on top of the stack. The index is taken from the INTEGER stack.
// Same question as for SHOVE is valid here.
// For example, in our implementation currently we are not really poping
// element from an array in POP, we only adjusting the counter.
// For removing index we would need to loop over the array to reindex.
}
else if (op == OpCode.BOOL_YANKDUP) {
// Task: Pushes a copy of an indexed item "deep" in the stack onto the top of the stack, without removing the deep item. The index is taken from the INTEGER stack.
uint256 index = uint256(intStack[intTop - 1]);
if (boolTop > 2) {
// pop int stack
intTop--;
// index in range (reverse array indexes)
index++; // adjust as boolTop is length, highest index is boolTop - 1
if (index > boolTop) {
index = 0;
} else {
index = boolTop - index;
}
// push value on bool stack
boolStack[boolTop] = boolStack[index];
boolTop++;
}
}
else if (op == OpCode.BOOL_DEFINE) {
// NAME is not implemented yet
}
else if (op == OpCode.BOOL_RAND) {
// Pushes a random BOOLEAN.
uint256 randomNum = uint256(keccak256(abi.encodePacked(block.prevrandao, block.timestamp, msg.sender)));
boolStack[boolTop] = extractBool(randomNum);
boolTop++;
} }
} }
} }
@@ -323,6 +515,11 @@ contract Push3Interpreter {
intStack[intTop] = int256(val); intStack[intTop] = int256(val);
intTop++; intTop++;
} }
else if (tag == CodeTag.BOOL_LITERAL) {
bool val = extractBool(topDesc);
boolStack[boolTop] = val;
boolTop++;
}
else if (tag == CodeTag.SUBLIST) { else if (tag == CodeTag.SUBLIST) {
// parse sublist => push in reverse // parse sublist => push in reverse
uint32 off = getOffset(topDesc); uint32 off = getOffset(topDesc);
@@ -330,8 +527,8 @@ contract Push3Interpreter {
if (off + len <= code.length) { if (off + len <= code.length) {
uint256[] memory parsed = parseSublist(code, off, len); uint256[] memory parsed = parseSublist(code, off, len);
for (uint256 p = 0; p < parsed.length; p++) { for (uint256 p = 0; p < parsed.length; p++) { // index 0 1 2
execStack[execTop] = parsed[parsed.length - 1 - p]; execStack[execTop] = parsed[parsed.length - 1 - p]; // [0x01, 0x20, 0x0a]
execTop++; execTop++;
} }
} }
@@ -356,5 +553,10 @@ contract Push3Interpreter {
for (uint256 i = 0; i < intTop; i++) { for (uint256 i = 0; i < intTop; i++) {
finalIntStack[i] = intStack[i]; finalIntStack[i] = intStack[i];
} }
finalBoolStack = new bool[](boolTop);
for (uint256 i = 0; i < boolTop; i++) {
finalBoolStack[i] = boolStack[i];
}
} }
} }
+11 -11
View File
@@ -23,12 +23,12 @@ contract Push3IntAdapterTest is Test {
} }
/** /**
* @notice Test run1In1Out with a minimal code array. * @notice Test run1In1Out with a minimal code array.
* For example, we might do a program that just leaves its input unchanged * For example, we might do a program that just leaves its input unchanged
* (like a NOOP). * (like a NOOP).
*/ */
function test_run1In1Out_noop() public view { function test_run1In1Out_noop() public view {
bytes memory code = hex"03000100"; bytes memory code = hex"04000100";
int256 inputVal = 123; int256 inputVal = 123;
int256 result = adapter.run1In1Out(code, inputVal); int256 result = adapter.run1In1Out(code, inputVal);
@@ -41,21 +41,21 @@ contract Push3IntAdapterTest is Test {
* @notice Test run2In1Out. We'll push 5, 7, do an op that leaves 12. * @notice Test run2In1Out. We'll push 5, 7, do an op that leaves 12.
*/ */
function test_run2In1Out_plus() public view { function test_run2In1Out_plus() public view {
bytes memory code = hex"03000101"; bytes memory code = hex"04000105";
int256 in1 = 5; int256 in1 = 5;
int256 in2 = 7; int256 in2 = 7;
int256 result = adapter.run2In1Out(code, in1, in2); int256 result = adapter.run2In1Out(code, in1, in2);
assertEq(result, 12, "Expected 5 + 7 = 12"); assertEq(result, 12, "Expected 5 + 7 = 12");
} }
/** /**
* @notice Test run1In2Out. Push a constant to a stack with 1. * @notice Test run1In2Out. Push a constant to a stack with 1.
* For now, we do a placeholder code. * For now, we do a placeholder code.
*/ */
function test_run1In2Out() public view { function test_run1In2Out() public view {
bytes memory code = hex"0300050200000003"; bytes memory code = hex"0400050200000003";
int256 inVal = 42; int256 inVal = 42;
(int256 top, int256 secondTop) = adapter.run1In2Out(code, inVal); (int256 top, int256 secondTop) = adapter.run1In2Out(code, inVal);
@@ -65,12 +65,12 @@ contract Push3IntAdapterTest is Test {
} }
/** /**
* @notice Test run0InNOut. * @notice Test run0InNOut.
* We'll feed a code that pushes some constants, and see the final stack. * We'll feed a code that pushes some constants, and see the final stack.
*/ */
function test_run0InNOut() public view { function test_run0InNOut() public view {
bytes memory code = hex"03000A02000000030200000005"; bytes memory code = hex"04000A02000000030200000005";
int256[] memory stackResult = adapter.run0InNOut(code); int256[] memory stackResult = adapter.run0InNOut(code);
+582 -51
View File
@@ -23,30 +23,30 @@ contract Push3InterpreterTest is Test {
* 3) Calls INTEGER_PLUS * 3) Calls INTEGER_PLUS
* *
* We'll store everything in a single SUBLIST: * We'll store everything in a single SUBLIST:
* 0x03 => SUBLIST * 0x04 => SUBLIST
* 0x00 0x0B => subLen=11 * 0x00 0x0B => subLen=11
* Then the next 11 bytes are: * Then the next 11 bytes are:
* 0x02 + (00 00 00 0A) => INT_LITERAL(10) * 0x02 + (00 00 00 0A) => INT_LITERAL(10)
* 0x02 + (00 00 00 20) => INT_LITERAL(32) * 0x02 + (00 00 00 20) => INT_LITERAL(32)
* 0x01 => INTEGER_PLUS * 0x05 => INTEGER_PLUS
* *
* So total = 1 + 2 + (1+4 + 1+4 + 1) = 14 bytes * So total = 1 + 2 + (1+4 + 1+4 + 1) = 14 bytes
* => 0x03 00 0B 02 00 00 00 0A 02 00 00 00 20 01 * => 0x04 00 0B 02 00 00 00 0A 02 00 00 00 20 05
*/ */
function test_LiteralsAndPlus() public view { function test_LiteralsAndPlus() public view {
// The final code array (14 bytes): // The final code array (14 bytes):
// [0] = 0x03 // [0] = 0x04
// [1..2] = 0x000B // [1..2] = 0x000B
// [3] = 0x02 // [3] = 0x02
// [4..7] = 0x0000000A => 10 // [4..7] = 0x0000000A => 10
// [8] = 0x02 // [8] = 0x02
// [9..12] = 0x00000020 => 32 // [9..12] = 0x00000020 => 32
// [13] = 0x01 => plus // [13] = 0x05 => plus
bytes memory code = hex"03000B020000000A020000002001"; bytes memory code = hex"04000B020000000A020000002005";
// Or fully concatenated: // Or fully concatenated:
// 0x03 00 0B 02 00 00 00 0A 02 00 00 00 20 01 // 0x04 00 0B 02 00 00 00 0A 02 00 00 00 20 05
// We'll parse offset=0, length=14 // We'll parse offset=0, length=14
uint256 sublistDesc = interpreter.makeDescriptor( uint256 sublistDesc = interpreter.makeDescriptor(
@@ -61,13 +61,15 @@ contract Push3InterpreterTest is Test {
initExecStack[0] = sublistDesc; initExecStack[0] = sublistDesc;
int256[] memory initIntStack = new int256[](0); int256[] memory initIntStack = new int256[](0);
bool[] memory initBoolStack = new bool[](0);
// Run it // Run it
( (
, ,
, ,
int256[] memory finalIntStack int256[] memory finalIntStack
) = interpreter.runInterpreter(code, initCodeStack, initExecStack, initIntStack); ,
) = interpreter.runInterpreter(code, initCodeStack, initExecStack, initIntStack, initBoolStack);
// Should produce finalIntStack = [42] // Should produce finalIntStack = [42]
assertEq(finalIntStack.length, 1, "finalIntStack should have length 1"); assertEq(finalIntStack.length, 1, "finalIntStack should have length 1");
@@ -78,25 +80,25 @@ contract Push3InterpreterTest is Test {
* @notice Test pushing literal 10, literal 3, then INTEGER_MINUS => (10 - 3) = 7 * @notice Test pushing literal 10, literal 3, then INTEGER_MINUS => (10 - 3) = 7
* *
* The plan: * The plan:
* 0x03 => SUBLIST token * 0x04 => SUBLIST token
* 0x00 0x0B => subLen=11 * 0x00 0x0B => subLen=11
* *
* Then 11 bytes: * Then 11 bytes:
* 0x02 + (00 00 00 0A) => INT_LITERAL(10) * 0x02 + (00 00 00 0A) => INT_LITERAL(10)
* 0x02 + (00 00 00 03) => INT_LITERAL(3) * 0x02 + (00 00 00 03) => INT_LITERAL(3)
* 0x04 => INTEGER_MINUS (assuming 0x04 is assigned to minus) * 0x06 => INTEGER_MINUS (assuming 0x06 is assigned to minus)
*/ */
function test_Minus() public view { function test_Minus() public view {
// We'll produce 14 total bytes, same structure as the plus example // We'll produce 14 total bytes, same structure as the plus example
// Format: [0x03, 0x000B, 0x02(10), 0x03(3), 0x04 => minus] // Format: [0x04, 0x000B, 0x02(10), 0x03(3), 0x06 => minus]
bytes memory code = hex"03000B020000000A020000000304"; bytes memory code = hex"04000B020000000A020000000306";
// Breaking it down: // Breaking it down:
// 0x03 => SUBLIST // 0x04 => SUBLIST
// 0x00 0x0B => length=11 // 0x00 0x0B => length=11
// 0x02 0000000A => INT_LITERAL(10) // 0x02 0000000A => INT_LITERAL(10)
// 0x02 00000003 => INT_LITERAL(3) // 0x02 00000003 => INT_LITERAL(3)
// 0x04 => INTEGER_MINUS // 0x06 => INTEGER_MINUS
// We'll parse offset=0, length=14 // We'll parse offset=0, length=14
uint256 sublistDesc = interpreter.makeDescriptor( uint256 sublistDesc = interpreter.makeDescriptor(
@@ -111,13 +113,15 @@ contract Push3InterpreterTest is Test {
initExecStack[0] = sublistDesc; initExecStack[0] = sublistDesc;
int256[] memory initIntStack = new int256[](0); int256[] memory initIntStack = new int256[](0);
bool[] memory initBoolStack = new bool[](0);
// Run // Run
( (
, ,
, ,
int256[] memory finalIntStack int256[] memory finalIntStack
) = interpreter.runInterpreter(code, initCodeStack, initExecStack, initIntStack); ,
) = interpreter.runInterpreter(code, initCodeStack, initExecStack, initIntStack, initBoolStack);
// Check final result => should be [7] // Check final result => should be [7]
assertEq(finalIntStack.length, 1, "finalIntStack should have length 1"); assertEq(finalIntStack.length, 1, "finalIntStack should have length 1");
@@ -128,25 +132,25 @@ contract Push3InterpreterTest is Test {
* @notice Test pushing literal 10, literal 3, then INTEGER_MULT => (10 * 3) = 30 * @notice Test pushing literal 10, literal 3, then INTEGER_MULT => (10 * 3) = 30
* *
* The plan: * The plan:
* 0x03 => SUBLIST token * 0x04 => SUBLIST token
* 0x00 0x0B => subLen=11 * 0x00 0x0B => subLen=11
* *
* Then 11 bytes: * Then 11 bytes:
* 0x02 + (00 00 00 0A) => INT_LITERAL(10) * 0x02 + (00 00 00 0A) => INT_LITERAL(10)
* 0x02 + (00 00 00 03) => INT_LITERAL(3) * 0x02 + (00 00 00 03) => INT_LITERAL(3)
* 0x05 => INTEGER_MULT * 0x07 => INTEGER_MULT
*/ */
function test_Mult() public view { function test_Mult() public view {
// We'll produce 14 total bytes, same structure as the plus example // We'll produce 14 total bytes, same structure as the plus example
// Format: [0x03, 0x000B, 0x02(10), 0x03(3), 0x05 => mul] // Format: [0x04, 0x000B, 0x02(10), 0x02(3), 0x07 => mul]
bytes memory code = hex"03000B020000000A020000000305"; bytes memory code = hex"04000B020000000A020000000307";
// Breaking it down: // Breaking it down:
// 0x03 => SUBLIST // 0x04 => SUBLIST
// 0x00 0x0B => length=11 // 0x00 0x0B => length=11
// 0x02 0000000A => INT_LITERAL(10) // 0x02 0000000A => INT_LITERAL(10)
// 0x02 00000003 => INT_LITERAL(3) // 0x02 00000003 => INT_LITERAL(3)
// 0x05 => INTEGER_MUL // 0x07 => INTEGER_MUL
// We'll parse offset=0, length=14 // We'll parse offset=0, length=14
uint256 sublistDesc = interpreter.makeDescriptor( uint256 sublistDesc = interpreter.makeDescriptor(
@@ -161,13 +165,15 @@ contract Push3InterpreterTest is Test {
initExecStack[0] = sublistDesc; initExecStack[0] = sublistDesc;
int256[] memory initIntStack = new int256[](0); int256[] memory initIntStack = new int256[](0);
bool[] memory initBoolStack = new bool[](0);
// Run // Run
( (
, ,
, ,
int256[] memory finalIntStack int256[] memory finalIntStack
) = interpreter.runInterpreter(code, initCodeStack, initExecStack, initIntStack); ,
) = interpreter.runInterpreter(code, initCodeStack, initExecStack, initIntStack, initBoolStack);
// Check final result => should be [30] // Check final result => should be [30]
assertEq(finalIntStack.length, 1, "finalIntStack should have length 1"); assertEq(finalIntStack.length, 1, "finalIntStack should have length 1");
@@ -176,12 +182,12 @@ contract Push3InterpreterTest is Test {
function test_Dup() public view { function test_Dup() public view {
bytes memory code = hex"030006020000000A06"; bytes memory code = hex"040009020000000A0803010A";
uint256 sublistDesc = interpreter.makeDescriptor( uint256 sublistDesc = interpreter.makeDescriptor(
Push3Interpreter.CodeTag.SUBLIST, Push3Interpreter.CodeTag.SUBLIST,
0, 0,
9, 12,
0 0
); );
@@ -190,26 +196,30 @@ contract Push3InterpreterTest is Test {
initExecStack[0] = sublistDesc; initExecStack[0] = sublistDesc;
int256[] memory initIntStack = new int256[](0); int256[] memory initIntStack = new int256[](0);
bool[] memory initBoolStack = new bool[](0);
// Run // Run
( (
, ,
, ,
int256[] memory finalIntStack int256[] memory finalIntStack,
) = interpreter.runInterpreter(code, initCodeStack, initExecStack, initIntStack); bool[] memory finalBoolStack
) = interpreter.runInterpreter(code, initCodeStack, initExecStack, initIntStack, initBoolStack);
assertEq(finalIntStack.length, 2, "finalIntStack should have length 1"); assertEq(finalIntStack.length, 2, "finalIntStack should have length 1");
assertEq(finalIntStack[0], finalIntStack[1], "The top 2 values on the stack should be equal."); assertEq(finalIntStack[0], finalIntStack[1], "The top 2 values on the int stack should be equal.");
assertEq(finalBoolStack.length, 2, "finalBoolStack should have length 2");
assertEq(finalBoolStack[0], finalBoolStack[1], "The top 2 values on the bool stack should be equal.");
} }
function test_Pop() public view { function test_Pop() public view {
bytes memory code = hex"030006020000000A07"; bytes memory code = hex"040009020000000A0903010B";
uint256 sublistDesc = interpreter.makeDescriptor( uint256 sublistDesc = interpreter.makeDescriptor(
Push3Interpreter.CodeTag.SUBLIST, Push3Interpreter.CodeTag.SUBLIST,
0, 0,
9, 12,
0 0
); );
@@ -218,33 +228,36 @@ contract Push3InterpreterTest is Test {
initExecStack[0] = sublistDesc; initExecStack[0] = sublistDesc;
int256[] memory initIntStack = new int256[](0); int256[] memory initIntStack = new int256[](0);
bool[] memory initBoolStack = new bool[](0);
// Run // Run
( (
, ,
, ,
int256[] memory finalIntStack int256[] memory finalIntStack,
) = interpreter.runInterpreter(code, initCodeStack, initExecStack, initIntStack); bool[] memory finalBoolStack
) = interpreter.runInterpreter(code, initCodeStack, initExecStack, initIntStack, initBoolStack);
assertEq(finalIntStack.length, 0, "finalIntStack should be empty"); assertEq(finalIntStack.length, 0, "finalIntStack should be empty");
assertEq(finalBoolStack.length, 0, "finalBoolStack should be empty");
} }
/** /**
* @notice Test with an unknown token (0xF0). * @notice Test with an unknown token (0xF0).
* We expect the parser to treat it as "unknown => NOOP" * We expect the parser to treat it as "unknown => NOOP"
* and produce a NOOP instruction descriptor. * and produce a NOOP instruction descriptor.
* We'll confirm finalIntStack remains empty (or unchanged). * We'll confirm finalIntStack remains empty (or unchanged).
*/ */
function test_UnknownToken() public view { function test_UnknownToken() public view {
// We'll create a 5-byte code: // We'll create a 5-byte code:
// 0x03 => SUBLIST // 0x04 => SUBLIST
// 0x00 0x01 => length=1 // 0x00 0x01 => length=1
// 0xF0 => unknown token // 0xF0 => unknown token
bytes memory code = hex"030001F0"; bytes memory code = hex"040001F0";
// We'll parse offset=0, length=4 // We'll parse offset=0, length=4
uint256 sublistDesc = interpreter.makeDescriptor( uint256 sublistDesc = interpreter.makeDescriptor(
Push3Interpreter.CodeTag.SUBLIST, Push3Interpreter.CodeTag.SUBLIST,
0, // offset 0, // offset
4, // length 4, // length
0 0
@@ -255,12 +268,14 @@ contract Push3InterpreterTest is Test {
uint256[] memory initExecStack = new uint256[](1); uint256[] memory initExecStack = new uint256[](1);
initExecStack[0] = sublistDesc; initExecStack[0] = sublistDesc;
int256[] memory initIntStack = new int256[](0); int256[] memory initIntStack = new int256[](0);
bool[] memory initBoolStack = new bool[](0);
( (
, ,
, ,
int256[] memory finalIntStack int256[] memory finalIntStack
) = interpreter.runInterpreter(code, initCodeStack, initExecStack, initIntStack); ,
) = interpreter.runInterpreter(code, initCodeStack, initExecStack, initIntStack, initBoolStack);
// finalIntStack should remain empty => no literal was pushed // finalIntStack should remain empty => no literal was pushed
assertEq(finalIntStack.length, 0, "Expected finalIntStack to remain empty with unknown token => NOOP"); assertEq(finalIntStack.length, 0, "Expected finalIntStack to remain empty with unknown token => NOOP");
@@ -268,18 +283,18 @@ contract Push3InterpreterTest is Test {
/** /**
* @notice Test a partial literal: we claim to have 4 bytes, but the code array ends early. * @notice Test a partial literal: we claim to have 4 bytes, but the code array ends early.
* This should trigger the `else { break; }` branch in parseSublist * This should trigger the `else { break; }` branch in parseSublist
* when trying to read 4 bytes for the INT_LITERAL. * when trying to read 4 bytes for the INT_LITERAL.
*/ */
function test_OutOfRangeLiteral() public view { function test_OutOfRangeLiteral() public view {
// 0x03 => SUBLIST // 0x04 => SUBLIST
// 0x00 0x04 => length=4 // 0x00 0x04 => length=4
// 0x02 => INT_LITERAL token // 0x02 => INT_LITERAL token
// Then we have only 1 byte left instead of 4 => insufficient // Then we have only 1 byte left instead of 4 => insufficient
// //
// total = 1 + 2 + 1 + 1 = 5 bytes // total = 1 + 2 + 1 + 1 = 5 bytes
// The parser tries to read 4 bytes after seeing 0x04, fails, hits break. // The parser tries to read 4 bytes after seeing 0x04, fails, hits break.
bytes memory code = hex"03000402FF"; bytes memory code = hex"04000402FF";
// parse offset=0, length=5 // parse offset=0, length=5
uint256 sublistDesc = interpreter.makeDescriptor( uint256 sublistDesc = interpreter.makeDescriptor(
@@ -293,12 +308,14 @@ contract Push3InterpreterTest is Test {
uint256[] memory initExecStack = new uint256[](1); uint256[] memory initExecStack = new uint256[](1);
initExecStack[0] = sublistDesc; initExecStack[0] = sublistDesc;
int256[] memory initIntStack = new int256[](0); int256[] memory initIntStack = new int256[](0);
bool[] memory initBoolStack = new bool[](0);
( (
, ,
, ,
int256[] memory finalIntStack int256[] memory finalIntStack
) = interpreter.runInterpreter(code, initCodeStack, initExecStack, initIntStack); ,
) = interpreter.runInterpreter(code, initCodeStack, initExecStack, initIntStack, initBoolStack);
// Because the parse breaks early, we expect finalIntStack is empty or unchanged // Because the parse breaks early, we expect finalIntStack is empty or unchanged
assertEq(finalIntStack.length, 0, "Expected parse to break on out-of-range literal => no ints pushed"); assertEq(finalIntStack.length, 0, "Expected parse to break on out-of-range literal => no ints pushed");
@@ -310,12 +327,12 @@ contract Push3InterpreterTest is Test {
* In the main loop, it sees intTop < 2 => it does nothing. * In the main loop, it sees intTop < 2 => it does nothing.
*/ */
function test_NotEnoughIntArgs() public view { function test_NotEnoughIntArgs() public view {
bytes memory code = hex"030006020000000305"; bytes memory code = hex"040006020000000307";
// Breaking it down: // Breaking it down:
// 0x03 => SUBLIST // 0x04 => SUBLIST
// 0x00 0x06 => length=6 // 0x00 0x06 => length=6
// 0x02 00000003 => INT_LITERAL(3) // 0x02 00000003 => INT_LITERAL(3)
// 0x05 => INTEGER_MUL // 0x07 => INTEGER_MUL
uint256 sublistDesc = interpreter.makeDescriptor( uint256 sublistDesc = interpreter.makeDescriptor(
Push3Interpreter.CodeTag.SUBLIST, Push3Interpreter.CodeTag.SUBLIST,
@@ -329,14 +346,16 @@ contract Push3InterpreterTest is Test {
uint256[] memory initExecStack = new uint256[](1); uint256[] memory initExecStack = new uint256[](1);
initExecStack[0] = sublistDesc; initExecStack[0] = sublistDesc;
int256[] memory initIntStack = new int256[](0); int256[] memory initIntStack = new int256[](0);
bool[] memory initBoolStack = new bool[](0);
( (
, ,
, ,
int256[] memory finalIntStack int256[] memory finalIntStack
) = interpreter.runInterpreter(code, initCodeStack, initExecStack, initIntStack); ,
) = interpreter.runInterpreter(code, initCodeStack, initExecStack, initIntStack, initBoolStack);
// We expect finalIntStack => [5], // We expect finalIntStack => [5],
// because the PLUS instruction sees only 1 int => does nothing => 5 remains // because the PLUS instruction sees only 1 int => does nothing => 5 remains
assertEq(finalIntStack.length, 1, "Should have 1 int left"); assertEq(finalIntStack.length, 1, "Should have 1 int left");
assertEq(finalIntStack[0], 3, "Expected stack top=3 after insufficient-args plus"); assertEq(finalIntStack[0], 3, "Expected stack top=3 after insufficient-args plus");
@@ -344,12 +363,12 @@ contract Push3InterpreterTest is Test {
/** /**
* @notice Test sublist length overflow: * @notice Test sublist length overflow:
* subLen claims bigger than the code array. Should trigger else { break; } * subLen claims bigger than the code array. Should trigger else { break; }
* in the sublist parsing for that sublist. * in the sublist parsing for that sublist.
*/ */
function test_SublistLengthOverflow() public view { function test_SublistLengthOverflow() public view {
bytes memory code = hex"050010FFFFFF"; bytes memory code = hex"050010FFFFFF";
uint256 sublistDesc = interpreter.makeDescriptor( uint256 sublistDesc = interpreter.makeDescriptor(
Push3Interpreter.CodeTag.SUBLIST, Push3Interpreter.CodeTag.SUBLIST,
@@ -363,14 +382,526 @@ contract Push3InterpreterTest is Test {
uint256[] memory initExecStack = new uint256[](1); uint256[] memory initExecStack = new uint256[](1);
initExecStack[0] = sublistDesc; initExecStack[0] = sublistDesc;
int256[] memory initIntStack = new int256[](0); int256[] memory initIntStack = new int256[](0);
bool[] memory initBoolStack = new bool[](0);
( (
, ,
, ,
int256[] memory finalIntStack int256[] memory finalIntStack
) = interpreter.runInterpreter(code, initCodeStack, initExecStack, initIntStack); ,
) = interpreter.runInterpreter(code, initCodeStack, initExecStack, initIntStack, initBoolStack);
// Expect no items pushed => finalIntStack empty // Expect no items pushed => finalIntStack empty
assertEq(finalIntStack.length, 0, "Expected empty stack if sublist length is out of range => parse break"); assertEq(finalIntStack.length, 0, "Expected empty stack if sublist length is out of range => parse break");
} }
// BOOL STACK
/**
* @notice Test pushing literal True, literal False, then BOOL_SWAP => [False, True]
*
* The plan:
* 0x04 => SUBLIST token
* 0x00 0x05 => subLen=5
*
* Then 5 bytes:
* 0x03 + (01) => BOOL_LITERAL(True)
* 0x03 + (00) => BOOL_LITERAL(False)
* 0x0C => BOOL_SWAP
*/
function test_BoolSwap() public view {
// We'll produce 8 total bytes, same structure
// Format: [0x04, 0x0005, 0x03(01), 0x03(00), 0x0C => bool_swap]
bytes memory code = hex"040005030103000C";
// Breaking it down:
// 0x04 => SUBLIST
// 0x00 0x05 => length=5
// 0x03 0x01 => BOOL_LITERAL(True)
// 0x03 0x00 => BOOL_LITERAL(False)
// 0x0C => BOOL_SWAP
// We'll parse offset=0, length=8
uint256 sublistDesc = interpreter.makeDescriptor(
Push3Interpreter.CodeTag.SUBLIST,
0, // offset
8, // length
0
);
uint256[] memory initCodeStack = new uint256[](0);
uint256[] memory initExecStack = new uint256[](1);
initExecStack[0] = sublistDesc;
int256[] memory initIntStack = new int256[](0);
bool[] memory initBoolStack = new bool[](0);
// Run
(
,
,
,
bool[] memory finalBoolStack
) = interpreter.runInterpreter(code, initCodeStack, initExecStack, initIntStack, initBoolStack);
// Check final result => should be [True, False] swapped into [False, True]
assertEq(finalBoolStack.length, 2, "finalBoolStack should have length 2");
assertEq(finalBoolStack[0], false, "Should be False");
assertEq(finalBoolStack[1], true, "Should be True");
}
/**
* @notice Test pushing literal True, literal False, then BOOL_FLUSH => []
* Result should be empty stack.
*/
function test_BoolFlush() public view {
// We'll produce 8 total bytes, same structure
// Format: [0x04, 0x0005, 0x03(01), 0x03(00), 0x0D => bool_flush]
bytes memory code = hex"040005030103000D";
// Breaking it down:
// 0x04 => SUBLIST
// 0x00 0x05 => length=5
// 0x03 0x01 => BOOL_LITERAL(True)
// 0x03 0x00 => BOOL_LITERAL(False)
// 0x0D => BOOL_FLUSH
// We'll parse offset=0, length=8
uint256 sublistDesc = interpreter.makeDescriptor(
Push3Interpreter.CodeTag.SUBLIST,
0, // offset
8, // length
0
);
uint256[] memory initCodeStack = new uint256[](0);
uint256[] memory initExecStack = new uint256[](1);
initExecStack[0] = sublistDesc;
int256[] memory initIntStack = new int256[](0);
bool[] memory initBoolStack = new bool[](0);
// Run
(
,
,
,
bool[] memory finalBoolStack
) = interpreter.runInterpreter(code, initCodeStack, initExecStack, initIntStack, initBoolStack);
// Check final result => should be empty bool stack
assertEq(finalBoolStack.length, 0, "finalBoolStack should have length 0");
}
/**
* @notice Test pushing literal True, literal False, then BOOL_STACKDEPTH => intStack[2]
* Result should be number of pushed literals as intStack top.
*/
function test_BoolStackDepth() public view {
// We'll produce 8 total bytes, same structure
// Format: [0x04, 0x0005, 0x03(01), 0x03(00), 0x0E => bool_stackdepth]
bytes memory code = hex"040005030103000E";
// Breaking it down:
// 0x04 => SUBLIST
// 0x00 0x05 => length=5
// 0x03 0x01 => BOOL_LITERAL(True)
// 0x03 0x00 => BOOL_LITERAL(False)
// 0x0E => BOOL_STACKDEPTH
// We'll parse offset=0, length=8
uint256 sublistDesc = interpreter.makeDescriptor(
Push3Interpreter.CodeTag.SUBLIST,
0, // offset
8, // length
0
);
uint256[] memory initCodeStack = new uint256[](0);
uint256[] memory initExecStack = new uint256[](1);
initExecStack[0] = sublistDesc;
int256[] memory initIntStack = new int256[](0);
bool[] memory initBoolStack = new bool[](0);
// Run
(
,
,
int256[] memory finalIntStack,
bool[] memory finalBoolStack
) = interpreter.runInterpreter(code, initCodeStack, initExecStack, initIntStack, initBoolStack);
// Check final result => should be empty bool stack
assertEq(finalIntStack.length, 1, "finalIntStack should have length 1");
assertEq(finalBoolStack.length, 2, "finalBoolStack should have length 2");
assertEq(finalIntStack[0], 2, "IntStack top value should be 2, as we pushed 2 literals onto bool stack");
}
/**
* @notice Test pushing literal True, then BOOL_NOT => boolStack[False]
* Result should be False on top of bool stack.
*/
function test_BoolNot() public view {
// We'll produce 6 total bytes, same structure
// Format: [0x04, 0x0003, 0x03(01), 0x0F => bool_not]
bytes memory code = hex"04000303010F";
// Breaking it down:
// 0x04 => SUBLIST
// 0x00 0x03 => length=3
// 0x03 0x01 => BOOL_LITERAL(True)
// 0x0F => BOOL_NOT
// We'll parse offset=0, length=6
uint256 sublistDesc = interpreter.makeDescriptor(
Push3Interpreter.CodeTag.SUBLIST,
0, // offset
6, // length
0
);
uint256[] memory initCodeStack = new uint256[](0);
uint256[] memory initExecStack = new uint256[](1);
initExecStack[0] = sublistDesc;
int256[] memory initIntStack = new int256[](0);
bool[] memory initBoolStack = new bool[](0);
// Run
(
,
,
,
bool[] memory finalBoolStack
) = interpreter.runInterpreter(code, initCodeStack, initExecStack, initIntStack, initBoolStack);
// Check final result => should be False on top of bool stack
assertEq(finalBoolStack.length, 1, "finalBoolStack should have length 1");
assertEq(finalBoolStack[0], false, "Expected to be False after logical NOT on True");
}
/**
* @notice Test pushing literal True, literal True, then BOOL_AND => boolStack[True]
* Result should be True on top of bool stack.
*/
function test_BoolAnd() public view {
// We'll produce 8 total bytes, same structure
// Format: [0x04, 0x0005, 0x03(01), 0x03(01) 0x10 => bool_and]
bytes memory code = hex"0400050301030110";
// Breaking it down:
// 0x04 => SUBLIST
// 0x00 0x05 => length=5
// 0x03 0x01 => BOOL_LITERAL(True)
// 0x03 0x01 => BOOL_LITERAL(True)
// 0x10 => BOOL_AND
// We'll parse offset=0, length=8
uint256 sublistDesc = interpreter.makeDescriptor(
Push3Interpreter.CodeTag.SUBLIST,
0, // offset
8, // length
0
);
uint256[] memory initCodeStack = new uint256[](0);
uint256[] memory initExecStack = new uint256[](1);
initExecStack[0] = sublistDesc;
int256[] memory initIntStack = new int256[](0);
bool[] memory initBoolStack = new bool[](0);
// Run
(
,
,
,
bool[] memory finalBoolStack
) = interpreter.runInterpreter(code, initCodeStack, initExecStack, initIntStack, initBoolStack);
// Check final result => should be True on top of bool stack
assertEq(finalBoolStack.length, 1, "finalBoolStack should have length 1");
assertEq(finalBoolStack[0], true, "Expected to be True after logical AND on True and True");
}
/**
* @notice Test pushing literal True, literal False, then BOOL_OR => boolStack[True]
* Result should be True on top of bool stack.
*/
function test_BoolOr() public view {
// We'll produce 8 total bytes, same structure
// Format: [0x04, 0x0005, 0x03(01), 0x03(00) 0x11 => bool_or]
bytes memory code = hex"0400050301030011";
// Breaking it down:
// 0x04 => SUBLIST
// 0x00 0x05 => length=5
// 0x03 0x01 => BOOL_LITERAL(True)
// 0x03 0x00 => BOOL_LITERAL(False)
// 0x11 => BOOL_OR
// We'll parse offset=0, length=8
uint256 sublistDesc = interpreter.makeDescriptor(
Push3Interpreter.CodeTag.SUBLIST,
0, // offset
8, // length
0
);
uint256[] memory initCodeStack = new uint256[](0);
uint256[] memory initExecStack = new uint256[](1);
initExecStack[0] = sublistDesc;
int256[] memory initIntStack = new int256[](0);
bool[] memory initBoolStack = new bool[](0);
// Run
(
,
,
,
bool[] memory finalBoolStack
) = interpreter.runInterpreter(code, initCodeStack, initExecStack, initIntStack, initBoolStack);
// Check final result => should be True on top of bool stack
assertEq(finalBoolStack.length, 1, "finalBoolStack should have length 1");
assertEq(finalBoolStack[0], true, "Expected to be True after logical OR on True and False");
}
/**
* @notice Test pushing literal True, literal False, then BOOL_EQ => boolStack[False]
* Result should be False on top of bool stack.
*/
function test_BoolEq() public view {
// We'll produce 8 total bytes, same structure
// Format: [0x04, 0x0005, 0x03(01), 0x03(00) 0x12 => bool_eq]
bytes memory code = hex"0400050301030012";
// Breaking it down:
// 0x04 => SUBLIST
// 0x00 0x05 => length=5
// 0x03 0x01 => BOOL_LITERAL(True)
// 0x03 0x00 => BOOL_LITERAL(False)
// 0x12 => BOOL_EQ
// We'll parse offset=0, length=8
uint256 sublistDesc = interpreter.makeDescriptor(
Push3Interpreter.CodeTag.SUBLIST,
0, // offset
8, // length
0
);
uint256[] memory initCodeStack = new uint256[](0);
uint256[] memory initExecStack = new uint256[](1);
initExecStack[0] = sublistDesc;
int256[] memory initIntStack = new int256[](0);
bool[] memory initBoolStack = new bool[](0);
// Run
(
,
,
,
bool[] memory finalBoolStack
) = interpreter.runInterpreter(code, initCodeStack, initExecStack, initIntStack, initBoolStack);
// Check final result => should be False on top of bool stack
assertEq(finalBoolStack.length, 1, "finalBoolStack should have length 1");
assertEq(finalBoolStack[0], false, "Expected to be False as True is not equal False");
}
/**
* @notice Test pushing literal 0x2145, then BOOL_FROMINTEGER => boolStack[True]
* Result should be True on top of bool stack.
*/
function test_BoolFromInteger() public view {
// We'll produce 9 total bytes, same structure
// Format: [0x04, 0x0004, 0x02(0x00002145), 0x14 => bool_frominteger]
bytes memory code = hex"040006020000214514";
// Breaking it down:
// 0x04 => SUBLIST
// 0x00 0x04 => length=6
// 0x02 0x00002145 => INT_LITERAL(0x2145)
// 0x14 => BOOL_FROMINTEGER
// We'll parse offset=0, length=9
uint256 sublistDesc = interpreter.makeDescriptor(
Push3Interpreter.CodeTag.SUBLIST,
0, // offset
9, // length
0
);
uint256[] memory initCodeStack = new uint256[](0);
uint256[] memory initExecStack = new uint256[](1);
initExecStack[0] = sublistDesc;
int256[] memory initIntStack = new int256[](0);
bool[] memory initBoolStack = new bool[](0);
// Run
(
,
,
int256[] memory finalIntStack,
bool[] memory finalBoolStack
) = interpreter.runInterpreter(code, initCodeStack, initExecStack, initIntStack, initBoolStack);
// Check final result => should be True on bool stack
assertEq(finalIntStack.length, 0, "finalIntStack should have length 0");
assertEq(finalBoolStack.length, 1, "finalBoolStack should have length 1");
assertEq(finalBoolStack[0], true, "boolStack top value should be True, as we pushed non-zero literal onto int stack");
}
/**
* @notice Test pushing literal True, literal False, literal True, then BOOL_ROT => boolStack[False, True, True]
* Result should be rotated bool stack from [True, False, True] into [False, True, True].
*/
function test_BoolRot() public view {
// We'll produce 10 total bytes, same structure
// Format: [0x04, 0x0007, 0x03(01), 0x03(00), 0x03(01), 0x15 => bool_rot]
bytes memory code = hex"04000703010300030115";
// Breaking it down:
// 0x04 => SUBLIST
// 0x00 0x07 => length=7
// 0x03 0x01 => BOOL_LITERAL(True)
// 0x03 0x00 => BOOL_LITERAL(False)
// 0x03 0x01 => BOOL_LITERAL(True)
// 0x15 => BOOL_ROT
// We'll parse offset=0, length=10
uint256 sublistDesc = interpreter.makeDescriptor(
Push3Interpreter.CodeTag.SUBLIST,
0, // offset
10, // length
0
);
uint256[] memory initCodeStack = new uint256[](0);
uint256[] memory initExecStack = new uint256[](1);
initExecStack[0] = sublistDesc;
int256[] memory initIntStack = new int256[](0);
bool[] memory initBoolStack = new bool[](0);
// Run
(
,
,
,
bool[] memory finalBoolStack
) = interpreter.runInterpreter(code, initCodeStack, initExecStack, initIntStack, initBoolStack);
// Check final result => should be [False, True, True] bool stack
assertEq(finalBoolStack.length, 3, "finalBoolStack should have length 3");
assertEq(finalBoolStack[0], false, "Expected to be False as value from middle position moved to bottom of the stack");
assertEq(finalBoolStack[1], true, "Expected to be True as value from top position moved to middle of the stack");
assertEq(finalBoolStack[2], true, "Expected to be True as value from bottom position moved to top of the stack");
}
/**
* @notice Test pushing literal 0x02, literal True, literal False, literal True, then BOOL_YANKDUP => boolStack[True, False, True, True]
* Result should be copied True on top of bool stack [True, False, True, True]
*/
function test_BoolYankDup() public view {
// We'll produce 15 total bytes, same structure
// Format: [0x04, 0x000C, 0x02(00 00 00 02) 0x03(01), 0x03(00), 0x03(01), 0x18 => bool_yankdup]
bytes memory code = hex"04000C020000000203010300030118";
// Breaking it down:
// 0x04 => SUBLIST
// 0x00 0x0C => length=12
// 0x02 0x00000002 => INT_LITERAL(0x02)
// 0x03 0x01 => BOOL_LITERAL(True)
// 0x03 0x00 => BOOL_LITERAL(False)
// 0x03 0x01 => BOOL_LITERAL(True)
// 0x18 => BOOL_YANKDUP
// We'll parse offset=0, length=15
uint256 sublistDesc = interpreter.makeDescriptor(
Push3Interpreter.CodeTag.SUBLIST,
0, // offset
15, // length
0
);
uint256[] memory initCodeStack = new uint256[](0);
uint256[] memory initExecStack = new uint256[](1);
initExecStack[0] = sublistDesc;
int256[] memory initIntStack = new int256[](0);
bool[] memory initBoolStack = new bool[](0);
// Run
(
,
,
,
bool[] memory finalBoolStack
) = interpreter.runInterpreter(code, initCodeStack, initExecStack, initIntStack, initBoolStack);
// Check final result => should be [True, False, True, True] bool stack
assertEq(finalBoolStack.length, 4, "finalBoolStack should have length 4");
assertEq(finalBoolStack[0], true, "Expected to be True as first value from bool literal");
assertEq(finalBoolStack[1], false, "Expected to be False as second value from bool literal");
assertEq(finalBoolStack[2], true, "Expected to be True as third value from bool literal");
assertEq(finalBoolStack[3], true, "Expected to be True as copied value at index 2, which is index 0 for an array");
}
/**
* @notice Test pushing BOOL_RAND => boolStack[True] or boolStack[False]
* Result should be either False or True on top of bool stack.
*/
function test_BoolRand() public {
// We'll produce 4 total bytes, same structure
// Format: [0x04, 0x0001, 0x1A => bool_rand]
bytes memory code = hex"0400011A";
// Breaking it down:
// 0x04 => SUBLIST
// 0x00 0x01 => length=1
// 0x1A => BOOL_RAND
// We'll parse offset=0, length=4
uint256 sublistDesc = interpreter.makeDescriptor(
Push3Interpreter.CodeTag.SUBLIST,
0, // offset
4, // length
0
);
uint256[] memory initCodeStack = new uint256[](0);
uint256[] memory initExecStack = new uint256[](1);
initExecStack[0] = sublistDesc;
int256[] memory initIntStack = new int256[](0);
bool[] memory initBoolStack = new bool[](0);
// Run
(
,
,
,
bool[] memory finalBoolStack
) = interpreter.runInterpreter(code, initCodeStack, initExecStack, initIntStack, initBoolStack);
// Check final result => should be random bool on top of bool stack
assertEq(finalBoolStack.length, 1, "finalBoolStack should have length 1");
assertEq(finalBoolStack[0], false, "Expected to be False for default prevrandao, timestamp and msg.sender");
// move to another timestamp to get different random result
vm.warp(1736055577);
(
,
,
,
finalBoolStack
) = interpreter.runInterpreter(code, initCodeStack, initExecStack, initIntStack, initBoolStack);
assertEq(finalBoolStack.length, 1, "finalBoolStack should have length 1");
assertEq(finalBoolStack[0], true, "Expected to be True for configured timestamp and default prevrandao, msg.sender");
}
} }