From e7d254e24262767a3e26dc379350fdb3ab5fe513 Mon Sep 17 00:00:00 2001 From: Dario Anongba Varela Date: Tue, 3 Dec 2024 14:41:09 +0100 Subject: [PATCH 1/4] chore: Initial commit --- .appveyor.yml | 11 --- .gitignore | 10 ++- CHANGELOG.md | 8 ++ CONTRIBUTING.md | 112 ++++++++++++++++++++++++ DEVELOPMENT_CYCLE.md | 12 +++ LICENSE | 14 +++ LICENSE-APACHE | 201 +++++++++++++++++++++++++++++++++++++++++++ LICENSE-MIT | 16 ++++ LICENSE_MIT | 25 ------ README.md | 87 +++++++++++-------- clippy.toml | 1 + rust-version | 1 + static/bdk.png | Bin 0 -> 5661 bytes 13 files changed, 427 insertions(+), 71 deletions(-) delete mode 100644 .appveyor.yml create mode 100644 CHANGELOG.md create mode 100644 CONTRIBUTING.md create mode 100644 DEVELOPMENT_CYCLE.md create mode 100644 LICENSE create mode 100644 LICENSE-APACHE create mode 100644 LICENSE-MIT delete mode 100644 LICENSE_MIT create mode 100644 clippy.toml create mode 100644 rust-version create mode 100644 static/bdk.png diff --git a/.appveyor.yml b/.appveyor.yml deleted file mode 100644 index 50910bd..0000000 --- a/.appveyor.yml +++ /dev/null @@ -1,11 +0,0 @@ -install: - - appveyor-retry appveyor DownloadFile https://win.rustup.rs/ -FileName rustup-init.exe - - if not defined RUSTFLAGS rustup-init.exe -y --default-host x86_64-pc-windows-msvc --default-toolchain nightly - - set PATH=%PATH%;C:\Users\appveyor\.cargo\bin - - rustc -V - - cargo -V - -build: false - -test_script: - - cargo test --locked diff --git a/.gitignore b/.gitignore index f84d100..cfd8b1e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,9 +1,17 @@ /target **/*.rs.bk Cargo.lock +/.vscode +.idea +*.swp +.cargo + bin/ pkg/ wasm-pack.log tmp/ -.env \ No newline at end of file +.DS_Store + +.env +.env.*.local \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..efbe75b --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,8 @@ +# Changelog + +All notable changes to this project can be found here and in each release's git tag and can be viewed with `git tag -ln100 "v*"`. See also [DEVELOPMENT_CYCLE.md](DEVELOPMENT_CYCLE.md) for more details. + +Contributors do not need to change this file but do need to add changelog details in their PR descriptions. The person making the next release will collect changelog details from included PRs and edit this file prior to each release. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..d823475 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,112 @@ +# Contributing to BDK-WASM + +The BDK-WASM project operates an open contributor model where anyone is welcome to +contribute towards development in the form of peer review, documentation, +testing and patches. + +Anyone is invited to contribute without regard to technical experience, +"expertise", OSS experience, age, or other concern. However, the development of +cryptocurrencies demands a high-level of rigor, adversarial thinking, thorough +testing and risk-minimization. +Any bug may cost users real money. That being said, we deeply welcome people +contributing for the first time to an open source project or picking up Rust while +contributing. Don't be shy, you'll learn. + +The project is currently maintained by the [MetaMask](https://github.com/MetaMask) organization. + +## Communications Channels + +Communication about BDK happens primarily on the [BDK Discord](https://discord.gg/dstn4dQ). + +Discussion about code base improvements happens in GitHub [issues](https://github.com/MetaMask/bdk-wasm/issues) and +on [pull requests](https://github.com/MetaMask/bdk-wasm/pulls). + +## Contribution Workflow + +The codebase is maintained using the "contributor workflow" where everyone +without exception contributes patch proposals using "pull requests". This +facilitates social contribution, easy testing and peer review. + +To contribute a patch, the workflow is as follows: + +1. Fork Repository +2. Create topic branch +3. Commit patches + +In general commits should be atomic and diffs should be easy to read. +For this reason do not mix any formatting fixes or code moves with actual code +changes. Further, each commit, individually, should compile and pass tests, in +order to ensure git bisect and other automated tools function properly. + +When adding a new feature, thought must be given to the long term technical +debt. +Every new feature should be covered by functional tests where possible. + +When refactoring, structure your PR to make it easy to review and don't +hesitate to split it into multiple small, focused PRs. + +The Minimum Supported Rust Version is **1.63.0** (enforced by our CI). + +Commits should cover both the issue fixed and the solution's rationale. +These [guidelines](https://chris.beams.io/posts/git-commit/) should be kept in mind. Commit messages follow the ["Conventional Commits 1.0.0"](https://www.conventionalcommits.org/en/v1.0.0/) to make commit histories easier to read by humans and automated tools. All commits must be [GPG signed](https://docs.github.com/en/authentication/managing-commit-signature-verification/signing-commits). + +To facilitate communication with other contributors, the project is making use +of GitHub's "assignee" field. First check that no one is assigned and then +comment suggesting that you're working on it. If someone is already assigned, +don't hesitate to ask if the assigned party or previous commenter are still +working on it if it has been awhile. + +## Deprecation policy + +Where possible, breaking existing APIs should be avoided. Instead, add new APIs and +use [`#[deprecated]`](https://github.com/rust-lang/rfcs/blob/master/text/1270-deprecation.md) +to discourage use of the old one. + +Deprecated APIs are typically maintained for one release cycle. In other words, an +API that has been deprecated with the 0.10 release can be expected to be removed in the +0.11 release. This allows for smoother upgrades without incurring too much technical +debt inside this library. + +If you deprecated an API as part of a contribution, we encourage you to "own" that API +and send a follow-up to remove it as part of the next release cycle. + +## Peer review + +Anyone may participate in peer review which is expressed by comments in the +pull request. Typically reviewers will review the code for obvious errors, as +well as test out the patch set and opine on the technical merits of the patch. +PR should be reviewed first on the conceptual level before focusing on code +style or grammar fixes. + +To merge a PR we require all CI tests to pass, the PR has at least one approving review by a maintainer with write access, and reasonable criticisms have been addressed. + +## Coding Conventions + +This codebase uses spaces, not tabs. +Use `cargo fmt` with the default settings to format code before committing. +This is also enforced by the CI. +All public items must be documented. We adhere to the [Rust API Guidelines](https://rust-lang.github.io/api-guidelines/about.html) with respect to documentation. + +The library is written using safe rust. Special consideration must be given to code which proposes an exception to the rule. + +All new features require testing. Tests should be unique and self-describing. If a test is in development or is broken or no longer useful, then a reason should be given for adding the `#[ignore]` attribute. + +## Security + +This repository being mainly a wrapper around the BDK (Rust) implementation, security is mainly inherited from the BDK and the goal of this package is not to enforce security beyond the features that may be added as part of the JS bindings. + +## Testing + +Due to the modular nature of the project, writing new functional tests is easy +and good test coverage of the codebase is an important goal. +Refactoring the project to enable fine-grained unit testing is also an ongoing +effort. + +## Going further + +You may be interested by Jon Atacks guide on [How to review Bitcoin Core PRs](https://github.com/jonatack/bitcoin-development/blob/master/how-to-review-bitcoin-core-prs.md) +and [How to make Bitcoin Core PRs](https://github.com/jonatack/bitcoin-development/blob/master/how-to-make-bitcoin-core-prs.md). +While there are differences between the projects in terms of context and +maturity, many of the suggestions offered apply to this project. + +Overall, have fun :) diff --git a/DEVELOPMENT_CYCLE.md b/DEVELOPMENT_CYCLE.md new file mode 100644 index 0000000..69128c1 --- /dev/null +++ b/DEVELOPMENT_CYCLE.md @@ -0,0 +1,12 @@ +# Development Cycle + +This project uses [Semantic Versioning], but is currently at MAJOR version zero (0.y.z) meaning it is still in initial development. Anything MAY change at any time. The public API SHOULD NOT be considered stable. Until we reach version `1.0.0` we will do our best to document any breaking API changes in the changelog info attached to each release tag. + +We decided to maintain a faster release cycle while the library is still in "beta", i.e. before release `1.0.0`: since we are constantly adding new features and, even more importantly, fixing issues, we want developers to have access to those updates as fast as possible. + +Once the project reaches a more mature state (>= `1.0.0`), we will very likely switch to longer release cycles. + +To create a new release a release manager will create a new issue using the `Release` template and follow the template instructions. + +[used by the Rust language]: https://doc.rust-lang.org/book/appendix-07-nightly-rust.html +[Semantic Versioning]: https://semver.org/ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..9c61848 --- /dev/null +++ b/LICENSE @@ -0,0 +1,14 @@ +This software is licensed under [Apache 2.0](LICENSE-APACHE) or +[MIT](LICENSE-MIT), at your option. + +Some files retain their own copyright notice, however, for full authorship +information, see version control history. + +Except as otherwise noted in individual files, all files in this repository are +licensed under the Apache License, Version 2.0 or the MIT license , at your option. + +You may not use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of this software or any files in this repository except in +accordance with one or both of these licenses. \ No newline at end of file diff --git a/LICENSE-APACHE b/LICENSE-APACHE new file mode 100644 index 0000000..f49a4e1 --- /dev/null +++ b/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/LICENSE-MIT b/LICENSE-MIT new file mode 100644 index 0000000..9d982a4 --- /dev/null +++ b/LICENSE-MIT @@ -0,0 +1,16 @@ +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/LICENSE_MIT b/LICENSE_MIT deleted file mode 100644 index 547bcd1..0000000 --- a/LICENSE_MIT +++ /dev/null @@ -1,25 +0,0 @@ -Copyright (c) 2018 Dario Anongba Varela - -Permission is hereby granted, free of charge, to any -person obtaining a copy of this software and associated -documentation files (the "Software"), to deal in the -Software without restriction, including without -limitation the rights to use, copy, modify, merge, -publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software -is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice -shall be included in all copies or substantial portions -of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF -ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED -TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT -SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR -IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md index 38ed96f..242c324 100644 --- a/README.md +++ b/README.md @@ -1,67 +1,86 @@
+

The Bitcoin Dev Kit: WebAssembly

-

wasm-pack-template

+ - A template for kick starting a Rust and WebAssembly project using wasm-pack. +

+ The Bitcoin Dev Kit for Browsers and Node! +

- Build Status + NPM Package + MIT or Apache-2.0 Licensed + + Rustc Version 1.63.0+ + Chat on Discord

-

- Tutorial - | - Chat -

+Built with 🦀🕸 by The Rust and WebAssembly Working Group - Built with 🦀🕸 by The Rust and WebAssembly Working Group
## About -[**📚 Read this template tutorial! 📚**][template-docs] +The `bdk-wasm` library aims at providing access to the excellent [BitcoinDevKit](https://github.com/bitcoindevkit/bdk) to JS and Node environments (and eventually any device supporting WebAssembly). +It specializes in compiling BDK on the `wasm32-unknown-unknown` target and use [`wasm-bindgen`](https://github.com/rustwasm/wasm-bindgen) to create JS bindings. -This template is designed for compiling Rust libraries into WebAssembly and -publishing the resulting package to NPM. +This repo also handles the packaging and publishing of the `bdk` NPM package, using `wasm-pack`. -Be sure to check out [other `wasm-pack` tutorials online][tutorials] for other -templates and usages of `wasm-pack`. +## Browser Usage -[tutorials]: https://rustwasm.github.io/docs/wasm-pack/tutorials/index.html -[template-docs]: https://rustwasm.github.io/docs/wasm-pack/tutorials/npm-browser-packages/index.html +```sh +yarn add bdk +``` -## 🚴 Usage +## Development Environment -### 🐑 Use `cargo generate` to Clone this Template +### Requirements -[Learn more about `cargo generate` here.](https://github.com/ashleygwilliams/cargo-generate) +- Install [Rust](https://www.rust-lang.org/tools/install) +- Install [wasm-pack](https://rustwasm.github.io/wasm-pack/installer/) -``` -cargo generate --git https://github.com/rustwasm/wasm-pack-template.git --name my-project -cd my-project +#### MacOS special requirement + +On MacOS, you should replace the default `llvm` with the one from `brew`: + +```sh +brew install llvm ``` -### 🛠️ Build with `wasm-pack build` +We recommend creating a `.cargo` folder at the root of the repo with the following `config.toml` file: +```toml +[env] +AR = "/opt/homebrew/opt/llvm/bin/llvm-ar" +CC = "/opt/homebrew/opt/llvm/bin/clang" ``` + +### Build with `wasm-pack build` + +```sh wasm-pack build ``` -### 🔬 Test in Headless Browsers with `wasm-pack test` +### Test in Headless Browsers with `wasm-pack test` -``` +```sh wasm-pack test --headless --firefox ``` -### 🎁 Publish to NPM with `wasm-pack publish` +> Works with `--firefox`, `--chrome` or `safari`. -``` -wasm-pack publish -``` +## License + +Licensed under either of + +- Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or ) +- MIT license ([LICENSE-MIT](LICENSE-MIT) or ) + +at your option. -## 🔋 Batteries Included +### Contribution -* [`wasm-bindgen`](https://github.com/rustwasm/wasm-bindgen) for communicating - between WebAssembly and JavaScript. -* [`console_error_panic_hook`](https://github.com/rustwasm/console_error_panic_hook) - for logging panic messages to the developer console. +Unless you explicitly state otherwise, any contribution intentionally +submitted for inclusion in the work by you, as defined in the Apache-2.0 +license, shall be dual licensed as above, without any additional terms or +conditions. diff --git a/clippy.toml b/clippy.toml new file mode 100644 index 0000000..b3c3a24 --- /dev/null +++ b/clippy.toml @@ -0,0 +1 @@ +msrv = "1.63.0" diff --git a/rust-version b/rust-version new file mode 100644 index 0000000..8f03ba2 --- /dev/null +++ b/rust-version @@ -0,0 +1 @@ +1.82.0 \ No newline at end of file diff --git a/static/bdk.png b/static/bdk.png new file mode 100644 index 0000000000000000000000000000000000000000..2174bade0f39e2b45cf27751b1229de730540579 GIT binary patch literal 5661 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 Qn+rI7($l&6#AV!n0V7$d8~^|S literal 0 HcmV?d00001 From 79060e689aa332a6a3f40ac5651f0f53d828c6e5 Mon Sep 17 00:00:00 2001 From: Dario Anongba Varela Date: Tue, 3 Dec 2024 16:37:52 +0100 Subject: [PATCH 2/4] add .github --- .github/ISSUE_TEMPLATE/bug_report.md | 29 ++++++ .github/ISSUE_TEMPLATE/enhancement_request.md | 19 ++++ .github/dependabot.yml | 8 ++ .github/pull_request_template.md | 34 +++++++ .github/workflows/audit.yml | 28 ++++++ .github/workflows/code_coverage.yml | 46 +++++++++ .github/workflows/cont_integration.yml | 94 +++++++++++++++++++ .travis.yml | 69 -------------- 8 files changed, 258 insertions(+), 69 deletions(-) create mode 100644 .github/ISSUE_TEMPLATE/bug_report.md create mode 100644 .github/ISSUE_TEMPLATE/enhancement_request.md create mode 100644 .github/dependabot.yml create mode 100644 .github/pull_request_template.md create mode 100644 .github/workflows/audit.yml create mode 100644 .github/workflows/code_coverage.yml create mode 100644 .github/workflows/cont_integration.yml delete mode 100644 .travis.yml diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..036c3ce --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,29 @@ +--- +name: Bug report +about: Create a report to help us improve +title: "" +labels: "bug" +assignees: "" +--- + +**Describe the bug** + + + +**To Reproduce** + + + +**Expected behavior** + + + +**Build environment** + +- BDK tag/commit: +- OS+version: +- Node version: + +**Additional context** + + diff --git a/.github/ISSUE_TEMPLATE/enhancement_request.md b/.github/ISSUE_TEMPLATE/enhancement_request.md new file mode 100644 index 0000000..e439bfb --- /dev/null +++ b/.github/ISSUE_TEMPLATE/enhancement_request.md @@ -0,0 +1,19 @@ +--- +name: Enhancement request +about: Request a new feature or change to an existing feature +title: "" +labels: "enhancement" +assignees: "" +--- + +**Describe the enhancement** + + + +**Use case** + + + +**Additional context** + + diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..453228e --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,8 @@ +# Set update schedule for GitHub Actions +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + # Check for updates to GitHub Actions every week + interval: "weekly" diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..cbf9f62 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,34 @@ + + +### Description + + + +### Notes to the reviewers + + + +### Changelog notice + + + + +### Checklists + +#### All Submissions: + +- [ ] I've signed all my commits +- [ ] I followed the [contribution guidelines](https://github.com/MetaMask/bdk-wasm/blob/master/CONTRIBUTING.md) +- [ ] I ran `cargo fmt` and `cargo clippy` before committing + +#### New Features: + +- [ ] I've added tests for the new feature +- [ ] I've added docs for the new feature + +#### Bugfixes: + +- [ ] This pull request breaks the existing API +- [ ] I've added tests to reproduce the issue which are now passing +- [ ] I'm linking the issue being fixed by this PR diff --git a/.github/workflows/audit.yml b/.github/workflows/audit.yml new file mode 100644 index 0000000..17f20ac --- /dev/null +++ b/.github/workflows/audit.yml @@ -0,0 +1,28 @@ +name: Audit + +on: + push: + paths: + # Run if workflow changes + - ".github/workflows/audit.yml" + # Run on changed dependencies + - "**/Cargo.toml" + - "**/Cargo.lock" + # Run if the configuration file changes + - "**/audit.toml" + # Rerun periodically to pick up new advisories + schedule: + - cron: "0 0 * * *" # Nightly + # Run manually + workflow_dispatch: + +jobs: + audit: + runs-on: ubuntu-latest + permissions: + contents: read + issues: write + steps: + - uses: actions/checkout@v4 + - uses: actions-rust-lang/audit@v1 + name: Audit Rust Dependencies diff --git a/.github/workflows/code_coverage.yml b/.github/workflows/code_coverage.yml new file mode 100644 index 0000000..c5dbec0 --- /dev/null +++ b/.github/workflows/code_coverage.yml @@ -0,0 +1,46 @@ +on: [push, pull_request] + +name: Code Coverage + +jobs: + Codecov: + name: Code Coverage + runs-on: ubuntu-latest + env: + RUSTFLAGS: "-Cinstrument-coverage" + RUSTDOCFLAGS: "-Cinstrument-coverage" + LLVM_PROFILE_FILE: "./target/coverage/%p-%m.profraw" + + steps: + - name: Checkout + uses: actions/checkout@v4 + - name: Install lcov tools + run: sudo apt-get install lcov -y + - name: Install Rust toolchain + uses: actions-rs/toolchain@v1 + with: + toolchain: stable + override: true + profile: minimal + components: llvm-tools-preview + - name: Rust Cache + uses: Swatinem/rust-cache@v2.7.5 + - name: Install grcov + run: if [[ ! -e ~/.cargo/bin/grcov ]]; then cargo install grcov; fi + - name: Test + run: cargo test --all-features + - name: Make coverage directory + run: mkdir coverage + - name: Run grcov + run: grcov . --binary-path ./target/debug/ -s . -t lcov --branch --ignore-not-existing --keep-only '**/crates/**' --ignore '**/tests/**' --ignore '**/examples/**' -o ./coverage/lcov.info + - name: Generate HTML coverage report + run: genhtml -o coverage-report.html --ignore-errors source ./coverage/lcov.info + - name: Coveralls upload + uses: coverallsapp/github-action@master + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + - name: Upload artifact + uses: actions/upload-artifact@v4 + with: + name: coverage-report + path: coverage-report.html diff --git a/.github/workflows/cont_integration.yml b/.github/workflows/cont_integration.yml new file mode 100644 index 0000000..1837871 --- /dev/null +++ b/.github/workflows/cont_integration.yml @@ -0,0 +1,94 @@ +on: [push, pull_request] + +name: CI + +jobs: + prepare: + runs-on: ubuntu-latest + outputs: + rust_version: ${{ steps.read_toolchain.outputs.rust_version }} + steps: + - name: "Checkout repo" + uses: actions/checkout@v4 + - name: "Read rust version" + id: read_toolchain + run: echo "rust_version=$(cat rust-version)" >> $GITHUB_OUTPUT + + build-test: + name: Build and test + runs-on: ubuntu-latest + strategy: + matrix: + rust: + - version: stable + clippy: true + - version: 1.63.0 # MSRV + features: + - --no-default-features + - --all-features + steps: + - name: checkout + uses: actions/checkout@v4 + - name: Install Rust toolchain + uses: actions-rs/toolchain@v1 + with: + toolchain: ${{ matrix.rust.version }} + override: true + profile: minimal + - name: Install wasm-pack + run: curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh -s -- -f + - name: Rust Cache + uses: Swatinem/rust-cache@v2.7.5 + - name: Pin dependencies for MSRV + if: matrix.rust.version == '1.63.0' + run: | + cargo update -p zstd-sys --precise "2.0.8+zstd.1.5.5" + cargo update -p time --precise "0.3.20" + cargo update -p home --precise "0.5.5" + cargo update -p proptest --precise "1.2.0" + cargo update -p url --precise "2.5.0" + cargo update -p cc --precise "1.0.105" + cargo update -p tokio --precise "1.38.1" + cargo update -p tokio-util --precise "0.7.11" + cargo update -p indexmap --precise "2.5.0" + cargo update -p security-framework-sys --precise "2.11.1" + - name: Build + run: wasm-pack build --features ${{ matrix.features }} + - name: Test + run: wasm-pack test --chrome --firefox --safari --headless --features ${{ matrix.features }} + + fmt: + name: Rust fmt + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + - name: Install Rust toolchain + uses: actions-rs/toolchain@v1 + with: + toolchain: stable + override: true + profile: minimal + components: rustfmt + - name: Check fmt + run: cargo fmt --all -- --config format_code_in_doc_comments=true --check + + clippy_check: + needs: prepare + runs-on: ubuntu-latest + permissions: + checks: write + steps: + - uses: actions/checkout@v4 + - uses: actions-rs/toolchain@v1 + with: + toolchain: ${{ needs.prepare.outputs.rust_version }} + components: clippy + override: true + - name: Rust Cache + uses: Swatinem/rust-cache@v2.7.5 + - uses: actions-rs/clippy-check@v1 + with: + token: ${{ secrets.GITHUB_TOKEN }} + name: Clippy Results + args: --all-features --all-targets -- -D warnings diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 7a91325..0000000 --- a/.travis.yml +++ /dev/null @@ -1,69 +0,0 @@ -language: rust -sudo: false - -cache: cargo - -matrix: - include: - - # Builds with wasm-pack. - - rust: beta - env: RUST_BACKTRACE=1 - addons: - firefox: latest - chrome: stable - before_script: - - (test -x $HOME/.cargo/bin/cargo-install-update || cargo install cargo-update) - - (test -x $HOME/.cargo/bin/cargo-generate || cargo install --vers "^0.2" cargo-generate) - - cargo install-update -a - - curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh -s -- -f - script: - - cargo generate --git . --name testing - # Having a broken Cargo.toml (in that it has curlies in fields) anywhere - # in any of our parent dirs is problematic. - - mv Cargo.toml Cargo.toml.tmpl - - cd testing - - wasm-pack build - - wasm-pack test --chrome --firefox --headless - - # Builds on nightly. - - rust: nightly - env: RUST_BACKTRACE=1 - before_script: - - (test -x $HOME/.cargo/bin/cargo-install-update || cargo install cargo-update) - - (test -x $HOME/.cargo/bin/cargo-generate || cargo install --vers "^0.2" cargo-generate) - - cargo install-update -a - - rustup target add wasm32-unknown-unknown - script: - - cargo generate --git . --name testing - - mv Cargo.toml Cargo.toml.tmpl - - cd testing - - cargo check - - cargo check --target wasm32-unknown-unknown - - cargo check --no-default-features - - cargo check --target wasm32-unknown-unknown --no-default-features - - cargo check --no-default-features --features console_error_panic_hook - - cargo check --target wasm32-unknown-unknown --no-default-features --features console_error_panic_hook - - cargo check --no-default-features --features "console_error_panic_hook wee_alloc" - - cargo check --target wasm32-unknown-unknown --no-default-features --features "console_error_panic_hook wee_alloc" - - # Builds on beta. - - rust: beta - env: RUST_BACKTRACE=1 - before_script: - - (test -x $HOME/.cargo/bin/cargo-install-update || cargo install cargo-update) - - (test -x $HOME/.cargo/bin/cargo-generate || cargo install --vers "^0.2" cargo-generate) - - cargo install-update -a - - rustup target add wasm32-unknown-unknown - script: - - cargo generate --git . --name testing - - mv Cargo.toml Cargo.toml.tmpl - - cd testing - - cargo check - - cargo check --target wasm32-unknown-unknown - - cargo check --no-default-features - - cargo check --target wasm32-unknown-unknown --no-default-features - - cargo check --no-default-features --features console_error_panic_hook - - cargo check --target wasm32-unknown-unknown --no-default-features --features console_error_panic_hook - # Note: no enabling the `wee_alloc` feature here because it requires - # nightly for now. From 7e6d092b0f56e405ac312f068baf618a93d470b0 Mon Sep 17 00:00:00 2001 From: Dario Anongba Varela Date: Tue, 3 Dec 2024 18:14:50 +0100 Subject: [PATCH 3/4] add test for wallet --- Cargo.toml | 33 ++++++-- src/bitcoin/descriptor.rs | 18 ++--- src/bitcoin/esplora_wallet.rs | 9 +-- src/bitcoin/mod.rs | 8 +- .../{metamask_wallet.rs => snap_wallet.rs} | 29 ++++--- src/bitcoin/wallet.rs | 11 +-- src/storage/mod.rs | 4 +- src/utils/descriptor.rs | 19 ++--- tests/esplora.rs | 74 +++++++++++++++++ tests/rpc.rs | 7 +- tests/{web.rs => wallet.rs} | 80 +++++++------------ 11 files changed, 173 insertions(+), 119 deletions(-) rename src/bitcoin/{metamask_wallet.rs => snap_wallet.rs} (90%) create mode 100644 tests/esplora.rs rename tests/{web.rs => wallet.rs} (59%) diff --git a/Cargo.toml b/Cargo.toml index 057f4c4..176fdc4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,24 +1,37 @@ [package] -name = "bdk-wasm" +name = "bdk_wasm" version = "0.1.0" -authors = ["Dario Anongba Varela "] +repository = "https://github.com/MetaMask/bdk-wasm" +description = "A modern, lightweight, descriptor-based wallet library for WASM and JS/TS" +keywords = [ + "bitcoin", + "wallet", + "descriptor", + "psbt", + "wasm", + "js", + "typescript", +] +readme = "README.md" +license = "MIT OR Apache-2.0" +authors = ["Bitcoin Developers"] edition = "2021" +rust-version = "1.63" [lib] crate-type = ["cdylib", "rlib"] [features] -default = ["esplora"] +default = [] esplora = ["bdk_esplora"] debug = ["console_error_panic_hook"] -metamask = [] +snap = ["esplora"] bitcoind = ["bdk_bitcoind_rpc"] [dependencies] wasm-bindgen = "0.2.95" wasm-bindgen-futures = "0.4.45" anyhow = "1.0.93" -console_error_panic_hook = { version = "0.1.7", optional = true } thiserror = "2.0.3" serde = { version = "1.0.215", default-features = false, features = ["derive"] } js-sys = "0.3.72" @@ -30,9 +43,7 @@ getrandom = { version = "0.2.15", features = ["js"] } ring = { version = "0.17.8", features = ["wasm32_unknown_unknown_js"] } # Bitcoin dependencies -bdk_wallet = { git = "https://github.com/bitcoindevkit/bdk", branch = "master", features = [ - "keys-bip39", -] } +bdk_wallet = { git = "https://github.com/bitcoindevkit/bdk", branch = "master" } bdk_esplora = { git = "https://github.com/bitcoindevkit/bdk", branch = "master", default-features = false, features = [ "async-https", ], optional = true } @@ -40,9 +51,15 @@ bitcoin = { version = "0.32.4", default-features = false } miniscript = "12.2.0" bdk_bitcoind_rpc = { version = "0.16.0", optional = true } +# Debug dependencies +console_error_panic_hook = { version = "0.1.7", optional = true } + [dev-dependencies] wasm-bindgen-test = "0.3.45" web-sys = { version = "0.3.72", features = ["console"] } +bdk_wallet = { git = "https://github.com/bitcoindevkit/bdk", branch = "master", features = [ + "keys-bip39", +] } [profile.release] # Tell `rustc` to optimize for small code size. diff --git a/src/bitcoin/descriptor.rs b/src/bitcoin/descriptor.rs index 3e706b4..743b2b3 100644 --- a/src/bitcoin/descriptor.rs +++ b/src/bitcoin/descriptor.rs @@ -1,6 +1,5 @@ use anyhow::{anyhow, Error}; use bdk_wallet::{ - bip39::Mnemonic, keys::{DerivableKey, ExtendedKey}, template::{ Bip44, Bip44Public, Bip49, Bip49Public, Bip84, Bip84Public, Bip86, Bip86Public, @@ -17,13 +16,12 @@ use bitcoin::{ use crate::types::SLIP10Node; -pub fn mnemonic_to_descriptor( - mnemonic: &str, - passphrase: &str, +pub fn seed_to_descriptor( + seed: &[u8], network: Network, address_type: AddressType, ) -> Result<(DescriptorTemplateOut, DescriptorTemplateOut), Error> { - let xprv = mnemonic_to_xpriv(mnemonic, passphrase, network)?; + let xprv = seed_to_xpriv(seed, network)?; match address_type { AddressType::P2pkh => build_xpriv_descriptor(Bip44, xprv, network), @@ -105,14 +103,8 @@ pub fn slip10_to_extended( } } -pub fn mnemonic_to_xpriv( - mnemonic: &str, - passphrase: &str, - network: Network, -) -> Result { - let mnemonic = Mnemonic::parse(mnemonic)?; - let xprv = Xpriv::new_master(network, &mnemonic.to_seed(passphrase))?; - +pub fn seed_to_xpriv(seed: &[u8], network: Network) -> Result { + let xprv = Xpriv::new_master(network, seed)?; Ok(xprv) } diff --git a/src/bitcoin/esplora_wallet.rs b/src/bitcoin/esplora_wallet.rs index 2b390a5..0ed66c0 100644 --- a/src/bitcoin/esplora_wallet.rs +++ b/src/bitcoin/esplora_wallet.rs @@ -11,7 +11,7 @@ use serde_wasm_bindgen::{from_value, to_value}; use wasm_bindgen::{prelude::wasm_bindgen, JsError, JsValue}; use crate::{ - bitcoin::{mnemonic_to_descriptor, xpriv_to_descriptor, xpub_to_descriptor}, + bitcoin::{seed_to_descriptor, xpriv_to_descriptor, xpub_to_descriptor}, result::JsResult, types::{AddressInfo, AddressType, Balance, KeychainKind, Network}, }; @@ -52,15 +52,14 @@ impl EsploraWallet { .map_err(|e| JsError::new(&e.to_string())) } - pub fn from_mnemonic( - mnemonic: &str, - passphrase: &str, + pub fn from_seed( + seed: &[u8], network: Network, address_type: AddressType, url: &str, ) -> JsResult { let (external_descriptor, internal_descriptor) = - mnemonic_to_descriptor(&mnemonic, &passphrase, network.into(), address_type.into()) + seed_to_descriptor(seed, network.into(), address_type.into()) .map_err(|e| JsError::new(&e.to_string()))?; Self::create(network, external_descriptor, internal_descriptor, url) diff --git a/src/bitcoin/mod.rs b/src/bitcoin/mod.rs index 9e5f36b..eaabb82 100644 --- a/src/bitcoin/mod.rs +++ b/src/bitcoin/mod.rs @@ -7,8 +7,8 @@ pub use wallet::*; #[cfg(feature = "esplora")] mod esplora_wallet; -#[cfg(feature = "metamask")] -mod metamask_wallet; +#[cfg(feature = "snap")] +mod snap_wallet; #[cfg(feature = "bitcoind")] mod rpc_wallet; @@ -16,8 +16,8 @@ mod rpc_wallet; #[cfg(feature = "esplora")] pub use esplora_wallet::EsploraWallet; -#[cfg(feature = "metamask")] -pub use metamask_wallet::MetaMaskWallet; +#[cfg(feature = "snap")] +pub use snap_wallet::SnapWallet; #[cfg(feature = "bitcoind")] pub use rpc_wallet::RpcWallet; diff --git a/src/bitcoin/metamask_wallet.rs b/src/bitcoin/snap_wallet.rs similarity index 90% rename from src/bitcoin/metamask_wallet.rs rename to src/bitcoin/snap_wallet.rs index 7e60d12..f42c2d1 100644 --- a/src/bitcoin/metamask_wallet.rs +++ b/src/bitcoin/snap_wallet.rs @@ -11,7 +11,7 @@ use serde_wasm_bindgen::to_value; use wasm_bindgen::{prelude::wasm_bindgen, JsError, JsValue}; use crate::{ - bitcoin::{mnemonic_to_descriptor, xpriv_to_descriptor, xpub_to_descriptor}, + bitcoin::{seed_to_descriptor, xpriv_to_descriptor, xpub_to_descriptor}, result::JsResult, storage::SnapPersister, types::{AddressInfo, AddressType, Balance, KeychainKind, Network}, @@ -20,20 +20,20 @@ use crate::{ const STORAGE_KEY: &str = "wallet"; #[wasm_bindgen] -pub struct MetaMaskWallet { +pub struct SnapWallet { wallet: PersistedWallet, client: AsyncClient, persister: SnapPersister, } #[wasm_bindgen] -impl MetaMaskWallet { +impl SnapWallet { async fn create( network: Network, external_descriptor: D, internal_descriptor: D, url: &str, - ) -> JsResult + ) -> JsResult where D: IntoWalletDescriptor + Send + Clone + 'static, { @@ -45,7 +45,7 @@ impl MetaMaskWallet { let client = Builder::new(&url).build_async()?; - Ok(MetaMaskWallet { + Ok(SnapWallet { wallet, client, persister, @@ -57,19 +57,18 @@ impl MetaMaskWallet { external_descriptor: String, internal_descriptor: String, url: &str, - ) -> JsResult { + ) -> JsResult { Self::create(network, external_descriptor, internal_descriptor, url).await } - pub async fn from_mnemonic( - mnemonic: &str, - passphrase: &str, + pub async fn from_seed( + seed: &[u8], network: Network, address_type: AddressType, url: &str, - ) -> JsResult { + ) -> JsResult { let (external_descriptor, internal_descriptor) = - mnemonic_to_descriptor(&mnemonic, &passphrase, network.into(), address_type.into()) + seed_to_descriptor(seed, network.into(), address_type.into()) .map_err(|e| JsError::new(&e.to_string()))?; Self::create(network, external_descriptor, internal_descriptor, url).await @@ -81,7 +80,7 @@ impl MetaMaskWallet { network: Network, address_type: AddressType, url: &str, - ) -> JsResult { + ) -> JsResult { let xprv = Xpriv::from_str(extended_privkey).map_err(|e| JsError::new(&e.to_string()))?; let fingerprint = Fingerprint::from_hex(fingerprint)?; @@ -98,7 +97,7 @@ impl MetaMaskWallet { network: Network, address_type: AddressType, url: &str, - ) -> JsResult { + ) -> JsResult { let xpub = Xpub::from_str(extended_pubkey)?; let fingerprint = Fingerprint::from_hex(fingerprint)?; @@ -109,7 +108,7 @@ impl MetaMaskWallet { Self::create(network, external_descriptor, internal_descriptor, url).await } - pub async fn load(url: &str) -> JsResult { + pub async fn load(url: &str) -> JsResult { let mut persister = SnapPersister::new(STORAGE_KEY); let wallet_opt = BdkWallet::load().load_wallet_async(&mut persister).await?; @@ -120,7 +119,7 @@ impl MetaMaskWallet { let client = Builder::new(&url).build_async()?; - Ok(MetaMaskWallet { + Ok(SnapWallet { wallet, client, persister, diff --git a/src/bitcoin/wallet.rs b/src/bitcoin/wallet.rs index f91b077..0d1ab8f 100644 --- a/src/bitcoin/wallet.rs +++ b/src/bitcoin/wallet.rs @@ -6,7 +6,7 @@ use serde_wasm_bindgen::{from_value, to_value}; use wasm_bindgen::{prelude::wasm_bindgen, JsError, JsValue}; use crate::{ - bitcoin::{mnemonic_to_descriptor, xpriv_to_descriptor, xpub_to_descriptor}, + bitcoin::{seed_to_descriptor, xpriv_to_descriptor, xpub_to_descriptor}, result::JsResult, types::{AddressInfo, AddressType, Balance, KeychainKind, Network}, }; @@ -42,14 +42,9 @@ impl Wallet { .map_err(|e| JsError::new(&e.to_string())) } - pub fn from_mnemonic( - mnemonic: &str, - passphrase: &str, - network: Network, - address_type: AddressType, - ) -> JsResult { + pub fn from_seed(seed: &[u8], network: Network, address_type: AddressType) -> JsResult { let (external_descriptor, internal_descriptor) = - mnemonic_to_descriptor(&mnemonic, &passphrase, network.into(), address_type.into()) + seed_to_descriptor(seed, network.into(), address_type.into()) .map_err(|e| JsError::new(&e.to_string()))?; Self::create(network, external_descriptor, internal_descriptor) diff --git a/src/storage/mod.rs b/src/storage/mod.rs index ad79c35..0a84d99 100644 --- a/src/storage/mod.rs +++ b/src/storage/mod.rs @@ -1,5 +1,5 @@ -#[cfg(feature = "metamask")] +#[cfg(feature = "snap")] mod snap_persister; -#[cfg(feature = "metamask")] +#[cfg(feature = "snap")] pub use snap_persister::SnapPersister; diff --git a/src/utils/descriptor.rs b/src/utils/descriptor.rs index 0660f41..73b9b62 100644 --- a/src/utils/descriptor.rs +++ b/src/utils/descriptor.rs @@ -10,19 +10,14 @@ use wasm_bindgen::prelude::{wasm_bindgen, JsError, JsValue}; use super::result::JsResult; #[wasm_bindgen] -pub fn mnemonic_to_descriptor( - mnemonic: &str, - passphrase: &str, +pub fn seed_to_descriptor( + seed: &[u8], network: Network, address_type: AddressType, ) -> JsResult { - let (external, internal) = crate::bitcoin::mnemonic_to_descriptor( - mnemonic, - passphrase, - network.into(), - address_type.into(), - ) - .map_err(|e| JsError::new(&e.to_string()))?; + let (external, internal) = + crate::bitcoin::seed_to_descriptor(seed, network.into(), address_type.into()) + .map_err(|e| JsError::new(&e.to_string()))?; Ok(DescriptorPair::new( external.0.to_string_with_secret(&external.1), @@ -71,8 +66,8 @@ pub fn xpub_to_descriptor( } #[wasm_bindgen] -pub fn mnemonic_to_xpriv(mnemonic: &str, passphrase: &str, network: Network) -> JsResult { - let xprv = crate::bitcoin::mnemonic_to_xpriv(mnemonic, passphrase, network.into()) +pub fn seed_to_xpriv(seed: &[u8], network: Network) -> JsResult { + let xprv = crate::bitcoin::seed_to_xpriv(seed, network.into()) .map_err(|e| JsError::new(&e.to_string()))?; Ok(xprv.to_string()) diff --git a/tests/esplora.rs b/tests/esplora.rs new file mode 100644 index 0000000..3cb1668 --- /dev/null +++ b/tests/esplora.rs @@ -0,0 +1,74 @@ +//! Test suite for the Web and headless browsers. + +#![cfg(all(feature = "esplora", target_arch = "wasm32"))] + +extern crate wasm_bindgen_test; + +use bdk_wallet::bip39::Mnemonic; +use bdk_wasm::{ + bitcoin::EsploraWallet, + set_panic_hook, + types::{AddressType, KeychainKind, Network}, +}; +use wasm_bindgen_test::*; + +wasm_bindgen_test_configure!(run_in_browser); + +const STOP_GAP: usize = 5; +const PARALLEL_REQUESTS: usize = 1; +const NETWORK: Network = Network::Testnet; +const ADDRESS_TYPE: AddressType = AddressType::P2wpkh; +const MNEMONIC: &str = "journey embrace permit coil indoor stereo welcome maid movie easy clock spider tent slush bright luxury awake waste legal modify awkward answer acid goose"; + +#[wasm_bindgen_test] +async fn test_esplora_wallet() { + set_panic_hook(); + + let esplora_url = match NETWORK { + Network::Bitcoin => "https://blockstream.info/api", + Network::Testnet => "https://blockstream.info/testnet/api", + Network::Testnet4 => "https://blockstream.info/testnet/api", + Network::Signet => "https://mutinynet.com/api", + Network::Regtest => "https://localhost:3000", + }; + + let seed = Mnemonic::parse(MNEMONIC).unwrap().to_seed(""); + let mut wallet = EsploraWallet::from_seed(&seed, NETWORK, ADDRESS_TYPE, esplora_url) + .expect("esplora_wallet"); + + wallet + .full_scan(STOP_GAP, PARALLEL_REQUESTS) + .await + .expect("full_scan"); + + let address0 = wallet.peek_address(KeychainKind::External, 0); + assert_eq!( + address0.address(), + "tb1qjtgffm20l9vu6a7gacxvpu2ej4kdcsgc26xfdz".to_string() + ); + + let balance = wallet.balance(); + assert_eq!(balance.total(), 0); + + let address1 = wallet.next_unused_address(KeychainKind::External); + assert_eq!(address1.keychain(), KeychainKind::External); + assert_eq!(address1.index(), 0); + + let address2 = wallet.reveal_next_address(KeychainKind::External); + assert_eq!(address2.index(), 1); + + let address3 = wallet.next_unused_address(KeychainKind::External); + assert_eq!(address3.index(), 0); + + // Should do a single call to the server (for each keychain) + wallet.sync(1).await.expect("sync"); + + // Should do a stop_gap calls to the server (for each keychain) and not start from beginning + wallet + .full_scan(STOP_GAP, PARALLEL_REQUESTS) + .await + .expect("second full_scan"); + + let unused_addresses = wallet.list_unused_addresses(KeychainKind::External); + assert_eq!(unused_addresses.len(), 2); +} diff --git a/tests/rpc.rs b/tests/rpc.rs index b9550d4..e8cf800 100644 --- a/tests/rpc.rs +++ b/tests/rpc.rs @@ -4,11 +4,12 @@ extern crate wasm_bindgen_test; +use bdk_wallet::bip39::Mnemonic; use web_sys::console; use bdk_wasm::{ bitcoin::RpcWallet, - mnemonic_to_descriptor, set_panic_hook, + seed_to_descriptor, set_panic_hook, types::{AddressType, Network}, }; use wasm_bindgen_test::*; @@ -22,8 +23,8 @@ const MNEMONIC: &str = "drip drum plug universe beyond gasp cram action hurt kee async fn test_rpc_wallet() { set_panic_hook(); - let descriptors = - mnemonic_to_descriptor(MNEMONIC, "", NETWORK, AddressType::P2wpkh).expect("descriptor"); + let seed = Mnemonic::parse(MNEMONIC).unwrap().to_seed(""); + let descriptors = seed_to_descriptor(&seed, NETWORK, AddressType::P2wpkh).expect("descriptor"); let rpc_url = "http://127.0.0.1:18443"; let wallet = RpcWallet::new( diff --git a/tests/web.rs b/tests/wallet.rs similarity index 59% rename from tests/web.rs rename to tests/wallet.rs index 2ddba4c..3987c74 100644 --- a/tests/web.rs +++ b/tests/wallet.rs @@ -4,25 +4,28 @@ extern crate wasm_bindgen_test; +use bdk_wallet::{bip39::Mnemonic, ChangeSet}; use bdk_wasm::{ - bitcoin::EsploraWallet, - mnemonic_to_descriptor, mnemonic_to_xpriv, set_panic_hook, + bitcoin::Wallet, + seed_to_descriptor, seed_to_xpriv, set_panic_hook, types::{AddressType, KeychainKind, Network}, xpriv_to_descriptor, xpub_to_descriptor, }; +use serde_wasm_bindgen::from_value; use wasm_bindgen_test::*; wasm_bindgen_test_configure!(run_in_browser); -const STOP_GAP: usize = 5; -const PARALLEL_REQUESTS: usize = 1; const NETWORK: Network = Network::Testnet; const ADDRESS_TYPE: AddressType = AddressType::P2wpkh; const MNEMONIC: &str = "journey embrace permit coil indoor stereo welcome maid movie easy clock spider tent slush bright luxury awake waste legal modify awkward answer acid goose"; #[wasm_bindgen_test] -async fn test_mnemonic_to_xpriv() { - let xprv = mnemonic_to_xpriv(MNEMONIC, "", NETWORK).expect("xpub_to_descriptor"); +async fn test_seed_to_xpriv() { + set_panic_hook(); + + let seed = Mnemonic::parse(MNEMONIC).unwrap().to_seed(""); + let xprv = seed_to_xpriv(&seed, NETWORK).expect("seed_to_xpriv"); assert_eq!( xprv, @@ -31,11 +34,11 @@ async fn test_mnemonic_to_xpriv() { } #[wasm_bindgen_test] -async fn test_mnemonic_to_descriptor() { +async fn test_seed_to_descriptor() { set_panic_hook(); - let descriptors = mnemonic_to_descriptor(MNEMONIC, "", NETWORK, ADDRESS_TYPE) - .expect("mnemonic_to_descriptor"); + let seed = Mnemonic::parse(MNEMONIC).unwrap().to_seed(""); + let descriptors = seed_to_descriptor(&seed, NETWORK, ADDRESS_TYPE).expect("seed_to_descriptor"); assert_eq!( descriptors.external(), @@ -86,53 +89,32 @@ async fn test_xpub_to_descriptor() { } #[wasm_bindgen_test] -async fn test_esplora_wallet() { +async fn test_wallet() { set_panic_hook(); - let esplora_url = match NETWORK { - Network::Bitcoin => "https://blockstream.info/api", - Network::Testnet => "https://blockstream.info/testnet/api", - Network::Testnet4 => "https://blockstream.info/testnet/api", - Network::Signet => "https://mutinynet.com/api", - Network::Regtest => "https://localhost:3000", - }; - - let mut wallet = EsploraWallet::from_mnemonic(MNEMONIC, "", NETWORK, ADDRESS_TYPE, esplora_url) - .expect("esplora_wallet"); - - wallet - .full_scan(STOP_GAP, PARALLEL_REQUESTS) - .await - .expect("full_scan"); - - let address0 = wallet.peek_address(KeychainKind::External, 0); - assert_eq!( - address0.address(), - "tb1qjtgffm20l9vu6a7gacxvpu2ej4kdcsgc26xfdz".to_string() - ); + let seed = Mnemonic::parse(MNEMONIC).unwrap().to_seed(""); + let mut wallet = Wallet::from_seed(&seed, NETWORK, ADDRESS_TYPE).expect("wallet"); let balance = wallet.balance(); assert_eq!(balance.total(), 0); - let address1 = wallet.next_unused_address(KeychainKind::External); - assert_eq!(address1.keychain(), KeychainKind::External); - assert_eq!(address1.index(), 0); - - let address2: bdk_wasm::types::AddressInfo = wallet.reveal_next_address(KeychainKind::External); - assert_eq!(address2.index(), 1); - - let address3 = wallet.next_unused_address(KeychainKind::External); - assert_eq!(address3.index(), 0); + let initial_changeset_js = wallet.take_staged().expect("take_staged"); + let initial_changeset: ChangeSet = + from_value(initial_changeset_js.clone()).expect("from_value"); + assert_eq!(initial_changeset.descriptor.unwrap().to_string(), "wpkh([27f9035f/84'/1'/0']tpubDCkv2fHDfPg5hB6bFqJ4fNiins2Z8r5vKtD4xq5irCG2HsUXkgHYsj3gfGTdvAv41hoJeXjfxu7EBQqZMm6SVkxztKFtaaE7HuLdkuL7KNq/0/*)#wle7e0wp"); + assert_eq!( + initial_changeset.change_descriptor.unwrap().to_string(), + "wpkh([27f9035f/84'/1'/0']tpubDCkv2fHDfPg5hB6bFqJ4fNiins2Z8r5vKtD4xq5irCG2HsUXkgHYsj3gfGTdvAv41hoJeXjfxu7EBQqZMm6SVkxztKFtaaE7HuLdkuL7KNq/1/*)#ltuly67e" + ); - // Should do a single call to the server (for each keychain) - wallet.sync(1).await.expect("sync"); + let address0 = wallet.reveal_next_address(KeychainKind::External); + assert_eq!(address0.index(), 0); - // Should do a stop_gap calls to the server (for each keychain) and not start from beginning - wallet - .full_scan(STOP_GAP, PARALLEL_REQUESTS) - .await - .expect("second full_scan"); + let address1 = wallet.reveal_next_address(KeychainKind::External); + assert_eq!(address1.index(), 1); - let unused_addresses = wallet.list_unused_addresses(KeychainKind::External); - assert_eq!(unused_addresses.len(), 2); + let final_changeset_js = wallet + .take_merged(initial_changeset_js) + .expect("take_merged"); + assert!(!final_changeset_js.is_null() && !final_changeset_js.is_undefined()); } From f5086e42b2997112a137e2c5a5b469a1ba8cab71 Mon Sep 17 00:00:00 2001 From: Dario Anongba Varela Date: Wed, 4 Dec 2024 11:15:46 +0100 Subject: [PATCH 4/4] complete README --- README.md | 21 ++++++++++++++++++--- src/bitcoin/snap_wallet.rs | 36 ++++++++++++++++++------------------ 2 files changed, 36 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index 242c324..9cbe3c9 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@

- The Bitcoin Dev Kit for Browsers and Node! + The Bitcoin Dev Kit for Browsers and Node

@@ -22,9 +22,22 @@ ## About The `bdk-wasm` library aims at providing access to the excellent [BitcoinDevKit](https://github.com/bitcoindevkit/bdk) to JS and Node environments (and eventually any device supporting WebAssembly). -It specializes in compiling BDK on the `wasm32-unknown-unknown` target and use [`wasm-bindgen`](https://github.com/rustwasm/wasm-bindgen) to create JS bindings. +It specializes in compiling BDK on the `wasm32-unknown-unknown` target and use [`wasm-bindgen`](https://github.com/rustwasm/wasm-bindgen) to create TypeScript bindings. -This repo also handles the packaging and publishing of the `bdk` NPM package, using `wasm-pack`. +This repo handles the packaging and publishing of the `bdk` NPM package, using `wasm-pack`. + +This library offers all the desired functionality to build a Bitcoin wallet out of the box: + +- UTXO management +- Coin selection +- Wallet upates by syncing and scanning the chain data +- Bitcoin descriptors for flexibility in the definition of spending conditions. Supports all address types from legacy to Taproot. +- State update and persistence +- Transaction creation, signing and broadcasting +- Dynamic addresses +- and much more + +For a lightweight library providing stateless utility functions, see [`bitcoinjs`](https://github.com/bitcoinjs/bitcoinjs-lib). ## Browser Usage @@ -61,6 +74,8 @@ CC = "/opt/homebrew/opt/llvm/bin/clang" wasm-pack build ``` +> Choose your desired features when building: `wasm-pack build --features "esplora default snap bitcoind"` + ### Test in Headless Browsers with `wasm-pack test` ```sh diff --git a/src/bitcoin/snap_wallet.rs b/src/bitcoin/snap_wallet.rs index f42c2d1..932af70 100644 --- a/src/bitcoin/snap_wallet.rs +++ b/src/bitcoin/snap_wallet.rs @@ -52,6 +52,24 @@ impl SnapWallet { }) } + pub async fn load(url: &str) -> JsResult { + let mut persister = SnapPersister::new(STORAGE_KEY); + let wallet_opt = BdkWallet::load().load_wallet_async(&mut persister).await?; + + let wallet = match wallet_opt { + Some(wallet) => wallet, + None => return Err(JsError::new("Failed to load wallet, check the changeset")), + }; + + let client = Builder::new(&url).build_async()?; + + Ok(SnapWallet { + wallet, + client, + persister, + }) + } + pub async fn from_descriptors( network: Network, external_descriptor: String, @@ -108,24 +126,6 @@ impl SnapWallet { Self::create(network, external_descriptor, internal_descriptor, url).await } - pub async fn load(url: &str) -> JsResult { - let mut persister = SnapPersister::new(STORAGE_KEY); - let wallet_opt = BdkWallet::load().load_wallet_async(&mut persister).await?; - - let wallet = match wallet_opt { - Some(wallet) => wallet, - None => return Err(JsError::new("Failed to load wallet, check the changeset")), - }; - - let client = Builder::new(&url).build_async()?; - - Ok(SnapWallet { - wallet, - client, - persister, - }) - } - pub async fn full_scan(&mut self, stop_gap: usize, parallel_requests: usize) -> JsResult<()> { let request = self.wallet.start_full_scan(); let update = self