Compare commits

...

26 Commits

Author SHA1 Message Date
farbanas df4587be62 chore: whitespace 2023-01-17 15:47:46 +01:00
farbanas 58d15429de feat: change Github hosted ubuntu-20.04 runners for our own custom-runner-linux 2023-01-17 13:05:35 +01:00
farbanas ca8a6150c9 fix: moved the if step to the root of the job, removed unused workflows 2023-01-16 14:01:20 +01:00
Raphaël Walther f4fd08f64e Github Actions: add audit workflow on trigger 2023-01-16 11:25:28 +01:00
Fouad 78247b973b upgrade storybook to latest (#2840) 2023-01-16 09:49:08 +00:00
Jon Häggblad 6b52132501 gateway: don't shutdown on connection handler drop (#2848) 2023-01-16 10:31:01 +01:00
Raphaël Walther d2f33180e2 Github Actions: fix notifications 2023-01-16 09:40:05 +01:00
Jon Häggblad dc71f6e94d common: dedup and move banner to common/logging (#2846) 2023-01-16 08:32:35 +01:00
Raphaël Walther cc7161c113 Github Actions: fix notifications 2023-01-13 16:54:09 +01:00
Jędrzej Stuczyński bbb46ebd90 chore: upgrade tokio to 1.24.1 (+ tokio-util and tokio-stream) (#2843)
* updated 'tokio' to 1.24.1 in the whole codebase

* ibid for 'tokio-stream'

* ibid for 'tokio-util'

* Removed lock file from verify-signature example
2023-01-13 14:46:10 +00:00
Jon Häggblad bc3fd236d8 client-core: fix bug with force-register-gateway (#2844) 2023-01-13 15:43:29 +01:00
dependabot[bot] ea95288940 build(deps): bump minimatch from 3.0.4 to 3.1.2 in /testnet-faucet (#2775)
Bumps [minimatch](https://github.com/isaacs/minimatch) from 3.0.4 to 3.1.2.
- [Release notes](https://github.com/isaacs/minimatch/releases)
- [Changelog](https://github.com/isaacs/minimatch/blob/main/changelog.md)
- [Commits](https://github.com/isaacs/minimatch/compare/v3.0.4...v3.1.2)

---
updated-dependencies:
- dependency-name: minimatch
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-01-13 13:37:36 +00:00
dependabot[bot] b182ed6925 build(deps): bump luxon from 2.4.0 to 2.5.2 (#2792)
Bumps [luxon](https://github.com/moment/luxon) from 2.4.0 to 2.5.2.
- [Release notes](https://github.com/moment/luxon/releases)
- [Changelog](https://github.com/moment/luxon/blob/master/CHANGELOG.md)
- [Commits](https://github.com/moment/luxon/compare/2.4.0...2.5.2)

---
updated-dependencies:
- dependency-name: luxon
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-01-13 13:36:20 +00:00
Fouad 017c9d2504 upgrade tauri to 1.2.3 (#2842) 2023-01-13 13:34:56 +00:00
Jędrzej Stuczyński 50c7d717c0 chore: fixed clippy warnings from the nightly toolchain (#2838) 2023-01-13 13:16:47 +00:00
Jędrzej Stuczyński b473aeb3be Feature/gateway graceful shutdown (#2834)
* task dependency

* unifying some startup code and passing TaskClient around

* graceful shutdown handling for mix socket listener

* graceful shutdown handling for clients listener

* graceful shutdown handling for packet forwarding

* unified waiting for interrupt across binaries

* made 'validate_bech32_address_or_exit' into a function that returns proper Result

* printing formatted message on main error

* fixed failing test

* removed duplicate code that should have been gone ages ago

* ibid

* removed biased selection for authenticated handler

* minor refactoring to 'ensure_config_version_compatibility'
2023-01-13 11:56:37 +00:00
Fran Arbanas fe2e1c29a2 Merge pull request #2828 from nymtech/2811-fix-clippy-check-failing
[2811] Fix dependabot clippy-check fails
2023-01-13 10:28:26 +01:00
Fouad 2eee5195cc React / React DOM / Types upgrade to version 18 (#2830)
* new react and reactdom packages in wallet

* new react and reactdom packages in root

* new react and reactdom packages in nym connect

* new react and reactdom packages in root

* update react and reactdom for explorer

* react and react-dom upgrade for ts-packages

remove unused import

fix linting error

* use custom FC typing

move typings folder

* fix type error
2023-01-12 17:15:31 +00:00
Jon Häggblad 3bd4343a39 client-core: tidy by removing some allow dead_code (#2832) 2023-01-12 14:18:46 +01:00
Jon Häggblad 74feb065f9 outfox: fix some clippy warnings in tests (#2831) 2023-01-12 14:03:26 +01:00
Mark Sinclair 65b819c649 GitHub Actions: add directory to fix error on runners with read-only file systems 2023-01-12 12:52:31 +00:00
Jon Häggblad bd12305a68 client-core: add note about msg string 2023-01-12 12:35:40 +01:00
Jędrzej Stuczyński 5709c45a50 Feature/circulating supply (#2814)
* Fixed typo in node_status_cache constant

* ibid

* Moved some caching stuff around so I can see what depends on what

* Finishing merge of conflicted files

* Minor smoothing

* Got cache reads working for circ supply and refactored common cache

* Refactored nyxd client usages to make things bit more clear

* Moved caching support stuff into the support folder

* Moved storage code into support module

* Removed dead code

* Tweaks

* Handling cases a little more nicely in circulating supply api

* Renamed nymd_client to nyxd_client

* Pulled CacheNotification into the caching support module

* Pulled some domain-specific helpers out of cache refresher

* Moving some more helper methods out of the cache refresher

* Deleting unused code

* Extracted a few more functions out of the cache refresher

* A few comments as breadcrumbs

* Renaming the anemic "helpers" to "node_sets"

* Renaming the validator_cache module to nym_contract_cache

* Renaming nym contract cache stuff to make things clearer

* Renamging a few things in comments

* Renaming validator_cache to nym_contract_cache

* foomp

* Started refactoring http and cli

* Extracted cli arg parsing into its own module

* Cleanup

* Extracted start methods into various modules to clean main up

* WIP commit

* Build working, swagger not

* Fixed swagger docs metadata

* Removed log statement

* Circulating supply cache now working with simple logic

* Fixed up circulating supply method names

* Starting to work in some (wrong) constants

* Documented the cache

* Renaming circulating-supply route

* nym-api compiling after the rebasing

but most likely not fully working yet

* removed unused imports

* only starting RewardedSetUpdater if the config flag is set

* nym-api compiling with coconut feature

* removed redundant process_runner

* removed generic aspect of nym-api nyxd::Client

* signle entry point for starting nym_contract_cache

* do not eagerly grab instances of managed state

* inlining openapi route spec

* CirculatingSupplyResponse type

* fixed compilation of coconut tests

* calculating circulating supply based on mixmining reserve and vesting tokens

* separated different variants of caching intervals

* allow nym-api to specify address of the vesting contract

* fixed types export

* renamed the query on the vesting contract

* reorganised startup procedure and made all start methods independent from rocket

* cleaned up startup procedure for nym-api

* startup checks for rewarding permisssions

* updated changelog

* added config flag to control whether circulating supply should be updated

Co-authored-by: Dave Hrycyszyn <futurechimp@users.noreply.github.com>
2023-01-12 10:39:21 +00:00
Jon Häggblad a7f1242961 client-core: clean up gateway registration (#2827)
* client-core: clean up gateway registration

* client-core: tidy docs and clippy

* clients: tidy output
2023-01-12 11:35:34 +01:00
Jon Häggblad 8b14321c4a connect,wallet: make fern use same colors as env_pretty_logger (#2829) 2023-01-12 11:35:11 +01:00
farbanas dddc6eae57 fix: added continue-on-error for clippy-check since they fail on forked repositories due to permission errors which we won't solve 2023-01-12 10:45:27 +01:00
382 changed files with 3715 additions and 6036 deletions
+1 -1
View File
@@ -26,7 +26,7 @@ jobs:
path: .github/workflows/support-files/notifications/deny.message
notification:
needs: cargo-deny
runs-on: ubuntu-20.04
runs-on: custom-runner-linux
steps:
- name: Check out repository code
uses: actions/checkout@v2
+55
View File
@@ -0,0 +1,55 @@
name: Daily security audit
on: workflow_dispatch
jobs:
cargo-deny:
runs-on: ubuntu-20.04
steps:
- name: Checkout repository code
uses: actions/checkout@v2
- name: Install rust toolchain
uses: actions-rs/toolchain@v1
with:
toolchain: stable
- name: Install cargo deny
run: cargo install --locked cargo-deny
- name: Run cargo deny
run: |
find . -name Cargo.toml -exec cargo deny --manifest-path {} check \
advisories -A advisory-not-detected --hide-inclusion-graph \; &> \
>(uniq &> .github/workflows/support-files/notifications/deny.message )
- uses: actions/upload-artifact@v3
with:
name: report
path: .github/workflows/support-files/notifications/deny.message
notification:
needs: cargo-deny
runs-on: custom-runner-linux
steps:
- name: Check out repository code
uses: actions/checkout@v2
- name: Download report from previous job
uses: actions/download-artifact@v3
with:
name: report
path: .github/workflows/support-files/notifications
- name: Keybase - Node Install
run: npm install
working-directory: .github/workflows/support-files
- name: Keybase - Send Notification
env:
NYM_NOTIFICATION_KIND: security
NYM_PROJECT_NAME: "Daily security report"
GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}"
KEYBASE_NYMBOT_USERNAME: "${{ secrets.KEYBASE_NYMBOT_USERNAME }}"
KEYBASE_NYMBOT_PAPERKEY: "${{ secrets.KEYBASE_NYMBOT_PAPERKEY }}"
KEYBASE_NYMBOT_TEAM: "${{ secrets.KEYBASE_NYMBOT_TEAM }}"
KEYBASE_NYM_CHANNEL: "security"
MATRIX_SERVER: "${{ secrets.MATRIX_SERVER }}"
MATRIX_ROOM: "${{ secrets.MATRIX_ROOM }}"
MATRIX_USER_ID: "${{ secrets.MATRIX_USER_ID }}"
MATRIX_TOKEN: "${{ secrets.MATRIX_TOKEN }}"
MATRIX_DEVICE_ID: "${{ secrets.MATRIX_DEVICE_ID }}"
uses: docker://keybaseio/client:stable-node
with:
args: .github/workflows/support-files/notifications/entry_point.sh
+1
View File
@@ -56,6 +56,7 @@ jobs:
- uses: actions-rs/clippy-check@v1
name: Clippy checks
continue-on-error: true
with:
token: ${{ secrets.GITHUB_TOKEN }}
args: --workspace --all-features
+1
View File
@@ -45,6 +45,7 @@ jobs:
- uses: actions-rs/clippy-check@v1
name: Clippy checks
continue-on-error: true
with:
token: ${{ secrets.GITHUB_TOKEN }}
args: --manifest-path nym-connect/Cargo.toml --workspace --all-features
@@ -1,56 +0,0 @@
name: CI for Network Explorer API
on:
workflow_dispatch:
release:
types: [created]
env:
NETWORK: mainnet
jobs:
publish-nym:
strategy:
fail-fast: false
matrix:
platform: [ubuntu-20.04]
runs-on: ${{ matrix.platform }}
steps:
- uses: actions/checkout@v3
- name: Install Dependencies (Linux)
run: sudo apt-get update && sudo apt-get -y install libwebkit2gtk-4.0-dev build-essential curl wget libssl-dev libgtk-3-dev libudev-dev squashfs-tools
- name: Check the release tag starts with `nym-explorer-api-`
if: startsWith(github.ref, 'refs/tags/nym-explorer-api-') == false && github.event_name != 'workflow_dispatch'
uses: actions/github-script@v3
with:
script: |
core.setFailed('Release tag did not start with nym-explorer-api-...')
- name: Install Rust stable
uses: actions-rs/toolchain@v1
with:
toolchain: stable
- name: Build all explorer-api
uses: actions-rs/cargo@v1
with:
command: build
args: --manifest-path explorer-api/Cargo.toml --workspace --release
- name: Upload Artifact
uses: actions/upload-artifact@v3
with:
name: my-artifact
path: |
target/release/explorer-api
retention-days: 30
- name: Upload to release based on tag name
uses: softprops/action-gh-release@v1
if: github.event_name == 'release'
with:
files: |
target/release/explorer-api
+2 -1
View File
@@ -83,6 +83,7 @@ jobs:
- uses: actions-rs/clippy-check@v1
name: Clippy checks
continue-on-error: true
with:
token: ${{ secrets.GITHUB_TOKEN }}
args: --all-features
@@ -160,7 +161,7 @@ jobs:
notification:
needs: build
runs-on: ubuntu-20.04
runs-on: custom-runner-linux
steps:
- name: Collect jobs status
uses: technote-space/workflow-conclusion-action@v2
+2 -1
View File
@@ -98,6 +98,7 @@ jobs:
- uses: actions-rs/clippy-check@v1
name: Clippy checks
continue-on-error: true
with:
token: ${{ secrets.GITHUB_TOKEN }}
args: --all-features
@@ -175,7 +176,7 @@ jobs:
notification:
needs: [build,get_release]
runs-on: ubuntu-20.04
runs-on: custom-runner-linux
steps:
- name: Collect jobs status
uses: technote-space/workflow-conclusion-action@v2
+2 -1
View File
@@ -98,6 +98,7 @@ jobs:
- uses: actions-rs/clippy-check@v1
name: Clippy checks
continue-on-error: true
with:
token: ${{ secrets.GITHUB_TOKEN }}
args: --all-features
@@ -175,7 +176,7 @@ jobs:
notification:
needs: [build,get_release]
runs-on: ubuntu-20.04
runs-on: custom-runner-linux
steps:
- name: Collect jobs status
uses: technote-space/workflow-conclusion-action@v2
-50
View File
@@ -1,50 +0,0 @@
name: Publish Nym CLI binaries
on:
workflow_dispatch:
release:
types: [created]
env:
NETWORK: mainnet
jobs:
publish-nym-cli:
strategy:
fail-fast: false
matrix:
platform: [ubuntu-20.04, windows-latest, macos-latest]
runs-on: ${{ matrix.platform }}
steps:
- uses: actions/checkout@v3
- name: Check the release tag starts with `nym-cli-`
if: startsWith(github.ref, 'refs/tags/nym-cli-') == false && github.event_name != 'workflow_dispatch'
uses: actions/github-script@v3
with:
script: |
core.setFailed('Release tag did not start with nym-cli-...')
- name: Install Rust stable
uses: actions-rs/toolchain@v1
with:
toolchain: stable
- name: Build binary
run: make build-nym-cli
- name: Upload Artifact
uses: actions/upload-artifact@v3
with:
name: nym-cli-${{ matrix.platform }}
path: |
target/release/nym-cli*
retention-days: 30
- name: Upload to release based on tag name
uses: softprops/action-gh-release@v1
if: github.event_name == 'release'
with:
files: |
target/release/nym-cli
@@ -10,6 +10,7 @@ defaults:
jobs:
publish-tauri:
if: ${{ startsWith(github.ref, 'refs/tags/nym-connect-') && github.event_name == 'release' }}
strategy:
fail-fast: false
matrix:
@@ -19,13 +20,6 @@ jobs:
steps:
- uses: actions/checkout@v2
- name: Check the release tag starts with `nym-connect-`
if: startsWith(github.ref, 'refs/tags/nym-connect-') == false && github.event_name != 'workflow_dispatch'
uses: actions/github-script@v3
with:
script: |
core.setFailed('Release tag did not start with nym-connect-...')
- name: Node v16
uses: actions/setup-node@v3
with:
@@ -10,10 +10,11 @@ defaults:
jobs:
publish-tauri:
if: ${{ startsWith(github.ref, 'refs/tags/nym-connect-') && github.event_name == 'release' }}
strategy:
fail-fast: false
matrix:
platform: [ubuntu-20.04]
platform: [custom-runner-linux]
runs-on: ${{ matrix.platform }}
steps:
@@ -23,17 +24,12 @@ jobs:
run: >
sudo apt-get update &&
sudo apt-get install -y webkit2gtk-4.0 libayatana-appindicator3-dev
- name: Check the release tag starts with `nym-connect-`
if: startsWith(github.ref, 'refs/tags/nym-connect-') == false && github.event_name != 'workflow_dispatch'
uses: actions/github-script@v3
with:
script: |
core.setFailed('Release tag did not start with nym-connect-...')
- name: Node v16
uses: actions/setup-node@v3
with:
node-version: 16
- name: Install Rust stable
uses: actions-rs/toolchain@v1
with:
@@ -10,6 +10,7 @@ defaults:
jobs:
publish-tauri:
if: ${{ startsWith(github.ref, 'refs/tags/nym-connect-') && github.event_name == 'release' }}
strategy:
fail-fast: false
matrix:
@@ -27,13 +28,6 @@ jobs:
- uses: actions/checkout@v3
- name: Check the release tag starts with `nym-connect-`
if: startsWith(github.ref, 'refs/tags/nym-connect-') == false && github.event_name != 'workflow_dispatch'
uses: actions/github-script@v3
with:
script: |
core.setFailed('Release tag did not start with nym-connect-...')
- name: Import signing certificate
env:
WINDOWS_CERTIFICATE: ${{ secrets.WINDOWS_CERTIFICATE }}
+4 -8
View File
@@ -16,10 +16,11 @@ env:
jobs:
publish-nym:
if: ${{ startsWith(github.ref, 'refs/tags/nym-binaries-') && github.event_name == 'release' }}
strategy:
fail-fast: false
matrix:
platform: [ubuntu-20.04]
platform: [custom-runner-linux]
runs-on: ${{ matrix.platform }}
steps:
@@ -27,13 +28,6 @@ jobs:
- name: Install Dependencies (Linux)
run: sudo apt-get update && sudo apt-get -y install libwebkit2gtk-4.0-dev build-essential curl wget libssl-dev libgtk-3-dev libudev-dev squashfs-tools
- name: Check the release tag starts with `nym-binaries-`
if: startsWith(github.ref, 'refs/tags/nym-binaries-') == false && github.event_name != 'workflow_dispatch'
uses: actions/github-script@v3
with:
script: |
core.setFailed('Release tag did not start with nym-binaries-...')
- name: Sets env vars for tokio if set in manual dispatch inputs
run: |
@@ -56,6 +50,7 @@ jobs:
with:
name: my-artifact
path: |
target/release/explorer-api
target/release/nym-client
target/release/nym-gateway
target/release/nym-mixnode
@@ -71,6 +66,7 @@ jobs:
if: github.event_name == 'release'
with:
files: |
target/release/explorer-api
target/release/nym-client
target/release/nym-gateway
target/release/nym-mixnode
@@ -10,6 +10,7 @@ defaults:
jobs:
publish-tauri:
if: ${{ startsWith(github.ref, 'refs/tags/nym-wallet-') && github.event_name == 'release' }}
strategy:
fail-fast: false
matrix:
@@ -19,13 +20,6 @@ jobs:
steps:
- uses: actions/checkout@v2
- name: Check the release tag starts with `nym-wallet-`
if: startsWith(github.ref, 'refs/tags/nym-wallet-') == false && github.event_name != 'workflow_dispatch'
uses: actions/github-script@v3
with:
script: |
core.setFailed('Release tag did not start with nym-wallet-...')
- name: Node v16
uses: actions/setup-node@v3
with:
@@ -9,10 +9,11 @@ defaults:
jobs:
publish-tauri:
if: ${{ startsWith(github.ref, 'refs/tags/nym-wallet-') && github.event_name == 'release' }}
strategy:
fail-fast: false
matrix:
platform: [ubuntu-20.04]
platform: [custom-runner-linux]
runs-on: ${{ matrix.platform }}
steps:
@@ -22,17 +23,12 @@ jobs:
run: >
sudo apt-get update &&
sudo apt-get install -y webkit2gtk-4.0
- name: Check the release tag starts with `nym-wallet-`
if: startsWith(github.ref, 'refs/tags/nym-wallet-') == false
uses: actions/github-script@v3
with:
script: |
core.setFailed('Release tag did not start with nym-wallet-...')
- name: Node v16
uses: actions/setup-node@v3
with:
node-version: 16
- name: Install Rust stable
uses: actions-rs/toolchain@v1
with:
@@ -9,6 +9,7 @@ defaults:
jobs:
publish-tauri:
if: ${{ startsWith(github.ref, 'refs/tags/nym-wallet-') && github.event_name == 'release' }}
strategy:
fail-fast: false
matrix:
@@ -26,13 +27,6 @@ jobs:
- uses: actions/checkout@v3
- name: Check the release tag starts with `nym-wallet-`
if: startsWith(github.ref, 'refs/tags/nym-wallet-') == false
uses: actions/github-script@v3
with:
script: |
core.setFailed('Release tag did not start with nym-wallet-...')
- name: Import signing certificate
env:
WINDOWS_CERTIFICATE: ${{ secrets.WINDOWS_CERTIFICATE }}
+1
View File
@@ -48,6 +48,7 @@ jobs:
- uses: actions-rs/clippy-check@v1
name: Clippy checks
continue-on-error: true
with:
token: ${{ secrets.GITHUB_TOKEN }}
args: --manifest-path nym-wallet/Cargo.toml --workspace --all-features
+2
View File
@@ -7,6 +7,7 @@ Post 1.0.0 release, the changelog format is based on [Keep a Changelog](https://
### Added
- nym-sdk: added initial version of a Rust client sdk
- nym-api: added `/circulating-supply` endpoint ([#2814])
### Changed
@@ -20,6 +21,7 @@ Post 1.0.0 release, the changelog format is based on [Keep a Changelog](https://
[#2753]: https://github.com/nymtech/nym/pull/2753
[#2762]: https://github.com/nymtech/nym/pull/2762
[#2814]: https://github.com/nymtech/nym/pull/2814
## [v1.1.5] (2022-01-10)
Generated
+21 -18
View File
@@ -2275,7 +2275,7 @@ dependencies = [
"indexmap",
"slab",
"tokio",
"tokio-util 0.7.3",
"tokio-util 0.7.4",
"tracing",
]
@@ -3035,8 +3035,9 @@ dependencies = [
"futures",
"log",
"nymsphinx",
"task",
"tokio",
"tokio-util 0.7.3",
"tokio-util 0.7.4",
]
[[package]]
@@ -3079,7 +3080,7 @@ dependencies = [
"task",
"thiserror",
"tokio",
"tokio-util 0.7.3",
"tokio-util 0.7.4",
"url",
"validator-client",
"version-checker",
@@ -3179,7 +3180,7 @@ dependencies = [
"slab",
"tokio",
"tokio-stream",
"tokio-util 0.7.3",
"tokio-util 0.7.4",
"wasm-timer",
]
@@ -3297,6 +3298,7 @@ dependencies = [
"url",
"validator-client",
"version-checker",
"vesting-contract-common",
]
[[package]]
@@ -3468,11 +3470,12 @@ dependencies = [
"sqlx 0.5.11",
"statistics-common",
"subtle-encoding",
"task",
"thiserror",
"tokio",
"tokio-stream",
"tokio-tungstenite 0.14.0",
"tokio-util 0.7.3",
"tokio-util 0.7.4",
"url",
"validator-client",
"version-checker",
@@ -3515,7 +3518,7 @@ dependencies = [
"sysinfo",
"task",
"tokio",
"tokio-util 0.7.3",
"tokio-util 0.7.4",
"toml",
"topology",
"url",
@@ -3831,7 +3834,7 @@ dependencies = [
"nymsphinx-params",
"nymsphinx-types",
"thiserror",
"tokio-util 0.7.3",
"tokio-util 0.7.4",
]
[[package]]
@@ -4402,7 +4405,7 @@ dependencies = [
"task",
"tokio",
"tokio-test",
"tokio-util 0.7.3",
"tokio-util 0.7.4",
]
[[package]]
@@ -4867,7 +4870,7 @@ dependencies = [
"time 0.3.17",
"tokio",
"tokio-stream",
"tokio-util 0.7.3",
"tokio-util 0.7.4",
"ubyte",
"version_check",
"yansi",
@@ -6091,9 +6094,9 @@ dependencies = [
[[package]]
name = "tokio"
version = "1.22.0"
version = "1.24.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d76ce4a75fb488c605c54bf610f221cea8b0dafb53333c1a67e8ee199dcd2ae3"
checksum = "1d9f76183f91ecfb55e1d7d5602bd1d979e38a3a522fe900241cf195624d67ae"
dependencies = [
"autocfg 1.1.0",
"bytes",
@@ -6107,7 +6110,7 @@ dependencies = [
"socket2",
"tokio-macros",
"tracing",
"winapi",
"windows-sys 0.42.0",
]
[[package]]
@@ -6165,14 +6168,14 @@ dependencies = [
[[package]]
name = "tokio-stream"
version = "0.1.9"
version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df54d54117d6fdc4e4fea40fe1e4e566b3505700e148a6827e59b34b0d2600d9"
checksum = "d660770404473ccd7bc9f8b28494a811bc18542b915c0855c51e8f419d5223ce"
dependencies = [
"futures-core",
"pin-project-lite",
"tokio",
"tokio-util 0.7.3",
"tokio-util 0.7.4",
]
[[package]]
@@ -6229,9 +6232,9 @@ dependencies = [
[[package]]
name = "tokio-util"
version = "0.7.3"
version = "0.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc463cd8deddc3770d20f9852143d50bf6094e640b485cb2e189a2099085ff45"
checksum = "0bb2e075f03b3d66d8d8785356224ba688d2906a371015e225beeb65ca92c740"
dependencies = [
"bytes",
"futures-core",
@@ -6323,7 +6326,7 @@ dependencies = [
"rand 0.8.5",
"slab",
"tokio",
"tokio-util 0.7.3",
"tokio-util 0.7.4",
"tower-layer",
"tower-service",
"tracing",
+4 -4
View File
@@ -20,7 +20,7 @@ serde_json = "1.0.89"
tap = "1.0.1"
thiserror = "1.0.34"
url = { version ="2.2", features = ["serde"] }
tokio = { version = "1.21.2", features = ["macros"]}
tokio = { version = "1.24.1", features = ["macros"]}
time = "0.3.17"
# internal
@@ -38,11 +38,11 @@ validator-client = { path = "../../common/client-libs/validator-client", default
task = { path = "../../common/task" }
[target."cfg(not(target_arch = \"wasm32\"))".dependencies.tokio-stream]
version = "0.1.9"
version = "0.1.11"
features = ["time"]
[target."cfg(not(target_arch = \"wasm32\"))".dependencies.tokio]
version = "1.21.2"
version = "1.24.1"
features = ["time"]
[target."cfg(not(target_arch = \"wasm32\"))".dependencies.sqlx]
@@ -75,7 +75,7 @@ features = ["wasm-bindgen"]
tempfile = "3.1.0"
[build-dependencies]
tokio = { version = "1.21.2", features = ["rt-multi-thread", "macros"] }
tokio = { version = "1.24.1", features = ["rt-multi-thread", "macros"] }
sqlx = { version = "0.6.2", features = ["runtime-tokio-rustls", "sqlite", "macros", "migrate"] }
[features]
+2 -2
View File
@@ -9,9 +9,9 @@ async fn main() {
use std::env;
let out_dir = env::var("OUT_DIR").unwrap();
let database_path = format!("{}/fs-surbs-example.sqlite", out_dir);
let database_path = format!("{out_dir}/fs-surbs-example.sqlite");
let mut conn = SqliteConnection::connect(&format!("sqlite://{}?mode=rwc", database_path))
let mut conn = SqliteConnection::connect(&format!("sqlite://{database_path}?mode=rwc"))
.await
.expect("Failed to create SQLx database connection");
@@ -53,7 +53,7 @@ fn archive_corrupted_database<P: AsRef<Path>>(db_path: P) -> io::Result<()> {
let new_extension =
if let Some(existing_extension) = db_path.extension().and_then(|ext| ext.to_str()) {
format!("{existing_extension}.{}", suffix)
format!("{existing_extension}.{suffix}")
} else {
suffix
};
@@ -42,9 +42,6 @@ pub struct KeyManager {
*/
impl KeyManager {
// this is actually **NOT** dead code
// I have absolutely no idea why the compiler insists it's unused. The call happens during client::init::execute
#[allow(dead_code)]
/// Creates new instance of a [`KeyManager`]
pub fn new<R>(rng: &mut R) -> Self
where
@@ -130,9 +127,6 @@ impl KeyManager {
Ok(key_manager)
}
// this is actually **NOT** dead code
// I have absolutely no idea why the compiler insists it's unused. The call happens during client::init::execute
#[allow(dead_code)]
/// Stores all available keys on the disk.
// While perhaps there is no much point in storing the `AckKey` on the disk,
// it is done so for the consistency sake so that you wouldn't require an rng instance
@@ -211,9 +205,6 @@ impl KeyManager {
Arc::clone(&self.ack_key)
}
// this is actually **NOT** dead code
// I have absolutely no idea why the compiler insists it's unused. The call happens during client::init::execute
#[allow(dead_code)]
/// After shared key with the gateway is derived, puts its ownership to this instance of a [`KeyManager`].
pub fn insert_gateway_shared_key(&mut self, gateway_shared_key: Arc<SharedKeys>) {
self.gateway_shared_key = Some(gateway_shared_key)
@@ -57,7 +57,7 @@ impl MixTrafficController {
if self.consecutive_gateway_failure_count == MAX_FAILURE_COUNT {
// todo: in the future this should initiate a 'graceful' shutdown or try
// to reconnect?
panic!("failed to send sphinx packet to the gateway {} times in a row - assuming the gateway is dead. Can't do anything about it yet :(", MAX_FAILURE_COUNT)
panic!("failed to send sphinx packet to the gateway {MAX_FAILURE_COUNT} times in a row - assuming the gateway is dead. Can't do anything about it yet :(")
}
}
Ok(_) => {
@@ -471,14 +471,10 @@ where
let mult = self.sending_delay_controller.current_multiplier();
let delay = self.current_average_message_sending_delay().as_millis();
let status_str = if self.config.disable_poisson_packet_distribution {
format!(
"Status: {lanes} lanes, backlog: {:.2} kiB ({packets}), no delay",
backlog
)
format!("Status: {lanes} lanes, backlog: {backlog:.2} kiB ({packets}), no delay")
} else {
format!(
"Status: {lanes} lanes, backlog: {:.2} kiB ({packets}), avg delay: {}ms ({mult})",
backlog, delay
"Status: {lanes} lanes, backlog: {backlog:.2} kiB ({packets}), avg delay: {delay}ms ({mult})"
)
};
if packets > 1000 {
@@ -44,8 +44,7 @@ impl TryFrom<StoredSenderTag> for (RecipientBytes, AnonymousSenderTag) {
let Ok(sender_tag_bytes) = value.tag.try_into() else {
return Err(StorageError::CorruptedData {
details: format!(
"the retrieved sender tag has length of {tag_len} while {} was expected",
SENDER_TAG_SIZE
"the retrieved sender tag has length of {tag_len} while {SENDER_TAG_SIZE} was expected",
),
});
};
@@ -132,8 +131,7 @@ impl TryFrom<StoredSurbSender> for (AnonymousSenderTag, i64) {
let Ok(sender_tag_bytes) = value.tag.try_into() else {
return Err(StorageError::CorruptedData {
details: format!(
"the retrieved sender tag has length of {tag_len} while {} was expected",
SENDER_TAG_SIZE
"the retrieved sender tag has length of {tag_len} while {SENDER_TAG_SIZE} was expected",
),
});
};
+1
View File
@@ -88,6 +88,7 @@ impl<T> Config<T> {
Config::default().with_id(id)
}
#[must_use]
pub fn with_id<S: Into<String>>(mut self, id: S) -> Self
where
T: NymConfig,
+2
View File
@@ -65,8 +65,10 @@ pub enum ClientCoreError {
/// Set of messages that the client can send to listeners via the task manager
#[derive(thiserror::Error, Debug)]
pub enum ClientCoreStatusMessage {
// NOTE: The nym-connect frontend listens for these strings, so don't change them until we have a more robust mechanism in place
#[error("The connected gateway is slow, or the connection to it is slow")]
GatewayIsSlow,
// NOTE: The nym-connect frontend listens for these strings, so don't change them until we have a more robust mechanism in place
#[error("The connected gateway is very slow, or the connection to it is very slow")]
GatewayIsVerySlow,
}
+2 -2
View File
@@ -18,7 +18,7 @@ use url::Url;
pub(super) async fn query_gateway_details(
validator_servers: Vec<Url>,
chosen_gateway_id: Option<String>,
chosen_gateway_id: Option<identity::PublicKey>,
) -> Result<gateway::Node, ClientCoreError> {
let nym_api = validator_servers
.choose(&mut thread_rng())
@@ -40,7 +40,7 @@ pub(super) async fn query_gateway_details(
if let Some(gateway_id) = chosen_gateway_id {
filtered_gateways
.iter()
.find(|gateway| gateway.identity_key.to_base58_string() == gateway_id)
.find(|gateway| gateway.identity_key == gateway_id)
.ok_or_else(|| ClientCoreError::NoGatewayWithId(gateway_id.to_string()))
.cloned()
} else {
+53 -69
View File
@@ -69,42 +69,21 @@ pub fn new_client_keys() -> KeyManager {
KeyManager::new(&mut rng)
}
/// Convenience function for setting up the gateway for a client. Depending on the arguments given
/// it will do the sensible thing.
pub async fn setup_gateway<C, T>(
register_gateway: bool,
// TODO: this should get refactored to instead take Option<identity::PublicKey>
user_chosen_gateway_id: Option<String>,
config: &Config<T>,
) -> Result<GatewayEndpointConfig, ClientCoreError>
where
C: NymConfig + ClientCoreConfigTrait,
T: NymConfig,
{
let id = config.get_id();
if register_gateway {
register_with_gateway_and_store(user_chosen_gateway_id, config).await
} else if let Some(user_chosen_gateway_id) = user_chosen_gateway_id {
config_gateway_with_existing_keys(user_chosen_gateway_id, config).await
} else {
reuse_existing_gateway_config::<C>(&id)
}
}
/// Get the gateway details by querying the validator-api. Either pick one at random or use
/// the chosen one if it's among the available ones.
/// Authenticate and register with a gateway.
/// Either pick one at random by querying the available gateways from the nym-api, or use the
/// chosen one if it's among the available ones.
/// The shared key is added to the supplied `KeyManager` and the endpoint details are returned.
pub async fn register_with_gateway(
key_manager: &mut KeyManager,
nym_api_endpoints: Vec<Url>,
chosen_gateway_id: Option<String>,
chosen_gateway_id: Option<identity::PublicKey>,
) -> Result<GatewayEndpointConfig, ClientCoreError> {
// Our identity is derived from our key
let our_identity = key_manager.identity_keypair();
// Get the gateway details of the gateway we will use
let gateway = helpers::query_gateway_details(nym_api_endpoints, chosen_gateway_id).await?;
log::debug!("Querying gateway gives: {}", gateway);
let our_identity = key_manager.identity_keypair();
// Establish connection, authenticate and generate keys for talking with the gateway
let shared_keys = helpers::register_with_gateway(&gateway, our_identity).await?;
key_manager.insert_gateway_shared_key(shared_keys);
@@ -112,59 +91,64 @@ pub async fn register_with_gateway(
Ok(gateway.into())
}
/// Get the gateway details by querying the validator-api. Either pick one at random or use
/// the chosen one if it's among the available ones.
/// Saves keys to disk, specified by the paths in `config`.
pub async fn register_with_gateway_and_store<T>(
chosen_gateway_id: Option<String>,
/// Convenience function for setting up the gateway for a client given a `Config`. Depending on the
/// arguments given it will do the sensible thing. Either it will
///
/// a. Reuse existing gateway configuration from storage.
/// b. Create a new gateway configuration but keep existing keys. This assumes that the caller
/// knows what they are doing and that the keys match the requested gateway.
/// c. Create a new gateway configuration with a newly registered gateway and keys.
pub async fn setup_gateway_from_config<C, T>(
register_gateway: bool,
user_chosen_gateway_id: Option<identity::PublicKey>,
config: &Config<T>,
) -> Result<GatewayEndpointConfig, ClientCoreError>
where
C: NymConfig + ClientCoreConfigTrait,
T: NymConfig,
{
println!("Configuring gateway");
let mut key_manager = new_client_keys();
let id = config.get_id();
let gateway = register_with_gateway(
&mut key_manager,
config.get_nym_api_endpoints(),
chosen_gateway_id,
)
.await?;
// If we are not going to register gateway, and an explicitly chosed gateway is not passed in,
// load the existing configuration file
if !register_gateway && user_chosen_gateway_id.is_none() {
println!("Not registering gateway, will reuse existing config and keys");
return load_existing_gateway_config::<C>(&id);
}
helpers::store_keys(&key_manager, config)?;
println!("Saved all generated keys");
Ok(gateway)
}
/// Set the gateway using the usual procedue of querying the validator-api, but don't register or
/// create any keys.
/// This assumes that the user knows what they are doing, and that the existing keys are valid for
/// the gateway being used
pub async fn config_gateway_with_existing_keys<T>(
user_chosen_gateway_id: String,
config: &Config<T>,
) -> Result<GatewayEndpointConfig, ClientCoreError>
where
T: NymConfig,
{
println!("Using gateway provided by user, keeping existing keys");
let gateway = helpers::query_gateway_details(
config.get_nym_api_endpoints(),
Some(user_chosen_gateway_id),
)
.await?;
// Else, we preceed by querying the nym-api
let gateway =
helpers::query_gateway_details(config.get_nym_api_endpoints(), user_chosen_gateway_id)
.await?;
log::debug!("Querying gateway gives: {}", gateway);
// If we are not registering, just return this and assume the caller has the keys already and
// wants to keep the,
if !register_gateway && user_chosen_gateway_id.is_some() {
println!("Using gateway provided by user, keeping existing keys");
return Ok(gateway.into());
}
// Create new keys and derive our identity
let mut key_manager = new_client_keys();
let our_identity = key_manager.identity_keypair();
// Establish connection, authenticate and generate keys for talking with the gateway
println!("Registering with new gateway");
let shared_keys = helpers::register_with_gateway(&gateway, our_identity).await?;
key_manager.insert_gateway_shared_key(shared_keys);
// Write all keys to storage and just return the gateway endpoint config. It is assumed that we
// will load keys from storage when actually connecting.
helpers::store_keys(&key_manager, config)?;
Ok(gateway.into())
}
/// Read and reuse the existing gateway configuration from a file that was generate earlier.
pub fn reuse_existing_gateway_config<T>(id: &str) -> Result<GatewayEndpointConfig, ClientCoreError>
pub fn load_existing_gateway_config<T>(id: &str) -> Result<GatewayEndpointConfig, ClientCoreError>
where
T: NymConfig + ClientCoreConfigTrait,
{
println!("Not registering gateway, will reuse existing config and keys");
T::load_from_file(Some(id))
.map(|existing_config| existing_config.get_gateway_endpoint().clone())
.map_err(|err| {
@@ -242,9 +226,9 @@ where
pub fn output_to_json<T: Serialize>(init_results: &T, output_file: &str) {
match std::fs::File::create(output_file) {
Ok(file) => match serde_json::to_writer_pretty(file, init_results) {
Ok(_) => println!("Saved: {}", output_file),
Err(err) => eprintln!("Could not save {}: {err}", output_file),
Ok(_) => println!("Saved: {output_file}"),
Err(err) => eprintln!("Could not save {output_file}: {err}"),
},
Err(err) => eprintln!("Could not save {}: {err}", output_file),
Err(err) => eprintln!("Could not save {output_file}: {err}"),
}
}
+1 -1
View File
@@ -13,7 +13,7 @@ rand = "0.7.3"
serde = { version = "1.0", features = ["derive"] }
thiserror = "1.0"
url = "2.2"
tokio = { version = "1.21.2", features = ["rt-multi-thread", "net", "signal", "macros"] } # async runtime
tokio = { version = "1.24.1", features = ["rt-multi-thread", "net", "signal", "macros"] } # async runtime
coconut-interface = { path = "../../common/coconut-interface" }
config = { path = "../../common/config" }
+1 -1
View File
@@ -30,7 +30,7 @@ serde = { version = "1.0.104", features = ["derive"] } # for config serializatio
serde_json = "1.0"
thiserror = "1.0.34"
tap = "1.0.1"
tokio = { version = "1.21.2", features = ["rt-multi-thread", "net", "signal"] } # async runtime
tokio = { version = "1.24.1", features = ["rt-multi-thread", "net", "signal"] } # async runtime
tokio-tungstenite = "0.14" # websocket
## internal
@@ -85,7 +85,7 @@ async fn send_file_without_reply() {
let (mut ws_stream, _) = connect_async(uri).await.unwrap();
let recipient = get_self_address(&mut ws_stream).await;
println!("our full address is: {}", recipient);
println!("our full address is: {recipient}");
let read_data = std::fs::read("examples/dummy_file").unwrap();
+5 -14
View File
@@ -36,7 +36,7 @@ async fn send_text_with_reply() {
let (mut ws_stream, _) = connect_async(uri).await.unwrap();
let recipient = get_self_address(&mut ws_stream).await;
println!("our full address is: {}", recipient);
println!("our full address is: {recipient}");
let send_request = json!({
"type" : "send",
@@ -45,10 +45,7 @@ async fn send_text_with_reply() {
"withReplySurb": true,
});
println!(
"sending {:?} (*with* reply SURB) over the mix network...",
message
);
println!("sending {message:?} (*with* reply SURB) over the mix network...");
let response =
send_message_and_get_json_response(&mut ws_stream, send_request.to_string()).await;
@@ -59,10 +56,7 @@ async fn send_text_with_reply() {
"replySurb": response["replySurb"]
});
println!(
"sending {:?} (using reply SURB!) over the mix network...",
reply_message
);
println!("sending {reply_message:?} (using reply SURB!) over the mix network...");
let response =
send_message_and_get_json_response(&mut ws_stream, reply_request.to_string()).await;
@@ -76,7 +70,7 @@ async fn send_text_without_reply() {
let (mut ws_stream, _) = connect_async(uri).await.unwrap();
let recipient = get_self_address(&mut ws_stream).await;
println!("our full address is: {}", recipient);
println!("our full address is: {recipient}");
let send_request = json!({
"type" : "send",
@@ -85,10 +79,7 @@ async fn send_text_without_reply() {
"withReplySurb": false,
});
println!(
"sending {:?} (*without* reply SURB) over the mix network...",
message
);
println!("sending {message:?} (*without* reply SURB) over the mix network...");
let response =
send_message_and_get_json_response(&mut ws_stream, send_request.to_string()).await;
+2 -9
View File
@@ -120,16 +120,9 @@ impl SocketClient {
/// blocking version of `start_socket` method. Will run forever (or until SIGINT is sent)
pub async fn run_socket_forever(self) -> Result<(), Box<dyn Error + Send + Sync>> {
let mut shutdown = self.start_socket().await?;
let res = task::wait_for_signal_and_error(&mut shutdown).await;
log::info!("Sending shutdown");
shutdown.signal_shutdown().ok();
log::info!("Waiting for tasks to finish... (Press ctrl-c to force)");
shutdown.wait_for_shutdown().await;
let shutdown = self.start_socket().await?;
let res = shutdown.catch_interrupt().await;
log::info!("Stopping nym-client");
res
}
+7 -8
View File
@@ -114,16 +114,15 @@ pub(crate) async fn execute(args: &Init) -> Result<(), ClientError> {
let already_init = Config::default_config_file_path(Some(id)).exists();
if already_init {
println!(
"Client \"{}\" was already initialised before! \
Config information will be overwritten (but keys will be kept)!",
id
);
println!("Client \"{id}\" was already initialised before");
}
// Usually you only register with the gateway on the first init, however you can force
// re-registering if wanted.
let user_wants_force_register = args.force_register_gateway;
if user_wants_force_register {
println!("Instructed to force registering gateway. This might overwrite keys!");
}
// If the client was already initialized, don't generate new keys and don't re-register with
// the gateway (because this would create a new shared key).
@@ -138,9 +137,9 @@ pub(crate) async fn execute(args: &Init) -> Result<(), ClientError> {
// Setup gateway by either registering a new one, or creating a new config from the selected
// one but with keys kept, or reusing the gateway configuration.
let gateway = client_core::init::setup_gateway::<Config, _>(
let gateway = client_core::init::setup_gateway_from_config::<Config, _>(
register_gateway,
user_chosen_gateway_id.map(|id| id.to_base58_string()),
user_chosen_gateway_id,
config.get_base(),
)
.await
@@ -169,7 +168,7 @@ pub(crate) async fn execute(args: &Init) -> Result<(), ClientError> {
fn print_saved_config(config: &Config) {
let config_save_location = config.get_config_file_save_location();
println!("Saved configuration file to {:?}", config_save_location);
println!("Saved configuration file to {config_save_location:?}");
println!("Using gateway: {}", config.get_base().get_gateway_id());
log::debug!("Gateway id: {}", config.get_base().get_gateway_id());
log::debug!("Gateway owner: {}", config.get_base().get_gateway_owner());
+7 -21
View File
@@ -17,36 +17,26 @@ fn fail_upgrade<D1: Display, D2: Display>(from_version: D1, to_version: D2) -> !
}
fn print_start_upgrade<D1: Display, D2: Display>(from: D1, to: D2) {
println!(
"\n==================\nTrying to upgrade client from {} to {} ...",
from, to
);
println!("\n==================\nTrying to upgrade client from {from} to {to} ...");
}
fn print_failed_upgrade<D1: Display, D2: Display>(from: D1, to: D2) {
eprintln!(
"Upgrade from {} to {} failed!\n==================\n",
from, to
);
eprintln!("Upgrade from {from} to {to} failed!\n==================\n");
}
fn print_successful_upgrade<D1: Display, D2: Display>(from: D1, to: D2) {
println!(
"Upgrade from {} to {} was successful!\n==================\n",
from, to
);
println!("Upgrade from {from} to {to} was successful!\n==================\n");
}
fn outdated_upgrade(config_version: &Version, package_version: &Version) -> ! {
eprintln!(
"Cannot perform upgrade from {} to {}. Your version is too old to perform the upgrade.!",
config_version, package_version
"Cannot perform upgrade from {config_version} to {package_version}. Your version is too old to perform the upgrade.!"
);
process::exit(1)
}
fn unsupported_upgrade(current_version: &Version, config_version: &Version) -> ! {
eprintln!("Cannot perform upgrade from {} to {}. Please let the developers know about this issue if you expected it to work!", config_version, current_version);
eprintln!("Cannot perform upgrade from {config_version} to {current_version}. Please let the developers know about this issue if you expected it to work!");
process::exit(1)
}
@@ -65,8 +55,7 @@ fn parse_config_version(config: &Config) -> Version {
if version.is_prerelease() || !version.build.is_empty() {
eprintln!(
"Trying to upgrade from a non-released version {}. This is not supported!",
version
"Trying to upgrade from a non-released version {version}. This is not supported!"
);
process::exit(1)
}
@@ -81,10 +70,7 @@ fn parse_package_version() -> Version {
// however, we are not using them ourselves at the moment and hence it should be fine.
// if we change our mind, we could easily tweak this code
if version.is_prerelease() || !version.build.is_empty() {
eprintln!(
"Trying to upgrade to a non-released version {}. This is not supported!",
version
);
eprintln!("Trying to upgrade to a non-released version {version}. This is not supported!");
process::exit(1)
}
+2 -19
View File
@@ -3,7 +3,7 @@
use std::error::Error;
use clap::{crate_version, Parser};
use clap::{crate_name, crate_version, Parser};
use logging::setup_logging;
use network_defaults::setup_env;
@@ -15,26 +15,9 @@ pub mod websocket;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
setup_logging();
println!("{}", banner());
println!("{}", logging::banner(crate_name!(), crate_version!()));
let args = commands::Cli::parse();
setup_env(args.config_env_file.as_ref());
commands::execute(&args).await
}
fn banner() -> String {
format!(
r#"
_ __ _ _ _ __ ___
| '_ \| | | | '_ \ _ \
| | | | |_| | | | | | |
|_| |_|\__, |_| |_| |_|
|___/
(client - version {:})
"#,
crate_version!()
)
}
+2 -6
View File
@@ -27,17 +27,13 @@ use tokio_tungstenite::{
};
use websocket_requests::{requests::ClientRequest, responses::ServerResponse};
#[derive(Default)]
enum ReceivedResponseType {
#[default]
Binary,
Text,
}
impl Default for ReceivedResponseType {
fn default() -> Self {
ReceivedResponseType::Binary
}
}
pub(crate) struct HandlerBuilder {
msg_input: InputMessageSender,
client_connection_tx: ConnectionCommandSender,
@@ -84,7 +84,7 @@ impl TryFrom<u8> for ErrorKind {
n => Err(Error::new(
ErrorKind::MalformedResponse,
format!("invalid error code {}", n),
format!("invalid error code {n}"),
)),
}
}
+1 -1
View File
@@ -23,7 +23,7 @@ serde = { version = "1.0", features = ["derive"] } # for config serialization/de
serde_json = "1.0.89"
tap = "1.0.1"
thiserror = "1.0.34"
tokio = { version = "1.21.2", features = ["rt-multi-thread", "net", "signal"] }
tokio = { version = "1.24.1", features = ["rt-multi-thread", "net", "signal"] }
url = "2.2"
# internal
+3 -10
View File
@@ -19,7 +19,7 @@ use gateway_client::bandwidth::BandwidthController;
use log::*;
use nymsphinx::addressing::clients::Recipient;
use std::error::Error;
use task::{wait_for_signal_and_error, TaskClient, TaskManager};
use task::{TaskClient, TaskManager};
pub mod config;
@@ -147,16 +147,9 @@ impl NymClient {
/// blocking version of `start` method. Will run forever (or until SIGINT is sent)
pub async fn run_forever(self) -> Result<(), Box<dyn Error + Send + Sync>> {
let mut shutdown = self.start().await?;
let res = wait_for_signal_and_error(&mut shutdown).await;
log::info!("Sending shutdown");
shutdown.signal_shutdown().ok();
log::info!("Waiting for tasks to finish... (Press ctrl-c to force)");
shutdown.wait_for_shutdown().await;
let shutdown = self.start().await?;
let res = shutdown.catch_interrupt().await;
log::info!("Stopping nym-socks5-client");
res
}
+6 -7
View File
@@ -124,16 +124,15 @@ pub(crate) async fn execute(args: &Init) -> Result<(), Socks5ClientError> {
let already_init = Config::default_config_file_path(Some(id)).exists();
if already_init {
println!(
"SOCKS5 client \"{}\" was already initialised before! \
Config information will be overwritten (but keys will be kept)!",
id
);
println!("SOCKS5 client \"{id}\" was already initialised before");
}
// Usually you only register with the gateway on the first init, however you can force
// re-registering if wanted.
let user_wants_force_register = args.force_register_gateway;
if user_wants_force_register {
println!("Instructed to force registering gateway. This might overwrite keys!");
}
// If the client was already initialized, don't generate new keys and don't re-register with
// the gateway (because this would create a new shared key).
@@ -151,9 +150,9 @@ pub(crate) async fn execute(args: &Init) -> Result<(), Socks5ClientError> {
// Setup gateway by either registering a new one, or creating a new config from the selected
// one but with keys kept, or reusing the gateway configuration.
let gateway = client_core::init::setup_gateway::<Config, _>(
let gateway = client_core::init::setup_gateway_from_config::<Config, _>(
register_gateway,
user_chosen_gateway_id.map(|id| id.to_base58_string()),
user_chosen_gateway_id,
config.get_base(),
)
.await
+2 -19
View File
@@ -3,7 +3,7 @@
use std::error::Error;
use clap::{crate_version, Parser};
use clap::{crate_name, crate_version, Parser};
use logging::setup_logging;
use network_defaults::setup_env;
@@ -15,26 +15,9 @@ pub mod socks;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
setup_logging();
println!("{}", banner());
println!("{}", logging::banner(crate_name!(), crate_version!()));
let args = commands::Cli::parse();
setup_env(args.config_env_file.as_ref());
commands::execute(&args).await
}
fn banner() -> String {
format!(
r#"
_ __ _ _ _ __ ___
| '_ \| | | | '_ \ _ \
| | | | |_| | | | | | |
|_| |_|\__, |_| |_| |_|
|___/
(socks5 proxy - version {:})
"#,
crate_version!()
)
}
+1 -1
View File
@@ -23,7 +23,7 @@ js-sys = "0.3"
rand = { version = "0.7.3", features = ["wasm-bindgen"] }
serde = { version = "1.0", features = ["derive"] }
serde-wasm-bindgen = "0.4"
tokio = { version = "1.21.2", features = ["sync"] }
tokio = { version = "1.24.1", features = ["sync"] }
url = "2.2"
wasm-bindgen = { version = "=0.2.83", features = ["serde-serialize"] }
wasm-bindgen-futures = "0.4"
+3 -3
View File
@@ -15,7 +15,7 @@ thiserror = "1.0"
url = "2.2"
rand = { version = "0.7.3", features = ["wasm-bindgen"] }
async-trait = { version = "0.1.51" }
tokio = { version = "1.21.2", features = ["macros"] }
tokio = { version = "1.24.1", features = ["macros"] }
# internal
coconut-interface = { path = "../../coconut-interface", optional = true }
@@ -36,11 +36,11 @@ default-features = false
# non-wasm-only dependencies
[target."cfg(not(target_arch = \"wasm32\"))".dependencies.tokio]
version = "1.21.2"
version = "1.24.1"
features = ["macros", "rt", "net", "sync", "time"]
[target."cfg(not(target_arch = \"wasm32\"))".dependencies.tokio-stream]
version = "0.1.9"
version = "0.1.11"
features = ["net", "sync", "time"]
[target."cfg(not(target_arch = \"wasm32\"))".dependencies.tokio-tungstenite]
+4 -3
View File
@@ -9,8 +9,9 @@ edition = "2021"
[dependencies]
futures = "0.3"
log = "0.4.8"
tokio = { version = "1.21.2", features = ["time", "net", "rt"] }
tokio-util = { version = "0.7.3", features = ["codec"] }
tokio = { version = "1.24.1", features = ["time", "net", "rt"] }
tokio-util = { version = "0.7.4", features = ["codec"] }
# internal
nymsphinx = {path = "../../nymsphinx" }
nymsphinx = { path = "../../nymsphinx" }
task = { path = "../../task" }
@@ -16,6 +16,7 @@ type MixForwardingReceiver = mpsc::UnboundedReceiver<MixPacket>;
pub struct PacketForwarder {
mixnet_client: Client,
packet_receiver: MixForwardingReceiver,
shutdown: task::TaskClient,
}
impl PacketForwarder {
@@ -25,6 +26,7 @@ impl PacketForwarder {
initial_connection_timeout: Duration,
maximum_connection_buffer_size: usize,
use_legacy_version: bool,
shutdown: task::TaskClient,
) -> (PacketForwarder, MixForwardingSender) {
let client_config = Config::new(
initial_reconnection_backoff,
@@ -40,26 +42,35 @@ impl PacketForwarder {
PacketForwarder {
mixnet_client: Client::new(client_config),
packet_receiver,
shutdown,
},
packet_sender,
)
}
pub async fn run(&mut self) {
while let Some(mix_packet) = self.packet_receiver.next().await {
trace!("Going to forward packet to {:?}", mix_packet.next_hop());
while !self.shutdown.is_shutdown() {
tokio::select! {
biased;
_ = self.shutdown.recv() => {
log::trace!("PacketForwarder: Received shutdown");
}
Some(mix_packet) = self.packet_receiver.next() => {
trace!("Going to forward packet to {:?}", mix_packet.next_hop());
let next_hop = mix_packet.next_hop();
let packet_mode = mix_packet.packet_mode();
let sphinx_packet = mix_packet.into_sphinx_packet();
// we don't care about responses, we just want to fire packets
// as quickly as possible
let next_hop = mix_packet.next_hop();
let packet_mode = mix_packet.packet_mode();
let sphinx_packet = mix_packet.into_sphinx_packet();
// we don't care about responses, we just want to fire packets
// as quickly as possible
if let Err(err) =
self.mixnet_client
.send_without_response(next_hop, sphinx_packet, packet_mode)
{
debug!("failed to forward the packet - {err}")
if let Err(err) =
self.mixnet_client
.send_without_response(next_hop, sphinx_packet, packet_mode)
{
debug!("failed to forward the packet - {err}")
}
}
}
}
}
@@ -24,7 +24,7 @@ reqwest = { version = "0.11", features = ["json"] }
thiserror = "1"
log = "0.4"
url = { version = "2.2", features = ["serde"] }
tokio = { version = "1.21.2", features = ["sync", "time"] }
tokio = { version = "1.24.1", features = ["sync", "time"] }
futures = "0.3"
coconut-interface = { path = "../../coconut-interface" }
@@ -6,7 +6,7 @@ use thiserror::Error;
#[derive(Error, Debug)]
pub enum ValidatorClientError {
#[error("There was an issue with the validator api request - {source}")]
#[error("nym api request failed - {source}")]
NymAPIError {
#[from]
source: nym_api::error::NymAPIError,
@@ -16,7 +16,7 @@ pub enum ValidatorClientError {
MalformedUrlProvided(#[from] url::ParseError),
#[cfg(feature = "nyxd-client")]
#[error("There was an issue with the Nyxd client - {0}")]
#[error("nyxd request failed - {0}")]
NyxdError(#[from] crate::nyxd::error::NyxdError),
#[error("No validator API url has been provided")]
@@ -9,10 +9,8 @@ pub mod nym_api;
#[cfg(feature = "nyxd-client")]
pub mod nyxd;
#[cfg(feature = "nyxd-client")]
pub use crate::client::{CoconutApiClient, NymApiClient};
pub use crate::error::ValidatorClientError;
pub use nym_api_requests::*;
#[cfg(feature = "nyxd-client")]
pub use client::{Client, Config};
pub use client::{Client, CoconutApiClient, Config, NymApiClient};
@@ -46,25 +46,25 @@ pub enum NyxdError {
#[error("{0} is not a valid tx hash")]
InvalidTxHash(String),
#[error("There was an issue with a tendermint RPC request - {0}")]
#[error("Tendermint RPC request failed - {0}")]
TendermintError(#[from] TendermintRpcError),
#[error("There was an issue when attempting to serialize data ({0})")]
#[error("Failed when attempting to serialize data ({0})")]
SerializationError(String),
#[error("There was an issue when attempting to deserialize data ({0})")]
#[error("Failed when attempting to deserialize data ({0})")]
DeserializationError(String),
#[error("There was an issue when attempting to encode our protobuf data - {0}")]
#[error("Failed when attempting to encode our protobuf data - {0}")]
ProtobufEncodingError(#[from] prost::EncodeError),
#[error("There was an issue when attempting to decode our protobuf data - {0}")]
#[error("Failed to decode our protobuf data - {0}")]
ProtobufDecodingError(#[from] prost::DecodeError),
#[error("Account {0} does not exist on the chain")]
NonExistentAccountError(AccountId),
#[error("There was an issue with the serialization/deserialization - {0}")]
#[error("Failed on json serialization/deserialization - {0}")]
SerdeJsonError(#[from] serde_json::Error),
#[error("Account {0} is not a valid account address")]
@@ -17,11 +17,13 @@ use cosmrs::rpc::HttpClientUrl;
use cosmrs::tx::Msg;
use execute::execute;
use log::debug;
use mixnet_contract_common::MixId;
use network_defaults::{ChainDetails, NymNetworkDetails};
use serde::{Deserialize, Serialize};
use std::convert::TryInto;
use std::time::SystemTime;
use vesting_contract_common::ExecuteMsg as VestingExecuteMsg;
use vesting_contract_common::PledgeCap;
pub use crate::nyxd::cosmwasm_client::client::CosmWasmClient;
pub use crate::nyxd::cosmwasm_client::signing_client::SigningCosmWasmClient;
@@ -43,10 +45,8 @@ pub use cosmrs::Coin as CosmosCoin;
pub use cosmrs::{bip32, AccountId, Decimal, Denom};
pub use cosmwasm_std::Coin as CosmWasmCoin;
pub use fee::{gas_price::GasPrice, GasAdjustable, GasAdjustment};
use mixnet_contract_common::MixId;
pub use signing_client::Client as SigningNyxdClient;
pub use traits::{VestingQueryClient, VestingSigningClient};
use vesting_contract_common::PledgeCap;
pub mod coin;
pub mod cosmwasm_client;
+4 -4
View File
@@ -80,7 +80,7 @@ pub fn create_signing_client(
match NyxdClient::connect_with_mnemonic(client_config, nyxd_url, mnemonic, None) {
Ok(client) => Ok(client),
Err(e) => Err(ContextError::NyxdError(format!("{:?}", e))),
Err(e) => Err(ContextError::NyxdError(format!("{e}"))),
}
}
@@ -99,7 +99,7 @@ pub fn create_query_client(
match NyxdClient::connect(client_config, nyxd_url) {
Ok(client) => Ok(client),
Err(e) => Err(ContextError::NyxdError(format!("{:?}", e))),
Err(e) => Err(ContextError::NyxdError(format!("{e}"))),
}
}
@@ -122,7 +122,7 @@ pub fn create_signing_client_with_nym_api(
match validator_client::client::Client::new_signing(client_config, mnemonic) {
Ok(client) => Ok(client),
Err(e) => Err(ContextError::NyxdError(format!("{:?}", e))),
Err(e) => Err(ContextError::NyxdError(format!("{e}"))),
}
}
@@ -134,6 +134,6 @@ pub fn create_query_client_with_nym_api(
match validator_client::client::Client::new_query(client_config) {
Ok(client) => Ok(client),
Err(e) => Err(ContextError::NyxdError(format!("{:?}", e))),
Err(e) => Err(ContextError::NyxdError(format!("{e}"))),
}
}
+3 -3
View File
@@ -15,7 +15,7 @@ pub fn pretty_coin(coin: &Coin) -> String {
} else {
&coin.denom
};
format!("{} {}", amount, denom)
format!("{amount} {denom}")
}
pub fn pretty_cosmwasm_coin(coin: &CosmWasmCoin) -> String {
@@ -25,12 +25,12 @@ pub fn pretty_cosmwasm_coin(coin: &CosmWasmCoin) -> String {
} else {
&coin.denom
};
format!("{} {}", amount, denom)
format!("{amount} {denom}")
}
pub fn pretty_decimal_with_denom(value: Decimal, denom: &str) -> String {
// TODO: we might have to truncate the value here (that's why I moved it to separate function)
format!("{} {}", value, denom)
format!("{value} {denom}")
}
pub fn show_error<E>(e: E)
@@ -57,7 +57,7 @@ pub async fn query_balance(
if denom.is_empty() || denom.eq_ignore_ascii_case(&coin.denom) {
if args.raw {
if !args.hide_denom {
println!("{}", coin);
println!("{coin}");
} else {
println!("{}", coin.amount);
}
@@ -77,12 +77,12 @@ pub async fn get_pubkey_from_chain(address: AccountId, client: &QueryClient) {
if let Some(pubkey) = base_account.pubkey {
println!("{}", pubkey.to_string());
} else {
println!("No account associated with address {}", address);
println!("No account associated with address {address}");
}
}
}
Ok(None) => {
println!("No account associated with address {}", address);
println!("No account associated with address {address}");
}
Err(e) => show_error(e),
}
@@ -43,5 +43,5 @@ pub async fn generate(args: Args) {
let res =
serde_json::to_string(&instantiate_msg).expect("failed to convert instantiate msg to json");
println!("{}", res)
println!("{res}")
}
@@ -96,5 +96,5 @@ pub async fn generate(args: Args) {
let res =
serde_json::to_string(&instantiate_msg).expect("failed to convert instantiate msg to json");
println!("{}", res)
println!("{res}")
}
@@ -105,5 +105,5 @@ pub async fn generate(args: Args) {
let res =
serde_json::to_string(&instantiate_msg).expect("failed to convert instantiate msg to json");
println!("{}", res)
println!("{res}")
}
@@ -58,5 +58,5 @@ pub async fn generate(args: Args) {
let res =
serde_json::to_string(&instantiate_msg).expect("failed to convert instantiate msg to json");
println!("{}", res)
println!("{res}")
}
@@ -39,5 +39,5 @@ pub async fn generate(args: Args) {
let res =
serde_json::to_string(&instantiate_msg).expect("failed to convert instantiate msg to json");
println!("{}", res)
println!("{res}")
}
@@ -13,5 +13,5 @@ pub fn decode_mixnode_key(args: Args) {
let b64_decoded = base64::decode(args.key).expect("failed to decode base64 string");
let b58_encoded = bs58::encode(&b64_decoded).into_string();
println!("{}", b58_encoded)
println!("{b58_encoded}")
}
+19
View File
@@ -148,6 +148,25 @@ pub trait OptionalSet {
}
}
fn with_validated_optional<F, T, V, E>(
self,
f: F,
value: Option<T>,
validate: V,
) -> Result<Self, E>
where
F: Fn(Self, T) -> Self,
V: Fn(&T) -> Result<(), E>,
Self: Sized,
{
if let Some(val) = value {
validate(&val)?;
Ok(f(self, val))
} else {
Ok(self)
}
}
fn with_optional_env<F, T>(self, f: F, val: Option<T>, env_var: &str) -> Self
where
F: Fn(Self, T) -> Self,
@@ -31,7 +31,7 @@ impl Display for ContractSafeBytes {
write!(f, "0x")?;
}
for byte in self.0.iter().take(MAX_DISPLAY_SIZE) {
write!(f, "{:02X}", byte)?;
write!(f, "{byte:02X}")?;
}
// just some sanity safeguards
if self.0.len() > MAX_DISPLAY_SIZE {
@@ -73,7 +73,7 @@ impl Percent {
impl Display for Percent {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
let adjusted = Decimal::from_ratio(100u32, 1u32) * self.0;
write!(f, "{}%", adjusted)
write!(f, "{adjusted}%")
}
}
@@ -86,7 +86,7 @@ impl ToString for MixnetEventType {
MixnetEventType::DelegationOnUnbonding => "delegation_on_unbonding_node",
};
format!("{}{}", EVENT_VERSION_PREFIX, event_name)
format!("{EVENT_VERSION_PREFIX}{event_name}")
}
}
@@ -6,9 +6,9 @@ use cosmwasm_std::{Decimal, StdError, StdResult, Uint128};
pub fn compare_decimals(a: Decimal, b: Decimal, epsilon: Option<Decimal>) {
let epsilon = epsilon.unwrap_or_else(|| Decimal::from_ratio(1u128, 100_000_000u128));
if a > b {
assert!(a - b < epsilon, "{} != {}", a, b)
assert!(a - b < epsilon, "{a} != {b}")
} else {
assert!(b - a < epsilon, "{} != {}", a, b)
assert!(b - a < epsilon, "{a} != {b}")
}
}
@@ -241,30 +241,30 @@ impl ExecuteMsg {
pub fn default_memo(&self) -> String {
match self {
ExecuteMsg::AssignNodeLayer { mix_id, layer } => {
format!("assigning mix {} for layer {:?}", mix_id, layer)
format!("assigning mix {mix_id} for layer {layer:?}")
}
ExecuteMsg::CreateFamily { .. } => "crating node family with".to_string(),
ExecuteMsg::JoinFamily { family_head, .. } => {
format!("joining family {}", family_head)
format!("joining family {family_head}")
}
ExecuteMsg::LeaveFamily { family_head, .. } => {
format!("leaving family {}", family_head)
format!("leaving family {family_head}")
}
ExecuteMsg::KickFamilyMember { member, .. } => {
format!("kicking {} from family", member)
format!("kicking {member} from family")
}
ExecuteMsg::CreateFamilyOnBehalf { .. } => "crating node family with".to_string(),
ExecuteMsg::JoinFamilyOnBehalf { family_head, .. } => {
format!("joining family {}", family_head)
format!("joining family {family_head}")
}
ExecuteMsg::LeaveFamilyOnBehalf { family_head, .. } => {
format!("leaving family {}", family_head)
format!("leaving family {family_head}")
}
ExecuteMsg::KickFamilyMemberOnBehalf { member, .. } => {
format!("kicking {} from family", member)
format!("kicking {member} from family")
}
ExecuteMsg::UpdateRewardingValidatorAddress { address } => {
format!("updating rewarding validator to {}", address)
format!("updating rewarding validator to {address}")
}
ExecuteMsg::UpdateContractStateParams { .. } => {
"updating mixnet state parameters".into()
@@ -273,21 +273,14 @@ impl ExecuteMsg {
active_set_size,
force_immediately,
} => format!(
"updating active set size to {}. forced: {}",
active_set_size, force_immediately
"updating active set size to {active_set_size}. forced: {force_immediately}"
),
ExecuteMsg::UpdateRewardingParams {
force_immediately, ..
} => format!(
"updating mixnet rewarding parameters. forced: {}",
force_immediately
),
} => format!("updating mixnet rewarding parameters. forced: {force_immediately}"),
ExecuteMsg::UpdateIntervalConfig {
force_immediately, ..
} => format!(
"updating mixnet interval configuration. forced: {}",
force_immediately
),
} => format!("updating mixnet interval configuration. forced: {force_immediately}"),
ExecuteMsg::AdvanceCurrentEpoch { .. } => "advancing current epoch".into(),
ExecuteMsg::ReconcileEpochEvents { .. } => "reconciling epoch events".into(),
ExecuteMsg::BondMixnode { mix_node, .. } => {
@@ -316,34 +309,30 @@ impl ExecuteMsg {
}
ExecuteMsg::UnbondGateway { .. } => "unbonding gateway".into(),
ExecuteMsg::UnbondGatewayOnBehalf { .. } => "unbonding gateway on behalf".into(),
ExecuteMsg::DelegateToMixnode { mix_id } => format!("delegating to mixnode {}", mix_id),
ExecuteMsg::DelegateToMixnode { mix_id } => format!("delegating to mixnode {mix_id}"),
ExecuteMsg::DelegateToMixnodeOnBehalf { mix_id, .. } => {
format!("delegating to mixnode {} on behalf", mix_id)
format!("delegating to mixnode {mix_id} on behalf")
}
ExecuteMsg::UndelegateFromMixnode { mix_id } => {
format!("removing delegation from mixnode {}", mix_id)
format!("removing delegation from mixnode {mix_id}")
}
ExecuteMsg::UndelegateFromMixnodeOnBehalf { mix_id, .. } => {
format!("removing delegation from mixnode {} on behalf", mix_id)
format!("removing delegation from mixnode {mix_id} on behalf")
}
ExecuteMsg::RewardMixnode {
mix_id,
performance,
} => format!(
"rewarding mixnode {} for performance {}",
mix_id, performance
),
} => format!("rewarding mixnode {mix_id} for performance {performance}"),
ExecuteMsg::WithdrawOperatorReward { .. } => "withdrawing operator reward".into(),
ExecuteMsg::WithdrawOperatorRewardOnBehalf { .. } => {
"withdrawing operator reward on behalf".into()
}
ExecuteMsg::WithdrawDelegatorReward { mix_id } => {
format!("withdrawing delegator reward from mixnode {}", mix_id)
format!("withdrawing delegator reward from mixnode {mix_id}")
}
ExecuteMsg::WithdrawDelegatorRewardOnBehalf { mix_id, .. } => {
format!("withdrawing delegator reward from mixnode {mix_id} on behalf")
}
ExecuteMsg::WithdrawDelegatorRewardOnBehalf { mix_id, .. } => format!(
"withdrawing delegator reward from mixnode {} on behalf",
mix_id
),
#[cfg(feature = "contract-testing")]
ExecuteMsg::TestingResolveAllPendingEvents { .. } => {
"resolving all pending events".into()
@@ -64,7 +64,7 @@ impl FromStr for PledgeCap {
Ok(p) => Ok(PledgeCap::Percent(p)),
Err(_) => match cap.parse::<u128>() {
Ok(i) => Ok(PledgeCap::Absolute(Uint128::from(i))),
Err(_e) => Err(format!("Could not parse {} as Percent or Uint128", cap)),
Err(_e) => Err(format!("Could not parse {cap} as Percent or Uint128")),
},
}
}
+2 -2
View File
@@ -11,9 +11,9 @@ async-trait = { version = "0.1.51" }
log = "0.4"
sqlx = { version = "0.5", features = ["runtime-tokio-rustls", "sqlite", "macros", "migrate"]}
thiserror = "1.0"
tokio = { version = "1.21.2", features = [ "rt-multi-thread", "net", "signal", "fs" ] }
tokio = { version = "1.24.1", features = [ "rt-multi-thread", "net", "signal", "fs" ] }
[build-dependencies]
sqlx = { version = "0.5", features = ["runtime-tokio-rustls", "sqlite", "macros", "migrate"] }
tokio = { version = "1.21.2", features = ["rt-multi-thread", "macros"] }
tokio = { version = "1.24.1", features = ["rt-multi-thread", "macros"] }
+2 -2
View File
@@ -9,9 +9,9 @@ use std::env;
#[tokio::main]
async fn main() {
let out_dir = env::var("OUT_DIR").unwrap();
let database_path = format!("{}/coconut-credential-example.sqlite", out_dir);
let database_path = format!("{out_dir}/coconut-credential-example.sqlite");
let mut conn = SqliteConnection::connect(&format!("sqlite://{}?mode=rwc", database_path))
let mut conn = SqliteConnection::connect(&format!("sqlite://{database_path}?mode=rwc"))
.await
.expect("Failed to create SQLx database connection");
+1 -4
View File
@@ -224,10 +224,7 @@ impl DecryptionKey {
let mut dh = Vec::with_capacity(dh_len);
for j in 0..dh_len {
let dh_i = deserialize_g2(&bytes[i..i + 96]).ok_or_else(|| {
DkgError::new_deserialization_failure(
format!("Node.dh_{}", j),
"invalid curve point",
)
DkgError::new_deserialization_failure(format!("Node.dh_{j}"), "invalid curve point")
})?;
dh.push(dh_i);
+1 -1
View File
@@ -60,7 +60,7 @@ pub fn setup() -> Params {
let f0 = hash_g2(b"f0", SETUP_DOMAIN);
let fh = (0..HASH_SECURITY_PARAM)
.map(|i| hash_g2(format!("fh{}", i), SETUP_DOMAIN))
.map(|i| hash_g2(format!("fh{i}"), SETUP_DOMAIN))
.collect();
let h = hash_g2(b"h", SETUP_DOMAIN);
@@ -21,8 +21,7 @@ pub fn validate_bech32_prefix(bech32_prefix: &str, address: &str) -> Result<(),
Ok(())
} else {
Err(Bech32Error::WrongPrefix(format!(
"your bech32 address prefix should be {}, not {}",
bech32_prefix, prefix
"your bech32 address prefix should be {bech32_prefix}, not {prefix}"
)))
}
}
@@ -70,8 +69,7 @@ mod tests {
fn wrong_prefix_fails() {
assert_eq!(
Err(Bech32Error::WrongPrefix(format!(
"your bech32 address prefix should be {}, not punk",
TEST_BECH32_PREFIX
"your bech32 address prefix should be {TEST_BECH32_PREFIX}, not punk"
))),
validate_bech32_prefix(
TEST_BECH32_PREFIX,
+1 -1
View File
@@ -7,4 +7,4 @@ edition = "2021"
[dependencies]
log = "0.4.0"
pretty_env_logger = "0.4.0"
pretty_env_logger = "0.4.0"
+17
View File
@@ -23,3 +23,20 @@ pub fn setup_logging() {
.filter_module("sled", log::LevelFilter::Warn)
.init();
}
pub fn banner(crate_name: &str, crate_version: &str) -> String {
format!(
r#"
_ __ _ _ _ __ ___
| '_ \| | | | '_ \ _ \
| | | | |_| | | | | | |
|_| |_|\__, |_| |_| |_|
|___/
({:} - version {:})
"#,
crate_name, crate_version
)
}
+2 -2
View File
@@ -13,8 +13,8 @@ humantime-serde = "1.0"
log = "0.4"
rand = "0.8"
serde = { version = "1.0", features = ["derive"] }
tokio = { version = "1.21.2", features = ["time", "macros", "rt", "net", "io-util"] }
tokio-util = { version = "0.7.3", features = ["codec"] }
tokio = { version = "1.24.1", features = ["time", "macros", "rt", "net", "io-util"] }
tokio-util = { version = "0.7.4", features = ["codec"] }
url = "2.2"
thiserror = "1.0.37"
+5 -5
View File
@@ -53,19 +53,19 @@ impl Display for RttError {
write!(f, "The received reply packet had invalid signature")
}
RttError::UnreachableNode(id, err) => {
write!(f, "Could not establish connection to {} - {err}", id)
write!(f, "Could not establish connection to {id} - {err}")
}
RttError::UnexpectedConnectionFailureWrite(id, err) => {
write!(f, "Failed to write echo packet to {} - {err}", id)
write!(f, "Failed to write echo packet to {id} - {err}")
}
RttError::UnexpectedConnectionFailureRead(id, err) => {
write!(f, "Failed to read reply packet from {} - {err}", id)
write!(f, "Failed to read reply packet from {id} - {err}")
}
RttError::ConnectionReadTimeout(id) => {
write!(f, "Timed out while trying to read reply packet from {}", id)
write!(f, "Timed out while trying to read reply packet from {id}")
}
RttError::ConnectionWriteTimeout(id) => {
write!(f, "Timed out while trying to write echo packet to {}", id)
write!(f, "Timed out while trying to write echo packet to {id}")
}
RttError::UnexpectedReplySequence => write!(
f,
+1 -1
View File
@@ -153,7 +153,7 @@ impl Default for ConfigBuilder {
fn default() -> Self {
ConfigBuilder(Config {
minimum_compatible_node_version: parse_version(MINIMUM_NODE_VERSION).unwrap(),
listening_address: format!("[::]:{}", DEFAULT_VERLOC_PORT).parse().unwrap(),
listening_address: format!("[::]:{DEFAULT_VERLOC_PORT}").parse().unwrap(),
packets_per_node: DEFAULT_PACKETS_PER_NODE,
packet_timeout: DEFAULT_PACKET_TIMEOUT,
connection_timeout: DEFAULT_CONNECTION_TIMEOUT,
+3 -3
View File
@@ -11,7 +11,7 @@ pub const STAKE_DENOM: DenomDetails = DenomDetails::new("unyx", "nyx", 6);
pub const MIXNET_CONTRACT_ADDRESS: &str =
"n17srjznxl9dvzdkpwpw24gg668wc73val88a6m5ajg6ankwvz9wtst0cznr";
pub(crate) const VESTING_CONTRACT_ADDRESS: &str =
pub const VESTING_CONTRACT_ADDRESS: &str =
"n1nc5tatafv6eyq7llkr2gv50ff9e22mnf70qgjlv737ktmt4eswrq73f2nw";
pub(crate) const BANDWIDTH_CLAIM_CONTRACT_ADDRESS: &str =
"n19lc9u84cz0yz3fww5283nucc9yvr8gsjmgeul0";
@@ -36,7 +36,7 @@ const DEFAULT_SUFFIX: &str = "_MAINNET_DEFAULT";
fn set_var_to_default(var: &str, value: &str) {
std::env::set_var(var, value);
std::env::set_var(format!("{}{}", var, DEFAULT_SUFFIX), "1")
std::env::set_var(format!("{var}{DEFAULT_SUFFIX}"), "1")
}
fn set_var_conditionally_to_default(var: &str, value: &str) {
@@ -46,7 +46,7 @@ fn set_var_conditionally_to_default(var: &str, value: &str) {
}
pub fn uses_default(var: &str) -> bool {
std::env::var(format!("{}{}", var, DEFAULT_SUFFIX)).is_ok()
std::env::var(format!("{var}{DEFAULT_SUFFIX}")).is_ok()
}
pub fn read_var_if_not_default(var: &str) -> Option<String> {
+3 -3
View File
@@ -7,9 +7,9 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
tokio = { version = "1.21.2", features = [] }
tokio-stream = "0.1.9" # this one seems to be a thing until `Stream` trait is stabilised in stdlib
tokio-util = { version = "0.7.3", features = ["time"] }
tokio = { version = "1.24.1", features = [] }
tokio-stream = "0.1.11" # this one seems to be a thing until `Stream` trait is stabilised in stdlib
tokio-util = { version = "0.7.4", features = ["time"] }
[target."cfg(target_arch = \"wasm32\")".dependencies.wasm-timer]
git = "https://github.com/mmsinclair/wasm-timer"
+2 -4
View File
@@ -68,8 +68,7 @@ impl TryFrom<&[u8]> for SecretKey {
if ys_len as usize != actual_ys_len {
return Err(CoconutError::Deserialization(format!(
"Tried to deserialize secret key with inconsistent ys len (expected {}, got {})",
ys_len, actual_ys_len
"Tried to deserialize secret key with inconsistent ys len (expected {ys_len}, got {actual_ys_len})"
)));
}
@@ -185,8 +184,7 @@ impl TryFrom<&[u8]> for VerificationKey {
if betas_len as usize != actual_betas_len {
return Err(
CoconutError::Deserialization(
format!("Tried to deserialize verification key with inconsistent betas len (expected {}, got {})",
betas_len, actual_betas_len
format!("Tried to deserialize verification key with inconsistent betas len (expected {betas_len}, got {actual_betas_len})"
)));
}
+1 -1
View File
@@ -33,7 +33,7 @@ impl Parameters {
}
let hs = (1..=num_attributes)
.map(|i| hash_g1(format!("h{}", i)).to_affine())
.map(|i| hash_g1(format!("h{i}")).to_affine())
.collect();
Ok(Parameters {
+1 -1
View File
@@ -34,5 +34,5 @@ mixnet-contract-common = { path = "../cosmwasm-smart-contracts/mixnet-contract"
path = "framing"
[target."cfg(not(target_arch = \"wasm32\"))".dependencies.tokio]
version = "1.21.2"
version = "1.24.1"
features = ["sync"]
+1 -1
View File
@@ -8,7 +8,7 @@ edition = "2021"
[dependencies]
bytes = "1.0"
tokio-util = { version = "0.7.3", features = ["codec"] }
tokio-util = { version = "0.7.4", features = ["codec"] }
thiserror = "1.0.37"
nymsphinx-types = { path = "../types" }
+2 -7
View File
@@ -11,10 +11,11 @@ pub struct InvalidPacketMode {
}
#[repr(u8)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum PacketMode {
/// Represents 'normal' packet sent through the network that should be delayed by an appropriate
/// value at each hop.
#[default]
Mix = 0,
/// Represents a VPN packet that should not be delayed and ideally cached pre-computed keys
@@ -43,9 +44,3 @@ impl TryFrom<u8> for PacketMode {
}
}
}
impl Default for PacketMode {
fn default() -> Self {
PacketMode::Mix
}
}
+2 -7
View File
@@ -34,9 +34,10 @@ pub enum InvalidPacketSize {
}
#[repr(u8)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum PacketSize {
// for example instant messaging use case
#[default]
RegularPacket = 1,
// for sending SURB-ACKs
@@ -136,9 +137,3 @@ impl PacketSize {
}
}
}
impl Default for PacketSize {
fn default() -> Self {
PacketSize::RegularPacket
}
}
+2 -2
View File
@@ -8,8 +8,8 @@ edition = "2021"
[dependencies]
bytes = "1.0"
tokio = { version = "1.21.2", features = [ "net", "io-util", "sync", "macros", "time", "rt-multi-thread" ] }
tokio-util = { version = "0.7.3", features = [ "io" ] } # reason for getting this guy is to to able to port to tokio 1.X more quickly by being able to use
tokio = { version = "1.24.1", features = [ "net", "io-util", "sync", "macros", "time", "rt-multi-thread" ] }
tokio-util = { version = "0.7.4", features = [ "io" ] } # reason for getting this guy is to to able to port to tokio 1.X more quickly by being able to use
# their `read_buf` [from the util crate] replacement rather than having to rethink/reimplement `AvailableReader` with the new AsyncRead trait definition.
# In the long run, the dependency should probably get removed in favour of pure-tokio implementation, but for time being it's fine.
futures = "0.3"
@@ -54,7 +54,7 @@ where
Some(data) => match data {
Ok(data) => (data, false),
Err(err) => {
error!(target: &*format!("({}) socks5 inbound", connection_id), "failed to read request from the socket - {err}");
error!(target: &*format!("({connection_id}) socks5 inbound"), "failed to read request from the socket - {err}");
(Default::default(), true)
}
},
@@ -62,7 +62,7 @@ where
};
debug!(
target: &*format!("({}) socks5 inbound", connection_id),
target: &*format!("({connection_id}) socks5 inbound"),
"[{} bytes]\t{} → local → mixnet → remote → {}. Local closed: {}",
read_data.len(),
local_destination_address,
@@ -103,7 +103,7 @@ where
// Technically we already informed it when we sent the message to mixnet above
debug!(
target: &*format!("({}) socks5 inbound", connection_id),
target: &*format!("({connection_id}) socks5 inbound"),
"The local socket is closed - won't receive any more data. Informing remote about that..."
);
}
@@ -23,7 +23,7 @@ async fn deal_with_message(
connection_id: ConnectionId,
) -> bool {
debug!(
target: &*format!("({}) socks5 outbound", connection_id),
target: &*format!("({connection_id}) socks5 outbound"),
"[{} bytes]\t{} → remote → mixnet → local → {} Remote closed: {}",
connection_message.payload.len(),
remote_source_address,
@@ -33,11 +33,11 @@ async fn deal_with_message(
if let Err(err) = writer.write_all(&connection_message.payload).await {
// the other half is probably going to blow up too (if not, this task also needs to notify the other one!!)
error!(target: &*format!("({}) socks5 outbound", connection_id), "failed to write response back to the socket - {err}");
error!(target: &*format!("({connection_id}) socks5 outbound"), "failed to write response back to the socket - {err}");
return true;
}
if connection_message.socket_closed {
debug!(target: &*format!("({}) socks5 outbound", connection_id),
debug!(target: &*format!("({connection_id}) socks5 outbound"),
"Remote socket got closed - closing the local socket too");
return true;
}
+1 -1
View File
@@ -16,4 +16,4 @@ serde = { version = "1.0", features = ["derive"] }
serde_json = "1"
sqlx = { version = "0.5", features = ["runtime-tokio-rustls", "chrono"]}
thiserror = "1"
tokio = { version = "1.21.2", features = [ "time" ] }
tokio = { version = "1.24.1", features = [ "time" ] }
+2 -7
View File
@@ -16,8 +16,7 @@ pub async fn build_and_send_statistics_request(
) -> Result<(), StatsError> {
reqwest::Client::new()
.post(format!(
"{}{}/{}",
url, STATISTICS_SERVICE_VERSION, STATISTICS_SERVICE_API_STATISTICS
"{url}{STATISTICS_SERVICE_VERSION}/{STATISTICS_SERVICE_API_STATISTICS}"
))
.json(&msg)
.send()
@@ -32,11 +31,7 @@ pub fn build_statistics_request_bytes(msg: StatsMessage) -> Result<Vec<u8>, Stat
let req = reqwest::Request::new(
reqwest::Method::POST,
reqwest::Url::parse(&format!(
"http://{}:{}{}/{}",
DEFAULT_STATISTICS_SERVICE_ADDRESS,
DEFAULT_STATISTICS_SERVICE_PORT,
STATISTICS_SERVICE_VERSION,
STATISTICS_SERVICE_API_STATISTICS
"http://{DEFAULT_STATISTICS_SERVICE_ADDRESS}:{DEFAULT_STATISTICS_SERVICE_PORT}{STATISTICS_SERVICE_VERSION}/{STATISTICS_SERVICE_API_STATISTICS}"
))
.unwrap(),
);
+3 -3
View File
@@ -9,10 +9,10 @@ edition = "2021"
futures = "0.3"
log = "0.4"
thiserror = "1.0.37"
tokio = { version = "1.21.2", features = ["macros", "sync"] }
tokio = { version = "1.24.1", features = ["macros", "sync"] }
[target."cfg(not(target_arch = \"wasm32\"))".dependencies.tokio]
version = "1.21.2"
version = "1.24.1"
features = ["signal", "time"]
[target."cfg(target_arch = \"wasm32\")".dependencies.wasm-bindgen-futures]
@@ -22,4 +22,4 @@ version = "0.4"
version = "0.2.83"
[dev-dependencies]
tokio = { version = "1.21.2", features = ["rt-multi-thread", "net", "signal", "test-util", "macros"] }
tokio = { version = "1.24.1", features = ["rt-multi-thread", "net", "signal", "test-util", "macros"] }
+1 -1
View File
@@ -8,6 +8,6 @@ pub mod spawn;
pub use manager::{StatusReceiver, StatusSender, TaskClient, TaskManager};
#[cfg(not(target_arch = "wasm32"))]
pub use signal::{wait_for_signal, wait_for_signal_and_error};
pub use signal::wait_for_signal_and_error;
pub use spawn::spawn_with_report_error;
+25
View File
@@ -1,6 +1,7 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use std::future::Future;
use std::{error::Error, time::Duration};
use futures::{future::pending, FutureExt, SinkExt, StreamExt};
@@ -92,6 +93,19 @@ impl TaskManager {
}
}
#[cfg(not(target_arch = "wasm32"))]
pub async fn catch_interrupt(mut self) -> Result<(), SentError> {
let res = crate::wait_for_signal_and_error(&mut self).await;
log::info!("Sending shutdown");
self.signal_shutdown().ok();
log::info!("Waiting for tasks to finish... (Press ctrl-c to force)");
self.wait_for_shutdown().await;
res
}
pub fn subscribe(&self) -> TaskClient {
TaskClient::new(
self.notify_rx
@@ -226,6 +240,17 @@ impl TaskClient {
}
}
pub async fn run_future<Fut, T>(&mut self, fut: Fut) -> Option<T>
where
Fut: Future<Output = T>,
{
tokio::select! {
biased;
_ = self.recv() => None,
res = fut => Some(res)
}
}
// Create a dummy that will never report that we should shutdown.
pub fn dummy() -> TaskClient {
let (_notify_tx, notify_rx) = watch::channel(());
+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");
+1 -5
View File
@@ -194,10 +194,6 @@ impl fmt::Display for MixnodeNodeDetailsResponse {
"Mix Port: {}, Verloc port: {}, Http Port: {}\n",
self.mix_port, self.verloc_port, self.http_api_port
)?;
writeln!(
f,
"You are bonding to wallet address: {}\n\n",
wallet_address
)
writeln!(f, "You are bonding to wallet address: {wallet_address}\n\n")
}
}
+2 -2
View File
@@ -618,7 +618,7 @@ pub fn query(deps: Deps<'_>, env: Env, msg: QueryMsg) -> Result<QueryResponse, C
QueryMsg::GetAccountsVestingCoinsPaged {
start_next_after,
limit,
} => to_binary(&try_get_all_accounts_locked_coins(
} => to_binary(&try_get_all_accounts_vesting_coins(
deps,
env,
start_next_after,
@@ -775,7 +775,7 @@ pub fn try_get_all_accounts(
})
}
pub fn try_get_all_accounts_locked_coins(
pub fn try_get_all_accounts_vesting_coins(
deps: Deps<'_>,
env: Env,
start_after: Option<String>,

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