├── .github ├── FUNDING.yml └── workflows │ ├── build.yml │ ├── codecov.yml │ ├── lint.yml │ └── test.yml ├── .gitignore ├── .rustfmt.toml ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── Cargo.lock ├── Cargo.toml ├── DCO ├── LICENSE ├── MAINTAINERS.md ├── README.md ├── SECURITY.md ├── _typos.toml ├── codecov.yml ├── doc ├── comparison.png └── isa.png ├── scripts └── typelib.sh ├── src ├── bin │ └── aluvm-stl.rs ├── core │ ├── core.rs │ ├── microcode.rs │ ├── mod.rs │ └── util.rs ├── isa │ ├── arch.rs │ ├── bytecode.rs │ ├── ctrl │ │ ├── bytecode.rs │ │ ├── exec.rs │ │ ├── instr.rs │ │ └── mod.rs │ ├── instr.rs │ ├── masm.rs │ └── mod.rs ├── lib.rs ├── library │ ├── armor.rs │ ├── assembler.rs │ ├── compiler.rs │ ├── exec.rs │ ├── lib.rs │ ├── marshaller.rs │ └── mod.rs ├── stl.rs └── vm.rs ├── stl ├── AluVM@0.1.0.sta ├── AluVM@0.1.0.stl └── AluVM@0.1.0.sty └── tests └── exec.rs /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: [ dr-orlovsky, UBIDECO, AluVM, LNP-BP ] 4 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | tags: 8 | - 'v[0-9]+.*' 9 | pull_request: 10 | branches: 11 | - master 12 | - develop 13 | - 'v[0-9]+.?*' 14 | 15 | env: 16 | CARGO_TERM_COLOR: always 17 | 18 | jobs: 19 | default: 20 | runs-on: ubuntu-latest 21 | steps: 22 | - uses: actions/checkout@v4 23 | - uses: dtolnay/rust-toolchain@stable 24 | - run: cargo check --workspace 25 | no-default: 26 | runs-on: ubuntu-latest 27 | steps: 28 | - uses: actions/checkout@v4 29 | - uses: dtolnay/rust-toolchain@stable 30 | - run: cargo check --workspace --no-default-features --features alloc 31 | features: 32 | runs-on: ubuntu-latest 33 | strategy: 34 | fail-fast: false 35 | matrix: 36 | feature: 37 | - log 38 | - armor 39 | - serde 40 | - stl 41 | steps: 42 | - uses: actions/checkout@v4 43 | - uses: dtolnay/rust-toolchain@stable 44 | - name: Feature ${{matrix.feature}} 45 | run: cargo check --workspace --no-default-features --features=std,${{matrix.feature}} 46 | - name: Feature ${{matrix.feature}} 47 | run: cargo check --workspace --features=${{matrix.feature}} 48 | platforms: 49 | runs-on: ${{ matrix.os }} 50 | strategy: 51 | fail-fast: false 52 | matrix: 53 | os: [ ubuntu-22.04, ubuntu-latest, macos-13, macos-latest, windows-2019, windows-latest ] 54 | steps: 55 | - uses: actions/checkout@v4 56 | - uses: dtolnay/rust-toolchain@stable 57 | - name: Platform ${{matrix.os}} 58 | run: cargo check --workspace --all-features # we skip test targets here to be sure that the main library can be built 59 | toolchains: 60 | runs-on: ubuntu-latest 61 | strategy: 62 | fail-fast: false 63 | matrix: 64 | toolchain: [ nightly, beta, stable, 1.81.0 ] 65 | steps: 66 | - uses: actions/checkout@v4 67 | - uses: dtolnay/rust-toolchain@master 68 | with: 69 | toolchain: ${{matrix.toolchain}} 70 | - name: Toolchain ${{matrix.toolchain}} 71 | run: cargo +${{matrix.toolchain}} check --workspace --all-targets --all-features 72 | -------------------------------------------------------------------------------- /.github/workflows/codecov.yml: -------------------------------------------------------------------------------- 1 | name: Codecov 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | tags: 8 | - 'v[0-9]+.*' 9 | pull_request: 10 | branches: 11 | - master 12 | - develop 13 | - 'v[0-9]+.?*' 14 | 15 | env: 16 | CARGO_TERM_COLOR: always 17 | 18 | jobs: 19 | codecov: 20 | runs-on: ubuntu-latest 21 | steps: 22 | - uses: actions/checkout@v4 23 | - uses: dtolnay/rust-toolchain@nightly 24 | with: 25 | components: llvm-tools-preview 26 | - uses: taiki-e/install-action@cargo-llvm-cov 27 | - uses: taiki-e/install-action@nextest 28 | - name: Collect coverage data (including doctests) 29 | run: | 30 | cargo +nightly llvm-cov --no-report nextest --workspace --all-features 31 | cargo +nightly llvm-cov --no-report --doc --workspace --all-features 32 | cargo +nightly llvm-cov report --doctests --lcov --output-path lcov.info 33 | - name: Upload coverage data to codecov 34 | uses: codecov/codecov-action@v4 35 | with: 36 | flags: rust 37 | files: lcov.info 38 | fail_ci_if_error: true 39 | token: ${{ secrets.CODECOV_TOKEN }} 40 | verbose: true 41 | -------------------------------------------------------------------------------- /.github/workflows/lint.yml: -------------------------------------------------------------------------------- 1 | name: Lints 2 | 3 | on: 4 | pull_request: 5 | branches: 6 | - master 7 | - develop 8 | - 'v[0-9]+.?*' 9 | 10 | env: 11 | CARGO_TERM_COLOR: always 12 | 13 | jobs: 14 | fmt: 15 | runs-on: ubuntu-latest 16 | steps: 17 | - uses: actions/checkout@v4 18 | - uses: dtolnay/rust-toolchain@nightly 19 | with: 20 | components: rustfmt 21 | - name: Formatting 22 | run: cargo +nightly fmt --all -- --check 23 | clippy: 24 | runs-on: ubuntu-latest 25 | steps: 26 | - uses: actions/checkout@v4 27 | - uses: dtolnay/rust-toolchain@stable 28 | with: 29 | components: clippy 30 | - name: Formatting 31 | run: cargo clippy --workspace --all-features --all-targets -- -D warnings 32 | doc: 33 | runs-on: ubuntu-latest 34 | steps: 35 | - uses: actions/checkout@v4 36 | - uses: dtolnay/rust-toolchain@nightly 37 | with: 38 | components: rust-docs 39 | - name: Formatting 40 | run: cargo +nightly doc --workspace --all-features 41 | typos: 42 | runs-on: ubuntu-latest 43 | steps: 44 | - uses: actions/checkout@v4 45 | - uses: crate-ci/typos@master 46 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Tests 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | tags: 8 | - 'v[0-9]+.*' 9 | pull_request: 10 | branches: 11 | - master 12 | - develop 13 | - 'v[0-9]+.?*' 14 | 15 | env: 16 | CARGO_TERM_COLOR: always 17 | 18 | jobs: 19 | testing: 20 | runs-on: ${{ matrix.os }} 21 | strategy: 22 | fail-fast: false 23 | matrix: 24 | os: [ ubuntu-latest, macos-13, macos-latest, windows-latest ] 25 | steps: 26 | - uses: actions/checkout@v4 27 | - uses: dtolnay/rust-toolchain@stable 28 | - name: Test ${{matrix.os}} 29 | run: cargo test --workspace --all-features --no-fail-fast 30 | wasm-testing: 31 | runs-on: ubuntu-latest 32 | steps: 33 | - uses: actions/checkout@v4 34 | - uses: dtolnay/rust-toolchain@nightly 35 | - uses: jetli/wasm-pack-action@v0.4.0 36 | - name: Add wasm32 target 37 | run: rustup target add wasm32-unknown-unknown 38 | - name: Test in headless Chrome 39 | run: RUSTFLAGS='--cfg getrandom_backend="wasm_js"' wasm-pack test --headless --chrome --all-features 40 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | /target/ 4 | 5 | # These are backup files generated by rustfmt 6 | **/*.rs.bk 7 | 8 | /.idea 9 | -------------------------------------------------------------------------------- /.rustfmt.toml: -------------------------------------------------------------------------------- 1 | edition = "2021" 2 | style_edition = "2021" 3 | 4 | max_width = 100 5 | array_width = 100 6 | attr_fn_like_width = 100 7 | comment_width = 100 8 | chain_width = 60 9 | fn_call_width = 100 10 | single_line_if_else_max_width = 100 11 | struct_lit_width = 60 12 | 13 | fn_single_line = true 14 | format_code_in_doc_comments = true 15 | format_macro_matchers = true 16 | format_macro_bodies = true 17 | format_strings = true 18 | merge_derives = false 19 | overflow_delimited_expr = true 20 | reorder_modules = false 21 | use_field_init_shorthand = true 22 | use_try_shorthand = true 23 | wrap_comments = true 24 | where_single_line = true 25 | unstable_features = true 26 | 27 | imports_granularity = "Module" 28 | group_imports = "StdExternalCrate" 29 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Code of Conduct 2 | 3 | We do not apply any code of conduct expectations for contributors and 4 | maintainers in their live and behaviour outside the scope of this project. 5 | We believe that a restriction is the word of sin: free people write code, take 6 | their decisions and act in a way they will, taking responsibility for the 7 | consequences. 8 | 9 | Moreover, we will try to protect the freedom of speech of contributors, and 10 | explicit distance from personal or public life of contributors, as long as 11 | they behave in a civil and productive way when contributing and interacting 12 | within the project, and will go to great lengths to not deny anyone 13 | participation. 14 | 15 | Actions within the technical scope of the project (code quality, spamming etc), 16 | as well as interaction with other maintainers and contributors of course is 17 | a factor of the access to the project development and lifecycle. The decision in 18 | these cases will be made by the project maintainers, with the right of veto or 19 | overriding vote reserved for the original project author, Maxim Orlovsky. 20 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | Contributing guidelines 2 | ======================= 3 | 4 | Contributions are very welcome. When contributing code, please follow these 5 | simple guidelines. 6 | 7 | #### Table Of Contents 8 | - [Contribution workflow](#contribution-workflow) 9 | * [Proposing changes](#proposing-changes) 10 | * [Preparing PRs](#preparing-prs) 11 | * [Peer review](#peer-review) 12 | - [Coding conventions](#coding-conventions) 13 | - [Security](#security) 14 | - [Testing](#testing) 15 | - [Going further](#going-further) 16 | 17 | Overview 18 | -------- 19 | 20 | * Before adding any code dependencies, check with the maintainers if this is okay. 21 | * Write properly formatted comments: they should be English sentences, eg: 22 | 23 | // Return the current UNIX time. 24 | 25 | * Read the DCO and make sure all commits are signed off, using `git commit -s`. 26 | * Follow the guidelines when proposing code changes (see below). 27 | * Write properly formatted git commits (see below). 28 | * Run the tests with `cargo test --workspace --all-features`. 29 | * Make sure you run `rustfmt` on your code (see below details). 30 | * Please don't file an issue to ask a question. Each repository - or 31 | GitHub organization has a "Discussions" with Q&A section; please post your 32 | questions there. You'll get faster results by using this channel. 33 | 34 | Contribution Workflow 35 | --------------------- 36 | The codebase is maintained using the "contributor workflow" where everyone 37 | without exception contributes patch proposals using "pull requests". This 38 | facilitates social contribution, easy testing and peer review. 39 | 40 | To contribute a patch, the workflow is a as follows: 41 | 42 | 1. Fork Repository 43 | 2. Create topic branch 44 | 3. Commit patches 45 | 46 | In general commits should be atomic and diffs should be easy to read. For this 47 | reason do not mix any formatting fixes or code moves with actual code changes. 48 | Further, each commit, individually, should compile and pass tests, in order to 49 | ensure git bisect and other automated tools function properly. 50 | 51 | When adding a new feature thought must be given to the long term technical debt. 52 | Every new features should be covered by unit tests. 53 | 54 | When refactoring, structure your PR to make it easy to review and don't hesitate 55 | to split it into multiple small, focused PRs. 56 | 57 | Commits should cover both the issue fixed and the solution's rationale. 58 | These [guidelines](https://chris.beams.io/posts/git-commit/) should be kept in 59 | mind. 60 | 61 | To facilitate communication with other contributors, the project is making use 62 | of GitHub's "assignee" field. First check that no one is assigned and then 63 | comment suggesting that you're working on it. If someone is already assigned, 64 | don't hesitate to ask if the assigned party or previous commenters are still 65 | working on it if it has been awhile. 66 | 67 | ### Proposing changes 68 | 69 | When proposing changes via a pull-request or patch: 70 | 71 | * Isolate changes in separate commits to make the review process easier. 72 | * Don't make unrelated changes, unless it happens to be an obvious improvement to 73 | code you are touching anyway ("boyscout rule"). 74 | * Rebase on `master` when needed. 75 | * Keep your changesets small, specific and uncontroversial, so that they can be 76 | merged more quickly. 77 | * If the change is substantial or requires re-architecting certain parts of the 78 | codebase, write a proposal in English first, and get consensus on that before 79 | proposing the code changes. 80 | 81 | ### Preparing PRs 82 | 83 | The main library development happens in the `master` branch. This branch must 84 | always compile without errors (using Travis CI). All external contributions are 85 | made within PRs into this branch. 86 | 87 | Prerequisites that a PR must satisfy for merging into the `master` branch: 88 | * the tip of any PR branch must compile and pass unit tests with no errors, with 89 | every feature combination (including compiling the fuzztests) on MSRV, stable 90 | and nightly compilers (this is partially automated with CI, so the rule 91 | is that we will not accept commits which do not pass GitHub CI); 92 | * contain all necessary tests for the introduced functional (either as a part of 93 | commits, or, more preferably, as separate commits, so that it's easy to 94 | reorder them during review and check that the new tests fail without the new 95 | code); 96 | * contain all inline docs for newly introduced API and pass doc tests; 97 | * be based on the recent `master` tip from the original repository at. 98 | 99 | NB: reviewers may run more complex test/CI scripts, thus, satisfying all the 100 | requirements above is just a preliminary, but not necessary sufficient step for 101 | getting the PR accepted as a valid candidate PR for the `master` branch. 102 | 103 | Additionally, to the `master` branch some repositories may have `develop` branch 104 | for any experimental developments. This branch may not compile and should not be 105 | used by any projects depending on the library. 106 | 107 | ### Writing Git commit messages 108 | 109 | A properly formed git commit subject line should always be able to complete the 110 | following sentence: 111 | 112 | If applied, this commit will _____ 113 | 114 | In addition, it should be capitalized and *must not* include a period. 115 | 116 | For example, the following message is well formed: 117 | 118 | Add support for .gif files 119 | 120 | While these ones are **not**: `Adding support for .gif files`, 121 | `Added support for .gif files`. 122 | 123 | When it comes to formatting, here's a model git commit message[1]: 124 | 125 | Capitalized, short (50 chars or less) summary 126 | 127 | More detailed explanatory text, if necessary. Wrap it to about 72 128 | characters or so. In some contexts, the first line is treated as the 129 | subject of an email and the rest of the text as the body. The blank 130 | line separating the summary from the body is critical (unless you omit 131 | the body entirely); tools like rebase can get confused if you run the 132 | two together. 133 | 134 | Write your commit message in the imperative: "Fix bug" and not "Fixed bug" 135 | or "Fixes bug." This convention matches up with commit messages generated 136 | by commands like git merge and git revert. 137 | 138 | Further paragraphs come after blank lines. 139 | 140 | - Bullet points are okay, too. 141 | 142 | - Typically a hyphen or asterisk is used for the bullet, followed by a 143 | single space, with blank lines in between, but conventions vary here. 144 | 145 | - Use a hanging indent. 146 | 147 | ### Peer review 148 | 149 | Anyone may participate in peer review which is expressed by comments in the pull 150 | request. Typically reviewers will review the code for obvious errors, as well as 151 | test out the patch set and opine on the technical merits of the patch. PR should 152 | be reviewed first on the conceptual level before focusing on code style or 153 | grammar fixes. 154 | 155 | Coding Conventions 156 | ------------------ 157 | Our CI enforces [clippy's](https://github.com/rust-lang/rust-clippy) 158 | [default linting](https://rust-lang.github.io/rust-clippy/rust-1.52.0/index.html) 159 | and [rustfmt](https://github.com/rust-lang/rustfmt) formatting defined by rules 160 | in [.rustfmt.toml](./.rustfmt.toml). The linter should be run with current 161 | stable rust compiler, while formatter requires nightly version due to the use of 162 | unstable formatting parameters. 163 | 164 | If you use rustup, to lint locally you may run the following instructions: 165 | 166 | ```console 167 | rustup component add clippy 168 | rustup component add fmt 169 | cargo +stable clippy --workspace --all-features 170 | cargo +nightly fmt --all 171 | ``` 172 | 173 | Security 174 | -------- 175 | Responsible disclosure of security vulnerabilities helps prevent user loss of 176 | privacy. If you believe a vulnerability may affect other implementations, please 177 | inform them. Guidelines for a responsible disclosure can be found in 178 | [SECURITY.md](./SECURITY.md) file in the project root. 179 | 180 | Note that some of our projects are currently considered "pre-production". 181 | Such projects can be distinguished by the absence of `SECURITY.md`. In such 182 | cases there are no special handling of security issues; please simply open 183 | an issue on GitHub. 184 | 185 | Going further 186 | ------------- 187 | You may be interested in Jon Atack guide on 188 | [How to review Bitcoin Core PRs][Review] and [How to make Bitcoin Core PRs][PR]. 189 | While there are differences between the projects in terms of context and 190 | maturity, many of the suggestions offered apply to this project. 191 | 192 | Overall, have fun :) 193 | 194 | [1]: http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html 195 | [Review]: https://github.com/jonatack/bitcoin-development/blob/master/how-to-review-bitcoin-core-prs.md 196 | [PR]: https://github.com/jonatack/bitcoin-development/blob/master/how-to-make-bitcoin-core-prs.md 197 | -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | version = 3 4 | 5 | [[package]] 6 | name = "aluvm" 7 | version = "0.12.0-rc.1" 8 | dependencies = [ 9 | "amplify", 10 | "ascii-armor", 11 | "baid64", 12 | "commit_verify", 13 | "getrandom 0.2.16", 14 | "getrandom 0.3.3", 15 | "paste", 16 | "rand", 17 | "serde", 18 | "strict_encoding", 19 | "strict_types", 20 | "wasm-bindgen", 21 | "wasm-bindgen-test", 22 | ] 23 | 24 | [[package]] 25 | name = "amplify" 26 | version = "4.9.0" 27 | source = "registry+https://github.com/rust-lang/crates.io-index" 28 | checksum = "3f7fb4ac7c881e54a8e7015e399b6112a2a5bc958b6c89ac510840ff20273b31" 29 | dependencies = [ 30 | "amplify_derive", 31 | "amplify_num", 32 | "amplify_syn", 33 | "ascii", 34 | "getrandom 0.2.16", 35 | "getrandom 0.3.3", 36 | "serde", 37 | "stringly_conversions", 38 | "wasm-bindgen", 39 | ] 40 | 41 | [[package]] 42 | name = "amplify_derive" 43 | version = "4.0.1" 44 | source = "registry+https://github.com/rust-lang/crates.io-index" 45 | checksum = "2a6309e6b8d89b36b9f959b7a8fa093583b94922a0f6438a24fb08936de4d428" 46 | dependencies = [ 47 | "amplify_syn", 48 | "proc-macro2", 49 | "quote", 50 | "syn 1.0.109", 51 | ] 52 | 53 | [[package]] 54 | name = "amplify_num" 55 | version = "0.5.3" 56 | source = "registry+https://github.com/rust-lang/crates.io-index" 57 | checksum = "99bcb75a2982047f733547042fc3968c0f460dfcf7d90b90dea3b2744580e9ad" 58 | dependencies = [ 59 | "serde", 60 | "wasm-bindgen", 61 | ] 62 | 63 | [[package]] 64 | name = "amplify_syn" 65 | version = "2.0.1" 66 | source = "registry+https://github.com/rust-lang/crates.io-index" 67 | checksum = "7736fb8d473c0d83098b5bac44df6a561e20470375cd8bcae30516dc889fd62a" 68 | dependencies = [ 69 | "proc-macro2", 70 | "quote", 71 | "syn 1.0.109", 72 | ] 73 | 74 | [[package]] 75 | name = "ascii" 76 | version = "1.1.0" 77 | source = "registry+https://github.com/rust-lang/crates.io-index" 78 | checksum = "d92bec98840b8f03a5ff5413de5293bfcd8bf96467cf5452609f939ec6f5de16" 79 | dependencies = [ 80 | "serde", 81 | ] 82 | 83 | [[package]] 84 | name = "ascii-armor" 85 | version = "0.9.0" 86 | source = "registry+https://github.com/rust-lang/crates.io-index" 87 | checksum = "0269eb842ec952b027df0fc33184b6a0dea5ea473160b36992274eb53758461e" 88 | dependencies = [ 89 | "amplify", 90 | "baid64", 91 | "base85", 92 | "sha2", 93 | "strict_encoding", 94 | ] 95 | 96 | [[package]] 97 | name = "baid64" 98 | version = "0.4.1" 99 | source = "registry+https://github.com/rust-lang/crates.io-index" 100 | checksum = "6cb4a8b2f1afee4ef00a190b260ad871842b93206177b59631fecd325d48d538" 101 | dependencies = [ 102 | "amplify", 103 | "base64", 104 | "mnemonic", 105 | "sha2", 106 | ] 107 | 108 | [[package]] 109 | name = "base64" 110 | version = "0.22.1" 111 | source = "registry+https://github.com/rust-lang/crates.io-index" 112 | checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" 113 | 114 | [[package]] 115 | name = "base85" 116 | version = "2.0.0" 117 | source = "registry+https://github.com/rust-lang/crates.io-index" 118 | checksum = "36915bbaca237c626689b5bd14d02f2ba7a5a359d30a2a08be697392e3718079" 119 | dependencies = [ 120 | "thiserror", 121 | ] 122 | 123 | [[package]] 124 | name = "bitflags" 125 | version = "2.9.1" 126 | source = "registry+https://github.com/rust-lang/crates.io-index" 127 | checksum = "1b8e56985ec62d17e9c1001dc89c88ecd7dc08e47eba5ec7c29c7b5eeecde967" 128 | 129 | [[package]] 130 | name = "block-buffer" 131 | version = "0.10.4" 132 | source = "registry+https://github.com/rust-lang/crates.io-index" 133 | checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" 134 | dependencies = [ 135 | "generic-array", 136 | ] 137 | 138 | [[package]] 139 | name = "bumpalo" 140 | version = "3.17.0" 141 | source = "registry+https://github.com/rust-lang/crates.io-index" 142 | checksum = "1628fb46dfa0b37568d12e5edd512553eccf6a22a78e8bde00bb4aed84d5bdbf" 143 | 144 | [[package]] 145 | name = "cc" 146 | version = "1.2.23" 147 | source = "registry+https://github.com/rust-lang/crates.io-index" 148 | checksum = "5f4ac86a9e5bc1e2b3449ab9d7d3a6a405e3d1bb28d7b9be8614f55846ae3766" 149 | dependencies = [ 150 | "shlex", 151 | ] 152 | 153 | [[package]] 154 | name = "cfg-if" 155 | version = "1.0.0" 156 | source = "registry+https://github.com/rust-lang/crates.io-index" 157 | checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" 158 | 159 | [[package]] 160 | name = "commit_encoding_derive" 161 | version = "0.12.0-rc.1" 162 | source = "registry+https://github.com/rust-lang/crates.io-index" 163 | checksum = "783e42e09ad9dbc48d01532fc59fd1f1c64c98c09f523abeb6a069756651c9c3" 164 | dependencies = [ 165 | "amplify", 166 | "amplify_syn", 167 | "proc-macro2", 168 | "quote", 169 | "syn 1.0.109", 170 | ] 171 | 172 | [[package]] 173 | name = "commit_verify" 174 | version = "0.12.0-rc.1" 175 | source = "registry+https://github.com/rust-lang/crates.io-index" 176 | checksum = "2c91d4e2c820279c133f8cb1c7c7544caba346c8049d6a7749dca1031d7acb68" 177 | dependencies = [ 178 | "amplify", 179 | "commit_encoding_derive", 180 | "getrandom 0.2.16", 181 | "getrandom 0.3.3", 182 | "ripemd", 183 | "sha2", 184 | "strict_encoding", 185 | "strict_types", 186 | "vesper-lang", 187 | "wasm-bindgen", 188 | ] 189 | 190 | [[package]] 191 | name = "cpufeatures" 192 | version = "0.2.17" 193 | source = "registry+https://github.com/rust-lang/crates.io-index" 194 | checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" 195 | dependencies = [ 196 | "libc", 197 | ] 198 | 199 | [[package]] 200 | name = "crypto-common" 201 | version = "0.1.6" 202 | source = "registry+https://github.com/rust-lang/crates.io-index" 203 | checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" 204 | dependencies = [ 205 | "generic-array", 206 | "typenum", 207 | ] 208 | 209 | [[package]] 210 | name = "digest" 211 | version = "0.10.7" 212 | source = "registry+https://github.com/rust-lang/crates.io-index" 213 | checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" 214 | dependencies = [ 215 | "block-buffer", 216 | "crypto-common", 217 | ] 218 | 219 | [[package]] 220 | name = "equivalent" 221 | version = "1.0.2" 222 | source = "registry+https://github.com/rust-lang/crates.io-index" 223 | checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" 224 | 225 | [[package]] 226 | name = "generic-array" 227 | version = "0.14.7" 228 | source = "registry+https://github.com/rust-lang/crates.io-index" 229 | checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" 230 | dependencies = [ 231 | "typenum", 232 | "version_check", 233 | ] 234 | 235 | [[package]] 236 | name = "getrandom" 237 | version = "0.2.16" 238 | source = "registry+https://github.com/rust-lang/crates.io-index" 239 | checksum = "335ff9f135e4384c8150d6f27c6daed433577f86b4750418338c01a1a2528592" 240 | dependencies = [ 241 | "cfg-if", 242 | "js-sys", 243 | "libc", 244 | "wasi 0.11.0+wasi-snapshot-preview1", 245 | "wasm-bindgen", 246 | ] 247 | 248 | [[package]] 249 | name = "getrandom" 250 | version = "0.3.3" 251 | source = "registry+https://github.com/rust-lang/crates.io-index" 252 | checksum = "26145e563e54f2cadc477553f1ec5ee650b00862f0a58bcd12cbdc5f0ea2d2f4" 253 | dependencies = [ 254 | "cfg-if", 255 | "js-sys", 256 | "libc", 257 | "r-efi", 258 | "wasi 0.14.2+wasi-0.2.4", 259 | "wasm-bindgen", 260 | ] 261 | 262 | [[package]] 263 | name = "hashbrown" 264 | version = "0.15.3" 265 | source = "registry+https://github.com/rust-lang/crates.io-index" 266 | checksum = "84b26c544d002229e640969970a2e74021aadf6e2f96372b9c58eff97de08eb3" 267 | 268 | [[package]] 269 | name = "heck" 270 | version = "0.5.0" 271 | source = "registry+https://github.com/rust-lang/crates.io-index" 272 | checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" 273 | 274 | [[package]] 275 | name = "indexmap" 276 | version = "2.9.0" 277 | source = "registry+https://github.com/rust-lang/crates.io-index" 278 | checksum = "cea70ddb795996207ad57735b50c5982d8844f38ba9ee5f1aedcfb708a2aa11e" 279 | dependencies = [ 280 | "equivalent", 281 | "hashbrown", 282 | ] 283 | 284 | [[package]] 285 | name = "js-sys" 286 | version = "0.3.77" 287 | source = "registry+https://github.com/rust-lang/crates.io-index" 288 | checksum = "1cfaf33c695fc6e08064efbc1f72ec937429614f25eef83af942d0e227c3a28f" 289 | dependencies = [ 290 | "once_cell", 291 | "wasm-bindgen", 292 | ] 293 | 294 | [[package]] 295 | name = "libc" 296 | version = "0.2.172" 297 | source = "registry+https://github.com/rust-lang/crates.io-index" 298 | checksum = "d750af042f7ef4f724306de029d18836c26c1765a54a6a3f094cbd23a7267ffa" 299 | 300 | [[package]] 301 | name = "log" 302 | version = "0.4.27" 303 | source = "registry+https://github.com/rust-lang/crates.io-index" 304 | checksum = "13dc2df351e3202783a1fe0d44375f7295ffb4049267b0f3018346dc122a1d94" 305 | 306 | [[package]] 307 | name = "minicov" 308 | version = "0.3.7" 309 | source = "registry+https://github.com/rust-lang/crates.io-index" 310 | checksum = "f27fe9f1cc3c22e1687f9446c2083c4c5fc7f0bcf1c7a86bdbded14985895b4b" 311 | dependencies = [ 312 | "cc", 313 | "walkdir", 314 | ] 315 | 316 | [[package]] 317 | name = "mnemonic" 318 | version = "1.1.1" 319 | source = "registry+https://github.com/rust-lang/crates.io-index" 320 | checksum = "f2b8f3a258db515d5e91a904ce4ae3f73e091149b90cadbdb93d210bee07f63b" 321 | 322 | [[package]] 323 | name = "once_cell" 324 | version = "1.21.3" 325 | source = "registry+https://github.com/rust-lang/crates.io-index" 326 | checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" 327 | 328 | [[package]] 329 | name = "paste" 330 | version = "1.0.15" 331 | source = "registry+https://github.com/rust-lang/crates.io-index" 332 | checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" 333 | 334 | [[package]] 335 | name = "ppv-lite86" 336 | version = "0.2.21" 337 | source = "registry+https://github.com/rust-lang/crates.io-index" 338 | checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" 339 | dependencies = [ 340 | "zerocopy", 341 | ] 342 | 343 | [[package]] 344 | name = "proc-macro2" 345 | version = "1.0.95" 346 | source = "registry+https://github.com/rust-lang/crates.io-index" 347 | checksum = "02b3e5e68a3a1a02aad3ec490a98007cbc13c37cbe84a3cd7b8e406d76e7f778" 348 | dependencies = [ 349 | "unicode-ident", 350 | ] 351 | 352 | [[package]] 353 | name = "quote" 354 | version = "1.0.40" 355 | source = "registry+https://github.com/rust-lang/crates.io-index" 356 | checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d" 357 | dependencies = [ 358 | "proc-macro2", 359 | ] 360 | 361 | [[package]] 362 | name = "r-efi" 363 | version = "5.2.0" 364 | source = "registry+https://github.com/rust-lang/crates.io-index" 365 | checksum = "74765f6d916ee2faa39bc8e68e4f3ed8949b48cccdac59983d287a7cb71ce9c5" 366 | 367 | [[package]] 368 | name = "rand" 369 | version = "0.9.1" 370 | source = "registry+https://github.com/rust-lang/crates.io-index" 371 | checksum = "9fbfd9d094a40bf3ae768db9361049ace4c0e04a4fd6b359518bd7b73a73dd97" 372 | dependencies = [ 373 | "rand_chacha", 374 | "rand_core", 375 | ] 376 | 377 | [[package]] 378 | name = "rand_chacha" 379 | version = "0.9.0" 380 | source = "registry+https://github.com/rust-lang/crates.io-index" 381 | checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" 382 | dependencies = [ 383 | "ppv-lite86", 384 | "rand_core", 385 | ] 386 | 387 | [[package]] 388 | name = "rand_core" 389 | version = "0.9.3" 390 | source = "registry+https://github.com/rust-lang/crates.io-index" 391 | checksum = "99d9a13982dcf210057a8a78572b2217b667c3beacbf3a0d8b454f6f82837d38" 392 | dependencies = [ 393 | "getrandom 0.3.3", 394 | ] 395 | 396 | [[package]] 397 | name = "ripemd" 398 | version = "0.1.3" 399 | source = "registry+https://github.com/rust-lang/crates.io-index" 400 | checksum = "bd124222d17ad93a644ed9d011a40f4fb64aa54275c08cc216524a9ea82fb09f" 401 | dependencies = [ 402 | "digest", 403 | ] 404 | 405 | [[package]] 406 | name = "rustversion" 407 | version = "1.0.20" 408 | source = "registry+https://github.com/rust-lang/crates.io-index" 409 | checksum = "eded382c5f5f786b989652c49544c4877d9f015cc22e145a5ea8ea66c2921cd2" 410 | 411 | [[package]] 412 | name = "same-file" 413 | version = "1.0.6" 414 | source = "registry+https://github.com/rust-lang/crates.io-index" 415 | checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" 416 | dependencies = [ 417 | "winapi-util", 418 | ] 419 | 420 | [[package]] 421 | name = "serde" 422 | version = "1.0.219" 423 | source = "registry+https://github.com/rust-lang/crates.io-index" 424 | checksum = "5f0e2c6ed6606019b4e29e69dbaba95b11854410e5347d525002456dbbb786b6" 425 | dependencies = [ 426 | "serde_derive", 427 | ] 428 | 429 | [[package]] 430 | name = "serde_derive" 431 | version = "1.0.219" 432 | source = "registry+https://github.com/rust-lang/crates.io-index" 433 | checksum = "5b0276cf7f2c73365f7157c8123c21cd9a50fbbd844757af28ca1f5925fc2a00" 434 | dependencies = [ 435 | "proc-macro2", 436 | "quote", 437 | "syn 2.0.101", 438 | ] 439 | 440 | [[package]] 441 | name = "serde_str_helpers" 442 | version = "0.1.2" 443 | source = "registry+https://github.com/rust-lang/crates.io-index" 444 | checksum = "b744a7c94f2f3785496af33a0d93857dfc0c521e25c38e993e9c5bb45f09c841" 445 | dependencies = [ 446 | "serde", 447 | "serde_derive", 448 | ] 449 | 450 | [[package]] 451 | name = "sha2" 452 | version = "0.10.9" 453 | source = "registry+https://github.com/rust-lang/crates.io-index" 454 | checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" 455 | dependencies = [ 456 | "cfg-if", 457 | "cpufeatures", 458 | "digest", 459 | ] 460 | 461 | [[package]] 462 | name = "shlex" 463 | version = "1.3.0" 464 | source = "registry+https://github.com/rust-lang/crates.io-index" 465 | checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" 466 | 467 | [[package]] 468 | name = "strict_encoding" 469 | version = "2.9.1" 470 | source = "registry+https://github.com/rust-lang/crates.io-index" 471 | checksum = "5b8d9721d221d797767f8d5ad72b3a34dcdb5b9d646fe76248ee0f5e6fa6ca89" 472 | dependencies = [ 473 | "amplify", 474 | "getrandom 0.2.16", 475 | "getrandom 0.3.3", 476 | "serde", 477 | "strict_encoding_derive", 478 | "wasm-bindgen", 479 | ] 480 | 481 | [[package]] 482 | name = "strict_encoding_derive" 483 | version = "2.8.0" 484 | source = "registry+https://github.com/rust-lang/crates.io-index" 485 | checksum = "34e3bc6e4a2450420b4dbfb6929d9ce005e8c36cf73bf215db99f0d09c9fa79f" 486 | dependencies = [ 487 | "amplify_syn", 488 | "heck", 489 | "proc-macro2", 490 | "quote", 491 | "syn 1.0.109", 492 | ] 493 | 494 | [[package]] 495 | name = "strict_types" 496 | version = "2.9.0" 497 | source = "registry+https://github.com/rust-lang/crates.io-index" 498 | checksum = "493821521630a023d79a210033fe1f5135ae3d3f8fccd8dbf1a98b7dfe56b144" 499 | dependencies = [ 500 | "amplify", 501 | "ascii-armor", 502 | "baid64", 503 | "getrandom 0.2.16", 504 | "getrandom 0.3.3", 505 | "indexmap", 506 | "sha2", 507 | "strict_encoding", 508 | "vesper-lang", 509 | "wasm-bindgen", 510 | ] 511 | 512 | [[package]] 513 | name = "stringly_conversions" 514 | version = "0.1.1" 515 | source = "registry+https://github.com/rust-lang/crates.io-index" 516 | checksum = "ff63080f492dd4d289ffcaed8d7ece38adfb423db910eb342c0e04d409536a7a" 517 | dependencies = [ 518 | "paste", 519 | "serde_str_helpers", 520 | ] 521 | 522 | [[package]] 523 | name = "syn" 524 | version = "1.0.109" 525 | source = "registry+https://github.com/rust-lang/crates.io-index" 526 | checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" 527 | dependencies = [ 528 | "proc-macro2", 529 | "quote", 530 | "unicode-ident", 531 | ] 532 | 533 | [[package]] 534 | name = "syn" 535 | version = "2.0.101" 536 | source = "registry+https://github.com/rust-lang/crates.io-index" 537 | checksum = "8ce2b7fc941b3a24138a0a7cf8e858bfc6a992e7978a068a5c760deb0ed43caf" 538 | dependencies = [ 539 | "proc-macro2", 540 | "quote", 541 | "unicode-ident", 542 | ] 543 | 544 | [[package]] 545 | name = "thiserror" 546 | version = "1.0.69" 547 | source = "registry+https://github.com/rust-lang/crates.io-index" 548 | checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" 549 | dependencies = [ 550 | "thiserror-impl", 551 | ] 552 | 553 | [[package]] 554 | name = "thiserror-impl" 555 | version = "1.0.69" 556 | source = "registry+https://github.com/rust-lang/crates.io-index" 557 | checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" 558 | dependencies = [ 559 | "proc-macro2", 560 | "quote", 561 | "syn 2.0.101", 562 | ] 563 | 564 | [[package]] 565 | name = "typenum" 566 | version = "1.18.0" 567 | source = "registry+https://github.com/rust-lang/crates.io-index" 568 | checksum = "1dccffe3ce07af9386bfd29e80c0ab1a8205a2fc34e4bcd40364df902cfa8f3f" 569 | 570 | [[package]] 571 | name = "unicode-ident" 572 | version = "1.0.18" 573 | source = "registry+https://github.com/rust-lang/crates.io-index" 574 | checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512" 575 | 576 | [[package]] 577 | name = "version_check" 578 | version = "0.9.5" 579 | source = "registry+https://github.com/rust-lang/crates.io-index" 580 | checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" 581 | 582 | [[package]] 583 | name = "vesper-lang" 584 | version = "0.2.1" 585 | source = "registry+https://github.com/rust-lang/crates.io-index" 586 | checksum = "cd2b7e3e27aeb0524204e58042f6e4531a720745d1b1a3978d3a084f1885f63d" 587 | dependencies = [ 588 | "amplify", 589 | "strict_encoding", 590 | ] 591 | 592 | [[package]] 593 | name = "walkdir" 594 | version = "2.5.0" 595 | source = "registry+https://github.com/rust-lang/crates.io-index" 596 | checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" 597 | dependencies = [ 598 | "same-file", 599 | "winapi-util", 600 | ] 601 | 602 | [[package]] 603 | name = "wasi" 604 | version = "0.11.0+wasi-snapshot-preview1" 605 | source = "registry+https://github.com/rust-lang/crates.io-index" 606 | checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" 607 | 608 | [[package]] 609 | name = "wasi" 610 | version = "0.14.2+wasi-0.2.4" 611 | source = "registry+https://github.com/rust-lang/crates.io-index" 612 | checksum = "9683f9a5a998d873c0d21fcbe3c083009670149a8fab228644b8bd36b2c48cb3" 613 | dependencies = [ 614 | "wit-bindgen-rt", 615 | ] 616 | 617 | [[package]] 618 | name = "wasm-bindgen" 619 | version = "0.2.100" 620 | source = "registry+https://github.com/rust-lang/crates.io-index" 621 | checksum = "1edc8929d7499fc4e8f0be2262a241556cfc54a0bea223790e71446f2aab1ef5" 622 | dependencies = [ 623 | "cfg-if", 624 | "once_cell", 625 | "rustversion", 626 | "wasm-bindgen-macro", 627 | ] 628 | 629 | [[package]] 630 | name = "wasm-bindgen-backend" 631 | version = "0.2.100" 632 | source = "registry+https://github.com/rust-lang/crates.io-index" 633 | checksum = "2f0a0651a5c2bc21487bde11ee802ccaf4c51935d0d3d42a6101f98161700bc6" 634 | dependencies = [ 635 | "bumpalo", 636 | "log", 637 | "proc-macro2", 638 | "quote", 639 | "syn 2.0.101", 640 | "wasm-bindgen-shared", 641 | ] 642 | 643 | [[package]] 644 | name = "wasm-bindgen-futures" 645 | version = "0.4.50" 646 | source = "registry+https://github.com/rust-lang/crates.io-index" 647 | checksum = "555d470ec0bc3bb57890405e5d4322cc9ea83cebb085523ced7be4144dac1e61" 648 | dependencies = [ 649 | "cfg-if", 650 | "js-sys", 651 | "once_cell", 652 | "wasm-bindgen", 653 | "web-sys", 654 | ] 655 | 656 | [[package]] 657 | name = "wasm-bindgen-macro" 658 | version = "0.2.100" 659 | source = "registry+https://github.com/rust-lang/crates.io-index" 660 | checksum = "7fe63fc6d09ed3792bd0897b314f53de8e16568c2b3f7982f468c0bf9bd0b407" 661 | dependencies = [ 662 | "quote", 663 | "wasm-bindgen-macro-support", 664 | ] 665 | 666 | [[package]] 667 | name = "wasm-bindgen-macro-support" 668 | version = "0.2.100" 669 | source = "registry+https://github.com/rust-lang/crates.io-index" 670 | checksum = "8ae87ea40c9f689fc23f209965b6fb8a99ad69aeeb0231408be24920604395de" 671 | dependencies = [ 672 | "proc-macro2", 673 | "quote", 674 | "syn 2.0.101", 675 | "wasm-bindgen-backend", 676 | "wasm-bindgen-shared", 677 | ] 678 | 679 | [[package]] 680 | name = "wasm-bindgen-shared" 681 | version = "0.2.100" 682 | source = "registry+https://github.com/rust-lang/crates.io-index" 683 | checksum = "1a05d73b933a847d6cccdda8f838a22ff101ad9bf93e33684f39c1f5f0eece3d" 684 | dependencies = [ 685 | "unicode-ident", 686 | ] 687 | 688 | [[package]] 689 | name = "wasm-bindgen-test" 690 | version = "0.3.50" 691 | source = "registry+https://github.com/rust-lang/crates.io-index" 692 | checksum = "66c8d5e33ca3b6d9fa3b4676d774c5778031d27a578c2b007f905acf816152c3" 693 | dependencies = [ 694 | "js-sys", 695 | "minicov", 696 | "wasm-bindgen", 697 | "wasm-bindgen-futures", 698 | "wasm-bindgen-test-macro", 699 | ] 700 | 701 | [[package]] 702 | name = "wasm-bindgen-test-macro" 703 | version = "0.3.50" 704 | source = "registry+https://github.com/rust-lang/crates.io-index" 705 | checksum = "17d5042cc5fa009658f9a7333ef24291b1291a25b6382dd68862a7f3b969f69b" 706 | dependencies = [ 707 | "proc-macro2", 708 | "quote", 709 | "syn 2.0.101", 710 | ] 711 | 712 | [[package]] 713 | name = "web-sys" 714 | version = "0.3.77" 715 | source = "registry+https://github.com/rust-lang/crates.io-index" 716 | checksum = "33b6dd2ef9186f1f2072e409e99cd22a975331a6b3591b12c764e0e55c60d5d2" 717 | dependencies = [ 718 | "js-sys", 719 | "wasm-bindgen", 720 | ] 721 | 722 | [[package]] 723 | name = "winapi-util" 724 | version = "0.1.9" 725 | source = "registry+https://github.com/rust-lang/crates.io-index" 726 | checksum = "cf221c93e13a30d793f7645a0e7762c55d169dbb0a49671918a2319d289b10bb" 727 | dependencies = [ 728 | "windows-sys", 729 | ] 730 | 731 | [[package]] 732 | name = "windows-sys" 733 | version = "0.59.0" 734 | source = "registry+https://github.com/rust-lang/crates.io-index" 735 | checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" 736 | dependencies = [ 737 | "windows-targets", 738 | ] 739 | 740 | [[package]] 741 | name = "windows-targets" 742 | version = "0.52.6" 743 | source = "registry+https://github.com/rust-lang/crates.io-index" 744 | checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" 745 | dependencies = [ 746 | "windows_aarch64_gnullvm", 747 | "windows_aarch64_msvc", 748 | "windows_i686_gnu", 749 | "windows_i686_gnullvm", 750 | "windows_i686_msvc", 751 | "windows_x86_64_gnu", 752 | "windows_x86_64_gnullvm", 753 | "windows_x86_64_msvc", 754 | ] 755 | 756 | [[package]] 757 | name = "windows_aarch64_gnullvm" 758 | version = "0.52.6" 759 | source = "registry+https://github.com/rust-lang/crates.io-index" 760 | checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" 761 | 762 | [[package]] 763 | name = "windows_aarch64_msvc" 764 | version = "0.52.6" 765 | source = "registry+https://github.com/rust-lang/crates.io-index" 766 | checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" 767 | 768 | [[package]] 769 | name = "windows_i686_gnu" 770 | version = "0.52.6" 771 | source = "registry+https://github.com/rust-lang/crates.io-index" 772 | checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" 773 | 774 | [[package]] 775 | name = "windows_i686_gnullvm" 776 | version = "0.52.6" 777 | source = "registry+https://github.com/rust-lang/crates.io-index" 778 | checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" 779 | 780 | [[package]] 781 | name = "windows_i686_msvc" 782 | version = "0.52.6" 783 | source = "registry+https://github.com/rust-lang/crates.io-index" 784 | checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" 785 | 786 | [[package]] 787 | name = "windows_x86_64_gnu" 788 | version = "0.52.6" 789 | source = "registry+https://github.com/rust-lang/crates.io-index" 790 | checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" 791 | 792 | [[package]] 793 | name = "windows_x86_64_gnullvm" 794 | version = "0.52.6" 795 | source = "registry+https://github.com/rust-lang/crates.io-index" 796 | checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" 797 | 798 | [[package]] 799 | name = "windows_x86_64_msvc" 800 | version = "0.52.6" 801 | source = "registry+https://github.com/rust-lang/crates.io-index" 802 | checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" 803 | 804 | [[package]] 805 | name = "wit-bindgen-rt" 806 | version = "0.39.0" 807 | source = "registry+https://github.com/rust-lang/crates.io-index" 808 | checksum = "6f42320e61fe2cfd34354ecb597f86f413484a798ba44a8ca1165c58d42da6c1" 809 | dependencies = [ 810 | "bitflags", 811 | ] 812 | 813 | [[package]] 814 | name = "zerocopy" 815 | version = "0.8.25" 816 | source = "registry+https://github.com/rust-lang/crates.io-index" 817 | checksum = "a1702d9583232ddb9174e01bb7c15a2ab8fb1bc6f227aa1233858c351a3ba0cb" 818 | dependencies = [ 819 | "zerocopy-derive", 820 | ] 821 | 822 | [[package]] 823 | name = "zerocopy-derive" 824 | version = "0.8.25" 825 | source = "registry+https://github.com/rust-lang/crates.io-index" 826 | checksum = "28a6e20d751156648aa063f3800b706ee209a32c0b4d9f24be3d980b01be55ef" 827 | dependencies = [ 828 | "proc-macro2", 829 | "quote", 830 | "syn 2.0.101", 831 | ] 832 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "aluvm" 3 | description = "Functional registry-based RISC virtual machine" 4 | version = "0.12.0-rc.1" 5 | authors = ["Dr Maxim Orlovsky "] 6 | repository = "https://github.com/aluvm/rust-aluvm" 7 | homepage = "https://aluvm.org" 8 | keywords = ["virtual-machine", "emulator", "functional", "risc", "edge-computing"] 9 | categories = ["no-std", "embedded", "compilers", "cryptography", "emulators"] 10 | rust-version = "1.81.0" # Due to `Error` in `core` 11 | edition = "2021" 12 | license = "Apache-2.0" 13 | readme = "README.md" 14 | exclude = [".github"] 15 | 16 | [lib] 17 | name = "aluvm" 18 | 19 | [[bin]] 20 | name = "aluvm-stl" 21 | required-features = ["stl"] 22 | 23 | [dependencies] 24 | amplify = { version = "~4.9.0", default-features = false, features = ["derive"] } 25 | commit_verify = "0.12.0-rc.1" 26 | strict_encoding = { version = "~2.9.1", default-features = false, features = ["derive"] } 27 | strict_types = { version = "~2.9.0", optional = true } 28 | ascii-armor = { version = "0.9.0", optional = true } 29 | baid64 = "0.4.1" 30 | paste = "1" 31 | serde = { version = "1", optional = true } 32 | 33 | [features] 34 | default = [] 35 | all = ["std", "stl", "log", "armor", "serde"] 36 | 37 | std = ["amplify/std"] 38 | armor = ["dep:ascii-armor", "strict_types/armor"] 39 | stl = ["armor", "strict_types"] 40 | log = [] 41 | alloc = ["amplify/alloc"] 42 | serde = ["dep:serde", "amplify/serde", "strict_encoding/serde"] 43 | 44 | tests = [] # Dedicated feature allowing methods used in tests by downstream crates 45 | 46 | [target.'cfg(target_arch = "wasm32")'.dependencies] 47 | wasm-bindgen = "0.2" 48 | rand = { version = "0.9.1", optional = true } 49 | getrandom = { version = "0.3", features = ["wasm_js"] } 50 | getrandom2 = { package = "getrandom", version = "0.2", features = ["js"] } 51 | 52 | [target.'cfg(target_arch = "wasm32")'.dev-dependencies] 53 | wasm-bindgen-test = "0.3" 54 | 55 | [package.metadata.docs.rs] 56 | features = ["all"] 57 | 58 | [lints.rust] 59 | unexpected_cfgs = { level = "allow", check-cfg = ['cfg(coverage_nightly)'] } 60 | -------------------------------------------------------------------------------- /DCO: -------------------------------------------------------------------------------- 1 | Developer's Certificate of Origin 1.1 2 | Copyright © 2004, 2006 The Linux Foundation and its contributors. 3 | 4 | --- 5 | 6 | By making a contribution to this project, I certify that: 7 | 8 | (a) The contribution was created in whole or in part by me and I 9 | have the right to submit it under the open source license 10 | indicated in the file; or 11 | 12 | (b) The contribution is based upon previous work that, to the best 13 | of my knowledge, is covered under an appropriate open source 14 | license and I have the right under that license to submit that 15 | work with modifications, whether created in whole or in part 16 | by me, under the same open source license (unless I am 17 | permitted to submit under a different license), as indicated 18 | in the file; or 19 | 20 | (c) The contribution was provided directly to me by some other 21 | person who certified (a), (b) or (c) and I have not modified 22 | it. 23 | 24 | (d) I understand and agree that this project and the contribution 25 | are public and that a record of the contribution (including all 26 | personal information I submit with it, including my sign-off) is 27 | maintained indefinitely and may be redistributed consistent with 28 | this project or the open source license(s) involved. 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 | -------------------------------------------------------------------------------- /MAINTAINERS.md: -------------------------------------------------------------------------------- 1 | The project is maintained by Laboratories for Ubiquitous Deterministic Computing (UBIDECO), 2 | Institute for Distributed and Cognitive Systems (InDCS), Switzerland. 3 | 4 | List of the project maintainers: 5 | 6 | 1. Maxim Orlovsky 7 | 8 | - GitHub: [@dr-orlovsky](https://github.com/dr-orlovsky) 9 | - GPG: `EAE730CEC0C663763F028A5860094BAF18A26EC9` 10 | - SSH: `BoSGFzbyOKC7Jm28MJElFboGepihCpHop60nS8OoG/A` 11 | - EMail: [orlovsky@ubideco.org](mailto:orlovsky@ubideco.org) 12 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # AluVM rust implementation 2 | 3 | ![Build](https://github.com/AluVM/aluvm/workflows/Build/badge.svg) 4 | ![Tests](https://github.com/AluVM/aluvm/workflows/Tests/badge.svg) 5 | ![Lints](https://github.com/AluVM/aluvm/workflows/Lints/badge.svg) 6 | [![codecov](https://codecov.io/gh/AluVM/aluvm/branch/master/graph/badge.svg)](https://codecov.io/gh/AluVM/aluvm) 7 | 8 | [![crates.io](https://img.shields.io/crates/v/aluvm)](https://crates.io/crates/aluvm) 9 | [![Docs](https://docs.rs/aluvm/badge.svg)](https://docs.rs/aluvm) 10 | [![unsafe forbidden](https://img.shields.io/badge/unsafe-forbidden-success.svg)](https://github.com/rust-secure-code/safety-dance/) 11 | [![Apache-2 licensed](https://img.shields.io/crates/l/aluvm)](./LICENSE) 12 | 13 | Rust implementation of AluVM (arithmetic logic unit virtual machine). 14 | 15 | AluVM is a pure functional register-based highly deterministic & exception-less instruction set 16 | architecture (ISA) and virtual machine (VM). The AluVM ISA can be extended by an environment running 17 | the virtual machine (runtime environment), providing ability to load data to the VM registers and 18 | support application-specific instructions (like SIMD). 19 | 20 | The main purpose for ALuVM is to be used in distributed systems whether robustness, 21 | platform-independent determinism are more important than the speed of computation. The main area of 22 | AluVM applications (using appropriate ISA extensions) is blockchain environments, consensus-critical 23 | computations, edge computing, multiparty computing (including deterministic machine learning), 24 | client-side-validation, sandboxed computing and genetic algorithms. 25 | 26 | For more details on AluVM, please check [the specification][AluVM], watch detailed presentation 27 | on [YouTube] or check [slides] from the presentation. 28 | 29 | ## Design 30 | 31 | The robustness lies at the very core of AluVM. It is designed to avoid any undefined behaviour. 32 | Specifically, 33 | 34 | * All registers may be in the undefined state; 35 | * Impossible/incorrect operations put destination register into a special *undefined state*; 36 | * Code always extended to 2^16 bytes with zeros, which corresponds to “set st0 register to false and 37 | stop execution” op-code; 38 | * There are no invalid jump operations; 39 | * There are no invalid instructions; 40 | * Cycles & jumps are counted with 2^16 limit (bounded-time execution); 41 | * No ambiguity: any two distinct byte strings always represent strictly distinct programs; 42 | * Code and embedded data signing; 43 | * Code commits to the used ISA extensions; 44 | * Libraries identified by their hashes; 45 | * Code does not run if not all libraries are present. 46 | 47 | ![Comparison table](doc/comparison.png) 48 | 49 | ## Instruction Set Architecture 50 | 51 | ![Instruction set architecture](doc/isa.png) 52 | 53 | ## History 54 | 55 | - The need for AluVM recognized as a part of RGB project in Mar, the 24 & 31st, 2021 (see developers 56 | call ) 57 | - Concept was presented on 19th of May 2021([check the recoding](https://youtu.be/Mma0oyiVbSE)) 58 | - v0.1 release of Rust AluVM implementation on the 28th of May 2021 59 | ([ISA & API docs](https://docs.rs/aluvm/0.1.0/alure/)) 60 | - v0.2 release with multiple enhancements on the 9 Jun 61 | 2021 ([ISA & API docs](https://docs.rs/aluvm/0.2.1/aluvm/)) – see presentation on [YouTube] or 62 | read [slides] 63 | - At the end of 2024 v0.12 became a complete re-write, abstracting most of the instructions into a 64 | ISA extensions. The remaining core of AluVM become zk-STARK and zk-STARK-compatible, so a 65 | dedicated ISA extensions can be used to create fully arithmetized applications. 66 | 67 | [AluVM]: https://github.com/AluVM/aluvm-spec 68 | 69 | [YouTube]: https://www.youtube.com/watch?v=brfWta7XXFQ 70 | 71 | [slides]: https://github.com/LNP-BP/presentations/blob/master/Presentation%20slides/AluVM.pdf 72 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security 2 | 3 | We take the security of our software products and services seriously, which 4 | includes all source code repositories managed through our GitHub organizations. 5 | 6 | If you believe you have found a security vulnerability in any of our repository 7 | that meets [definition of a security vulnerability][definition], please report 8 | it to us as described below. 9 | 10 | ## Reporting Security Issues 11 | 12 | **Please do not report security vulnerabilities through public GitHub issues.** 13 | 14 | Instead, please report them to the repository maintainers by sending a **GPG 15 | encrypted e-mail** to _all maintainers of a specific repo_ using their GPG keys. 16 | 17 | A list of repository maintainers and their keys and e-mail addresses are 18 | provided inside MAINTAINERS.md file and MANIFEST.yml, with the latter also 19 | included in the README.md as a manifest block, which looks in the following way: 20 | 21 | ```yaml 22 | Name: 23 | ... 24 | Maintained: 25 | Maintainers: 26 | : 27 | GPG: 28 | EMail: 29 | : 30 | ... 31 | ``` 32 | 33 | You should receive a response within 72 hours. If for some reason you do not, 34 | please follow up via email to ensure we received your original message. 35 | 36 | Please include the requested information listed below (as much as you can 37 | provide) to help us better understand the nature and scope of the possible 38 | issue: 39 | 40 | * Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.) 41 | * Full paths of source file(s) related to the manifestation of the issue 42 | * The location of the affected source code (tag/branch/commit or direct URL) 43 | * Any special configuration required to reproduce the issue 44 | * Step-by-step instructions to reproduce the issue 45 | * Proof-of-concept or exploit code (if possible) 46 | * Impact of the issue, including how an attacker might exploit the issue 47 | 48 | This information will help us triage your report more quickly. 49 | 50 | ## Preferred Languages 51 | 52 | We prefer all communications to be in English. 53 | 54 | ## Policy 55 | 56 | We follow the principle of [Coordinated Vulnerability Disclosure][disclosure]. 57 | 58 | [definition]: https://aka.ms/opensource/security/definition 59 | [disclosure]: https://aka.ms/opensource/security/cvd 60 | -------------------------------------------------------------------------------- /_typos.toml: -------------------------------------------------------------------------------- 1 | [files] 2 | # exclude the directory "stl/" 3 | extend-exclude = ["stl/"] 4 | 5 | [default.extend-words] 6 | # Don't correct the name "Jon Atack". 7 | Atack = "Atack" 8 | 9 | [default] 10 | extend-ignore-re = [ 11 | # Don't correct URIs 12 | "([a-z]+:)*[.~0-9A-Za-z-]+", 13 | ] 14 | -------------------------------------------------------------------------------- /codecov.yml: -------------------------------------------------------------------------------- 1 | codecov: 2 | require_ci_to_pass: no 3 | 4 | coverage: 5 | precision: 1 6 | round: nearest 7 | range: "0...95" 8 | status: 9 | project: 10 | default: 11 | threshold: 1% 12 | branches: 13 | - master 14 | patch: 15 | default: 16 | threshold: 1% 17 | only_pulls: true 18 | -------------------------------------------------------------------------------- /doc/comparison.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AluVM/aluvm/b72e543d4373036965323775b6113e05a0b43bef/doc/comparison.png -------------------------------------------------------------------------------- /doc/isa.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AluVM/aluvm/b72e543d4373036965323775b6113e05a0b43bef/doc/isa.png -------------------------------------------------------------------------------- /scripts/typelib.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | cargo run --features stl --bin aluvm-stl -- --stl 4 | cargo run --features stl --bin aluvm-stl -- --sty 5 | cargo run --features stl --bin aluvm-stl -- --sta 6 | -------------------------------------------------------------------------------- /src/bin/aluvm-stl.rs: -------------------------------------------------------------------------------- 1 | // Reference rust implementation of AluVM (arithmetic logic unit virtual machine). 2 | // To find more on AluVM please check 3 | // 4 | // SPDX-License-Identifier: Apache-2.0 5 | // 6 | // Designed in 2021-2025 by Dr Maxim Orlovsky 7 | // Written in 2021-2025 by Dr Maxim Orlovsky 8 | // 9 | // Copyright (C) 2021-2024 LNP/BP Standards Association, Switzerland. 10 | // Copyright (C) 2024-2025 Laboratories for Ubiquitous Deterministic Computing (UBIDECO), 11 | // Institute for Distributed and Cognitive Systems (InDCS), Switzerland. 12 | // Copyright (C) 2021-2025 Dr Maxim Orlovsky. 13 | // All rights under the above copyrights are reserved. 14 | // 15 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 16 | // in compliance with the License. You may obtain a copy of the License at 17 | // 18 | // http://www.apache.org/licenses/LICENSE-2.0 19 | // 20 | // Unless required by applicable law or agreed to in writing, software distributed under the License 21 | // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 22 | // or implied. See the License for the specific language governing permissions and limitations under 23 | // the License. 24 | 25 | #![cfg_attr(coverage_nightly, feature(coverage_attribute), coverage(off))] 26 | 27 | use aluvm::stl; 28 | use strict_types::typelib::parse_args; 29 | 30 | fn main() { 31 | let (format, dir) = parse_args(); 32 | 33 | stl::aluvm_stl() 34 | .serialize( 35 | format, 36 | dir, 37 | "0.1.0", 38 | Some( 39 | " 40 | Description: AluVM data type library 41 | Author: Dr Maxim Orlovsky 42 | Copyright (C) 2024-2025 Laboratories for Ubiquitous Deterministic Computing (UBIDECO), 43 | Institute for Distributed and Cognitive Systems (InDCS), Switzerland. 44 | Copyright (C) 2021-2025 Dr Maxim Orlovsky. 45 | License: Apache-2.0", 46 | ), 47 | ) 48 | .expect("unable to write to the file"); 49 | } 50 | -------------------------------------------------------------------------------- /src/core/core.rs: -------------------------------------------------------------------------------- 1 | // Reference rust implementation of AluVM (arithmetic logic unit virtual machine). 2 | // To find more on AluVM please check 3 | // 4 | // SPDX-License-Identifier: Apache-2.0 5 | // 6 | // Designed in 2021-2025 by Dr Maxim Orlovsky 7 | // Written in 2021-2025 by Dr Maxim Orlovsky 8 | // 9 | // Copyright (C) 2021-2024 LNP/BP Standards Association, Switzerland. 10 | // Copyright (C) 2024-2025 Laboratories for Ubiquitous Deterministic Computing (UBIDECO), 11 | // Institute for Distributed and Cognitive Systems (InDCS), Switzerland. 12 | // Copyright (C) 2021-2025 Dr Maxim Orlovsky. 13 | // All rights under the above copyrights are reserved. 14 | // 15 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 16 | // in compliance with the License. You may obtain a copy of the License at 17 | // 18 | // http://www.apache.org/licenses/LICENSE-2.0 19 | // 20 | // Unless required by applicable law or agreed to in writing, software distributed under the License 21 | // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 22 | // or implied. See the License for the specific language governing permissions and limitations under 23 | // the License. 24 | 25 | use core::fmt::{self, Debug, Formatter}; 26 | 27 | use amplify::confinement::ConfinedVec; 28 | 29 | use super::{Site, SiteId, Status}; 30 | use crate::{Register, LIB_NAME_ALUVM}; 31 | 32 | /// Maximal size of the call stack. 33 | /// 34 | /// Equals to 0xFFFF (i.e., maximum limited by `cy` and `cp` bit size). 35 | pub const CALL_STACK_SIZE_MAX: u16 = 0xFF; 36 | 37 | /// Extension to the AluVM core provided by an ISA. 38 | pub trait CoreExt: Clone + Debug { 39 | /// A type of registers provided by the ISA. 40 | type Reg: Register; 41 | /// A configuration used in initializing the core extension. 42 | type Config: Default; 43 | 44 | /// Constructs the core extensions to be added to AluVM core. 45 | fn with(config: Self::Config) -> Self; 46 | 47 | /// Read the value of a register. 48 | fn get(&self, reg: Self::Reg) -> Option<::Value>; 49 | 50 | /// Clear the register by setting it to `None`. 51 | fn clr(&mut self, reg: Self::Reg); 52 | 53 | /// Set the register to the provided value. 54 | fn set(&mut self, reg: Self::Reg, val: ::Value) { 55 | self.put(reg, Some(val)) 56 | } 57 | 58 | /// Put either a value or None to the register. 59 | fn put(&mut self, reg: Self::Reg, val: Option<::Value>); 60 | 61 | /// Reset the core extension by setting all the registers to `None`. 62 | fn reset(&mut self); 63 | } 64 | 65 | /// A trait for the external part of AluVM core which can operate with core ISA extensions. 66 | pub trait Supercore { 67 | /// An ISA extension subcore. 68 | fn subcore(&self) -> Subcore; 69 | 70 | /// Merge the values generated in the subcore ISA extension with the main core. 71 | fn merge_subcore(&mut self, subcore: Subcore); 72 | } 73 | 74 | /// Registers of a single CPU/VM core. 75 | #[derive(Clone)] 76 | pub struct Core< 77 | Id: SiteId, 78 | Cx: CoreExt, 79 | const CALL_STACK_SIZE: usize = { CALL_STACK_SIZE_MAX as usize }, 80 | > { 81 | /// Halt register. If set to `true`, halts program when `CK` is set to [`Status::Failed`] for 82 | /// the first time. 83 | /// 84 | /// # See also 85 | /// 86 | /// - [`Core::ck`] register 87 | /// - [`Core::cf`] register 88 | pub(super) ch: bool, 89 | 90 | /// Check register, which is set on any failure (accessing register in `None` state, zero 91 | /// division, etc.). Can be reset. 92 | /// 93 | /// # See also 94 | /// 95 | /// - [`Core::ch`] register 96 | /// - [`Core::cf`] register 97 | pub(super) ck: Status, 98 | 99 | /// Failure register, which counts how many times `CK` was set, and can't be reset. 100 | /// 101 | /// # See also 102 | /// 103 | /// - [`Core::ch`] register 104 | /// - [`Core::ck`] register 105 | pub(super) cf: u64, 106 | 107 | /// Test register, which acts as a boolean test result (also a carry flag). 108 | pub(super) co: Status, 109 | 110 | /// Counts number of jumps (possible cycles). The number of jumps is limited by 2^16 per 111 | /// script. 112 | pub(super) cy: u16, 113 | 114 | /// Complexity accumulator / counter. 115 | /// 116 | /// Each instruction has an associated computational complexity level. This register sums 117 | /// the complexity of executed instructions. 118 | /// 119 | /// # See also 120 | /// 121 | /// - [`Core::cy`] register 122 | /// - [`Core::cl`] register 123 | pub(super) ca: u64, 124 | 125 | /// Complexity limit. 126 | /// 127 | /// If this register has a value set, once [`Core::ca`] reaches this value, the VM will stop 128 | /// program execution setting `CK` to a failure. 129 | pub(super) cl: Option, 130 | 131 | /// Call stack. 132 | /// 133 | /// # See also 134 | /// 135 | /// - [`CALL_STACK_SIZE_MAX`] constant 136 | /// - [`Core::cp`] register 137 | pub(super) cs: ConfinedVec, 0, CALL_STACK_SIZE>, 138 | 139 | /// Core extension module. 140 | pub cx: Cx, 141 | } 142 | 143 | /// Configuration for [`Core`] initialization. 144 | #[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Hash, Debug)] 145 | #[derive(StrictType, StrictEncode, StrictDecode)] 146 | #[strict_type(lib = LIB_NAME_ALUVM)] 147 | #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] 148 | pub struct CoreConfig { 149 | /// Initial value for the `CH` register. 150 | pub halt: bool, 151 | /// Initial value for the `CL` register. 152 | pub complexity_lim: Option, 153 | } 154 | 155 | impl Default for CoreConfig { 156 | /// Sets 157 | /// - [`CoreConfig::halt`] to `true`, 158 | /// - [`CoreConfig::complexity_lim`] to `None` 159 | /// 160 | /// # See also 161 | /// 162 | /// - [`CoreConfig::halt`] 163 | /// - [`CoreConfig::complexity_lim`] 164 | fn default() -> Self { CoreConfig { halt: true, complexity_lim: None } } 165 | } 166 | 167 | impl Default 168 | for Core 169 | { 170 | fn default() -> Self { Core::new() } 171 | } 172 | 173 | impl Core { 174 | /// Initializes registers. Sets `CK` to `true`, counters to zero, call stack to empty and the 175 | /// rest of registers to `None` value. 176 | /// 177 | /// An alias for [`Core::with`]`(`[`CoreConfig::default()`]`, Cx::default())`. 178 | #[inline] 179 | pub fn new() -> Self { 180 | assert!(CALL_STACK_SIZE <= CALL_STACK_SIZE_MAX as usize, "Call stack size is too large"); 181 | Core::with(default!(), default!()) 182 | } 183 | 184 | /// Initializes registers using a configuration object [`CoreConfig`]. 185 | pub fn with(config: CoreConfig, cx_config: Cx::Config) -> Self { 186 | assert!(CALL_STACK_SIZE <= CALL_STACK_SIZE_MAX as usize, "Call stack size is too large"); 187 | Core { 188 | ch: config.halt, 189 | ck: Status::Ok, 190 | cf: 0, 191 | co: Status::Ok, 192 | cy: 0, 193 | ca: 0, 194 | cl: config.complexity_lim, 195 | cs: ConfinedVec::with_capacity(CALL_STACK_SIZE), 196 | cx: Cx::with(cx_config), 197 | } 198 | } 199 | 200 | /// Reset the core extension by setting all the registers to `None`. 201 | pub fn reset(&mut self) { 202 | let mut new = Self::new(); 203 | new.ch = self.ch; 204 | new.cl = self.cl; 205 | new.cx.reset(); 206 | *self = new; 207 | } 208 | } 209 | 210 | #[cfg_attr(coverage_nightly, coverage(off))] 211 | impl Debug 212 | for Core 213 | { 214 | fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { 215 | let (sect, reg, val, reset) = if f.alternate() { 216 | ("\x1B[0;4;1m", "\x1B[0;1m", "\x1B[0;32m", "\x1B[0m") 217 | } else { 218 | ("", "", "", "") 219 | }; 220 | 221 | writeln!(f, "{sect}C-regs:{reset}")?; 222 | write!(f, "{reg}CH{reset} {val}{}{reset}, ", self.ch)?; 223 | write!(f, "{reg}CK{reset} {val}{}{reset}, ", self.ck)?; 224 | write!(f, "{reg}CF{reset} {val}{}{reset}, ", self.cf)?; 225 | write!(f, "{reg}CO{reset} {val}{}{reset}, ", self.co)?; 226 | write!(f, "{reg}CY{reset} {val}{}{reset}, ", self.cy)?; 227 | write!(f, "{reg}CA{reset} {val}{}{reset}, ", self.ca)?; 228 | let cl = self 229 | .cl 230 | .map(|v| v.to_string()) 231 | .unwrap_or_else(|| "~".to_string()); 232 | write!(f, "{reg}CL{reset} {val}{cl}{reset}, ")?; 233 | write!(f, "{reg}CP{reset} {val}{}{reset}, ", self.cp())?; 234 | write!(f, "\n{reg}CS{reset} {val}{reset}")?; 235 | for item in &self.cs { 236 | write!(f, "{} ", item)?; 237 | } 238 | writeln!(f)?; 239 | 240 | Debug::fmt(&self.cx, f) 241 | } 242 | } 243 | 244 | impl, Cx2: CoreExt, const CALL_STACK_SIZE: usize> 245 | Supercore> for Core 246 | { 247 | fn subcore(&self) -> Core { 248 | Core { 249 | ch: self.ch, 250 | ck: self.ck, 251 | cf: self.cf, 252 | co: self.co, 253 | cy: self.cy, 254 | ca: self.ca, 255 | cl: self.cl, 256 | cs: self.cs.clone(), 257 | cx: self.cx.subcore(), 258 | } 259 | } 260 | 261 | fn merge_subcore(&mut self, subcore: Core) { 262 | assert_eq!(self.ch, subcore.ch); 263 | self.ck = subcore.ck; 264 | self.co = subcore.co; 265 | self.cf = subcore.cf; 266 | self.cy = subcore.cy; 267 | self.ca = subcore.ca; 268 | assert_eq!(self.cl, subcore.cl); 269 | self.cs = subcore.cs; 270 | self.cx.merge_subcore(subcore.cx); 271 | } 272 | } 273 | -------------------------------------------------------------------------------- /src/core/microcode.rs: -------------------------------------------------------------------------------- 1 | // Reference rust implementation of AluVM (arithmetic logic unit virtual machine). 2 | // To find more on AluVM please check 3 | // 4 | // SPDX-License-Identifier: Apache-2.0 5 | // 6 | // Designed in 2021-2025 by Dr Maxim Orlovsky 7 | // Written in 2021-2025 by Dr Maxim Orlovsky 8 | // 9 | // Copyright (C) 2021-2024 LNP/BP Standards Association, Switzerland. 10 | // Copyright (C) 2024-2025 Laboratories for Ubiquitous Deterministic Computing (UBIDECO), 11 | // Institute for Distributed and Cognitive Systems (InDCS), Switzerland. 12 | // Copyright (C) 2021-2025 Dr Maxim Orlovsky. 13 | // All rights under the above copyrights are reserved. 14 | // 15 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 16 | // in compliance with the License. You may obtain a copy of the License at 17 | // 18 | // http://www.apache.org/licenses/LICENSE-2.0 19 | // 20 | // Unless required by applicable law or agreed to in writing, software distributed under the License 21 | // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 22 | // or implied. See the License for the specific language governing permissions and limitations under 23 | // the License. 24 | 25 | use crate::core::{Core, CoreExt, SiteId, Status}; 26 | use crate::{Register, Site}; 27 | 28 | /// Microcode for flag registers. 29 | impl Core { 30 | /// Read overflow/carry flag. 31 | pub fn co(&self) -> Status { self.co } 32 | 33 | /// Set overflow/carry flag to a value. 34 | pub fn set_co(&mut self, co: Status) { self.co = co; } 35 | 36 | /// Return how many times `ck` was set to a failed state. 37 | pub fn cf(&self) -> u64 { self.cf } 38 | 39 | /// Return `true` if `ck` was in a failed state for at least once. 40 | pub fn has_failed(&self) -> bool { self.cf > 0 } 41 | 42 | /// Return whether check register `ck` is in a failed state. 43 | pub fn ck(&self) -> Status { self.ck } 44 | 45 | /// Set `CK` register to a failed state. 46 | /// 47 | /// Returns whether further execution should be stopped (i.e. `ch` register value). 48 | #[must_use] 49 | pub(crate) fn fail_ck(&mut self) -> bool { 50 | self.ck = Status::Fail; 51 | self.cf += 1; 52 | self.ch 53 | } 54 | 55 | /// Reset `CK` register. 56 | pub fn reset_ck(&mut self) { self.ck = Status::Ok } 57 | 58 | /// Return the size of the call stack. 59 | pub fn cp(&self) -> u16 { self.cs.len() as u16 } 60 | 61 | /// Push a location to a call stack. 62 | /// 63 | /// # Returns 64 | /// 65 | /// Top of the call stack. 66 | pub fn push_cs(&mut self, from: Site) -> Option { 67 | self.cs.push(from).ok()?; 68 | Some(self.cp()) 69 | } 70 | 71 | /// Pops a call stack item. 72 | pub fn pop_cs(&mut self) -> Option> { self.cs.pop() } 73 | 74 | /// Return complexity limit value. 75 | pub fn cl(&self) -> Option { self.cl } 76 | 77 | /// Accumulate complexity value. 78 | /// 79 | /// # Returns 80 | /// 81 | /// Boolean indicating whether the complexity limit is reached. 82 | pub fn acc_complexity(&mut self, complexity: u64) -> bool { 83 | self.ca = self.ca.saturating_add(complexity); 84 | self.cl().map(|lim| self.ca < lim).unwrap_or(true) 85 | } 86 | 87 | /// Get register value. 88 | pub fn get(&self, reg: Cx::Reg) -> Option<::Value> { self.cx.get(reg) } 89 | } 90 | -------------------------------------------------------------------------------- /src/core/mod.rs: -------------------------------------------------------------------------------- 1 | // Reference rust implementation of AluVM (arithmetic logic unit virtual machine). 2 | // To find more on AluVM please check 3 | // 4 | // SPDX-License-Identifier: Apache-2.0 5 | // 6 | // Designed in 2021-2025 by Dr Maxim Orlovsky 7 | // Written in 2021-2025 by Dr Maxim Orlovsky 8 | // 9 | // Copyright (C) 2021-2024 LNP/BP Standards Association, Switzerland. 10 | // Copyright (C) 2024-2025 Laboratories for Ubiquitous Deterministic Computing (UBIDECO), 11 | // Institute for Distributed and Cognitive Systems (InDCS), Switzerland. 12 | // Copyright (C) 2021-2025 Dr Maxim Orlovsky. 13 | // All rights under the above copyrights are reserved. 14 | // 15 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 16 | // in compliance with the License. You may obtain a copy of the License at 17 | // 18 | // http://www.apache.org/licenses/LICENSE-2.0 19 | // 20 | // Unless required by applicable law or agreed to in writing, software distributed under the License 21 | // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 22 | // or implied. See the License for the specific language governing permissions and limitations under 23 | // the License. 24 | 25 | //! AluVM registers system 26 | 27 | #[allow(clippy::module_inception)] 28 | mod core; 29 | mod microcode; 30 | mod util; 31 | 32 | pub use self::core::{Core, CoreConfig, CoreExt, Supercore, CALL_STACK_SIZE_MAX}; 33 | pub use self::util::{NoExt, NoRegs, Register, Site, SiteId, Status}; 34 | -------------------------------------------------------------------------------- /src/core/util.rs: -------------------------------------------------------------------------------- 1 | // Reference rust implementation of AluVM (arithmetic logic unit virtual machine). 2 | // To find more on AluVM please check 3 | // 4 | // SPDX-License-Identifier: Apache-2.0 5 | // 6 | // Designed in 2021-2025 by Dr Maxim Orlovsky 7 | // Written in 2021-2025 by Dr Maxim Orlovsky 8 | // 9 | // Copyright (C) 2021-2024 LNP/BP Standards Association, Switzerland. 10 | // Copyright (C) 2024-2025 Laboratories for Ubiquitous Deterministic Computing (UBIDECO), 11 | // Institute for Distributed and Cognitive Systems (InDCS), Switzerland. 12 | // Copyright (C) 2021-2025 Dr Maxim Orlovsky. 13 | // All rights under the above copyrights are reserved. 14 | // 15 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 16 | // in compliance with the License. You may obtain a copy of the License at 17 | // 18 | // http://www.apache.org/licenses/LICENSE-2.0 19 | // 20 | // Unless required by applicable law or agreed to in writing, software distributed under the License 21 | // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 22 | // or implied. See the License for the specific language governing permissions and limitations under 23 | // the License. 24 | 25 | use core::cmp::Ordering; 26 | use core::fmt::{self, Debug, Display, Formatter}; 27 | use core::ops::Not; 28 | use core::str::FromStr; 29 | 30 | use crate::core::CoreExt; 31 | 32 | /// A trait for a set of registers provided by an ISA extension. 33 | pub trait Register: Copy + Ord + Debug + Display { 34 | /// The value type contained in the registers. 35 | type Value: Copy + Debug + Display; 36 | 37 | /// The size of the value in the register, in bytes. 38 | fn bytes(self) -> u16; 39 | } 40 | 41 | /// Default [`Register`] implementation for ISA extensions providing no new registers. 42 | #[derive(Debug)] 43 | pub enum NoRegs {} 44 | #[allow(clippy::non_canonical_clone_impl)] 45 | impl Clone for NoRegs { 46 | fn clone(&self) -> Self { unreachable!() } 47 | } 48 | impl Copy for NoRegs {} 49 | #[allow(clippy::non_canonical_clone_impl)] 50 | impl PartialEq for NoRegs { 51 | fn eq(&self, _: &Self) -> bool { unreachable!() } 52 | } 53 | impl Eq for NoRegs {} 54 | impl Ord for NoRegs { 55 | fn cmp(&self, _: &Self) -> Ordering { unreachable!() } 56 | } 57 | #[allow(clippy::non_canonical_partial_ord_impl)] 58 | impl PartialOrd for NoRegs { 59 | fn partial_cmp(&self, _: &Self) -> Option { unreachable!() } 60 | } 61 | impl Display for NoRegs { 62 | fn fmt(&self, _: &mut Formatter<'_>) -> fmt::Result { unreachable!() } 63 | } 64 | impl Register for NoRegs { 65 | type Value = u8; 66 | fn bytes(self) -> u16 { unreachable!() } 67 | } 68 | 69 | /// Status for flag registers. 70 | #[derive(Copy, Clone, Eq, PartialEq, Debug, Display)] 71 | #[repr(i8)] 72 | pub enum Status { 73 | /// Flag is not set, indicating absence of failures. 74 | #[display("ok")] 75 | Ok = 0, 76 | 77 | /// Flag is set, indicating a failure. 78 | #[display("fail")] 79 | Fail = -1, 80 | } 81 | 82 | impl Status { 83 | /// Checks if the flag is not set, and no failure has happened. 84 | pub fn is_ok(self) -> bool { self == Status::Ok } 85 | } 86 | 87 | impl Not for Status { 88 | type Output = Status; 89 | 90 | fn not(self) -> Self::Output { 91 | match self { 92 | Status::Ok => Status::Fail, 93 | Status::Fail => Status::Ok, 94 | } 95 | } 96 | } 97 | 98 | /// Trait for program identifiers. 99 | /// 100 | /// This type is required in addition to [`crate::LibId`] in order to achieve proper abstraction, 101 | /// layering, and separation of concerns: the core must know nothing about library structure. 102 | pub trait SiteId: Copy + Ord + Debug + Display + FromStr {} 103 | 104 | /// Location inside the instruction sequence which can be executed by the core. 105 | /// 106 | /// This type is required in addition to [`crate::LibSite`] in order to achieve proper abstraction, 107 | /// layering, and separation of concerns: the core must know nothing about library structure. 108 | #[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug)] 109 | pub struct Site { 110 | /// Identifier of the program. 111 | pub prog_id: Id, 112 | /// Offset in the code segment within the program. 113 | pub offset: u16, 114 | } 115 | 116 | impl Site { 117 | /// Construct a new code site out of program identifier and code offset. 118 | #[inline] 119 | pub fn new(prog_id: Id, offset: u16) -> Self { Self { prog_id, offset } } 120 | } 121 | 122 | impl Display for Site { 123 | fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { 124 | write!(f, "{}@{:04}", self.prog_id, self.offset) 125 | } 126 | } 127 | 128 | /// Helper data structure for base core which has no ISA extensions. 129 | #[derive(Copy, Clone, Eq, PartialEq, Debug)] 130 | pub struct NoExt; 131 | 132 | impl CoreExt for NoExt { 133 | type Reg = NoRegs; 134 | type Config = (); 135 | 136 | fn with(_config: Self::Config) -> Self { NoExt } 137 | 138 | fn get(&self, _reg: Self::Reg) -> Option { unreachable!() } 139 | 140 | fn clr(&mut self, _reg: Self::Reg) { unreachable!() } 141 | 142 | fn put(&mut self, _reg: Self::Reg, _val: Option) { unreachable!() } 143 | 144 | fn reset(&mut self) {} 145 | } 146 | -------------------------------------------------------------------------------- /src/isa/arch.rs: -------------------------------------------------------------------------------- 1 | // Reference rust implementation of AluVM (arithmetic logic unit virtual machine). 2 | // To find more on AluVM please check 3 | // 4 | // SPDX-License-Identifier: Apache-2.0 5 | // 6 | // Designed in 2021-2025 by Dr Maxim Orlovsky 7 | // Written in 2021-2025 by Dr Maxim Orlovsky 8 | // 9 | // Copyright (C) 2021-2024 LNP/BP Standards Association, Switzerland. 10 | // Copyright (C) 2024-2025 Laboratories for Ubiquitous Deterministic Computing (UBIDECO), 11 | // Institute for Distributed and Cognitive Systems (InDCS), Switzerland. 12 | // Copyright (C) 2021-2025 Dr Maxim Orlovsky. 13 | // All rights under the above copyrights are reserved. 14 | // 15 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 16 | // in compliance with the License. You may obtain a copy of the License at 17 | // 18 | // http://www.apache.org/licenses/LICENSE-2.0 19 | // 20 | // Unless required by applicable law or agreed to in writing, software distributed under the License 21 | // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 22 | // or implied. See the License for the specific language governing permissions and limitations under 23 | // the License. 24 | 25 | use core::fmt::Debug; 26 | 27 | use strict_encoding::stl::AlphaCapsNum; 28 | use strict_encoding::{RString, StrictDumb}; 29 | 30 | use super::CtrlInstr; 31 | use crate::core::SiteId; 32 | use crate::LIB_NAME_ALUVM; 33 | 34 | /// Maximal length of the ISA identifier. 35 | pub const ISA_ID_MAX_LEN: usize = 16; 36 | 37 | /// Macro for constructing ISA identifiers 38 | #[macro_export] 39 | macro_rules! isa { 40 | ($id:literal) => { 41 | $crate::IsaId::from($id) 42 | }; 43 | ($id:ident) => { 44 | $crate::IsaId::from($id) 45 | }; 46 | } 47 | 48 | /// ISA identifier. 49 | /// 50 | /// ISA identifier is a capitalized ASCII alphanumeric string, consisting of minimum one character 51 | /// and with a maximal length up to [`ISA_ID_MAX_LEN`]. 52 | #[derive(Wrapper, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug, From)] 53 | #[wrapper(Deref, Display, FromStr)] 54 | #[derive(StrictType, StrictEncode, StrictDecode)] 55 | #[strict_type(lib = LIB_NAME_ALUVM)] 56 | #[cfg_attr(feature = "serde", derive(Serialize, Deserialize), serde(transparent))] 57 | pub struct IsaId(RString); 58 | 59 | impl StrictDumb for IsaId { 60 | fn strict_dumb() -> Self { Self::from("DUMB") } 61 | } 62 | 63 | impl From<&'static str> for IsaId { 64 | fn from(id: &'static str) -> Self { Self(RString::from(id)) } 65 | } 66 | 67 | /// Reserved instruction, which equal to [`crate::ExecStep::Fail`]. 68 | #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Display)] 69 | #[display("halt {0:#02X}.h")] 70 | pub struct ReservedInstr(/** Reserved instruction op code value */ pub(super) u8); 71 | 72 | impl Default for ReservedInstr { 73 | fn default() -> Self { Self(0xFF) } 74 | } 75 | 76 | /// Complete AluVM ISA. 77 | #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Display, From)] 78 | #[display(inner)] 79 | pub enum Instr { 80 | /// Control flow instructions. 81 | #[from] 82 | Ctrl(CtrlInstr), 83 | 84 | // #[cfg(feature = "str")] 85 | // Str(array::instr::StrInstr), 86 | /// Reserved instruction for future use in core `ALU` ISAs. 87 | #[from] 88 | Reserved(ReservedInstr), 89 | } 90 | -------------------------------------------------------------------------------- /src/isa/bytecode.rs: -------------------------------------------------------------------------------- 1 | // Reference rust implementation of AluVM (arithmetic logic unit virtual machine). 2 | // To find more on AluVM please check 3 | // 4 | // SPDX-License-Identifier: Apache-2.0 5 | // 6 | // Designed in 2021-2025 by Dr Maxim Orlovsky 7 | // Written in 2021-2025 by Dr Maxim Orlovsky 8 | // 9 | // Copyright (C) 2021-2024 LNP/BP Standards Association, Switzerland. 10 | // Copyright (C) 2024-2025 Laboratories for Ubiquitous Deterministic Computing (UBIDECO), 11 | // Institute for Distributed and Cognitive Systems (InDCS), Switzerland. 12 | // Copyright (C) 2021-2025 Dr Maxim Orlovsky. 13 | // All rights under the above copyrights are reserved. 14 | // 15 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 16 | // in compliance with the License. You may obtain a copy of the License at 17 | // 18 | // http://www.apache.org/licenses/LICENSE-2.0 19 | // 20 | // Unless required by applicable law or agreed to in writing, software distributed under the License 21 | // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 22 | // or implied. See the License for the specific language governing permissions and limitations under 23 | // the License. 24 | 25 | use core::fmt::Debug; 26 | use core::ops::RangeInclusive; 27 | 28 | use amplify::confinement::SmallBlob; 29 | use amplify::num::{u1, u2, u3, u4, u5, u6, u7}; 30 | 31 | use crate::core::SiteId; 32 | 33 | /// Non-failing byte encoding for the instruction set. 34 | /// 35 | /// We can't use `io` since (1) we are no_std, (2) it operates data with unlimited length (while we 36 | /// are bound by u16), (3) it provides too many fails in situations when we can't fail because of 37 | /// `u16`-bounding and exclusive in-memory encoding handling. 38 | pub trait Bytecode { 39 | /// Returns the range of instruction bytecodes covered by a set of operations. 40 | fn op_range() -> RangeInclusive; 41 | 42 | /// Returns byte representing instruction code (without its arguments). 43 | fn opcode_byte(&self) -> u8; 44 | 45 | /// Returns the number of bytes used by the instruction and its arguments when serialized into 46 | /// the code segment. 47 | fn code_byte_len(&self) -> u16; 48 | 49 | /// If the instruction calls or references any external program, returns a reference to it. 50 | fn external_ref(&self) -> Option; 51 | 52 | /// Write an instruction as bytecode. 53 | fn encode_instr(&self, writer: &mut W) -> Result<(), W::Error> 54 | where W: BytecodeWrite { 55 | writer.write_byte(self.opcode_byte())?; 56 | self.encode_operands(writer)?; 57 | writer.check_aligned(); 58 | Ok(()) 59 | } 60 | 61 | /// Writes an instruction operands as bytecode, omitting opcode byte. 62 | fn encode_operands(&self, writer: &mut W) -> Result<(), W::Error> 63 | where W: BytecodeWrite; 64 | 65 | /// Reads an instruction from bytecode. 66 | fn decode_instr(reader: &mut R) -> Result 67 | where 68 | Self: Sized, 69 | R: BytecodeRead, 70 | { 71 | let opcode = reader.read_byte()?; 72 | let instr = Self::decode_operands(reader, opcode)?; 73 | reader.check_aligned(); 74 | Ok(instr) 75 | } 76 | 77 | /// Reads an instruction operands from bytecode, provided the opcode byte. 78 | fn decode_operands(reader: &mut R, opcode: u8) -> Result 79 | where 80 | Self: Sized, 81 | R: BytecodeRead; 82 | } 83 | 84 | /// Error indicating that an end-of-code segment boundary is reached during read or write operation. 85 | #[derive(Clone, Copy, Ord, PartialOrd, Eq, PartialEq, Hash, Debug, Display, Error)] 86 | #[display("attempt to read or write outside of a code segment (i.e., at position > 0xFFFF)")] 87 | pub struct CodeEofError; 88 | 89 | /// Reader from a bytecode for instruction deserialization. 90 | pub trait BytecodeRead { 91 | /// Return the current byte offset of the cursor. Does not account for bits. 92 | /// If the position is exactly at EOF, returns `None`. 93 | fn pos(&self) -> u16; 94 | /// Set the current cursor byte offset to the provided value if it is less than the underlying 95 | /// buffer length. 96 | /// 97 | /// # Returns 98 | /// 99 | /// Previous position. 100 | fn seek(&mut self, byte_pos: u16) -> Result; 101 | /// Return whether end of the bytecode is reached. 102 | fn is_eof(&self) -> bool; 103 | /// Peek a single byte without moving cursor. 104 | fn peek_byte(&self) -> Result; 105 | 106 | /// Read single bit as a bool value. 107 | fn read_bool(&mut self) -> Result { Ok(self.read_1bit()? == u1::ONE) } 108 | /// Read single bit. 109 | fn read_1bit(&mut self) -> Result; 110 | /// Read two bits. 111 | fn read_2bits(&mut self) -> Result; 112 | /// Read three bits. 113 | fn read_3bits(&mut self) -> Result; 114 | /// Read four bits. 115 | fn read_4bits(&mut self) -> Result; 116 | /// Read five bits. 117 | fn read_5bits(&mut self) -> Result; 118 | /// Read six bits. 119 | fn read_6bits(&mut self) -> Result; 120 | /// Read seven bits. 121 | fn read_7bits(&mut self) -> Result; 122 | 123 | /// Read byte. 124 | fn read_byte(&mut self) -> Result; 125 | /// Read word. 126 | fn read_word(&mut self) -> Result; 127 | 128 | /// Read the fixed number of bytes and convert it into a result type. 129 | /// 130 | /// # Returns 131 | /// 132 | /// Resulting data type and a flag for `CK` registry indicating whether it was possible to read 133 | /// all the data. 134 | fn read_fixed( 135 | &mut self, 136 | f: impl FnOnce([u8; LEN]) -> N, 137 | ) -> Result; 138 | 139 | /// Read variable-length byte string. 140 | /// 141 | /// # Returns 142 | /// 143 | /// Resulting data type and a flag for `CK` registry indicating whether it was possible to read 144 | /// all the data. 145 | fn read_bytes(&mut self) -> Result<(SmallBlob, bool), CodeEofError>; 146 | 147 | /// Read external reference id. 148 | fn read_ref(&mut self) -> Result 149 | where Id: Sized; 150 | 151 | /// Check if the current cursor position is aligned to the next byte. 152 | /// 153 | /// # Panics 154 | /// 155 | /// If the position is not aligned, panics. 156 | fn check_aligned(&self); 157 | } 158 | 159 | /// Writer converting instructions into a bytecode. 160 | pub trait BytecodeWrite { 161 | /// Error type returned during writing procedures. 162 | type Error: Debug; 163 | 164 | /// Write a single bit from a bool value. 165 | fn write_bool(&mut self, data: bool) -> Result<(), Self::Error> { 166 | self.write_1bit(if data { u1::ONE } else { u1::ZERO }) 167 | } 168 | 169 | /// Write a single bit. 170 | fn write_1bit(&mut self, data: u1) -> Result<(), Self::Error>; 171 | /// Write two bits. 172 | fn write_2bits(&mut self, data: u2) -> Result<(), Self::Error>; 173 | /// Write three bits. 174 | fn write_3bits(&mut self, data: u3) -> Result<(), Self::Error>; 175 | /// Write four bits. 176 | fn write_4bits(&mut self, data: u4) -> Result<(), Self::Error>; 177 | /// Write five bits. 178 | fn write_5bits(&mut self, data: u5) -> Result<(), Self::Error>; 179 | /// Write six bits. 180 | fn write_6bits(&mut self, data: u6) -> Result<(), Self::Error>; 181 | /// Write seven bits. 182 | fn write_7bits(&mut self, data: u7) -> Result<(), Self::Error>; 183 | 184 | /// Write byte. 185 | fn write_byte(&mut self, data: u8) -> Result<(), Self::Error>; 186 | /// Write word. 187 | fn write_word(&mut self, data: u16) -> Result<(), Self::Error>; 188 | 189 | /// Write data representable as a fixed-length byte array. 190 | fn write_fixed(&mut self, data: [u8; LEN]) -> Result<(), Self::Error>; 191 | 192 | /// Write variable-length byte string. 193 | fn write_bytes(&mut self, data: &[u8]) -> Result<(), Self::Error>; 194 | 195 | /// Write external reference id. 196 | fn write_ref(&mut self, id: Id) -> Result<(), Self::Error>; 197 | 198 | /// Check if the current cursor position is aligned to the next byte. 199 | /// 200 | /// # Panics 201 | /// 202 | /// If the position is not aligned, panics. 203 | fn check_aligned(&self); 204 | } 205 | -------------------------------------------------------------------------------- /src/isa/ctrl/bytecode.rs: -------------------------------------------------------------------------------- 1 | // Reference rust implementation of AluVM (arithmetic logic unit virtual machine). 2 | // To find more on AluVM please check 3 | // 4 | // SPDX-License-Identifier: Apache-2.0 5 | // 6 | // Designed in 2021-2025 by Dr Maxim Orlovsky 7 | // Written in 2021-2025 by Dr Maxim Orlovsky 8 | // 9 | // Copyright (C) 2021-2024 LNP/BP Standards Association, Switzerland. 10 | // Copyright (C) 2024-2025 Laboratories for Ubiquitous Deterministic Computing (UBIDECO), 11 | // Institute for Distributed and Cognitive Systems (InDCS), Switzerland. 12 | // Copyright (C) 2021-2025 Dr Maxim Orlovsky. 13 | // All rights under the above copyrights are reserved. 14 | // 15 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 16 | // in compliance with the License. You may obtain a copy of the License at 17 | // 18 | // http://www.apache.org/licenses/LICENSE-2.0 19 | // 20 | // Unless required by applicable law or agreed to in writing, software distributed under the License 21 | // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 22 | // or implied. See the License for the specific language governing permissions and limitations under 23 | // the License. 24 | 25 | use core::ops::RangeInclusive; 26 | 27 | use super::CtrlInstr; 28 | use crate::core::SiteId; 29 | use crate::isa::bytecode::CodeEofError; 30 | use crate::isa::{Bytecode, BytecodeRead, BytecodeWrite, Instr, ReservedInstr}; 31 | use crate::Site; 32 | 33 | impl Bytecode for Instr { 34 | fn op_range() -> RangeInclusive { 0..=0xFF } 35 | 36 | fn opcode_byte(&self) -> u8 { 37 | match self { 38 | Instr::Ctrl(instr) => instr.opcode_byte(), 39 | Instr::Reserved(instr) => Bytecode::::opcode_byte(instr), 40 | } 41 | } 42 | 43 | fn code_byte_len(&self) -> u16 { 44 | match self { 45 | Instr::Ctrl(instr) => instr.code_byte_len(), 46 | Instr::Reserved(instr) => Bytecode::::code_byte_len(instr), 47 | } 48 | } 49 | 50 | fn external_ref(&self) -> Option { 51 | match self { 52 | Instr::Ctrl(instr) => instr.external_ref(), 53 | Instr::Reserved(instr) => Bytecode::::external_ref(instr), 54 | } 55 | } 56 | 57 | fn encode_operands(&self, writer: &mut W) -> Result<(), W::Error> 58 | where W: BytecodeWrite { 59 | match self { 60 | Instr::Ctrl(instr) => instr.encode_operands(writer), 61 | Instr::Reserved(instr) => instr.encode_operands(writer), 62 | } 63 | } 64 | 65 | fn decode_operands(reader: &mut R, opcode: u8) -> Result 66 | where 67 | Self: Sized, 68 | R: BytecodeRead, 69 | { 70 | match opcode { 71 | op if CtrlInstr::::op_range().contains(&op) => { 72 | CtrlInstr::::decode_operands(reader, op).map(Self::Ctrl) 73 | } 74 | _ => ReservedInstr::decode_operands(reader, opcode).map(Self::Reserved), 75 | } 76 | } 77 | } 78 | 79 | impl Bytecode for ReservedInstr { 80 | fn op_range() -> RangeInclusive { 0..=0x7F } 81 | 82 | fn opcode_byte(&self) -> u8 { self.0 } 83 | 84 | fn code_byte_len(&self) -> u16 { 1 } 85 | 86 | fn external_ref(&self) -> Option { None } 87 | 88 | fn encode_operands(&self, _writer: &mut W) -> Result<(), W::Error> 89 | where W: BytecodeWrite { 90 | Ok(()) 91 | } 92 | 93 | fn decode_operands(_reader: &mut R, opcode: u8) -> Result 94 | where 95 | Self: Sized, 96 | R: BytecodeRead, 97 | { 98 | Ok(ReservedInstr(opcode)) 99 | } 100 | } 101 | 102 | #[allow(missing_docs)] 103 | impl CtrlInstr { 104 | const START: u8 = 0; 105 | const END: u8 = Self::START + Self::STOP; 106 | 107 | pub const NOP: u8 = 0; 108 | pub const NOCO: u8 = 1; 109 | pub const CHCO: u8 = 2; 110 | pub const CHCK: u8 = 3; 111 | pub const FAIL: u8 = 4; 112 | pub const RSET: u8 = 5; 113 | pub const JMP: u8 = 6; 114 | pub const JINE: u8 = 7; 115 | pub const JIFAIL: u8 = 8; 116 | pub const SH: u8 = 9; 117 | pub const SHNE: u8 = 10; 118 | pub const SHFAIL: u8 = 11; 119 | pub const EXEC: u8 = 12; 120 | pub const FN: u8 = 13; 121 | pub const CALL: u8 = 14; 122 | pub const RET: u8 = 15; 123 | pub const STOP: u8 = 16; 124 | } 125 | 126 | impl Bytecode for CtrlInstr { 127 | fn op_range() -> RangeInclusive { Self::START..=Self::END } 128 | 129 | fn opcode_byte(&self) -> u8 { 130 | match self { 131 | CtrlInstr::Nop => Self::NOP, 132 | CtrlInstr::ChkCo => Self::CHCO, 133 | CtrlInstr::ChkCk => Self::CHCK, 134 | CtrlInstr::NotCo => Self::NOCO, 135 | CtrlInstr::FailCk => Self::FAIL, 136 | CtrlInstr::RsetCk => Self::RSET, 137 | CtrlInstr::Jmp { .. } => Self::JMP, 138 | CtrlInstr::JiOvfl { .. } => Self::JINE, 139 | CtrlInstr::JiFail { .. } => Self::JIFAIL, 140 | CtrlInstr::Sh { .. } => Self::SH, 141 | CtrlInstr::ShOvfl { .. } => Self::SHNE, 142 | CtrlInstr::ShFail { .. } => Self::SHFAIL, 143 | CtrlInstr::Exec { .. } => Self::EXEC, 144 | CtrlInstr::Fn { .. } => Self::FN, 145 | CtrlInstr::Call { .. } => Self::CALL, 146 | CtrlInstr::Ret => Self::RET, 147 | CtrlInstr::Stop => Self::STOP, 148 | } 149 | } 150 | 151 | fn code_byte_len(&self) -> u16 { 152 | let arg_bytes = match self { 153 | CtrlInstr::Nop 154 | | CtrlInstr::ChkCo 155 | | CtrlInstr::ChkCk 156 | | CtrlInstr::NotCo 157 | | CtrlInstr::FailCk 158 | | CtrlInstr::RsetCk => 0, 159 | CtrlInstr::Jmp { pos: _ } 160 | | CtrlInstr::JiOvfl { pos: _ } 161 | | CtrlInstr::JiFail { pos: _ } 162 | | CtrlInstr::Fn { pos: _ } => 2, 163 | CtrlInstr::Sh { shift: _ } 164 | | CtrlInstr::ShOvfl { shift: _ } 165 | | CtrlInstr::ShFail { shift: _ } => 1, 166 | CtrlInstr::Exec { site: _ } | CtrlInstr::Call { site: _ } => 3, 167 | CtrlInstr::Ret | CtrlInstr::Stop => 0, 168 | }; 169 | arg_bytes + 1 170 | } 171 | 172 | fn external_ref(&self) -> Option { 173 | match *self { 174 | CtrlInstr::Nop 175 | | CtrlInstr::ChkCo 176 | | CtrlInstr::ChkCk 177 | | CtrlInstr::FailCk 178 | | CtrlInstr::RsetCk 179 | | CtrlInstr::NotCo 180 | | CtrlInstr::Ret 181 | | CtrlInstr::Stop => None, 182 | 183 | CtrlInstr::Jmp { pos: _ } 184 | | CtrlInstr::JiOvfl { pos: _ } 185 | | CtrlInstr::JiFail { pos: _ } 186 | | CtrlInstr::Fn { pos: _ } => None, 187 | CtrlInstr::Sh { shift: _ } 188 | | CtrlInstr::ShOvfl { shift: _ } 189 | | CtrlInstr::ShFail { shift: _ } => None, 190 | CtrlInstr::Call { site } | CtrlInstr::Exec { site } => Some(site.prog_id), 191 | } 192 | } 193 | 194 | fn encode_operands(&self, writer: &mut W) -> Result<(), W::Error> 195 | where W: BytecodeWrite { 196 | match *self { 197 | CtrlInstr::Nop 198 | | CtrlInstr::ChkCo 199 | | CtrlInstr::ChkCk 200 | | CtrlInstr::FailCk 201 | | CtrlInstr::RsetCk 202 | | CtrlInstr::NotCo 203 | | CtrlInstr::Ret 204 | | CtrlInstr::Stop => {} 205 | 206 | CtrlInstr::Jmp { pos } 207 | | CtrlInstr::JiOvfl { pos } 208 | | CtrlInstr::JiFail { pos } 209 | | CtrlInstr::Fn { pos } => writer.write_word(pos)?, 210 | CtrlInstr::Sh { shift } | CtrlInstr::ShOvfl { shift } | CtrlInstr::ShFail { shift } => { 211 | writer.write_byte(shift.to_le_bytes()[0])? 212 | } 213 | CtrlInstr::Call { site } | CtrlInstr::Exec { site } => { 214 | let site = Site::new(site.prog_id, site.offset); 215 | writer.write_ref(site.prog_id)?; 216 | writer.write_word(site.offset)?; 217 | } 218 | } 219 | Ok(()) 220 | } 221 | 222 | fn decode_operands(reader: &mut R, opcode: u8) -> Result 223 | where 224 | Self: Sized, 225 | R: BytecodeRead, 226 | { 227 | Ok(match opcode { 228 | Self::NOP => Self::Nop, 229 | Self::CHCO => Self::ChkCo, 230 | Self::CHCK => Self::ChkCk, 231 | Self::FAIL => Self::FailCk, 232 | Self::RSET => Self::RsetCk, 233 | Self::NOCO => Self::NotCo, 234 | Self::RET => Self::Ret, 235 | Self::STOP => Self::Stop, 236 | 237 | Self::JMP => CtrlInstr::Jmp { pos: reader.read_word()? }, 238 | Self::JINE => CtrlInstr::JiOvfl { pos: reader.read_word()? }, 239 | Self::JIFAIL => CtrlInstr::JiFail { pos: reader.read_word()? }, 240 | Self::FN => CtrlInstr::Fn { pos: reader.read_word()? }, 241 | 242 | Self::SH => CtrlInstr::Sh { shift: i8::from_le_bytes([reader.read_byte()?]) }, 243 | Self::SHNE => CtrlInstr::ShOvfl { shift: i8::from_le_bytes([reader.read_byte()?]) }, 244 | Self::SHFAIL => CtrlInstr::ShFail { shift: i8::from_le_bytes([reader.read_byte()?]) }, 245 | 246 | Self::CALL => { 247 | let prog_id = reader.read_ref()?; 248 | let offset = reader.read_word()?; 249 | let site = Site::new(prog_id, offset); 250 | CtrlInstr::Call { site } 251 | } 252 | Self::EXEC => { 253 | let prog_id = reader.read_ref()?; 254 | let offset = reader.read_word()?; 255 | let site = Site::new(prog_id, offset); 256 | CtrlInstr::Exec { site } 257 | } 258 | 259 | _ => unreachable!(), 260 | }) 261 | } 262 | } 263 | 264 | #[cfg(test)] 265 | mod test { 266 | #![cfg_attr(coverage_nightly, coverage(off))] 267 | use core::str::FromStr; 268 | 269 | use amplify::confinement::SmallBlob; 270 | 271 | use super::*; 272 | use crate::library::{LibId, LibsSeg, Marshaller}; 273 | 274 | const LIB_ID: &str = "5iMb1eHJ-bN5BOe6-9RvBjYL-jF1ELjj-VV7c8Bm-WvFen1Q"; 275 | 276 | fn roundtrip(instr: impl Into>, bytecode: impl AsRef<[u8]>) -> SmallBlob { 277 | let instr = instr.into(); 278 | let mut libs = LibsSeg::new(); 279 | libs.push(LibId::from_str(LIB_ID).unwrap()).unwrap(); 280 | let mut marshaller = Marshaller::new(&libs); 281 | instr.encode_instr(&mut marshaller).unwrap(); 282 | let (code, data) = marshaller.finish(); 283 | assert_eq!(code.len(), instr.code_byte_len() as usize); 284 | assert_eq!(code.as_slice(), bytecode.as_ref()); 285 | let mut marshaller = Marshaller::with(code, data, &libs); 286 | let decoded = Instr::::decode_instr(&mut marshaller).unwrap(); 287 | assert_eq!(decoded, instr); 288 | marshaller.into_code_data().1 289 | } 290 | 291 | #[test] 292 | fn nop() { 293 | let instr = Instr::::Ctrl(CtrlInstr::Nop); 294 | roundtrip(instr, [CtrlInstr::::NOP]); 295 | assert_eq!(instr.code_byte_len(), 1); 296 | assert_eq!(instr.opcode_byte(), CtrlInstr::::NOP); 297 | assert_eq!(instr.external_ref(), None); 298 | } 299 | 300 | #[test] 301 | fn chk() { 302 | let instr = Instr::::Ctrl(CtrlInstr::ChkCk); 303 | roundtrip(instr, [CtrlInstr::::CHCK]); 304 | assert_eq!(instr.code_byte_len(), 1); 305 | assert_eq!(instr.opcode_byte(), CtrlInstr::::CHCK); 306 | assert_eq!(instr.external_ref(), None); 307 | } 308 | 309 | #[test] 310 | fn not_co() { 311 | let instr = Instr::::Ctrl(CtrlInstr::NotCo); 312 | roundtrip(instr, [CtrlInstr::::NOCO]); 313 | assert_eq!(instr.code_byte_len(), 1); 314 | assert_eq!(instr.opcode_byte(), CtrlInstr::::NOCO); 315 | assert_eq!(instr.external_ref(), None); 316 | } 317 | 318 | #[test] 319 | fn fail_ck() { 320 | let instr = Instr::::Ctrl(CtrlInstr::FailCk); 321 | roundtrip(instr, [CtrlInstr::::FAIL]); 322 | assert_eq!(instr.code_byte_len(), 1); 323 | assert_eq!(instr.opcode_byte(), CtrlInstr::::FAIL); 324 | assert_eq!(instr.external_ref(), None); 325 | } 326 | 327 | #[test] 328 | fn reset_ck() { 329 | let instr = Instr::::Ctrl(CtrlInstr::RsetCk); 330 | roundtrip(instr, [CtrlInstr::::RSET]); 331 | assert_eq!(instr.code_byte_len(), 1); 332 | assert_eq!(instr.opcode_byte(), CtrlInstr::::RSET); 333 | assert_eq!(instr.external_ref(), None); 334 | } 335 | 336 | #[test] 337 | fn jmp() { 338 | let instr = Instr::::Ctrl(CtrlInstr::Jmp { pos: 0x75AE }); 339 | roundtrip(instr, [CtrlInstr::::JMP, 0xAE, 0x75]); 340 | assert_eq!(instr.code_byte_len(), 3); 341 | assert_eq!(instr.opcode_byte(), CtrlInstr::::JMP); 342 | assert_eq!(instr.external_ref(), None); 343 | } 344 | 345 | #[test] 346 | fn jine() { 347 | let instr = Instr::::Ctrl(CtrlInstr::JiOvfl { pos: 0x75AE }); 348 | roundtrip(instr, [CtrlInstr::::JINE, 0xAE, 0x75]); 349 | assert_eq!(instr.code_byte_len(), 3); 350 | assert_eq!(instr.opcode_byte(), CtrlInstr::::JINE); 351 | assert_eq!(instr.external_ref(), None); 352 | } 353 | 354 | #[test] 355 | fn jifail() { 356 | let instr = Instr::::Ctrl(CtrlInstr::JiFail { pos: 0x75AE }); 357 | roundtrip(instr, [CtrlInstr::::JIFAIL, 0xAE, 0x75]); 358 | assert_eq!(instr.code_byte_len(), 3); 359 | assert_eq!(instr.opcode_byte(), CtrlInstr::::JIFAIL); 360 | assert_eq!(instr.external_ref(), None); 361 | } 362 | 363 | #[test] 364 | fn sh() { 365 | let instr = Instr::::Ctrl(CtrlInstr::Sh { shift: -0x5 }); 366 | roundtrip(instr, [CtrlInstr::::SH, 255 - 5 + 1]); 367 | assert_eq!(instr.code_byte_len(), 2); 368 | assert_eq!(instr.opcode_byte(), CtrlInstr::::SH); 369 | assert_eq!(instr.external_ref(), None); 370 | } 371 | 372 | #[test] 373 | fn shne() { 374 | let instr = Instr::::Ctrl(CtrlInstr::ShOvfl { shift: -0x5 }); 375 | roundtrip(instr, [CtrlInstr::::SHNE, 255 - 5 + 1]); 376 | assert_eq!(instr.code_byte_len(), 2); 377 | assert_eq!(instr.opcode_byte(), CtrlInstr::::SHNE); 378 | assert_eq!(instr.external_ref(), None); 379 | } 380 | 381 | #[test] 382 | fn shfail() { 383 | let instr = Instr::::Ctrl(CtrlInstr::ShFail { shift: -0x5 }); 384 | roundtrip(instr, [CtrlInstr::::SHFAIL, 255 - 5 + 1]); 385 | assert_eq!(instr.code_byte_len(), 2); 386 | assert_eq!(instr.opcode_byte(), CtrlInstr::::SHFAIL); 387 | assert_eq!(instr.external_ref(), None); 388 | } 389 | 390 | #[test] 391 | fn exec() { 392 | let lib_id = LibId::from_str(LIB_ID).unwrap(); 393 | let instr = Instr::::Ctrl(CtrlInstr::Exec { site: Site::new(lib_id, 0x69AB) }); 394 | roundtrip(instr, [CtrlInstr::::EXEC, 0x00, 0xAB, 0x69]); 395 | assert_eq!(instr.code_byte_len(), 4); 396 | assert_eq!(instr.opcode_byte(), CtrlInstr::::EXEC); 397 | assert_eq!(instr.external_ref(), Some(lib_id)); 398 | } 399 | 400 | #[test] 401 | fn func() { 402 | let instr = Instr::::Ctrl(CtrlInstr::Fn { pos: 0x75AE }); 403 | roundtrip(instr, [CtrlInstr::::FN, 0xAE, 0x75]); 404 | assert_eq!(instr.code_byte_len(), 3); 405 | assert_eq!(instr.opcode_byte(), CtrlInstr::::FN); 406 | assert_eq!(instr.external_ref(), None); 407 | } 408 | 409 | #[test] 410 | fn call() { 411 | let lib_id = LibId::from_str(LIB_ID).unwrap(); 412 | let instr = Instr::::Ctrl(CtrlInstr::Call { site: Site::new(lib_id, 0x69AB) }); 413 | roundtrip(instr, [CtrlInstr::::CALL, 0x00, 0xAB, 0x69]); 414 | assert_eq!(instr.code_byte_len(), 4); 415 | assert_eq!(instr.opcode_byte(), CtrlInstr::::CALL); 416 | assert_eq!(instr.external_ref(), Some(lib_id)); 417 | } 418 | 419 | #[test] 420 | fn ret() { 421 | let instr = Instr::::Ctrl(CtrlInstr::Ret); 422 | roundtrip(instr, [CtrlInstr::::RET]); 423 | assert_eq!(instr.code_byte_len(), 1); 424 | assert_eq!(instr.opcode_byte(), CtrlInstr::::RET); 425 | assert_eq!(instr.external_ref(), None); 426 | } 427 | 428 | #[test] 429 | fn stop() { 430 | let instr = Instr::::Ctrl(CtrlInstr::Stop); 431 | roundtrip(instr, [CtrlInstr::::STOP]); 432 | assert_eq!(instr.code_byte_len(), 1); 433 | assert_eq!(instr.opcode_byte(), CtrlInstr::::STOP); 434 | assert_eq!(instr.external_ref(), None); 435 | } 436 | 437 | #[test] 438 | fn reserved() { 439 | let instr = Instr::::Reserved(default!()); 440 | roundtrip(instr, [0xFF]); 441 | 442 | assert_eq!(instr.code_byte_len(), 1); 443 | assert_eq!(instr.opcode_byte(), 0xFF); 444 | assert_eq!(instr.external_ref(), None); 445 | } 446 | } 447 | -------------------------------------------------------------------------------- /src/isa/ctrl/instr.rs: -------------------------------------------------------------------------------- 1 | // Reference rust implementation of AluVM (arithmetic logic unit virtual machine). 2 | // To find more on AluVM please check 3 | // 4 | // SPDX-License-Identifier: Apache-2.0 5 | // 6 | // Designed in 2021-2025 by Dr Maxim Orlovsky 7 | // Written in 2021-2025 by Dr Maxim Orlovsky 8 | // 9 | // Copyright (C) 2021-2024 LNP/BP Standards Association, Switzerland. 10 | // Copyright (C) 2024-2025 Laboratories for Ubiquitous Deterministic Computing (UBIDECO), 11 | // Institute for Distributed and Cognitive Systems (InDCS), Switzerland. 12 | // Copyright (C) 2021-2025 Dr Maxim Orlovsky. 13 | // All rights under the above copyrights are reserved. 14 | // 15 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 16 | // in compliance with the License. You may obtain a copy of the License at 17 | // 18 | // http://www.apache.org/licenses/LICENSE-2.0 19 | // 20 | // Unless required by applicable law or agreed to in writing, software distributed under the License 21 | // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 22 | // or implied. See the License for the specific language governing permissions and limitations under 23 | // the License. 24 | 25 | use crate::core::SiteId; 26 | use crate::Site; 27 | 28 | /// Control flow instructions. 29 | #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Display)] 30 | #[display(inner)] 31 | pub enum CtrlInstr { 32 | /// Not an operation. 33 | #[display("nop")] 34 | Nop, 35 | 36 | /// Test `CO` value, terminates if set to true. 37 | #[display("chk CO")] 38 | ChkCo, 39 | 40 | /// Test `CK` value, terminates if in a failed state. 41 | #[display("chk CK")] 42 | ChkCk, 43 | 44 | /// Invert `CO` register. 45 | #[display("not CO")] 46 | NotCo, 47 | 48 | /// Set `CK` register to a failed state. 49 | #[display("fail CK")] 50 | FailCk, 51 | 52 | /// Assigns `CK` value to `CO` resister and sets `CK` to a non-failed state. 53 | #[display("mov CO, CK")] 54 | RsetCk, 55 | 56 | /// Jump to location (unconditionally). 57 | #[display("jmp {pos}")] 58 | Jmp { 59 | /** Target position to jump to */ 60 | pos: u16, 61 | }, 62 | 63 | /// Jump to location if `CO` is in a failed state. 64 | #[display("jif CO, {pos}")] 65 | JiOvfl { 66 | /** Target position to jump to */ 67 | pos: u16, 68 | }, 69 | 70 | /// Jump to location if `CK` is in a failed state. 71 | #[display("jif CK, {pos}")] 72 | JiFail { 73 | /** Target position to jump to */ 74 | pos: u16, 75 | }, 76 | 77 | /// Relative jump. 78 | #[display("jmp {shift:+}")] 79 | Sh { 80 | /** Number of bytes for the relative shift */ 81 | shift: i8, 82 | }, 83 | 84 | /// Relative jump if `CO` is in a failed state. 85 | #[display("jif CO, {shift:+}")] 86 | ShOvfl { 87 | /** Number of bytes for the relative shift */ 88 | shift: i8, 89 | }, 90 | 91 | /// Relative jump if `CK` is in a failed state. 92 | #[display("jif CK, {shift:+}")] 93 | ShFail { 94 | /** Number of bytes for the relative shift */ 95 | shift: i8, 96 | }, 97 | 98 | /// External jump. 99 | #[display("jmp {site}")] 100 | Exec { 101 | /** Target site to jump to */ 102 | site: Site, 103 | }, 104 | 105 | /// Subroutine call. 106 | #[display("call {pos}")] 107 | Fn { 108 | /** Target position for the function jump */ 109 | pos: u16, 110 | }, 111 | 112 | /// External subroutine call. 113 | #[display("call {site}")] 114 | Call { 115 | /** Target site */ 116 | site: Site, 117 | }, 118 | 119 | /// Return from a subroutine or finish the program. 120 | #[display("ret")] 121 | Ret, 122 | 123 | /// Stop the program. 124 | #[display("stop")] 125 | Stop, 126 | } 127 | -------------------------------------------------------------------------------- /src/isa/ctrl/mod.rs: -------------------------------------------------------------------------------- 1 | // Reference rust implementation of AluVM (arithmetic logic unit virtual machine). 2 | // To find more on AluVM please check 3 | // 4 | // SPDX-License-Identifier: Apache-2.0 5 | // 6 | // Designed in 2021-2025 by Dr Maxim Orlovsky 7 | // Written in 2021-2025 by Dr Maxim Orlovsky 8 | // 9 | // Copyright (C) 2021-2024 LNP/BP Standards Association, Switzerland. 10 | // Copyright (C) 2024-2025 Laboratories for Ubiquitous Deterministic Computing (UBIDECO), 11 | // Institute for Distributed and Cognitive Systems (InDCS), Switzerland. 12 | // Copyright (C) 2021-2025 Dr Maxim Orlovsky. 13 | // All rights under the above copyrights are reserved. 14 | // 15 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 16 | // in compliance with the License. You may obtain a copy of the License at 17 | // 18 | // http://www.apache.org/licenses/LICENSE-2.0 19 | // 20 | // Unless required by applicable law or agreed to in writing, software distributed under the License 21 | // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 22 | // or implied. See the License for the specific language governing permissions and limitations under 23 | // the License. 24 | 25 | //! ALU64 instruction set architecture. 26 | 27 | mod bytecode; 28 | mod instr; 29 | mod exec; 30 | 31 | pub use instr::CtrlInstr; 32 | -------------------------------------------------------------------------------- /src/isa/instr.rs: -------------------------------------------------------------------------------- 1 | // Reference rust implementation of AluVM (arithmetic logic unit virtual machine). 2 | // To find more on AluVM please check 3 | // 4 | // SPDX-License-Identifier: Apache-2.0 5 | // 6 | // Designed in 2021-2025 by Dr Maxim Orlovsky 7 | // Written in 2021-2025 by Dr Maxim Orlovsky 8 | // 9 | // Copyright (C) 2021-2024 LNP/BP Standards Association, Switzerland. 10 | // Copyright (C) 2024-2025 Laboratories for Ubiquitous Deterministic Computing (UBIDECO), 11 | // Institute for Distributed and Cognitive Systems (InDCS), Switzerland. 12 | // Copyright (C) 2021-2025 Dr Maxim Orlovsky. 13 | // All rights under the above copyrights are reserved. 14 | // 15 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 16 | // in compliance with the License. You may obtain a copy of the License at 17 | // 18 | // http://www.apache.org/licenses/LICENSE-2.0 19 | // 20 | // Unless required by applicable law or agreed to in writing, software distributed under the License 21 | // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 22 | // or implied. See the License for the specific language governing permissions and limitations under 23 | // the License. 24 | 25 | use alloc::collections::BTreeSet; 26 | use core::fmt::{Debug, Display}; 27 | 28 | use amplify::confinement::TinyOrdSet; 29 | 30 | use crate::core::{Core, Register, Site, SiteId}; 31 | use crate::isa::Bytecode; 32 | use crate::{CoreExt, IsaId}; 33 | 34 | /// Turing machine movement after instruction execution 35 | #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] 36 | pub enum ExecStep { 37 | /// Stop program execution. 38 | Stop, 39 | 40 | /// Set `CK` to `Fail`. The program execution will halt if `CH` is set. 41 | Fail, 42 | 43 | /// Move to the next instruction. 44 | Next, 45 | 46 | /// Jump to the offset from the origin. 47 | Jump(u16), 48 | 49 | /// Jump to another code fragment. 50 | Call(Site), 51 | 52 | /// Return to the next instruction after the original caller position. 53 | Ret(Site), 54 | } 55 | 56 | /// A local goto position for the jump instructions. 57 | #[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] 58 | pub enum GotoTarget<'a> { 59 | /// The instruction does not perform a local jump. 60 | /// 61 | /// NB: It still may call a code from an external library, use [`Instruction::remote_goto_pos`] 62 | /// to check that. 63 | None, 64 | 65 | /// An absolute offset in the code segment of the library. 66 | Absolute(&'a mut u16), 67 | 68 | /// An offset relative to the current position. 69 | Relative(&'a mut i8), 70 | } 71 | 72 | /// Trait for instructions 73 | pub trait Instruction: Display + Debug + Bytecode + Clone + Eq { 74 | /// The names of the ISA extension set these instructions cover. 75 | const ISA_EXT: &'static [&'static str]; 76 | 77 | /// Extensions to the AluVM core unit provided by this instruction set. 78 | type Core: CoreExt; 79 | /// Context: external data which are accessible to the ISA. 80 | type Context<'ctx>; 81 | 82 | /// Convert the set of ISA extensions from [`Self::ISA_EXT`] into a set of [`IsaId`]. 83 | fn isa_ext() -> TinyOrdSet { 84 | let iter = Self::ISA_EXT.iter().copied().map(IsaId::from); 85 | TinyOrdSet::from_iter_checked(iter) 86 | } 87 | 88 | /// Whether the instruction can be used as a goto-target. 89 | fn is_goto_target(&self) -> bool; 90 | 91 | /// If an instruction is a jump operation inside the library, it should return its goto target 92 | /// position number. 93 | fn local_goto_pos(&mut self) -> GotoTarget; 94 | 95 | /// If an instruction is a jump operation into an external library, it should return its remote 96 | /// target. 97 | fn remote_goto_pos(&mut self) -> Option<&mut Site>; 98 | 99 | /// Lists all registers which are used by the instruction. 100 | fn regs(&self) -> BTreeSet<::Reg> { 101 | let mut regs = self.src_regs(); 102 | regs.extend(self.dst_regs()); 103 | regs 104 | } 105 | 106 | /// List of registers which value is taken into account by the instruction. 107 | fn src_regs(&self) -> BTreeSet<::Reg>; 108 | 109 | /// List of registers which value may be changed by the instruction. 110 | fn dst_regs(&self) -> BTreeSet<::Reg>; 111 | 112 | /// The number of bytes in the source registers. 113 | fn src_reg_bytes(&self) -> u16 { 114 | self.src_regs() 115 | .into_iter() 116 | .map(::Reg::bytes) 117 | .sum() 118 | } 119 | 120 | /// The number of bytes in the destination registers. 121 | fn dst_reg_bytes(&self) -> u16 { 122 | self.dst_regs() 123 | .into_iter() 124 | .map(::Reg::bytes) 125 | .sum() 126 | } 127 | 128 | /// The size of the data coming as an instruction operand (i.e., except data coming from 129 | /// registers or read from outside the instruction operands). 130 | fn op_data_bytes(&self) -> u16; 131 | 132 | /// The size of the data read by the instruction from outside the registers (except data coming 133 | /// as a parameter). 134 | fn ext_data_bytes(&self) -> u16; 135 | 136 | /// Computes base (non-adjusted) complexity of the instruction. 137 | /// 138 | /// Called by the default [`Self::complexity`] implementation. See it for more details. 139 | fn base_complexity(&self) -> u64 { 140 | (self.op_data_bytes() as u64 141 | + self.src_reg_bytes() as u64 142 | + self.dst_reg_bytes() as u64 143 | + self.ext_data_bytes() as u64 * 2) 144 | * 8 // per bit 145 | * 1000 // by default use large unit 146 | } 147 | 148 | /// Returns computational complexity of the instruction. 149 | /// 150 | /// Computational complexity is the number of "CPU ticks" required to process the instruction. 151 | fn complexity(&self) -> u64 { self.base_complexity() } 152 | 153 | /// Executes the given instruction taking all registers as input and output. 154 | /// 155 | /// # Arguments 156 | /// 157 | /// The method is provided with the current code position which may be used by the instruction 158 | /// for constructing call stack. 159 | /// 160 | /// # Returns 161 | /// 162 | /// Returns whether further execution should be stopped. 163 | fn exec( 164 | &self, 165 | site: Site, 166 | core: &mut Core, 167 | context: &Self::Context<'_>, 168 | ) -> ExecStep>; 169 | } 170 | -------------------------------------------------------------------------------- /src/isa/masm.rs: -------------------------------------------------------------------------------- 1 | // Reference rust implementation of AluVM (arithmetic logic unit virtual machine). 2 | // To find more on AluVM please check 3 | // 4 | // SPDX-License-Identifier: Apache-2.0 5 | // 6 | // Designed in 2021-2025 by Dr Maxim Orlovsky 7 | // Written in 2021-2025 by Dr Maxim Orlovsky 8 | // 9 | // Copyright (C) 2021-2024 LNP/BP Standards Association, Switzerland. 10 | // Copyright (C) 2024-2025 Laboratories for Ubiquitous Deterministic Computing (UBIDECO), 11 | // Institute for Distributed and Cognitive Systems (InDCS), Switzerland. 12 | // Copyright (C) 2021-2025 Dr Maxim Orlovsky. 13 | // All rights under the above copyrights are reserved. 14 | // 15 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 16 | // in compliance with the License. You may obtain a copy of the License at 17 | // 18 | // http://www.apache.org/licenses/LICENSE-2.0 19 | // 20 | // Unless required by applicable law or agreed to in writing, software distributed under the License 21 | // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 22 | // or implied. See the License for the specific language governing permissions and limitations under 23 | // the License. 24 | 25 | /// Macro compiler for AluVM assembler. 26 | /// 27 | /// # Example 28 | /// 29 | /// ``` 30 | /// ##![cfg_attr(coverage_nightly, feature(coverage_attribute), coverage(off))] 31 | /// use aluvm::isa::Instr; 32 | /// use aluvm::regs::Status; 33 | /// use aluvm::{aluasm, Lib, LibId, LibSite, Vm}; 34 | /// 35 | /// const START: u16 = 0; 36 | /// 37 | /// let code = aluasm! { 38 | /// routine START: 39 | /// not CO; 40 | /// fail CK; 41 | /// mov CO, CK; 42 | /// chk CO; 43 | /// jif CO, +2; 44 | /// jif CK, -2; 45 | /// jmp +2; 46 | /// call START; 47 | /// stop; 48 | /// }; 49 | /// 50 | /// let lib = Lib::assemble::>(&code).unwrap(); 51 | /// let mut vm = Vm::>::new(); 52 | /// match vm.exec(LibSite::new(lib.lib_id(), 0), &(), |_| Some(&lib)) { 53 | /// Status::Ok => println!("success"), 54 | /// Status::Fail => println!("failure"), 55 | /// } 56 | /// ``` 57 | #[macro_export] 58 | macro_rules! aluasm { 59 | ($( $tt:tt )+) => {{ 60 | use $crate::instr; 61 | #[cfg(not(feature = "std"))] 62 | use alloc::vec::Vec; 63 | 64 | let mut code: Vec<$crate::isa::Instr<$crate::LibId>> = Default::default(); 65 | #[allow(unreachable_code)] { 66 | $crate::aluasm_inner! { code => $( $tt )+ } 67 | } 68 | code 69 | }}; 70 | } 71 | 72 | #[doc(hidden)] 73 | #[macro_export] 74 | macro_rules! aluasm_inner { 75 | // end of program 76 | { $code:ident => } => { }; 77 | // skipped annotations 78 | { $code:ident => offset $_:literal : $($tt:tt)* } => { 79 | $crate::aluasm_inner! { $code => $( $tt )* } 80 | }; 81 | { $code:ident => site $lib:ident @ $_:literal : $($tt:tt)* } => { 82 | $crate::aluasm_inner! { $code => $( $tt )* } 83 | }; 84 | // macro instruction 85 | { $code:ident => $masm:ident $label:ident : $($tt:tt)* } => { 86 | $code.push(instr!{ $masm $label : }); 87 | $crate::aluasm_inner! { $code => $( $tt )* } 88 | }; 89 | // no operands 90 | { $code:ident => $op:ident ; $($tt:tt)* } => { 91 | $code.push(instr!{ $op }); 92 | $crate::aluasm_inner! { $code => $( $tt )* } 93 | }; 94 | // operands are all literals 95 | { $code:ident => $op:ident $( $arg:literal ),+ ; $($tt:tt)* } => { 96 | $code.push(instr!{ $op $( $arg ),+ }); 97 | $crate::aluasm_inner! { $code => $( $tt )* } 98 | }; 99 | // operands are all idents 100 | { $code:ident => $op:ident $( $arg:ident ),+ ; $($tt:tt)* } => { 101 | $code.push(instr!{ $op $( $arg ),+ }); 102 | $crate::aluasm_inner! { $code => $( $tt )* } 103 | }; 104 | // operand is a positive shift 105 | { $code:ident => $op:ident + $pos:literal ; $($tt:tt)* } => { 106 | $code.push(instr!{ $op + $pos }); 107 | $crate::aluasm_inner! { $code => $( $tt )* } 108 | }; 109 | { $code:ident => $op:ident $arg:ident, + $pos:literal ; $($tt:tt)* } => { 110 | $code.push(instr!{ $op $arg, + $pos }); 111 | $crate::aluasm_inner! { $code => $( $tt )* } 112 | }; 113 | // operand is a negative shift 114 | { $code:ident => $op:ident - $pos:literal ; $($tt:tt)* } => { 115 | $code.push(instr!{ $op - $pos }); 116 | $crate::aluasm_inner! { $code => $( $tt )* } 117 | }; 118 | { $code:ident => $op:ident $arg:ident, - $pos:literal ; $($tt:tt)* } => { 119 | $code.push(instr!{ $op $arg, - $pos }); 120 | $crate::aluasm_inner! { $code => $( $tt )* } 121 | }; 122 | // operands are indent followed by a literal 123 | { $code:ident => $op:ident $arg:ident, $val:literal ; $($tt:tt)* } => { 124 | $code.push(instr!{ $op $arg, $val }); 125 | $crate::aluasm_inner! { $code => $( $tt )* } 126 | }; 127 | // suffixes 128 | { $code:ident => $op:ident $val:literal . $ty:ident ; $($tt:tt)* } => { 129 | $code.push(instr!{ $op $val.$ty }); 130 | $crate::aluasm_inner! { $code => $( $tt )* } 131 | }; 132 | { $code:ident => $op:ident $reg:ident, $val:literal . $ty:ident ; $($tt:tt)* } => { 133 | $code.push(instr!{ $op $reg, $val.$ty }); 134 | $crate::aluasm_inner! { $code => $( $tt )* } 135 | }; 136 | // external constants and variables 137 | { $code:ident => $op:ident & $val:ident ; $($tt:tt)* } => { 138 | $code.push(instr!{ $op & $val }); 139 | $crate::aluasm_inner! { $code => $( $tt )* } 140 | }; 141 | { $code:ident => $op:ident $reg:ident, & $val:ident ; $($tt:tt)* } => { 142 | $code.push(instr!{ $op $reg, & $val }); 143 | $crate::aluasm_inner! { $code => $( $tt )* } 144 | }; 145 | } 146 | 147 | #[doc(hidden)] 148 | #[macro_export] 149 | macro_rules! instr { 150 | (routine $_:ident :) => { 151 | $crate::isa::CtrlInstr::Nop.into() 152 | }; 153 | (proc $_:ident :) => { 154 | $crate::isa::CtrlInstr::Nop.into() 155 | }; 156 | (label $_:ident :) => { 157 | $crate::isa::CtrlInstr::Nop.into() 158 | }; 159 | (loop $_:ident :) => { 160 | $crate::isa::CtrlInstr::Nop.into() 161 | }; 162 | 163 | (nop) => { 164 | $crate::isa::CtrlInstr::Nop.into() 165 | }; 166 | (chk CO) => { 167 | $crate::isa::CtrlInstr::ChkCo.into() 168 | }; 169 | (chk CK) => { 170 | $crate::isa::CtrlInstr::ChkCk.into() 171 | }; 172 | (not CO) => { 173 | $crate::isa::CtrlInstr::NotCo.into() 174 | }; 175 | (fail CK) => { 176 | $crate::isa::CtrlInstr::FailCk.into() 177 | }; 178 | (mov CO,CK) => { 179 | $crate::isa::CtrlInstr::RsetCk.into() 180 | }; 181 | (ret) => { 182 | $crate::isa::CtrlInstr::Ret.into() 183 | }; 184 | (stop) => { 185 | $crate::isa::CtrlInstr::Stop.into() 186 | }; 187 | 188 | // Jumps 189 | (jmp $pos:literal) => { 190 | $crate::isa::CtrlInstr::Jmp { pos: $pos }.into() 191 | }; 192 | (jmp $pos:ident) => { 193 | $crate::isa::CtrlInstr::Jmp { pos: $pos }.into() 194 | }; 195 | 196 | (jif CO, + $shift:literal) => { 197 | $crate::isa::CtrlInstr::ShOvfl { shift: $shift }.into() 198 | }; 199 | (jif CO, - $shift:literal) => { 200 | $crate::isa::CtrlInstr::ShOvfl { shift: -$shift }.into() 201 | }; 202 | (jif CK, + $shift:literal) => { 203 | $crate::isa::CtrlInstr::ShFail { shift: $shift }.into() 204 | }; 205 | (jif CK, - $shift:literal) => { 206 | $crate::isa::CtrlInstr::ShFail { shift: -$shift }.into() 207 | }; 208 | (jif CO, $pos:literal) => { 209 | $crate::isa::CtrlInstr::JiOvfl { pos: $pos }.into() 210 | }; 211 | (jif CK, $pos:literal) => { 212 | $crate::isa::CtrlInstr::JiFail { pos: $pos }.into() 213 | }; 214 | (jif CO, $pos:ident) => { 215 | $crate::isa::CtrlInstr::JiOvfl { pos: $pos }.into() 216 | }; 217 | (jif CK, $pos:ident) => { 218 | $crate::isa::CtrlInstr::JiFail { pos: $pos }.into() 219 | }; 220 | (jmp + $shift:literal) => { 221 | $crate::isa::CtrlInstr::Sh { shift: $shift }.into() 222 | }; 223 | (jmp - $shift:literal) => { 224 | $crate::isa::CtrlInstr::Sh { shift: -$shift }.into() 225 | }; 226 | 227 | // Calls 228 | (jmp $lib:ident, $pos:literal) => { 229 | $crate::isa::CtrlInstr::Exec { site: $crate::Site::new($lib, $pos).into() }.into() 230 | }; 231 | (jmp $lib:ident, $pos:ident) => { 232 | $crate::isa::CtrlInstr::Exec { site: $crate::Site::new($lib, $pos).into() }.into() 233 | }; 234 | (call $lib:ident, $pos:literal) => { 235 | $crate::isa::CtrlInstr::Call { site: $crate::Site::new($lib, $pos).into() }.into() 236 | }; 237 | (call $lib:ident, $pos:ident) => { 238 | $crate::isa::CtrlInstr::Call { site: $crate::Site::new($lib, $pos).into() }.into() 239 | }; 240 | (call $pos:literal) => { 241 | $crate::isa::CtrlInstr::Fn { pos: $pos }.into() 242 | }; 243 | (call $pos:ident) => { 244 | $crate::isa::CtrlInstr::Fn { pos: $pos }.into() 245 | }; 246 | 247 | // Halt 248 | (halt) => { 249 | $crate::isa::ReservedInstr::default().into() 250 | }; 251 | } 252 | -------------------------------------------------------------------------------- /src/isa/mod.rs: -------------------------------------------------------------------------------- 1 | // Reference rust implementation of AluVM (arithmetic logic unit virtual machine). 2 | // To find more on AluVM please check 3 | // 4 | // SPDX-License-Identifier: Apache-2.0 5 | // 6 | // Designed in 2021-2025 by Dr Maxim Orlovsky 7 | // Written in 2021-2025 by Dr Maxim Orlovsky 8 | // 9 | // Copyright (C) 2021-2024 LNP/BP Standards Association, Switzerland. 10 | // Copyright (C) 2024-2025 Laboratories for Ubiquitous Deterministic Computing (UBIDECO), 11 | // Institute for Distributed and Cognitive Systems (InDCS), Switzerland. 12 | // Copyright (C) 2021-2025 Dr Maxim Orlovsky. 13 | // All rights under the above copyrights are reserved. 14 | // 15 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 16 | // in compliance with the License. You may obtain a copy of the License at 17 | // 18 | // http://www.apache.org/licenses/LICENSE-2.0 19 | // 20 | // Unless required by applicable law or agreed to in writing, software distributed under the License 21 | // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 22 | // or implied. See the License for the specific language governing permissions and limitations under 23 | // the License. 24 | 25 | //! AluVM instruction set architecture. 26 | 27 | mod instr; 28 | mod bytecode; 29 | mod arch; 30 | 31 | mod ctrl; 32 | mod masm; 33 | 34 | pub use arch::{Instr, IsaId, ReservedInstr, ISA_ID_MAX_LEN}; 35 | pub use bytecode::{Bytecode, BytecodeRead, BytecodeWrite, CodeEofError}; 36 | pub use ctrl::CtrlInstr; 37 | pub use instr::{ExecStep, GotoTarget, Instruction}; 38 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | // Reference rust implementation of AluVM (arithmetic logic unit virtual machine). 2 | // To find more on AluVM please check 3 | // 4 | // SPDX-License-Identifier: Apache-2.0 5 | // 6 | // Designed in 2021-2025 by Dr Maxim Orlovsky 7 | // Written in 2021-2025 by Dr Maxim Orlovsky 8 | // 9 | // Copyright (C) 2021-2024 LNP/BP Standards Association, Switzerland. 10 | // Copyright (C) 2024-2025 Laboratories for Ubiquitous Deterministic Computing (UBIDECO), 11 | // Institute for Distributed and Cognitive Systems (InDCS), Switzerland. 12 | // Copyright (C) 2021-2025 Dr Maxim Orlovsky. 13 | // All rights under the above copyrights are reserved. 14 | // 15 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 16 | // in compliance with the License. You may obtain a copy of the License at 17 | // 18 | // http://www.apache.org/licenses/LICENSE-2.0 19 | // 20 | // Unless required by applicable law or agreed to in writing, software distributed under the License 21 | // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 22 | // or implied. See the License for the specific language governing permissions and limitations under 23 | // the License. 24 | 25 | #![deny( 26 | unsafe_code, 27 | dead_code, 28 | missing_docs, 29 | unused_variables, 30 | unused_mut, 31 | unused_imports, 32 | non_upper_case_globals, 33 | non_camel_case_types, 34 | non_snake_case 35 | )] 36 | #![allow(clippy::bool_assert_comparison)] 37 | #![cfg_attr(coverage_nightly, feature(coverage_attribute))] 38 | #![cfg_attr(docsrs, feature(doc_auto_cfg))] 39 | 40 | //! Rust implementation of AluVM (arithmetic logic unit virtual machine) and assembler from Alu 41 | //! Assembly language into bytecode. 42 | //! 43 | //! AluVM is a pure functional register-based highly deterministic & exception-less instruction set 44 | //! architecture (ISA) and virtual machine (VM) without random memory access, capable of performing 45 | //! arithmetic operations, including operations on elliptic curves. The AluVM ISA can be extended by 46 | //! the environment running the virtual machine (host environment), providing an ability to load 47 | //! data to the VM registers and support application-specific instructions (like SIMD). 48 | //! 49 | //! The main purpose for ALuVM is to be used in distributed systems whether robustness, 50 | //! platform-independent determinism are more important than the speed of computation. The main area 51 | //! of AluVM applications (using appropriate ISA extensions) is blockchain environments, 52 | //! consensus-critical computations, multiparty computing (including deterministic machine 53 | //! learning), client-side-validation, sandboxed Internet2 computing, and genetic algorithms. 54 | //! 55 | //! For more details on AluVM, please check [the specification][AluVM] 56 | //! 57 | //! 58 | //! ## Design 59 | //! 60 | //! The robustness lies at the very core of AluVM. It is designed to avoid any 61 | //! undefined behavior. Specifically, 62 | //! * All registers may be in the undefined statel 63 | //! * Impossible/incorrect operations put destination register into a special *undefined state*; 64 | //! * Code always extended to 2^16 bytes with zeros, which corresponds to no-operation; 65 | //! * There are no invalid jump operations; 66 | //! * There are no invalid instructions; 67 | //! * Cycles & jumps are counted with 2^16 limit (bounded-time execution); 68 | //! * No ambiguity: any two distinct byte strings always represent strictly distinct programs; 69 | //! * Code is always signed; 70 | //! * Data segment is always signed; 71 | //! * Code commits to the used ISA extensions; 72 | //! * Libraries identified by the signature; 73 | //! * Code does not run if not all libraries are present; 74 | //! 75 | //! ![Comparison table](doc/comparison.png) 76 | //! 77 | //! 78 | //! ## Instruction Set Architecture 79 | //! 80 | //! ![Instruction set architecture](doc/isa.png) 81 | //! 82 | //! ### Instruction opcodes 83 | //! 84 | //! One will find all opcode implementation details documented in [`isa::Instr`] API docs. 85 | //! 86 | //! - RISC: only 256 instructions 87 | //! - 3 families of core instructions: 88 | //! * Control flow 89 | //! * Data load / movement between registers 90 | //! * ALU (including cryptography) 91 | //! - Extensible with ISA extensions: 127 of the operations are reserved for extensions 92 | //! * More cryptography 93 | //! * Custom data I/O (blockchain, LN, client-side-validation) 94 | //! * Genetic algorithms / code self-modification 95 | //! 96 | //! The arithmetic ISA is designed with strong robustness goals: 97 | //! - Impossible arithmetic operation (0/0, Inf/inf) always sets the destination register into 98 | //! undefined state (unlike NaN in IEEE-754 it has only a single unique value) 99 | //! - Operation resulting in the value which can't fit the bit dimensions under a used encoding, 100 | //! including representation of infinity for integer encodings (x/0 if x != 0) results in: 101 | //! * for float underflows, subnormally encoded number, 102 | //! * for x/0 if x != 0 on float numbers, ±Inf float value, 103 | //! * for overflows in integer checked operations and floats: undefined value, setting `CK` to 104 | //! false, 105 | //! * for overflows in integer wrapped operations, modulo division on the maximum register value 106 | //! 107 | //! Most of the arithmetic operations has to be provided with flags specifying which of the encoding 108 | //! and exception handling should be used: 109 | //! * Integer encodings have two flags: 110 | //! - one for signed/unsigned variant of the encoding 111 | //! - one for checked or wrapped variant of exception handling 112 | //! * Float encoding has 4 variants of rounding, matching IEEE-754 options 113 | //! 114 | //! Thus, many arithmetic instructions have 8 variants, indicating the used encoding (unsigned, 115 | //! signed integer or float) and operation behavior in a situation when resulting value does not fit 116 | //! into the register (overflow or wrap for integers and one of four rounding options for floats). 117 | //! 118 | //! Check [the specification][AluVM] for the details. 119 | //! 120 | //! ### Registers 121 | //! 122 | //! **ALU registers:** 8 blocks of 32 registers 123 | //! - Integer arithmetic (A-registers) blocks: 8, 16, 32, 64, 128, 256, 512, 1024 bits 124 | //! - Float arithmetic (F-registers) blocks: 125 | //! * IEEE: binary-half, single, double, quad, oct precision 126 | //! * IEEE extension: 80-bit X87 register 127 | //! * BFloat16 register, used in Machine learning 128 | //! - Cryptographic operations (R-registers) blocks: 128, 160, 256, 512, 1024, 2048, 4096, 8192 bits 129 | //! - String registers (S-registers): 1 block of 256 registers, 64kb each 130 | //! 131 | //! **Control flow registers:** 132 | //! - Status (`CK`), boolean (one bit) 133 | //! - Cycle counter (`CY`), 16 bits 134 | //! - Instruction complexity accumulator (`CA`), 16 bits 135 | //! - Call stack register (`CS`), 3*2^16 bits (192kB block) 136 | //! - Call stack pointer register (`CP`), 16 bits 137 | //! 138 | //! [AluVM]: https://github.com/AluVM/aluvm-spec 139 | 140 | extern crate alloc; 141 | 142 | #[macro_use] 143 | extern crate amplify; 144 | #[macro_use] 145 | extern crate strict_encoding; 146 | #[macro_use] 147 | extern crate commit_verify; 148 | #[cfg(feature = "serde")] 149 | #[macro_use] 150 | extern crate serde; 151 | 152 | mod core; 153 | #[macro_use] 154 | pub mod isa; 155 | mod library; 156 | mod vm; 157 | #[cfg(feature = "stl")] 158 | pub mod stl; 159 | 160 | /// Module providing register information 161 | pub mod regs { 162 | pub use crate::core::{Status, CALL_STACK_SIZE_MAX}; 163 | } 164 | 165 | pub use isa::{ExecStep, IsaId, ISA_ID_MAX_LEN}; 166 | #[cfg(feature = "armor")] 167 | pub use library::armor::LibArmorError; 168 | pub use library::{ 169 | AssemblerError, CompiledLib, CompilerError, Lib, LibId, LibSite, LibsSeg, MarshallError, 170 | Marshaller, 171 | }; 172 | #[doc(hidden)] 173 | pub use paste::paste; 174 | pub use vm::Vm; 175 | 176 | pub use self::core::{Core, CoreConfig, CoreExt, NoExt, NoRegs, Register, Site, SiteId, Supercore}; 177 | 178 | /// Name of the strict types library for AluVM. 179 | pub const LIB_NAME_ALUVM: &str = "AluVM"; 180 | -------------------------------------------------------------------------------- /src/library/armor.rs: -------------------------------------------------------------------------------- 1 | // Reference rust implementation of AluVM (arithmetic logic unit virtual machine). 2 | // To find more on AluVM please check 3 | // 4 | // SPDX-License-Identifier: Apache-2.0 5 | // 6 | // Designed in 2021-2025 by Dr Maxim Orlovsky 7 | // Written in 2021-2025 by Dr Maxim Orlovsky 8 | // 9 | // Copyright (C) 2021-2024 LNP/BP Standards Association, Switzerland. 10 | // Copyright (C) 2024-2025 Laboratories for Ubiquitous Deterministic Computing (UBIDECO), 11 | // Institute for Distributed and Cognitive Systems (InDCS), Switzerland. 12 | // Copyright (C) 2021-2025 Dr Maxim Orlovsky. 13 | // All rights under the above copyrights are reserved. 14 | // 15 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 16 | // in compliance with the License. You may obtain a copy of the License at 17 | // 18 | // http://www.apache.org/licenses/LICENSE-2.0 19 | // 20 | // Unless required by applicable law or agreed to in writing, software distributed under the License 21 | // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 22 | // or implied. See the License for the specific language governing permissions and limitations under 23 | // the License. 24 | 25 | use ::armor::{ArmorHeader, ArmorParseError, AsciiArmor, ASCII_ARMOR_ID}; 26 | use amplify::confinement::{self, Confined, U24 as U24MAX}; 27 | use strict_encoding::{DeserializeError, StrictDeserialize, StrictSerialize}; 28 | 29 | use super::*; 30 | 31 | const ASCII_ARMOR_ISAE: &str = "ISA-Extensions"; 32 | const ASCII_ARMOR_DEPENDENCY: &str = "Dependency"; 33 | 34 | /// Errors while deserializing lib-old from an ASCII Armor. 35 | #[derive(Clone, Eq, PartialEq, Debug, Display, Error, From)] 36 | #[display(inner)] 37 | pub enum LibArmorError { 38 | /// Armor parse error. 39 | #[from] 40 | Armor(ArmorParseError), 41 | 42 | /// The provided data exceed maximum possible lib-old size. 43 | #[from(confinement::Error)] 44 | TooLarge, 45 | 46 | /// Library data deserialization error. 47 | #[from] 48 | Decode(DeserializeError), 49 | } 50 | 51 | impl AsciiArmor for Lib { 52 | type Err = LibArmorError; 53 | const PLATE_TITLE: &'static str = "ALUVM LIB"; 54 | 55 | fn ascii_armored_headers(&self) -> Vec { 56 | let mut headers = vec![ 57 | ArmorHeader::new(ASCII_ARMOR_ID, self.lib_id().to_string()), 58 | ArmorHeader::new(ASCII_ARMOR_ISAE, self.isae_string()), 59 | ]; 60 | for dep in &self.libs { 61 | headers.push(ArmorHeader::new(ASCII_ARMOR_DEPENDENCY, dep.to_string())); 62 | } 63 | headers 64 | } 65 | 66 | fn to_ascii_armored_data(&self) -> Vec { 67 | self.to_strict_serialized::() 68 | .expect("type guarantees") 69 | .to_vec() 70 | } 71 | 72 | fn with_headers_data(_headers: Vec, data: Vec) -> Result { 73 | // TODO: check id, dependencies and ISAE 74 | let data = Confined::try_from(data)?; 75 | let me = Self::from_strict_serialized::(data)?; 76 | Ok(me) 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/library/assembler.rs: -------------------------------------------------------------------------------- 1 | // Reference rust implementation of AluVM (arithmetic logic unit virtual machine). 2 | // To find more on AluVM please check 3 | // 4 | // SPDX-License-Identifier: Apache-2.0 5 | // 6 | // Designed in 2021-2025 by Dr Maxim Orlovsky 7 | // Written in 2021-2025 by Dr Maxim Orlovsky 8 | // 9 | // Copyright (C) 2021-2024 LNP/BP Standards Association, Switzerland. 10 | // Copyright (C) 2024-2025 Laboratories for Ubiquitous Deterministic Computing (UBIDECO), 11 | // Institute for Distributed and Cognitive Systems (InDCS), Switzerland. 12 | // Copyright (C) 2021-2025 Dr Maxim Orlovsky. 13 | // All rights under the above copyrights are reserved. 14 | // 15 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 16 | // in compliance with the License. You may obtain a copy of the License at 17 | // 18 | // http://www.apache.org/licenses/LICENSE-2.0 19 | // 20 | // Unless required by applicable law or agreed to in writing, software distributed under the License 21 | // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 22 | // or implied. See the License for the specific language governing permissions and limitations under 23 | // the License. 24 | 25 | use amplify::confinement::{self, TinyOrdSet}; 26 | 27 | use super::{Lib, LibId, MarshallError, Marshaller}; 28 | use crate::isa::{BytecodeRead, CodeEofError, Instruction}; 29 | 30 | /// Errors while assembling lib-old from the instruction set. 31 | #[derive(Clone, Copy, Eq, PartialEq, Hash, Debug, Display, Error, From)] 32 | #[display(inner)] 33 | pub enum AssemblerError { 34 | /// Error assembling code and data segments. 35 | #[from] 36 | Bytecode(MarshallError), 37 | 38 | /// Error assembling a library segment. 39 | #[from] 40 | LibSegOverflow(confinement::Error), 41 | } 42 | 43 | impl Lib { 44 | /// Assembles a library from the provided instructions by encoding them into bytecode. 45 | pub fn assemble(code: &[Isa]) -> Result 46 | where Isa: Instruction { 47 | let call_sites = code.iter().filter_map(|instr| instr.external_ref()); 48 | let libs_segment = TinyOrdSet::try_from_iter(call_sites)?; 49 | 50 | let mut writer = Marshaller::new(&libs_segment); 51 | for instr in code.iter() { 52 | instr.encode_instr(&mut writer)?; 53 | } 54 | let (code_segment, data_segment) = writer.finish(); 55 | 56 | Ok(Lib { 57 | isae: Isa::isa_ext(), 58 | libs: libs_segment, 59 | code: code_segment, 60 | data: data_segment, 61 | }) 62 | } 63 | 64 | /// Disassembles the library into a set of instructions. 65 | pub fn disassemble(&self) -> Result, CodeEofError> 66 | where Isa: Instruction { 67 | let mut code = Vec::new(); 68 | let mut reader = Marshaller::with(&self.code, &self.data, &self.libs); 69 | while !reader.is_eof() { 70 | code.push(Isa::decode_instr(&mut reader)?); 71 | } 72 | Ok(code) 73 | } 74 | 75 | /// Disassembles the library into a set of instructions and offsets and prints it to the writer. 76 | pub fn print_disassemble( 77 | &self, 78 | mut writer: impl std::io::Write, 79 | ) -> Result<(), std::io::Error> 80 | where 81 | Isa: Instruction, 82 | { 83 | let mut reader = Marshaller::with(&self.code, &self.data, &self.libs); 84 | while !reader.is_eof() { 85 | let pos = reader.offset().0 as usize; 86 | write!(writer, "offset {pos:06}: ")?; 87 | match Isa::decode_instr(&mut reader) { 88 | Ok(instr) => writeln!(writer, "{instr}")?, 89 | Err(_) => writeln!(writer, "; ")?, 90 | } 91 | } 92 | Ok(()) 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /src/library/compiler.rs: -------------------------------------------------------------------------------- 1 | // Reference rust implementation of AluVM (arithmetic logic unit virtual machine). 2 | // To find more on AluVM please check 3 | // 4 | // SPDX-License-Identifier: Apache-2.0 5 | // 6 | // Designed in 2021-2025 by Dr Maxim Orlovsky 7 | // Written in 2021-2025 by Dr Maxim Orlovsky 8 | // 9 | // Copyright (C) 2021-2024 LNP/BP Standards Association, Switzerland. 10 | // Copyright (C) 2024-2025 Laboratories for Ubiquitous Deterministic Computing (UBIDECO), 11 | // Institute for Distributed and Cognitive Systems (InDCS), Switzerland. 12 | // Copyright (C) 2021-2025 Dr Maxim Orlovsky. 13 | // All rights under the above copyrights are reserved. 14 | // 15 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 16 | // in compliance with the License. You may obtain a copy of the License at 17 | // 18 | // http://www.apache.org/licenses/LICENSE-2.0 19 | // 20 | // Unless required by applicable law or agreed to in writing, software distributed under the License 21 | // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 22 | // or implied. See the License for the specific language governing permissions and limitations under 23 | // the License. 24 | 25 | use alloc::vec::Vec; 26 | use std::collections::BTreeMap; 27 | 28 | use crate::isa::{GotoTarget, Instruction}; 29 | use crate::library::assembler::AssemblerError; 30 | use crate::{Lib, LibId, LibSite}; 31 | 32 | /// Errors generated during the library compilation. 33 | #[derive(Clone, Eq, PartialEq, Hash, Debug, Display, Error, From)] 34 | #[display(doc_comments)] 35 | pub enum CompilerError> { 36 | /// Error in assembling the bytecode (see [`AssemblerError`] for the details). 37 | #[from] 38 | #[display(inner)] 39 | Assemble(AssemblerError), 40 | 41 | /// instruction number {1} `{0}` (offset {2:#x}) references goto target absent in the code. Use 42 | /// `nop` instruction to mark the goto target. 43 | /// 44 | /// The known goto target offsets are: {3:#x?} 45 | InvalidRef(Isa, usize, u16, Vec), 46 | 47 | /// instruction number {1} `{0}` (offset {2:#x}) references library which is not a dependency 48 | /// (lib id {3}). 49 | InvalidLib(Isa, usize, u16, LibId), 50 | } 51 | 52 | /// The compiled AluVM library containing information about the routines. 53 | pub struct CompiledLib { 54 | id: LibId, 55 | lib: Lib, 56 | routines: Vec, 57 | } 58 | 59 | impl CompiledLib { 60 | /// Compiles a library from the provided instructions by resolving local call pointers first 61 | /// and then assembling it into a bytecode by calling [`Self::assemble`]. 62 | pub fn compile( 63 | mut code: impl AsMut<[Isa]>, 64 | deps: &[&CompiledLib], 65 | ) -> Result> 66 | where 67 | Isa: Instruction, 68 | { 69 | let deps = deps 70 | .iter() 71 | .map(|lib| (lib.id, lib)) 72 | .collect::>(); 73 | let code = code.as_mut(); 74 | let mut routines = vec![]; 75 | let mut cursor = 0u16; 76 | for instr in &*code { 77 | if instr.is_goto_target() { 78 | routines.push(cursor); 79 | } 80 | cursor += instr.code_byte_len(); 81 | } 82 | let mut cursor = 0u16; 83 | for (no, instr) in code.iter_mut().enumerate() { 84 | if let GotoTarget::Absolute(goto_pos) = instr.local_goto_pos() { 85 | let Some(pos) = routines.get(*goto_pos as usize) else { 86 | return Err(CompilerError::InvalidRef(instr.clone(), no, cursor, routines)); 87 | }; 88 | *goto_pos = *pos; 89 | } 90 | let cloned_instr = instr.clone(); 91 | if let Some(remote_pos) = instr.remote_goto_pos() { 92 | let Some(lib) = deps.get(&remote_pos.prog_id) else { 93 | return Err(CompilerError::InvalidLib( 94 | cloned_instr, 95 | no, 96 | cursor, 97 | remote_pos.prog_id, 98 | )); 99 | }; 100 | remote_pos.offset = lib.routine(remote_pos.offset).offset; 101 | } 102 | cursor += instr.code_byte_len(); 103 | } 104 | let lib = Lib::assemble(code)?; 105 | let id = lib.lib_id(); 106 | Ok(Self { id, lib, routines }) 107 | } 108 | 109 | /// Count the number of routines in the library. 110 | pub fn routines_count(&self) -> usize { self.routines.len() } 111 | 112 | /// Returns code offset for the entry point of a given routine. 113 | /// 114 | /// # Panics 115 | /// 116 | /// Panics if the routine with the given number is not defined 117 | pub fn routine(&self, no: u16) -> LibSite { 118 | let pos = self.routines[no as usize]; 119 | LibSite::new(self.id, pos) 120 | } 121 | 122 | /// Get a reference to the underlying [`Lib`]. 123 | pub fn as_lib(&self) -> &Lib { &self.lib } 124 | 125 | /// Convert into the underlying [`Lib`]. 126 | pub fn into_lib(self) -> Lib { self.lib } 127 | } 128 | -------------------------------------------------------------------------------- /src/library/exec.rs: -------------------------------------------------------------------------------- 1 | // Reference rust implementation of AluVM (arithmetic logic unit virtual machine). 2 | // To find more on AluVM please check 3 | // 4 | // SPDX-License-Identifier: Apache-2.0 5 | // 6 | // Designed in 2021-2025 by Dr Maxim Orlovsky 7 | // Written in 2021-2025 by Dr Maxim Orlovsky 8 | // 9 | // Copyright (C) 2021-2024 LNP/BP Standards Association, Switzerland. 10 | // Copyright (C) 2024-2025 Laboratories for Ubiquitous Deterministic Computing (UBIDECO), 11 | // Institute for Distributed and Cognitive Systems (InDCS), Switzerland. 12 | // Copyright (C) 2021-2025 Dr Maxim Orlovsky. 13 | // All rights under the above copyrights are reserved. 14 | // 15 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 16 | // in compliance with the License. You may obtain a copy of the License at 17 | // 18 | // http://www.apache.org/licenses/LICENSE-2.0 19 | // 20 | // Unless required by applicable law or agreed to in writing, software distributed under the License 21 | // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 22 | // or implied. See the License for the specific language governing permissions and limitations under 23 | // the License. 24 | 25 | use amplify::num::u3; 26 | #[cfg(feature = "log")] 27 | use baid64::DisplayBaid64; 28 | 29 | use super::{Lib, Marshaller}; 30 | use crate::isa::{Bytecode, BytecodeRead, ExecStep, Instruction}; 31 | use crate::{Core, LibId, Site, SiteId}; 32 | 33 | #[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug, Display)] 34 | pub enum Jump { 35 | #[display("halt")] 36 | Halt, 37 | 38 | #[display("={0}")] 39 | Instr(Site), 40 | 41 | #[display(">{0}")] 42 | Next(Site), 43 | } 44 | 45 | impl Lib { 46 | /// Execute library code starting at the entrypoint. 47 | /// 48 | /// # Returns 49 | /// 50 | /// Location for the external code jump, if any. 51 | pub fn exec( 52 | &self, 53 | entrypoint: u16, 54 | skip_first: bool, 55 | core: &mut Core, 56 | context: &Instr::Context<'_>, 57 | ) -> Jump 58 | where 59 | Instr: Instruction + Bytecode, 60 | { 61 | #[cfg(feature = "log")] 62 | let (m, w, d, g, r, y, z) = ( 63 | "\x1B[0;35m", 64 | "\x1B[1;1m", 65 | "\x1B[0;37;2m", 66 | "\x1B[0;32m", 67 | "\x1B[0;31m", 68 | "\x1B[0;33m", 69 | "\x1B[0m", 70 | ); 71 | 72 | let mut marshaller = Marshaller::with(&self.code, &self.data, &self.libs); 73 | let lib_id = self.lib_id(); 74 | 75 | #[cfg(feature = "log")] 76 | let lib_mnemonic = lib_id.to_baid64_mnemonic(); 77 | #[cfg(feature = "log")] 78 | let lib_ref = lib_mnemonic.split_at(5).0; 79 | 80 | if marshaller.seek(entrypoint).is_err() { 81 | let _ = core.fail_ck(); 82 | #[cfg(feature = "log")] 83 | eprintln!("jump to non-existing offset; halting, {y}CK{z} is set to {r}false{z}"); 84 | return Jump::Halt; 85 | } 86 | 87 | #[cfg(feature = "log")] 88 | let mut ck0 = core.ck(); 89 | #[cfg(feature = "log")] 90 | let mut co0 = core.co(); 91 | 92 | if marshaller.is_eof() { 93 | return Jump::Halt; 94 | } 95 | // Skip instruction if required 96 | if skip_first { 97 | if Instr::decode_instr(&mut marshaller).is_err() { 98 | #[cfg(feature = "log")] 99 | { 100 | let (byte, bit) = marshaller.offset(); 101 | eprintln!( 102 | "; unable to decode instruction at byte pos {byte:06X}.h, bit pos {bit}", 103 | ); 104 | } 105 | return Jump::Halt; 106 | }; 107 | let next_pos = marshaller.offset(); 108 | debug_assert_eq!(next_pos.1, u3::ZERO); 109 | #[cfg(feature = "log")] 110 | eprintln!("; return to the caller offset {:06X}.h", next_pos.0); 111 | } 112 | 113 | while !marshaller.is_eof() { 114 | let pos = marshaller.pos(); 115 | 116 | let Ok(instr) = Instr::decode_instr(&mut marshaller) else { 117 | #[cfg(feature = "log")] 118 | { 119 | let (byte, bit) = marshaller.offset(); 120 | eprintln!( 121 | "unable to decode instruction at byte pos {byte:06X}.h, bit pos {bit}", 122 | ); 123 | } 124 | return Jump::Halt; 125 | }; 126 | 127 | #[cfg(feature = "log")] 128 | let mut prev = bmap![]; 129 | 130 | #[cfg(feature = "log")] 131 | // Stupid compiler can't reason between `cfg` blocks 132 | #[allow(unused_assignments)] 133 | let mut src_empty = true; 134 | #[cfg(feature = "log")] 135 | { 136 | for reg in instr.dst_regs() { 137 | prev.insert(reg, core.get(reg)); 138 | } 139 | eprint!("site {m}{}@{pos:06}:{z} {: <32}; ", lib_ref, instr.to_string()); 140 | let src_regs = instr.src_regs(); 141 | src_empty = src_regs.is_empty(); 142 | let mut iter = src_regs.into_iter().peekable(); 143 | while let Some(reg) = iter.next() { 144 | eprint!("{d}{reg}{z} "); 145 | if let Some(val) = core.get(reg) { 146 | eprint!("{w}{}{z}", val); 147 | } else { 148 | eprint!("{d}~{z}"); 149 | } 150 | if iter.peek().is_some() { 151 | eprint!(", "); 152 | } 153 | } 154 | } 155 | 156 | let next = instr.exec(Site::new(lib_id, pos), core, context); 157 | 158 | #[cfg(feature = "log")] 159 | { 160 | if !src_empty { 161 | if !prev.is_empty() { 162 | eprint!(" => "); 163 | } else if ck0 != core.ck() || co0 != core.co() || next != ExecStep::Next { 164 | eprint!("; "); 165 | } 166 | } 167 | 168 | let mut iter = instr.dst_regs().into_iter().peekable(); 169 | while let Some(reg) = iter.next() { 170 | eprint!("{g}{reg}{z} "); 171 | if let Some(val) = prev.get(®).unwrap() { 172 | eprint!("{y}{}{z}", val); 173 | } else { 174 | eprint!("{d}~{z}"); 175 | } 176 | eprint!(" -> "); 177 | if let Some(val) = core.get(reg) { 178 | eprint!("{y}{}{z}", val); 179 | } else { 180 | eprint!("{d}~{z}"); 181 | } 182 | if iter.peek().is_some() { 183 | eprint!(", "); 184 | } 185 | } 186 | if !prev.is_empty() && (ck0 != core.ck() || co0 != core.co()) { 187 | eprint!(", "); 188 | } 189 | if ck0 != core.ck() { 190 | let p = if ck0.is_ok() { g } else { r }; 191 | let c = if core.ck().is_ok() { g } else { r }; 192 | eprint!("{y}CK{z} {p}{ck0}{z} -> {c}{}{z}", core.ck()); 193 | } 194 | if ck0 != core.ck() && co0 != core.co() { 195 | eprint!(", "); 196 | } 197 | if co0 != core.co() { 198 | let p = if co0.is_ok() { g } else { r }; 199 | let c = if core.co().is_ok() { g } else { r }; 200 | eprint!("{y}CO{z} {p}{co0}{z} -> {c}{}{z}", core.co()); 201 | } 202 | if (!prev.is_empty() || ck0 != core.ck() || co0 != core.co()) 203 | && next != ExecStep::Next 204 | { 205 | eprint!(", "); 206 | } 207 | 208 | ck0 = core.ck(); 209 | co0 = core.co(); 210 | } 211 | 212 | if !core.acc_complexity(instr.complexity()) { 213 | let _ = core.fail_ck(); 214 | #[cfg(feature = "log")] 215 | { 216 | if !src_empty || !prev.is_empty() { 217 | eprint!(", "); 218 | } 219 | eprintln!("halting, complexity overflow"); 220 | } 221 | return Jump::Halt; 222 | } 223 | match next { 224 | ExecStep::Stop => { 225 | return Jump::Halt; 226 | } 227 | ExecStep::Fail => { 228 | #[cfg(feature = "log")] 229 | eprint!("{y}CK{z} {g}success{z} -> {r}fail{z}"); 230 | if core.fail_ck() { 231 | #[cfg(feature = "log")] 232 | eprintln!(", {y}CH{z} is {g}true{z}: halting"); 233 | return Jump::Halt; 234 | } 235 | #[cfg(feature = "log")] 236 | eprintln!(", {y}CH{z} is {r}false{z}: continuing"); 237 | continue; 238 | } 239 | ExecStep::Next => { 240 | #[cfg(feature = "log")] 241 | eprintln!(); 242 | continue; 243 | } 244 | ExecStep::Jump(pos) => { 245 | #[cfg(feature = "log")] 246 | eprintln!("{d}jumping to{z} {m}{pos:06}{z}"); 247 | if marshaller.seek(pos).is_err() { 248 | let _ = core.fail_ck(); 249 | #[cfg(feature = "log")] 250 | eprintln!( 251 | "jump to non-existing offset: unconditionally halting; {y}CK{z} is \ 252 | set to {r}fail{z}" 253 | ); 254 | return Jump::Halt; 255 | } 256 | } 257 | ExecStep::Call(site) => { 258 | #[cfg(feature = "log")] 259 | eprintln!("{d}calling{z} {m}{site}{z}"); 260 | return Jump::Instr(site); 261 | } 262 | ExecStep::Ret(site) => { 263 | #[cfg(feature = "log")] 264 | eprintln!("{d}returning to{z} {m}{site}{z}"); 265 | return Jump::Next(site); 266 | } 267 | } 268 | } 269 | 270 | Jump::Halt 271 | } 272 | } 273 | -------------------------------------------------------------------------------- /src/library/lib.rs: -------------------------------------------------------------------------------- 1 | // Reference rust implementation of AluVM (arithmetic logic unit virtual machine). 2 | // To find more on AluVM please check 3 | // 4 | // SPDX-License-Identifier: Apache-2.0 5 | // 6 | // Designed in 2021-2025 by Dr Maxim Orlovsky 7 | // Written in 2021-2025 by Dr Maxim Orlovsky 8 | // 9 | // Copyright (C) 2021-2024 LNP/BP Standards Association, Switzerland. 10 | // Copyright (C) 2024-2025 Laboratories for Ubiquitous Deterministic Computing (UBIDECO), 11 | // Institute for Distributed and Cognitive Systems (InDCS), Switzerland. 12 | // Copyright (C) 2021-2025 Dr Maxim Orlovsky. 13 | // All rights under the above copyrights are reserved. 14 | // 15 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 16 | // in compliance with the License. You may obtain a copy of the License at 17 | // 18 | // http://www.apache.org/licenses/LICENSE-2.0 19 | // 20 | // Unless required by applicable law or agreed to in writing, software distributed under the License 21 | // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 22 | // or implied. See the License for the specific language governing permissions and limitations under 23 | // the License. 24 | 25 | use core::fmt; 26 | use core::fmt::{Display, Formatter}; 27 | use core::str::FromStr; 28 | 29 | use amplify::confinement::{SmallBlob, TinyOrdSet}; 30 | use amplify::Bytes32; 31 | use baid64::{Baid64ParseError, DisplayBaid64, FromBaid64Str}; 32 | use commit_verify::{CommitId, CommitmentId, Digest, Sha256}; 33 | use strict_encoding::{StrictDeserialize, StrictSerialize}; 34 | 35 | use crate::core::SiteId; 36 | use crate::{IsaId, Site, LIB_NAME_ALUVM}; 37 | 38 | pub const LIB_ID_TAG: &str = "urn:ubideco:aluvm:lib:v01#241020"; 39 | 40 | /// Unique identifier for an AluVM library. 41 | #[derive(Wrapper, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Default, Debug, From)] 42 | #[wrapper(Deref, BorrowSlice, Hex, Index, RangeOps)] 43 | #[derive(StrictType, StrictEncode, StrictDecode)] 44 | #[strict_type(lib = LIB_NAME_ALUVM)] 45 | #[cfg_attr(feature = "serde", derive(Serialize, Deserialize), serde(transparent))] 46 | pub struct LibId( 47 | #[from] 48 | #[from([u8; 32])] 49 | Bytes32, 50 | ); 51 | 52 | impl SiteId for LibId {} 53 | 54 | impl CommitmentId for LibId { 55 | const TAG: &'static str = LIB_ID_TAG; 56 | } 57 | 58 | impl DisplayBaid64 for LibId { 59 | const HRI: &'static str = "alu"; 60 | const CHUNKING: bool = true; 61 | const PREFIX: bool = true; 62 | const EMBED_CHECKSUM: bool = false; 63 | const MNEMONIC: bool = true; 64 | fn to_baid64_payload(&self) -> [u8; 32] { self.to_byte_array() } 65 | } 66 | impl FromBaid64Str for LibId {} 67 | impl FromStr for LibId { 68 | type Err = Baid64ParseError; 69 | fn from_str(s: &str) -> Result { Self::from_baid64_str(s) } 70 | } 71 | impl Display for LibId { 72 | fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { self.fmt_baid64(f) } 73 | } 74 | 75 | impl From for LibId { 76 | fn from(hash: Sha256) -> Self { Self(Bytes32::from_byte_array(hash.finalize())) } 77 | } 78 | 79 | /// Location inside the instruction sequence which can be executed by the core. 80 | #[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug, Display)] 81 | #[display("{lib_id}@{offset:04}")] 82 | #[derive(StrictType, StrictDumb, StrictEncode, StrictDecode)] 83 | #[strict_type(lib = LIB_NAME_ALUVM)] 84 | #[cfg_attr(feature = "serde", derive(Serialize, Deserialize), serde(rename_all = "camelCase"))] 85 | pub struct LibSite { 86 | /// The identifier of the library. 87 | pub lib_id: LibId, 88 | /// The offset within the library. 89 | pub offset: u16, 90 | } 91 | 92 | impl From> for LibSite { 93 | fn from(site: Site) -> Self { Self { lib_id: site.prog_id, offset: site.offset } } 94 | } 95 | 96 | impl LibSite { 97 | /// Construct a new library site out of library identifier and code offset. 98 | #[inline] 99 | pub fn new(lib_id: LibId, offset: u16) -> Self { LibSite { lib_id, offset } } 100 | } 101 | 102 | /// Library segment inside AluVM library which stores references to the external library ids for the 103 | /// external calls made within the library. 104 | pub type LibsSeg = TinyOrdSet; 105 | 106 | /// An AluVM library, which can be executed on a VM instance. 107 | #[derive(Clone, PartialEq, Eq, Ord, PartialOrd, Hash, Debug)] 108 | #[derive(StrictType, StrictDumb, StrictEncode, StrictDecode)] 109 | #[strict_type(lib = LIB_NAME_ALUVM)] 110 | #[derive(CommitEncode)] 111 | #[commit_encode(id = LibId, strategy = strict)] 112 | #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] 113 | pub struct Lib { 114 | /// ISA extension segment. 115 | pub isae: TinyOrdSet, 116 | /// Code segment. 117 | pub code: SmallBlob, 118 | /// Data segment. 119 | pub data: SmallBlob, 120 | /// Library segment keeping external library references. 121 | pub libs: LibsSeg, 122 | } 123 | 124 | impl StrictSerialize for Lib {} 125 | impl StrictDeserialize for Lib {} 126 | 127 | impl AsRef for Lib { 128 | fn as_ref(&self) -> &Self { self } 129 | } 130 | 131 | impl Lib { 132 | /// Compute a library identifier, which serves as a cryptographic commitment to the library 133 | /// contents. 134 | pub fn lib_id(&self) -> LibId { self.commit_id() } 135 | 136 | /// String containing all ISA extensions used by the library, enumerated with spaces. 137 | pub fn isae_string(&self) -> String { 138 | self.isae 139 | .iter() 140 | .map(IsaId::to_string) 141 | .collect::>() 142 | .join(" ") 143 | } 144 | } 145 | 146 | impl Display for Lib { 147 | fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { 148 | writeln!(f, "ISAE: {}", self.isae_string())?; 149 | writeln!(f, "CODE: {:x}", self.code)?; 150 | writeln!(f, "DATA: {:x}", self.data)?; 151 | if !self.libs.is_empty() { 152 | writeln!( 153 | f, 154 | "LIBS: {:8}", 155 | self.libs 156 | .iter() 157 | .map(LibId::to_string) 158 | .collect::>() 159 | .join("\n ") 160 | ) 161 | } else { 162 | writeln!(f, "LIBS: ~") 163 | } 164 | } 165 | } 166 | 167 | #[cfg(test)] 168 | mod test { 169 | #![cfg_attr(coverage_nightly, coverage(off))] 170 | use strict_encoding::StrictDumb; 171 | 172 | use super::*; 173 | 174 | #[test] 175 | fn lib_id_display() { 176 | let id = Lib::strict_dumb().lib_id(); 177 | assert_eq!( 178 | format!("{id}"), 179 | "alu:uZkzX1J9-i5EvGTf-J1TB79p-OBvKq5x-1U2n4qd-8Nso3Ag#reunion-cable-tractor" 180 | ); 181 | assert_eq!( 182 | format!("{id:-}"), 183 | "uZkzX1J9-i5EvGTf-J1TB79p-OBvKq5x-1U2n4qd-8Nso3Ag#reunion-cable-tractor" 184 | ); 185 | assert_eq!(format!("{id:#}"), "alu:uZkzX1J9-i5EvGTf-J1TB79p-OBvKq5x-1U2n4qd-8Nso3Ag"); 186 | assert_eq!(format!("{id:-#}"), "uZkzX1J9-i5EvGTf-J1TB79p-OBvKq5x-1U2n4qd-8Nso3Ag"); 187 | } 188 | 189 | #[test] 190 | fn lib_id_from_str() { 191 | let id = Lib::strict_dumb().lib_id(); 192 | assert_eq!( 193 | id, 194 | LibId::from_str( 195 | "alu:uZkzX1J9-i5EvGTf-J1TB79p-OBvKq5x-1U2n4qd-8Nso3Ag#reunion-cable-tractor" 196 | ) 197 | .unwrap() 198 | ); 199 | assert_eq!(id, LibId::from_str("alu:uZkzX1J9i5EvGTfJ1TB79pOBvKq5x1U2n4qd8Nso3Ag").unwrap()); 200 | assert_eq!( 201 | id, 202 | LibId::from_str( 203 | "alu:uZkzX1J9i5EvGTfJ1TB79pOBvKq5x1U2n4qd8Nso3Ag#reunion-cable-tractor" 204 | ) 205 | .unwrap() 206 | ); 207 | 208 | assert_eq!(id, LibId::from_str("uZkzX1J9i5EvGTfJ1TB79pOBvKq5x1U2n4qd8Nso3Ag").unwrap()); 209 | } 210 | } 211 | -------------------------------------------------------------------------------- /src/library/marshaller.rs: -------------------------------------------------------------------------------- 1 | // Reference rust implementation of AluVM (arithmetic logic unit virtual machine). 2 | // To find more on AluVM please check 3 | // 4 | // SPDX-License-Identifier: Apache-2.0 5 | // 6 | // Designed in 2021-2025 by Dr Maxim Orlovsky 7 | // Written in 2021-2025 by Dr Maxim Orlovsky 8 | // 9 | // Copyright (C) 2021-2024 LNP/BP Standards Association, Switzerland. 10 | // Copyright (C) 2024-2025 Laboratories for Ubiquitous Deterministic Computing (UBIDECO), 11 | // Institute for Distributed and Cognitive Systems (InDCS), Switzerland. 12 | // Copyright (C) 2021-2025 Dr Maxim Orlovsky. 13 | // All rights under the above copyrights are reserved. 14 | // 15 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 16 | // in compliance with the License. You may obtain a copy of the License at 17 | // 18 | // http://www.apache.org/licenses/LICENSE-2.0 19 | // 20 | // Unless required by applicable law or agreed to in writing, software distributed under the License 21 | // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 22 | // or implied. See the License for the specific language governing permissions and limitations under 23 | // the License. 24 | 25 | use core::fmt::{self, Debug, Formatter}; 26 | 27 | use amplify::confinement::SmallBlob; 28 | use amplify::num::{u1, u2, u3, u4, u5, u6, u7}; 29 | 30 | use super::{LibId, LibsSeg}; 31 | use crate::isa::{BytecodeRead, BytecodeWrite, CodeEofError}; 32 | 33 | /// Errors write operations 34 | #[derive(Clone, Copy, Ord, PartialOrd, Eq, PartialEq, Hash, Debug, Display, Error, From)] 35 | #[display(doc_comments)] 36 | pub enum MarshallError { 37 | /// attempt to read or write outside of code segment (i.e. at position > 0xFF). 38 | #[from(CodeEofError)] 39 | CodeNotFittingSegment, 40 | 41 | /// data size {0} exceeds limit of 0xFF bytes. 42 | DataExceedsLimit(usize), 43 | 44 | /// attempt to write data which does not fit code segment. 45 | DataNotFittingSegment, 46 | 47 | /// attempt to write library reference for the lib id {0} which is not a part of program 48 | /// segment. 49 | LibAbsent(LibId), 50 | } 51 | 52 | /// Marshals instructions to and from bytecode representation. 53 | pub struct Marshaller<'a, C, D> 54 | where 55 | C: AsRef<[u8]>, 56 | D: AsRef<[u8]>, 57 | Self: 'a, 58 | { 59 | bit_pos: u3, 60 | byte_pos: u16, 61 | bytecode: C, 62 | data: D, 63 | libs: &'a LibsSeg, 64 | } 65 | 66 | #[cfg_attr(coverage_nightly, coverage(off))] 67 | impl<'a, C, D> Debug for Marshaller<'a, C, D> 68 | where 69 | C: AsRef<[u8]>, 70 | D: AsRef<[u8]>, 71 | Self: 'a, 72 | { 73 | fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { 74 | f.debug_struct("Marshaller") 75 | .field("bytecode", &SmallBlob::from_slice_checked(self.bytecode.as_ref())) 76 | .field("byte_pos", &self.byte_pos) 77 | .field("bit_pos", &self.bit_pos) 78 | .field("data", &SmallBlob::from_slice_checked(self.data.as_ref())) 79 | .field("libs", &self.libs) 80 | .finish() 81 | } 82 | } 83 | 84 | impl<'a> Marshaller<'a, Vec, Vec> 85 | where Self: 'a 86 | { 87 | /// Creates a new marshaller using provided set of libraries. 88 | #[inline] 89 | pub fn new(libs: &'a LibsSeg) -> Self { 90 | Self { 91 | bytecode: default!(), 92 | byte_pos: 0, 93 | bit_pos: u3::MIN, 94 | data: default!(), 95 | libs, 96 | } 97 | } 98 | 99 | /// Completes marshalling, returning produced data segment. 100 | /// 101 | /// # Panics 102 | /// 103 | /// If marshaller position is not at byte margin. 104 | #[inline] 105 | pub fn finish(self) -> (SmallBlob, SmallBlob) { 106 | if self.bit_pos != u3::ZERO { 107 | panic!("incomplete marshalling") 108 | } 109 | (SmallBlob::from_checked(self.bytecode), SmallBlob::from_checked(self.data)) 110 | } 111 | } 112 | 113 | impl<'a> Marshaller<'a, SmallBlob, SmallBlob> 114 | where Self: 'a 115 | { 116 | /// Convert data accumulated by the marshaller into code and data segments. 117 | #[cfg(any(test, feature = "tests"))] 118 | pub fn into_code_data(self) -> (SmallBlob, SmallBlob) { (self.bytecode, self.data) } 119 | } 120 | 121 | impl<'a, C, D> Marshaller<'a, C, D> 122 | where 123 | C: AsRef<[u8]>, 124 | D: AsRef<[u8]>, 125 | Self: 'a, 126 | { 127 | /// Create marshaller from byte string utilizing existing bytecode. 128 | /// 129 | /// # Panics 130 | /// 131 | /// If the length of the bytecode or data segment exceeds 0xFF. 132 | #[inline] 133 | pub fn with(bytecode: C, data: D, libs: &'a LibsSeg) -> Self { 134 | Self { bytecode, byte_pos: 0, bit_pos: u3::MIN, data, libs } 135 | } 136 | 137 | /// Returns the current offset of the marshaller 138 | pub const fn offset(&self) -> (u16, u3) { (self.byte_pos, self.bit_pos) } 139 | 140 | fn read(&mut self, bit_count: u5) -> Result { 141 | let mut ret = 0u32; 142 | let mut cnt = bit_count.to_u8(); 143 | while cnt > 0 { 144 | if self.is_eof() { 145 | return Err(CodeEofError); 146 | } 147 | let byte = &self.bytecode.as_ref()[self.byte_pos as usize]; 148 | let remaining_bits = 8 - self.bit_pos.to_u8(); 149 | let mask = match remaining_bits < cnt { 150 | true => 0xFFu8 << self.bit_pos.to_u8(), 151 | false => (((1u16 << (cnt)) - 1) << (self.bit_pos.to_u8() as u16)) as u8, 152 | }; 153 | let value = ((byte & mask) >> self.bit_pos.to_u8()) as u32; 154 | ret |= value << (bit_count.to_u8() - cnt); 155 | match remaining_bits.min(cnt) { 156 | 8 => { 157 | self.inc_bytes(1)?; 158 | } 159 | _ => { 160 | self.inc_bits(u3::with(remaining_bits.min(cnt)))?; 161 | } 162 | } 163 | cnt = cnt.saturating_sub(remaining_bits); 164 | } 165 | Ok(ret) 166 | } 167 | 168 | fn inc_bits(&mut self, bit_count: u3) -> Result<(), CodeEofError> { 169 | let pos = self.bit_pos.to_u8() + bit_count.to_u8(); 170 | self.bit_pos = u3::with(pos % 8); 171 | self._inc_bytes_inner(pos as u16 / 8) 172 | } 173 | 174 | fn inc_bytes(&mut self, byte_count: u16) -> Result<(), CodeEofError> { 175 | assert_eq!( 176 | self.bit_pos.to_u8(), 177 | 0, 178 | "attempt to access (multiple) bytes at a non-byte aligned position" 179 | ); 180 | self._inc_bytes_inner(byte_count) 181 | } 182 | 183 | #[inline] 184 | fn _inc_bytes_inner(&mut self, byte_count: u16) -> Result<(), CodeEofError> { 185 | self.byte_pos = self.byte_pos.checked_add(byte_count).ok_or(CodeEofError)?; 186 | Ok(()) 187 | } 188 | } 189 | 190 | impl<'a, C, D> Marshaller<'a, C, D> 191 | where 192 | C: AsRef<[u8]> + AsMut<[u8]> + Extend, 193 | D: AsRef<[u8]>, 194 | Self: 'a, 195 | { 196 | fn write(&mut self, value: u32, bit_count: u5) -> Result<(), CodeEofError> { 197 | let mut cnt = bit_count.to_u8(); 198 | let value = ((value as u64) << (self.bit_pos.to_u8())).to_le_bytes(); 199 | let n_bytes = (cnt + self.bit_pos.to_u8()).div_ceil(8); 200 | for i in 0..n_bytes { 201 | if self.bytecode.as_ref().len() >= u16::MAX as usize { 202 | return Err(CodeEofError); 203 | } 204 | if self.is_eof() { 205 | self.bytecode.extend([0]); 206 | } 207 | let byte_pos = self.byte_pos as usize; 208 | let bit_pos = self.bit_pos.to_u8(); 209 | let byte = &mut self.bytecode.as_mut()[byte_pos]; 210 | *byte |= value[i as usize]; 211 | match (bit_pos, cnt) { 212 | (0, cnt) if cnt >= 8 => { 213 | self.inc_bytes(1)?; 214 | } 215 | (_, cnt) => { 216 | self.inc_bits(u3::with(cnt.min(8 - bit_pos)))?; 217 | } 218 | } 219 | cnt = cnt.saturating_sub(cnt.min(8 - bit_pos)); 220 | } 221 | Ok(()) 222 | } 223 | } 224 | 225 | impl<'a, C, D> Marshaller<'a, C, D> 226 | where 227 | C: AsRef<[u8]> + AsMut<[u8]>, 228 | D: AsRef<[u8]> + AsMut<[u8]> + Extend, 229 | Self: 'a, 230 | { 231 | fn write_unique(&mut self, bytes: &[u8]) -> Result { 232 | // We write the value only if the value is not yet present in the data segment 233 | let len = bytes.len(); 234 | let offset = self.data.as_ref().len(); 235 | if len == 0 { 236 | Ok(offset as u16) 237 | } else if let Some(offset) = self 238 | .data 239 | .as_ref() 240 | .windows(len) 241 | .position(|window| window == bytes) 242 | { 243 | Ok(offset as u16) 244 | } else if offset + len > u16::MAX as usize { 245 | Err(MarshallError::DataNotFittingSegment) 246 | } else { 247 | self.data.extend(bytes.iter().copied()); 248 | Ok(offset as u16) 249 | } 250 | } 251 | } 252 | 253 | impl<'a, C, D> BytecodeRead for Marshaller<'a, C, D> 254 | where 255 | C: AsRef<[u8]>, 256 | D: AsRef<[u8]>, 257 | Self: 'a, 258 | { 259 | #[inline] 260 | fn pos(&self) -> u16 { self.byte_pos } 261 | 262 | #[inline] 263 | fn seek(&mut self, byte_pos: u16) -> Result { 264 | if byte_pos as usize >= self.bytecode.as_ref().len() { 265 | return Err(CodeEofError); 266 | } 267 | let old_pos = self.byte_pos; 268 | self.byte_pos = byte_pos; 269 | Ok(old_pos) 270 | } 271 | 272 | #[inline] 273 | fn is_eof(&self) -> bool { self.byte_pos as usize >= self.bytecode.as_ref().len() } 274 | 275 | fn peek_byte(&self) -> Result { 276 | if self.is_eof() { 277 | return Err(CodeEofError); 278 | } 279 | Ok(self.bytecode.as_ref()[self.byte_pos as usize]) 280 | } 281 | 282 | fn read_bool(&mut self) -> Result { Ok(self.read(u5::with(1))? == 0x01) } 283 | 284 | fn read_1bit(&mut self) -> Result { 285 | let res = self.read(u5::with(1))? as u8; 286 | Ok(res.try_into().expect("bit extractor failure")) 287 | } 288 | 289 | fn read_2bits(&mut self) -> Result { 290 | let res = self.read(u5::with(2))? as u8; 291 | Ok(res.try_into().expect("bit extractor failure")) 292 | } 293 | 294 | fn read_3bits(&mut self) -> Result { 295 | let res = self.read(u5::with(3))? as u8; 296 | Ok(res.try_into().expect("bit extractor failure")) 297 | } 298 | 299 | fn read_4bits(&mut self) -> Result { 300 | let res = self.read(u5::with(4))? as u8; 301 | Ok(res.try_into().expect("bit extractor failure")) 302 | } 303 | 304 | fn read_5bits(&mut self) -> Result { 305 | let res = self.read(u5::with(5))? as u8; 306 | Ok(res.try_into().expect("bit extractor failure")) 307 | } 308 | 309 | fn read_6bits(&mut self) -> Result { 310 | let res = self.read(u5::with(6))? as u8; 311 | Ok(res.try_into().expect("bit extractor failure")) 312 | } 313 | 314 | fn read_7bits(&mut self) -> Result { 315 | let res = self.read(u5::with(7))? as u8; 316 | Ok(res.try_into().expect("bit extractor failure")) 317 | } 318 | 319 | fn read_byte(&mut self) -> Result { 320 | let res = self.read(u5::with(8))? as u8; 321 | Ok(res) 322 | } 323 | 324 | fn read_word(&mut self) -> Result { 325 | let res = self.read(u5::with(16))? as u16; 326 | Ok(res) 327 | } 328 | 329 | fn read_fixed( 330 | &mut self, 331 | f: impl FnOnce([u8; LEN]) -> N, 332 | ) -> Result { 333 | let pos = self.read_word()? as usize; 334 | let end = pos + LEN; 335 | if end > self.data.as_ref().len() { 336 | return Err(CodeEofError); 337 | } 338 | let mut buf = [0u8; LEN]; 339 | buf.copy_from_slice(&self.data.as_ref()[pos..end]); 340 | Ok(f(buf)) 341 | } 342 | 343 | fn read_bytes(&mut self) -> Result<(SmallBlob, bool), CodeEofError> { 344 | let pos = self.read_word()? as usize; 345 | let end = pos + self.read_word()? as usize; 346 | let ck = end >= self.data.as_ref().len(); 347 | let data = &self.data.as_ref()[pos.min(0xFF)..end.min(0xFF)]; 348 | Ok((SmallBlob::from_slice_checked(data), ck)) 349 | } 350 | 351 | fn read_ref(&mut self) -> Result 352 | where LibId: Sized { 353 | let pos = self.read_byte()? as usize; 354 | Ok(self.libs.iter().nth(pos).copied().unwrap_or_default()) 355 | } 356 | 357 | fn check_aligned(&self) { 358 | debug_assert_eq!(self.bit_pos, u3::ZERO, "not all instruction operands are read") 359 | } 360 | } 361 | 362 | impl<'a, C, D> BytecodeWrite for Marshaller<'a, C, D> 363 | where 364 | C: AsRef<[u8]> + AsMut<[u8]> + Extend, 365 | D: AsRef<[u8]> + AsMut<[u8]> + Extend, 366 | Self: 'a, 367 | { 368 | type Error = MarshallError; 369 | 370 | fn write_1bit(&mut self, data: u1) -> Result<(), MarshallError> { 371 | self.write(data.into_u8() as u32, u5::with(1)) 372 | .map_err(MarshallError::from) 373 | } 374 | 375 | fn write_2bits(&mut self, data: u2) -> Result<(), MarshallError> { 376 | self.write(data.to_u8() as u32, u5::with(2)) 377 | .map_err(MarshallError::from) 378 | } 379 | 380 | fn write_3bits(&mut self, data: u3) -> Result<(), MarshallError> { 381 | self.write(data.to_u8() as u32, u5::with(3)) 382 | .map_err(MarshallError::from) 383 | } 384 | 385 | fn write_4bits(&mut self, data: u4) -> Result<(), MarshallError> { 386 | self.write(data.to_u8() as u32, u5::with(4)) 387 | .map_err(MarshallError::from) 388 | } 389 | 390 | fn write_5bits(&mut self, data: u5) -> Result<(), MarshallError> { 391 | self.write(data.to_u8() as u32, u5::with(5)) 392 | .map_err(MarshallError::from) 393 | } 394 | 395 | fn write_6bits(&mut self, data: u6) -> Result<(), MarshallError> { 396 | self.write(data.to_u8() as u32, u5::with(6)) 397 | .map_err(MarshallError::from) 398 | } 399 | 400 | fn write_7bits(&mut self, data: u7) -> Result<(), MarshallError> { 401 | self.write(data.to_u8() as u32, u5::with(7)) 402 | .map_err(MarshallError::from) 403 | } 404 | 405 | fn write_byte(&mut self, data: u8) -> Result<(), MarshallError> { 406 | self.write(data as u32, u5::with(8)) 407 | .map_err(MarshallError::from) 408 | } 409 | 410 | fn write_word(&mut self, data: u16) -> Result<(), MarshallError> { 411 | self.write(data as u32, u5::with(16)) 412 | .map_err(MarshallError::from) 413 | } 414 | 415 | fn write_fixed(&mut self, data: [u8; LEN]) -> Result<(), Self::Error> { 416 | if LEN >= u16::MAX as usize { 417 | return Err(MarshallError::DataExceedsLimit(LEN)); 418 | } 419 | let offset = self.write_unique(&data)?; 420 | self.write_word(offset) 421 | } 422 | 423 | fn write_bytes(&mut self, data: &[u8]) -> Result<(), Self::Error> { 424 | let len = data.len(); 425 | if len >= u16::MAX as usize { 426 | return Err(MarshallError::DataExceedsLimit(len)); 427 | } 428 | let offset = self.write_unique(data)?; 429 | self.write_word(offset)?; 430 | self.write_word(len as u16) 431 | } 432 | 433 | fn write_ref(&mut self, id: LibId) -> Result<(), Self::Error> { 434 | let pos = self 435 | .libs 436 | .iter() 437 | .position(|lib| *lib == id) 438 | .ok_or(MarshallError::LibAbsent(id))?; 439 | self.write_byte(pos as u8) 440 | } 441 | 442 | fn check_aligned(&self) { 443 | debug_assert_eq!(self.bit_pos, u3::ZERO, "not all instruction operands are written") 444 | } 445 | } 446 | 447 | #[cfg(test)] 448 | mod tests { 449 | #![cfg_attr(coverage_nightly, coverage(off))] 450 | use super::*; 451 | 452 | #[test] 453 | fn read() { 454 | let libseg = LibsSeg::default(); 455 | let mut marshaller = Marshaller::with([0b01010111, 0b00001001], [], &libseg); 456 | assert_eq!(marshaller.read_2bits().unwrap().to_u8(), 0b00000011); 457 | assert_eq!(marshaller.read_2bits().unwrap().to_u8(), 0b00000001); 458 | assert_eq!(marshaller.read_byte().unwrap(), 0b10010101); 459 | 460 | let mut marshaller = Marshaller::with([0b01010111, 0b00001001], [], &libseg); 461 | assert_eq!(marshaller.read_2bits().unwrap().to_u8(), 0b00000011); 462 | assert_eq!(marshaller.read_3bits().unwrap().to_u8(), 0b00000101); 463 | assert_eq!(marshaller.read_byte().unwrap(), 0b01001010); 464 | 465 | let mut marshaller = Marshaller::with([0b01110111, 0b00001111], [], &libseg); 466 | assert_eq!(marshaller.read_byte().unwrap(), 0b01110111); 467 | assert_eq!(marshaller.read_3bits().unwrap().to_u8(), 0b00000111); 468 | assert_eq!(marshaller.read_5bits().unwrap().to_u8(), 0b00000001); 469 | 470 | let bytes = 0b11101011_11110000_01110111; 471 | let mut marshaller = Marshaller::with(u32::to_le_bytes(bytes), [], &libseg); 472 | assert_eq!(marshaller.read(u5::with(24)).unwrap(), bytes); 473 | } 474 | 475 | #[test] 476 | fn read_eof() { 477 | let libseg = LibsSeg::default(); 478 | let mut marshaller = Marshaller::with([0b01010111], [], &libseg); 479 | assert_eq!(marshaller.read_2bits().unwrap().to_u8(), 0b00000011); 480 | assert_eq!(marshaller.read_2bits().unwrap().to_u8(), 0b00000001); 481 | assert!(marshaller.read_byte().is_err()); 482 | } 483 | 484 | #[test] 485 | fn write() { 486 | let libseg = LibsSeg::default(); 487 | let mut marshaller = Marshaller::with(vec![], vec![], &libseg); 488 | marshaller.write_2bits(u2::with(0b00000011)).unwrap(); 489 | marshaller.write_3bits(u3::with(0b00000101)).unwrap(); 490 | marshaller.write_7bits(u7::with(0b01011111)).unwrap(); 491 | marshaller.write_byte(0b11100111).unwrap(); 492 | marshaller.write_bool(true).unwrap(); 493 | marshaller.write_3bits(u3::with(0b00000110)).unwrap(); 494 | let two_bytes = 0b11110000_10101010u16; 495 | marshaller.write_word(two_bytes).unwrap(); 496 | let number = 255u8; 497 | marshaller.write_fixed(255u8.to_le_bytes()).unwrap(); 498 | let (code, data) = marshaller.finish(); 499 | 500 | let mut marshaller = Marshaller::with(code, data, &libseg); 501 | assert_eq!(marshaller.read_2bits().unwrap().to_u8(), 0b00000011); 502 | assert_eq!(marshaller.read_3bits().unwrap().to_u8(), 0b00000101); 503 | assert_eq!(marshaller.read_7bits().unwrap().to_u8(), 0b01011111); 504 | assert_eq!(marshaller.read_byte().unwrap(), 0b11100111); 505 | assert!(marshaller.read_bool().unwrap()); 506 | assert_eq!(marshaller.read_3bits().unwrap().to_u8(), 0b00000110); 507 | assert_eq!(marshaller.read_word().unwrap(), two_bytes); 508 | assert_eq!(marshaller.read_fixed(u8::from_le_bytes).unwrap(), number); 509 | } 510 | 511 | #[test] 512 | fn write_data() { 513 | let libseg = LibsSeg::default(); 514 | let mut marshaller = Marshaller::with(vec![], vec![], &libseg); 515 | marshaller.write_fixed(256u16.to_le_bytes()).unwrap(); 516 | assert_eq!(marshaller.data, vec![0, 1]); 517 | } 518 | 519 | #[test] 520 | fn write_eof() { 521 | let libseg = LibsSeg::default(); 522 | let mut marshaller = Marshaller::with(vec![0x00; 0xFFFD], vec![], &libseg); 523 | marshaller.seek(0xFFFD).unwrap_err(); 524 | marshaller.byte_pos = 0xFFFD; 525 | marshaller.write_2bits(u2::with(0b00000011)).unwrap(); 526 | marshaller.write_3bits(u3::with(0b00000101)).unwrap(); 527 | marshaller.write_7bits(u7::with(0b01011111)).unwrap(); 528 | marshaller.write_byte(0b11100111).unwrap_err(); 529 | assert_eq!(&marshaller.bytecode[0xFFFD..], &[0b11110111, 0b1011]); 530 | } 531 | 532 | #[test] 533 | #[should_panic(expected = "incomplete marshalling")] 534 | fn incomplete_byte() { 535 | let libseg = LibsSeg::default(); 536 | let mut marshaller = Marshaller::with(vec![], vec![], &libseg); 537 | marshaller.write_2bits(u2::with(0b00000011)).unwrap(); 538 | marshaller.write_3bits(u3::with(0b00000101)).unwrap(); 539 | marshaller.write_7bits(u7::with(0b00000000)).unwrap(); 540 | marshaller.finish(); 541 | } 542 | 543 | #[test] 544 | fn bit_order() { 545 | let libseg = LibsSeg::default(); 546 | let mut marshaller = Marshaller::with(vec![], vec![], &libseg); 547 | marshaller.write_2bits(u2::with(0b00000011)).unwrap(); 548 | marshaller.write_3bits(u3::with(0b00000101)).unwrap(); 549 | marshaller.write_3bits(u3::with(0b00000001)).unwrap(); 550 | let (code, data) = marshaller.finish(); 551 | assert_eq!(code.release(), vec![0b0011_0111u8]); 552 | assert!(data.is_empty()); 553 | } 554 | } 555 | -------------------------------------------------------------------------------- /src/library/mod.rs: -------------------------------------------------------------------------------- 1 | // Reference rust implementation of AluVM (arithmetic logic unit virtual machine). 2 | // To find more on AluVM please check 3 | // 4 | // SPDX-License-Identifier: Apache-2.0 5 | // 6 | // Designed in 2021-2025 by Dr Maxim Orlovsky 7 | // Written in 2021-2025 by Dr Maxim Orlovsky 8 | // 9 | // Copyright (C) 2021-2024 LNP/BP Standards Association, Switzerland. 10 | // Copyright (C) 2024-2025 Laboratories for Ubiquitous Deterministic Computing (UBIDECO), 11 | // Institute for Distributed and Cognitive Systems (InDCS), Switzerland. 12 | // Copyright (C) 2021-2025 Dr Maxim Orlovsky. 13 | // All rights under the above copyrights are reserved. 14 | // 15 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 16 | // in compliance with the License. You may obtain a copy of the License at 17 | // 18 | // http://www.apache.org/licenses/LICENSE-2.0 19 | // 20 | // Unless required by applicable law or agreed to in writing, software distributed under the License 21 | // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 22 | // or implied. See the License for the specific language governing permissions and limitations under 23 | // the License. 24 | 25 | mod lib; 26 | #[cfg(feature = "armor")] 27 | pub mod armor; 28 | mod assembler; 29 | mod compiler; 30 | mod marshaller; 31 | mod exec; 32 | 33 | pub use assembler::AssemblerError; 34 | pub use compiler::{CompiledLib, CompilerError}; 35 | pub use exec::Jump; 36 | pub use lib::{Lib, LibId, LibSite, LibsSeg}; 37 | pub use marshaller::{MarshallError, Marshaller}; 38 | -------------------------------------------------------------------------------- /src/stl.rs: -------------------------------------------------------------------------------- 1 | // Reference rust implementation of AluVM (arithmetic logic unit virtual machine). 2 | // To find more on AluVM please check 3 | // 4 | // SPDX-License-Identifier: Apache-2.0 5 | // 6 | // Designed in 2021-2025 by Dr Maxim Orlovsky 7 | // Written in 2021-2025 by Dr Maxim Orlovsky 8 | // 9 | // Copyright (C) 2021-2024 LNP/BP Standards Association, Switzerland. 10 | // Copyright (C) 2024-2025 Laboratories for Ubiquitous Deterministic Computing (UBIDECO), 11 | // Institute for Distributed and Cognitive Systems (InDCS), Switzerland. 12 | // Copyright (C) 2021-2025 Dr Maxim Orlovsky. 13 | // All rights under the above copyrights are reserved. 14 | // 15 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 16 | // in compliance with the License. You may obtain a copy of the License at 17 | // 18 | // http://www.apache.org/licenses/LICENSE-2.0 19 | // 20 | // Unless required by applicable law or agreed to in writing, software distributed under the License 21 | // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 22 | // or implied. See the License for the specific language governing permissions and limitations under 23 | // the License. 24 | 25 | //! Strict types library generator methods. 26 | 27 | use strict_types::typelib::{CompileError, LibBuilder}; 28 | use strict_types::TypeLib; 29 | 30 | use crate::{CoreConfig, Lib, LibSite, LIB_NAME_ALUVM}; 31 | 32 | /// Strict type id for the lib-old providing data types from this crate. 33 | pub const LIB_ID_ALUVM: &str = 34 | "stl:t1kptI_t-R8Ei0Wa-e0m53SK-toGi5AC-si8GK5F-MbQp588#reward-accent-swim"; 35 | 36 | #[allow(clippy::result_large_err)] 37 | fn _aluvm_stl() -> Result { 38 | LibBuilder::with(libname!(LIB_NAME_ALUVM), [ 39 | strict_types::stl::std_stl().to_dependency_types(), 40 | strict_types::stl::strict_types_stl().to_dependency_types(), 41 | ]) 42 | .transpile::() 43 | .transpile::() 44 | .transpile::() 45 | .compile() 46 | } 47 | 48 | /// Generates strict type lib-old providing data types from this crate. 49 | pub fn aluvm_stl() -> TypeLib { _aluvm_stl().expect("invalid strict type AluVM lib-old") } 50 | 51 | #[cfg(test)] 52 | mod test { 53 | #![cfg_attr(coverage_nightly, coverage(off))] 54 | use super::*; 55 | 56 | #[test] 57 | fn lib_id() { 58 | let lib = aluvm_stl(); 59 | assert_eq!(lib.id().to_string(), LIB_ID_ALUVM); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/vm.rs: -------------------------------------------------------------------------------- 1 | // Reference rust implementation of AluVM (arithmetic logic unit virtual machine). 2 | // To find more on AluVM please check 3 | // 4 | // SPDX-License-Identifier: Apache-2.0 5 | // 6 | // Designed in 2021-2025 by Dr Maxim Orlovsky 7 | // Written in 2021-2025 by Dr Maxim Orlovsky 8 | // 9 | // Copyright (C) 2021-2024 LNP/BP Standards Association, Switzerland. 10 | // Copyright (C) 2024-2025 Laboratories for Ubiquitous Deterministic Computing (UBIDECO), 11 | // Institute for Distributed and Cognitive Systems (InDCS), Switzerland. 12 | // Copyright (C) 2021-2025 Dr Maxim Orlovsky. 13 | // All rights under the above copyrights are reserved. 14 | // 15 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 16 | // in compliance with the License. You may obtain a copy of the License at 17 | // 18 | // http://www.apache.org/licenses/LICENSE-2.0 19 | // 20 | // Unless required by applicable law or agreed to in writing, software distributed under the License 21 | // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 22 | // or implied. See the License for the specific language governing permissions and limitations under 23 | // the License. 24 | 25 | //! Alu virtual machine 26 | 27 | use core::marker::PhantomData; 28 | 29 | use crate::core::{Core, CoreConfig, CoreExt, Status}; 30 | use crate::isa::{Instr, Instruction}; 31 | use crate::library::{Jump, Lib, LibId, LibSite}; 32 | 33 | /// Alu virtual machine providing single-core execution environment 34 | #[derive(Clone, Debug, Default)] 35 | pub struct Vm> 36 | where Isa: Instruction 37 | { 38 | /// A set of registers 39 | pub core: Core, 40 | 41 | phantom: PhantomData, 42 | } 43 | 44 | /// Runtime for program execution. 45 | impl Vm 46 | where Isa: Instruction 47 | { 48 | /// Constructs new virtual machine instance with default core configuration. 49 | pub fn new() -> Self { Self { core: Core::new(), phantom: Default::default() } } 50 | 51 | /// Constructs new virtual machine instance with default core configuration. 52 | pub fn with(config: CoreConfig, cx_config: ::Config) -> Self { 53 | Self { 54 | core: Core::with(config, cx_config), 55 | phantom: Default::default(), 56 | } 57 | } 58 | 59 | /// Resets all registers of the VM except those which were set up with the config object. 60 | pub fn reset(&mut self) { self.core.reset(); } 61 | 62 | /// Executes the program starting from the provided entry point. 63 | /// 64 | /// # Returns 65 | /// 66 | /// Value of the `CK` register at the end of the program execution. 67 | pub fn exec>( 68 | &mut self, 69 | entry_point: LibSite, 70 | context: &Isa::Context<'_>, 71 | lib_resolver: impl Fn(LibId) -> Option, 72 | ) -> Status { 73 | let mut site = entry_point; 74 | let mut skip = false; 75 | loop { 76 | if let Some(lib) = lib_resolver(site.lib_id) { 77 | let jump = lib 78 | .as_ref() 79 | .exec::(site.offset, skip, &mut self.core, context); 80 | match jump { 81 | Jump::Halt => { 82 | #[cfg(feature = "log")] 83 | { 84 | let core = &self.core; 85 | let z = "\x1B[0m"; 86 | let y = "\x1B[0;33m"; 87 | let c = if core.ck().is_ok() { "\x1B[0;32m" } else { "\x1B[0;31m" }; 88 | eprintln!(); 89 | eprintln!( 90 | ">; execution stopped: {y}CK{z} {c}{}{z}, {y}CO{z} {c}{}{z}", 91 | core.ck(), 92 | core.co() 93 | ); 94 | } 95 | break; 96 | } 97 | Jump::Instr(new_site) => { 98 | skip = false; 99 | site = new_site.into(); 100 | } 101 | Jump::Next(new_site) => { 102 | skip = true; 103 | site = new_site.into(); 104 | } 105 | } 106 | } else { 107 | let fail = self.core.fail_ck(); 108 | // We stop execution if the failure flag is set 109 | if fail { 110 | break; 111 | } else if let Some(pos) = site.offset.checked_add(1) { 112 | // Otherwise we just proceed 113 | site.offset = pos; 114 | } else { 115 | // or we still stop if we reached the end of the code 116 | break; 117 | } 118 | }; 119 | } 120 | self.core.ck() 121 | } 122 | } 123 | -------------------------------------------------------------------------------- /stl/AluVM@0.1.0.sta: -------------------------------------------------------------------------------- 1 | -----BEGIN STRICT TYPE LIB----- 2 | Id: stl:t1kptI_t-R8Ei0Wa-e0m53SK-toGi5AC-si8GK5F-MbQp588#reward-accent-swim 3 | Name: AluVM 4 | Dependencies: Std#delete-roman-hair 5 | Check-SHA256: 14b68ec0fe5d0af2cfe20b9d141c5dbce404dfb3b7e694581f930dac7697c649 6 | 7 | 1wm|eR!sqdiR(=d3vg7gbV~*3!PlK51EySK%g?1}nECovJTYnmQ*>kj15|Z*pZrZ*FF3X9fZUXkl!00)mO_O%DrjRIhYP1?a)oog)LLTw}}6rDvG=`c^zKYGH;V(R;4& 10 | W&+>mb;*F>vukd;=m`ygb@x#_>`RmOO$}pjZE$R5cxiNbOlfTZ1OfmAZf|a7000011aog~WdH>M000OD 11 | NpoRIWCZ~L1p)$siR(=d3vg7gbV~*3!PlK51EySK%g?1}nECovJTYo|M~0;jPqm@t3InIR0Ny%Ft`YGA 12 | h^_-OV-~qNrBQ4E2m*qM>rD>}a8$2!O9kk`*PSB+rd(so&!uOW`TABoF=~28hNTZrwV~w-1E;$H-a1RJ 13 | 5%B|vt^+e;7P&d4QEUJJ00000000jF000000009_X<`Nh1Zi_&WdI2QWv$_rj1;Ln94Z{?gZ&kLW~lle 14 | DM+%Me^-~ElJ>=!0000000000{{R30000001Y>VxWdH~O06+i$000000096000000000DJVRT^t2mk;; 15 | 0000000000|Nj60000001Z-(ya{vher!Z9lE%{u?@QI^EqCb}2Q7OO^w+`_q*ddTXmHSf)0000000000 16 | {{R30000001x#sTNn`~900#g7Kp+4IOle|MX>?@<0tIYoVo78Hr!Z9lE%{u?@QI^EqCb}2Q7OO^w+`_q 17 | *ddTXmHSf)25)9&b7gb@00I 18 | 19 | -----END STRICT TYPE LIB----- 20 | 21 | -------------------------------------------------------------------------------- /stl/AluVM@0.1.0.stl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AluVM/aluvm/b72e543d4373036965323775b6113e05a0b43bef/stl/AluVM@0.1.0.stl -------------------------------------------------------------------------------- /stl/AluVM@0.1.0.sty: -------------------------------------------------------------------------------- 1 | {- 2 | Id: stl:t1kptI_t-R8Ei0Wa-e0m53SK-toGi5AC-si8GK5F-MbQp588#reward-accent-swim 3 | Name: AluVM 4 | Version: 0.1.0 5 | Description: AluVM data type library 6 | Author: Dr Maxim Orlovsky 7 | Copyright (C) 2024-2025 Laboratories for Ubiquitous Deterministic Computing (UBIDECO), 8 | Institute for Distributed and Cognitive Systems (InDCS), Switzerland. 9 | Copyright (C) 2021-2025 Dr Maxim Orlovsky. 10 | License: Apache-2.0 11 | -} 12 | 13 | @context 14 | typelib AluVM 15 | 16 | import Std#delete-roman-hair 17 | use Bool#oxygen-complex-duet 18 | use AlphaCapsNum#aladdin-zebra-marble 19 | 20 | 21 | @mnemonic(ventura-ibiza-special) 22 | data CoreConfig : halt Std.Bool, complexityLim U64? 23 | 24 | @mnemonic(mobile-letter-absorb) 25 | data IsaId : Std.AlphaCapsNum, [Std.AlphaCapsNum ^ ..0xf] 26 | 27 | @mnemonic(pinball-legend-camel) 28 | data Lib : isae {IsaId ^ ..0xff} 29 | , code [Byte] 30 | , data [Byte] 31 | , libs {LibId ^ ..0xff} 32 | 33 | @mnemonic(germany-culture-olivia) 34 | data LibId : [Byte ^ 32] 35 | 36 | @mnemonic(friend-beatles-carlo) 37 | data LibSite : libId LibId, offset U16 38 | 39 | 40 | -------------------------------------------------------------------------------- /tests/exec.rs: -------------------------------------------------------------------------------- 1 | // Reference rust implementation of AluVM (arithmetic logic unit virtual machine). 2 | // To find more on AluVM please check 3 | // 4 | // SPDX-License-Identifier: Apache-2.0 5 | // 6 | // Designed in 2021-2025 by Dr Maxim Orlovsky 7 | // Written in 2021-2025 by Dr Maxim Orlovsky 8 | // 9 | // Copyright (C) 2021-2024 LNP/BP Standards Association, Switzerland. 10 | // Copyright (C) 2024-2025 Laboratories for Ubiquitous Deterministic Computing (UBIDECO), 11 | // Institute for Distributed and Cognitive Systems (InDCS), Switzerland. 12 | // Copyright (C) 2021-2025 Dr Maxim Orlovsky. 13 | // All rights under the above copyrights are reserved. 14 | // 15 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 16 | // in compliance with the License. You may obtain a copy of the License at 17 | // 18 | // http://www.apache.org/licenses/LICENSE-2.0 19 | // 20 | // Unless required by applicable law or agreed to in writing, software distributed under the License 21 | // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 22 | // or implied. See the License for the specific language governing permissions and limitations under 23 | // the License. 24 | 25 | extern crate alloc; 26 | 27 | use aluvm::isa::{CtrlInstr, Instr}; 28 | use aluvm::regs::Status; 29 | use aluvm::{aluasm, CompiledLib, CoreConfig, LibId, LibSite, Vm}; 30 | 31 | fn code() -> Vec> { 32 | const MAIN: u16 = 0; 33 | const SUB: u16 = 1; 34 | const END: u16 = 2; 35 | 36 | aluasm! { 37 | routine MAIN: 38 | chk CO; 39 | chk CK; 40 | 41 | jif CO, MAIN; 42 | jif CO, -1; 43 | 44 | jif CK, MAIN; 45 | jif CK, -1; 46 | 47 | fail CK; 48 | mov CO, CK; 49 | chk CK; 50 | not CO; 51 | chk CO; 52 | 53 | jmp +5; 54 | jmp MAIN; // this is skipped 55 | 56 | call SUB; 57 | stop; 58 | 59 | routine SUB: 60 | jmp END; 61 | label END: 62 | ret; 63 | } 64 | } 65 | 66 | #[test] 67 | fn run() { 68 | let code = code(); 69 | 70 | let lib = CompiledLib::compile(code.clone(), &[]).unwrap().into_lib(); 71 | let mut disasm = lib.disassemble::>().unwrap(); 72 | assert_eq!(disasm[14], CtrlInstr::Fn { pos: 27 }.into()); 73 | assert_eq!(disasm[17], CtrlInstr::Jmp { pos: 31 }.into()); 74 | disasm[14] = CtrlInstr::Fn { pos: 1 }.into(); 75 | disasm[17] = CtrlInstr::Jmp { pos: 2 }.into(); 76 | assert_eq!(disasm, code); 77 | 78 | let mut vm_main = 79 | Vm::>::with(CoreConfig { halt: false, complexity_lim: None }, ()); 80 | let resolver = |_: LibId| Some(&lib); 81 | let status = vm_main.exec(LibSite::new(lib.lib_id(), 0), &(), resolver); 82 | assert_eq!(status, Status::Ok); 83 | } 84 | 85 | #[test] 86 | fn print_disassemble() { 87 | let lib = CompiledLib::compile(code(), &[]).unwrap().into_lib(); 88 | let mut buf = Vec::new(); 89 | lib.print_disassemble::>(&mut buf).unwrap(); 90 | assert_eq!( 91 | String::from_utf8(buf).unwrap(), 92 | "offset 000000: nop 93 | offset 000001: chk CO 94 | offset 000002: chk CK 95 | offset 000003: jif CO, 0 96 | offset 000006: jif CO, -1 97 | offset 000008: jif CK, 0 98 | offset 000011: jif CK, -1 99 | offset 000013: fail CK 100 | offset 000014: mov CO, CK 101 | offset 000015: chk CK 102 | offset 000016: not CO 103 | offset 000017: chk CO 104 | offset 000018: jmp +5 105 | offset 000020: jmp 0 106 | offset 000023: call 27 107 | offset 000026: stop 108 | offset 000027: nop 109 | offset 000028: jmp 31 110 | offset 000031: nop 111 | offset 000032: ret 112 | " 113 | ); 114 | } 115 | --------------------------------------------------------------------------------