Compare commits
107 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f9b90ee62b | |||
| f04fc452dc | |||
| be90d03129 | |||
| 0a3e42700c | |||
| 55d554701c | |||
| 19c4769260 | |||
| 71aadc8e1b | |||
| 95340b5817 | |||
| 12751665bb | |||
| 01b86bcc0d | |||
| c6ce8caaf7 | |||
| 265713b9d2 | |||
| c9af4721f3 | |||
| 8c0ab7c697 | |||
| 92b220ca4b | |||
| c218cba96c | |||
| c958975fff | |||
| c2d28740a5 | |||
| 9ab3a133d9 | |||
| f3b82fa032 | |||
| 5d385ba10f | |||
| f4d0a120bb | |||
| 027b0dbc39 | |||
| 130ac50834 | |||
| 5711230ae3 | |||
| 4db656d074 | |||
| 95080c3ecc | |||
| 17771b5742 | |||
| 48af0ae6b4 | |||
| 4c19187c78 | |||
| e1ec3594ea | |||
| ded7e51071 | |||
| b75199e4dc | |||
| a0ed1c8edd | |||
| a693fa9190 | |||
| e83e83abed | |||
| d03f769b14 | |||
| 86e9463c42 | |||
| 5376c2a4ba | |||
| cbeac10383 | |||
| 63a4bdf5a6 | |||
| 0e0a62938d | |||
| f1d0bd0bf4 | |||
| 404473c128 | |||
| a980d6f804 | |||
| c6a5e08188 | |||
| b2ed078e0f | |||
| 886e2ed5e7 | |||
| aa545ee6c6 | |||
| 62741889bc | |||
| 64c963e36e | |||
| d6f87c40ed | |||
| 39562e653a | |||
| e548d6f1f8 | |||
| 48def795d9 | |||
| 80017d258d | |||
| 6d6d9d4359 | |||
| 59185f3b87 | |||
| c708a7cc12 | |||
| ea35a37d4c | |||
| e40d25a97b | |||
| cf903aa2e5 | |||
| 0a2e0d6a8f | |||
| 8eb3dbd191 | |||
| a0661fecb2 | |||
| ea68d42886 | |||
| d4298c61a0 | |||
| 65ed611c24 | |||
| d713b926f8 | |||
| f305901a18 | |||
| 082a8ad8ee | |||
| 031092815b | |||
| 645cb88074 | |||
| 6b96e474f7 | |||
| f4fd08f64e | |||
| 78247b973b | |||
| 6b52132501 | |||
| d2f33180e2 | |||
| dc71f6e94d | |||
| cc7161c113 | |||
| bbb46ebd90 | |||
| bc3fd236d8 | |||
| ea95288940 | |||
| b182ed6925 | |||
| 017c9d2504 | |||
| 50c7d717c0 | |||
| b473aeb3be | |||
| ac10e03aec | |||
| fe2e1c29a2 | |||
| 2eee5195cc | |||
| 3bd4343a39 | |||
| 74feb065f9 | |||
| 65b819c649 | |||
| bd12305a68 | |||
| 4854e929ed | |||
| 5709c45a50 | |||
| a7f1242961 | |||
| 8b14321c4a | |||
| 5f88517e1d | |||
| dddc6eae57 | |||
| c7d8f3af97 | |||
| 1e84f87bf5 | |||
| 70ae45b6c9 | |||
| 96444509d0 | |||
| aab91e424e | |||
| 0628565684 | |||
| 280ac34115 |
@@ -26,7 +26,7 @@ jobs:
|
|||||||
path: .github/workflows/support-files/notifications/deny.message
|
path: .github/workflows/support-files/notifications/deny.message
|
||||||
notification:
|
notification:
|
||||||
needs: cargo-deny
|
needs: cargo-deny
|
||||||
runs-on: ubuntu-20.04
|
runs-on: custom-runner-linux
|
||||||
steps:
|
steps:
|
||||||
- name: Check out repository code
|
- name: Check out repository code
|
||||||
uses: actions/checkout@v2
|
uses: actions/checkout@v2
|
||||||
@@ -35,6 +35,10 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
name: report
|
name: report
|
||||||
path: .github/workflows/support-files/notifications
|
path: .github/workflows/support-files/notifications
|
||||||
|
- name: install npm
|
||||||
|
uses: actions/setup-node@v3
|
||||||
|
with:
|
||||||
|
node-version: 16
|
||||||
- name: Keybase - Node Install
|
- name: Keybase - Node Install
|
||||||
run: npm install
|
run: npm install
|
||||||
working-directory: .github/workflows/support-files
|
working-directory: .github/workflows/support-files
|
||||||
|
|||||||
@@ -0,0 +1,113 @@
|
|||||||
|
name: Build and upload binaries to CI
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
push:
|
||||||
|
paths:
|
||||||
|
- 'clients/**'
|
||||||
|
- 'common/**'
|
||||||
|
- 'contracts/**'
|
||||||
|
- 'explorer-api/**'
|
||||||
|
- 'gateway/**'
|
||||||
|
- 'integrations/**'
|
||||||
|
- 'mixnode/**'
|
||||||
|
- 'sdk/rust/nym-sdk/**'
|
||||||
|
- 'service-providers/**'
|
||||||
|
- 'nym-api/**'
|
||||||
|
- 'nym-outfox/**'
|
||||||
|
- 'tools/nym-cli/**'
|
||||||
|
- 'tools/ts-rs-cli/**'
|
||||||
|
pull_request:
|
||||||
|
paths:
|
||||||
|
- 'clients/**'
|
||||||
|
- 'common/**'
|
||||||
|
- 'contracts/**'
|
||||||
|
- 'explorer-api/**'
|
||||||
|
- 'gateway/**'
|
||||||
|
- 'integrations/**'
|
||||||
|
- 'mixnode/**'
|
||||||
|
- 'sdk/rust/nym-sdk/**'
|
||||||
|
- 'service-providers/**'
|
||||||
|
- 'nym-api/**'
|
||||||
|
- 'nym-outfox/**'
|
||||||
|
- 'tools/nym-cli/**'
|
||||||
|
- 'tools/ts-rs-cli/**'
|
||||||
|
|
||||||
|
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: Prepare build output directory
|
||||||
|
shell: bash
|
||||||
|
env:
|
||||||
|
OUTPUT_DIR: ci-builds/${{ github.ref_name }}
|
||||||
|
run: |
|
||||||
|
rm -rf ci-builds || true
|
||||||
|
mkdir -p $OUTPUT_DIR
|
||||||
|
echo $OUTPUT_DIR
|
||||||
|
|
||||||
|
- 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
|
||||||
|
continue-on-error: true
|
||||||
|
|
||||||
|
- name: Install Rust stable
|
||||||
|
uses: actions-rs/toolchain@v1
|
||||||
|
with:
|
||||||
|
toolchain: stable
|
||||||
|
|
||||||
|
- name: Build all binaries
|
||||||
|
uses: actions-rs/cargo@v1
|
||||||
|
with:
|
||||||
|
command: build
|
||||||
|
args: --workspace --release
|
||||||
|
|
||||||
|
- name: Install Rust stable
|
||||||
|
uses: actions-rs/toolchain@v1
|
||||||
|
with:
|
||||||
|
toolchain: stable
|
||||||
|
target: wasm32-unknown-unknown
|
||||||
|
override: true
|
||||||
|
components: rustfmt, clippy
|
||||||
|
|
||||||
|
- name: Build release contracts
|
||||||
|
run: make wasm
|
||||||
|
|
||||||
|
- name: Prepare build output
|
||||||
|
shell: bash
|
||||||
|
env:
|
||||||
|
OUTPUT_DIR: ci-builds/${{ github.ref_name }}
|
||||||
|
run: |
|
||||||
|
cp target/release/nym-client $OUTPUT_DIR
|
||||||
|
cp target/release/nym-gateway $OUTPUT_DIR
|
||||||
|
cp target/release/nym-mixnode $OUTPUT_DIR
|
||||||
|
cp target/release/nym-socks5-client $OUTPUT_DIR
|
||||||
|
cp target/release/nym-api $OUTPUT_DIR
|
||||||
|
cp target/release/nym-network-requester $OUTPUT_DIR
|
||||||
|
cp target/release/nym-network-statistics $OUTPUT_DIR
|
||||||
|
cp target/release/nym-cli $OUTPUT_DIR
|
||||||
|
|
||||||
|
cp contracts/target/wasm32-unknown-unknown/release/mixnet_contract.wasm $OUTPUT_DIR
|
||||||
|
cp contracts/target/wasm32-unknown-unknown/release/vesting_contract.wasm $OUTPUT_DIR
|
||||||
|
|
||||||
|
- name: Deploy branch to CI www
|
||||||
|
continue-on-error: true
|
||||||
|
uses: easingthemes/ssh-deploy@main
|
||||||
|
env:
|
||||||
|
SSH_PRIVATE_KEY: ${{ secrets.CI_WWW_SSH_PRIVATE_KEY }}
|
||||||
|
ARGS: "-avzr"
|
||||||
|
SOURCE: "ci-builds/"
|
||||||
|
REMOTE_HOST: ${{ secrets.CI_WWW_REMOTE_HOST }}
|
||||||
|
REMOTE_USER: ${{ secrets.CI_WWW_REMOTE_USER }}
|
||||||
|
TARGET: ${{ secrets.CI_WWW_REMOTE_TARGET }}/builds/
|
||||||
|
EXCLUDE: "/dist/, /node_modules/"
|
||||||
|
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
name: Build and upload binaries to artifact storage
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
add_tokio_unstable:
|
||||||
|
description: 'True to add RUSTFLAGS="--cfg tokio_unstable"'
|
||||||
|
required: true
|
||||||
|
default: false
|
||||||
|
type: boolean
|
||||||
|
|
||||||
|
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
|
||||||
|
continue-on-error: true
|
||||||
|
|
||||||
|
- name: Sets env vars for tokio if set in manual dispatch inputs
|
||||||
|
run: |
|
||||||
|
echo 'RUSTFLAGS="--cfg tokio_unstable"' >> $GITHUB_ENV
|
||||||
|
if: github.event_name == 'workflow_dispatch' && inputs.add_tokio_unstable == true
|
||||||
|
|
||||||
|
- name: Install Rust stable
|
||||||
|
uses: actions-rs/toolchain@v1
|
||||||
|
with:
|
||||||
|
toolchain: stable
|
||||||
|
|
||||||
|
- name: Build all binaries
|
||||||
|
uses: actions-rs/cargo@v1
|
||||||
|
with:
|
||||||
|
command: build
|
||||||
|
args: --workspace --release
|
||||||
|
|
||||||
|
- name: Upload Artifact
|
||||||
|
uses: actions/upload-artifact@v3
|
||||||
|
with:
|
||||||
|
name: nym-binaries-artifacts
|
||||||
|
path: |
|
||||||
|
target/release/nym-client
|
||||||
|
target/release/nym-gateway
|
||||||
|
target/release/nym-mixnode
|
||||||
|
target/release/nym-socks5-client
|
||||||
|
target/release/nym-api
|
||||||
|
target/release/nym-network-requester
|
||||||
|
target/release/nym-network-statistics
|
||||||
|
target/release/nym-cli
|
||||||
|
retention-days: 30
|
||||||
@@ -12,6 +12,7 @@ jobs:
|
|||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v2
|
||||||
- name: Install rsync
|
- name: Install rsync
|
||||||
run: sudo apt-get install rsync
|
run: sudo apt-get install rsync
|
||||||
|
continue-on-error: true
|
||||||
- uses: rlespinasse/github-slug-action@v3.x
|
- uses: rlespinasse/github-slug-action@v3.x
|
||||||
- uses: actions/setup-node@v3
|
- uses: actions/setup-node@v3
|
||||||
with:
|
with:
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- name: Install Dependencies (Linux)
|
- 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
|
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
|
||||||
|
continue-on-error: true
|
||||||
|
|
||||||
- name: Check out repository code
|
- name: Check out repository code
|
||||||
uses: actions/checkout@v2
|
uses: actions/checkout@v2
|
||||||
@@ -41,6 +42,12 @@ jobs:
|
|||||||
command: build
|
command: build
|
||||||
args: --workspace
|
args: --workspace
|
||||||
|
|
||||||
|
- name: Build all examples
|
||||||
|
uses: actions-rs/cargo@v1
|
||||||
|
with:
|
||||||
|
command: build
|
||||||
|
args: --workspace --examples
|
||||||
|
|
||||||
- name: Run all tests
|
- name: Run all tests
|
||||||
uses: actions-rs/cargo@v1
|
uses: actions-rs/cargo@v1
|
||||||
with:
|
with:
|
||||||
@@ -56,6 +63,7 @@ jobs:
|
|||||||
|
|
||||||
- uses: actions-rs/clippy-check@v1
|
- uses: actions-rs/clippy-check@v1
|
||||||
name: Clippy checks
|
name: Clippy checks
|
||||||
|
continue-on-error: true
|
||||||
with:
|
with:
|
||||||
token: ${{ secrets.GITHUB_TOKEN }}
|
token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
args: --workspace --all-features
|
args: --workspace --all-features
|
||||||
@@ -64,7 +72,7 @@ jobs:
|
|||||||
uses: actions-rs/cargo@v1
|
uses: actions-rs/cargo@v1
|
||||||
with:
|
with:
|
||||||
command: clippy
|
command: clippy
|
||||||
args: --workspace -- -D warnings
|
args: --workspace --all-targets --all-features -- -D warnings
|
||||||
|
|
||||||
# COCONUT stuff
|
# COCONUT stuff
|
||||||
|
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- name: Install Dependencies (Linux)
|
- 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 squashfs-tools libayatana-appindicator3-dev
|
run: sudo apt-get update && sudo apt-get -y install libwebkit2gtk-4.0-dev build-essential curl wget libssl-dev libgtk-3-dev squashfs-tools libayatana-appindicator3-dev
|
||||||
|
continue-on-error: true
|
||||||
|
|
||||||
- name: Check out repository code
|
- name: Check out repository code
|
||||||
uses: actions/checkout@v2
|
uses: actions/checkout@v2
|
||||||
@@ -45,6 +46,7 @@ jobs:
|
|||||||
|
|
||||||
- uses: actions-rs/clippy-check@v1
|
- uses: actions-rs/clippy-check@v1
|
||||||
name: Clippy checks
|
name: Clippy checks
|
||||||
|
continue-on-error: true
|
||||||
with:
|
with:
|
||||||
token: ${{ secrets.GITHUB_TOKEN }}
|
token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
args: --manifest-path nym-connect/Cargo.toml --workspace --all-features
|
args: --manifest-path nym-connect/Cargo.toml --workspace --all-features
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ jobs:
|
|||||||
|
|
||||||
- name: Install Dependencies (Linux)
|
- 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
|
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
|
||||||
|
continue-on-error: true
|
||||||
|
|
||||||
- name: Check the release tag starts with `nym-explorer-api-`
|
- 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'
|
if: startsWith(github.ref, 'refs/tags/nym-explorer-api-') == false && github.event_name != 'workflow_dispatch'
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ jobs:
|
|||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v2
|
||||||
- name: Install rsync
|
- name: Install rsync
|
||||||
run: sudo apt-get install rsync
|
run: sudo apt-get install rsync
|
||||||
|
continue-on-error: true
|
||||||
- uses: rlespinasse/github-slug-action@v3.x
|
- uses: rlespinasse/github-slug-action@v3.x
|
||||||
- uses: actions/setup-node@v3
|
- uses: actions/setup-node@v3
|
||||||
with:
|
with:
|
||||||
|
|||||||
@@ -25,6 +25,7 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- name: Install Dependencies (Linux)
|
- name: Install Dependencies (Linux)
|
||||||
run: sudo apt-get update && sudo apt-get install libwebkit2gtk-4.0-dev build-essential curl wget libssl-dev libgtk-3-dev libudev-dev squashfs-tools
|
run: sudo apt-get update && sudo apt-get install libwebkit2gtk-4.0-dev build-essential curl wget libssl-dev libgtk-3-dev libudev-dev squashfs-tools
|
||||||
|
continue-on-error: true
|
||||||
if: matrix.os == 'ubuntu-20.04'
|
if: matrix.os == 'ubuntu-20.04'
|
||||||
|
|
||||||
- name: Check out repository code
|
- name: Check out repository code
|
||||||
@@ -38,6 +39,12 @@ jobs:
|
|||||||
override: true
|
override: true
|
||||||
components: rustfmt, clippy
|
components: rustfmt, clippy
|
||||||
|
|
||||||
|
- name: Check formatting
|
||||||
|
uses: actions-rs/cargo@v1
|
||||||
|
with:
|
||||||
|
command: fmt
|
||||||
|
args: --all -- --check
|
||||||
|
|
||||||
- name: Build all binaries
|
- name: Build all binaries
|
||||||
uses: actions-rs/cargo@v1
|
uses: actions-rs/cargo@v1
|
||||||
with:
|
with:
|
||||||
@@ -50,6 +57,18 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
command: clean
|
command: clean
|
||||||
|
|
||||||
|
- name: Build all examples
|
||||||
|
uses: actions-rs/cargo@v1
|
||||||
|
with:
|
||||||
|
command: build
|
||||||
|
args: --workspace --examples
|
||||||
|
|
||||||
|
- name: Reclaim some disk space (because Windows is being annoying)
|
||||||
|
uses: actions-rs/cargo@v1
|
||||||
|
if: ${{ matrix.os == 'windows-latest' }}
|
||||||
|
with:
|
||||||
|
command: clean
|
||||||
|
|
||||||
- name: Run all tests
|
- name: Run all tests
|
||||||
uses: actions-rs/cargo@v1
|
uses: actions-rs/cargo@v1
|
||||||
with:
|
with:
|
||||||
@@ -69,12 +88,6 @@ jobs:
|
|||||||
command: test
|
command: test
|
||||||
args: --workspace --all-features -- --ignored
|
args: --workspace --all-features -- --ignored
|
||||||
|
|
||||||
- name: Check formatting
|
|
||||||
uses: actions-rs/cargo@v1
|
|
||||||
with:
|
|
||||||
command: fmt
|
|
||||||
args: --all -- --check
|
|
||||||
|
|
||||||
- name: Reclaim some disk space (because Windows is being annoying)
|
- name: Reclaim some disk space (because Windows is being annoying)
|
||||||
uses: actions-rs/cargo@v1
|
uses: actions-rs/cargo@v1
|
||||||
if: ${{ matrix.os == 'windows-latest' }}
|
if: ${{ matrix.os == 'windows-latest' }}
|
||||||
@@ -83,6 +96,7 @@ jobs:
|
|||||||
|
|
||||||
- uses: actions-rs/clippy-check@v1
|
- uses: actions-rs/clippy-check@v1
|
||||||
name: Clippy checks
|
name: Clippy checks
|
||||||
|
continue-on-error: true
|
||||||
with:
|
with:
|
||||||
token: ${{ secrets.GITHUB_TOKEN }}
|
token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
args: --all-features
|
args: --all-features
|
||||||
@@ -92,7 +106,7 @@ jobs:
|
|||||||
if: ${{ matrix.rust != 'nightly' }}
|
if: ${{ matrix.rust != 'nightly' }}
|
||||||
with:
|
with:
|
||||||
command: clippy
|
command: clippy
|
||||||
args: --workspace --all-targets -- -D warnings
|
args: --workspace --all-targets --all-features -- -D warnings
|
||||||
|
|
||||||
- name: Reclaim some disk space
|
- name: Reclaim some disk space
|
||||||
uses: actions-rs/cargo@v1
|
uses: actions-rs/cargo@v1
|
||||||
@@ -160,12 +174,17 @@ jobs:
|
|||||||
|
|
||||||
notification:
|
notification:
|
||||||
needs: build
|
needs: build
|
||||||
runs-on: ubuntu-20.04
|
runs-on: custom-runner-linux
|
||||||
steps:
|
steps:
|
||||||
- name: Collect jobs status
|
- name: Collect jobs status
|
||||||
uses: technote-space/workflow-conclusion-action@v2
|
uses: technote-space/workflow-conclusion-action@v2
|
||||||
- name: Check out repository code
|
- name: Check out repository code
|
||||||
uses: actions/checkout@v2
|
uses: actions/checkout@v2
|
||||||
|
- name: install npm
|
||||||
|
uses: actions/setup-node@v3
|
||||||
|
if: env.WORKFLOW_CONCLUSION == 'failure'
|
||||||
|
with:
|
||||||
|
node-version: 16
|
||||||
- name: Keybase - Node Install
|
- name: Keybase - Node Install
|
||||||
if: env.WORKFLOW_CONCLUSION == 'failure'
|
if: env.WORKFLOW_CONCLUSION == 'failure'
|
||||||
run: npm install
|
run: npm install
|
||||||
|
|||||||
@@ -38,6 +38,7 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- name: Install Dependencies (Linux)
|
- name: Install Dependencies (Linux)
|
||||||
run: sudo apt-get update && sudo apt-get install libwebkit2gtk-4.0-dev build-essential curl wget libssl-dev libgtk-3-dev libudev-dev squashfs-tools
|
run: sudo apt-get update && sudo apt-get install libwebkit2gtk-4.0-dev build-essential curl wget libssl-dev libgtk-3-dev libudev-dev squashfs-tools
|
||||||
|
continue-on-error: true
|
||||||
if: matrix.os == 'ubuntu-20.04'
|
if: matrix.os == 'ubuntu-20.04'
|
||||||
|
|
||||||
- name: Check out latest release branch
|
- name: Check out latest release branch
|
||||||
@@ -98,6 +99,7 @@ jobs:
|
|||||||
|
|
||||||
- uses: actions-rs/clippy-check@v1
|
- uses: actions-rs/clippy-check@v1
|
||||||
name: Clippy checks
|
name: Clippy checks
|
||||||
|
continue-on-error: true
|
||||||
with:
|
with:
|
||||||
token: ${{ secrets.GITHUB_TOKEN }}
|
token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
args: --all-features
|
args: --all-features
|
||||||
@@ -175,12 +177,17 @@ jobs:
|
|||||||
|
|
||||||
notification:
|
notification:
|
||||||
needs: [build,get_release]
|
needs: [build,get_release]
|
||||||
runs-on: ubuntu-20.04
|
runs-on: custom-runner-linux
|
||||||
steps:
|
steps:
|
||||||
- name: Collect jobs status
|
- name: Collect jobs status
|
||||||
uses: technote-space/workflow-conclusion-action@v2
|
uses: technote-space/workflow-conclusion-action@v2
|
||||||
- name: Check out repository code
|
- name: Check out repository code
|
||||||
uses: actions/checkout@v3
|
uses: actions/checkout@v3
|
||||||
|
- name: install npm
|
||||||
|
uses: actions/setup-node@v3
|
||||||
|
if: env.WORKFLOW_CONCLUSION == 'failure'
|
||||||
|
with:
|
||||||
|
node-version: 16
|
||||||
- name: Keybase - Node Install
|
- name: Keybase - Node Install
|
||||||
if: env.WORKFLOW_CONCLUSION == 'failure'
|
if: env.WORKFLOW_CONCLUSION == 'failure'
|
||||||
run: npm install
|
run: npm install
|
||||||
|
|||||||
@@ -38,6 +38,7 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- name: Install Dependencies (Linux)
|
- name: Install Dependencies (Linux)
|
||||||
run: sudo apt-get update && sudo apt-get install libwebkit2gtk-4.0-dev build-essential curl wget libssl-dev libgtk-3-dev libudev-dev squashfs-tools
|
run: sudo apt-get update && sudo apt-get install libwebkit2gtk-4.0-dev build-essential curl wget libssl-dev libgtk-3-dev libudev-dev squashfs-tools
|
||||||
|
continue-on-error: true
|
||||||
if: matrix.os == 'ubuntu-20.04'
|
if: matrix.os == 'ubuntu-20.04'
|
||||||
|
|
||||||
- name: Check out latest release branch
|
- name: Check out latest release branch
|
||||||
@@ -98,6 +99,7 @@ jobs:
|
|||||||
|
|
||||||
- uses: actions-rs/clippy-check@v1
|
- uses: actions-rs/clippy-check@v1
|
||||||
name: Clippy checks
|
name: Clippy checks
|
||||||
|
continue-on-error: true
|
||||||
with:
|
with:
|
||||||
token: ${{ secrets.GITHUB_TOKEN }}
|
token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
args: --all-features
|
args: --all-features
|
||||||
@@ -175,12 +177,17 @@ jobs:
|
|||||||
|
|
||||||
notification:
|
notification:
|
||||||
needs: [build,get_release]
|
needs: [build,get_release]
|
||||||
runs-on: ubuntu-20.04
|
runs-on: custom-runner-linux
|
||||||
steps:
|
steps:
|
||||||
- name: Collect jobs status
|
- name: Collect jobs status
|
||||||
uses: technote-space/workflow-conclusion-action@v2
|
uses: technote-space/workflow-conclusion-action@v2
|
||||||
- name: Check out repository code
|
- name: Check out repository code
|
||||||
uses: actions/checkout@v3
|
uses: actions/checkout@v3
|
||||||
|
- name: install npm
|
||||||
|
uses: actions/setup-node@v3
|
||||||
|
if: env.WORKFLOW_CONCLUSION == 'failure'
|
||||||
|
with:
|
||||||
|
node-version: 16
|
||||||
- name: Keybase - Node Install
|
- name: Keybase - Node Install
|
||||||
if: env.WORKFLOW_CONCLUSION == 'failure'
|
if: env.WORKFLOW_CONCLUSION == 'failure'
|
||||||
run: npm install
|
run: npm install
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ jobs:
|
|||||||
run: >
|
run: >
|
||||||
sudo apt-get update &&
|
sudo apt-get update &&
|
||||||
sudo apt-get install -y webkit2gtk-4.0 libayatana-appindicator3-dev
|
sudo apt-get install -y webkit2gtk-4.0 libayatana-appindicator3-dev
|
||||||
|
continue-on-error: true
|
||||||
- name: Check the release tag starts with `nym-connect-`
|
- name: Check the release tag starts with `nym-connect-`
|
||||||
if: startsWith(github.ref, 'refs/tags/nym-connect-') == false && github.event_name != 'workflow_dispatch'
|
if: startsWith(github.ref, 'refs/tags/nym-connect-') == false && github.event_name != 'workflow_dispatch'
|
||||||
uses: actions/github-script@v3
|
uses: actions/github-script@v3
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ jobs:
|
|||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v2
|
||||||
- name: Install rsync
|
- name: Install rsync
|
||||||
run: sudo apt-get install rsync
|
run: sudo apt-get install rsync
|
||||||
|
continue-on-error: true
|
||||||
- uses: rlespinasse/github-slug-action@v3.x
|
- uses: rlespinasse/github-slug-action@v3.x
|
||||||
- uses: actions/setup-node@v3
|
- uses: actions/setup-node@v3
|
||||||
with:
|
with:
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ jobs:
|
|||||||
|
|
||||||
- name: Install Dependencies (Linux)
|
- 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
|
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
|
||||||
|
continue-on-error: true
|
||||||
|
|
||||||
- name: Check the release tag starts with `nym-binaries-`
|
- name: Check the release tag starts with `nym-binaries-`
|
||||||
if: startsWith(github.ref, 'refs/tags/nym-binaries-') == false && github.event_name != 'workflow_dispatch'
|
if: startsWith(github.ref, 'refs/tags/nym-binaries-') == false && github.event_name != 'workflow_dispatch'
|
||||||
@@ -60,7 +61,7 @@ jobs:
|
|||||||
target/release/nym-gateway
|
target/release/nym-gateway
|
||||||
target/release/nym-mixnode
|
target/release/nym-mixnode
|
||||||
target/release/nym-socks5-client
|
target/release/nym-socks5-client
|
||||||
target/release/nym-validator-api
|
target/release/nym-api
|
||||||
target/release/nym-network-requester
|
target/release/nym-network-requester
|
||||||
target/release/nym-network-statistics
|
target/release/nym-network-statistics
|
||||||
target/release/nym-cli
|
target/release/nym-cli
|
||||||
@@ -75,7 +76,7 @@ jobs:
|
|||||||
target/release/nym-gateway
|
target/release/nym-gateway
|
||||||
target/release/nym-mixnode
|
target/release/nym-mixnode
|
||||||
target/release/nym-socks5-client
|
target/release/nym-socks5-client
|
||||||
target/release/nym-validator-api
|
target/release/nym-api
|
||||||
target/release/nym-network-requester
|
target/release/nym-network-requester
|
||||||
target/release/nym-network-statistics
|
target/release/nym-network-statistics
|
||||||
target/release/nym-cli
|
target/release/nym-cli
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ jobs:
|
|||||||
run: >
|
run: >
|
||||||
sudo apt-get update &&
|
sudo apt-get update &&
|
||||||
sudo apt-get install -y webkit2gtk-4.0
|
sudo apt-get install -y webkit2gtk-4.0
|
||||||
|
continue-on-error: true
|
||||||
- name: Check the release tag starts with `nym-wallet-`
|
- name: Check the release tag starts with `nym-wallet-`
|
||||||
if: startsWith(github.ref, 'refs/tags/nym-wallet-') == false
|
if: startsWith(github.ref, 'refs/tags/nym-wallet-') == false
|
||||||
uses: actions/github-script@v3
|
uses: actions/github-script@v3
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ jobs:
|
|||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v2
|
||||||
- name: Install rsync
|
- name: Install rsync
|
||||||
run: sudo apt-get install rsync
|
run: sudo apt-get install rsync
|
||||||
|
continue-on-error: true
|
||||||
- uses: rlespinasse/github-slug-action@v3.x
|
- uses: rlespinasse/github-slug-action@v3.x
|
||||||
- uses: actions/setup-node@v3
|
- uses: actions/setup-node@v3
|
||||||
with:
|
with:
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ jobs:
|
|||||||
libappindicator3-dev
|
libappindicator3-dev
|
||||||
webkit2gtk-driver
|
webkit2gtk-driver
|
||||||
xvfb
|
xvfb
|
||||||
|
continue-on-error: true
|
||||||
|
|
||||||
- name: Install minimal stable
|
- name: Install minimal stable
|
||||||
uses: actions-rs/toolchain@v1
|
uses: actions-rs/toolchain@v1
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
name: CI for linting Typescript
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
paths:
|
||||||
|
- 'ts-packages/**'
|
||||||
|
- 'sdk/typescript/**'
|
||||||
|
- nym-connect
|
||||||
|
- nym-wallet
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
runs-on: custom-runner-linux
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v2
|
||||||
|
- name: Install rsync
|
||||||
|
run: sudo apt-get install rsync
|
||||||
|
continue-on-error: true
|
||||||
|
- uses: rlespinasse/github-slug-action@v3.x
|
||||||
|
- uses: actions/setup-node@v3
|
||||||
|
with:
|
||||||
|
node-version: 16
|
||||||
|
- name: Setup yarn
|
||||||
|
run: npm install -g yarn
|
||||||
|
- name: Lint
|
||||||
|
run: yarn && yarn lint && yarn tsc
|
||||||
|
- name: Keybase - Node Install
|
||||||
|
run: npm install
|
||||||
|
working-directory: .github/workflows/support-files
|
||||||
|
- name: Keybase - Send Notification
|
||||||
|
env:
|
||||||
|
NYM_NOTIFICATION_KIND: ts-packages
|
||||||
|
NYM_PROJECT_NAME: "ts-packages"
|
||||||
|
NYM_CI_WWW_BASE: "${{ secrets.NYM_CI_WWW_BASE }}"
|
||||||
|
NYM_CI_WWW_LOCATION: "ts-${{ env.GITHUB_REF_SLUG }}"
|
||||||
|
GIT_COMMIT_MESSAGE: "${{ github.event.head_commit.message }}"
|
||||||
|
GIT_BRANCH: "${GITHUB_REF##*/}"
|
||||||
|
KEYBASE_NYMBOT_USERNAME: "${{ secrets.KEYBASE_NYMBOT_USERNAME }}"
|
||||||
|
KEYBASE_NYMBOT_PAPERKEY: "${{ secrets.KEYBASE_NYMBOT_PAPERKEY }}"
|
||||||
|
KEYBASE_NYMBOT_TEAM: "${{ secrets.KEYBASE_NYMBOT_TEAM }}"
|
||||||
|
KEYBASE_NYM_CHANNEL: "ci-ts-packages"
|
||||||
|
IS_SUCCESS: "${{ job.status == 'success' }}"
|
||||||
|
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
|
||||||
@@ -48,6 +48,7 @@ jobs:
|
|||||||
|
|
||||||
- uses: actions-rs/clippy-check@v1
|
- uses: actions-rs/clippy-check@v1
|
||||||
name: Clippy checks
|
name: Clippy checks
|
||||||
|
continue-on-error: true
|
||||||
with:
|
with:
|
||||||
token: ${{ secrets.GITHUB_TOKEN }}
|
token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
args: --manifest-path nym-wallet/Cargo.toml --workspace --all-features
|
args: --manifest-path nym-wallet/Cargo.toml --workspace --all-features
|
||||||
|
|||||||
@@ -29,11 +29,6 @@ jobs:
|
|||||||
command: build
|
command: build
|
||||||
args: --manifest-path clients/webassembly/Cargo.toml --target wasm32-unknown-unknown --features=coconut
|
args: --manifest-path clients/webassembly/Cargo.toml --target wasm32-unknown-unknown --features=coconut
|
||||||
|
|
||||||
- uses: actions-rs/cargo@v1
|
|
||||||
with:
|
|
||||||
command: test
|
|
||||||
args: --manifest-path clients/webassembly/Cargo.toml
|
|
||||||
|
|
||||||
- uses: actions-rs/cargo@v1
|
- uses: actions-rs/cargo@v1
|
||||||
with:
|
with:
|
||||||
command: fmt
|
command: fmt
|
||||||
|
|||||||
@@ -41,3 +41,4 @@ storybook-static
|
|||||||
envs/qwerty.env
|
envs/qwerty.env
|
||||||
Cargo.lock
|
Cargo.lock
|
||||||
nym-connect/Cargo.lock
|
nym-connect/Cargo.lock
|
||||||
|
.parcel-cache
|
||||||
|
|||||||
+64
-3
@@ -2,26 +2,87 @@
|
|||||||
|
|
||||||
Post 1.0.0 release, the changelog format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
Post 1.0.0 release, the changelog format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||||
|
|
||||||
## [Unreleased]
|
# [Unreleased]
|
||||||
|
|
||||||
|
# [v1.1.8] (2023-01-31)
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- Rust SDK - Support SURBS (anonymous send + storage) ([#2754])
|
||||||
|
- dkg rerun from scratch and dkg-specific epochs ([#2810])
|
||||||
|
- Rename `'initial_supply'` field to `'total_supply'` in the circulating supply endpoint ([#2931])
|
||||||
|
- Circulating supply api endpoint (read the note inside before testing/deploying) ([#1902])
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- nym-api: an `--id` flag is now always explicitly required ([#2873])
|
||||||
|
|
||||||
|
[#2754]: https://github.com/nymtech/nym/issues/2754
|
||||||
|
[#2839]: https://github.com/nymtech/nym/issues/2810
|
||||||
|
[#2931]: https://github.com/nymtech/nym/issues/2931
|
||||||
|
[#1902]: https://github.com/nymtech/nym/issues/1902
|
||||||
|
[#2873]: https://github.com/nymtech/nym/issues/2873
|
||||||
|
|
||||||
|
|
||||||
|
# [v1.1.7] (2023-01-24)
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- Gateways now shut down gracefully ([#2019]).
|
||||||
|
- Rust SDK - Initial version for nym-client ([#2669]).
|
||||||
|
- Introduce vesting contract query for addresses of all vesting accounts (required for the circulating supply calculation) ([#2778]).
|
||||||
|
- Add threshold value to the contract storage ([#1893])
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- Refactor vesting account storage (and in particular, ACCOUNTS saving) ([#2795]).
|
||||||
|
- Move from manual advancing DKG state to an automatic process ([#2670]).
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- Gateways now shut down gracefully ([#2019]).
|
||||||
|
|
||||||
|
[#2019]: https://github.com/nymtech/nym/issues/2019
|
||||||
|
[#2669]: https://github.com/nymtech/nym/issues/2669
|
||||||
|
[#2795]: https://github.com/nymtech/nym/issues/2795
|
||||||
|
[#2778]: https://github.com/nymtech/nym/issues/2778
|
||||||
|
[#2670]: https://github.com/nymtech/nym/issues/2670
|
||||||
|
[#1893]: https://github.com/nymtech/nym/issues/1893
|
||||||
|
|
||||||
|
## [v1.1.6] (2023-01-17)
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
|
||||||
- nym-sdk: added initial version of a Rust client sdk
|
- nym-sdk: added initial version of a Rust client sdk
|
||||||
|
- nym-api: added `/circulating-supply` endpoint ([#2814])
|
||||||
|
- nym-api: add endpoint listing detailed gateway info by @octol in https://github.com/nymtech/nym/pull/2833
|
||||||
|
|
||||||
### Changed
|
### Changed
|
||||||
|
|
||||||
|
- streamline override_config functions -> there's a lot of duplicate if statements everywhere ([#2774])
|
||||||
|
- clean-up nym-api startup arguments/flags to use clap 3 and its macro-derived arguments ([#2772])
|
||||||
- renamed all references to validator_api to nym_api
|
- renamed all references to validator_api to nym_api
|
||||||
- renamed all references to nymd to nyxd
|
- renamed all references to nymd to nyxd ([#2696])
|
||||||
- all-binaries: standarised argument names (note: old names should still be accepted) ([#2762]
|
- all-binaries: standarised argument names (note: old names should still be accepted) ([#2762]
|
||||||
|
|
||||||
### Fixed
|
### Fixed
|
||||||
|
|
||||||
- nym-api: should now correctly use `rewarding.enabled` config flag ([#2753])
|
- nym-api: should now correctly use `rewarding.enabled` config flag ([#2753])
|
||||||
|
|
||||||
|
[#2696]: https://github.com/nymtech/nym/pull/2696
|
||||||
[#2753]: https://github.com/nymtech/nym/pull/2753
|
[#2753]: https://github.com/nymtech/nym/pull/2753
|
||||||
[#2762]: https://github.com/nymtech/nym/pull/2762
|
[#2762]: https://github.com/nymtech/nym/pull/2762
|
||||||
|
[#2814]: https://github.com/nymtech/nym/pull/2814
|
||||||
|
[#2772]: https://github.com/nymtech/nym/pull/2772
|
||||||
|
[#2774]: https://github.com/nymtech/nym/pull/2774
|
||||||
|
|
||||||
## [v1.1.5] (2022-01-10)
|
## [v1.1.5] (2023-01-10)
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
## [v1.1.5] (2023-01-10)
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
|
||||||
|
|||||||
Generated
+1001
-809
File diff suppressed because it is too large
Load Diff
+10
@@ -34,6 +34,7 @@ members = [
|
|||||||
"common/cosmwasm-smart-contracts/coconut-bandwidth-contract",
|
"common/cosmwasm-smart-contracts/coconut-bandwidth-contract",
|
||||||
"common/cosmwasm-smart-contracts/coconut-dkg",
|
"common/cosmwasm-smart-contracts/coconut-dkg",
|
||||||
"common/cosmwasm-smart-contracts/contracts-common",
|
"common/cosmwasm-smart-contracts/contracts-common",
|
||||||
|
"common/cosmwasm-smart-contracts/group-contract",
|
||||||
"common/cosmwasm-smart-contracts/mixnet-contract",
|
"common/cosmwasm-smart-contracts/mixnet-contract",
|
||||||
"common/cosmwasm-smart-contracts/multisig-contract",
|
"common/cosmwasm-smart-contracts/multisig-contract",
|
||||||
"common/cosmwasm-smart-contracts/vesting-contract",
|
"common/cosmwasm-smart-contracts/vesting-contract",
|
||||||
@@ -95,3 +96,12 @@ default-members = [
|
|||||||
]
|
]
|
||||||
|
|
||||||
exclude = ["explorer", "contracts", "clients/webassembly", "nym-wallet", "nym-connect"]
|
exclude = ["explorer", "contracts", "clients/webassembly", "nym-wallet", "nym-connect"]
|
||||||
|
|
||||||
|
[workspace.package]
|
||||||
|
authors = ["Nym Technologies SA"]
|
||||||
|
repository = "https://github.com/nymtech/nym"
|
||||||
|
homepage = "https://nymtech.net"
|
||||||
|
edition = "2021"
|
||||||
|
|
||||||
|
[workspace.dependencies]
|
||||||
|
log = "0.4"
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ no-clippy: build cargo-test wasm fmt
|
|||||||
happy: fmt clippy-happy test
|
happy: fmt clippy-happy test
|
||||||
clippy-all: clippy-main clippy-coconut clippy-all-contracts clippy-all-wallet clippy-all-connect clippy-all-wasm-client
|
clippy-all: clippy-main clippy-coconut clippy-all-contracts clippy-all-wallet clippy-all-connect clippy-all-wasm-client
|
||||||
clippy-happy: clippy-happy-main clippy-happy-contracts clippy-happy-wallet clippy-happy-connect
|
clippy-happy: clippy-happy-main clippy-happy-contracts clippy-happy-wallet clippy-happy-connect
|
||||||
cargo-test: test-main test-contracts test-wallet test-connect test-coconut test-wasm-client
|
cargo-test: test-main test-contracts test-wallet test-connect test-coconut
|
||||||
cargo-test-expensive: test-main-expensive test-contracts-expensive test-wallet-expensive test-connect-expensive test-coconut-expensive
|
cargo-test-expensive: test-main-expensive test-contracts-expensive test-wallet-expensive test-connect-expensive test-coconut-expensive
|
||||||
build: build-contracts build-wallet build-main build-connect build-wasm-client
|
build: build-contracts build-wallet build-main build-connect build-wasm-client
|
||||||
fmt: fmt-main fmt-contracts fmt-wallet fmt-connect fmt-wasm-client
|
fmt: fmt-main fmt-contracts fmt-wallet fmt-connect fmt-wasm-client
|
||||||
@@ -68,9 +68,6 @@ test-wallet:
|
|||||||
test-wallet-expensive:
|
test-wallet-expensive:
|
||||||
cargo test --manifest-path nym-wallet/Cargo.toml --all-features -- --ignored
|
cargo test --manifest-path nym-wallet/Cargo.toml --all-features -- --ignored
|
||||||
|
|
||||||
test-wasm-client:
|
|
||||||
cargo test --workspace --manifest-path clients/webassembly/Cargo.toml --all-features
|
|
||||||
|
|
||||||
test-connect:
|
test-connect:
|
||||||
cargo test --manifest-path nym-connect/Cargo.toml --all-features
|
cargo test --manifest-path nym-connect/Cargo.toml --all-features
|
||||||
|
|
||||||
|
|||||||
Vendored
BIN
Binary file not shown.
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "client-core"
|
name = "client-core"
|
||||||
version = "1.1.5"
|
version = "1.1.8"
|
||||||
authors = ["Dave Hrycyszyn <futurechimp@users.noreply.github.com>"]
|
authors = ["Dave Hrycyszyn <futurechimp@users.noreply.github.com>"]
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
rust-version = "1.66"
|
rust-version = "1.66"
|
||||||
@@ -13,14 +13,14 @@ dirs = "4.0"
|
|||||||
dashmap = "5.4.0"
|
dashmap = "5.4.0"
|
||||||
futures = "0.3"
|
futures = "0.3"
|
||||||
humantime-serde = "1.0"
|
humantime-serde = "1.0"
|
||||||
log = "0.4"
|
log = { workspace = true }
|
||||||
rand = { version = "0.7.3", features = ["wasm-bindgen"] }
|
rand = { version = "0.7.3", features = ["wasm-bindgen"] }
|
||||||
serde = { version = "1.0", features = ["derive"] }
|
serde = { version = "1.0", features = ["derive"] }
|
||||||
serde_json = "1.0.89"
|
serde_json = "1.0.89"
|
||||||
tap = "1.0.1"
|
tap = "1.0.1"
|
||||||
thiserror = "1.0.34"
|
thiserror = "1.0.34"
|
||||||
url = { version ="2.2", features = ["serde"] }
|
url = { version ="2.2", features = ["serde"] }
|
||||||
tokio = { version = "1.21.2", features = ["macros"]}
|
tokio = { version = "1.24.1", features = ["macros"]}
|
||||||
time = "0.3.17"
|
time = "0.3.17"
|
||||||
|
|
||||||
# internal
|
# internal
|
||||||
@@ -38,11 +38,11 @@ validator-client = { path = "../../common/client-libs/validator-client", default
|
|||||||
task = { path = "../../common/task" }
|
task = { path = "../../common/task" }
|
||||||
|
|
||||||
[target."cfg(not(target_arch = \"wasm32\"))".dependencies.tokio-stream]
|
[target."cfg(not(target_arch = \"wasm32\"))".dependencies.tokio-stream]
|
||||||
version = "0.1.9"
|
version = "0.1.11"
|
||||||
features = ["time"]
|
features = ["time"]
|
||||||
|
|
||||||
[target."cfg(not(target_arch = \"wasm32\"))".dependencies.tokio]
|
[target."cfg(not(target_arch = \"wasm32\"))".dependencies.tokio]
|
||||||
version = "1.21.2"
|
version = "1.24.1"
|
||||||
features = ["time"]
|
features = ["time"]
|
||||||
|
|
||||||
[target."cfg(not(target_arch = \"wasm32\"))".dependencies.sqlx]
|
[target."cfg(not(target_arch = \"wasm32\"))".dependencies.sqlx]
|
||||||
@@ -75,7 +75,7 @@ features = ["wasm-bindgen"]
|
|||||||
tempfile = "3.1.0"
|
tempfile = "3.1.0"
|
||||||
|
|
||||||
[build-dependencies]
|
[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"] }
|
sqlx = { version = "0.6.2", features = ["runtime-tokio-rustls", "sqlite", "macros", "migrate"] }
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
|
|||||||
@@ -9,9 +9,9 @@ async fn main() {
|
|||||||
use std::env;
|
use std::env;
|
||||||
|
|
||||||
let out_dir = env::var("OUT_DIR").unwrap();
|
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
|
.await
|
||||||
.expect("Failed to create SQLx database connection");
|
.expect("Failed to create SQLx database connection");
|
||||||
|
|
||||||
|
|||||||
@@ -25,6 +25,8 @@ use client_connections::{ConnectionCommandReceiver, ConnectionCommandSender, Lan
|
|||||||
use crypto::asymmetric::{encryption, identity};
|
use crypto::asymmetric::{encryption, identity};
|
||||||
use futures::channel::mpsc;
|
use futures::channel::mpsc;
|
||||||
use gateway_client::bandwidth::BandwidthController;
|
use gateway_client::bandwidth::BandwidthController;
|
||||||
|
#[cfg(target_arch = "wasm32")]
|
||||||
|
use gateway_client::wasm_mockups::CosmWasmClient;
|
||||||
use gateway_client::{
|
use gateway_client::{
|
||||||
AcknowledgementReceiver, AcknowledgementSender, GatewayClient, MixnetMessageReceiver,
|
AcknowledgementReceiver, AcknowledgementSender, GatewayClient, MixnetMessageReceiver,
|
||||||
MixnetMessageSender,
|
MixnetMessageSender,
|
||||||
@@ -39,6 +41,8 @@ use std::time::Duration;
|
|||||||
use tap::TapFallible;
|
use tap::TapFallible;
|
||||||
use task::{TaskClient, TaskManager};
|
use task::{TaskClient, TaskManager};
|
||||||
use url::Url;
|
use url::Url;
|
||||||
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
|
use validator_client::nyxd::CosmWasmClient;
|
||||||
|
|
||||||
use super::received_buffer::ReceivedBufferMessage;
|
use super::received_buffer::ReceivedBufferMessage;
|
||||||
|
|
||||||
@@ -129,7 +133,7 @@ impl From<bool> for CredentialsToggle {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct BaseClientBuilder<'a, B> {
|
pub struct BaseClientBuilder<'a, B, C: Clone> {
|
||||||
// due to wasm limitations I had to split it like this : (
|
// due to wasm limitations I had to split it like this : (
|
||||||
gateway_config: &'a GatewayEndpointConfig,
|
gateway_config: &'a GatewayEndpointConfig,
|
||||||
debug_config: &'a DebugConfig,
|
debug_config: &'a DebugConfig,
|
||||||
@@ -137,20 +141,21 @@ pub struct BaseClientBuilder<'a, B> {
|
|||||||
nym_api_endpoints: Vec<Url>,
|
nym_api_endpoints: Vec<Url>,
|
||||||
reply_storage_backend: B,
|
reply_storage_backend: B,
|
||||||
|
|
||||||
bandwidth_controller: Option<BandwidthController>,
|
bandwidth_controller: Option<BandwidthController<C>>,
|
||||||
key_manager: KeyManager,
|
key_manager: KeyManager,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a, B> BaseClientBuilder<'a, B>
|
impl<'a, B, C> BaseClientBuilder<'a, B, C>
|
||||||
where
|
where
|
||||||
B: ReplyStorageBackend + Send + Sync + 'static,
|
B: ReplyStorageBackend + Send + Sync + 'static,
|
||||||
|
C: CosmWasmClient + Sync + Send + Clone + 'static,
|
||||||
{
|
{
|
||||||
pub fn new_from_base_config<T>(
|
pub fn new_from_base_config<T>(
|
||||||
base_config: &'a Config<T>,
|
base_config: &'a Config<T>,
|
||||||
key_manager: KeyManager,
|
key_manager: KeyManager,
|
||||||
bandwidth_controller: Option<BandwidthController>,
|
bandwidth_controller: Option<BandwidthController<C>>,
|
||||||
reply_storage_backend: B,
|
reply_storage_backend: B,
|
||||||
) -> BaseClientBuilder<'a, B> {
|
) -> BaseClientBuilder<'a, B, C> {
|
||||||
BaseClientBuilder {
|
BaseClientBuilder {
|
||||||
gateway_config: base_config.get_gateway_endpoint_config(),
|
gateway_config: base_config.get_gateway_endpoint_config(),
|
||||||
debug_config: base_config.get_debug_config(),
|
debug_config: base_config.get_debug_config(),
|
||||||
@@ -166,11 +171,11 @@ where
|
|||||||
gateway_config: &'a GatewayEndpointConfig,
|
gateway_config: &'a GatewayEndpointConfig,
|
||||||
debug_config: &'a DebugConfig,
|
debug_config: &'a DebugConfig,
|
||||||
key_manager: KeyManager,
|
key_manager: KeyManager,
|
||||||
bandwidth_controller: Option<BandwidthController>,
|
bandwidth_controller: Option<BandwidthController<C>>,
|
||||||
reply_storage_backend: B,
|
reply_storage_backend: B,
|
||||||
credentials_toggle: CredentialsToggle,
|
credentials_toggle: CredentialsToggle,
|
||||||
nym_api_endpoints: Vec<Url>,
|
nym_api_endpoints: Vec<Url>,
|
||||||
) -> BaseClientBuilder<'a, B> {
|
) -> BaseClientBuilder<'a, B, C> {
|
||||||
BaseClientBuilder {
|
BaseClientBuilder {
|
||||||
gateway_config,
|
gateway_config,
|
||||||
debug_config,
|
debug_config,
|
||||||
@@ -279,7 +284,7 @@ where
|
|||||||
mixnet_message_sender: MixnetMessageSender,
|
mixnet_message_sender: MixnetMessageSender,
|
||||||
ack_sender: AcknowledgementSender,
|
ack_sender: AcknowledgementSender,
|
||||||
shutdown: TaskClient,
|
shutdown: TaskClient,
|
||||||
) -> Result<GatewayClient, ClientCoreError> {
|
) -> Result<GatewayClient<C>, ClientCoreError> {
|
||||||
let gateway_id = self.gateway_config.gateway_id.clone();
|
let gateway_id = self.gateway_config.gateway_id.clone();
|
||||||
if gateway_id.is_empty() {
|
if gateway_id.is_empty() {
|
||||||
return Err(ClientCoreError::GatewayIdUnknown);
|
return Err(ClientCoreError::GatewayIdUnknown);
|
||||||
@@ -365,7 +370,7 @@ where
|
|||||||
// over it. Perhaps GatewayClient needs to be thread-shareable or have some channel for
|
// over it. Perhaps GatewayClient needs to be thread-shareable or have some channel for
|
||||||
// requests?
|
// requests?
|
||||||
fn start_mix_traffic_controller(
|
fn start_mix_traffic_controller(
|
||||||
gateway_client: GatewayClient,
|
gateway_client: GatewayClient<C>,
|
||||||
shutdown: TaskClient,
|
shutdown: TaskClient,
|
||||||
) -> BatchMixMessageSender {
|
) -> BatchMixMessageSender {
|
||||||
info!("Starting mix traffic controller...");
|
info!("Starting mix traffic controller...");
|
||||||
@@ -381,22 +386,32 @@ where
|
|||||||
where
|
where
|
||||||
<B as ReplyStorageBackend>::StorageError: Sync + Send,
|
<B as ReplyStorageBackend>::StorageError: Sync + Send,
|
||||||
{
|
{
|
||||||
let persistent_storage = PersistentReplyStorage::new(backend);
|
if backend.is_active() {
|
||||||
let mem_store = persistent_storage
|
log::trace!("Setup persistent reply storage");
|
||||||
.load_state_from_backend()
|
let persistent_storage = PersistentReplyStorage::new(backend);
|
||||||
.await
|
let mem_store = persistent_storage
|
||||||
.map_err(|err| ClientCoreError::SurbStorageError {
|
.load_state_from_backend()
|
||||||
source: Box::new(err),
|
|
||||||
})?;
|
|
||||||
|
|
||||||
let store_clone = mem_store.clone();
|
|
||||||
spawn_future(async move {
|
|
||||||
persistent_storage
|
|
||||||
.flush_on_shutdown(store_clone, shutdown)
|
|
||||||
.await
|
.await
|
||||||
});
|
.map_err(|err| ClientCoreError::SurbStorageError {
|
||||||
|
source: Box::new(err),
|
||||||
|
})?;
|
||||||
|
|
||||||
Ok(mem_store)
|
let store_clone = mem_store.clone();
|
||||||
|
spawn_future(async move {
|
||||||
|
persistent_storage
|
||||||
|
.flush_on_shutdown(store_clone, shutdown)
|
||||||
|
.await
|
||||||
|
});
|
||||||
|
|
||||||
|
Ok(mem_store)
|
||||||
|
} else {
|
||||||
|
log::trace!("Setup inactive reply storage");
|
||||||
|
Ok(backend
|
||||||
|
.get_inactive_storage()
|
||||||
|
.map_err(|err| ClientCoreError::SurbStorageError {
|
||||||
|
source: Box::new(err),
|
||||||
|
})?)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn start_base(mut self) -> Result<BaseClient, ClientCoreError>
|
pub async fn start_base(mut self) -> Result<BaseClient, ClientCoreError>
|
||||||
|
|||||||
@@ -43,6 +43,14 @@ async fn setup_fresh_backend<P: AsRef<Path>>(
|
|||||||
Ok(storage_backend)
|
Ok(storage_backend)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn setup_inactive_backend(debug_config: &DebugConfig) -> fs_backend::Backend {
|
||||||
|
info!("creating inactive surb database");
|
||||||
|
fs_backend::Backend::new_inactive(
|
||||||
|
debug_config.minimum_reply_surb_storage_threshold,
|
||||||
|
debug_config.maximum_reply_surb_storage_threshold,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
fn archive_corrupted_database<P: AsRef<Path>>(db_path: P) -> io::Result<()> {
|
fn archive_corrupted_database<P: AsRef<Path>>(db_path: P) -> io::Result<()> {
|
||||||
let db_path = db_path.as_ref();
|
let db_path = db_path.as_ref();
|
||||||
debug_assert!(db_path.exists());
|
debug_assert!(db_path.exists());
|
||||||
@@ -53,7 +61,7 @@ fn archive_corrupted_database<P: AsRef<Path>>(db_path: P) -> io::Result<()> {
|
|||||||
|
|
||||||
let new_extension =
|
let new_extension =
|
||||||
if let Some(existing_extension) = db_path.extension().and_then(|ext| ext.to_str()) {
|
if let Some(existing_extension) = db_path.extension().and_then(|ext| ext.to_str()) {
|
||||||
format!("{existing_extension}.{}", suffix)
|
format!("{existing_extension}.{suffix}")
|
||||||
} else {
|
} else {
|
||||||
suffix
|
suffix
|
||||||
};
|
};
|
||||||
@@ -65,24 +73,29 @@ fn archive_corrupted_database<P: AsRef<Path>>(db_path: P) -> io::Result<()> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub async fn setup_fs_reply_surb_backend<P: AsRef<Path>>(
|
pub async fn setup_fs_reply_surb_backend<P: AsRef<Path>>(
|
||||||
db_path: P,
|
db_path: Option<P>,
|
||||||
debug_config: &DebugConfig,
|
debug_config: &DebugConfig,
|
||||||
) -> Result<fs_backend::Backend, ClientCoreError> {
|
) -> Result<fs_backend::Backend, ClientCoreError> {
|
||||||
// if the database file doesnt exist, initialise fresh storage, otherwise attempt to load the existing one
|
if let Some(db_path) = db_path {
|
||||||
let db_path = db_path.as_ref();
|
// if the database file doesnt exist, initialise fresh storage, otherwise attempt to load
|
||||||
if db_path.exists() {
|
// the existing one
|
||||||
info!("loading existing surb database");
|
let db_path = db_path.as_ref();
|
||||||
match fs_backend::Backend::try_load(db_path).await {
|
if db_path.exists() {
|
||||||
Ok(backend) => Ok(backend),
|
info!("loading existing surb database");
|
||||||
Err(err) => {
|
match fs_backend::Backend::try_load(db_path).await {
|
||||||
error!("failed to setup persistent storage backend for our reply needs: {err}. We're going to create a fresh database instead. This behaviour might change in the future");
|
Ok(backend) => Ok(backend),
|
||||||
|
Err(err) => {
|
||||||
|
error!("failed to setup persistent storage backend for our reply needs: {err}. We're going to create a fresh database instead. This behaviour might change in the future");
|
||||||
|
|
||||||
archive_corrupted_database(db_path)?;
|
archive_corrupted_database(db_path)?;
|
||||||
setup_fresh_backend(db_path, debug_config).await
|
setup_fresh_backend(db_path, debug_config).await
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
setup_fresh_backend(db_path, debug_config).await
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
setup_fresh_backend(db_path, debug_config).await
|
Ok(setup_inactive_backend(debug_config))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -42,9 +42,6 @@ pub struct KeyManager {
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
impl 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`]
|
/// Creates new instance of a [`KeyManager`]
|
||||||
pub fn new<R>(rng: &mut R) -> Self
|
pub fn new<R>(rng: &mut R) -> Self
|
||||||
where
|
where
|
||||||
@@ -130,9 +127,6 @@ impl KeyManager {
|
|||||||
Ok(key_manager)
|
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.
|
/// Stores all available keys on the disk.
|
||||||
// While perhaps there is no much point in storing the `AckKey` 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
|
// 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)
|
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`].
|
/// 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>) {
|
pub fn insert_gateway_shared_key(&mut self, gateway_shared_key: Arc<SharedKeys>) {
|
||||||
self.gateway_shared_key = Some(gateway_shared_key)
|
self.gateway_shared_key = Some(gateway_shared_key)
|
||||||
|
|||||||
@@ -2,9 +2,13 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
|
||||||
use crate::spawn_future;
|
use crate::spawn_future;
|
||||||
|
#[cfg(target_arch = "wasm32")]
|
||||||
|
use gateway_client::wasm_mockups::CosmWasmClient;
|
||||||
use gateway_client::GatewayClient;
|
use gateway_client::GatewayClient;
|
||||||
use log::*;
|
use log::*;
|
||||||
use nymsphinx::forwarding::packet::MixPacket;
|
use nymsphinx::forwarding::packet::MixPacket;
|
||||||
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
|
use validator_client::nyxd::CosmWasmClient;
|
||||||
|
|
||||||
pub type BatchMixMessageSender = tokio::sync::mpsc::Sender<Vec<MixPacket>>;
|
pub type BatchMixMessageSender = tokio::sync::mpsc::Sender<Vec<MixPacket>>;
|
||||||
pub type BatchMixMessageReceiver = tokio::sync::mpsc::Receiver<Vec<MixPacket>>;
|
pub type BatchMixMessageReceiver = tokio::sync::mpsc::Receiver<Vec<MixPacket>>;
|
||||||
@@ -13,10 +17,10 @@ pub type BatchMixMessageReceiver = tokio::sync::mpsc::Receiver<Vec<MixPacket>>;
|
|||||||
pub const MIX_MESSAGE_RECEIVER_BUFFER_SIZE: usize = 32;
|
pub const MIX_MESSAGE_RECEIVER_BUFFER_SIZE: usize = 32;
|
||||||
const MAX_FAILURE_COUNT: usize = 100;
|
const MAX_FAILURE_COUNT: usize = 100;
|
||||||
|
|
||||||
pub struct MixTrafficController {
|
pub struct MixTrafficController<C: Clone> {
|
||||||
// TODO: most likely to be replaced by some higher level construct as
|
// TODO: most likely to be replaced by some higher level construct as
|
||||||
// later on gateway_client will need to be accessible by other entities
|
// later on gateway_client will need to be accessible by other entities
|
||||||
gateway_client: GatewayClient,
|
gateway_client: GatewayClient<C>,
|
||||||
mix_rx: BatchMixMessageReceiver,
|
mix_rx: BatchMixMessageReceiver,
|
||||||
|
|
||||||
// TODO: this is temporary work-around.
|
// TODO: this is temporary work-around.
|
||||||
@@ -24,8 +28,13 @@ pub struct MixTrafficController {
|
|||||||
consecutive_gateway_failure_count: usize,
|
consecutive_gateway_failure_count: usize,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl MixTrafficController {
|
impl<C> MixTrafficController<C>
|
||||||
pub fn new(gateway_client: GatewayClient) -> (MixTrafficController, BatchMixMessageSender) {
|
where
|
||||||
|
C: CosmWasmClient + Sync + Send + Clone + 'static,
|
||||||
|
{
|
||||||
|
pub fn new(
|
||||||
|
gateway_client: GatewayClient<C>,
|
||||||
|
) -> (MixTrafficController<C>, BatchMixMessageSender) {
|
||||||
let (sphinx_message_sender, sphinx_message_receiver) =
|
let (sphinx_message_sender, sphinx_message_receiver) =
|
||||||
tokio::sync::mpsc::channel(MIX_MESSAGE_RECEIVER_BUFFER_SIZE);
|
tokio::sync::mpsc::channel(MIX_MESSAGE_RECEIVER_BUFFER_SIZE);
|
||||||
(
|
(
|
||||||
@@ -57,7 +66,7 @@ impl MixTrafficController {
|
|||||||
if self.consecutive_gateway_failure_count == MAX_FAILURE_COUNT {
|
if self.consecutive_gateway_failure_count == MAX_FAILURE_COUNT {
|
||||||
// todo: in the future this should initiate a 'graceful' shutdown or try
|
// todo: in the future this should initiate a 'graceful' shutdown or try
|
||||||
// to reconnect?
|
// 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(_) => {
|
Ok(_) => {
|
||||||
|
|||||||
@@ -471,14 +471,10 @@ where
|
|||||||
let mult = self.sending_delay_controller.current_multiplier();
|
let mult = self.sending_delay_controller.current_multiplier();
|
||||||
let delay = self.current_average_message_sending_delay().as_millis();
|
let delay = self.current_average_message_sending_delay().as_millis();
|
||||||
let status_str = if self.config.disable_poisson_packet_distribution {
|
let status_str = if self.config.disable_poisson_packet_distribution {
|
||||||
format!(
|
format!("Status: {lanes} lanes, backlog: {backlog:.2} kiB ({packets}), no delay")
|
||||||
"Status: {lanes} lanes, backlog: {:.2} kiB ({packets}), no delay",
|
|
||||||
backlog
|
|
||||||
)
|
|
||||||
} else {
|
} else {
|
||||||
format!(
|
format!(
|
||||||
"Status: {lanes} lanes, backlog: {:.2} kiB ({packets}), avg delay: {}ms ({mult})",
|
"Status: {lanes} lanes, backlog: {backlog:.2} kiB ({packets}), avg delay: {delay}ms ({mult})"
|
||||||
backlog, delay
|
|
||||||
)
|
)
|
||||||
};
|
};
|
||||||
if packets > 1000 {
|
if packets > 1000 {
|
||||||
|
|||||||
@@ -41,4 +41,8 @@ impl ReplyStorageBackend for Backend {
|
|||||||
async fn load_surb_storage(&self) -> Result<CombinedReplyStorage, Self::StorageError> {
|
async fn load_surb_storage(&self) -> Result<CombinedReplyStorage, Self::StorageError> {
|
||||||
self.empty.load_surb_storage().await
|
self.empty.load_surb_storage().await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn get_inactive_storage(&self) -> Result<CombinedReplyStorage, Self::StorageError> {
|
||||||
|
self.empty.get_inactive_storage()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,6 +10,12 @@ pub enum StorageError {
|
|||||||
#[error("the provided database path doesn't have a filename defined")]
|
#[error("the provided database path doesn't have a filename defined")]
|
||||||
DatabasePathWithoutFilename { provided_path: PathBuf },
|
DatabasePathWithoutFilename { provided_path: PathBuf },
|
||||||
|
|
||||||
|
#[error("unable to create the directory for the database")]
|
||||||
|
DatabasePathUnableToCreateParentDirectory {
|
||||||
|
provided_path: PathBuf,
|
||||||
|
source: io::Error,
|
||||||
|
},
|
||||||
|
|
||||||
#[error("failed to rename our databse file - {source}")]
|
#[error("failed to rename our databse file - {source}")]
|
||||||
DatabaseRenameError {
|
DatabaseRenameError {
|
||||||
#[source]
|
#[source]
|
||||||
|
|||||||
@@ -20,6 +20,16 @@ impl StorageManager {
|
|||||||
database_path: P,
|
database_path: P,
|
||||||
fresh: bool,
|
fresh: bool,
|
||||||
) -> Result<Self, StorageError> {
|
) -> Result<Self, StorageError> {
|
||||||
|
// ensure the whole directory structure exists
|
||||||
|
if let Some(parent_dir) = database_path.as_ref().parent() {
|
||||||
|
std::fs::create_dir_all(parent_dir).map_err(|source| {
|
||||||
|
StorageError::DatabasePathUnableToCreateParentDirectory {
|
||||||
|
provided_path: database_path.as_ref().to_path_buf(),
|
||||||
|
source,
|
||||||
|
}
|
||||||
|
})?;
|
||||||
|
}
|
||||||
|
|
||||||
let mut opts = sqlx::sqlite::SqliteConnectOptions::new()
|
let mut opts = sqlx::sqlite::SqliteConnectOptions::new()
|
||||||
.filename(database_path)
|
.filename(database_path)
|
||||||
.create_if_missing(fresh);
|
.create_if_missing(fresh);
|
||||||
|
|||||||
@@ -22,11 +22,49 @@ mod error;
|
|||||||
mod manager;
|
mod manager;
|
||||||
mod models;
|
mod models;
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
enum StorageManagerState {
|
||||||
|
Storage(StorageManager),
|
||||||
|
Inactive(InactiveMetadata),
|
||||||
|
}
|
||||||
|
|
||||||
|
// When the storage backaed is initialized as inactive, it will still contain metadata parameters
|
||||||
|
// that will be needed when the in-mem storage is fetched for use.
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct InactiveMetadata {
|
||||||
|
pub minimum_reply_surb_storage_threshold: usize,
|
||||||
|
pub maximum_reply_surb_storage_threshold: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl StorageManagerState {
|
||||||
|
fn get(&self) -> &StorageManager {
|
||||||
|
match self {
|
||||||
|
StorageManagerState::Storage(manager) => manager,
|
||||||
|
StorageManagerState::Inactive(_) => {
|
||||||
|
panic!("tried to get storage of an inactive backend")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_mut(&mut self) -> &mut StorageManager {
|
||||||
|
match self {
|
||||||
|
StorageManagerState::Storage(manager) => manager,
|
||||||
|
StorageManagerState::Inactive(_) => {
|
||||||
|
panic!("tried to get storage of an inactive backend")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_active(&self) -> bool {
|
||||||
|
matches!(self, StorageManagerState::Storage(_))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct Backend {
|
pub struct Backend {
|
||||||
temporary_old_path: Option<PathBuf>,
|
temporary_old_path: Option<PathBuf>,
|
||||||
database_path: PathBuf,
|
database_path: PathBuf,
|
||||||
manager: StorageManager,
|
manager: StorageManagerState,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Backend {
|
impl Backend {
|
||||||
@@ -40,17 +78,32 @@ impl Backend {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let manager = StorageManager::init(database_path, true).await?;
|
||||||
|
manager.create_status_table().await?;
|
||||||
|
|
||||||
let backend = Backend {
|
let backend = Backend {
|
||||||
temporary_old_path: None,
|
temporary_old_path: None,
|
||||||
database_path: owned_path,
|
database_path: owned_path,
|
||||||
manager: StorageManager::init(database_path, true).await?,
|
manager: StorageManagerState::Storage(manager),
|
||||||
};
|
};
|
||||||
|
|
||||||
backend.manager.create_status_table().await?;
|
|
||||||
|
|
||||||
Ok(backend)
|
Ok(backend)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn new_inactive(
|
||||||
|
minimum_reply_surb_storage_threshold: usize,
|
||||||
|
maximum_reply_surb_storage_threshold: usize,
|
||||||
|
) -> Self {
|
||||||
|
Backend {
|
||||||
|
temporary_old_path: None,
|
||||||
|
database_path: PathBuf::new(),
|
||||||
|
manager: StorageManagerState::Inactive(InactiveMetadata {
|
||||||
|
minimum_reply_surb_storage_threshold,
|
||||||
|
maximum_reply_surb_storage_threshold,
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn try_load<P: AsRef<Path>>(database_path: P) -> Result<Self, StorageError> {
|
pub async fn try_load<P: AsRef<Path>>(database_path: P) -> Result<Self, StorageError> {
|
||||||
let owned_path: PathBuf = database_path.as_ref().into();
|
let owned_path: PathBuf = database_path.as_ref().into();
|
||||||
if owned_path.file_name().is_none() {
|
if owned_path.file_name().is_none() {
|
||||||
@@ -119,12 +172,12 @@ impl Backend {
|
|||||||
Ok(Backend {
|
Ok(Backend {
|
||||||
temporary_old_path: None,
|
temporary_old_path: None,
|
||||||
database_path: owned_path,
|
database_path: owned_path,
|
||||||
manager,
|
manager: StorageManagerState::Storage(manager),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn close_pool(&mut self) {
|
async fn close_pool(&mut self) {
|
||||||
self.manager.connection_pool.close().await;
|
self.manager.get_mut().connection_pool.close().await;
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn rotate(&mut self) -> Result<(), StorageError> {
|
async fn rotate(&mut self) -> Result<(), StorageError> {
|
||||||
@@ -143,8 +196,9 @@ impl Backend {
|
|||||||
|
|
||||||
fs::rename(&self.database_path, &temp_old)
|
fs::rename(&self.database_path, &temp_old)
|
||||||
.map_err(|err| StorageError::DatabaseRenameError { source: err })?;
|
.map_err(|err| StorageError::DatabaseRenameError { source: err })?;
|
||||||
self.manager = StorageManager::init(&self.database_path, true).await?;
|
self.manager =
|
||||||
self.manager.create_status_table().await?;
|
StorageManagerState::Storage(StorageManager::init(&self.database_path, true).await?);
|
||||||
|
self.manager.get_mut().create_status_table().await?;
|
||||||
|
|
||||||
self.temporary_old_path = Some(temp_old);
|
self.temporary_old_path = Some(temp_old);
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -161,26 +215,27 @@ impl Backend {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async fn start_storage_flush(&self) -> Result<(), StorageError> {
|
async fn start_storage_flush(&self) -> Result<(), StorageError> {
|
||||||
Ok(self.manager.set_flush_status(true).await?)
|
Ok(self.manager.get().set_flush_status(true).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn end_storage_flush(&self) -> Result<(), StorageError> {
|
async fn end_storage_flush(&self) -> Result<(), StorageError> {
|
||||||
self.manager
|
self.manager
|
||||||
|
.get()
|
||||||
.set_previous_flush_timestamp(OffsetDateTime::now_utc().unix_timestamp())
|
.set_previous_flush_timestamp(OffsetDateTime::now_utc().unix_timestamp())
|
||||||
.await?;
|
.await?;
|
||||||
Ok(self.manager.set_flush_status(false).await?)
|
Ok(self.manager.get().set_flush_status(false).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn start_client_use(&self) -> Result<(), StorageError> {
|
async fn start_client_use(&self) -> Result<(), StorageError> {
|
||||||
Ok(self.manager.set_client_in_use_status(true).await?)
|
Ok(self.manager.get().set_client_in_use_status(true).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn stop_client_use(&self) -> Result<(), StorageError> {
|
async fn stop_client_use(&self) -> Result<(), StorageError> {
|
||||||
Ok(self.manager.set_client_in_use_status(false).await?)
|
Ok(self.manager.get().set_client_in_use_status(false).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn get_stored_tags(&self) -> Result<UsedSenderTags, StorageError> {
|
async fn get_stored_tags(&self) -> Result<UsedSenderTags, StorageError> {
|
||||||
let stored = self.manager.get_tags().await?;
|
let stored = self.manager.get().get_tags().await?;
|
||||||
|
|
||||||
// stop at the first instance of corruption. if even a single entry is malformed,
|
// stop at the first instance of corruption. if even a single entry is malformed,
|
||||||
// something weird has happened and we can't trust the rest of the data
|
// something weird has happened and we can't trust the rest of the data
|
||||||
@@ -196,6 +251,7 @@ impl Backend {
|
|||||||
for map_ref in tags.as_raw_iter() {
|
for map_ref in tags.as_raw_iter() {
|
||||||
let (recipient, tag) = map_ref.pair();
|
let (recipient, tag) = map_ref.pair();
|
||||||
self.manager
|
self.manager
|
||||||
|
.get()
|
||||||
.insert_tag(StoredSenderTag::new(*recipient, *tag))
|
.insert_tag(StoredSenderTag::new(*recipient, *tag))
|
||||||
.await?;
|
.await?;
|
||||||
}
|
}
|
||||||
@@ -203,7 +259,7 @@ impl Backend {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async fn get_stored_reply_keys(&self) -> Result<SentReplyKeys, StorageError> {
|
async fn get_stored_reply_keys(&self) -> Result<SentReplyKeys, StorageError> {
|
||||||
let stored = self.manager.get_reply_keys().await?;
|
let stored = self.manager.get().get_reply_keys().await?;
|
||||||
|
|
||||||
// stop at the first instance of corruption. if even a single entry is malformed,
|
// stop at the first instance of corruption. if even a single entry is malformed,
|
||||||
// something weird has happened and we can't trust the rest of the data
|
// something weird has happened and we can't trust the rest of the data
|
||||||
@@ -219,6 +275,7 @@ impl Backend {
|
|||||||
for map_ref in reply_keys.as_raw_iter() {
|
for map_ref in reply_keys.as_raw_iter() {
|
||||||
let (digest, key) = map_ref.pair();
|
let (digest, key) = map_ref.pair();
|
||||||
self.manager
|
self.manager
|
||||||
|
.get()
|
||||||
.insert_reply_key(StoredReplyKey::new(*digest, *key))
|
.insert_reply_key(StoredReplyKey::new(*digest, *key))
|
||||||
.await?;
|
.await?;
|
||||||
}
|
}
|
||||||
@@ -226,7 +283,7 @@ impl Backend {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async fn get_stored_reply_surbs(&self) -> Result<ReceivedReplySurbsMap, StorageError> {
|
async fn get_stored_reply_surbs(&self) -> Result<ReceivedReplySurbsMap, StorageError> {
|
||||||
let surb_senders = self.manager.get_surb_senders().await?;
|
let surb_senders = self.manager.get().get_surb_senders().await?;
|
||||||
|
|
||||||
let metadata = self.get_reply_surb_storage_metadata().await?;
|
let metadata = self.get_reply_surb_storage_metadata().await?;
|
||||||
let mut received_surbs = Vec::with_capacity(surb_senders.len());
|
let mut received_surbs = Vec::with_capacity(surb_senders.len());
|
||||||
@@ -236,6 +293,7 @@ impl Backend {
|
|||||||
sender.try_into()?;
|
sender.try_into()?;
|
||||||
let stored_surbs = self
|
let stored_surbs = self
|
||||||
.manager
|
.manager
|
||||||
|
.get()
|
||||||
.get_reply_surbs(sender_id)
|
.get_reply_surbs(sender_id)
|
||||||
.await?
|
.await?
|
||||||
.into_iter()
|
.into_iter()
|
||||||
@@ -263,6 +321,7 @@ impl Backend {
|
|||||||
let (tag, received_surbs) = map_ref.pair();
|
let (tag, received_surbs) = map_ref.pair();
|
||||||
let sender_id = self
|
let sender_id = self
|
||||||
.manager
|
.manager
|
||||||
|
.get()
|
||||||
.insert_surb_sender(StoredSurbSender::new(
|
.insert_surb_sender(StoredSurbSender::new(
|
||||||
*tag,
|
*tag,
|
||||||
received_surbs.surbs_last_received_at(),
|
received_surbs.surbs_last_received_at(),
|
||||||
@@ -271,6 +330,7 @@ impl Backend {
|
|||||||
|
|
||||||
for reply_surb in received_surbs.surbs_ref() {
|
for reply_surb in received_surbs.surbs_ref() {
|
||||||
self.manager
|
self.manager
|
||||||
|
.get()
|
||||||
.insert_reply_surb(StoredReplySurb::new(sender_id, reply_surb))
|
.insert_reply_surb(StoredReplySurb::new(sender_id, reply_surb))
|
||||||
.await?
|
.await?
|
||||||
}
|
}
|
||||||
@@ -282,6 +342,7 @@ impl Backend {
|
|||||||
&self,
|
&self,
|
||||||
) -> Result<ReplySurbStorageMetadata, StorageError> {
|
) -> Result<ReplySurbStorageMetadata, StorageError> {
|
||||||
self.manager
|
self.manager
|
||||||
|
.get()
|
||||||
.get_reply_surb_storage_metadata()
|
.get_reply_surb_storage_metadata()
|
||||||
.await
|
.await
|
||||||
.map_err(Into::into)
|
.map_err(Into::into)
|
||||||
@@ -292,6 +353,7 @@ impl Backend {
|
|||||||
reply_surbs: &ReceivedReplySurbsMap,
|
reply_surbs: &ReceivedReplySurbsMap,
|
||||||
) -> Result<(), StorageError> {
|
) -> Result<(), StorageError> {
|
||||||
self.manager
|
self.manager
|
||||||
|
.get()
|
||||||
.insert_reply_surb_storage_metadata(ReplySurbStorageMetadata::new(
|
.insert_reply_surb_storage_metadata(ReplySurbStorageMetadata::new(
|
||||||
reply_surbs.min_surb_threshold(),
|
reply_surbs.min_surb_threshold(),
|
||||||
reply_surbs.max_surb_threshold(),
|
reply_surbs.max_surb_threshold(),
|
||||||
@@ -305,6 +367,10 @@ impl Backend {
|
|||||||
impl ReplyStorageBackend for Backend {
|
impl ReplyStorageBackend for Backend {
|
||||||
type StorageError = error::StorageError;
|
type StorageError = error::StorageError;
|
||||||
|
|
||||||
|
fn is_active(&self) -> bool {
|
||||||
|
self.manager.is_active()
|
||||||
|
}
|
||||||
|
|
||||||
async fn start_storage_session(&self) -> Result<(), Self::StorageError> {
|
async fn start_storage_session(&self) -> Result<(), Self::StorageError> {
|
||||||
self.start_client_use().await
|
self.start_client_use().await
|
||||||
}
|
}
|
||||||
@@ -342,6 +408,18 @@ impl ReplyStorageBackend for Backend {
|
|||||||
Ok(CombinedReplyStorage::load(reply_keys, reply_surbs, tags))
|
Ok(CombinedReplyStorage::load(reply_keys, reply_surbs, tags))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn get_inactive_storage(&self) -> Result<CombinedReplyStorage, Self::StorageError> {
|
||||||
|
match self.manager {
|
||||||
|
StorageManagerState::Storage(_) => {
|
||||||
|
panic!("tried to get inactive storage from an active storage backend")
|
||||||
|
}
|
||||||
|
StorageManagerState::Inactive(ref state) => Ok(CombinedReplyStorage::new(
|
||||||
|
state.minimum_reply_surb_storage_threshold,
|
||||||
|
state.maximum_reply_surb_storage_threshold,
|
||||||
|
)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async fn stop_storage_session(self) -> Result<(), Self::StorageError> {
|
async fn stop_storage_session(self) -> Result<(), Self::StorageError> {
|
||||||
self.stop_client_use().await
|
self.stop_client_use().await
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -44,8 +44,7 @@ impl TryFrom<StoredSenderTag> for (RecipientBytes, AnonymousSenderTag) {
|
|||||||
let Ok(sender_tag_bytes) = value.tag.try_into() else {
|
let Ok(sender_tag_bytes) = value.tag.try_into() else {
|
||||||
return Err(StorageError::CorruptedData {
|
return Err(StorageError::CorruptedData {
|
||||||
details: format!(
|
details: format!(
|
||||||
"the retrieved sender tag has length of {tag_len} while {} was expected",
|
"the retrieved sender tag has length of {tag_len} while {SENDER_TAG_SIZE} was expected",
|
||||||
SENDER_TAG_SIZE
|
|
||||||
),
|
),
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
@@ -132,8 +131,7 @@ impl TryFrom<StoredSurbSender> for (AnonymousSenderTag, i64) {
|
|||||||
let Ok(sender_tag_bytes) = value.tag.try_into() else {
|
let Ok(sender_tag_bytes) = value.tag.try_into() else {
|
||||||
return Err(StorageError::CorruptedData {
|
return Err(StorageError::CorruptedData {
|
||||||
details: format!(
|
details: format!(
|
||||||
"the retrieved sender tag has length of {tag_len} while {} was expected",
|
"the retrieved sender tag has length of {tag_len} while {SENDER_TAG_SIZE} was expected",
|
||||||
SENDER_TAG_SIZE
|
|
||||||
),
|
),
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -50,12 +50,23 @@ impl ReplyStorageBackend for Empty {
|
|||||||
self.max_surb_threshold,
|
self.max_surb_threshold,
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn get_inactive_storage(&self) -> Result<CombinedReplyStorage, Self::StorageError> {
|
||||||
|
Ok(CombinedReplyStorage::new(
|
||||||
|
self.min_surb_threshold,
|
||||||
|
self.max_surb_threshold,
|
||||||
|
))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
pub trait ReplyStorageBackend: Sized {
|
pub trait ReplyStorageBackend: Sized {
|
||||||
type StorageError: Error + 'static;
|
type StorageError: Error + 'static;
|
||||||
|
|
||||||
|
fn is_active(&self) -> bool {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
async fn start_storage_session(&self) -> Result<(), Self::StorageError> {
|
async fn start_storage_session(&self) -> Result<(), Self::StorageError> {
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -73,6 +84,11 @@ pub trait ReplyStorageBackend: Sized {
|
|||||||
|
|
||||||
async fn load_surb_storage(&self) -> Result<CombinedReplyStorage, Self::StorageError>;
|
async fn load_surb_storage(&self) -> Result<CombinedReplyStorage, Self::StorageError>;
|
||||||
|
|
||||||
|
/// In the case the storage backend is initialized in an inactive state (persisting data is
|
||||||
|
/// disabled), we might still need to fetch the (in-mem) storage and the parameters it was
|
||||||
|
/// created with.
|
||||||
|
fn get_inactive_storage(&self) -> Result<CombinedReplyStorage, Self::StorageError>;
|
||||||
|
|
||||||
async fn stop_storage_session(self) -> Result<(), Self::StorageError> {
|
async fn stop_storage_session(self) -> Result<(), Self::StorageError> {
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -88,6 +88,7 @@ impl<T> Config<T> {
|
|||||||
Config::default().with_id(id)
|
Config::default().with_id(id)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
pub fn with_id<S: Into<String>>(mut self, id: S) -> Self
|
pub fn with_id<S: Into<String>>(mut self, id: S) -> Self
|
||||||
where
|
where
|
||||||
T: NymConfig,
|
T: NymConfig,
|
||||||
@@ -540,35 +541,35 @@ impl<T: NymConfig> Default for Client<T> {
|
|||||||
|
|
||||||
impl<T: NymConfig> Client<T> {
|
impl<T: NymConfig> Client<T> {
|
||||||
fn default_private_identity_key_file(id: &str) -> PathBuf {
|
fn default_private_identity_key_file(id: &str) -> PathBuf {
|
||||||
T::default_data_directory(Some(id)).join("private_identity.pem")
|
T::default_data_directory(id).join("private_identity.pem")
|
||||||
}
|
}
|
||||||
|
|
||||||
fn default_public_identity_key_file(id: &str) -> PathBuf {
|
fn default_public_identity_key_file(id: &str) -> PathBuf {
|
||||||
T::default_data_directory(Some(id)).join("public_identity.pem")
|
T::default_data_directory(id).join("public_identity.pem")
|
||||||
}
|
}
|
||||||
|
|
||||||
fn default_private_encryption_key_file(id: &str) -> PathBuf {
|
fn default_private_encryption_key_file(id: &str) -> PathBuf {
|
||||||
T::default_data_directory(Some(id)).join("private_encryption.pem")
|
T::default_data_directory(id).join("private_encryption.pem")
|
||||||
}
|
}
|
||||||
|
|
||||||
fn default_public_encryption_key_file(id: &str) -> PathBuf {
|
fn default_public_encryption_key_file(id: &str) -> PathBuf {
|
||||||
T::default_data_directory(Some(id)).join("public_encryption.pem")
|
T::default_data_directory(id).join("public_encryption.pem")
|
||||||
}
|
}
|
||||||
|
|
||||||
fn default_gateway_shared_key_file(id: &str) -> PathBuf {
|
fn default_gateway_shared_key_file(id: &str) -> PathBuf {
|
||||||
T::default_data_directory(Some(id)).join("gateway_shared.pem")
|
T::default_data_directory(id).join("gateway_shared.pem")
|
||||||
}
|
}
|
||||||
|
|
||||||
fn default_ack_key_file(id: &str) -> PathBuf {
|
fn default_ack_key_file(id: &str) -> PathBuf {
|
||||||
T::default_data_directory(Some(id)).join("ack_key.pem")
|
T::default_data_directory(id).join("ack_key.pem")
|
||||||
}
|
}
|
||||||
|
|
||||||
fn default_reply_surb_database_path(id: &str) -> PathBuf {
|
fn default_reply_surb_database_path(id: &str) -> PathBuf {
|
||||||
T::default_data_directory(Some(id)).join("persistent_reply_store.sqlite")
|
T::default_data_directory(id).join("persistent_reply_store.sqlite")
|
||||||
}
|
}
|
||||||
|
|
||||||
fn default_database_path(id: &str) -> PathBuf {
|
fn default_database_path(id: &str) -> PathBuf {
|
||||||
T::default_data_directory(Some(id)).join(DB_FILE_NAME)
|
T::default_data_directory(id).join(DB_FILE_NAME)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -65,8 +65,10 @@ pub enum ClientCoreError {
|
|||||||
/// Set of messages that the client can send to listeners via the task manager
|
/// Set of messages that the client can send to listeners via the task manager
|
||||||
#[derive(thiserror::Error, Debug)]
|
#[derive(thiserror::Error, Debug)]
|
||||||
pub enum ClientCoreStatusMessage {
|
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")]
|
#[error("The connected gateway is slow, or the connection to it is slow")]
|
||||||
GatewayIsSlow,
|
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")]
|
#[error("The connected gateway is very slow, or the connection to it is very slow")]
|
||||||
GatewayIsVerySlow,
|
GatewayIsVerySlow,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,6 +8,8 @@ use crate::{
|
|||||||
};
|
};
|
||||||
use config::NymConfig;
|
use config::NymConfig;
|
||||||
use crypto::asymmetric::identity;
|
use crypto::asymmetric::identity;
|
||||||
|
#[cfg(target_arch = "wasm32")]
|
||||||
|
use gateway_client::wasm_mockups::SigningNyxdClient;
|
||||||
use gateway_client::GatewayClient;
|
use gateway_client::GatewayClient;
|
||||||
use gateway_requests::registration::handshake::SharedKeys;
|
use gateway_requests::registration::handshake::SharedKeys;
|
||||||
use rand::{seq::SliceRandom, thread_rng};
|
use rand::{seq::SliceRandom, thread_rng};
|
||||||
@@ -15,10 +17,12 @@ use std::{sync::Arc, time::Duration};
|
|||||||
use tap::TapFallible;
|
use tap::TapFallible;
|
||||||
use topology::{filter::VersionFilterable, gateway};
|
use topology::{filter::VersionFilterable, gateway};
|
||||||
use url::Url;
|
use url::Url;
|
||||||
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
|
use validator_client::nyxd::SigningNyxdClient;
|
||||||
|
|
||||||
pub(super) async fn query_gateway_details(
|
pub(super) async fn query_gateway_details(
|
||||||
validator_servers: Vec<Url>,
|
validator_servers: Vec<Url>,
|
||||||
chosen_gateway_id: Option<String>,
|
chosen_gateway_id: Option<identity::PublicKey>,
|
||||||
) -> Result<gateway::Node, ClientCoreError> {
|
) -> Result<gateway::Node, ClientCoreError> {
|
||||||
let nym_api = validator_servers
|
let nym_api = validator_servers
|
||||||
.choose(&mut thread_rng())
|
.choose(&mut thread_rng())
|
||||||
@@ -40,7 +44,7 @@ pub(super) async fn query_gateway_details(
|
|||||||
if let Some(gateway_id) = chosen_gateway_id {
|
if let Some(gateway_id) = chosen_gateway_id {
|
||||||
filtered_gateways
|
filtered_gateways
|
||||||
.iter()
|
.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()))
|
.ok_or_else(|| ClientCoreError::NoGatewayWithId(gateway_id.to_string()))
|
||||||
.cloned()
|
.cloned()
|
||||||
} else {
|
} else {
|
||||||
@@ -56,7 +60,7 @@ pub(super) async fn register_with_gateway(
|
|||||||
our_identity: Arc<identity::KeyPair>,
|
our_identity: Arc<identity::KeyPair>,
|
||||||
) -> Result<Arc<SharedKeys>, ClientCoreError> {
|
) -> Result<Arc<SharedKeys>, ClientCoreError> {
|
||||||
let timeout = Duration::from_millis(1500);
|
let timeout = Duration::from_millis(1500);
|
||||||
let mut gateway_client = GatewayClient::new_init(
|
let mut gateway_client: GatewayClient<SigningNyxdClient> = GatewayClient::new_init(
|
||||||
gateway.clients_address(),
|
gateway.clients_address(),
|
||||||
gateway.identity_key,
|
gateway.identity_key,
|
||||||
gateway.owner.clone(),
|
gateway.owner.clone(),
|
||||||
|
|||||||
@@ -69,42 +69,21 @@ pub fn new_client_keys() -> KeyManager {
|
|||||||
KeyManager::new(&mut rng)
|
KeyManager::new(&mut rng)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Convenience function for setting up the gateway for a client. Depending on the arguments given
|
/// Authenticate and register with a gateway.
|
||||||
/// it will do the sensible thing.
|
/// Either pick one at random by querying the available gateways from the nym-api, or use the
|
||||||
pub async fn setup_gateway<C, T>(
|
/// chosen one if it's among the available ones.
|
||||||
register_gateway: bool,
|
/// The shared key is added to the supplied `KeyManager` and the endpoint details are returned.
|
||||||
// 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.
|
|
||||||
pub async fn register_with_gateway(
|
pub async fn register_with_gateway(
|
||||||
key_manager: &mut KeyManager,
|
key_manager: &mut KeyManager,
|
||||||
nym_api_endpoints: Vec<Url>,
|
nym_api_endpoints: Vec<Url>,
|
||||||
chosen_gateway_id: Option<String>,
|
chosen_gateway_id: Option<identity::PublicKey>,
|
||||||
) -> Result<GatewayEndpointConfig, ClientCoreError> {
|
) -> 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
|
// Get the gateway details of the gateway we will use
|
||||||
let gateway = helpers::query_gateway_details(nym_api_endpoints, chosen_gateway_id).await?;
|
let gateway = helpers::query_gateway_details(nym_api_endpoints, chosen_gateway_id).await?;
|
||||||
log::debug!("Querying gateway gives: {}", gateway);
|
log::debug!("Querying gateway gives: {}", gateway);
|
||||||
|
|
||||||
|
let our_identity = key_manager.identity_keypair();
|
||||||
|
|
||||||
// Establish connection, authenticate and generate keys for talking with the gateway
|
// Establish connection, authenticate and generate keys for talking with the gateway
|
||||||
let shared_keys = helpers::register_with_gateway(&gateway, our_identity).await?;
|
let shared_keys = helpers::register_with_gateway(&gateway, our_identity).await?;
|
||||||
key_manager.insert_gateway_shared_key(shared_keys);
|
key_manager.insert_gateway_shared_key(shared_keys);
|
||||||
@@ -112,60 +91,65 @@ pub async fn register_with_gateway(
|
|||||||
Ok(gateway.into())
|
Ok(gateway.into())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get the gateway details by querying the validator-api. Either pick one at random or use
|
/// Convenience function for setting up the gateway for a client given a `Config`. Depending on the
|
||||||
/// the chosen one if it's among the available ones.
|
/// arguments given it will do the sensible thing. Either it will
|
||||||
/// Saves keys to disk, specified by the paths in `config`.
|
///
|
||||||
pub async fn register_with_gateway_and_store<T>(
|
/// a. Reuse existing gateway configuration from storage.
|
||||||
chosen_gateway_id: Option<String>,
|
/// 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>,
|
config: &Config<T>,
|
||||||
) -> Result<GatewayEndpointConfig, ClientCoreError>
|
) -> Result<GatewayEndpointConfig, ClientCoreError>
|
||||||
where
|
where
|
||||||
|
C: NymConfig + ClientCoreConfigTrait,
|
||||||
T: NymConfig,
|
T: NymConfig,
|
||||||
{
|
{
|
||||||
println!("Configuring gateway");
|
let id = config.get_id();
|
||||||
let mut key_manager = new_client_keys();
|
|
||||||
|
|
||||||
let gateway = register_with_gateway(
|
// If we are not going to register gateway, and an explicitly chosed gateway is not passed in,
|
||||||
&mut key_manager,
|
// load the existing configuration file
|
||||||
config.get_nym_api_endpoints(),
|
if !register_gateway && user_chosen_gateway_id.is_none() {
|
||||||
chosen_gateway_id,
|
println!("Not registering gateway, will reuse existing config and keys");
|
||||||
)
|
return load_existing_gateway_config::<C>(&id);
|
||||||
.await?;
|
}
|
||||||
|
|
||||||
helpers::store_keys(&key_manager, config)?;
|
// Else, we preceed by querying the nym-api
|
||||||
println!("Saved all generated keys");
|
let gateway =
|
||||||
|
helpers::query_gateway_details(config.get_nym_api_endpoints(), user_chosen_gateway_id)
|
||||||
Ok(gateway)
|
.await?;
|
||||||
}
|
|
||||||
|
|
||||||
/// 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?;
|
|
||||||
log::debug!("Querying gateway gives: {}", gateway);
|
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())
|
Ok(gateway.into())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Read and reuse the existing gateway configuration from a file that was generate earlier.
|
/// 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
|
where
|
||||||
T: NymConfig + ClientCoreConfigTrait,
|
T: NymConfig + ClientCoreConfigTrait,
|
||||||
{
|
{
|
||||||
println!("Not registering gateway, will reuse existing config and keys");
|
T::load_from_file(id)
|
||||||
T::load_from_file(Some(id))
|
|
||||||
.map(|existing_config| existing_config.get_gateway_endpoint().clone())
|
.map(|existing_config| existing_config.get_gateway_endpoint().clone())
|
||||||
.map_err(|err| {
|
.map_err(|err| {
|
||||||
log::error!(
|
log::error!(
|
||||||
@@ -242,9 +226,9 @@ where
|
|||||||
pub fn output_to_json<T: Serialize>(init_results: &T, output_file: &str) {
|
pub fn output_to_json<T: Serialize>(init_results: &T, output_file: &str) {
|
||||||
match std::fs::File::create(output_file) {
|
match std::fs::File::create(output_file) {
|
||||||
Ok(file) => match serde_json::to_writer_pretty(file, init_results) {
|
Ok(file) => match serde_json::to_writer_pretty(file, init_results) {
|
||||||
Ok(_) => println!("Saved: {}", output_file),
|
Ok(_) => println!("Saved: {output_file}"),
|
||||||
Err(err) => eprintln!("Could not save {}: {err}", 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}"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ rand = "0.7.3"
|
|||||||
serde = { version = "1.0", features = ["derive"] }
|
serde = { version = "1.0", features = ["derive"] }
|
||||||
thiserror = "1.0"
|
thiserror = "1.0"
|
||||||
url = "2.2"
|
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" }
|
coconut-interface = { path = "../../common/coconut-interface" }
|
||||||
config = { path = "../../common/config" }
|
config = { path = "../../common/config" }
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ use credentials::coconut::bandwidth::{BandwidthVoucher, TOTAL_ATTRIBUTES};
|
|||||||
use credentials::coconut::utils::obtain_aggregate_signature;
|
use credentials::coconut::utils::obtain_aggregate_signature;
|
||||||
use crypto::asymmetric::{encryption, identity};
|
use crypto::asymmetric::{encryption, identity};
|
||||||
use network_defaults::{NymNetworkDetails, VOUCHER_INFO};
|
use network_defaults::{NymNetworkDetails, VOUCHER_INFO};
|
||||||
|
use validator_client::nyxd::traits::DkgQueryClient;
|
||||||
use validator_client::nyxd::tx::Hash;
|
use validator_client::nyxd::tx::Hash;
|
||||||
use validator_client::{CoconutApiClient, Config};
|
use validator_client::{CoconutApiClient, Config};
|
||||||
|
|
||||||
@@ -80,7 +81,8 @@ pub(crate) async fn get_credential(state: &State, shared_storage: PersistentStor
|
|||||||
let network_details = NymNetworkDetails::new_from_env();
|
let network_details = NymNetworkDetails::new_from_env();
|
||||||
let config = Config::try_from_nym_network_details(&network_details)?;
|
let config = Config::try_from_nym_network_details(&network_details)?;
|
||||||
let client = validator_client::Client::new_query(config)?;
|
let client = validator_client::Client::new_query(config)?;
|
||||||
let coconut_api_clients = CoconutApiClient::all_coconut_api_clients(&client).await?;
|
let epoch_id = client.nyxd.get_current_epoch().await?.epoch_id;
|
||||||
|
let coconut_api_clients = CoconutApiClient::all_coconut_api_clients(&client, epoch_id).await?;
|
||||||
|
|
||||||
let params = Parameters::new(TOTAL_ATTRIBUTES).unwrap();
|
let params = Parameters::new(TOTAL_ATTRIBUTES).unwrap();
|
||||||
let bandwidth_credential_attributes = BandwidthVoucher::new(
|
let bandwidth_credential_attributes = BandwidthVoucher::new(
|
||||||
@@ -106,6 +108,7 @@ pub(crate) async fn get_credential(state: &State, shared_storage: PersistentStor
|
|||||||
bandwidth_credential_attributes.get_private_attributes()[0].to_bs58(),
|
bandwidth_credential_attributes.get_private_attributes()[0].to_bs58(),
|
||||||
bandwidth_credential_attributes.get_private_attributes()[1].to_bs58(),
|
bandwidth_credential_attributes.get_private_attributes()[1].to_bs58(),
|
||||||
signature.to_bs58(),
|
signature.to_bs58(),
|
||||||
|
epoch_id.to_string(),
|
||||||
)
|
)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "nym-client"
|
name = "nym-client"
|
||||||
version = "1.1.5"
|
version = "1.1.8"
|
||||||
authors = ["Dave Hrycyszyn <futurechimp@users.noreply.github.com>", "Jędrzej Stuczyński <andrew@nymtech.net>"]
|
authors = ["Dave Hrycyszyn <futurechimp@users.noreply.github.com>", "Jędrzej Stuczyński <andrew@nymtech.net>"]
|
||||||
description = "Implementation of the Nym Client"
|
description = "Implementation of the Nym Client"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
@@ -23,14 +23,14 @@ url = "2.2"
|
|||||||
clap = { version = "4.0", features = ["cargo", "derive"] }
|
clap = { version = "4.0", features = ["cargo", "derive"] }
|
||||||
dirs = "4.0"
|
dirs = "4.0"
|
||||||
lazy_static = "1.4.0"
|
lazy_static = "1.4.0"
|
||||||
log = "0.4" # self explanatory
|
log = { workspace = true } # self explanatory
|
||||||
pretty_env_logger = "0.4" # for formatting log messages
|
pretty_env_logger = "0.4" # for formatting log messages
|
||||||
rand = { version = "0.7.3", features = ["wasm-bindgen"] } # rng-related traits + some rng implementation to use
|
rand = { version = "0.7.3", features = ["wasm-bindgen"] } # rng-related traits + some rng implementation to use
|
||||||
serde = { version = "1.0.104", features = ["derive"] } # for config serialization/deserialization
|
serde = { version = "1.0.104", features = ["derive"] } # for config serialization/deserialization
|
||||||
serde_json = "1.0"
|
serde_json = "1.0"
|
||||||
thiserror = "1.0.34"
|
thiserror = "1.0.34"
|
||||||
tap = "1.0.1"
|
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
|
tokio-tungstenite = "0.14" # websocket
|
||||||
|
|
||||||
## internal
|
## internal
|
||||||
|
|||||||
@@ -85,7 +85,7 @@ async fn send_file_without_reply() {
|
|||||||
let (mut ws_stream, _) = connect_async(uri).await.unwrap();
|
let (mut ws_stream, _) = connect_async(uri).await.unwrap();
|
||||||
|
|
||||||
let recipient = get_self_address(&mut ws_stream).await;
|
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();
|
let read_data = std::fs::read("examples/dummy_file").unwrap();
|
||||||
|
|
||||||
|
|||||||
@@ -36,7 +36,7 @@ async fn send_text_with_reply() {
|
|||||||
let (mut ws_stream, _) = connect_async(uri).await.unwrap();
|
let (mut ws_stream, _) = connect_async(uri).await.unwrap();
|
||||||
|
|
||||||
let recipient = get_self_address(&mut ws_stream).await;
|
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!({
|
let send_request = json!({
|
||||||
"type" : "send",
|
"type" : "send",
|
||||||
@@ -45,10 +45,7 @@ async fn send_text_with_reply() {
|
|||||||
"withReplySurb": true,
|
"withReplySurb": true,
|
||||||
});
|
});
|
||||||
|
|
||||||
println!(
|
println!("sending {message:?} (*with* reply SURB) over the mix network...");
|
||||||
"sending {:?} (*with* reply SURB) over the mix network...",
|
|
||||||
message
|
|
||||||
);
|
|
||||||
let response =
|
let response =
|
||||||
send_message_and_get_json_response(&mut ws_stream, send_request.to_string()).await;
|
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"]
|
"replySurb": response["replySurb"]
|
||||||
});
|
});
|
||||||
|
|
||||||
println!(
|
println!("sending {reply_message:?} (using reply SURB!) over the mix network...");
|
||||||
"sending {:?} (using reply SURB!) over the mix network...",
|
|
||||||
reply_message
|
|
||||||
);
|
|
||||||
|
|
||||||
let response =
|
let response =
|
||||||
send_message_and_get_json_response(&mut ws_stream, reply_request.to_string()).await;
|
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 (mut ws_stream, _) = connect_async(uri).await.unwrap();
|
||||||
|
|
||||||
let recipient = get_self_address(&mut ws_stream).await;
|
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!({
|
let send_request = json!({
|
||||||
"type" : "send",
|
"type" : "send",
|
||||||
@@ -85,10 +79,7 @@ async fn send_text_without_reply() {
|
|||||||
"withReplySurb": false,
|
"withReplySurb": false,
|
||||||
});
|
});
|
||||||
|
|
||||||
println!(
|
println!("sending {message:?} (*without* reply SURB) over the mix network...");
|
||||||
"sending {:?} (*without* reply SURB) over the mix network...",
|
|
||||||
message
|
|
||||||
);
|
|
||||||
let response =
|
let response =
|
||||||
send_message_and_get_json_response(&mut ws_stream, send_request.to_string()).await;
|
send_message_and_get_json_response(&mut ws_stream, send_request.to_string()).await;
|
||||||
|
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ use nymsphinx::addressing::clients::Recipient;
|
|||||||
use nymsphinx::anonymous_replies::requests::AnonymousSenderTag;
|
use nymsphinx::anonymous_replies::requests::AnonymousSenderTag;
|
||||||
use nymsphinx::receiver::ReconstructedMessage;
|
use nymsphinx::receiver::ReconstructedMessage;
|
||||||
use task::TaskManager;
|
use task::TaskManager;
|
||||||
|
use validator_client::nyxd::QueryNyxdClient;
|
||||||
|
|
||||||
pub(crate) mod config;
|
pub(crate) mod config;
|
||||||
|
|
||||||
@@ -44,42 +45,28 @@ impl SocketClient {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn create_bandwidth_controller(config: &Config) -> BandwidthController {
|
async fn create_bandwidth_controller(config: &Config) -> BandwidthController<QueryNyxdClient> {
|
||||||
#[cfg(feature = "coconut")]
|
let details = network_defaults::NymNetworkDetails::new_from_env();
|
||||||
let bandwidth_controller = {
|
let mut client_config = validator_client::Config::try_from_nym_network_details(&details)
|
||||||
let details = network_defaults::NymNetworkDetails::new_from_env();
|
.expect("failed to construct validator client config");
|
||||||
let mut client_config =
|
let nyxd_url = config
|
||||||
validator_client::Config::try_from_nym_network_details(&details)
|
.get_base()
|
||||||
.expect("failed to construct validator client config");
|
.get_validator_endpoints()
|
||||||
let nyxd_url = config
|
.pop()
|
||||||
.get_base()
|
.expect("No nyxd validator endpoint provided");
|
||||||
.get_validator_endpoints()
|
let api_url = config
|
||||||
.pop()
|
.get_base()
|
||||||
.expect("No nyxd validator endpoint provided");
|
.get_nym_api_endpoints()
|
||||||
let api_url = config
|
.pop()
|
||||||
.get_base()
|
.expect("No validator api endpoint provided");
|
||||||
.get_nym_api_endpoints()
|
// overwrite env configuration with config URLs
|
||||||
.pop()
|
client_config = client_config.with_urls(nyxd_url, api_url);
|
||||||
.expect("No validator api endpoint provided");
|
let client = validator_client::Client::new_query(client_config)
|
||||||
// overwrite env configuration with config URLs
|
.expect("Could not construct query client");
|
||||||
client_config = client_config.with_urls(nyxd_url, api_url);
|
BandwidthController::new(
|
||||||
let client = validator_client::Client::new_query(client_config)
|
|
||||||
.expect("Could not construct query client");
|
|
||||||
let coconut_api_clients =
|
|
||||||
validator_client::CoconutApiClient::all_coconut_api_clients(&client)
|
|
||||||
.await
|
|
||||||
.expect("Could not query api clients");
|
|
||||||
BandwidthController::new(
|
|
||||||
credential_storage::initialise_storage(config.get_base().get_database_path()).await,
|
|
||||||
coconut_api_clients,
|
|
||||||
)
|
|
||||||
};
|
|
||||||
#[cfg(not(feature = "coconut"))]
|
|
||||||
let bandwidth_controller = BandwidthController::new(
|
|
||||||
credential_storage::initialise_storage(config.get_base().get_database_path()).await,
|
credential_storage::initialise_storage(config.get_base().get_database_path()).await,
|
||||||
|
client,
|
||||||
)
|
)
|
||||||
.expect("Could not create bandwidth controller");
|
|
||||||
bandwidth_controller
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn start_websocket_listener(
|
fn start_websocket_listener(
|
||||||
@@ -120,16 +107,9 @@ impl SocketClient {
|
|||||||
|
|
||||||
/// blocking version of `start_socket` method. Will run forever (or until SIGINT is sent)
|
/// 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>> {
|
pub async fn run_socket_forever(self) -> Result<(), Box<dyn Error + Send + Sync>> {
|
||||||
let mut shutdown = self.start_socket().await?;
|
let 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 res = shutdown.catch_interrupt().await;
|
||||||
log::info!("Stopping nym-client");
|
log::info!("Stopping nym-client");
|
||||||
res
|
res
|
||||||
}
|
}
|
||||||
@@ -144,7 +124,7 @@ impl SocketClient {
|
|||||||
self.key_manager,
|
self.key_manager,
|
||||||
Some(Self::create_bandwidth_controller(&self.config).await),
|
Some(Self::create_bandwidth_controller(&self.config).await),
|
||||||
non_wasm_helpers::setup_fs_reply_surb_backend(
|
non_wasm_helpers::setup_fs_reply_surb_backend(
|
||||||
self.config.get_base().get_reply_surb_database_path(),
|
Some(self.config.get_base().get_reply_surb_database_path()),
|
||||||
self.config.get_debug_settings(),
|
self.config.get_debug_settings(),
|
||||||
)
|
)
|
||||||
.await?,
|
.await?,
|
||||||
@@ -181,7 +161,7 @@ impl SocketClient {
|
|||||||
self.key_manager,
|
self.key_manager,
|
||||||
Some(Self::create_bandwidth_controller(&self.config).await),
|
Some(Self::create_bandwidth_controller(&self.config).await),
|
||||||
non_wasm_helpers::setup_fs_reply_surb_backend(
|
non_wasm_helpers::setup_fs_reply_surb_backend(
|
||||||
self.config.get_base().get_reply_surb_database_path(),
|
Some(self.config.get_base().get_reply_surb_database_path()),
|
||||||
self.config.get_debug_settings(),
|
self.config.get_debug_settings(),
|
||||||
)
|
)
|
||||||
.await?,
|
.await?,
|
||||||
|
|||||||
@@ -112,18 +112,17 @@ pub(crate) async fn execute(args: &Init) -> Result<(), ClientError> {
|
|||||||
|
|
||||||
let id = &args.id;
|
let id = &args.id;
|
||||||
|
|
||||||
let already_init = Config::default_config_file_path(Some(id)).exists();
|
let already_init = Config::default_config_file_path(id).exists();
|
||||||
if already_init {
|
if already_init {
|
||||||
println!(
|
println!("Client \"{id}\" was already initialised before");
|
||||||
"Client \"{}\" was already initialised before! \
|
|
||||||
Config information will be overwritten (but keys will be kept)!",
|
|
||||||
id
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Usually you only register with the gateway on the first init, however you can force
|
// Usually you only register with the gateway on the first init, however you can force
|
||||||
// re-registering if wanted.
|
// re-registering if wanted.
|
||||||
let user_wants_force_register = args.force_register_gateway;
|
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
|
// 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).
|
// 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
|
// 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.
|
// 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,
|
register_gateway,
|
||||||
user_chosen_gateway_id.map(|id| id.to_base58_string()),
|
user_chosen_gateway_id,
|
||||||
config.get_base(),
|
config.get_base(),
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
@@ -169,7 +168,7 @@ pub(crate) async fn execute(args: &Init) -> Result<(), ClientError> {
|
|||||||
|
|
||||||
fn print_saved_config(config: &Config) {
|
fn print_saved_config(config: &Config) {
|
||||||
let config_save_location = config.get_config_file_save_location();
|
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());
|
println!("Using gateway: {}", config.get_base().get_gateway_id());
|
||||||
log::debug!("Gateway id: {}", 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());
|
log::debug!("Gateway owner: {}", config.get_base().get_gateway_owner());
|
||||||
|
|||||||
@@ -99,7 +99,7 @@ fn version_check(cfg: &Config) -> bool {
|
|||||||
pub(crate) async fn execute(args: &Run) -> Result<(), Box<dyn Error + Send + Sync>> {
|
pub(crate) async fn execute(args: &Run) -> Result<(), Box<dyn Error + Send + Sync>> {
|
||||||
let id = &args.id;
|
let id = &args.id;
|
||||||
|
|
||||||
let mut config = match Config::load_from_file(Some(id)) {
|
let mut config = match Config::load_from_file(id) {
|
||||||
Ok(cfg) => cfg,
|
Ok(cfg) => cfg,
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
error!("Failed to load config for {}. Are you sure you have run `init` before? (Error was: {err})", id);
|
error!("Failed to load config for {}. Are you sure you have run `init` before? (Error was: {err})", id);
|
||||||
|
|||||||
@@ -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) {
|
fn print_start_upgrade<D1: Display, D2: Display>(from: D1, to: D2) {
|
||||||
println!(
|
println!("\n==================\nTrying to upgrade client from {from} to {to} ...");
|
||||||
"\n==================\nTrying to upgrade client from {} to {} ...",
|
|
||||||
from, to
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn print_failed_upgrade<D1: Display, D2: Display>(from: D1, to: D2) {
|
fn print_failed_upgrade<D1: Display, D2: Display>(from: D1, to: D2) {
|
||||||
eprintln!(
|
eprintln!("Upgrade from {from} to {to} failed!\n==================\n");
|
||||||
"Upgrade from {} to {} failed!\n==================\n",
|
|
||||||
from, to
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn print_successful_upgrade<D1: Display, D2: Display>(from: D1, to: D2) {
|
fn print_successful_upgrade<D1: Display, D2: Display>(from: D1, to: D2) {
|
||||||
println!(
|
println!("Upgrade from {from} to {to} was successful!\n==================\n");
|
||||||
"Upgrade from {} to {} was successful!\n==================\n",
|
|
||||||
from, to
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn outdated_upgrade(config_version: &Version, package_version: &Version) -> ! {
|
fn outdated_upgrade(config_version: &Version, package_version: &Version) -> ! {
|
||||||
eprintln!(
|
eprintln!(
|
||||||
"Cannot perform upgrade from {} to {}. Your version is too old to perform the upgrade.!",
|
"Cannot perform upgrade from {config_version} to {package_version}. Your version is too old to perform the upgrade.!"
|
||||||
config_version, package_version
|
|
||||||
);
|
);
|
||||||
process::exit(1)
|
process::exit(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn unsupported_upgrade(current_version: &Version, config_version: &Version) -> ! {
|
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)
|
process::exit(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -65,8 +55,7 @@ fn parse_config_version(config: &Config) -> Version {
|
|||||||
|
|
||||||
if version.is_prerelease() || !version.build.is_empty() {
|
if version.is_prerelease() || !version.build.is_empty() {
|
||||||
eprintln!(
|
eprintln!(
|
||||||
"Trying to upgrade from a non-released version {}. This is not supported!",
|
"Trying to upgrade from a non-released version {version}. This is not supported!"
|
||||||
version
|
|
||||||
);
|
);
|
||||||
process::exit(1)
|
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.
|
// 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 we change our mind, we could easily tweak this code
|
||||||
if version.is_prerelease() || !version.build.is_empty() {
|
if version.is_prerelease() || !version.build.is_empty() {
|
||||||
eprintln!(
|
eprintln!("Trying to upgrade to a non-released version {version}. This is not supported!");
|
||||||
"Trying to upgrade to a non-released version {}. This is not supported!",
|
|
||||||
version
|
|
||||||
);
|
|
||||||
process::exit(1)
|
process::exit(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -145,7 +131,7 @@ pub(crate) fn execute(args: &Upgrade) {
|
|||||||
|
|
||||||
let id = &args.id;
|
let id = &args.id;
|
||||||
|
|
||||||
let existing_config = Config::load_from_file(Some(id)).unwrap_or_else(|err| {
|
let existing_config = Config::load_from_file(id).unwrap_or_else(|err| {
|
||||||
eprintln!("failed to load existing config file! - {err}");
|
eprintln!("failed to load existing config file! - {err}");
|
||||||
process::exit(1)
|
process::exit(1)
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
|
|
||||||
use std::error::Error;
|
use std::error::Error;
|
||||||
|
|
||||||
use clap::{crate_version, Parser};
|
use clap::{crate_name, crate_version, Parser};
|
||||||
use logging::setup_logging;
|
use logging::setup_logging;
|
||||||
use network_defaults::setup_env;
|
use network_defaults::setup_env;
|
||||||
|
|
||||||
@@ -15,26 +15,9 @@ pub mod websocket;
|
|||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
async fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
|
async fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
|
||||||
setup_logging();
|
setup_logging();
|
||||||
println!("{}", banner());
|
println!("{}", logging::banner(crate_name!(), crate_version!()));
|
||||||
|
|
||||||
let args = commands::Cli::parse();
|
let args = commands::Cli::parse();
|
||||||
setup_env(args.config_env_file.as_ref());
|
setup_env(args.config_env_file.as_ref());
|
||||||
commands::execute(&args).await
|
commands::execute(&args).await
|
||||||
}
|
}
|
||||||
|
|
||||||
fn banner() -> String {
|
|
||||||
format!(
|
|
||||||
r#"
|
|
||||||
|
|
||||||
_ __ _ _ _ __ ___
|
|
||||||
| '_ \| | | | '_ \ _ \
|
|
||||||
| | | | |_| | | | | | |
|
|
||||||
|_| |_|\__, |_| |_| |_|
|
|
||||||
|___/
|
|
||||||
|
|
||||||
(client - version {:})
|
|
||||||
|
|
||||||
"#,
|
|
||||||
crate_version!()
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -27,17 +27,13 @@ use tokio_tungstenite::{
|
|||||||
};
|
};
|
||||||
use websocket_requests::{requests::ClientRequest, responses::ServerResponse};
|
use websocket_requests::{requests::ClientRequest, responses::ServerResponse};
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
enum ReceivedResponseType {
|
enum ReceivedResponseType {
|
||||||
|
#[default]
|
||||||
Binary,
|
Binary,
|
||||||
Text,
|
Text,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for ReceivedResponseType {
|
|
||||||
fn default() -> Self {
|
|
||||||
ReceivedResponseType::Binary
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) struct HandlerBuilder {
|
pub(crate) struct HandlerBuilder {
|
||||||
msg_input: InputMessageSender,
|
msg_input: InputMessageSender,
|
||||||
client_connection_tx: ConnectionCommandSender,
|
client_connection_tx: ConnectionCommandSender,
|
||||||
|
|||||||
@@ -84,7 +84,7 @@ impl TryFrom<u8> for ErrorKind {
|
|||||||
|
|
||||||
n => Err(Error::new(
|
n => Err(Error::new(
|
||||||
ErrorKind::MalformedResponse,
|
ErrorKind::MalformedResponse,
|
||||||
format!("invalid error code {}", n),
|
format!("invalid error code {n}"),
|
||||||
)),
|
)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "nym-socks5-client"
|
name = "nym-socks5-client"
|
||||||
version = "1.1.5"
|
version = "1.1.8"
|
||||||
authors = ["Dave Hrycyszyn <futurechimp@users.noreply.github.com>"]
|
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"
|
description = "A SOCKS5 localhost proxy that converts incoming messages to Sphinx and sends them to a Nym address"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
@@ -15,7 +15,7 @@ clap = { version = "4.0", features = ["cargo", "derive"] }
|
|||||||
dirs = "4.0"
|
dirs = "4.0"
|
||||||
futures = "0.3"
|
futures = "0.3"
|
||||||
lazy_static = "1.4.0"
|
lazy_static = "1.4.0"
|
||||||
log = "0.4"
|
log = { workspace = true }
|
||||||
pin-project = "1.0"
|
pin-project = "1.0"
|
||||||
pretty_env_logger = "0.4"
|
pretty_env_logger = "0.4"
|
||||||
rand = { version = "0.7.3", features = ["wasm-bindgen"] }
|
rand = { version = "0.7.3", features = ["wasm-bindgen"] }
|
||||||
@@ -23,7 +23,7 @@ serde = { version = "1.0", features = ["derive"] } # for config serialization/de
|
|||||||
serde_json = "1.0.89"
|
serde_json = "1.0.89"
|
||||||
tap = "1.0.1"
|
tap = "1.0.1"
|
||||||
thiserror = "1.0.34"
|
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"
|
url = "2.2"
|
||||||
|
|
||||||
# internal
|
# internal
|
||||||
|
|||||||
@@ -19,7 +19,8 @@ use gateway_client::bandwidth::BandwidthController;
|
|||||||
use log::*;
|
use log::*;
|
||||||
use nymsphinx::addressing::clients::Recipient;
|
use nymsphinx::addressing::clients::Recipient;
|
||||||
use std::error::Error;
|
use std::error::Error;
|
||||||
use task::{wait_for_signal_and_error, TaskClient, TaskManager};
|
use task::{TaskClient, TaskManager};
|
||||||
|
use validator_client::nyxd::QueryNyxdClient;
|
||||||
|
|
||||||
pub mod config;
|
pub mod config;
|
||||||
|
|
||||||
@@ -53,42 +54,28 @@ impl NymClient {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn create_bandwidth_controller(config: &Config) -> BandwidthController {
|
async fn create_bandwidth_controller(config: &Config) -> BandwidthController<QueryNyxdClient> {
|
||||||
#[cfg(feature = "coconut")]
|
let details = network_defaults::NymNetworkDetails::new_from_env();
|
||||||
let bandwidth_controller = {
|
let mut client_config = validator_client::Config::try_from_nym_network_details(&details)
|
||||||
let details = network_defaults::NymNetworkDetails::new_from_env();
|
.expect("failed to construct validator client config");
|
||||||
let mut client_config =
|
let nyxd_url = config
|
||||||
validator_client::Config::try_from_nym_network_details(&details)
|
.get_base()
|
||||||
.expect("failed to construct validator client config");
|
.get_validator_endpoints()
|
||||||
let nyxd_url = config
|
.pop()
|
||||||
.get_base()
|
.expect("No nyxd validator endpoint provided");
|
||||||
.get_validator_endpoints()
|
let api_url = config
|
||||||
.pop()
|
.get_base()
|
||||||
.expect("No nyxd validator endpoint provided");
|
.get_nym_api_endpoints()
|
||||||
let api_url = config
|
.pop()
|
||||||
.get_base()
|
.expect("No validator api endpoint provided");
|
||||||
.get_nym_api_endpoints()
|
// overwrite env configuration with config URLs
|
||||||
.pop()
|
client_config = client_config.with_urls(nyxd_url, api_url);
|
||||||
.expect("No validator api endpoint provided");
|
let client = validator_client::Client::new_query(client_config)
|
||||||
// overwrite env configuration with config URLs
|
.expect("Could not construct query client");
|
||||||
client_config = client_config.with_urls(nyxd_url, api_url);
|
BandwidthController::new(
|
||||||
let client = validator_client::Client::new_query(client_config)
|
|
||||||
.expect("Could not construct query client");
|
|
||||||
let coconut_api_clients =
|
|
||||||
validator_client::CoconutApiClient::all_coconut_api_clients(&client)
|
|
||||||
.await
|
|
||||||
.expect("Could not query api clients");
|
|
||||||
BandwidthController::new(
|
|
||||||
credential_storage::initialise_storage(config.get_base().get_database_path()).await,
|
|
||||||
coconut_api_clients,
|
|
||||||
)
|
|
||||||
};
|
|
||||||
#[cfg(not(feature = "coconut"))]
|
|
||||||
let bandwidth_controller = BandwidthController::new(
|
|
||||||
credential_storage::initialise_storage(config.get_base().get_database_path()).await,
|
credential_storage::initialise_storage(config.get_base().get_database_path()).await,
|
||||||
|
client,
|
||||||
)
|
)
|
||||||
.expect("Could not create bandwidth controller");
|
|
||||||
bandwidth_controller
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn start_socks5_listener(
|
fn start_socks5_listener(
|
||||||
@@ -147,16 +134,9 @@ impl NymClient {
|
|||||||
|
|
||||||
/// blocking version of `start` method. Will run forever (or until SIGINT is sent)
|
/// 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>> {
|
pub async fn run_forever(self) -> Result<(), Box<dyn Error + Send + Sync>> {
|
||||||
let mut shutdown = self.start().await?;
|
let 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 res = shutdown.catch_interrupt().await;
|
||||||
log::info!("Stopping nym-socks5-client");
|
log::info!("Stopping nym-socks5-client");
|
||||||
res
|
res
|
||||||
}
|
}
|
||||||
@@ -213,7 +193,7 @@ impl NymClient {
|
|||||||
self.key_manager,
|
self.key_manager,
|
||||||
Some(Self::create_bandwidth_controller(&self.config).await),
|
Some(Self::create_bandwidth_controller(&self.config).await),
|
||||||
non_wasm_helpers::setup_fs_reply_surb_backend(
|
non_wasm_helpers::setup_fs_reply_surb_backend(
|
||||||
self.config.get_base().get_reply_surb_database_path(),
|
Some(self.config.get_base().get_reply_surb_database_path()),
|
||||||
self.config.get_debug_settings(),
|
self.config.get_debug_settings(),
|
||||||
)
|
)
|
||||||
.await?,
|
.await?,
|
||||||
|
|||||||
@@ -122,18 +122,17 @@ pub(crate) async fn execute(args: &Init) -> Result<(), Socks5ClientError> {
|
|||||||
let id = &args.id;
|
let id = &args.id;
|
||||||
let provider_address = &args.provider;
|
let provider_address = &args.provider;
|
||||||
|
|
||||||
let already_init = Config::default_config_file_path(Some(id)).exists();
|
let already_init = Config::default_config_file_path(id).exists();
|
||||||
if already_init {
|
if already_init {
|
||||||
println!(
|
println!("SOCKS5 client \"{id}\" was already initialised before");
|
||||||
"SOCKS5 client \"{}\" was already initialised before! \
|
|
||||||
Config information will be overwritten (but keys will be kept)!",
|
|
||||||
id
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Usually you only register with the gateway on the first init, however you can force
|
// Usually you only register with the gateway on the first init, however you can force
|
||||||
// re-registering if wanted.
|
// re-registering if wanted.
|
||||||
let user_wants_force_register = args.force_register_gateway;
|
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
|
// 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).
|
// 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
|
// 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.
|
// 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,
|
register_gateway,
|
||||||
user_chosen_gateway_id.map(|id| id.to_base58_string()),
|
user_chosen_gateway_id,
|
||||||
config.get_base(),
|
config.get_base(),
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
|
|||||||
@@ -113,7 +113,7 @@ fn version_check(cfg: &Config) -> bool {
|
|||||||
pub(crate) async fn execute(args: &Run) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
pub(crate) async fn execute(args: &Run) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||||
let id = &args.id;
|
let id = &args.id;
|
||||||
|
|
||||||
let mut config = match Config::load_from_file(Some(id)) {
|
let mut config = match Config::load_from_file(id) {
|
||||||
Ok(cfg) => cfg,
|
Ok(cfg) => cfg,
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
error!("Failed to load config for {}. Are you sure you have run `init` before? (Error was: {err})", id);
|
error!("Failed to load config for {}. Are you sure you have run `init` before? (Error was: {err})", id);
|
||||||
|
|||||||
@@ -144,7 +144,7 @@ pub(crate) fn execute(args: &Upgrade) {
|
|||||||
|
|
||||||
let id = &args.id;
|
let id = &args.id;
|
||||||
|
|
||||||
let existing_config = Config::load_from_file(Some(id)).unwrap_or_else(|err| {
|
let existing_config = Config::load_from_file(id).unwrap_or_else(|err| {
|
||||||
eprintln!("failed to load existing config file! - {err}");
|
eprintln!("failed to load existing config file! - {err}");
|
||||||
process::exit(1)
|
process::exit(1)
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
|
|
||||||
use std::error::Error;
|
use std::error::Error;
|
||||||
|
|
||||||
use clap::{crate_version, Parser};
|
use clap::{crate_name, crate_version, Parser};
|
||||||
use logging::setup_logging;
|
use logging::setup_logging;
|
||||||
use network_defaults::setup_env;
|
use network_defaults::setup_env;
|
||||||
|
|
||||||
@@ -15,26 +15,9 @@ pub mod socks;
|
|||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
async fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
|
async fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
|
||||||
setup_logging();
|
setup_logging();
|
||||||
println!("{}", banner());
|
println!("{}", logging::banner(crate_name!(), crate_version!()));
|
||||||
|
|
||||||
let args = commands::Cli::parse();
|
let args = commands::Cli::parse();
|
||||||
setup_env(args.config_env_file.as_ref());
|
setup_env(args.config_env_file.as_ref());
|
||||||
commands::execute(&args).await
|
commands::execute(&args).await
|
||||||
}
|
}
|
||||||
|
|
||||||
fn banner() -> String {
|
|
||||||
format!(
|
|
||||||
r#"
|
|
||||||
|
|
||||||
_ __ _ _ _ __ ___
|
|
||||||
| '_ \| | | | '_ \ _ \
|
|
||||||
| | | | |_| | | | | | |
|
|
||||||
|_| |_|\__, |_| |_| |_|
|
|
||||||
|___/
|
|
||||||
|
|
||||||
(socks5 proxy - version {:})
|
|
||||||
|
|
||||||
"#,
|
|
||||||
crate_version!()
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -22,8 +22,10 @@ futures = "0.3"
|
|||||||
js-sys = "0.3"
|
js-sys = "0.3"
|
||||||
rand = { version = "0.7.3", features = ["wasm-bindgen"] }
|
rand = { version = "0.7.3", features = ["wasm-bindgen"] }
|
||||||
serde = { version = "1.0", features = ["derive"] }
|
serde = { version = "1.0", features = ["derive"] }
|
||||||
|
serde_json = "1.0"
|
||||||
|
anyhow = "1.0"
|
||||||
serde-wasm-bindgen = "0.4"
|
serde-wasm-bindgen = "0.4"
|
||||||
tokio = { version = "1.21.2", features = ["sync"] }
|
tokio = { version = "1.24.1", features = ["sync"] }
|
||||||
url = "2.2"
|
url = "2.2"
|
||||||
wasm-bindgen = { version = "=0.2.83", features = ["serde-serialize"] }
|
wasm-bindgen = { version = "=0.2.83", features = ["serde-serialize"] }
|
||||||
wasm-bindgen-futures = "0.4"
|
wasm-bindgen-futures = "0.4"
|
||||||
|
|||||||
@@ -16,11 +16,7 @@ They should be implemented soon. You can build your applications, but don't rely
|
|||||||
|
|
||||||
## Using it
|
## Using it
|
||||||
|
|
||||||
See the [Nym docs](https://nymtech.net/docs).
|
See the [SDK directory](../../sdk/typescript/examples) for examples on how to use it and the NPM packages available.
|
||||||
|
|
||||||
### Demo
|
|
||||||
|
|
||||||
There's a demo web application in the `js-example` folder. To run it, first make sure you've got a recent `npm` installed, then follow the instructions in its README.
|
|
||||||
|
|
||||||
## Developing
|
## Developing
|
||||||
|
|
||||||
@@ -36,8 +32,13 @@ To be clear, this is not something that most JS developers need to worry about,
|
|||||||
|
|
||||||
### Packaging
|
### Packaging
|
||||||
|
|
||||||
If you're a Nym platform developer who's made changes to the Rust (or JS) files and wants to re-publish the package to NPM, here's how you do it:
|
If you're a Nym platform developer who's made changes to the Rust files and wants to re-publish the package to NPM, here's how you do it:
|
||||||
|
|
||||||
1. bump version numbers as necessary for SemVer
|
1. bump version numbers as necessary for SemVer
|
||||||
2. `wasm-pack build --scope nymproject` builds the wasm binaries into the `pkg` directory (not in source control)
|
2. go the `sdk/typescript` directory (off the project root)
|
||||||
3. `cd pkg && npm publish --access=public` will publish your changed package to NPM
|
3. run:
|
||||||
|
```
|
||||||
|
yarn
|
||||||
|
yarn build
|
||||||
|
yarn publish
|
||||||
|
```
|
||||||
@@ -1,217 +0,0 @@
|
|||||||
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
|
|
||||||
// SPDX-License-Identifier: Apache-2.0
|
|
||||||
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
use wasm_bindgen::prelude::*;
|
|
||||||
use wasm_bindgen::JsCast;
|
|
||||||
|
|
||||||
#[wasm_bindgen(typescript_custom_section)]
|
|
||||||
const TS_DEFS: &'static str = r#"
|
|
||||||
export interface BinaryMessage {
|
|
||||||
kind: number,
|
|
||||||
payload: Uint8Array;
|
|
||||||
headers: string,
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface StringMessage {
|
|
||||||
kind: number,
|
|
||||||
payload: string;
|
|
||||||
}
|
|
||||||
"#;
|
|
||||||
|
|
||||||
#[wasm_bindgen]
|
|
||||||
extern "C" {
|
|
||||||
#[wasm_bindgen(typescript_type = "BinaryMessage")]
|
|
||||||
pub type IBinaryMessage;
|
|
||||||
#[wasm_bindgen(typescript_type = "StringMessage")]
|
|
||||||
pub type IStringMessage;
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize)]
|
|
||||||
pub struct BinaryMessage {
|
|
||||||
pub kind: u8,
|
|
||||||
pub payload: Vec<u8>,
|
|
||||||
pub headers: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize)]
|
|
||||||
pub struct StringMessage {
|
|
||||||
pub kind: u8,
|
|
||||||
pub payload: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Create a new binary message with a user-specified `kind`.
|
|
||||||
#[wasm_bindgen]
|
|
||||||
pub fn create_binary_message(kind: u8, payload: Vec<u8>) -> Vec<u8> {
|
|
||||||
create_binary_message_with_headers(kind, payload, "".to_string())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Create a new message with a UTF-8 encoded string `payload` and a user-specified `kind`.
|
|
||||||
#[wasm_bindgen]
|
|
||||||
pub fn create_binary_message_from_string(kind: u8, payload: String) -> Vec<u8> {
|
|
||||||
create_binary_message_with_headers(kind, payload.as_bytes().to_vec(), "".to_string())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Create a new binary message with a user-specified `kind`, and `headers` as a string.
|
|
||||||
#[wasm_bindgen]
|
|
||||||
pub fn create_binary_message_with_headers(kind: u8, payload: Vec<u8>, headers: String) -> Vec<u8> {
|
|
||||||
let headers = headers.as_bytes().to_vec();
|
|
||||||
let size = (headers.len() as u64).to_be_bytes().to_vec();
|
|
||||||
vec![vec![kind], size, headers, payload].concat()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Parse the `kind` and byte array `payload` from a byte array
|
|
||||||
#[wasm_bindgen]
|
|
||||||
pub async fn parse_binary_message(message: Vec<u8>) -> Result<IBinaryMessage, JsError> {
|
|
||||||
if message.len() < 2 {
|
|
||||||
return Err(JsError::new(
|
|
||||||
"Could not parse message, as less than 2 bytes long",
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
let (kind, _headers, payload) = parse_binary_payload(&message);
|
|
||||||
|
|
||||||
Ok(serde_wasm_bindgen::to_value(&BinaryMessage {
|
|
||||||
kind,
|
|
||||||
payload: payload.to_vec(),
|
|
||||||
headers: "".to_string(),
|
|
||||||
})
|
|
||||||
.unwrap()
|
|
||||||
.unchecked_into::<IBinaryMessage>())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Parse the `kind` and byte array `payload` from a byte array with headers
|
|
||||||
#[wasm_bindgen]
|
|
||||||
pub async fn parse_binary_message_with_headers(
|
|
||||||
message: Vec<u8>,
|
|
||||||
) -> Result<IBinaryMessage, JsError> {
|
|
||||||
if message.len() < 2 {
|
|
||||||
return Err(JsError::new(
|
|
||||||
"Could not parse message, as less than 2 bytes long",
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
let (kind, headers, payload) = parse_binary_payload(&message);
|
|
||||||
|
|
||||||
Ok(serde_wasm_bindgen::to_value(&BinaryMessage {
|
|
||||||
kind,
|
|
||||||
payload: payload.to_vec(),
|
|
||||||
headers,
|
|
||||||
})
|
|
||||||
.unwrap()
|
|
||||||
.unchecked_into::<IBinaryMessage>())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Parse the `kind` and UTF-8 string `payload` from a byte array with headers
|
|
||||||
#[wasm_bindgen]
|
|
||||||
pub async fn parse_string_message_with_headers(
|
|
||||||
message: Vec<u8>,
|
|
||||||
) -> Result<IStringMessage, JsError> {
|
|
||||||
if message.len() < 2 {
|
|
||||||
return Err(JsError::new(
|
|
||||||
"Could not parse message, as less than 2 bytes long",
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
let (kind, _headers, payload) = parse_binary_payload(&message);
|
|
||||||
let payload = String::from_utf8_lossy(payload).into_owned();
|
|
||||||
|
|
||||||
Ok(
|
|
||||||
serde_wasm_bindgen::to_value(&StringMessage { kind, payload })
|
|
||||||
.unwrap()
|
|
||||||
.unchecked_into::<IStringMessage>(),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
pub(crate) fn parse_binary_payload(message: &[u8]) -> (u8, String, &[u8]) {
|
|
||||||
// 1st byte is the kind
|
|
||||||
let kind = message[0];
|
|
||||||
|
|
||||||
// then the size as u64 big endian
|
|
||||||
let mut size = [0u8; 8];
|
|
||||||
size.clone_from_slice(&message[1..9]);
|
|
||||||
let size = u64::from_be_bytes(size) as usize;
|
|
||||||
|
|
||||||
// then the headers
|
|
||||||
let headers = String::from_utf8_lossy(&message[9..9 + size]).into_owned();
|
|
||||||
|
|
||||||
// finally the payload
|
|
||||||
let payload = &message[9 + size..];
|
|
||||||
|
|
||||||
(kind, headers, payload)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Parse the `kind` and UTF-8 string `payload` from a byte array
|
|
||||||
#[wasm_bindgen]
|
|
||||||
pub async fn parse_string_message(message: Vec<u8>) -> Result<IStringMessage, JsError> {
|
|
||||||
if message.len() < 2 {
|
|
||||||
return Err(JsError::new(
|
|
||||||
"Could not parse message, as less than 2 bytes long",
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
let kind = message[0];
|
|
||||||
let payload = String::from_utf8_lossy(&message[1..]).into_owned();
|
|
||||||
|
|
||||||
Ok(
|
|
||||||
serde_wasm_bindgen::to_value(&StringMessage { kind, payload })
|
|
||||||
.unwrap()
|
|
||||||
.unchecked_into::<IStringMessage>(),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::{create_binary_message_with_headers, parse_binary_payload};
|
|
||||||
use wasm_bindgen_test::*;
|
|
||||||
|
|
||||||
#[wasm_bindgen_test]
|
|
||||||
fn test_binary_with_headers() {
|
|
||||||
let message_as_bytes = create_binary_message_with_headers(
|
|
||||||
42u8,
|
|
||||||
vec![0u8, 1u8, 2u8],
|
|
||||||
"test headers".to_string(),
|
|
||||||
);
|
|
||||||
|
|
||||||
// calculate header size
|
|
||||||
let headers = "test headers".as_bytes().to_vec();
|
|
||||||
let size = headers.len();
|
|
||||||
|
|
||||||
// the expected size
|
|
||||||
let expected_size = 12;
|
|
||||||
assert_eq!(size, expected_size);
|
|
||||||
|
|
||||||
assert_eq!(message_as_bytes[0], 42u8);
|
|
||||||
assert_eq!(message_as_bytes[1..9], 12u64.to_be_bytes());
|
|
||||||
assert_eq!(
|
|
||||||
message_as_bytes[9 + expected_size..9 + expected_size + 3],
|
|
||||||
vec![0u8, 1u8, 2u8]
|
|
||||||
);
|
|
||||||
|
|
||||||
let res = parse_binary_payload(&message_as_bytes);
|
|
||||||
|
|
||||||
assert_eq!(res.0, 42u8);
|
|
||||||
assert_eq!(res.1, "test headers".to_string());
|
|
||||||
assert_eq!(res.2, vec![0u8, 1u8, 2u8]);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[wasm_bindgen_test]
|
|
||||||
fn test_binary_with_empty_headers() {
|
|
||||||
let message_as_bytes =
|
|
||||||
create_binary_message_with_headers(42u8, vec![0u8, 1u8, 2u8], "".to_string());
|
|
||||||
|
|
||||||
let expected_size = 0;
|
|
||||||
|
|
||||||
assert_eq!(message_as_bytes[0], 42u8);
|
|
||||||
assert_eq!(message_as_bytes[1..9], 0u64.to_be_bytes());
|
|
||||||
assert_eq!(
|
|
||||||
message_as_bytes[9 + expected_size..9 + expected_size + 3],
|
|
||||||
vec![0u8, 1u8, 2u8]
|
|
||||||
);
|
|
||||||
|
|
||||||
let res = parse_binary_payload(&message_as_bytes);
|
|
||||||
|
|
||||||
assert_eq!(res.0, 42u8);
|
|
||||||
assert_eq!(res.1, "".to_string());
|
|
||||||
assert_eq!(res.2, vec![0u8, 1u8, 2u8]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -11,6 +11,7 @@ use client_core::client::base_client::{
|
|||||||
use client_core::client::replies::reply_storage::browser_backend;
|
use client_core::client::replies::reply_storage::browser_backend;
|
||||||
use client_core::client::{inbound_messages::InputMessage, key_manager::KeyManager};
|
use client_core::client::{inbound_messages::InputMessage, key_manager::KeyManager};
|
||||||
use gateway_client::bandwidth::BandwidthController;
|
use gateway_client::bandwidth::BandwidthController;
|
||||||
|
use gateway_client::wasm_mockups::SigningNyxdClient;
|
||||||
use js_sys::Promise;
|
use js_sys::Promise;
|
||||||
use nymsphinx::addressing::clients::Recipient;
|
use nymsphinx::addressing::clients::Recipient;
|
||||||
use nymsphinx::anonymous_replies::requests::AnonymousSenderTag;
|
use nymsphinx::anonymous_replies::requests::AnonymousSenderTag;
|
||||||
@@ -47,7 +48,7 @@ pub struct NymClientBuilder {
|
|||||||
on_message: js_sys::Function,
|
on_message: js_sys::Function,
|
||||||
|
|
||||||
// unimplemented:
|
// unimplemented:
|
||||||
bandwidth_controller: Option<BandwidthController>,
|
bandwidth_controller: Option<BandwidthController<SigningNyxdClient>>,
|
||||||
disabled_credentials: bool,
|
disabled_credentials: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,238 @@
|
|||||||
|
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
|
||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use wasm_bindgen::prelude::*;
|
||||||
|
use wasm_bindgen::JsCast;
|
||||||
|
|
||||||
|
#[wasm_bindgen(typescript_custom_section)]
|
||||||
|
const TS_DEFS: &'static str = r#"
|
||||||
|
export interface EncodedPayload {
|
||||||
|
mimeType: string,
|
||||||
|
payload: Uint8Array;
|
||||||
|
headers: string,
|
||||||
|
}
|
||||||
|
"#;
|
||||||
|
|
||||||
|
#[wasm_bindgen]
|
||||||
|
extern "C" {
|
||||||
|
#[wasm_bindgen(typescript_type = "EncodedPayload")]
|
||||||
|
pub type IEncodedPayload;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct EncodedPayload {
|
||||||
|
pub mime_type: String,
|
||||||
|
pub payload: Vec<u8>,
|
||||||
|
pub headers: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct EncodedPayloadMetadata {
|
||||||
|
pub mime_type: String,
|
||||||
|
pub headers: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Encode a payload
|
||||||
|
#[wasm_bindgen]
|
||||||
|
pub fn encode_payload(mime_type: String, payload: Vec<u8>) -> Result<Vec<u8>, JsValue> {
|
||||||
|
encode_payload_with_headers(mime_type, payload, None)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Create a new binary message with a user-specified `kind`, and `headers` as a string.
|
||||||
|
#[wasm_bindgen]
|
||||||
|
pub fn encode_payload_with_headers(
|
||||||
|
mime_type: String,
|
||||||
|
payload: Vec<u8>,
|
||||||
|
headers: Option<String>,
|
||||||
|
) -> Result<Vec<u8>, JsValue> {
|
||||||
|
match serde_json::to_string(&EncodedPayloadMetadata { mime_type, headers }) {
|
||||||
|
Ok(metadata) => {
|
||||||
|
let metadata = metadata.as_bytes().to_vec();
|
||||||
|
let size = (metadata.len() as u64).to_be_bytes().to_vec();
|
||||||
|
Ok(vec![size, metadata, payload].concat())
|
||||||
|
}
|
||||||
|
Err(e) => Err(JsValue::from(JsError::new(
|
||||||
|
format!("Could not encode message: {}", e).as_str(),
|
||||||
|
))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parse the `kind` and byte array `payload` from a byte array
|
||||||
|
#[wasm_bindgen]
|
||||||
|
pub fn decode_payload(message: Vec<u8>) -> Result<IEncodedPayload, JsValue> {
|
||||||
|
if message.len() < 8 {
|
||||||
|
return Err(JsValue::from(JsError::new(
|
||||||
|
"Could not parse message, as less than 8 bytes long",
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
|
||||||
|
match parse_payload(&message) {
|
||||||
|
Ok((metadata, payload)) => Ok(serde_wasm_bindgen::to_value(&EncodedPayload {
|
||||||
|
mime_type: metadata.mime_type,
|
||||||
|
payload: payload.to_vec(),
|
||||||
|
headers: metadata.headers,
|
||||||
|
})
|
||||||
|
.unwrap()
|
||||||
|
.unchecked_into::<IEncodedPayload>()),
|
||||||
|
Err(e) => Err(JsValue::from(JsError::new(
|
||||||
|
format!("Could not parse message: {}", e).as_str(),
|
||||||
|
))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn parse_payload(message: &[u8]) -> anyhow::Result<(EncodedPayloadMetadata, &[u8])> {
|
||||||
|
// 1st 8 bytes are the size (as u64 big endian)
|
||||||
|
let mut size = [0u8; 8];
|
||||||
|
size.clone_from_slice(&message[0..8]);
|
||||||
|
let size = u64::from_be_bytes(size) as usize;
|
||||||
|
|
||||||
|
// then the metadata
|
||||||
|
let metadata = String::from_utf8_lossy(&message[8..8 + size]).into_owned();
|
||||||
|
let metadata: EncodedPayloadMetadata = serde_json::from_str(metadata.as_str())?;
|
||||||
|
|
||||||
|
// finally the payload
|
||||||
|
let payload = &message[8 + size..];
|
||||||
|
|
||||||
|
Ok((metadata, payload))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Try parse a UTF-8 string from an array of bytes
|
||||||
|
#[wasm_bindgen]
|
||||||
|
pub fn parse_utf8_string(payload: Vec<u8>) -> String {
|
||||||
|
String::from_utf8_lossy(&payload).into_owned()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Converts a UTF-8 string into an array of bytes
|
||||||
|
///
|
||||||
|
/// This method is provided as a replacement for the mess of `atob`
|
||||||
|
/// (https://developer.mozilla.org/en-US/docs/Web/API/atob) helpers provided by browsers and NodeJS.
|
||||||
|
///
|
||||||
|
/// Feel free to use `atob` if you know you won't have problems with polyfills or encoding issues.
|
||||||
|
#[wasm_bindgen]
|
||||||
|
pub fn utf8_string_to_byte_array(message: String) -> Vec<u8> {
|
||||||
|
message.into_bytes()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use wasm_bindgen_test::*;
|
||||||
|
|
||||||
|
#[wasm_bindgen_test]
|
||||||
|
async fn test_encode_payload_with_headers() {
|
||||||
|
let message_as_bytes = encode_payload_with_headers(
|
||||||
|
"text/plain".to_string(),
|
||||||
|
vec![0u8, 1u8, 2u8],
|
||||||
|
Some("test headers".to_string()),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
// the expected message size
|
||||||
|
let size = message_as_bytes.len();
|
||||||
|
let expected_size = 61;
|
||||||
|
assert_eq!(size, expected_size);
|
||||||
|
|
||||||
|
let expected_header_size = 50usize;
|
||||||
|
assert_eq!(
|
||||||
|
message_as_bytes[0..8],
|
||||||
|
(expected_header_size as u64).to_be_bytes()
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
message_as_bytes[8 + expected_header_size..8 + expected_header_size + 3],
|
||||||
|
vec![0u8, 1u8, 2u8]
|
||||||
|
);
|
||||||
|
|
||||||
|
let res = parse_payload(&message_as_bytes).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(res.0.mime_type, "text/plain");
|
||||||
|
assert_eq!(res.0.headers.unwrap(), "test headers".to_string());
|
||||||
|
assert_eq!(res.1, vec![0u8, 1u8, 2u8]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[wasm_bindgen_test]
|
||||||
|
async fn test_encode_payload_with_empty_headers() {
|
||||||
|
let message_as_bytes =
|
||||||
|
encode_payload_with_headers("text/plain".to_string(), vec![0u8, 1u8, 2u8], None)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
// the expected message size
|
||||||
|
let size = message_as_bytes.len();
|
||||||
|
let expected_size = 51;
|
||||||
|
assert_eq!(size, expected_size);
|
||||||
|
|
||||||
|
let expected_header_size = 40usize;
|
||||||
|
assert_eq!(
|
||||||
|
message_as_bytes[0..8],
|
||||||
|
(expected_header_size as u64).to_be_bytes()
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
message_as_bytes[8 + expected_header_size..8 + expected_header_size + 3],
|
||||||
|
vec![0u8, 1u8, 2u8]
|
||||||
|
);
|
||||||
|
let res = parse_payload(&message_as_bytes).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(res.0.mime_type, "text/plain");
|
||||||
|
assert_eq!(res.0.headers, None);
|
||||||
|
assert_eq!(res.1, vec![0u8, 1u8, 2u8]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[wasm_bindgen_test]
|
||||||
|
async fn test_encode_payload_with_empty_headers_and_empty_mime_type() {
|
||||||
|
let message_as_bytes =
|
||||||
|
encode_payload_with_headers("".to_string(), vec![0u8, 1u8, 2u8], None).unwrap();
|
||||||
|
|
||||||
|
// the expected message size
|
||||||
|
let size = message_as_bytes.len();
|
||||||
|
let expected_size = 41;
|
||||||
|
assert_eq!(size, expected_size);
|
||||||
|
|
||||||
|
let expected_header_size = 30usize;
|
||||||
|
assert_eq!(
|
||||||
|
message_as_bytes[0..8],
|
||||||
|
(expected_header_size as u64).to_be_bytes()
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
message_as_bytes[8 + expected_header_size..8 + expected_header_size + 3],
|
||||||
|
vec![0u8, 1u8, 2u8]
|
||||||
|
);
|
||||||
|
let res = parse_payload(&message_as_bytes).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(res.0.mime_type, "");
|
||||||
|
assert_eq!(res.0.headers, None);
|
||||||
|
assert_eq!(res.1, vec![0u8, 1u8, 2u8]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[wasm_bindgen_test]
|
||||||
|
async fn test_encode_payload_with_all_empty() {
|
||||||
|
let empty: Vec<u8> = vec![];
|
||||||
|
let message_as_bytes =
|
||||||
|
encode_payload_with_headers("".to_string(), empty.clone(), None).unwrap();
|
||||||
|
|
||||||
|
// the expected message size
|
||||||
|
let size = message_as_bytes.len();
|
||||||
|
let expected_size = 38;
|
||||||
|
assert_eq!(size, expected_size);
|
||||||
|
|
||||||
|
let expected_header_size = 30usize;
|
||||||
|
assert_eq!(
|
||||||
|
message_as_bytes[0..8],
|
||||||
|
(expected_header_size as u64).to_be_bytes()
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
message_as_bytes[8 + expected_header_size..8 + expected_header_size],
|
||||||
|
empty
|
||||||
|
);
|
||||||
|
let res = parse_payload(&message_as_bytes).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(res.0.mime_type, "");
|
||||||
|
assert_eq!(res.0.headers, None);
|
||||||
|
assert_eq!(res.1, empty);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,12 +3,14 @@
|
|||||||
|
|
||||||
use wasm_bindgen::prelude::*;
|
use wasm_bindgen::prelude::*;
|
||||||
|
|
||||||
#[cfg(target_arch = "wasm32")]
|
|
||||||
pub mod binary_message_helper;
|
|
||||||
#[cfg(target_arch = "wasm32")]
|
#[cfg(target_arch = "wasm32")]
|
||||||
mod client;
|
mod client;
|
||||||
#[cfg(target_arch = "wasm32")]
|
#[cfg(target_arch = "wasm32")]
|
||||||
|
pub mod encoded_payload_helper;
|
||||||
|
#[cfg(target_arch = "wasm32")]
|
||||||
pub mod gateway_selector;
|
pub mod gateway_selector;
|
||||||
|
#[cfg(target_arch = "wasm32")]
|
||||||
|
pub mod validation;
|
||||||
|
|
||||||
#[wasm_bindgen]
|
#[wasm_bindgen]
|
||||||
pub fn set_panic_hook() {
|
pub fn set_panic_hook() {
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
use nymsphinx::addressing::clients::Recipient;
|
||||||
|
use wasm_bindgen::prelude::*;
|
||||||
|
|
||||||
|
#[wasm_bindgen]
|
||||||
|
pub fn validate_recipient(recipient: String) -> Result<(), JsError> {
|
||||||
|
match Recipient::try_from_base58_string(recipient) {
|
||||||
|
Ok(_) => Ok(()),
|
||||||
|
Err(e) => Err(JsError::new(format!("{}", e).as_str())),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::validate_recipient;
|
||||||
|
use wasm_bindgen_test::*;
|
||||||
|
|
||||||
|
#[wasm_bindgen_test]
|
||||||
|
fn test_recipient_validation_ok() {
|
||||||
|
let res = validate_recipient("DyQmXnst5NGGjzUZxRC5Bjs5bd7CBF3xMpsSmbRiizr2.GH6YTBP2NXU3AVqd8WjiTMVyeMjunXMEsp7gVCMEJqpD@336yuXAeGEgedRfqTJZsG2YV7P13QH1bHv1SjCZYarc9".to_string());
|
||||||
|
assert!(res.is_ok())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[wasm_bindgen_test]
|
||||||
|
fn test_recipient_validation_fails() {
|
||||||
|
assert!(validate_recipient(" DyQmXnst5NGGjzUZxRC5Bjs5bd7CBF3xMpsSmbRiizr2.GH6YTBP2NXU3AVqd8WjiTMVyeMjunXMEsp7gVCMEJqpD@336yuXAeGEgedRfqTJZsG2YV7P13QH1bHv1SjCZYarc9".to_string()).is_err());
|
||||||
|
assert!(validate_recipient(
|
||||||
|
"DyQmXnst5NGGjzUZxRC5BjbRiizr2.GH6YTBP2NXU3AVqd8WD@336yuXAeGEgedRfqTJZQH1bHv1SjCZYarc9"
|
||||||
|
.to_string()
|
||||||
|
)
|
||||||
|
.is_err());
|
||||||
|
assert!(validate_recipient("🙀🙀🙀🙀".to_string()).is_err());
|
||||||
|
assert!(validate_recipient("".to_string()).is_err());
|
||||||
|
assert!(validate_recipient(" ".to_string()).is_err());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,4 +7,4 @@ edition = "2021"
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
futures = "0.3"
|
futures = "0.3"
|
||||||
log = "0.4.17"
|
log = { workspace = true }
|
||||||
|
|||||||
@@ -10,12 +10,12 @@ edition = "2021"
|
|||||||
# TODO: (for this and other crates), similarly to 'tokio', import only required "futures" modules rather than
|
# TODO: (for this and other crates), similarly to 'tokio', import only required "futures" modules rather than
|
||||||
# the entire crate
|
# the entire crate
|
||||||
futures = "0.3"
|
futures = "0.3"
|
||||||
log = "0.4"
|
log = { workspace = true }
|
||||||
thiserror = "1.0"
|
thiserror = "1.0"
|
||||||
url = "2.2"
|
url = "2.2"
|
||||||
rand = { version = "0.7.3", features = ["wasm-bindgen"] }
|
rand = { version = "0.7.3", features = ["wasm-bindgen"] }
|
||||||
async-trait = { version = "0.1.51" }
|
async-trait = { version = "0.1.51" }
|
||||||
tokio = { version = "1.21.2", features = ["macros"] }
|
tokio = { version = "1.24.1", features = ["macros"] }
|
||||||
|
|
||||||
# internal
|
# internal
|
||||||
coconut-interface = { path = "../../coconut-interface", optional = true }
|
coconut-interface = { path = "../../coconut-interface", optional = true }
|
||||||
@@ -25,7 +25,7 @@ gateway-requests = { path = "../../../gateway/gateway-requests" }
|
|||||||
network-defaults = { path = "../../network-defaults" }
|
network-defaults = { path = "../../network-defaults" }
|
||||||
nymsphinx = { path = "../../nymsphinx" }
|
nymsphinx = { path = "../../nymsphinx" }
|
||||||
pemstore = { path = "../../pemstore" }
|
pemstore = { path = "../../pemstore" }
|
||||||
validator-client = { path = "../validator-client", optional = true }
|
validator-client = { path = "../validator-client" }
|
||||||
task = { path = "../../task" }
|
task = { path = "../../task" }
|
||||||
serde = { version = "1.0", features = ["derive"]}
|
serde = { version = "1.0", features = ["derive"]}
|
||||||
|
|
||||||
@@ -36,11 +36,11 @@ default-features = false
|
|||||||
|
|
||||||
# non-wasm-only dependencies
|
# non-wasm-only dependencies
|
||||||
[target."cfg(not(target_arch = \"wasm32\"))".dependencies.tokio]
|
[target."cfg(not(target_arch = \"wasm32\"))".dependencies.tokio]
|
||||||
version = "1.21.2"
|
version = "1.24.1"
|
||||||
features = ["macros", "rt", "net", "sync", "time"]
|
features = ["macros", "rt", "net", "sync", "time"]
|
||||||
|
|
||||||
[target."cfg(not(target_arch = \"wasm32\"))".dependencies.tokio-stream]
|
[target."cfg(not(target_arch = \"wasm32\"))".dependencies.tokio-stream]
|
||||||
version = "0.1.9"
|
version = "0.1.11"
|
||||||
features = ["net", "sync", "time"]
|
features = ["net", "sync", "time"]
|
||||||
|
|
||||||
[target."cfg(not(target_arch = \"wasm32\"))".dependencies.tokio-tungstenite]
|
[target."cfg(not(target_arch = \"wasm32\"))".dependencies.tokio-tungstenite]
|
||||||
@@ -79,5 +79,5 @@ features = ["js"]
|
|||||||
#url = "2.1"
|
#url = "2.1"
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
coconut = ["gateway-requests/coconut", "coconut-interface", "validator-client", "credentials/coconut"]
|
coconut = ["gateway-requests/coconut", "coconut-interface", "credentials/coconut"]
|
||||||
wasm = []
|
wasm = []
|
||||||
|
|||||||
@@ -1,23 +1,26 @@
|
|||||||
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
|
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
|
||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
|
||||||
|
#[cfg(feature = "coconut")]
|
||||||
use crate::error::GatewayClientError;
|
use crate::error::GatewayClientError;
|
||||||
|
|
||||||
#[cfg(target_arch = "wasm32")]
|
#[cfg(target_arch = "wasm32")]
|
||||||
use crate::wasm_storage::Storage;
|
use crate::wasm_mockups::Storage;
|
||||||
#[cfg(not(target_arch = "wasm32"))]
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
use credential_storage::storage::Storage;
|
use credential_storage::storage::Storage;
|
||||||
|
|
||||||
#[cfg(all(target_arch = "wasm32", feature = "coconut"))]
|
#[cfg(all(target_arch = "wasm32", feature = "coconut"))]
|
||||||
use crate::wasm_storage::StorageError;
|
use crate::wasm_mockups::StorageError;
|
||||||
|
|
||||||
#[cfg(all(not(target_arch = "wasm32"), feature = "coconut"))]
|
#[cfg(all(not(target_arch = "wasm32"), feature = "coconut"))]
|
||||||
use credential_storage::error::StorageError;
|
use credential_storage::error::StorageError;
|
||||||
|
|
||||||
|
#[cfg(target_arch = "wasm32")]
|
||||||
|
use crate::wasm_mockups::{Client, CosmWasmClient};
|
||||||
#[cfg(feature = "coconut")]
|
#[cfg(feature = "coconut")]
|
||||||
use std::str::FromStr;
|
use std::str::FromStr;
|
||||||
#[cfg(feature = "coconut")]
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
use validator_client::client::CoconutApiClient;
|
use validator_client::{nyxd::CosmWasmClient, Client};
|
||||||
#[cfg(feature = "coconut")]
|
#[cfg(feature = "coconut")]
|
||||||
use {
|
use {
|
||||||
coconut_interface::Base58,
|
coconut_interface::Base58,
|
||||||
@@ -28,41 +31,34 @@ use {
|
|||||||
|
|
||||||
// TODO: make it nicer for wasm (I don't want to touch it for this experiment)
|
// TODO: make it nicer for wasm (I don't want to touch it for this experiment)
|
||||||
#[cfg(target_arch = "wasm32")]
|
#[cfg(target_arch = "wasm32")]
|
||||||
use crate::wasm_storage::PersistentStorage;
|
use crate::wasm_mockups::PersistentStorage;
|
||||||
|
|
||||||
#[cfg(not(target_arch = "wasm32"))]
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
use credential_storage::PersistentStorage;
|
use credential_storage::PersistentStorage;
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct BandwidthController<St: Storage = PersistentStorage> {
|
#[allow(dead_code)]
|
||||||
#[allow(dead_code)]
|
pub struct BandwidthController<C: Clone, St: Storage = PersistentStorage> {
|
||||||
storage: St,
|
storage: St,
|
||||||
#[cfg(feature = "coconut")]
|
nyxd_client: Client<C>,
|
||||||
coconut_api_clients: Vec<CoconutApiClient>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<St> BandwidthController<St>
|
impl<C, St> BandwidthController<C, St>
|
||||||
where
|
where
|
||||||
|
C: CosmWasmClient + Sync + Send + Clone,
|
||||||
St: Storage + Clone + 'static,
|
St: Storage + Clone + 'static,
|
||||||
{
|
{
|
||||||
#[cfg(feature = "coconut")]
|
pub fn new(storage: St, nyxd_client: Client<C>) -> Self {
|
||||||
pub fn new(storage: St, coconut_api_clients: Vec<CoconutApiClient>) -> Self {
|
|
||||||
BandwidthController {
|
BandwidthController {
|
||||||
storage,
|
storage,
|
||||||
coconut_api_clients,
|
nyxd_client,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(feature = "coconut"))]
|
|
||||||
pub fn new(storage: St) -> Result<Self, GatewayClientError> {
|
|
||||||
Ok(BandwidthController { storage })
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(feature = "coconut")]
|
#[cfg(feature = "coconut")]
|
||||||
pub async fn prepare_coconut_credential(
|
pub async fn prepare_coconut_credential(
|
||||||
&self,
|
&self,
|
||||||
) -> Result<(coconut_interface::Credential, i64), GatewayClientError> {
|
) -> Result<(coconut_interface::Credential, i64), GatewayClientError> {
|
||||||
let verification_key = obtain_aggregate_verification_key(&self.coconut_api_clients).await?;
|
|
||||||
let bandwidth_credential = self.storage.get_next_coconut_credential().await?;
|
let bandwidth_credential = self.storage.get_next_coconut_credential().await?;
|
||||||
let voucher_value = u64::from_str(&bandwidth_credential.voucher_value)
|
let voucher_value = u64::from_str(&bandwidth_credential.voucher_value)
|
||||||
.map_err(|_| StorageError::InconsistentData)?;
|
.map_err(|_| StorageError::InconsistentData)?;
|
||||||
@@ -73,6 +69,19 @@ where
|
|||||||
coconut_interface::Attribute::try_from_bs58(bandwidth_credential.binding_number)?;
|
coconut_interface::Attribute::try_from_bs58(bandwidth_credential.binding_number)?;
|
||||||
let signature =
|
let signature =
|
||||||
coconut_interface::Signature::try_from_bs58(bandwidth_credential.signature)?;
|
coconut_interface::Signature::try_from_bs58(bandwidth_credential.signature)?;
|
||||||
|
let epoch_id = u64::from_str(&bandwidth_credential.epoch_id)
|
||||||
|
.map_err(|_| StorageError::InconsistentData)?;
|
||||||
|
|
||||||
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
|
let coconut_api_clients = validator_client::CoconutApiClient::all_coconut_api_clients(
|
||||||
|
&self.nyxd_client,
|
||||||
|
epoch_id,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.expect("Could not query api clients");
|
||||||
|
#[cfg(target_arch = "wasm32")]
|
||||||
|
let coconut_api_clients = vec![];
|
||||||
|
let verification_key = obtain_aggregate_verification_key(&coconut_api_clients).await?;
|
||||||
|
|
||||||
// the below would only be executed once we know where we want to spend it (i.e. which gateway and stuff)
|
// the below would only be executed once we know where we want to spend it (i.e. which gateway and stuff)
|
||||||
Ok((
|
Ok((
|
||||||
@@ -81,6 +90,7 @@ where
|
|||||||
voucher_info,
|
voucher_info,
|
||||||
serial_number,
|
serial_number,
|
||||||
binding_number,
|
binding_number,
|
||||||
|
epoch_id,
|
||||||
&signature,
|
&signature,
|
||||||
&verification_key,
|
&verification_key,
|
||||||
)?,
|
)?,
|
||||||
|
|||||||
@@ -32,9 +32,13 @@ use coconut_interface::Credential;
|
|||||||
use credential_storage::PersistentStorage;
|
use credential_storage::PersistentStorage;
|
||||||
#[cfg(not(target_arch = "wasm32"))]
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
use tokio_tungstenite::connect_async;
|
use tokio_tungstenite::connect_async;
|
||||||
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
|
use validator_client::nyxd::CosmWasmClient;
|
||||||
|
|
||||||
#[cfg(target_arch = "wasm32")]
|
#[cfg(target_arch = "wasm32")]
|
||||||
use crate::wasm_storage::PersistentStorage;
|
use crate::wasm_mockups::CosmWasmClient;
|
||||||
|
#[cfg(target_arch = "wasm32")]
|
||||||
|
use crate::wasm_mockups::PersistentStorage;
|
||||||
#[cfg(target_arch = "wasm32")]
|
#[cfg(target_arch = "wasm32")]
|
||||||
use wasm_timer;
|
use wasm_timer;
|
||||||
#[cfg(target_arch = "wasm32")]
|
#[cfg(target_arch = "wasm32")]
|
||||||
@@ -43,7 +47,7 @@ use wasm_utils::websocket::JSWebsocket;
|
|||||||
const DEFAULT_RECONNECTION_ATTEMPTS: usize = 10;
|
const DEFAULT_RECONNECTION_ATTEMPTS: usize = 10;
|
||||||
const DEFAULT_RECONNECTION_BACKOFF: Duration = Duration::from_secs(5);
|
const DEFAULT_RECONNECTION_BACKOFF: Duration = Duration::from_secs(5);
|
||||||
|
|
||||||
pub struct GatewayClient {
|
pub struct GatewayClient<C: Clone> {
|
||||||
authenticated: bool,
|
authenticated: bool,
|
||||||
disabled_credentials_mode: bool,
|
disabled_credentials_mode: bool,
|
||||||
bandwidth_remaining: i64,
|
bandwidth_remaining: i64,
|
||||||
@@ -55,7 +59,7 @@ pub struct GatewayClient {
|
|||||||
connection: SocketState,
|
connection: SocketState,
|
||||||
packet_router: PacketRouter,
|
packet_router: PacketRouter,
|
||||||
response_timeout_duration: Duration,
|
response_timeout_duration: Duration,
|
||||||
bandwidth_controller: Option<BandwidthController<PersistentStorage>>,
|
bandwidth_controller: Option<BandwidthController<C, PersistentStorage>>,
|
||||||
|
|
||||||
// reconnection related variables
|
// reconnection related variables
|
||||||
/// Specifies whether client should try to reconnect to gateway on connection failure.
|
/// Specifies whether client should try to reconnect to gateway on connection failure.
|
||||||
@@ -70,7 +74,10 @@ pub struct GatewayClient {
|
|||||||
shutdown: TaskClient,
|
shutdown: TaskClient,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl GatewayClient {
|
impl<C> GatewayClient<C>
|
||||||
|
where
|
||||||
|
C: CosmWasmClient + Sync + Send + Clone,
|
||||||
|
{
|
||||||
// TODO: put it all in a Config struct
|
// TODO: put it all in a Config struct
|
||||||
#[allow(clippy::too_many_arguments)]
|
#[allow(clippy::too_many_arguments)]
|
||||||
pub fn new(
|
pub fn new(
|
||||||
@@ -82,7 +89,7 @@ impl GatewayClient {
|
|||||||
mixnet_message_sender: MixnetMessageSender,
|
mixnet_message_sender: MixnetMessageSender,
|
||||||
ack_sender: AcknowledgementSender,
|
ack_sender: AcknowledgementSender,
|
||||||
response_timeout_duration: Duration,
|
response_timeout_duration: Duration,
|
||||||
bandwidth_controller: Option<BandwidthController<PersistentStorage>>,
|
bandwidth_controller: Option<BandwidthController<C, PersistentStorage>>,
|
||||||
shutdown: TaskClient,
|
shutdown: TaskClient,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
GatewayClient {
|
GatewayClient {
|
||||||
@@ -138,7 +145,7 @@ impl GatewayClient {
|
|||||||
let shutdown = TaskClient::dummy();
|
let shutdown = TaskClient::dummy();
|
||||||
let packet_router = PacketRouter::new(ack_tx, mix_tx, shutdown.clone());
|
let packet_router = PacketRouter::new(ack_tx, mix_tx, shutdown.clone());
|
||||||
|
|
||||||
GatewayClient {
|
GatewayClient::<C> {
|
||||||
authenticated: false,
|
authenticated: false,
|
||||||
disabled_credentials_mode: true,
|
disabled_credentials_mode: true,
|
||||||
bandwidth_remaining: 0,
|
bandwidth_remaining: 0,
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
|
||||||
#[cfg(target_arch = "wasm32")]
|
#[cfg(target_arch = "wasm32")]
|
||||||
use crate::wasm_storage::StorageError;
|
use crate::wasm_mockups::StorageError;
|
||||||
#[cfg(not(target_arch = "wasm32"))]
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
use credential_storage::error::StorageError;
|
use credential_storage::error::StorageError;
|
||||||
use gateway_requests::registration::handshake::error::HandshakeError;
|
use gateway_requests::registration::handshake::error::HandshakeError;
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ pub mod error;
|
|||||||
pub mod packet_router;
|
pub mod packet_router;
|
||||||
pub mod socket_state;
|
pub mod socket_state;
|
||||||
#[cfg(target_arch = "wasm32")]
|
#[cfg(target_arch = "wasm32")]
|
||||||
mod wasm_storage;
|
pub mod wasm_mockups;
|
||||||
|
|
||||||
/// Helper method for reading from websocket stream. Helps to flatten the structure.
|
/// Helper method for reading from websocket stream. Helps to flatten the structure.
|
||||||
pub(crate) fn cleanup_socket_message(
|
pub(crate) fn cleanup_socket_message(
|
||||||
|
|||||||
+14
@@ -2,6 +2,7 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
|
||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
|
use std::marker::PhantomData;
|
||||||
use thiserror::Error;
|
use thiserror::Error;
|
||||||
|
|
||||||
#[derive(Error, Debug)]
|
#[derive(Error, Debug)]
|
||||||
@@ -14,6 +15,18 @@ pub enum StorageError {
|
|||||||
InconsistentData,
|
InconsistentData,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub trait CosmWasmClient {}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct SigningNyxdClient {}
|
||||||
|
|
||||||
|
impl CosmWasmClient for SigningNyxdClient {}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct Client<C> {
|
||||||
|
_phantom: PhantomData<C>,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct PersistentStorage {}
|
pub struct PersistentStorage {}
|
||||||
|
|
||||||
@@ -24,6 +37,7 @@ pub struct CoconutCredential {
|
|||||||
pub serial_number: String,
|
pub serial_number: String,
|
||||||
pub binding_number: String,
|
pub binding_number: String,
|
||||||
pub signature: String,
|
pub signature: String,
|
||||||
|
pub epoch_id: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
@@ -8,9 +8,10 @@ edition = "2021"
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
futures = "0.3"
|
futures = "0.3"
|
||||||
log = "0.4.8"
|
log = { workspace = true }
|
||||||
tokio = { version = "1.21.2", features = ["time", "net", "rt"] }
|
tokio = { version = "1.24.1", features = ["time", "net", "rt"] }
|
||||||
tokio-util = { version = "0.7.3", features = ["codec"] }
|
tokio-util = { version = "0.7.4", features = ["codec"] }
|
||||||
|
|
||||||
# internal
|
# internal
|
||||||
nymsphinx = {path = "../../nymsphinx" }
|
nymsphinx = { path = "../../nymsphinx" }
|
||||||
|
task = { path = "../../task" }
|
||||||
@@ -16,6 +16,7 @@ type MixForwardingReceiver = mpsc::UnboundedReceiver<MixPacket>;
|
|||||||
pub struct PacketForwarder {
|
pub struct PacketForwarder {
|
||||||
mixnet_client: Client,
|
mixnet_client: Client,
|
||||||
packet_receiver: MixForwardingReceiver,
|
packet_receiver: MixForwardingReceiver,
|
||||||
|
shutdown: task::TaskClient,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl PacketForwarder {
|
impl PacketForwarder {
|
||||||
@@ -25,6 +26,7 @@ impl PacketForwarder {
|
|||||||
initial_connection_timeout: Duration,
|
initial_connection_timeout: Duration,
|
||||||
maximum_connection_buffer_size: usize,
|
maximum_connection_buffer_size: usize,
|
||||||
use_legacy_version: bool,
|
use_legacy_version: bool,
|
||||||
|
shutdown: task::TaskClient,
|
||||||
) -> (PacketForwarder, MixForwardingSender) {
|
) -> (PacketForwarder, MixForwardingSender) {
|
||||||
let client_config = Config::new(
|
let client_config = Config::new(
|
||||||
initial_reconnection_backoff,
|
initial_reconnection_backoff,
|
||||||
@@ -40,26 +42,35 @@ impl PacketForwarder {
|
|||||||
PacketForwarder {
|
PacketForwarder {
|
||||||
mixnet_client: Client::new(client_config),
|
mixnet_client: Client::new(client_config),
|
||||||
packet_receiver,
|
packet_receiver,
|
||||||
|
shutdown,
|
||||||
},
|
},
|
||||||
packet_sender,
|
packet_sender,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn run(&mut self) {
|
pub async fn run(&mut self) {
|
||||||
while let Some(mix_packet) = self.packet_receiver.next().await {
|
while !self.shutdown.is_shutdown() {
|
||||||
trace!("Going to forward packet to {:?}", mix_packet.next_hop());
|
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 next_hop = mix_packet.next_hop();
|
||||||
let packet_mode = mix_packet.packet_mode();
|
let packet_mode = mix_packet.packet_mode();
|
||||||
let sphinx_packet = mix_packet.into_sphinx_packet();
|
let sphinx_packet = mix_packet.into_sphinx_packet();
|
||||||
// we don't care about responses, we just want to fire packets
|
// we don't care about responses, we just want to fire packets
|
||||||
// as quickly as possible
|
// as quickly as possible
|
||||||
|
|
||||||
if let Err(err) =
|
if let Err(err) =
|
||||||
self.mixnet_client
|
self.mixnet_client
|
||||||
.send_without_response(next_hop, sphinx_packet, packet_mode)
|
.send_without_response(next_hop, sphinx_packet, packet_mode)
|
||||||
{
|
{
|
||||||
debug!("failed to forward the packet - {err}")
|
debug!("failed to forward the packet - {err}")
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,14 +17,15 @@ mixnet-contract-common = { path= "../../cosmwasm-smart-contracts/mixnet-contract
|
|||||||
vesting-contract-common = { path= "../../cosmwasm-smart-contracts/vesting-contract" }
|
vesting-contract-common = { path= "../../cosmwasm-smart-contracts/vesting-contract" }
|
||||||
coconut-bandwidth-contract-common = { path= "../../cosmwasm-smart-contracts/coconut-bandwidth-contract" }
|
coconut-bandwidth-contract-common = { path= "../../cosmwasm-smart-contracts/coconut-bandwidth-contract" }
|
||||||
multisig-contract-common = { path = "../../cosmwasm-smart-contracts/multisig-contract" }
|
multisig-contract-common = { path = "../../cosmwasm-smart-contracts/multisig-contract" }
|
||||||
|
group-contract-common = { path = "../../cosmwasm-smart-contracts/group-contract" }
|
||||||
vesting-contract = { path = "../../../contracts/vesting" }
|
vesting-contract = { path = "../../../contracts/vesting" }
|
||||||
serde = { version = "1", features = ["derive"] }
|
serde = { version = "1", features = ["derive"] }
|
||||||
serde_json = "1"
|
serde_json = "1"
|
||||||
reqwest = { version = "0.11", features = ["json"] }
|
reqwest = { version = "0.11", features = ["json"] }
|
||||||
thiserror = "1"
|
thiserror = "1"
|
||||||
log = "0.4"
|
log = { workspace = true }
|
||||||
url = { version = "2.2", features = ["serde"] }
|
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"
|
futures = "0.3"
|
||||||
|
|
||||||
coconut-interface = { path = "../../coconut-interface" }
|
coconut-interface = { path = "../../coconut-interface" }
|
||||||
@@ -39,6 +40,7 @@ bip39 = { version = "1", features = ["rand"], optional = true }
|
|||||||
config = { path = "../../config", optional = true }
|
config = { path = "../../config", optional = true }
|
||||||
cosmrs = { git = "https://github.com/neacsu/cosmos-rust", branch = "neacsu/feegrant_support", features = ["rpc", "bip32", "cosmwasm"], optional = true}
|
cosmrs = { git = "https://github.com/neacsu/cosmos-rust", branch = "neacsu/feegrant_support", features = ["rpc", "bip32", "cosmwasm"], optional = true}
|
||||||
cw3 = { version = "0.13.4", optional = true }
|
cw3 = { version = "0.13.4", optional = true }
|
||||||
|
cw4 = { version = "0.13.4", optional = true }
|
||||||
prost = { version = "0.10", default-features = false, optional = true }
|
prost = { version = "0.10", default-features = false, optional = true }
|
||||||
flate2 = { version = "1.0.20", optional = true }
|
flate2 = { version = "1.0.20", optional = true }
|
||||||
sha2 = { version = "0.9.5", optional = true }
|
sha2 = { version = "0.9.5", optional = true }
|
||||||
@@ -56,6 +58,7 @@ nyxd-client = [
|
|||||||
"config",
|
"config",
|
||||||
"cosmrs",
|
"cosmrs",
|
||||||
"cw3",
|
"cw3",
|
||||||
|
"cw4",
|
||||||
"prost",
|
"prost",
|
||||||
"flate2",
|
"flate2",
|
||||||
"sha2",
|
"sha2",
|
||||||
|
|||||||
@@ -21,7 +21,9 @@ use crate::nyxd::traits::{DkgQueryClient, MixnetQueryClient, MultisigQueryClient
|
|||||||
use crate::nyxd::{self, CosmWasmClient, NyxdClient, QueryNyxdClient, SigningNyxdClient};
|
use crate::nyxd::{self, CosmWasmClient, NyxdClient, QueryNyxdClient, SigningNyxdClient};
|
||||||
#[cfg(feature = "nyxd-client")]
|
#[cfg(feature = "nyxd-client")]
|
||||||
use coconut_dkg_common::{
|
use coconut_dkg_common::{
|
||||||
dealer::ContractDealing, types::DealerDetails, verification_key::ContractVKShare,
|
dealer::ContractDealing,
|
||||||
|
types::{DealerDetails, EpochId},
|
||||||
|
verification_key::ContractVKShare,
|
||||||
};
|
};
|
||||||
#[cfg(feature = "nyxd-client")]
|
#[cfg(feature = "nyxd-client")]
|
||||||
use coconut_interface::Base58;
|
use coconut_interface::Base58;
|
||||||
@@ -128,7 +130,8 @@ impl Config {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "nyxd-client")]
|
#[cfg(feature = "nyxd-client")]
|
||||||
pub struct Client<C> {
|
#[derive(Clone)]
|
||||||
|
pub struct Client<C: Clone> {
|
||||||
// TODO: we really shouldn't be storing a mnemonic here, but removing it would be
|
// TODO: we really shouldn't be storing a mnemonic here, but removing it would be
|
||||||
// non-trivial amount of work and it's out of scope of the current branch
|
// non-trivial amount of work and it's out of scope of the current branch
|
||||||
mnemonic: Option<bip39::Mnemonic>,
|
mnemonic: Option<bip39::Mnemonic>,
|
||||||
@@ -218,7 +221,10 @@ impl Client<QueryNyxdClient> {
|
|||||||
|
|
||||||
// nyxd wrappers
|
// nyxd wrappers
|
||||||
#[cfg(feature = "nyxd-client")]
|
#[cfg(feature = "nyxd-client")]
|
||||||
impl<C> Client<C> {
|
impl<C> Client<C>
|
||||||
|
where
|
||||||
|
C: Clone,
|
||||||
|
{
|
||||||
// use case: somebody initialised client without a contract in order to upload and initialise one
|
// use case: somebody initialised client without a contract in order to upload and initialise one
|
||||||
// and now they want to actually use it without making new client
|
// and now they want to actually use it without making new client
|
||||||
|
|
||||||
@@ -676,6 +682,7 @@ impl<C> Client<C> {
|
|||||||
|
|
||||||
pub async fn get_all_nyxd_verification_key_shares(
|
pub async fn get_all_nyxd_verification_key_shares(
|
||||||
&self,
|
&self,
|
||||||
|
epoch_id: EpochId,
|
||||||
) -> Result<Vec<ContractVKShare>, ValidatorClientError>
|
) -> Result<Vec<ContractVKShare>, ValidatorClientError>
|
||||||
where
|
where
|
||||||
C: CosmWasmClient + Sync + Send,
|
C: CosmWasmClient + Sync + Send,
|
||||||
@@ -685,7 +692,11 @@ impl<C> Client<C> {
|
|||||||
loop {
|
loop {
|
||||||
let mut paged_response = self
|
let mut paged_response = self
|
||||||
.nyxd
|
.nyxd
|
||||||
.get_vk_shares_paged(start_after.take(), self.verification_key_page_limit)
|
.get_vk_shares_paged(
|
||||||
|
epoch_id,
|
||||||
|
start_after.take(),
|
||||||
|
self.verification_key_page_limit,
|
||||||
|
)
|
||||||
.await?;
|
.await?;
|
||||||
shares.append(&mut paged_response.shares);
|
shares.append(&mut paged_response.shares);
|
||||||
|
|
||||||
@@ -730,7 +741,10 @@ impl<C> Client<C> {
|
|||||||
|
|
||||||
// validator-api wrappers
|
// validator-api wrappers
|
||||||
#[cfg(feature = "nyxd-client")]
|
#[cfg(feature = "nyxd-client")]
|
||||||
impl<C> Client<C> {
|
impl<C> Client<C>
|
||||||
|
where
|
||||||
|
C: Clone,
|
||||||
|
{
|
||||||
pub fn change_nym_api(&mut self, new_endpoint: Url) {
|
pub fn change_nym_api(&mut self, new_endpoint: Url) {
|
||||||
self.nym_api.change_url(new_endpoint)
|
self.nym_api.change_url(new_endpoint)
|
||||||
}
|
}
|
||||||
@@ -792,14 +806,15 @@ pub struct CoconutApiClient {
|
|||||||
|
|
||||||
#[cfg(feature = "nyxd-client")]
|
#[cfg(feature = "nyxd-client")]
|
||||||
impl CoconutApiClient {
|
impl CoconutApiClient {
|
||||||
pub async fn all_coconut_api_clients<C>(
|
pub async fn all_coconut_api_clients<C: Clone>(
|
||||||
nyxd_client: &Client<C>,
|
nyxd_client: &Client<C>,
|
||||||
|
epoch_id: EpochId,
|
||||||
) -> Result<Vec<Self>, ValidatorClientError>
|
) -> Result<Vec<Self>, ValidatorClientError>
|
||||||
where
|
where
|
||||||
C: CosmWasmClient + Sync + Send,
|
C: CosmWasmClient + Sync + Send,
|
||||||
{
|
{
|
||||||
Ok(nyxd_client
|
Ok(nyxd_client
|
||||||
.get_all_nyxd_verification_key_shares()
|
.get_all_nyxd_verification_key_shares(epoch_id)
|
||||||
.await?
|
.await?
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.filter_map(Self::try_from)
|
.filter_map(Self::try_from)
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ use thiserror::Error;
|
|||||||
|
|
||||||
#[derive(Error, Debug)]
|
#[derive(Error, Debug)]
|
||||||
pub enum ValidatorClientError {
|
pub enum ValidatorClientError {
|
||||||
#[error("There was an issue with the validator api request - {source}")]
|
#[error("nym api request failed - {source}")]
|
||||||
NymAPIError {
|
NymAPIError {
|
||||||
#[from]
|
#[from]
|
||||||
source: nym_api::error::NymAPIError,
|
source: nym_api::error::NymAPIError,
|
||||||
@@ -16,7 +16,7 @@ pub enum ValidatorClientError {
|
|||||||
MalformedUrlProvided(#[from] url::ParseError),
|
MalformedUrlProvided(#[from] url::ParseError),
|
||||||
|
|
||||||
#[cfg(feature = "nyxd-client")]
|
#[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),
|
NyxdError(#[from] crate::nyxd::error::NyxdError),
|
||||||
|
|
||||||
#[error("No validator API url has been provided")]
|
#[error("No validator API url has been provided")]
|
||||||
|
|||||||
@@ -9,10 +9,8 @@ pub mod nym_api;
|
|||||||
#[cfg(feature = "nyxd-client")]
|
#[cfg(feature = "nyxd-client")]
|
||||||
pub mod nyxd;
|
pub mod nyxd;
|
||||||
|
|
||||||
#[cfg(feature = "nyxd-client")]
|
|
||||||
pub use crate::client::{CoconutApiClient, NymApiClient};
|
|
||||||
pub use crate::error::ValidatorClientError;
|
pub use crate::error::ValidatorClientError;
|
||||||
pub use nym_api_requests::*;
|
pub use nym_api_requests::*;
|
||||||
|
|
||||||
#[cfg(feature = "nyxd-client")]
|
#[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")]
|
#[error("{0} is not a valid tx hash")]
|
||||||
InvalidTxHash(String),
|
InvalidTxHash(String),
|
||||||
|
|
||||||
#[error("There was an issue with a tendermint RPC request - {0}")]
|
#[error("Tendermint RPC request failed - {0}")]
|
||||||
TendermintError(#[from] TendermintRpcError),
|
TendermintError(#[from] TendermintRpcError),
|
||||||
|
|
||||||
#[error("There was an issue when attempting to serialize data ({0})")]
|
#[error("Failed when attempting to serialize data ({0})")]
|
||||||
SerializationError(String),
|
SerializationError(String),
|
||||||
|
|
||||||
#[error("There was an issue when attempting to deserialize data ({0})")]
|
#[error("Failed when attempting to deserialize data ({0})")]
|
||||||
DeserializationError(String),
|
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),
|
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),
|
ProtobufDecodingError(#[from] prost::DecodeError),
|
||||||
|
|
||||||
#[error("Account {0} does not exist on the chain")]
|
#[error("Account {0} does not exist on the chain")]
|
||||||
NonExistentAccountError(AccountId),
|
NonExistentAccountError(AccountId),
|
||||||
|
|
||||||
#[error("There was an issue with the serialization/deserialization - {0}")]
|
#[error("Failed on json serialization/deserialization - {0}")]
|
||||||
SerdeJsonError(#[from] serde_json::Error),
|
SerdeJsonError(#[from] serde_json::Error),
|
||||||
|
|
||||||
#[error("Account {0} is not a valid account address")]
|
#[error("Account {0} is not a valid account address")]
|
||||||
|
|||||||
@@ -17,11 +17,13 @@ use cosmrs::rpc::HttpClientUrl;
|
|||||||
use cosmrs::tx::Msg;
|
use cosmrs::tx::Msg;
|
||||||
use execute::execute;
|
use execute::execute;
|
||||||
use log::debug;
|
use log::debug;
|
||||||
|
use mixnet_contract_common::MixId;
|
||||||
use network_defaults::{ChainDetails, NymNetworkDetails};
|
use network_defaults::{ChainDetails, NymNetworkDetails};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use std::convert::TryInto;
|
use std::convert::TryInto;
|
||||||
use std::time::SystemTime;
|
use std::time::SystemTime;
|
||||||
use vesting_contract_common::ExecuteMsg as VestingExecuteMsg;
|
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::client::CosmWasmClient;
|
||||||
pub use crate::nyxd::cosmwasm_client::signing_client::SigningCosmWasmClient;
|
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 cosmrs::{bip32, AccountId, Decimal, Denom};
|
||||||
pub use cosmwasm_std::Coin as CosmWasmCoin;
|
pub use cosmwasm_std::Coin as CosmWasmCoin;
|
||||||
pub use fee::{gas_price::GasPrice, GasAdjustable, GasAdjustment};
|
pub use fee::{gas_price::GasPrice, GasAdjustable, GasAdjustment};
|
||||||
use mixnet_contract_common::MixId;
|
|
||||||
pub use signing_client::Client as SigningNyxdClient;
|
pub use signing_client::Client as SigningNyxdClient;
|
||||||
pub use traits::{VestingQueryClient, VestingSigningClient};
|
pub use traits::{VestingQueryClient, VestingSigningClient};
|
||||||
use vesting_contract_common::PledgeCap;
|
|
||||||
|
|
||||||
pub mod coin;
|
pub mod coin;
|
||||||
pub mod cosmwasm_client;
|
pub mod cosmwasm_client;
|
||||||
@@ -65,6 +65,7 @@ pub struct Config {
|
|||||||
pub(crate) vesting_contract_address: Option<AccountId>,
|
pub(crate) vesting_contract_address: Option<AccountId>,
|
||||||
pub(crate) bandwidth_claim_contract_address: Option<AccountId>,
|
pub(crate) bandwidth_claim_contract_address: Option<AccountId>,
|
||||||
pub(crate) coconut_bandwidth_contract_address: Option<AccountId>,
|
pub(crate) coconut_bandwidth_contract_address: Option<AccountId>,
|
||||||
|
pub(crate) group_contract_address: Option<AccountId>,
|
||||||
pub(crate) multisig_contract_address: Option<AccountId>,
|
pub(crate) multisig_contract_address: Option<AccountId>,
|
||||||
pub(crate) coconut_dkg_contract_address: Option<AccountId>,
|
pub(crate) coconut_dkg_contract_address: Option<AccountId>,
|
||||||
// TODO: add this in later commits
|
// TODO: add this in later commits
|
||||||
@@ -119,6 +120,10 @@ impl Config {
|
|||||||
.as_ref(),
|
.as_ref(),
|
||||||
prefix,
|
prefix,
|
||||||
)?,
|
)?,
|
||||||
|
group_contract_address: Self::parse_optional_account(
|
||||||
|
details.contracts.group_contract_address.as_ref(),
|
||||||
|
prefix,
|
||||||
|
)?,
|
||||||
multisig_contract_address: Self::parse_optional_account(
|
multisig_contract_address: Self::parse_optional_account(
|
||||||
details.contracts.multisig_contract_address.as_ref(),
|
details.contracts.multisig_contract_address.as_ref(),
|
||||||
prefix,
|
prefix,
|
||||||
@@ -131,8 +136,8 @@ impl Config {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Clone, Debug)]
|
||||||
pub struct NyxdClient<C> {
|
pub struct NyxdClient<C: Clone> {
|
||||||
client: C,
|
client: C,
|
||||||
config: Config,
|
config: Config,
|
||||||
client_address: Option<Vec<AccountId>>,
|
client_address: Option<Vec<AccountId>>,
|
||||||
@@ -209,7 +214,10 @@ impl NyxdClient<SigningNyxdClient> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<C> NyxdClient<C> {
|
impl<C> NyxdClient<C>
|
||||||
|
where
|
||||||
|
C: Clone,
|
||||||
|
{
|
||||||
pub fn current_config(&self) -> &Config {
|
pub fn current_config(&self) -> &Config {
|
||||||
&self.config
|
&self.config
|
||||||
}
|
}
|
||||||
@@ -276,6 +284,10 @@ impl<C> NyxdClient<C> {
|
|||||||
.unwrap()
|
.unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn group_contract_address(&self) -> &AccountId {
|
||||||
|
self.config.group_contract_address.as_ref().unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
// TODO: this should get changed into Result<&AccountId, NyxdError> (or Option<&AccountId> in future commits
|
// TODO: this should get changed into Result<&AccountId, NyxdError> (or Option<&AccountId> in future commits
|
||||||
// note: what unwrap is doing here is just moving a failure that would have normally
|
// note: what unwrap is doing here is just moving a failure that would have normally
|
||||||
// occurred in `connect` when attempting to parse an empty address,
|
// occurred in `connect` when attempting to parse an empty address,
|
||||||
|
|||||||
+1
-1
@@ -18,7 +18,7 @@ pub trait CoconutBandwidthQueryClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl<C: CosmWasmClient + Sync + Send> CoconutBandwidthQueryClient for NyxdClient<C> {
|
impl<C: CosmWasmClient + Sync + Send + Clone> CoconutBandwidthQueryClient for NyxdClient<C> {
|
||||||
async fn get_spent_credential(
|
async fn get_spent_credential(
|
||||||
&self,
|
&self,
|
||||||
blinded_serial_number: String,
|
blinded_serial_number: String,
|
||||||
|
|||||||
+3
-1
@@ -30,7 +30,9 @@ pub trait CoconutBandwidthSigningClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl<C: SigningCosmWasmClient + Sync + Send> CoconutBandwidthSigningClient for NyxdClient<C> {
|
impl<C: SigningCosmWasmClient + Sync + Send + Clone> CoconutBandwidthSigningClient
|
||||||
|
for NyxdClient<C>
|
||||||
|
{
|
||||||
async fn deposit(
|
async fn deposit(
|
||||||
&self,
|
&self,
|
||||||
amount: Coin,
|
amount: Coin,
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ use coconut_dkg_common::dealer::{
|
|||||||
DealerDetailsResponse, PagedDealerResponse, PagedDealingsResponse,
|
DealerDetailsResponse, PagedDealerResponse, PagedDealingsResponse,
|
||||||
};
|
};
|
||||||
use coconut_dkg_common::msg::QueryMsg as DkgQueryMsg;
|
use coconut_dkg_common::msg::QueryMsg as DkgQueryMsg;
|
||||||
use coconut_dkg_common::types::Epoch;
|
use coconut_dkg_common::types::{Epoch, EpochId};
|
||||||
use coconut_dkg_common::verification_key::PagedVKSharesResponse;
|
use coconut_dkg_common::verification_key::PagedVKSharesResponse;
|
||||||
use cosmrs::AccountId;
|
use cosmrs::AccountId;
|
||||||
|
|
||||||
@@ -39,6 +39,7 @@ pub trait DkgQueryClient {
|
|||||||
) -> Result<PagedDealingsResponse, NyxdError>;
|
) -> Result<PagedDealingsResponse, NyxdError>;
|
||||||
async fn get_vk_shares_paged(
|
async fn get_vk_shares_paged(
|
||||||
&self,
|
&self,
|
||||||
|
epoch_id: EpochId,
|
||||||
start_after: Option<String>,
|
start_after: Option<String>,
|
||||||
page_limit: Option<u32>,
|
page_limit: Option<u32>,
|
||||||
) -> Result<PagedVKSharesResponse, NyxdError>;
|
) -> Result<PagedVKSharesResponse, NyxdError>;
|
||||||
@@ -47,7 +48,7 @@ pub trait DkgQueryClient {
|
|||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl<C> DkgQueryClient for NyxdClient<C>
|
impl<C> DkgQueryClient for NyxdClient<C>
|
||||||
where
|
where
|
||||||
C: CosmWasmClient + Send + Sync,
|
C: CosmWasmClient + Send + Sync + Clone,
|
||||||
{
|
{
|
||||||
async fn get_current_epoch(&self) -> Result<Epoch, NyxdError> {
|
async fn get_current_epoch(&self) -> Result<Epoch, NyxdError> {
|
||||||
let request = DkgQueryMsg::GetCurrentEpochState {};
|
let request = DkgQueryMsg::GetCurrentEpochState {};
|
||||||
@@ -119,10 +120,12 @@ where
|
|||||||
|
|
||||||
async fn get_vk_shares_paged(
|
async fn get_vk_shares_paged(
|
||||||
&self,
|
&self,
|
||||||
|
epoch_id: EpochId,
|
||||||
start_after: Option<String>,
|
start_after: Option<String>,
|
||||||
page_limit: Option<u32>,
|
page_limit: Option<u32>,
|
||||||
) -> Result<PagedVKSharesResponse, NyxdError> {
|
) -> Result<PagedVKSharesResponse, NyxdError> {
|
||||||
let request = DkgQueryMsg::GetVerificationKeys {
|
let request = DkgQueryMsg::GetVerificationKeys {
|
||||||
|
epoch_id,
|
||||||
limit: page_limit,
|
limit: page_limit,
|
||||||
start_after,
|
start_after,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -36,7 +36,7 @@ pub trait DkgSigningClient {
|
|||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl<C> DkgSigningClient for NyxdClient<C>
|
impl<C> DkgSigningClient for NyxdClient<C>
|
||||||
where
|
where
|
||||||
C: SigningCosmWasmClient + Send + Sync,
|
C: SigningCosmWasmClient + Send + Sync + Clone,
|
||||||
{
|
{
|
||||||
async fn advance_dkg_epoch_state(&self, fee: Option<Fee>) -> Result<ExecuteResult, NyxdError> {
|
async fn advance_dkg_epoch_state(&self, fee: Option<Fee>) -> Result<ExecuteResult, NyxdError> {
|
||||||
let req = DkgExecuteMsg::AdvanceEpochState {};
|
let req = DkgExecuteMsg::AdvanceEpochState {};
|
||||||
|
|||||||
@@ -0,0 +1,28 @@
|
|||||||
|
// Copyright 2023 - Nym Technologies SA <contact@nymtech.net>
|
||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
|
||||||
|
use crate::nyxd::error::NyxdError;
|
||||||
|
use crate::nyxd::{CosmWasmClient, NyxdClient};
|
||||||
|
|
||||||
|
use group_contract_common::msg::QueryMsg;
|
||||||
|
|
||||||
|
use async_trait::async_trait;
|
||||||
|
use cw4::MemberResponse;
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
pub trait GroupQueryClient {
|
||||||
|
async fn member(&self, addr: String) -> Result<MemberResponse, NyxdError>;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl<C: CosmWasmClient + Sync + Send + Clone> GroupQueryClient for NyxdClient<C> {
|
||||||
|
async fn member(&self, addr: String) -> Result<MemberResponse, NyxdError> {
|
||||||
|
let request = QueryMsg::Member {
|
||||||
|
addr,
|
||||||
|
at_height: None,
|
||||||
|
};
|
||||||
|
self.client
|
||||||
|
.query_contract_smart(self.group_contract_address(), &request)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -395,7 +395,7 @@ pub trait MixnetQueryClient {
|
|||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl<C> MixnetQueryClient for NyxdClient<C>
|
impl<C> MixnetQueryClient for NyxdClient<C>
|
||||||
where
|
where
|
||||||
C: CosmWasmClient + Sync + Send,
|
C: CosmWasmClient + Sync + Send + Clone,
|
||||||
{
|
{
|
||||||
async fn query_mixnet_contract<T>(&self, query: MixnetQueryMsg) -> Result<T, NyxdError>
|
async fn query_mixnet_contract<T>(&self, query: MixnetQueryMsg) -> Result<T, NyxdError>
|
||||||
where
|
where
|
||||||
@@ -410,7 +410,7 @@ where
|
|||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl<C> MixnetQueryClient for crate::Client<C>
|
impl<C> MixnetQueryClient for crate::Client<C>
|
||||||
where
|
where
|
||||||
C: CosmWasmClient + Sync + Send,
|
C: CosmWasmClient + Sync + Send + Clone,
|
||||||
{
|
{
|
||||||
async fn query_mixnet_contract<T>(&self, query: MixnetQueryMsg) -> Result<T, NyxdError>
|
async fn query_mixnet_contract<T>(&self, query: MixnetQueryMsg) -> Result<T, NyxdError>
|
||||||
where
|
where
|
||||||
|
|||||||
@@ -627,7 +627,7 @@ pub trait MixnetSigningClient {
|
|||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl<C> MixnetSigningClient for NyxdClient<C>
|
impl<C> MixnetSigningClient for NyxdClient<C>
|
||||||
where
|
where
|
||||||
C: SigningCosmWasmClient + Sync + Send,
|
C: SigningCosmWasmClient + Sync + Send + Clone,
|
||||||
{
|
{
|
||||||
async fn execute_mixnet_contract(
|
async fn execute_mixnet_contract(
|
||||||
&self,
|
&self,
|
||||||
@@ -653,7 +653,7 @@ where
|
|||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl<C> MixnetSigningClient for crate::Client<C>
|
impl<C> MixnetSigningClient for crate::Client<C>
|
||||||
where
|
where
|
||||||
C: SigningCosmWasmClient + Sync + Send,
|
C: SigningCosmWasmClient + Sync + Send + Clone,
|
||||||
{
|
{
|
||||||
async fn execute_mixnet_contract(
|
async fn execute_mixnet_contract(
|
||||||
&self,
|
&self,
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ mod coconut_bandwidth_query_client;
|
|||||||
mod coconut_bandwidth_signing_client;
|
mod coconut_bandwidth_signing_client;
|
||||||
mod dkg_query_client;
|
mod dkg_query_client;
|
||||||
mod dkg_signing_client;
|
mod dkg_signing_client;
|
||||||
|
mod group_query_client;
|
||||||
mod mixnet_query_client;
|
mod mixnet_query_client;
|
||||||
mod mixnet_signing_client;
|
mod mixnet_signing_client;
|
||||||
mod multisig_query_client;
|
mod multisig_query_client;
|
||||||
@@ -16,6 +17,7 @@ pub use coconut_bandwidth_query_client::CoconutBandwidthQueryClient;
|
|||||||
pub use coconut_bandwidth_signing_client::CoconutBandwidthSigningClient;
|
pub use coconut_bandwidth_signing_client::CoconutBandwidthSigningClient;
|
||||||
pub use dkg_query_client::DkgQueryClient;
|
pub use dkg_query_client::DkgQueryClient;
|
||||||
pub use dkg_signing_client::DkgSigningClient;
|
pub use dkg_signing_client::DkgSigningClient;
|
||||||
|
pub use group_query_client::GroupQueryClient;
|
||||||
pub use mixnet_query_client::MixnetQueryClient;
|
pub use mixnet_query_client::MixnetQueryClient;
|
||||||
pub use mixnet_signing_client::MixnetSigningClient;
|
pub use mixnet_signing_client::MixnetSigningClient;
|
||||||
pub use multisig_query_client::MultisigQueryClient;
|
pub use multisig_query_client::MultisigQueryClient;
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ pub trait MultisigQueryClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl<C: CosmWasmClient + Sync + Send> MultisigQueryClient for NyxdClient<C> {
|
impl<C: CosmWasmClient + Sync + Send + Clone> MultisigQueryClient for NyxdClient<C> {
|
||||||
async fn get_proposal(&self, proposal_id: u64) -> Result<ProposalResponse, NyxdError> {
|
async fn get_proposal(&self, proposal_id: u64) -> Result<ProposalResponse, NyxdError> {
|
||||||
let request = QueryMsg::Proposal { proposal_id };
|
let request = QueryMsg::Proposal { proposal_id };
|
||||||
self.client
|
self.client
|
||||||
|
|||||||
@@ -38,7 +38,7 @@ pub trait MultisigSigningClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl<C: SigningCosmWasmClient + Sync + Send> MultisigSigningClient for NyxdClient<C> {
|
impl<C: SigningCosmWasmClient + Sync + Send + Clone> MultisigSigningClient for NyxdClient<C> {
|
||||||
async fn propose_release_funds(
|
async fn propose_release_funds(
|
||||||
&self,
|
&self,
|
||||||
title: String,
|
title: String,
|
||||||
|
|||||||
@@ -269,7 +269,7 @@ pub trait VestingQueryClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl<C: CosmWasmClient + Sync + Send> VestingQueryClient for NyxdClient<C> {
|
impl<C: CosmWasmClient + Sync + Send + Clone> VestingQueryClient for NyxdClient<C> {
|
||||||
async fn query_vesting_contract<T>(&self, query: VestingQueryMsg) -> Result<T, NyxdError>
|
async fn query_vesting_contract<T>(&self, query: VestingQueryMsg) -> Result<T, NyxdError>
|
||||||
where
|
where
|
||||||
for<'a> T: Deserialize<'a>,
|
for<'a> T: Deserialize<'a>,
|
||||||
|
|||||||
@@ -129,7 +129,7 @@ pub trait VestingSigningClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl<C: SigningCosmWasmClient + Sync + Send> VestingSigningClient for NyxdClient<C> {
|
impl<C: SigningCosmWasmClient + Sync + Send + Clone> VestingSigningClient for NyxdClient<C> {
|
||||||
async fn execute_vesting_contract(
|
async fn execute_vesting_contract(
|
||||||
&self,
|
&self,
|
||||||
fee: Option<Fee>,
|
fee: Option<Fee>,
|
||||||
|
|||||||
@@ -18,6 +18,8 @@ pub struct Credential {
|
|||||||
theta: Theta,
|
theta: Theta,
|
||||||
voucher_value: u64,
|
voucher_value: u64,
|
||||||
voucher_info: String,
|
voucher_info: String,
|
||||||
|
#[getset(get = "pub")]
|
||||||
|
epoch_id: u64,
|
||||||
}
|
}
|
||||||
impl Credential {
|
impl Credential {
|
||||||
pub fn new(
|
pub fn new(
|
||||||
@@ -25,12 +27,14 @@ impl Credential {
|
|||||||
theta: Theta,
|
theta: Theta,
|
||||||
voucher_value: u64,
|
voucher_value: u64,
|
||||||
voucher_info: String,
|
voucher_info: String,
|
||||||
|
epoch_id: u64,
|
||||||
) -> Credential {
|
) -> Credential {
|
||||||
Credential {
|
Credential {
|
||||||
n_params,
|
n_params,
|
||||||
theta,
|
theta,
|
||||||
voucher_value,
|
voucher_value,
|
||||||
voucher_info,
|
voucher_info,
|
||||||
|
epoch_id,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -68,6 +72,7 @@ impl Credential {
|
|||||||
let theta_bytes = self.theta.to_bytes();
|
let theta_bytes = self.theta.to_bytes();
|
||||||
let theta_bytes_len = theta_bytes.len();
|
let theta_bytes_len = theta_bytes.len();
|
||||||
let voucher_value_bytes = self.voucher_value.to_be_bytes();
|
let voucher_value_bytes = self.voucher_value.to_be_bytes();
|
||||||
|
let epoch_id_bytes = self.epoch_id.to_be_bytes();
|
||||||
let voucher_info_bytes = self.voucher_info.as_bytes();
|
let voucher_info_bytes = self.voucher_info.as_bytes();
|
||||||
let voucher_info_len = voucher_info_bytes.len();
|
let voucher_info_len = voucher_info_bytes.len();
|
||||||
|
|
||||||
@@ -76,6 +81,7 @@ impl Credential {
|
|||||||
bytes.extend_from_slice(&(theta_bytes_len as u64).to_be_bytes());
|
bytes.extend_from_slice(&(theta_bytes_len as u64).to_be_bytes());
|
||||||
bytes.extend_from_slice(&theta_bytes);
|
bytes.extend_from_slice(&theta_bytes);
|
||||||
bytes.extend_from_slice(&voucher_value_bytes);
|
bytes.extend_from_slice(&voucher_value_bytes);
|
||||||
|
bytes.extend_from_slice(&epoch_id_bytes);
|
||||||
bytes.extend_from_slice(voucher_info_bytes);
|
bytes.extend_from_slice(voucher_info_bytes);
|
||||||
|
|
||||||
bytes
|
bytes
|
||||||
@@ -103,7 +109,9 @@ impl Credential {
|
|||||||
.map_err(|e| CoconutError::Deserialization(e.to_string()))?;
|
.map_err(|e| CoconutError::Deserialization(e.to_string()))?;
|
||||||
eight_byte.copy_from_slice(&bytes[12 + theta_len as usize..20 + theta_len as usize]);
|
eight_byte.copy_from_slice(&bytes[12 + theta_len as usize..20 + theta_len as usize]);
|
||||||
let voucher_value = u64::from_be_bytes(eight_byte);
|
let voucher_value = u64::from_be_bytes(eight_byte);
|
||||||
let voucher_info = String::from_utf8(bytes[20 + theta_len as usize..].to_vec())
|
eight_byte.copy_from_slice(&bytes[20 + theta_len as usize..28 + theta_len as usize]);
|
||||||
|
let epoch_id = u64::from_be_bytes(eight_byte);
|
||||||
|
let voucher_info = String::from_utf8(bytes[28 + theta_len as usize..].to_vec())
|
||||||
.map_err(|e| CoconutError::Deserialization(e.to_string()))?;
|
.map_err(|e| CoconutError::Deserialization(e.to_string()))?;
|
||||||
|
|
||||||
Ok(Credential {
|
Ok(Credential {
|
||||||
@@ -111,6 +119,7 @@ impl Credential {
|
|||||||
theta,
|
theta,
|
||||||
voucher_value,
|
voucher_value,
|
||||||
voucher_info,
|
voucher_info,
|
||||||
|
epoch_id,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -166,7 +175,7 @@ mod tests {
|
|||||||
binding_number,
|
binding_number,
|
||||||
)
|
)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
let credential = Credential::new(4, theta, voucher_value, voucher_info);
|
let credential = Credential::new(4, theta, voucher_value, voucher_info, 42);
|
||||||
|
|
||||||
let serialized_credential = credential.as_bytes();
|
let serialized_credential = credential.as_bytes();
|
||||||
let deserialized_credential = Credential::from_bytes(&serialized_credential).unwrap();
|
let deserialized_credential = Credential::from_bytes(&serialized_credential).unwrap();
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "nym-cli-commands"
|
name = "nym-cli-commands"
|
||||||
version = "1.0.0"
|
version = "1.0.0"
|
||||||
authors = ["Nym Technologies SA"]
|
authors.workspace = true
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
@@ -15,7 +15,7 @@ cw-utils = { version = "0.13.4" }
|
|||||||
handlebars = "3.0.1"
|
handlebars = "3.0.1"
|
||||||
humantime-serde = "1.0"
|
humantime-serde = "1.0"
|
||||||
k256 = { version = "0.10", features = ["ecdsa", "sha256"] }
|
k256 = { version = "0.10", features = ["ecdsa", "sha256"] }
|
||||||
log = "0.4"
|
log = { workspace = true }
|
||||||
rand = {version = "0.6", features = ["std"] }
|
rand = {version = "0.6", features = ["std"] }
|
||||||
serde = { version = "1.0", features = ["derive"] }
|
serde = { version = "1.0", features = ["derive"] }
|
||||||
serde_json = "1"
|
serde_json = "1"
|
||||||
|
|||||||
@@ -80,7 +80,7 @@ pub fn create_signing_client(
|
|||||||
|
|
||||||
match NyxdClient::connect_with_mnemonic(client_config, nyxd_url, mnemonic, None) {
|
match NyxdClient::connect_with_mnemonic(client_config, nyxd_url, mnemonic, None) {
|
||||||
Ok(client) => Ok(client),
|
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) {
|
match NyxdClient::connect(client_config, nyxd_url) {
|
||||||
Ok(client) => Ok(client),
|
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) {
|
match validator_client::client::Client::new_signing(client_config, mnemonic) {
|
||||||
Ok(client) => Ok(client),
|
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) {
|
match validator_client::client::Client::new_query(client_config) {
|
||||||
Ok(client) => Ok(client),
|
Ok(client) => Ok(client),
|
||||||
Err(e) => Err(ContextError::NyxdError(format!("{:?}", e))),
|
Err(e) => Err(ContextError::NyxdError(format!("{e}"))),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user