From a4fd4ea2d4606f2eceaec9224b64aa34ecfacc51 Mon Sep 17 00:00:00 2001 From: Rosco Kalis Date: Fri, 25 Sep 2026 12:00:45 +0200 Subject: [PATCH 1/3] feat: add peephole optimisations and check all optimisations against the VM - Add new peephole optimisations for in-place increments/decrements (OP_DUP OP_1ADD OP_NIP), alt stack round trips from reassignments inside loops, OP_ROT OP_ROT OP_2DROP, and extraneous OP_SWAPs before OP_BOOLOR, OP_BOOLAND, OP_MIN, OP_MAX and OP_2DROP - Remove OP_CAT OP_DROP => OP_2DROP, which removed OP_CAT's maximum stack item size check for unused concatenations - Document why the OP_NOT optimisations drop a VM number check, and why OP_0 OP_NUMEQUAL => OP_NOT is not safe - Require optimisation patterns to start at a token boundary - Add a VM equivalence fuzz test for every optimisation (replacing the manual optimisation proofs placeholder) and a reference implementation test for optimiseBytecode Co-Authored-By: Claude Opus 5.5 --- .../valid-contract-files/complex_loop.ts | 16 +- .../valid-contract-files/deep_replace.ts | 11 +- .../valid-contract-files/do_while_loop.ts | 12 +- .../do_while_loop_require_inside_loop.ts | 10 +- .../valid-contract-files/everything.ts | 16 +- .../valid-contract-files/for_loop_basic.ts | 12 +- .../for_loop_stack_items.ts | 16 +- .../valid-contract-files/for_while_nested.ts | 20 +-- .../global_function_in_control_flow.ts | 14 +- .../valid-contract-files/sum_input_amount.ts | 14 +- .../tuple_reassignment.ts | 18 +-- .../tuple_reassignment_after_final_read.ts | 12 +- .../tuple_reassignment_branches.ts | 14 +- .../valid-contract-files/while_loop.ts | 14 +- .../valid-contract-files/while_loop_basic.ts | 12 +- .../valid-contract-files/while_loop_nested.ts | 14 +- packages/utils/src/optimisations.ts | 21 ++- packages/utils/src/script.ts | 5 +- .../test/fixtures/bitauth-script.fixture.ts | 106 ++++++------- .../test/manual-optimisation-proofs.test.ts | 57 ------- packages/utils/test/optimisations.test.ts | 150 ++++++++++++++++++ packages/utils/test/script.test.ts | 69 +++++++- website/docs/releases/release-notes.md | 2 + 23 files changed, 408 insertions(+), 227 deletions(-) delete mode 100644 packages/utils/test/manual-optimisation-proofs.test.ts create mode 100644 packages/utils/test/optimisations.test.ts diff --git a/packages/cashc/test/generation/fixtures/valid-contract-files/complex_loop.ts b/packages/cashc/test/generation/fixtures/valid-contract-files/complex_loop.ts index f362178e9..77f4cb841 100644 --- a/packages/cashc/test/generation/fixtures/valid-contract-files/complex_loop.ts +++ b/packages/cashc/test/generation/fixtures/valid-contract-files/complex_loop.ts @@ -6,20 +6,20 @@ export const fixtures: Fixture[] = [ contractName: 'Loopy', constructorInputs: [], abi: [{ name: 'doLoop', inputs: [] }], - bytecode: 'OP_0 OP_0 OP_0 OP_0 OP_BEGIN OP_DUP OP_UTXOVALUE OP_4 OP_ROLL OP_DROP OP_SWAP OP_TOALTSTACK OP_SWAP OP_TOALTSTACK OP_SWAP OP_FROMALTSTACK OP_FROMALTSTACK OP_DUP OP_1ADD OP_NIP OP_TXOUTPUTCOUNT OP_2DUP OP_LESSTHAN OP_DUP OP_IF OP_2 OP_PICK OP_OUTPUTTOKENCATEGORY OP_0 OP_EQUAL OP_NOT OP_NIP OP_DUP OP_IF OP_4 OP_PICK OP_3 OP_PICK OP_OUTPUTVALUE OP_ADD OP_5 OP_ROLL OP_DROP OP_SWAP OP_TOALTSTACK OP_SWAP OP_TOALTSTACK OP_SWAP OP_TOALTSTACK OP_SWAP OP_FROMALTSTACK OP_FROMALTSTACK OP_FROMALTSTACK OP_ELSE OP_3 OP_PICK OP_1ADD OP_4 OP_ROLL OP_DROP OP_SWAP OP_TOALTSTACK OP_SWAP OP_TOALTSTACK OP_SWAP OP_FROMALTSTACK OP_FROMALTSTACK OP_ENDIF OP_ENDIF OP_2DROP OP_DUP OP_TXINPUTCOUNT OP_GREATERTHANOREQUAL OP_UNTIL OP_2SWAP OP_GREATERTHAN OP_VERIFY OP_SWAP OP_0 OP_GREATERTHAN OP_NIP', + bytecode: 'OP_0 OP_0 OP_0 OP_0 OP_BEGIN OP_DUP OP_UTXOVALUE OP_4 OP_ROLL OP_DROP OP_SWAP OP_TOALTSTACK OP_ROT OP_ROT OP_FROMALTSTACK OP_1ADD OP_TXOUTPUTCOUNT OP_2DUP OP_LESSTHAN OP_DUP OP_IF OP_2 OP_PICK OP_OUTPUTTOKENCATEGORY OP_0 OP_EQUAL OP_NOT OP_NIP OP_DUP OP_IF OP_4 OP_PICK OP_3 OP_PICK OP_OUTPUTVALUE OP_ADD OP_5 OP_ROLL OP_DROP OP_SWAP OP_TOALTSTACK OP_SWAP OP_TOALTSTACK OP_ROT OP_ROT OP_FROMALTSTACK OP_FROMALTSTACK OP_ELSE OP_3 OP_PICK OP_1ADD OP_4 OP_ROLL OP_DROP OP_SWAP OP_TOALTSTACK OP_ROT OP_ROT OP_FROMALTSTACK OP_ENDIF OP_ENDIF OP_2DROP OP_DUP OP_TXINPUTCOUNT OP_GREATERTHANOREQUAL OP_UNTIL OP_2SWAP OP_GREATERTHAN OP_VERIFY OP_SWAP OP_0 OP_GREATERTHAN OP_NIP', debug: { - bytecode: '000000006576c6547a757c6b7c6b7c6c6c768b77c46e9f76635279d100879177766354795379cc93557a757c6b7c6b7c6b7c6c6c6c6753798b547a757c6b7c6b7c6c6c68686d76c3a26672a0697c00a077', - sourceMap: '3:23:3:24;4:24:4:25;5:25:5:26;6:16:6:17;8:8:26:39;9:33:9:34;:23::41:1;:12::42;;;;;;;;;;10:16:10:17:0;:::21:1;:12::22;12:20:12:37:0;13:21:13:26;::::1;15:16:15:17:0;:19:25:13;16:31:16:32;;:20::47:1;:51::53:0;:20:::1;;:16::54;18:20:18:21:0;:23:20:17;19:32:19:41;;:55::56;;:44::63:1;:32;:20::64;;;;;;;;;;;;;20:23:22:17:0;21:33:21:43;;:::47:1;:20::48;;;;;;;;;;20:23:22:17;15:19:25:13;8:11:26:9;26:17::18:0;:21::37;8:8::39:1;;28:16:28:36:0;::::1;:8::38;29:16:29:26:0;:29::30;:8::32:1;2:22:30:5', + bytecode: '000000006576c6547a757c6b7b7b6c8bc46e9f76635279d100879177766354795379cc93557a757c6b7c6b7b7b6c6c6753798b547a757c6b7b7b6c68686d76c3a26672a0697c00a077', + sourceMap: '3:23:3:24;4:24:4:25;5:25:5:26;6:16:6:17;8:8:26:39;9:33:9:34;:23::41:1;:12::42;;;;;;;;10::10:22;12:20:12:37:0;13:21:13:26;::::1;15:16:15:17:0;:19:25:13;16:31:16:32;;:20::47:1;:51::53:0;:20:::1;;:16::54;18:20:18:21:0;:23:20:17;19:32:19:41;;:55::56;;:44::63:1;:32;:20::64;;;;;;;;;;;20:23:22:17:0;21:33:21:43;;:::47:1;:20::48;;;;;;;;20:23:22:17;15:19:25:13;8:11:26:9;26:17::18:0;:21::37;8:8::39:1;;28:16:28:36:0;::::1;:8::38;29:16:29:26:0;:29::30;:8::32:1;2:22:30:5', logs: [ - { ip: 68, line: 24, data: [{ stackIndex: 3, type: 'int', ip: 68 }] }, + { ip: 60, line: 24, data: [{ stackIndex: 3, type: 'int', ip: 60 }] }, ], requires: [ - { ip: 76, line: 28 }, - { ip: 80, line: 29 }, + { ip: 68, line: 28 }, + { ip: 72, line: 29 }, ], - sourceTags: '69:69:sc;80:80:sc', + sourceTags: '61:61:sc;72:72:sc', }, - fingerprint: 'fa36d9b24d49525e027ba3cf3accd349e9f84d0c1bbd1141e98d6894173a1a2a', + fingerprint: 'b91e25a054a9cad4ddfb496c397c5d7e7e24a7ed131326b91e93d48bbee00e24', }, }, ]; diff --git a/packages/cashc/test/generation/fixtures/valid-contract-files/deep_replace.ts b/packages/cashc/test/generation/fixtures/valid-contract-files/deep_replace.ts index ef8985c15..bd8694560 100644 --- a/packages/cashc/test/generation/fixtures/valid-contract-files/deep_replace.ts +++ b/packages/cashc/test/generation/fixtures/valid-contract-files/deep_replace.ts @@ -13,18 +13,17 @@ export const fixtures: Fixture[] = [ + 'OP_5 OP_PICK OP_3 OP_LESSTHAN OP_IF ' // a = 3 } + 'OP_3 OP_6 OP_ROLL OP_DROP OP_SWAP OP_TOALTSTACK OP_SWAP OP_TOALTSTACK OP_SWAP ' - + 'OP_TOALTSTACK OP_SWAP OP_TOALTSTACK OP_SWAP OP_FROMALTSTACK OP_FROMALTSTACK ' - + 'OP_FROMALTSTACK OP_FROMALTSTACK OP_ENDIF ' + + 'OP_TOALTSTACK OP_ROT OP_ROT OP_FROMALTSTACK OP_FROMALTSTACK OP_FROMALTSTACK OP_ENDIF ' // require(a > b + c + d + e + f); + 'OP_2ROT OP_5 OP_ROLL OP_ADD OP_4 OP_ROLL OP_ADD ' + 'OP_3 OP_ROLL OP_ADD OP_ROT OP_ADD OP_GREATERTHAN', debug: { - bytecode: '5152535455565579539f6353567a757c6b7c6b7c6b7c6b7c6c6c6c6c6871557a93547a93537a937b93a0', + bytecode: '5152535455565579539f6353567a757c6b7c6b7c6b7b7b6c6c6c6871557a93547a93537a937b93a0', logs: [], - requires: [{ ip: 42, line: 14 }], - sourceMap: '3:16:3:17;4::4;5::5;6::6;7::7;8::8;10:12:10:13;;:16::17;:12:::1;:19:12:9:0;11:16:11:17;:12::18:1;;;;;;;;;;;;;;;;10:19:12:9;14:16:14:21:0;:24::25;;:20:::1;:28::29:0;;:20:::1;:32::33:0;;:20:::1;:36::37:0;:20:::1;:8::39', + requires: [{ ip: 40, line: 14 }], + sourceMap: '3:16:3:17;4::4;5::5;6::6;7::7;8::8;10:12:10:13;;:16::17;:12:::1;:19:12:9:0;11:16:11:17;:12::18:1;;;;;;;;;;;;;;10:19:12:9;14:16:14:21:0;:24::25;;:20:::1;:28::29:0;;:20:::1;:32::33:0;;:20:::1;:36::37:0;:20:::1;:8::39', }, - fingerprint: '5ec5f2a100dc5c29c95f58ed51e4da469b74e5932b070e38f3c30c3405f40005', + fingerprint: 'e586fb63aa0c9791cdf96f5472328a702565bd0e1da1bb101dc2619c5655f465', }, }, ]; diff --git a/packages/cashc/test/generation/fixtures/valid-contract-files/do_while_loop.ts b/packages/cashc/test/generation/fixtures/valid-contract-files/do_while_loop.ts index 7e03e275a..c0df0c751 100644 --- a/packages/cashc/test/generation/fixtures/valid-contract-files/do_while_loop.ts +++ b/packages/cashc/test/generation/fixtures/valid-contract-files/do_while_loop.ts @@ -12,17 +12,17 @@ export const fixtures: Fixture[] = [ // do { + 'OP_BEGIN ' // i = i + 1; - + 'OP_DUP OP_1ADD OP_NIP ' + + 'OP_1ADD ' // } while (i < tx.inputs.length); + 'OP_DUP OP_TXINPUTCOUNT OP_GREATERTHANOREQUAL OP_UNTIL ' // require(i > 2); + 'OP_2 OP_GREATERTHAN', - fingerprint: '45d5cf43034d482df71ca54496793bff3f932d37dd77e95367edeb22a98a9154', + fingerprint: 'a1926f6964606192bb765db69639d46975507c021b233c1456d344398fa5b8f5', debug: { - bytecode: '0065768b7776c3a26652a0', - sourceMap: '3:16:3:17;5:8:7:39;6:16:6:17;:::21:1;:12::22;7:17:7:18:0;:21::37;5:8::39:1;;10:20:10:21:0;:8::23:1', - logs: [{ ip: 9, line: 9, data: [{ stackIndex: 0, type: 'int', ip: 9 }] }], - requires: [{ ip: 11, line: 10 }], + bytecode: '00658b76c3a26652a0', + sourceMap: '3:16:3:17;5:8:7:39;6:12:6:22:1;7:17:7:18:0;:21::37;5:8::39:1;;10:20:10:21:0;:8::23:1', + logs: [{ ip: 7, line: 9, data: [{ stackIndex: 0, type: 'int', ip: 7 }] }], + requires: [{ ip: 9, line: 10 }], }, }, }, diff --git a/packages/cashc/test/generation/fixtures/valid-contract-files/do_while_loop_require_inside_loop.ts b/packages/cashc/test/generation/fixtures/valid-contract-files/do_while_loop_require_inside_loop.ts index 807a47786..25965c127 100644 --- a/packages/cashc/test/generation/fixtures/valid-contract-files/do_while_loop_require_inside_loop.ts +++ b/packages/cashc/test/generation/fixtures/valid-contract-files/do_while_loop_require_inside_loop.ts @@ -12,19 +12,19 @@ export const fixtures: Fixture[] = [ // do { + 'OP_BEGIN ' // i = i + 1; - + 'OP_DUP OP_1ADD OP_NIP ' + + 'OP_1ADD ' // require(i < 10); + 'OP_DUP OP_10 OP_LESSTHAN OP_VERIFY ' // } while (i < tx.inputs.length); + 'OP_DUP OP_TXINPUTCOUNT OP_GREATERTHANOREQUAL OP_UNTIL ' // } + 'OP_DROP OP_1', - fingerprint: 'ce6d7a3b336f2b8c85a25c362635f801df5ebc31a54f6940c02df6966d7dd484', + fingerprint: '8ba3e5e6fcc79a8e3fb57ac388692ae3b49fbece9f528e547380b24338a8d8b9', debug: { - bytecode: '0065768b77765a9f6976c3a2667551', - sourceMap: '3:16:3:17;5:8:8:39;6:16:6:17;:::21:1;:12::22;7:20:7:21:0;:24::26;:20:::1;:12::28;8:17:8:18:0;:21::37;5:8::39:1;;2:22:9:5;', + bytecode: '00658b765a9f6976c3a2667551', + sourceMap: '3:16:3:17;5:8:8:39;6:12:6:22:1;7:20:7:21:0;:24::26;:20:::1;:12::28;8:17:8:18:0;:21::37;5:8::39:1;;2:22:9:5;', logs: [], - requires: [{ ip: 8, line: 7 }], + requires: [{ ip: 6, line: 7 }], }, }, }, diff --git a/packages/cashc/test/generation/fixtures/valid-contract-files/everything.ts b/packages/cashc/test/generation/fixtures/valid-contract-files/everything.ts index 84c710c8b..8fd84b618 100644 --- a/packages/cashc/test/generation/fixtures/valid-contract-files/everything.ts +++ b/packages/cashc/test/generation/fixtures/valid-contract-files/everything.ts @@ -30,7 +30,7 @@ export const fixtures: Fixture[] = [ // if (i > 400) { + 'OP_4 OP_PICK 9001 OP_GREATERTHAN OP_IF ' // i = 400; - + '9001 OP_5 OP_ROLL OP_DROP OP_SWAP OP_TOALTSTACK OP_SWAP OP_TOALTSTACK OP_SWAP OP_TOALTSTACK OP_SWAP OP_FROMALTSTACK OP_FROMALTSTACK OP_FROMALTSTACK ' + + '9001 OP_5 OP_ROLL OP_DROP OP_SWAP OP_TOALTSTACK OP_SWAP OP_TOALTSTACK OP_ROT OP_ROT OP_FROMALTSTACK OP_FROMALTSTACK ' // } + 'OP_ENDIF ' // if (x > 10) { @@ -47,20 +47,20 @@ export const fixtures: Fixture[] = [ + 'OP_ELSE OP_DUP OP_1 OP_NUMEQUALVERIFY OP_ENDIF OP_ENDIF ' // } + 'OP_2DROP OP_2DROP OP_2DROP OP_2DROP OP_1', - fingerprint: '5c83820f08cc787eb0078463cbf16b3b8c605a21bf42464bf9d4f9f31f254569', + fingerprint: 'db741271dde641b395ed7d3f282179c607d56f29b2ba7cddff3b7670a24072e2', debug: { - bytecode: '02900178930807364897987fe80753797e5a0094527978935297765479a06953795a547aa678a68802f401b275567a8277018a9f695479029001a063029001557a757c6b7c6b7c6b7c6c6c6c6855795aa063547901149f6956795879ad675579559f6300696776519d68686d6d6d6d51', - sourceMap: '9:16:9:19;:22::23;:16:::1;10:18:10:35:0;:44::45;;:18::46:1;12:25:12:27:0;:34::39;:25::40:1;13:31:13:32:0;;:35::45;:31:::1;:49::50:0;:30:::1;14:16:14:31:0;:82::83;;:16:::1;:8::85;16:26:16:27:0;;17:21:17:23;19:26:19:27;;:16::28:1;:48::58:0;:32::60:1;:8::62;20:28:20:31:0;:8::33:1;;21:16:21:17:0;;:::24:1;;:27::30:0;:16:::1;:8::32;23:12:23:13:0;;:16::19;:12:::1;:21:25:9:0;24:16:24:19;:12::20:1;;;;;;;;;;;;;23:21:25:9;27:12:27:13:0;;:16::18;:12:::1;:20:30:9:0;28::28:21;;:24::26;:20:::1;:12::28;29:29:29:30:0;;:32::34;;:12::37:1;30:15:33::0;:19:30:20;;:23::24;:19:::1;:26:32:9:0;31:20:31:25;:12::27:1;33::33:37:0;:20::30;:34::35;:12::37:1;;30:15;8:37:34:5;;;;', + bytecode: '02900178930807364897987fe80753797e5a0094527978935297765479a06953795a547aa678a68802f401b275567a8277018a9f695479029001a063029001557a757c6b7c6b7b7b6c6c6855795aa063547901149f6956795879ad675579559f6300696776519d68686d6d6d6d51', + sourceMap: '9:16:9:19;:22::23;:16:::1;10:18:10:35:0;:44::45;;:18::46:1;12:25:12:27:0;:34::39;:25::40:1;13:31:13:32:0;;:35::45;:31:::1;:49::50:0;:30:::1;14:16:14:31:0;:82::83;;:16:::1;:8::85;16:26:16:27:0;;17:21:17:23;19:26:19:27;;:16::28:1;:48::58:0;:32::60:1;:8::62;20:28:20:31:0;:8::33:1;;21:16:21:17:0;;:::24:1;;:27::30:0;:16:::1;:8::32;23:12:23:13:0;;:16::19;:12:::1;:21:25:9:0;24:16:24:19;:12::20:1;;;;;;;;;;;23:21:25:9;27:12:27:13:0;;:16::18;:12:::1;:20:30:9:0;28::28:21;;:24::26;:20:::1;:12::28;29:29:29:30:0;;:32::34;;:12::37:1;30:15:33::0;:19:30:20;;:23::24;:19:::1;:26:32:9:0;31:20:31:25;:12::27:1;33::33:37:0;:20::30;:34::35;:12::37:1;;30:15;8:37:34:5;;;;', logs: [], requires: [ { ip: 22, line: 14 }, { ip: 31, line: 19 }, { ip: 33, line: 20 }, { ip: 41, line: 21 }, - { ip: 71, line: 28 }, - { ip: 76, line: 29 }, - { ip: 84, line: 31 }, - { ip: 88, line: 33 }, + { ip: 69, line: 28 }, + { ip: 74, line: 29 }, + { ip: 82, line: 31 }, + { ip: 86, line: 33 }, ], }, }, diff --git a/packages/cashc/test/generation/fixtures/valid-contract-files/for_loop_basic.ts b/packages/cashc/test/generation/fixtures/valid-contract-files/for_loop_basic.ts index cf31a691f..bc5eb5ecd 100644 --- a/packages/cashc/test/generation/fixtures/valid-contract-files/for_loop_basic.ts +++ b/packages/cashc/test/generation/fixtures/valid-contract-files/for_loop_basic.ts @@ -6,17 +6,17 @@ export const fixtures: Fixture[] = [ contractName: 'ForLoopBasic', constructorInputs: [], abi: [{ name: 'spend', inputs: [] }], - bytecode: 'OP_0 OP_0 OP_BEGIN OP_DUP OP_3 OP_LESSTHAN OP_DUP OP_TOALTSTACK OP_IF OP_2DUP OP_ADD OP_ROT OP_DROP OP_SWAP OP_DUP OP_1ADD OP_NIP OP_ENDIF OP_FROMALTSTACK OP_NOT OP_UNTIL OP_DROP OP_3 OP_NUMEQUAL', + bytecode: 'OP_0 OP_0 OP_BEGIN OP_DUP OP_3 OP_LESSTHAN OP_DUP OP_TOALTSTACK OP_IF OP_2DUP OP_ADD OP_ROT OP_DROP OP_SWAP OP_1ADD OP_ENDIF OP_FROMALTSTACK OP_NOT OP_UNTIL OP_DROP OP_3 OP_NUMEQUAL', debug: { - bytecode: '00006576539f766b636e937b757c768b77686c916675539c', - sourceMap: '3:18:3:19;5:21:5:22;:8:7:9;:24:5:25;:28::29;:24:::1;;;:36:7:9:0;6:18:6:25;::::1;:12::26;;;5:31:5:32:0;:::34:1;;:36:7:9;;:8;;;9:23:9:24:0;:8::26:1', + bytecode: '00006576539f766b636e937b757c8b686c916675539c', + sourceMap: '3:18:3:19;5:21:5:22;:8:7:9;:24:5:25;:28::29;:24:::1;;;:36:7:9:0;6:18:6:25;::::1;:12::26;;;5:31:5:34;:36:7:9;;:8;;;9:23:9:24:0;:8::26:1', logs: [], requires: [ - { ip: 24, line: 9 }, + { ip: 22, line: 9 }, ], - sourceTags: '14:16:fu;17:20:lc;21:21:sc', + sourceTags: '14:14:fu;15:18:lc;19:19:sc', }, - fingerprint: '9e52dba656b0743057d4eda76f051c8a1f4460a2becf8f372c690b1901512b4e', + fingerprint: 'aceb2ca5de4008ec57f47990a22ff9da84d30f5ffcbb475d3eb28c69f2a13fc9', }, }, ]; diff --git a/packages/cashc/test/generation/fixtures/valid-contract-files/for_loop_stack_items.ts b/packages/cashc/test/generation/fixtures/valid-contract-files/for_loop_stack_items.ts index 063af7457..760c05b14 100644 --- a/packages/cashc/test/generation/fixtures/valid-contract-files/for_loop_stack_items.ts +++ b/packages/cashc/test/generation/fixtures/valid-contract-files/for_loop_stack_items.ts @@ -6,19 +6,19 @@ export const fixtures: Fixture[] = [ contractName: 'ForLoopBasic', constructorInputs: [], abi: [{ name: 'spend', inputs: [] }], - bytecode: 'OP_0 OP_1 OP_1 OP_0 OP_BEGIN OP_DUP OP_3 OP_LESSTHAN OP_DUP OP_TOALTSTACK OP_IF OP_3 OP_PICK OP_OVER OP_ADD OP_4 OP_ROLL OP_DROP OP_SWAP OP_TOALTSTACK OP_SWAP OP_TOALTSTACK OP_SWAP OP_FROMALTSTACK OP_FROMALTSTACK OP_DUP OP_1ADD OP_NIP OP_ENDIF OP_FROMALTSTACK OP_NOT OP_UNTIL OP_DROP OP_ROT OP_3 OP_NUMEQUALVERIFY OP_SWAP OP_1 OP_NUMEQUALVERIFY OP_1 OP_NUMEQUAL', + bytecode: 'OP_0 OP_1 OP_1 OP_0 OP_BEGIN OP_DUP OP_3 OP_LESSTHAN OP_DUP OP_TOALTSTACK OP_IF OP_3 OP_PICK OP_OVER OP_ADD OP_4 OP_ROLL OP_DROP OP_SWAP OP_TOALTSTACK OP_ROT OP_ROT OP_FROMALTSTACK OP_1ADD OP_ENDIF OP_FROMALTSTACK OP_NOT OP_UNTIL OP_DROP OP_ROT OP_3 OP_NUMEQUALVERIFY OP_SWAP OP_1 OP_NUMEQUALVERIFY OP_1 OP_NUMEQUAL', debug: { - bytecode: '005151006576539f766b6353797893547a757c6b7c6b7c6c6c768b77686c9166757b539d7c519d519c', - sourceMap: '3:18:3:19;4:16:4:17;5::5;7:21:7:22;:8:9:9;:24:7:25;:28::29;:24:::1;;;:39:9:9:0;8:18:8:21;;:24::25;:18:::1;:12::26;;;;;;;;;;7:31:7:32:0;:::37:1;;:39:9:9;;:8;;;11:16:11:19:0;:23::24;:8::26:1;12:16:12:17:0;:21::22;:8::24:1;13:21:13:22:0;:8::24:1', + bytecode: '005151006576539f766b6353797893547a757c6b7b7b6c8b686c9166757b539d7c519d519c', + sourceMap: '3:18:3:19;4:16:4:17;5::5;7:21:7:22;:8:9:9;:24:7:25;:28::29;:24:::1;;;:39:9:9:0;8:18:8:21;;:24::25;:18:::1;:12::26;;;;;;;;7:31:7:37;:39:9:9;;:8;;;11:16:11:19:0;:23::24;:8::26:1;12:16:12:17:0;:21::22;:8::24:1;13:21:13:22:0;:8::24:1', logs: [], requires: [ - { ip: 35, line: 11 }, - { ip: 38, line: 12 }, - { ip: 41, line: 13 }, + { ip: 31, line: 11 }, + { ip: 34, line: 12 }, + { ip: 37, line: 13 }, ], - sourceTags: '25:27:fu;28:31:lc;32:32:sc', + sourceTags: '23:23:fu;24:27:lc;28:28:sc', }, - fingerprint: '05430d75d110ff5d4525f7e34bbf2c86b8d22f4e5758f2e109180b801b21b8ec', + fingerprint: 'd15bc8a0fcecc3388e80e770890c8d097045a99258ffad7d409a306bae42513e', }, }, ]; diff --git a/packages/cashc/test/generation/fixtures/valid-contract-files/for_while_nested.ts b/packages/cashc/test/generation/fixtures/valid-contract-files/for_while_nested.ts index 3d00a2526..55067cc19 100644 --- a/packages/cashc/test/generation/fixtures/valid-contract-files/for_while_nested.ts +++ b/packages/cashc/test/generation/fixtures/valid-contract-files/for_while_nested.ts @@ -6,30 +6,30 @@ export const fixtures: Fixture[] = [ contractName: 'ForWhileNested', constructorInputs: [], abi: [{ name: 'spend', inputs: [] }], - bytecode: 'OP_0 OP_0 OP_BEGIN OP_DUP OP_2 OP_LESSTHAN OP_DUP OP_TOALTSTACK OP_IF OP_0 OP_BEGIN OP_DUP OP_2 OP_LESSTHAN OP_DUP OP_TOALTSTACK OP_IF OP_2 OP_PICK OP_2 OP_PICK OP_ADD OP_OVER OP_ADD OP_3 OP_ROLL OP_DROP OP_SWAP OP_TOALTSTACK OP_SWAP OP_FROMALTSTACK OP_DUP OP_1ADD OP_NIP OP_ENDIF OP_FROMALTSTACK OP_NOT OP_UNTIL OP_OVER OP_1ADD OP_ROT OP_DROP OP_NIP OP_ENDIF OP_FROMALTSTACK OP_NOT OP_UNTIL OP_DROP OP_4 OP_NUMEQUAL', + bytecode: 'OP_0 OP_0 OP_BEGIN OP_DUP OP_2 OP_LESSTHAN OP_DUP OP_TOALTSTACK OP_IF OP_0 OP_BEGIN OP_DUP OP_2 OP_LESSTHAN OP_DUP OP_TOALTSTACK OP_IF OP_2 OP_PICK OP_2 OP_PICK OP_ADD OP_OVER OP_ADD OP_3 OP_ROLL OP_DROP OP_ROT OP_ROT OP_1ADD OP_ENDIF OP_FROMALTSTACK OP_NOT OP_UNTIL OP_OVER OP_1ADD OP_ROT OP_DROP OP_NIP OP_ENDIF OP_FROMALTSTACK OP_NOT OP_UNTIL OP_DROP OP_4 OP_NUMEQUAL', debug: { - bytecode: '00006576529f766b63006576529f766b6352795279937893537a757c6b7c6c768b77686c9166788b7b7577686c916675549c', - sourceMap: '3:18:3:19;5:21:5:22;:8:13:9;:24:5:25;:28::29;:24:::1;;;:42:13:9:0;6:20:6:21;8:12:12:13;:19:8:20;:23::24;:19:::1;;;:26:12:13:0;9:22:9:25;;:28::29;;:22:::1;:32::33:0;:22:::1;:16::34;;;;;;;10:20:10:21:0;:::25:1;:16::26;8:26:12:13;;:12;;5:35:5:36:0;:::40:1;:31;;::13:9;:42;;:8;;;15:23:15:24:0;:8::26:1', + bytecode: '00006576529f766b63006576529f766b6352795279937893537a757b7b8b686c9166788b7b7577686c916675549c', + sourceMap: '3:18:3:19;5:21:5:22;:8:13:9;:24:5:25;:28::29;:24:::1;;;:42:13:9:0;6:20:6:21;8:12:12:13;:19:8:20;:23::24;:19:::1;;;:26:12:13:0;9:22:9:25;;:28::29;;:22:::1;:32::33:0;:22:::1;:16::34;;;;;10::10:26;8:26:12:13;;:12;;5:35:5:36:0;:::40:1;:31;;::13:9;:42;;:8;;;15:23:15:24:0;:8::26:1', logs: [ { - ip: 34, + ip: 30, line: 11, data: [ 'sum:', - { stackIndex: 2, type: 'int', ip: 34 }, + { stackIndex: 2, type: 'int', ip: 30 }, 'i:', - { stackIndex: 1, type: 'int', ip: 34 }, + { stackIndex: 1, type: 'int', ip: 30 }, 'j:', - { stackIndex: 0, type: 'int', ip: 34 }, + { stackIndex: 0, type: 'int', ip: 30 }, ], }, ], requires: [ - { ip: 50, line: 15 }, + { ip: 46, line: 15 }, ], - sourceTags: '34:37:lc;38:42:fu;43:46:lc;47:47:sc', + sourceTags: '30:33:lc;34:38:fu;39:42:lc;43:43:sc', }, - fingerprint: '9eb2ec48e103cb2b0d75a326b533756d8f5edb49b2ea43a5578f5ceebde8c2ce', + fingerprint: '6e3242d4469324cf4c6a1b2186dce828984c74bbdc05c8a5abd1917142b4c5e9', }, }, ]; diff --git a/packages/cashc/test/generation/fixtures/valid-contract-files/global_function_in_control_flow.ts b/packages/cashc/test/generation/fixtures/valid-contract-files/global_function_in_control_flow.ts index b6573cedb..c602161a6 100644 --- a/packages/cashc/test/generation/fixtures/valid-contract-files/global_function_in_control_flow.ts +++ b/packages/cashc/test/generation/fixtures/valid-contract-files/global_function_in_control_flow.ts @@ -18,7 +18,7 @@ export const fixtures: Fixture[] = [ // total = total + triple(x); + 'OP_OVER OP_3 OP_PICK OP_3 OP_MUL OP_ADD OP_ROT OP_DROP OP_SWAP ' // For loop update - + 'OP_DUP OP_1ADD OP_NIP ' + + 'OP_1ADD ' // Loop condition + 'OP_ENDIF OP_FROMALTSTACK OP_NOT OP_UNTIL ' // Cleanup @@ -33,13 +33,13 @@ export const fixtures: Fixture[] = [ + 'OP_9 OP_NUMEQUAL ' // Cleanup + 'OP_NIP', - fingerprint: '55b4a10e6ce60560acbb358c02189f85620385e0fcfd5013fe236339e8b238bb', + fingerprint: 'c14759968b45b80fb6bdf19f487d3dbad06e493976633b61eeb4d1522085b5cc', debug: { - bytecode: '7c92007c63006576539f766b637853795395937b757c768b77686c916675677853957768599c77', - sourceMap: '6:26:6:38;;7:20:7:21;8:12:8:19;:21:12:9;9:25:9:26;:12:11:13;:28:9:29;:32::33;:28:::1;;;:46:11:13:0;10:24:10:29;:39::40;;:32::41:1;;:24;:16::42;;;9:39:9:40:0;:::44:1;:35;:46:11:13;;:12;;;12:15:14:9:0;13:27:13:28;:20::29:1;;:12::30;12:15:14:9;15:25:15:26:0;:8::28:1;6:40:16:5', + bytecode: '7c92007c63006576539f766b637853795395937b757c8b686c916675677853957768599c77', + sourceMap: '6:26:6:38;;7:20:7:21;8:12:8:19;:21:12:9;9:25:9:26;:12:11:13;:28:9:29;:32::33;:28:::1;;;:46:11:13:0;10:24:10:29;:39::40;;:32::41:1;;:24;:16::42;;;9:35:9:44;:46:11:13;;:12;;;12:15:14:9:0;13:27:13:28;:20::29:1;;:12::30;12:15:14:9;15:25:15:26:0;:8::28:1;6:40:16:5', logs: [], - requires: [{ ip: 38, line: 15 }], - sourceTags: '0:1:pv;22:24:fu;25:28:lc;29:29:sc;38:38:sc', + requires: [{ ip: 36, line: 15 }], + sourceTags: '0:1:pv;22:22:fu;23:26:lc;27:27:sc;36:36:sc', functions: [ { name: 'triple', @@ -50,7 +50,7 @@ export const fixtures: Fixture[] = [ requires: [], }, ], - inlineRanges: '16:17:triple;32:33:triple', + inlineRanges: '16:17:triple;30:31:triple', }, }, }, diff --git a/packages/cashc/test/generation/fixtures/valid-contract-files/sum_input_amount.ts b/packages/cashc/test/generation/fixtures/valid-contract-files/sum_input_amount.ts index 79a939efe..62cea672e 100644 --- a/packages/cashc/test/generation/fixtures/valid-contract-files/sum_input_amount.ts +++ b/packages/cashc/test/generation/fixtures/valid-contract-files/sum_input_amount.ts @@ -16,20 +16,20 @@ export const fixtures: Fixture[] = [ // sum = tx.inputs[i].value; + 'OP_DUP OP_UTXOVALUE OP_ROT OP_DROP OP_SWAP ' // i = i + 1; - + 'OP_DUP OP_1ADD OP_NIP ' + + 'OP_1ADD ' // } while (i < tx.inputs.length); + 'OP_DUP OP_TXINPUTCOUNT OP_GREATERTHANOREQUAL OP_UNTIL ' // require(sum > 2000); + 'OP_SWAP d007 OP_GREATERTHAN ' // Cleanup + 'OP_NIP', - fingerprint: '8c4abe3e5702b4328f4d4c094e77bb69228aba3e7f7a2b51a84f9e5f119fd68d', + fingerprint: '46abccb7ef0a81c35e6f20ae62afd904d9e72e7bca703798a6726d7434ab7ad1', debug: { - bytecode: '00006576c67b757c768b7776c3a2667c02d007a077', - sourceMap: '3:18:3:19;4:16:4:17;6:8:9:39;7:28:7:29;:18::36:1;:12::37;;;8:16:8:17:0;:::21:1;:12::22;9:17:9:18:0;:21::37;6:8::39:1;;12:16:12:19:0;:22::26;:8::28:1;2:22:13:5', - logs: [{ ip: 15, line: 11, data: [{ stackIndex: 1, type: 'int', ip: 15 }] }], - requires: [{ ip: 18, line: 12 }], - sourceTags: '18:18:sc', + bytecode: '00006576c67b757c8b76c3a2667c02d007a077', + sourceMap: '3:18:3:19;4:16:4:17;6:8:9:39;7:28:7:29;:18::36:1;:12::37;;;8::8:22;9:17:9:18:0;:21::37;6:8::39:1;;12:16:12:19:0;:22::26;:8::28:1;2:22:13:5', + logs: [{ ip: 13, line: 11, data: [{ stackIndex: 1, type: 'int', ip: 13 }] }], + requires: [{ ip: 16, line: 12 }], + sourceTags: '16:16:sc', }, }, }, diff --git a/packages/cashc/test/generation/fixtures/valid-contract-files/tuple_reassignment.ts b/packages/cashc/test/generation/fixtures/valid-contract-files/tuple_reassignment.ts index 407c97540..faa537c29 100644 --- a/packages/cashc/test/generation/fixtures/valid-contract-files/tuple_reassignment.ts +++ b/packages/cashc/test/generation/fixtures/valid-contract-files/tuple_reassignment.ts @@ -10,17 +10,17 @@ export const fixtures: Fixture[] = [ contractName: 'TupleReassignment', constructorInputs: [], abi: [{ name: 'spend', inputs: [{ name: 'seed', type: 'int' }] }], - bytecode: 'OP_DUP OP_1ADD OP_2DUP OP_SWAP OP_2DUP OP_SWAP OP_0 OP_BEGIN OP_DUP OP_4 OP_LESSTHAN OP_DUP OP_TOALTSTACK OP_IF OP_OVER OP_4 OP_PICK OP_SWAP OP_5 OP_ROLL OP_DROP OP_SWAP OP_TOALTSTACK OP_SWAP OP_TOALTSTACK OP_SWAP OP_TOALTSTACK OP_SWAP OP_FROMALTSTACK OP_FROMALTSTACK OP_FROMALTSTACK OP_ROT OP_DROP OP_SWAP OP_DUP OP_1ADD OP_NIP OP_ENDIF OP_FROMALTSTACK OP_NOT OP_UNTIL OP_DROP OP_0 OP_BEGIN OP_DUP OP_4 OP_LESSTHAN OP_DUP OP_TOALTSTACK OP_IF OP_OVER OP_4 OP_PICK OP_OVER OP_2 OP_PICK OP_3 OP_ROLL OP_MUL OP_1ADD OP_TOALTSTACK OP_5 OP_ROLL OP_DROP OP_SWAP OP_TOALTSTACK OP_SWAP OP_TOALTSTACK OP_SWAP OP_TOALTSTACK OP_SWAP OP_FROMALTSTACK OP_FROMALTSTACK OP_FROMALTSTACK OP_ROT OP_DROP OP_SWAP OP_FROMALTSTACK OP_DUP OP_0 OP_GREATERTHANOREQUAL OP_VERIFY OP_OVER OP_1ADD OP_ROT OP_DROP OP_NIP OP_ENDIF OP_FROMALTSTACK OP_NOT OP_UNTIL OP_DROP OP_0 OP_BEGIN OP_DUP OP_2 OP_LESSTHAN OP_DUP OP_TOALTSTACK OP_IF OP_OVER OP_4 OP_PICK OP_OVER OP_2 OP_PICK OP_3 OP_ROLL OP_MUL OP_1ADD OP_6 OP_ROLL OP_DROP OP_SWAP OP_TOALTSTACK OP_SWAP OP_TOALTSTACK OP_SWAP OP_TOALTSTACK OP_SWAP OP_TOALTSTACK OP_SWAP OP_FROMALTSTACK OP_FROMALTSTACK OP_FROMALTSTACK OP_FROMALTSTACK OP_TOALTSTACK OP_ROT OP_DROP OP_SWAP OP_FROMALTSTACK OP_DUP OP_0 OP_GREATERTHANOREQUAL OP_VERIFY OP_OVER OP_1ADD OP_ROT OP_DROP OP_NIP OP_ENDIF OP_FROMALTSTACK OP_NOT OP_UNTIL OP_DROP OP_2DUP OP_ROT OP_ROT OP_ADD OP_ROT OP_ADD OP_ADD OP_0 OP_GREATERTHANOREQUAL OP_VERIFY OP_2DROP OP_2DROP OP_1', + bytecode: 'OP_DUP OP_1ADD OP_2DUP OP_SWAP OP_2DUP OP_SWAP OP_0 OP_BEGIN OP_DUP OP_4 OP_LESSTHAN OP_DUP OP_TOALTSTACK OP_IF OP_OVER OP_4 OP_PICK OP_SWAP OP_5 OP_ROLL OP_DROP OP_SWAP OP_TOALTSTACK OP_SWAP OP_TOALTSTACK OP_ROT OP_ROT OP_FROMALTSTACK OP_FROMALTSTACK OP_ROT OP_DROP OP_SWAP OP_1ADD OP_ENDIF OP_FROMALTSTACK OP_NOT OP_UNTIL OP_DROP OP_0 OP_BEGIN OP_DUP OP_4 OP_LESSTHAN OP_DUP OP_TOALTSTACK OP_IF OP_OVER OP_4 OP_PICK OP_OVER OP_2 OP_PICK OP_3 OP_ROLL OP_MUL OP_1ADD OP_TOALTSTACK OP_5 OP_ROLL OP_DROP OP_SWAP OP_TOALTSTACK OP_SWAP OP_TOALTSTACK OP_ROT OP_ROT OP_FROMALTSTACK OP_FROMALTSTACK OP_ROT OP_DROP OP_SWAP OP_FROMALTSTACK OP_DUP OP_0 OP_GREATERTHANOREQUAL OP_VERIFY OP_OVER OP_1ADD OP_ROT OP_DROP OP_NIP OP_ENDIF OP_FROMALTSTACK OP_NOT OP_UNTIL OP_DROP OP_0 OP_BEGIN OP_DUP OP_2 OP_LESSTHAN OP_DUP OP_TOALTSTACK OP_IF OP_OVER OP_4 OP_PICK OP_OVER OP_2 OP_PICK OP_3 OP_ROLL OP_MUL OP_1ADD OP_6 OP_ROLL OP_DROP OP_SWAP OP_TOALTSTACK OP_SWAP OP_TOALTSTACK OP_SWAP OP_TOALTSTACK OP_ROT OP_ROT OP_FROMALTSTACK OP_FROMALTSTACK OP_FROMALTSTACK OP_TOALTSTACK OP_ROT OP_DROP OP_SWAP OP_FROMALTSTACK OP_DUP OP_0 OP_GREATERTHANOREQUAL OP_VERIFY OP_OVER OP_1ADD OP_ROT OP_DROP OP_NIP OP_ENDIF OP_FROMALTSTACK OP_NOT OP_UNTIL OP_DROP OP_2DUP OP_ROT OP_ROT OP_ADD OP_ROT OP_ADD OP_ADD OP_0 OP_GREATERTHANOREQUAL OP_VERIFY OP_2DROP OP_2DROP OP_1', debug: { - bytecode: '768b6e7c6e7c006576549f766b637854797c557a757c6b7c6b7c6b7c6c6c6c7b757c768b77686c916675006576549f766b63785479785279537a958b6b557a757c6b7c6b7c6b7c6c6c6c7b757c6c7600a269788b7b7577686c916675006576529f766b63785479785279537a958b567a757c6b7c6b7c6b7c6b7c6c6c6c6c6b7b757c6c7600a269788b7b7577686c9166756e7b7b937b939300a2696d6d51', - sourceMap: '17:16:18:20;18:::24:1;21:22:21:26:0;:17::27:1;24:26:24:30:0;:21::31:1;27::27:22:0;:8:29:9;:24:27:25;:28::29;:24:::1;;;:42:29:9:0;28:26:28:27;:29::30;;:21::31:1;:12::32;;;;;;;;;;;;;;;;27:35:27:36:0;:::40:1;:31;:42:29:9;;:8;;;33:21:33:22:0;:8:36:9;:24:33:25;:28::29;:24:::1;;;:42:36:9:0;34:34:34:35;:37::38;;:29::39:1;;;;;;;:12::40;;;;;;;;;;;;;;;;;;35:20:35:22:0;:26::27;:20:::1;:12::29;33:35:33:36:0;:::40:1;:31;;::36:9;:42;;:8;;;40:21:40:22:0;:8:43:9;:24:40:25;:28::29;:24:::1;;;:42:43:9:0;41:34:41:35;:37::38;;:29::39:1;;;;;;;:12::40;;;;;;;;;;;;;;;;;;;;;42:20:42:22:0;:26::27;:20:::1;:12::29;40:35:40:36:0;:::40:1;:31;;::43:9;:42;;:8;;;46:24:46:28:0;48:16:48:17;:20::21;:16:::1;:24::25:0;:16:::1;:::29;:33::34:0;:16:::1;:8::36;16:29:49:5;;', + bytecode: '768b6e7c6e7c006576549f766b637854797c557a757c6b7c6b7b7b6c6c7b757c8b686c916675006576549f766b63785479785279537a958b6b557a757c6b7c6b7b7b6c6c7b757c6c7600a269788b7b7577686c916675006576529f766b63785479785279537a958b567a757c6b7c6b7c6b7b7b6c6c6c6b7b757c6c7600a269788b7b7577686c9166756e7b7b937b939300a2696d6d51', + sourceMap: '17:16:18:20;18:::24:1;21:22:21:26:0;:17::27:1;24:26:24:30:0;:21::31:1;27::27:22:0;:8:29:9;:24:27:25;:28::29;:24:::1;;;:42:29:9:0;28:26:28:27;:29::30;;:21::31:1;:12::32;;;;;;;;;;;;;;27:31:27:40;:42:29:9;;:8;;;33:21:33:22:0;:8:36:9;:24:33:25;:28::29;:24:::1;;;:42:36:9:0;34:34:34:35;:37::38;;:29::39:1;;;;;;;:12::40;;;;;;;;;;;;;;;;35:20:35:22:0;:26::27;:20:::1;:12::29;33:35:33:36:0;:::40:1;:31;;::36:9;:42;;:8;;;40:21:40:22:0;:8:43:9;:24:40:25;:28::29;:24:::1;;;:42:43:9:0;41:34:41:35;:37::38;;:29::39:1;;;;;;;:12::40;;;;;;;;;;;;;;;;;;;42:20:42:22:0;:26::27;:20:::1;:12::29;40:35:40:36:0;:::40:1;:31;;::43:9;:42;;:8;;;46:24:46:28:0;48:16:48:17;:20::21;:16:::1;:24::25:0;:16:::1;:::29;:33::34:0;:16:::1;:8::36;16:29:49:5;;', logs: [], requires: [ - { ip: 81, line: 35 }, - { ip: 134, line: 42 }, - { ip: 154, line: 48 }, + { ip: 75, line: 35 }, + { ip: 126, line: 42 }, + { ip: 146, line: 48 }, ], - sourceTags: '34:36:fu;37:40:lc;41:41:sc;82:86:fu;87:90:lc;91:91:sc;135:139:fu;140:143:lc;144:144:sc', + sourceTags: '32:32:fu;33:36:lc;37:37:sc;76:80:fu;81:84:lc;85:85:sc;127:131:fu;132:135:lc;136:136:sc', functions: [ { name: 'swap', @@ -39,9 +39,9 @@ export const fixtures: Fixture[] = [ requires: [], }, ], - inlineRanges: '3:3:swap;5:5:swap;17:17:swap;53:59:step;103:109:step;146:146:swap', + inlineRanges: '3:3:swap;5:5:swap;17:17:swap;49:55:step;97:103:step;138:138:swap', }, - fingerprint: 'fd8a1643726f50a4c38fd67d463cab2a753fc405088134cd6b72a87b9d3bca6a', + fingerprint: '0c488b42372749a5a7278c738799b229e4346abe52a7172d3d1813764dbc67e2', }, }, ]; diff --git a/packages/cashc/test/generation/fixtures/valid-contract-files/tuple_reassignment_after_final_read.ts b/packages/cashc/test/generation/fixtures/valid-contract-files/tuple_reassignment_after_final_read.ts index 21bc2d29d..b77c5ed1f 100644 --- a/packages/cashc/test/generation/fixtures/valid-contract-files/tuple_reassignment_after_final_read.ts +++ b/packages/cashc/test/generation/fixtures/valid-contract-files/tuple_reassignment_after_final_read.ts @@ -43,7 +43,7 @@ export const fixtures: Fixture[] = [ // (p, q) = pair(x); + 'OP_2 OP_PICK OP_DUP OP_2 OP_MUL OP_SWAP OP_1ADD OP_ROT OP_DROP OP_SWAP OP_ROT OP_DROP OP_SWAP ' // x = x + 1; - + 'OP_2 OP_PICK OP_1ADD OP_3 OP_ROLL OP_DROP OP_SWAP OP_TOALTSTACK OP_SWAP OP_FROMALTSTACK ' + + 'OP_2 OP_PICK OP_1ADD OP_3 OP_ROLL OP_DROP OP_ROT OP_ROT ' // Loop condition + 'OP_ENDIF OP_FROMALTSTACK OP_NOT OP_UNTIL ' // require(q == 0 || q == 2); @@ -52,13 +52,13 @@ export const fixtures: Fixture[] = [ + 'OP_NIP OP_NIP ' // } + 'OP_ENDIF', - fingerprint: '510ff239ab3ec7cc5d4301e1ef31a179c01bc4b6e73e800f03bd2674c9996ae3', + fingerprint: 'c8619cca31b03183005fff30a7e1a4abac2b15f0dab8e28526c17aa5edbd6659', debug: { - bytecode: '76009c635a00785a9d5379519c6353797652957c8b7b757c7b757c6876009c7c529c9b77777767519d5a00785a9d655279519c766b6352797652957c8b7b757c7b757c52798b537a757c6b7c6c686c916676009c7c529c9b777768', - sourceMap: '11:4:19:5;;;;12:16:12:18;13::13:17;14::14;:21::23;:8::25:1;15:12:15:13:0;;:17::18;:12:::1;:20:17:9:0;16:26:16:27;;:21::28:1;;;;;:12::29;;;;;;15:20:17:9;18:16:18:17:0;:21::22;:16:::1;:26::27:0;:31::32;:26:::1;:8::34;11:29:19:5;;;:4;21::30::0;;22:16:22:18;23::23:17;24::24;:21::23;:8::25:1;25::28:9:0;:15:25:16;;:20::21;:15:::1;;;:23:28:9:0;26:26:26:27;;:21::28:1;;;;;:12::29;;;;;;27:16:27:17:0;;:::21:1;:12::22;;;;;;;25:23:28:9;;:8;;29:16:29:17:0;:21::22;:16:::1;:26::27:0;:31::32;:26:::1;:8::34;21:30:30:5;;10:0:31:1', + bytecode: '76009c635a00785a9d5379519c6353797652957c8b7b757c7b757c6876009c7c529c9b77777767519d5a00785a9d655279519c766b6352797652957c8b7b757c7b757c52798b537a757b7b686c916676009c7c529c9b777768', + sourceMap: '11:4:19:5;;;;12:16:12:18;13::13:17;14::14;:21::23;:8::25:1;15:12:15:13:0;;:17::18;:12:::1;:20:17:9:0;16:26:16:27;;:21::28:1;;;;;:12::29;;;;;;15:20:17:9;18:16:18:17:0;:21::22;:16:::1;:26::27:0;:31::32;:26:::1;:8::34;11:29:19:5;;;:4;21::30::0;;22:16:22:18;23::23:17;24::24;:21::23;:8::25:1;25::28:9:0;:15:25:16;;:20::21;:15:::1;;;:23:28:9:0;26:26:26:27;;:21::28:1;;;;;:12::29;;;;;;27:16:27:17:0;;:::21:1;:12::22;;;;;25:23:28:9;;:8;;29:16:29:17:0;:21::22;:16:::1;:26::27:0;:31::32;:26:::1;:8::34;21:30:30:5;;10:0:31:1', logs: [], - requires: [{ ip: 8, line: 14 }, { ip: 35, line: 18 }, { ip: 45, line: 24 }, { ip: 88, line: 29 }], - sourceTags: '35:37:sc;77:80:lc;88:89:sc', + requires: [{ ip: 8, line: 14 }, { ip: 35, line: 18 }, { ip: 45, line: 24 }, { ip: 86, line: 29 }], + sourceTags: '35:37:sc;75:78:lc;86:87:sc', functions: [ { name: 'pair', diff --git a/packages/cashc/test/generation/fixtures/valid-contract-files/tuple_reassignment_branches.ts b/packages/cashc/test/generation/fixtures/valid-contract-files/tuple_reassignment_branches.ts index 406602dec..7be2de447 100644 --- a/packages/cashc/test/generation/fixtures/valid-contract-files/tuple_reassignment_branches.ts +++ b/packages/cashc/test/generation/fixtures/valid-contract-files/tuple_reassignment_branches.ts @@ -38,7 +38,7 @@ export const fixtures: Fixture[] = [ + 'OP_OVER OP_10 OP_GREATERTHAN OP_IF ' // (total, int extra) = branchPair(a + 1) — call, park extra's value on the altstack, // fold total's value into its slot (OP_NIP), restore extra's value - + 'OP_OVER OP_1ADD OP_0 OP_INVOKE OP_TOALTSTACK OP_NIP OP_FROMALTSTACK ' + + 'OP_OVER OP_1ADD OP_0 OP_INVOKE OP_ROT OP_DROP ' // require(extra != 0) + 'OP_DUP OP_0 OP_NUMNOTEQUAL OP_VERIFY ' // scope cleanup (drop extra) @@ -46,16 +46,16 @@ export const fixtures: Fixture[] = [ // require(total >= 0) + cleanup + 'OP_0 OP_GREATERTHANOREQUAL OP_NIP OP_ENDIF', debug: { - bytecode: '127653957857979378529693768b7c52957b94008976009c630052795aa0635279008a7b757c76009e69756800a2777767519d00785aa063788b008a6b776c76009e69756800a27768', - sourceMap: '7::10:1;;::::1;14:4:21:5:0;;;;15:20:15:21;16:12:16:13;;:16::18;:12:::1;:20:19:9:0;17:38:17:39;;:27::40:1;;:12::41;;;18:20:18:21:0;:25::26;:20:::1;:12::28;16:20:19:9;;20:25:20:26:0;:8::28:1;14:37:21:5;;:4;25::32::0;;26:20:26:21;27:12:27:13;:16::18;:12:::1;:20:30:9:0;28:44:28:45;:::49:1;:33::50;;:12::51;;;29:20:29:25:0;:29::30;:20:::1;:12::32;27:20:30:9;;31:25:31:26:0;:8::28:1;25:38:32:5;12:0:33:1', + bytecode: '127653957857979378529693768b7c52957b94008976009c630052795aa0635279008a7b757c76009e69756800a2777767519d00785aa063788b008a7b7576009e69756800a27768', + sourceMap: '7::10:1;;::::1;14:4:21:5:0;;;;15:20:15:21;16:12:16:13;;:16::18;:12:::1;:20:19:9:0;17:38:17:39;;:27::40:1;;:12::41;;;18:20:18:21:0;:25::26;:20:::1;:12::28;16:20:19:9;;20:25:20:26:0;:8::28:1;14:37:21:5;;:4;25::32::0;;26:20:26:21;27:12:27:13;:16::18;:12:::1;:20:30:9:0;28:44:28:45;:::49:1;:33::50;;:12::51;;29:20:29:25:0;:29::30;:20:::1;:12::32;27:20:30:9;;31:25:31:26:0;:8::28:1;25:38:32:5;12:0:33:1', logs: [], requires: [ { ip: 23, line: 18 }, { ip: 28, line: 20 }, - { ip: 48, line: 29 }, - { ip: 53, line: 31 }, + { ip: 47, line: 29 }, + { ip: 52, line: 31 }, ], - sourceTags: '24:24:sc;28:29:sc;49:49:sc;53:53:sc', + sourceTags: '24:24:sc;28:29:sc;48:48:sc;52:52:sc', functions: [ { id: 0, @@ -68,7 +68,7 @@ export const fixtures: Fixture[] = [ }, ], }, - fingerprint: 'da4982948327a26f2c708b13af6977715747aa0b5c64bc00b04e3ddbc11ca67d', + fingerprint: '8d4e93cb8ad5d2bae6e6bf508bc0f5cd008120352e9a434f80b0af47241e67c0', }, }, ]; diff --git a/packages/cashc/test/generation/fixtures/valid-contract-files/while_loop.ts b/packages/cashc/test/generation/fixtures/valid-contract-files/while_loop.ts index 79812f925..a456e02eb 100644 --- a/packages/cashc/test/generation/fixtures/valid-contract-files/while_loop.ts +++ b/packages/cashc/test/generation/fixtures/valid-contract-files/while_loop.ts @@ -6,19 +6,19 @@ export const fixtures: Fixture[] = [ contractName: 'Loopy', constructorInputs: [], abi: [{ name: 'doLoop', inputs: [] }], - bytecode: 'OP_0 OP_BEGIN OP_DUP OP_TXINPUTCOUNT OP_LESSTHAN OP_DUP OP_TOALTSTACK OP_IF OP_DUP OP_1ADD OP_NIP OP_ENDIF OP_FROMALTSTACK OP_NOT OP_UNTIL OP_2 OP_GREATERTHAN', + bytecode: 'OP_0 OP_BEGIN OP_DUP OP_TXINPUTCOUNT OP_LESSTHAN OP_DUP OP_TOALTSTACK OP_IF OP_1ADD OP_ENDIF OP_FROMALTSTACK OP_NOT OP_UNTIL OP_2 OP_GREATERTHAN', debug: { - bytecode: '006576c39f766b63768b77686c916652a0', - sourceMap: '3:16:3:17;5:8:7:9;:15:5:16;:19::35;:15:::1;;;:37:7:9:0;6:16:6:17;:::21:1;:12::22;5:37:7:9;;:8;;10:20:10:21:0;:8::23:1', + bytecode: '006576c39f766b638b686c916652a0', + sourceMap: '3:16:3:17;5:8:7:9;:15:5:16;:19::35;:15:::1;;;:37:7:9:0;6:12:6:22:1;5:37:7:9;;:8;;10:20:10:21:0;:8::23:1', logs: [ - { ip: 15, line: 9, data: [{ stackIndex: 0, type: 'int', ip: 15 }] }, + { ip: 13, line: 9, data: [{ stackIndex: 0, type: 'int', ip: 13 }] }, ], requires: [ - { ip: 17, line: 10 }, + { ip: 15, line: 10 }, ], - sourceTags: '11:14:lc', + sourceTags: '9:12:lc', }, - fingerprint: '00fc9253e439b8a2f39ba60d1d173ff4d19f557802b40b750eb6df5f92b1001e', + fingerprint: 'baa407724b9c7e497eec65233682d98b661de3e82d4d3447964b64b6a2929b09', }, }, ]; diff --git a/packages/cashc/test/generation/fixtures/valid-contract-files/while_loop_basic.ts b/packages/cashc/test/generation/fixtures/valid-contract-files/while_loop_basic.ts index 09635a1c1..f5e430986 100644 --- a/packages/cashc/test/generation/fixtures/valid-contract-files/while_loop_basic.ts +++ b/packages/cashc/test/generation/fixtures/valid-contract-files/while_loop_basic.ts @@ -6,17 +6,17 @@ export const fixtures: Fixture[] = [ contractName: 'WhileLoopBasic', constructorInputs: [], abi: [{ name: 'spend', inputs: [] }], - bytecode: 'OP_0 OP_BEGIN OP_DUP OP_3 OP_LESSTHAN OP_DUP OP_TOALTSTACK OP_IF OP_DUP OP_1ADD OP_NIP OP_ENDIF OP_FROMALTSTACK OP_NOT OP_UNTIL OP_3 OP_NUMEQUAL', + bytecode: 'OP_0 OP_BEGIN OP_DUP OP_3 OP_LESSTHAN OP_DUP OP_TOALTSTACK OP_IF OP_1ADD OP_ENDIF OP_FROMALTSTACK OP_NOT OP_UNTIL OP_3 OP_NUMEQUAL', debug: { - bytecode: '006576539f766b63768b77686c9166539c', - sourceMap: '3:16:3:17;5:8:7:9;:15:5:16;:19::20;:15:::1;;;:22:7:9:0;6:16:6:17;:::21:1;:12::22;5:22:7:9;;:8;;9:21:9:22:0;:8::24:1', + bytecode: '006576539f766b638b686c9166539c', + sourceMap: '3:16:3:17;5:8:7:9;:15:5:16;:19::20;:15:::1;;;:22:7:9:0;6:12:6:22:1;5:22:7:9;;:8;;9:21:9:22:0;:8::24:1', logs: [], requires: [ - { ip: 17, line: 9 }, + { ip: 15, line: 9 }, ], - sourceTags: '11:14:lc', + sourceTags: '9:12:lc', }, - fingerprint: '5a456e72142ae6beb6f64a3af7edfe9e14295b17724c4dfec0d84940c545d457', + fingerprint: 'de46b0953afd7e2ca5b0e1c9e6c934500ddfb384061239e545d89b4848dd2384', }, }, ]; diff --git a/packages/cashc/test/generation/fixtures/valid-contract-files/while_loop_nested.ts b/packages/cashc/test/generation/fixtures/valid-contract-files/while_loop_nested.ts index b2d0036a1..a9281c3b5 100644 --- a/packages/cashc/test/generation/fixtures/valid-contract-files/while_loop_nested.ts +++ b/packages/cashc/test/generation/fixtures/valid-contract-files/while_loop_nested.ts @@ -20,11 +20,11 @@ export const fixtures: Fixture[] = [ // total = total + 1; + 'OP_OVER OP_1ADD OP_ROT OP_DROP OP_SWAP ' // j = j + 1; - + 'OP_DUP OP_1ADD OP_NIP ' + + 'OP_1ADD ' // Loop condition + 'OP_ENDIF OP_FROMALTSTACK OP_NOT OP_UNTIL ' // i = i + 1; - + 'OP_2 OP_PICK OP_1ADD OP_3 OP_ROLL OP_DROP OP_SWAP OP_TOALTSTACK OP_SWAP OP_FROMALTSTACK ' + + 'OP_2 OP_PICK OP_1ADD OP_3 OP_ROLL OP_DROP OP_ROT OP_ROT ' // Cleanup + 'OP_DROP ' // Loop condition @@ -33,13 +33,13 @@ export const fixtures: Fixture[] = [ + 'OP_SWAP OP_2 OP_NUMEQUALVERIFY ' // require(total == 4); + 'OP_4 OP_NUMEQUAL', - fingerprint: '1305b87f8914755fb2e52934624cd80fc3bf61117d6957730845fcbc2002e8b4', + fingerprint: '1994bca592984b848eb3fba2915fe03e0ef2fbd13e0e6e5f6efb60849cec54aa', debug: { - bytecode: '00006578529f766b63006576529f766b63788b7b757c768b77686c916652798b537a757c6b7c6c75686c91667c529d549c', - sourceMap: '3:16:3:17;4:20:4:21;6:8:15:9;:15:6:16;:19::20;:15:::1;;;:22:15:9:0;7:20:7:21;9:12:12:13;:19:9:20;:23::24;:19:::1;;;:26:12:13:0;10:24:10:29;:::33:1;:16::34;;;11:20:11:21:0;:::25:1;:16::26;9:26:12:13;;:12;;14:16:14:17:0;;:::21:1;:12::22;;;;;;;6:22:15:9;;;:8;;17:16:17:17:0;:21::22;:8::24:1;18:25:18:26:0;:8::28:1', + bytecode: '00006578529f766b63006576529f766b63788b7b757c8b686c916652798b537a757b7b75686c91667c529d549c', + sourceMap: '3:16:3:17;4:20:4:21;6:8:15:9;:15:6:16;:19::20;:15:::1;;;:22:15:9:0;7:20:7:21;9:12:12:13;:19:9:20;:23::24;:19:::1;;;:26:12:13:0;10:24:10:29;:::33:1;:16::34;;;11::11:26;9:26:12:13;;:12;;14:16:14:17:0;;:::21:1;:12::22;;;;;6:22:15:9;;;:8;;17:16:17:17:0;:21::22;:8::24:1;18:25:18:26:0;:8::28:1', logs: [], - requires: [{ ip: 46, line: 17 }, { ip: 49, line: 18 }], - sourceTags: '25:28:lc;39:39:sc;40:43:lc', + requires: [{ ip: 42, line: 17 }, { ip: 45, line: 18 }], + sourceTags: '23:26:lc;35:35:sc;36:39:lc', }, }, }, diff --git a/packages/utils/src/optimisations.ts b/packages/utils/src/optimisations.ts index fb52c677c..e6ac79bbb 100644 --- a/packages/utils/src/optimisations.ts +++ b/packages/utils/src/optimisations.ts @@ -73,7 +73,7 @@ export const optimisationReplacements = [ // Random optimisations (don't know what I'm targeting with this) ['OP_2DUP OP_DROP', 'OP_OVER'], ['OP_2DUP OP_NIP', 'OP_DUP'], - ['OP_CAT OP_DROP', 'OP_2DROP'], + // Note: OP_CAT OP_DROP => OP_2DROP is not safe, since it removes OP_CAT's maximum element size check ['OP_NIP OP_DROP', 'OP_2DROP'], // Far-fetched stuff @@ -123,6 +123,9 @@ export const optimisationReplacements = [ ['OP_SIZE OP_SPLIT OP_DROP', ''], // Hardcoded arithmetic + // Note that OP_NOT does a VM-number check that OP_NOTIF does not, which gets removed by this optimisation. Compiled + // bools are always valid VM numbers unless they come from unsafe_bool() or unenforced function parameter types. + // This is also why OP_0 OP_NUMEQUAL => OP_NOT is not safe: it would remove the function selector's number check ['OP_NOT OP_IF', 'OP_NOTIF'], // Merge OP_VERIFY @@ -153,4 +156,20 @@ export const optimisationReplacements = [ ['OP_NOT OP_NOT OP_UNTIL', 'OP_UNTIL'], ['OP_NOT OP_NOTIF', 'OP_IF'], ['OP_NOT OP_NOT OP_VERIFY', 'OP_VERIFY'], + + // Remove extraneous OP_DUP/OP_NIP around in-place increments (e.g. for-loop updates) + ['OP_DUP OP_1ADD OP_NIP', 'OP_1ADD'], + ['OP_DUP OP_1SUB OP_NIP', 'OP_1SUB'], + + // Replace alt stack round trips (e.g. from reassignments inside loops) with regular stack ops + ['OP_SWAP OP_TOALTSTACK OP_SWAP OP_FROMALTSTACK', 'OP_ROT OP_ROT'], + ['OP_TOALTSTACK OP_NIP OP_FROMALTSTACK', 'OP_ROT OP_DROP'], + ['OP_ROT OP_ROT OP_2DROP', 'OP_NIP OP_NIP'], + + // Remove extraneous OP_SWAP before order-independent operations + ['OP_SWAP OP_BOOLOR', 'OP_BOOLOR'], + ['OP_SWAP OP_BOOLAND', 'OP_BOOLAND'], + ['OP_SWAP OP_MIN', 'OP_MIN'], + ['OP_SWAP OP_MAX', 'OP_MAX'], + ['OP_SWAP OP_2DROP', 'OP_2DROP'], ] as [string, string][]; diff --git a/packages/utils/src/script.ts b/packages/utils/src/script.ts index cb6077716..9cb080e78 100644 --- a/packages/utils/src/script.ts +++ b/packages/utils/src/script.ts @@ -236,8 +236,9 @@ function replaceOps( const replacementLength = replacement === '' ? 0 : replacement.split(/\s+/).length; const lengthDiff = patternLength - replacementLength; - // (?=\s|$) requires the pattern to end at a token boundary (no partial matches) without consuming the separator - const regex = new RegExp(`${pattern}(?=\\s|$)`, 'g'); + // (?>> loop condition check */ - /* } */ -OP_OVER OP_1ADD OP_ROT OP_DROP OP_NIP /* >>> for-loop update (i = i + 1) */ -OP_ENDIF OP_FROMALTSTACK OP_NOT OP_UNTIL /* >>> loop condition check */ -OP_DROP /* >>> scope cleanup */ - /* } */ - /* */ -OP_4 OP_NUMEQUAL /* require(sum == 4); */ - /* } */ - /* } */ + /* contract ForWhileNested() { */ + /* function spend() { */ +OP_0 /* int sum = 0; */ + /* */ +OP_0 OP_BEGIN OP_DUP OP_2 OP_LESSTHAN OP_DUP OP_TOALTSTACK OP_IF /* for (int i = 0; i < 2; i = i + 1) { */ +OP_0 /* int j = 0; */ + /* */ +OP_BEGIN OP_DUP OP_2 OP_LESSTHAN OP_DUP OP_TOALTSTACK OP_IF /* while (j < 2) { */ +OP_2 OP_PICK OP_2 OP_PICK OP_ADD OP_OVER OP_ADD OP_3 OP_ROLL OP_DROP OP_ROT OP_ROT /* sum = sum + i + j; */ +OP_1ADD /* j = j + 1; */ + /* console.log("sum:", sum, "i:", i, "j:", j); */ +OP_ENDIF OP_FROMALTSTACK OP_NOT OP_UNTIL /* >>> loop condition check */ + /* } */ +OP_OVER OP_1ADD OP_ROT OP_DROP OP_NIP /* >>> for-loop update (i = i + 1) */ +OP_ENDIF OP_FROMALTSTACK OP_NOT OP_UNTIL /* >>> loop condition check */ +OP_DROP /* >>> scope cleanup */ + /* } */ + /* */ +OP_4 OP_NUMEQUAL /* require(sum == 4); */ + /* } */ + /* } */ `.replace(/^\n+/, '').replace(/\n+$/, ''), }, { @@ -279,35 +279,35 @@ OP_4 OP_NUMEQUAL require(total + count == 12); } }`, - asmBytecode: 'OP_0 OP_0 OP_BEGIN OP_DUP OP_3 OP_LESSTHAN OP_DUP OP_TOALTSTACK OP_IF OP_0 OP_BEGIN OP_DUP OP_2 OP_LESSTHAN OP_DUP OP_TOALTSTACK OP_IF OP_2 OP_PICK OP_2 OP_PICK OP_ADD OP_OVER OP_ADD OP_3 OP_ROLL OP_DROP OP_SWAP OP_TOALTSTACK OP_SWAP OP_FROMALTSTACK OP_DUP OP_1ADD OP_NIP OP_ENDIF OP_FROMALTSTACK OP_NOT OP_UNTIL OP_DROP OP_DUP OP_1ADD OP_NIP OP_ENDIF OP_FROMALTSTACK OP_NOT OP_UNTIL OP_DROP OP_0 OP_BEGIN OP_DUP OP_1ADD OP_NIP OP_DUP OP_3 OP_GREATERTHANOREQUAL OP_UNTIL OP_ADD OP_12 OP_NUMEQUAL', - sourceMap: '3:20:3:21;5:21:5:22;:8:10:9;:24:5:25;:28::29;:24:::1;;;6:19:10:9:0;7:25:7:26;:12:9:13;:28:7:29;:32::33;:28:::1;;;:46:9:13:0;8:24:8:29;;:32::33;;:24:::1;:36::37:0;:24:::1;:16::38;;;;;;;7:39:7:40:0;:::44:1;:35;:46:9:13;;:12;;;6::6::0;:::17:1;5:31;6:19:10:9;;5:8;;;12:20:12:21:0;13:8:15:28;14:20:14:25;:::29:1;:12::30;15:17:15:22:0;:25::26;13:8::28:1;;17:16:17:29;:33::35:0;:8::37:1', - sourceTags: '31:33:fu;34:37:lc;38:38:sc;39:41:fu;42:45:lc;46:46:sc', + asmBytecode: 'OP_0 OP_0 OP_BEGIN OP_DUP OP_3 OP_LESSTHAN OP_DUP OP_TOALTSTACK OP_IF OP_0 OP_BEGIN OP_DUP OP_2 OP_LESSTHAN OP_DUP OP_TOALTSTACK OP_IF OP_2 OP_PICK OP_2 OP_PICK OP_ADD OP_OVER OP_ADD OP_3 OP_ROLL OP_DROP OP_ROT OP_ROT OP_1ADD OP_ENDIF OP_FROMALTSTACK OP_NOT OP_UNTIL OP_DROP OP_1ADD OP_ENDIF OP_FROMALTSTACK OP_NOT OP_UNTIL OP_DROP OP_0 OP_BEGIN OP_1ADD OP_DUP OP_3 OP_GREATERTHANOREQUAL OP_UNTIL OP_ADD OP_12 OP_NUMEQUAL', + sourceMap: '3:20:3:21;5:21:5:22;:8:10:9;:24:5:25;:28::29;:24:::1;;;6:19:10:9:0;7:25:7:26;:12:9:13;:28:7:29;:32::33;:28:::1;;;:46:9:13:0;8:24:8:29;;:32::33;;:24:::1;:36::37:0;:24:::1;:16::38;;;;;7:35:7:44;:46:9:13;;:12;;;5:31:6:17;6:19:10:9;;5:8;;;12:20:12:21:0;13:8:15:28;14:12:14:30:1;15:17:15:22:0;:25::26;13:8::28:1;;17:16:17:29;:33::35:0;:8::37:1', + sourceTags: '29:29:fu;30:33:lc;34:34:sc;35:35:fu;36:39:lc;40:40:sc', expectedBitAuthScript: ` - /* contract NestedForWithDoWhile() { */ - /* function spend() { */ -OP_0 /* int total = 0; */ - /* */ -OP_0 OP_BEGIN OP_DUP OP_3 OP_LESSTHAN OP_DUP OP_TOALTSTACK /* for (int i = 0; i < 3; i = */ -OP_IF /* i + 1) { */ -OP_0 OP_BEGIN OP_DUP OP_2 OP_LESSTHAN OP_DUP OP_TOALTSTACK OP_IF /* for (int j = 0; j < 2; j = j + 1) { */ -OP_2 OP_PICK OP_2 OP_PICK OP_ADD OP_OVER OP_ADD OP_3 OP_ROLL OP_DROP OP_SWAP OP_TOALTSTACK OP_SWAP OP_FROMALTSTACK /* total = total + i + j; */ -OP_DUP OP_1ADD OP_NIP /* >>> for-loop update (j = j + 1) */ -OP_ENDIF OP_FROMALTSTACK OP_NOT OP_UNTIL /* >>> loop condition check */ -OP_DROP /* >>> scope cleanup */ - /* } */ -OP_DUP OP_1ADD OP_NIP /* >>> for-loop update (i + 1) */ -OP_ENDIF OP_FROMALTSTACK OP_NOT OP_UNTIL /* >>> loop condition check */ -OP_DROP /* >>> scope cleanup */ - /* } */ - /* */ -OP_0 /* int count = 0; */ -OP_BEGIN /* do { */ -OP_DUP OP_1ADD OP_NIP /* count = count + 1; */ -OP_DUP OP_3 OP_GREATERTHANOREQUAL OP_UNTIL /* } while (count < 3); */ - /* */ -OP_ADD OP_12 OP_NUMEQUAL /* require(total + count == 12); */ - /* } */ - /* } */ + /* contract NestedForWithDoWhile() { */ + /* function spend() { */ +OP_0 /* int total = 0; */ + /* */ +OP_0 OP_BEGIN OP_DUP OP_3 OP_LESSTHAN OP_DUP OP_TOALTSTACK /* for (int i = 0; i < 3; i = */ +OP_IF /* i + 1) { */ +OP_0 OP_BEGIN OP_DUP OP_2 OP_LESSTHAN OP_DUP OP_TOALTSTACK OP_IF /* for (int j = 0; j < 2; j = j + 1) { */ +OP_2 OP_PICK OP_2 OP_PICK OP_ADD OP_OVER OP_ADD OP_3 OP_ROLL OP_DROP OP_ROT OP_ROT /* total = total + i + j; */ +OP_1ADD /* >>> for-loop update (j = j + 1) */ +OP_ENDIF OP_FROMALTSTACK OP_NOT OP_UNTIL /* >>> loop condition check */ +OP_DROP /* >>> scope cleanup */ + /* } */ +OP_1ADD /* >>> for-loop update () */ +OP_ENDIF OP_FROMALTSTACK OP_NOT OP_UNTIL /* >>> loop condition check */ +OP_DROP /* >>> scope cleanup */ + /* } */ + /* */ +OP_0 /* int count = 0; */ +OP_BEGIN /* do { */ +OP_1ADD /* count = count + 1; */ +OP_DUP OP_3 OP_GREATERTHANOREQUAL OP_UNTIL /* } while (count < 3); */ + /* */ +OP_ADD OP_12 OP_NUMEQUAL /* require(total + count == 12); */ + /* } */ + /* } */ `.replace(/^\n+/, '').replace(/\n+$/, ''), }, { @@ -459,7 +459,7 @@ contract LocalFunctions() { OP_0 /* int sum = 0; */ OP_0 OP_BEGIN OP_DUP OP_3 OP_PICK OP_LESSTHAN OP_DUP OP_TOALTSTACK OP_IF /* for (int i = 0; i < n; i = i + 1) { */ OP_2DUP OP_ADD OP_ROT OP_DROP OP_SWAP /* sum = sum + i; */ - OP_DUP OP_1ADD OP_NIP /* >>> for-loop update (i = i + 1) */ + OP_1ADD /* >>> for-loop update (i = i + 1) */ OP_ENDIF OP_FROMALTSTACK OP_NOT OP_UNTIL /* >>> loop condition check */ OP_DROP /* >>> scope cleanup */ /* } */ diff --git a/packages/utils/test/manual-optimisation-proofs.test.ts b/packages/utils/test/manual-optimisation-proofs.test.ts deleted file mode 100644 index d2a50d131..000000000 --- a/packages/utils/test/manual-optimisation-proofs.test.ts +++ /dev/null @@ -1,57 +0,0 @@ -describe('Manual Optimisation Proofs', () => { - it.todo('Properly implement automated tests'); - // <1> <2> OP_GREATERTHAN OP_NOT - // <1> <2> OP_LESSTHANOREQUAL - // OP_EQUALVERIFY - - // <2> <1> OP_GREATERTHAN OP_NOT - // <2> <1> OP_LESSTHANOREQUAL - // OP_EQUALVERIFY - - // <1> <1> OP_GREATERTHAN OP_NOT - // <1> <1> OP_LESSTHANOREQUAL - // OP_EQUALVERIFY - - - - - // <1> <2> OP_LESSTHAN OP_NOT - // <1> <2> OP_GREATERTHANOREQUAL - // OP_EQUALVERIFY - - // <2> <1> OP_LESSTHAN OP_NOT - // <2> <1> OP_GREATERTHANOREQUAL - // OP_EQUALVERIFY - - // <1> <1> OP_LESSTHAN OP_NOT - // <1> <1> OP_GREATERTHANOREQUAL - // OP_EQUALVERIFY - - - - // <1> <2> OP_LESSTHANOREQUAL OP_NOT - // <1> <2> OP_GREATERTHAN - // OP_EQUALVERIFY - - // <2> <1> OP_LESSTHANOREQUAL OP_NOT - // <2> <1> OP_GREATERTHAN - // OP_EQUALVERIFY - - // <1> <1> OP_LESSTHANOREQUAL OP_NOT - // <1> <1> OP_GREATERTHAN - // OP_EQUALVERIFY - - - - // <1> <2> OP_GREATERTHANOREQUAL OP_NOT - // <1> <2> OP_LESSTHAN - // OP_EQUALVERIFY - - // <2> <1> OP_GREATERTHANOREQUAL OP_NOT - // <2> <1> OP_LESSTHAN - // OP_EQUALVERIFY - - // <1> <1> OP_GREATERTHANOREQUAL OP_NOT - // <1> <1> OP_LESSTHAN - // OP_EQUALVERIFY -}); diff --git a/packages/utils/test/optimisations.test.ts b/packages/utils/test/optimisations.test.ts new file mode 100644 index 000000000..3a3dc1731 --- /dev/null +++ b/packages/utils/test/optimisations.test.ts @@ -0,0 +1,150 @@ +import { + AuthenticationInstruction, + createVirtualMachineBch2026, + decodeAuthenticationInstructions, +} from '@bitauth/libauth'; +import { optimisationReplacements } from '../src/optimisations.js'; +import { asmToBytecode } from '../src/script.js'; + +// These optimisations remove the VM-number check of OP_NOT, so they are only equivalent when the original succeeds +const NUMBER_CHECK_REMOVING_OPTIMISATIONS = [ + 'OP_NOT OP_IF', + 'OP_NOT OP_NOTIF', + 'OP_NOT OP_NOT OP_UNTIL', + 'OP_NOT OP_NOT OP_VERIFY', +]; + +const TRIALS_PER_OPTIMISATION = 100; +const STACK_DEPTH = 20; +const ALTERNATE_STACK_DEPTH = 3; + +const vm = createVirtualMachineBch2026(); +const initialState = vm.stateInitialize({ + inputIndex: 0, + sourceOutputs: [{ lockingBytecode: Uint8Array.of(0x51), valueSatoshis: 10_000n }], + transaction: { + version: 2, + locktime: 0, + inputs: [{ + outpointIndex: 0, + outpointTransactionHash: new Uint8Array(32), + sequenceNumber: 0, + // A large unlocking bytecode raises the operation cost budget so it never limits the fuzzed scripts + unlockingBytecode: new Uint8Array(10_000), + }], + outputs: [{ lockingBytecode: Uint8Array.of(0x51), valueSatoshis: 1_000n }], + }, +}); + +describe('Optimisations', () => { + optimisationReplacements.forEach(([pattern, replacement]) => { + it(`${pattern} => ${replacement || '(nothing)'} should be equivalent in the VM`, () => { + const random = createRandom(hashString(pattern)); + const patternInstructions = toInstructions(pattern); + const replacementInstructions = toInstructions(replacement); + const onlyCheckSuccesses = NUMBER_CHECK_REMOVING_OPTIMISATIONS.includes(pattern); + + for (let i = 0; i < TRIALS_PER_OPTIMISATION; i += 1) { + const stack = createStack(random, STACK_DEPTH, i); + const alternateStack = createStack(random, ALTERNATE_STACK_DEPTH, i); + + const expected = evaluate(patternInstructions, stack, alternateStack); + if (onlyCheckSuccesses && expected.error) continue; + + const actual = evaluate(replacementInstructions, stack, alternateStack); + + // Comparing with toEqual() directly is too slow for the large stack items, so we only use it for the error message + if (!isSameEvaluationResult(actual, expected)) { + expect({ actual, trial: i }).toEqual({ expected, trial: i }); + } + } + }); + }); +}); + +// Control flow opcodes need to be balanced, so we wrap the pattern in a loop / branch if needed +function toInstructions(asm: string): AuthenticationInstruction[] { + const tokens = asm.split(' '); + let wrappedAsm = asm; + if (tokens.includes('OP_UNTIL')) wrappedAsm = `OP_BEGIN ${wrappedAsm}`; + if (tokens.includes('OP_IF') || tokens.includes('OP_NOTIF')) wrappedAsm = `${wrappedAsm} OP_1 OP_ELSE OP_2 OP_ENDIF`; + return decodeAuthenticationInstructions(asmToBytecode(wrappedAsm)); +} + +interface EvaluationResult { + error: boolean; + stack: Uint8Array[]; + alternateStack: Uint8Array[]; +} + +function evaluate( + instructions: AuthenticationInstruction[], + stack: Uint8Array[], + alternateStack: Uint8Array[], +): EvaluationResult { + const state = vm.stateEvaluate({ + ...vm.stateClone(initialState), + instructions, + stack: [...stack], + alternateStack: [...alternateStack], + }); + + // Error messages can differ between equivalent scripts, so we only compare whether an error occurred + if (state.error !== undefined) return { error: true, stack: [], alternateStack: [] }; + return { error: false, stack: state.stack, alternateStack: state.alternateStack }; +} + +function isSameEvaluationResult(a: EvaluationResult, b: EvaluationResult): boolean { + return a.error === b.error && isSameStack(a.stack, b.stack) && isSameStack(a.alternateStack, b.alternateStack); +} + +function isSameStack(a: Uint8Array[], b: Uint8Array[]): boolean { + return a.length === b.length && a.every((item, i) => Buffer.from(item).equals(b[i])); +} + +type Random = (max: number) => number; + +// Stack items that exercise the edge cases of the VM's number, boolean and size checks +const STACK_ITEM_GENERATORS: ((random: Random) => Uint8Array)[] = [ + () => Uint8Array.of(), + (random) => Uint8Array.of(random(16) + 1), + (random) => Uint8Array.of(random(127) + 1), + () => Uint8Array.of(0x81), + () => Uint8Array.of(0x00), + () => Uint8Array.of(0x80), + () => Uint8Array.of(0x00, 0x80), + () => Uint8Array.of(0x01, 0x00), + (random) => createRandomBytes(random, random(8) + 1), + (random) => createRandomBytes(random, random(40)), + // Two of these exceed the maximum stack item size when concatenated + (random) => new Uint8Array(5_001 + random(100)), +]; + +// The first trials fill the entire stack with a single kind of item, so interactions between items of the same kind +// (e.g. concatenating two large items) are always covered. Later trials mix random kinds of items. +function createStack(random: Random, depth: number, trial: number): Uint8Array[] { + const pickGenerator = (): ((random: Random) => Uint8Array) => ( + STACK_ITEM_GENERATORS[trial < STACK_ITEM_GENERATORS.length ? trial : random(STACK_ITEM_GENERATORS.length)] + ); + + return Array.from({ length: depth }, () => pickGenerator()(random)); +} + +function createRandomBytes(random: Random, length: number): Uint8Array { + return Uint8Array.from({ length }, () => random(256)); +} + +// Seeded PRNG (mulberry32), so that failures are reproducible +function createRandom(seed: number): Random { + let state = seed; + return (max: number) => { + state = (state + 0x6d2b79f5) | 0; + let t = Math.imul(state ^ (state >>> 15), 1 | state); + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; + return Math.floor((((t ^ (t >>> 14)) >>> 0) / 4294967296) * max); + }; +} + +function hashString(str: string): number { + return [...str].reduce((hash, char) => Math.imul(hash, 31) + char.charCodeAt(0), 0); +} diff --git a/packages/utils/test/script.test.ts b/packages/utils/test/script.test.ts index fa7ae8f4a..f5946d4df 100644 --- a/packages/utils/test/script.test.ts +++ b/packages/utils/test/script.test.ts @@ -7,9 +7,13 @@ import { calculateBytesize, countOpcodes, encodeNullDataScript, + optimiseBytecode, + PositionHint, scriptToAsm, scriptToBytecode, + SingleLocationData, } from '../src/index.js'; +import { optimisationReplacements } from '../src/optimisations.js'; import { fixtures } from './script.fixture.js'; describe('script utils', () => { @@ -101,6 +105,69 @@ describe('script utils', () => { describe.skip('TODO: generateContractBytecodeScript()', () => { }); - describe.skip('TODO: optimiseBytecode()', () => { + describe('optimiseBytecode()', () => { + const location: SingleLocationData = { + location: { start: { line: 1, column: 0 }, end: { line: 1, column: 0 } }, + positionHint: PositionHint.START, + }; + + it('should match a token-based reference implementation on random scripts', () => { + let seed = 1; + const random = (max: number): number => { + seed = (seed * 16807) % 2147483647; + return seed % max; + }; + + for (let i = 0; i < 500; i += 1) { + // Scripts are built from rule patterns and loose tokens, so matches are frequent, adjacent and cascading + const segments = Array.from({ length: 12 }, () => { + if (random(2) === 0) return optimisationReplacements[random(optimisationReplacements.length)][0]; + return REFERENCE_TOKENS[random(REFERENCE_TOKENS.length)]; + }); + const script = asmToScript(segments.join(' ')); + + const result = optimiseBytecode(script, script.map(() => location), [], [], [], [], 0); + + expect(scriptToAsm(result.script)).toEqual(referenceOptimise(scriptToAsm(script))); + expect(result.locationData).toHaveLength(result.script.length); + } + }); }); }); + +const REFERENCE_TOKENS = [ + ...new Set(optimisationReplacements.flatMap(([pattern, replacement]) => `${pattern} ${replacement}`.split(/\s+/))), + 'beef', + '0102', +].filter((token) => token !== ''); + +// Applies every optimisation left-to-right without overlap (like a global regex replace), until a fixed point +function referenceOptimise(asm: string): string { + let tokens = asm.split(' ').filter((token) => token !== ''); + let previous: string; + + do { + previous = tokens.join(' '); + for (const [pattern, replacement] of optimisationReplacements) { + tokens = replaceTokens(tokens, pattern.split(' '), replacement === '' ? [] : replacement.split(' ')); + } + } while (tokens.join(' ') !== previous); + + return previous; +} + +function replaceTokens(tokens: string[], pattern: string[], replacement: string[]): string[] { + const result: string[] = []; + + for (let i = 0; i < tokens.length;) { + if (pattern.every((token, j) => tokens[i + j] === token)) { + result.push(...replacement); + i += pattern.length; + } else { + result.push(tokens[i]); + i += 1; + } + } + + return result; +} diff --git a/website/docs/releases/release-notes.md b/website/docs/releases/release-notes.md index 9b6f938e6..d819609ee 100644 --- a/website/docs/releases/release-notes.md +++ b/website/docs/releases/release-notes.md @@ -16,7 +16,9 @@ This release contains several breaking changes, please refer to the [migration n - :hammer_and_wrench: Unused variables that are not marked `unused` now produce a compiler warning instead of a compilation error. Warnings are printed with `console.warn`, or passed to the new `warningListener` compiler option. - :hammer_and_wrench: Add a compiler warning for values assigned to a variable that are never read afterwards. - :bug: Fix bug where date literal parsing was different per locale, it now uses UTC. +- :bug: Remove the `OP_CAT OP_DROP` optimisation, because it removed the maximum size check of an unused concatenation. - :racehorse: Add new `OP_SWAP OP_MUL`, `OP_NOT OP_NOT` and `TO_ALTSTACK OP_FROMALTSTACK` optimisations. +- :racehorse: Add new optimisations for loop counter updates, reassignments inside loops and order-independent operations (`OP_BOOLAND`, `OP_BOOLOR`, `OP_MIN`, `OP_MAX`). - :racehorse: Greatly improve compiler speed for very large contracts. #### CashScript SDK From 74468666686835765d7a0dae9dae1cea83508af7 Mon Sep 17 00:00:00 2001 From: Rosco Kalis Date: Fri, 25 Sep 2026 13:05:17 +0200 Subject: [PATCH 2/3] feat: keep the OP_CAT OP_DROP optimisation It only removes OP_CAT's maximum stack item size check for concatenations whose result is never used, so it is kept and documented like the OP_NOT optimisations, and only checked where the original succeeds in the VM equivalence test. Co-Authored-By: Claude Opus 5.5 --- packages/utils/src/optimisations.ts | 3 ++- packages/utils/test/optimisations.test.ts | 8 +++++--- website/docs/releases/release-notes.md | 1 - 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/packages/utils/src/optimisations.ts b/packages/utils/src/optimisations.ts index e6ac79bbb..32bd65567 100644 --- a/packages/utils/src/optimisations.ts +++ b/packages/utils/src/optimisations.ts @@ -73,7 +73,8 @@ export const optimisationReplacements = [ // Random optimisations (don't know what I'm targeting with this) ['OP_2DUP OP_DROP', 'OP_OVER'], ['OP_2DUP OP_NIP', 'OP_DUP'], - // Note: OP_CAT OP_DROP => OP_2DROP is not safe, since it removes OP_CAT's maximum element size check + // Note that this removes OP_CAT's maximum stack item size check, which only matters for unused concatenations + ['OP_CAT OP_DROP', 'OP_2DROP'], ['OP_NIP OP_DROP', 'OP_2DROP'], // Far-fetched stuff diff --git a/packages/utils/test/optimisations.test.ts b/packages/utils/test/optimisations.test.ts index 3a3dc1731..a73848fe5 100644 --- a/packages/utils/test/optimisations.test.ts +++ b/packages/utils/test/optimisations.test.ts @@ -6,12 +6,14 @@ import { import { optimisationReplacements } from '../src/optimisations.js'; import { asmToBytecode } from '../src/script.js'; -// These optimisations remove the VM-number check of OP_NOT, so they are only equivalent when the original succeeds -const NUMBER_CHECK_REMOVING_OPTIMISATIONS = [ +// These optimisations remove a check, so they are only equivalent when the original succeeds: the VM-number check of +// OP_NOT, and the maximum stack item size check of an unused OP_CAT result +const CHECK_REMOVING_OPTIMISATIONS = [ 'OP_NOT OP_IF', 'OP_NOT OP_NOTIF', 'OP_NOT OP_NOT OP_UNTIL', 'OP_NOT OP_NOT OP_VERIFY', + 'OP_CAT OP_DROP', ]; const TRIALS_PER_OPTIMISATION = 100; @@ -42,7 +44,7 @@ describe('Optimisations', () => { const random = createRandom(hashString(pattern)); const patternInstructions = toInstructions(pattern); const replacementInstructions = toInstructions(replacement); - const onlyCheckSuccesses = NUMBER_CHECK_REMOVING_OPTIMISATIONS.includes(pattern); + const onlyCheckSuccesses = CHECK_REMOVING_OPTIMISATIONS.includes(pattern); for (let i = 0; i < TRIALS_PER_OPTIMISATION; i += 1) { const stack = createStack(random, STACK_DEPTH, i); diff --git a/website/docs/releases/release-notes.md b/website/docs/releases/release-notes.md index d819609ee..8ab42ab3b 100644 --- a/website/docs/releases/release-notes.md +++ b/website/docs/releases/release-notes.md @@ -16,7 +16,6 @@ This release contains several breaking changes, please refer to the [migration n - :hammer_and_wrench: Unused variables that are not marked `unused` now produce a compiler warning instead of a compilation error. Warnings are printed with `console.warn`, or passed to the new `warningListener` compiler option. - :hammer_and_wrench: Add a compiler warning for values assigned to a variable that are never read afterwards. - :bug: Fix bug where date literal parsing was different per locale, it now uses UTC. -- :bug: Remove the `OP_CAT OP_DROP` optimisation, because it removed the maximum size check of an unused concatenation. - :racehorse: Add new `OP_SWAP OP_MUL`, `OP_NOT OP_NOT` and `TO_ALTSTACK OP_FROMALTSTACK` optimisations. - :racehorse: Add new optimisations for loop counter updates, reassignments inside loops and order-independent operations (`OP_BOOLAND`, `OP_BOOLOR`, `OP_MIN`, `OP_MAX`). - :racehorse: Greatly improve compiler speed for very large contracts. From c148ab5f8eb9c2be81a2be55ffbfde45fbcca51d Mon Sep 17 00:00:00 2001 From: Rosco Kalis Date: Fri, 25 Sep 2026 16:36:21 +0200 Subject: [PATCH 3/3] test: remove the optimisation equivalence and reference tests Co-Authored-By: Claude Opus 5.5 --- .../test/manual-optimisation-proofs.test.ts | 57 +++++++ packages/utils/test/optimisations.test.ts | 152 ------------------ packages/utils/test/script.test.ts | 69 +------- 3 files changed, 58 insertions(+), 220 deletions(-) create mode 100644 packages/utils/test/manual-optimisation-proofs.test.ts delete mode 100644 packages/utils/test/optimisations.test.ts diff --git a/packages/utils/test/manual-optimisation-proofs.test.ts b/packages/utils/test/manual-optimisation-proofs.test.ts new file mode 100644 index 000000000..d2a50d131 --- /dev/null +++ b/packages/utils/test/manual-optimisation-proofs.test.ts @@ -0,0 +1,57 @@ +describe('Manual Optimisation Proofs', () => { + it.todo('Properly implement automated tests'); + // <1> <2> OP_GREATERTHAN OP_NOT + // <1> <2> OP_LESSTHANOREQUAL + // OP_EQUALVERIFY + + // <2> <1> OP_GREATERTHAN OP_NOT + // <2> <1> OP_LESSTHANOREQUAL + // OP_EQUALVERIFY + + // <1> <1> OP_GREATERTHAN OP_NOT + // <1> <1> OP_LESSTHANOREQUAL + // OP_EQUALVERIFY + + + + + // <1> <2> OP_LESSTHAN OP_NOT + // <1> <2> OP_GREATERTHANOREQUAL + // OP_EQUALVERIFY + + // <2> <1> OP_LESSTHAN OP_NOT + // <2> <1> OP_GREATERTHANOREQUAL + // OP_EQUALVERIFY + + // <1> <1> OP_LESSTHAN OP_NOT + // <1> <1> OP_GREATERTHANOREQUAL + // OP_EQUALVERIFY + + + + // <1> <2> OP_LESSTHANOREQUAL OP_NOT + // <1> <2> OP_GREATERTHAN + // OP_EQUALVERIFY + + // <2> <1> OP_LESSTHANOREQUAL OP_NOT + // <2> <1> OP_GREATERTHAN + // OP_EQUALVERIFY + + // <1> <1> OP_LESSTHANOREQUAL OP_NOT + // <1> <1> OP_GREATERTHAN + // OP_EQUALVERIFY + + + + // <1> <2> OP_GREATERTHANOREQUAL OP_NOT + // <1> <2> OP_LESSTHAN + // OP_EQUALVERIFY + + // <2> <1> OP_GREATERTHANOREQUAL OP_NOT + // <2> <1> OP_LESSTHAN + // OP_EQUALVERIFY + + // <1> <1> OP_GREATERTHANOREQUAL OP_NOT + // <1> <1> OP_LESSTHAN + // OP_EQUALVERIFY +}); diff --git a/packages/utils/test/optimisations.test.ts b/packages/utils/test/optimisations.test.ts deleted file mode 100644 index a73848fe5..000000000 --- a/packages/utils/test/optimisations.test.ts +++ /dev/null @@ -1,152 +0,0 @@ -import { - AuthenticationInstruction, - createVirtualMachineBch2026, - decodeAuthenticationInstructions, -} from '@bitauth/libauth'; -import { optimisationReplacements } from '../src/optimisations.js'; -import { asmToBytecode } from '../src/script.js'; - -// These optimisations remove a check, so they are only equivalent when the original succeeds: the VM-number check of -// OP_NOT, and the maximum stack item size check of an unused OP_CAT result -const CHECK_REMOVING_OPTIMISATIONS = [ - 'OP_NOT OP_IF', - 'OP_NOT OP_NOTIF', - 'OP_NOT OP_NOT OP_UNTIL', - 'OP_NOT OP_NOT OP_VERIFY', - 'OP_CAT OP_DROP', -]; - -const TRIALS_PER_OPTIMISATION = 100; -const STACK_DEPTH = 20; -const ALTERNATE_STACK_DEPTH = 3; - -const vm = createVirtualMachineBch2026(); -const initialState = vm.stateInitialize({ - inputIndex: 0, - sourceOutputs: [{ lockingBytecode: Uint8Array.of(0x51), valueSatoshis: 10_000n }], - transaction: { - version: 2, - locktime: 0, - inputs: [{ - outpointIndex: 0, - outpointTransactionHash: new Uint8Array(32), - sequenceNumber: 0, - // A large unlocking bytecode raises the operation cost budget so it never limits the fuzzed scripts - unlockingBytecode: new Uint8Array(10_000), - }], - outputs: [{ lockingBytecode: Uint8Array.of(0x51), valueSatoshis: 1_000n }], - }, -}); - -describe('Optimisations', () => { - optimisationReplacements.forEach(([pattern, replacement]) => { - it(`${pattern} => ${replacement || '(nothing)'} should be equivalent in the VM`, () => { - const random = createRandom(hashString(pattern)); - const patternInstructions = toInstructions(pattern); - const replacementInstructions = toInstructions(replacement); - const onlyCheckSuccesses = CHECK_REMOVING_OPTIMISATIONS.includes(pattern); - - for (let i = 0; i < TRIALS_PER_OPTIMISATION; i += 1) { - const stack = createStack(random, STACK_DEPTH, i); - const alternateStack = createStack(random, ALTERNATE_STACK_DEPTH, i); - - const expected = evaluate(patternInstructions, stack, alternateStack); - if (onlyCheckSuccesses && expected.error) continue; - - const actual = evaluate(replacementInstructions, stack, alternateStack); - - // Comparing with toEqual() directly is too slow for the large stack items, so we only use it for the error message - if (!isSameEvaluationResult(actual, expected)) { - expect({ actual, trial: i }).toEqual({ expected, trial: i }); - } - } - }); - }); -}); - -// Control flow opcodes need to be balanced, so we wrap the pattern in a loop / branch if needed -function toInstructions(asm: string): AuthenticationInstruction[] { - const tokens = asm.split(' '); - let wrappedAsm = asm; - if (tokens.includes('OP_UNTIL')) wrappedAsm = `OP_BEGIN ${wrappedAsm}`; - if (tokens.includes('OP_IF') || tokens.includes('OP_NOTIF')) wrappedAsm = `${wrappedAsm} OP_1 OP_ELSE OP_2 OP_ENDIF`; - return decodeAuthenticationInstructions(asmToBytecode(wrappedAsm)); -} - -interface EvaluationResult { - error: boolean; - stack: Uint8Array[]; - alternateStack: Uint8Array[]; -} - -function evaluate( - instructions: AuthenticationInstruction[], - stack: Uint8Array[], - alternateStack: Uint8Array[], -): EvaluationResult { - const state = vm.stateEvaluate({ - ...vm.stateClone(initialState), - instructions, - stack: [...stack], - alternateStack: [...alternateStack], - }); - - // Error messages can differ between equivalent scripts, so we only compare whether an error occurred - if (state.error !== undefined) return { error: true, stack: [], alternateStack: [] }; - return { error: false, stack: state.stack, alternateStack: state.alternateStack }; -} - -function isSameEvaluationResult(a: EvaluationResult, b: EvaluationResult): boolean { - return a.error === b.error && isSameStack(a.stack, b.stack) && isSameStack(a.alternateStack, b.alternateStack); -} - -function isSameStack(a: Uint8Array[], b: Uint8Array[]): boolean { - return a.length === b.length && a.every((item, i) => Buffer.from(item).equals(b[i])); -} - -type Random = (max: number) => number; - -// Stack items that exercise the edge cases of the VM's number, boolean and size checks -const STACK_ITEM_GENERATORS: ((random: Random) => Uint8Array)[] = [ - () => Uint8Array.of(), - (random) => Uint8Array.of(random(16) + 1), - (random) => Uint8Array.of(random(127) + 1), - () => Uint8Array.of(0x81), - () => Uint8Array.of(0x00), - () => Uint8Array.of(0x80), - () => Uint8Array.of(0x00, 0x80), - () => Uint8Array.of(0x01, 0x00), - (random) => createRandomBytes(random, random(8) + 1), - (random) => createRandomBytes(random, random(40)), - // Two of these exceed the maximum stack item size when concatenated - (random) => new Uint8Array(5_001 + random(100)), -]; - -// The first trials fill the entire stack with a single kind of item, so interactions between items of the same kind -// (e.g. concatenating two large items) are always covered. Later trials mix random kinds of items. -function createStack(random: Random, depth: number, trial: number): Uint8Array[] { - const pickGenerator = (): ((random: Random) => Uint8Array) => ( - STACK_ITEM_GENERATORS[trial < STACK_ITEM_GENERATORS.length ? trial : random(STACK_ITEM_GENERATORS.length)] - ); - - return Array.from({ length: depth }, () => pickGenerator()(random)); -} - -function createRandomBytes(random: Random, length: number): Uint8Array { - return Uint8Array.from({ length }, () => random(256)); -} - -// Seeded PRNG (mulberry32), so that failures are reproducible -function createRandom(seed: number): Random { - let state = seed; - return (max: number) => { - state = (state + 0x6d2b79f5) | 0; - let t = Math.imul(state ^ (state >>> 15), 1 | state); - t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; - return Math.floor((((t ^ (t >>> 14)) >>> 0) / 4294967296) * max); - }; -} - -function hashString(str: string): number { - return [...str].reduce((hash, char) => Math.imul(hash, 31) + char.charCodeAt(0), 0); -} diff --git a/packages/utils/test/script.test.ts b/packages/utils/test/script.test.ts index f5946d4df..fa7ae8f4a 100644 --- a/packages/utils/test/script.test.ts +++ b/packages/utils/test/script.test.ts @@ -7,13 +7,9 @@ import { calculateBytesize, countOpcodes, encodeNullDataScript, - optimiseBytecode, - PositionHint, scriptToAsm, scriptToBytecode, - SingleLocationData, } from '../src/index.js'; -import { optimisationReplacements } from '../src/optimisations.js'; import { fixtures } from './script.fixture.js'; describe('script utils', () => { @@ -105,69 +101,6 @@ describe('script utils', () => { describe.skip('TODO: generateContractBytecodeScript()', () => { }); - describe('optimiseBytecode()', () => { - const location: SingleLocationData = { - location: { start: { line: 1, column: 0 }, end: { line: 1, column: 0 } }, - positionHint: PositionHint.START, - }; - - it('should match a token-based reference implementation on random scripts', () => { - let seed = 1; - const random = (max: number): number => { - seed = (seed * 16807) % 2147483647; - return seed % max; - }; - - for (let i = 0; i < 500; i += 1) { - // Scripts are built from rule patterns and loose tokens, so matches are frequent, adjacent and cascading - const segments = Array.from({ length: 12 }, () => { - if (random(2) === 0) return optimisationReplacements[random(optimisationReplacements.length)][0]; - return REFERENCE_TOKENS[random(REFERENCE_TOKENS.length)]; - }); - const script = asmToScript(segments.join(' ')); - - const result = optimiseBytecode(script, script.map(() => location), [], [], [], [], 0); - - expect(scriptToAsm(result.script)).toEqual(referenceOptimise(scriptToAsm(script))); - expect(result.locationData).toHaveLength(result.script.length); - } - }); + describe.skip('TODO: optimiseBytecode()', () => { }); }); - -const REFERENCE_TOKENS = [ - ...new Set(optimisationReplacements.flatMap(([pattern, replacement]) => `${pattern} ${replacement}`.split(/\s+/))), - 'beef', - '0102', -].filter((token) => token !== ''); - -// Applies every optimisation left-to-right without overlap (like a global regex replace), until a fixed point -function referenceOptimise(asm: string): string { - let tokens = asm.split(' ').filter((token) => token !== ''); - let previous: string; - - do { - previous = tokens.join(' '); - for (const [pattern, replacement] of optimisationReplacements) { - tokens = replaceTokens(tokens, pattern.split(' '), replacement === '' ? [] : replacement.split(' ')); - } - } while (tokens.join(' ') !== previous); - - return previous; -} - -function replaceTokens(tokens: string[], pattern: string[], replacement: string[]): string[] { - const result: string[] = []; - - for (let i = 0; i < tokens.length;) { - if (pattern.every((token, j) => tokens[i + j] === token)) { - result.push(...replacement); - i += pattern.length; - } else { - result.push(tokens[i]); - i += 1; - } - } - - return result; -}