From 409c8aa4cebd7cb9ac29dc1434ab5091255adef9 Mon Sep 17 00:00:00 2001 From: Sean Bowe Date: Fri, 30 Sep 2022 09:18:47 -0600 Subject: [PATCH] Create new `zcash_script` crate that will contain logic for verifying Zcash transparent scripts. --- Cargo.toml | 1 + zcash_script/Cargo.toml | 16 ++ zcash_script/LICENSE-APACHE | 202 ++++++++++++++++ zcash_script/LICENSE-MIT | 21 ++ zcash_script/README.md | 20 ++ zcash_script/src/lib.rs | 462 ++++++++++++++++++++++++++++++++++++ zcash_script/src/opcodes.rs | 244 +++++++++++++++++++ 7 files changed, 966 insertions(+) create mode 100644 zcash_script/Cargo.toml create mode 100644 zcash_script/LICENSE-APACHE create mode 100644 zcash_script/LICENSE-MIT create mode 100644 zcash_script/README.md create mode 100644 zcash_script/src/lib.rs create mode 100644 zcash_script/src/opcodes.rs diff --git a/Cargo.toml b/Cargo.toml index 0ddd568e43..88314172a8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,6 +11,7 @@ members = [ "zcash_history", "zcash_primitives", "zcash_proofs", + "zcash_script", ] [profile.release] diff --git a/zcash_script/Cargo.toml b/zcash_script/Cargo.toml new file mode 100644 index 0000000000..ee84f57e04 --- /dev/null +++ b/zcash_script/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "zcash_script" +description = "" +version = "0.0.0" +authors = [ + "Sean Bowe ", +] +homepage = "https://github.com/zcash/librustzcash" +repository = "https://github.com/zcash/librustzcash" +readme = "README.md" +license = "MIT OR Apache-2.0" +edition = "2018" +categories = ["cryptography::cryptocurrencies"] +publish = false + +[dependencies] diff --git a/zcash_script/LICENSE-APACHE b/zcash_script/LICENSE-APACHE new file mode 100644 index 0000000000..1e5006dc14 --- /dev/null +++ b/zcash_script/LICENSE-APACHE @@ -0,0 +1,202 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + diff --git a/zcash_script/LICENSE-MIT b/zcash_script/LICENSE-MIT new file mode 100644 index 0000000000..1581c90d16 --- /dev/null +++ b/zcash_script/LICENSE-MIT @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2017-2019 Electric Coin Company + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/zcash_script/README.md b/zcash_script/README.md new file mode 100644 index 0000000000..e32faa53f6 --- /dev/null +++ b/zcash_script/README.md @@ -0,0 +1,20 @@ +# zcash_script + +This is a WIP library for verifying Zcash scripts in transparent transactions. + +## License + +Licensed under either of + + * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or + http://www.apache.org/licenses/LICENSE-2.0) + * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) + +at your option. + +### Contribution + +Unless you explicitly state otherwise, any contribution intentionally +submitted for inclusion in the work by you, as defined in the Apache-2.0 +license, shall be dual licensed as above, without any additional terms or +conditions. diff --git a/zcash_script/src/lib.rs b/zcash_script/src/lib.rs new file mode 100644 index 0000000000..6b1ea011bb --- /dev/null +++ b/zcash_script/src/lib.rs @@ -0,0 +1,462 @@ +pub mod opcodes; +use opcodes::*; + +/// Maximum allowed size of data (in bytes) that can be pushed to the stack. +pub const MAX_SCRIPT_ELEMENT_SIZE: usize = 520; + +/// Maximum allowed script length in bytes. +pub const MAX_SCRIPT_SIZE: usize = 10000; + +// Threshold for nLockTime: below this value it is interpreted as block number, +// otherwise as UNIX timestamp. +pub const LOCKTIME_THRESHOLD: usize = 500000000; // Tue Nov 5 00:53:20 1985 UTC + +#[derive(Copy, Clone, PartialEq, Eq, Debug)] +pub enum ScriptError { + ReadError { + expected_bytes: usize, + available_bytes: usize, + }, + InvalidOpcode, + PushSize, + OpCount, + DisabledOpcode, + ScriptSize, + MinimalData, + StackSize, + UnbalancedConditional, + UpgradableNops, + InvalidStackOperation, + OpReturn, +} + +pub struct ExecutionOptions { + pub require_minimal_pushes: bool, + pub enable_checklocktimeverify: bool, + pub discourage_upgradable_nops: bool, +} + +#[derive(Clone)] +pub struct Script<'a>(pub &'a [u8]); + +impl<'a> Script<'a> { + /// Returns true iff this script is P2PKH. + pub fn is_p2pkh(&self) -> bool { + (self.0.len() == 25) + && (self.0[0] == Opcode::OP_DUP as u8) + && (self.0[1] == Opcode::OP_HASH160 as u8) + && (self.0[2] == 0x14) + && (self.0[23] == Opcode::OP_EQUALVERIFY as u8) + && (self.0[24] == Opcode::OP_CHECKSIG as u8) + } + + /// Returns true iff this script is P2SH. + pub fn is_p2sh(&self) -> bool { + (self.0.len() == 23) + && (self.0[0] == Opcode::OP_HASH160 as u8) + && (self.0[1] == 0x14) + && (self.0[22] == Opcode::OP_EQUAL as u8) + } + + pub fn evaluate( + &self, + stack: &mut Vec>, + options: &ExecutionOptions, + ) -> Result<(), ScriptError> { + // There's a limit on how large scripts can be. + if self.0.len() > MAX_SCRIPT_SIZE { + return Err(ScriptError::ScriptSize); + } + + let mut script = (*self).clone(); + let mut push_data = vec![]; + + // We keep track of how many operations have executed so far to prevent + // expensive-to-verify scripts + let mut op_count = 0; + + // This keeps track of the conditional flags at each nesting level + // during execution. If we're in a branch of execution where *any* + // of these conditionals are false, we ignore opcodes unless those + // opcodes direct control flow (OP_IF, OP_ELSE, etc.). + let mut exec: Vec = vec![]; + + let mut alt_stack: Vec> = vec![]; + + // Main execution loop + while !script.0.is_empty() { + // Are we in an executing branch of the script? + let executing = exec.iter().all(|value| *value); + + // Consume an opcode + let operation = parse_opcode(&mut script.0, Some(&mut push_data))?; + + match operation { + Operation::PushBytes(raw_opcode) => { + // There's a limit to the size of the values we'll put on + // the stack. + if push_data.len() > MAX_SCRIPT_ELEMENT_SIZE { + return Err(ScriptError::PushSize); + } + + if executing { + // Data is being pushed to the stack here; we may need to check + // that the minimal script size was used to do so if our caller + // requires it. + if options.require_minimal_pushes + && !check_minimal_push(&push_data, raw_opcode) + { + return Err(ScriptError::MinimalData); + } + + stack.push(push_data.clone()); + } + } + Operation::Constant(value) => { + todo!() + } + + // Invalid and disabled opcodes do technically contribute to + // op_count, but they always result in a failed script execution + // anyway. + Operation::Invalid => return Err(ScriptError::InvalidOpcode), + Operation::Disabled => return Err(ScriptError::DisabledOpcode), + + Operation::Opcode(opcode) => { + // There's a limit on how many operations can execute in a + // script. We consider opcodes beyond OP_16 to be "actual" + // opcodes as ones below that just involve data pushes. All + // opcodes defined by the Opcode enum qualify except for + // OP_RESERVED, which is not beyond OP_16. + // + // Note: operations even if they are not executed but are + // still present in the script count toward this count. + if opcode != Opcode::OP_RESERVED { + op_count += 1; + if op_count > 201 { + return Err(ScriptError::OpCount); + } + } + + if executing || opcode.is_control_flow_opcode() { + match opcode { + Opcode::OP_RESERVED + | Opcode::OP_VER + | Opcode::OP_RESERVED1 + | Opcode::OP_RESERVED2 => { + // These are considered "invalid" opcodes but + // only inside of *executing* OP_IF branches of + // the script. + return Err(ScriptError::InvalidOpcode); + } + Opcode::OP_NOP => { + // Do nothing. + } + Opcode::OP_NOP1 + | Opcode::OP_NOP3 + | Opcode::OP_NOP4 + | Opcode::OP_NOP5 + | Opcode::OP_NOP6 + | Opcode::OP_NOP7 + | Opcode::OP_NOP8 + | Opcode::OP_NOP9 + | Opcode::OP_NOP10 => { + // Do nothing, though if the caller wants to + // prevent people from using these NOPs (as part + // of a standard tx rule, for example) they can + // enable `discourage_upgradable_nops` to turn + // these opcodes into errors. + if options.discourage_upgradable_nops { + return Err(ScriptError::UpgradableNops); + } + } + Opcode::OP_CHECKLOCKTIMEVERIFY => { + // This was originally OP_NOP2 but has been repurposed + // for OP_CHECKLOCKTIMEVERIFY. So, we should act based + // on whether or not CLTV has been activated in a soft + // fork. + if !options.enable_checklocktimeverify { + if options.discourage_upgradable_nops { + return Err(ScriptError::UpgradableNops); + } + } else { + todo!() + } + } + Opcode::OP_IF | Opcode::OP_NOTIF => { + let mut value = false; + if executing { + if stack.is_empty() { + return Err(ScriptError::UnbalancedConditional); + } + todo!() + } + exec.push(value); + } + Opcode::OP_ELSE => { + if exec.is_empty() { + return Err(ScriptError::UnbalancedConditional); + } + + exec.last_mut().map(|last| *last = !*last); + } + Opcode::OP_ENDIF => { + if exec.is_empty() { + return Err(ScriptError::UnbalancedConditional); + } + + exec.pop(); + } + Opcode::OP_VERIFY => { + if stack.is_empty() { + return Err(ScriptError::InvalidStackOperation); + } + + let value = stack.pop().unwrap(); + + todo!() + } + Opcode::OP_RETURN => return Err(ScriptError::OpReturn), + Opcode::OP_TOALTSTACK => { + if stack.is_empty() { + return Err(ScriptError::InvalidStackOperation); + } + + alt_stack.push(stack.pop().unwrap()); + } + Opcode::OP_FROMALTSTACK => { + if alt_stack.is_empty() { + return Err(ScriptError::InvalidStackOperation); + } + + stack.push(alt_stack.pop().unwrap()); + } + Opcode::OP_2DROP => { + if stack.len() < 2 { + return Err(ScriptError::InvalidStackOperation); + } + + stack.pop(); + stack.pop(); + } + Opcode::OP_2DUP => { + if stack.len() < 2 { + return Err(ScriptError::InvalidStackOperation); + } + + let b = stack.pop().unwrap(); + let a = stack.pop().unwrap(); + stack.push(a.clone()); + stack.push(b.clone()); + stack.push(a); + stack.push(b); + } + Opcode::OP_3DUP => { + if stack.len() < 3 { + return Err(ScriptError::InvalidStackOperation); + } + + let c = stack.pop().unwrap(); + let b = stack.pop().unwrap(); + let a = stack.pop().unwrap(); + stack.push(a.clone()); + stack.push(b.clone()); + stack.push(c.clone()); + stack.push(a); + stack.push(b); + stack.push(c); + } + Opcode::OP_2OVER => { + if stack.len() < 4 { + return Err(ScriptError::InvalidStackOperation); + } + + let d = stack.pop().unwrap(); + let c = stack.pop().unwrap(); + let b = stack.pop().unwrap(); + let a = stack.pop().unwrap(); + stack.push(a.clone()); + stack.push(b.clone()); + stack.push(c); + stack.push(d); + stack.push(a); + stack.push(b); + } + Opcode::OP_2ROT => { + if stack.len() < 6 { + return Err(ScriptError::InvalidStackOperation); + } + + let f = stack.pop().unwrap(); + let e = stack.pop().unwrap(); + let d = stack.pop().unwrap(); + let c = stack.pop().unwrap(); + let b = stack.pop().unwrap(); + let a = stack.pop().unwrap(); + stack.push(c); + stack.push(d); + stack.push(e); + stack.push(f); + stack.push(a); + stack.push(b); + } + Opcode::OP_2SWAP => { + if stack.len() < 4 { + return Err(ScriptError::InvalidStackOperation); + } + + let d = stack.pop().unwrap(); + let c = stack.pop().unwrap(); + let b = stack.pop().unwrap(); + let a = stack.pop().unwrap(); + stack.push(c); + stack.push(d); + stack.push(a); + stack.push(b); + } + Opcode::OP_IFDUP => { + if stack.is_empty() { + return Err(ScriptError::InvalidStackOperation); + } + + todo!() + } + Opcode::OP_DEPTH => { + todo!() + } + Opcode::OP_DROP => { + if stack.is_empty() { + return Err(ScriptError::InvalidStackOperation); + } + + stack.pop(); + } + Opcode::OP_DUP => { + if stack.is_empty() { + return Err(ScriptError::InvalidStackOperation); + } + + let a = stack.pop().unwrap(); + stack.push(a.clone()); + stack.push(a); + } + Opcode::OP_NIP => { + if stack.len() < 2 { + return Err(ScriptError::InvalidStackOperation); + } + + let b = stack.pop().unwrap(); + stack.pop(); + stack.push(b); + } + Opcode::OP_OVER => { + if stack.len() < 2 { + return Err(ScriptError::InvalidStackOperation); + } + + let b = stack.pop().unwrap(); + let a = stack.pop().unwrap(); + stack.push(a.clone()); + stack.push(b); + stack.push(a); + } + Opcode::OP_PICK | Opcode::OP_ROLL => { + todo!() + } + Opcode::OP_ROT => { + todo!() + } + Opcode::OP_SWAP => { + if stack.len() < 2 { + return Err(ScriptError::InvalidStackOperation); + } + + let b = stack.pop().unwrap(); + let a = stack.pop().unwrap(); + stack.push(b); + stack.push(a); + } + Opcode::OP_TUCK => { + if stack.len() < 2 { + return Err(ScriptError::InvalidStackOperation); + } + + let b = stack.pop().unwrap(); + let a = stack.pop().unwrap(); + stack.push(b.clone()); + stack.push(a); + stack.push(b); + } + Opcode::OP_SIZE => { + todo!() + } + Opcode::OP_EQUAL | Opcode::OP_EQUALVERIFY => { + if stack.len() < 2 { + return Err(ScriptError::InvalidStackOperation); + } + + todo!() + } + Opcode::OP_1ADD + | Opcode::OP_1SUB + | Opcode::OP_NEGATE + | Opcode::OP_ABS + | Opcode::OP_NOT + | Opcode::OP_0NOTEQUAL => { + todo!() + } + Opcode::OP_ADD + | Opcode::OP_SUB + | Opcode::OP_BOOLAND + | Opcode::OP_BOOLOR + | Opcode::OP_NUMEQUAL + | Opcode::OP_NUMEQUALVERIFY + | Opcode::OP_NUMNOTEQUAL + | Opcode::OP_LESSTHAN + | Opcode::OP_GREATERTHAN + | Opcode::OP_LESSTHANOREQUAL + | Opcode::OP_GREATERTHANOREQUAL + | Opcode::OP_MIN + | Opcode::OP_MAX => { + todo!() + } + Opcode::OP_WITHIN => { + todo!() + } + Opcode::OP_RIPEMD160 + | Opcode::OP_SHA1 + | Opcode::OP_SHA256 + | Opcode::OP_HASH160 + | Opcode::OP_HASH256 => { + todo!() + } + Opcode::OP_CHECKSIG | Opcode::OP_CHECKSIGVERIFY => { + todo!() + } + Opcode::OP_CHECKMULTISIG | Opcode::OP_CHECKMULTISIGVERIFY => { + todo!() + } + } + } + } + } + + // There's a limit to how many items can be added to the stack and + // alt stack. This limit is enforced upon finishing the execution of + // an opcode. + if stack.len() + alt_stack.len() > 1000 { + return Err(ScriptError::StackSize); + } + } + + if exec.is_empty() { + Ok(()) + } else { + Err(ScriptError::UnbalancedConditional) + } + } +} + +fn check_minimal_push(data: &[u8], raw_opcode: u8) -> bool { + todo!() +} diff --git a/zcash_script/src/opcodes.rs b/zcash_script/src/opcodes.rs new file mode 100644 index 0000000000..4a57d1b0c4 --- /dev/null +++ b/zcash_script/src/opcodes.rs @@ -0,0 +1,244 @@ +#![allow(non_camel_case_types)] + +use super::ScriptError; + +// Opcodes for pushing to the stack +const OP_0: u8 = 0x00; +const OP_PUSHDATA1: u8 = 0x4c; +const OP_PUSHDATA2: u8 = 0x4d; +const OP_PUSHDATA4: u8 = 0x4e; + +// First and last opcodes for pushing constants to the stack. OP_RESERVED is +// 0x50, which is included in this range, but it does not push anything to the +// stack and is considered invalid when it appears in an executing branch. +const OP_1NEGATE: u8 = 0x4f; +const OP_16: u8 = 0x60; + +// The first and last of the opcodes that are actually executed (with the +// exception of OP_VERIF and OP_VERNOTIF as noted next) +const OP_NOP: u8 = 0x61; +const OP_NOP10: u8 = 0xb9; + +// These opcodes are considered invalid because they appear as control flow +// opcodes (forcing their execution) but do not have a defined behavior during +// execution and so behave like unknown opcodes. +const OP_VERIF: u8 = 0x65; +const OP_VERNOTIF: u8 = 0x66; + +// Explicitly disabled opcodes +const OP_CAT: u8 = 0x7e; +const OP_SUBSTR: u8 = 0x7f; +const OP_LEFT: u8 = 0x80; +const OP_RIGHT: u8 = 0x81; +const OP_INVERT: u8 = 0x83; +const OP_AND: u8 = 0x84; +const OP_OR: u8 = 0x85; +const OP_XOR: u8 = 0x86; +const OP_2MUL: u8 = 0x8d; +const OP_2DIV: u8 = 0x8e; +const OP_MUL: u8 = 0x95; +const OP_DIV: u8 = 0x96; +const OP_MOD: u8 = 0x97; +const OP_LSHIFT: u8 = 0x98; +const OP_RSHIFT: u8 = 0x99; +const OP_CODESEPARATOR: u8 = 0xab; + +pub enum Operation { + PushBytes(u8), + Constant(i64), + Opcode(Opcode), + Invalid, + Disabled, +} + +#[derive(Copy, Clone, PartialEq, Eq, Debug)] +pub enum Opcode { + // OP_RESERVED is technically a valid operation inside of a non-executing + // OP_IF branch + OP_RESERVED = 0x50, + + OP_NOP = 0x61, + + // OP_VER is technically a valid operation inside of a non-executing OP_IF + // branch + OP_VER = 0x62, + OP_IF = 0x63, + OP_NOTIF = 0x64, + + OP_ELSE = 0x67, + OP_ENDIF = 0x68, + OP_VERIFY = 0x69, + OP_RETURN = 0x6a, + OP_TOALTSTACK = 0x6b, + OP_FROMALTSTACK = 0x6c, + OP_2DROP = 0x6d, + OP_2DUP = 0x6e, + OP_3DUP = 0x6f, + OP_2OVER = 0x70, + OP_2ROT = 0x71, + OP_2SWAP = 0x72, + OP_IFDUP = 0x73, + OP_DEPTH = 0x74, + OP_DROP = 0x75, + OP_DUP = 0x76, + OP_NIP = 0x77, + OP_OVER = 0x78, + OP_PICK = 0x79, + OP_ROLL = 0x7a, + OP_ROT = 0x7b, + OP_SWAP = 0x7c, + OP_TUCK = 0x7d, + OP_SIZE = 0x82, + OP_EQUAL = 0x87, + OP_EQUALVERIFY = 0x88, + + // OP_RESERVED1 and OP_RESERVED2 are technically valid in non-executing + // OP_IF branches + OP_RESERVED1 = 0x89, + OP_RESERVED2 = 0x8a, + + OP_1ADD = 0x8b, + OP_1SUB = 0x8c, + OP_NEGATE = 0x8f, + OP_ABS = 0x90, + OP_NOT = 0x91, + OP_0NOTEQUAL = 0x92, + OP_ADD = 0x93, + OP_SUB = 0x94, + OP_BOOLAND = 0x9a, + OP_BOOLOR = 0x9b, + OP_NUMEQUAL = 0x9c, + OP_NUMEQUALVERIFY = 0x9d, + OP_NUMNOTEQUAL = 0x9e, + OP_LESSTHAN = 0x9f, + OP_GREATERTHAN = 0xa0, + OP_LESSTHANOREQUAL = 0xa1, + OP_GREATERTHANOREQUAL = 0xa2, + OP_MIN = 0xa3, + OP_MAX = 0xa4, + OP_WITHIN = 0xa5, + OP_RIPEMD160 = 0xa6, + OP_SHA1 = 0xa7, + OP_SHA256 = 0xa8, + OP_HASH160 = 0xa9, + OP_HASH256 = 0xaa, + OP_CHECKSIG = 0xac, + OP_CHECKSIGVERIFY = 0xad, + OP_CHECKMULTISIG = 0xae, + OP_CHECKMULTISIGVERIFY = 0xaf, + OP_NOP1 = 0xb0, + + // OP_NOP2 was renamed to OP_CHECKLOCKTIMEVERIFY + OP_CHECKLOCKTIMEVERIFY = 0xb1, + + OP_NOP3 = 0xb2, + OP_NOP4 = 0xb3, + OP_NOP5 = 0xb4, + OP_NOP6 = 0xb5, + OP_NOP7 = 0xb6, + OP_NOP8 = 0xb7, + OP_NOP9 = 0xb8, + OP_NOP10 = 0xb9, +} + +impl Opcode { + /// Control flow opcodes are those between OP_IF and OP_ENDIF. Notably this + /// includes OP_VERIF and OP_VERNOTIF, which are not valid because they have + /// no implementations. + pub fn is_control_flow_opcode(&self) -> bool { + (Opcode::OP_IF) as u8 <= (*self as u8) && (*self as u8) <= (Opcode::OP_ENDIF as u8) + } +} + +pub fn parse_opcode( + script: &mut &[u8], + mut buffer: Option<&mut Vec>, +) -> Result { + if script.is_empty() { + panic!("attempting to parse an opcode from an empty script"); + } + + // Empty the provided buffer, if any + buffer.as_mut().map(|buffer| { + buffer.truncate(0); + }); + + let leading_byte = script[0]; + *script = &script[1..]; + + Ok(match leading_byte { + OP_PUSHDATA1 | OP_PUSHDATA2 | OP_PUSHDATA4 => { + let read_le = |script: &mut &[u8], needed_bytes: usize| { + if script.len() < needed_bytes { + Err(ScriptError::ReadError { + expected_bytes: needed_bytes, + available_bytes: script.len(), + }) + } else { + let mut size = 0; + for i in (0..needed_bytes).rev() { + size <<= 8; + size |= script[i] as usize; + } + *script = &script[needed_bytes..]; + Ok(size) + } + }; + + let size = match leading_byte { + OP_PUSHDATA1 => read_le(script, 1), + OP_PUSHDATA2 => read_le(script, 2), + OP_PUSHDATA4 => read_le(script, 4), + _ => unreachable!(), + }?; + + if script.len() < size { + return Err(ScriptError::ReadError { + expected_bytes: size, + available_bytes: script.len(), + }); + } + + buffer.map(|buffer| { + buffer.extend(&script[0..size]); + *script = &script[size..]; + }); + + Operation::PushBytes(leading_byte) + } + // OP_0/OP_FALSE doesn't actually push a constant 0 onto the stack but + // pushes an empty array. (Thus we leave the buffer truncated to 0 length) + OP_0 => Operation::PushBytes(leading_byte), + // OP_1NEGATE through OP_16 + byte if byte >= OP_1NEGATE && byte <= OP_16 => { + let value = byte as i64; + let value = value - 0x50; + + if value == 0 { + // This is actually OP_RESERVED (0x50) + Operation::Opcode(Opcode::OP_RESERVED) + } else { + // This is either OP_1NEGATE (-1) or one of OP_1/OP_TRUE through OP_16 + Operation::Constant(value) + } + } + // OP_NOP through OP_NOP10 + byte if byte >= OP_NOP && byte <= OP_NOP10 => { + match byte { + OP_CAT | OP_SUBSTR | OP_LEFT | OP_RIGHT | OP_INVERT | OP_AND | OP_OR | OP_XOR + | OP_2MUL | OP_2DIV | OP_MUL | OP_DIV | OP_MOD | OP_LSHIFT | OP_RSHIFT + | OP_CODESEPARATOR => Operation::Disabled, + OP_VERIF | OP_VERNOTIF => Operation::Invalid, + _ => { + let opcode: Opcode = unsafe { + // Safety: between OP_NOP and OP_NOP10, 8-bit opcode descriminants + // are defined (except for the opcodes above which we account for) + core::mem::transmute(byte) + }; + Operation::Opcode(opcode) + } + } + } + _ => Operation::Invalid, + }) +}