Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 1c9a4b803e | |||
| a0fa3b9b5f |
@@ -2,14 +2,15 @@ name: cd-docs
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
paths:
|
||||
- 'documentation/docs/**'
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-20.04-16-core
|
||||
runs-on: custom-linux
|
||||
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
|
||||
@@ -25,11 +26,14 @@ jobs:
|
||||
with:
|
||||
command: build
|
||||
args: --workspace --release
|
||||
- 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: 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: Build all projects in documentation/ & move to ~/dist/docs/
|
||||
run: cd documentation && ./build_all_to_dist.sh
|
||||
continue-on-error: false
|
||||
@@ -48,7 +52,6 @@ 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'
|
||||
@@ -58,18 +61,15 @@ 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,7 +79,6 @@ 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
|
||||
|
||||
@@ -9,11 +9,9 @@ on:
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-20.04-16-core
|
||||
runs-on: custom-linux
|
||||
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
|
||||
@@ -29,15 +27,22 @@ jobs:
|
||||
with:
|
||||
command: build
|
||||
args: --workspace --release
|
||||
- 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
|
||||
- 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: Build all projects in documentation/ & move to ~/dist/docs/
|
||||
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
|
||||
@@ -49,7 +54,6 @@ 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
|
||||
|
||||
@@ -19,7 +19,7 @@ jobs:
|
||||
|
||||
outputs:
|
||||
release_id: ${{ steps.create-release.outputs.id }}
|
||||
release_date: ${{ fromJSON(steps.create-release.outputs.assets)[0].created_at }}
|
||||
release_date: ${{ fromJSON(steps.create-release.outputs.assets)[0].published_at }}
|
||||
version: ${{ steps.release-info.outputs.version }}
|
||||
filename: ${{ steps.release-info.outputs.filename }}
|
||||
file_hash: ${{ steps.release-info.outputs.file_hash }}
|
||||
@@ -93,6 +93,18 @@ jobs:
|
||||
if: ${{ always() }}
|
||||
run: |
|
||||
security delete-keychain $RUNNER_TEMP/app-signing.keychain-db
|
||||
|
||||
- name: debug print
|
||||
run: |
|
||||
echo "Release ID: ${{ steps.create-release.outputs.id }}"
|
||||
echo "Release Assets: ${{ steps.create-release.outputs.assets }}"
|
||||
|
||||
# this is failing somehow, let's see what's being outputted
|
||||
- name: debug print 2
|
||||
run: |
|
||||
echo "Release ID: ${{ steps.create-release.outputs.id }}"
|
||||
echo "Release Assets: ${{ steps.create-release.outputs.assets }}"
|
||||
|
||||
- id: create-release
|
||||
name: Upload to release based on tag name
|
||||
uses: softprops/action-gh-release@v1
|
||||
|
||||
Generated
+87
-83
@@ -628,6 +628,17 @@ 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"
|
||||
@@ -1019,6 +1030,29 @@ 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"
|
||||
@@ -2303,25 +2337,6 @@ 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"
|
||||
@@ -4177,6 +4192,22 @@ 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"
|
||||
@@ -5663,29 +5694,6 @@ 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"
|
||||
@@ -5696,21 +5704,7 @@ dependencies = [
|
||||
"bitflags 1.3.2",
|
||||
"byteorder",
|
||||
"libc",
|
||||
"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-core",
|
||||
"netlink-packet-utils",
|
||||
]
|
||||
|
||||
@@ -5726,20 +5720,6 @@ 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"
|
||||
@@ -5749,7 +5729,7 @@ dependencies = [
|
||||
"bytes",
|
||||
"futures",
|
||||
"log",
|
||||
"netlink-packet-core 0.4.2",
|
||||
"netlink-packet-core",
|
||||
"netlink-sys",
|
||||
"thiserror",
|
||||
"tokio",
|
||||
@@ -5780,6 +5760,18 @@ 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"
|
||||
@@ -5789,7 +5781,6 @@ dependencies = [
|
||||
"bitflags 2.4.1",
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"memoffset 0.9.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6491,7 +6482,6 @@ dependencies = [
|
||||
"clap 4.4.7",
|
||||
"colored",
|
||||
"dashmap",
|
||||
"defguard_wireguard_rs",
|
||||
"dirs 4.0.0",
|
||||
"dotenvy",
|
||||
"futures",
|
||||
@@ -6618,9 +6608,7 @@ dependencies = [
|
||||
"bincode",
|
||||
"bytes",
|
||||
"nym-sphinx",
|
||||
"rand 0.8.5",
|
||||
"serde",
|
||||
"thiserror",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6645,14 +6633,12 @@ dependencies = [
|
||||
"nym-tun",
|
||||
"nym-wireguard",
|
||||
"nym-wireguard-types",
|
||||
"rand 0.8.5",
|
||||
"reqwest",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tap",
|
||||
"thiserror",
|
||||
"tokio",
|
||||
"tokio-tun",
|
||||
"url",
|
||||
]
|
||||
|
||||
@@ -7565,15 +7551,28 @@ dependencies = [
|
||||
name = "nym-wireguard"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"async-recursion",
|
||||
"base64 0.21.4",
|
||||
"defguard_wireguard_rs",
|
||||
"bincode",
|
||||
"boringtun",
|
||||
"bytes",
|
||||
"dashmap",
|
||||
"etherparse",
|
||||
"futures",
|
||||
"ip_network",
|
||||
"ip_network_table",
|
||||
"log",
|
||||
"nym-network-defaults",
|
||||
"nym-sphinx",
|
||||
"nym-task",
|
||||
"nym-tun",
|
||||
"nym-wireguard-types",
|
||||
"rand 0.8.5",
|
||||
"serde",
|
||||
"tap",
|
||||
"thiserror",
|
||||
"tokio",
|
||||
"x25519-dalek 2.0.0",
|
||||
"tokio-tun",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -7581,8 +7580,12 @@ 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",
|
||||
@@ -7590,6 +7593,7 @@ dependencies = [
|
||||
"serde_json",
|
||||
"sha2 0.10.8",
|
||||
"thiserror",
|
||||
"tokio",
|
||||
"utoipa",
|
||||
"x25519-dalek 2.0.0",
|
||||
]
|
||||
@@ -9216,7 +9220,7 @@ checksum = "322c53fd76a18698f1c27381d58091de3a043d356aa5bd0d510608b565f469a0"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"log",
|
||||
"netlink-packet-route 0.12.0",
|
||||
"netlink-packet-route",
|
||||
"netlink-proto",
|
||||
"nix 0.24.3",
|
||||
"thiserror",
|
||||
@@ -10945,9 +10949,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tokio-tun"
|
||||
version = "0.11.2"
|
||||
version = "0.9.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bf2efaf33e86779a3a68b1f1d6e9e13a346c1c75ee3cab7a4293235c463b2668"
|
||||
checksum = "c4a67d1405a577ba1f4cd61f46608f1db2cadbb6a9549c3fc2eed7f1195393c9"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"nix 0.27.1",
|
||||
|
||||
@@ -139,6 +139,7 @@ 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"
|
||||
dashmap = "5.5.3"
|
||||
|
||||
@@ -1,439 +0,0 @@
|
||||
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.
|
||||
|
||||
|
||||
@@ -366,7 +366,11 @@ pub fn creating_proof_of_chunking_for_100_parties(c: &mut Criterion) {
|
||||
.map(|&node_index| polynomial.evaluate_at(&Scalar::from(node_index)).into())
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let remote_share_key_pairs = shares.iter().zip(receivers.values()).collect::<Vec<_>>();
|
||||
let remote_share_key_pairs = shares
|
||||
.iter()
|
||||
.zip(receivers.values())
|
||||
.map(|(share, key)| (share, key))
|
||||
.collect::<Vec<_>>();
|
||||
let ordered_public_keys = receivers.values().copied().collect::<Vec<_>>();
|
||||
|
||||
let (ciphertexts, hazmat) = encrypt_shares(&remote_share_key_pairs, ¶ms, &mut rng);
|
||||
@@ -396,7 +400,11 @@ pub fn verifying_proof_of_chunking_for_100_parties(c: &mut Criterion) {
|
||||
.map(|&node_index| polynomial.evaluate_at(&Scalar::from(node_index)).into())
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let remote_share_key_pairs = shares.iter().zip(receivers.values()).collect::<Vec<_>>();
|
||||
let remote_share_key_pairs = shares
|
||||
.iter()
|
||||
.zip(receivers.values())
|
||||
.map(|(share, key)| (share, key))
|
||||
.collect::<Vec<_>>();
|
||||
let ordered_public_keys = receivers.values().copied().collect::<Vec<_>>();
|
||||
|
||||
let (ciphertexts, hazmat) = encrypt_shares(&remote_share_key_pairs, ¶ms, &mut rng);
|
||||
@@ -428,7 +436,11 @@ 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::<Vec<_>>();
|
||||
|
||||
let remote_share_key_pairs = shares.iter().zip(receivers.values()).collect::<Vec<_>>();
|
||||
let remote_share_key_pairs = shares
|
||||
.iter()
|
||||
.zip(receivers.values())
|
||||
.map(|(share, key)| (share, key))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let (ciphertexts, hazmat) = encrypt_shares(&remote_share_key_pairs, ¶ms, &mut rng);
|
||||
|
||||
@@ -466,7 +478,11 @@ 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::<Vec<_>>();
|
||||
|
||||
let remote_share_key_pairs = shares.iter().zip(receivers.values()).collect::<Vec<_>>();
|
||||
let remote_share_key_pairs = shares
|
||||
.iter()
|
||||
.zip(receivers.values())
|
||||
.map(|(share, key)| (share, key))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let (ciphertexts, hazmat) = encrypt_shares(&remote_share_key_pairs, ¶ms, &mut rng);
|
||||
|
||||
@@ -529,7 +545,11 @@ pub fn share_encryption_100(c: &mut Criterion) {
|
||||
.map(|&node_index| polynomial.evaluate_at(&Scalar::from(node_index)).into())
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let remote_share_key_pairs = shares.iter().zip(receivers.values()).collect::<Vec<_>>();
|
||||
let remote_share_key_pairs = shares
|
||||
.iter()
|
||||
.zip(receivers.values())
|
||||
.map(|(share, key)| (share, key))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
c.bench_function("100 shares encryption", |b| {
|
||||
b.iter(|| black_box(encrypt_shares(&remote_share_key_pairs, ¶ms, &mut rng)))
|
||||
|
||||
@@ -14,6 +14,4 @@ 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 }
|
||||
|
||||
@@ -1,308 +1,35 @@
|
||||
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(serde::Serialize, serde::Deserialize)]
|
||||
pub struct TaggedIpPacket {
|
||||
pub packet: bytes::Bytes,
|
||||
pub return_address: nym_sphinx::addressing::clients::Recipient,
|
||||
pub return_mix_hops: Option<u8>,
|
||||
// pub return_mix_delays: Option<f64>,
|
||||
}
|
||||
|
||||
#[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<u8>,
|
||||
reply_to_avg_mix_delays: Option<f64>,
|
||||
) -> (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<u8>,
|
||||
reply_to_avg_mix_delays: Option<f64>,
|
||||
) -> (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 }),
|
||||
impl TaggedIpPacket {
|
||||
pub fn new(
|
||||
packet: bytes::Bytes,
|
||||
return_address: nym_sphinx::addressing::clients::Recipient,
|
||||
return_mix_hops: Option<u8>,
|
||||
) -> Self {
|
||||
TaggedIpPacket {
|
||||
packet,
|
||||
return_address,
|
||||
return_mix_hops,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn id(&self) -> Option<u64> {
|
||||
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<Vec<u8>, bincode::Error> {
|
||||
use bincode::Options;
|
||||
make_bincode_serializer().serialize(self)
|
||||
}
|
||||
|
||||
pub fn from_reconstructed_message(
|
||||
message: &nym_sphinx::receiver::ReconstructedMessage,
|
||||
) -> Result<Self, bincode::Error> {
|
||||
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<u8>,
|
||||
pub reply_to_avg_mix_delays: Option<f64>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
|
||||
pub struct DynamicConnectRequest {
|
||||
pub request_id: u64,
|
||||
pub reply_to: Recipient,
|
||||
pub reply_to_hops: Option<u8>,
|
||||
pub reply_to_avg_mix_delays: Option<f64>,
|
||||
}
|
||||
|
||||
#[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<u64> {
|
||||
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<Vec<u8>, bincode::Error> {
|
||||
use bincode::Options;
|
||||
make_bincode_serializer().serialize(self)
|
||||
}
|
||||
|
||||
pub fn from_reconstructed_message(
|
||||
message: &nym_sphinx::receiver::ReconstructedMessage,
|
||||
) -> Result<Self, bincode::Error> {
|
||||
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 {
|
||||
@@ -311,63 +38,3 @@ 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]),
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,10 +6,9 @@ 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, prepare_blind_sign,
|
||||
prove_bandwidth_credential, setup, ttp_keygen, verify_credential,
|
||||
verify_partial_blind_signature, Attribute, BlindedSignature, Parameters, Signature,
|
||||
SignatureShare, VerificationKey,
|
||||
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,
|
||||
};
|
||||
use rand::seq::SliceRandom;
|
||||
use std::ops::Neg;
|
||||
@@ -176,6 +175,8 @@ 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();
|
||||
@@ -241,29 +242,6 @@ 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<u64> = (1..=case.num_authorities).collect();
|
||||
// aggregate verification keys
|
||||
|
||||
@@ -14,7 +14,6 @@ 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;
|
||||
|
||||
@@ -3,14 +3,12 @@
|
||||
|
||||
use std::convert::TryFrom;
|
||||
use std::convert::TryInto;
|
||||
use std::ops::Neg;
|
||||
|
||||
use bls12_381::{multi_miller_loop, G1Affine, G1Projective, G2Prepared, Scalar};
|
||||
use group::{Curve, Group, GroupEncoding};
|
||||
use bls12_381::{G1Affine, G1Projective, Scalar};
|
||||
use group::{Curve, 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;
|
||||
@@ -320,97 +318,6 @@ 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::<Vec<_>>();
|
||||
|
||||
// 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,
|
||||
@@ -447,7 +354,6 @@ pub fn sign(
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::scheme::keygen::keygen;
|
||||
|
||||
#[test]
|
||||
fn blind_sign_request_bytes_roundtrip() {
|
||||
@@ -479,81 +385,4 @@ 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()
|
||||
),);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,4 +18,7 @@ log.workspace = true
|
||||
nym-wireguard-types = { path = "../wireguard-types", optional = true }
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
tokio-tun = "0.11.2"
|
||||
tokio-tun = "0.9.0"
|
||||
|
||||
[features]
|
||||
wireguard = ["nym-wireguard-types"]
|
||||
|
||||
@@ -15,6 +15,14 @@ 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)]
|
||||
@@ -25,6 +33,13 @@ 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]
|
||||
@@ -77,12 +92,13 @@ 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 {
|
||||
@@ -92,8 +108,26 @@ impl RoutingMode {
|
||||
})
|
||||
}
|
||||
|
||||
pub fn new_passthrough() -> Self {
|
||||
RoutingMode::Passthrough
|
||||
#[cfg(feature = "wireguard")]
|
||||
pub fn new_allowed_ips(peers_by_ip: std::sync::Arc<tokio::sync::Mutex<PeersByIp>>) -> Self {
|
||||
RoutingMode::AllowedIps(AllowedIpsInner { peers_by_ip })
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "wireguard")]
|
||||
pub struct AllowedIpsInner {
|
||||
peers_by_ip: std::sync::Arc<tokio::sync::Mutex<PeersByIp>>,
|
||||
}
|
||||
|
||||
#[cfg(feature = "wireguard")]
|
||||
impl AllowedIpsInner {
|
||||
async fn lock(&self) -> Result<tokio::sync::MutexGuard<PeersByIp>, TunDeviceError> {
|
||||
timeout(
|
||||
Duration::from_millis(MUTEX_LOCK_TIMEOUT_MS),
|
||||
self.peers_by_ip.as_ref().lock(),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| TunDeviceError::FailedToLockPeer)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -112,7 +146,15 @@ impl TunDevice {
|
||||
routing_mode: RoutingMode,
|
||||
config: TunDeviceConfig,
|
||||
) -> (Self, TunTaskTx, TunTaskResponseRx) {
|
||||
let tun = Self::new_device_only(config);
|
||||
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());
|
||||
|
||||
// Channels to communicate with the other tasks
|
||||
let (tun_task_tx, tun_task_rx) = tun_task_channel();
|
||||
@@ -128,19 +170,6 @@ 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;
|
||||
@@ -151,6 +180,7 @@ 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);
|
||||
}
|
||||
@@ -168,13 +198,26 @@ 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({dst_addr} <- {src_addr}, {} bytes)",
|
||||
"iface: read Packet({src_addr} -> {dst_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) {
|
||||
@@ -185,15 +228,6 @@ 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");
|
||||
@@ -221,7 +255,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!("iface: handle_tun_write failed: {err}");
|
||||
log::error!("ifcae: handle_tun_write failed: {err}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,10 +12,14 @@ 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"] }
|
||||
|
||||
@@ -29,7 +33,13 @@ sha2 = { version = "0.10.8", optional = true }
|
||||
utoipa = { workspace = true, optional = true }
|
||||
serde_json = { workspace = true, optional = true }
|
||||
|
||||
x25519-dalek = { version = "2.0.0", features = ["static_secrets"] }
|
||||
# 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"
|
||||
|
||||
|
||||
[dev-dependencies]
|
||||
rand = "0.7.3"
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
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;
|
||||
|
||||
@@ -10,14 +10,20 @@ use std::hash::{Hash, Hasher};
|
||||
use std::ops::Deref;
|
||||
use std::str::FromStr;
|
||||
|
||||
use x25519_dalek::PublicKey;
|
||||
// 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;
|
||||
|
||||
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
|
||||
pub struct PeerPublicKey(PublicKey);
|
||||
pub struct PeerPublicKey(BoringtunPublicKey);
|
||||
|
||||
impl PeerPublicKey {
|
||||
#[allow(dead_code)]
|
||||
pub fn new(key: PublicKey) -> Self {
|
||||
pub fn new(key: BoringtunPublicKey) -> Self {
|
||||
PeerPublicKey(key)
|
||||
}
|
||||
|
||||
@@ -39,7 +45,7 @@ impl Hash for PeerPublicKey {
|
||||
}
|
||||
|
||||
impl Deref for PeerPublicKey {
|
||||
type Target = PublicKey;
|
||||
type Target = BoringtunPublicKey;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.0
|
||||
@@ -65,7 +71,7 @@ impl FromStr for PeerPublicKey {
|
||||
})?;
|
||||
};
|
||||
|
||||
Ok(PeerPublicKey(PublicKey::from(key_arr)))
|
||||
Ok(PeerPublicKey(BoringtunPublicKey::from(key_arr)))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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 = x25519_dalek::StaticSecret::from(local_secret.to_bytes());
|
||||
let local_public: x25519_dalek::PublicKey = (&static_secret).into();
|
||||
let static_secret = boringtun::x25519::StaticSecret::from(local_secret.to_bytes());
|
||||
let local_public: boringtun::x25519::PublicKey = (&static_secret).into();
|
||||
|
||||
let remote_public = x25519_dalek::PublicKey::from(remote_public.to_bytes());
|
||||
let remote_public = boringtun::x25519::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 = x25519_dalek::StaticSecret::from(gateway_key.to_bytes());
|
||||
let static_secret = boringtun::x25519::StaticSecret::from(gateway_key.to_bytes());
|
||||
|
||||
let dh = static_secret.diffie_hellman(&self.pub_key);
|
||||
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
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<PeerEventSender>;
|
||||
|
||||
// Channels that are used to communicate with the various tunnels
|
||||
#[derive(Clone)]
|
||||
pub struct PeerEventSender(mpsc::Sender<Event>);
|
||||
pub struct PeerEventReceiver(mpsc::Receiver<Event>);
|
||||
|
||||
#[derive(thiserror::Error, Debug)]
|
||||
pub enum PeerEventSenderError {
|
||||
#[error("send failed: timeout: {source}")]
|
||||
SendTimeoutError {
|
||||
#[from]
|
||||
source: mpsc::error::SendTimeoutError<Event>,
|
||||
},
|
||||
|
||||
#[error("send failed: {source}")]
|
||||
SendError {
|
||||
#[from]
|
||||
source: mpsc::error::SendError<Event>,
|
||||
},
|
||||
}
|
||||
|
||||
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<Event> {
|
||||
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<x25519::PublicKey, PeerEventSender>;
|
||||
pub(crate) type PeersByAddr = DashMap<SocketAddr, PeerEventSender>;
|
||||
|
||||
#[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<RefMut<'_, x25519::PublicKey, PeerEventSender>> {
|
||||
self.active_peers.get_mut(public_key)
|
||||
}
|
||||
|
||||
pub fn get_by_addr(&self, addr: &SocketAddr) -> Option<Ref<'_, SocketAddr, PeerEventSender>> {
|
||||
self.active_peers_by_addr.get(addr)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
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} }}")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
pub mod active_peers;
|
||||
pub mod event;
|
||||
pub mod network_table;
|
||||
@@ -0,0 +1,25 @@
|
||||
use std::net::IpAddr;
|
||||
|
||||
use ip_network::IpNetwork;
|
||||
use ip_network_table::IpNetworkTable;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct NetworkTable<T> {
|
||||
ips: IpNetworkTable<T>,
|
||||
}
|
||||
|
||||
impl<T> NetworkTable<T> {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
ips: IpNetworkTable::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn insert<N: Into<IpNetwork>>(&mut self, network: N, data: T) -> Option<T> {
|
||||
self.ips.insert(network, data)
|
||||
}
|
||||
|
||||
pub fn longest_match<I: Into<IpAddr>>(&self, ip: I) -> Option<(IpNetwork, &T)> {
|
||||
self.ips.longest_match(ip)
|
||||
}
|
||||
}
|
||||
@@ -11,15 +11,31 @@ 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.
|
||||
x25519-dalek = "2.0.0"
|
||||
defguard_wireguard_rs = { git = "https://github.com/neacsu/wireguard-rs.git", rev = "c2cd0c1119f699f4bc43f5e6ffd6fc242caa42ed" }
|
||||
#boringtun = "0.6.0"
|
||||
boringtun = { workspace = true }
|
||||
bytes = "1.5.0"
|
||||
dashmap = "5.5.3"
|
||||
etherparse = "0.13.0"
|
||||
futures = "0.3.28"
|
||||
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"
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Error, Debug)]
|
||||
pub enum WgError {
|
||||
#[error("unable to get tunnel")]
|
||||
UnableToGetTunnel,
|
||||
#[error("handshake failed")]
|
||||
HandshakeFailed,
|
||||
}
|
||||
+65
-32
@@ -3,55 +3,88 @@
|
||||
// #![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 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};
|
||||
use nym_tun::tun_device;
|
||||
|
||||
/// Start wireguard device
|
||||
use nym_tun::tun_task_channel;
|
||||
|
||||
/// 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.
|
||||
#[cfg(target_os = "linux")]
|
||||
pub async fn start_wireguard(
|
||||
mut task_client: nym_task::TaskClient,
|
||||
_gateway_client_registry: Arc<GatewayClientRegistry>,
|
||||
) -> Result<WGApi, Box<dyn std::error::Error + Send + Sync + 'static>> {
|
||||
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![],
|
||||
task_client: nym_task::TaskClient,
|
||||
gateway_client_registry: Arc<GatewayClientRegistry>,
|
||||
) -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
|
||||
// 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: nym_network_defaults::WG_TUN_BASE_NAME.to_string(),
|
||||
ip: nym_network_defaults::WG_TUN_DEVICE_ADDRESS.parse().unwrap(),
|
||||
netmask: nym_network_defaults::WG_TUN_DEVICE_NETMASK.parse().unwrap(),
|
||||
};
|
||||
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()])?;
|
||||
let (tun, tun_task_tx, tun_task_response_rx) = tun_device::TunDevice::new(routing_mode, config);
|
||||
tun.start();
|
||||
|
||||
tokio::spawn(async move { task_client.recv().await });
|
||||
// We also index peers by a tag
|
||||
let peers_by_tag = Arc::new(tokio::sync::Mutex::new(wg_tunnel::PeersByTag::new()));
|
||||
|
||||
Ok(wgapi)
|
||||
// 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(())
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
pub async fn start_wireguard(
|
||||
_task_client: nym_task::TaskClient,
|
||||
_gateway_client_registry: Arc<GatewayClientRegistry>,
|
||||
) -> Result<WGApi, Box<dyn std::error::Error + Send + Sync + 'static>> {
|
||||
) -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
|
||||
todo!("WireGuard is currently only supported on Linux")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
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<u8>)>);
|
||||
pub(crate) struct PacketRelayReceiver(pub(crate) mpsc::Receiver<(u64, Vec<u8>)>);
|
||||
|
||||
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<tokio::sync::Mutex<HashMap<u64, PeerEventSender>>>,
|
||||
}
|
||||
|
||||
impl PacketRelayer {
|
||||
pub(crate) fn new(
|
||||
tun_task_tx: TunTaskTx,
|
||||
tun_task_response_rx: TunTaskResponseRx,
|
||||
peers_by_tag: Arc<tokio::sync::Mutex<HashMap<u64, PeerEventSender>>>,
|
||||
) -> (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 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
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<PeerPublicKey, Arc<tokio::sync::Mutex<RegisteredPeer>>>,
|
||||
peers_by_idx: HashMap<PeerIdx, Arc<tokio::sync::Mutex<RegisteredPeer>>>,
|
||||
}
|
||||
|
||||
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<tokio::sync::Mutex<RegisteredPeer>>) {
|
||||
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<tokio::sync::Mutex<RegisteredPeer>>> {
|
||||
self.peers.get(public_key)
|
||||
}
|
||||
|
||||
pub(crate) fn get_by_idx(
|
||||
&self,
|
||||
peer_idx: PeerIdx,
|
||||
) -> Option<&Arc<tokio::sync::Mutex<RegisteredPeer>>> {
|
||||
self.peers_by_idx.get(&peer_idx)
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
use std::net::IpAddr;
|
||||
|
||||
use base64::{engine::general_purpose, Engine as _};
|
||||
use boringtun::x25519;
|
||||
use log::info;
|
||||
|
||||
// The wireguard UDP listener
|
||||
@@ -8,7 +9,7 @@ pub const WG_ADDRESS: &str = "0.0.0.0";
|
||||
|
||||
// The private key of the listener
|
||||
// Corresponding public key: "WM8s8bYegwMa0TJ+xIwhk+dImk2IpDUKslDBCZPizlE="
|
||||
pub(crate) const PRIVATE_KEY: &str = "AEqXrLFT4qjYq3wmX0456iv94uM6nDj5ugp6Jedcflg=";
|
||||
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.
|
||||
@@ -22,11 +23,11 @@ fn decode_base64_key(base64_key: &str) -> [u8; 32] {
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
pub fn server_static_private_key() -> x25519_dalek::StaticSecret {
|
||||
pub fn server_static_private_key() -> x25519::StaticSecret {
|
||||
// TODO: this is a temporary solution for development
|
||||
let static_private_bytes: [u8; 32] = decode_base64_key(PRIVATE_KEY);
|
||||
let static_private = x25519_dalek::StaticSecret::from(static_private_bytes);
|
||||
let static_public = x25519_dalek::PublicKey::from(&static_private);
|
||||
let static_private = x25519::StaticSecret::from(static_private_bytes);
|
||||
let static_public = x25519::PublicKey::from(&static_private);
|
||||
info!(
|
||||
"wg public key: {}",
|
||||
general_purpose::STANDARD.encode(static_public)
|
||||
@@ -34,14 +35,14 @@ pub fn server_static_private_key() -> x25519_dalek::StaticSecret {
|
||||
static_private
|
||||
}
|
||||
|
||||
pub fn peer_static_public_key() -> x25519_dalek::PublicKey {
|
||||
pub fn peer_static_public_key() -> x25519::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_dalek::PublicKey::from(peer_static_public_bytes);
|
||||
let peer_static_public = x25519::PublicKey::from(peer_static_public_bytes);
|
||||
info!(
|
||||
"Adding wg peer public key: {}",
|
||||
general_purpose::STANDARD.encode(peer_static_public)
|
||||
@@ -51,6 +52,6 @@ pub fn peer_static_public_key() -> x25519_dalek::PublicKey {
|
||||
|
||||
pub fn peer_allowed_ips() -> ip_network::IpNetwork {
|
||||
let key: IpAddr = ALLOWED_IPS.parse().unwrap();
|
||||
let cidr = 32u8;
|
||||
let cidr = 0u8;
|
||||
ip_network::IpNetwork::new_truncate(key, cidr).unwrap()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,281 @@
|
||||
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_network_defaults::WG_PORT;
|
||||
use nym_task::TaskClient;
|
||||
use nym_wireguard_types::{
|
||||
registration::GatewayClientRegistry,
|
||||
tun_common::{
|
||||
active_peers::{ActivePeers, PeersByIp},
|
||||
event::Event,
|
||||
},
|
||||
PeerPublicKey,
|
||||
};
|
||||
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<tokio::sync::Mutex<PeersByIp>>,
|
||||
|
||||
// ... or alternatively we can map peers by their tag
|
||||
peers_by_tag: Arc<tokio::sync::Mutex<PeersByTag>>,
|
||||
|
||||
// The UDP socket to the peer
|
||||
udp: Arc<UdpSocket>,
|
||||
|
||||
// Send data to the TUN device for sending
|
||||
packet_tx: PacketRelaySender,
|
||||
|
||||
// Wireguard rate limiter
|
||||
rate_limiter: RateLimiter,
|
||||
|
||||
gateway_client_registry: Arc<GatewayClientRegistry>,
|
||||
}
|
||||
|
||||
impl WgUdpListener {
|
||||
pub async fn new(
|
||||
packet_tx: PacketRelaySender,
|
||||
peers_by_ip: Arc<tokio::sync::Mutex<PeersByIp>>,
|
||||
peers_by_tag: Arc<tokio::sync::Mutex<PeersByTag>>,
|
||||
gateway_client_registry: Arc<GatewayClientRegistry>,
|
||||
) -> Result<Self, Box<dyn std::error::Error + Send + Sync + 'static>> {
|
||||
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<GatewayClientRegistry>,
|
||||
) -> Result<Option<&'a Arc<tokio::sync::Mutex<RegisteredPeer>>>, 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)
|
||||
}
|
||||
@@ -0,0 +1,351 @@
|
||||
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<u64, PeerEventSender>;
|
||||
|
||||
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<UdpSocket>,
|
||||
|
||||
// Peer endpoint
|
||||
endpoint: Arc<tokio::sync::RwLock<SocketAddr>>,
|
||||
|
||||
// AllowedIPs for this peer
|
||||
allowed_ips: NetworkTable<()>,
|
||||
|
||||
// `boringtun` tunnel, used for crypto & WG protocol
|
||||
wg_tunnel: Arc<tokio::sync::Mutex<Tunn>>,
|
||||
|
||||
// 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<UdpSocket>,
|
||||
endpoint: SocketAddr,
|
||||
static_private: x25519::StaticSecret,
|
||||
peer_static_public: x25519::PublicKey,
|
||||
index: PeerIdx,
|
||||
peer_allowed_ips: ip_network::IpNetwork,
|
||||
// rate_limiter: Option<RateLimiter>,
|
||||
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<tokio::sync::MutexGuard<'_, Tunn>, 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<u8> {
|
||||
// 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<UdpSocket>,
|
||||
static_private: x25519::StaticSecret,
|
||||
peer_static_public: x25519::PublicKey,
|
||||
peer_index: PeerIdx,
|
||||
peer_allowed_ips: ip_network::IpNetwork,
|
||||
packet_tx: PacketRelaySender,
|
||||
) -> (
|
||||
tokio::task::JoinHandle<x25519::PublicKey>,
|
||||
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)
|
||||
}
|
||||
+7
-23
@@ -6,34 +6,18 @@ 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
|
||||
|
||||
* <p xmlns:cc="http://creativecommons.org/ns#" xmlns:dct="http://purl.org/dc/terms/"><a property="dct:title" rel="cc:attributionURL" href="https://nymtech.net/docs">Nym Documentation</a> by <a rel="cc:attributionURL dct:creator" property="cc:attributionName" href="https://nymtech.net">Nym Technologies</a> is licensed under <a href="http://creativecommons.org/licenses/by-nc-sa/4.0/?ref=chooser-v1" target="_blank" rel="license noopener noreferrer" style="display:inline-block;">CC BY-NC-SA 4.0<img style="height:22px!important;margin-left:3px;vertical-align:text-bottom;" src="https://mirrors.creativecommons.org/presskit/icons/cc.svg?ref=chooser-v1"><img style="height:22px!important;margin-left:3px;vertical-align:text-bottom;" src="https://mirrors.creativecommons.org/presskit/icons/by.svg?ref=chooser-v1"><img style="height:22px!important;margin-left:3px;vertical-align:text-bottom;" src="https://mirrors.creativecommons.org/presskit/icons/nc.svg?ref=chooser-v1"><img style="height:22px!important;margin-left:3px;vertical-align:text-bottom;" src="https://mirrors.creativecommons.org/presskit/icons/sa.svg?ref=chooser-v1"></a></p>
|
||||
|
||||
* 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.
|
||||
@@ -198,7 +198,5 @@ 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.
|
||||
|
||||
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).
|
||||
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.
|
||||
|
||||
|
||||
@@ -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 [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 **new [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 [TS SDK Handbook](https://sdk.nymtech.net/).
|
||||
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/)** !
|
||||
@@ -1,11 +1,10 @@
|
||||
# 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
|
||||
|
||||
* <p xmlns:cc="http://creativecommons.org/ns#" xmlns:dct="http://purl.org/dc/terms/"><a property="dct:title" rel="cc:attributionURL" href="https://nymtech.net/docs">Nym Documentation</a> by <a rel="cc:attributionURL dct:creator" property="cc:attributionName" href="https://nymtech.net">Nym Technologies</a> is licensed under <a href="http://creativecommons.org/licenses/by-nc-sa/4.0/?ref=chooser-v1" target="_blank" rel="license noopener noreferrer" style="display:inline-block;">CC BY-NC-SA 4.0<img style="height:22px!important;margin-left:3px;vertical-align:text-bottom;" src="https://mirrors.creativecommons.org/presskit/icons/cc.svg?ref=chooser-v1"><img style="height:22px!important;margin-left:3px;vertical-align:text-bottom;" src="https://mirrors.creativecommons.org/presskit/icons/by.svg?ref=chooser-v1"><img style="height:22px!important;margin-left:3px;vertical-align:text-bottom;" src="https://mirrors.creativecommons.org/presskit/icons/nc.svg?ref=chooser-v1"><img style="height:22px!important;margin-left:3px;vertical-align:text-bottom;" src="https://mirrors.creativecommons.org/presskit/icons/sa.svg?ref=chooser-v1"></a></p>
|
||||
|
||||
* 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.
|
||||
Again, for accurate information, please check individual files.
|
||||
|
||||
@@ -1,11 +1,8 @@
|
||||
# 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
|
||||
|
||||
* <p xmlns:cc="http://creativecommons.org/ns#" xmlns:dct="http://purl.org/dc/terms/"><a property="dct:title" rel="cc:attributionURL" href="https://nymtech.net/docs">Nym Documentation</a> by <a rel="cc:attributionURL dct:creator" property="cc:attributionName" href="https://nymtech.net">Nym Technologies</a> is licensed under <a href="http://creativecommons.org/licenses/by-nc-sa/4.0/?ref=chooser-v1" target="_blank" rel="license noopener noreferrer" style="display:inline-block;">CC BY-NC-SA 4.0<img style="height:22px!important;margin-left:3px;vertical-align:text-bottom;" src="https://mirrors.creativecommons.org/presskit/icons/cc.svg?ref=chooser-v1"><img style="height:22px!important;margin-left:3px;vertical-align:text-bottom;" src="https://mirrors.creativecommons.org/presskit/icons/by.svg?ref=chooser-v1"><img style="height:22px!important;margin-left:3px;vertical-align:text-bottom;" src="https://mirrors.creativecommons.org/presskit/icons/nc.svg?ref=chooser-v1"><img style="height:22px!important;margin-left:3px;vertical-align:text-bottom;" src="https://mirrors.creativecommons.org/presskit/icons/sa.svg?ref=chooser-v1"></a></p>
|
||||
|
||||
* 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.
|
||||
Again, for accurate information, please check individual files.
|
||||
|
||||
@@ -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/faq/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/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/faq/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/integrations/faq.html).
|
||||
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
# CLI Wallet
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
### 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](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.
|
||||
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.
|
||||
|
||||
For more on interacting with the chain, see the [Interacting with Nyx Chain and Smart Contracts](../nyx/interacting-with-chain.md) page.
|
||||
|
||||
@@ -1,80 +0,0 @@
|
||||
#!/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;
|
||||
@@ -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", "./custom.css", "./mdbook-admonish.css"]
|
||||
additional-css = ["theme/pagetoc.css", "././mdbook-admonish.css","./custom.css", "./mdbook-admonish.css"]
|
||||
additional-js = ["theme/pagetoc.js"]
|
||||
git-repository-url = "https://github.com/nymtech/nym"
|
||||
git-repository-icon = "fa-github"
|
||||
|
||||
@@ -1,11 +1,8 @@
|
||||
# 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
|
||||
|
||||
* <p xmlns:cc="http://creativecommons.org/ns#" xmlns:dct="http://purl.org/dc/terms/"><a property="dct:title" rel="cc:attributionURL" href="https://nymtech.net/docs">Nym Documentation</a> by <a rel="cc:attributionURL dct:creator" property="cc:attributionName" href="https://nymtech.net">Nym Technologies</a> is licensed under <a href="http://creativecommons.org/licenses/by-nc-sa/4.0/?ref=chooser-v1" target="_blank" rel="license noopener noreferrer" style="display:inline-block;">CC BY-NC-SA 4.0<img style="height:22px!important;margin-left:3px;vertical-align:text-bottom;" src="https://mirrors.creativecommons.org/presskit/icons/cc.svg?ref=chooser-v1"><img style="height:22px!important;margin-left:3px;vertical-align:text-bottom;" src="https://mirrors.creativecommons.org/presskit/icons/by.svg?ref=chooser-v1"><img style="height:22px!important;margin-left:3px;vertical-align:text-bottom;" src="https://mirrors.creativecommons.org/presskit/icons/nc.svg?ref=chooser-v1"><img style="height:22px!important;margin-left:3px;vertical-align:text-bottom;" src="https://mirrors.creativecommons.org/presskit/icons/sa.svg?ref=chooser-v1"></a></p>
|
||||
|
||||
* 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.
|
||||
Again, for accurate information, please check individual files.
|
||||
|
||||
@@ -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 any 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 ny 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 first**, then follow the steps below:
|
||||
You can bond your Gateway via the Desktop wallet. Make sure your Gateway is running and 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 `<YOUR_ID>` we used `supergateway`):
|
||||
* And paste it into the wallet nodal, press `Next` and confirm the transaction.
|
||||
|
||||

|
||||
*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.
|
||||
|
||||
|
||||
@@ -30,7 +30,7 @@ Follow these steps to upgrade your Node binary and update its config file:
|
||||
* Replace the existing `<NODE>` 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 `<NODE>` ([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 automated, just `run` your `<NODE>` with `./nym-<NODE> run --id <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 your node is not automitized, just `run` your `<NODE>` with `./nym-<NODE> run --id <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:
|
||||
```sh
|
||||
systemctl daemon-reload # to pickup the new unit file
|
||||
@@ -117,34 +117,7 @@ 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.
|
||||
|
||||
### 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/<ID>/config/config.toml`.
|
||||
Now you can run WSS on your Gateway.
|
||||
|
||||
### WSS on an existing Gateway
|
||||
|
||||
@@ -230,6 +203,29 @@ 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/<ID>/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 `<NODE>` is now ready to receive traffic, your server may not be. The following commands will allow you to set up a firewall using `ufw`.
|
||||
@@ -254,9 +250,6 @@ Finally open your `<NODE>` 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
|
||||
|
||||
@@ -273,13 +266,9 @@ For more information about your node's port configuration, check the [port refer
|
||||
|
||||
## VPS Setup and Automation
|
||||
|
||||
> Replace `<NODE>` 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. 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!
|
||||
Although it’s not totally necessary, it's useful to have the Mix Node automatically start at system boot time.
|
||||
|
||||
#### nohup
|
||||
|
||||
@@ -330,7 +319,7 @@ tmux attach-session
|
||||
|
||||
#### systemd
|
||||
|
||||
To automate with `systemd` use this init service file and follow the steps below.
|
||||
Here's a systemd service file to do that:
|
||||
|
||||
##### For Mix Node
|
||||
|
||||
@@ -352,7 +341,7 @@ RestartSec=30
|
||||
WantedBy=multi-user.target
|
||||
```
|
||||
|
||||
* 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).
|
||||
* Put the above file onto your system at `/etc/systemd/system/nym-mixnode.service`.
|
||||
|
||||
##### For Gateway
|
||||
|
||||
@@ -374,7 +363,7 @@ RestartSec=30
|
||||
WantedBy=multi-user.target
|
||||
```
|
||||
|
||||
* 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).
|
||||
* Put the above file onto your system at `/etc/systemd/system/nym-gateway.service`.
|
||||
|
||||
##### For Network Requester
|
||||
|
||||
@@ -396,79 +385,21 @@ 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).
|
||||
|
||||
#### Following steps for Nym nodes running as `systemd` service
|
||||
|
||||
Change the `<PATH>` in `ExecStart` to point at your `<NODE>` binary (`nym-mixnode`, `nym-gateway` or `nym-network-requester`), and the `<USER>` so it is the user you are running as.
|
||||
|
||||
Example: If you have built nym in the `$HOME` directory on your server, your username is `jetpanther`, and node `<ID>` 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:
|
||||
|
||||
`ExecStart=/home/jetpanther/nym/target/release/nym-mixnode run --id puma`.
|
||||
|
||||
Basically, you want the full `/<PATH>/<TO>/nym-mixnode run --id <WHATEVER-YOUR-NODE-ID-IS>`. If you are unsure about your `/<PATH>/<TO>/<NODE>`, then `cd` to your directory where you run your `<NODE>` from and run `pwd` command which returns the full path for you.
|
||||
|
||||
Once done, save the script and follow these steps:
|
||||
Now enable and start your requester:
|
||||
|
||||
```sh
|
||||
systemctl daemon-reload
|
||||
# to pickup the new unit file
|
||||
```
|
||||
|
||||
Enable the newly created service:
|
||||
|
||||
```sh
|
||||
# for Mix Node
|
||||
systemctl enable nym-mixnode.service
|
||||
|
||||
# for Gateway
|
||||
systemctl enable nym-gateway.service
|
||||
|
||||
# for Network Requester
|
||||
systemctl enable nym-network-requester.service
|
||||
systemctl start nym-network-requester.service
|
||||
|
||||
# you can always check your requester has succesfully started with:
|
||||
systemctl status nym-network-requester.service
|
||||
```
|
||||
|
||||
Start your `<NODE>` as a `systemd` service:
|
||||
|
||||
```sh
|
||||
# for Mix Node
|
||||
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, your `<NODE>` will come back up automatically.
|
||||
|
||||
You can monitor system logs of your node by running:
|
||||
```sh
|
||||
journalctl -f -u <NODE>.service
|
||||
# for example journalctl -f -u nym-mixnode.service
|
||||
```
|
||||
|
||||
Or check a status by running:
|
||||
```sh
|
||||
systemctl status <NODE>.service
|
||||
# for example systemctl status nym-mixnode.service
|
||||
```
|
||||
|
||||
You can also do `service <NODE> stop` or `service <NODE> restart`.
|
||||
|
||||
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. Then restart your `<NODE>`.
|
||||
|
||||
* Put the above file onto your system at `/etc/systemd/system/nym-network-requester.service`.
|
||||
|
||||
##### For Validator
|
||||
|
||||
Below is a `systemd` unit file to place at `/etc/systemd/system/nymd.service` to automate your validator:
|
||||
Below is a systemd unit file to place at `/etc/systemd/system/nymd.service`:
|
||||
|
||||
```ini
|
||||
[Unit]
|
||||
@@ -498,6 +429,61 @@ systemctl start nymd # to actually start the service
|
||||
journalctl -f -u nymd # to monitor system logs showing the service start
|
||||
```
|
||||
|
||||
##### Following steps for Nym Mixnet nodes
|
||||
|
||||
Change the `<PATH>` in `ExecStart` to point at your `<NODE>` binary (`nym-mixnode`, `nym-gateway` or `nym-network-requester`), and the `<USER>` 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 <YOUR_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
|
||||
```
|
||||
|
||||
```sh
|
||||
# for Mix Node
|
||||
systemctl enable nym-mixnode.service
|
||||
|
||||
# for Gateway
|
||||
systemctl enable nym-gateway.service
|
||||
```
|
||||
|
||||
Start your node:
|
||||
|
||||
```sh
|
||||
# for Mix Node
|
||||
service nym-mixnode start
|
||||
|
||||
# for Gateway
|
||||
service nym-gateway start
|
||||
|
||||
```
|
||||
|
||||
This will cause your node to start at system boot time. If you restart your machine, the node will come back up automatically.
|
||||
|
||||
You can monitor system logs of your node by running:
|
||||
```sh
|
||||
journalctl -f -u <NODE>.service
|
||||
```
|
||||
|
||||
Or check a status by running:
|
||||
```sh
|
||||
systemctl status <NODE>.service
|
||||
```
|
||||
|
||||
You can also do `service <NODE> stop` or `service <NODE> restart`.
|
||||
|
||||
Note: if you make any changes to your systemd script after you've enabled it, you will need to run:
|
||||
|
||||
```
|
||||
systemctl daemon-reload
|
||||
```
|
||||
|
||||
This lets your operating system know it's ok to reload the service configuration.
|
||||
|
||||
### Setting the ulimit
|
||||
|
||||
Linux machines limit how many open files a user is allowed to have. This is called a `ulimit`.
|
||||
@@ -625,12 +611,11 @@ scp -r -3 <SOURCE_USER_NAME>@<SOURCE_HOST_ADDRESS>:~/.nym/mixnodes/<YOUR_ID> <TA
|
||||
|
||||
|
||||
## Virtual IPs and hosting via Google & AWS
|
||||
|
||||
For true internet decentralization we encourage operators to use diverse VPS providers instead of the largest companies offering such services. If for some reasons you have already running AWS or Google and want to setup a `<NODE>` 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 -4 https://ifconfig.me)`, but that may not the public IP address to bond your `<NODE>` in the wallet.
|
||||
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`.
|
||||
|
||||
You can run `ifconfig` command. For example, on a Google machine, you may see the following output:
|
||||
For example, on a Google machine, you may see the following output from the `ifconfig` command:
|
||||
|
||||
```sh
|
||||
ens4: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1460
|
||||
@@ -640,14 +625,20 @@ ens4: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> 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`.
|
||||
|
||||
To find the right IP configuration, contact your VPS provider for support to find the right public IP and use it to bond your `<NODE>` with the `nym-api` via Nym wallet.
|
||||
`./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.
|
||||
|
||||
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.
|
||||
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`.
|
||||
|
||||
It's up to you as a node operator to ensure that your public and private IPs match up properly.
|
||||
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.
|
||||
|
||||
## 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
|
||||
@@ -835,5 +826,4 @@ All validator-specific port configuration can be found in `$HOME/.nymd/config/co
|
||||
| 26656 | Listen for incoming peer connections |
|
||||
| 26660 | Listen for Prometheus connections |
|
||||
|
||||
|
||||
|
||||
/
|
||||
|
||||
@@ -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 <YOUR_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/<YOUR_ID>/config/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/<YOUR_ID>/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-mixnode` process in order for the new description to be propagated.
|
||||
> Remember to restart your `nym-mix-node` process in order for the new description to be propagated.
|
||||
|
||||
## Running your Mix Node
|
||||
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
#!/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
|
||||
+2
-4
@@ -77,10 +77,8 @@ 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-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 }
|
||||
nym-ip-packet-router = { path = "../service-providers/ip-packet-router" }
|
||||
|
||||
[dev-dependencies]
|
||||
tower = "0.4.13"
|
||||
@@ -97,4 +95,4 @@ sqlx = { version = "0.5", features = [
|
||||
] }
|
||||
|
||||
[features]
|
||||
wireguard = ["nym-wireguard", "defguard_wireguard_rs"]
|
||||
wireguard = ["nym-wireguard"]
|
||||
|
||||
@@ -22,8 +22,6 @@ 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};
|
||||
@@ -206,7 +204,8 @@ impl<St> Gateway<St> {
|
||||
async fn start_wireguard(
|
||||
&self,
|
||||
shutdown: TaskClient,
|
||||
) -> Result<WGApi, Box<dyn Error + Send + Sync>> {
|
||||
) -> Result<(), Box<dyn Error + Send + Sync>> {
|
||||
// TODO: possibly we should start the UDP listener and TUN device explicitly here
|
||||
nym_wireguard::start_wireguard(shutdown, Arc::clone(&self.client_registry)).await
|
||||
}
|
||||
|
||||
@@ -524,10 +523,13 @@ impl<St> Gateway<St> {
|
||||
// Once this is a bit more mature, make this a commandline flag instead of a compile time
|
||||
// flag
|
||||
#[cfg(feature = "wireguard")]
|
||||
let wg_api = self
|
||||
if let Err(err) = self
|
||||
.start_wireguard(shutdown.subscribe().named("wireguard"))
|
||||
.await
|
||||
.ok();
|
||||
{
|
||||
// that's a nasty workaround, but anyhow errors are generally nicer, especially on exit
|
||||
bail!("{err}")
|
||||
}
|
||||
|
||||
info!("Finished nym gateway startup procedure - it should now be able to receive mix and client traffic!");
|
||||
|
||||
@@ -535,10 +537,6 @@ impl<St> Gateway<St> {
|
||||
// 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(())
|
||||
}
|
||||
}
|
||||
|
||||
Generated
+87
-10
@@ -514,6 +514,15 @@ 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"
|
||||
@@ -601,6 +610,29 @@ 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"
|
||||
@@ -3225,6 +3257,28 @@ 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"
|
||||
@@ -3499,7 +3553,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4ae926706ba42c425c9457121178330d75e273df2e82e28b758faf3de3a9acb9"
|
||||
dependencies = [
|
||||
"arrayref",
|
||||
"blake2",
|
||||
"blake2 0.8.1",
|
||||
"chacha",
|
||||
"keystream",
|
||||
]
|
||||
@@ -3716,6 +3770,18 @@ 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"
|
||||
@@ -4697,11 +4763,16 @@ 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",
|
||||
"thiserror",
|
||||
"tokio",
|
||||
"x25519-dalek 2.0.0",
|
||||
]
|
||||
|
||||
@@ -5732,7 +5803,7 @@ dependencies = [
|
||||
"libc",
|
||||
"once_cell",
|
||||
"spin 0.5.2",
|
||||
"untrusted",
|
||||
"untrusted 0.7.1",
|
||||
"web-sys",
|
||||
"winapi",
|
||||
]
|
||||
@@ -5888,7 +5959,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3c7d5dece342910d9ba34d259310cae3e0154b873b35408b787b59bce53d34fe"
|
||||
dependencies = [
|
||||
"ring",
|
||||
"untrusted",
|
||||
"untrusted 0.7.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5971,7 +6042,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b362b83898e0e69f38515b82ee15aa80636befe47c3b6d3d89a911e78fc228ce"
|
||||
dependencies = [
|
||||
"ring",
|
||||
"untrusted",
|
||||
"untrusted 0.7.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5981,7 +6052,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d53dcdb7c9f8158937a7981b48accfd39a43af418591a5d008c7b22b5e1b7ca4"
|
||||
dependencies = [
|
||||
"ring",
|
||||
"untrusted",
|
||||
"untrusted 0.7.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6531,7 +6602,7 @@ checksum = "cc43eda802856ee82a7555c7b75ceb9e07451741c7a2f5f23d036020e01189d4"
|
||||
dependencies = [
|
||||
"aes 0.7.5",
|
||||
"arrayref",
|
||||
"blake2",
|
||||
"blake2 0.8.1",
|
||||
"bs58 0.4.0",
|
||||
"byteorder",
|
||||
"chacha",
|
||||
@@ -7811,6 +7882,12 @@ 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"
|
||||
@@ -8161,7 +8238,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b8e38c0608262c46d4a56202ebabdeb094cef7e560ca7a226c6bf055188aa4ea"
|
||||
dependencies = [
|
||||
"ring",
|
||||
"untrusted",
|
||||
"untrusted 0.7.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -8171,7 +8248,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "07ecc0cd7cac091bf682ec5efa18b1cff79d617b84181f38b3951dbe135f607f"
|
||||
dependencies = [
|
||||
"ring",
|
||||
"untrusted",
|
||||
"untrusted 0.7.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -8647,7 +8724,7 @@ version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2769203cd13a0c6015d515be729c526d041e9cf2c0cc478d57faee85f40c6dcd"
|
||||
dependencies = [
|
||||
"nix",
|
||||
"nix 0.26.2",
|
||||
"winapi",
|
||||
]
|
||||
|
||||
@@ -8684,7 +8761,7 @@ dependencies = [
|
||||
"futures-sink",
|
||||
"futures-util",
|
||||
"hex",
|
||||
"nix",
|
||||
"nix 0.26.2",
|
||||
"once_cell",
|
||||
"ordered-stream",
|
||||
"rand 0.8.5",
|
||||
|
||||
@@ -4,47 +4,18 @@ 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', 'import'],
|
||||
plugins: ['@typescript-eslint'],
|
||||
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 `<root>@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' }],
|
||||
},
|
||||
};
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<!doctype html>
|
||||
<html lang="en" class="text-[12px]">
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||
@@ -8,7 +8,7 @@
|
||||
</head>
|
||||
|
||||
<body class="h-screen">
|
||||
<div id="root" class="h-full font-sans"></div>
|
||||
<div id="root" class="h-full bg-gray-900 text-gray-400"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -18,12 +18,10 @@
|
||||
"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",
|
||||
@@ -41,9 +39,6 @@
|
||||
"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",
|
||||
|
||||
Generated
-1
@@ -1811,7 +1811,6 @@ dependencies = [
|
||||
"tauri",
|
||||
"tauri-build",
|
||||
"thiserror",
|
||||
"time",
|
||||
"tokio",
|
||||
"toml 0.8.5",
|
||||
"tracing",
|
||||
|
||||
@@ -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,7 +23,6 @@ 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
|
||||
|
||||
@@ -1,46 +0,0 @@
|
||||
use tauri::State;
|
||||
use tracing::{debug, instrument};
|
||||
|
||||
use crate::{
|
||||
error::{CmdError, CmdErrorSource},
|
||||
fs::data::AppData,
|
||||
states::SharedAppData,
|
||||
};
|
||||
|
||||
#[instrument]
|
||||
#[tauri::command]
|
||||
pub async fn set_app_data(
|
||||
state: State<'_, SharedAppData>,
|
||||
data: Option<AppData>,
|
||||
) -> 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<AppData>,
|
||||
) -> Result<AppData, CmdError> {
|
||||
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)
|
||||
}
|
||||
@@ -1,48 +1,26 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use tauri::{Manager, State};
|
||||
use time::OffsetDateTime;
|
||||
use tokio::time::sleep;
|
||||
use tracing::{debug, error, instrument, trace};
|
||||
use tracing::{debug, instrument, trace};
|
||||
|
||||
use crate::{
|
||||
error::{CmdError, CmdErrorSource},
|
||||
states::{
|
||||
app::{ConnectionState, VpnMode},
|
||||
SharedAppData, SharedAppState,
|
||||
},
|
||||
error::CommandError,
|
||||
states::{app::ConnectionState, SharedAppState},
|
||||
};
|
||||
|
||||
const EVENT_CONNECTION_STATE: &str = "connection-state";
|
||||
const EVENT_CONNECTION_PROGRESS: &str = "connection-progress";
|
||||
const EVENT_CONNECTION: &str = "connection-state";
|
||||
|
||||
#[derive(Clone, serde::Serialize)]
|
||||
struct ConnectionEventPayload {
|
||||
struct EventPayload {
|
||||
state: ConnectionState,
|
||||
error: Option<String>,
|
||||
start_time: Option<i64>, // unix timestamp in seconds
|
||||
}
|
||||
|
||||
impl ConnectionEventPayload {
|
||||
fn new(state: ConnectionState, error: Option<String>, start_time: Option<i64>) -> 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<ConnectionState, CmdError> {
|
||||
) -> Result<ConnectionState, CommandError> {
|
||||
debug!("get_connection_state");
|
||||
let app_state = state.lock().await;
|
||||
Ok(app_state.state)
|
||||
@@ -53,14 +31,14 @@ pub async fn get_connection_state(
|
||||
pub async fn connect(
|
||||
app: tauri::AppHandle,
|
||||
state: State<'_, SharedAppState>,
|
||||
) -> Result<ConnectionState, CmdError> {
|
||||
) -> Result<ConnectionState, CommandError> {
|
||||
debug!("connect");
|
||||
let mut app_state = state.lock().await;
|
||||
let ConnectionState::Disconnected = app_state.state else {
|
||||
return Err(CmdError::new(
|
||||
CmdErrorSource::CallerError,
|
||||
format!("cannot connect from state {:?}", app_state.state),
|
||||
));
|
||||
return Err(CommandError::CallerError(format!(
|
||||
"cannot connect from state {:?}",
|
||||
app_state.state
|
||||
)));
|
||||
};
|
||||
|
||||
// switch to "Connecting" state
|
||||
@@ -68,51 +46,25 @@ pub async fn connect(
|
||||
// unlock the mutex
|
||||
drop(app_state);
|
||||
app.emit_all(
|
||||
EVENT_CONNECTION_STATE,
|
||||
ConnectionEventPayload::new(ConnectionState::Connecting, None, None),
|
||||
EVENT_CONNECTION,
|
||||
EventPayload {
|
||||
state: ConnectionState::Connecting,
|
||||
},
|
||||
)
|
||||
.ok();
|
||||
|
||||
// TODO fake some delay to establish connection
|
||||
let app_state_cloned = state.inner().clone();
|
||||
let task = tokio::spawn(async move {
|
||||
app.emit_all(
|
||||
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;
|
||||
sleep(Duration::from_secs(2)).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_state_cloned.lock().await.state = ConnectionState::Connected;
|
||||
debug!("sending event [{}]: connected", EVENT_CONNECTION);
|
||||
app.emit_all(
|
||||
EVENT_CONNECTION_STATE,
|
||||
ConnectionEventPayload::new(
|
||||
ConnectionState::Connected,
|
||||
None,
|
||||
Some(now.unix_timestamp()),
|
||||
),
|
||||
EVENT_CONNECTION,
|
||||
EventPayload {
|
||||
state: ConnectionState::Connected,
|
||||
},
|
||||
)
|
||||
.ok();
|
||||
});
|
||||
@@ -128,14 +80,14 @@ pub async fn connect(
|
||||
pub async fn disconnect(
|
||||
app: tauri::AppHandle,
|
||||
state: State<'_, SharedAppState>,
|
||||
) -> Result<ConnectionState, CmdError> {
|
||||
) -> Result<ConnectionState, CommandError> {
|
||||
debug!("disconnect");
|
||||
let mut app_state = state.lock().await;
|
||||
let ConnectionState::Connected = app_state.state else {
|
||||
return Err(CmdError::new(
|
||||
CmdErrorSource::CallerError,
|
||||
format!("cannot disconnect from state {:?}", app_state.state),
|
||||
));
|
||||
return Err(CommandError::CallerError(format!(
|
||||
"cannot disconnect from state {:?}",
|
||||
app_state.state
|
||||
)));
|
||||
};
|
||||
|
||||
// switch to "Disconnecting" state
|
||||
@@ -143,25 +95,25 @@ pub async fn disconnect(
|
||||
// unlock the mutex
|
||||
drop(app_state);
|
||||
app.emit_all(
|
||||
EVENT_CONNECTION_STATE,
|
||||
ConnectionEventPayload::new(ConnectionState::Disconnecting, None, None),
|
||||
EVENT_CONNECTION,
|
||||
EventPayload {
|
||||
state: ConnectionState::Disconnecting,
|
||||
},
|
||||
)
|
||||
.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(1)).await;
|
||||
sleep(Duration::from_secs(2)).await;
|
||||
trace!("disconnected");
|
||||
|
||||
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_state_cloned.lock().await.state = ConnectionState::Disconnected;
|
||||
debug!("sending event [{}]: disconnected", EVENT_CONNECTION);
|
||||
app.emit_all(
|
||||
EVENT_CONNECTION_STATE,
|
||||
ConnectionEventPayload::new(ConnectionState::Disconnected, None, None),
|
||||
EVENT_CONNECTION,
|
||||
EventPayload {
|
||||
state: ConnectionState::Disconnected,
|
||||
},
|
||||
)
|
||||
.ok();
|
||||
});
|
||||
@@ -171,47 +123,3 @@ 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<Option<i64>, 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(())
|
||||
}
|
||||
|
||||
@@ -1,2 +1,11 @@
|
||||
pub mod app_data;
|
||||
use tracing::{debug, instrument};
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
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(())
|
||||
}
|
||||
@@ -1,39 +1,12 @@
|
||||
use std::fmt::{self, Display};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use thiserror::Error;
|
||||
use ts_rs::TS;
|
||||
|
||||
#[derive(Error, Debug, Serialize, Deserialize, TS)]
|
||||
#[ts(export)]
|
||||
pub enum CmdErrorSource {
|
||||
#[error("internal error")]
|
||||
InternalError,
|
||||
#[error("caller error")]
|
||||
CallerError,
|
||||
#[derive(Error, Debug, Serialize, Deserialize)]
|
||||
pub enum CommandError {
|
||||
#[error("internal error: `{0}`")]
|
||||
InternalError(String),
|
||||
#[error("caller error: `{0}`")]
|
||||
CallerError(String),
|
||||
#[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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,24 +1,13 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use ts_rs::TS;
|
||||
|
||||
use crate::states::app::{NodeConfig, VpnMode};
|
||||
use crate::states::app::{NodeConfig, PrivacyMode};
|
||||
|
||||
#[derive(Default, Serialize, Deserialize, Debug, Clone, TS)]
|
||||
#[ts(export)]
|
||||
pub enum UiTheme {
|
||||
Dark,
|
||||
#[default]
|
||||
Light,
|
||||
}
|
||||
|
||||
#[derive(Default, Serialize, Deserialize, Debug, Clone, TS)]
|
||||
#[ts(export)]
|
||||
#[derive(Default, Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct AppData {
|
||||
pub monitoring: Option<bool>,
|
||||
pub autoconnect: Option<bool>,
|
||||
pub killswitch: Option<bool>,
|
||||
pub ui_theme: Option<UiTheme>,
|
||||
pub vpn_mode: Option<VpnMode>,
|
||||
pub privacy_mode: Option<PrivacyMode>,
|
||||
pub entry_node: Option<NodeConfig>,
|
||||
pub exit_node: Option<NodeConfig>,
|
||||
}
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
use anyhow::{anyhow, Context, Result};
|
||||
use serde::{de::DeserializeOwned, Serialize};
|
||||
use std::{fmt, path::PathBuf, str};
|
||||
use std::{fmt, fs, path::PathBuf, str};
|
||||
use tauri::api::path::data_dir;
|
||||
use tokio::fs;
|
||||
use tracing::{debug, error, instrument};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -16,14 +15,14 @@ where
|
||||
pub full_path: PathBuf,
|
||||
}
|
||||
|
||||
async fn create_directory_path(path: &PathBuf) -> Result<()> {
|
||||
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).await.context(format!(
|
||||
fs::create_dir_all(&data_dir).context(format!(
|
||||
"Failed to create data directory {}",
|
||||
data_dir.display()
|
||||
))
|
||||
@@ -46,18 +45,12 @@ where
|
||||
}
|
||||
|
||||
#[instrument]
|
||||
pub async fn read(&self) -> Result<T> {
|
||||
pub fn read(&self) -> Result<T> {
|
||||
// create the full directory path if it is missing
|
||||
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?,
|
||||
}
|
||||
create_directory_path(&self.dir_path)?;
|
||||
|
||||
debug!("reading stored data from {}", self.full_path.display());
|
||||
let content = fs::read(&self.full_path).await.context(format!(
|
||||
let content = fs::read(&self.full_path).context(format!(
|
||||
"Failed to read data from {}",
|
||||
self.full_path.display()
|
||||
))?;
|
||||
@@ -69,23 +62,23 @@ where
|
||||
}
|
||||
|
||||
#[instrument]
|
||||
pub async fn write(&self) -> Result<()> {
|
||||
pub fn write(&self) -> Result<()> {
|
||||
// create the full directory path if it is missing
|
||||
create_directory_path(&self.dir_path).await?;
|
||||
create_directory_path(&self.dir_path)?;
|
||||
|
||||
debug!("writing data to {}", self.full_path.display());
|
||||
let toml = toml::to_string(&self.data)?;
|
||||
fs::write(&self.full_path, toml).await?;
|
||||
fs::write(&self.full_path, toml)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[instrument]
|
||||
pub async fn clear(&self) -> Result<()> {
|
||||
pub fn clear(&self) -> Result<()> {
|
||||
// create the full directory path if it is missing
|
||||
create_directory_path(&self.dir_path).await?;
|
||||
create_directory_path(&self.dir_path)?;
|
||||
|
||||
debug!("clearing data {}", self.full_path.display());
|
||||
fs::write(&self.full_path, vec![]).await?;
|
||||
fs::write(&self.full_path, vec![])?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,13 +51,12 @@ fn main() -> Result<()> {
|
||||
Ok(())
|
||||
})
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
connection::set_vpn_mode,
|
||||
greet,
|
||||
connection::get_connection_state,
|
||||
connection::connect,
|
||||
connection::disconnect,
|
||||
connection::get_connection_start_time,
|
||||
app_data::get_app_data,
|
||||
app_data::set_app_data,
|
||||
settings::save_user_settings,
|
||||
settings::set_user_settings,
|
||||
])
|
||||
.run(tauri::generate_context!())
|
||||
.expect("error while running tauri application");
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use time::OffsetDateTime;
|
||||
use ts_rs::TS;
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone, TS)]
|
||||
#[ts(export)]
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub struct NodeConfig {
|
||||
pub id: String,
|
||||
pub country: String,
|
||||
@@ -17,15 +15,16 @@ pub enum ConnectionState {
|
||||
Disconnected,
|
||||
Connecting,
|
||||
Disconnecting,
|
||||
Unknown,
|
||||
Error,
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Serialize, Deserialize, TS, Clone)]
|
||||
#[ts(export)]
|
||||
pub enum VpnMode {
|
||||
Mixnet,
|
||||
pub enum PrivacyMode {
|
||||
High,
|
||||
Medium,
|
||||
#[default]
|
||||
TwoHop,
|
||||
Low,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, TS)]
|
||||
@@ -38,10 +37,8 @@ pub struct TunnelConfig {
|
||||
#[derive(Debug, Default)]
|
||||
pub struct AppState {
|
||||
pub state: ConnectionState,
|
||||
pub error: Option<String>,
|
||||
pub vpn_mode: VpnMode,
|
||||
pub privacy_mode: PrivacyMode,
|
||||
pub entry_node: Option<NodeConfig>,
|
||||
pub exit_node: Option<NodeConfig>,
|
||||
pub tunnel: Option<TunnelConfig>,
|
||||
pub connection_start_time: Option<OffsetDateTime>,
|
||||
}
|
||||
|
||||
@@ -46,8 +46,8 @@
|
||||
"fullscreen": false,
|
||||
"resizable": true,
|
||||
"title": "NymVPN",
|
||||
"width": 440,
|
||||
"height": 920
|
||||
"width": 400,
|
||||
"height": 600
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
+21
-11
@@ -1,20 +1,30 @@
|
||||
import { RouterProvider } from 'react-router-dom';
|
||||
import dayjs from 'dayjs';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import router from './router';
|
||||
import { createBrowserRouter, RouterProvider } from 'react-router-dom';
|
||||
import { Home, Settings, Error, PageLayout } from './pages';
|
||||
import { MainStateProvider } from './state';
|
||||
import './i18n/config';
|
||||
import { ThemeSetter } from './ui';
|
||||
|
||||
const router = createBrowserRouter([
|
||||
{
|
||||
element: <PageLayout />,
|
||||
children: [
|
||||
{
|
||||
path: '/',
|
||||
element: <Home />,
|
||||
errorElement: <Error />,
|
||||
},
|
||||
{
|
||||
path: '/settings',
|
||||
element: <Settings />,
|
||||
errorElement: <Error />,
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
|
||||
function App() {
|
||||
const { i18n } = useTranslation();
|
||||
dayjs.locale(i18n.language);
|
||||
|
||||
return (
|
||||
<MainStateProvider>
|
||||
<ThemeSetter>
|
||||
<RouterProvider router={router} />
|
||||
</ThemeSetter>
|
||||
<RouterProvider router={router} />
|
||||
</MainStateProvider>
|
||||
);
|
||||
}
|
||||
|
||||
Binary file not shown.
@@ -1,10 +1 @@
|
||||
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';
|
||||
|
||||
@@ -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<AppState>(initialState);
|
||||
export const MainDispatchContext =
|
||||
|
||||
@@ -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,18 +32,5 @@ export function mockTauriIPC() {
|
||||
setTimeout(() => resolve('Disconnected'), 2000),
|
||||
);
|
||||
}
|
||||
if (cmd === 'get_app_data') {
|
||||
return new Promise<AppDataFromBackend>((resolve) =>
|
||||
resolve({
|
||||
monitoring: false,
|
||||
autoconnect: false,
|
||||
killswitch: false,
|
||||
ui_theme: 'Dark',
|
||||
vpn_mode: 'TwoHop',
|
||||
entry_node: null,
|
||||
exit_node: null,
|
||||
}),
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,24 +1,17 @@
|
||||
import i18n from 'i18next';
|
||||
import { initReactI18next } from 'react-i18next';
|
||||
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';
|
||||
import main from './en/main.json';
|
||||
|
||||
const defaultNS = 'common';
|
||||
const defaultNS = 'main';
|
||||
|
||||
i18n.use(initReactI18next).init({
|
||||
lng: 'en',
|
||||
debug: import.meta.env.DEV,
|
||||
resources: {
|
||||
en: {
|
||||
common,
|
||||
home,
|
||||
settings,
|
||||
nodeLocation,
|
||||
main,
|
||||
},
|
||||
},
|
||||
ns: ['common', 'home', 'settings', 'nodeLocation'],
|
||||
defaultNS,
|
||||
|
||||
interpolation: {
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
{
|
||||
"connect": "Connect",
|
||||
"disconnect": "Disconnect",
|
||||
"first-hop-selection": "First hop selection",
|
||||
"last-hop-selection": "Last hop selection",
|
||||
"settings": "Settings"
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
{
|
||||
"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}})"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"connect": "Connect",
|
||||
"disconnect": "Disconnect"
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
{}
|
||||
@@ -1 +0,0 @@
|
||||
{}
|
||||
@@ -1,8 +1,5 @@
|
||||
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';
|
||||
@@ -12,9 +9,6 @@ if (import.meta.env.MODE === 'dev-browser') {
|
||||
mockTauriIPC();
|
||||
}
|
||||
|
||||
dayjs.extend(relativeTime);
|
||||
dayjs.extend(duration);
|
||||
|
||||
ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
|
||||
<React.StrictMode>
|
||||
<App />
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
import { Outlet } from 'react-router-dom';
|
||||
import { TopBar } from '../ui';
|
||||
|
||||
function NavLayout() {
|
||||
return (
|
||||
<div className="h-full flex flex-col bg-blanc-nacre dark:bg-baltic-sea text-baltic-sea dark:text-white">
|
||||
<TopBar />
|
||||
<Outlet />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default NavLayout;
|
||||
@@ -1,17 +0,0 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
type Props = {
|
||||
node: 'entry' | 'exit';
|
||||
};
|
||||
|
||||
function NodeLocation({ node }: Props) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<div>
|
||||
{node === 'entry' ? t('fist-hop-selection') : t('last-hop-selection')}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default NodeLocation;
|
||||
@@ -1,9 +0,0 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
function Settings() {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return <div>{t('settings')}</div>;
|
||||
}
|
||||
|
||||
export default Settings;
|
||||
@@ -5,7 +5,7 @@ type routerErrorType = {
|
||||
message: string;
|
||||
};
|
||||
|
||||
export default function Error() {
|
||||
export default function ErrorPage() {
|
||||
const error: routerErrorType = useRouteError() as unknown as routerErrorType;
|
||||
console.error(error);
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
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 (
|
||||
<div>
|
||||
<h2>NymVPN</h2>
|
||||
connection state: {state.state}
|
||||
{state.loading ? (
|
||||
'loading…'
|
||||
) : (
|
||||
<button onClick={handleClick}>
|
||||
{state.state === 'Disconnected' ? t('connect') : t('disconnect')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default Home;
|
||||
@@ -1,84 +0,0 @@
|
||||
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 (
|
||||
<div className="h-64 flex flex-col justify-center items-center gap-y-2">
|
||||
<div className="flex flex-1 items-end">
|
||||
<div
|
||||
className={clsx([
|
||||
...statusBadgeDynStyles[state.state],
|
||||
'font-bold py-4 px-6 rounded-full text-lg',
|
||||
])}
|
||||
>
|
||||
{getStatusText(state.state)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-1">
|
||||
{state.loading && state.progressMessages.length > 0 && (
|
||||
<p className="text-dim-gray dark:text-mercury-mist font-bold">
|
||||
{state.progressMessages[state.progressMessages.length - 1]}
|
||||
</p>
|
||||
)}
|
||||
{state.state === 'Connected' && <ConnectionTimer />}
|
||||
{state.error && (
|
||||
<p className="text-teaberry font-bold">{state.error}</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default ConnectionStatus;
|
||||
@@ -1,41 +0,0 @@
|
||||
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 (
|
||||
<div className="flex flex-col items-center">
|
||||
<p className="font-bold text-dim-gray dark:text-mercury-mist">
|
||||
{t('connection-time')}
|
||||
</p>
|
||||
<p className="font-bold text-baltic-sea dark:text-white">
|
||||
{connectionTime}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default ConnectionTimer;
|
||||
@@ -1,79 +0,0 @@
|
||||
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 (
|
||||
<div className="flex justify-center items-center animate-spin">
|
||||
<span className="font-icon text-2xl font-medium">autorenew</span>
|
||||
</div>
|
||||
);
|
||||
case 'Disconnecting':
|
||||
return (
|
||||
<div className="flex justify-center items-center animate-spin">
|
||||
<span className="font-icon text-2xl font-medium">autorenew</span>
|
||||
</div>
|
||||
);
|
||||
case 'Unknown':
|
||||
return t('status.unknown');
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="h-full flex flex-col p-4">
|
||||
<ConnectionStatus />
|
||||
<div className="flex grow flex-col justify-between gap-y-2">
|
||||
<div className="flex flex-col justify-between">
|
||||
<NetworkModeSelect />
|
||||
<div></div>
|
||||
</div>
|
||||
<Button
|
||||
className={clsx([
|
||||
'rounded-lg text-lg font-bold py-4 px-6 h-16 focus:outline-none focus:ring-4 focus:ring-black focus:dark:ring-white shadow',
|
||||
(state.state === 'Disconnected' || state.state === 'Connecting') &&
|
||||
'bg-melon text-white dark:text-baltic-sea',
|
||||
(state.state === 'Connected' || state.state === 'Disconnecting') &&
|
||||
'bg-cornflower text-white dark:text-baltic-sea',
|
||||
])}
|
||||
onClick={handleClick}
|
||||
disabled={state.loading}
|
||||
>
|
||||
{getButtonText(state.state)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default Home;
|
||||
@@ -1,116 +0,0 @@
|
||||
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<void>('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 (
|
||||
<div className="">
|
||||
<RadioGroup value={selected} onChange={handleSelect}>
|
||||
<RadioGroup.Label
|
||||
as="div"
|
||||
className="font-semibold text-lg text-baltic-sea dark:text-white mb-4"
|
||||
>
|
||||
{t('select-network-label')}
|
||||
</RadioGroup.Label>
|
||||
<div className="space-y-4">
|
||||
{vpnModes.map((mode) => (
|
||||
<RadioGroup.Option
|
||||
key={mode.name}
|
||||
value={mode.name}
|
||||
className={({ checked }) =>
|
||||
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 (
|
||||
<div className="flex flex-1 items-center justify-between gap-4">
|
||||
{checked ? (
|
||||
<span className="font-icon text-2xl text-melon">
|
||||
radio_button_checked
|
||||
</span>
|
||||
) : (
|
||||
<span className="font-icon text-2xl text-mercury-pinkish">
|
||||
radio_button_unchecked
|
||||
</span>
|
||||
)}
|
||||
<div className="flex flex-1 items-center">
|
||||
<div className="text-sm">
|
||||
<RadioGroup.Label
|
||||
as="p"
|
||||
className="font-semibold text-lg text-baltic-sea dark:text-mercury-pinkish"
|
||||
>
|
||||
{mode.title}
|
||||
</RadioGroup.Label>
|
||||
<RadioGroup.Description
|
||||
as="span"
|
||||
className="text-base text-ciment-feet dark:text-mercury-mist"
|
||||
>
|
||||
<span>{mode.desc}</span>
|
||||
</RadioGroup.Description>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}}
|
||||
</RadioGroup.Option>
|
||||
))}
|
||||
</div>
|
||||
</RadioGroup>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default NetworkModeSelect;
|
||||
@@ -1 +0,0 @@
|
||||
export { default as Home } from './Home';
|
||||
@@ -1,5 +1,4 @@
|
||||
export * from './home';
|
||||
export { default as NavLayout } from './NavLayout';
|
||||
export { default as Settings } from './Settings';
|
||||
export { default as NodeLocation } from './NodeLocation';
|
||||
export { default as Error } from './Error';
|
||||
export { default as PageLayout } from './pageLayout';
|
||||
export { default as Home } from './home';
|
||||
export { default as Settings } from './settings';
|
||||
export { default as Error } from './error';
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import { Outlet } from 'react-router-dom';
|
||||
|
||||
function PageLayout() {
|
||||
return (
|
||||
<div>
|
||||
<Outlet />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default PageLayout;
|
||||
@@ -0,0 +1,5 @@
|
||||
function Settings() {
|
||||
return <div>Settings</div>;
|
||||
}
|
||||
|
||||
export default Settings;
|
||||
@@ -1,35 +0,0 @@
|
||||
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: <NavLayout />,
|
||||
children: [
|
||||
{
|
||||
element: <Home />,
|
||||
errorElement: <Error />,
|
||||
index: true,
|
||||
},
|
||||
{
|
||||
path: routes.settings,
|
||||
element: <Settings />,
|
||||
errorElement: <Error />,
|
||||
},
|
||||
{
|
||||
path: routes.entryNodeLocation,
|
||||
// eslint-disable-next-line react/jsx-no-undef
|
||||
element: <NodeLocation node="entry" />,
|
||||
errorElement: <Error />,
|
||||
},
|
||||
{
|
||||
path: routes.exitNodeLocation,
|
||||
element: <NodeLocation node="exit" />,
|
||||
errorElement: <Error />,
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
|
||||
export default router;
|
||||
@@ -1,54 +1,21 @@
|
||||
import dayjs from 'dayjs';
|
||||
import { AppData, AppState, ConnectionState, VpnMode } from '../types';
|
||||
import { AppState, ConnectionState } from '../types';
|
||||
|
||||
export type StateAction =
|
||||
| { type: 'set-partial-state'; partialState: Partial<AppState> }
|
||||
| { 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: 'set-connected'; startTime: number }
|
||||
| { type: 'set-connection-start-time'; startTime?: number | null }
|
||||
| { type: 'set-disconnected' }
|
||||
| { type: 'reset' }
|
||||
| { type: 'set-app-data'; data: AppData };
|
||||
| { type: 'reset' };
|
||||
|
||||
export const initialState: AppState = {
|
||||
state: 'Disconnected',
|
||||
loading: false,
|
||||
vpnMode: 'TwoHop',
|
||||
privacyMode: 'High',
|
||||
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,
|
||||
@@ -62,42 +29,6 @@ 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 'reset':
|
||||
return initialState;
|
||||
}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import React, { useEffect, useReducer } from 'react';
|
||||
import { 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,52 +20,9 @@ export function MainStateProvider({ children }: Props) {
|
||||
return await invoke<ConnectionState>('get_connection_state');
|
||||
};
|
||||
|
||||
// initialize session start time
|
||||
const getSessionStartTime = async () => {
|
||||
return await invoke<number | undefined>('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<AppDataFromBackend>('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 (
|
||||
|
||||
@@ -1,75 +1,39 @@
|
||||
import { useCallback, useEffect } from 'react';
|
||||
import { listen } from '@tauri-apps/api/event';
|
||||
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 });
|
||||
}
|
||||
import { EventPayload, StateDispatch } from '../types';
|
||||
import { ConnectionEvent } from '../constants';
|
||||
|
||||
export function useTauriEvents(dispatch: StateDispatch) {
|
||||
const registerStateListener = useCallback(() => {
|
||||
return listen<ConnectionEventPayload>(ConnectionEvent, (event) => {
|
||||
const registerListener = useCallback(() => {
|
||||
return listen<EventPayload>(ConnectionEvent, (event) => {
|
||||
console.log(
|
||||
`received event ${event.event}, state: ${event.payload.state}`,
|
||||
);
|
||||
switch (event.payload.state) {
|
||||
case 'Connected':
|
||||
dispatch({
|
||||
type: 'set-connected',
|
||||
startTime: event.payload.start_time || dayjs().unix(),
|
||||
});
|
||||
handleError(dispatch, event.payload.error);
|
||||
dispatch({ type: 'change-connection-state', state: 'Connected' });
|
||||
break;
|
||||
case 'Disconnected':
|
||||
dispatch({ type: 'set-disconnected' });
|
||||
handleError(dispatch, event.payload.error);
|
||||
dispatch({ type: 'change-connection-state', state: 'Disconnected' });
|
||||
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 'Unknown':
|
||||
dispatch({ type: 'change-connection-state', state: 'Unknown' });
|
||||
handleError(dispatch, event.payload.error);
|
||||
case 'Error':
|
||||
break;
|
||||
}
|
||||
});
|
||||
}, [dispatch]);
|
||||
|
||||
const registerProgressListener = useCallback(() => {
|
||||
return listen<ProgressEventPayload>(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 unlistenState = registerStateListener();
|
||||
const unlistenProgress = registerProgressListener();
|
||||
const unlisten = registerListener();
|
||||
|
||||
return () => {
|
||||
unlistenState.then((f) => f());
|
||||
unlistenProgress.then((f) => f());
|
||||
unlisten.then((f) => f());
|
||||
};
|
||||
}, [registerStateListener, registerProgressListener]);
|
||||
}, [registerListener]);
|
||||
}
|
||||
|
||||
@@ -1,11 +1,3 @@
|
||||
@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');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
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;
|
||||
}
|
||||
@@ -1,16 +1,14 @@
|
||||
import { Dispatch } from 'react';
|
||||
import { Dayjs } from 'dayjs';
|
||||
import { StateAction } from '../state';
|
||||
import { AppData } from './app-data';
|
||||
|
||||
export type ConnectionState =
|
||||
| 'Connected'
|
||||
| 'Disconnected'
|
||||
| 'Connecting'
|
||||
| 'Disconnecting'
|
||||
| 'Unknown';
|
||||
| 'Error';
|
||||
|
||||
export type VpnMode = 'TwoHop' | 'Mixnet';
|
||||
export type PrivacyMode = 'High' | 'Medium' | 'Low';
|
||||
|
||||
export interface TunnelConfig {
|
||||
id: string;
|
||||
@@ -20,23 +18,12 @@ export interface TunnelConfig {
|
||||
export type AppState = {
|
||||
state: ConnectionState;
|
||||
loading: boolean;
|
||||
error?: string | null;
|
||||
progressMessages: string[];
|
||||
sessionStartDate?: Dayjs | null;
|
||||
vpnMode: VpnMode;
|
||||
privacyMode: PrivacyMode;
|
||||
tunnel: TunnelConfig;
|
||||
uiTheme: 'Light' | 'Dark';
|
||||
localAppData: AppData;
|
||||
};
|
||||
|
||||
export type ConnectionEventPayload = {
|
||||
export type EventPayload = {
|
||||
state: ConnectionState;
|
||||
error?: string | null;
|
||||
start_time?: number | null; // unix timestamp in seconds
|
||||
};
|
||||
|
||||
export type ProgressEventPayload = {
|
||||
message: string;
|
||||
};
|
||||
|
||||
export type StateDispatch = Dispatch<StateAction>;
|
||||
|
||||
@@ -1,4 +1 @@
|
||||
export * from './app-state';
|
||||
export * from './app-data';
|
||||
export * from './tauri-ipc';
|
||||
export * from './routes';
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
import { routes } from '../constants';
|
||||
|
||||
export type Routes = (typeof routes)[keyof typeof routes];
|
||||
@@ -1,6 +0,0 @@
|
||||
export type CmdErrorSource = 'InternalError' | 'CallerError' | 'Unknown';
|
||||
|
||||
export interface CmdError {
|
||||
source: CmdErrorSource;
|
||||
message: string;
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
import React from 'react';
|
||||
import clsx from 'clsx';
|
||||
import { useMainState } from '../contexts';
|
||||
|
||||
export default function ThemeSetter({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
const { uiTheme } = useMainState();
|
||||
|
||||
return (
|
||||
<div className={clsx([uiTheme === 'Dark' && 'dark', 'h-full'])}>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,95 +0,0 @@
|
||||
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<NavLocation>({
|
||||
title: AppName,
|
||||
rightIcon: 'settings',
|
||||
handleRightNav: () => {
|
||||
navigate(routes.settings);
|
||||
},
|
||||
});
|
||||
|
||||
const navBarData = useMemo<NavBarData>(() => {
|
||||
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 (
|
||||
<nav className="flex flex-row flex-nowrap justify-between items-center shrink-0 bg-white text-baltic-sea dark:bg-baltic-sea-jaguar dark:text-mercury-pinkish h-16 text-xl">
|
||||
{currentNavLocation?.leftIcon ? (
|
||||
<button className="w-6 mx-4" onClick={currentNavLocation.handleLeftNav}>
|
||||
<span className="font-icon dark:text-laughing-jack text-2xl">
|
||||
{currentNavLocation.leftIcon}
|
||||
</span>
|
||||
</button>
|
||||
) : (
|
||||
<div className="w-6 mx-4" />
|
||||
)}
|
||||
<p className="justify-self-center">{currentNavLocation.title}</p>
|
||||
{currentNavLocation?.rightIcon ? (
|
||||
<button
|
||||
className="w-6 mx-4"
|
||||
onClick={currentNavLocation.handleRightNav}
|
||||
>
|
||||
<span className="font-icon dark:text-laughing-jack text-2xl">
|
||||
{currentNavLocation.rightIcon}
|
||||
</span>
|
||||
</button>
|
||||
) : (
|
||||
<div className="w-6 mx-4" />
|
||||
)}
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user