diff --git a/.github/workflows/cd-docs.yml b/.github/workflows/cd-docs.yml index 2f1f9248616..9b6e6facc56 100644 --- a/.github/workflows/cd-docs.yml +++ b/.github/workflows/cd-docs.yml @@ -2,15 +2,14 @@ name: cd-docs on: workflow_dispatch: - push: - paths: - - 'documentation/docs/**' jobs: build: - runs-on: custom-linux + runs-on: ubuntu-20.04-16-core steps: - uses: actions/checkout@v3 + - name: Install Dependencies (Linux) + run: sudo apt-get update && sudo apt-get install -y build-essential curl wget libssl-dev libudev-dev squashfs-tools protobuf-compiler - name: Install rsync run: sudo apt-get install rsync - uses: rlespinasse/github-slug-action@v3.x @@ -26,14 +25,11 @@ jobs: with: command: build args: --workspace --release - - name: Install mdbook - run: (test -x $HOME/.cargo/bin/mdbook || cargo install --vers "^0.4.33" mdbook) - - name: Install mdbook plugins - run: | - cargo install --vers "=0.2.2" mdbook-variables && cargo install \ - --vers "^1.8.0" mdbook-admonish && cargo install --vers \ - "^0.1.2" mdbook-last-changed && cargo install --vers "^0.1.2" mdbook-theme \ - && cargo install --vers "^0.7.7" mdbook-linkcheck + - name: Install mdbook and plugins + run: cd documentation && ./install_mdbook_deps.sh + - name: Remove existing Nym config directory (`~/.nym/`) + run: cd documentation && ./remove_existing_config.sh + continue-on-error: false - name: Build all projects in documentation/ & move to ~/dist/docs/ run: cd documentation && ./build_all_to_dist.sh continue-on-error: false @@ -52,6 +48,7 @@ jobs: - name: Install Vercel CLI run: npm install --global vercel@latest + continue-on-error: false - name: Pull Vercel Environment Information (preview) if: github.ref != 'refs/heads/master' @@ -61,15 +58,18 @@ jobs: if: github.ref == 'refs/heads/master' run: vercel pull --yes --environment=production --token=${{ secrets.VERCEL_TOKEN }} working-directory: dist/docs + continue-on-error: false - name: Build Project Artifacts (preview) if: github.ref != 'refs/heads/master' run: vercel build --token=${{ secrets.VERCEL_TOKEN }} working-directory: dist/docs + continue-on-error: false - name: Build Project Artifacts (production) if: github.ref == 'refs/heads/master' run: vercel build --prod --token=${{ secrets.VERCEL_TOKEN }} working-directory: dist/docs + continue-on-error: false - name: Deploy Project Artifacts to Vercel (preview) if: github.ref != 'refs/heads/master' @@ -79,6 +79,7 @@ jobs: if: github.ref == 'refs/heads/master' run: vercel deploy --prebuilt --prod --token=${{ secrets.VERCEL_TOKEN }} working-directory: dist/docs + continue-on-error: false - name: Matrix - Node Install run: npm install diff --git a/.github/workflows/ci-docs.yml b/.github/workflows/ci-docs.yml index 3bcf0a26792..7e67a9f4326 100644 --- a/.github/workflows/ci-docs.yml +++ b/.github/workflows/ci-docs.yml @@ -9,9 +9,11 @@ on: jobs: build: - runs-on: custom-linux + runs-on: ubuntu-20.04-16-core steps: - uses: actions/checkout@v3 + - name: Install Dependencies (Linux) + run: sudo apt-get update && sudo apt-get install -y build-essential curl wget libssl-dev libudev-dev squashfs-tools protobuf-compiler - name: Install rsync run: sudo apt-get install rsync - uses: rlespinasse/github-slug-action@v3.x @@ -27,22 +29,15 @@ jobs: with: command: build args: --workspace --release - - name: Install mdbook - run: (test -x $HOME/.cargo/bin/mdbook || cargo install --vers "^0.4.35" mdbook) - - name: Install mdbook plugins - run: | - cargo install --vers "=0.2.2" mdbook-variables && cargo install \ - --vers "^1.8.0" mdbook-admonish --force && cargo install --vers \ - "^0.1.2" mdbook-last-changed && cargo install --vers "^0.1.2" mdbook-theme \ - && cargo install --vers "^0.7.7" mdbook-linkcheck \ - # && cd documentation \ - # && mdbook-admonish install dev-portal \ - # && mdbook-admonish install docs \ - # && mdbook-admonish install operators - + - name: Install mdbook and plugins + run: cd documentation && ./install_mdbook_deps.sh + - name: Remove existing Nym config directory (`~/.nym/`) + run: cd documentation && ./remove_existing_config.sh + continue-on-error: false - name: Build all projects in documentation/ & move to ~/dist/docs/ - run: cd documentation && ./build_all_to_dist.sh + run: cd documentation && ./build_all_to_dist.sh continue-on-error: false + - name: Deploy branch to CI www continue-on-error: true uses: easingthemes/ssh-deploy@main @@ -54,6 +49,7 @@ jobs: REMOTE_USER: ${{ secrets.CI_WWW_REMOTE_USER }} TARGET: ${{ secrets.CI_WWW_REMOTE_TARGET }}/docs-${{ env.GITHUB_REF_SLUG }} EXCLUDE: "/node_modules/" + - name: Matrix - Node Install run: npm install working-directory: .github/workflows/support-files diff --git a/CHANGELOG.md b/CHANGELOG.md index bc5d422ecd8..f5a720221c8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,28 @@ Post 1.0.0 release, the changelog format is based on [Keep a Changelog](https:// ## [Unreleased] +## [2023.5-rolo] (2023-11-28) + +- Gateway won't open websocket listener until embedded Network Requester becomes available ([#4166]) +- Feature/gateway described nr ([#4147]) +- Bugfix/prerelease versionbump ([#4145]) +- returning 'nil' for non-existing origin as opposed to an empty string ([#4135]) +- using performance^20 when calculating active set selection weight ([#4126]) +- Change default http API timeout from 3s to 10s ([#4117]) + +[#4166]: https://github.com/nymtech/nym/issues/4166 +[#4147]: https://github.com/nymtech/nym/pull/4147 +[#4145]: https://github.com/nymtech/nym/pull/4145 +[#4135]: https://github.com/nymtech/nym/pull/4135 +[#4126]: https://github.com/nymtech/nym/pull/4126 +[#4117]: https://github.com/nymtech/nym/pull/4117 + +## [2023.nyxd-upgrade] (2023-11-22) + +- Chore/nyxd 043 upgrade ([#3968]) + +[#3968]: https://github.com/nymtech/nym/pull/3968 + ## [2023.4-galaxy] (2023-11-07) - DRY up client cli ([#4077]) diff --git a/Cargo.lock b/Cargo.lock index 2f406bb985b..0b8497f9a0c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -628,17 +628,6 @@ dependencies = [ "event-listener", ] -[[package]] -name = "async-recursion" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5fd55a5ba1179988837d24ab4c7cc8ed6efdeff578ede0416b4225a5fca35bd0" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.38", -] - [[package]] name = "async-stream" version = "0.3.5" @@ -1030,29 +1019,6 @@ version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "845141a4fade3f790628b7daaaa298a25b204fb28907eb54febe5142db6ce653" -[[package]] -name = "boringtun" -version = "0.6.0" -source = "git+https://github.com/cloudflare/boringtun?rev=e1d6360d6ab4529fc942a078e4c54df107abe2ba#e1d6360d6ab4529fc942a078e4c54df107abe2ba" -dependencies = [ - "aead 0.5.2", - "base64 0.13.1", - "blake2 0.10.6", - "chacha20poly1305 0.10.1", - "hex", - "hmac 0.12.1", - "ip_network", - "ip_network_table", - "libc", - "nix 0.25.1", - "parking_lot 0.12.1", - "rand_core 0.6.4", - "ring 0.16.20", - "tracing", - "untrusted 0.9.0", - "x25519-dalek 2.0.0", -] - [[package]] name = "brotli" version = "3.4.0" @@ -1554,8 +1520,8 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2895653b4d9f1538a83970077cb01dfc77a4810524e51a110944688e916b18e" dependencies = [ - "prost", - "prost-types", + "prost 0.11.9", + "prost-types 0.11.9", "tonic", "tracing-core", ] @@ -1572,7 +1538,7 @@ dependencies = [ "futures", "hdrhistogram", "humantime 2.1.0", - "prost-types", + "prost-types 0.11.9", "serde", "serde_json", "thread_local", @@ -1661,30 +1627,30 @@ dependencies = [ [[package]] name = "cosmos-sdk-proto" -version = "0.19.0" +version = "0.20.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73c9d2043a9e617b0d602fbc0a0ecd621568edbf3a9774890a6d562389bd8e1c" +checksum = "32560304ab4c365791fd307282f76637213d8083c1a98490c35159cd67852237" dependencies = [ - "prost", - "prost-types", + "prost 0.12.1", + "prost-types 0.12.1", "tendermint-proto", ] [[package]] name = "cosmrs" -version = "0.14.0" +version = "0.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af13955d6f356272e6def9ff5e2450a7650df536d8934f47052a20c76513d2f6" +checksum = "47126f5364df9387b9d8559dcef62e99010e1d4098f39eb3f7ee4b5c254e40ea" dependencies = [ "bip32", "cosmos-sdk-proto", "ecdsa 0.16.8", "eyre", - "getrandom 0.2.10", "k256", "rand_core 0.6.4", "serde", "serde_json", + "signature 2.1.0", "subtle-encoding", "tendermint", "tendermint-rpc", @@ -2009,15 +1975,6 @@ dependencies = [ "subtle 2.4.1", ] -[[package]] -name = "ct-logs" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1a816186fa68d9e426e3cb4ae4dff1fcd8e4a2c34b781bf7a822574a0d0aac8" -dependencies = [ - "sct 0.6.1", -] - [[package]] name = "ctor" version = "0.1.26" @@ -2346,6 +2303,25 @@ dependencies = [ "syn 1.0.109", ] +[[package]] +name = "defguard_wireguard_rs" +version = "0.3.0" +source = "git+https://github.com/neacsu/wireguard-rs.git?rev=c2cd0c1119f699f4bc43f5e6ffd6fc242caa42ed#c2cd0c1119f699f4bc43f5e6ffd6fc242caa42ed" +dependencies = [ + "base64 0.21.4", + "libc", + "log", + "netlink-packet-core 0.7.0", + "netlink-packet-generic", + "netlink-packet-route 0.17.1", + "netlink-packet-utils", + "netlink-packet-wireguard", + "netlink-sys", + "nix 0.27.1", + "serde", + "thiserror", +] + [[package]] name = "der" version = "0.6.1" @@ -2938,7 +2914,7 @@ checksum = "0206175f82b8d6bf6652ff7d71a1e27fd2e4efde587fd368662814d6ec1d9ce0" [[package]] name = "explorer-api" -version = "1.1.31" +version = "1.1.32" dependencies = [ "chrono", "clap 4.4.7", @@ -3696,30 +3672,6 @@ dependencies = [ "num-traits", ] -[[package]] -name = "headers" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06683b93020a07e3dbcf5f8c0f6d40080d725bea7936fc01ad345c01b97dc270" -dependencies = [ - "base64 0.21.4", - "bytes", - "headers-core", - "http", - "httpdate", - "mime", - "sha1", -] - -[[package]] -name = "headers-core" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7f66481bfee273957b1f20485a4ff3362987f85b2c236580d81b4eb7a326429" -dependencies = [ - "http", -] - [[package]] name = "heck" version = "0.3.3" @@ -3957,41 +3909,18 @@ dependencies = [ "want", ] -[[package]] -name = "hyper-proxy" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca815a891b24fdfb243fa3239c86154392b0953ee584aa1a2a1f66d20cbe75cc" -dependencies = [ - "bytes", - "futures", - "headers", - "http", - "hyper", - "hyper-rustls", - "rustls-native-certs", - "tokio", - "tokio-rustls 0.22.0", - "tower-service", - "webpki 0.21.4", -] - [[package]] name = "hyper-rustls" -version = "0.22.1" +version = "0.24.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f9f7a97316d44c0af9b0301e65010573a853a9fc97046d7331d7f6bc0fd5a64" +checksum = "8d78e1e73ec14cf7375674f74d7dde185c8206fd9dea6fb6295e8a98098aaa97" dependencies = [ - "ct-logs", "futures-util", + "http", "hyper", - "log", - "rustls 0.19.1", - "rustls-native-certs", + "rustls 0.21.7", "tokio", - "tokio-rustls 0.22.0", - "webpki 0.21.4", - "webpki-roots 0.21.1", + "tokio-rustls 0.24.1", ] [[package]] @@ -4248,22 +4177,6 @@ version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aa2f047c0a98b2f299aa5d6d7088443570faae494e9ae1305e48be000c9e0eb1" -[[package]] -name = "ip_network_table" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4099b7cfc5c5e2fe8c5edf3f6f7adf7a714c9cc697534f63a5a5da30397cb2c0" -dependencies = [ - "ip_network", - "ip_network_table-deps-treebitmap", -] - -[[package]] -name = "ip_network_table-deps-treebitmap" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e537132deb99c0eb4b752f0346b6a836200eaaa3516dd7e5514b63930a09e5d" - [[package]] name = "ipconfig" version = "0.3.2" @@ -4658,7 +4571,7 @@ dependencies = [ "once_cell", "parking_lot 0.12.1", "pin-project", - "prost", + "prost 0.11.9", "prost-build", "rand 0.8.5", "rw-stream-sink 0.3.0 (git+https://github.com/ChainSafe/rust-libp2p.git?rev=e3440d25681df380c9f0f8cfdcfd5ecc0a4f2fb6)", @@ -4744,7 +4657,7 @@ dependencies = [ "libp2p-swarm 0.42.0", "log", "prometheus-client", - "prost", + "prost 0.11.9", "prost-build", "prost-codec", "rand 0.8.5", @@ -4802,7 +4715,7 @@ dependencies = [ "libp2p-swarm 0.42.0", "log", "lru 0.9.0", - "prost", + "prost 0.11.9", "prost-build", "prost-codec", "smallvec", @@ -4952,7 +4865,7 @@ dependencies = [ "libp2p-core 0.39.0", "log", "once_cell", - "prost", + "prost 0.11.9", "prost-build", "rand 0.8.5", "sha2 0.10.8", @@ -5204,7 +5117,7 @@ dependencies = [ "libp2p-noise 0.42.0", "log", "multihash", - "prost", + "prost 0.11.9", "prost-build", "prost-codec", "rand 0.8.5", @@ -5750,6 +5663,29 @@ dependencies = [ "netlink-packet-utils", ] +[[package]] +name = "netlink-packet-core" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72724faf704479d67b388da142b186f916188505e7e0b26719019c525882eda4" +dependencies = [ + "anyhow", + "byteorder", + "netlink-packet-utils", +] + +[[package]] +name = "netlink-packet-generic" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1cd7eb8ad331c84c6b8cb7f685b448133e5ad82e1ffd5acafac374af4a5a308b" +dependencies = [ + "anyhow", + "byteorder", + "netlink-packet-core 0.7.0", + "netlink-packet-utils", +] + [[package]] name = "netlink-packet-route" version = "0.12.0" @@ -5760,7 +5696,21 @@ dependencies = [ "bitflags 1.3.2", "byteorder", "libc", - "netlink-packet-core", + "netlink-packet-core 0.4.2", + "netlink-packet-utils", +] + +[[package]] +name = "netlink-packet-route" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053998cea5a306971f88580d0829e90f270f940befd7cf928da179d4187a5a66" +dependencies = [ + "anyhow", + "bitflags 1.3.2", + "byteorder", + "libc", + "netlink-packet-core 0.7.0", "netlink-packet-utils", ] @@ -5776,6 +5726,20 @@ dependencies = [ "thiserror", ] +[[package]] +name = "netlink-packet-wireguard" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60b25b050ff1f6a1e23c6777b72db22790fe5b6b5ccfd3858672587a79876c8f" +dependencies = [ + "anyhow", + "byteorder", + "libc", + "log", + "netlink-packet-generic", + "netlink-packet-utils", +] + [[package]] name = "netlink-proto" version = "0.10.0" @@ -5785,7 +5749,7 @@ dependencies = [ "bytes", "futures", "log", - "netlink-packet-core", + "netlink-packet-core 0.4.2", "netlink-sys", "thiserror", "tokio", @@ -5816,18 +5780,6 @@ dependencies = [ "memoffset 0.6.5", ] -[[package]] -name = "nix" -version = "0.25.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f346ff70e7dbfd675fe90590b92d59ef2de15a8779ae305ebcbfd3f0caf59be4" -dependencies = [ - "autocfg 1.1.0", - "bitflags 1.3.2", - "cfg-if", - "libc", -] - [[package]] name = "nix" version = "0.27.1" @@ -5837,6 +5789,7 @@ dependencies = [ "bitflags 2.4.1", "cfg-if", "libc", + "memoffset 0.9.0", ] [[package]] @@ -5961,7 +5914,7 @@ dependencies = [ [[package]] name = "nym-api" -version = "1.1.32" +version = "1.1.34" dependencies = [ "actix-web", "anyhow", @@ -6111,7 +6064,7 @@ dependencies = [ [[package]] name = "nym-cli" -version = "1.1.31" +version = "1.1.33" dependencies = [ "anyhow", "base64 0.13.1", @@ -6184,7 +6137,7 @@ dependencies = [ [[package]] name = "nym-client" -version = "1.1.31" +version = "1.1.32" dependencies = [ "clap 4.4.7", "dirs 4.0.0", @@ -6528,7 +6481,7 @@ dependencies = [ [[package]] name = "nym-gateway" -version = "1.1.31" +version = "1.1.32" dependencies = [ "anyhow", "async-trait", @@ -6538,6 +6491,7 @@ dependencies = [ "clap 4.4.7", "colored", "dashmap", + "defguard_wireguard_rs", "dirs 4.0.0", "dotenvy", "futures", @@ -6664,7 +6618,9 @@ dependencies = [ "bincode", "bytes", "nym-sphinx", + "rand 0.8.5", "serde", + "thiserror", ] [[package]] @@ -6689,12 +6645,14 @@ dependencies = [ "nym-tun", "nym-wireguard", "nym-wireguard-types", + "rand 0.8.5", "reqwest", "serde", "serde_json", "tap", "thiserror", "tokio", + "tokio-tun", "url", ] @@ -6733,7 +6691,7 @@ dependencies = [ [[package]] name = "nym-mixnode" -version = "1.1.33" +version = "1.1.34" dependencies = [ "anyhow", "axum", @@ -6853,7 +6811,7 @@ dependencies = [ [[package]] name = "nym-network-requester" -version = "1.1.31" +version = "1.1.32" dependencies = [ "anyhow", "async-file-watcher", @@ -6901,7 +6859,7 @@ dependencies = [ [[package]] name = "nym-network-statistics" -version = "1.1.31" +version = "1.1.32" dependencies = [ "dirs 4.0.0", "log", @@ -7146,7 +7104,7 @@ dependencies = [ [[package]] name = "nym-socks5-client" -version = "1.1.31" +version = "1.1.32" dependencies = [ "clap 4.4.7", "lazy_static", @@ -7525,6 +7483,7 @@ version = "0.1.0" dependencies = [ "async-trait", "base64 0.13.1", + "bip32", "bip39", "colored", "cosmrs", @@ -7555,7 +7514,7 @@ dependencies = [ "nym-service-provider-directory-common", "nym-vesting-contract-common", "openssl", - "prost", + "prost 0.12.1", "reqwest", "serde", "serde_json", @@ -7606,27 +7565,15 @@ dependencies = [ name = "nym-wireguard" version = "0.1.0" dependencies = [ - "async-recursion", "base64 0.21.4", - "bincode", - "boringtun", - "bytes", - "dashmap", - "etherparse", - "futures", + "defguard_wireguard_rs", "ip_network", - "ip_network_table", "log", - "nym-sphinx", + "nym-network-defaults", "nym-task", - "nym-tun", "nym-wireguard-types", - "rand 0.8.5", - "serde", - "tap", - "thiserror", "tokio", - "tokio-tun", + "x25519-dalek 2.0.0", ] [[package]] @@ -7634,12 +7581,8 @@ name = "nym-wireguard-types" version = "0.1.0" dependencies = [ "base64 0.21.4", - "boringtun", - "bytes", "dashmap", "hmac 0.12.1", - "ip_network", - "ip_network_table", "log", "nym-crypto", "rand 0.7.3", @@ -7647,7 +7590,6 @@ dependencies = [ "serde_json", "sha2 0.10.8", "thiserror", - "tokio", "utoipa", "x25519-dalek 2.0.0", ] @@ -8431,7 +8373,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b82eaa1d779e9a4bc1c3217db8ffbeabaae1dca241bf70183242128d48681cd" dependencies = [ "bytes", - "prost-derive", + "prost-derive 0.11.9", +] + +[[package]] +name = "prost" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4fdd22f3b9c31b53c060df4a0613a1c7f062d4115a2b984dd15b1858f7e340d" +dependencies = [ + "bytes", + "prost-derive 0.12.1", ] [[package]] @@ -8448,8 +8400,8 @@ dependencies = [ "multimap", "petgraph", "prettyplease", - "prost", - "prost-types", + "prost 0.11.9", + "prost-types 0.11.9", "regex", "syn 1.0.109", "tempfile", @@ -8463,7 +8415,7 @@ source = "git+https://github.com/ChainSafe/rust-libp2p.git?rev=e3440d25681df380c dependencies = [ "asynchronous-codec", "bytes", - "prost", + "prost 0.11.9", "thiserror", "unsigned-varint", ] @@ -8481,13 +8433,35 @@ dependencies = [ "syn 1.0.109", ] +[[package]] +name = "prost-derive" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "265baba7fabd416cf5078179f7d2cbeca4ce7a9041111900675ea7c4cb8a4c32" +dependencies = [ + "anyhow", + "itertools 0.11.0", + "proc-macro2", + "quote", + "syn 2.0.38", +] + [[package]] name = "prost-types" version = "0.11.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "213622a1460818959ac1181aaeb2dc9c7f63df720db7d788b3e24eacd1983e13" dependencies = [ - "prost", + "prost 0.11.9", +] + +[[package]] +name = "prost-types" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e081b29f63d83a4bc75cfc9f3fe424f9156cf92d8a4f0c9407cce9a1b67327cf" +dependencies = [ + "prost 0.12.1", ] [[package]] @@ -8999,6 +8973,7 @@ dependencies = [ "http", "http-body", "hyper", + "hyper-rustls", "hyper-tls", "ipnet", "js-sys", @@ -9008,12 +8983,16 @@ dependencies = [ "once_cell", "percent-encoding", "pin-project-lite 0.2.13", + "rustls 0.21.7", + "rustls-native-certs", + "rustls-pemfile", "serde", "serde_json", "serde_urlencoded", "system-configuration", "tokio", "tokio-native-tls", + "tokio-rustls 0.24.1", "tokio-socks", "tower-service", "url", @@ -9237,7 +9216,7 @@ checksum = "322c53fd76a18698f1c27381d58091de3a043d356aa5bd0d510608b565f469a0" dependencies = [ "futures", "log", - "netlink-packet-route", + "netlink-packet-route 0.12.0", "netlink-proto", "nix 0.24.3", "thiserror", @@ -9413,12 +9392,12 @@ dependencies = [ [[package]] name = "rustls-native-certs" -version = "0.5.0" +version = "0.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a07b7c1885bd8ed3831c289b7870b13ef46fe0e856d288c30d9cc17d75a2092" +checksum = "a9aace74cb666635c918e9c12bc0d348266037aa8eb599b5cba565709a8dff00" dependencies = [ "openssl-probe", - "rustls 0.19.1", + "rustls-pemfile", "schannel", "security-framework", ] @@ -10619,9 +10598,9 @@ dependencies = [ [[package]] name = "tendermint" -version = "0.32.2" +version = "0.34.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f0a7d05cf78524782337f8edd55cbc578d159a16ad4affe2135c92f7dbac7f0" +checksum = "bc2294fa667c8b548ee27a9ba59115472d0a09c2ba255771092a7f1dcf03a789" dependencies = [ "bytes", "digest 0.10.7", @@ -10632,8 +10611,8 @@ dependencies = [ "k256", "num-traits", "once_cell", - "prost", - "prost-types", + "prost 0.12.1", + "prost-types 0.12.1", "ripemd", "serde", "serde_bytes", @@ -10650,9 +10629,9 @@ dependencies = [ [[package]] name = "tendermint-config" -version = "0.32.2" +version = "0.34.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "71a72dbbea6dde12045d261f2c70c0de039125675e8a026c8d5ad34522756372" +checksum = "5a25dbe8b953e80f3d61789fbdb83bf9ad6c0ef16df5ca6546f49912542cc137" dependencies = [ "flex-error", "serde", @@ -10664,16 +10643,16 @@ dependencies = [ [[package]] name = "tendermint-proto" -version = "0.32.2" +version = "0.34.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0cec054567d16d85e8c3f6a3139963d1a66d9d3051ed545d31562550e9bcc3d" +checksum = "2cc728a4f9e891d71adf66af6ecaece146f9c7a11312288a3107b3e1d6979aaf" dependencies = [ "bytes", "flex-error", "num-derive", "num-traits", - "prost", - "prost-types", + "prost 0.12.1", + "prost-types 0.12.1", "serde", "serde_bytes", "subtle-encoding", @@ -10682,21 +10661,18 @@ dependencies = [ [[package]] name = "tendermint-rpc" -version = "0.32.2" +version = "0.34.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d119d83a130537fc4a98c3c9eb6899ebe857fea4860400a61675bfb5f0b35129" +checksum = "dfbf0a4753b46a190f367337e0163d0b552a2674a6bac54e74f9f2cdcde2969b" dependencies = [ "async-trait", "bytes", "flex-error", "futures", "getrandom 0.2.10", - "http", - "hyper", - "hyper-proxy", - "hyper-rustls", "peg", "pin-project", + "reqwest", "semver 1.0.20", "serde", "serde_bytes", @@ -10920,6 +10896,16 @@ dependencies = [ "webpki 0.22.4", ] +[[package]] +name = "tokio-rustls" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c28327cf380ac148141087fbfb9de9d7bd4e84ab5d2c28fbc911d753de8a7081" +dependencies = [ + "rustls 0.21.7", + "tokio", +] + [[package]] name = "tokio-socks" version = "0.5.1" @@ -10959,9 +10945,9 @@ dependencies = [ [[package]] name = "tokio-tun" -version = "0.9.1" +version = "0.11.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4a67d1405a577ba1f4cd61f46608f1db2cadbb6a9549c3fc2eed7f1195393c9" +checksum = "bf2efaf33e86779a3a68b1f1d6e9e13a346c1c75ee3cab7a4293235c463b2668" dependencies = [ "libc", "nix 0.27.1", @@ -11111,7 +11097,7 @@ dependencies = [ "hyper-timeout", "percent-encoding", "pin-project", - "prost", + "prost 0.11.9", "tokio", "tokio-stream", "tower", diff --git a/Cargo.toml b/Cargo.toml index a7f53657117..a8443fc8162 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -139,24 +139,8 @@ async-trait = "0.1.68" axum = "0.6.20" base64 = "0.21.4" bip39 = { version = "2.0.0", features = ["zeroize"] } -boringtun = { git = "https://github.com/cloudflare/boringtun", rev = "e1d6360d6ab4529fc942a078e4c54df107abe2ba" } clap = "4.4.7" cfg-if = "1.0.0" -cosmwasm-derive = "=1.3.0" -cosmwasm-schema = "=1.3.0" -cosmwasm-std = "=1.3.0" -# use 0.5.0 as that's the version used by cosmwasm-std 1.3.0 -# (and ideally we don't want to pull the same dependency twice) -serde-json-wasm = "=0.5.0" -cosmwasm-storage = "=1.3.0" -cosmrs = "=0.14.0" -# same version as used by cosmrs -cw-utils = "=1.0.1" -cw-storage-plus = "=1.1.0" -cw2 = { version = "=1.1.0" } -cw3 = { version = "=1.1.0" } -cw4 = { version = "=1.1.0" } -cw-controllers = { version = "=1.1.0" } dashmap = "5.5.3" dotenvy = "0.15.6" futures = "0.3.28" @@ -174,7 +158,6 @@ schemars = "0.8.1" serde = "1.0.152" serde_json = "1.0.91" tap = "1.0.1" -tendermint-rpc = "0.32" # same version as used by cosmrs thiserror = "1.0.48" tokio = "1.24.1" tokio-tungstenite = "0.20.1" @@ -186,6 +169,28 @@ utoipa-swagger-ui = "3.1.5" url = "2.4" zeroize = "1.6.0" +# cosmwasm-related +cosmwasm-derive = "=1.3.0" +cosmwasm-schema = "=1.3.0" +cosmwasm-std = "=1.3.0" +# use 0.5.0 as that's the version used by cosmwasm-std 1.3.0 +# (and ideally we don't want to pull the same dependency twice) +serde-json-wasm = "=0.5.0" +cosmwasm-storage = "=1.3.0" +# same version as used by cosmwasm +cw-utils = "=1.0.1" +cw-storage-plus = "=1.1.0" +cw2 = { version = "=1.1.0" } +cw3 = { version = "=1.1.0" } +cw4 = { version = "=1.1.0" } +cw-controllers = { version = "=1.1.0" } + +# cosmrs-related +bip32 = "0.5.1" +cosmrs = "=0.15.0" +tendermint-rpc = "0.34" # same version as used by cosmrs +prost = "0.12" + # wasm-related dependencies gloo-utils = "0.1.7" js-sys = "0.3.63" diff --git a/LICENSES/CC-BY-NC-SA-4.0.txt b/LICENSES/CC-BY-NC-SA-4.0.txt new file mode 100644 index 00000000000..8e418ce3854 --- /dev/null +++ b/LICENSES/CC-BY-NC-SA-4.0.txt @@ -0,0 +1,439 @@ +Attribution-NonCommercial-ShareAlike 4.0 International + +======================================================================= + +Creative Commons Corporation ("Creative Commons") is not a law firm and +does not provide legal services or legal advice. Distribution of +Creative Commons public licenses does not create a lawyer-client or +other relationship. Creative Commons makes its licenses and related +information available on an "as-is" basis. Creative Commons gives no +warranties regarding its licenses, any material licensed under their +terms and conditions, or any related information. Creative Commons +disclaims all liability for damages resulting from their use to the +fullest extent possible. + +Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and +conditions that creators and other rights holders may use to share +original works of authorship and other material subject to copyright +and certain other rights specified in the public license below. The +following considerations are for informational purposes only, are not +exhaustive, and do not form part of our licenses. + + Considerations for licensors: Our public licenses are + intended for use by those authorized to give the public + permission to use material in ways otherwise restricted by + copyright and certain other rights. Our licenses are + irrevocable. Licensors should read and understand the terms + and conditions of the license they choose before applying it. + Licensors should also secure all rights necessary before + applying our licenses so that the public can reuse the + material as expected. Licensors should clearly mark any + material not subject to the license. This includes other CC- + licensed material, or material used under an exception or + limitation to copyright. More considerations for licensors: + wiki.creativecommons.org/Considerations_for_licensors + + Considerations for the public: By using one of our public + licenses, a licensor grants the public permission to use the + licensed material under specified terms and conditions. If + the licensor's permission is not necessary for any reason--for + example, because of any applicable exception or limitation to + copyright--then that use is not regulated by the license. Our + licenses grant only permissions under copyright and certain + other rights that a licensor has authority to grant. Use of + the licensed material may still be restricted for other + reasons, including because others have copyright or other + rights in the material. A licensor may make special requests, + such as asking that all changes be marked or described. + Although not required by our licenses, you are encouraged to + respect those requests where reasonable. More considerations + for the public: + wiki.creativecommons.org/Considerations_for_licensees + +======================================================================= + +Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International +Public License + +By exercising the Licensed Rights (defined below), You accept and agree +to be bound by the terms and conditions of this Creative Commons +Attribution-NonCommercial-ShareAlike 4.0 International Public License +("Public License"). To the extent this Public License may be +interpreted as a contract, You are granted the Licensed Rights in +consideration of Your acceptance of these terms and conditions, and the +Licensor grants You such rights in consideration of benefits the +Licensor receives from making the Licensed Material available under +these terms and conditions. + + +Section 1 -- Definitions. + + a. Adapted Material means material subject to Copyright and Similar + Rights that is derived from or based upon the Licensed Material + and in which the Licensed Material is translated, altered, + arranged, transformed, or otherwise modified in a manner requiring + permission under the Copyright and Similar Rights held by the + Licensor. For purposes of this Public License, where the Licensed + Material is a musical work, performance, or sound recording, + Adapted Material is always produced where the Licensed Material is + synched in timed relation with a moving image. + + b. Adapter's License means the license You apply to Your Copyright + and Similar Rights in Your contributions to Adapted Material in + accordance with the terms and conditions of this Public License. + + c. BY-NC-SA Compatible License means a license listed at + creativecommons.org/compatiblelicenses, approved by Creative + Commons as essentially the equivalent of this Public License. + + d. Copyright and Similar Rights means copyright and/or similar rights + closely related to copyright including, without limitation, + performance, broadcast, sound recording, and Sui Generis Database + Rights, without regard to how the rights are labeled or + categorized. For purposes of this Public License, the rights + specified in Section 2(b)(1)-(2) are not Copyright and Similar + Rights. + + e. Effective Technological Measures means those measures that, in the + absence of proper authority, may not be circumvented under laws + fulfilling obligations under Article 11 of the WIPO Copyright + Treaty adopted on December 20, 1996, and/or similar international + agreements. + + f. Exceptions and Limitations means fair use, fair dealing, and/or + any other exception or limitation to Copyright and Similar Rights + that applies to Your use of the Licensed Material. + + g. License Elements means the license attributes listed in the name + of a Creative Commons Public License. The License Elements of this + Public License are Attribution, NonCommercial, and ShareAlike. + + h. Licensed Material means the artistic or literary work, database, + or other material to which the Licensor applied this Public + License. + + i. Licensed Rights means the rights granted to You subject to the + terms and conditions of this Public License, which are limited to + all Copyright and Similar Rights that apply to Your use of the + Licensed Material and that the Licensor has authority to license. + + j. Licensor means the individual(s) or entity(ies) granting rights + under this Public License. + + k. NonCommercial means not primarily intended for or directed towards + commercial advantage or monetary compensation. For purposes of + this Public License, the exchange of the Licensed Material for + other material subject to Copyright and Similar Rights by digital + file-sharing or similar means is NonCommercial provided there is + no payment of monetary compensation in connection with the + exchange. + + l. Share means to provide material to the public by any means or + process that requires permission under the Licensed Rights, such + as reproduction, public display, public performance, distribution, + dissemination, communication, or importation, and to make material + available to the public including in ways that members of the + public may access the material from a place and at a time + individually chosen by them. + + m. Sui Generis Database Rights means rights other than copyright + resulting from Directive 96/9/EC of the European Parliament and of + the Council of 11 March 1996 on the legal protection of databases, + as amended and/or succeeded, as well as other essentially + equivalent rights anywhere in the world. + + n. You means the individual or entity exercising the Licensed Rights + under this Public License. Your has a corresponding meaning. + + +Section 2 -- Scope. + + a. License grant. + + 1. Subject to the terms and conditions of this Public License, + the Licensor hereby grants You a worldwide, royalty-free, + non-sublicensable, non-exclusive, irrevocable license to + exercise the Licensed Rights in the Licensed Material to: + + a. reproduce and Share the Licensed Material, in whole or + in part, for NonCommercial purposes only; and + + b. produce, reproduce, and Share Adapted Material for + NonCommercial purposes only. + + 2. Exceptions and Limitations. For the avoidance of doubt, where + Exceptions and Limitations apply to Your use, this Public + License does not apply, and You do not need to comply with + its terms and conditions. + + 3. Term. The term of this Public License is specified in Section + 6(a). + + 4. Media and formats; technical modifications allowed. The + Licensor authorizes You to exercise the Licensed Rights in + all media and formats whether now known or hereafter created, + and to make technical modifications necessary to do so. The + Licensor waives and/or agrees not to assert any right or + authority to forbid You from making technical modifications + necessary to exercise the Licensed Rights, including + technical modifications necessary to circumvent Effective + Technological Measures. For purposes of this Public License, + simply making modifications authorized by this Section 2(a) + (4) never produces Adapted Material. + + 5. Downstream recipients. + + a. Offer from the Licensor -- Licensed Material. Every + recipient of the Licensed Material automatically + receives an offer from the Licensor to exercise the + Licensed Rights under the terms and conditions of this + Public License. + + b. Additional offer from the Licensor -- Adapted Material. + Every recipient of Adapted Material from You + automatically receives an offer from the Licensor to + exercise the Licensed Rights in the Adapted Material + under the conditions of the Adapter's License You apply. + + c. No downstream restrictions. You may not offer or impose + any additional or different terms or conditions on, or + apply any Effective Technological Measures to, the + Licensed Material if doing so restricts exercise of the + Licensed Rights by any recipient of the Licensed + Material. + + 6. No endorsement. Nothing in this Public License constitutes or + may be construed as permission to assert or imply that You + are, or that Your use of the Licensed Material is, connected + with, or sponsored, endorsed, or granted official status by, + the Licensor or others designated to receive attribution as + provided in Section 3(a)(1)(A)(i). + + b. Other rights. + + 1. Moral rights, such as the right of integrity, are not + licensed under this Public License, nor are publicity, + privacy, and/or other similar personality rights; however, to + the extent possible, the Licensor waives and/or agrees not to + assert any such rights held by the Licensor to the limited + extent necessary to allow You to exercise the Licensed + Rights, but not otherwise. + + 2. Patent and trademark rights are not licensed under this + Public License. + + 3. To the extent possible, the Licensor waives any right to + collect royalties from You for the exercise of the Licensed + Rights, whether directly or through a collecting society + under any voluntary or waivable statutory or compulsory + licensing scheme. In all other cases the Licensor expressly + reserves any right to collect such royalties, including when + the Licensed Material is used other than for NonCommercial + purposes. + + +Section 3 -- License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the +following conditions. + + a. Attribution. + + 1. If You Share the Licensed Material (including in modified + form), You must: + + a. retain the following if it is supplied by the Licensor + with the Licensed Material: + + i. identification of the creator(s) of the Licensed + Material and any others designated to receive + attribution, in any reasonable manner requested by + the Licensor (including by pseudonym if + designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of + warranties; + + v. a URI or hyperlink to the Licensed Material to the + extent reasonably practicable; + + b. indicate if You modified the Licensed Material and + retain an indication of any previous modifications; and + + c. indicate the Licensed Material is licensed under this + Public License, and include the text of, or the URI or + hyperlink to, this Public License. + + 2. You may satisfy the conditions in Section 3(a)(1) in any + reasonable manner based on the medium, means, and context in + which You Share the Licensed Material. For example, it may be + reasonable to satisfy the conditions by providing a URI or + hyperlink to a resource that includes the required + information. + 3. If requested by the Licensor, You must remove any of the + information required by Section 3(a)(1)(A) to the extent + reasonably practicable. + + b. ShareAlike. + + In addition to the conditions in Section 3(a), if You Share + Adapted Material You produce, the following conditions also apply. + + 1. The Adapter's License You apply must be a Creative Commons + license with the same License Elements, this version or + later, or a BY-NC-SA Compatible License. + + 2. You must include the text of, or the URI or hyperlink to, the + Adapter's License You apply. You may satisfy this condition + in any reasonable manner based on the medium, means, and + context in which You Share Adapted Material. + + 3. You may not offer or impose any additional or different terms + or conditions on, or apply any Effective Technological + Measures to, Adapted Material that restrict exercise of the + rights granted under the Adapter's License You apply. + + +Section 4 -- Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that +apply to Your use of the Licensed Material: + + a. for the avoidance of doubt, Section 2(a)(1) grants You the right + to extract, reuse, reproduce, and Share all or a substantial + portion of the contents of the database for NonCommercial purposes + only; + + b. if You include all or a substantial portion of the database + contents in a database in which You have Sui Generis Database + Rights, then the database in which You have Sui Generis Database + Rights (but not its individual contents) is Adapted Material, + including for purposes of Section 3(b); and + + c. You must comply with the conditions in Section 3(a) if You Share + all or a substantial portion of the contents of the database. + +For the avoidance of doubt, this Section 4 supplements and does not +replace Your obligations under this Public License where the Licensed +Rights include other Copyright and Similar Rights. + + +Section 5 -- Disclaimer of Warranties and Limitation of Liability. + + a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE + EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS + AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF + ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, + IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, + WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR + PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, + ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT + KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT + ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. + + b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE + TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, + NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, + INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, + COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR + USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN + ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR + DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR + IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. + + c. The disclaimer of warranties and limitation of liability provided + above shall be interpreted in a manner that, to the extent + possible, most closely approximates an absolute disclaimer and + waiver of all liability. + + +Section 6 -- Term and Termination. + + a. This Public License applies for the term of the Copyright and + Similar Rights licensed here. However, if You fail to comply with + this Public License, then Your rights under this Public License + terminate automatically. + + b. Where Your right to use the Licensed Material has terminated under + Section 6(a), it reinstates: + + 1. automatically as of the date the violation is cured, provided + it is cured within 30 days of Your discovery of the + violation; or + + 2. upon express reinstatement by the Licensor. + + For the avoidance of doubt, this Section 6(b) does not affect any + right the Licensor may have to seek remedies for Your violations + of this Public License. + + c. For the avoidance of doubt, the Licensor may also offer the + Licensed Material under separate terms or conditions or stop + distributing the Licensed Material at any time; however, doing so + will not terminate this Public License. + + d. Sections 1, 5, 6, 7, and 8 survive termination of this Public + License. + + +Section 7 -- Other Terms and Conditions. + + a. The Licensor shall not be bound by any additional or different + terms or conditions communicated by You unless expressly agreed. + + b. Any arrangements, understandings, or agreements regarding the + Licensed Material not stated herein are separate from and + independent of the terms and conditions of this Public License. + + +Section 8 -- Interpretation. + + a. For the avoidance of doubt, this Public License does not, and + shall not be interpreted to, reduce, limit, restrict, or impose + conditions on any use of the Licensed Material that could lawfully + be made without permission under this Public License. + + b. To the extent possible, if any provision of this Public License is + deemed unenforceable, it shall be automatically reformed to the + minimum extent necessary to make it enforceable. If the provision + cannot be reformed, it shall be severed from this Public License + without affecting the enforceability of the remaining terms and + conditions. + + c. No term or condition of this Public License will be waived and no + failure to comply consented to unless expressly agreed to by the + Licensor. + + d. Nothing in this Public License constitutes or may be interpreted + as a limitation upon, or waiver of, any privileges and immunities + that apply to the Licensor or You, including from the legal + processes of any jurisdiction or authority. + +======================================================================= + +Creative Commons is not a party to its public +licenses. Notwithstanding, Creative Commons may elect to apply one of +its public licenses to material it publishes and in those instances +will be considered the “Licensor.” The text of the Creative Commons +public licenses is dedicated to the public domain under the CC0 Public +Domain Dedication. Except for the limited purpose of indicating that +material is shared under a Creative Commons public license or as +otherwise permitted by the Creative Commons policies published at +creativecommons.org/policies, Creative Commons does not authorize the +use of the trademark "Creative Commons" or any other trademark or logo +of Creative Commons without its prior written consent including, +without limitation, in connection with any unauthorized modifications +to any of its public licenses or any other arrangements, +understandings, or agreements concerning use of licensed material. For +the avoidance of doubt, this paragraph does not form part of the +public licenses. + +Creative Commons may be contacted at creativecommons.org. + + diff --git a/LICENSES/gpl-3.0 b/LICENSES/gpl-3.0 new file mode 100644 index 00000000000..d4f30f00ab1 --- /dev/null +++ b/LICENSES/gpl-3.0 @@ -0,0 +1,675 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means tocopy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. + diff --git a/clients/native/Cargo.toml b/clients/native/Cargo.toml index eaec06aa210..03827720bad 100644 --- a/clients/native/Cargo.toml +++ b/clients/native/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "nym-client" -version = "1.1.31" +version = "1.1.32" authors = ["Dave Hrycyszyn ", "Jędrzej Stuczyński "] description = "Implementation of the Nym Client" edition = "2021" diff --git a/clients/socks5/Cargo.toml b/clients/socks5/Cargo.toml index 3dc2b411ce6..3bd0cde7925 100644 --- a/clients/socks5/Cargo.toml +++ b/clients/socks5/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "nym-socks5-client" -version = "1.1.31" +version = "1.1.32" authors = ["Dave Hrycyszyn "] description = "A SOCKS5 localhost proxy that converts incoming messages to Sphinx and sends them to a Nym address" edition = "2021" diff --git a/common/client-core/src/client/base_client/storage/gateway_details.rs b/common/client-core/src/client/base_client/storage/gateway_details.rs index fe04aee5c34..d9eaddfa873 100644 --- a/common/client-core/src/client/base_client/storage/gateway_details.rs +++ b/common/client-core/src/client/base_client/storage/gateway_details.rs @@ -77,7 +77,7 @@ pub struct PersistedGatewayConfig { key_hash: Vec, /// Actual gateway details being persisted. - pub(crate) details: GatewayEndpointConfig, + pub details: GatewayEndpointConfig, } #[derive(Debug, Clone, Serialize, Deserialize)] diff --git a/common/client-libs/validator-client/Cargo.toml b/common/client-libs/validator-client/Cargo.toml index e16345f446d..808bacaad6b 100644 --- a/common/client-libs/validator-client/Cargo.toml +++ b/common/client-libs/validator-client/Cargo.toml @@ -45,13 +45,17 @@ cosmrs = { workspace = true, features = ["bip32", "cosmwasm"] } # import it just for the `Client` trait tendermint-rpc = { workspace = true } +# this is an extremely nasty import. we're explicitly bringing in bip32 so that via the magic (or curse, pick your poison) +# of cargo's feature unification we'd get `bip32/std` meaning we'd get `std::error::Error` for the re-exported (via cosmrs) bip32::Error type +bip32 = { workspace = true, default-features = false, features = ["std"] } + eyre = { version = "0.6" } cw-utils = { workspace = true } cw2 = { workspace = true } cw3 = { workspace = true } cw4 = { workspace = true } cw-controllers = { workspace = true } -prost = { version = "0.11", default-features = false } +prost = { workspace = true, default-features = false } flate2 = { version = "1.0.20" } sha2 = { version = "0.9.5" } itertools = { version = "0.10" } diff --git a/common/client-libs/validator-client/src/nyxd/cosmwasm_client/helpers.rs b/common/client-libs/validator-client/src/nyxd/cosmwasm_client/helpers.rs index b639b223e31..1718ab2f026 100644 --- a/common/client-libs/validator-client/src/nyxd/cosmwasm_client/helpers.rs +++ b/common/client-libs/validator-client/src/nyxd/cosmwasm_client/helpers.rs @@ -20,12 +20,12 @@ impl CheckResponse for broadcast::tx_commit::Response { }); } - if self.deliver_tx.code.is_err() { + if self.tx_result.code.is_err() { return Err(NyxdError::BroadcastTxErrorDeliverTx { hash: self.hash, height: Some(self.height), - code: self.deliver_tx.code.value(), - raw_log: self.deliver_tx.log, + code: self.tx_result.code.value(), + raw_log: self.tx_result.log, }); } diff --git a/common/client-libs/validator-client/src/nyxd/fee/mod.rs b/common/client-libs/validator-client/src/nyxd/fee/mod.rs index ee30d1ffe5a..f062dfdb493 100644 --- a/common/client-libs/validator-client/src/nyxd/fee/mod.rs +++ b/common/client-libs/validator-client/src/nyxd/fee/mod.rs @@ -11,7 +11,7 @@ pub mod gas_price; pub type GasAdjustment = f32; -pub const DEFAULT_SIMULATED_GAS_MULTIPLIER: GasAdjustment = 1.3; +pub const DEFAULT_SIMULATED_GAS_MULTIPLIER: GasAdjustment = 1.5; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct AutoFeeGrant { diff --git a/common/client-libs/validator-client/src/nyxd/mod.rs b/common/client-libs/validator-client/src/nyxd/mod.rs index e7d66500529..c9c27370e26 100644 --- a/common/client-libs/validator-client/src/nyxd/mod.rs +++ b/common/client-libs/validator-client/src/nyxd/mod.rs @@ -34,7 +34,9 @@ pub use crate::nyxd::fee::Fee; pub use crate::rpc::TendermintRpcClient; pub use coin::Coin; pub use cosmrs::bank::MsgSend; -pub use cosmrs::tendermint::abci::{response::DeliverTx, Event, EventAttribute}; +pub use cosmrs::tendermint::abci::{ + response::DeliverTx, types::ExecTxResult, Event, EventAttribute, +}; pub use cosmrs::tendermint::block::Height; pub use cosmrs::tendermint::hash::{self, Algorithm, Hash}; pub use cosmrs::tendermint::validator::Info as TendermintValidatorInfo; diff --git a/common/client-libs/validator-client/src/rpc/mod.rs b/common/client-libs/validator-client/src/rpc/mod.rs index fd3f7991ba2..78f5476b48c 100644 --- a/common/client-libs/validator-client/src/rpc/mod.rs +++ b/common/client-libs/validator-client/src/rpc/mod.rs @@ -28,7 +28,7 @@ where U: TryInto, { HttpRpcClient::builder(url.try_into()?) - .compat_mode(CompatMode::V0_34) + .compat_mode(CompatMode::V0_37) .build() } diff --git a/common/client-libs/validator-client/src/rpc/reqwest.rs b/common/client-libs/validator-client/src/rpc/reqwest.rs index ffad7dd815d..973fb633768 100644 --- a/common/client-libs/validator-client/src/rpc/reqwest.rs +++ b/common/client-libs/validator-client/src/rpc/reqwest.rs @@ -36,7 +36,8 @@ pub struct ReqwestRpcClient { impl ReqwestRpcClient { pub fn new(url: Url) -> Self { ReqwestRpcClient { - compat: CompatMode::V0_34, + // after updating to nyxd 0.42 and thus updating to cometbft, the compat mode changed + compat: CompatMode::V0_37, inner: reqwest::Client::new(), url, } diff --git a/common/cosmwasm-smart-contracts/contracts-common/src/types.rs b/common/cosmwasm-smart-contracts/contracts-common/src/types.rs index 4dca6b173bd..218bd6ca505 100644 --- a/common/cosmwasm-smart-contracts/contracts-common/src/types.rs +++ b/common/cosmwasm-smart-contracts/contracts-common/src/types.rs @@ -3,6 +3,7 @@ use cosmwasm_schema::cw_serde; use cosmwasm_std::Decimal; +use cosmwasm_std::OverflowError; use cosmwasm_std::Uint128; use serde::de::Error; use serde::{Deserialize, Deserializer}; @@ -71,6 +72,10 @@ impl Percent { // we know the cast from u128 to u8 is a safe one since the internal value must be within 0 - 1 range truncate_decimal(hundred * self.0).u128() as u8 } + + pub fn checked_pow(&self, exp: u32) -> Result { + self.0.checked_pow(exp).map(Percent) + } } impl Display for Percent { diff --git a/common/dkg/benches/benchmarks.rs b/common/dkg/benches/benchmarks.rs index 483c6d20e99..2951a57a7c9 100644 --- a/common/dkg/benches/benchmarks.rs +++ b/common/dkg/benches/benchmarks.rs @@ -366,11 +366,7 @@ pub fn creating_proof_of_chunking_for_100_parties(c: &mut Criterion) { .map(|&node_index| polynomial.evaluate_at(&Scalar::from(node_index)).into()) .collect::>(); - let remote_share_key_pairs = shares - .iter() - .zip(receivers.values()) - .map(|(share, key)| (share, key)) - .collect::>(); + let remote_share_key_pairs = shares.iter().zip(receivers.values()).collect::>(); let ordered_public_keys = receivers.values().copied().collect::>(); let (ciphertexts, hazmat) = encrypt_shares(&remote_share_key_pairs, ¶ms, &mut rng); @@ -400,11 +396,7 @@ pub fn verifying_proof_of_chunking_for_100_parties(c: &mut Criterion) { .map(|&node_index| polynomial.evaluate_at(&Scalar::from(node_index)).into()) .collect::>(); - let remote_share_key_pairs = shares - .iter() - .zip(receivers.values()) - .map(|(share, key)| (share, key)) - .collect::>(); + let remote_share_key_pairs = shares.iter().zip(receivers.values()).collect::>(); let ordered_public_keys = receivers.values().copied().collect::>(); let (ciphertexts, hazmat) = encrypt_shares(&remote_share_key_pairs, ¶ms, &mut rng); @@ -436,11 +428,7 @@ pub fn creating_proof_of_secret_sharing_for_100_parties(c: &mut Criterion) { .map(|&node_index| polynomial.evaluate_at(&Scalar::from(node_index)).into()) .collect::>(); - let remote_share_key_pairs = shares - .iter() - .zip(receivers.values()) - .map(|(share, key)| (share, key)) - .collect::>(); + let remote_share_key_pairs = shares.iter().zip(receivers.values()).collect::>(); let (ciphertexts, hazmat) = encrypt_shares(&remote_share_key_pairs, ¶ms, &mut rng); @@ -478,11 +466,7 @@ pub fn verifying_proof_of_secret_sharing_for_100_parties(c: &mut Criterion) { .map(|&node_index| polynomial.evaluate_at(&Scalar::from(node_index)).into()) .collect::>(); - let remote_share_key_pairs = shares - .iter() - .zip(receivers.values()) - .map(|(share, key)| (share, key)) - .collect::>(); + let remote_share_key_pairs = shares.iter().zip(receivers.values()).collect::>(); let (ciphertexts, hazmat) = encrypt_shares(&remote_share_key_pairs, ¶ms, &mut rng); @@ -545,11 +529,7 @@ pub fn share_encryption_100(c: &mut Criterion) { .map(|&node_index| polynomial.evaluate_at(&Scalar::from(node_index)).into()) .collect::>(); - let remote_share_key_pairs = shares - .iter() - .zip(receivers.values()) - .map(|(share, key)| (share, key)) - .collect::>(); + let remote_share_key_pairs = shares.iter().zip(receivers.values()).collect::>(); c.bench_function("100 shares encryption", |b| { b.iter(|| black_box(encrypt_shares(&remote_share_key_pairs, ¶ms, &mut rng))) diff --git a/common/ip-packet-requests/Cargo.toml b/common/ip-packet-requests/Cargo.toml index d77f0f93962..2a92715f822 100644 --- a/common/ip-packet-requests/Cargo.toml +++ b/common/ip-packet-requests/Cargo.toml @@ -14,4 +14,6 @@ license.workspace = true bincode = "1.3.3" bytes = "1.5.0" nym-sphinx = { path = "../nymsphinx" } +rand = "0.8.5" serde = { workspace = true, features = ["derive"] } +thiserror = { workspace = true } diff --git a/common/ip-packet-requests/src/lib.rs b/common/ip-packet-requests/src/lib.rs index ef7672bf170..290deec697b 100644 --- a/common/ip-packet-requests/src/lib.rs +++ b/common/ip-packet-requests/src/lib.rs @@ -1,35 +1,308 @@ -#[derive(serde::Serialize, serde::Deserialize)] -pub struct TaggedIpPacket { - pub packet: bytes::Bytes, - pub return_address: nym_sphinx::addressing::clients::Recipient, - pub return_mix_hops: Option, - // pub return_mix_delays: Option, -} - -impl TaggedIpPacket { - pub fn new( - packet: bytes::Bytes, - return_address: nym_sphinx::addressing::clients::Recipient, - return_mix_hops: Option, - ) -> Self { - TaggedIpPacket { - packet, - return_address, - return_mix_hops, +use std::net::IpAddr; + +use nym_sphinx::addressing::clients::Recipient; +use serde::{Deserialize, Serialize}; + +pub const CURRENT_VERSION: u8 = 1; + +fn generate_random() -> u64 { + use rand::RngCore; + let mut rng = rand::rngs::OsRng; + rng.next_u64() +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct IpPacketRequest { + pub version: u8, + pub data: IpPacketRequestData, +} + +impl IpPacketRequest { + pub fn new_static_connect_request( + ip: IpAddr, + reply_to: Recipient, + reply_to_hops: Option, + reply_to_avg_mix_delays: Option, + ) -> (Self, u64) { + let request_id = generate_random(); + ( + Self { + version: CURRENT_VERSION, + data: IpPacketRequestData::StaticConnect(StaticConnectRequest { + request_id, + ip, + reply_to, + reply_to_hops, + reply_to_avg_mix_delays, + }), + }, + request_id, + ) + } + + pub fn new_dynamic_connect_request( + reply_to: Recipient, + reply_to_hops: Option, + reply_to_avg_mix_delays: Option, + ) -> (Self, u64) { + let request_id = generate_random(); + ( + Self { + version: CURRENT_VERSION, + data: IpPacketRequestData::DynamicConnect(DynamicConnectRequest { + request_id, + reply_to, + reply_to_hops, + reply_to_avg_mix_delays, + }), + }, + request_id, + ) + } + + pub fn new_ip_packet(ip_packet: bytes::Bytes) -> Self { + Self { + version: CURRENT_VERSION, + data: IpPacketRequestData::Data(DataRequest { ip_packet }), + } + } + + pub fn id(&self) -> Option { + match &self.data { + IpPacketRequestData::StaticConnect(request) => Some(request.request_id), + IpPacketRequestData::DynamicConnect(request) => Some(request.request_id), + IpPacketRequestData::Data(_) => None, } } + pub fn recipient(&self) -> Option<&Recipient> { + match &self.data { + IpPacketRequestData::StaticConnect(request) => Some(&request.reply_to), + IpPacketRequestData::DynamicConnect(request) => Some(&request.reply_to), + IpPacketRequestData::Data(_) => None, + } + } + + pub fn to_bytes(&self) -> Result, bincode::Error> { + use bincode::Options; + make_bincode_serializer().serialize(self) + } + pub fn from_reconstructed_message( message: &nym_sphinx::receiver::ReconstructedMessage, ) -> Result { use bincode::Options; make_bincode_serializer().deserialize(&message.message) } +} + +#[allow(clippy::large_enum_variant)] +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub enum IpPacketRequestData { + StaticConnect(StaticConnectRequest), + DynamicConnect(DynamicConnectRequest), + Data(DataRequest), +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct StaticConnectRequest { + pub request_id: u64, + pub ip: IpAddr, + pub reply_to: Recipient, + pub reply_to_hops: Option, + pub reply_to_avg_mix_delays: Option, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct DynamicConnectRequest { + pub request_id: u64, + pub reply_to: Recipient, + pub reply_to_hops: Option, + pub reply_to_avg_mix_delays: Option, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct DataRequest { + pub ip_packet: bytes::Bytes, +} + +// --- + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct IpPacketResponse { + pub version: u8, + pub data: IpPacketResponseData, +} + +impl IpPacketResponse { + pub fn new_static_connect_success(request_id: u64, reply_to: Recipient) -> Self { + Self { + version: CURRENT_VERSION, + data: IpPacketResponseData::StaticConnect(StaticConnectResponse { + request_id, + reply_to, + reply: StaticConnectResponseReply::Success, + }), + } + } + + pub fn new_static_connect_failure( + request_id: u64, + reply_to: Recipient, + reason: StaticConnectFailureReason, + ) -> Self { + Self { + version: CURRENT_VERSION, + data: IpPacketResponseData::StaticConnect(StaticConnectResponse { + request_id, + reply_to, + reply: StaticConnectResponseReply::Failure(reason), + }), + } + } + + pub fn new_dynamic_connect_success(request_id: u64, reply_to: Recipient, ip: IpAddr) -> Self { + Self { + version: CURRENT_VERSION, + data: IpPacketResponseData::DynamicConnect(DynamicConnectResponse { + request_id, + reply_to, + reply: DynamicConnectResponseReply::Success(DynamicConnectSuccess { ip }), + }), + } + } + + pub fn new_dynamic_connect_failure( + request_id: u64, + reply_to: Recipient, + reason: DynamicConnectFailureReason, + ) -> Self { + Self { + version: CURRENT_VERSION, + data: IpPacketResponseData::DynamicConnect(DynamicConnectResponse { + request_id, + reply_to, + reply: DynamicConnectResponseReply::Failure(reason), + }), + } + } + + pub fn new_ip_packet(ip_packet: bytes::Bytes) -> Self { + Self { + version: CURRENT_VERSION, + data: IpPacketResponseData::Data(DataResponse { ip_packet }), + } + } + + pub fn id(&self) -> Option { + match &self.data { + IpPacketResponseData::StaticConnect(response) => Some(response.request_id), + IpPacketResponseData::DynamicConnect(response) => Some(response.request_id), + IpPacketResponseData::Data(_) => None, + } + } + + pub fn recipient(&self) -> Option<&Recipient> { + match &self.data { + IpPacketResponseData::StaticConnect(response) => Some(&response.reply_to), + IpPacketResponseData::DynamicConnect(response) => Some(&response.reply_to), + IpPacketResponseData::Data(_) => None, + } + } pub fn to_bytes(&self) -> Result, bincode::Error> { use bincode::Options; make_bincode_serializer().serialize(self) } + + pub fn from_reconstructed_message( + message: &nym_sphinx::receiver::ReconstructedMessage, + ) -> Result { + use bincode::Options; + make_bincode_serializer().deserialize(&message.message) + } +} + +#[allow(clippy::large_enum_variant)] +#[derive(Clone, Debug, Serialize, Deserialize)] +pub enum IpPacketResponseData { + StaticConnect(StaticConnectResponse), + DynamicConnect(DynamicConnectResponse), + Data(DataResponse), +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct StaticConnectResponse { + pub request_id: u64, + pub reply_to: Recipient, + pub reply: StaticConnectResponseReply, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub enum StaticConnectResponseReply { + Success, + Failure(StaticConnectFailureReason), +} + +impl StaticConnectResponseReply { + pub fn is_success(&self) -> bool { + match self { + StaticConnectResponseReply::Success => true, + StaticConnectResponseReply::Failure(_) => false, + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize, thiserror::Error)] +pub enum StaticConnectFailureReason { + #[error("requested ip address is already in use")] + RequestedIpAlreadyInUse, + #[error("requested nym-address is already in use")] + RequestedNymAddressAlreadyInUse, + #[error("{0}")] + Other(String), +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct DynamicConnectResponse { + pub request_id: u64, + pub reply_to: Recipient, + pub reply: DynamicConnectResponseReply, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub enum DynamicConnectResponseReply { + Success(DynamicConnectSuccess), + Failure(DynamicConnectFailureReason), +} + +impl DynamicConnectResponseReply { + pub fn is_success(&self) -> bool { + match self { + DynamicConnectResponseReply::Success(_) => true, + DynamicConnectResponseReply::Failure(_) => false, + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct DynamicConnectSuccess { + pub ip: IpAddr, +} + +#[derive(Clone, Debug, Serialize, Deserialize, thiserror::Error)] +pub enum DynamicConnectFailureReason { + #[error("requested nym-address is already in use")] + RequestedNymAddressAlreadyInUse, + #[error("no available ip address")] + NoAvailableIp, + #[error("{0}")] + Other(String), +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct DataResponse { + pub ip_packet: bytes::Bytes, } fn make_bincode_serializer() -> impl bincode::Options { @@ -38,3 +311,63 @@ fn make_bincode_serializer() -> impl bincode::Options { .with_big_endian() .with_varint_encoding() } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn check_size_of_request() { + let connect = IpPacketRequest { + version: 4, + data: IpPacketRequestData::StaticConnect( + StaticConnectRequest { + request_id: 123, + ip: IpAddr::from([10, 0, 0, 1]), + reply_to: Recipient::try_from_base58_string("D1rrpsysCGCYXy9saP8y3kmNpGtJZUXN9SvFoUcqAsM9.9Ssso1ea5NfkbMASdiseDSjTN1fSWda5SgEVjdSN4CvV@GJqd3ZxpXWSNxTfx7B1pPtswpetH4LnJdFeLeuY5KUuN").unwrap(), + reply_to_hops: None, + reply_to_avg_mix_delays: None, + }, + ) + }; + assert_eq!(connect.to_bytes().unwrap().len(), 107); + } + + #[test] + fn check_size_of_data() { + let data = IpPacketRequest { + version: 4, + data: IpPacketRequestData::Data(DataRequest { + ip_packet: bytes::Bytes::from(vec![1u8; 32]), + }), + }; + assert_eq!(data.to_bytes().unwrap().len(), 35); + } + + #[test] + fn serialize_and_deserialize_data_request() { + let data = IpPacketRequest { + version: 4, + data: IpPacketRequestData::Data(DataRequest { + ip_packet: bytes::Bytes::from(vec![1, 2, 4, 2, 5]), + }), + }; + + let serialized = data.to_bytes().unwrap(); + let deserialized = IpPacketRequest::from_reconstructed_message( + &nym_sphinx::receiver::ReconstructedMessage { + message: serialized, + sender_tag: None, + }, + ) + .unwrap(); + + assert_eq!(deserialized.version, 4); + assert_eq!( + deserialized.data, + IpPacketRequestData::Data(DataRequest { + ip_packet: bytes::Bytes::from(vec![1, 2, 4, 2, 5]), + }) + ); + } +} diff --git a/common/network-defaults/src/lib.rs b/common/network-defaults/src/lib.rs index b45b5483e9d..bcf02d1f028 100644 --- a/common/network-defaults/src/lib.rs +++ b/common/network-defaults/src/lib.rs @@ -476,3 +476,11 @@ pub const DEFAULT_NYM_NODE_HTTP_PORT: u16 = 8080; pub const TOTAL_SUPPLY: u128 = 1_000_000_000_000_000; pub const DEFAULT_PROFIT_MARGIN: u8 = 10; + +// WIREGUARD +pub const WG_PORT: u16 = 51822; + +// The interface used to route traffic +pub const WG_TUN_BASE_NAME: &str = "nymwg"; +pub const WG_TUN_DEVICE_ADDRESS: &str = "10.1.0.1"; +pub const WG_TUN_DEVICE_NETMASK: &str = "255.255.255.0"; diff --git a/common/nymcoconut/benches/benchmarks.rs b/common/nymcoconut/benches/benchmarks.rs index 74149c15c96..6627b437e14 100644 --- a/common/nymcoconut/benches/benchmarks.rs +++ b/common/nymcoconut/benches/benchmarks.rs @@ -6,9 +6,10 @@ use criterion::{criterion_group, criterion_main, Criterion}; use ff::Field; use group::{Curve, Group}; use nym_coconut::{ - aggregate_signature_shares, aggregate_verification_keys, blind_sign, elgamal_keygen, - prepare_blind_sign, prove_bandwidth_credential, setup, ttp_keygen, verify_credential, - Attribute, BlindedSignature, Parameters, Signature, SignatureShare, VerificationKey, + aggregate_signature_shares, aggregate_verification_keys, blind_sign, prepare_blind_sign, + prove_bandwidth_credential, setup, ttp_keygen, verify_credential, + verify_partial_blind_signature, Attribute, BlindedSignature, Parameters, Signature, + SignatureShare, VerificationKey, }; use rand::seq::SliceRandom; use std::ops::Neg; @@ -175,8 +176,6 @@ fn bench_coconut(c: &mut Criterion) { let binding_number = params.random_scalar(); let private_attributes = vec![serial_number, binding_number]; - let _elgamal_keypair = elgamal_keygen(¶ms); - // The prepare blind sign is performed by the user let (pedersen_commitments_openings, blind_sign_request) = prepare_blind_sign(¶ms, &private_attributes, &public_attributes).unwrap(); @@ -242,6 +241,29 @@ fn bench_coconut(c: &mut Criterion) { .map(|keypair| keypair.verification_key()) .collect(); + // verify a random partial blind signature + let rand_idx = 1; + let random_blind_signature = blinded_signatures.get(rand_idx).unwrap(); + let partial_verification_key = verification_keys.get(rand_idx).unwrap(); + + group.bench_function( + &format!( + "verify_partial_blind_signature_{}_private_attributes_{}_public_attributes", + case.num_private_attrs, case.num_public_attrs + ), + |b| { + b.iter(|| { + verify_partial_blind_signature( + ¶ms, + &blind_sign_request, + &public_attributes, + random_blind_signature, + partial_verification_key, + ) + }) + }, + ); + // Lets bench worse case, ie aggregating all let indices: Vec = (1..=case.num_authorities).collect(); // aggregate verification keys diff --git a/common/nymcoconut/src/lib.rs b/common/nymcoconut/src/lib.rs index a98b546fc11..821b1b3b29a 100644 --- a/common/nymcoconut/src/lib.rs +++ b/common/nymcoconut/src/lib.rs @@ -14,6 +14,7 @@ pub use scheme::aggregation::aggregate_signature_shares; pub use scheme::aggregation::aggregate_verification_keys; pub use scheme::issuance::blind_sign; pub use scheme::issuance::prepare_blind_sign; +pub use scheme::issuance::verify_partial_blind_signature; pub use scheme::issuance::BlindSignRequest; pub use scheme::keygen::ttp_keygen; pub use scheme::keygen::KeyPair; diff --git a/common/nymcoconut/src/scheme/issuance.rs b/common/nymcoconut/src/scheme/issuance.rs index 710fc41df95..1109dfe8909 100644 --- a/common/nymcoconut/src/scheme/issuance.rs +++ b/common/nymcoconut/src/scheme/issuance.rs @@ -3,12 +3,14 @@ use std::convert::TryFrom; use std::convert::TryInto; +use std::ops::Neg; -use bls12_381::{G1Affine, G1Projective, Scalar}; -use group::{Curve, GroupEncoding}; +use bls12_381::{multi_miller_loop, G1Affine, G1Projective, G2Prepared, Scalar}; +use group::{Curve, Group, GroupEncoding}; use crate::error::{CoconutError, Result}; use crate::proofs::ProofCmCs; +use crate::scheme::keygen::VerificationKey; use crate::scheme::setup::Parameters; use crate::scheme::BlindedSignature; use crate::scheme::SecretKey; @@ -318,6 +320,97 @@ pub fn blind_sign( Ok(BlindedSignature(h, sig)) } +/// Verifies a partial blind signature using the provided parameters and validator's verification key. +/// +/// # Arguments +/// +/// * `params` - A reference to the cryptographic parameters. +/// * `blind_sign_request` - A reference to the blind signature request signed by the client. +/// * `public_attributes` - A reference to the public attributes included in the client's request. +/// * `blind_sig` - A reference to the issued partial blinded signature to be verified. +/// * `partial_verification_key` - A reference to the validator's partial verification key. +/// +/// # Returns +/// +/// A boolean indicating whether the partial blind signature is valid (`true`) or not (`false`). +/// +/// # Remarks +/// +/// This function verifies the correctness and validity of a partial blind signature using +/// the provided cryptographic parameters, blind signature request, blinded signature, +/// and partial verification key. +/// It calculates pairings based on the provided values and checks whether the partial blind signature +/// is consistent with the verification key and commitments in the blind signature request. +/// The function returns `true` if the partial blind signature is valid, and `false` otherwise. +pub fn verify_partial_blind_signature( + params: &Parameters, + blind_sign_request: &BlindSignRequest, + public_attributes: &[Attribute], + blind_sig: &BlindedSignature, + partial_verification_key: &VerificationKey, +) -> bool { + let num_private_attributes = blind_sign_request.private_attributes_commitments.len(); + if num_private_attributes + public_attributes.len() > partial_verification_key.beta_g2.len() { + return false; + } + + // TODO: we're losing some memory here due to extra allocation, + // but worst-case scenario (given SANE amount of attributes), it's just few kb at most + let c_neg = blind_sig.1.to_affine().neg(); + let g2_prep = params.prepared_miller_g2(); + + let mut terms = vec![ + // (c^{-1}, g2) + (c_neg, g2_prep.clone()), + // (s, alpha) + ( + blind_sig.0.to_affine(), + G2Prepared::from(partial_verification_key.alpha.to_affine()), + ), + ]; + + // for each private attribute, add (cm_i, beta_i) to the miller terms + for (private_attr_commit, beta_g2) in blind_sign_request + .private_attributes_commitments + .iter() + .zip(&partial_verification_key.beta_g2) + { + // (cm_i, beta_i) + terms.push(( + private_attr_commit.to_affine(), + G2Prepared::from(beta_g2.to_affine()), + )) + } + + // for each public attribute, add (s^pub_j, beta_{priv + j}) to the miller terms + for (pub_attr, beta_g2) in public_attributes.iter().zip( + partial_verification_key + .beta_g2 + .iter() + .skip(num_private_attributes), + ) { + // (s^pub_j, beta_j) + terms.push(( + (blind_sig.0 * pub_attr).to_affine(), + G2Prepared::from(beta_g2.to_affine()), + )) + } + + // get the references to all the terms to get the arguments the miller loop expects + #[allow(clippy::map_identity)] + let terms_refs = terms.iter().map(|(g1, g2)| (g1, g2)).collect::>(); + + // since checking whether e(a, b) == e(c, d) + // is equivalent to checking e(a, b) • e(c, d)^{-1} == id + // and thus to e(a, b) • e(c^{-1}, d) == id + // + // compute e(c^1, g2) • e(s, alpha) • e(cm_0, beta_0) • e(cm_i, beta_i) • (s^pub_0, beta_{i+1}) (s^pub_j, beta_{i + j}) + multi_miller_loop(&terms_refs) + .final_exponentiation() + .is_identity() + .into() +} + #[cfg(test)] pub fn sign( params: &mut Parameters, @@ -354,6 +447,7 @@ pub fn sign( #[cfg(test)] mod tests { use super::*; + use crate::scheme::keygen::keygen; #[test] fn blind_sign_request_bytes_roundtrip() { @@ -385,4 +479,81 @@ mod tests { lambda ); } + + #[test] + fn successful_verify_partial_blind_signature() { + let params = Parameters::new(4).unwrap(); + let private_attributes = params.n_random_scalars(2); + let public_attributes = params.n_random_scalars(2); + + let (_commitments_openings, request) = + prepare_blind_sign(¶ms, &private_attributes, &public_attributes).unwrap(); + + let validator_keypair = keygen(¶ms); + let blind_sig = blind_sign( + ¶ms, + &validator_keypair.secret_key(), + &request, + &public_attributes, + ) + .unwrap(); + + assert!(verify_partial_blind_signature( + ¶ms, + &request, + &public_attributes, + &blind_sig, + &validator_keypair.verification_key() + )); + } + + #[test] + fn successful_verify_partial_blind_signature_no_public_attributes() { + let params = Parameters::new(4).unwrap(); + let private_attributes = params.n_random_scalars(2); + + let (_commitments_openings, request) = + prepare_blind_sign(¶ms, &private_attributes, &[]).unwrap(); + + let validator_keypair = keygen(¶ms); + let blind_sig = + blind_sign(¶ms, &validator_keypair.secret_key(), &request, &[]).unwrap(); + + assert!(verify_partial_blind_signature( + ¶ms, + &request, + &[], + &blind_sig, + &validator_keypair.verification_key() + )); + } + + #[test] + fn fail_verify_partial_blind_signature_with_wrong_key() { + let params = Parameters::new(4).unwrap(); + let private_attributes = params.n_random_scalars(2); + let public_attributes = params.n_random_scalars(2); + + let (_commitments_openings, request) = + prepare_blind_sign(¶ms, &private_attributes, &public_attributes).unwrap(); + + let validator_keypair = keygen(¶ms); + let validator2_keypair = keygen(¶ms); + let blind_sig = blind_sign( + ¶ms, + &validator_keypair.secret_key(), + &request, + &public_attributes, + ) + .unwrap(); + + // this assertion should fail, as we try to verify with a wrong validator key + assert!(!verify_partial_blind_signature( + ¶ms, + &request, + &public_attributes, + &blind_sig, + &validator2_keypair.verification_key() + ),); + } } diff --git a/common/tun/Cargo.toml b/common/tun/Cargo.toml index 07df2a4bed5..2cde7db2803 100644 --- a/common/tun/Cargo.toml +++ b/common/tun/Cargo.toml @@ -18,7 +18,4 @@ log.workspace = true nym-wireguard-types = { path = "../wireguard-types", optional = true } [target.'cfg(target_os = "linux")'.dependencies] -tokio-tun = "0.9.0" - -[features] -wireguard = ["nym-wireguard-types"] +tokio-tun = "0.11.2" diff --git a/common/tun/src/linux/tun_device.rs b/common/tun/src/linux/tun_device.rs index 84a62a1220c..20f514f4a93 100644 --- a/common/tun/src/linux/tun_device.rs +++ b/common/tun/src/linux/tun_device.rs @@ -15,14 +15,6 @@ use crate::tun_task_channel::{ TunTaskResponseSendError, TunTaskResponseTx, TunTaskRx, TunTaskTx, }; -#[cfg(feature = "wireguard")] -use nym_wireguard_types::tun_common::{ - active_peers::{PeerEventSenderError, PeersByIp}, - event::Event, -}; - -#[cfg(feature = "wireguard")] -const MUTEX_LOCK_TIMEOUT_MS: u64 = 200; const TUN_WRITE_TIMEOUT_MS: u64 = 1000; #[derive(thiserror::Error, Debug)] @@ -33,13 +25,6 @@ pub enum TunDeviceError { #[error("error writing to tun device: {source}")] TunWriteError { source: std::io::Error }, - #[cfg(feature = "wireguard")] - #[error("failed forwarding packet to peer: {source}")] - ForwardToPeerFailed { - #[from] - source: PeerEventSenderError, - }, - #[error("failed to forward responding packet with tag: {source}")] ForwardNatResponseFailed { #[from] @@ -92,13 +77,12 @@ pub struct TunDevice { } pub enum RoutingMode { - // The routing table, as how wireguard does it - #[cfg(feature = "wireguard")] - AllowedIps(AllowedIpsInner), - // This is an alternative to the routing table, where we just match outgoing source IP with // incoming destination IP. Nat(NatInner), + + // Just forward without checking anything + Passthrough, } impl RoutingMode { @@ -108,26 +92,8 @@ impl RoutingMode { }) } - #[cfg(feature = "wireguard")] - pub fn new_allowed_ips(peers_by_ip: std::sync::Arc>) -> Self { - RoutingMode::AllowedIps(AllowedIpsInner { peers_by_ip }) - } -} - -#[cfg(feature = "wireguard")] -pub struct AllowedIpsInner { - peers_by_ip: std::sync::Arc>, -} - -#[cfg(feature = "wireguard")] -impl AllowedIpsInner { - async fn lock(&self) -> Result, TunDeviceError> { - timeout( - Duration::from_millis(MUTEX_LOCK_TIMEOUT_MS), - self.peers_by_ip.as_ref().lock(), - ) - .await - .map_err(|_| TunDeviceError::FailedToLockPeer) + pub fn new_passthrough() -> Self { + RoutingMode::Passthrough } } @@ -146,15 +112,7 @@ impl TunDevice { routing_mode: RoutingMode, config: TunDeviceConfig, ) -> (Self, TunTaskTx, TunTaskResponseRx) { - let TunDeviceConfig { - base_name, - ip, - netmask, - } = config; - let name = format!("{base_name}%d"); - - let tun = setup_tokio_tun_device(&name, ip, netmask); - log::info!("Created TUN device: {}", tun.name()); + let tun = Self::new_device_only(config); // Channels to communicate with the other tasks let (tun_task_tx, tun_task_rx) = tun_task_channel(); @@ -170,6 +128,19 @@ impl TunDevice { (tun_device, tun_task_tx, tun_task_response_rx) } + pub fn new_device_only(config: TunDeviceConfig) -> tokio_tun::Tun { + let TunDeviceConfig { + base_name, + ip, + netmask, + } = config; + let name = format!("{base_name}%d"); + + let tun = setup_tokio_tun_device(&name, ip, netmask); + log::info!("Created TUN device: {}", tun.name()); + tun + } + // Send outbound packets out on the wild internet async fn handle_tun_write(&mut self, data: TunTaskPayload) -> Result<(), TunDeviceError> { let (tag, packet) = data; @@ -180,7 +151,6 @@ impl TunDevice { ); // TODO: expire old entries - #[allow(irrefutable_let_patterns)] if let RoutingMode::Nat(nat_table) = &mut self.routing_mode { nat_table.nat_table.insert(src_addr, tag); } @@ -198,26 +168,13 @@ impl TunDevice { async fn handle_tun_read(&self, packet: &[u8]) -> Result<(), TunDeviceError> { let ParsedAddresses { src_addr, dst_addr } = parse_src_dst_address(packet)?; log::debug!( - "iface: read Packet({src_addr} -> {dst_addr}, {} bytes)", + "iface: read Packet({dst_addr} <- {src_addr}, {} bytes)", packet.len(), ); // Route packet to the correct peer. match self.routing_mode { - // This is how wireguard does it, by consulting the AllowedIPs table. - #[cfg(feature = "wireguard")] - RoutingMode::AllowedIps(ref peers_by_ip) => { - let peers = peers_by_ip.lock().await?; - if let Some(peer_tx) = peers.longest_match(dst_addr).map(|(_, tx)| tx) { - log::debug!("Forward packet to wg tunnel"); - return peer_tx - .send(Event::Ip(packet.to_vec().into())) - .await - .map_err(|err| err.into()); - } - } - // But we can also do it by consulting the NAT table. RoutingMode::Nat(ref nat_table) => { if let Some(tag) = nat_table.nat_table.get(&dst_addr) { @@ -228,6 +185,15 @@ impl TunDevice { .map_err(|err| err.into()); } } + + RoutingMode::Passthrough => { + // TODO: skip the parsing at the top of the function + log::debug!("Forward packet without checking anything"); + return self + .tun_task_response_tx + .try_send((0, packet.to_vec())) + .map_err(|err| err.into()); + } } log::info!("No peer found, packet dropped"); @@ -255,7 +221,7 @@ impl TunDevice { // Writing to the TUN device Some(data) = self.tun_task_rx.recv() => { if let Err(err) = self.handle_tun_write(data).await { - log::error!("ifcae: handle_tun_write failed: {err}"); + log::error!("iface: handle_tun_write failed: {err}"); } } } diff --git a/common/wireguard-types/Cargo.toml b/common/wireguard-types/Cargo.toml index e8825688cf0..07d440ad6ba 100644 --- a/common/wireguard-types/Cargo.toml +++ b/common/wireguard-types/Cargo.toml @@ -12,14 +12,10 @@ license.workspace = true [dependencies] base64 = { workspace = true } -bytes = "1.5.0" dashmap = { workspace = true } -ip_network = "0.4.1" -ip_network_table = "0.2.0" log = { workspace = true } serde = { workspace = true, features = ["derive"] } thiserror = { workspace = true } -tokio = { workspace = true, features = ["sync", "time"] } nym-crypto = { path = "../crypto", features = ["asymmetric"] } @@ -33,13 +29,7 @@ sha2 = { version = "0.10.8", optional = true } utoipa = { workspace = true, optional = true } serde_json = { workspace = true, optional = true } -# target-specific dependencies -[target."cfg(not(target_arch = \"wasm32\"))".dependencies.boringtun] -workspace = true - -[target."cfg(target_arch = \"wasm32\")".dependencies.x25519-dalek] -version = "2.0.0" - +x25519-dalek = { version = "2.0.0", features = ["static_secrets"] } [dev-dependencies] rand = "0.7.3" diff --git a/common/wireguard-types/src/lib.rs b/common/wireguard-types/src/lib.rs index 605b30ba82e..acb3366f86a 100644 --- a/common/wireguard-types/src/lib.rs +++ b/common/wireguard-types/src/lib.rs @@ -4,8 +4,6 @@ pub mod error; pub mod public_key; pub mod registration; -#[cfg(not(target_arch = "wasm32"))] -pub mod tun_common; pub use error::Error; pub use public_key::PeerPublicKey; @@ -15,5 +13,3 @@ pub use registration::{ #[cfg(feature = "verify")] pub use registration::HmacSha256; - -pub const WG_PORT: u16 = 51822; diff --git a/common/wireguard-types/src/public_key.rs b/common/wireguard-types/src/public_key.rs index 7843f35c4c1..b6bad8ec80a 100644 --- a/common/wireguard-types/src/public_key.rs +++ b/common/wireguard-types/src/public_key.rs @@ -10,20 +10,14 @@ use std::hash::{Hash, Hasher}; use std::ops::Deref; use std::str::FromStr; -// underneath the same library is being used, i.e. x25519-dalek 2.0, -// which is being reexported by boringtun but wasm hates internals of boringtun -#[cfg(target_arch = "wasm32")] -use x25519_dalek::PublicKey as BoringtunPublicKey; - -#[cfg(not(target_arch = "wasm32"))] -use boringtun::x25519::PublicKey as BoringtunPublicKey; +use x25519_dalek::PublicKey; #[derive(Debug, Clone, Copy, Eq, PartialEq)] -pub struct PeerPublicKey(BoringtunPublicKey); +pub struct PeerPublicKey(PublicKey); impl PeerPublicKey { #[allow(dead_code)] - pub fn new(key: BoringtunPublicKey) -> Self { + pub fn new(key: PublicKey) -> Self { PeerPublicKey(key) } @@ -45,7 +39,7 @@ impl Hash for PeerPublicKey { } impl Deref for PeerPublicKey { - type Target = BoringtunPublicKey; + type Target = PublicKey; fn deref(&self) -> &Self::Target { &self.0 @@ -71,7 +65,7 @@ impl FromStr for PeerPublicKey { })?; }; - Ok(PeerPublicKey(BoringtunPublicKey::from(key_arr))) + Ok(PeerPublicKey(PublicKey::from(key_arr))) } } diff --git a/common/wireguard-types/src/registration.rs b/common/wireguard-types/src/registration.rs index ceabc625c33..e698609ab7b 100644 --- a/common/wireguard-types/src/registration.rs +++ b/common/wireguard-types/src/registration.rs @@ -93,10 +93,10 @@ impl GatewayClient { ) -> Self { // convert from 1.0 x25519-dalek private key into 2.0 x25519-dalek #[allow(clippy::expect_used)] - let static_secret = boringtun::x25519::StaticSecret::from(local_secret.to_bytes()); - let local_public: boringtun::x25519::PublicKey = (&static_secret).into(); + let static_secret = x25519_dalek::StaticSecret::from(local_secret.to_bytes()); + let local_public: x25519_dalek::PublicKey = (&static_secret).into(); - let remote_public = boringtun::x25519::PublicKey::from(remote_public.to_bytes()); + let remote_public = x25519_dalek::PublicKey::from(remote_public.to_bytes()); let dh = static_secret.diffie_hellman(&remote_public); @@ -122,7 +122,7 @@ impl GatewayClient { pub fn verify(&self, gateway_key: &PrivateKey, nonce: u64) -> Result<(), Error> { // convert from 1.0 x25519-dalek private key into 2.0 x25519-dalek #[allow(clippy::expect_used)] - let static_secret = boringtun::x25519::StaticSecret::from(gateway_key.to_bytes()); + let static_secret = x25519_dalek::StaticSecret::from(gateway_key.to_bytes()); let dh = static_secret.diffie_hellman(&self.pub_key); diff --git a/common/wireguard-types/src/tun_common/active_peers.rs b/common/wireguard-types/src/tun_common/active_peers.rs deleted file mode 100644 index 6fc82298e5b..00000000000 --- a/common/wireguard-types/src/tun_common/active_peers.rs +++ /dev/null @@ -1,92 +0,0 @@ -use std::{net::SocketAddr, time::Duration}; - -use boringtun::x25519; -use dashmap::{ - mapref::one::{Ref, RefMut}, - DashMap, -}; -use tokio::sync::mpsc::{self}; - -use crate::tun_common::{event::Event, network_table::NetworkTable}; - -// Registered peers -pub type PeersByIp = NetworkTable; - -// Channels that are used to communicate with the various tunnels -#[derive(Clone)] -pub struct PeerEventSender(mpsc::Sender); -pub struct PeerEventReceiver(mpsc::Receiver); - -#[derive(thiserror::Error, Debug)] -pub enum PeerEventSenderError { - #[error("send failed: timeout: {source}")] - SendTimeoutError { - #[from] - source: mpsc::error::SendTimeoutError, - }, - - #[error("send failed: {source}")] - SendError { - #[from] - source: mpsc::error::SendError, - }, -} - -impl PeerEventSender { - pub async fn send(&self, event: Event) -> Result<(), PeerEventSenderError> { - Ok(self - .0 - .send_timeout(event, Duration::from_millis(1000)) - .await?) - } -} - -impl PeerEventReceiver { - pub async fn recv(&mut self) -> Option { - self.0.recv().await - } -} - -pub fn peer_event_channel() -> (PeerEventSender, PeerEventReceiver) { - let (tx, rx) = mpsc::channel(16); - (PeerEventSender(tx), PeerEventReceiver(rx)) -} - -pub(crate) type PeersByKey = DashMap; -pub(crate) type PeersByAddr = DashMap; - -#[derive(Default)] -pub struct ActivePeers { - active_peers: PeersByKey, - active_peers_by_addr: PeersByAddr, -} - -impl ActivePeers { - pub fn remove(&self, public_key: &x25519::PublicKey) { - log::info!("Removing peer: {public_key:?}"); - self.active_peers.remove(public_key); - log::warn!("TODO: remove from peers_by_ip?"); - log::warn!("TODO: remove from peers_by_addr"); - } - - pub fn insert( - &self, - public_key: x25519::PublicKey, - addr: SocketAddr, - peer_tx: PeerEventSender, - ) { - self.active_peers.insert(public_key, peer_tx.clone()); - self.active_peers_by_addr.insert(addr, peer_tx); - } - - pub fn get_by_key_mut( - &self, - public_key: &x25519::PublicKey, - ) -> Option> { - self.active_peers.get_mut(public_key) - } - - pub fn get_by_addr(&self, addr: &SocketAddr) -> Option> { - self.active_peers_by_addr.get(addr) - } -} diff --git a/common/wireguard-types/src/tun_common/event.rs b/common/wireguard-types/src/tun_common/event.rs deleted file mode 100644 index 226d20bafaa..00000000000 --- a/common/wireguard-types/src/tun_common/event.rs +++ /dev/null @@ -1,34 +0,0 @@ -use std::fmt::{Display, Formatter}; - -use bytes::Bytes; - -#[allow(unused)] -#[derive(Debug)] -pub enum Event { - /// IP packet received from the WireGuard tunnel that should be passed through to the - /// corresponding virtual device/internet. - Wg(Bytes), - /// IP packet received from the WireGuard tunnel that was verified as part of the handshake. - WgVerified(Bytes), - /// IP packet to be sent through the WireGuard tunnel as crafted by the virtual device. - Ip(Bytes), -} - -impl Display for Event { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - match self { - Event::Wg(data) => { - let size = data.len(); - write!(f, "Wg{{ size={size} }}") - } - Event::WgVerified(data) => { - let size = data.len(); - write!(f, "WgVerified{{ size={size} }}") - } - Event::Ip(data) => { - let size = data.len(); - write!(f, "Ip{{ size={size} }}") - } - } - } -} diff --git a/common/wireguard-types/src/tun_common/mod.rs b/common/wireguard-types/src/tun_common/mod.rs deleted file mode 100644 index d0536cbeb11..00000000000 --- a/common/wireguard-types/src/tun_common/mod.rs +++ /dev/null @@ -1,3 +0,0 @@ -pub mod active_peers; -pub mod event; -pub mod network_table; diff --git a/common/wireguard-types/src/tun_common/network_table.rs b/common/wireguard-types/src/tun_common/network_table.rs deleted file mode 100644 index be2284bc1c7..00000000000 --- a/common/wireguard-types/src/tun_common/network_table.rs +++ /dev/null @@ -1,25 +0,0 @@ -use std::net::IpAddr; - -use ip_network::IpNetwork; -use ip_network_table::IpNetworkTable; - -#[derive(Default)] -pub struct NetworkTable { - ips: IpNetworkTable, -} - -impl NetworkTable { - pub fn new() -> Self { - Self { - ips: IpNetworkTable::new(), - } - } - - pub fn insert>(&mut self, network: N, data: T) -> Option { - self.ips.insert(network, data) - } - - pub fn longest_match>(&self, ip: I) -> Option<(IpNetwork, &T)> { - self.ips.longest_match(ip) - } -} diff --git a/common/wireguard/Cargo.toml b/common/wireguard/Cargo.toml index f2ac47abdce..d1744d975b8 100644 --- a/common/wireguard/Cargo.toml +++ b/common/wireguard/Cargo.toml @@ -11,30 +11,15 @@ license.workspace = true # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -async-recursion = "1.0.4" base64 = "0.21.3" -bincode = "1.3.3" # The latest version on crates.io at the time of writing this (6.0.0) has a # version mismatch with x25519-dalek/curve25519-dalek that is resolved in the # latest commit. So pick that for now. -#boringtun = "0.6.0" -boringtun = { workspace = true } -bytes = "1.5.0" -dashmap = "5.5.3" -etherparse = "0.13.0" -futures = "0.3.28" +x25519-dalek = "2.0.0" +defguard_wireguard_rs = { git = "https://github.com/neacsu/wireguard-rs.git", rev = "c2cd0c1119f699f4bc43f5e6ffd6fc242caa42ed" } ip_network = "0.4.1" -ip_network_table = "0.2.0" log.workspace = true +nym-network-defaults = { path = "../network-defaults" } nym-task = { path = "../task" } nym-wireguard-types = { path = "../wireguard-types" } -nym-sphinx = { path = "../nymsphinx" } -nym-tun = { path = "../tun" , features = ["wireguard"] } -rand.workspace = true -serde = { workspace = true, features = ["derive"] } -tap.workspace = true -thiserror.workspace = true tokio = { workspace = true, features = ["rt-multi-thread", "net", "io-util"] } - -[target.'cfg(target_os = "linux")'.dependencies] -tokio-tun = "0.9.0" diff --git a/common/wireguard/src/error.rs b/common/wireguard/src/error.rs deleted file mode 100644 index ec528854bdc..00000000000 --- a/common/wireguard/src/error.rs +++ /dev/null @@ -1,9 +0,0 @@ -use thiserror::Error; - -#[derive(Error, Debug)] -pub enum WgError { - #[error("unable to get tunnel")] - UnableToGetTunnel, - #[error("handshake failed")] - HandshakeFailed, -} diff --git a/common/wireguard/src/lib.rs b/common/wireguard/src/lib.rs index b987dbd31c7..d9e72f382ba 100644 --- a/common/wireguard/src/lib.rs +++ b/common/wireguard/src/lib.rs @@ -3,88 +3,55 @@ // #![warn(clippy::expect_used)] // #![warn(clippy::unwrap_used)] -mod error; -mod packet_relayer; -mod registered_peers; pub mod setup; -mod udp_listener; -mod wg_tunnel; use nym_wireguard_types::registration::GatewayClientRegistry; use std::sync::Arc; // Currently the module related to setting up the virtual network device is platform specific. #[cfg(target_os = "linux")] -use nym_tun::tun_device; - -use nym_tun::tun_task_channel; +use crate::setup::{peer_allowed_ips, peer_static_public_key, PRIVATE_KEY}; +use defguard_wireguard_rs::WGApi; +#[cfg(target_os = "linux")] +use defguard_wireguard_rs::{ + host::Peer, key::Key, net::IpAddrMask, InterfaceConfiguration, WireguardInterfaceApi, +}; +#[cfg(target_os = "linux")] +use nym_network_defaults::{WG_PORT, WG_TUN_DEVICE_ADDRESS}; -/// Start wireguard UDP listener and TUN device -/// -/// # Errors -/// -/// This function will return an error if either the UDP listener of the TUN device fails to start. +/// Start wireguard device #[cfg(target_os = "linux")] pub async fn start_wireguard( - task_client: nym_task::TaskClient, - gateway_client_registry: Arc, -) -> Result<(), Box> { - // TODO: make this configurable - - // We can optionally index peers by their IP like standard wireguard. If we don't then we do - // plain NAT where we match incoming destination IP with outgoing source IP. - - use nym_wireguard_types::tun_common::network_table::NetworkTable; - let peers_by_ip = Arc::new(tokio::sync::Mutex::new(NetworkTable::new())); - - // Alternative 1: - let routing_mode = tun_device::RoutingMode::new_allowed_ips(peers_by_ip.clone()); - // Alternative 2: - //let routing_mode = tun_device::RoutingMode::new_nat(); - - // Start the tun device that is used to relay traffic outbound - let config = tun_device::TunDeviceConfig { - base_name: setup::TUN_BASE_NAME.to_string(), - ip: setup::TUN_DEVICE_ADDRESS.parse().unwrap(), - netmask: setup::TUN_DEVICE_NETMASK.parse().unwrap(), + mut task_client: nym_task::TaskClient, + _gateway_client_registry: Arc, +) -> Result> { + let ifname = String::from("wg0"); + let wgapi = WGApi::new(ifname.clone(), false)?; + wgapi.create_interface()?; + let interface_config = InterfaceConfiguration { + name: ifname.clone(), + prvkey: PRIVATE_KEY.to_string(), + address: WG_TUN_DEVICE_ADDRESS.to_string(), + port: WG_PORT as u32, + peers: vec![], }; - let (tun, tun_task_tx, tun_task_response_rx) = tun_device::TunDevice::new(routing_mode, config); - tun.start(); - - // We also index peers by a tag - let peers_by_tag = Arc::new(tokio::sync::Mutex::new(wg_tunnel::PeersByTag::new())); - - // If we want to have the tun device on a separate host, it's the tun_task and - // tun_task_response channels that needs to be sent over the network to the host where the tun - // device is running. - - // The packet relayer's responsibility is to route packets between the correct tunnel and the - // tun device. The tun device may or may not be on a separate host, which is why we can't do - // this routing in the tun device itself. - let (packet_relayer, packet_tx) = packet_relayer::PacketRelayer::new( - tun_task_tx.clone(), - tun_task_response_rx, - peers_by_tag.clone(), - ); - packet_relayer.start(); - - // Start the UDP listener that clients connect to - let udp_listener = udp_listener::WgUdpListener::new( - packet_tx, - peers_by_ip, - peers_by_tag, - Arc::clone(&gateway_client_registry), - ) - .await?; - udp_listener.start(task_client); - - Ok(()) + wgapi.configure_interface(&interface_config)?; + let peer = peer_static_public_key(); + let mut peer = Peer::new(Key::new(peer.to_bytes())); + let peer_ip = peer_allowed_ips(); + let peer_ip_mask = IpAddrMask::new(peer_ip.network_address(), peer_ip.netmask()); + peer.set_allowed_ips(vec![peer_ip_mask]); + wgapi.configure_peer(&peer)?; + wgapi.configure_peer_routing(&[peer.clone()])?; + + tokio::spawn(async move { task_client.recv().await }); + + Ok(wgapi) } - #[cfg(not(target_os = "linux"))] pub async fn start_wireguard( _task_client: nym_task::TaskClient, _gateway_client_registry: Arc, -) -> Result<(), Box> { +) -> Result> { todo!("WireGuard is currently only supported on Linux") } diff --git a/common/wireguard/src/packet_relayer.rs b/common/wireguard/src/packet_relayer.rs deleted file mode 100644 index 2888a73e1c5..00000000000 --- a/common/wireguard/src/packet_relayer.rs +++ /dev/null @@ -1,74 +0,0 @@ -use std::{collections::HashMap, sync::Arc}; - -use tap::TapFallible; -use tokio::sync::mpsc::{self}; - -use crate::tun_task_channel::{TunTaskResponseRx, TunTaskTx}; - -use nym_wireguard_types::tun_common::{active_peers::PeerEventSender, event::Event}; - -#[derive(Clone)] -pub struct PacketRelaySender(pub(crate) mpsc::Sender<(u64, Vec)>); -pub(crate) struct PacketRelayReceiver(pub(crate) mpsc::Receiver<(u64, Vec)>); - -pub(crate) fn packet_relay_channel() -> (PacketRelaySender, PacketRelayReceiver) { - let (tx, rx) = mpsc::channel(16); - (PacketRelaySender(tx), PacketRelayReceiver(rx)) -} - -// The tunnels send packets to the packet relayer, which then relays it to the tun device. And -// conversely, it's where the tun device send responses to, which are relayed back to the correct -// tunnel. -pub(crate) struct PacketRelayer { - // Receive packets from the various tunnels - packet_rx: PacketRelayReceiver, - - // After receive from tunnels, send to the tun device - tun_task_tx: TunTaskTx, - - // Receive responses from the tun device - tun_task_response_rx: TunTaskResponseRx, - - // After receiving from the tun device, relay back to the correct tunnel - peers_by_tag: Arc>>, -} - -impl PacketRelayer { - pub(crate) fn new( - tun_task_tx: TunTaskTx, - tun_task_response_rx: TunTaskResponseRx, - peers_by_tag: Arc>>, - ) -> (Self, PacketRelaySender) { - let (packet_tx, packet_rx) = packet_relay_channel(); - ( - Self { - packet_rx, - tun_task_tx, - tun_task_response_rx, - peers_by_tag, - }, - packet_tx, - ) - } - - pub(crate) async fn run(mut self) { - loop { - tokio::select! { - Some((tag, packet)) = self.packet_rx.0.recv() => { - log::info!("Sent packet to tun device with tag: {tag}"); - self.tun_task_tx.send((tag, packet)).await.tap_err(|e| log::error!("{e}")).ok(); - }, - Some((tag, packet)) = self.tun_task_response_rx.recv() => { - log::info!("Received response from tun device with tag: {tag}"); - if let Some(tx) = self.peers_by_tag.lock().await.get(&tag) { - tx.send(Event::Ip(packet.into())).await.tap_err(|e| log::error!("{e}")).ok(); - } - } - } - } - } - - pub(crate) fn start(self) { - tokio::spawn(async move { self.run().await }); - } -} diff --git a/common/wireguard/src/registered_peers.rs b/common/wireguard/src/registered_peers.rs deleted file mode 100644 index a0a5b7f6dc6..00000000000 --- a/common/wireguard/src/registered_peers.rs +++ /dev/null @@ -1,61 +0,0 @@ -use std::{collections::HashMap, sync::Arc}; - -use ip_network::IpNetwork; -use nym_wireguard_types::PeerPublicKey; - -pub(crate) type PeerIdx = u32; - -#[derive(Debug)] -pub(crate) struct RegisteredPeer { - pub(crate) public_key: PeerPublicKey, - pub(crate) index: PeerIdx, - pub(crate) allowed_ips: IpNetwork, - // endpoint: SocketAddr, -} - -#[derive(Debug, Default)] -pub(crate) struct RegisteredPeers { - peers: HashMap>>, - peers_by_idx: HashMap>>, -} - -impl RegisteredPeers { - pub(crate) fn contains_key(&self, public_key: &PeerPublicKey) -> bool { - self.peers.contains_key(public_key) - } - - pub(crate) fn next_idx(&self) -> PeerIdx { - self.peers_by_idx.keys().max().unwrap_or(&0) + 1 - } - - pub(crate) async fn insert(&mut self, peer: Arc>) { - let peer_idx = { peer.lock().await.index }; - let public_key = { peer.lock().await.public_key }; - self.peers.insert(public_key, Arc::clone(&peer)); - self.peers_by_idx.insert(peer_idx, peer); - } - - #[allow(unused)] - pub(crate) async fn remove(&mut self, public_key: &PeerPublicKey) { - if let Some(peer) = self.peers.remove(public_key) { - let peer_idx = peer.lock().await.index; - if self.peers_by_idx.remove(&peer_idx).is_none() { - log::error!("Removed registered peer but no registered index was found"); - } - } - } - - pub(crate) fn get_by_key( - &self, - public_key: &PeerPublicKey, - ) -> Option<&Arc>> { - self.peers.get(public_key) - } - - pub(crate) fn get_by_idx( - &self, - peer_idx: PeerIdx, - ) -> Option<&Arc>> { - self.peers_by_idx.get(&peer_idx) - } -} diff --git a/common/wireguard/src/setup.rs b/common/wireguard/src/setup.rs index a4ee4e582d0..5cda585a528 100644 --- a/common/wireguard/src/setup.rs +++ b/common/wireguard/src/setup.rs @@ -1,20 +1,14 @@ use std::net::IpAddr; use base64::{engine::general_purpose, Engine as _}; -use boringtun::x25519; use log::info; // The wireguard UDP listener pub const WG_ADDRESS: &str = "0.0.0.0"; -// The interface used to route traffic -pub const TUN_BASE_NAME: &str = "nymwg"; -pub const TUN_DEVICE_ADDRESS: &str = "10.1.0.1"; -pub const TUN_DEVICE_NETMASK: &str = "255.255.255.0"; - // The private key of the listener // Corresponding public key: "WM8s8bYegwMa0TJ+xIwhk+dImk2IpDUKslDBCZPizlE=" -const PRIVATE_KEY: &str = "AEqXrLFT4qjYq3wmX0456iv94uM6nDj5ugp6Jedcflg="; +pub(crate) const PRIVATE_KEY: &str = "AEqXrLFT4qjYq3wmX0456iv94uM6nDj5ugp6Jedcflg="; // The AllowedIPs for the connected peer, which is one a single IP and the same as the IP that the // peer has configured on their side. @@ -28,11 +22,11 @@ fn decode_base64_key(base64_key: &str) -> [u8; 32] { .unwrap() } -pub fn server_static_private_key() -> x25519::StaticSecret { +pub fn server_static_private_key() -> x25519_dalek::StaticSecret { // TODO: this is a temporary solution for development let static_private_bytes: [u8; 32] = decode_base64_key(PRIVATE_KEY); - let static_private = x25519::StaticSecret::from(static_private_bytes); - let static_public = x25519::PublicKey::from(&static_private); + let static_private = x25519_dalek::StaticSecret::from(static_private_bytes); + let static_public = x25519_dalek::PublicKey::from(&static_private); info!( "wg public key: {}", general_purpose::STANDARD.encode(static_public) @@ -40,14 +34,14 @@ pub fn server_static_private_key() -> x25519::StaticSecret { static_private } -pub fn peer_static_public_key() -> x25519::PublicKey { +pub fn peer_static_public_key() -> x25519_dalek::PublicKey { // A single static public key is used during development // Read from NYM_PEER_PUBLIC_KEY env variable let peer = std::env::var("NYM_PEER_PUBLIC_KEY").expect("NYM_PEER_PUBLIC_KEY must be set"); let peer_static_public_bytes: [u8; 32] = decode_base64_key(&peer); - let peer_static_public = x25519::PublicKey::from(peer_static_public_bytes); + let peer_static_public = x25519_dalek::PublicKey::from(peer_static_public_bytes); info!( "Adding wg peer public key: {}", general_purpose::STANDARD.encode(peer_static_public) @@ -57,6 +51,6 @@ pub fn peer_static_public_key() -> x25519::PublicKey { pub fn peer_allowed_ips() -> ip_network::IpNetwork { let key: IpAddr = ALLOWED_IPS.parse().unwrap(); - let cidr = 0u8; + let cidr = 32u8; ip_network::IpNetwork::new_truncate(key, cidr).unwrap() } diff --git a/common/wireguard/src/udp_listener.rs b/common/wireguard/src/udp_listener.rs deleted file mode 100644 index 88bab9c1620..00000000000 --- a/common/wireguard/src/udp_listener.rs +++ /dev/null @@ -1,280 +0,0 @@ -use std::{net::SocketAddr, sync::Arc, time::Duration}; - -use boringtun::{ - noise::{self, handshake::parse_handshake_anon, rate_limiter::RateLimiter, TunnResult}, - x25519, -}; -use futures::StreamExt; -use log::error; -use nym_task::TaskClient; -use nym_wireguard_types::{ - registration::GatewayClientRegistry, - tun_common::{ - active_peers::{ActivePeers, PeersByIp}, - event::Event, - }, - PeerPublicKey, WG_PORT, -}; -use tap::TapFallible; -use tokio::{net::UdpSocket, sync::Mutex}; - -use crate::{ - error::WgError, - packet_relayer::PacketRelaySender, - registered_peers::{RegisteredPeer, RegisteredPeers}, - setup::{self, WG_ADDRESS}, - wg_tunnel::PeersByTag, -}; - -const MAX_PACKET: usize = 65535; - -async fn add_test_peer(registered_peers: &mut RegisteredPeers) { - let peer_static_public = PeerPublicKey::new(setup::peer_static_public_key()); - let peer_index = 0; - let peer_allowed_ips = setup::peer_allowed_ips(); - let test_peer = Arc::new(tokio::sync::Mutex::new(RegisteredPeer { - public_key: peer_static_public, - index: peer_index, - allowed_ips: peer_allowed_ips, - })); - registered_peers.insert(test_peer).await; -} - -pub struct WgUdpListener { - // Our private key - static_private: x25519::StaticSecret, - - // Our public key - static_public: x25519::PublicKey, - - // The list of registered peers that we allow - registered_peers: RegisteredPeers, - - // The routing table, as defined by wireguard - peers_by_ip: Arc>, - - // ... or alternatively we can map peers by their tag - peers_by_tag: Arc>, - - // The UDP socket to the peer - udp: Arc, - - // Send data to the TUN device for sending - packet_tx: PacketRelaySender, - - // Wireguard rate limiter - rate_limiter: RateLimiter, - - gateway_client_registry: Arc, -} - -impl WgUdpListener { - pub async fn new( - packet_tx: PacketRelaySender, - peers_by_ip: Arc>, - peers_by_tag: Arc>, - gateway_client_registry: Arc, - ) -> Result> { - let wg_address = SocketAddr::new(WG_ADDRESS.parse().unwrap(), WG_PORT); - log::info!("Starting wireguard UDP listener on {wg_address}"); - let udp = Arc::new(UdpSocket::bind(wg_address).await?); - - // Setup our own keys - let static_private = setup::server_static_private_key(); - let static_public = x25519::PublicKey::from(&static_private); - let handshake_max_rate = 100u64; - let rate_limiter = RateLimiter::new(&static_public, handshake_max_rate); - - // Create a test peer for dev - let mut registered_peers = RegisteredPeers::default(); - add_test_peer(&mut registered_peers).await; - - Ok(Self { - static_private, - static_public, - registered_peers, - peers_by_ip, - peers_by_tag, - udp, - packet_tx, - rate_limiter, - gateway_client_registry, - }) - } - - pub async fn run(mut self, mut task_client: TaskClient) { - // The set of active tunnels - let active_peers = ActivePeers::default(); - // Each tunnel is run in its own task, and the task handle is stored here so we can remove - // it from `active_peers` when the tunnel is closed - let mut active_peers_task_handles = futures::stream::FuturesUnordered::new(); - - let mut buf = [0u8; MAX_PACKET]; - let mut dst_buf = [0u8; MAX_PACKET]; - - while !task_client.is_shutdown() { - tokio::select! { - () = task_client.recv() => { - log::trace!("WireGuard UDP listener: received shutdown"); - break; - } - // Reset the rate limiter every 1 sec - () = tokio::time::sleep(Duration::from_secs(1)) => { - self.rate_limiter.reset_count(); - }, - // Handle tunnel closing - Some(public_key) = active_peers_task_handles.next() => { - match public_key { - Ok(public_key) => { - active_peers.remove(&public_key); - } - Err(err) => { - error!("WireGuard UDP listener: error receiving shutdown from peer: {err}"); - } - } - }, - // Handle incoming packets - Ok((len, addr)) = self.udp.recv_from(&mut buf) => { - log::trace!("udp: received {} bytes from {}", len, addr); - - // If this addr has already been encountered, send directly to tunnel - // TODO: optimization opportunity to instead create a connected UDP socket - // inside the wg tunnel, where you can recv the data directly. - if let Some(peer_tx) = active_peers.get_by_addr(&addr) { - log::info!("udp: received {len} bytes from {addr} from known peer"); - peer_tx - .send(Event::Wg(buf[..len].to_vec().into())) - .await - .tap_err(|e| log::error!("{e}")) - .ok(); - continue; - } - - // Verify the incoming packet - let verified_packet = match self.rate_limiter.verify_packet(Some(addr.ip()), &buf[..len], &mut dst_buf) { - Ok(packet) => packet, - Err(TunnResult::WriteToNetwork(cookie)) => { - log::info!("Send back cookie to: {addr}"); - self.udp.send_to(cookie, addr).await.tap_err(|e| log::error!("{e}")).ok(); - continue; - } - Err(err) => { - log::warn!("{err:?}"); - continue; - } - }; - - // Check if this is a registered peer, if not, just skip - let registered_peer = match parse_peer( - verified_packet, - &mut self.registered_peers, - &self.static_private, - &self.static_public, - Arc::clone(&self.gateway_client_registry), - ).await { - Ok(Some(peer)) => peer.lock().await, - Ok(None) => { - log::warn!("Peer not registered: {addr}"); - continue; - } - Err(err) => { - log::error!("{err}"); - continue; - }, - }; - - // Look up if the peer is already connected - if let Some(peer_tx) = active_peers.get_by_key_mut(®istered_peer.public_key) { - // We found the peer as connected, even though the addr was not known - log::info!("udp: received {len} bytes from {addr} which is a known peer with unknown addr"); - peer_tx.send(Event::WgVerified(buf[..len].to_vec().into())) - .await - .tap_err(|err| log::error!("{err}")) - .ok(); - } else { - // If it isn't, start a new tunnel - log::info!("udp: received {len} bytes from {addr} from unknown peer, starting tunnel"); - // NOTE: we are NOT passing in the existing rate_limiter. Re-visit this - // choice later. - log::warn!("Creating new rate limiter, consider re-using?"); - let (join_handle, peer_tx, tag) = crate::wg_tunnel::start_wg_tunnel( - addr, - self.udp.clone(), - self.static_private.clone(), - *registered_peer.public_key, - registered_peer.index, - registered_peer.allowed_ips, - // self.tun_task_tx.clone(), - self.packet_tx.clone(), - ); - - self.peers_by_ip.lock().await.insert(registered_peer.allowed_ips, peer_tx.clone()); - self.peers_by_tag.lock().await.insert(tag, peer_tx.clone()); - - peer_tx.send(Event::Wg(buf[..len].to_vec().into())) - .await - .tap_err(|e| log::error!("{e}")) - .ok(); - - log::info!("Adding peer: {:?}: {addr}", registered_peer.public_key); - active_peers.insert(*registered_peer.public_key, addr, peer_tx); - active_peers_task_handles.push(join_handle); - } - }, - } - } - log::info!("WireGuard listener: shutting down"); - } - - pub fn start(self, task_client: TaskClient) { - tokio::spawn(async move { self.run(task_client).await }); - } -} - -async fn parse_peer<'a>( - verified_packet: noise::Packet<'a>, - registered_peers: &'a mut RegisteredPeers, - static_private: &x25519::StaticSecret, - static_public: &x25519::PublicKey, - gateway_client_registry: Arc, -) -> Result>>, WgError> { - let registered_peer = match verified_packet { - noise::Packet::HandshakeInit(ref packet) => { - let Ok(handshake) = parse_handshake_anon(static_private, static_public, packet) else { - return Err(WgError::HandshakeFailed); - }; - let peer_public_key = - PeerPublicKey::new(x25519::PublicKey::from(handshake.peer_static_public)); - - let already_registered = registered_peers.contains_key(&peer_public_key); - - if already_registered { - registered_peers.get_by_key(&peer_public_key) - } else if gateway_client_registry.contains_key(&peer_public_key) { - let peer_idx = registered_peers.next_idx(); - let peer = Arc::new(Mutex::new(RegisteredPeer { - public_key: peer_public_key, - index: peer_idx, - allowed_ips: setup::peer_allowed_ips(), - })); - registered_peers.insert(peer).await; - registered_peers.get_by_key(&peer_public_key) - } else { - None - } - } - noise::Packet::HandshakeResponse(packet) => { - let peer_idx = packet.receiver_idx >> 8; - registered_peers.get_by_idx(peer_idx) - } - noise::Packet::PacketCookieReply(packet) => { - let peer_idx = packet.receiver_idx >> 8; - registered_peers.get_by_idx(peer_idx) - } - noise::Packet::PacketData(packet) => { - let peer_idx = packet.receiver_idx >> 8; - registered_peers.get_by_idx(peer_idx) - } - }; - Ok(registered_peer) -} diff --git a/common/wireguard/src/wg_tunnel.rs b/common/wireguard/src/wg_tunnel.rs deleted file mode 100644 index dfacd4d1540..00000000000 --- a/common/wireguard/src/wg_tunnel.rs +++ /dev/null @@ -1,351 +0,0 @@ -use std::{collections::HashMap, net::SocketAddr, sync::Arc, time::Duration}; - -use async_recursion::async_recursion; -use boringtun::{ - noise::{errors::WireGuardError, rate_limiter::RateLimiter, Tunn, TunnResult}, - x25519, -}; -use bytes::Bytes; -use log::{debug, error, info, warn}; -use nym_wireguard_types::tun_common::{ - active_peers::{peer_event_channel, PeerEventReceiver, PeerEventSender}, - event::Event, - network_table::NetworkTable, -}; -use rand::RngCore; -use tap::TapFallible; -use tokio::{net::UdpSocket, sync::broadcast, time::timeout}; - -use crate::{error::WgError, packet_relayer::PacketRelaySender, registered_peers::PeerIdx}; - -const HANDSHAKE_MAX_RATE: u64 = 10; - -const MAX_PACKET: usize = 65535; - -// We index the tunnels by tag -pub(crate) type PeersByTag = HashMap; - -pub struct WireGuardTunnel { - // Incoming data from the UDP socket received in the main event loop - peer_rx: PeerEventReceiver, - - // UDP socket used for sending data - udp: Arc, - - // Peer endpoint - endpoint: Arc>, - - // AllowedIPs for this peer - allowed_ips: NetworkTable<()>, - - // `boringtun` tunnel, used for crypto & WG protocol - wg_tunnel: Arc>, - - // Signal close - close_tx: broadcast::Sender<()>, - close_rx: broadcast::Receiver<()>, - - // Send data to the task that handles sending data through the tun device - packet_tx: PacketRelaySender, - - tag: u64, -} - -impl Drop for WireGuardTunnel { - fn drop(&mut self) { - info!("WireGuard tunnel: dropping"); - self.close(); - } -} - -impl WireGuardTunnel { - pub(crate) fn new( - udp: Arc, - endpoint: SocketAddr, - static_private: x25519::StaticSecret, - peer_static_public: x25519::PublicKey, - index: PeerIdx, - peer_allowed_ips: ip_network::IpNetwork, - // rate_limiter: Option, - packet_tx: PacketRelaySender, - ) -> (Self, PeerEventSender, u64) { - let local_addr = udp.local_addr().unwrap(); - let peer_addr = udp.peer_addr(); - log::info!("New wg tunnel: endpoint: {endpoint}, local_addr: {local_addr}, peer_addr: {peer_addr:?}"); - - let preshared_key = None; - let persistent_keepalive = None; - - let static_public = x25519::PublicKey::from(&static_private); - let rate_limiter = Some(Arc::new(RateLimiter::new( - &static_public, - HANDSHAKE_MAX_RATE, - ))); - - let wg_tunnel = Arc::new(tokio::sync::Mutex::new( - Tunn::new( - static_private, - peer_static_public, - preshared_key, - persistent_keepalive, - index, - rate_limiter, - ) - .expect("failed to create Tunn instance"), - )); - - // Channels with incoming data that is received by the main event loop - let (peer_tx, peer_rx) = peer_event_channel(); - - // Signal close tunnel - let (close_tx, close_rx) = broadcast::channel(1); - - let mut allowed_ips = NetworkTable::new(); - allowed_ips.insert(peer_allowed_ips, ()); - - let tag = Self::new_tag(); - - let tunnel = WireGuardTunnel { - peer_rx, - udp, - endpoint: Arc::new(tokio::sync::RwLock::new(endpoint)), - allowed_ips, - wg_tunnel, - close_tx, - close_rx, - packet_tx, - tag, - }; - - (tunnel, peer_tx, tag) - } - - fn new_tag() -> u64 { - // TODO: check for collisions - rand::thread_rng().next_u64() - } - - fn close(&self) { - let _ = self.close_tx.send(()); - } - - pub async fn spin_off(&mut self) { - loop { - tokio::select! { - _ = self.close_rx.recv() => { - info!("WireGuard tunnel: received msg to close"); - break; - }, - packet = self.peer_rx.recv() => match packet { - Some(packet) => { - info!("event loop: {packet}"); - match packet { - Event::Wg(data) => { - let _ = self.consume_wg(&data) - .await - .tap_err(|err| error!("WireGuard tunnel: consume_wg error: {err}")); - }, - Event::WgVerified(data) => { - let _ = self.consume_verified_wg(&data) - .await - .tap_err(|err| error!("WireGuard tunnel: consume_verified_wg error: {err}")); - } - Event::Ip(data) => self.consume_eth(&data).await, - } - }, - None => { - info!("WireGuard tunnel: incoming UDP stream closed, closing tunnel"); - break; - }, - }, - () = tokio::time::sleep(Duration::from_millis(250)) => { - let _ = self.update_wg_timers() - .await - .map_err(|err| error!("WireGuard tunnel: update_wg_timers error: {err}")); - }, - } - } - info!("WireGuard tunnel ({}): closed", self.endpoint.read().await); - } - - async fn wg_tunnel_lock(&self) -> Result, WgError> { - timeout(Duration::from_millis(100), self.wg_tunnel.lock()) - .await - .map_err(|_| WgError::UnableToGetTunnel) - } - - #[allow(unused)] - async fn set_endpoint(&self, addr: SocketAddr) { - if *self.endpoint.read().await != addr { - log::info!("wg tunnel update endpoint: {addr}"); - *self.endpoint.write().await = addr; - } - } - - async fn consume_wg(&mut self, data: &[u8]) -> Result<(), WgError> { - let mut send_buf = [0u8; MAX_PACKET]; - let mut tunnel = self.wg_tunnel_lock().await?; - match tunnel.decapsulate(None, data, &mut send_buf) { - TunnResult::WriteToNetwork(packet) => { - let endpoint = self.endpoint.read().await; - log::info!("udp: send {} bytes to {}", packet.len(), *endpoint); - if let Err(err) = self.udp.send_to(packet, *endpoint).await { - error!("Failed to send decapsulation-instructed packet to WireGuard endpoint: {err:?}"); - }; - // Flush pending queue - loop { - let mut send_buf = [0u8; MAX_PACKET]; - match tunnel.decapsulate(None, &[], &mut send_buf) { - TunnResult::WriteToNetwork(packet) => { - log::info!("udp: send {} bytes to {}", packet.len(), *endpoint); - if let Err(err) = self.udp.send_to(packet, *endpoint).await { - error!("Failed to send decapsulation-instructed packet to WireGuard endpoint: {err:?}"); - break; - }; - } - _ => { - break; - } - } - } - } - TunnResult::WriteToTunnelV4(packet, addr) => { - if self.allowed_ips.longest_match(addr).is_some() { - self.packet_tx - .0 - .send((self.tag, packet.to_vec())) - .await - .unwrap(); - } else { - warn!("Packet from {addr} not in allowed_ips"); - } - } - TunnResult::WriteToTunnelV6(packet, addr) => { - if self.allowed_ips.longest_match(addr).is_some() { - self.packet_tx - .0 - .send((self.tag, packet.to_vec())) - .await - .unwrap(); - } else { - warn!("Packet (v6) from {addr} not in allowed_ips"); - } - } - TunnResult::Done => { - debug!("WireGuard: decapsulate done"); - } - TunnResult::Err(err) => { - error!("WireGuard: decapsulate error: {err:?}"); - } - } - Ok(()) - } - - async fn consume_verified_wg(&mut self, data: &[u8]) -> Result<(), WgError> { - // Potentially we could take some shortcuts here in the name of performance, but currently - // I don't see that the needed functions in boringtun is exposed in the public API. - // TODO: make sure we don't put double pressure on the rate limiter! - self.consume_wg(data).await - } - - async fn consume_eth(&self, data: &Bytes) { - info!("consume_eth: raw packet size: {}", data.len()); - let encapsulated_packet = self.encapsulate_packet(data).await; - info!( - "consume_eth: after encapsulate: {}", - encapsulated_packet.len() - ); - - let endpoint = self.endpoint.read().await; - info!("consume_eth: send to {}: {}", *endpoint, data.len()); - self.udp - .send_to(&encapsulated_packet, *endpoint) - .await - .unwrap(); - } - - async fn encapsulate_packet(&self, payload: &[u8]) -> Vec { - // TODO: use fixed dst and src buffers that we can reuse - let len = 148.max(payload.len() + 32); - let mut dst = vec![0; len]; - - let mut wg_tunnel = self.wg_tunnel_lock().await.unwrap(); - - match wg_tunnel.encapsulate(payload, &mut dst) { - TunnResult::WriteToNetwork(packet) => packet.to_vec(), - unexpected => { - error!("{:?}", unexpected); - vec![] - } - } - } - - async fn update_wg_timers(&mut self) -> Result<(), WgError> { - let mut send_buf = [0u8; MAX_PACKET]; - let mut tun = self.wg_tunnel_lock().await?; - let tun_result = tun.update_timers(&mut send_buf); - self.handle_routine_tun_result(tun_result).await; - Ok(()) - } - - #[async_recursion] - async fn handle_routine_tun_result<'a: 'async_recursion>(&self, result: TunnResult<'a>) { - match result { - TunnResult::WriteToNetwork(packet) => { - let endpoint = self.endpoint.read().await; - log::info!("routine: write to network: {}: {}", endpoint, packet.len()); - if let Err(err) = self.udp.send_to(packet, *endpoint).await { - error!("routine: failed to send packet: {err:?}"); - }; - } - TunnResult::Err(WireGuardError::ConnectionExpired) => { - warn!("Wireguard handshake has expired!"); - // WIP(JON): consider just closing the tunnel here - let mut buf = vec![0u8; MAX_PACKET]; - let Ok(mut peer) = self.wg_tunnel_lock().await else { - warn!("Failed to lock WireGuard peer, closing tunnel"); - self.close(); - return; - }; - peer.format_handshake_initiation(&mut buf[..], false); - self.handle_routine_tun_result(result).await; - } - TunnResult::Err(err) => { - error!("Failed to prepare routine packet for WireGuard endpoint: {err:?}"); - } - TunnResult::Done => {} - other => { - warn!("Unexpected WireGuard routine task state: {other:?}"); - } - }; - } -} - -pub(crate) fn start_wg_tunnel( - endpoint: SocketAddr, - udp: Arc, - static_private: x25519::StaticSecret, - peer_static_public: x25519::PublicKey, - peer_index: PeerIdx, - peer_allowed_ips: ip_network::IpNetwork, - packet_tx: PacketRelaySender, -) -> ( - tokio::task::JoinHandle, - PeerEventSender, - u64, -) { - let (mut tunnel, peer_tx, tag) = WireGuardTunnel::new( - udp, - endpoint, - static_private, - peer_static_public, - peer_index, - peer_allowed_ips, - packet_tx, - ); - let join_handle = tokio::spawn(async move { - tunnel.spin_off().await; - peer_static_public - }); - (join_handle, peer_tx, tag) -} diff --git a/documentation/README.md b/documentation/README.md index b7244f480f0..66293cf92fc 100644 --- a/documentation/README.md +++ b/documentation/README.md @@ -6,18 +6,34 @@ Each directory contains a readme with more information about running and contrib * `dev-portal` contains developer documentation hosted at [https://nymtech.net/developers](https://nymtech.net/developers) * `operators` contains node setup and maintenance guides hosted at [https://nymtech.net/operators](https://nymtech.net/operators) +> If you are looking for the Typescript SDK documentation located at [sdk.nymtech.net](https://sdk.nymtech.net) this can be found in `../sdk/typescript/docs/` + +## Contribution +* If you wish to add to the documentation please create a PR against this repo. +* If you are **adding a plugin dependency** make sure to also **add that to the list of plugins in `install_mdbook_deps.sh` line 12**. + ## Scripts * `bump_versions.sh` allows you to update the ~~`platform_release_version` and~~ `wallet_release_version` variable~~s~~ in the `book.toml` of each mdbook project at once. You can also optionally update the `minimum_rust_version` as well. Helpful for lazy-updating when cutting a new version of the docs. -* `build_all_to_dist.sh` is used by the `ci-dev.yml` and `cd-dev.yml` scripts for building all mdbook projects and moving the rendered html to `../dist/` to be rsynced with various servers. -* `post_process.sh` is a script called by the github CI and CD workflows to post process CSS/image/href links for serving several mdbooks from a subdirectory. +* The following scripts are used by the `ci-dev.yml` and `cd-dev.yml` scripts (located in `../.github/workflows/`): + * `build_all_to_dist.sh` is used for building all mdbook projects and moving the rendered html to `../dist/` to be rsynced with various servers. + * `install_mdbook_deps.sh` checks for an existing install of mdbook (and plugins), uninstalls them, and then installs them on a clean slate. This is to avoid weird dependency clashes if relying on an existing mdbook version. + * `post_process.sh` is used to post process CSS/image/href links for serving several mdbooks from a subdirectory. + * `removed_existing_config.sh` is used to check for existing nym client/node config files on the CI/CD server and remove it if it exists. This is to mitigate issues with `mdbook-cmdrun` where e.g. a node is already initialised, and the command fails. + +## CI/CD +Deployment of the docs is partially automated and partially manual. +* `ci-docs.yml` will run on pushes to all branches **apart from `master`** +* `cd-docs.yml` must be run manually. This pushes to a staging branch which then must be manually promoted to production. -### Licensing and copyright information +## Licensing and copyright information This is a monorepo and components that make up Nym as a system are licensed individually, so for accurate information, please check individual files. As a general approach, licensing is as follows this pattern: -- applications and binaries are GPLv3 -- libraries and components are Apache 2.0 or MIT -- documentation is Apache 2.0 or CC0-1.0 -For accurate information, please check individual files. \ No newline at end of file +*

Nym Documentation by Nym Technologies is licensed under CC BY-NC-SA 4.0

+ +* Nym applications and binaries are [GPL-3.0-only](https://www.gnu.org/licenses/) + +* Used libraries and different components are [Apache 2.0](https://www.apache.org/licenses/LICENSE-2.0.html) or [MIT](https://mit-license.org/) + diff --git a/documentation/dev-portal/src/faq/integrations-faq.md b/documentation/dev-portal/src/faq/integrations-faq.md index e02cc0dd2e1..649d1ff8967 100644 --- a/documentation/dev-portal/src/faq/integrations-faq.md +++ b/documentation/dev-portal/src/faq/integrations-faq.md @@ -198,5 +198,7 @@ For the moment then yes, the mixnet is free to use. There are no limits on the a No, although we do recommend that apps that wish to integrate look into running some of their own infrastructure such as gateways in order to assure uptime. ### How can I find out if an application is already supported by network requester services? -You can check the [default allowed list](https://nymtech.net/.wellknown/network-requester/standard-allowed-list.txt) file to see which application traffic is whitelisted by default. If the domain is present on that list, it means that existing [network requesters](https://nymtech.net/docs/nodes/network-requester.html) can be used to privacy-protect your application traffic. Simply use [NymConnect](../quickstart/nymconnect-gui.md) to connect to this service through the mixnet. +You can check the [default allowed list](https://nymtech.net/.wellknown/network-requester/standard-allowed-list.txt) file to see which application traffic is whitelisted by default. If the domain is present on that list, it means that existing [network requesters](https://nymtech.net/docs/nodes/network-requester.html) can be used to privacy-protect your application traffic. Simply use [NymConnect](../quickstart/nymconnect-gui.md) to connect to this service through the mixnet. + +Currently we are undergoing changes on this policy under the name [Project Smoosh](https://nymtech.net/operators/faq/smoosh-faq.html) where a new type of node [Exit Gateway](https://nymtech.net/operators/legal/exit-gateway.html) will allow users to connect to much wider range of domains, restricted by our new [exit policy](https://nymtech.net/.wellknown/network-requester/exit-policy.txt). Follow the changes [here](https://nymtech.net/operators/faq/smoosh-faq.html#what-are-the-changes). diff --git a/documentation/dev-portal/src/introduction.md b/documentation/dev-portal/src/introduction.md index 6085a3038bc..742853c56c9 100644 --- a/documentation/dev-portal/src/introduction.md +++ b/documentation/dev-portal/src/introduction.md @@ -4,6 +4,6 @@ Welcome to the Nym Developer Portal, containing quickstart resources, user manua For more in-depth information about nodes, network traffic flows, clients, coconut etc check out the [docs](https://nymtech.net/docs). -If you are looking for information and setup guides for the various pieces of Nym mixnet infrastructure (mix nodes, gateways and network requesters) and Nyx blockchain validators see the **new [Operators Guides](https://nymtech.net/operators)** book. +If you are looking for information and setup guides for the various pieces of Nym mixnet infrastructure (mix nodes, gateways and network requesters) and Nyx blockchain validators see the [Operators Guides](https://nymtech.net/operators) book. -If you're looking for TypeScript/JavaScript related information such as SDKs to build your own tools, step-by-step tutorials, live playgrounds and more, make sure to check out the **new [TS SDK Handbook](https://sdk.nymtech.net/)** ! \ No newline at end of file +If you're looking for TypeScript/JavaScript related information such as SDKs to build your own tools, step-by-step tutorials, live playgrounds and more, make sure to check out the [TS SDK Handbook](https://sdk.nymtech.net/). diff --git a/documentation/dev-portal/src/licensing.md b/documentation/dev-portal/src/licensing.md index 6663c2fb56c..b569231b757 100644 --- a/documentation/dev-portal/src/licensing.md +++ b/documentation/dev-portal/src/licensing.md @@ -1,10 +1,11 @@ # Licensing -Components that make up Nym as a system are licensed individually, so for accurate information, please check individual files. - As a general approach, licensing is as follows this pattern: -- applications and binaries are GPLv3 -- libraries and components are Apache 2.0 or MIT -- documentation is Apache 2.0 or CC0-1.0 -Again, for accurate information, please check individual files. +*

Nym Documentation by Nym Technologies is licensed under CC BY-NC-SA 4.0

+ +* Nym applications and binaries are [GPL-3.0-only](https://www.gnu.org/licenses/) + +* Used libraries and different components are [Apache 2.0](https://www.apache.org/licenses/LICENSE-2.0.html) or [MIT](https://mit-license.org/) + +For accurate information, please check individual files. diff --git a/documentation/dev-portal/src/tutorials/cosmos-service/preparing-env.md b/documentation/dev-portal/src/tutorials/cosmos-service/preparing-env.md index 9192903001b..e970821148e 100644 --- a/documentation/dev-portal/src/tutorials/cosmos-service/preparing-env.md +++ b/documentation/dev-portal/src/tutorials/cosmos-service/preparing-env.md @@ -29,7 +29,7 @@ cargo new nym-cosmos-service ``` [dependencies] clap = { version = "4.0", features = ["derive"] } -cosmrs = "=0.14.0" +cosmrs = "=0.15.0" tokio = { version = "1.24.1", features = ["rt-multi-thread", "macros"] } serde = "1.0.152" serde_json = "1.0.91" diff --git a/documentation/docs/src/licensing.md b/documentation/docs/src/licensing.md index f0f5fb7d0ca..b569231b757 100644 --- a/documentation/docs/src/licensing.md +++ b/documentation/docs/src/licensing.md @@ -1,8 +1,11 @@ # Licensing As a general approach, licensing is as follows this pattern: -- applications and binaries are GPLv3 -- libraries and components are Apache 2.0 or MIT -- documentation is Apache 2.0 or CC0-1.0 -Again, for accurate information, please check individual files. +*

Nym Documentation by Nym Technologies is licensed under CC BY-NC-SA 4.0

+ +* Nym applications and binaries are [GPL-3.0-only](https://www.gnu.org/licenses/) + +* Used libraries and different components are [Apache 2.0](https://www.apache.org/licenses/LICENSE-2.0.html) or [MIT](https://mit-license.org/) + +For accurate information, please check individual files. diff --git a/documentation/docs/src/nyx/interacting-with-chain.md b/documentation/docs/src/nyx/interacting-with-chain.md index 98a0fbaad0a..5ebd5484bd3 100644 --- a/documentation/docs/src/nyx/interacting-with-chain.md +++ b/documentation/docs/src/nyx/interacting-with-chain.md @@ -7,11 +7,11 @@ There are two options for interacting with the blockchain to send tokens or inte ## Nym-CLI tool (recommended in most cases) The `nym-cli` tool is a binary offering a simple interface for interacting with deployed smart contract (for instance, bonding and unbonding a mix node from the CLI), as well as creating and managing accounts and keypairs, sending tokens, and querying the blockchain. -Instructions on how to do so can be found on the [`nym-cli` docs page](../tools/nym-cli.md), and there are example commands in the [integrations FAQ](https://nymtech.net/developers/integrations/faq.html). +Instructions on how to do so can be found on the [`nym-cli` docs page](../tools/nym-cli.md), and there are example commands in the [integrations FAQ](https://nymtech.net/developers/faq/integrations-faq.html). ## Nyxd binary The `nyxd` binary, although more complex to compile and use, offers the full range of commands availiable to users of CosmosSDK chains. Use this if you are (e.g.) wanting to perform more granular queries about transactions from the CLI. -You can use the instructions on how to do this on from the [`gaiad` docs page](https://hub.cosmos.network/main/delegators/delegator-guide-cli.html#querying-the-state), and there are example commands in the [integrations FAQ](https://nymtech.net/developers/integrations/faq.html). +You can use the instructions on how to do this on from the [`gaiad` docs page](https://hub.cosmos.network/main/delegators/delegator-guide-cli.html#querying-the-state), and there are example commands in the [integrations FAQ](https://nymtech.net/developers/faq/integrations-faq.html). diff --git a/documentation/docs/src/wallet/cli-wallet.md b/documentation/docs/src/wallet/cli-wallet.md index 36670190a30..a6195646729 100644 --- a/documentation/docs/src/wallet/cli-wallet.md +++ b/documentation/docs/src/wallet/cli-wallet.md @@ -1,8 +1,8 @@ # CLI Wallet -If you have already read our validator setup and maintenance [documentation](../nodes/validator.md) you will have seen that we compile and use the `nyxd` binary primarily for our validators. This binary can however be used for many other tasks, such as creating and using keypairs for wallets, or automated setups that require the signing and broadcasting of transactions. +If you have already read our validator setup and maintenance [documentation](https://nymtech.net/operators/nodes/validator-setup.html) you will have seen that we compile and use the `nyxd` binary primarily for our validators. This binary can however be used for many other tasks, such as creating and using keypairs for wallets, or automated setups that require the signing and broadcasting of transactions. ### Using `nyxd` binary as a CLI wallet -You can use the `nyxd` as a minimal CLI wallet if you want to set up an account (or multiple accounts). Just compile the binary as per the documentation, **stopping after** the [building your validator](../nodes/validator.md) step is complete. You can then run `nyxd keys --help` to see how you can set up and store different keypairs with which to interact with the Nyx blockchain. +You can use the `nyxd` as a minimal CLI wallet if you want to set up an account (or multiple accounts). Just compile the binary as per the documentation, **stopping after** the [building your validator](https://nymtech.net/operators/nodes/validator-setup.html#building-your-validator) step is complete. You can then run `nyxd keys --help` to see how you can set up and store different keypairs with which to interact with the Nyx blockchain. For more on interacting with the chain, see the [Interacting with Nyx Chain and Smart Contracts](../nyx/interacting-with-chain.md) page. diff --git a/documentation/install_mdbook_deps.sh b/documentation/install_mdbook_deps.sh new file mode 100755 index 00000000000..7344b1e586b --- /dev/null +++ b/documentation/install_mdbook_deps.sh @@ -0,0 +1,80 @@ +#!/usr/bin/env bash + +set -o errexit +set -o nounset +set -o pipefail + +# simple script to automate cleaning an existing mdbook install then installing it fresh for each deploy. + +# pinning minor version allows for updates but no breaking changes +MINOR_VERSION=0.4 +# if a new plugin is added to the books it needs to be added here also +declare -a plugins=("admonish" "linkcheck" "last-changed" "theme" "variables" "cmdrun") + +# install mdbook + plugins +install_mdbook_deps() { + printf "\ninstalling mdbook..." + # installing mdbook with only specific features for speed +# cargo install mdbook --no-default-features --features search --vers "^$MINOR_VERSION" + cargo install mdbook --vers "^$MINOR_VERSION" + + printf "\ninstalling plugins..." + for i in "${plugins[@]}" + do + cargo install mdbook-$i + done + +# mdbook-admonish config +# if [ $(pwd | awk -F/ '{print $NF}') != "documentation" ]; then +# printf "not in documentation/ - changing dir but something isn't right in the workflow file" +# cd documentation/ +# mdbook-admonish install dev-portal +# mdbook-admonish install docs +# mdbook-admonish install operators +# else +# mdbook-admonish install dev-portal +# mdbook-admonish install docs +# mdbook-admonish install operators +# fi +} + +# uninstall mdbook + plugins +uninstall_mdbook_deps() { + # mdbook + printf "\nuninstalling existing mdbook installation...\n" + cargo uninstall mdbook + # check it worked + if [ $? -ne 0 ]; then + printf "\nsomething went wrong, exiting" + exit 1 + else + printf "\nmdbook deleted\n" + fi + + # plugins + printf "\nuninstalling existing plugins...\n" + for i in "${plugins[@]}" + do + cargo uninstall mdbook-$i + # check it worked + if [ $? -ne 0 ]; then + printf "\nsomething went wrong, exiting" + exit 1 + else + printf "\nmdbook-$i deleted\n" + fi + done +} + +main() { + if test -f ~/.cargo/bin/mdbook; then + printf "mdbook already installed (located at: $(which mdbook))" + uninstall_mdbook_deps; + install_mdbook_deps; + else + printf "mdbook not installed" + install_mdbook_deps; + fi +} + +main; diff --git a/documentation/operators/book.toml b/documentation/operators/book.toml index 56a5b00162f..5ede8ee22a7 100644 --- a/documentation/operators/book.toml +++ b/documentation/operators/book.toml @@ -83,7 +83,7 @@ curly-quotes = true # mathjax-support = false # useful if we want to pull equations in copy-fonts = true no-section-label = false -additional-css = ["theme/pagetoc.css", "././mdbook-admonish.css","./custom.css", "./mdbook-admonish.css"] +additional-css = ["theme/pagetoc.css", "./custom.css", "./mdbook-admonish.css"] additional-js = ["theme/pagetoc.js"] git-repository-url = "https://github.com/nymtech/nym" git-repository-icon = "fa-github" diff --git a/documentation/operators/src/licensing.md b/documentation/operators/src/licensing.md index f0f5fb7d0ca..b569231b757 100644 --- a/documentation/operators/src/licensing.md +++ b/documentation/operators/src/licensing.md @@ -1,8 +1,11 @@ # Licensing As a general approach, licensing is as follows this pattern: -- applications and binaries are GPLv3 -- libraries and components are Apache 2.0 or MIT -- documentation is Apache 2.0 or CC0-1.0 -Again, for accurate information, please check individual files. +*

Nym Documentation by Nym Technologies is licensed under CC BY-NC-SA 4.0

+ +* Nym applications and binaries are [GPL-3.0-only](https://www.gnu.org/licenses/) + +* Used libraries and different components are [Apache 2.0](https://www.apache.org/licenses/LICENSE-2.0.html) or [MIT](https://mit-license.org/) + +For accurate information, please check individual files. diff --git a/documentation/operators/src/nodes/gateway-setup.md b/documentation/operators/src/nodes/gateway-setup.md index 1f2fe529274..c3cfb48f9f9 100644 --- a/documentation/operators/src/nodes/gateway-setup.md +++ b/documentation/operators/src/nodes/gateway-setup.md @@ -189,12 +189,12 @@ The `run` command starts the Gateway: ## Bonding your Gateway ```admonish info -Before you bond your Gateway, please make sure the [firewall configuration](./maintenance.md#configure-your-firewall) is setup so your Gateway can be reached from the outside. You can also setup [WSS on your Gateway](./maintenance.md#run-web-secure-socket-wss-on-gateway) and [automate](./maintenance.md#vps-setup-and-automation) your Gateway to simplify the operation overhead. We highly recommend to run ny of these steps before bonding to prevent disruption of your Gateway's routing score later on. +Before you bond your Gateway, please make sure the [firewall configuration](./maintenance.md#configure-your-firewall) is setup so your Gateway can be reached from the outside. You can also setup [WSS on your Gateway](./maintenance.md#run-web-secure-socket-wss-on-gateway) and [automate](./maintenance.md#vps-setup-and-automation) your Gateway to simplify the operation overhead. We highly recommend to run any of these steps before bonding to prevent disruption of your Gateway's routing score later on. ``` ### Via the Desktop wallet (recommended) -You can bond your Gateway via the Desktop wallet. Make sure your Gateway is running and follow the steps below: +You can bond your Gateway via the Desktop wallet. **Make sure your Gateway is running first**, then follow the steps below: 1. Open your wallet, and head to the `Bonding` page, then select the node type `Gateway` and input your node details. Press `Next`. @@ -240,7 +240,7 @@ It will look something like this (as `` we used `supergateway`): * And paste it into the wallet nodal, press `Next` and confirm the transaction. ![Paste Signature](../images/wallet-screenshots/wallet-gateway-sign.png) -*This image is just an example, copy-paste your own base58-encoded signature* +*This image is just an example, copy-paste your own base58-encoded signature.* * Your Gateway is now bonded. diff --git a/documentation/operators/src/nodes/maintenance.md b/documentation/operators/src/nodes/maintenance.md index b0a1a0ddb0a..998c09f878c 100644 --- a/documentation/operators/src/nodes/maintenance.md +++ b/documentation/operators/src/nodes/maintenance.md @@ -16,25 +16,26 @@ For example `./target/debug/nym-network-requester --no-banner build-info --outpu ## Upgrading your node -> The process is the similar for Mix Node, Gateway and Network Requester. In the following steps we use a placeholder `` in the commands, please change it for the type of node you want to upgrade. Any particularities for the given type of node are included. +> The process is the similar for Mix Node, Gateway and Network Requester. In the following steps we use a placeholder `` in the commands, please change it for the binary name you want to upgrade (ie `nym-mixnode`). Any particularities for the given type of node are included. Upgrading your node is a two-step process: -* Updating the binary and `~/.nym///config/config.toml` on your VPS -* Updating the node information in the [mixnet smart contract](https://nymtech.net/docs/nyx/mixnet-contract.html). **This is the information that is present on the [mixnet explorer](https://explorer.nymtech.net)**. + +1. Updating the binary and `~/.nym///config/config.toml` on your VPS +2. Updating the node information in the [mixnet smart contract](https://nymtech.net/docs/nyx/mixnet-contract.html). **This is the information that is present on the [mixnet explorer](https://explorer.nymtech.net)**. ### Step 1: Upgrading your binary Follow these steps to upgrade your Node binary and update its config file: * Pause your node process. - if you see the terminal window with your node, press `ctrl + c` - - if you run it as `systemd` service, run: `systemctl stop nym-.service` + - if you run it as `systemd` service, run: `systemctl stop .service` * Replace the existing `` binary with the newest binary (which you can either [compile yourself](https://nymtech.net/docs/binaries/building-nym.html) or grab from our [releases page](https://github.com/nymtech/nym/releases)). * Re-run `init` with the same values as you used initially for your `` ([Mix Node](./mix-node-setup.md#initialising-your-mix-node), [Gateway](./gateway-setup.md#initialising-your-gateway)) . **This will just update the config file, it will not overwrite existing keys**. * Restart your node process with the new binary: - - if your node is not automitized, just `run` your `` with `./nym- run --id `. Here are exact guidelines for [Mix Node](./mix-node-setup.md#running-your-mix-node) and [Gateway](./gateway-setup.md#running-your-gateway). - - if you automatized your node via systemd (recommended) run: + - if your node is *not automated*, just `run` your `` with `./ run --id `. Here are exact guidelines for [Mix Node](./mix-node-setup.md#running-your-mix-node) and [Gateway](./gateway-setup.md#running-your-gateway). + - if you *automated* your node with systemd (recommended) run: ```sh systemctl daemon-reload # to pickup the new unit file -systemctl start nym-.service +systemctl start .service journalctl -f -u .service # to monitor log of you node ``` @@ -52,7 +53,7 @@ You can either do this graphically via the Desktop Wallet, or the CLI. ![Bonding page](../images/wallet-screenshots/bonding.png) -* Update the fields in the `Node Settings` page and click `Submit changes to the blockchain`. +* Update the fields in the `Node Settings` page (usually the field `Version` is the only one to change) and click `Submit changes to the blockchain`. ![Node Settings Page](../images/wallet-screenshots/node_settings.png) @@ -117,7 +118,34 @@ If the `/dev/sda` partition is almost full, try pruning some of the `.gz` syslog ## Run Web Secure Socket (WSS) on Gateway -Now you can run WSS on your Gateway. +Now you can run WSS on your Gateway. + +### WSS on a new Gateway + +These steps are for an operator who is setting up a [Gateway](gateway-setup.md) for the first time and wants to run it with WSS. + +1. New flags will need to be added to the `init` and `run` command. The `--host` option should be replaced with these flags: + +- `--listening-address`: The IP address which is used for receiving sphinx packets and listening to client data. +- `--public-ips`: A comma separated list of IP’s that are announced to the `nym-api`. In the most cases `--public-ips` **is the address used for bonding.** + +```sh +--listening-address 0.0.0.0 --public-ips "$(curl -4 https://ifconfig.me)" +``` + +- `--hostname` (optional): This flag is required if the operator wishes to run WSS. It can be something like `mainnet-gateway2.nymtech.net`. + +2. Make sure to enable all necessary [ports](maintenance.md#configure-your-firewall) on the Gateway: + +```sh +sudo ufw allow 1789,1790,8000,9000,9001,22/tcp, 9001/tcp +``` + +The Gateway will then be accessible on something like: *http://85.159.211.99:8080/api/v1/swagger/index.html* + +Are you seeing something like: *this node attempted to announce an invalid public address: 0.0.0.0.*? + +Please modify `[host.public_ips]` section of your config file stored as `~/.nym/gateways//config/config.toml`. ### WSS on an existing Gateway @@ -203,29 +231,6 @@ ufw allow 9001/tcp Lastly don't forget to restart your Gateway, now the API will render the WSS details for this Gateway: - -### WSS on a new Gateway - -These steps are for an operator who is setting up a Gateway for the first time and wants to run it with WSS. - -New flags will need to be added to the `init` and `run` command. The `--host` option is still accepted for now, but can and should be replaced with `--listening-address`, this is the IP address which is used for receiving sphinx packets and listening to client data. - -Another flag `--public-ips` is required; it's a comma separated list of IP’s that are announced to the `nym-api`, it is usually the address which is used for bonding. - -If the operator wishes to run WSS, an optional `--hostname` flag is also required, that can be something like `mainnet-gateway2.nymtech.net`. Make sure to enable all necessary [ports](maintenance.md#configure-your-firewall) on the Gateway. - -The Gateway will then be accessible on something like: *http://85.159.211.99:8080/api/v1/swagger/index.html* - -Are you seeing something like: *this node attempted to announce an invalid public address: 0.0.0.0.*? - -Please modify `[host.public_ips]` section of your config file stored as `~/.nym/gateways//config/config.toml`. - -If so the flags are going to be slightly different: - -``` ---listening-address "0.0.0.0" --public-ips "$(curl -4 https://ifconfig.me)" -``` - ## Configure your firewall Although your `` is now ready to receive traffic, your server may not be. The following commands will allow you to set up a firewall using `ufw`. @@ -250,6 +255,9 @@ Finally open your `` p2p port, as well as ports for ssh and ports for verl # for Mix Node, Gateway and Network Requester sudo ufw allow 1789,1790,8000,9000,9001,22/tcp +# in case of setting up WSS on Gateway add: +sudo ufw allow 9001/tcp + # In case of reverse proxy for the Gateway swagger page add: sudo ufw allow 8080,80/443 @@ -266,9 +274,13 @@ For more information about your node's port configuration, check the [port refer ## VPS Setup and Automation +> Replace `` variable with `nym-mixnode`, `nym-gateway` or `nym-network-requester` according the node you running on your machine. + ### Automating your node with nohup, tmux and systemd -Although it’s not totally necessary, it's useful to have the Mix Node automatically start at system boot time. +Although it’s not totally necessary, it's useful to have the Mix Node automatically start at system boot time. We recommend to run your remote operation via [`tmux`](maintenance.md#tmux) for easier management and a handy return to your previous session. For full automation, including a failed node auto-restart and `ulimit` setup, [`systemd`](maintenance.md#systemd) is a good choice. + +> Do any of these steps and run your automated node before you start bonding process! #### nohup @@ -319,7 +331,7 @@ tmux attach-session #### systemd -Here's a systemd service file to do that: +To automate with `systemd` use this init service file and follow the steps below. ##### For Mix Node @@ -341,7 +353,7 @@ RestartSec=30 WantedBy=multi-user.target ``` -* Put the above file onto your system at `/etc/systemd/system/nym-mixnode.service`. +* Put the above file onto your system at `/etc/systemd/system/nym-mixnode.service` and follow the [next steps](maintenance.md#following-steps-for-nym-nodes-running-as-systemd-service). ##### For Gateway @@ -363,7 +375,7 @@ RestartSec=30 WantedBy=multi-user.target ``` -* Put the above file onto your system at `/etc/systemd/system/nym-gateway.service`. +* Put the above file onto your system at `/etc/systemd/system/nym-gateway.service` and follow the [next steps](maintenance.md#following-steps-for-nym-nodes-running-as-systemd-service). ##### For Network Requester @@ -385,63 +397,26 @@ RestartSec=30 [Install] WantedBy=multi-user.target ``` +* Put the above file onto your system at `/etc/systemd/system/nym-network-requester.service` and follow the [next steps](maintenance.md#following-steps-for-nym-nodes-running-as-systemd-service). -Now enable and start your requester: +#### Following steps for Nym nodes running as `systemd` service -```sh -systemctl enable nym-network-requester.service -systemctl start nym-network-requester.service +Change the `` in `ExecStart` to point at your `` binary (`nym-mixnode`, `nym-gateway` or `nym-network-requester`), and the `` so it is the user you are running as. -# you can always check your requester has succesfully started with: -systemctl status nym-network-requester.service -``` -* Put the above file onto your system at `/etc/systemd/system/nym-network-requester.service`. +Example: If you have built nym in the `$HOME` directory on your server, your username is `jetpanther`, and node `` is `puma`, then the `ExecStart` line (command) in the script located in `/etc/systemd/system/nym-mixnode.service` for Nym Mixnode might look like this: -##### For Validator +`ExecStart=/home/jetpanther/nym/target/release/nym-mixnode run --id puma`. -Below is a systemd unit file to place at `/etc/systemd/system/nymd.service`: +Basically, you want the full `///nym-mixnode run --id `. If you are unsure about your `///`, then `cd` to your directory where you run your `` from and run `pwd` command which returns the full path for you. -```ini -[Unit] -Description=Nyxd -StartLimitInterval=350 -StartLimitBurst=10 - -[Service] -User= # change to your user -Type=simple -Environment="LD_LIBRARY_PATH=/home//" # change to correct path -ExecStart=/home///nymd start # change to correct path -Restart=on-failure -RestartSec=30 -LimitNOFILE=infinity - -[Install] -WantedBy=multi-user.target -``` - -Proceed to start it with: +Once done, save the script and follow these steps: ```sh -systemctl daemon-reload # to pickup the new unit file -systemctl enable nymd # to enable the service -systemctl start nymd # to actually start the service -journalctl -f -u nymd # to monitor system logs showing the service start +systemctl daemon-reload +# to pickup the new unit file ``` -##### Following steps for Nym Mixnet nodes - -Change the `` in `ExecStart` to point at your `` binary (`nym-mixnode`, `nym-gateway` or `nym-network-requester`), and the `` so it is the user you are running as. - -If you have built nym in the `$HOME` directory on your server, and your username is `jetpanther`, then the start command for nym mixnode might look like this: - -`ExecStart=/home/jetpanther/nym/target/release/nym-mixnode run --id `. Basically, you want the full `/path/to/nym-mixnode run --id whatever-your-node-id-is` - -Then run: - -```sh -systemctl daemon-reload # to pickup the new unit file -``` +Enable the newly created service: ```sh # for Mix Node @@ -449,9 +424,12 @@ systemctl enable nym-mixnode.service # for Gateway systemctl enable nym-gateway.service + +# for Network Requester +systemctl enable nym-network-requester.service ``` -Start your node: +Start your `` as a `systemd` service: ```sh # for Mix Node @@ -460,29 +438,66 @@ service nym-mixnode start # for Gateway service nym-gateway start +# for Network Requester +service nym-network-requester.service ``` -This will cause your node to start at system boot time. If you restart your machine, the node will come back up automatically. +This will cause your `` to start at system boot time. If you restart your machine, your `` will come back up automatically. You can monitor system logs of your node by running: ```sh journalctl -f -u .service +# for example journalctl -f -u nym-mixnode.service ``` Or check a status by running: ```sh systemctl status .service +# for example systemctl status nym-mixnode.service ``` You can also do `service stop` or `service restart`. -Note: if you make any changes to your systemd script after you've enabled it, you will need to run: +Note: if you make any changes to your `systemd` script after you've enabled it, you will need to run: -``` +```sh systemctl daemon-reload ``` -This lets your operating system know it's ok to reload the service configuration. +This lets your operating system know it's ok to reload the service configuration. Then restart your ``. + + +##### For Validator + +Below is a `systemd` unit file to place at `/etc/systemd/system/nymd.service` to automate your validator: + +```ini +[Unit] +Description=Nyxd +StartLimitInterval=350 +StartLimitBurst=10 + +[Service] +User= # change to your user +Type=simple +Environment="LD_LIBRARY_PATH=/home//" # change to correct path +ExecStart=/home///nymd start # change to correct path +Restart=on-failure +RestartSec=30 +LimitNOFILE=infinity + +[Install] +WantedBy=multi-user.target +``` + +Proceed to start it with: + +```sh +systemctl daemon-reload # to pickup the new unit file +systemctl enable nymd # to enable the service +systemctl start nymd # to actually start the service +journalctl -f -u nymd # to monitor system logs showing the service start +``` ### Setting the ulimit @@ -611,11 +626,12 @@ scp -r -3 @:~/.nym/mixnodes/ ` there, please read the following. -On some services (AWS, Google, etc) the machine's available bind address is not the same as the public IP address. In this case, bind `--host` to the local machine address returned by `$(curl ifconfig.me)`, but also specify `--announce-host` with the public IP. Please make sure that you pass the correct, routable `--announce-host`. +On some services (AWS, Google, etc) the machine's available bind address is not the same as the public IP address. In this case, bind `--host` to the local machine address returned by `$(curl -4 https://ifconfig.me)`, but that may not the public IP address to bond your `` in the wallet. -For example, on a Google machine, you may see the following output from the `ifconfig` command: +You can run `ifconfig` command. For example, on a Google machine, you may see the following output: ```sh ens4: flags=4163 mtu 1460 @@ -625,20 +641,14 @@ ens4: flags=4163 mtu 1460 The `ens4` interface has the IP `10.126.5.7`. But this isn't the public IP of the machine, it's the IP of the machine on Google's internal network. Google uses virtual routing, so the public IP of this machine is something else, maybe `36.68.243.18`. -`./nym-mixnode init --host 10.126.5.7`, initalises the Mix Node, but no packets will be routed because `10.126.5.7` is not on the public internet. +To find the right IP configuration, contact your VPS provider for support to find the right public IP and use it to bond your `` with the `nym-api` via Nym wallet. -Trying `nym-mixnode init --host 36.68.243.18`, you'll get back a startup error saying `AddrNotAvailable`. This is because the Mix Node doesn't know how to bind to a host that's not in the output of `ifconfig`. +On self-hosted machine it's a bit more tricky. In that case as an operator you must be sure that your ISP allows for public IPv4 and IPv6 and then it may be a bit of playing around to find the right configuration. One way may be to bind your binary with the `--host` flag to local address `127.0.0.1` and run `echo "$(curl -4 https://ifconfig.me)"` to get a public address which you use to bond your Mix Node to `nym-api` via Nym wallet. -The right thing to do in this situation is to init with a command: -```sh -./nym-mixnode init --host 10.126.5.7 --announce-host 36.68.243.18 -``` - -This will bind the Mix Node to the available host `10.126.5.7`, but announce the Mix Node's public IP to the directory server as `36.68.243.18`. It's up to you as a node operator to ensure that your public and private IPs match up properly. - -To find the right IP configuration, contact your VPS provider for support. +It's up to you as a node operator to ensure that your public and private IPs match up properly. ## Nym API (previously 'Validator API') endpoints + Numerous API endpoints are documented on the Nym API (previously 'Validator API')'s [Swagger Documentation](https://validator.nymtech.net/api/swagger/index.html). There you can also try out various requests from your browser, and download the response from the API. Swagger will also show you what commands it is running, so that you can run these from an app or from your CLI if you prefer. ### Mix Node Reward Estimation API endpoint @@ -826,4 +836,5 @@ All validator-specific port configuration can be found in `$HOME/.nymd/config/co | 26656 | Listen for incoming peer connections | | 26660 | Listen for Prometheus connections | -/ + + diff --git a/documentation/operators/src/nodes/mix-node-setup.md b/documentation/operators/src/nodes/mix-node-setup.md index 21516a091fa..44ffa295f2b 100644 --- a/documentation/operators/src/nodes/mix-node-setup.md +++ b/documentation/operators/src/nodes/mix-node-setup.md @@ -89,7 +89,7 @@ In order to easily identify your node via human-readable information later on, y ``` Node description is a short text that describes your node. It is displayed in the `./nym-mixnode list` command and in the `./nym-mixnode node-details --id ` command. It also shows up in the node explorer to let people know what your node is about and link to your website. -You can set your node description, by creating a file called `description.toml` and put it in the same directory as your `config.toml` file (`~/.nym/mixnodes//description.toml`). The file should look like this example: +You can set your node description, by creating a file called `description.toml` and put it in the same directory as your `config.toml` file (`~/.nym/mixnodes//config/description.toml`). The file should look like this example: ```toml name = "Winston Smith" @@ -98,7 +98,7 @@ link = "https://nymtech.net" location = "Giza, Egypt" ``` -> Remember to restart your `nym-mix-node` process in order for the new description to be propagated. +> Remember to restart your `nym-mixnode` process in order for the new description to be propagated. ## Running your Mix Node diff --git a/documentation/remove_existing_config.sh b/documentation/remove_existing_config.sh new file mode 100755 index 00000000000..ae2b767512f --- /dev/null +++ b/documentation/remove_existing_config.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash + +set -o errexit +set -o nounset +set -o pipefail + +# Script to remove existing ~'/.nym/ files on docs deployment. Used to avoid issues with `mdbook-cmdrun` output when +# e.g. erroring about overwriting existing keys. `mdbook-cmdrun` output for the moment has to be checked manually. + +DIR=~/.nym + +# check for config directory +if [ ! -d $DIR ]; then + echo "config dir doesn't exist: nothing to do" +else + echo "config dir exists - deleting" + rm -rf $DIR + # check exit code of rm -rf - if !0 then exit + if [ $? -ne 0 ]; then + echo "exit code was $?. looks like the something went wrong with deleting the directory" + exit 1 + fi +fi \ No newline at end of file diff --git a/explorer-api/Cargo.toml b/explorer-api/Cargo.toml index aadfc916d7b..3778b480b9e 100644 --- a/explorer-api/Cargo.toml +++ b/explorer-api/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "explorer-api" -version = "1.1.31" +version = "1.1.32" edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/gateway/Cargo.toml b/gateway/Cargo.toml index ffaf439c7f4..285864be20d 100644 --- a/gateway/Cargo.toml +++ b/gateway/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "nym-gateway" license = "GPL-3" -version = "1.1.31" +version = "1.1.32" authors = [ "Dave Hrycyszyn ", "Jędrzej Stuczyński ", @@ -77,9 +77,11 @@ nym-statistics-common = { path = "../common/statistics" } nym-task = { path = "../common/task" } nym-types = { path = "../common/types" } nym-validator-client = { path = "../common/client-libs/validator-client" } -nym-wireguard = { path = "../common/wireguard", optional = true } nym-ip-packet-router = { path = "../service-providers/ip-packet-router" } +nym-wireguard = { path = "../common/wireguard", optional = true } +defguard_wireguard_rs = { git = "https://github.com/neacsu/wireguard-rs.git", rev = "c2cd0c1119f699f4bc43f5e6ffd6fc242caa42ed", optional = true } + [dev-dependencies] tower = "0.4.13" rand = "0.8.5" @@ -95,4 +97,4 @@ sqlx = { version = "0.5", features = [ ] } [features] -wireguard = ["nym-wireguard"] +wireguard = ["nym-wireguard", "defguard_wireguard_rs"] diff --git a/gateway/src/node/mod.rs b/gateway/src/node/mod.rs index b61628d4328..a77a358a8c2 100644 --- a/gateway/src/node/mod.rs +++ b/gateway/src/node/mod.rs @@ -22,6 +22,8 @@ use crate::node::statistics::collector::GatewayStatisticsCollector; use crate::node::storage::Storage; use anyhow::bail; use dashmap::DashMap; +#[cfg(feature = "wireguard")] +use defguard_wireguard_rs::{WGApi, WireguardInterfaceApi}; use futures::channel::{mpsc, oneshot}; use log::*; use nym_crypto::asymmetric::{encryption, identity}; @@ -204,8 +206,7 @@ impl Gateway { async fn start_wireguard( &self, shutdown: TaskClient, - ) -> Result<(), Box> { - // TODO: possibly we should start the UDP listener and TUN device explicitly here + ) -> Result> { nym_wireguard::start_wireguard(shutdown, Arc::clone(&self.client_registry)).await } @@ -476,6 +477,13 @@ impl Gateway { }); } + self.start_client_websocket_listener( + mix_forwarding_channel.clone(), + active_clients_store.clone(), + shutdown.subscribe().named("websocket::Listener"), + Arc::new(coconut_verifier), + ); + let nr_request_filter = if self.config.network_requester.enabled { let embedded_nr = self .start_network_requester( @@ -496,7 +504,7 @@ impl Gateway { if self.config.ip_packet_router.enabled { let embedded_ip_sp = self .start_ip_packet_router( - mix_forwarding_channel.clone(), + mix_forwarding_channel, shutdown.subscribe().named("ip_service_provider"), ) .await?; @@ -513,23 +521,13 @@ impl Gateway { .with_maybe_network_request_filter(nr_request_filter) .start(shutdown.subscribe().named("http-api"))?; - self.start_client_websocket_listener( - mix_forwarding_channel, - active_clients_store, - shutdown.subscribe().named("websocket::Listener"), - Arc::new(coconut_verifier), - ); - // Once this is a bit more mature, make this a commandline flag instead of a compile time // flag #[cfg(feature = "wireguard")] - if let Err(err) = self + let wg_api = self .start_wireguard(shutdown.subscribe().named("wireguard")) .await - { - // that's a nasty workaround, but anyhow errors are generally nicer, especially on exit - bail!("{err}") - } + .ok(); info!("Finished nym gateway startup procedure - it should now be able to receive mix and client traffic!"); @@ -537,6 +535,10 @@ impl Gateway { // that's a nasty workaround, but anyhow errors are generally nicer, especially on exit bail!("{err}") } + #[cfg(feature = "wireguard")] + if let Some(wg_api) = wg_api { + wg_api.remove_interface()?; + } Ok(()) } } diff --git a/mixnode/Cargo.toml b/mixnode/Cargo.toml index 86973cb99d3..bdcb0b3a9bf 100644 --- a/mixnode/Cargo.toml +++ b/mixnode/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "nym-mixnode" license = "GPL-3" -version = "1.1.33" +version = "1.1.34" authors = [ "Dave Hrycyszyn ", "Jędrzej Stuczyński ", diff --git a/nym-api/Cargo.toml b/nym-api/Cargo.toml index 0c310bc8a81..514f664cb9e 100644 --- a/nym-api/Cargo.toml +++ b/nym-api/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "nym-api" license = "GPL-3" -version = "1.1.32" +version = "1.1.34" authors = [ "Dave Hrycyszyn ", "Jędrzej Stuczyński ", diff --git a/nym-api/src/coconut/tests.rs b/nym-api/src/coconut/tests.rs index 1f08f4a197d..54af19dcaee 100644 --- a/nym-api/src/coconut/tests.rs +++ b/nym-api/src/coconut/tests.rs @@ -29,7 +29,7 @@ use nym_validator_client::nym_api::routes::{ }; use nym_validator_client::nyxd::Coin; use nym_validator_client::nyxd::{ - AccountId, Algorithm, DeliverTx, Event, EventAttribute, Fee, Hash, TxResponse, + AccountId, Algorithm, Event, EventAttribute, ExecTxResult, Fee, Hash, TxResponse, }; use crate::coconut::State; @@ -490,7 +490,7 @@ pub fn tx_entry_fixture(tx_hash: &str) -> TxResponse { hash: Hash::from_str(tx_hash).unwrap(), height: Default::default(), index: 0, - tx_result: DeliverTx { + tx_result: ExecTxResult { code: Default::default(), data: Default::default(), log: Default::default(), diff --git a/nym-api/src/epoch_operations/rewarded_set_assignment.rs b/nym-api/src/epoch_operations/rewarded_set_assignment.rs index a1713e6e7bb..08a794768c7 100644 --- a/nym-api/src/epoch_operations/rewarded_set_assignment.rs +++ b/nym-api/src/epoch_operations/rewarded_set_assignment.rs @@ -24,7 +24,15 @@ struct MixnodeWithStakeAndPerformance { impl MixnodeWithStakeAndPerformance { fn to_selection_weight(&self) -> f64 { - let scaled_stake = self.total_stake * self.performance; + let scaled_performance = match self.performance.checked_pow(20) { + Ok(perf) => perf, + Err(overflow) => { + warn!("the node's performance ({}) has overflow while scaling it by the factor of 20: {overflow}. Setting it to 0 instead.", self.performance); + return 0.; + } + }; + + let scaled_stake = self.total_stake * scaled_performance; stake_to_f64(scaled_stake) } } diff --git a/nym-connect/desktop/Cargo.lock b/nym-connect/desktop/Cargo.lock index e3a9fce4c25..42ec60ea3dd 100644 --- a/nym-connect/desktop/Cargo.lock +++ b/nym-connect/desktop/Cargo.lock @@ -514,15 +514,6 @@ dependencies = [ "opaque-debug 0.2.3", ] -[[package]] -name = "blake2" -version = "0.10.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe" -dependencies = [ - "digest 0.10.7", -] - [[package]] name = "blake3" version = "1.4.1" @@ -610,29 +601,6 @@ version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "845141a4fade3f790628b7daaaa298a25b204fb28907eb54febe5142db6ce653" -[[package]] -name = "boringtun" -version = "0.6.0" -source = "git+https://github.com/cloudflare/boringtun?rev=e1d6360d6ab4529fc942a078e4c54df107abe2ba#e1d6360d6ab4529fc942a078e4c54df107abe2ba" -dependencies = [ - "aead", - "base64 0.13.1", - "blake2 0.10.6", - "chacha20poly1305", - "hex", - "hmac 0.12.1", - "ip_network", - "ip_network_table", - "libc", - "nix 0.25.1", - "parking_lot 0.12.1", - "rand_core 0.6.4", - "ring", - "tracing", - "untrusted 0.9.0", - "x25519-dalek 2.0.0", -] - [[package]] name = "brotli" version = "3.3.4" @@ -705,9 +673,9 @@ checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610" [[package]] name = "bytes" -version = "1.4.0" +version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89b2fd2a0dcf38d7971e2194b6b6eebab45ae01067456a7fd93d5547a61b70be" +checksum = "a2bd12c1caf447e69cd4528f47f94d203fd2582878ecb9e9465484c4148a8223" dependencies = [ "serde", ] @@ -1068,9 +1036,9 @@ dependencies = [ [[package]] name = "cosmos-sdk-proto" -version = "0.19.0" +version = "0.20.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73c9d2043a9e617b0d602fbc0a0ecd621568edbf3a9774890a6d562389bd8e1c" +checksum = "32560304ab4c365791fd307282f76637213d8083c1a98490c35159cd67852237" dependencies = [ "prost", "prost-types", @@ -1079,19 +1047,19 @@ dependencies = [ [[package]] name = "cosmrs" -version = "0.14.0" +version = "0.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af13955d6f356272e6def9ff5e2450a7650df536d8934f47052a20c76513d2f6" +checksum = "47126f5364df9387b9d8559dcef62e99010e1d4098f39eb3f7ee4b5c254e40ea" dependencies = [ "bip32", "cosmos-sdk-proto", "ecdsa 0.16.8", "eyre", - "getrandom 0.2.10", "k256 0.13.1", "rand_core 0.6.4", "serde", "serde_json", + "signature 2.1.0", "subtle-encoding", "tendermint", "tendermint-rpc", @@ -1347,15 +1315,6 @@ dependencies = [ "syn 2.0.28", ] -[[package]] -name = "ct-logs" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1a816186fa68d9e426e3cb4ae4dff1fcd8e4a2c34b781bf7a822574a0d0aac8" -dependencies = [ - "sct 0.6.1", -] - [[package]] name = "ctor" version = "0.1.26" @@ -2883,31 +2842,6 @@ dependencies = [ "hashbrown 0.14.0", ] -[[package]] -name = "headers" -version = "0.3.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3e372db8e5c0d213e0cd0b9be18be2aca3d44cf2fe30a9d46a65581cd454584" -dependencies = [ - "base64 0.13.1", - "bitflags 1.3.2", - "bytes", - "headers-core", - "http", - "httpdate", - "mime", - "sha1", -] - -[[package]] -name = "headers-core" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7f66481bfee273957b1f20485a4ff3362987f85b2c236580d81b4eb7a326429" -dependencies = [ - "http", -] - [[package]] name = "heck" version = "0.3.3" @@ -3119,41 +3053,18 @@ dependencies = [ "want", ] -[[package]] -name = "hyper-proxy" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca815a891b24fdfb243fa3239c86154392b0953ee584aa1a2a1f66d20cbe75cc" -dependencies = [ - "bytes", - "futures", - "headers", - "http", - "hyper", - "hyper-rustls", - "rustls-native-certs", - "tokio", - "tokio-rustls 0.22.0", - "tower-service", - "webpki 0.21.4", -] - [[package]] name = "hyper-rustls" -version = "0.22.1" +version = "0.24.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f9f7a97316d44c0af9b0301e65010573a853a9fc97046d7331d7f6bc0fd5a64" +checksum = "8d78e1e73ec14cf7375674f74d7dde185c8206fd9dea6fb6295e8a98098aaa97" dependencies = [ - "ct-logs", "futures-util", + "http", "hyper", - "log", - "rustls 0.19.1", - "rustls-native-certs", + "rustls 0.21.7", "tokio", - "tokio-rustls 0.22.0", - "webpki 0.21.4", - "webpki-roots 0.21.1", + "tokio-rustls 0.24.1", ] [[package]] @@ -3314,28 +3225,6 @@ dependencies = [ "windows-sys 0.48.0", ] -[[package]] -name = "ip_network" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa2f047c0a98b2f299aa5d6d7088443570faae494e9ae1305e48be000c9e0eb1" - -[[package]] -name = "ip_network_table" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4099b7cfc5c5e2fe8c5edf3f6f7adf7a714c9cc697534f63a5a5da30397cb2c0" -dependencies = [ - "ip_network", - "ip_network_table-deps-treebitmap", -] - -[[package]] -name = "ip_network_table-deps-treebitmap" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e537132deb99c0eb4b752f0346b6a836200eaaa3516dd7e5514b63930a09e5d" - [[package]] name = "ipnet" version = "2.8.0" @@ -3468,9 +3357,7 @@ dependencies = [ "cfg-if", "ecdsa 0.16.8", "elliptic-curve 0.13.5", - "once_cell", "sha2 0.10.8", - "signature 2.1.0", ] [[package]] @@ -3612,7 +3499,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4ae926706ba42c425c9457121178330d75e273df2e82e28b758faf3de3a9acb9" dependencies = [ "arrayref", - "blake2 0.8.1", + "blake2", "chacha", "keystream", ] @@ -3829,18 +3716,6 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e4a24736216ec316047a1fc4252e27dabb04218aa4a3f37c6e7ddbf1f9782b54" -[[package]] -name = "nix" -version = "0.25.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f346ff70e7dbfd675fe90590b92d59ef2de15a8779ae305ebcbfd3f0caf59be4" -dependencies = [ - "autocfg", - "bitflags 1.3.2", - "cfg-if", - "libc", -] - [[package]] name = "nix" version = "0.26.2" @@ -4761,6 +4636,7 @@ version = "0.1.0" dependencies = [ "async-trait", "base64 0.13.1", + "bip32", "bip39", "colored 2.0.4", "cosmrs", @@ -4821,8 +4697,8 @@ name = "nym-wireguard-types" version = "0.1.0" dependencies = [ "base64 0.21.4", - "boringtun", "dashmap", + "log", "nym-crypto", "serde", "thiserror", @@ -5488,9 +5364,9 @@ dependencies = [ [[package]] name = "prost" -version = "0.11.9" +version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b82eaa1d779e9a4bc1c3217db8ffbeabaae1dca241bf70183242128d48681cd" +checksum = "f4fdd22f3b9c31b53c060df4a0613a1c7f062d4115a2b984dd15b1858f7e340d" dependencies = [ "bytes", "prost-derive", @@ -5498,22 +5374,22 @@ dependencies = [ [[package]] name = "prost-derive" -version = "0.11.9" +version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5d2d8d10f3c6ded6da8b05b5fb3b8a5082514344d56c9f871412d29b4e075b4" +checksum = "265baba7fabd416cf5078179f7d2cbeca4ce7a9041111900675ea7c4cb8a4c32" dependencies = [ "anyhow", "itertools", "proc-macro2", "quote", - "syn 1.0.109", + "syn 2.0.28", ] [[package]] name = "prost-types" -version = "0.11.9" +version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "213622a1460818959ac1181aaeb2dc9c7f63df720db7d788b3e24eacd1983e13" +checksum = "e081b29f63d83a4bc75cfc9f3fe424f9156cf92d8a4f0c9407cce9a1b67327cf" dependencies = [ "prost", ] @@ -5770,6 +5646,7 @@ dependencies = [ "http", "http-body", "hyper", + "hyper-rustls", "hyper-tls", "ipnet", "js-sys", @@ -5779,12 +5656,16 @@ dependencies = [ "once_cell", "percent-encoding", "pin-project-lite", + "rustls 0.21.7", + "rustls-native-certs", + "rustls-pemfile", "serde", "serde_json", "serde_urlencoded", "system-configuration", "tokio", "tokio-native-tls", + "tokio-rustls 0.24.1", "tokio-socks", "tokio-util", "tower-service", @@ -5851,7 +5732,7 @@ dependencies = [ "libc", "once_cell", "spin 0.5.2", - "untrusted 0.7.1", + "untrusted", "web-sys", "winapi", ] @@ -5967,14 +5848,26 @@ dependencies = [ "webpki 0.22.2", ] +[[package]] +name = "rustls" +version = "0.21.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd8d6c9f025a446bc4d18ad9632e69aec8f287aa84499ee335599fabd20c3fd8" +dependencies = [ + "log", + "ring", + "rustls-webpki", + "sct 0.7.0", +] + [[package]] name = "rustls-native-certs" -version = "0.5.0" +version = "0.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a07b7c1885bd8ed3831c289b7870b13ef46fe0e856d288c30d9cc17d75a2092" +checksum = "a9aace74cb666635c918e9c12bc0d348266037aa8eb599b5cba565709a8dff00" dependencies = [ "openssl-probe", - "rustls 0.19.1", + "rustls-pemfile", "schannel", "security-framework", ] @@ -5988,6 +5881,16 @@ dependencies = [ "base64 0.21.4", ] +[[package]] +name = "rustls-webpki" +version = "0.101.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c7d5dece342910d9ba34d259310cae3e0154b873b35408b787b59bce53d34fe" +dependencies = [ + "ring", + "untrusted", +] + [[package]] name = "rustversion" version = "1.0.14" @@ -6068,7 +5971,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b362b83898e0e69f38515b82ee15aa80636befe47c3b6d3d89a911e78fc228ce" dependencies = [ "ring", - "untrusted 0.7.1", + "untrusted", ] [[package]] @@ -6078,7 +5981,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d53dcdb7c9f8158937a7981b48accfd39a43af418591a5d008c7b22b5e1b7ca4" dependencies = [ "ring", - "untrusted 0.7.1", + "untrusted", ] [[package]] @@ -6628,7 +6531,7 @@ checksum = "cc43eda802856ee82a7555c7b75ceb9e07451741c7a2f5f23d036020e01189d4" dependencies = [ "aes 0.7.5", "arrayref", - "blake2 0.8.1", + "blake2", "bs58 0.4.0", "byteorder", "chacha", @@ -7340,9 +7243,9 @@ dependencies = [ [[package]] name = "tendermint" -version = "0.32.2" +version = "0.34.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f0a7d05cf78524782337f8edd55cbc578d159a16ad4affe2135c92f7dbac7f0" +checksum = "bc2294fa667c8b548ee27a9ba59115472d0a09c2ba255771092a7f1dcf03a789" dependencies = [ "bytes", "digest 0.10.7", @@ -7371,9 +7274,9 @@ dependencies = [ [[package]] name = "tendermint-config" -version = "0.32.2" +version = "0.34.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "71a72dbbea6dde12045d261f2c70c0de039125675e8a026c8d5ad34522756372" +checksum = "5a25dbe8b953e80f3d61789fbdb83bf9ad6c0ef16df5ca6546f49912542cc137" dependencies = [ "flex-error", "serde", @@ -7385,9 +7288,9 @@ dependencies = [ [[package]] name = "tendermint-proto" -version = "0.32.2" +version = "0.34.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0cec054567d16d85e8c3f6a3139963d1a66d9d3051ed545d31562550e9bcc3d" +checksum = "2cc728a4f9e891d71adf66af6ecaece146f9c7a11312288a3107b3e1d6979aaf" dependencies = [ "bytes", "flex-error", @@ -7403,21 +7306,18 @@ dependencies = [ [[package]] name = "tendermint-rpc" -version = "0.32.2" +version = "0.34.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d119d83a130537fc4a98c3c9eb6899ebe857fea4860400a61675bfb5f0b35129" +checksum = "dfbf0a4753b46a190f367337e0163d0b552a2674a6bac54e74f9f2cdcde2969b" dependencies = [ "async-trait", "bytes", "flex-error", "futures", "getrandom 0.2.10", - "http", - "hyper", - "hyper-proxy", - "hyper-rustls", "peg", "pin-project", + "reqwest", "semver 1.0.18", "serde", "serde_bytes", @@ -7599,6 +7499,16 @@ dependencies = [ "webpki 0.22.2", ] +[[package]] +name = "tokio-rustls" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c28327cf380ac148141087fbfb9de9d7bd4e84ab5d2c28fbc911d753de8a7081" +dependencies = [ + "rustls 0.21.7", + "tokio", +] + [[package]] name = "tokio-socks" version = "0.5.1" @@ -7901,12 +7811,6 @@ version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a" -[[package]] -name = "untrusted" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" - [[package]] name = "ureq" version = "2.7.1" @@ -7922,9 +7826,9 @@ dependencies = [ [[package]] name = "url" -version = "2.4.0" +version = "2.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50bff7831e19200a85b17131d085c25d7811bc4e186efdaf54bbd132994a88cb" +checksum = "143b538f18257fac9cad154828a57c6bf5157e1aa604d4816b5995bf6de87ae5" dependencies = [ "form_urlencoded", "idna", @@ -8257,7 +8161,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8e38c0608262c46d4a56202ebabdeb094cef7e560ca7a226c6bf055188aa4ea" dependencies = [ "ring", - "untrusted 0.7.1", + "untrusted", ] [[package]] @@ -8267,7 +8171,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "07ecc0cd7cac091bf682ec5efa18b1cff79d617b84181f38b3951dbe135f607f" dependencies = [ "ring", - "untrusted 0.7.1", + "untrusted", ] [[package]] @@ -8743,7 +8647,7 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2769203cd13a0c6015d515be729c526d041e9cf2c0cc478d57faee85f40c6dcd" dependencies = [ - "nix 0.26.2", + "nix", "winapi", ] @@ -8780,7 +8684,7 @@ dependencies = [ "futures-sink", "futures-util", "hex", - "nix 0.26.2", + "nix", "once_cell", "ordered-stream", "rand 0.8.5", diff --git a/nym-node/src/config/mod.rs b/nym-node/src/config/mod.rs index c8419d1ca99..3b712f2e638 100644 --- a/nym-node/src/config/mod.rs +++ b/nym-node/src/config/mod.rs @@ -1,8 +1,7 @@ // Copyright 2023 - Nym Technologies SA // SPDX-License-Identifier: GPL-3.0-only -use nym_config::defaults::DEFAULT_NYM_NODE_HTTP_PORT; -use nym_wireguard_types::WG_PORT; +use nym_config::defaults::{DEFAULT_NYM_NODE_HTTP_PORT, WG_PORT}; use serde::{Deserialize, Serialize}; use serde_helpers::*; use std::net::{IpAddr, Ipv4Addr, SocketAddr}; diff --git a/nym-vpn/ui/.eslintrc.cjs b/nym-vpn/ui/.eslintrc.cjs index 5c7c3e4c953..ff65dd7c035 100644 --- a/nym-vpn/ui/.eslintrc.cjs +++ b/nym-vpn/ui/.eslintrc.cjs @@ -4,18 +4,47 @@ module.exports = { 'plugin:@typescript-eslint/recommended', 'plugin:react/recommended', 'plugin:react/jsx-runtime', + 'plugin:jsx-a11y/recommended', 'plugin:react-hooks/recommended', + 'plugin:import/typescript', 'prettier', ], parser: '@typescript-eslint/parser', parserOptions: { project: './tsconfig.json', }, - plugins: ['@typescript-eslint'], + plugins: ['@typescript-eslint', 'import'], root: true, settings: { react: { version: 'detect', }, + // https://github.com/import-js/eslint-import-resolver-typescript#configuration + 'import/parsers': { + '@typescript-eslint/parser': ['.ts', '.tsx'], + }, + 'import/resolver': { + typescript: { + alwaysTryTypes: true, // always try to resolve types under `@types` directory even it doesn't contain any source code, like `@types/unist` + project: 'tsconfig.json', + }, + }, + }, + rules: { + 'sort-imports': [ + 'error', + { + ignoreDeclarationSort: true, + allowSeparatedGroups: true, + }, + ], + 'import/first': 'error', + 'import/order': [ + 'error', + { + groups: ['builtin', 'external', 'parent', 'sibling', 'index'], + }, + ], + 'import/extensions': ['error', 'never', { json: 'always', svg: 'always' }], }, }; diff --git a/nym-vpn/ui/index.html b/nym-vpn/ui/index.html index f77d86eb69c..a548f6417f6 100644 --- a/nym-vpn/ui/index.html +++ b/nym-vpn/ui/index.html @@ -1,5 +1,5 @@ - + @@ -8,7 +8,7 @@ -
+
diff --git a/nym-vpn/ui/package.json b/nym-vpn/ui/package.json index 3520196c5a3..cd6bbc3034d 100644 --- a/nym-vpn/ui/package.json +++ b/nym-vpn/ui/package.json @@ -18,10 +18,12 @@ "tauri": "tauri" }, "dependencies": { + "@headlessui/react": "^1.7.17", + "@headlessui/tailwindcss": "^0.2.0", "@mui/base": "^5.0.0-beta.24", - "@mui/material": "^5.14.14", "@tauri-apps/api": "^1.5.0", "clsx": "^2.0.0", + "dayjs": "^1.11.10", "i18next": "^23.7.6", "react": "^18.2.0", "react-dom": "^18.2.0", @@ -39,6 +41,9 @@ "autoprefixer": "^10.4.16", "eslint": "^8.52.0", "eslint-config-prettier": "^9.0.0", + "eslint-import-resolver-typescript": "^3.6.1", + "eslint-plugin-import": "^2.29.0", + "eslint-plugin-jsx-a11y": "^6.8.0", "eslint-plugin-react": "^7.33.2", "eslint-plugin-react-hooks": "^4.6.0", "postcss": "^8.4.31", diff --git a/nym-vpn/ui/src-tauri/Cargo.lock b/nym-vpn/ui/src-tauri/Cargo.lock index d17f418e805..9e8b65c41eb 100644 --- a/nym-vpn/ui/src-tauri/Cargo.lock +++ b/nym-vpn/ui/src-tauri/Cargo.lock @@ -1811,6 +1811,7 @@ dependencies = [ "tauri", "tauri-build", "thiserror", + "time", "tokio", "toml 0.8.5", "tracing", diff --git a/nym-vpn/ui/src-tauri/Cargo.toml b/nym-vpn/ui/src-tauri/Cargo.toml index d508a21cbfb..0edbe87d18d 100644 --- a/nym-vpn/ui/src-tauri/Cargo.toml +++ b/nym-vpn/ui/src-tauri/Cargo.toml @@ -11,7 +11,7 @@ edition = "2021" tauri-build = { version = "1.5", features = [] } [dependencies] -tauri = { version = "1.5.2", features = [ "updater", "shell-open"] } +tauri = { version = "1.5.2", features = ["updater", "shell-open"] } tokio = { version = "1.33", features = ["rt", "sync", "time", "fs"] } serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" @@ -23,6 +23,7 @@ thiserror = "1.0" ts-rs = { version = "7.0.0", features = ["chrono-impl"] } once_cell = "1.18.0" toml = "0.8.5" +time = "0.3.9" [features] # this feature is used for production builds or when `devPath` points to the filesystem diff --git a/nym-vpn/ui/src-tauri/src/commands/app_data.rs b/nym-vpn/ui/src-tauri/src/commands/app_data.rs new file mode 100644 index 00000000000..b586fb0d0e2 --- /dev/null +++ b/nym-vpn/ui/src-tauri/src/commands/app_data.rs @@ -0,0 +1,69 @@ +use tauri::State; +use tracing::{debug, instrument}; + +use crate::{ + error::{CmdError, CmdErrorSource}, + fs::data::{AppData, UiTheme}, + states::SharedAppData, +}; + +#[instrument] +#[tauri::command] +pub async fn set_app_data( + state: State<'_, SharedAppData>, + data: Option, +) -> Result<(), CmdError> { + debug!("set_app_data"); + let mut app_data_store = state.lock().await; + if let Some(data) = data { + app_data_store.data = data; + } + app_data_store + .write() + .await + .map_err(|e| CmdError::new(CmdErrorSource::InternalError, e.to_string()))?; + + Ok(()) +} + +#[instrument] +#[tauri::command] +pub async fn get_app_data( + state: State<'_, SharedAppData>, + data: Option, +) -> Result { + debug!("get_app_data"); + let mut app_data_store = state.lock().await; + if let Some(data) = data { + app_data_store.data = data; + } + let data = app_data_store + .read() + .await + .map_err(|e| CmdError::new(CmdErrorSource::InternalError, e.to_string()))?; + + Ok(data) +} + +#[instrument(skip_all)] +#[tauri::command] +pub async fn set_ui_theme( + data_state: State<'_, SharedAppData>, + theme: UiTheme, +) -> Result<(), CmdError> { + debug!("set_ui_theme"); + + // save the selected UI theme to disk + let mut app_data_store = data_state.lock().await; + let mut app_data = app_data_store + .read() + .await + .map_err(|e| CmdError::new(CmdErrorSource::InternalError, e.to_string()))?; + app_data.ui_theme = Some(theme); + app_data_store.data = app_data; + app_data_store + .write() + .await + .map_err(|e| CmdError::new(CmdErrorSource::InternalError, e.to_string()))?; + Ok(()) +} diff --git a/nym-vpn/ui/src-tauri/src/commands/connection.rs b/nym-vpn/ui/src-tauri/src/commands/connection.rs index 7251ee62fb3..944337eb53d 100644 --- a/nym-vpn/ui/src-tauri/src/commands/connection.rs +++ b/nym-vpn/ui/src-tauri/src/commands/connection.rs @@ -1,26 +1,48 @@ use std::time::Duration; use tauri::{Manager, State}; +use time::OffsetDateTime; use tokio::time::sleep; -use tracing::{debug, instrument, trace}; +use tracing::{debug, error, instrument, trace}; use crate::{ - error::CommandError, - states::{app::ConnectionState, SharedAppState}, + error::{CmdError, CmdErrorSource}, + states::{ + app::{ConnectionState, VpnMode}, + SharedAppData, SharedAppState, + }, }; -const EVENT_CONNECTION: &str = "connection-state"; +const EVENT_CONNECTION_STATE: &str = "connection-state"; +const EVENT_CONNECTION_PROGRESS: &str = "connection-progress"; #[derive(Clone, serde::Serialize)] -struct EventPayload { +struct ConnectionEventPayload { state: ConnectionState, + error: Option, + start_time: Option, // unix timestamp in seconds +} + +impl ConnectionEventPayload { + fn new(state: ConnectionState, error: Option, start_time: Option) -> Self { + Self { + state, + error, + start_time, + } + } +} + +#[derive(Clone, serde::Serialize)] +struct ProgressEventPayload { + message: String, } #[instrument(skip_all)] #[tauri::command] pub async fn get_connection_state( state: State<'_, SharedAppState>, -) -> Result { +) -> Result { debug!("get_connection_state"); let app_state = state.lock().await; Ok(app_state.state) @@ -31,14 +53,14 @@ pub async fn get_connection_state( pub async fn connect( app: tauri::AppHandle, state: State<'_, SharedAppState>, -) -> Result { +) -> Result { debug!("connect"); let mut app_state = state.lock().await; let ConnectionState::Disconnected = app_state.state else { - return Err(CommandError::CallerError(format!( - "cannot connect from state {:?}", - app_state.state - ))); + return Err(CmdError::new( + CmdErrorSource::CallerError, + format!("cannot connect from state {:?}", app_state.state), + )); }; // switch to "Connecting" state @@ -46,27 +68,53 @@ pub async fn connect( // unlock the mutex drop(app_state); app.emit_all( - EVENT_CONNECTION, - EventPayload { - state: ConnectionState::Connecting, - }, + EVENT_CONNECTION_STATE, + ConnectionEventPayload::new(ConnectionState::Connecting, None, None), ) .ok(); // TODO fake some delay to establish connection let app_state_cloned = state.inner().clone(); let task = tokio::spawn(async move { - sleep(Duration::from_secs(2)).await; - trace!("connected"); - app_state_cloned.lock().await.state = ConnectionState::Connected; - debug!("sending event [{}]: connected", EVENT_CONNECTION); app.emit_all( - EVENT_CONNECTION, - EventPayload { - state: ConnectionState::Connected, + EVENT_CONNECTION_PROGRESS, + ProgressEventPayload { + message: "Connecting to the network…".to_string(), }, ) .ok(); + sleep(Duration::from_millis(300)).await; + app.emit_all( + EVENT_CONNECTION_PROGRESS, + ProgressEventPayload { + message: "Fetching nodes and gateways…".to_string(), + }, + ) + .ok(); + sleep(Duration::from_millis(400)).await; + app.emit_all( + EVENT_CONNECTION_PROGRESS, + ProgressEventPayload { + message: "Done".to_string(), + }, + ) + .ok(); + sleep(Duration::from_millis(200)).await; + trace!("connected"); + let now = OffsetDateTime::now_utc(); + let mut state = app_state_cloned.lock().await; + state.state = ConnectionState::Connected; + state.connection_start_time = Some(now); + debug!("sending event [{}]: connected", EVENT_CONNECTION_STATE); + app.emit_all( + EVENT_CONNECTION_STATE, + ConnectionEventPayload::new( + ConnectionState::Connected, + None, + Some(now.unix_timestamp()), + ), + ) + .ok(); }); let _ = task.await; @@ -80,14 +128,14 @@ pub async fn connect( pub async fn disconnect( app: tauri::AppHandle, state: State<'_, SharedAppState>, -) -> Result { +) -> Result { debug!("disconnect"); let mut app_state = state.lock().await; let ConnectionState::Connected = app_state.state else { - return Err(CommandError::CallerError(format!( - "cannot disconnect from state {:?}", - app_state.state - ))); + return Err(CmdError::new( + CmdErrorSource::CallerError, + format!("cannot disconnect from state {:?}", app_state.state), + )); }; // switch to "Disconnecting" state @@ -95,25 +143,25 @@ pub async fn disconnect( // unlock the mutex drop(app_state); app.emit_all( - EVENT_CONNECTION, - EventPayload { - state: ConnectionState::Disconnecting, - }, + EVENT_CONNECTION_STATE, + ConnectionEventPayload::new(ConnectionState::Disconnecting, None, None), ) .ok(); // TODO fake some delay to confirm disconnection let app_state_cloned = state.inner().clone(); let task = tokio::spawn(async move { - sleep(Duration::from_secs(2)).await; + sleep(Duration::from_secs(1)).await; trace!("disconnected"); - app_state_cloned.lock().await.state = ConnectionState::Disconnected; - debug!("sending event [{}]: disconnected", EVENT_CONNECTION); + + let mut state = app_state_cloned.lock().await; + state.state = ConnectionState::Disconnected; + state.connection_start_time = None; + + debug!("sending event [{}]: disconnected", EVENT_CONNECTION_STATE); app.emit_all( - EVENT_CONNECTION, - EventPayload { - state: ConnectionState::Disconnected, - }, + EVENT_CONNECTION_STATE, + ConnectionEventPayload::new(ConnectionState::Disconnected, None, None), ) .ok(); }); @@ -123,3 +171,47 @@ pub async fn disconnect( let app_state = state.lock().await; Ok(app_state.state) } + +#[instrument(skip_all)] +#[tauri::command] +pub async fn get_connection_start_time( + state: State<'_, SharedAppState>, +) -> Result, CmdError> { + debug!("get_connection_start_time"); + let app_state = state.lock().await; + Ok(app_state.connection_start_time.map(|t| t.unix_timestamp())) +} + +#[instrument(skip_all)] +#[tauri::command] +pub async fn set_vpn_mode( + app_state: State<'_, SharedAppState>, + data_state: State<'_, SharedAppData>, + mode: VpnMode, +) -> Result<(), CmdError> { + debug!("set_vpn_mode"); + + let mut state = app_state.lock().await; + + if let ConnectionState::Disconnected = state.state { + } else { + let err_message = format!("cannot change vpn mode from state {:?}", state.state); + error!(err_message); + return Err(CmdError::new(CmdErrorSource::CallerError, err_message)); + } + state.vpn_mode = mode.clone(); + + // save the selected mode to disk + let mut app_data_store = data_state.lock().await; + let mut app_data = app_data_store + .read() + .await + .map_err(|e| CmdError::new(CmdErrorSource::InternalError, e.to_string()))?; + app_data.vpn_mode = Some(mode); + app_data_store.data = app_data; + app_data_store + .write() + .await + .map_err(|e| CmdError::new(CmdErrorSource::InternalError, e.to_string()))?; + Ok(()) +} diff --git a/nym-vpn/ui/src-tauri/src/commands/mod.rs b/nym-vpn/ui/src-tauri/src/commands/mod.rs index c28bd8ce475..917050e1160 100644 --- a/nym-vpn/ui/src-tauri/src/commands/mod.rs +++ b/nym-vpn/ui/src-tauri/src/commands/mod.rs @@ -1,11 +1,2 @@ -use tracing::{debug, instrument}; - +pub mod app_data; pub mod connection; -pub mod settings; - -#[instrument] -#[tauri::command] -pub fn greet(name: &str) -> String { - debug!("greet"); - format!("Hello, {}! You've been greeted from Rust!", name) -} diff --git a/nym-vpn/ui/src-tauri/src/commands/settings.rs b/nym-vpn/ui/src-tauri/src/commands/settings.rs deleted file mode 100644 index ee9701ea9e6..00000000000 --- a/nym-vpn/ui/src-tauri/src/commands/settings.rs +++ /dev/null @@ -1,32 +0,0 @@ -use tauri::State; -use tracing::{debug, instrument}; - -use crate::{error::CommandError, fs::data::AppData, states::SharedAppData}; - -#[instrument] -#[tauri::command] -pub async fn save_user_settings(state: State<'_, SharedAppData>) -> Result<(), CommandError> { - debug!("save_user_settings"); - let app_data = state.lock().await; - app_data - .write() - .map_err(|e| CommandError::InternalError(e.to_string()))?; - - Ok(()) -} - -#[instrument] -#[tauri::command] -pub async fn set_user_settings( - state: State<'_, SharedAppData>, - settings: AppData, -) -> Result<(), CommandError> { - debug!("set_user_settings"); - let mut app_data = state.lock().await; - app_data.data = settings; - app_data - .write() - .map_err(|e| CommandError::InternalError(e.to_string()))?; - - Ok(()) -} diff --git a/nym-vpn/ui/src-tauri/src/error.rs b/nym-vpn/ui/src-tauri/src/error.rs index 34f57b66b2f..e4be67cc806 100644 --- a/nym-vpn/ui/src-tauri/src/error.rs +++ b/nym-vpn/ui/src-tauri/src/error.rs @@ -1,12 +1,39 @@ +use std::fmt::{self, Display}; + use serde::{Deserialize, Serialize}; use thiserror::Error; +use ts_rs::TS; -#[derive(Error, Debug, Serialize, Deserialize)] -pub enum CommandError { - #[error("internal error: `{0}`")] - InternalError(String), - #[error("caller error: `{0}`")] - CallerError(String), +#[derive(Error, Debug, Serialize, Deserialize, TS)] +#[ts(export)] +pub enum CmdErrorSource { + #[error("internal error")] + InternalError, + #[error("caller error")] + CallerError, #[error("unknown error")] Unknown, } + +#[derive(Error, Debug, Serialize, Deserialize, TS)] +#[ts(export)] +pub struct CmdError { + #[source] + pub source: CmdErrorSource, + pub message: String, +} + +impl CmdError { + pub fn new(error: CmdErrorSource, message: String) -> Self { + Self { + message, + source: error, + } + } +} + +impl Display for CmdError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}: {}", self.source, self.message) + } +} diff --git a/nym-vpn/ui/src-tauri/src/fs/data.rs b/nym-vpn/ui/src-tauri/src/fs/data.rs index cbc177b281b..18df75cb14d 100644 --- a/nym-vpn/ui/src-tauri/src/fs/data.rs +++ b/nym-vpn/ui/src-tauri/src/fs/data.rs @@ -1,13 +1,24 @@ use serde::{Deserialize, Serialize}; +use ts_rs::TS; -use crate::states::app::{NodeConfig, PrivacyMode}; +use crate::states::app::{NodeConfig, VpnMode}; -#[derive(Default, Serialize, Deserialize, Debug, Clone)] +#[derive(Default, Serialize, Deserialize, Debug, Clone, TS)] +#[ts(export)] +pub enum UiTheme { + Dark, + #[default] + Light, +} + +#[derive(Default, Serialize, Deserialize, Debug, Clone, TS)] +#[ts(export)] pub struct AppData { pub monitoring: Option, pub autoconnect: Option, pub killswitch: Option, - pub privacy_mode: Option, + pub ui_theme: Option, + pub vpn_mode: Option, pub entry_node: Option, pub exit_node: Option, } diff --git a/nym-vpn/ui/src-tauri/src/fs/storage.rs b/nym-vpn/ui/src-tauri/src/fs/storage.rs index 70a2e6287be..cd718a52d6f 100644 --- a/nym-vpn/ui/src-tauri/src/fs/storage.rs +++ b/nym-vpn/ui/src-tauri/src/fs/storage.rs @@ -1,7 +1,8 @@ use anyhow::{anyhow, Context, Result}; use serde::{de::DeserializeOwned, Serialize}; -use std::{fmt, fs, path::PathBuf, str}; +use std::{fmt, path::PathBuf, str}; use tauri::api::path::data_dir; +use tokio::fs; use tracing::{debug, error, instrument}; #[derive(Debug, Clone)] @@ -15,14 +16,14 @@ where pub full_path: PathBuf, } -fn create_directory_path(path: &PathBuf) -> Result<()> { +async fn create_directory_path(path: &PathBuf) -> Result<()> { let mut data_dir = data_dir().ok_or(anyhow!( "Failed to retrieve data directory {:?}", path.display() ))?; data_dir.push(path); - fs::create_dir_all(&data_dir).context(format!( + fs::create_dir_all(&data_dir).await.context(format!( "Failed to create data directory {}", data_dir.display() )) @@ -45,12 +46,18 @@ where } #[instrument] - pub fn read(&self) -> Result { + pub async fn read(&self) -> Result { // create the full directory path if it is missing - create_directory_path(&self.dir_path)?; + create_directory_path(&self.dir_path).await?; + + // check if the file exists, if not create it + match fs::try_exists(&self.full_path).await { + Ok(true) => {} + _ => fs::write(&self.full_path, []).await?, + } debug!("reading stored data from {}", self.full_path.display()); - let content = fs::read(&self.full_path).context(format!( + let content = fs::read(&self.full_path).await.context(format!( "Failed to read data from {}", self.full_path.display() ))?; @@ -62,23 +69,23 @@ where } #[instrument] - pub fn write(&self) -> Result<()> { + pub async fn write(&self) -> Result<()> { // create the full directory path if it is missing - create_directory_path(&self.dir_path)?; + create_directory_path(&self.dir_path).await?; debug!("writing data to {}", self.full_path.display()); let toml = toml::to_string(&self.data)?; - fs::write(&self.full_path, toml)?; + fs::write(&self.full_path, toml).await?; Ok(()) } #[instrument] - pub fn clear(&self) -> Result<()> { + pub async fn clear(&self) -> Result<()> { // create the full directory path if it is missing - create_directory_path(&self.dir_path)?; + create_directory_path(&self.dir_path).await?; debug!("clearing data {}", self.full_path.display()); - fs::write(&self.full_path, vec![])?; + fs::write(&self.full_path, vec![]).await?; Ok(()) } } diff --git a/nym-vpn/ui/src-tauri/src/main.rs b/nym-vpn/ui/src-tauri/src/main.rs index 12d474f40ec..c12ba8d6c31 100644 --- a/nym-vpn/ui/src-tauri/src/main.rs +++ b/nym-vpn/ui/src-tauri/src/main.rs @@ -51,12 +51,14 @@ fn main() -> Result<()> { Ok(()) }) .invoke_handler(tauri::generate_handler![ - greet, + connection::set_vpn_mode, connection::get_connection_state, connection::connect, connection::disconnect, - settings::save_user_settings, - settings::set_user_settings, + connection::get_connection_start_time, + app_data::get_app_data, + app_data::set_app_data, + app_data::set_ui_theme, ]) .run(tauri::generate_context!()) .expect("error while running tauri application"); diff --git a/nym-vpn/ui/src-tauri/src/states/app.rs b/nym-vpn/ui/src-tauri/src/states/app.rs index 6354409d92d..8ef242a24b6 100644 --- a/nym-vpn/ui/src-tauri/src/states/app.rs +++ b/nym-vpn/ui/src-tauri/src/states/app.rs @@ -1,7 +1,9 @@ use serde::{Deserialize, Serialize}; +use time::OffsetDateTime; use ts_rs::TS; -#[derive(Debug, Serialize, Deserialize, Clone)] +#[derive(Debug, Serialize, Deserialize, Clone, TS)] +#[ts(export)] pub struct NodeConfig { pub id: String, pub country: String, @@ -15,16 +17,15 @@ pub enum ConnectionState { Disconnected, Connecting, Disconnecting, - Error, + Unknown, } #[derive(Default, Debug, Serialize, Deserialize, TS, Clone)] #[ts(export)] -pub enum PrivacyMode { - High, - Medium, +pub enum VpnMode { + Mixnet, #[default] - Low, + TwoHop, } #[derive(Debug, Serialize, Deserialize, TS)] @@ -37,8 +38,10 @@ pub struct TunnelConfig { #[derive(Debug, Default)] pub struct AppState { pub state: ConnectionState, - pub privacy_mode: PrivacyMode, + pub error: Option, + pub vpn_mode: VpnMode, pub entry_node: Option, pub exit_node: Option, pub tunnel: Option, + pub connection_start_time: Option, } diff --git a/nym-vpn/ui/src-tauri/tauri.conf.json b/nym-vpn/ui/src-tauri/tauri.conf.json index c118ebbd257..7c565fd47de 100644 --- a/nym-vpn/ui/src-tauri/tauri.conf.json +++ b/nym-vpn/ui/src-tauri/tauri.conf.json @@ -46,8 +46,8 @@ "fullscreen": false, "resizable": true, "title": "NymVPN", - "width": 400, - "height": 600 + "width": 440, + "height": 920 } ] } diff --git a/nym-vpn/ui/src/App.tsx b/nym-vpn/ui/src/App.tsx index 68d4109aee9..273d7786f5b 100644 --- a/nym-vpn/ui/src/App.tsx +++ b/nym-vpn/ui/src/App.tsx @@ -1,30 +1,20 @@ -import { createBrowserRouter, RouterProvider } from 'react-router-dom'; -import { Home, Settings, Error, PageLayout } from './pages'; +import { RouterProvider } from 'react-router-dom'; +import dayjs from 'dayjs'; +import { useTranslation } from 'react-i18next'; +import router from './router'; import { MainStateProvider } from './state'; import './i18n/config'; - -const router = createBrowserRouter([ - { - element: , - children: [ - { - path: '/', - element: , - errorElement: , - }, - { - path: '/settings', - element: , - errorElement: , - }, - ], - }, -]); +import { ThemeSetter } from './ui'; function App() { + const { i18n } = useTranslation(); + dayjs.locale(i18n.language); + return ( - + + + ); } diff --git a/nym-vpn/ui/src/assets/.gitkeep b/nym-vpn/ui/src/assets/.gitkeep deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/nym-vpn/ui/src/assets/fonts/MaterialSymbolsOutlined.woff2 b/nym-vpn/ui/src/assets/fonts/MaterialSymbolsOutlined.woff2 new file mode 100644 index 00000000000..93b97c722ed Binary files /dev/null and b/nym-vpn/ui/src/assets/fonts/MaterialSymbolsOutlined.woff2 differ diff --git a/nym-vpn/ui/src/constants.ts b/nym-vpn/ui/src/constants.ts index d061f363aa5..c217fcdc07f 100644 --- a/nym-vpn/ui/src/constants.ts +++ b/nym-vpn/ui/src/constants.ts @@ -1 +1,10 @@ +export const routes = { + root: '/', + settings: '/settings', + entryNodeLocation: '/entry-node-location', + exitNodeLocation: '/exit-node-location', +} as const; + +export const AppName = 'NymVPN'; export const ConnectionEvent = 'connection-state'; +export const ProgressEvent = 'connection-progress'; diff --git a/nym-vpn/ui/src/contexts/main.ts b/nym-vpn/ui/src/contexts/main.ts index 3329d464b43..cc9cb74eaf3 100644 --- a/nym-vpn/ui/src/contexts/main.ts +++ b/nym-vpn/ui/src/contexts/main.ts @@ -1,6 +1,6 @@ import { createContext, useContext } from 'react'; +import { StateAction, initialState } from '../state'; import { AppState } from '../types'; -import { initialState, StateAction } from '../state'; export const MainStateContext = createContext(initialState); export const MainDispatchContext = diff --git a/nym-vpn/ui/src/dev/setup.ts b/nym-vpn/ui/src/dev/setup.ts index 8bb1a168380..b0e8edd0927 100644 --- a/nym-vpn/ui/src/dev/setup.ts +++ b/nym-vpn/ui/src/dev/setup.ts @@ -1,6 +1,6 @@ import { mockIPC, mockWindows } from '@tauri-apps/api/mocks'; -import { ConnectionState } from '../types'; import { emit } from '@tauri-apps/api/event'; +import { AppDataFromBackend, ConnectionState } from '../types'; import { ConnectionEvent } from '../constants'; export function mockTauriIPC() { @@ -32,5 +32,18 @@ export function mockTauriIPC() { setTimeout(() => resolve('Disconnected'), 2000), ); } + if (cmd === 'get_app_data') { + return new Promise((resolve) => + resolve({ + monitoring: false, + autoconnect: false, + killswitch: false, + ui_theme: 'Dark', + vpn_mode: 'TwoHop', + entry_node: null, + exit_node: null, + }), + ); + } }); } diff --git a/nym-vpn/ui/src/i18n/config.ts b/nym-vpn/ui/src/i18n/config.ts index 510ec19020e..2acb27fb6c0 100644 --- a/nym-vpn/ui/src/i18n/config.ts +++ b/nym-vpn/ui/src/i18n/config.ts @@ -1,17 +1,24 @@ import i18n from 'i18next'; import { initReactI18next } from 'react-i18next'; -import main from './en/main.json'; +import common from './en/common.json'; +import home from './en/home.json'; +import settings from './en/settings.json'; +import nodeLocation from './en/node-location.json'; -const defaultNS = 'main'; +const defaultNS = 'common'; i18n.use(initReactI18next).init({ lng: 'en', debug: import.meta.env.DEV, resources: { en: { - main, + common, + home, + settings, + nodeLocation, }, }, + ns: ['common', 'home', 'settings', 'nodeLocation'], defaultNS, interpolation: { diff --git a/nym-vpn/ui/src/i18n/en/common.json b/nym-vpn/ui/src/i18n/en/common.json new file mode 100644 index 00000000000..824ef148fbf --- /dev/null +++ b/nym-vpn/ui/src/i18n/en/common.json @@ -0,0 +1,7 @@ +{ + "connect": "Connect", + "disconnect": "Disconnect", + "first-hop-selection": "First hop selection", + "last-hop-selection": "Last hop selection", + "settings": "Settings" +} diff --git a/nym-vpn/ui/src/i18n/en/home.json b/nym-vpn/ui/src/i18n/en/home.json new file mode 100644 index 00000000000..56929bc48aa --- /dev/null +++ b/nym-vpn/ui/src/i18n/en/home.json @@ -0,0 +1,27 @@ +{ + "connect": "Connect", + "disconnect": "Disconnect", + "status": { + "connected": "Connected", + "disconnected": "Disconnected", + "connecting": "Connecting…", + "disconnecting": "Disconnecting…", + "unknown": "Unknown" + }, + "connecting-message": "Establishing connection", + "connection-time": "Connection time", + "select-network-label": "Select network", + "select-node-title": "Connect to", + "mixnet-mode": { + "title": "5-hop mixnet", + "desc": "Best for payments, emails, messages" + }, + "twohop-mode": { + "title": "2-hop WireGuard", + "desc": "Best for browsing, streaming, sharing" + }, + "last-node-select": { + "label": "Last hop", + "text": "Quick connect ({{country}})" + } +} diff --git a/nym-vpn/ui/src/i18n/en/main.json b/nym-vpn/ui/src/i18n/en/main.json deleted file mode 100644 index 8cd9e27b682..00000000000 --- a/nym-vpn/ui/src/i18n/en/main.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "connect": "Connect", - "disconnect": "Disconnect" -} diff --git a/nym-vpn/ui/src/i18n/en/node-location.json b/nym-vpn/ui/src/i18n/en/node-location.json new file mode 100644 index 00000000000..0967ef424bc --- /dev/null +++ b/nym-vpn/ui/src/i18n/en/node-location.json @@ -0,0 +1 @@ +{} diff --git a/nym-vpn/ui/src/i18n/en/settings.json b/nym-vpn/ui/src/i18n/en/settings.json new file mode 100644 index 00000000000..0967ef424bc --- /dev/null +++ b/nym-vpn/ui/src/i18n/en/settings.json @@ -0,0 +1 @@ +{} diff --git a/nym-vpn/ui/src/main.tsx b/nym-vpn/ui/src/main.tsx index c15dabc8ad5..f0292032d0f 100644 --- a/nym-vpn/ui/src/main.tsx +++ b/nym-vpn/ui/src/main.tsx @@ -1,5 +1,8 @@ import React from 'react'; import ReactDOM from 'react-dom/client'; +import dayjs from 'dayjs'; +import relativeTime from 'dayjs/plugin/relativeTime'; +import duration from 'dayjs/plugin/duration'; import App from './App'; import { mockTauriIPC } from './dev/setup'; import './styles.css'; @@ -9,6 +12,9 @@ if (import.meta.env.MODE === 'dev-browser') { mockTauriIPC(); } +dayjs.extend(relativeTime); +dayjs.extend(duration); + ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render( diff --git a/nym-vpn/ui/src/pages/error.tsx b/nym-vpn/ui/src/pages/Error.tsx similarity index 91% rename from nym-vpn/ui/src/pages/error.tsx rename to nym-vpn/ui/src/pages/Error.tsx index bd379f21167..f6b70714d03 100644 --- a/nym-vpn/ui/src/pages/error.tsx +++ b/nym-vpn/ui/src/pages/Error.tsx @@ -5,7 +5,7 @@ type routerErrorType = { message: string; }; -export default function ErrorPage() { +export default function Error() { const error: routerErrorType = useRouteError() as unknown as routerErrorType; console.error(error); diff --git a/nym-vpn/ui/src/pages/NavLayout.tsx b/nym-vpn/ui/src/pages/NavLayout.tsx new file mode 100644 index 00000000000..2fba78c3386 --- /dev/null +++ b/nym-vpn/ui/src/pages/NavLayout.tsx @@ -0,0 +1,13 @@ +import { Outlet } from 'react-router-dom'; +import { TopBar } from '../ui'; + +function NavLayout() { + return ( +
+ + +
+ ); +} + +export default NavLayout; diff --git a/nym-vpn/ui/src/pages/NodeLocation.tsx b/nym-vpn/ui/src/pages/NodeLocation.tsx new file mode 100644 index 00000000000..2c55ddd30b1 --- /dev/null +++ b/nym-vpn/ui/src/pages/NodeLocation.tsx @@ -0,0 +1,17 @@ +import { useTranslation } from 'react-i18next'; + +type Props = { + node: 'entry' | 'exit'; +}; + +function NodeLocation({ node }: Props) { + const { t } = useTranslation(); + + return ( +
+ {node === 'entry' ? t('fist-hop-selection') : t('last-hop-selection')} +
+ ); +} + +export default NodeLocation; diff --git a/nym-vpn/ui/src/pages/home.tsx b/nym-vpn/ui/src/pages/home.tsx deleted file mode 100644 index 50d43e8f2d7..00000000000 --- a/nym-vpn/ui/src/pages/home.tsx +++ /dev/null @@ -1,41 +0,0 @@ -import { useTranslation } from 'react-i18next'; -import { invoke } from '@tauri-apps/api'; -import { useMainDispatch, useMainState } from '../contexts'; -import { StateDispatch } from '../types'; - -function Home() { - const state = useMainState(); - const dispatch = useMainDispatch() as StateDispatch; - - const { t } = useTranslation(); - - const handleClick = async () => { - if (state.state === 'Connected') { - dispatch({ type: 'disconnect' }); - invoke('disconnect').then((result) => { - console.log(result); - }); - } else if (state.state === 'Disconnected') { - dispatch({ type: 'connect' }); - invoke('connect').then((result) => { - console.log(result); - }); - } - }; - - return ( -
-

NymVPN

- connection state: {state.state} - {state.loading ? ( - 'loading…' - ) : ( - - )} -
- ); -} - -export default Home; diff --git a/nym-vpn/ui/src/pages/home/ConnectionStatus.tsx b/nym-vpn/ui/src/pages/home/ConnectionStatus.tsx new file mode 100644 index 00000000000..0da9232f4a9 --- /dev/null +++ b/nym-vpn/ui/src/pages/home/ConnectionStatus.tsx @@ -0,0 +1,84 @@ +import clsx from 'clsx'; +import { useTranslation } from 'react-i18next'; +import { ConnectionState } from '../../types'; +import { useMainState } from '../../contexts'; +import ConnectionTimer from './ConnectionTimer'; + +function ConnectionStatus() { + const state = useMainState(); + + const { t } = useTranslation('home'); + const statusBadgeDynStyles = { + Connected: [ + 'bg-blanc-nacre-icicle', + 'text-vert-menthe', + 'dark:bg-baltic-sea-quartzite', + ], + Disconnected: [ + 'bg-blanc-nacre-platinum', + 'text-coal-mine-light', + 'dark:bg-baltic-sea-oil', + 'dark:text-coal-mine-dark', + ], + Connecting: [ + 'bg-blanc-nacre-platinum', + 'text-baltic-sea', + 'dark:bg-baltic-sea-oil', + 'dark:text-white', + ], + Disconnecting: [ + 'bg-blanc-nacre-platinum', + 'text-baltic-sea', + 'dark:bg-baltic-sea-oil', + 'dark:text-white', + ], + Unknown: [ + 'bg-blanc-nacre-platinum', + 'text-coal-mine-light', + 'dark:bg-baltic-sea-oil', + 'dark:text-coal-mine-dark', + ], + }; + + const getStatusText = (state: ConnectionState) => { + switch (state) { + case 'Connected': + return t('status.connected'); + case 'Disconnected': + return t('status.disconnected'); + case 'Connecting': + return t('status.connecting'); + case 'Disconnecting': + return t('status.disconnecting'); + case 'Unknown': + return t('status.unknown'); + } + }; + return ( +
+
+
+ {getStatusText(state.state)} +
+
+
+ {state.loading && state.progressMessages.length > 0 && ( +

+ {state.progressMessages[state.progressMessages.length - 1]} +

+ )} + {state.state === 'Connected' && } + {state.error && ( +

{state.error}

+ )} +
+
+ ); +} + +export default ConnectionStatus; diff --git a/nym-vpn/ui/src/pages/home/ConnectionTimer.tsx b/nym-vpn/ui/src/pages/home/ConnectionTimer.tsx new file mode 100644 index 00000000000..bc06d93102b --- /dev/null +++ b/nym-vpn/ui/src/pages/home/ConnectionTimer.tsx @@ -0,0 +1,41 @@ +import { useEffect, useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import dayjs from 'dayjs'; +import { useMainState } from '../../contexts'; + +function ConnectionTimer() { + const { sessionStartDate } = useMainState(); + const [connectionTime, setConnectionTime] = useState('00:00:00'); + const { t } = useTranslation('home'); + + useEffect(() => { + if (!sessionStartDate) { + return; + } + + const elapsed = dayjs.duration(dayjs().diff(sessionStartDate)); + setConnectionTime(elapsed.format('HH:mm:ss')); + + const interval = setInterval(() => { + const elapsed = dayjs.duration(dayjs().diff(sessionStartDate)); + setConnectionTime(elapsed.format('HH:mm:ss')); + }, 500); + + return () => { + clearInterval(interval); + }; + }, [sessionStartDate]); + + return ( +
+

+ {t('connection-time')} +

+

+ {connectionTime} +

+
+ ); +} + +export default ConnectionTimer; diff --git a/nym-vpn/ui/src/pages/home/Home.tsx b/nym-vpn/ui/src/pages/home/Home.tsx new file mode 100644 index 00000000000..cc53da9df3b --- /dev/null +++ b/nym-vpn/ui/src/pages/home/Home.tsx @@ -0,0 +1,79 @@ +import { useTranslation } from 'react-i18next'; +import { invoke } from '@tauri-apps/api'; +import clsx from 'clsx'; +import { Button } from '@mui/base'; +import { useMainDispatch, useMainState } from '../../contexts'; +import { ConnectionState, StateDispatch } from '../../types'; +import NetworkModeSelect from './NetworkModeSelect'; +import ConnectionStatus from './ConnectionStatus'; + +function Home() { + const state = useMainState(); + const dispatch = useMainDispatch() as StateDispatch; + + const { t } = useTranslation('home'); + + const handleClick = async () => { + if (state.state === 'Connected') { + dispatch({ type: 'disconnect' }); + invoke('disconnect').then((result) => { + console.log(result); + }); + } else if (state.state === 'Disconnected') { + dispatch({ type: 'connect' }); + invoke('connect').then((result) => { + console.log(result); + }); + } + }; + + const getButtonText = (state: ConnectionState) => { + switch (state) { + case 'Connected': + return t('disconnect'); + case 'Disconnected': + return t('connect'); + case 'Connecting': + return ( +
+ autorenew +
+ ); + case 'Disconnecting': + return ( +
+ autorenew +
+ ); + case 'Unknown': + return t('status.unknown'); + } + }; + + return ( +
+ +
+
+ +
+
+ +
+
+ ); +} + +export default Home; diff --git a/nym-vpn/ui/src/pages/home/NetworkModeSelect.tsx b/nym-vpn/ui/src/pages/home/NetworkModeSelect.tsx new file mode 100644 index 00000000000..432233ff608 --- /dev/null +++ b/nym-vpn/ui/src/pages/home/NetworkModeSelect.tsx @@ -0,0 +1,116 @@ +import { useState } from 'react'; +import { RadioGroup } from '@headlessui/react'; +import { invoke } from '@tauri-apps/api'; +import clsx from 'clsx'; +import { useTranslation } from 'react-i18next'; +import { useMainDispatch, useMainState } from '../../contexts'; +import { StateDispatch, VpnMode } from '../../types'; + +type VpnModeOption = { name: VpnMode; title: string; desc: string }; + +function NetworkModeSelect() { + const state = useMainState(); + const dispatch = useMainDispatch() as StateDispatch; + const [selected, setSelected] = useState(state.vpnMode); + const [loading, setLoading] = useState(false); + + const { t } = useTranslation('home'); + + const handleNetworkModeChange = async (value: VpnMode) => { + if (state.state === 'Disconnected' && value !== state.vpnMode) { + setLoading(true); + try { + await invoke('set_vpn_mode', { mode: value }); + dispatch({ type: 'set-vpn-mode', mode: value }); + } catch (e) { + console.log(e); + } finally { + setLoading(false); + } + } + }; + + const vpnModes: VpnModeOption[] = [ + { + name: 'Mixnet', + title: t('mixnet-mode.title'), + desc: t('mixnet-mode.desc'), + }, + { + name: 'TwoHop', + title: t('twohop-mode.title'), + desc: t('twohop-mode.desc'), + }, + ]; + + const handleSelect = (value: VpnMode) => { + setSelected(value); + handleNetworkModeChange(value); + }; + + return ( +
+ + + {t('select-network-label')} + +
+ {vpnModes.map((mode) => ( + + clsx([ + 'bg-white dark:bg-baltic-sea-jaguar relative flex rounded-lg px-5 py-3 shadow-md focus:outline-none', + (state.state !== 'Disconnected' || loading) && + 'cursor-not-allowed', + checked && + 'ring-0 ring-melon ring-offset-2 ring-offset-melon', + state.state === 'Disconnected' && 'cursor-pointer', + ]) + } + disabled={state.state !== 'Disconnected' || loading} + > + {({ checked }) => { + return ( +
+ {checked ? ( + + radio_button_checked + + ) : ( + + radio_button_unchecked + + )} +
+
+ + {mode.title} + + + {mode.desc} + +
+
+
+ ); + }} +
+ ))} +
+
+
+ ); +} + +export default NetworkModeSelect; diff --git a/nym-vpn/ui/src/pages/home/index.ts b/nym-vpn/ui/src/pages/home/index.ts new file mode 100644 index 00000000000..c2d92a57466 --- /dev/null +++ b/nym-vpn/ui/src/pages/home/index.ts @@ -0,0 +1 @@ +export { default as Home } from './Home'; diff --git a/nym-vpn/ui/src/pages/index.ts b/nym-vpn/ui/src/pages/index.ts index a49d340c0c3..45aece47e1c 100644 --- a/nym-vpn/ui/src/pages/index.ts +++ b/nym-vpn/ui/src/pages/index.ts @@ -1,4 +1,5 @@ -export { default as PageLayout } from './pageLayout'; -export { default as Home } from './home'; -export { default as Settings } from './settings'; -export { default as Error } from './error'; +export * from './home'; +export * from './settings'; +export { default as NavLayout } from './NavLayout'; +export { default as NodeLocation } from './NodeLocation'; +export { default as Error } from './Error'; diff --git a/nym-vpn/ui/src/pages/pageLayout.tsx b/nym-vpn/ui/src/pages/pageLayout.tsx deleted file mode 100644 index 25121bb9ed6..00000000000 --- a/nym-vpn/ui/src/pages/pageLayout.tsx +++ /dev/null @@ -1,11 +0,0 @@ -import { Outlet } from 'react-router-dom'; - -function PageLayout() { - return ( -
- -
- ); -} - -export default PageLayout; diff --git a/nym-vpn/ui/src/pages/settings.tsx b/nym-vpn/ui/src/pages/settings.tsx deleted file mode 100644 index 14f65912dbc..00000000000 --- a/nym-vpn/ui/src/pages/settings.tsx +++ /dev/null @@ -1,5 +0,0 @@ -function Settings() { - return
Settings
; -} - -export default Settings; diff --git a/nym-vpn/ui/src/pages/settings/Settings.tsx b/nym-vpn/ui/src/pages/settings/Settings.tsx new file mode 100644 index 00000000000..220105a8577 --- /dev/null +++ b/nym-vpn/ui/src/pages/settings/Settings.tsx @@ -0,0 +1,58 @@ +import { useEffect, useState } from 'react'; +import clsx from 'clsx'; +import { invoke } from '@tauri-apps/api'; +import { Switch } from '@headlessui/react'; +import { useMainDispatch, useMainState } from '../../contexts'; +import { StateDispatch } from '../../types'; + +function Settings() { + const state = useMainState(); + const dispatch = useMainDispatch() as StateDispatch; + + const [enabled, setEnabled] = useState(state.uiTheme === 'Dark'); + + useEffect(() => { + setEnabled(state.uiTheme === 'Dark'); + }, [state.uiTheme]); + + const handleThemeChange = async (darkMode: boolean) => { + if (darkMode && state.uiTheme === 'Light') { + dispatch({ type: 'set-ui-theme', theme: 'Dark' }); + } else if (!darkMode && state.uiTheme === 'Dark') { + dispatch({ type: 'set-ui-theme', theme: 'Light' }); + } + invoke('set_ui_theme', { theme: darkMode ? 'Dark' : 'Light' }).catch( + (e) => { + console.log(e); + }, + ); + }; + + return ( +
+
+

+ Dark Mode +

+ + Dark mode + + +
+
+ ); +} + +export default Settings; diff --git a/nym-vpn/ui/src/pages/settings/index.ts b/nym-vpn/ui/src/pages/settings/index.ts new file mode 100644 index 00000000000..1f16002f16c --- /dev/null +++ b/nym-vpn/ui/src/pages/settings/index.ts @@ -0,0 +1 @@ +export { default as Settings } from './Settings'; diff --git a/nym-vpn/ui/src/router.tsx b/nym-vpn/ui/src/router.tsx new file mode 100644 index 00000000000..a7b8dc5d39b --- /dev/null +++ b/nym-vpn/ui/src/router.tsx @@ -0,0 +1,35 @@ +import { createBrowserRouter } from 'react-router-dom'; +import { Error, Home, NavLayout, NodeLocation, Settings } from './pages'; +import { routes } from './constants'; + +const router = createBrowserRouter([ + { + path: routes.root, + element: , + children: [ + { + element: , + errorElement: , + index: true, + }, + { + path: routes.settings, + element: , + errorElement: , + }, + { + path: routes.entryNodeLocation, + // eslint-disable-next-line react/jsx-no-undef + element: , + errorElement: , + }, + { + path: routes.exitNodeLocation, + element: , + errorElement: , + }, + ], + }, +]); + +export default router; diff --git a/nym-vpn/ui/src/state/main.ts b/nym-vpn/ui/src/state/main.ts index 822364f458a..48d6c1aa1f6 100644 --- a/nym-vpn/ui/src/state/main.ts +++ b/nym-vpn/ui/src/state/main.ts @@ -1,21 +1,55 @@ -import { AppState, ConnectionState } from '../types'; +import dayjs from 'dayjs'; +import { AppData, AppState, ConnectionState, UiTheme, VpnMode } from '../types'; export type StateAction = + | { type: 'set-partial-state'; partialState: Partial } | { type: 'change-connection-state'; state: ConnectionState } + | { type: 'set-vpn-mode'; mode: VpnMode } + | { type: 'set-error'; error: string } + | { type: 'reset-error' } + | { type: 'new-progress-message'; message: string } | { type: 'connect' } | { type: 'disconnect' } - | { type: 'reset' }; + | { type: 'set-connected'; startTime: number } + | { type: 'set-connection-start-time'; startTime?: number | null } + | { type: 'set-disconnected' } + | { type: 'reset' } + | { type: 'set-app-data'; data: AppData } + | { type: 'set-ui-theme'; theme: UiTheme }; export const initialState: AppState = { state: 'Disconnected', loading: false, - privacyMode: 'High', + vpnMode: 'TwoHop', tunnel: { name: 'nym', id: 'nym' }, + uiTheme: 'Light', + progressMessages: [], + localAppData: { + monitoring: false, + autoconnect: false, + killswitch: false, + uiTheme: 'Light', + vpnMode: 'TwoHop', + entryNode: null, + exitNode: null, + }, }; export function reducer(state: AppState, action: StateAction): AppState { switch (action.type) { + case 'set-vpn-mode': + return { + ...state, + vpnMode: action.mode, + localAppData: { ...state.localAppData, vpnMode: action.mode }, + }; + case 'set-partial-state': { + return { ...state, ...action.partialState }; + } case 'change-connection-state': { + if (action.state === state.state) { + return state; + } return { ...state, state: action.state, @@ -29,6 +63,48 @@ export function reducer(state: AppState, action: StateAction): AppState { case 'disconnect': { return { ...state, state: 'Disconnecting', loading: true }; } + case 'set-connected': { + return { + ...state, + state: 'Connected', + loading: false, + progressMessages: [], + sessionStartDate: dayjs.unix(action.startTime), + }; + } + case 'set-disconnected': { + return { + ...state, + state: 'Disconnected', + loading: false, + progressMessages: [], + sessionStartDate: null, + }; + } + case 'set-connection-start-time': + return { + ...state, + sessionStartDate: + (action.startTime && dayjs.unix(action.startTime)) || null, + }; + case 'set-app-data': { + return { ...state, localAppData: action.data }; + } + case 'set-error': + return { ...state, error: action.error }; + case 'reset-error': + return { ...state, error: null }; + case 'new-progress-message': + return { + ...state, + progressMessages: [...state.progressMessages, action.message], + }; + case 'set-ui-theme': + return { + ...state, + uiTheme: action.theme, + localAppData: { ...state.localAppData, uiTheme: action.theme }, + }; case 'reset': return initialState; } diff --git a/nym-vpn/ui/src/state/provider.tsx b/nym-vpn/ui/src/state/provider.tsx index 8f2f7657f3d..981a23973af 100644 --- a/nym-vpn/ui/src/state/provider.tsx +++ b/nym-vpn/ui/src/state/provider.tsx @@ -1,9 +1,9 @@ -import { useEffect, useReducer } from 'react'; +import React, { useEffect, useReducer } from 'react'; import { invoke } from '@tauri-apps/api'; +import { MainDispatchContext, MainStateContext } from '../contexts'; +import { AppDataFromBackend, CmdError, ConnectionState } from '../types'; import { initialState, reducer } from './main'; import { useTauriEvents } from './useTauriEvents'; -import { MainDispatchContext, MainStateContext } from '../contexts'; -import { ConnectionState } from '../types'; type Props = { children?: React.ReactNode; @@ -20,9 +20,52 @@ export function MainStateProvider({ children }: Props) { return await invoke('get_connection_state'); }; + // initialize session start time + const getSessionStartTime = async () => { + return await invoke('get_connection_start_time'); + }; + getInitialConnectionState().then((state) => dispatch({ type: 'change-connection-state', state }), ); + getSessionStartTime().then((startTime) => + dispatch({ type: 'set-connection-start-time', startTime }), + ); + }, []); + + // get saved on disk app data and restore state from it + useEffect(() => { + const getAppData = async () => { + return await invoke('get_app_data'); + }; + + getAppData() + .then((data) => { + console.log(data); + dispatch({ + type: 'set-app-data', + data: { + autoconnect: data.autoconnect || false, + monitoring: data.monitoring || false, + killswitch: data.killswitch || false, + uiTheme: data.ui_theme || 'Light', + vpnMode: data.vpn_mode || 'TwoHop', + entryNode: data.entry_node, + exitNode: data.exit_node, + }, + }); + dispatch({ + type: 'set-partial-state', + partialState: { + uiTheme: data.ui_theme || 'Light', + vpnMode: data.vpn_mode || 'TwoHop', + }, + }); + }) + .catch((err: CmdError) => { + // TODO handle error properly + console.log(err); + }); }, []); return ( diff --git a/nym-vpn/ui/src/state/useTauriEvents.ts b/nym-vpn/ui/src/state/useTauriEvents.ts index fb4f4a3bfe8..794df421a9b 100644 --- a/nym-vpn/ui/src/state/useTauriEvents.ts +++ b/nym-vpn/ui/src/state/useTauriEvents.ts @@ -1,39 +1,75 @@ import { useCallback, useEffect } from 'react'; import { listen } from '@tauri-apps/api/event'; -import { EventPayload, StateDispatch } from '../types'; -import { ConnectionEvent } from '../constants'; +import dayjs from 'dayjs'; +import { + ConnectionEventPayload, + ProgressEventPayload, + StateDispatch, +} from '../types'; +import { ConnectionEvent, ProgressEvent } from '../constants'; + +function handleError(dispatch: StateDispatch, error?: string | null) { + if (!error) { + dispatch({ type: 'reset-error' }); + return; + } + dispatch({ type: 'set-error', error }); +} export function useTauriEvents(dispatch: StateDispatch) { - const registerListener = useCallback(() => { - return listen(ConnectionEvent, (event) => { + const registerStateListener = useCallback(() => { + return listen(ConnectionEvent, (event) => { console.log( `received event ${event.event}, state: ${event.payload.state}`, ); switch (event.payload.state) { case 'Connected': - dispatch({ type: 'change-connection-state', state: 'Connected' }); + dispatch({ + type: 'set-connected', + startTime: event.payload.start_time || dayjs().unix(), + }); + handleError(dispatch, event.payload.error); break; case 'Disconnected': - dispatch({ type: 'change-connection-state', state: 'Disconnected' }); + dispatch({ type: 'set-disconnected' }); + handleError(dispatch, event.payload.error); break; case 'Connecting': dispatch({ type: 'change-connection-state', state: 'Connecting' }); + handleError(dispatch, event.payload.error); break; case 'Disconnecting': dispatch({ type: 'change-connection-state', state: 'Disconnecting' }); + handleError(dispatch, event.payload.error); break; - case 'Error': + case 'Unknown': + dispatch({ type: 'change-connection-state', state: 'Unknown' }); + handleError(dispatch, event.payload.error); break; } }); }, [dispatch]); + const registerProgressListener = useCallback(() => { + return listen(ProgressEvent, (event) => { + console.log( + `received event ${event.event}, message: ${event.payload.message}`, + ); + dispatch({ + type: 'new-progress-message', + message: event.payload.message, + }); + }); + }, [dispatch]); + // register/unregister event listener useEffect(() => { - const unlisten = registerListener(); + const unlistenState = registerStateListener(); + const unlistenProgress = registerProgressListener(); return () => { - unlisten.then((f) => f()); + unlistenState.then((f) => f()); + unlistenProgress.then((f) => f()); }; - }, [registerListener]); + }, [registerStateListener, registerProgressListener]); } diff --git a/nym-vpn/ui/src/styles.css b/nym-vpn/ui/src/styles.css index b5c61c95671..aed8571c631 100644 --- a/nym-vpn/ui/src/styles.css +++ b/nym-vpn/ui/src/styles.css @@ -1,3 +1,11 @@ @tailwind base; @tailwind components; @tailwind utilities; + +@layer base { + @font-face { + font-family: 'Material Symbols Outlined'; + font-style: normal; + src: url(assets/fonts/MaterialSymbolsOutlined.woff2) format('woff2'); + } +} diff --git a/nym-vpn/ui/src/types/app-data.ts b/nym-vpn/ui/src/types/app-data.ts new file mode 100644 index 00000000000..73d6f0c1898 --- /dev/null +++ b/nym-vpn/ui/src/types/app-data.ts @@ -0,0 +1,29 @@ +import { VpnMode } from './app-state'; + +export type UiTheme = 'Dark' | 'Light'; + +export interface NodeConfig { + id: string; + country: string; +} + +export interface AppData { + monitoring: boolean; + autoconnect: boolean; + killswitch: boolean; + uiTheme: UiTheme; + vpnMode: VpnMode; + entryNode?: NodeConfig | null; + exitNode?: NodeConfig | null; +} + +// tauri type, hence the use of snake_case +export interface AppDataFromBackend { + monitoring: boolean | null; + autoconnect: boolean | null; + killswitch: boolean | null; + ui_theme: UiTheme | null; + vpn_mode: VpnMode; + entry_node: NodeConfig | null; + exit_node: NodeConfig | null; +} diff --git a/nym-vpn/ui/src/types/app-state.ts b/nym-vpn/ui/src/types/app-state.ts index 3a0c1edb5b2..c30f0aa5e93 100644 --- a/nym-vpn/ui/src/types/app-state.ts +++ b/nym-vpn/ui/src/types/app-state.ts @@ -1,14 +1,16 @@ import { Dispatch } from 'react'; +import { Dayjs } from 'dayjs'; import { StateAction } from '../state'; +import { AppData } from './app-data'; export type ConnectionState = | 'Connected' | 'Disconnected' | 'Connecting' | 'Disconnecting' - | 'Error'; + | 'Unknown'; -export type PrivacyMode = 'High' | 'Medium' | 'Low'; +export type VpnMode = 'TwoHop' | 'Mixnet'; export interface TunnelConfig { id: string; @@ -18,12 +20,23 @@ export interface TunnelConfig { export type AppState = { state: ConnectionState; loading: boolean; - privacyMode: PrivacyMode; + error?: string | null; + progressMessages: string[]; + sessionStartDate?: Dayjs | null; + vpnMode: VpnMode; tunnel: TunnelConfig; + uiTheme: 'Light' | 'Dark'; + localAppData: AppData; }; -export type EventPayload = { +export type ConnectionEventPayload = { state: ConnectionState; + error?: string | null; + start_time?: number | null; // unix timestamp in seconds +}; + +export type ProgressEventPayload = { + message: string; }; export type StateDispatch = Dispatch; diff --git a/nym-vpn/ui/src/types/index.ts b/nym-vpn/ui/src/types/index.ts index c875a5746ce..f9d47f3c04e 100644 --- a/nym-vpn/ui/src/types/index.ts +++ b/nym-vpn/ui/src/types/index.ts @@ -1 +1,4 @@ export * from './app-state'; +export * from './app-data'; +export * from './tauri-ipc'; +export * from './routes'; diff --git a/nym-vpn/ui/src/types/routes.ts b/nym-vpn/ui/src/types/routes.ts new file mode 100644 index 00000000000..a18280924ef --- /dev/null +++ b/nym-vpn/ui/src/types/routes.ts @@ -0,0 +1,3 @@ +import { routes } from '../constants'; + +export type Routes = (typeof routes)[keyof typeof routes]; diff --git a/nym-vpn/ui/src/types/tauri-ipc.ts b/nym-vpn/ui/src/types/tauri-ipc.ts new file mode 100644 index 00000000000..9df3c44f36c --- /dev/null +++ b/nym-vpn/ui/src/types/tauri-ipc.ts @@ -0,0 +1,6 @@ +export type CmdErrorSource = 'InternalError' | 'CallerError' | 'Unknown'; + +export interface CmdError { + source: CmdErrorSource; + message: string; +} diff --git a/nym-vpn/ui/src/ui/ThemeSetter.tsx b/nym-vpn/ui/src/ui/ThemeSetter.tsx new file mode 100644 index 00000000000..99941e74cc4 --- /dev/null +++ b/nym-vpn/ui/src/ui/ThemeSetter.tsx @@ -0,0 +1,17 @@ +import React from 'react'; +import clsx from 'clsx'; +import { useMainState } from '../contexts'; + +export default function ThemeSetter({ + children, +}: { + children: React.ReactNode; +}) { + const { uiTheme } = useMainState(); + + return ( +
+ {children} +
+ ); +} diff --git a/nym-vpn/ui/src/ui/TopBar.tsx b/nym-vpn/ui/src/ui/TopBar.tsx new file mode 100644 index 00000000000..db31a5fcb30 --- /dev/null +++ b/nym-vpn/ui/src/ui/TopBar.tsx @@ -0,0 +1,95 @@ +import { useEffect, useMemo, useState } from 'react'; +import { useLocation, useNavigate } from 'react-router-dom'; +import { useTranslation } from 'react-i18next'; +import { AppName, routes } from '../constants'; +import { Routes } from '../types'; + +type NavLocation = { + title: string; + leftIcon?: React.ReactNode; + handleLeftNav?: () => void; + rightIcon?: React.ReactNode; + handleRightNav?: () => void; +}; + +type NavBarData = { + [key in Routes]: NavLocation; +}; + +export default function TopBar() { + const location = useLocation(); + const navigate = useNavigate(); + const { t } = useTranslation(); + + const [currentNavLocation, setCurrentNavLocation] = useState({ + title: AppName, + rightIcon: 'settings', + handleRightNav: () => { + navigate(routes.settings); + }, + }); + + const navBarData = useMemo(() => { + return { + '/': { + title: AppName, + rightIcon: 'settings', + handleRightNav: () => { + navigate(routes.settings); + }, + }, + '/settings': { + title: t('settings'), + leftIcon: 'arrow_back', + handleLeftNav: () => { + navigate(-1); + }, + }, + '/entry-node-location': { + title: t('first-hop-selection'), + leftIcon: 'arrow_back', + handleLeftNav: () => { + navigate(-1); + }, + }, + '/exit-node-location': { + title: t('last-hop-selection'), + leftIcon: 'arrow_back', + handleLeftNav: () => { + navigate(-1); + }, + }, + }; + }, [t, navigate]); + + useEffect(() => { + setCurrentNavLocation(navBarData[location.pathname as Routes]); + }, [location.pathname, navBarData]); + + return ( + + ); +} diff --git a/nym-vpn/ui/src/ui/index.ts b/nym-vpn/ui/src/ui/index.ts new file mode 100644 index 00000000000..f3af8c7dd61 --- /dev/null +++ b/nym-vpn/ui/src/ui/index.ts @@ -0,0 +1,2 @@ +export { default as ThemeSetter } from './ThemeSetter'; +export { default as TopBar } from './TopBar'; diff --git a/nym-vpn/ui/tailwind.config.js b/nym-vpn/ui/tailwind.config.js deleted file mode 100644 index a1f67d7f614..00000000000 --- a/nym-vpn/ui/tailwind.config.js +++ /dev/null @@ -1,10 +0,0 @@ -/** @type {import('tailwindcss').Config} */ -export default { - content: ['./index.html', './src/**/*.{js,ts,jsx,tsx}'], - theme: { - extend: {}, - }, - plugins: [], - // Toggling dark mode manually - darkMode: 'class', -}; diff --git a/nym-vpn/ui/tailwind.config.ts b/nym-vpn/ui/tailwind.config.ts new file mode 100644 index 00000000000..7a1a584e349 --- /dev/null +++ b/nym-vpn/ui/tailwind.config.ts @@ -0,0 +1,88 @@ +import type { Config } from 'tailwindcss'; +import defaultTheme from 'tailwindcss/defaultTheme'; +import headlessui from '@headlessui/tailwindcss'; + +export default { + content: ['./index.html', './src/**/*.{js,ts,jsx,tsx}'], + theme: { + colors: { + transparent: 'transparent', + current: 'currentColor', + 'baltic-sea': { + // [D] bg for top-bar nav + // [D] bg for network modes + jaguar: '#2A2831', + // [L] status-line title text + icon + // [L] connection timer text + // [L] "Connecting" status text + // [L] main titles text + // [L] network mode title text + icon + // [L] node location select text value + icon + label + // [D] button text + DEFAULT: '#1C1B1F', // [D] main bg + oil: '#1F1F22', // [D] connection status bg + quartzite: '#202C25', // [D] "Connected" status bg + }, + 'blanc-nacre': { + DEFAULT: '#F2F4F6', // [L] main bg + platinum: '#E7E8EC', // [L] connection status bg + icicle: '#E1EFE7', // [L] "Connected" status bg + }, + // [DL] primary accent + melon: '#FB6E4E', + // [DL] secondary accent + cornflower: '#7075FF', + // [DL] error status text + teaberry: '#E33B5A', + // [DL] "Connected" status text + 'vert-menthe': '#2BC761', + // [D] main titles text + // [D] connection timer text + // [D] "Connecting" status text + // [L] bg for top-bar nav + // [L] bg for network modes + // [L] button text + white: '#FFF', + black: '#000', + mercury: { + // [D] status-line title text + icon + // [D] network mode title text + icon + // [D] node location select text value + icon + label + pinkish: '#E6E1E5', + DEFAULT: '#E1EFE7', + // [D] network mode desc text + // [D] "Connection time" + // [D] main status desc text + mist: '#938F99', + }, + // [DL] "Disconnected" status text + 'coal-mine': { dark: '#56545A', light: '#A4A4A4' }, + // [L] "Connection time" + // [L] main status desc text + 'dim-gray': '#696571', + // [L] network mode desc text + // [L] node location select outline + 'ciment-feet': '#79747E', + // [D] node location select outline + 'gun-powder': '#49454F', + // [D] top-bar icon + 'laughing-jack': '#CAC4D0', + // [L] button bg in disabled state + 'wind-chime': '#DEDEE1', + }, + extend: { + fontFamily: { + sans: ['Lato', ...defaultTheme.fontFamily.sans], + icon: [ + 'Material Symbols Outlined', + { + fontVariationSettings: '"opsz" 24; "wght" 400;', + }, + ], + }, + }, + }, + plugins: [headlessui], + // Toggling dark mode manually + darkMode: 'class', +} satisfies Config; diff --git a/nym-vpn/ui/yarn.lock b/nym-vpn/ui/yarn.lock index fad7168c69a..2ce2fdec39b 100644 --- a/nym-vpn/ui/yarn.lock +++ b/nym-vpn/ui/yarn.lock @@ -12,44 +12,13 @@ resolved "https://registry.yarnpkg.com/@alloc/quick-lru/-/quick-lru-5.2.0.tgz#7bf68b20c0a350f936915fcae06f58e32007ce30" integrity sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw== -"@babel/runtime@^7.22.5", "@babel/runtime@^7.23.2", "@babel/runtime@^7.5.5", "@babel/runtime@^7.8.7": +"@babel/runtime@^7.22.5", "@babel/runtime@^7.23.2": version "7.23.2" resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.23.2.tgz#062b0ac103261d68a966c4c7baf2ae3e62ec3885" integrity sha512-mM8eg4yl5D6i3lu2QKPuPH4FArvJ8KhTofbE7jwMUv9KX5mBvwPAqnV3MlyBNqdp9RyRKP6Yck8TrfYrPvX3bg== dependencies: regenerator-runtime "^0.14.0" -"@emotion/cache@^11.11.0": - version "11.11.0" - resolved "https://registry.yarnpkg.com/@emotion/cache/-/cache-11.11.0.tgz#809b33ee6b1cb1a625fef7a45bc568ccd9b8f3ff" - integrity sha512-P34z9ssTCBi3e9EI1ZsWpNHcfY1r09ZO0rZbRO2ob3ZQMnFI35jB536qoXbkdesr5EUhYi22anuEJuyxifaqAQ== - dependencies: - "@emotion/memoize" "^0.8.1" - "@emotion/sheet" "^1.2.2" - "@emotion/utils" "^1.2.1" - "@emotion/weak-memoize" "^0.3.1" - stylis "4.2.0" - -"@emotion/memoize@^0.8.1": - version "0.8.1" - resolved "https://registry.yarnpkg.com/@emotion/memoize/-/memoize-0.8.1.tgz#c1ddb040429c6d21d38cc945fe75c818cfb68e17" - integrity sha512-W2P2c/VRW1/1tLox0mVUalvnWXxavmv/Oum2aPsRcoDJuob75FC3Y8FbpfLwUegRcxINtGUMPq0tFCvYNTBXNA== - -"@emotion/sheet@^1.2.2": - version "1.2.2" - resolved "https://registry.yarnpkg.com/@emotion/sheet/-/sheet-1.2.2.tgz#d58e788ee27267a14342303e1abb3d508b6d0fec" - integrity sha512-0QBtGvaqtWi+nx6doRwDdBIzhNdZrXUppvTM4dtZZWEGTXL/XE/yJxLMGlDT1Gt+UHH5IX1n+jkXyytE/av7OA== - -"@emotion/utils@^1.2.1": - version "1.2.1" - resolved "https://registry.yarnpkg.com/@emotion/utils/-/utils-1.2.1.tgz#bbab58465738d31ae4cb3dbb6fc00a5991f755e4" - integrity sha512-Y2tGf3I+XVnajdItskUCn6LX+VUDmP6lTL4fcqsXAv43dnlbZiuW4MWQW38rW/BVWSE7Q/7+XQocmpnRYILUmg== - -"@emotion/weak-memoize@^0.3.1": - version "0.3.1" - resolved "https://registry.yarnpkg.com/@emotion/weak-memoize/-/weak-memoize-0.3.1.tgz#d0fce5d07b0620caa282b5131c297bb60f9d87e6" - integrity sha512-EsBwpc7hBUJWAsNPBmJy4hxWx12v6bshQsldrVmjxJoc3isbxhOrF2IcCpaXxfvq03NwkI7sbsOLXbYuqF/8Ww== - "@esbuild/android-arm64@0.19.6": version "0.19.6" resolved "https://registry.yarnpkg.com/@esbuild/android-arm64/-/android-arm64-0.19.6.tgz#13d98a34bbbde4237867cc232307a20ded139b6f" @@ -219,6 +188,18 @@ resolved "https://registry.yarnpkg.com/@floating-ui/utils/-/utils-0.1.6.tgz#22958c042e10b67463997bd6ea7115fe28cbcaf9" integrity sha512-OfX7E2oUDYxtBvsuS4e/jSn4Q9Qb6DzgeYtsAdkPZ47znpoNsMgZw0+tVijiv3uGNR6dgNlty6r9rzIzHjtd/A== +"@headlessui/react@^1.7.17": + version "1.7.17" + resolved "https://registry.yarnpkg.com/@headlessui/react/-/react-1.7.17.tgz#a0ec23af21b527c030967245fd99776aa7352bc6" + integrity sha512-4am+tzvkqDSSgiwrsEpGWqgGo9dz8qU5M3znCkC4PgkpY4HcCZzEDEvozltGGGHIKl9jbXbZPSH5TWn4sWJdow== + dependencies: + client-only "^0.0.1" + +"@headlessui/tailwindcss@^0.2.0": + version "0.2.0" + resolved "https://registry.yarnpkg.com/@headlessui/tailwindcss/-/tailwindcss-0.2.0.tgz#2c55c98fd8eee4b4f21ec6eb35a014b840059eec" + integrity sha512-fpL830Fln1SykOCboExsWr3JIVeQKieLJ3XytLe/tt1A0XzqUthOftDmjcCYLW62w7mQI7wXcoPXr3tZ9QfGxw== + "@humanwhocodes/config-array@^0.11.13": version "0.11.13" resolved "https://registry.yarnpkg.com/@humanwhocodes/config-array/-/config-array-0.11.13.tgz#075dc9684f40a531d9b26b0822153c1e832ee297" @@ -270,7 +251,7 @@ "@jridgewell/resolve-uri" "^3.1.0" "@jridgewell/sourcemap-codec" "^1.4.14" -"@mui/base@5.0.0-beta.24", "@mui/base@^5.0.0-beta.24": +"@mui/base@^5.0.0-beta.24": version "5.0.0-beta.24" resolved "https://registry.yarnpkg.com/@mui/base/-/base-5.0.0-beta.24.tgz#1a0638388291828dacf9547b466bc21fbaad3a2a" integrity sha512-bKt2pUADHGQtqWDZ8nvL2Lvg2GNJyd/ZUgZAJoYzRgmnxBL9j36MSlS3+exEdYkikcnvVafcBtD904RypFKb0w== @@ -283,62 +264,6 @@ clsx "^2.0.0" prop-types "^15.8.1" -"@mui/core-downloads-tracker@^5.14.18": - version "5.14.18" - resolved "https://registry.yarnpkg.com/@mui/core-downloads-tracker/-/core-downloads-tracker-5.14.18.tgz#f8b187dc89756fa5c0b7d15aea537a6f73f0c2d8" - integrity sha512-yFpF35fEVDV81nVktu0BE9qn2dD/chs7PsQhlyaV3EnTeZi9RZBuvoEfRym1/jmhJ2tcfeWXiRuHG942mQXJJQ== - -"@mui/material@^5.14.14": - version "5.14.18" - resolved "https://registry.yarnpkg.com/@mui/material/-/material-5.14.18.tgz#d0a89be3e27afe90135d542ddbf160b3f34e869c" - integrity sha512-y3UiR/JqrkF5xZR0sIKj6y7xwuEiweh9peiN3Zfjy1gXWXhz5wjlaLdoxFfKIEBUFfeQALxr/Y8avlHH+B9lpQ== - dependencies: - "@babel/runtime" "^7.23.2" - "@mui/base" "5.0.0-beta.24" - "@mui/core-downloads-tracker" "^5.14.18" - "@mui/system" "^5.14.18" - "@mui/types" "^7.2.9" - "@mui/utils" "^5.14.18" - "@types/react-transition-group" "^4.4.8" - clsx "^2.0.0" - csstype "^3.1.2" - prop-types "^15.8.1" - react-is "^18.2.0" - react-transition-group "^4.4.5" - -"@mui/private-theming@^5.14.18": - version "5.14.18" - resolved "https://registry.yarnpkg.com/@mui/private-theming/-/private-theming-5.14.18.tgz#98f97139ea21570493391ab377c1deb47fc6d1a2" - integrity sha512-WSgjqRlzfHU+2Rou3HlR2Gqfr4rZRsvFgataYO3qQ0/m6gShJN+lhVEvwEiJ9QYyVzMDvNpXZAcqp8Y2Vl+PAw== - dependencies: - "@babel/runtime" "^7.23.2" - "@mui/utils" "^5.14.18" - prop-types "^15.8.1" - -"@mui/styled-engine@^5.14.18": - version "5.14.18" - resolved "https://registry.yarnpkg.com/@mui/styled-engine/-/styled-engine-5.14.18.tgz#82d427bc975b85cecdbab2fd9353ed6c2df7eae1" - integrity sha512-pW8bpmF9uCB5FV2IPk6mfbQCjPI5vGI09NOLhtGXPeph/4xIfC3JdIX0TILU0WcTs3aFQqo6s2+1SFgIB9rCXA== - dependencies: - "@babel/runtime" "^7.23.2" - "@emotion/cache" "^11.11.0" - csstype "^3.1.2" - prop-types "^15.8.1" - -"@mui/system@^5.14.18": - version "5.14.18" - resolved "https://registry.yarnpkg.com/@mui/system/-/system-5.14.18.tgz#0f671e8f0a5e8e965b79235d77c50098f54195b5" - integrity sha512-hSQQdb3KF72X4EN2hMEiv8EYJZSflfdd1TRaGPoR7CIAG347OxCslpBUwWngYobaxgKvq6xTrlIl+diaactVww== - dependencies: - "@babel/runtime" "^7.23.2" - "@mui/private-theming" "^5.14.18" - "@mui/styled-engine" "^5.14.18" - "@mui/types" "^7.2.9" - "@mui/utils" "^5.14.18" - clsx "^2.0.0" - csstype "^3.1.2" - prop-types "^15.8.1" - "@mui/types@^7.2.9": version "7.2.9" resolved "https://registry.yarnpkg.com/@mui/types/-/types-7.2.9.tgz#730ee83a37af292a5973962f78ce5c95f31213a7" @@ -605,6 +530,11 @@ resolved "https://registry.yarnpkg.com/@types/json-schema/-/json-schema-7.0.15.tgz#596a1747233694d50f6ad8a7869fcb6f56cf5841" integrity sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA== +"@types/json5@^0.0.29": + version "0.0.29" + resolved "https://registry.yarnpkg.com/@types/json5/-/json5-0.0.29.tgz#ee28707ae94e11d2b827bcbe5270bcea7f3e71ee" + integrity sha512-dRLjCWHYg4oaA77cxO64oO+7JwCwnIzkZPdrrC71jQmQtlhM556pwKo5bUzqvZndkVbeFLIIi+9TC40JNF5hNQ== + "@types/prop-types@*", "@types/prop-types@^15.7.10": version "15.7.10" resolved "https://registry.yarnpkg.com/@types/prop-types/-/prop-types-15.7.10.tgz#892afc9332c4d62a5ea7e897fe48ed2085bbb08a" @@ -634,13 +564,6 @@ "@types/history" "^4.7.11" "@types/react" "*" -"@types/react-transition-group@^4.4.8": - version "4.4.9" - resolved "https://registry.yarnpkg.com/@types/react-transition-group/-/react-transition-group-4.4.9.tgz#12a1a1b5b8791067198149867b0823fbace31579" - integrity sha512-ZVNmWumUIh5NhH8aMD9CR2hdW0fNuYInlocZHaZ+dgk/1K49j1w/HoAuK1ki+pgscQrOFRTlXeoURtuzEkV3dg== - dependencies: - "@types/react" "*" - "@types/react@*", "@types/react@^18.2.37": version "18.2.37" resolved "https://registry.yarnpkg.com/@types/react/-/react-18.2.37.tgz#0f03af69e463c0f19a356c2660dbca5d19c44cae" @@ -812,6 +735,13 @@ argparse@^2.0.1: resolved "https://registry.yarnpkg.com/argparse/-/argparse-2.0.1.tgz#246f50f3ca78a3240f6c997e8a9bd1eac49e4b38" integrity sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q== +aria-query@^5.3.0: + version "5.3.0" + resolved "https://registry.yarnpkg.com/aria-query/-/aria-query-5.3.0.tgz#650c569e41ad90b51b3d7df5e5eed1c7549c103e" + integrity sha512-b0P0sZPKtyu8HkeRAfCq0IfURZK+SuwMjY1UXGBU27wpAiTwQAIlq56IbIO+ytk/JjS1fMR14ee5WBBfKi5J6A== + dependencies: + dequal "^2.0.3" + array-buffer-byte-length@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/array-buffer-byte-length/-/array-buffer-byte-length-1.0.0.tgz#fabe8bc193fea865f317fe7807085ee0dee5aead" @@ -820,7 +750,7 @@ array-buffer-byte-length@^1.0.0: call-bind "^1.0.2" is-array-buffer "^3.0.1" -array-includes@^3.1.6: +array-includes@^3.1.6, array-includes@^3.1.7: version "3.1.7" resolved "https://registry.yarnpkg.com/array-includes/-/array-includes-3.1.7.tgz#8cd2e01b26f7a3086cbc87271593fe921c62abda" integrity sha512-dlcsNBIiWhPkHdOEEKnehA+RNUWDc4UqFtnIXU4uuYDPtA4LDkr7qip2p0VvFAEXNDr0yWZ9PJyIRiGjRLQzwQ== @@ -836,7 +766,18 @@ array-union@^2.1.0: resolved "https://registry.yarnpkg.com/array-union/-/array-union-2.1.0.tgz#b798420adbeb1de828d84acd8a2e23d3efe85e8d" integrity sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw== -array.prototype.flat@^1.3.1: +array.prototype.findlastindex@^1.2.3: + version "1.2.3" + resolved "https://registry.yarnpkg.com/array.prototype.findlastindex/-/array.prototype.findlastindex-1.2.3.tgz#b37598438f97b579166940814e2c0493a4f50207" + integrity sha512-LzLoiOMAxvy+Gd3BAq3B7VeIgPdo+Q8hthvKtXybMvRV0jrXfJM/t8mw7nNlpEcVlVUnCnM2KSX4XU5HmpodOA== + dependencies: + call-bind "^1.0.2" + define-properties "^1.2.0" + es-abstract "^1.22.1" + es-shim-unscopables "^1.0.0" + get-intrinsic "^1.2.1" + +array.prototype.flat@^1.3.1, array.prototype.flat@^1.3.2: version "1.3.2" resolved "https://registry.yarnpkg.com/array.prototype.flat/-/array.prototype.flat-1.3.2.tgz#1476217df8cff17d72ee8f3ba06738db5b387d18" integrity sha512-djYB+Zx2vLewY8RWlNCUdHjDXs2XOgm602S9E7P/UpHgfeHL00cRiIF+IN/G/aUJ7kGPb6yO/ErDI5V2s8iycA== @@ -846,7 +787,7 @@ array.prototype.flat@^1.3.1: es-abstract "^1.22.1" es-shim-unscopables "^1.0.0" -array.prototype.flatmap@^1.3.1: +array.prototype.flatmap@^1.3.1, array.prototype.flatmap@^1.3.2: version "1.3.2" resolved "https://registry.yarnpkg.com/array.prototype.flatmap/-/array.prototype.flatmap-1.3.2.tgz#c9a7c6831db8e719d6ce639190146c24bbd3e527" integrity sha512-Ewyx0c9PmpcsByhSW4r+9zDU7sGjFc86qf/kKtuSCRdhfbk0SNLLkaT5qvcHnRGgc5NP/ly/y+qkXkqONX54CQ== @@ -880,6 +821,11 @@ arraybuffer.prototype.slice@^1.0.2: is-array-buffer "^3.0.2" is-shared-array-buffer "^1.0.2" +ast-types-flow@^0.0.8: + version "0.0.8" + resolved "https://registry.yarnpkg.com/ast-types-flow/-/ast-types-flow-0.0.8.tgz#0a85e1c92695769ac13a428bb653e7538bea27d6" + integrity sha512-OH/2E5Fg20h2aPrbe+QL8JZQFko0YZaF+j4mnQ7BGhfavO7OpSLa8a0y9sBwomHdSbkhTS8TQNayBfnW5DwbvQ== + asynciterator.prototype@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/asynciterator.prototype/-/asynciterator.prototype-1.0.0.tgz#8c5df0514936cdd133604dfcc9d3fb93f09b2b62" @@ -904,6 +850,18 @@ available-typed-arrays@^1.0.5: resolved "https://registry.yarnpkg.com/available-typed-arrays/-/available-typed-arrays-1.0.5.tgz#92f95616501069d07d10edb2fc37d3e1c65123b7" integrity sha512-DMD0KiN46eipeziST1LPP/STfDU0sufISXmjSgvVsoU2tqxctQeASejWcfNtxYKqETM1UxQ8sp2OrSBWpHY6sw== +axe-core@=4.7.0: + version "4.7.0" + resolved "https://registry.yarnpkg.com/axe-core/-/axe-core-4.7.0.tgz#34ba5a48a8b564f67e103f0aa5768d76e15bbbbf" + integrity sha512-M0JtH+hlOL5pLQwHOLNYZaXuhqmvS8oExsqB1SBYgA4Dk7u/xx+YdGHXaK5pyUfed5mYXdlYiphWq3G8cRi5JQ== + +axobject-query@^3.2.1: + version "3.2.1" + resolved "https://registry.yarnpkg.com/axobject-query/-/axobject-query-3.2.1.tgz#39c378a6e3b06ca679f29138151e45b2b32da62a" + integrity sha512-jsyHu61e6N4Vbz/v18DHwWYKK0bSWLqn47eeDSKPB7m8tqMHF9YJ+mhIk2lVteyZrY8tnSj/jHOv4YiTCuCJgg== + dependencies: + dequal "^2.0.3" + balanced-match@^1.0.0: version "1.0.2" resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.2.tgz#e83e3a7e3f300b34cb9d87f615fa0cbf357690ee" @@ -986,6 +944,11 @@ chokidar@^3.5.3: optionalDependencies: fsevents "~2.3.2" +client-only@^0.0.1: + version "0.0.1" + resolved "https://registry.yarnpkg.com/client-only/-/client-only-0.0.1.tgz#38bba5d403c41ab150bff64a95c85013cf73bca1" + integrity sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA== + clsx@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/clsx/-/clsx-2.0.0.tgz#12658f3fd98fafe62075595a5c30e43d18f3d00b" @@ -1027,11 +990,28 @@ cssesc@^3.0.0: resolved "https://registry.yarnpkg.com/cssesc/-/cssesc-3.0.0.tgz#37741919903b868565e1c09ea747445cd18983ee" integrity sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg== -csstype@^3.0.2, csstype@^3.1.2: +csstype@^3.0.2: version "3.1.2" resolved "https://registry.yarnpkg.com/csstype/-/csstype-3.1.2.tgz#1d4bf9d572f11c14031f0436e1c10bc1f571f50b" integrity sha512-I7K1Uu0MBPzaFKg4nI5Q7Vs2t+3gWWW648spaF+Rg7pI9ds18Ugn+lvg4SHczUdKlHI5LWBXyqfS8+DufyBsgQ== +damerau-levenshtein@^1.0.8: + version "1.0.8" + resolved "https://registry.yarnpkg.com/damerau-levenshtein/-/damerau-levenshtein-1.0.8.tgz#b43d286ccbd36bc5b2f7ed41caf2d0aba1f8a6e7" + integrity sha512-sdQSFB7+llfUcQHUQO3+B8ERRj0Oa4w9POWMI/puGtuf7gFywGmkaLCElnudfTiKZV+NvHqL0ifzdrI8Ro7ESA== + +dayjs@^1.11.10: + version "1.11.10" + resolved "https://registry.yarnpkg.com/dayjs/-/dayjs-1.11.10.tgz#68acea85317a6e164457d6d6947564029a6a16a0" + integrity sha512-vjAczensTgRcqDERK0SR2XMwsF/tSvnvlv6VcF2GIhg6Sx4yOIt/irsr1RDJsKiIyBzJDpCoXiWWq28MqH2cnQ== + +debug@^3.2.7: + version "3.2.7" + resolved "https://registry.yarnpkg.com/debug/-/debug-3.2.7.tgz#72580b7e9145fb39b6676f9c5e5fb100b934179a" + integrity sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ== + dependencies: + ms "^2.1.1" + debug@^4.1.1, debug@^4.3.2, debug@^4.3.4: version "4.3.4" resolved "https://registry.yarnpkg.com/debug/-/debug-4.3.4.tgz#1319f6579357f2338d3337d2cdd4914bb5dcc865" @@ -1062,6 +1042,11 @@ define-properties@^1.1.3, define-properties@^1.1.4, define-properties@^1.2.0, de has-property-descriptors "^1.0.0" object-keys "^1.1.1" +dequal@^2.0.3: + version "2.0.3" + resolved "https://registry.yarnpkg.com/dequal/-/dequal-2.0.3.tgz#2644214f1997d39ed0ee0ece72335490a7ac67be" + integrity sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA== + didyoumean@^1.2.2: version "1.2.2" resolved "https://registry.yarnpkg.com/didyoumean/-/didyoumean-1.2.2.tgz#989346ffe9e839b4555ecf5666edea0d3e8ad037" @@ -1093,19 +1078,24 @@ doctrine@^3.0.0: dependencies: esutils "^2.0.2" -dom-helpers@^5.0.1: - version "5.2.1" - resolved "https://registry.yarnpkg.com/dom-helpers/-/dom-helpers-5.2.1.tgz#d9400536b2bf8225ad98fe052e029451ac40e902" - integrity sha512-nRCa7CK3VTrM2NmGkIy4cbK7IZlgBE/PYMn55rrXefr5xXDP0LdtfPnblFDoVdcAfslJ7or6iqAUnx0CCGIWQA== - dependencies: - "@babel/runtime" "^7.8.7" - csstype "^3.0.2" - electron-to-chromium@^1.4.535: version "1.4.588" resolved "https://registry.yarnpkg.com/electron-to-chromium/-/electron-to-chromium-1.4.588.tgz#d553f3c008e73488fb181fdf2601fdb0b1ffbb78" integrity sha512-soytjxwbgcCu7nh5Pf4S2/4wa6UIu+A3p03U2yVr53qGxi1/VTR3ENI+p50v+UxqqZAfl48j3z55ud7VHIOr9w== +emoji-regex@^9.2.2: + version "9.2.2" + resolved "https://registry.yarnpkg.com/emoji-regex/-/emoji-regex-9.2.2.tgz#840c8803b0d8047f4ff0cf963176b32d4ef3ed72" + integrity sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg== + +enhanced-resolve@^5.12.0: + version "5.15.0" + resolved "https://registry.yarnpkg.com/enhanced-resolve/-/enhanced-resolve-5.15.0.tgz#1af946c7d93603eb88e9896cee4904dc012e9c35" + integrity sha512-LXYT42KJ7lpIKECr2mAXIaMldcNCh/7E0KBKOu4KSfkHmP+mZmSs+8V5gBAqisWBy0OO4W5Oyys0GO1Y8KtdKg== + dependencies: + graceful-fs "^4.2.4" + tapable "^2.2.0" + es-abstract@^1.22.1: version "1.22.3" resolved "https://registry.yarnpkg.com/es-abstract/-/es-abstract-1.22.3.tgz#48e79f5573198de6dee3589195727f4f74bc4f32" @@ -1151,7 +1141,7 @@ es-abstract@^1.22.1: unbox-primitive "^1.0.2" which-typed-array "^1.1.13" -es-iterator-helpers@^1.0.12: +es-iterator-helpers@^1.0.12, es-iterator-helpers@^1.0.15: version "1.0.15" resolved "https://registry.yarnpkg.com/es-iterator-helpers/-/es-iterator-helpers-1.0.15.tgz#bd81d275ac766431d19305923707c3efd9f1ae40" integrity sha512-GhoY8uYqd6iwUl2kgjTm4CZAf6oo5mHK7BPqx3rKgx893YSsy0LGHV6gfqqQvZt/8xM8xeOnfXBCfqclMKkJ5g== @@ -1239,6 +1229,80 @@ eslint-config-prettier@^9.0.0: resolved "https://registry.yarnpkg.com/eslint-config-prettier/-/eslint-config-prettier-9.0.0.tgz#eb25485946dd0c66cd216a46232dc05451518d1f" integrity sha512-IcJsTkJae2S35pRsRAwoCE+925rJJStOdkKnLVgtE+tEpqU0EVVM7OqrwxqgptKdX29NUwC82I5pXsGFIgSevw== +eslint-import-resolver-node@^0.3.9: + version "0.3.9" + resolved "https://registry.yarnpkg.com/eslint-import-resolver-node/-/eslint-import-resolver-node-0.3.9.tgz#d4eaac52b8a2e7c3cd1903eb00f7e053356118ac" + integrity sha512-WFj2isz22JahUv+B788TlO3N6zL3nNJGU8CcZbPZvVEkBPaJdCV4vy5wyghty5ROFbCRnm132v8BScu5/1BQ8g== + dependencies: + debug "^3.2.7" + is-core-module "^2.13.0" + resolve "^1.22.4" + +eslint-import-resolver-typescript@^3.6.1: + version "3.6.1" + resolved "https://registry.yarnpkg.com/eslint-import-resolver-typescript/-/eslint-import-resolver-typescript-3.6.1.tgz#7b983680edd3f1c5bce1a5829ae0bc2d57fe9efa" + integrity sha512-xgdptdoi5W3niYeuQxKmzVDTATvLYqhpwmykwsh7f6HIOStGWEIL9iqZgQDF9u9OEzrRwR8no5q2VT+bjAujTg== + dependencies: + debug "^4.3.4" + enhanced-resolve "^5.12.0" + eslint-module-utils "^2.7.4" + fast-glob "^3.3.1" + get-tsconfig "^4.5.0" + is-core-module "^2.11.0" + is-glob "^4.0.3" + +eslint-module-utils@^2.7.4, eslint-module-utils@^2.8.0: + version "2.8.0" + resolved "https://registry.yarnpkg.com/eslint-module-utils/-/eslint-module-utils-2.8.0.tgz#e439fee65fc33f6bba630ff621efc38ec0375c49" + integrity sha512-aWajIYfsqCKRDgUfjEXNN/JlrzauMuSEy5sbd7WXbtW3EH6A6MpwEh42c7qD+MqQo9QMJ6fWLAeIJynx0g6OAw== + dependencies: + debug "^3.2.7" + +eslint-plugin-import@^2.29.0: + version "2.29.0" + resolved "https://registry.yarnpkg.com/eslint-plugin-import/-/eslint-plugin-import-2.29.0.tgz#8133232e4329ee344f2f612885ac3073b0b7e155" + integrity sha512-QPOO5NO6Odv5lpoTkddtutccQjysJuFxoPS7fAHO+9m9udNHvTCPSAMW9zGAYj8lAIdr40I8yPCdUYrncXtrwg== + dependencies: + array-includes "^3.1.7" + array.prototype.findlastindex "^1.2.3" + array.prototype.flat "^1.3.2" + array.prototype.flatmap "^1.3.2" + debug "^3.2.7" + doctrine "^2.1.0" + eslint-import-resolver-node "^0.3.9" + eslint-module-utils "^2.8.0" + hasown "^2.0.0" + is-core-module "^2.13.1" + is-glob "^4.0.3" + minimatch "^3.1.2" + object.fromentries "^2.0.7" + object.groupby "^1.0.1" + object.values "^1.1.7" + semver "^6.3.1" + tsconfig-paths "^3.14.2" + +eslint-plugin-jsx-a11y@^6.8.0: + version "6.8.0" + resolved "https://registry.yarnpkg.com/eslint-plugin-jsx-a11y/-/eslint-plugin-jsx-a11y-6.8.0.tgz#2fa9c701d44fcd722b7c771ec322432857fcbad2" + integrity sha512-Hdh937BS3KdwwbBaKd5+PLCOmYY6U4f2h9Z2ktwtNKvIdIEu137rjYbcb9ApSbVJfWxANNuiKTD/9tOKjK9qOA== + dependencies: + "@babel/runtime" "^7.23.2" + aria-query "^5.3.0" + array-includes "^3.1.7" + array.prototype.flatmap "^1.3.2" + ast-types-flow "^0.0.8" + axe-core "=4.7.0" + axobject-query "^3.2.1" + damerau-levenshtein "^1.0.8" + emoji-regex "^9.2.2" + es-iterator-helpers "^1.0.15" + hasown "^2.0.0" + jsx-ast-utils "^3.3.5" + language-tags "^1.0.9" + minimatch "^3.1.2" + object.entries "^1.1.7" + object.fromentries "^2.0.7" + eslint-plugin-react-hooks@^4.6.0: version "4.6.0" resolved "https://registry.yarnpkg.com/eslint-plugin-react-hooks/-/eslint-plugin-react-hooks-4.6.0.tgz#4c3e697ad95b77e93f8646aaa1630c1ba607edd3" @@ -1361,7 +1425,7 @@ fast-deep-equal@^3.1.1, fast-deep-equal@^3.1.3: resolved "https://registry.yarnpkg.com/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz#3a7d56b559d6cbc3eb512325244e619a65c6c525" integrity sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q== -fast-glob@^3.2.9, fast-glob@^3.3.0: +fast-glob@^3.2.9, fast-glob@^3.3.0, fast-glob@^3.3.1: version "3.3.2" resolved "https://registry.yarnpkg.com/fast-glob/-/fast-glob-3.3.2.tgz#a904501e57cfdd2ffcded45e99a54fef55e46129" integrity sha512-oX2ruAFQwf/Orj8m737Y5adxDQO0LAB7/S5MnxCdTNDd4p6BsyIVsv9JQsATbTSq8KHRpLwIHbVlUNatxd+1Ow== @@ -1485,6 +1549,13 @@ get-symbol-description@^1.0.0: call-bind "^1.0.2" get-intrinsic "^1.1.1" +get-tsconfig@^4.5.0: + version "4.7.2" + resolved "https://registry.yarnpkg.com/get-tsconfig/-/get-tsconfig-4.7.2.tgz#0dcd6fb330391d46332f4c6c1bf89a6514c2ddce" + integrity sha512-wuMsz4leaj5hbGgg4IvDU0bqJagpftG5l5cXIAvo8uZrqn0NJqwtfupTN00VnkQJPcIRrxYrm1Ue24btpCha2A== + dependencies: + resolve-pkg-maps "^1.0.0" + glob-parent@^5.1.2, glob-parent@~5.1.2: version "5.1.2" resolved "https://registry.yarnpkg.com/glob-parent/-/glob-parent-5.1.2.tgz#869832c58034fe68a4093c17dc15e8340d8401c4" @@ -1556,6 +1627,11 @@ gopd@^1.0.1: dependencies: get-intrinsic "^1.1.3" +graceful-fs@^4.2.4: + version "4.2.11" + resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.11.tgz#4183e4e8bf08bb6e05bbb2f7d2e0c8f712ca40e3" + integrity sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ== + graphemer@^1.4.0: version "1.4.0" resolved "https://registry.yarnpkg.com/graphemer/-/graphemer-1.4.0.tgz#fb2f1d55e0e3a1849aeffc90c4fa0dd53a0e66c6" @@ -1699,7 +1775,7 @@ is-callable@^1.1.3, is-callable@^1.1.4, is-callable@^1.2.7: resolved "https://registry.yarnpkg.com/is-callable/-/is-callable-1.2.7.tgz#3bc2a85ea742d9e36205dcacdd72ca1fdc51b055" integrity sha512-1BC0BVFhS/p0qtw6enp8e+8OD0UrK0oFLztSjNzhcKA3WDuJxxAPXzPuPtKkjEY9UUoEWlX/8fgKeu2S8i9JTA== -is-core-module@^2.13.0: +is-core-module@^2.11.0, is-core-module@^2.13.0, is-core-module@^2.13.1: version "2.13.1" resolved "https://registry.yarnpkg.com/is-core-module/-/is-core-module-2.13.1.tgz#ad0d7532c6fea9da1ebdc82742d74525c6273384" integrity sha512-hHrIjvZsftOsvKSn2TRYl63zvxsgE0K+0mYMoH6gD4omR5IWB2KynivBQczo3+wF1cCkjzvptnI9Q0sPU66ilw== @@ -1880,7 +1956,14 @@ json-stable-stringify-without-jsonify@^1.0.1: resolved "https://registry.yarnpkg.com/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz#9db7b59496ad3f3cfef30a75142d2d930ad72651" integrity sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw== -"jsx-ast-utils@^2.4.1 || ^3.0.0": +json5@^1.0.2: + version "1.0.2" + resolved "https://registry.yarnpkg.com/json5/-/json5-1.0.2.tgz#63d98d60f21b313b77c4d6da18bfa69d80e1d593" + integrity sha512-g1MWMLBiz8FKi1e4w0UyVL3w+iJceWAFBAaBnnGKOpNa5f8TLktkbre1+s6oICydWAm+HRUGTmI+//xv2hvXYA== + dependencies: + minimist "^1.2.0" + +"jsx-ast-utils@^2.4.1 || ^3.0.0", jsx-ast-utils@^3.3.5: version "3.3.5" resolved "https://registry.yarnpkg.com/jsx-ast-utils/-/jsx-ast-utils-3.3.5.tgz#4766bd05a8e2a11af222becd19e15575e52a853a" integrity sha512-ZZow9HBI5O6EPgSJLUb8n2NKgmVWTwCvHGwFuJlMjvLFqlGG6pjirPhtdsseaLZjSibD8eegzmYpUZwoIlj2cQ== @@ -1897,6 +1980,18 @@ keyv@^4.5.3: dependencies: json-buffer "3.0.1" +language-subtag-registry@^0.3.20: + version "0.3.22" + resolved "https://registry.yarnpkg.com/language-subtag-registry/-/language-subtag-registry-0.3.22.tgz#2e1500861b2e457eba7e7ae86877cbd08fa1fd1d" + integrity sha512-tN0MCzyWnoz/4nHS6uxdlFWoUZT7ABptwKPQ52Ea7URk6vll88bWBVhodtnlfEuCcKWNGoc+uGbw1cwa9IKh/w== + +language-tags@^1.0.9: + version "1.0.9" + resolved "https://registry.yarnpkg.com/language-tags/-/language-tags-1.0.9.tgz#1ffdcd0ec0fafb4b1be7f8b11f306ad0f9c08777" + integrity sha512-MbjN408fEndfiQXbFQ1vnd+1NoLDsnQW41410oQBXiyXDMYH5z505juWa4KUE1LqxRC7DgOgZDbKLxHIwm27hA== + dependencies: + language-subtag-registry "^0.3.20" + levn@^0.4.1: version "0.4.1" resolved "https://registry.yarnpkg.com/levn/-/levn-0.4.1.tgz#ae4562c007473b932a6200d403268dd2fffc6ade" @@ -1966,11 +2061,21 @@ minimatch@^3.0.4, minimatch@^3.0.5, minimatch@^3.1.1, minimatch@^3.1.2: dependencies: brace-expansion "^1.1.7" +minimist@^1.2.0, minimist@^1.2.6: + version "1.2.8" + resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.8.tgz#c1a464e7693302e082a075cee0c057741ac4772c" + integrity sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA== + ms@2.1.2: version "2.1.2" resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.2.tgz#d09d1f357b443f493382a8eb3ccd183872ae6009" integrity sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w== +ms@^2.1.1: + version "2.1.3" + resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.3.tgz#574c8138ce1d2b5861f0b44579dbadd60c6615b2" + integrity sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA== + mz@^2.7.0: version "2.7.0" resolved "https://registry.yarnpkg.com/mz/-/mz-2.7.0.tgz#95008057a56cafadc2bc63dde7f9ff6955948e32" @@ -2035,7 +2140,7 @@ object.assign@^4.1.4: has-symbols "^1.0.3" object-keys "^1.1.1" -object.entries@^1.1.6: +object.entries@^1.1.6, object.entries@^1.1.7: version "1.1.7" resolved "https://registry.yarnpkg.com/object.entries/-/object.entries-1.1.7.tgz#2b47760e2a2e3a752f39dd874655c61a7f03c131" integrity sha512-jCBs/0plmPsOnrKAfFQXRG2NFjlhZgjjcBLSmTnEhU8U6vVTsVe8ANeQJCHTl3gSsI4J+0emOoCgoKlmQPMgmA== @@ -2044,7 +2149,7 @@ object.entries@^1.1.6: define-properties "^1.2.0" es-abstract "^1.22.1" -object.fromentries@^2.0.6: +object.fromentries@^2.0.6, object.fromentries@^2.0.7: version "2.0.7" resolved "https://registry.yarnpkg.com/object.fromentries/-/object.fromentries-2.0.7.tgz#71e95f441e9a0ea6baf682ecaaf37fa2a8d7e616" integrity sha512-UPbPHML6sL8PI/mOqPwsH4G6iyXcCGzLin8KvEPenOZN5lpCNBZZQ+V62vdjB1mQHrmqGQt5/OJzemUA+KJmEA== @@ -2053,6 +2158,16 @@ object.fromentries@^2.0.6: define-properties "^1.2.0" es-abstract "^1.22.1" +object.groupby@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/object.groupby/-/object.groupby-1.0.1.tgz#d41d9f3c8d6c778d9cbac86b4ee9f5af103152ee" + integrity sha512-HqaQtqLnp/8Bn4GL16cj+CUYbnpe1bh0TtEaWvybszDG4tgxCJuRpV8VGuvNaI1fAnI4lUJzDG55MXcOH4JZcQ== + dependencies: + call-bind "^1.0.2" + define-properties "^1.2.0" + es-abstract "^1.22.1" + get-intrinsic "^1.2.1" + object.hasown@^1.1.2: version "1.1.3" resolved "https://registry.yarnpkg.com/object.hasown/-/object.hasown-1.1.3.tgz#6a5f2897bb4d3668b8e79364f98ccf971bda55ae" @@ -2061,7 +2176,7 @@ object.hasown@^1.1.2: define-properties "^1.2.0" es-abstract "^1.22.1" -object.values@^1.1.6: +object.values@^1.1.6, object.values@^1.1.7: version "1.1.7" resolved "https://registry.yarnpkg.com/object.values/-/object.values-1.1.7.tgz#617ed13272e7e1071b43973aa1655d9291b8442a" integrity sha512-aU6xnDFYT3x17e/f0IiiwlGPTy2jzMySGfUB4fq6z7CV8l85CWHDk5ErhyhpfDHhrOMwGFhSQkhMGHaIotA6Ng== @@ -2218,7 +2333,7 @@ prettier@^3.0.3: resolved "https://registry.yarnpkg.com/prettier/-/prettier-3.1.0.tgz#c6d16474a5f764ea1a4a373c593b779697744d5e" integrity sha512-TQLvXjq5IAibjh8EpBIkNKxO749UEWABoiIZehEPiY4GNpVdhaFKqSTu+QrlU6D2dPAfubRmtJTi4K4YkQ5eXw== -prop-types@^15.6.2, prop-types@^15.8.1: +prop-types@^15.8.1: version "15.8.1" resolved "https://registry.yarnpkg.com/prop-types/-/prop-types-15.8.1.tgz#67d87bf1a694f48435cf332c24af10214a3140b5" integrity sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg== @@ -2278,16 +2393,6 @@ react-router@6.19.0: dependencies: "@remix-run/router" "1.12.0" -react-transition-group@^4.4.5: - version "4.4.5" - resolved "https://registry.yarnpkg.com/react-transition-group/-/react-transition-group-4.4.5.tgz#e53d4e3f3344da8521489fbef8f2581d42becdd1" - integrity sha512-pZcd1MCJoiKiBR2NRxeCRg13uCXbydPnmB4EOeRrY7480qNWO8IIgQG6zlDkm6uRMsURXPuKq0GWtiM59a5Q6g== - dependencies: - "@babel/runtime" "^7.5.5" - dom-helpers "^5.0.1" - loose-envify "^1.4.0" - prop-types "^15.6.2" - react@^18.2.0: version "18.2.0" resolved "https://registry.yarnpkg.com/react/-/react-18.2.0.tgz#555bd98592883255fa00de14f1151a917b5d77d5" @@ -2340,7 +2445,12 @@ resolve-from@^4.0.0: resolved "https://registry.yarnpkg.com/resolve-from/-/resolve-from-4.0.0.tgz#4abcd852ad32dd7baabfe9b40e00a36db5f392e6" integrity sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g== -resolve@^1.1.7, resolve@^1.22.2: +resolve-pkg-maps@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz#616b3dc2c57056b5588c31cdf4b3d64db133720f" + integrity sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw== + +resolve@^1.1.7, resolve@^1.22.2, resolve@^1.22.4: version "1.22.8" resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.22.8.tgz#b6c87a9f2aa06dfab52e3d70ac8cde321fa5a48d" integrity sha512-oKWePCxqpd6FlLvGV1VU0x7bkPmmCNolxzjMf4NczoDnQcIWrAF+cPtZn5i6n+RfD2d9i0tzpKnG6Yk168yIyw== @@ -2533,16 +2643,16 @@ strip-ansi@^6.0.1: dependencies: ansi-regex "^5.0.1" +strip-bom@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/strip-bom/-/strip-bom-3.0.0.tgz#2334c18e9c759f7bdd56fdef7e9ae3d588e68ed3" + integrity sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA== + strip-json-comments@^3.1.1: version "3.1.1" resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-3.1.1.tgz#31f1281b3832630434831c310c01cccda8cbe006" integrity sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig== -stylis@4.2.0: - version "4.2.0" - resolved "https://registry.yarnpkg.com/stylis/-/stylis-4.2.0.tgz#79daee0208964c8fe695a42fcffcac633a211a51" - integrity sha512-Orov6g6BB1sDfYgzWfTHDOxamtX1bE/zo104Dh9e6fqJ3PooipYyfJ0pUmrZO2wAvO8YbEyeFrkV91XTsGMSrw== - sucrase@^3.32.0: version "3.34.0" resolved "https://registry.yarnpkg.com/sucrase/-/sucrase-3.34.0.tgz#1e0e2d8fcf07f8b9c3569067d92fbd8690fb576f" @@ -2596,6 +2706,11 @@ tailwindcss@^3.3.3: resolve "^1.22.2" sucrase "^3.32.0" +tapable@^2.2.0: + version "2.2.1" + resolved "https://registry.yarnpkg.com/tapable/-/tapable-2.2.1.tgz#1967a73ef4060a82f12ab96af86d52fdb76eeca0" + integrity sha512-GNzQvQTOIP6RyTfE2Qxb8ZVlNmw0n88vp1szwWRimP02mnTsx3Wtn5qRdqY9w2XduFNUgvOwhNnQsjwCp+kqaQ== + text-table@^0.2.0: version "0.2.0" resolved "https://registry.yarnpkg.com/text-table/-/text-table-0.2.0.tgz#7f5ee823ae805207c00af2df4a84ec3fcfa570b4" @@ -2632,6 +2747,16 @@ ts-interface-checker@^0.1.9: resolved "https://registry.yarnpkg.com/ts-interface-checker/-/ts-interface-checker-0.1.13.tgz#784fd3d679722bc103b1b4b8030bcddb5db2a699" integrity sha512-Y/arvbn+rrz3JCKl9C4kVNfTfSm2/mEp5FSz5EsZSANGPSlQrpRI5M4PKF+mJnE52jOO90PnPSc3Ur3bTQw0gA== +tsconfig-paths@^3.14.2: + version "3.14.2" + resolved "https://registry.yarnpkg.com/tsconfig-paths/-/tsconfig-paths-3.14.2.tgz#6e32f1f79412decd261f92d633a9dc1cfa99f088" + integrity sha512-o/9iXgCYc5L/JxCHPe3Hvh8Q/2xm5Z+p18PESBU6Ff33695QnCHBEjcytY2q19ua7Mbl/DavtBOLq+oG0RCL+g== + dependencies: + "@types/json5" "^0.0.29" + json5 "^1.0.2" + minimist "^1.2.6" + strip-bom "^3.0.0" + type-check@^0.4.0, type-check@~0.4.0: version "0.4.0" resolved "https://registry.yarnpkg.com/type-check/-/type-check-0.4.0.tgz#07b8203bfa7056c0657050e3ccd2c37730bab8f1" diff --git a/nym-wallet/Cargo.lock b/nym-wallet/Cargo.lock index cfb7f62908c..f54f027fd89 100644 --- a/nym-wallet/Cargo.lock +++ b/nym-wallet/Cargo.lock @@ -418,29 +418,6 @@ version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "845141a4fade3f790628b7daaaa298a25b204fb28907eb54febe5142db6ce653" -[[package]] -name = "boringtun" -version = "0.6.0" -source = "git+https://github.com/cloudflare/boringtun?rev=e1d6360d6ab4529fc942a078e4c54df107abe2ba#e1d6360d6ab4529fc942a078e4c54df107abe2ba" -dependencies = [ - "aead", - "base64 0.13.1", - "blake2 0.10.6", - "chacha20poly1305", - "hex", - "hmac 0.12.1", - "ip_network", - "ip_network_table", - "libc", - "nix", - "parking_lot", - "rand_core 0.6.4", - "ring", - "tracing", - "untrusted 0.9.0", - "x25519-dalek 2.0.0", -] - [[package]] name = "brotli" version = "3.3.4" @@ -615,30 +592,6 @@ dependencies = [ "keystream", ] -[[package]] -name = "chacha20" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818" -dependencies = [ - "cfg-if", - "cipher 0.4.4", - "cpufeatures", -] - -[[package]] -name = "chacha20poly1305" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35" -dependencies = [ - "aead", - "chacha20", - "cipher 0.4.4", - "poly1305", - "zeroize", -] - [[package]] name = "cipher" version = "0.3.0" @@ -656,7 +609,6 @@ checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" dependencies = [ "crypto-common", "inout", - "zeroize", ] [[package]] @@ -847,9 +799,9 @@ dependencies = [ [[package]] name = "cosmos-sdk-proto" -version = "0.19.0" +version = "0.20.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73c9d2043a9e617b0d602fbc0a0ecd621568edbf3a9774890a6d562389bd8e1c" +checksum = "32560304ab4c365791fd307282f76637213d8083c1a98490c35159cd67852237" dependencies = [ "prost", "prost-types", @@ -858,19 +810,19 @@ dependencies = [ [[package]] name = "cosmrs" -version = "0.14.0" +version = "0.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af13955d6f356272e6def9ff5e2450a7650df536d8934f47052a20c76513d2f6" +checksum = "47126f5364df9387b9d8559dcef62e99010e1d4098f39eb3f7ee4b5c254e40ea" dependencies = [ "bip32", "cosmos-sdk-proto", "ecdsa 0.16.8", "eyre", - "getrandom 0.2.10", "k256 0.13.1", "rand_core 0.6.4", "serde", "serde_json", + "signature 2.1.0", "subtle-encoding", "tendermint", "tendermint-rpc", @@ -1062,15 +1014,6 @@ dependencies = [ "syn 2.0.28", ] -[[package]] -name = "ct-logs" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1a816186fa68d9e426e3cb4ae4dff1fcd8e4a2c34b781bf7a822574a0d0aac8" -dependencies = [ - "sct", -] - [[package]] name = "ctor" version = "0.1.26" @@ -2361,31 +2304,6 @@ version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2c6201b9ff9fd90a5a3bac2e56a830d0caa509576f0e503818ee82c181b3437a" -[[package]] -name = "headers" -version = "0.3.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3e372db8e5c0d213e0cd0b9be18be2aca3d44cf2fe30a9d46a65581cd454584" -dependencies = [ - "base64 0.13.1", - "bitflags 1.3.2", - "bytes", - "headers-core", - "http", - "httpdate", - "mime", - "sha1", -] - -[[package]] -name = "headers-core" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7f66481bfee273957b1f20485a4ff3362987f85b2c236580d81b4eb7a326429" -dependencies = [ - "http", -] - [[package]] name = "heck" version = "0.3.3" @@ -2574,41 +2492,18 @@ dependencies = [ "want", ] -[[package]] -name = "hyper-proxy" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca815a891b24fdfb243fa3239c86154392b0953ee584aa1a2a1f66d20cbe75cc" -dependencies = [ - "bytes", - "futures", - "headers", - "http", - "hyper", - "hyper-rustls", - "rustls-native-certs", - "tokio", - "tokio-rustls", - "tower-service", - "webpki", -] - [[package]] name = "hyper-rustls" -version = "0.22.1" +version = "0.24.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f9f7a97316d44c0af9b0301e65010573a853a9fc97046d7331d7f6bc0fd5a64" +checksum = "ec3efd23720e2049821a693cbc7e65ea87c72f1c58ff2f9522ff332b1491e590" dependencies = [ - "ct-logs", "futures-util", + "http", "hyper", - "log", "rustls", - "rustls-native-certs", "tokio", "tokio-rustls", - "webpki", - "webpki-roots", ] [[package]] @@ -2734,28 +2629,6 @@ dependencies = [ "cfg-if", ] -[[package]] -name = "ip_network" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa2f047c0a98b2f299aa5d6d7088443570faae494e9ae1305e48be000c9e0eb1" - -[[package]] -name = "ip_network_table" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4099b7cfc5c5e2fe8c5edf3f6f7adf7a714c9cc697534f63a5a5da30397cb2c0" -dependencies = [ - "ip_network", - "ip_network_table-deps-treebitmap", -] - -[[package]] -name = "ip_network_table-deps-treebitmap" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e537132deb99c0eb4b752f0346b6a836200eaaa3516dd7e5514b63930a09e5d" - [[package]] name = "ipnet" version = "2.8.0" @@ -3166,18 +3039,6 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e4a24736216ec316047a1fc4252e27dabb04218aa4a3f37c6e7ddbf1f9782b54" -[[package]] -name = "nix" -version = "0.25.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f346ff70e7dbfd675fe90590b92d59ef2de15a8779ae305ebcbfd3f0caf59be4" -dependencies = [ - "autocfg", - "bitflags 1.3.2", - "cfg-if", - "libc", -] - [[package]] name = "nodrop" version = "0.1.14" @@ -3602,6 +3463,7 @@ version = "0.1.0" dependencies = [ "async-trait", "base64 0.13.1", + "bip32", "bip39", "colored 2.0.4", "cosmrs", @@ -3696,11 +3558,7 @@ name = "nym-wireguard-types" version = "0.1.0" dependencies = [ "base64 0.21.4", - "boringtun", - "bytes", "dashmap", - "ip_network", - "ip_network_table", "log", "nym-crypto", "serde", @@ -3711,7 +3569,7 @@ dependencies = [ [[package]] name = "nym_wallet" -version = "1.2.10" +version = "1.2.11" dependencies = [ "async-trait", "base64 0.13.1", @@ -4269,17 +4127,6 @@ dependencies = [ "miniz_oxide", ] -[[package]] -name = "poly1305" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf" -dependencies = [ - "cpufeatures", - "opaque-debug 0.3.0", - "universal-hash", -] - [[package]] name = "polyval" version = "0.6.1" @@ -4365,9 +4212,9 @@ dependencies = [ [[package]] name = "prost" -version = "0.11.9" +version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b82eaa1d779e9a4bc1c3217db8ffbeabaae1dca241bf70183242128d48681cd" +checksum = "146c289cda302b98a28d40c8b3b90498d6e526dd24ac2ecea73e4e491685b94a" dependencies = [ "bytes", "prost-derive", @@ -4375,22 +4222,22 @@ dependencies = [ [[package]] name = "prost-derive" -version = "0.11.9" +version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5d2d8d10f3c6ded6da8b05b5fb3b8a5082514344d56c9f871412d29b4e075b4" +checksum = "efb6c9a1dd1def8e2124d17e83a20af56f1570d6c2d2bd9e266ccb768df3840e" dependencies = [ "anyhow", - "itertools 0.10.5", + "itertools 0.11.0", "proc-macro2", "quote", - "syn 1.0.109", + "syn 2.0.28", ] [[package]] name = "prost-types" -version = "0.11.9" +version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "213622a1460818959ac1181aaeb2dc9c7f63df720db7d788b3e24eacd1983e13" +checksum = "193898f59edcf43c26227dcd4c8427f00d99d61e95dcde58dabd49fa291d470e" dependencies = [ "prost", ] @@ -4616,6 +4463,7 @@ dependencies = [ "http", "http-body", "hyper", + "hyper-rustls", "hyper-tls", "ipnet", "js-sys", @@ -4625,12 +4473,16 @@ dependencies = [ "once_cell", "percent-encoding", "pin-project-lite", + "rustls", + "rustls-native-certs", + "rustls-pemfile", "serde", "serde_json", "serde_urlencoded", "system-configuration", "tokio", "tokio-native-tls", + "tokio-rustls", "tower-service", "url", "wasm-bindgen", @@ -4686,17 +4538,16 @@ dependencies = [ [[package]] name = "ring" -version = "0.16.20" +version = "0.17.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3053cf52e236a3ed746dfc745aa9cacf1b791d846bdaf412f60a8d7d6e17c8fc" +checksum = "9babe80d5c16becf6594aa32ad2be8fe08498e7ae60b77de8df700e67f191d7e" dependencies = [ "cc", + "getrandom 0.2.10", "libc", - "once_cell", "spin", - "untrusted 0.7.1", - "web-sys", - "winapi", + "untrusted", + "windows-sys 0.48.0", ] [[package]] @@ -4738,29 +4589,47 @@ dependencies = [ [[package]] name = "rustls" -version = "0.19.1" +version = "0.21.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "35edb675feee39aec9c99fa5ff985081995a06d594114ae14cbe797ad7b7a6d7" +checksum = "629648aced5775d558af50b2b4c7b02983a04b312126d45eeead26e7caa498b9" dependencies = [ - "base64 0.13.1", "log", "ring", + "rustls-webpki", "sct", - "webpki", ] [[package]] name = "rustls-native-certs" -version = "0.5.0" +version = "0.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a07b7c1885bd8ed3831c289b7870b13ef46fe0e856d288c30d9cc17d75a2092" +checksum = "a9aace74cb666635c918e9c12bc0d348266037aa8eb599b5cba565709a8dff00" dependencies = [ "openssl-probe", - "rustls", + "rustls-pemfile", "schannel", "security-framework", ] +[[package]] +name = "rustls-pemfile" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c74cae0a4cf6ccbbf5f359f08efdf8ee7e1dc532573bf0db71968cb56b1448c" +dependencies = [ + "base64 0.21.4", +] + +[[package]] +name = "rustls-webpki" +version = "0.101.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b6275d1ee7a1cd780b64aca7726599a1dbc893b1e64144529e55c3c2f745765" +dependencies = [ + "ring", + "untrusted", +] + [[package]] name = "rustversion" version = "1.0.14" @@ -4836,12 +4705,12 @@ checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" [[package]] name = "sct" -version = "0.6.1" +version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b362b83898e0e69f38515b82ee15aa80636befe47c3b6d3d89a911e78fc228ce" +checksum = "da046153aa2352493d6cb7da4b6e5c0c057d8a1d0a9aa8560baffdd945acd414" dependencies = [ "ring", - "untrusted 0.7.1", + "untrusted", ] [[package]] @@ -5088,17 +4957,6 @@ dependencies = [ "stable_deref_trait", ] -[[package]] -name = "sha1" -version = "0.10.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f04293dc80c3993519f2d7f6f511707ee7094fe0c6d3406feb330cdb3540eba3" -dependencies = [ - "cfg-if", - "cpufeatures", - "digest 0.10.7", -] - [[package]] name = "sha2" version = "0.9.9" @@ -5262,9 +5120,9 @@ dependencies = [ [[package]] name = "spin" -version = "0.5.2" +version = "0.9.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d" +checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67" [[package]] name = "spki" @@ -5734,9 +5592,9 @@ dependencies = [ [[package]] name = "tendermint" -version = "0.32.2" +version = "0.34.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f0a7d05cf78524782337f8edd55cbc578d159a16ad4affe2135c92f7dbac7f0" +checksum = "bc2294fa667c8b548ee27a9ba59115472d0a09c2ba255771092a7f1dcf03a789" dependencies = [ "bytes", "digest 0.10.7", @@ -5765,9 +5623,9 @@ dependencies = [ [[package]] name = "tendermint-config" -version = "0.32.2" +version = "0.34.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "71a72dbbea6dde12045d261f2c70c0de039125675e8a026c8d5ad34522756372" +checksum = "5a25dbe8b953e80f3d61789fbdb83bf9ad6c0ef16df5ca6546f49912542cc137" dependencies = [ "flex-error", "serde", @@ -5779,9 +5637,9 @@ dependencies = [ [[package]] name = "tendermint-proto" -version = "0.32.2" +version = "0.34.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0cec054567d16d85e8c3f6a3139963d1a66d9d3051ed545d31562550e9bcc3d" +checksum = "2cc728a4f9e891d71adf66af6ecaece146f9c7a11312288a3107b3e1d6979aaf" dependencies = [ "bytes", "flex-error", @@ -5797,21 +5655,18 @@ dependencies = [ [[package]] name = "tendermint-rpc" -version = "0.32.2" +version = "0.34.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d119d83a130537fc4a98c3c9eb6899ebe857fea4860400a61675bfb5f0b35129" +checksum = "dfbf0a4753b46a190f367337e0163d0b552a2674a6bac54e74f9f2cdcde2969b" dependencies = [ "async-trait", "bytes", "flex-error", "futures", "getrandom 0.2.10", - "http", - "hyper", - "hyper-proxy", - "hyper-rustls", "peg", "pin-project", + "reqwest", "semver 1.0.18", "serde", "serde_bytes", @@ -5973,13 +5828,12 @@ dependencies = [ [[package]] name = "tokio-rustls" -version = "0.22.0" +version = "0.24.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc6844de72e57df1980054b38be3a9f4702aba4858be64dd700181a8a6d0e1b6" +checksum = "c28327cf380ac148141087fbfb9de9d7bd4e84ab5d2c28fbc911d753de8a7081" dependencies = [ "rustls", "tokio", - "webpki", ] [[package]] @@ -6194,12 +6048,6 @@ dependencies = [ "subtle 2.4.1", ] -[[package]] -name = "untrusted" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a" - [[package]] name = "untrusted" version = "0.9.0" @@ -6208,9 +6056,9 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" [[package]] name = "url" -version = "2.4.0" +version = "2.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50bff7831e19200a85b17131d085c25d7811bc4e186efdaf54bbd132994a88cb" +checksum = "143b538f18257fac9cad154828a57c6bf5157e1aa604d4816b5995bf6de87ae5" dependencies = [ "form_urlencoded", "idna", @@ -6460,25 +6308,6 @@ dependencies = [ "system-deps 6.1.1", ] -[[package]] -name = "webpki" -version = "0.21.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8e38c0608262c46d4a56202ebabdeb094cef7e560ca7a226c6bf055188aa4ea" -dependencies = [ - "ring", - "untrusted 0.7.1", -] - -[[package]] -name = "webpki-roots" -version = "0.21.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aabe153544e473b775453675851ecc86863d2a81d786d741f6b76778f2a48940" -dependencies = [ - "webpki", -] - [[package]] name = "webview2-com" version = "0.19.1" diff --git a/nym-wallet/nym-wallet-types/Cargo.toml b/nym-wallet/nym-wallet-types/Cargo.toml index ca422a98327..924d8168e92 100644 --- a/nym-wallet/nym-wallet-types/Cargo.toml +++ b/nym-wallet/nym-wallet-types/Cargo.toml @@ -12,7 +12,7 @@ strum = { version = "0.23", features = ["derive"] } ts-rs = "7.0.0" cosmwasm-std = "1.3.0" -cosmrs = "=0.14.0" +cosmrs = "=0.15.0" nym-config = { path = "../../common/config" } nym-network-defaults = { path = "../../common/network-defaults" } diff --git a/nym-wallet/src-tauri/Cargo.toml b/nym-wallet/src-tauri/Cargo.toml index eaced888a4f..1182ef2d1c6 100644 --- a/nym-wallet/src-tauri/Cargo.toml +++ b/nym-wallet/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "nym_wallet" -version = "1.2.10" +version = "1.2.11" description = "Nym Native Wallet" authors = ["Nym Technologies SA"] license = "" @@ -49,7 +49,7 @@ base64 = "0.13" zeroize = { version = "1.5", features = ["zeroize_derive", "serde"] } cosmwasm-std = "1.3.0" -cosmrs = "=0.14.0" +cosmrs = "=0.15.0" nym-validator-client = { path = "../../common/client-libs/validator-client" } nym-crypto = { path = "../../common/crypto", features = ["asymmetric"] } diff --git a/nym-wallet/src-tauri/tauri.conf.json b/nym-wallet/src-tauri/tauri.conf.json index 43330b25871..8aabb2bc803 100644 --- a/nym-wallet/src-tauri/tauri.conf.json +++ b/nym-wallet/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "package": { "productName": "nym-wallet", - "version": "1.2.10" + "version": "1.2.11" }, "build": { "distDir": "../dist", diff --git a/sdk/rust/nym-sdk/src/mixnet/client.rs b/sdk/rust/nym-sdk/src/mixnet/client.rs index 227ee5868c1..1c18a5f3d0c 100644 --- a/sdk/rust/nym-sdk/src/mixnet/client.rs +++ b/sdk/rust/nym-sdk/src/mixnet/client.rs @@ -11,7 +11,9 @@ use crate::{Error, Result}; use futures::channel::mpsc; use futures::StreamExt; use log::warn; -use nym_client_core::client::base_client::storage::gateway_details::GatewayDetailsStore; +use nym_client_core::client::base_client::storage::gateway_details::{ + GatewayDetailsStore, PersistedGatewayDetails, +}; use nym_client_core::client::base_client::storage::{ Ephemeral, MixnetClientStorage, OnDiskPersistent, }; @@ -24,6 +26,7 @@ use nym_client_core::{ client::{base_client::BaseClientBuilder, replies::reply_storage::ReplyStorageBackend}, config::GatewayEndpointConfig, }; +use nym_network_defaults::{DEFAULT_CLIENT_LISTENING_PORT, WG_TUN_DEVICE_ADDRESS}; use nym_socks5_client_core::config::Socks5; use nym_task::manager::TaskStatus; use nym_task::{TaskClient, TaskHandle}; @@ -44,6 +47,7 @@ pub struct MixnetClientBuilder { gateway_config: Option, socks5_config: Option, + wireguard_mode: bool, wait_for_gateway: bool, custom_topology_provider: Option>, custom_gateway_transceiver: Option>, @@ -79,6 +83,7 @@ impl MixnetClientBuilder { storage_paths: None, gateway_config: None, socks5_config: None, + wireguard_mode: false, wait_for_gateway: false, custom_topology_provider: None, storage: storage_paths @@ -109,6 +114,7 @@ where storage_paths: None, gateway_config: None, socks5_config: None, + wireguard_mode: false, wait_for_gateway: false, custom_topology_provider: None, custom_gateway_transceiver: None, @@ -127,6 +133,7 @@ where storage_paths: self.storage_paths, gateway_config: self.gateway_config, socks5_config: self.socks5_config, + wireguard_mode: self.wireguard_mode, wait_for_gateway: self.wait_for_gateway, custom_topology_provider: self.custom_topology_provider, custom_gateway_transceiver: self.custom_gateway_transceiver, @@ -205,6 +212,13 @@ where self } + /// Attempt to wait for the selected gateway (if applicable) to come online if its currently not bonded. + #[must_use] + pub fn with_wireguard_mode(mut self, wireguard_mode: bool) -> Self { + self.wireguard_mode = wireguard_mode; + self + } + /// Attempt to wait for the selected gateway (if applicable) to come online if its currently not bonded. #[must_use] pub fn with_wait_for_gateway(mut self, wait_for_gateway: bool) -> Self { @@ -235,6 +249,7 @@ where .custom_gateway_transceiver(self.custom_gateway_transceiver) .custom_topology_provider(self.custom_topology_provider) .custom_shutdown(self.custom_shutdown) + .wireguard_mode(self.wireguard_mode) .wait_for_gateway(self.wait_for_gateway) .force_tls(self.force_tls); @@ -274,6 +289,9 @@ where /// advanced usage of custom gateways custom_gateway_transceiver: Option>, + /// If the client connects via Wireguard tunnel to the gateway. + wireguard_mode: bool, + /// Attempt to wait for the selected gateway (if applicable) to come online if its currently not bonded. wait_for_gateway: bool, @@ -326,6 +344,7 @@ where storage, custom_topology_provider: None, custom_gateway_transceiver: None, + wireguard_mode: false, wait_for_gateway: false, force_tls: false, custom_shutdown: None, @@ -356,6 +375,12 @@ where self } + #[must_use] + pub fn wireguard_mode(mut self, wireguard_mode: bool) -> Self { + self.wireguard_mode = wireguard_mode; + self + } + #[must_use] pub fn wait_for_gateway(mut self, wait_for_gateway: bool) -> Self { self.wait_for_gateway = wait_for_gateway; @@ -503,11 +528,7 @@ where let known_gateway = self.has_valid_gateway_info().await; - let mut base_builder: BaseClientBuilder<_, _> = - BaseClientBuilder::new(&base_config, self.storage, self.dkg_query_client) - .with_wait_for_gateway(self.wait_for_gateway); - - if !known_gateway { + let mut base_builder: BaseClientBuilder<_, _> = if !known_gateway { let selection_spec = GatewaySelectionSpecification::new( self.config.user_chosen_gateway, None, @@ -515,14 +536,49 @@ where ); let mut rng = OsRng; + let mut available_gateways = current_gateways(&mut rng, &nym_api_endpoints).await?; + if self.wireguard_mode { + available_gateways + .iter_mut() + .for_each(|node| node.host = WG_TUN_DEVICE_ADDRESS.parse().unwrap()); + } let setup = GatewaySetup::New { specification: selection_spec, - available_gateways: current_gateways(&mut rng, &nym_api_endpoints).await?, + available_gateways, overwrite_data: !self.config.key_mode.is_keep(), }; - base_builder = base_builder.with_gateway_setup(setup) - } + BaseClientBuilder::new(&base_config, self.storage, self.dkg_query_client) + .with_wait_for_gateway(self.wait_for_gateway) + .with_gateway_setup(setup) + } else if self.wireguard_mode { + if let Ok(PersistedGatewayDetails::Default(mut config)) = self + .storage + .gateway_details_store() + .load_gateway_details() + .await + { + config.details.gateway_listener = format!( + "ws://{}:{}", + WG_TUN_DEVICE_ADDRESS, DEFAULT_CLIENT_LISTENING_PORT + ); + if let Err(e) = self + .storage + .gateway_details_store() + .store_gateway_details(&PersistedGatewayDetails::Default(config)) + .await + { + warn!("Could not switch to using wireguard mode - {:?}", e); + } + } else { + warn!("Storage type not supported with wireguard mode"); + } + BaseClientBuilder::new(&base_config, self.storage, self.dkg_query_client) + .with_wait_for_gateway(self.wait_for_gateway) + } else { + BaseClientBuilder::new(&base_config, self.storage, self.dkg_query_client) + .with_wait_for_gateway(self.wait_for_gateway) + }; if let Some(topology_provider) = self.custom_topology_provider { base_builder = base_builder.with_topology_provider(topology_provider); diff --git a/service-providers/ip-packet-router/Cargo.toml b/service-providers/ip-packet-router/Cargo.toml index df9822937e5..01ae4fb8974 100644 --- a/service-providers/ip-packet-router/Cargo.toml +++ b/service-providers/ip-packet-router/Cargo.toml @@ -27,6 +27,7 @@ nym-task = { path = "../../common/task" } nym-tun = { path = "../../common/tun" } nym-wireguard = { path = "../../common/wireguard" } nym-wireguard-types = { path = "../../common/wireguard-types" } +rand = "0.8.5" reqwest.workspace = true serde = { workspace = true, features = ["derive"] } serde_json = { workspace = true } @@ -34,3 +35,6 @@ tap.workspace = true thiserror = { workspace = true } tokio = { workspace = true, features = ["rt-multi-thread", "net", "io-util"] } url.workspace = true + +[target.'cfg(target_os = "linux")'.dependencies] +tokio-tun = "0.11.2" diff --git a/service-providers/ip-packet-router/src/constants.rs b/service-providers/ip-packet-router/src/constants.rs new file mode 100644 index 00000000000..8fc028a88d3 --- /dev/null +++ b/service-providers/ip-packet-router/src/constants.rs @@ -0,0 +1,9 @@ +use std::time::Duration; + +// The interface used to route traffic +pub const TUN_BASE_NAME: &str = "nymtun"; +pub const TUN_DEVICE_ADDRESS: &str = "10.0.0.1"; +pub const TUN_DEVICE_NETMASK: &str = "255.255.255.0"; + +pub(crate) const DISCONNECT_TIMER_INTERVAL: Duration = Duration::from_secs(10); +pub(crate) const CLIENT_INACTIVITY_TIMEOUT: Duration = Duration::from_secs(5 * 60); diff --git a/service-providers/ip-packet-router/src/error.rs b/service-providers/ip-packet-router/src/error.rs index 9c417a8f6e9..370b6014dbf 100644 --- a/service-providers/ip-packet-router/src/error.rs +++ b/service-providers/ip-packet-router/src/error.rs @@ -30,6 +30,9 @@ pub enum IpPacketRouterError { #[error("the entity wrapping the network requester has disconnected")] DisconnectedParent, + #[error("received packet has an invalid version: {0}")] + InvalidPacketVersion(u8), + #[error("failed to deserialize tagged packet: {source}")] FailedToDeserializeTaggedPacket { source: bincode::Error }, @@ -47,6 +50,9 @@ pub enum IpPacketRouterError { source: tokio::sync::mpsc::error::TrySendError<(u64, Vec)>, }, + #[error("failed to write packet to tun")] + FailedToWritePacketToTun, + #[error("the provided socket address, '{addr}' is not covered by the exit policy!")] AddressNotCoveredByExitPolicy { addr: SocketAddr }, diff --git a/service-providers/ip-packet-router/src/ip_packet_router.rs b/service-providers/ip-packet-router/src/ip_packet_router.rs new file mode 100644 index 00000000000..c514be4f1b0 --- /dev/null +++ b/service-providers/ip-packet-router/src/ip_packet_router.rs @@ -0,0 +1,500 @@ +#![cfg_attr(not(target_os = "linux"), allow(dead_code))] +#![cfg_attr(not(target_os = "linux"), allow(unused_imports))] + +use std::{collections::HashMap, net::IpAddr, path::Path}; + +use futures::{channel::oneshot, StreamExt}; +use nym_client_core::{ + client::mix_traffic::transceiver::GatewayTransceiver, HardcodedTopologyProvider, + TopologyProvider, +}; +use nym_ip_packet_requests::{ + DynamicConnectFailureReason, IpPacketRequest, IpPacketRequestData, IpPacketResponse, + StaticConnectFailureReason, +}; +use nym_sdk::mixnet::{InputMessage, MixnetMessageSender, Recipient}; +use nym_sphinx::receiver::ReconstructedMessage; +use nym_task::{connections::TransmissionLane, TaskClient, TaskHandle}; +#[cfg(target_os = "linux")] +use tokio::io::AsyncWriteExt; + +use crate::{ + constants::{CLIENT_INACTIVITY_TIMEOUT, DISCONNECT_TIMER_INTERVAL}, + error::IpPacketRouterError, + request_filter::{self, RequestFilter}, + util::generate_new_ip, + util::parse_ip::{parse_packet, ParsedPacket}, + Config, +}; + +pub struct OnStartData { + // to add more fields as required + pub address: Recipient, + + pub request_filter: RequestFilter, +} + +impl OnStartData { + pub fn new(address: Recipient, request_filter: RequestFilter) -> Self { + Self { + address, + request_filter, + } + } +} + +pub struct IpPacketRouterBuilder { + #[allow(unused)] + config: Config, + wait_for_gateway: bool, + custom_topology_provider: Option>, + custom_gateway_transceiver: Option>, + shutdown: Option, + on_start: Option>, +} + +impl IpPacketRouterBuilder { + pub fn new(config: Config) -> Self { + Self { + config, + wait_for_gateway: false, + custom_topology_provider: None, + custom_gateway_transceiver: None, + shutdown: None, + on_start: None, + } + } + + #[must_use] + pub fn with_shutdown(mut self, shutdown: TaskClient) -> Self { + self.shutdown = Some(shutdown); + self + } + + #[must_use] + pub fn with_custom_gateway_transceiver( + mut self, + gateway_transceiver: Box, + ) -> Self { + self.custom_gateway_transceiver = Some(gateway_transceiver); + self + } + + #[must_use] + pub fn with_wait_for_gateway(mut self, wait_for_gateway: bool) -> Self { + self.wait_for_gateway = wait_for_gateway; + self + } + + #[must_use] + pub fn with_on_start(mut self, on_start: oneshot::Sender) -> Self { + self.on_start = Some(on_start); + self + } + + #[must_use] + pub fn with_custom_topology_provider( + mut self, + topology_provider: Box, + ) -> Self { + self.custom_topology_provider = Some(topology_provider); + self + } + + pub fn with_stored_topology>( + mut self, + file: P, + ) -> Result { + self.custom_topology_provider = + Some(Box::new(HardcodedTopologyProvider::new_from_file(file)?)); + Ok(self) + } + + #[cfg(not(target_os = "linux"))] + pub async fn run_service_provider(self) -> Result<(), IpPacketRouterError> { + todo!("service provider is not yet supported on this platform") + } + + #[cfg(target_os = "linux")] + pub async fn run_service_provider(self) -> Result<(), IpPacketRouterError> { + // Used to notify tasks to shutdown. Not all tasks fully supports this (yet). + let task_handle: TaskHandle = self.shutdown.map(Into::into).unwrap_or_default(); + + // Connect to the mixnet + let mixnet_client = crate::mixnet_client::create_mixnet_client( + &self.config.base, + task_handle.get_handle().named("nym_sdk::MixnetClient"), + self.custom_gateway_transceiver, + self.custom_topology_provider, + self.wait_for_gateway, + &self.config.storage_paths.common_paths, + ) + .await?; + + let self_address = *mixnet_client.nym_address(); + + // Create the TUN device that we interact with the rest of the world with + let config = nym_tun::tun_device::TunDeviceConfig { + base_name: crate::constants::TUN_BASE_NAME.to_string(), + ip: crate::constants::TUN_DEVICE_ADDRESS.parse().unwrap(), + netmask: crate::constants::TUN_DEVICE_NETMASK.parse().unwrap(), + }; + let (tun_reader, tun_writer) = + tokio::io::split(nym_tun::tun_device::TunDevice::new_device_only(config)); + + // Channel used by the IpPacketRouter to signal connected and disconnected clients to the + // TunListener + let (connected_client_tx, connected_client_rx) = tokio::sync::mpsc::unbounded_channel(); + + let tun_listener = crate::tun_listener::TunListener { + tun_reader, + mixnet_client_sender: mixnet_client.split_sender(), + task_client: task_handle.get_handle(), + connected_clients: Default::default(), + connected_client_rx, + }; + tun_listener.start(); + + let request_filter = request_filter::RequestFilter::new(&self.config).await?; + request_filter.start_update_tasks().await; + + let ip_packet_router_service = IpPacketRouter { + _config: self.config, + request_filter: request_filter.clone(), + tun_writer, + mixnet_client, + task_handle, + connected_clients: Default::default(), + connected_client_tx, + }; + + log::info!("The address of this client is: {self_address}"); + log::info!("All systems go. Press CTRL-C to stop the server."); + + if let Some(on_start) = self.on_start { + if on_start + .send(OnStartData::new(self_address, request_filter)) + .is_err() + { + // the parent has dropped the channel before receiving the response + return Err(IpPacketRouterError::DisconnectedParent); + } + } + + ip_packet_router_service.run().await + } +} + +#[cfg(target_os = "linux")] +struct IpPacketRouter { + _config: Config, + request_filter: request_filter::RequestFilter, + tun_writer: tokio::io::WriteHalf, + mixnet_client: nym_sdk::mixnet::MixnetClient, + task_handle: TaskHandle, + + connected_clients: HashMap, + connected_client_tx: tokio::sync::mpsc::UnboundedSender, +} + +pub(crate) struct ConnectedClient { + pub(crate) nym_address: Recipient, + pub(crate) last_activity: std::time::Instant, +} + +#[cfg(target_os = "linux")] +impl IpPacketRouter { + async fn on_static_connect_request( + &mut self, + connect_request: nym_ip_packet_requests::StaticConnectRequest, + ) -> Result, IpPacketRouterError> { + log::info!( + "Received static connect request from {sender_address}", + sender_address = connect_request.reply_to + ); + + let request_id = connect_request.request_id; + let requested_ip = connect_request.ip; + let reply_to = connect_request.reply_to; + // TODO: ignoring reply_to_hops and reply_to_avg_mix_delays for now + + // Check that the IP is available in the set of connected clients + let is_ip_taken = self.connected_clients.contains_key(&requested_ip); + + // Check that the nym address isn't already registered + let is_nym_address_taken = self + .connected_clients + .values() + .any(|client| client.nym_address == reply_to); + + match (is_ip_taken, is_nym_address_taken) { + (true, true) => { + log::info!("Connecting an already connected client"); + // Update the last activity time for the client + if let Some(client) = self.connected_clients.get_mut(&requested_ip) { + client.last_activity = std::time::Instant::now(); + } else { + log::error!("Failed to update last activity time for client"); + } + Ok(Some(IpPacketResponse::new_static_connect_success( + request_id, reply_to, + ))) + } + (false, false) => { + log::info!("Connecting a new client"); + self.connected_clients.insert( + requested_ip, + ConnectedClient { + nym_address: reply_to, + last_activity: std::time::Instant::now(), + }, + ); + self.connected_client_tx + .send(ConnectedClientEvent::Connect( + requested_ip, + Box::new(reply_to), + )) + .unwrap(); + Ok(Some(IpPacketResponse::new_static_connect_success( + request_id, reply_to, + ))) + } + (true, false) => { + log::info!("Requested IP is not available"); + Ok(Some(IpPacketResponse::new_static_connect_failure( + request_id, + reply_to, + StaticConnectFailureReason::RequestedIpAlreadyInUse, + ))) + } + (false, true) => { + log::info!("Nym address is already registered"); + Ok(Some(IpPacketResponse::new_static_connect_failure( + request_id, + reply_to, + StaticConnectFailureReason::RequestedNymAddressAlreadyInUse, + ))) + } + } + } + + async fn on_dynamic_connect_request( + &mut self, + connect_request: nym_ip_packet_requests::DynamicConnectRequest, + ) -> Result, IpPacketRouterError> { + log::info!( + "Received dynamic connect request from {sender_address}", + sender_address = connect_request.reply_to + ); + + let request_id = connect_request.request_id; + let reply_to = connect_request.reply_to; + // TODO: ignoring reply_to_hops and reply_to_avg_mix_delays for now + + // Check if it's the same client connecting again, then we just reuse the same IP + // TODO: this is problematic. Until we sign connect requests this means you can spam people + // with return traffic + let existing_ip = self.connected_clients.iter().find_map(|(ip, client)| { + if client.nym_address == reply_to { + Some(*ip) + } else { + None + } + }); + + if let Some(existing_ip) = existing_ip { + log::info!("Found existing client for nym address"); + // Update the last activity time for the client + if let Some(client) = self.connected_clients.get_mut(&existing_ip) { + client.last_activity = std::time::Instant::now(); + } else { + log::error!("Failed to update last activity time for client"); + } + return Ok(Some(IpPacketResponse::new_dynamic_connect_success( + request_id, + reply_to, + existing_ip, + ))); + } + + let Some(new_ip) = generate_new_ip::find_new_ip(&self.connected_clients) else { + log::info!("No available IP address"); + return Ok(Some(IpPacketResponse::new_dynamic_connect_failure( + request_id, + reply_to, + DynamicConnectFailureReason::NoAvailableIp, + ))); + }; + + self.connected_clients.insert( + new_ip, + ConnectedClient { + nym_address: reply_to, + last_activity: std::time::Instant::now(), + }, + ); + self.connected_client_tx + .send(ConnectedClientEvent::Connect(new_ip, Box::new(reply_to))) + .unwrap(); + Ok(Some(IpPacketResponse::new_dynamic_connect_success( + request_id, reply_to, new_ip, + ))) + } + + async fn on_data_request( + &mut self, + data_request: nym_ip_packet_requests::DataRequest, + ) -> Result, IpPacketRouterError> { + log::trace!("Received data request"); + + // We don't forward packets that we are not able to parse. BUT, there might be a good + // reason to still forward them. + // + // For example, if we are running in a mode where we are only supposed to forward + // packets to a specific destination, we might want to forward them anyway. + // + // TODO: look into this + let ParsedPacket { + packet_type, + src_addr, + dst_addr, + dst, + } = parse_packet(&data_request.ip_packet)?; + + let dst_str = dst.map_or(dst_addr.to_string(), |dst| dst.to_string()); + log::info!("Received packet: {packet_type}: {src_addr} -> {dst_str}"); + + // Check if there is a connected client for this src_addr. If there is, update the last activity time + // for the client. If there isn't, drop the packet. + if let Some(client) = self.connected_clients.get_mut(&src_addr) { + client.last_activity = std::time::Instant::now(); + } else { + log::info!("Dropping packet: no connected client for {src_addr}"); + return Ok(None); + } + + // Filter check + if let Some(dst) = dst { + if !self.request_filter.check_address(&dst).await { + log::warn!("Failed filter check: {dst}"); + // TODO: we could consider sending back a response here + return Err(IpPacketRouterError::AddressFailedFilterCheck { addr: dst }); + } + } else { + // TODO: we should also filter packets without port number + log::warn!("Ignoring filter check for packet without port number! TODO!"); + } + + // TODO: consider changing from Vec to bytes::Bytes? + let packet = data_request.ip_packet; + self.tun_writer + .write_all(&packet) + .await + .map_err(|_| IpPacketRouterError::FailedToWritePacketToTun)?; + + Ok(None) + } + async fn on_reconstructed_message( + &mut self, + reconstructed: ReconstructedMessage, + ) -> Result, IpPacketRouterError> { + log::debug!( + "Received message with sender_tag: {:?}", + reconstructed.sender_tag + ); + + // Check version of request + if let Some(version) = reconstructed.message.first() { + // The idea is that in the future we can add logic here to parse older versions to stay + // backwards compatible. + if *version != nym_ip_packet_requests::CURRENT_VERSION { + log::warn!("Received packet with invalid version"); + return Err(IpPacketRouterError::InvalidPacketVersion(*version)); + } + } + + let request = IpPacketRequest::from_reconstructed_message(&reconstructed) + .map_err(|err| IpPacketRouterError::FailedToDeserializeTaggedPacket { source: err })?; + + match request.data { + IpPacketRequestData::StaticConnect(connect_request) => { + self.on_static_connect_request(connect_request).await + } + IpPacketRequestData::DynamicConnect(connect_request) => { + self.on_dynamic_connect_request(connect_request).await + } + IpPacketRequestData::Data(data_request) => self.on_data_request(data_request).await, + } + } + + async fn run(mut self) -> Result<(), IpPacketRouterError> { + let mut task_client = self.task_handle.fork("main_loop"); + let mut disconnect_timer = tokio::time::interval(DISCONNECT_TIMER_INTERVAL); + + while !task_client.is_shutdown() { + tokio::select! { + _ = task_client.recv() => { + log::debug!("IpPacketRouter [main loop]: received shutdown"); + }, + _ = disconnect_timer.tick() => { + let now = std::time::Instant::now(); + let inactive_clients: Vec = self.connected_clients.iter() + .filter_map(|(ip, client)| { + if now.duration_since(client.last_activity) > CLIENT_INACTIVITY_TIMEOUT { + Some(*ip) + } else { + None + } + }) + .collect(); + for ip in inactive_clients { + log::info!("Disconnect inactive client: {ip}"); + self.connected_clients.remove(&ip); + self.connected_client_tx.send(ConnectedClientEvent::Disconnect(ip)).unwrap(); + } + }, + msg = self.mixnet_client.next() => { + if let Some(msg) = msg { + match self.on_reconstructed_message(msg).await { + Ok(Some(response)) => { + let Some(recipient) = response.recipient() else { + log::error!("IpPacketRouter [main loop]: failed to get recipient from response"); + continue; + }; + let response_packet = response.to_bytes(); + let Ok(response_packet) = response_packet else { + log::error!("Failed to serialize response packet"); + continue; + }; + let lane = TransmissionLane::General; + let packet_type = None; + let input_message = InputMessage::new_regular(*recipient, response_packet, lane, packet_type); + if let Err(err) = self.mixnet_client.send(input_message).await { + log::error!("IpPacketRouter [main loop]: failed to send packet to mixnet: {err}"); + }; + }, + Ok(None) => { + continue; + }, + Err(err) => { + log::error!("Error handling mixnet message: {err}"); + } + + }; + } else { + log::trace!("IpPacketRouter [main loop]: stopping since channel closed"); + break; + }; + }, + + } + } + log::debug!("IpPacketRouter: stopping"); + Ok(()) + } +} + +pub(crate) enum ConnectedClientEvent { + Disconnect(IpAddr), + Connect(IpAddr, Box), +} diff --git a/service-providers/ip-packet-router/src/lib.rs b/service-providers/ip-packet-router/src/lib.rs index d77fcba90ba..7739f4cff61 100644 --- a/service-providers/ip-packet-router/src/lib.rs +++ b/service-providers/ip-packet-router/src/lib.rs @@ -1,395 +1,14 @@ #![cfg_attr(not(target_os = "linux"), allow(dead_code))] - -use std::{ - net::{IpAddr, SocketAddr}, - path::Path, -}; - -use error::IpPacketRouterError; -use futures::{channel::oneshot, StreamExt}; -use nym_client_core::{ - client::mix_traffic::transceiver::GatewayTransceiver, - config::disk_persistence::CommonClientPaths, HardcodedTopologyProvider, TopologyProvider, -}; -use nym_sdk::{ - mixnet::{InputMessage, MixnetMessageSender, Recipient}, - NymNetworkDetails, -}; -use nym_sphinx::receiver::ReconstructedMessage; -use nym_task::{connections::TransmissionLane, TaskClient, TaskHandle}; -use request_filter::RequestFilter; - -use crate::config::BaseClientConfig; +#![cfg_attr(not(target_os = "linux"), allow(unused_imports))] pub use crate::config::Config; +pub use ip_packet_router::{IpPacketRouterBuilder, OnStartData}; pub mod config; +mod constants; pub mod error; +mod ip_packet_router; +mod mixnet_client; mod request_filter; - -// The interface used to route traffic -pub const TUN_BASE_NAME: &str = "nymtun"; -pub const TUN_DEVICE_ADDRESS: &str = "10.0.0.1"; -pub const TUN_DEVICE_NETMASK: &str = "255.255.255.0"; - -pub struct OnStartData { - // to add more fields as required - pub address: Recipient, - - pub request_filter: RequestFilter, -} - -impl OnStartData { - pub fn new(address: Recipient, request_filter: RequestFilter) -> Self { - Self { - address, - request_filter, - } - } -} - -pub struct IpPacketRouterBuilder { - #[allow(unused)] - config: Config, - wait_for_gateway: bool, - custom_topology_provider: Option>, - custom_gateway_transceiver: Option>, - shutdown: Option, - on_start: Option>, -} - -impl IpPacketRouterBuilder { - pub fn new(config: Config) -> Self { - Self { - config, - wait_for_gateway: false, - custom_topology_provider: None, - custom_gateway_transceiver: None, - shutdown: None, - on_start: None, - } - } - - #[must_use] - pub fn with_shutdown(mut self, shutdown: TaskClient) -> Self { - self.shutdown = Some(shutdown); - self - } - - #[must_use] - pub fn with_custom_gateway_transceiver( - mut self, - gateway_transceiver: Box, - ) -> Self { - self.custom_gateway_transceiver = Some(gateway_transceiver); - self - } - - #[must_use] - pub fn with_wait_for_gateway(mut self, wait_for_gateway: bool) -> Self { - self.wait_for_gateway = wait_for_gateway; - self - } - - #[must_use] - pub fn with_on_start(mut self, on_start: oneshot::Sender) -> Self { - self.on_start = Some(on_start); - self - } - - #[must_use] - pub fn with_custom_topology_provider( - mut self, - topology_provider: Box, - ) -> Self { - self.custom_topology_provider = Some(topology_provider); - self - } - - pub fn with_stored_topology>( - mut self, - file: P, - ) -> Result { - self.custom_topology_provider = - Some(Box::new(HardcodedTopologyProvider::new_from_file(file)?)); - Ok(self) - } - - #[cfg(not(target_os = "linux"))] - pub async fn run_service_provider(self) -> Result<(), IpPacketRouterError> { - todo!("service provider is not yet supported on this platform") - } - - #[cfg(target_os = "linux")] - pub async fn run_service_provider(self) -> Result<(), IpPacketRouterError> { - // Used to notify tasks to shutdown. Not all tasks fully supports this (yet). - let task_handle: TaskHandle = self.shutdown.map(Into::into).unwrap_or_default(); - - // Connect to the mixnet - let mixnet_client = create_mixnet_client( - &self.config.base, - task_handle.get_handle().named("nym_sdk::MixnetClient"), - self.custom_gateway_transceiver, - self.custom_topology_provider, - self.wait_for_gateway, - &self.config.storage_paths.common_paths, - ) - .await?; - - let self_address = *mixnet_client.nym_address(); - - // Create the TUN device that we interact with the rest of the world with - let config = nym_tun::tun_device::TunDeviceConfig { - base_name: TUN_BASE_NAME.to_string(), - ip: TUN_DEVICE_ADDRESS.parse().unwrap(), - netmask: TUN_DEVICE_NETMASK.parse().unwrap(), - }; - let (tun, tun_task_tx, tun_task_response_rx) = nym_tun::tun_device::TunDevice::new( - nym_tun::tun_device::RoutingMode::new_nat(), - config, - ); - tun.start(); - - let request_filter = request_filter::RequestFilter::new(&self.config).await?; - request_filter.start_update_tasks().await; - - let ip_packet_router_service = IpPacketRouter { - _config: self.config, - request_filter: request_filter.clone(), - tun_task_tx, - tun_task_response_rx, - mixnet_client, - task_handle, - }; - - log::info!("The address of this client is: {self_address}"); - log::info!("All systems go. Press CTRL-C to stop the server."); - - if let Some(on_start) = self.on_start { - if on_start - .send(OnStartData::new(self_address, request_filter)) - .is_err() - { - // the parent has dropped the channel before receiving the response - return Err(IpPacketRouterError::DisconnectedParent); - } - } - - ip_packet_router_service.run().await - } -} - -#[allow(unused)] -struct IpPacketRouter { - _config: Config, - request_filter: request_filter::RequestFilter, - tun_task_tx: nym_tun::tun_task_channel::TunTaskTx, - tun_task_response_rx: nym_tun::tun_task_channel::TunTaskResponseRx, - mixnet_client: nym_sdk::mixnet::MixnetClient, - task_handle: TaskHandle, -} - -#[allow(unused)] -impl IpPacketRouter { - async fn run(mut self) -> Result<(), IpPacketRouterError> { - let mut task_client = self.task_handle.fork("main_loop"); - - while !task_client.is_shutdown() { - tokio::select! { - _ = task_client.recv() => { - log::debug!("IpPacketRouter [main loop]: received shutdown"); - }, - msg = self.mixnet_client.next() => { - if let Some(msg) = msg { - if let Err(err) = self.on_message(msg).await { - log::error!("Error handling mixnet message: {err}"); - }; - } else { - log::trace!("IpPacketRouter [main loop]: stopping since channel closed"); - break; - }; - }, - packet = self.tun_task_response_rx.recv() => { - if let Some((_tag, packet)) = packet { - // Read recipient from env variable NYM_CLIENT_ADDR which is a base58 - // string of the nym-address of the client that the packet should be - // sent back to. - // - // In the near future we will let the client expose it's nym-address - // directly, and after that, provide SURBS - let recipient = std::env::var("NYM_CLIENT_ADDR").ok().and_then(|addr| { - Recipient::try_from_base58_string(addr).ok() - }); - - if let Some(recipient) = recipient { - let lane = TransmissionLane::General; - let packet_type = None; - let input_message = InputMessage::new_regular(recipient, packet, lane, packet_type); - - if let Err(err) = self.mixnet_client.send(input_message).await { - log::error!("IpPacketRouter [main loop]: failed to send packet to mixnet: {err}"); - }; - } else { - log::error!("NYM_CLIENT_ADDR not set or invalid"); - } - } else { - log::trace!("IpPacketRouter [main loop]: stopping since channel closed"); - break; - } - } - - } - } - log::info!("IpPacketRouter: stopping"); - Ok(()) - } - - async fn on_message( - &mut self, - reconstructed: ReconstructedMessage, - ) -> Result<(), IpPacketRouterError> { - log::debug!( - "Received message with sender_tag: {:?}", - reconstructed.sender_tag - ); - - let tagged_packet = - nym_ip_packet_requests::TaggedIpPacket::from_reconstructed_message(&reconstructed) - .map_err(|err| IpPacketRouterError::FailedToDeserializeTaggedPacket { - source: err, - })?; - - // We don't forward packets that we are not able to parse. BUT, there might be a good - // reason to still forward them. - // - // For example, if we are running in a mode where we are only supposed to forward - // packets to a specific destination, we might want to forward them anyway. - // - // TODO: look into this - let ParsedPacket { - packet_type, - src_addr, - dst_addr, - dst, - } = parse_packet(&tagged_packet.packet)?; - - let dst_str = dst.map_or(dst_addr.to_string(), |dst| dst.to_string()); - log::info!("Received packet: {packet_type}: {src_addr} -> {dst_str}"); - - // Filter check - if let Some(dst) = dst { - if !self.request_filter.check_address(&dst).await { - log::warn!("Failed filter check: {dst}"); - // TODO: we could consider sending back a response here - return Err(IpPacketRouterError::AddressFailedFilterCheck { addr: dst }); - } - } else { - // TODO: we should also filter packets without port number - log::warn!("Ignoring filter check for packet without port number! TODO!"); - } - - // TODO: set the tag correctly. Can we just reuse sender_tag? - let peer_tag = 0; - self.tun_task_tx - .try_send((peer_tag, tagged_packet.packet.into())) - .map_err(|err| IpPacketRouterError::FailedToSendPacketToTun { source: err })?; - - Ok(()) - } -} - -struct ParsedPacket<'a> { - packet_type: &'a str, - src_addr: IpAddr, - dst_addr: IpAddr, - dst: Option, -} - -fn parse_packet(packet: &[u8]) -> Result { - let headers = etherparse::SlicedPacket::from_ip(packet).map_err(|err| { - log::warn!("Unable to parse incoming data as IP packet: {err}"); - IpPacketRouterError::PacketParseFailed { source: err } - })?; - - let (packet_type, dst_port) = match headers.transport { - Some(etherparse::TransportSlice::Udp(header)) => ("ipv4", Some(header.destination_port())), - Some(etherparse::TransportSlice::Tcp(header)) => ("ipv6", Some(header.destination_port())), - Some(etherparse::TransportSlice::Icmpv4(_)) => ("icmpv4", None), - Some(etherparse::TransportSlice::Icmpv6(_)) => ("icmpv6", None), - Some(etherparse::TransportSlice::Unknown(_)) => ("unknown", None), - None => { - log::warn!("Received packet missing transport header"); - return Err(IpPacketRouterError::PacketMissingTransportHeader); - } - }; - - let (src_addr, dst_addr, dst) = match headers.ip { - Some(etherparse::InternetSlice::Ipv4(ipv4_header, _)) => { - let src_addr: IpAddr = ipv4_header.source_addr().into(); - let dst_addr: IpAddr = ipv4_header.destination_addr().into(); - let dst = dst_port.map(|port| SocketAddr::new(dst_addr, port)); - (src_addr, dst_addr, dst) - } - Some(etherparse::InternetSlice::Ipv6(ipv6_header, _)) => { - let src_addr: IpAddr = ipv6_header.source_addr().into(); - let dst_addr: IpAddr = ipv6_header.destination_addr().into(); - let dst = dst_port.map(|port| SocketAddr::new(dst_addr, port)); - (src_addr, dst_addr, dst) - } - None => { - log::warn!("Received packet missing IP header"); - return Err(IpPacketRouterError::PacketMissingIpHeader); - } - }; - Ok(ParsedPacket { - packet_type, - src_addr, - dst_addr, - dst, - }) -} - -// Helper function to create the mixnet client. -// This is NOT in the SDK since we don't want to expose any of the client-core config types. -// We could however consider moving it to a crate in common in the future. -// TODO: refactor this function and its arguments -#[allow(unused)] -async fn create_mixnet_client( - config: &BaseClientConfig, - shutdown: TaskClient, - custom_transceiver: Option>, - custom_topology_provider: Option>, - wait_for_gateway: bool, - paths: &CommonClientPaths, -) -> Result { - let debug_config = config.debug; - - let storage_paths = nym_sdk::mixnet::StoragePaths::from(paths.clone()); - - let mut client_builder = - nym_sdk::mixnet::MixnetClientBuilder::new_with_default_storage(storage_paths) - .await - .map_err(|err| IpPacketRouterError::FailedToSetupMixnetClient { source: err })? - .network_details(NymNetworkDetails::new_from_env()) - .debug_config(debug_config) - .custom_shutdown(shutdown) - .with_wait_for_gateway(wait_for_gateway); - if !config.get_disabled_credentials_mode() { - client_builder = client_builder.enable_credentials_mode(); - } - if let Some(gateway_transceiver) = custom_transceiver { - client_builder = client_builder.custom_gateway_transceiver(gateway_transceiver); - } - if let Some(topology_provider) = custom_topology_provider { - client_builder = client_builder.custom_topology_provider(topology_provider); - } - - let mixnet_client = client_builder - .build() - .map_err(|err| IpPacketRouterError::FailedToSetupMixnetClient { source: err })?; - - mixnet_client - .connect_to_mixnet() - .await - .map_err(|err| IpPacketRouterError::FailedToConnectToMixnet { source: err }) -} +mod tun_listener; +mod util; diff --git a/service-providers/ip-packet-router/src/mixnet_client.rs b/service-providers/ip-packet-router/src/mixnet_client.rs new file mode 100644 index 00000000000..1d9695c0011 --- /dev/null +++ b/service-providers/ip-packet-router/src/mixnet_client.rs @@ -0,0 +1,49 @@ +use nym_client_core::{config::disk_persistence::CommonClientPaths, TopologyProvider}; +use nym_sdk::{GatewayTransceiver, NymNetworkDetails}; +use nym_task::TaskClient; + +use crate::{config::BaseClientConfig, error::IpPacketRouterError}; + +// Helper function to create the mixnet client. +// This is NOT in the SDK since we don't want to expose any of the client-core config types. +// We could however consider moving it to a crate in common in the future. +// TODO: refactor this function and its arguments +pub(crate) async fn create_mixnet_client( + config: &BaseClientConfig, + shutdown: TaskClient, + custom_transceiver: Option>, + custom_topology_provider: Option>, + wait_for_gateway: bool, + paths: &CommonClientPaths, +) -> Result { + let debug_config = config.debug; + + let storage_paths = nym_sdk::mixnet::StoragePaths::from(paths.clone()); + + let mut client_builder = + nym_sdk::mixnet::MixnetClientBuilder::new_with_default_storage(storage_paths) + .await + .map_err(|err| IpPacketRouterError::FailedToSetupMixnetClient { source: err })? + .network_details(NymNetworkDetails::new_from_env()) + .debug_config(debug_config) + .custom_shutdown(shutdown) + .with_wait_for_gateway(wait_for_gateway); + if !config.get_disabled_credentials_mode() { + client_builder = client_builder.enable_credentials_mode(); + } + if let Some(gateway_transceiver) = custom_transceiver { + client_builder = client_builder.custom_gateway_transceiver(gateway_transceiver); + } + if let Some(topology_provider) = custom_topology_provider { + client_builder = client_builder.custom_topology_provider(topology_provider); + } + + let mixnet_client = client_builder + .build() + .map_err(|err| IpPacketRouterError::FailedToSetupMixnetClient { source: err })?; + + mixnet_client + .connect_to_mixnet() + .await + .map_err(|err| IpPacketRouterError::FailedToConnectToMixnet { source: err }) +} diff --git a/service-providers/ip-packet-router/src/tun_listener.rs b/service-providers/ip-packet-router/src/tun_listener.rs new file mode 100644 index 00000000000..93a16d316da --- /dev/null +++ b/service-providers/ip-packet-router/src/tun_listener.rs @@ -0,0 +1,92 @@ +use std::{collections::HashMap, net::IpAddr}; + +use nym_ip_packet_requests::IpPacketResponse; +use nym_sdk::mixnet::{InputMessage, MixnetMessageSender}; +use nym_task::{connections::TransmissionLane, TaskClient}; +#[cfg(target_os = "linux")] +use tokio::io::AsyncReadExt; +use tokio::sync::mpsc::UnboundedReceiver; + +use crate::{error::IpPacketRouterError, ip_packet_router, util::parse_ip::parse_dst_addr}; + +// Reads packet from TUN and writes to mixnet client +#[cfg(target_os = "linux")] +pub(crate) struct TunListener { + pub(crate) tun_reader: tokio::io::ReadHalf, + pub(crate) mixnet_client_sender: nym_sdk::mixnet::MixnetClientSender, + pub(crate) task_client: TaskClient, + + // A mirror of the one in IpPacketRouter + pub(crate) connected_clients: HashMap, + pub(crate) connected_client_rx: UnboundedReceiver, +} + +#[cfg(target_os = "linux")] +impl TunListener { + async fn run(mut self) -> Result<(), IpPacketRouterError> { + let mut buf = [0u8; 65535]; + while !self.task_client.is_shutdown() { + tokio::select! { + _ = self.task_client.recv() => { + log::trace!("TunListener: received shutdown"); + }, + event = self.connected_client_rx.recv() => match event { + Some(ip_packet_router::ConnectedClientEvent::Connect(ip, nym_addr)) => { + log::trace!("Connect client: {ip}"); + self.connected_clients.insert(ip, ip_packet_router::ConnectedClient { + nym_address: *nym_addr, + last_activity: std::time::Instant::now(), + }); + }, + Some(ip_packet_router::ConnectedClientEvent::Disconnect(ip)) => { + log::trace!("Disconnect client: {ip}"); + self.connected_clients.remove(&ip); + }, + None => {}, + }, + len = self.tun_reader.read(&mut buf) => match len { + Ok(len) => { + let Some(dst_addr) = parse_dst_addr(&buf[..len]) else { + log::warn!("Failed to parse packet"); + continue; + }; + + let recipient = self.connected_clients.get(&dst_addr).map(|c| c.nym_address); + + if let Some(recipient) = recipient { + let lane = TransmissionLane::General; + let packet_type = None; + let packet = buf[..len].to_vec(); + let response_packet = IpPacketResponse::new_ip_packet(packet.into()).to_bytes(); + let Ok(response_packet) = response_packet else { + log::error!("Failed to serialize response packet"); + continue; + }; + let input_message = InputMessage::new_regular(recipient, response_packet, lane, packet_type); + + if let Err(err) = self.mixnet_client_sender.send(input_message).await { + log::error!("TunListener: failed to send packet to mixnet: {err}"); + }; + } else { + log::info!("No registered nym-address for packet - dropping"); + } + }, + Err(err) => { + log::warn!("iface: read error: {err}"); + // break; + } + } + } + } + log::debug!("TunListener: stopping"); + Ok(()) + } + + pub(crate) fn start(self) { + tokio::spawn(async move { + if let Err(err) = self.run().await { + log::error!("tun listener router has failed: {err}") + } + }); + } +} diff --git a/service-providers/ip-packet-router/src/util/generate_new_ip.rs b/service-providers/ip-packet-router/src/util/generate_new_ip.rs new file mode 100644 index 00000000000..54aa1750763 --- /dev/null +++ b/service-providers/ip-packet-router/src/util/generate_new_ip.rs @@ -0,0 +1,38 @@ +use std::{ + collections::HashMap, + net::{IpAddr, Ipv4Addr}, +}; + +use crate::{constants::TUN_DEVICE_ADDRESS, ip_packet_router::ConnectedClient}; + +// Find an available IP address in self.connected_clients +// TODO: make this nicer +fn generate_random_ip_within_subnet() -> Ipv4Addr { + let mut rng = rand::thread_rng(); + // Generate a random number in the range 1-254 + let last_octet = rand::Rng::gen_range(&mut rng, 1..=254); + Ipv4Addr::new(10, 0, 0, last_octet) +} + +fn is_ip_taken( + connected_clients: &HashMap, + tun_ip: Ipv4Addr, + ip: Ipv4Addr, +) -> bool { + connected_clients.contains_key(&ip.into()) || ip == tun_ip +} + +// TODO: brute force approach. We could consider using a more efficient algorithm +pub(crate) fn find_new_ip(connected_clients: &HashMap) -> Option { + let mut new_ip = generate_random_ip_within_subnet(); + let mut tries = 0; + let tun_ip = TUN_DEVICE_ADDRESS.parse::().unwrap(); + while is_ip_taken(connected_clients, tun_ip, new_ip) { + new_ip = generate_random_ip_within_subnet(); + tries += 1; + if tries > 100 { + return None; + } + } + Some(new_ip.into()) +} diff --git a/service-providers/ip-packet-router/src/util/mod.rs b/service-providers/ip-packet-router/src/util/mod.rs new file mode 100644 index 00000000000..62f035c4fb5 --- /dev/null +++ b/service-providers/ip-packet-router/src/util/mod.rs @@ -0,0 +1,2 @@ +pub(crate) mod generate_new_ip; +pub(crate) mod parse_ip; diff --git a/service-providers/ip-packet-router/src/util/parse_ip.rs b/service-providers/ip-packet-router/src/util/parse_ip.rs new file mode 100644 index 00000000000..6b99a2ba898 --- /dev/null +++ b/service-providers/ip-packet-router/src/util/parse_ip.rs @@ -0,0 +1,104 @@ +use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; + +use crate::error::IpPacketRouterError; + +pub(crate) struct ParsedPacket<'a> { + pub(crate) packet_type: &'a str, + pub(crate) src_addr: IpAddr, + pub(crate) dst_addr: IpAddr, + pub(crate) dst: Option, +} + +pub(crate) fn parse_packet(packet: &[u8]) -> Result { + let headers = etherparse::SlicedPacket::from_ip(packet).map_err(|err| { + log::warn!("Unable to parse incoming data as IP packet: {err}"); + IpPacketRouterError::PacketParseFailed { source: err } + })?; + + let (packet_type, dst_port) = match headers.transport { + Some(etherparse::TransportSlice::Udp(header)) => ("udp", Some(header.destination_port())), + Some(etherparse::TransportSlice::Tcp(header)) => ("tcp", Some(header.destination_port())), + Some(etherparse::TransportSlice::Icmpv4(_)) => ("icmpv4", None), + Some(etherparse::TransportSlice::Icmpv6(_)) => ("icmpv6", None), + Some(etherparse::TransportSlice::Unknown(_)) => ("unknown", None), + None => { + log::warn!("Received packet missing transport header"); + return Err(IpPacketRouterError::PacketMissingTransportHeader); + } + }; + + let (src_addr, dst_addr, dst) = match headers.ip { + Some(etherparse::InternetSlice::Ipv4(ipv4_header, _)) => { + let src_addr: IpAddr = ipv4_header.source_addr().into(); + let dst_addr: IpAddr = ipv4_header.destination_addr().into(); + let dst = dst_port.map(|port| SocketAddr::new(dst_addr, port)); + (src_addr, dst_addr, dst) + } + Some(etherparse::InternetSlice::Ipv6(ipv6_header, _)) => { + let src_addr: IpAddr = ipv6_header.source_addr().into(); + let dst_addr: IpAddr = ipv6_header.destination_addr().into(); + let dst = dst_port.map(|port| SocketAddr::new(dst_addr, port)); + (src_addr, dst_addr, dst) + } + None => { + log::warn!("Received packet missing IP header"); + return Err(IpPacketRouterError::PacketMissingIpHeader); + } + }; + Ok(ParsedPacket { + packet_type, + src_addr, + dst_addr, + dst, + }) +} + +// Constants for IPv4 and IPv6 headers +const IPV4_DEST_ADDR_START: usize = 16; +const IPV4_DEST_ADDR_LEN: usize = 4; +const IPV6_DEST_ADDR_START: usize = 24; +const IPV6_DEST_ADDR_LEN: usize = 16; + +// Only parse the destination address, for when we don't need the other stuff +pub(crate) fn parse_dst_addr(packet: &[u8]) -> Option { + let version = packet.first().map(|v| v >> 4)?; + match version { + 4 => { + // IPv4 + let addr_end = IPV4_DEST_ADDR_START + IPV4_DEST_ADDR_LEN; + let addr_array: [u8; IPV4_DEST_ADDR_LEN] = packet + .get(IPV4_DEST_ADDR_START..addr_end)? + .try_into() + .ok()?; + Some(IpAddr::V4(Ipv4Addr::from(addr_array))) + } + 6 => { + // IPv6 + let addr_end = IPV6_DEST_ADDR_START + IPV6_DEST_ADDR_LEN; + let addr_array: [u8; IPV6_DEST_ADDR_LEN] = packet + .get(IPV6_DEST_ADDR_START..addr_end)? + .try_into() + .ok()?; + Some(IpAddr::V6(Ipv6Addr::from(addr_array))) + } + _ => None, // Unknown IP version + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parse_destination_from_ip_packet() { + // Create packet + let builder = + etherparse::PacketBuilder::ipv4([192, 168, 1, 1], [192, 168, 1, 2], 20).udp(21, 1234); + let payload = [1, 2, 3, 4, 5, 6, 7, 8]; + let mut packet = Vec::::with_capacity(builder.size(payload.len())); + builder.write(&mut packet, &payload).unwrap(); + + let dst_addr = parse_dst_addr(&packet).unwrap(); + assert_eq!(dst_addr, IpAddr::V4(Ipv4Addr::new(192, 168, 1, 2))); + } +} diff --git a/service-providers/network-requester/Cargo.toml b/service-providers/network-requester/Cargo.toml index a530110fee0..d3a9f2f168a 100644 --- a/service-providers/network-requester/Cargo.toml +++ b/service-providers/network-requester/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "nym-network-requester" license = "GPL-3" -version = "1.1.31" +version = "1.1.32" authors.workspace = true edition.workspace = true rust-version = "1.65" diff --git a/service-providers/network-statistics/Cargo.toml b/service-providers/network-statistics/Cargo.toml index e2f5d56ae1f..63bda25a804 100644 --- a/service-providers/network-statistics/Cargo.toml +++ b/service-providers/network-statistics/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "nym-network-statistics" -version = "1.1.31" +version = "1.1.32" edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/tools/nym-cli/Cargo.toml b/tools/nym-cli/Cargo.toml index a537c80b1c3..18c3bc6a3c4 100644 --- a/tools/nym-cli/Cargo.toml +++ b/tools/nym-cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "nym-cli" -version = "1.1.31" +version = "1.1.33" authors.workspace = true edition = "2021"