Compare commits

..

2 Commits

Author SHA1 Message Date
Bogdan-Ștefan Neacşu 0303dc690e Different crate 2023-11-28 18:59:38 +01:00
Bogdan-Ștefan Neacşu 9f2c425106 Test wg crate 2023-11-28 13:36:37 +01:00
476 changed files with 3010 additions and 10989 deletions
@@ -3,27 +3,8 @@ import fetch from "node-fetch";
import { Octokit } from "@octokit/rest";
import fs from "fs";
import path from "path";
import { execSync } from "child_process";
function getBinInfo(path) {
// let's be super naive about it. add a+x bits on the file and try to run the command
try {
let mode = fs.statSync(path).mode
fs.chmodSync(path, mode | 0o111)
const raw = execSync(`${path} build-info --output=json`, { stdio: 'pipe', encoding: "utf8" });
const parsed = JSON.parse(raw)
return parsed
} catch (_) {
return undefined
}
}
async function run(assets, algorithm, filename, cache) {
if (!cache) {
console.warn("cache is set to 'false', but we we no longer support it")
}
try {
fs.mkdirSync('.tmp');
} catch(e) {
@@ -38,25 +19,26 @@ async function run(assets, algorithm, filename, cache) {
let buffer = null;
let sig = null;
if(cache) {
// cache in `${WORKING_DIR}/.tmp/`
const cacheFilename = path.resolve(`.tmp/${asset.name}`);
if(!fs.existsSync(cacheFilename)) {
console.log(`Downloading ${asset.browser_download_url}... to ${cacheFilename}`);
buffer = Buffer.from(await fetch(asset.browser_download_url).then(res => res.arrayBuffer()));
fs.writeFileSync(cacheFilename, buffer);
} else {
console.log(`Loading from ${cacheFilename}`);
buffer = Buffer.from(fs.readFileSync(cacheFilename));
// cache in `${WORKING_DIR}/.tmp/`
const cacheFilename = path.resolve(`.tmp/${asset.name}`);
if(!fs.existsSync(cacheFilename)) {
console.log(`Downloading ${asset.browser_download_url}... to ${cacheFilename}`);
buffer = Buffer.from(await fetch(asset.browser_download_url).then(res => res.arrayBuffer()));
fs.writeFileSync(cacheFilename, buffer);
// console.log('Reading signature from content');
// if(asset.name.endsWith('.sig')) {
// sig = fs.readFileSync(cacheFilename).toString();
// }
}
} else {
console.log(`Loading from ${cacheFilename}`);
buffer = Buffer.from(fs.readFileSync(cacheFilename));
// console.log('Reading signature from content');
// if(asset.name.endsWith('.sig')) {
// sig = fs.readFileSync(cacheFilename).toString();
// }
// fetch always
buffer = Buffer.from(await fetch(asset.browser_download_url).then(res => res.arrayBuffer()));
}
const binInfo = getBinInfo(cacheFilename)
if(!hashes[asset.name]) {
hashes[asset.name] = {};
}
@@ -117,9 +99,6 @@ async function run(assets, algorithm, filename, cache) {
if(kind) {
hashes[asset.name].kind = kind;
}
if(binInfo) {
hashes[asset.name].details = binInfo;
}
// process Tauri signature files
if(asset.name.endsWith('.sig')) {
@@ -246,8 +225,6 @@ export async function createHashesFromReleaseTagOrNameOrId({ releaseTagOrNameOrI
assets: hashes,
};
console.log(output)
if(upload) {
console.log(`🚚 Uploading ${filename} to release name="${release.name}" id=${release.id} (${release.upload_url})...`);
+12 -13
View File
@@ -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
+16 -12
View File
@@ -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
-16
View File
@@ -4,22 +4,6 @@ Post 1.0.0 release, the changelog format is based on [Keep a Changelog](https://
## [Unreleased]
## [2023.5-rolo] (2023-11-28)
- Gateway won't open websocket listener until embedded Network Requester becomes available ([#4166])
- Feature/gateway described nr ([#4147])
- Bugfix/prerelease versionbump ([#4145])
- returning 'nil' for non-existing origin as opposed to an empty string ([#4135])
- using performance^20 when calculating active set selection weight ([#4126])
- Change default http API timeout from 3s to 10s ([#4117])
[#4166]: https://github.com/nymtech/nym/issues/4166
[#4147]: https://github.com/nymtech/nym/pull/4147
[#4145]: https://github.com/nymtech/nym/pull/4145
[#4135]: https://github.com/nymtech/nym/pull/4135
[#4126]: https://github.com/nymtech/nym/pull/4126
[#4117]: https://github.com/nymtech/nym/pull/4117
## [2023.nyxd-upgrade] (2023-11-22)
- Chore/nyxd 043 upgrade ([#3968])
Generated
+129 -83
View File
@@ -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"
@@ -2306,7 +2340,7 @@ dependencies = [
[[package]]
name = "defguard_wireguard_rs"
version = "0.3.0"
source = "git+https://github.com/neacsu/wireguard-rs.git?rev=c2cd0c1119f699f4bc43f5e6ffd6fc242caa42ed#c2cd0c1119f699f4bc43f5e6ffd6fc242caa42ed"
source = "git+https://github.com/DefGuard/wireguard-rs?rev=d40df5c4e598918253682c42c4aa189d0ec2499a#d40df5c4e598918253682c42c4aa189d0ec2499a"
dependencies = [
"base64 0.21.4",
"libc",
@@ -2914,7 +2948,7 @@ checksum = "0206175f82b8d6bf6652ff7d71a1e27fd2e4efde587fd368662814d6ec1d9ce0"
[[package]]
name = "explorer-api"
version = "1.1.32"
version = "1.1.31"
dependencies = [
"chrono",
"clap 4.4.7",
@@ -4177,6 +4211,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"
@@ -5755,6 +5805,19 @@ dependencies = [
"tokio",
]
[[package]]
name = "netlink-request"
version = "1.6.0"
dependencies = [
"netlink-packet-core 0.7.0",
"netlink-packet-generic",
"netlink-packet-route 0.17.1",
"netlink-packet-utils",
"netlink-sys",
"nix 0.25.1",
"once_cell",
]
[[package]]
name = "netlink-sys"
version = "0.8.5"
@@ -5780,6 +5843,20 @@ 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",
"memoffset 0.6.5",
"pin-utils",
]
[[package]]
name = "nix"
version = "0.27.1"
@@ -5914,7 +5991,7 @@ dependencies = [
[[package]]
name = "nym-api"
version = "1.1.34"
version = "1.1.33"
dependencies = [
"actix-web",
"anyhow",
@@ -6064,7 +6141,7 @@ dependencies = [
[[package]]
name = "nym-cli"
version = "1.1.33"
version = "1.1.32"
dependencies = [
"anyhow",
"base64 0.13.1",
@@ -6137,7 +6214,7 @@ dependencies = [
[[package]]
name = "nym-client"
version = "1.1.32"
version = "1.1.31"
dependencies = [
"clap 4.4.7",
"dirs 4.0.0",
@@ -6481,7 +6558,7 @@ dependencies = [
[[package]]
name = "nym-gateway"
version = "1.1.32"
version = "1.1.31"
dependencies = [
"anyhow",
"async-trait",
@@ -6618,9 +6695,7 @@ dependencies = [
"bincode",
"bytes",
"nym-sphinx",
"rand 0.8.5",
"serde",
"thiserror",
]
[[package]]
@@ -6645,14 +6720,12 @@ dependencies = [
"nym-tun",
"nym-wireguard",
"nym-wireguard-types",
"rand 0.8.5",
"reqwest",
"serde",
"serde_json",
"tap",
"thiserror",
"tokio",
"tokio-tun",
"url",
]
@@ -6691,7 +6764,7 @@ dependencies = [
[[package]]
name = "nym-mixnode"
version = "1.1.34"
version = "1.1.33"
dependencies = [
"anyhow",
"axum",
@@ -6811,7 +6884,7 @@ dependencies = [
[[package]]
name = "nym-network-requester"
version = "1.1.32"
version = "1.1.31"
dependencies = [
"anyhow",
"async-file-watcher",
@@ -6859,7 +6932,7 @@ dependencies = [
[[package]]
name = "nym-network-statistics"
version = "1.1.32"
version = "1.1.31"
dependencies = [
"dirs 4.0.0",
"log",
@@ -7104,7 +7177,7 @@ dependencies = [
[[package]]
name = "nym-socks5-client"
version = "1.1.32"
version = "1.1.31"
dependencies = [
"clap 4.4.7",
"lazy_static",
@@ -7565,15 +7638,29 @@ 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",
"wireguard-control",
]
[[package]]
@@ -7581,8 +7668,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,40 +7681,11 @@ dependencies = [
"serde_json",
"sha2 0.10.8",
"thiserror",
"tokio",
"utoipa",
"x25519-dalek 2.0.0",
]
[[package]]
name = "nymvisor"
version = "0.1.0"
dependencies = [
"anyhow",
"async-file-watcher",
"bytes",
"clap 4.4.7",
"dotenvy",
"flate2",
"futures",
"hex",
"humantime 2.1.0",
"humantime-serde",
"nix 0.27.1",
"nym-bin-common",
"nym-config",
"nym-task",
"reqwest",
"serde",
"serde_json",
"sha2 0.10.8",
"tar",
"thiserror",
"time",
"tokio",
"tracing",
"url",
]
[[package]]
name = "object"
version = "0.32.1"
@@ -9024,12 +9086,10 @@ dependencies = [
"tokio-native-tls",
"tokio-rustls 0.24.1",
"tokio-socks",
"tokio-util",
"tower-service",
"url",
"wasm-bindgen",
"wasm-bindgen-futures",
"wasm-streams",
"web-sys",
"winreg",
]
@@ -10615,17 +10675,6 @@ version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369"
[[package]]
name = "tar"
version = "0.4.40"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b16afcea1f22891c49a00c751c7b63b2233284064f11a200fc624137c51e2ddb"
dependencies = [
"filetime",
"libc",
"xattr",
]
[[package]]
name = "tempfile"
version = "3.8.0"
@@ -10988,9 +11037,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",
@@ -11990,19 +12039,6 @@ dependencies = [
"wasm-utils",
]
[[package]]
name = "wasm-streams"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4609d447824375f43e1ffbc051b50ad8f4b3ae8219680c94452ea05eb240ac7"
dependencies = [
"futures-util",
"js-sys",
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
]
[[package]]
name = "wasm-timer"
version = "0.2.5"
@@ -12537,6 +12573,25 @@ dependencies = [
"windows-sys 0.48.0",
]
[[package]]
name = "wireguard-control"
version = "1.6.0"
dependencies = [
"base64 0.13.1",
"hex",
"libc",
"log",
"netlink-packet-core 0.7.0",
"netlink-packet-generic",
"netlink-packet-route 0.17.1",
"netlink-packet-utils",
"netlink-packet-wireguard",
"netlink-request",
"netlink-sys",
"rand_core 0.6.4",
"x25519-dalek 2.0.0",
]
[[package]]
name = "with_builtin_macros"
version = "0.0.3"
@@ -12627,15 +12682,6 @@ dependencies = [
"time",
]
[[package]]
name = "xattr"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f4686009f71ff3e5c4dbcf1a282d0a44db3f021ba69350cd42086b3e5f1c6985"
dependencies = [
"libc",
]
[[package]]
name = "yamux"
version = "0.10.2"
+1 -3
View File
@@ -105,7 +105,6 @@ members = [
"tools/internal/sdk-version-bump",
"tools/nym-cli",
"tools/nym-nr-query",
"tools/nymvisor",
"tools/ts-rs-cli",
"wasm/client",
# "wasm/full-nym-wasm",
@@ -121,7 +120,6 @@ default-members = [
"service-providers/network-statistics",
"mixnode",
"nym-api",
"tools/nymvisor",
"explorer-api",
]
@@ -141,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"
@@ -160,7 +159,6 @@ schemars = "0.8.1"
serde = "1.0.152"
serde_json = "1.0.91"
tap = "1.0.1"
time = "0.3.30"
thiserror = "1.0.48"
tokio = "1.24.1"
tokio-tungstenite = "0.20.1"
-439
View File
@@ -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.
-675
View File
@@ -1,675 +0,0 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means tocopy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "nym-client"
version = "1.1.32"
version = "1.1.31"
authors = ["Dave Hrycyszyn <futurechimp@users.noreply.github.com>", "Jędrzej Stuczyński <andrew@nymtech.net>"]
description = "Implementation of the Nym Client"
edition = "2021"
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "nym-socks5-client"
version = "1.1.32"
version = "1.1.31"
authors = ["Dave Hrycyszyn <futurechimp@users.noreply.github.com>"]
description = "A SOCKS5 localhost proxy that converts incoming messages to Sphinx and sends them to a Nym address"
edition = "2021"
+6 -8
View File
@@ -10,8 +10,6 @@ use std::path::{Path, PathBuf};
use std::time::Duration;
use tokio::time::Instant;
pub use notify::{Error as NotifyError, Result as NotifyResult};
pub type FileWatcherEventSender = mpsc::UnboundedSender<Event>;
pub type FileWatcherEventReceiver = mpsc::UnboundedReceiver<Event>;
@@ -24,7 +22,7 @@ pub struct AsyncFileWatcher {
last_received: HashMap<EventKind, Instant>,
tick_duration: Duration,
inner_rx: mpsc::UnboundedReceiver<NotifyResult<Event>>,
inner_rx: mpsc::UnboundedReceiver<notify::Result<Event>>,
event_sender: FileWatcherEventSender,
}
@@ -32,7 +30,7 @@ impl AsyncFileWatcher {
pub fn new_file_changes_watcher<P: AsRef<Path>>(
path: P,
event_sender: FileWatcherEventSender,
) -> NotifyResult<Self> {
) -> notify::Result<Self> {
Self::new(
path,
event_sender,
@@ -50,7 +48,7 @@ impl AsyncFileWatcher {
event_sender: FileWatcherEventSender,
filters: Option<Vec<EventKind>>,
tick_duration: Option<Duration>,
) -> NotifyResult<Self> {
) -> notify::Result<Self> {
let watcher_config = Config::default();
let (inner_tx, inner_rx) = mpsc::unbounded();
let watcher = RecommendedWatcher::new(
@@ -114,17 +112,17 @@ impl AsyncFileWatcher {
false
}
fn start_watching(&mut self) -> NotifyResult<()> {
fn start_watching(&mut self) -> notify::Result<()> {
self.is_watching = true;
self.watcher.watch(&self.path, RecursiveMode::NonRecursive)
}
fn stop_watching(&mut self) -> NotifyResult<()> {
fn stop_watching(&mut self) -> notify::Result<()> {
self.is_watching = false;
self.watcher.unwatch(&self.path)
}
pub async fn watch(&mut self) -> NotifyResult<()> {
pub async fn watch(&mut self) -> notify::Result<()> {
self.start_watching()?;
while let Some(event) = self.inner_rx.next().await {
+1 -2
View File
@@ -47,9 +47,8 @@ default = []
openapi = ["utoipa"]
output_format = ["serde_json"]
bin_info_schema = ["schemars"]
basic_tracing = ["tracing-subscriber"]
tracing = [
"basic_tracing",
"tracing-subscriber",
"tracing-tree",
"opentelemetry-jaeger",
"tracing-opentelemetry",
@@ -80,7 +80,7 @@ impl BinaryBuildInformation {
}
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[derive(Clone, Debug, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "bin_info_schema", derive(schemars::JsonSchema))]
pub struct BinaryBuildInformationOwned {
-24
View File
@@ -43,30 +43,6 @@ pub fn setup_logging() {
.init();
}
#[cfg(feature = "basic_tracing")]
pub fn setup_tracing_logger() {
let log_builder = tracing_subscriber::fmt()
// Use a more compact, abbreviated log format
.compact()
// Display source code file paths
.with_file(true)
// Display source code line numbers
.with_line_number(true)
// Don't display the event's target (module path)
.with_target(false);
if ::std::env::var("RUST_LOG").is_ok() {
log_builder
.with_env_filter(tracing_subscriber::filter::EnvFilter::from_default_env())
.init()
} else {
// default to 'Info
log_builder
.with_max_level(tracing_subscriber::filter::LevelFilter::INFO)
.init()
}
}
// TODO: This has to be a macro, running it as a function does not work for the file_appender for some reason
#[cfg(feature = "tracing")]
#[macro_export]
@@ -28,7 +28,6 @@ pub enum InputMessage {
recipient: Recipient,
data: Vec<u8>,
lane: TransmissionLane,
mix_hops: Option<u8>,
},
/// Creates a message used for a duplex anonymous communication where the recipient
@@ -44,7 +43,6 @@ pub enum InputMessage {
data: Vec<u8>,
reply_surbs: u32,
lane: TransmissionLane,
mix_hops: Option<u8>,
},
/// Attempt to use our internally received and stored `ReplySurb` to send the message back
@@ -94,29 +92,6 @@ impl InputMessage {
recipient,
data,
lane,
mix_hops: None,
};
if let Some(packet_type) = packet_type {
InputMessage::new_wrapper(message, packet_type)
} else {
message
}
}
// IMHO `new_regular` should take `mix_hops: Option<u8>` as an argument instead of creating
// this function, but that would potentially break backwards compatibility with the current API
pub fn new_regular_with_custom_hops(
recipient: Recipient,
data: Vec<u8>,
lane: TransmissionLane,
packet_type: Option<PacketType>,
mix_hops: Option<u8>,
) -> Self {
let message = InputMessage::Regular {
recipient,
data,
lane,
mix_hops,
};
if let Some(packet_type) = packet_type {
InputMessage::new_wrapper(message, packet_type)
@@ -137,31 +112,6 @@ impl InputMessage {
data,
reply_surbs,
lane,
mix_hops: None,
};
if let Some(packet_type) = packet_type {
InputMessage::new_wrapper(message, packet_type)
} else {
message
}
}
// IMHO `new_anonymous` should take `mix_hops: Option<u8>` as an argument instead of creating
// this function, but that would potentially break backwards compatibility with the current API
pub fn new_anonymous_with_custom_hops(
recipient: Recipient,
data: Vec<u8>,
reply_surbs: u32,
lane: TransmissionLane,
packet_type: Option<PacketType>,
mix_hops: Option<u8>,
) -> Self {
let message = InputMessage::Anonymous {
recipient,
data,
reply_surbs,
lane,
mix_hops,
};
if let Some(packet_type) = packet_type {
InputMessage::new_wrapper(message, packet_type)
@@ -73,11 +73,10 @@ where
content: Vec<u8>,
lane: TransmissionLane,
packet_type: PacketType,
mix_hops: Option<u8>,
) {
if let Err(err) = self
.message_handler
.try_send_plain_message(recipient, content, lane, packet_type, mix_hops)
.try_send_plain_message(recipient, content, lane, packet_type)
.await
{
warn!("failed to send a plain message - {err}")
@@ -91,18 +90,10 @@ where
reply_surbs: u32,
lane: TransmissionLane,
packet_type: PacketType,
mix_hops: Option<u8>,
) {
if let Err(err) = self
.message_handler
.try_send_message_with_reply_surbs(
recipient,
content,
reply_surbs,
lane,
packet_type,
mix_hops,
)
.try_send_message_with_reply_surbs(recipient, content, reply_surbs, lane, packet_type)
.await
{
warn!("failed to send a repliable message - {err}")
@@ -115,9 +106,8 @@ where
recipient,
data,
lane,
mix_hops,
} => {
self.handle_plain_message(recipient, data, lane, PacketType::Mix, mix_hops)
self.handle_plain_message(recipient, data, lane, PacketType::Mix)
.await
}
InputMessage::Anonymous {
@@ -125,17 +115,9 @@ where
data,
reply_surbs,
lane,
mix_hops,
} => {
self.handle_repliable_message(
recipient,
data,
reply_surbs,
lane,
PacketType::Mix,
mix_hops,
)
.await
self.handle_repliable_message(recipient, data, reply_surbs, lane, PacketType::Mix)
.await
}
InputMessage::Reply {
recipient_tag,
@@ -153,9 +135,8 @@ where
recipient,
data,
lane,
mix_hops,
} => {
self.handle_plain_message(recipient, data, lane, packet_type, mix_hops)
self.handle_plain_message(recipient, data, lane, packet_type)
.await
}
InputMessage::Anonymous {
@@ -163,17 +144,9 @@ where
data,
reply_surbs,
lane,
mix_hops,
} => {
self.handle_repliable_message(
recipient,
data,
reply_surbs,
lane,
packet_type,
mix_hops,
)
.await
self.handle_repliable_message(recipient, data, reply_surbs, lane, packet_type)
.await
}
InputMessage::Reply {
recipient_tag,
@@ -69,7 +69,6 @@ pub(crate) struct PendingAcknowledgement {
message_chunk: Fragment,
delay: SphinxDelay,
destination: PacketDestination,
mix_hops: Option<u8>,
}
impl PendingAcknowledgement {
@@ -78,13 +77,11 @@ impl PendingAcknowledgement {
message_chunk: Fragment,
delay: SphinxDelay,
recipient: Recipient,
mix_hops: Option<u8>,
) -> Self {
PendingAcknowledgement {
message_chunk,
delay,
destination: PacketDestination::KnownRecipient(recipient.into()),
mix_hops,
}
}
@@ -101,9 +98,6 @@ impl PendingAcknowledgement {
recipient_tag,
extra_surb_request,
},
// Messages sent using SURBs are using the number of mix hops set by the recipient when
// they provided the SURBs, so it doesn't make sense to include it here.
mix_hops: None,
}
}
@@ -49,18 +49,12 @@ where
packet_recipient: Recipient,
chunk_data: Fragment,
packet_type: PacketType,
mix_hops: Option<u8>,
) -> Result<PreparedFragment, PreparationError> {
debug!("retransmitting normal packet...");
// TODO: Figure out retransmission packet type signaling
self.message_handler
.try_prepare_single_chunk_for_sending(
packet_recipient,
chunk_data,
packet_type,
mix_hops,
)
.try_prepare_single_chunk_for_sending(packet_recipient, chunk_data, packet_type)
.await
}
@@ -95,7 +89,6 @@ where
**recipient,
timed_out_ack.message_chunk.clone(),
packet_type,
timed_out_ack.mix_hops,
)
.await
}
@@ -418,10 +418,9 @@ where
message: Vec<u8>,
lane: TransmissionLane,
packet_type: PacketType,
mix_hops: Option<u8>,
) -> Result<(), PreparationError> {
let message = NymMessage::new_plain(message);
self.try_split_and_send_non_reply_message(message, recipient, lane, packet_type, mix_hops)
self.try_split_and_send_non_reply_message(message, recipient, lane, packet_type)
.await
}
@@ -431,7 +430,6 @@ where
recipient: Recipient,
lane: TransmissionLane,
packet_type: PacketType,
mix_hops: Option<u8>,
) -> Result<(), PreparationError> {
debug!("Sending non-reply message with packet type {packet_type}");
// TODO: I really dislike existence of this assertion, it implies code has to be re-organised
@@ -463,7 +461,6 @@ where
&self.config.ack_key,
&recipient,
packet_type,
mix_hops,
)?;
let real_message = RealMessage::new(
@@ -471,8 +468,7 @@ where
Some(fragment.fragment_identifier()),
);
let delay = prepared_fragment.total_delay;
let pending_ack =
PendingAcknowledgement::new_known(fragment, delay, recipient, mix_hops);
let pending_ack = PendingAcknowledgement::new_known(fragment, delay, recipient);
real_messages.push(real_message);
pending_acks.push(pending_ack);
@@ -489,7 +485,6 @@ where
recipient: Recipient,
amount: u32,
packet_type: PacketType,
mix_hops: Option<u8>,
) -> Result<(), PreparationError> {
debug!("Sending additional reply SURBs with packet type {packet_type}");
let sender_tag = self.get_or_create_sender_tag(&recipient);
@@ -506,7 +501,6 @@ where
recipient,
TransmissionLane::AdditionalReplySurbs,
packet_type,
mix_hops,
)
.await?;
@@ -523,7 +517,6 @@ where
num_reply_surbs: u32,
lane: TransmissionLane,
packet_type: PacketType,
mix_hops: Option<u8>,
) -> Result<(), SurbWrappedPreparationError> {
debug!("Sending message with reply SURBs with packet type {packet_type}");
let sender_tag = self.get_or_create_sender_tag(&recipient);
@@ -534,7 +527,7 @@ where
let message =
NymMessage::new_repliable(RepliableMessage::new_data(message, sender_tag, reply_surbs));
self.try_split_and_send_non_reply_message(message, recipient, lane, packet_type, mix_hops)
self.try_split_and_send_non_reply_message(message, recipient, lane, packet_type)
.await?;
log::trace!("storing {} reply keys", reply_keys.len());
@@ -548,7 +541,6 @@ where
recipient: Recipient,
chunk: Fragment,
packet_type: PacketType,
mix_hops: Option<u8>,
) -> Result<PreparedFragment, PreparationError> {
debug!("Sending single chunk with packet type {packet_type}");
let topology_permit = self.topology_access.get_read_permit().await;
@@ -562,7 +554,6 @@ where
&self.config.ack_key,
&recipient,
packet_type,
mix_hops,
)
.unwrap();
@@ -516,7 +516,6 @@ where
recipient,
to_send,
nym_sphinx::params::PacketType::Mix,
self.config.reply_surbs.surb_mix_hops,
)
.await
{
-5
View File
@@ -607,10 +607,6 @@ pub struct ReplySurbs {
/// This is going to be superseded by key rotation once implemented.
#[serde(with = "humantime_serde")]
pub maximum_reply_key_age: Duration,
/// Specifies the number of mixnet hops the packet should go through. If not specified, then
/// the default value is used.
pub surb_mix_hops: Option<u8>,
}
impl Default for ReplySurbs {
@@ -626,7 +622,6 @@ impl Default for ReplySurbs {
maximum_reply_surb_drop_waiting_period: DEFAULT_MAXIMUM_REPLY_SURB_DROP_WAITING_PERIOD,
maximum_reply_surb_age: DEFAULT_MAXIMUM_REPLY_SURB_AGE,
maximum_reply_key_age: DEFAULT_MAXIMUM_REPLY_KEY_AGE,
surb_mix_hops: None,
}
}
}
@@ -155,7 +155,6 @@ impl From<ConfigV1_1_30> for Config {
.maximum_reply_surb_drop_waiting_period,
maximum_reply_surb_age: value.debug.reply_surbs.maximum_reply_surb_age,
maximum_reply_key_age: value.debug.reply_surbs.maximum_reply_key_age,
surb_mix_hops: None,
},
},
}
-1
View File
@@ -259,7 +259,6 @@ pub(super) fn get_specified_gateway(
gateways: &[gateway::Node],
must_use_tls: bool,
) -> Result<gateway::Node, ClientCoreError> {
log::debug!("Requesting specified gateway: {}", gateway_identity);
let user_gateway = identity::PublicKey::from_base58_string(gateway_identity)
.map_err(ClientCoreError::UnableToCreatePublicKeyFromGatewayId)?;
+1 -1
View File
@@ -212,7 +212,7 @@ where
D::StorageError: Send + Sync + 'static,
T: DeserializeOwned + Serialize + Send + Sync,
{
log::debug!("Setting up gateway");
log::trace!("Setting up gateway");
match setup {
GatewaySetup::MustLoad => use_loaded_gateway_details(key_store, details_store).await,
GatewaySetup::New {
@@ -792,7 +792,6 @@ pub struct InitOnly;
impl GatewayClient<InitOnly, EphemeralCredentialStorage> {
// for initialisation we do not need credential storage. Though it's still a bit weird we have to set the generic...
pub fn new_init(config: GatewayConfig, local_identity: Arc<identity::KeyPair>) -> Self {
log::trace!("Initialising gateway client");
use futures::channel::mpsc;
// note: this packet_router is completely invalid in normal circumstances, but "works"
@@ -376,11 +376,7 @@ where
})
}
pub async fn simulate<I, M>(
&self,
messages: I,
memo: impl Into<String> + Send + 'static,
) -> Result<SimulateResponse, NyxdError>
pub async fn simulate<I, M>(&self, messages: I) -> Result<SimulateResponse, NyxdError>
where
I: IntoIterator<Item = M> + Send,
M: Msg,
@@ -395,7 +391,7 @@ where
.map_err(|_| {
NyxdError::SerializationError("custom simulate messages".to_owned())
})?,
memo,
"simulating execution of transactions",
)
.await
}
+1 -1
View File
@@ -21,7 +21,7 @@ rand = {version = "0.6", features = ["std"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = { workspace = true }
thiserror = { workspace = true }
time = { workspace = true, features = ["parsing", "formatting"] }
time = { version = "0.3.6", features = ["parsing", "formatting"] }
toml = "0.5.6"
url = { workspace = true }
tap = "1"
+5 -11
View File
@@ -4,7 +4,7 @@
use handlebars::{Handlebars, TemplateRenderError};
use serde::de::DeserializeOwned;
use serde::Serialize;
use std::fs::{create_dir_all, File};
use std::fs::File;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::{fs, io};
@@ -72,22 +72,16 @@ where
C: NymConfigTemplate,
P: AsRef<Path>,
{
let path = path.as_ref();
log::debug!("trying to save config file to {}", path.display());
log::debug!("trying to save config file to {}", path.as_ref().display());
let file = File::create(path.as_ref())?;
if let Some(parent) = path.parent() {
create_dir_all(parent)?;
}
let file = File::create(path)?;
// TODO: check for whether any of our configs store anything sensitive
// TODO: check for whether any of our configs stores anything sensitive
// and change that to 0o644 instead
#[cfg(target_family = "unix")]
{
use std::os::unix::fs::PermissionsExt;
let mut perms = fs::metadata(path)?.permissions();
let mut perms = fs::metadata(path.as_ref())?.permissions();
perms.set_mode(0o600);
fs::set_permissions(path, perms)?;
}
@@ -3,7 +3,6 @@
use cosmwasm_schema::cw_serde;
use cosmwasm_std::Decimal;
use cosmwasm_std::OverflowError;
use cosmwasm_std::Uint128;
use serde::de::Error;
use serde::{Deserialize, Deserializer};
@@ -72,10 +71,6 @@ impl Percent {
// we know the cast from u128 to u8 is a safe one since the internal value must be within 0 - 1 range
truncate_decimal(hundred * self.0).u128() as u8
}
pub fn checked_pow(&self, exp: u32) -> Result<Self, OverflowError> {
self.0.checked_pow(exp).map(Percent)
}
}
impl Display for Percent {
@@ -25,12 +25,12 @@ humantime-serde = "1.1.1"
# TO CHECK WHETHER STILL NEEDED:
log = { workspace = true }
time = { workspace = true, features = ["parsing", "formatting"] }
time = { version = "0.3.6", features = ["parsing", "formatting"] }
ts-rs = { workspace = true, optional = true }
[dev-dependencies]
rand_chacha = "0.3"
time = { workspace = true, features = ["serde", "macros"] }
time = { version = "0.3.5", features = ["serde", "macros"] }
[features]
default = []
+25 -5
View File
@@ -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, &params, &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, &params, &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, &params, &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, &params, &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, &params, &mut rng)))
-2
View File
@@ -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 }
+16 -359
View File
@@ -1,318 +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,
// The nym-address the response should be sent back to
pub reply_to: Recipient,
// The number of mix node hops that responses should take, in addition to the entry and exit
// node. Zero means only client -> entry -> exit -> client.
pub reply_to_hops: Option<u8>,
// The average delay at each mix node, in milliseconds. Currently this is not supported by the
// ip packet router.
pub reply_to_avg_mix_delays: Option<f64>,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct DynamicConnectRequest {
pub request_id: u64,
// The nym-address the response should be sent back to
pub reply_to: Recipient,
// The number of mix node hops that responses should take, in addition to the entry and exit
// node. Zero means only client -> entry -> exit -> client.
pub reply_to_hops: Option<u8>,
// The average delay at each mix node, in milliseconds. Currently this is not supported by the
// ip packet router.
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 {
@@ -321,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]),
})
);
}
}
-1
View File
@@ -258,7 +258,6 @@ where
&address,
&address,
PacketType::Mix,
None,
)?)
}
+5 -27
View File
@@ -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(&params);
// The prepare blind sign is performed by the user
let (pedersen_commitments_openings, blind_sign_request) =
prepare_blind_sign(&params, &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(
&params,
&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
-1
View File
@@ -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;
+2 -173
View File
@@ -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(&params, &private_attributes, &public_attributes).unwrap();
let validator_keypair = keygen(&params);
let blind_sig = blind_sign(
&params,
&validator_keypair.secret_key(),
&request,
&public_attributes,
)
.unwrap();
assert!(verify_partial_blind_signature(
&params,
&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(&params, &private_attributes, &[]).unwrap();
let validator_keypair = keygen(&params);
let blind_sig =
blind_sign(&params, &validator_keypair.secret_key(), &request, &[]).unwrap();
assert!(verify_partial_blind_signature(
&params,
&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(&params, &private_attributes, &public_attributes).unwrap();
let validator_keypair = keygen(&params);
let validator2_keypair = keygen(&params);
let blind_sig = blind_sign(
&params,
&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(
&params,
&request,
&public_attributes,
&blind_sig,
&validator2_keypair.verification_key()
),);
}
}
+1 -6
View File
@@ -181,7 +181,6 @@ pub trait FragmentPreparer {
/// - compute vk_b = g^x || v_b
/// - compute sphinx_plaintext = SURB_ACK || g^x || v_b
/// - compute sphinx_packet = Sphinx(recipient, sphinx_plaintext)
#[allow(clippy::too_many_arguments)]
fn prepare_chunk_for_sending(
&mut self,
fragment: Fragment,
@@ -190,7 +189,6 @@ pub trait FragmentPreparer {
packet_sender: &Recipient,
packet_recipient: &Recipient,
packet_type: PacketType,
mix_hops: Option<u8>,
) -> Result<PreparedFragment, NymTopologyError> {
// each plain or repliable packet (i.e. not a reply) attaches an ephemeral public key so that the recipient
// could perform diffie-hellman with its own keys followed by a kdf to re-derive
@@ -228,8 +226,7 @@ pub trait FragmentPreparer {
};
// generate pseudorandom route for the packet
let hops = mix_hops.unwrap_or(self.num_mix_hops());
log::trace!("Preparing chunk for sending with {} mix hops", hops);
let hops = self.num_mix_hops();
let route =
topology.random_route_to_gateway(self.rng(), hops, packet_recipient.gateway())?;
let destination = packet_recipient.as_sphinx_destination();
@@ -392,7 +389,6 @@ where
ack_key: &AckKey,
packet_recipient: &Recipient,
packet_type: PacketType,
mix_hops: Option<u8>,
) -> Result<PreparedFragment, NymTopologyError> {
let sender = self.sender_address;
@@ -404,7 +400,6 @@ where
&sender,
packet_recipient,
packet_type,
mix_hops,
)
}
-4
View File
@@ -169,10 +169,6 @@ pub struct SphinxMessageReceiver {
impl SphinxMessageReceiver {
/// Allows setting non-default number of expected mix hops in the network.
// IMPORTANT NOTE: this is among others used to deserialize SURBs. Meaning that this is a
// global setting and currently always set to the default value. The implication is that it is
// not currently possible to have different number of hops for different SURB messages. So,
// don't try to use <3 mix hops for SURBs until this is refactored.
#[must_use]
pub fn with_mix_hops(mut self, hops: u8) -> Self {
self.num_mix_hops = hops;
+3 -6
View File
@@ -494,15 +494,12 @@ impl Drop for TaskClient {
fn drop(&mut self) {
if !self.mode.should_signal_on_drop() {
self.log(
Level::Debug,
"the task client is getting dropped: this is expected during client shutdown",
Level::Trace,
"the task client is getting dropped (but instructed to not signal)",
);
return;
} else {
self.log(
Level::Info,
"the task client is getting dropped: this is expected during client shutdown",
);
self.log(Level::Debug, "the task client is getting dropped");
}
if !self.is_shutdown_poll() {
+1
View File
@@ -1,6 +1,7 @@
use crate::{manager::SentError, TaskManager};
#[cfg(unix)]
#[deprecated]
pub async fn wait_for_signal() {
use tokio::signal::unix::{signal, SignalKind};
let mut sigterm = signal(SignalKind::terminate()).expect("Failed to setup SIGTERM channel");
+4 -1
View File
@@ -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"]
+64 -30
View File
@@ -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}");
}
}
}
+5 -10
View File
@@ -77,7 +77,7 @@ impl GatewayBond {
}
}
#[derive(Debug, Serialize, Deserialize)]
#[derive(Serialize, Deserialize)]
pub struct GatewayNodeDetailsResponse {
pub identity_key: String,
pub sphinx_key: String,
@@ -88,7 +88,6 @@ pub struct GatewayNodeDetailsResponse {
pub data_store: String,
pub network_requester: Option<GatewayNetworkRequesterDetails>,
pub ip_packet_router: Option<GatewayIpPacketRouterDetails>,
}
impl fmt::Display for GatewayNodeDetailsResponse {
@@ -99,7 +98,7 @@ impl fmt::Display for GatewayNodeDetailsResponse {
writeln!(f, "bind address: {}", self.bind_address)?;
writeln!(
f,
"mix port: {}, clients port: {}",
"mix Port: {}, clients port: {}",
self.mix_port, self.clients_port
)?;
@@ -108,15 +107,11 @@ impl fmt::Display for GatewayNodeDetailsResponse {
if let Some(nr) = &self.network_requester {
nr.fmt(f)?;
}
if let Some(ipr) = &self.ip_packet_router {
ipr.fmt(f)?;
}
Ok(())
}
}
#[derive(Debug, Serialize, Deserialize)]
#[derive(Serialize, Deserialize)]
pub struct GatewayNetworkRequesterDetails {
pub enabled: bool,
@@ -154,7 +149,7 @@ impl fmt::Display for GatewayNetworkRequesterDetails {
}
}
#[derive(Debug, Serialize, Deserialize)]
#[derive(Serialize, Deserialize)]
pub struct GatewayIpPacketRouterDetails {
pub enabled: bool,
@@ -169,7 +164,7 @@ pub struct GatewayIpPacketRouterDetails {
impl fmt::Display for GatewayIpPacketRouterDetails {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!(f, "ip packet router:")?;
writeln!(f, "IP packet router:")?;
writeln!(f, "\tenabled: {}", self.enabled)?;
writeln!(f, "\tconfig path: {}", self.config_path)?;
@@ -434,10 +434,6 @@ pub struct ReplySurbsWasm {
/// Defines maximum amount of time given reply key is going to be valid for.
/// This is going to be superseded by key rotation once implemented.
pub maximum_reply_key_age_ms: u32,
/// Defines how many mix nodes the reply surb should go through.
/// If not set, the default value is going to be used.
pub surb_mix_hops: Option<u8>,
}
impl Default for ReplySurbsWasm {
@@ -467,7 +463,6 @@ impl From<ReplySurbsWasm> for ConfigReplySurbs {
maximum_reply_key_age: Duration::from_millis(
reply_surbs.maximum_reply_key_age_ms as u64,
),
surb_mix_hops: reply_surbs.surb_mix_hops,
}
}
}
@@ -489,7 +484,6 @@ impl From<ConfigReplySurbs> for ReplySurbsWasm {
.as_millis() as u32,
maximum_reply_surb_age_ms: reply_surbs.maximum_reply_surb_age.as_millis() as u32,
maximum_reply_key_age_ms: reply_surbs.maximum_reply_key_age.as_millis() as u32,
surb_mix_hops: reply_surbs.surb_mix_hops,
}
}
}
@@ -303,9 +303,6 @@ pub struct ReplySurbsWasmOverride {
/// This is going to be superseded by key rotation once implemented.
#[tsify(optional)]
pub maximum_reply_key_age_ms: Option<u32>,
#[tsify(optional)]
pub surb_mix_hops: Option<u8>,
}
impl From<ReplySurbsWasmOverride> for ReplySurbsWasm {
@@ -340,7 +337,6 @@ impl From<ReplySurbsWasmOverride> for ReplySurbsWasm {
maximum_reply_key_age_ms: value
.maximum_reply_key_age_ms
.unwrap_or(def.maximum_reply_key_age_ms),
surb_mix_hops: value.surb_mix_hops,
}
}
}
+11 -1
View File
@@ -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"
+2
View File
@@ -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;
+11 -5
View File
@@ -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)))
}
}
+4 -4
View File
@@ -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)
}
}
+20 -2
View File
@@ -11,15 +11,33 @@ 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"
#defguard_wireguard_rs = { git = "https://github.com/DefGuard/wireguard-rs", rev = "d40df5c4e598918253682c42c4aa189d0ec2499a" }
wireguard-control = { path = "../../../innernet/wireguard-control" }
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"
+9
View File
@@ -0,0 +1,9 @@
use thiserror::Error;
#[derive(Error, Debug)]
pub enum WgError {
#[error("unable to get tunnel")]
UnableToGetTunnel,
#[error("handshake failed")]
HandshakeFailed,
}
+25 -36
View File
@@ -3,55 +3,44 @@
// #![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;
use nym_network_defaults::{WG_PORT, WG_TUN_DEVICE_ADDRESS};
use nym_tun::tun_task_channel;
use setup::PRIVATE_KEY;
use wireguard_control::{Backend, Device, DeviceUpdate, Key, KeyPair, PeerConfigBuilder};
/// Start wireguard device
#[cfg(target_os = "linux")]
/// Start wireguard device
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![],
};
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()])?;
) -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
let peer = std::env::var("NYM_PEER_PUBLIC_KEY").expect("NYM_PEER_PUBLIC_KEY must be set");
let peer = PeerConfigBuilder::new(&Key::from_base64(&peer).unwrap())
.add_allowed_ip("10.1.0.2".parse()?, 32);
DeviceUpdate::new()
.set_keypair(KeyPair::from_private(
Key::from_base64(PRIVATE_KEY).unwrap(),
))
.set_listen_port(WG_PORT)
.add_peer(peer)
.apply(&"wg0".parse().unwrap(), Backend::Kernel)
.unwrap();
tokio::spawn(async move { task_client.recv().await });
Ok(wgapi)
}
#[cfg(not(target_os = "linux"))]
pub async fn start_wireguard(
_task_client: nym_task::TaskClient,
_gateway_client_registry: Arc<GatewayClientRegistry>,
) -> Result<WGApi, Box<dyn std::error::Error + Send + Sync + 'static>> {
todo!("WireGuard is currently only supported on Linux")
Ok(())
}
+74
View File
@@ -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 });
}
}
+61
View File
@@ -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)
}
}
+7 -6
View File
@@ -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
@@ -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()
}
+281
View File
@@ -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(&registered_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)
}
+351
View File
@@ -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)
}
+10 -27
View File
@@ -551,15 +551,6 @@ dependencies = [
"zeroize",
]
[[package]]
name = "deranged"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0f32d04922c60427da6f9fef14d042d9edddef64cb9d4ce0d64d0685fbeb1fd3"
dependencies = [
"powerfmt",
]
[[package]]
name = "derivative"
version = "2.2.0"
@@ -1567,12 +1558,6 @@ version = "0.3.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ac9a59f73473f1b8d852421e59e64809f025994837ef743615c6d0c5b305160"
[[package]]
name = "powerfmt"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"
[[package]]
name = "ppv-lite86"
version = "0.2.17"
@@ -1885,9 +1870,9 @@ checksum = "bebd363326d05ec3e2f532ab7660680f3b02130d780c299bca73469d521bc0ed"
[[package]]
name = "serde"
version = "1.0.190"
version = "1.0.160"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "91d3c334ca1ee894a2c6f6ad698fe8c435b76d504b13d436f0685d648d6d96f7"
checksum = "bb2f3770c8bce3bcda7e149193a069a0f4365bda1fa5cd88e03bca26afc1216c"
dependencies = [
"serde_derive",
]
@@ -1903,9 +1888,9 @@ dependencies = [
[[package]]
name = "serde_derive"
version = "1.0.190"
version = "1.0.160"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67c5609f394e5c2bd7fc51efda478004ea80ef42fee983d5c67a65e34f32c0e3"
checksum = "291a097c63d8497e00160b166a967a4a79c64f3facdd01cbd7502231688d77df"
dependencies = [
"proc-macro2",
"quote",
@@ -2100,13 +2085,11 @@ dependencies = [
[[package]]
name = "time"
version = "0.3.30"
version = "0.3.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c4a34ab300f2dee6e562c10a046fc05e358b29f9bf92277f30c3c8d82275f6f5"
checksum = "cd0cbfecb4d19b5ea75bb31ad904eb5b9fa13f21079c3b92017ebdf4999a5890"
dependencies = [
"deranged",
"itoa",
"powerfmt",
"serde",
"time-core",
"time-macros",
@@ -2114,15 +2097,15 @@ dependencies = [
[[package]]
name = "time-core"
version = "0.1.2"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ef927ca75afb808a4d64dd374f00a2adf8d0fcff8e7b184af886c3c87ec4a3f3"
checksum = "2e153e1f1acaef8acc537e68b44906d2db6436e2b35ac2c6b42640fff91f00fd"
[[package]]
name = "time-macros"
version = "0.2.15"
version = "0.2.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ad70d68dba9e1f8aceda7aa6711965dfec1cac869f311a51bd08b3a2ccbce20"
checksum = "fd80a657e71da814b8e5d60d3374fc6d35045062245d80224748ae522dd76f36"
dependencies = [
"time-core",
]
+4 -85
View File
@@ -10,22 +10,19 @@ use crate::dealings::transactions::try_commit_dealings;
use crate::epoch_state::queries::{
query_current_epoch, query_current_epoch_threshold, query_initial_dealers,
};
use crate::epoch_state::storage::{CURRENT_EPOCH, THRESHOLD};
use crate::epoch_state::storage::CURRENT_EPOCH;
use crate::epoch_state::transactions::{advance_epoch_state, try_surpassed_threshold};
use crate::error::ContractError;
use crate::state::{State, MULTISIG, STATE};
use crate::verification_key_shares::queries::query_vk_shares_paged;
use crate::verification_key_shares::storage::vk_shares;
use crate::verification_key_shares::transactions::try_commit_verification_key_share;
use crate::verification_key_shares::transactions::try_verify_verification_key_share;
use cosmwasm_std::{
entry_point, to_binary, Addr, Deps, DepsMut, Env, MessageInfo, QueryResponse, Response,
Timestamp,
entry_point, to_binary, Deps, DepsMut, Env, MessageInfo, QueryResponse, Response,
};
use cw4::Cw4Contract;
use nym_coconut_dkg_common::msg::{ExecuteMsg, InstantiateMsg, MigrateMsg, QueryMsg};
use nym_coconut_dkg_common::types::{Epoch, EpochId, EpochState, TimeConfiguration};
use nym_coconut_dkg_common::verification_key::ContractVKShare;
use nym_coconut_dkg_common::types::{Epoch, EpochState};
/// Instantiate the contract.
///
@@ -130,85 +127,7 @@ pub fn query(deps: Deps<'_>, _env: Env, msg: QueryMsg) -> Result<QueryResponse,
}
#[entry_point]
pub fn migrate(deps: DepsMut<'_>, env: Env, _msg: MigrateMsg) -> Result<Response, ContractError> {
CURRENT_EPOCH.save(
deps.storage,
&Epoch {
state: EpochState::InProgress,
epoch_id: 0,
time_configuration: TimeConfiguration {
public_key_submission_time_secs: 999999,
dealing_exchange_time_secs: 999999,
verification_key_submission_time_secs: 999999,
verification_key_validation_time_secs: 999999,
verification_key_finalization_time_secs: 999999,
in_progress_time_secs: 999999,
},
finish_timestamp: env.block.time.plus_days(10000),
},
)?;
let apis = [
"https://qa-nym-api-coconut1.qa.nymte.ch/api",
"https://qa-nym-api-coconut2.qa.nymte.ch/api",
"https://qa-nym-api-coconut3.qa.nymte.ch/api",
"https://qa-nym-api-coconut-6.qa.nymte.ch/api",
"https://qa-nym-api-coconut-7.qa.nymte.ch/api",
"https://qa-nym-api-coconut-8.qa.nymte.ch/api",
"https://qa-nym-api-coconut-9.qa.nymte.ch/api",
"https://qa-nym-api-coconut-10.qa.nymte.ch/api",
"https://qa-nym-api-coconut-11.qa.nymte.ch/api",
"https://qa-nym-api-coconut-12.qa.nymte.ch/api",
];
let addresses = [
Addr::unchecked("n1e6wkf0x2l4qt45uwkft9t7fs3ka02rsmft5jjn"),
Addr::unchecked("n190f6rwtcpfgx3y84af6eapg54suehd4nzq4sh3"),
Addr::unchecked("n1c7nu7wncuru09eg2m8429d5ff6umytet993xmf"),
Addr::unchecked("n144fypmxc9jrdk28qrjlptpqn7h077f30vvvdjf"),
Addr::unchecked("n15rmhp3psrnlcgp8tsa9y528ppwt0vvwuazfa4a"),
Addr::unchecked("n18dy35dtsg7ycyp7g9pvlj29ksmjpu9h6tznxdl"),
Addr::unchecked("n17usrtqe6ypvn3r4v05sspu3ufs30uykc7euwne"),
Addr::unchecked("n1efpvtu5x7x4v293pc42a2fwkf265lnh05r023z"),
Addr::unchecked("n15k2zadxm7m3wyfyx7g2uk2tctmmp43syxuqmdf"),
Addr::unchecked("n1k4w8pp62htn0tdmrsv3gh9kzrap4tpalw8eqd7"),
];
let keys = [
"ANFuTGQ2AVgbgaUCuYW7QZS8heTZjvJgPY8Xw3ekYRFsAq9uWJmSPctB7Qp5XCHsVk4yLF9CHr5YypWMy47kiMR8nrwVjS6Du2Ek2kCpjZTYEqMFfQqgS3YgYKrN2BYwgko2T9tx3SgCgeN7w7aWpypYPRNVDcVJ17GetAor4NGiKBSBboT4Y2WPLoDhqAmjwpeoSHTip2T3Wt9mQAcUv88my4cM8UwSEcF7P69h5nRaFxZ5ZGdofrcju9CrM2yjher5av25idSwFrfHWaqqP1dJcK4XbuSLczVvYYMaUkBsMD4w9fcdCkLeDu3sd3yv8doBiYXzWSve5QKvYKTqELbebuqimVnL7YkXPuksb482hUh5HVMsfW2Mw4jigSG1p42XsYpuLVEpKB7479Dn4pG4yL9iATkycg6myA6yQKVA42ztbtoqg3cbkLDZG1LFm4rLpWoc6BqkucRKPNRZx4xn8ZzXfuQqso11h1DLurDuWSrCVcxmSYQ5zCMGmEeeKpBLvVsmopptHr4dVrQLeG5RZqWhXEviGjHMLBYwRS6ffZVeB4yPATXroPtXTCgiYj9PpXhfTkeDkQLiEAWBXb7xPioXhcGBBfCs7JSSRGKdQFQHwCQpCFdTsmsAmurwqrmu8TnrSh6simDfUDSukWhxY5R5Q8oN2x9w8QoGiUgdiAuP68LvvdXPEuSMzdVXGZKGv5p9k5LsqRiU4MnmjGdGQjfThZzZz9zZKZJC8GEHVmRapz2StkFTFGqk3MxEZmw9G2PYKyQiMkkGcSx27opRJuKgrVY5u7yKcUnaW7u5AKXNoEYSUQwhzsHzuxL3GpCEqT7WpbBfT1NBuL2nshV69wCCGXdB4Jc7d3sa7vRfNRGtcP3guRwtkJyRehJkUYXApG1HKwNkLnVXYCbey9MqyckB3ZVG3",
"ARAqwgaJv5nqGVjHymhMM1UUZj8YdWYDjUTNepBJefRfTyaHAsHs2yyazEGV4r4cYt5cXQgFVPQxFYAodPLfWcjXYZ72QVdrNrwQWju2kpeManXUrTQpNouyvc5XNhPN7ZiV4cTfPqowj7QtZC83AJhwVX7FkdQD5YzyZijB5FuvP96hG8CttidBq19ChUEDpVxN6zas3yBAs2R1kFcXBnK2mpXRYUj6Tx3LfV6FgDi8KU6upaggwyqmCsN4KYW3DPZsXy33kDx6T15fc3SfM7HWcyz3WS4c6uuCZtBYPZHz1TbJJQhxx22iS581oqj1yUVQqyKYyeRFh88XXS7oeMejBCnmqj99HuBQquwCRbViDbQoR74sPCWviFREQjLPHQK4jrKUsJNCyedSfo9es5ANA7pNDFokEfbg4RwoibZtk1nSMy9PwLjVsGMnBSzdNDTSzMVKtmdGgFEWQHLa8vhMpJvEW2tAbYq1inJwYYGTT1zgZGiMCNrcHh93j1YvXMdRKeScaWBKqMZ6TB24349CcdU34Uh4grYMnHchfzm66fYqC4FrzdPs8KuyQ2qrpCE3aGkFPrngzMbtkPJTAAsujeRnGm5U88PTEP9e9axa8zus2ab9RArhXA6jVHYo7b8rBACfYFfQwQRVeZd6NnPHbzdRh5KpM6YjKV9jx6LmsRQtWUbfokFUbPhHDsftuYxB7p3GJdnPABqkTZPLuuEBgs62dK2BD4r1PSQsSiLeSeR6CPdEPJ8hibRU5FV9qmvnivVjZdbnfEb8DuAnPADxUvfstsp4NFwjPj6DpGo7TASzYNitSuoXffwpTKNcQYDLygPFbzoymrzBLjKrMNj7cY9Y8DGBAXQ8CHNcrbzsZi56KXYyk4LBBEeGKuL9s6bU9K6UpXgSbFQMDHAodVPdHaXGi6aUv",
"9kCmPfjfAXZyES7T8m4PQ1RXEowa7raooGcyPUCYxCCMo798ZdRvj9mdmX9PVgZWttbsWUDgywDA5uC1WqJLPVDmbuwowZ8pP3QTkM4bBwThBvY4Ureoq3Zw5QZhJCwsH7oRpYU1TXd8eAuv4a8oALZCiNPLPB1CYpxFxxB2Hxs4DxKVaSfMqvKLu8n11K1GRFpAYjFAEuDrgTQA63n8QwDdKuYrxcbQcbuiYsnsocheVLUcmZdKdXPACZXd8yufq4qcwdGqokVmQSxUMwEFVCu49skYnrvuTckSefTHFApTT7RqpzczcCADtyPAfYu3FBgxCNMUJ9EgZGLMp24LiLBPY4BNSb98Cu7frhWueefhFicLVBbUnLuBQ9oDh9dRqit944NLg1Vfj53yBEkoqZxH5NTd6sUJztS14ieJzLhkfpbJ7a6C4EaXA2hx4ziHipPFENNPg9vvq1q1rDSN336CwYrsKQhoPaSJs7apPWJfRLHw3vqJLhkHExDBGgGzh5vfCw7qvxxcC8f7FjpWNiQxcNzcqSCgNrsbiRBhqxiYjJixN1C5uMkYm2JcfyufgnRA8MzXPfPTNQMMY2dYAw5WfVhAc4VNRiSdPF5dCcP8H4ejg5q9KZgChgrTSHVWxNa7HfRSFSXoFeh1VJVAMyL1p1tNmW2ax2Cjhiq5r1wWXAaCYTgtrLxuTyZCUuNtzz5ZXjgynJsRyuLmRypTV1ior1AeLQsvU4DqfD8dLW3QeurZfxSzEkoKPknQeM4BAyDnA3iDsVsAUh2KCq3UZJanaJB8EWvirxK7K4E1CWTWNR4966gsCgoexvRaT7SFZTy6vVn3joCkpm7NUFgSW3dN8CV4iijpkMehhP822btLPXV21chUT8mStc6gbrnF2kzJJeGkcWFpAUqtpUBFTM7EKZSuzdddf",
"AVmJTFnQNqiMV8Fe3WNvUdRK6E285aKrhD2VjvH3SzRr8oQyzZsuZCAdeQXiiZAp8rcjWCQqDZoevVcP1V68Y2TFC61bCkJoVTvRzK26ij9GhX43sNLx1gdGvPUPVgNfnF1A9z94m2WevRm8wkq7tPyVtx2izhrSKyoc7sPSh57rX5oSwYRBALnmBjZVUjESTV32nEgFgDUH1UX3sh2LB2fAh91DDqcWC8oGJzwURfuU2jSkXmVr1BfXgRxeu6AX8W7GJKJ6qwQQ5XhtT5Hpk6fjNHUHC42qLLc8LWiFEZKULrkEY42tuEquBJrJgMT73tt73MN7L7LDzx6BW8xYQoMiC3TogPTqpJbFGCpKy9A9GM2xzYVGQMA7q8Y5jvjHLHGYcq4o3unGTLkpQAfrYZaxMUPmXWL4vEgRxDTjuwDAD3dTx46pX8iytwzGmWR2e2J1Qa6nqPsipGskuroMxmvfxcdTnf2Fu5wpEnRhFB1Tb65sN6PivKTXDyjD8iiPA5PgdvoNxJ1hR2sJYbaQxKFM3kLxSLRT42DrWJ3oqPpit3aHNoL4uDpBS8fMeB3xNkdz1K66QCPhPZHt1QQq7WjXjFL9N4DYULrEeN9TQHuEV2dEZ5RjyypRVzcXtuGqJAZAtFbLYxdNiiafmxJd5LZWbp13ZDoNV4z5FcsGcMKxMhUvVUtpEirQi58R3dZ4fhkbkdcy8yUmSmNMQxnRViPoiSfxWhKn5anvvbWScAQdefy56JgMP8JYn74iR3T2WdBFCdKAuSnKJfoWRhkHJLQemYeAHERgJBAYQsrv1HatRfa9qs1eMtn5fbWzBqgkAFQHBvSdVjzmY4SAzoucmB6scvSbCh48PAgDr1sBWCHFpGJQUvoELAEV6nTtVs85aMRJZbU7S4muv6xwNWm2RyL5Y9hDyuY8n",
"8KsXTBGHT8Hq2TShNFqpXC9h5Z2gduvGhybDD4n8K8zGEgNwkHgQtCYyVEWwghGjHifyCdEBgb8tsoTN3ppWd7o3H7bnz1Rm7pFhgW8nAWJi2vH67XNEzi9hRvqFWNUpTAkUF2CLvVZN181i6iXaHezQmzm3xk6kndCfzpepCdmSW1EQkAL3pPE4dDTXzig1jECLp1T9dcmutTsXzcACqJwcQVeiUgfffrYm3BUTg1BjXV5QCM5ndfHYcjdK7dDLB6Pfbiy6CZLh2yPiaxGAzB1KAn6eN9WBg58eWmZ4s1L85JwArSvBk7G7mjfQiwww8qDzyF7TJEanaK7tL24hhkv3WmrCSs1TBGh1YmBWYhwMNJrj5q7T4UnLAjaTL7yYuaJSa1kasagLniDDBYkmCUJs6wuQdxqoxdxn6dEo1jaaNZnsc8XtPcNGMEaoje5j5ARCDGk1B9477HvNzandhzrSBiBZhE2i89FgaUQdFBLH34UAWFo9szuZNRT9Tna8F86WEHCYbU1HAQShDsVYMkL3yYnc9m1CehB1TC3CMgMEj7p3Ma7PqtYQWjGZqRPo6s3xyUYQFKhM1QjUnr68k64KX6ejTkbNaDgNLisQwK2eJKjBwxDZFQQoqTeLH18QhVg4ju5VMYegjbzw8F8btyu6Er3UpnSqT1R8BWZvBkbqmadGCRXHM4t51GFf824LRZvGMtdrvRNQNjq6oTLeJ4PwvagCWxpxcdhtbfWRr9f3mr8xyJH2jYnxgbFecgZh2y2DeCATsm7kLfF6LvYFioUHWHitYUTAe4pNKgUT6pghY1hq5cP8h1cPrCdLykutBEMPQCGRpJPbKqd8fZBTSebSH4vSTzHQQZwfZCPRqg3FSS7XbK7YukUBT1JLjX9VSuU7MZ84ka6yr8u5ivQmUCnYgyjU1q9CC",
"8iy5uKH1444RXi1meR3DziSXhPYU9DKowBc42qbNCcenRvxNvivEdPTxuzjPa37ruwShBP7dyyGHxdtPL23PhAcx4k5azP2RQBezpURFkVtaYZeZc9Ww4tgSRwcz1Em7sWmY7NsuaNT7WHf7SKaSCitzuzs1FJX26kynJa86CeiripRBZHNDNmCRb5GkpNTvQ6XPsrioMhqzq1BQkS58h76qo7bVm9GrQg3ZbnXmnWaFfUruUfQBGBRx6JFuDvJNCpQGddhTk4uhYj48WG2uvSPqwVMXfQjwpUuoQcengL6ZXR5t7bkAi3jNsiKP3kewVWsJabBYqGtvtHtk6mikYwq2MMSfeu82HthzGQohawutLuicottsyC7xHRqRr622QhGNrra7xv4fh6EeAgJkrH2FGfknpuo7LbygGjDdhvy9L3JswAGz1xZGqstpxKDjonMvDB3jbbF2PhcZ1YCwFgmVHEKKpdPSpgxudo3swSfWYMNURmUPEZ7aEsV11t7a4ueLTBYTsAW7WwrB7YwCdB2EuiBJwMWiBioTov9LTyeF57Eoznse8xcpG4Teyy5QHDYVzvgUG5uAtzsGRqHE9xRjXDmBgasD6d6zxPNbZah11UzKqHF4D1SYudDbcztHD7RPir9mXR8mvrM6odRrcmnRQ16J3w6UShsemRaNqfYoU2dgLhbrXEMgsjzST4xcTJ4ChVfMNpH837cDoyHwZ8NUVAvmTgTipyNNnxNCti3JfCGLyy5gW5vo5BGM7BfPbtQCranuQRVH6AWUPWxe4DhhRwcCNJtsPFsTn44E7KHqt773Frd9u3NX6s4558azbf7r3QeJ2ub1B555iLSx4i6v1hpMmz5TPtbhD8fafvbRbSJBHhKF3yt2fsGTedoYovbWsMe6hEmZmEdN4AxnFGvF2qg4mtvcA",
"8tiA2WBGaqsosaL1e2Ukus5YDiddfuqnKSdDTasdhB7yrjthdwfHCvLHiZX5HeMz7ZQWvQHhZzqimPVQkABJVWRH4wMtv1FXAjnyQ48CwWbXYZNPEXJpC35RXaixQBa8F4bYsusHNyyDAtdEveKV3trq5bjthdNsbYwCoYYnDDSMRMPggg64PTrBUVeS8pNWTarWe8uDc9ABN9wnhN7fsMBNyza6WKHkN7dvU3Zaytd4EZXcaPyRL1rRpMP2k8KC3gBtz3CZNQEgjZd4j2sA5DM2KYLi7aGJSG5LWrxRF8Ze9AzvJbLeTELTQYbHtr3RSqQkEQGANoJf8cqZZ6Ngdq5cCxj5PWixDQjcYey8jsTRzXcRo4gQZwjhmVBvqb1w7qnnY2kpxx95iAGGzfs2ivbbPo1EfVCrFGhdmMbXwLwrbCqcqHUweTk7x4ucC3XjP2XqCf6xu7M52YQXbKnst5i5aN4MgpNBogCVd7Q15dr2rJt1juJhp65LozSQrPfXWo3AX2p95eJe4mxaS1XcgN9cZVsMvxLFRpsFxBxx2NaWqrU5jFCo56AeBLP2qsEJgxmv9BG7hZLnZ7xshYjgM5uyt9xkBiUycL5huLjVCDrW2qnX9TZwYjqXum9pyTkhrLJPugsf8DHjmjvvJJxtssqZjoQwPU2j6DoZREjyyp5dNNFiL8L2rkoXNbT9KwdStbmKjBWXEKazMPdYJgs5Gi5wnwNvywo9UbPKbomkdZBF9edRwBWRHpfFo1jo1EQMRhrPgj54Cg8sqWebcaWBBifFDAcRkXxGJhQd2DVeHRWgXXQyWgcftW44CCQV5qD7FX5GbBjvsLWoPjcs3qYPQC8NVuRNaAitB4SwuCHQriLxYmBRTktoSeJ5M5n82N8h6o3ChoYxKbB8jpX2xxgo36j7BjKztDTZy",
"AVv8vjCkXVsQNLkDCxMNYib7kgisTajfQE55NENySPUH2qgFq3mN43dww86rcgHgAhs87gjYjJbebZeGWn6JcUgdY2KCuNofmF38qf56rV9ax8xiy28jNrtqxZFXhZgqAzN9X7ncDThwEVCiHiPmHEcbVcXw3if7ozbNVqEZyc7kF2kSKF4xwtK1GpQ1av7WTPwyByM5Ti24DdBrgKu7iiTMRDtbExiyjJjVvK84yXkhEZui4VvM9aMTocNJByuku5TkM2kjnu1r1Fb8ByRiu6nPe9nWbz5CVfcLNURtTQD4o65dopDzip5KcJuGVeAgjQYQP3Y2iEht3Gk3m5SsEkbrfe1nhCtYschcQxEv4fwqCeqSmUJbaRqqzXMfQSHJcSCYg98rMJ72CKRjeNN6vdY4xx8LSDJz5MDVvwaF6er5DR3jfQw5iYXiV8a6PY2ipm7kf9qGE8dMAXfopH3QqC9hQh3jNXiSr76QjGft2NZLNcm6xS51wwM12w9eGWwbDRxD7nvm6ANFf9jtH3Ctp8T34NbqzDK6hkeUmmSCvu3kqM8RcdLTBw2f4BKZ3S5ffR8Dz5ZnxsT9i72XgbKykdyfBBGEkdvutyzXmjEGTHEgp859zd14LKpsNChwqwwjmRttEn6HMgVuQU7p3vDvmkHpMVMH7Ae1oPwFSivVAi6w4a9jDV7oPns8ffMK2v4kK8rbpYApFDm2dBGZXwVQMmcRoSXBzX3yHCBCbWFbahH6a9edxopxsBmk5fkAiPw9TK3bCtSs53d2GpArb2vixzGufLxX5gWTQ4iRd9c9sLaSVgHsYAY2oSUqBmKczhKdBnacZUN7Eidqmgay8e8Ty96crFf2iNeTnYhgqLKZw8kdM2KQNyXXdpU1QtmL9S5noC2ibhDqvE7PSDe6K6z16jFfUroRtRyB9",
"9vS4jyKJ9XKi5NuaDfysRWPjiJNLMhtsWicNkd3jFmMJUT2E3oUhqZkKd3zQaAoJEsT5QkreQE49SiQmbYKgWx5KHpbRv36AEs9abDtJD3Vzie9aKGMnrxVBMsu8E4H8FbHY91cNHZ64JAt8hKcAR131CBZMGnG4JctHNnz9yk9ynkeakx9TWvsRJpPWzxnowy1aUGnBGALxvjNsee4SPcY2TvmUKtkkjrgEGxZRfqyM3YnNPZVr2RLWQ4oeMMCPojFqzgNfdtGjg3Mns82sokNwMN8ZGpX1cxKWCp92gg8cmuPruythtu4j1MWQR2AsnT963Pp4H2CdsHBbv8KFPBSaS9SWnGwyG9xibbfK8RtdoGK4xxrhM2DdJP5Qpxu8e3nYwknVMYNHKfJjhupAtDHbrJscJQm2NqHJDw9kLjfGCwYYLVDxx7NLnqUNSKn13Lc4BJmwSyYUP9YdMYgkMwfscGRrtZGRwUAPY5rPcd6Tde7X43GCib87bFx1UpypafBdbQjfthRmZthggL84hZapNbfHwFZu5ttZAV6FUy1jYJ2ByMkFF45QPRz4BJZRzZVWLDzdP6QCrf7S1TifYEtcGdMN2mHZDfkc8NGFy6jGgg8ULRd1vPTco6fzXjqZJf5gXY6xGfTimBuZBwTqS43qyLGtahCq2Ue51hcWqi8x6mSS9pZukDVthQEAbWmNs3U3NSErpYd25iQtGwbJVrYr4XY1TbPGHN1L3HftQJcUerSWughCzp85PY1yBzM8E2t9DAo4cEK8vvwCmbbHLnwrhXfNLYHvrdpsziVprEz3yRBcRqcYaSaaNkd5DYwzp8UqnE6eS11grHhUgd2VVuaTgpmgcbCjBUhqET25aJ5w7Lwy7xMhNdF4HePwbEiqnAWqKk6bQhFqndmB7UKVnRwSi55iVN5KK",
"8vi5eKGVaSjNKx27tf4ncS7WiZNeeXeBvwHWVbiAW1gDjtbtT8tnFaGBUiNz9bDB4Shr1YcGz8gGeFCsv7GZgbP9rEM96dQnPPXH3draEqyVw8ZwzwvosZai3UXBYqBaWQQFEvk48XKJbowwPzNtERR3G2qNdViag1k8Pp841Nw7Dz6cLNsenQ3uH67d52tVNsqqvSwsPMBbd2xjRbCEbXWUc8UFqK3V2cU2koLFRc79fJPACys3ymKYqCsoKDL1xDBarpXumKVV4H8WKPC3coSG4RbaT9eMYeaYqp3Kct2nLzWP3xrFJpZRKNR2Y5fXSsbqZLS7XdfAV624p9YRA2TWsZfdQekoQADzMnoZyVjp7pHapmh2aY4xg853GrCfsCq7JXiFprxTruWqKy3xkcmv6yTAvC7vVkyczVpqyBbZ9atQtn34QELzYWXmq9tojcWgg2m5687z6mRBAjboxmYVJ7YskM1i7vrgHes2bsy4WM76zST2wiHMGiBcDvJsWj1f6VefjZm93BWqyTEJwpEBWKUFjqAEB3XmK8xeKCvQPFkVc8WBLjDosGoAXE584SfbWYdrQi2Bwb4aWGgSmmYUmAUkvnhmWA2RFqm6jjZKJsSHwn9qegcknPAnRVAGi3eLLtNpTZ3W7GehSjWse5KKBPWJyDtDR9qtLvkiwd7upQvYy5qyMeJhS3WbpVxcPQc1qPSJs4nVpDJMY2Qm1SCNVETPn5jAb4gQA81MuRsmdy9LmX3RwLYGLPznvCuHNTB8zis72cj2SKX2RygAR9cMjFutQkuGhsqMyiPx69UWAsnqhgSU5xcn2X1ex4gaA3vwaWJSSsJ17SpDAsxiJKKYUFSXNArwJ7w17dDGuQwikev8x2LeDqgvFvepyeqn1Hz3bR2JdP41A2MEoQDEM7WjwsJdTZKLJ",
"9sokmCXUBroQ161SoMrPJPpU6B1jQjCfzx6aVfUKZqutCzBCZX1D6S3AMjzPKJo3dGcNN9jYVTSHR8K1qzsuq7B7T9FDuqjHSu4mSptNNo7a4mRiE7xc1C3k5PH48z86j8DYedJS7khM21mrPrAShBNG8yVM8reRWKuVjrNJBT3aUFD7psjNXhRVSL74YJx8ECf8sNAL2i8jGDC5mgZkKWx5tTXADLgZZSRPTTcjztWEFXTgWUcjr8UnedKgNa3C8NNRLyxmPXVEjh3LQEDPsFejHARJPRi1TgG8yTo9jXoe7wsWoptQpQjeDBZC3DthzJ8RBNcYNY5DhdC3aUpPEVRs3DE4XsEWNTkJYHcFAMGbFYckjMaAtrCSCm9ePGg8ywYSANutHb9cCyboSqhsPXxbe6cf2g8obTkJVqWtrykQhY2YajBPs6bpXj8pmay2DwKTKtREyNyspzufXH5VPypsmJg8Zicy5Jy57YJgfanJaEgCEhor5F6k5CN54ZSmKWnap6Pks7KmTpJdoJxqpLxTGXfMd6FJxdqQ5rXB9S4Fb9xtQQAiZ9STeXvGQaMxpCdwVgBw9oXYLpq8DT9VEgYNWoTuTtLLHQZrKj7ToUYpPvKvrXAzifBjETMvvsogoUnXKCQA33WGv2wASXPpoynvWzbr9W96hkeJucrofXBdYDVowzQCCQACwdFzTFz2on37iCx95McgEZg2B2wwE49RQ7bTSXC9L1zj3LetZu9eEiZ2UgZsc7JCV1E8E4k6rdC8euz1cRZHvQ1RgF4cyB3MgHwSCHKyukoUk1humpB7ftLpYaq6y7qRBuPnWqCxGcjGo6rfpRmJt8aNSNDVXZGAhpFWUVsnvWqpVSSwrZuK26n18rMPkufYkXpAQ1yptszkb1yodZU6e9aQaLB9uNAoiQJiE8mR2",
"9ft11E8rkGmYbFYppZrFpjh2akPDTgcexV5RiMnGsU1ekr7GJvicVSBniEmAKHzAvbpbQhgSpydrFwE8sxpVvH3cqqbWx6htPmtv3GxDWHVp4J9o32egWPgmNGBmtH1SxRJiKhCdNmW7gKCEAqymDQhM2YDvFVdtXoSrpyM5kBxqkjQhvRGUVkeerxEmuFHB1QGjzV1k1zc77wRoKoWeN4ZpdUBQ4PCDdJ5jgtTefj4DLbvLxJAioSQf9Ef38sjrerfEhoh5N3upgMVJuBEwUxyk7B8TZ41SMUtva45cR7hDfLJUCbem6QTPxs1ADxDRSjrvYuzJE4RxWow8Hrp6hz42B13YgAkZ9cqMp1S9JMzEuzBCdzm8vPyjbZkfNAQqiGVA21o6m4BUTCseanAziDsakrsDZZAMpC4X8Tjm3AaUNQP2rBz4nb6ZkQVPUUQB5AvXqh5zupKfzYNV5WUK4EvzN8YknwVh11ckdw3JKCo5Kk1rhguz4gaCqg2mYZNoJdf4zjSwsRaHrWRXJdEhXQKZQxaWwNPEQbK2amfPoC7ungEXMiwQei1wSC1p1TY6FZTnekYwuYBtDRCyiNqXJwvv4WRfuJCykLjBHomrhKhR3hoYPD3DcynQWWdanHiFVE9rQQQKYv7UJQ8gELu9CCSrUgt5LDmPGhSMvYbfUzCofWvMSjhsRPiwheqLp3sEr2fNfssNZ382ZpKDdQPCaDnQhi7naLfuAp5gyo7rZC3QYUhhM2bbEaPRYGixhWf7uv6q8j6RR2u7sQnqemjdSsJnRfe6r5DwAuWxNkTm2sPUJ8pmvjfT6WLHkq8PmcrD4vNGQK8SGBRbaTweTckig1ri8WMN5JY8UbGkMkCtJxZWPqAq8rvyZf1agvEDHeKHf2u5ZTBEqGtLFyNrgziM2YCURQLLTW87b",
];
for (i, ((address, api), key)) in addresses
.iter()
.zip(apis.iter())
.zip(keys.iter())
.enumerate()
{
let share = ContractVKShare {
share: key.to_string(),
announce_address: api.to_string(),
node_index: (i + 1) as u64,
owner: address.clone(),
epoch_id: 0,
verified: true,
};
vk_shares().save(deps.storage, (address, 0), &share)?;
}
THRESHOLD.save(deps.storage, &7)?;
pub fn migrate(_deps: DepsMut<'_>, _env: Env, _msg: MigrateMsg) -> Result<Response, ContractError> {
Ok(Default::default())
}
+7 -23
View File
@@ -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.
+2 -2
View File
@@ -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/)** !
+6 -7
View File
@@ -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.
@@ -60,8 +60,6 @@ Quite a bit of stuff gets built. The key working parts are:
* [socks5 client](../clients/socks5-client.md): `nym-socks5-client`
* [network requester](../nodes/network-requester.md): `nym-network-requester`
* [nym-cli tool](../tools/nym-cli.md): `nym-cli`
* [nym-api](https://nymtech.net/operators/nodes/nym-api.html): `nym-api`
* [nymvisor](https://nymtech.net/operators/nodes/nymvisor-upgrade.html): `nymvisor`
The repository also contains Typescript applications which aren't built in this process. These can be built by following the instructions on their respective docs pages.
* [Nym Wallet](../wallet/desktop-wallet.md)
+4 -7
View File
@@ -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).
+2 -2
View File
@@ -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.
-80
View File
@@ -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;
+1 -1
View File
@@ -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"
-3
View File
@@ -17,10 +17,7 @@
- [Gateway](nodes/gateway-setup.md)
- [Network Requester](nodes/network-requester-setup.md)
- [Nyx Validator Setup](nodes/validator-setup.md)
- [Nym API Setup](nodes/nym-api.md)
- [Maintenance](nodes/maintenance.md)
- [Manual Node Upgrade](nodes/manual-upgrade.md)
- [Automatic Node Upgrade: Nymvisor Setup and Usage](nodes/nymvisor-upgrade.md)
- [Troubleshooting](nodes/troubleshooting.md)
# FAQ
@@ -61,9 +61,7 @@ Quite a bit of stuff gets built. The key working parts are:
* [webassembly client](https://nymtech.net/docs/clients/webassembly-client.html): `webassembly-client`
* [network requester](../nodes/network-requester-setup.md): `nym-network-requester`
* [nym-cli tool](https://nymtech.net/docs/tools/nym-cli.html): `nym-cli`
* [nym-api](../nodes/nym-api.md): `nym-api`
* [nymvisor](../nodes/nymvisor-upgrade.md): `nymvisor`
The repository also contains Typescript applications which aren't built in this process. These can be built by following the instructions on their respective docs pages.
* [Nym Wallet](https://nymtech.net/docs/wallet/desktop-wallet.html)
* [Nym Connect](https://nymtech.net/developers/quickstart/nymconnect-gui.html)
+4 -7
View File
@@ -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.
@@ -84,7 +84,7 @@ Additionally
#### Add Network Requester to an existing Gateway
If you already [upgraded](./manual-upgrade.md) your Gateway to the [latest version](./gateway-setup.md#current-version) and initialised without a Network Requester, you can easily change its functionality to Exit Gateway with a command `setup-network-requester`.
If you already [upgraded](./maintenance.md#upgrading-your-node) your Gateway to the [latest version](./gateway-setup.md#current-version) and initialised without a Network Requester, you can easily change its functionality to Exit Gateway with a command `setup-network-requester`.
See the options:
@@ -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.
![Paste Signature](../images/wallet-screenshots/wallet-gateway-sign.png)
*This image is just an example, copy-paste your own base58-encoded signature.*
*This image is just an example, copy-paste your own base58-encoded signature*
* Your Gateway is now bonded.
+194 -165
View File
@@ -14,37 +14,110 @@ For example `./target/debug/nym-network-requester --no-banner build-info --outpu
{"binary_name":"nym-network-requester","build_timestamp":"2023-07-24T15:38:37.00657Z","build_version":"1.1.23","commit_sha":"c70149400206dce24cf20babb1e64f22202672dd","commit_timestamp":"2023-07-24T14:45:45Z","commit_branch":"feature/simplify-cli-parsing","rustc_version":"1.71.0","rustc_channel":"stable","cargo_profile":"debug"}
```
## Upgrading your node
> The process is the similar for Mix Node, Gateway and Network Requester. In the following steps we use a placeholder `<NODE>` in the commands, please change it for the type of node you want to upgrade. Any particularities for the given type of node are included.
Upgrading your node is a two-step process:
* Updating the binary and `~/.nym/<NODE>/<YOUR_ID>/config/config.toml` on your VPS
* Updating the node information in the [mixnet smart contract](https://nymtech.net/docs/nyx/mixnet-contract.html). **This is the information that is present on the [mixnet explorer](https://explorer.nymtech.net)**.
### Step 1: Upgrading your binary
Follow these steps to upgrade your Node binary and update its config file:
* Pause your node process.
- if you see the terminal window with your node, press `ctrl + c`
- if you run it as `systemd` service, run: `systemctl stop nym-<NODE>.service`
* 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 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
systemctl start nym-<NODE>.service
journalctl -f -u <NODE>.service # to monitor log of you node
```
If these steps are too difficult and you prefer to just run a script, you can use [ExploreNYM script](https://github.com/ExploreNYM/bash-tool) or one done by [Nym developers](https://gist.github.com/tommyv1987/4dca7cc175b70742c9ecb3d072eb8539).
> In case of a Network Requester this is all, the following step is only for Mix Nodes and Gateways.
### Step 2: Updating your node information in the smart contract
Follow these steps to update the information about your `<NODE>` which is publicly available from the [`nym-api`](https://validator.nymtech.net/api/swagger/index.html) and information displayed on the [Mixnet explorer](https://explorer.nymtech.net).
You can either do this graphically via the Desktop Wallet, or the CLI.
### Updating node information via the Desktop Wallet (recommended)
* Navigate to the `Bonding` page and click the `Node Settings` link in the top right corner:
![Bonding page](../images/wallet-screenshots/bonding.png)
* Update the fields in the `Node Settings` page and click `Submit changes to the blockchain`.
![Node Settings Page](../images/wallet-screenshots/node_settings.png)
### Updating node information via the CLI
If you want to bond your `<NODE>` via the CLI, then check out the [relevant section in the Nym CLI](https://nymtech.net/docs/tools/nym-cli.html#upgrade-a-mix-node) docs.
### Upgrading Network Requester to >= v1.1.10 from <v1.1.9
In the previous version of the network-requester, users were required to run a nym-client along side it to function. As of `v1.1.10`, the network-requester now has a nym client embedded into the binary, so it can run standalone.
If you are running an existing Network Requester registered with nym-connect, upgrading requires you move your old keys over to the new Network Requester configuration. We suggest following these instructions carefully to ensure a smooth transition.
Initiate the new Network Requester:
```sh
nym-network-requester init --id <YOUR_ID>
```
Copy the old keys from your client to the network-requester configuration that was created above:
```sh
cp -vr ~/.nym/clients/myoldclient/data/* ~/.nym/service-providers/network-requester/<YOUR_ID>/data
```
Edit the configuration to match what you used on your client. Specifically, edit the configuration file at:
```sh
~/.nym/service-providers/network-requester/<YOUR_ID>/config/config.toml
```
Ensure that the fields `gateway_id`, `gateway_owner`, `gateway_listener` in the new config match those in the old client config at:
```sh
~/.nym/clients/myoldclient/config/config.toml
```
### Upgrading your validator
Upgrading from `v0.31.1` -> `v0.32.0` process is fairly simple. Grab the `v0.32.0` release tarball from the [`nyxd` releases page](https://github.com/nymtech/nyxd/releases), and untar it. Inside are two files:
- the new validator (`nyxd`) v0.32.0
- the new wasmvm (it depends on your platform, but most common filename is `libwasmvm.x86_64.so`)
Wait for the upgrade height to be reached and the chain to halt awaiting upgrade, then:
* copy `libwasmvm.x86_64.so` to the default LD_LIBRARY_PATH on your system (on Ubuntu 20.04 this is `/lib/x86_64-linux-gnu/`) replacing your existing file with the same name.
* swap in your new `nyxd` binary and restart.
You can also use something like [Cosmovisor](https://github.com/cosmos/cosmos-sdk/tree/main/tools/cosmovisor) - grab the relevant information from the current upgrade proposal [here](https://nym.explorers.guru/proposal/9).
Note: Cosmovisor will swap the `nyxd` binary, but you'll need to already have the `libwasmvm.x86_64.so` in place.
#### Common reasons for your validator being jailed
The most common reason for your validator being jailed is that your validator is out of memory because of bloated syslogs.
Running the command `df -H` will return the size of the various partitions of your VPS.
If the `/dev/sda` partition is almost full, try pruning some of the `.gz` syslog archives and restart your validator process.
## 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 IPs 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
@@ -130,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 IPs 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`.
@@ -154,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
@@ -173,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 its 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 its not totally necessary, it's useful to have the Mix Node automatically start at system boot time.
#### nohup
@@ -209,7 +298,7 @@ In case it didn't work for your distribution, see how to build `tmux` from [vers
**Running tmux**
Now you have installed tmux on your VPS, let's run a Mix Node on tmux, which allows you to detach your terminal and let your `<NODE>` run on its own on the VPS.
No when you installed tmux on your VPS, let's run a Mix Node on tmux, which allows you to detach your terminal and let your `<NODE>` run on its own on the VPS.
* Pause your `<NODE>`
* Start tmux with the command
@@ -230,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
@@ -252,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
@@ -274,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
@@ -296,108 +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).
##### For Nymvisor
> Since you're running your node via a Nymvisor instance, as well as creating a Nymvisor `.service` file, you will also want to **stop any previous node automation process you already have running**.
```
[Unit]
Description=Nymvisor <VERSION>
StartLimitInterval=350
StartLimitBurst=10
[Service]
User=nym # replace this with whatever user you wish
LimitNOFILE=65536
ExecStart=/home/<USER>/<PATH>/nymvisor run run --id <NODE_ID>
KillSignal=SIGINT
Restart=on-failure
RestartSec=30
[Install]
WantedBy=multi-user.target
```
* Put the above file onto your system at `/etc/systemd/system/nymvisor.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
# for Nymvisor
systemctl enable nymvisor.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
# for Nymvisor
service nymvisor.service start
```
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]
@@ -427,37 +429,60 @@ systemctl start nymd # to actually start the service
journalctl -f -u nymd # to monitor system logs showing the service start
```
##### For Nym API
##### Following steps for Nym Mixnet nodes
Below is a `systemd` unit file to place at `/etc/systemd/system/nym-api.service` to automate your API instance:
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.
```ini
[Unit]
Description=NymAPI
StartLimitInterval=350
StartLimitBurst=10
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:
[Service]
User=<USER> # change to your user
Type=simple
ExecStart=/home/<USER>/<PATH_TO_BINARY>/nym-api start # change to correct path
Restart=on-failure
RestartSec=30
LimitNOFILE=infinity
`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`
[Install]
WantedBy=multi-user.target
```
Proceed to start it with:
Then run:
```sh
systemctl daemon-reload # to pickup the new unit file
systemctl enable nym-api # to enable the service
systemctl start nym-api # to actually start the service
journalctl -f -u nym-api # to monitor system logs showing the service start
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
@@ -586,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
@@ -601,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
@@ -796,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 |
/
@@ -1,101 +0,0 @@
# Manual Node Upgrade
> The process here is similar for the Mix Node, Gateway and Network Requester binaries. In the following steps we use a placeholder `<NODE>` in the commands, please change it for the binary name you want to upgrade (e.g.`nym-mixnode`). Any particularities for the given type of node are included.
Upgrading your node is a two-step process:
1. Updating the binary and `~/.nym/<NODE>/<YOUR_ID>/config/config.toml` on your VPS
2. Updating the node information in the [mixnet smart contract](https://nymtech.net/docs/nyx/mixnet-contract.html). **This is the information that is present on the [mixnet explorer](https://explorer.nymtech.net)**.
## Step 1: Upgrading your binary
Follow these steps to upgrade your Node binary and update its config file:
* Pause your node process.
- if you see the terminal window with your node, press `ctrl + c`
- if you run it as `systemd` service, run: `systemctl stop <NODE>.service`
* 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 `./<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 *automated* your node with systemd (recommended) run:
```sh
systemctl daemon-reload # to pickup the new unit file
systemctl start <NODE>.service
journalctl -f -u <NODE>.service # to monitor log of you node
```
If these steps are too difficult and you prefer to just run a script, you can use [ExploreNYM script](https://github.com/ExploreNYM/bash-tool) or one done by [Nym developers](https://gist.github.com/tommyv1987/4dca7cc175b70742c9ecb3d072eb8539).
> In case of a Network Requester this is all, the following step is only for Mix Nodes and Gateways.
## Step 2: Updating your node information in the smart contract
Follow these steps to update the information about your `<NODE>` which is publicly available from the [`nym-api`](https://validator.nymtech.net/api/swagger/index.html) and information displayed on the [Mixnet explorer](https://explorer.nymtech.net).
You can either do this graphically via the Desktop Wallet, or the CLI.
### Updating node information via the Desktop Wallet (recommended)
* Navigate to the `Bonding` page and click the `Node Settings` link in the top right corner:
![Bonding page](../images/wallet-screenshots/bonding.png)
* Update the fields in the `Node Settings` page (usually the field `Version` is the only one to change) and click `Submit changes to the blockchain`.
![Node Settings Page](../images/wallet-screenshots/node_settings.png)
### Updating node information via the CLI
If you want to bond your `<NODE>` via the CLI, then check out the [relevant section in the Nym CLI](https://nymtech.net/docs/tools/nym-cli.html#upgrade-a-mix-node) docs.
## Upgrading Network Requester to >= v1.1.10 from <v1.1.9
In the previous version of the network-requester, users were required to run a nym-client along side it to function. As of `v1.1.10`, the network-requester now has a nym client embedded into the binary, so it can run standalone.
If you are running an existing Network Requester registered with nym-connect, upgrading requires you move your old keys over to the new Network Requester configuration. We suggest following these instructions carefully to ensure a smooth transition.
Initiate the new Network Requester:
```sh
nym-network-requester init --id <YOUR_ID>
```
Copy the old keys from your client to the network-requester configuration that was created above:
```sh
cp -vr ~/.nym/clients/myoldclient/data/* ~/.nym/service-providers/network-requester/<YOUR_ID>/data
```
Edit the configuration to match what you used on your client. Specifically, edit the configuration file at:
```sh
~/.nym/service-providers/network-requester/<YOUR_ID>/config/config.toml
```
Ensure that the fields `gateway_id`, `gateway_owner`, `gateway_listener` in the new config match those in the old client config at:
```sh
~/.nym/clients/myoldclient/config/config.toml
```
## Upgrading your validator
Upgrading from `v0.31.1` -> `v0.32.0` process is fairly simple. Grab the `v0.32.0` release tarball from the [`nyxd` releases page](https://github.com/nymtech/nyxd/releases), and untar it. Inside are two files:
- the new validator (`nyxd`) v0.32.0
- the new wasmvm (it depends on your platform, but most common filename is `libwasmvm.x86_64.so`)
Wait for the upgrade height to be reached and the chain to halt awaiting upgrade, then:
* copy `libwasmvm.x86_64.so` to the default LD_LIBRARY_PATH on your system (on Ubuntu 20.04 this is `/lib/x86_64-linux-gnu/`) replacing your existing file with the same name.
* swap in your new `nyxd` binary and restart.
You can also use something like [Cosmovisor](https://github.com/cosmos/cosmos-sdk/tree/main/tools/cosmovisor) - grab the relevant information from the current upgrade proposal [here](https://nym.explorers.guru/proposal/9).
Note: Cosmovisor will swap the `nyxd` binary, but you'll need to already have the `libwasmvm.x86_64.so` in place.
### Common reasons for your validator being jailed
The most common reason for your validator being jailed is that your validator is out of memory because of bloated syslogs.
Running the command `df -H` will return the size of the various partitions of your VPS.
If the `/dev/sda` partition is almost full, try pruning some of the `.gz` syslog archives and restart your validator process.
@@ -68,7 +68,7 @@ Initialise your Mix Node with the following command, replacing the value of `--i
```
./nym-mixnode init --id <YOUR_ID> --host $(curl -4 https://ifconfig.me)
```
If `<YOUR_ID>` was `my-node`, the output will look like this:
If `<YOUR_ID>` was `my-node`, the output shall look like like this:
~~~admonish example collapsible=true title="Console output"
```
@@ -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,164 +0,0 @@
# Nym API Setup
[//]: # (> The Nym API binary was built in the [building nym]&#40;../binaries/building-nym.md&#41; section. If you haven't yet built Nym and want to run the code, go there first. You can build just the API with `cargo build --release --bin nym-api`.)
[//]: # ()
> The `nym-api` binary should be coming out in the next release - we're releasing this document beforehand so that Validators have information as soon as possible and get an idea of what to expect. This doc will be expanded over time as we release the API binary itself as well as start enabling functionality.
> Any syntax in `<>` brackets is a user's unique variable. Exchange with a corresponding name without the `<>` brackets.
## What is the Nym API?
The Nym API is a binary that will be operated by some or all of the Nyx Blockchain Validator set. This binary can be run in several different modes, and has two main bits of functionality:
* network monitoring (calculating the routing score of Mixnet nodes)
* generation and validation of [zk-Nyms](https://blog.nymtech.net/zk-nyms-are-here-a-major-milestone-towards-a-market-ready-mixnet-a3470c9ab10a), our implementation of the Coconut Selective Disclosure Credential Scheme.
This is important for both the proper decentralisation of the network uptime calculation and, more pressingly, enabling the NymVPN to utilise privacy preserving payments.
The process of enabling these different aspects of the system will take time. Operators of the Nym API binary for the moment will only have to run the binary in a minimal 'caching' mode in order to get used to maintaining an additional process running alongside their Validator.
### Rewards
Operators of Nym API instances will be rewarded for performing the extra work of taking part in credential generation. These rewards will be calculated **separately** from rewards for block production.
Rewards for credential signing will be calculated hourly, with API operators receiving a proportional amount of the reward pool (333NYM per hour / 237600NYM per month) according to the % of credentials they have signed.
### (Coming Soon) Machine Specs
We are working on load testing currently in order to get good specs for a Validator + Nym API setup. Bear in mind that credential signing is primarily CPU-bound.
### (Coming Soon) Credential Generation
Validators that take part in the DKG ceremony (more details on this soon) will become part of the quorum generating and verifying zk-Nym credentials. These will initially be used for private proof of payment for NymVPN (see our blogposts [here](https://blog.nymtech.net/nymvpn-an-invitation-for-privacy-experts-and-enthusiasts-63644139d09d) and [here](https://blog.nymtech.net/zk-nyms-are-here-a-major-milestone-towards-a-market-ready-mixnet-a3470c9ab10a) for more on this), and in the future will be expanded into more general usecases such as [offline ecash](https://arxiv.org/abs/2303.08221).
## Current version
```
<!-- cmdrun ../../../../target/release/nym-api --version | grep "Build Version" | cut -b 21-26 -->
```
## Setup and Usage
### Viewing command help
You can check that your binary is properly compiled with:
```
./nym-api --help
```
Which should return a list of all available commands.
~~~admonish example collapsible=true title="Console output"
```
<!-- cmdrun ../../../../target/release/nym-api --help -->
```
~~~
You can also check the various arguments required for individual commands with:
```
./nym-api <COMMAND> --help
```
### Initialising your Nym API Instance
Initialise your API instance with:
```
./nym-api init
```
You can optionally pass a local identifier for this instance with the `--instance` flag. Otherwise the ID of your instance defaults to `default`.
### Running your Nym API Instance
The API binary currently defaults to running in caching mode. You can run your API with:
```
./nym-api run
```
By default the API will be trying to query a running `nyxd` process (either a validator or RPC node) on `localhost:26657`. This value can be modified either via the `--nyxd-validator ` flag on `run`:
```
./nym-api run --nyxd-validator https://rpc.nymtech.net:443
```
> You can also change the value of `local_validator` in the config file found by default in `$HOME/.nym/nym-api/<ID>/config/config.toml`.
This process is quite noisy, but informative:
~~~admonish example collapsible=true title="Console output"
```
Starting nym api...
2023-12-12T14:29:55.800Z INFO rocket::launch > 🔧 Configured for release.
2023-12-12T14:29:55.800Z INFO rocket::launch::_ > address: 127.0.0.1
2023-12-12T14:29:55.800Z INFO rocket::launch::_ > port: 8000
2023-12-12T14:29:55.800Z INFO rocket::launch::_ > workers: 4
2023-12-12T14:29:55.800Z INFO rocket::launch::_ > max blocking threads: 512
2023-12-12T14:29:55.800Z INFO rocket::launch::_ > ident: Rocket
2023-12-12T14:29:55.800Z INFO rocket::launch::_ > IP header: X-Real-IP
2023-12-12T14:29:55.800Z INFO rocket::launch::_ > limits: bytes = 8KiB, data-form = 2MiB, file = 1MiB, form = 32KiB, json = 1MiB, msgpack = 1MiB, string = 8KiB
2023-12-12T14:29:55.800Z INFO rocket::launch::_ > temp dir: /tmp
2023-12-12T14:29:55.800Z INFO rocket::launch::_ > http/2: true
2023-12-12T14:29:55.800Z INFO rocket::launch::_ > keep-alive: 5s
2023-12-12T14:29:55.800Z INFO rocket::launch::_ > tls: disabled
2023-12-12T14:29:55.800Z INFO rocket::launch::_ > shutdown: ctrlc = true, force = true, signals = [SIGTERM], grace = 2s, mercy = 3s
2023-12-12T14:29:55.800Z INFO rocket::launch::_ > log level: critical
2023-12-12T14:29:55.800Z INFO rocket::launch::_ > cli colors: true
2023-12-12T14:29:55.800Z INFO rocket::launch > 📬 Routes:
2023-12-12T14:29:55.800Z INFO rocket::launch::_ > (get_registered_names) GET /v1/names
2023-12-12T14:29:55.800Z INFO rocket::launch::_ > (get_mixnodes) GET /v1/mixnodes
2023-12-12T14:29:55.800Z INFO rocket::launch::_ > (get_gateways) GET /v1/gateways
2023-12-12T14:29:55.800Z INFO rocket::launch::_ > (get_services) GET /v1/services
2023-12-12T14:29:55.800Z INFO rocket::launch::_ > GET /v1/openapi.json
2023-12-12T14:29:55.800Z INFO rocket::launch::_ > (get_full_circulating_supply) GET /v1/circulating-supply
2023-12-12T14:29:55.800Z INFO rocket::launch::_ > (get_current_epoch) GET /v1/epoch/current
2023-12-12T14:29:55.800Z INFO rocket::launch::_ > (get_active_set) GET /v1/mixnodes/active
2023-12-12T14:29:55.800Z INFO rocket::launch::_ > (get_mixnodes_detailed) GET /v1/mixnodes/detailed
2023-12-12T14:29:55.800Z INFO rocket::launch::_ > (get_rewarded_set) GET /v1/mixnodes/rewarded
2023-12-12T14:29:55.800Z INFO rocket::launch::_ > (get_gateways_described) GET /v1/gateways/described
2023-12-12T14:29:55.800Z INFO rocket::launch::_ > (get_interval_reward_params) GET /v1/epoch/reward_params
2023-12-12T14:29:55.800Z INFO rocket::launch::_ > (get_blacklisted_mixnodes) GET /v1/mixnodes/blacklisted
2023-12-12T14:29:55.800Z INFO rocket::launch::_ > (get_blacklisted_gateways) GET /v1/gateways/blacklisted
2023-12-12T14:29:55.800Z INFO rocket::launch::_ > (get_total_supply) GET /v1/circulating-supply/total-supply-value
2023-12-12T14:29:55.800Z INFO rocket::launch::_ > (get_circulating_supply) GET /v1/circulating-supply/circulating-supply-value
2023-12-12T14:29:55.800Z INFO rocket::launch::_ > (get_active_set_detailed) GET /v1/mixnodes/active/detailed
2023-12-12T14:29:55.800Z INFO rocket::launch::_ > (get_rewarded_set_detailed) GET /v1/mixnodes/rewarded/detailed
2023-12-12T14:29:55.800Z INFO rocket::launch::_ > GET /cors/<status>
2023-12-12T14:29:55.800Z INFO rocket::launch::_ > GET /swagger/
2023-12-12T14:29:55.800Z INFO rocket::launch::_ > GET /swagger/index.css
2023-12-12T14:29:55.800Z INFO rocket::launch::_ > GET /swagger/index.html
2023-12-12T14:29:55.800Z INFO rocket::launch::_ > GET /swagger/swagger-ui.css
2023-12-12T14:29:55.800Z INFO rocket::launch::_ > GET /swagger/oauth2-redirect.html
2023-12-12T14:29:55.800Z INFO rocket::launch::_ > GET /swagger/swagger-ui-bundle.js
2023-12-12T14:29:55.800Z INFO rocket::launch::_ > GET /swagger/swagger-ui-config.json
2023-12-12T14:29:55.800Z INFO rocket::launch::_ > GET /swagger/swagger-initializer.js
2023-12-12T14:29:55.800Z INFO rocket::launch::_ > GET /swagger/swagger-ui-standalone-preset.js
2023-12-12T14:29:55.800Z INFO rocket::launch::_ > (get_mixnodes_detailed) GET /v1/status/mixnodes/detailed
2023-12-12T14:29:55.800Z INFO rocket::launch::_ > (get_mixnode_inclusion_probabilities) GET /v1/status/mixnodes/inclusion_probability
2023-12-12T14:29:55.800Z INFO rocket::launch::_ > (get_mixnode_status) GET /v1/status/mixnode/<mix_id>/status
2023-12-12T14:29:55.800Z INFO rocket::launch::_ > (get_active_set_detailed) GET /v1/status/mixnodes/active/detailed
2023-12-12T14:29:55.800Z INFO rocket::launch::_ > (get_rewarded_set_detailed) GET /v1/status/mixnodes/rewarded/detailed
2023-12-12T14:29:55.800Z INFO rocket::launch::_ > (get_mixnode_stake_saturation) GET /v1/status/mixnode/<mix_id>/stake-saturation
2023-12-12T14:29:55.800Z INFO rocket::launch::_ > (get_mixnode_inclusion_probability) GET /v1/status/mixnode/<mix_id>/inclusion-probability
2023-12-12T14:29:55.800Z INFO rocket::launch::_ > (network_details) GET /v1/network/details
2023-12-12T14:29:55.800Z INFO rocket::launch::_ > (nym_contracts) GET /v1/network/nym-contracts
2023-12-12T14:29:55.800Z INFO rocket::launch::_ > (nym_contracts_detailed) GET /v1/network/nym-contracts-detailed
2023-12-12T14:29:55.800Z INFO rocket::launch > 📡 Fairings:
2023-12-12T14:29:55.800Z INFO rocket::launch::_ > Validator Cache Stage (ignite)
2023-12-12T14:29:55.800Z INFO rocket::launch::_ > Circulating Supply Cache Stage (ignite)
2023-12-12T14:29:55.800Z INFO rocket::launch::_ > Shield (liftoff, response, singleton)
2023-12-12T14:29:55.801Z INFO rocket::launch::_ > CORS (ignite, request, response)
2023-12-12T14:29:55.801Z INFO rocket::launch::_ > Node Status Cache (ignite)
2023-12-12T14:29:55.801Z INFO rocket::shield::shield > 🛡️ Shield:
2023-12-12T14:29:55.801Z INFO rocket::shield::shield::_ > X-Content-Type-Options: nosniff
2023-12-12T14:29:55.801Z INFO rocket::shield::shield::_ > X-Frame-Options: SAMEORIGIN
2023-12-12T14:29:55.801Z INFO rocket::shield::shield::_ > Permissions-Policy: interest-cohort=()
2023-12-12T14:29:55.801Z WARN rocket::launch > 🚀 Rocket has launched from http://127.0.0.1:8000
2023-12-12T14:29:56.375Z INFO nym_api::nym_contract_cache::cache::refresher > Updating validator cache. There are 888 mixnodes and 105 gateways
2023-12-12T14:29:56.375Z INFO nym_api::node_status_api::cache::refresher > Updating node status cache
2023-12-12T14:29:57.359Z INFO nym_api::circulating_supply_api::cache > Updating circulating supply cache
2023-12-12T14:29:57.359Z INFO nym_api::circulating_supply_api::cache > the mixmining reserve is now 220198535489690unym
2023-12-12T14:29:57.359Z INFO nym_api::circulating_supply_api::cache > the number of tokens still vesting is now 145054386857730unym
2023-12-12T14:29:57.359Z INFO nym_api::circulating_supply_api::cache > the circulating supply is now 634747077652580unym
2023-12-12T14:30:00.803Z INFO nym_api::support::caching::refresher > node-self-described-data-refresher: refreshing cache state
2023-12-12T14:31:56.290Z INFO nym_api::nym_contract_cache::cache::refresher > Updating validator cache. There are 888 mixnodes and 105 gateways
2023-12-12T14:31:56.291Z INFO nym_api::node_status_api::cache::refresher > Updating node status cache
```
~~~
## Automation
You will most likely want to automate your validator restarting if your server reboots. Checkout the [maintenance page](./maintenance.md) for an example `service` file.
@@ -1,299 +0,0 @@
# Automatic Node Upgrade: Nymvisor Setup and Usage
> The Nymvisor binary was built in the [building nym](../binaries/building-nym.md) section. If you haven't yet built Nym and want to run the code, go there first. You can build just Nymvisor with `cargo build --release --bin nymvisor`.
> Any syntax in `<>` brackets is a user's unique variable. Exchange with a corresponding name without the `<>` brackets.
## What is Nymvisor?
Nymvisor is a process manager for Nym binaries that monitors the Nym release information for any newly released binaries. If it detects any changes, Nymvisor can automatically download the binary, stop the current binary, switch from the old binary to the new one, and finally restart the underlying process with the new binary.
In essence, it tries to mirror the behaviour of [Cosmovisor](https://github.com/cosmos/cosmos-sdk/tree/main/tools/cosmovisor), a tool used by Cosmos blockchain operators for managing/automating chain upgrades. Nymvisor, however, introduces some Nym-specific changes since, for example, upgrade information is obtained from our GitHub [releases page](https://github.com/nymtech/nym/releases) instead of (in the case of Cosmos blockchains) governance proposals.
You can use Nymvisor to automate the upgrades of the following binaries:
* `nym-api`
* `nym-mixnode`
* `nym-gateway`
* `nym-network-requester`
* `nym-client`
* `nym-socks5-client`
```admonish warning
Nymvisor is an early and experimental software. Users should use it at their own risk.
```
## Current version
```
<!-- cmdrun ../../../../target/release/nymvisor --version | grep "Build Version" | cut -b 21-26 -->
```
## Preliminary steps
You need to have at least one Mixnet node / client / Nym API instance already set up on the **same VPS** that you wish to run Nymvisor on.
> Using Nymvisor presumes your VPS is running an operating system that is compatible with the pre-compiled binaries avaliable on the [Github releases page](https://github.com/nymtech/nym/releases). If you're not, then until we're packaging for a greater variety of operating systems, you're stuck with [manually upgrading your node](manual-upgrade.md).
## Setup and Usage
### Viewing command help
You can check that your binaries are properly compiled with:
```
./nymvisor --help
```
Which should return a list of all available commands.
~~~admonish example collapsible=true title="Console output"
```
<!-- cmdrun ../../../../target/release/nymvisor --help -->
```
~~~
You can also check the various arguments required for individual commands with:
```
./nymvisor <COMMAND> --help
```
### Initialising your Nymvisor Instance
> This example will use the Mix Node binary as an example - however replacing `nym-mixnode` with any other supported binary will work the same.
Initialise your Nymvisor instance with the following command. You must initialise Nymvisor with the binary you wish to add upgrades for:
```
./nymvisor init --daemon-home ~/.nym/<NODE_TYPE>/<NODE_ID> <PATH_TO_NODE_BINARY>
```
Where the value of `--daemon-home` might be `~/.nym/mixnodes/my-node` and `<PATH_TO_NODE_BINARY>` might be `/home/my_user/nym/target/release/nym-mixnode`, or wherever your node binary is located.
~~~admonish example collapsible=true title="Console output"
```
<!-- cmdrun ../../../../target/release/nymvisor init --daemon-home ~/.nym/mixnodes/my-node ../../../../target/release/nym-mixnode | tail -20 -->
```
~~~
By default this will create config files at `~/.nym/nymvisors/instances/<NODE_TYPE>-default/config/config.toml` as shown in the console output above. For config options look at the different `--flags` available, or the [environment variables](nymvisor-upgrade.md#environment-variables) section below.
### Running your Nymvisor Instance
Nymvisor acts as a wrapper around the specified node process - it has to do this in order to be able to pause and restart this process. As such, you need to run your node _via_ Nymvisor!
The interface to the `nymvisor run <ARGS>` command is quite simple. Any argument passed after the `run` command will be passed directly to the underlying daemon, for example: `nymvisor run run --id my-mixnode` will run the `$DAEMON_NAME run --id my-mixnode` command (where `DAEMON_NAME` is the name of the binary itself (e.g. `nym-api`, `nym-mixnode`, etc.)).
`run` Nymvisor and start your node via the following command. Make sure to stop any existing node before running this command.
```
./nymvisor run run --id <NODE_ID>
```
~~~admonish example collapsible=true title="Console output"
```
<!-- cmdrun ../../../../target/release/nymvisor run run --id my-node -->
```
~~~
Nymvisor will now manage your node process (for an in-depth overview of this command check the [in-depth command information](./nymvisor-upgrade.md#commands-in-depth) below). It will periodically poll [this endpoint](https://nymtech.net/.wellknown/nym-mixnode/upgrade-info.json) (replace `nym-mixnode` with whatever node you may actually be running via Nymvisor) and check for a new `version` of the binary it is watching. If this exists, it will then, using the information there:
* pause your node process
* grab the new binary (`version`)
* verify it against the provided `checksum`
* perform a data backup of the existing node
* replace the old binary with the new one
* restart the process
And that's it! Check the [maintenance page](./maintenance.md#for-nymvisor) for information on Nymvisor process maintenance and automation, and you can find more in-depth information about the various aspects of Nymvisor such as what happens [under the hood](#commands-in-depth) for various commands.
### Creating an Adhoc Upgrade
`nymvisor add-upgrade <PATH_TO_EXECUTABLE> --upgrade-name=<NAME> --arg1=value1 --arg2=value2 ...` can be used to amend an existing `upgrade-plan.json` by creating new entries or to add an executable to an existing scheduled upgrade so that it would not have to be downloaded.
>Generally users **will not have to use this command**. Situations in which this command might be used are:
> - an adhoc upgrade if e.g. a patched version of a binary was required
> - if a user doesn't trust the verification process of Nymvisor's pipeline and wishes to build/verify the binary themselves before using Nymvisor to perform the upgrade
> - if a user isn't using a currently supported operating system and needs to manually specify a binary they have built themselves
Similarly to `init`, `add-upgrade` requires a positional argument specifying a valid path to the upgrade binary. Furthermore, the `--upgrade-name` keyword argument must be set in order to declare the upgrade name. The remaining arguments are optional. They include:
- `--force` - if specified, will allow Nymvisor to overwrite existing upgrade binary / `upgrade-info.json` files if they already exist
- `--add-binary` - indicate that this command should only add binary to an existing scheduled upgrade
- `--now` - if specified will force the upgrade to be performed immediately (technically not 'immediately' within few seconds). It can't be specified alongside either `--upgrade-time` or `--upgrade-delay` arguments
- `--publish-date` - if a new `upgrade-info.json` file is going to be created, this argument will specify the `publish_date` metadata field. Otherwise, the current time will be used. The [RFC3339 datetime](https://www.rfc-editor.org/rfc/rfc3339) format is expected
- `--upgrade-time` - specifies the time at which the provided upgrade will be performed (RFC3339 formatted). If left unset, the upgrade will be performed in 15 minutes. It can't be specified alongside either `--now` or `--upgrade-delay` arguments.
- `--upgrade-delay` - specifies delay until the provided upgrade is going to get performed. If let unset, the upgrade will be performed in 15 minutes. It can't be specified alongside either `--upgrade_time` or `--now` arguments.
## Config
The output format of `nymvisor config` can be further configured with `--output` argument. By default a human-readable text representation is used:
```
id: nym-mixnode-default
daemon name: nym-mixnode
daemon home: /home/nym/.nym/mixnodes/my-mixnode
upstream base upgrade url: https://nymtech.net/.wellknown/
disable nymvisor logs: false
CUSTOM upgrade data directory ""
upstream absolute upgrade url: ""
allow binaries download: true
enforce download checksum: true
restart after upgrade: true
restart on failure: false
on failure restart delay: 10s
max startup failures: 10
startup period duration: 2m
shutdown grace period: 10s
CUSTOM backup data directory ""
UNSAFE skip backups false
```
Adding `--output=json` would format the same data into JSON which can be more easily parsed programmatically to e.g. pipe the output into `jq` for further processing.
```
nymvisor config --output=json
```
outputs:
```
{"nymvisor":{"id":"nym-mixnode-default","upstream_base_upgrade_url":"https://nymtech.net/.wellknown/","upstream_polling_rate":"1h","disable_logs":false,"upgrade_data_directory":null},"daemon":{"name":"nym-mixnode","home":"/home/nym/.nym/mixnodes/my-mixnode","absolute_upstream_upgrade_url":null,"allow_binaries_download":true,"enforce_download_checksum":true,"restart_after_upgrade":true,"restart_on_failure":false,"failure_restart_delay":"10s","max_startup_failures":10,"startup_period_duration":"2m","shutdown_grace_period":"10s","backup_data_directory":null,"unsafe_skip_backup":false}}
```
## CLI Overview
Command options are:
- `help`, `--help`, or `-h` - Output Nymvisor help information and display the available commands.
- `config` - Display the current Nymvisor configuration, that means displaying the current configuration file that might have been overridden with environment variables value that Nymvisor is using.
- `init` - Generate a `config.toml` file for this instance of Nymvisor that will use the provided arguments alongside any environmental variables that are set.
- `add-upgrade` - Add an upgrade manually to Nymvisor. This command allows you to easily add the binary corresponding to an upgrade or amend the existing `upgrade-plan.json` whilst creating new `upgrade-info.json` file.
- `build-info` - Output the build information.
- `daemon-build-info` - Output the build information of the current binary used by the associated daemon.
- `run` - Run the configured binary using the rest of the provided arguments.
- `-V` or `--version` - Output the Nymvisor version
Similarly to other Nym binaries, Nymvisor supports a global `--config-env-file` or `-c` flag that allows specifying path to a `.env` file defining any relevant environmental variables that are going to be applied to any of the Nymvisor commands as described in the [Environment section](./nymvisor-upgrade.md#environment-variables).
For commands that depend on Nymvisor config file (i.e. all but `init`), the configuration file is loaded as follows:
- if available, reading `$NYMVISOR_CONFIG_PATH`
- otherwise, if `$NYMVISOR_ID` is set, a default path will be used, i.e. `$HOME/.nym/nymvisors/instances/$NYMVISOR_ID/config/config.toml`
- finally, if there's only a single `nymvisor` instance instantiated (as defined by directories in `$HOME/.nym/nymvisors/instances`), that one will be loaded
- if all of the above fails, an error is returned
Nymvisor attempts to load the file from the derived path. If it fails, it attempts to use one of the older schemas to and upgrade it as it goes, the loaded configuration is then overridden with any value that might have been set in the environment.
## Environment Variables
> Please note environmental variables take precedence over any arguments passed, i.e. if one were to specify `--daemon_home="/foo"` and set `DAEMON_HOME="bar"`, the value of `"bar"` would end up being used.
For any of its commands as described in [CLI Overview section](./nymvisor-upgrade.md#cli-overview), Nymvisor reads its configuration from the following environment variables:
- `NYMVISOR_ID` is the human-readable identifier of the particular Nymvisor instance.
- `NYMVISOR_CONFIG_PATH` is used to manually override path to the configuration file of the Nymvisor instance.
- `NYMVISOR_UPSTREAM_BASE_UPGRADE_URL` (defaults to https://nymtech.net/.wellknown/) is the base url of the upstream source for obtaining upgrade information for the daemon. It will be used fo constructing the full url, i.e. `$NYMVISOR_UPSTREAM_BASE_UPGRADE_URL/$DAEMON_NAME/upgrade-info.json`.
- `NYMVISOR_UPSTREAM_POLLING_RATE` (defaults to 1h) is polling rate the upstream url for upgrade information.
- `NYMVISOR_DISABLE_LOGS` (defaults to `false`). If set to `true`, this will disable Nymvisor logs (but not the underlying process) completely.
- `NYMVISOR_UPGRADE_DATA_DIRECTORY` is the custom directory for upgrade data - binaries and upgrade plans. If not set, the global Nymvisors' data directory will be used instead.
- `DAEMON_NAME` is the name of the binary itself (e.g. `nym-api`, `nym-mixnode`, etc.).
- `DAEMON_HOME` is the location where the `nymvisor/` directory is kept that contains the auxiliary files associated with the underlying daemon instance, such as any backups or current version information, e.g. `$HOME/.nym/nym-api/my-nym-api`, `$HOME/.nym/mixnodes/my-mixnode`, etc.
- `DAEMON_ABSOLUTE_UPSTREAM_UPGRADE_URL` is the absolute (i.e. the full url) upstream source for upgrade plans for this daemon. The url has to point to an endpoint containing a valid `UpgradeInfo` json file. If set it takes precedence over `NYMVISOR_UPSTREAM_BASE_UPGRADE_URL`.
- `DAEMON_ALLOW_BINARIES_DOWNLOAD` (defaults to `true`), if set to `true`, it will enable auto-downloading of new binaries (as declared by urls in corresponding `upgrade-info.json` files). For security reasons one might wish to disable it and instead manually provide binaries by either placing them in the appropriate directory or by invoking `add-upgrade` command.
- `DAEMON_ENFORCE_DOWNLOAD_CHECKSUM` (defaults to `true`), if set to `true` Nymvisor will require that a checksum is provided in the upgrade plan for the upgrade binary to be downloaded. If disabled, Nymvisor will not require a checksum to be provided, but still check the checksum if one is provided.
- `DAEMON_RESTART_AFTER_UPGRADE` (defaults to `true`), if set to `true` Nymvisor will restart the subprocess with the same command-line arguments and flags (but with the new binary) after a successful upgrade. Otherwise (`false`), Nymvisor stops running after an upgrade and requires the system administrator to manually restart it. **Note restart is only after the upgrade and does not auto-restart the subprocess after an error occurs.** That is controlled via `DAEMON_RESTART_ON_FAILURE`.
- `DAEMON_RESTART_ON_FAILURE` (defaults to `true`), if set to `true`, Nymvisor will restart the subprocess with the same command-line arguments and flags if it has terminated with a non-zero exit code.
- `DAEMON_FAILURE_RESTART_DELAY` (defaults to 10s), if `DAEMON_RESTART_ON_FAILURE` is set to `true`, this will specify a delay between the process shutdown (with a non-zero exit code) and it being restarted.
- `DAEMON_MAX_STARTUP_FAILURES` (defaults to 10) if `DAEMON_RESTART_ON_FAILURE` is set to `true`, this defines the maximum number of startup failures the subprocess can experience in a quick succession before no further restarts will be attempted and Nymvisor will terminate.
- `DAEMON_STARTUP_PERIOD_DURATION` (defaults to 120s) if `DAEMON_RESTART_ON_FAILURE` is set to `true`, this defines the length of time during which the subprocess is still considered to be in the startup phase when its failures are going to be counted towards the limit defined in `DAEMON_MAX_STARTUP_FAILURES`.
- `DAEMON_SHUTDOWN_GRACE_PERIOD` (defaults to 10s), specifies the amount of time Nymvisor is willing to wait for the subprocess to undergo graceful shutdown after receiving an interrupt before it sends a kill signal.
- `DAEMON_BACKUP_DATA_DIRECTORY` specifies custom backup directory for daemon data. If not set, `DAEMON_HOME/nymvisor/backups` is used instead.
- `DAEMON_UNSAFE_SKIP_BACKUP` (defaults to `false`), if set to `true`, all upgrades will be performed directly without performing any backups. Otherwise (`false`), Nymvisor will back up the contents of `DAEMON_HOME` before trying the upgrade.
## Dir structure
The folder structure of Nymvisor is heavily inspired by Cosmovisor, but with some notable changes to accommodate our binaries having possibly multiple instances due to their different `--id` flags. The data is spread through three main directories:
- in a global `nymvisors` data directory shared by all Nymvisor instances (default: `$HOME/.nym/nymvisors/data`) that contains daemon upgrade plans, binaries and upgrades histories. It includes a subdirectory for each version of the application (i.e. `genesis` or `upgrades<name>`). Within each subdirectory is the application binary (i.e. `bin/$DAEMON_NAME`), the associated `upgrade-info.json` and any additional auxiliary files associated with each binary. `current` is a symbolic link to the currently active directory (i.e. `genesis` or `upgrades/<NAME>`)
- in a home directory of a particular `nymvisor` instance (e.g. `$HOME/.nym/nymvisors/instances/<nymvisor-instance-id>/`). It includes subdirectories for its configuration file (i.e. `config/config.toml`), that preconfigures the instance, and for any additional persistent data that might be added in the future (i.e. `data`)
- in a `nymvisor` data directory inside the home directory of the managed daemon instance (default: `$HOME/.nym/$DAEMON_NAME/nymvisor`) that contains subdirectories for data backups (i.e. `backups/<name>`) and current version information (`current-version-info.json`)
A sample full structure looks as follows:
```
~/.nym
├── nymvisors
│ ├── instances
│ │ ├── <id1>
│ │ │ ├── config
│ │ │ │ └── config.toml
│ │ │ └── data
│ │ │ └── ...
│ │ └── <id2>
│ │ └── ...
│ └── data
│ ├── nym-api
│ │ ├── current -> genesis or upgrades/<name>
│ │ ├── genesis
│ │ │ ├── bin
│ │ │ │ └── nym-api
│ │ │ └── upgrade-info.json
│ │ ├── upgrades
│ │ │ └── <upgrade-name>
│ │ │ ├── bin
│ │ │ │ └── nym-api
│ │ │ └── upgrade-info.json
│ │ ├── upgrade-history.json
│ │ └── upgrade-plan.json
│ ├── nym-mixnode
│ │ └── ...
│ └── $DAEMON_NAME
│ └── ...
└── nym-api
├── <id1>
│ ├── config
│ │ └── <nym-api-config-data>
│ ├── data
│ │ └── <nym-api-data>
│ └── nymvisor
│ ├── backups
│ │ └── <upgrade-name>
│ │ └── ....
│ └── current-version-info.json
└── <id2>
└── ...
```
## Commands In-Depth
This section outlines what happens under the hood with the following commands:
### Init
`init` does the following:
- executes the `$DAEMON_NAME build-info` command on the daemon executable to check its validity and obtain its name
- creates the required directory structure:
- `$DAEMON_HOME/nymvisor` folder if it doesn't yet exist
- `$DAEMON_BACKUP_DATA_DIRECTORY` folder if it doesn't yet exist
- `$NYMVISOR_UPGRADE_DATA_DIRECTORY` folder if it doesn't yet exist
- `$NYMVISOR_UPGRADE_DATA_DIRECTORY/$DAEMON_NAME/genesis/bin` folder if it doesn't yet exist
- `$NYMVISOR_UPGRADE_DATA_DIRECTORY/$DAEMON_NAME/upgrades` folder if it doesn't yet exist
- copies the provided executable to `$NYMVISOR_UPGRADE_DATA_DIRECTORY/$DAEMON_NAME/genesis/bin/$DAEMON_NAME`
- generates initial `$NYMVISOR_UPGRADE_DATA_DIRECTORY/$DAEMON_NAME/genesis/upgrade-info.json` file based on the provided binary
- generates initial `$DAEMON_HOME/nymvisor/current-version-info.json` file based on the provided binary
- creates a `$NYMVISOR_UPGRADE_DATA_DIRECTORY/$DAEMON_NAME/current` symlink pointing to `$NYMVISOR_UPGRADE_DATA_DIRECTORY/$DAEMON_NAME/genesis`
- saves the Nymvisor instance's config file to `$NYMVISOR_CONFIG_PATH` and creates the full directory structure for the file
- outputs (to `stdout`) the full configuration used
> `nymvisor init` is specifically for initializing Nymvisor, and should **not** be confused with a daemon's `init` command - such as `nym-mixnode init` (e.g. `cosmovisor run init`).
### Run
`nymvisor run` is a lightweight wrapper around the underlying daemon. It uses only a single thread and spawns three simple tasks:
- an upstream poller that checks the upstream source (as defined by `DAEMON_ABSOLUTE_UPSTREAM_UPGRADE_URL` or derived from `NYMVISOR_UPSTREAM_BASE_UPGRADE_URL`) for any recently released upgrades. It then creates appropriate `upgrade-info.json` file and updates the `upgrade-plan.json`
- a file watcher for the `upgrade-plan.json` file that can notify the main run loop of upgrades that were added by either the above upstream poller task or via the `add-upgrade` command,
- the daemon run loop that:
- runs the `DAEMON_NAME` with the provided arguments until:
- it completes the execution (with any exit code),
- Nymvisor receives a `SIGINT`, `SIGTERM` or `SIGQUIT`,
- a new upgrade is scheduled to be performed (by other task watching for changes in `upgrade-plan.json` and waiting until the `upgrade_time`,
- if `DAEMON_UNSAFE_SKIP_BACKUP` is not set to `true`, it backups the content of `DAEMON_HOME` directory,
- performs the binary upgrade by:
- creating a temporary, exclusive and non-blocking, `upgrade.lock` file for the `DAEMON_NAME`. `flock` with `LOCK_EX | LOCK_NB` is used for that purpose. The file is created in case users didn't read any warnings and attempted to run multiple instances of `nymvisor` managing the same `DAEMON_NAME`,
- downloading the upgrade binary for the runners architecture using one of the urls defined in `upgrade-info.json`. Note, however, that this is only done if the binary associated with the `<UPGRADE-NAME>` does not already exist and `DAEMON_ALLOW_DOWNLOAD_BINARIES` is set to `true`,
- if the binary has been downloaded and `DAEMON_ENFORCE_DOWNLOAD_CHECKSUM` is set to true, the file checksum is verified using the specified algorithm,
- verifying the upgrade binary - checking if it's a valid executable with expected `build-info`. Note that this will also set `a+x` bits on the file if those permissions have not already been set,
- removing the queued upgrade from `upgrade-plan.json`,
- inserting new upgrade into the `upgrade-history.json`,
- updating the `current-version-info.json`,
- updating the `$NYMVISOR_UPGRADE_DATA_DIRECTORY/$DAEMON_NAME/current` symlink to the upgrade directory,
- removing the `upgrade.lock` file.
- the above loop is repeated if either:
- the daemon has crashed and `DAEMON_MAX_STARTUP_FAILURES` has not been reached yet,
- the daemon has successfully been upgraded, `DAEMON_RESTART_AFTER_UPGRADE` has been set to `true` and the manual flag on the performed upgrade has been set to `false`.
### Add-Upgrade
`nymvisor add-upgrade` does the following:
- executes the `$DAEMON_NAME build-info` command on the daemon executable to check its validity and obtain its name
- attempts to load existing `upgrade-info.json` for the provided `<upgrade-name>`. If it already exists and neither `--force` nor `--add-binary` was specified, Nymvisor will terminate
- checks if `upgrades/<upgrade-name>/$DAEMON_NAME` binary already exists. If it does and `--force` flag was not specified, Nymvisor will terminate the provided upgrade binary is copied to its appropriate location
- if applicable, new `upgrade-info.json` is created and written to its appropriate location
- `upgrade-plan.json` is updated with the new upgrade details. If there's an active Nymvisor instance running, this change will be detected to initialise upgrade process
@@ -438,6 +438,7 @@ With above command you can specify the `gpg` key last numbers (as used in `keyba
### Automating your validator with systemd
You will most likely want to automate your validator restarting if your server reboots. Checkout the [maintenance page](./maintenance.md#systemd) with a quick tutorial.
### Setting the ulimit
Linux machines limit how many open files a user is allowed to have. This is called a `ulimit`. We need to set it to a higher value than the default 1024. Follow the instructions in the [maintenance page](./maintenance.md#Setting-the-ulimit) to change the `ulimit` value for validators.
-23
View File
@@ -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 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "explorer-api"
version = "1.1.32"
version = "1.1.31"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@@ -8,7 +8,7 @@ edition = "2021"
[dependencies]
chrono = { version = "0.4.31", features = ["serde"] }
clap = { workspace = true, features = ["cargo", "derive"] }
dotenvy = { workspace = true }
dotenvy = "0.15.6"
humantime-serde = "1.0"
isocountry = "0.3.2"
itertools = "0.10.3"
+2 -2
View File
@@ -4,7 +4,7 @@
[package]
name = "nym-gateway"
license = "GPL-3"
version = "1.1.32"
version = "1.1.31"
authors = [
"Dave Hrycyszyn <futurechimp@users.noreply.github.com>",
"Jędrzej Stuczyński <andrew@nymtech.net>",
@@ -80,7 +80,7 @@ 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 }
defguard_wireguard_rs = { git = "https://github.com/DefGuard/wireguard-rs", rev = "d40df5c4e598918253682c42c4aa189d0ec2499a", optional = true }
[dev-dependencies]
tower = "0.4.13"
-57
View File
@@ -103,50 +103,10 @@ fn load_network_requester_details(
)
}
fn load_ip_packet_router_details(
config: &Config,
ip_packet_router_config: &nym_ip_packet_router::Config,
) -> Result<api_requests::v1::ip_packet_router::models::IpPacketRouter, GatewayError> {
let identity_public_key: identity::PublicKey = load_public_key(
&ip_packet_router_config
.storage_paths
.common_paths
.keys
.public_identity_key_file,
"ip packet router identity",
)?;
let dh_public_key: encryption::PublicKey = load_public_key(
&ip_packet_router_config
.storage_paths
.common_paths
.keys
.public_encryption_key_file,
"ip packet router diffie hellman",
)?;
let gateway_identity_public_key: identity::PublicKey = load_public_key(
&config.storage_paths.keys.public_identity_key_file,
"gateway identity",
)?;
Ok(api_requests::v1::ip_packet_router::models::IpPacketRouter {
encoded_identity_key: identity_public_key.to_base58_string(),
encoded_x25519_key: dh_public_key.to_base58_string(),
address: Recipient::new(
identity_public_key,
dh_public_key,
gateway_identity_public_key,
)
.to_string(),
})
}
pub(crate) struct HttpApiBuilder<'a> {
gateway_config: &'a Config,
network_requester_config: Option<&'a nym_network_requester::Config>,
exit_policy: Option<UsedExitPolicy>,
ip_packet_router_config: Option<&'a nym_ip_packet_router::Config>,
identity_keypair: &'a identity::KeyPair,
// TODO: this should be a wg specific key and not re-used sphinx
@@ -164,7 +124,6 @@ impl<'a> HttpApiBuilder<'a> {
HttpApiBuilder {
gateway_config,
network_requester_config: None,
ip_packet_router_config: None,
exit_policy: None,
identity_keypair,
sphinx_keypair,
@@ -228,15 +187,6 @@ impl<'a> HttpApiBuilder<'a> {
self
}
#[must_use]
pub(crate) fn with_maybe_ip_packet_router(
mut self,
ip_packet_router_config: Option<&'a nym_ip_packet_router::Config>,
) -> Self {
self.ip_packet_router_config = ip_packet_router_config;
self
}
#[must_use]
pub(crate) fn with_wireguard_client_registry(
mut self,
@@ -275,13 +225,6 @@ impl<'a> HttpApiBuilder<'a> {
}
}
if let Some(ipr_config) = self.ip_packet_router_config {
config = config.with_ip_packet_router(load_ip_packet_router_details(
self.gateway_config,
ipr_config,
)?);
}
let wireguard_private_network = IpNetwork::new(
IpAddr::from(Ipv4Addr::new(10, 1, 0, 0)),
self.gateway_config.wireguard.private_network_prefix,
+1 -38
View File
@@ -8,9 +8,7 @@ use nym_crypto::asymmetric::{encryption, identity};
use nym_pemstore::traits::{PemStorableKey, PemStorableKeyPair};
use nym_pemstore::KeyPairPath;
use nym_sphinx::addressing::clients::Recipient;
use nym_types::gateway::{
GatewayIpPacketRouterDetails, GatewayNetworkRequesterDetails, GatewayNodeDetailsResponse,
};
use nym_types::gateway::{GatewayNetworkRequesterDetails, GatewayNodeDetailsResponse};
use std::path::Path;
fn display_maybe_path<P: AsRef<Path>>(path: Option<P>) -> String {
@@ -73,40 +71,6 @@ pub(crate) fn node_details(config: &Config) -> Result<GatewayNodeDetailsResponse
None
};
let ip_packet_router = if let Some(nr_cfg_path) = &config.storage_paths.ip_packet_router_config
{
let cfg = load_ip_packet_router_config(&config.gateway.id, nr_cfg_path)?;
let nr_identity_public_key: identity::PublicKey = load_public_key(
&cfg.storage_paths.common_paths.keys.public_identity_key_file,
"ip packet router identity",
)?;
let nr_encryption_key: encryption::PublicKey = load_public_key(
&cfg.storage_paths
.common_paths
.keys
.public_encryption_key_file,
"ip packet router encryption",
)?;
let address = Recipient::new(
nr_identity_public_key,
nr_encryption_key,
gateway_identity_public_key,
);
Some(GatewayIpPacketRouterDetails {
enabled: config.ip_packet_router.enabled,
identity_key: nr_identity_public_key.to_base58_string(),
encryption_key: nr_encryption_key.to_base58_string(),
address: address.to_string(),
config_path: display_path(nr_cfg_path),
})
} else {
None
};
Ok(GatewayNodeDetailsResponse {
identity_key: gateway_identity_public_key.to_base58_string(),
sphinx_key: gateway_sphinx_public_key.to_base58_string(),
@@ -116,7 +80,6 @@ pub(crate) fn node_details(config: &Config) -> Result<GatewayNodeDetailsResponse
config_path: display_maybe_path(config.save_path.as_ref()),
data_store: display_path(&config.storage_paths.clients_storage),
network_requester,
ip_packet_router,
})
}
+18 -26
View File
@@ -22,7 +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::*;
@@ -202,11 +201,12 @@ impl<St> Gateway<St> {
mixnet_handling::Listener::new(listening_address, shutdown).start(connection_handler);
}
#[cfg(feature = "wireguard")]
#[cfg(target_os = "linux")]
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
}
@@ -347,19 +347,19 @@ impl<St> Gateway<St> {
// TODO: well, wire it up internally to gateway traffic, shutdowns, etc.
let (on_start_tx, on_start_rx) = oneshot::channel();
let mut ip_packet_router =
nym_ip_packet_router::IpPacketRouter::new(ip_opts.config.clone())
let mut ip_builder =
nym_ip_packet_router::IpPacketRouterBuilder::new(ip_opts.config.clone())
.with_shutdown(shutdown)
.with_custom_gateway_transceiver(Box::new(transceiver))
.with_wait_for_gateway(true)
.with_on_start(on_start_tx);
if let Some(custom_mixnet) = &ip_opts.custom_mixnet_path {
ip_packet_router = ip_packet_router.with_stored_topology(custom_mixnet)?
ip_builder = ip_builder.with_stored_topology(custom_mixnet)?
}
tokio::spawn(async move {
if let Err(err) = ip_packet_router.run_service_provider().await {
if let Err(err) = ip_builder.run_service_provider().await {
// no need to panic as we have passed a task client to the ip packet router so
// we're most likely already in the process of shutting down
error!("ip packet router has failed: {err}")
@@ -477,13 +477,6 @@ impl<St> Gateway<St> {
});
}
self.start_client_websocket_listener(
mix_forwarding_channel.clone(),
active_clients_store.clone(),
shutdown.subscribe().named("websocket::Listener"),
Arc::new(coconut_verifier),
);
let nr_request_filter = if self.config.network_requester.enabled {
let embedded_nr = self
.start_network_requester(
@@ -504,7 +497,7 @@ impl<St> Gateway<St> {
if self.config.ip_packet_router.enabled {
let embedded_ip_sp = self
.start_ip_packet_router(
mix_forwarding_channel,
mix_forwarding_channel.clone(),
shutdown.subscribe().named("ip_service_provider"),
)
.await?;
@@ -519,16 +512,19 @@ impl<St> Gateway<St> {
.with_wireguard_client_registry(self.client_registry.clone())
.with_maybe_network_requester(self.network_requester_opts.as_ref().map(|o| &o.config))
.with_maybe_network_request_filter(nr_request_filter)
.with_maybe_ip_packet_router(self.ip_packet_router_opts.as_ref().map(|o| &o.config))
.start(shutdown.subscribe().named("http-api"))?;
// 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
.start_wireguard(shutdown.subscribe().named("wireguard"))
self.start_client_websocket_listener(
mix_forwarding_channel,
active_clients_store,
shutdown.subscribe().named("websocket::Listener"),
Arc::new(coconut_verifier),
);
#[cfg(target_os = "linux")]
self.start_wireguard(shutdown.subscribe().named("wireguard"))
.await
.ok();
.expect("Could not start wireguard");
info!("Finished nym gateway startup procedure - it should now be able to receive mix and client traffic!");
@@ -536,10 +532,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(())
}
}
+1 -1
View File
@@ -4,7 +4,7 @@
[package]
name = "nym-mixnode"
license = "GPL-3"
version = "1.1.34"
version = "1.1.33"
authors = [
"Dave Hrycyszyn <futurechimp@users.noreply.github.com>",
"Jędrzej Stuczyński <andrew@nymtech.net>",
+2 -2
View File
@@ -4,7 +4,7 @@
[package]
name = "nym-api"
license = "GPL-3"
version = "1.1.34"
version = "1.1.33"
authors = [
"Dave Hrycyszyn <futurechimp@users.noreply.github.com>",
"Jędrzej Stuczyński <andrew@nymtech.net>",
@@ -37,7 +37,7 @@ serde = { workspace = true }
serde_json = { workspace = true }
tap = "1.0"
thiserror = { workspace = true }
time = { workspace = true, features = ["serde-human-readable", "parsing"] }
time = { version = "0.3.14", features = ["serde-human-readable", "parsing"] }
tokio = { version = "1.24.1", features = [
"rt-multi-thread",
"macros",
-9
View File
@@ -366,9 +366,6 @@ pub struct NymNodeDescription {
#[serde(default)]
pub network_requester: Option<NetworkRequesterDetails>,
#[serde(default)]
pub ip_packet_router: Option<IpPacketRouterDetails>,
// for now we only care about their ws/wss situation, nothing more
pub mixnet_websockets: WebSockets,
}
@@ -396,9 +393,3 @@ pub struct NetworkRequesterDetails {
/// flag indicating whether this network requester uses the exit policy rather than the deprecated allow list
pub uses_exit_policy: bool,
}
#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema)]
pub struct IpPacketRouterDetails {
/// address of the embedded ip packet router
pub address: String,
}
+17 -19
View File
@@ -57,14 +57,14 @@ impl<R: RngCore + CryptoRng + Clone> DkgController<R> {
&config.storage_paths.decryption_key_path,
&config.storage_paths.public_key_with_proof_path,
))?;
// if let Ok(coconut_keypair_value) =
// nym_pemstore::load_keypair(&nym_pemstore::KeyPairPath::new(
// &config.storage_paths.secret_key_path,
// &config.storage_paths.verification_key_path,
// ))
// {
// coconut_keypair.set(Some(coconut_keypair_value)).await;
// }
if let Ok(coconut_keypair_value) =
nym_pemstore::load_keypair(&nym_pemstore::KeyPairPath::new(
&config.storage_paths.secret_key_path,
&config.storage_paths.verification_key_path,
))
{
coconut_keypair.set(Some(coconut_keypair_value)).await;
}
let persistent_state =
PersistentState::load_from_file(&config.storage_paths.dkg_persistent_state_path)
.unwrap_or_default();
@@ -186,17 +186,15 @@ impl<R: RngCore + CryptoRng + Clone> DkgController<R> {
}
pub(crate) async fn run(mut self, mut shutdown: TaskClient) {
warn!("ignoring the dkg epochs!");
shutdown.mark_as_success();
// let mut interval = interval(self.polling_rate);
// while !shutdown.is_shutdown() {
// tokio::select! {
// _ = interval.tick() => self.handle_epoch_state().await,
// _ = shutdown.recv() => {
// trace!("DkgController: Received shutdown");
// }
// }
// }
let mut interval = interval(self.polling_rate);
while !shutdown.is_shutdown() {
tokio::select! {
_ = interval.tick() => self.handle_epoch_state().await,
_ = shutdown.recv() => {
trace!("DkgController: Received shutdown");
}
}
}
}
// TODO: can we make it non-async? it seems we'd have to modify `coconut_keypair.set(coconut_keypair_value)` in new
@@ -24,15 +24,7 @@ struct MixnodeWithStakeAndPerformance {
impl MixnodeWithStakeAndPerformance {
fn to_selection_weight(&self) -> f64 {
let scaled_performance = match self.performance.checked_pow(20) {
Ok(perf) => perf,
Err(overflow) => {
warn!("the node's performance ({}) has overflow while scaling it by the factor of 20: {overflow}. Setting it to 0 instead.", self.performance);
return 0.;
}
};
let scaled_stake = self.total_stake * scaled_performance;
let scaled_stake = self.total_stake * self.performance;
stake_to_f64(scaled_stake)
}
}
-8
View File
@@ -80,14 +80,6 @@ async fn start_nym_api_tasks(
let network_details = NetworkDetails::new(connected_nyxd.to_string(), nym_network_details);
let coconut_keypair = coconut::keypair::KeyPair::new();
let keys = nym_pemstore::load_keypair(&nym_pemstore::KeyPairPath::new(
&config.coconut_signer.storage_paths.secret_key_path,
&config.coconut_signer.storage_paths.verification_key_path,
))
.expect("failed to load coconut keys");
coconut_keypair.set(Some(keys)).await;
info!("set coconut keys");
// let's build our rocket!
let rocket = http::setup_rocket(
+1 -12
View File
@@ -7,9 +7,7 @@ use crate::support::caching::refresher::{CacheItemProvider, CacheRefresher};
use crate::support::config;
use crate::support::config::DEFAULT_NODE_DESCRIBE_BATCH_SIZE;
use futures_util::{stream, StreamExt};
use nym_api_requests::models::{
IpPacketRouterDetails, NetworkRequesterDetails, NymNodeDescription,
};
use nym_api_requests::models::{NetworkRequesterDetails, NymNodeDescription};
use nym_config::defaults::{mainnet, DEFAULT_NYM_NODE_HTTP_PORT};
use nym_contracts_common::IdentityKey;
use nym_mixnet_contract_common::Gateway;
@@ -172,19 +170,10 @@ async fn get_gateway_description(
None
};
let ip_packet_router = if let Ok(ipr) = client.get_ip_packet_router().await {
Some(IpPacketRouterDetails {
address: ipr.address,
})
} else {
None
};
let description = NymNodeDescription {
host_information: host_info.data,
build_information: build_info,
network_requester,
ip_packet_router,
mixnet_websockets: websockets,
};
+2 -2
View File
@@ -375,7 +375,7 @@ impl crate::coconut::client::Client for Client {
fee: Option<Fee>,
) -> Result<(), CoconutError> {
self.0
.write()
.read()
.await
.vote_proposal(proposal_id, vote_yes, fee)
.await?;
@@ -384,7 +384,7 @@ impl crate::coconut::client::Client for Client {
async fn execute_proposal(&self, proposal_id: u64) -> crate::coconut::error::Result<()> {
self.0
.write()
.read()
.await
.execute_proposal(proposal_id, None)
.await?;
+99 -30
View File
@@ -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"
@@ -1578,11 +1610,10 @@ dependencies = [
[[package]]
name = "deranged"
version = "0.3.9"
version = "0.3.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0f32d04922c60427da6f9fef14d042d9edddef64cb9d4ce0d64d0685fbeb1fd3"
checksum = "7684a49fb1af197853ef7b2ee694bc1f5b4179556f1e5710e1760c5db6f5e929"
dependencies = [
"powerfmt",
"serde",
]
@@ -3226,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"
@@ -3500,7 +3553,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ae926706ba42c425c9457121178330d75e273df2e82e28b758faf3de3a9acb9"
dependencies = [
"arrayref",
"blake2",
"blake2 0.8.1",
"chacha",
"keystream",
]
@@ -3717,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"
@@ -4698,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",
]
@@ -5292,12 +5362,6 @@ dependencies = [
"universal-hash",
]
[[package]]
name = "powerfmt"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"
[[package]]
name = "ppv-lite86"
version = "0.2.17"
@@ -5739,7 +5803,7 @@ dependencies = [
"libc",
"once_cell",
"spin 0.5.2",
"untrusted",
"untrusted 0.7.1",
"web-sys",
"winapi",
]
@@ -5895,7 +5959,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c7d5dece342910d9ba34d259310cae3e0154b873b35408b787b59bce53d34fe"
dependencies = [
"ring",
"untrusted",
"untrusted 0.7.1",
]
[[package]]
@@ -5978,7 +6042,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b362b83898e0e69f38515b82ee15aa80636befe47c3b6d3d89a911e78fc228ce"
dependencies = [
"ring",
"untrusted",
"untrusted 0.7.1",
]
[[package]]
@@ -5988,7 +6052,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d53dcdb7c9f8158937a7981b48accfd39a43af418591a5d008c7b22b5e1b7ca4"
dependencies = [
"ring",
"untrusted",
"untrusted 0.7.1",
]
[[package]]
@@ -6221,9 +6285,9 @@ dependencies = [
[[package]]
name = "serde"
version = "1.0.190"
version = "1.0.183"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "91d3c334ca1ee894a2c6f6ad698fe8c435b76d504b13d436f0685d648d6d96f7"
checksum = "32ac8da02677876d532745a130fc9d8e6edfa81a269b107c5b00829b91d8eb3c"
dependencies = [
"serde_derive",
]
@@ -6248,9 +6312,9 @@ dependencies = [
[[package]]
name = "serde_derive"
version = "1.0.190"
version = "1.0.183"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67c5609f394e5c2bd7fc51efda478004ea80ef42fee983d5c67a65e34f32c0e3"
checksum = "aafe972d60b0b9bee71a91b92fee2d4fb3c9d7e8f6b179aa99f27203d99a4816"
dependencies = [
"proc-macro2",
"quote",
@@ -6538,7 +6602,7 @@ checksum = "cc43eda802856ee82a7555c7b75ceb9e07451741c7a2f5f23d036020e01189d4"
dependencies = [
"aes 0.7.5",
"arrayref",
"blake2",
"blake2 0.8.1",
"bs58 0.4.0",
"byteorder",
"chacha",
@@ -7401,16 +7465,15 @@ dependencies = [
[[package]]
name = "time"
version = "0.3.30"
version = "0.3.25"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c4a34ab300f2dee6e562c10a046fc05e358b29f9bf92277f30c3c8d82275f6f5"
checksum = "b0fdd63d58b18d663fbdf70e049f00a22c8e42be082203be7f26589213cd75ea"
dependencies = [
"deranged",
"itoa 1.0.9",
"js-sys",
"libc",
"num_threads",
"powerfmt",
"serde",
"time-core",
"time-macros",
@@ -7418,15 +7481,15 @@ dependencies = [
[[package]]
name = "time-core"
version = "0.1.2"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ef927ca75afb808a4d64dd374f00a2adf8d0fcff8e7b184af886c3c87ec4a3f3"
checksum = "7300fbefb4dadc1af235a9cef3737cea692a9d97e1b9cbcd4ebdae6f8868e6fb"
[[package]]
name = "time-macros"
version = "0.2.15"
version = "0.2.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ad70d68dba9e1f8aceda7aa6711965dfec1cac869f311a51bd08b3a2ccbce20"
checksum = "eb71511c991639bb078fd5bf97757e03914361c48100d52878b8e52b46fb92cd"
dependencies = [
"time-core",
]
@@ -7819,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"
@@ -8169,7 +8238,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8e38c0608262c46d4a56202ebabdeb094cef7e560ca7a226c6bf055188aa4ea"
dependencies = [
"ring",
"untrusted",
"untrusted 0.7.1",
]
[[package]]
@@ -8179,7 +8248,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "07ecc0cd7cac091bf682ec5efa18b1cff79d617b84181f38b3951dbe135f607f"
dependencies = [
"ring",
"untrusted",
"untrusted 0.7.1",
]
[[package]]
@@ -8655,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",
]
@@ -8692,7 +8761,7 @@ dependencies = [
"futures-sink",
"futures-util",
"hex",
"nix",
"nix 0.26.2",
"once_cell",
"ordered-stream",
"rand 0.8.5",
@@ -11,7 +11,6 @@ use nym_bin_common::build_information::BinaryBuildInformationOwned;
use nym_wireguard_types::{ClientMessage, ClientRegistrationResponse};
use crate::api::v1::health::models::NodeHealth;
use crate::api::v1::ip_packet_router::models::IpPacketRouter;
use crate::api::v1::network_requester::exit_policy::models::UsedExitPolicy;
use crate::api::v1::network_requester::models::NetworkRequester;
pub use http_api_client::Client;
@@ -55,11 +54,6 @@ pub trait NymNodeApiClientExt: ApiClient {
.await
}
async fn get_ip_packet_router(&self) -> Result<IpPacketRouter, NymNodeApiClientError> {
self.get_json_from(routes::api::v1::ip_packet_router_absolute())
.await
}
async fn post_gateway_register_client(
&self,
client_message: &ClientMessage,

Some files were not shown because too many files have changed in this diff Show More