Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 51576c2b3b | |||
| db8730d13a |
+4
-4
@@ -19,10 +19,10 @@
|
|||||||
Cargo.* @durch @futurechimp @jstuczyn @neacsu @octol
|
Cargo.* @durch @futurechimp @jstuczyn @neacsu @octol
|
||||||
|
|
||||||
# JS rules:
|
# JS rules:
|
||||||
*.js @mmsinclair @fmtabbara
|
*.js @mmsinclair @fmtabbara @Aid19801
|
||||||
*.ts @mmsinclair @fmtabbara
|
*.ts @mmsinclair @fmtabbara @Aid19801
|
||||||
*.tsx @mmsinclair @fmtabbara
|
*.tsx @mmsinclair @fmtabbara @Aid19801
|
||||||
*.jsx @mmsinclair @fmtabbara
|
*.jsx @mmsinclair @fmtabbara @Aid19801
|
||||||
|
|
||||||
# Something looking like possible documentation rules:
|
# Something looking like possible documentation rules:
|
||||||
*.md @mfahampshire
|
*.md @mfahampshire
|
||||||
|
|||||||
@@ -1,50 +0,0 @@
|
|||||||
[
|
|
||||||
{
|
|
||||||
"os":"ubuntu-latest",
|
|
||||||
"rust":"stable",
|
|
||||||
"runOnEvent":"workflow_dispatch"
|
|
||||||
},
|
|
||||||
|
|
||||||
{
|
|
||||||
"os":"windows-latest",
|
|
||||||
"rust":"stable",
|
|
||||||
"runOnEvent":"workflow_dispatch"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"os":"macos-latest",
|
|
||||||
"rust":"stable",
|
|
||||||
"runOnEvent":"workflow_dispatch"
|
|
||||||
},
|
|
||||||
|
|
||||||
{
|
|
||||||
"os":"ubuntu-latest",
|
|
||||||
"rust":"beta",
|
|
||||||
"runOnEvent":"workflow_dispatch"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"os":"windows-latest",
|
|
||||||
"rust":"beta",
|
|
||||||
"runOnEvent":"workflow_dispatch"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"os":"macos-latest",
|
|
||||||
"rust":"beta",
|
|
||||||
"runOnEvent":"workflow_dispatch"
|
|
||||||
},
|
|
||||||
|
|
||||||
{
|
|
||||||
"os":"ubuntu-latest",
|
|
||||||
"rust":"nightly",
|
|
||||||
"runOnEvent":"workflow_dispatch"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"os":"windows-latest",
|
|
||||||
"rust":"nightly",
|
|
||||||
"runOnEvent":"workflow_dispatch"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"os":"macos-latest",
|
|
||||||
"rust":"nightly",
|
|
||||||
"runOnEvent":"workflow_dispatch"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
@@ -1,174 +0,0 @@
|
|||||||
name: Nightly builds on dispatch
|
|
||||||
|
|
||||||
on: workflow_dispatch
|
|
||||||
jobs:
|
|
||||||
matrix_prep:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
outputs:
|
|
||||||
matrix: ${{ steps.set-matrix.outputs.matrix }}
|
|
||||||
steps:
|
|
||||||
# creates the matrix strategy from nightly_build_matrix_includes.json
|
|
||||||
- uses: actions/checkout@v2
|
|
||||||
- id: set-matrix
|
|
||||||
uses: JoshuaTheMiller/conditional-build-matrix@main
|
|
||||||
with:
|
|
||||||
inputFile: '.github/workflows/nightly_build_matrix_on_dispatch.json'
|
|
||||||
filter: '[?runOnEvent==`${{ github.event_name }}` || runOnEvent==`always`]'
|
|
||||||
build:
|
|
||||||
needs: matrix_prep
|
|
||||||
strategy:
|
|
||||||
matrix: ${{fromJson(needs.matrix_prep.outputs.matrix)}}
|
|
||||||
runs-on: ${{ matrix.os }}
|
|
||||||
continue-on-error: ${{ matrix.rust == 'nightly' || matrix.rust == 'beta' || matrix.rust == 'stable' }}
|
|
||||||
steps:
|
|
||||||
- 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 squashfs-tools
|
|
||||||
if: matrix.os == 'ubuntu-latest'
|
|
||||||
|
|
||||||
- name: Check out repository code
|
|
||||||
uses: actions/checkout@v2
|
|
||||||
|
|
||||||
- name: Install rust toolchain
|
|
||||||
uses: actions-rs/toolchain@v1
|
|
||||||
with:
|
|
||||||
profile: minimal
|
|
||||||
toolchain: ${{ matrix.rust }}
|
|
||||||
override: true
|
|
||||||
components: rustfmt, clippy
|
|
||||||
|
|
||||||
- name: Build all binaries
|
|
||||||
uses: actions-rs/cargo@v1
|
|
||||||
with:
|
|
||||||
command: build
|
|
||||||
args: --workspace
|
|
||||||
|
|
||||||
- name: Run all tests
|
|
||||||
uses: actions-rs/cargo@v1
|
|
||||||
with:
|
|
||||||
command: test
|
|
||||||
args: --workspace
|
|
||||||
|
|
||||||
- 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 expensive tests
|
|
||||||
if: github.ref == 'refs/heads/develop' || github.event.pull_request.base.ref == 'develop' || github.event.pull_request.base.ref == 'master'
|
|
||||||
uses: actions-rs/cargo@v1
|
|
||||||
with:
|
|
||||||
command: test
|
|
||||||
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)
|
|
||||||
uses: actions-rs/cargo@v1
|
|
||||||
if: ${{ matrix.os == 'windows-latest' }}
|
|
||||||
with:
|
|
||||||
command: clean
|
|
||||||
|
|
||||||
- uses: actions-rs/clippy-check@v1
|
|
||||||
name: Clippy checks
|
|
||||||
with:
|
|
||||||
token: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
args: --all-features
|
|
||||||
|
|
||||||
- name: Run clippy
|
|
||||||
uses: actions-rs/cargo@v1
|
|
||||||
if: ${{ matrix.rust != 'nightly' }}
|
|
||||||
with:
|
|
||||||
command: clippy
|
|
||||||
args: --workspace --all-targets -- -D warnings
|
|
||||||
|
|
||||||
- name: Reclaim some disk space
|
|
||||||
uses: actions-rs/cargo@v1
|
|
||||||
if: ${{ matrix.os == 'windows-latest' || matrix.os == 'ubuntu-latest' }}
|
|
||||||
with:
|
|
||||||
command: clean
|
|
||||||
|
|
||||||
# COCONUT stuff
|
|
||||||
- name: Build all binaries with coconut enabled
|
|
||||||
uses: actions-rs/cargo@v1
|
|
||||||
with:
|
|
||||||
command: build
|
|
||||||
args: --workspace --features=coconut
|
|
||||||
|
|
||||||
- name: Run all tests with coconut enabled
|
|
||||||
uses: actions-rs/cargo@v1
|
|
||||||
with:
|
|
||||||
command: test
|
|
||||||
args: --workspace --features=coconut
|
|
||||||
|
|
||||||
- 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 clippy with coconut enabled
|
|
||||||
uses: actions-rs/cargo@v1
|
|
||||||
if: ${{ matrix.rust != 'nightly' }}
|
|
||||||
with:
|
|
||||||
command: clippy
|
|
||||||
args: --workspace --all-targets --features=coconut -- -D warnings
|
|
||||||
|
|
||||||
# nym-wallet (the rust part)
|
|
||||||
- name: Build nym-wallet rust code
|
|
||||||
uses: actions-rs/cargo@v1
|
|
||||||
with:
|
|
||||||
command: build
|
|
||||||
args: --manifest-path nym-wallet/Cargo.toml --workspace
|
|
||||||
|
|
||||||
- name: Run nym-wallet tests
|
|
||||||
uses: actions-rs/cargo@v1
|
|
||||||
with:
|
|
||||||
command: test
|
|
||||||
args: --manifest-path nym-wallet/Cargo.toml --workspace
|
|
||||||
|
|
||||||
- name: Check nym-wallet formatting
|
|
||||||
uses: actions-rs/cargo@v1
|
|
||||||
with:
|
|
||||||
command: fmt
|
|
||||||
args: --manifest-path nym-wallet/Cargo.toml --all -- --check
|
|
||||||
|
|
||||||
- name: Run clippy for nym-wallet
|
|
||||||
uses: actions-rs/cargo@v1
|
|
||||||
if: ${{ matrix.rust != 'nightly' }}
|
|
||||||
with:
|
|
||||||
command: clippy
|
|
||||||
args: --manifest-path nym-wallet/Cargo.toml --workspace --all-targets -- -D warnings
|
|
||||||
|
|
||||||
notification:
|
|
||||||
needs: build
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- name: Collect jobs status
|
|
||||||
uses: technote-space/workflow-conclusion-action@v2
|
|
||||||
- name: Check out repository code
|
|
||||||
uses: actions/checkout@v2
|
|
||||||
- name: Keybase - Node Install
|
|
||||||
if: env.WORKFLOW_CONCLUSION == 'failure'
|
|
||||||
run: npm install
|
|
||||||
working-directory: .github/workflows/support-files
|
|
||||||
- name: Keybase - Send Notification
|
|
||||||
if: env.WORKFLOW_CONCLUSION == 'failure'
|
|
||||||
env:
|
|
||||||
NYM_NOTIFICATION_KIND: nightly
|
|
||||||
NYM_PROJECT_NAME: "Nym nightly build"
|
|
||||||
GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}"
|
|
||||||
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-nightly"
|
|
||||||
IS_SUCCESS: "${{ env.WORKFLOW_CONCLUSION == 'success' }}"
|
|
||||||
uses: docker://keybaseio/client:stable-node
|
|
||||||
with:
|
|
||||||
args: .github/workflows/support-files/notifications/entry_point.sh
|
|
||||||
+3
-18
@@ -9,9 +9,6 @@ Post 1.0.0 release, the changelog format is based on [Keep a Changelog](https://
|
|||||||
|
|
||||||
- socks5 client/websocket client: add `--force-register-gateway` flag, useful when rerunning init ([#1353])
|
- socks5 client/websocket client: add `--force-register-gateway` flag, useful when rerunning init ([#1353])
|
||||||
- nym-connect: initial proof-of-concept of a UI around the socks5 client was added
|
- nym-connect: initial proof-of-concept of a UI around the socks5 client was added
|
||||||
- nym-connect: add ability to select network requester and gateway ([#1427])
|
|
||||||
- nym-connect: add ability to export gateway keys as JSON
|
|
||||||
- nym-connect: add auto updater
|
|
||||||
- all: added network compilation target to `--help` (or `--version`) commands ([#1256]).
|
- all: added network compilation target to `--help` (or `--version`) commands ([#1256]).
|
||||||
- explorer-api: learned how to sum the delegations by owner in a new endpoint.
|
- explorer-api: learned how to sum the delegations by owner in a new endpoint.
|
||||||
- explorer-api: add apy values to `mix_nodes` endpoint
|
- explorer-api: add apy values to `mix_nodes` endpoint
|
||||||
@@ -24,15 +21,14 @@ Post 1.0.0 release, the changelog format is based on [Keep a Changelog](https://
|
|||||||
- validator-api: Added new endpoints for coconut spending flow and communications with coconut & multisig contracts ([#1261])
|
- validator-api: Added new endpoints for coconut spending flow and communications with coconut & multisig contracts ([#1261])
|
||||||
- validator-api: add `uptime`, `estimated_operator_apy`, `estimated_delegators_apy` to `/mixnodes/detailed` endpoint ([#1393])
|
- validator-api: add `uptime`, `estimated_operator_apy`, `estimated_delegators_apy` to `/mixnodes/detailed` endpoint ([#1393])
|
||||||
- network-statistics: a new mixnet service that aggregates and exposes anonymized data about mixnet services ([#1328])
|
- network-statistics: a new mixnet service that aggregates and exposes anonymized data about mixnet services ([#1328])
|
||||||
|
- wallet: when simulating gas costs, an automatic adjustment is being used ([#1388]).
|
||||||
- mixnode: Added basic mixnode hardware reporting to the HTTP API ([#1308]).
|
- mixnode: Added basic mixnode hardware reporting to the HTTP API ([#1308]).
|
||||||
- validator-api: endpoint, in coconut mode, for returning the validator-api cosmos address ([#1404]).
|
- validator-api: endpoint, in coconut mode, for returning the validator-api cosmos address ([#1404]).
|
||||||
- validator-client: add `denom` argument and add simple test for querying an account balance
|
|
||||||
|
|
||||||
### Fixed
|
### Fixed
|
||||||
|
|
||||||
- mixnode, gateway: attempting to determine reconnection backoff to persistently failing mixnode could result in a crash ([#1260])
|
- mixnode, gateway: attempting to determine reconnection backoff to persistently failing mixnode could result in a crash ([#1260])
|
||||||
- mixnode: the mixnode learned how to shutdown gracefully
|
- mixnode: the mixnode learned how to shutdown gracefully
|
||||||
- mixnode: listen out for SIGTERM and SIGQUIT too, making it play nicely as a system service.
|
|
||||||
- native & socks5 clients: fail early when clients try to re-init with a different gateway, which is not supported yet ([#1322])
|
- native & socks5 clients: fail early when clients try to re-init with a different gateway, which is not supported yet ([#1322])
|
||||||
- native & socks5 clients: rerun init will now reuse previous gateway configuration instead of failing ([#1353])
|
- native & socks5 clients: rerun init will now reuse previous gateway configuration instead of failing ([#1353])
|
||||||
- native & socks5 clients: deduplicate big chunks of init logic
|
- native & socks5 clients: deduplicate big chunks of init logic
|
||||||
@@ -40,15 +36,12 @@ Post 1.0.0 release, the changelog format is based on [Keep a Changelog](https://
|
|||||||
|
|
||||||
### Changed
|
### Changed
|
||||||
|
|
||||||
- nym-connect: reuse config id instead of creating a new id on each connection
|
- nym-connect: reuse config id instead of creating a new id on each connection.
|
||||||
- validator-client: created internal `Coin` type that replaces coins from `cosmrs` and `cosmwasm` for API entrypoints [[#1295]]
|
- validator-client: created internal `Coin` type that replaces coins from `cosmrs` and `cosmwasm` for API entrypoints [[#1295]]
|
||||||
- all: updated all `cosmwasm`-related dependencies to `1.0.0` and `cw-storage-plus` to `0.13.4` [[#1318]]
|
- all: updated all `cosmwasm`-related dependencies to `1.0.0` and `cw-storage-plus` to `0.13.4` [[#1318]]
|
||||||
- all: updated `rocket` to `0.5.0-rc.2`.
|
- all: updated `rocket` to `0.5.0-rc.2`.
|
||||||
- network-requester: allow to voluntarily store and send statistical data about the number of bytes the proxied server serves ([#1328])
|
- network-requester: allow to voluntarily store and send statistical data about the number of bytes the proxied server serves ([#1328])
|
||||||
- gateway: allow to voluntarily send statistical data about the number of active inboxes served by a gateway ([#1376])
|
- gateway: allow to voluntarily send statistical data about the number of active inboxes served by a gateway ([#1376])
|
||||||
- gateway & mixnode: move detailed build info back to `--version` from `--help`.
|
|
||||||
- socks5 client/websocket client: upgrade to latest clap and switched to declarative commandline parsing.
|
|
||||||
- validator-api: fee payment for multisig operations comes from the gateway account instead of the validator APIs' accounts ([#1419])
|
|
||||||
|
|
||||||
[#1249]: https://github.com/nymtech/nym/pull/1249
|
[#1249]: https://github.com/nymtech/nym/pull/1249
|
||||||
[#1256]: https://github.com/nymtech/nym/pull/1256
|
[#1256]: https://github.com/nymtech/nym/pull/1256
|
||||||
@@ -66,17 +59,9 @@ Post 1.0.0 release, the changelog format is based on [Keep a Changelog](https://
|
|||||||
[#1329]: https://github.com/nymtech/nym/pull/1329
|
[#1329]: https://github.com/nymtech/nym/pull/1329
|
||||||
[#1353]: https://github.com/nymtech/nym/pull/1353
|
[#1353]: https://github.com/nymtech/nym/pull/1353
|
||||||
[#1376]: https://github.com/nymtech/nym/pull/1376
|
[#1376]: https://github.com/nymtech/nym/pull/1376
|
||||||
|
[#1388]: https://github.com/nymtech/nym/pull/1388
|
||||||
[#1393]: https://github.com/nymtech/nym/pull/1393
|
[#1393]: https://github.com/nymtech/nym/pull/1393
|
||||||
[#1404]: https://github.com/nymtech/nym/pull/1404
|
[#1404]: https://github.com/nymtech/nym/pull/1404
|
||||||
[#1419]: https://github.com/nymtech/nym/pull/1419
|
|
||||||
[#1427]: https://github.com/nymtech/nym/pull/1427
|
|
||||||
|
|
||||||
## [nym-wallet-v1.0.7](https://github.com/nymtech/nym/tree/nym-wallet-v1.0.7) (2022-07-11)
|
|
||||||
|
|
||||||
- wallet: dark mode
|
|
||||||
- wallet: when simulating gas costs, an automatic adjustment is being used ([#1388]).
|
|
||||||
|
|
||||||
[#1388]: https://github.com/nymtech/nym/pull/1388
|
|
||||||
|
|
||||||
## [nym-contracts-v1.0.1](https://github.com/nymtech/nym/tree/nym-contracts-v1.0.1) (2022-06-22)
|
## [nym-contracts-v1.0.1](https://github.com/nymtech/nym/tree/nym-contracts-v1.0.1) (2022-06-22)
|
||||||
|
|
||||||
|
|||||||
Generated
+47
-28
@@ -568,16 +568,16 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "clap"
|
name = "clap"
|
||||||
version = "3.2.8"
|
version = "3.1.8"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "190814073e85d238f31ff738fcb0bf6910cedeb73376c87cd69291028966fd83"
|
checksum = "71c47df61d9e16dc010b55dba1952a57d8c215dbb533fd13cdd13369aac73b1c"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"atty",
|
"atty",
|
||||||
"bitflags",
|
"bitflags",
|
||||||
"clap_derive",
|
"clap_derive",
|
||||||
"clap_lex",
|
|
||||||
"indexmap",
|
"indexmap",
|
||||||
"once_cell",
|
"lazy_static",
|
||||||
|
"os_str_bytes",
|
||||||
"strsim 0.10.0",
|
"strsim 0.10.0",
|
||||||
"termcolor",
|
"termcolor",
|
||||||
"textwrap 0.15.0",
|
"textwrap 0.15.0",
|
||||||
@@ -585,9 +585,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "clap_derive"
|
name = "clap_derive"
|
||||||
version = "3.2.7"
|
version = "3.1.7"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "759bf187376e1afa7b85b959e6a664a3e7a95203415dba952ad19139e798f902"
|
checksum = "a3aab4734e083b809aaf5794e14e756d1c798d2c69c7f7de7a09a2f5214993c1"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"heck 0.4.0",
|
"heck 0.4.0",
|
||||||
"proc-macro-error",
|
"proc-macro-error",
|
||||||
@@ -596,15 +596,6 @@ dependencies = [
|
|||||||
"syn",
|
"syn",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "clap_lex"
|
|
||||||
version = "0.2.4"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "2850f2f5a82cbf437dd5af4d49848fbdfc27c157c3d010345776f952765261c5"
|
|
||||||
dependencies = [
|
|
||||||
"os_str_bytes",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "client-core"
|
name = "client-core"
|
||||||
version = "1.0.1"
|
version = "1.0.1"
|
||||||
@@ -782,8 +773,9 @@ checksum = "5827cebf4670468b8772dd191856768aedcb1b0278a04f989f7766351917b9dc"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "cosmos-sdk-proto"
|
name = "cosmos-sdk-proto"
|
||||||
version = "0.12.3"
|
version = "0.12.2"
|
||||||
source = "git+https://github.com/neacsu/cosmos-rust?branch=neacsu/feegrant_support#f63ded63ec13e753ebe8bdafe9dc503df265d67d"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "f109fe191e73898d74b8020c50f86018364ad19bc30318aa074616c382b52856"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"prost 0.10.3",
|
"prost 0.10.3",
|
||||||
"prost-types 0.10.1",
|
"prost-types 0.10.1",
|
||||||
@@ -792,8 +784,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "cosmrs"
|
name = "cosmrs"
|
||||||
version = "0.7.1"
|
version = "0.7.0"
|
||||||
source = "git+https://github.com/neacsu/cosmos-rust?branch=neacsu/feegrant_support#f63ded63ec13e753ebe8bdafe9dc503df265d67d"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "8413275b23cb5a0734d9d1e3e33f0b5b94547c1e94776dbc3149dbf46588a533"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"bip32",
|
"bip32",
|
||||||
"cosmos-sdk-proto",
|
"cosmos-sdk-proto",
|
||||||
@@ -891,7 +884,7 @@ dependencies = [
|
|||||||
"async-trait",
|
"async-trait",
|
||||||
"bip39",
|
"bip39",
|
||||||
"cfg-if 0.1.10",
|
"cfg-if 0.1.10",
|
||||||
"clap 3.2.8",
|
"clap 3.1.8",
|
||||||
"coconut-interface",
|
"coconut-interface",
|
||||||
"credential-storage",
|
"credential-storage",
|
||||||
"credentials",
|
"credentials",
|
||||||
@@ -1350,9 +1343,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "dirs"
|
name = "dirs"
|
||||||
version = "4.0.0"
|
version = "3.0.2"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "ca3aa72a6f96ea37bbc5aa912f6788242832f75369bdfdadcb0e38423f100059"
|
checksum = "30baa043103c9d0c2a57cf537cc2f35623889dc0d405e6c3cccfadbc81c71309"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"dirs-sys",
|
"dirs-sys",
|
||||||
]
|
]
|
||||||
@@ -3056,7 +3049,7 @@ dependencies = [
|
|||||||
name = "nym-client"
|
name = "nym-client"
|
||||||
version = "1.0.1"
|
version = "1.0.1"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"clap 3.2.8",
|
"clap 2.34.0",
|
||||||
"client-core",
|
"client-core",
|
||||||
"coconut-interface",
|
"coconut-interface",
|
||||||
"config",
|
"config",
|
||||||
@@ -3096,7 +3089,7 @@ dependencies = [
|
|||||||
"bandwidth-claim-contract",
|
"bandwidth-claim-contract",
|
||||||
"bip39",
|
"bip39",
|
||||||
"bs58",
|
"bs58",
|
||||||
"clap 3.2.8",
|
"clap 3.1.8",
|
||||||
"coconut-interface",
|
"coconut-interface",
|
||||||
"colored",
|
"colored",
|
||||||
"config",
|
"config",
|
||||||
@@ -3141,7 +3134,7 @@ version = "1.0.1"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"bs58",
|
"bs58",
|
||||||
"clap 3.2.8",
|
"clap 3.1.8",
|
||||||
"colored",
|
"colored",
|
||||||
"config",
|
"config",
|
||||||
"crypto",
|
"crypto",
|
||||||
@@ -3163,6 +3156,7 @@ dependencies = [
|
|||||||
"rand 0.7.3",
|
"rand 0.7.3",
|
||||||
"rocket",
|
"rocket",
|
||||||
"serde",
|
"serde",
|
||||||
|
"serial_test",
|
||||||
"sysinfo",
|
"sysinfo",
|
||||||
"task",
|
"task",
|
||||||
"tokio",
|
"tokio",
|
||||||
@@ -3223,7 +3217,7 @@ dependencies = [
|
|||||||
name = "nym-socks5-client"
|
name = "nym-socks5-client"
|
||||||
version = "1.0.1"
|
version = "1.0.1"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"clap 3.2.8",
|
"clap 2.34.0",
|
||||||
"client-core",
|
"client-core",
|
||||||
"coconut-interface",
|
"coconut-interface",
|
||||||
"config",
|
"config",
|
||||||
@@ -3507,9 +3501,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "once_cell"
|
name = "once_cell"
|
||||||
version = "1.13.0"
|
version = "1.10.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "18a6dbe30758c9f83eb00cbea4ac95966305f5a7772f3f42ebfc7fc7eddbd8e1"
|
checksum = "87f3e037eac156d1775da914196f0f37741a274155e34a0b7e427c35d2a2ecb9"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "oorandom"
|
name = "oorandom"
|
||||||
@@ -3574,6 +3568,9 @@ name = "os_str_bytes"
|
|||||||
version = "6.0.0"
|
version = "6.0.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "8e22443d1643a904602595ba1cd8f7d896afe56d26712531c5ff73a15b2fbf64"
|
checksum = "8e22443d1643a904602595ba1cd8f7d896afe56d26712531c5ff73a15b2fbf64"
|
||||||
|
dependencies = [
|
||||||
|
"memchr",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "pairing"
|
name = "pairing"
|
||||||
@@ -5022,6 +5019,28 @@ dependencies = [
|
|||||||
"yaml-rust",
|
"yaml-rust",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "serial_test"
|
||||||
|
version = "0.5.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "e0bccbcf40c8938196944a3da0e133e031a33f4d6b72db3bda3cc556e361905d"
|
||||||
|
dependencies = [
|
||||||
|
"lazy_static",
|
||||||
|
"parking_lot 0.11.2",
|
||||||
|
"serial_test_derive",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "serial_test_derive"
|
||||||
|
version = "0.5.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "b2acd6defeddb41eb60bb468f8825d0cfd0c2a76bc03bfd235b6a1dc4f6a1ad5"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"syn",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "sha-1"
|
name = "sha-1"
|
||||||
version = "0.8.2"
|
version = "0.8.2"
|
||||||
|
|||||||
+1
-1
@@ -81,4 +81,4 @@ default-members = [
|
|||||||
"explorer-api",
|
"explorer-api",
|
||||||
]
|
]
|
||||||
|
|
||||||
exclude = ["explorer", "contracts", "tokenomics-py", "clients/webassembly", "nym-wallet", "nym-connect"]
|
exclude = ["explorer", "contracts", "tokenomics-py", "clients/webassembly", "nym-wallet"]
|
||||||
|
|||||||
@@ -9,8 +9,8 @@ The platform is composed of multiple Rust crates. Top-level executable binary cr
|
|||||||
|
|
||||||
* nym-mixnode - shuffles [Sphinx](https://github.com/nymtech/sphinx) packets together to provide privacy against network-level attackers.
|
* nym-mixnode - shuffles [Sphinx](https://github.com/nymtech/sphinx) packets together to provide privacy against network-level attackers.
|
||||||
* nym-client - an executable which you can build into your own applications. Use it for interacting with Nym nodes.
|
* nym-client - an executable which you can build into your own applications. Use it for interacting with Nym nodes.
|
||||||
* nym-socks5-client - a Socks5 proxy you can run on your machine and use with existing applications.
|
* nym-socks5-client - a Socks5 proxy you can run on your machine, and use with existing applications
|
||||||
* nym-gateway - acts sort of like a mailbox for mixnet messages, which removes the need for direct delivery to potentially offline or firewalled devices.
|
* nym-gateway - acts sort of like a mailbox for mixnet messages, removing the need for directly delivery to potentially offline or firewalled devices.
|
||||||
* nym-network-monitor - sends packets through the full system to check that they are working as expected, and stores node uptime histories as the basis of a rewards system ("mixmining" or "proof-of-mixing").
|
* nym-network-monitor - sends packets through the full system to check that they are working as expected, and stores node uptime histories as the basis of a rewards system ("mixmining" or "proof-of-mixing").
|
||||||
* nym-explorer - a (projected) block explorer and (existing) mixnet viewer.
|
* nym-explorer - a (projected) block explorer and (existing) mixnet viewer.
|
||||||
* nym-wallet - a desktop wallet implemented using the [Tauri](https://tauri.studio/en/docs/about/intro) framework.
|
* nym-wallet - a desktop wallet implemented using the [Tauri](https://tauri.studio/en/docs/about/intro) framework.
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ edition = "2021"
|
|||||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
dirs = "4.0"
|
dirs = "3.0"
|
||||||
futures = "0.3"
|
futures = "0.3"
|
||||||
humantime-serde = "1.0"
|
humantime-serde = "1.0"
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
|
|||||||
@@ -272,7 +272,7 @@ impl<T: NymConfig> Default for Config<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Eq, Serialize)]
|
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
|
||||||
pub struct GatewayEndpoint {
|
pub struct GatewayEndpoint {
|
||||||
/// gateway_id specifies ID of the gateway to which the client should send messages.
|
/// gateway_id specifies ID of the gateway to which the client should send messages.
|
||||||
/// If initially omitted, a random gateway will be chosen from the available topology.
|
/// If initially omitted, a random gateway will be chosen from the available topology.
|
||||||
@@ -296,7 +296,7 @@ impl From<topology::gateway::Node> for GatewayEndpoint {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Deserialize, PartialEq, Eq, Serialize)]
|
#[derive(Debug, Deserialize, PartialEq, Serialize)]
|
||||||
pub struct Client<T> {
|
pub struct Client<T> {
|
||||||
/// Version of the client for which this configuration was created.
|
/// Version of the client for which this configuration was created.
|
||||||
#[serde(default = "missing_string_value")]
|
#[serde(default = "missing_string_value")]
|
||||||
@@ -419,7 +419,7 @@ impl<T: NymConfig> Client<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Default, Deserialize, PartialEq, Eq, Serialize)]
|
#[derive(Debug, Default, Deserialize, PartialEq, Serialize)]
|
||||||
#[serde(deny_unknown_fields)]
|
#[serde(deny_unknown_fields)]
|
||||||
pub struct Logging {}
|
pub struct Logging {}
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,6 @@
|
|||||||
name = "nym-client"
|
name = "nym-client"
|
||||||
version = "1.0.1"
|
version = "1.0.1"
|
||||||
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"
|
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
rust-version = "1.56"
|
rust-version = "1.56"
|
||||||
|
|
||||||
@@ -20,8 +19,8 @@ futures = "0.3" # bunch of futures stuff, however, now that I think about it, it
|
|||||||
# and the single instance of abortable we have should really be refactored anyway
|
# and the single instance of abortable we have should really be refactored anyway
|
||||||
url = "2.2"
|
url = "2.2"
|
||||||
|
|
||||||
clap = { version = "3.2.8", features = ["cargo", "derive"] }
|
clap = "2.33.0" # for the command line arguments
|
||||||
dirs = "4.0"
|
dirs = "3.0" # for determining default store directories in config
|
||||||
dotenv = "0.15.0" # for obtaining environmental variables (only used for RUST_LOG for time being)
|
dotenv = "0.15.0" # for obtaining environmental variables (only used for RUST_LOG for time being)
|
||||||
log = "0.4" # self explanatory
|
log = "0.4" # self explanatory
|
||||||
pretty_env_logger = "0.4" # for formatting log messages
|
pretty_env_logger = "0.4" # for formatting log messages
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ use std::path::PathBuf;
|
|||||||
|
|
||||||
mod template;
|
mod template;
|
||||||
|
|
||||||
#[derive(Debug, Deserialize, PartialEq, Eq, Serialize, Clone, Copy)]
|
#[derive(Debug, Deserialize, PartialEq, Serialize, Clone, Copy)]
|
||||||
#[serde(deny_unknown_fields)]
|
#[serde(deny_unknown_fields)]
|
||||||
pub enum SocketType {
|
pub enum SocketType {
|
||||||
WebSocket,
|
WebSocket,
|
||||||
@@ -105,7 +105,7 @@ impl Config {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Deserialize, PartialEq, Eq, Serialize)]
|
#[derive(Debug, Deserialize, PartialEq, Serialize)]
|
||||||
#[serde(deny_unknown_fields)]
|
#[serde(deny_unknown_fields)]
|
||||||
pub struct Socket {
|
pub struct Socket {
|
||||||
socket_type: SocketType,
|
socket_type: SocketType,
|
||||||
|
|||||||
@@ -1,100 +1,88 @@
|
|||||||
// 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
|
||||||
|
|
||||||
use clap::Args;
|
use clap::{App, Arg, ArgMatches};
|
||||||
use client_core::config::GatewayEndpoint;
|
use client_core::config::GatewayEndpoint;
|
||||||
use config::NymConfig;
|
use config::NymConfig;
|
||||||
|
|
||||||
use crate::{
|
use crate::client::config::Config;
|
||||||
client::config::Config,
|
use crate::commands::override_config;
|
||||||
commands::{override_config, OverrideConfig},
|
#[cfg(feature = "eth")]
|
||||||
|
#[cfg(not(feature = "coconut"))]
|
||||||
|
use crate::commands::{
|
||||||
|
DEFAULT_ETH_ENDPOINT, DEFAULT_ETH_PRIVATE_KEY, ENABLED_CREDENTIALS_MODE_ARG_NAME,
|
||||||
|
ETH_ENDPOINT_ARG_NAME, ETH_PRIVATE_KEY_ARG_NAME,
|
||||||
};
|
};
|
||||||
|
|
||||||
#[cfg(all(feature = "eth", not(feature = "coconut")))]
|
pub fn command_args<'a, 'b>() -> clap::App<'a, 'b> {
|
||||||
use crate::commands::{DEFAULT_ETH_ENDPOINT, DEFAULT_ETH_PRIVATE_KEY};
|
let app = App::new("init")
|
||||||
|
.about("Initialise a Nym client. Do this first!")
|
||||||
|
.arg(Arg::with_name("id")
|
||||||
|
.long("id")
|
||||||
|
.help("Id of the nym-mixnet-client we want to create config for.")
|
||||||
|
.takes_value(true)
|
||||||
|
.required(true)
|
||||||
|
)
|
||||||
|
.arg(Arg::with_name("gateway")
|
||||||
|
.long("gateway")
|
||||||
|
.help("Id of the gateway we are going to connect to.")
|
||||||
|
.takes_value(true)
|
||||||
|
)
|
||||||
|
.arg(Arg::with_name("force-register-gateway")
|
||||||
|
.long("force-register-gateway")
|
||||||
|
.help("Force register gateway. WARNING: this will overwrite any existing keys for the given id, potentially causing loss of access.")
|
||||||
|
.takes_value(false)
|
||||||
|
)
|
||||||
|
.arg(Arg::with_name("validators")
|
||||||
|
.long("validators")
|
||||||
|
.help("Comma separated list of rest endpoints of the validators")
|
||||||
|
.takes_value(true),
|
||||||
|
)
|
||||||
|
.arg(Arg::with_name("disable-socket")
|
||||||
|
.long("disable-socket")
|
||||||
|
.help("Whether to not start the websocket")
|
||||||
|
)
|
||||||
|
.arg(Arg::with_name("port")
|
||||||
|
.short("p")
|
||||||
|
.long("port")
|
||||||
|
.help("Port for the socket (if applicable) to listen on in all subsequent runs")
|
||||||
|
.takes_value(true)
|
||||||
|
)
|
||||||
|
.arg(Arg::with_name("fastmode")
|
||||||
|
.long("fastmode")
|
||||||
|
.hidden(true) // this will prevent this flag from being displayed in `--help`
|
||||||
|
.help("Mostly debug-related option to increase default traffic rate so that you would not need to modify config post init")
|
||||||
|
);
|
||||||
|
#[cfg(feature = "eth")]
|
||||||
|
#[cfg(not(feature = "coconut"))]
|
||||||
|
let app = app
|
||||||
|
.arg(
|
||||||
|
Arg::with_name(ENABLED_CREDENTIALS_MODE_ARG_NAME)
|
||||||
|
.long(ENABLED_CREDENTIALS_MODE_ARG_NAME)
|
||||||
|
.help("Set this client to work in a disabled credentials mode that would attempt to use gateway without bandwidth credential requirement. If this value is set, --eth_endpoint and --eth_private_key don't need to be set.")
|
||||||
|
.conflicts_with_all(&[ETH_ENDPOINT_ARG_NAME, ETH_PRIVATE_KEY_ARG_NAME])
|
||||||
|
)
|
||||||
|
.arg(Arg::with_name(ETH_ENDPOINT_ARG_NAME)
|
||||||
|
.long(ETH_ENDPOINT_ARG_NAME)
|
||||||
|
.help("URL of an Ethereum full node that we want to use for getting bandwidth tokens from ERC20 tokens. If you don't want to set this value, use --testnet-mode instead")
|
||||||
|
.takes_value(true)
|
||||||
|
.default_value_if(ENABLED_CREDENTIALS_MODE_ARG_NAME, None, DEFAULT_ETH_ENDPOINT)
|
||||||
|
.required(true))
|
||||||
|
.arg(Arg::with_name(ETH_PRIVATE_KEY_ARG_NAME)
|
||||||
|
.long(ETH_PRIVATE_KEY_ARG_NAME)
|
||||||
|
.help("Ethereum private key used for obtaining bandwidth tokens from ERC20 tokens. If you don't want to set this value, use --testnet-mode instead")
|
||||||
|
.takes_value(true)
|
||||||
|
.default_value_if(ENABLED_CREDENTIALS_MODE_ARG_NAME, None, DEFAULT_ETH_PRIVATE_KEY)
|
||||||
|
.required(true)
|
||||||
|
);
|
||||||
|
|
||||||
#[derive(Args, Clone)]
|
app
|
||||||
pub(crate) struct Init {
|
|
||||||
/// Id of the nym-mixnet-client we want to create config for.
|
|
||||||
#[clap(long)]
|
|
||||||
id: String,
|
|
||||||
|
|
||||||
/// Id of the gateway we are going to connect to.
|
|
||||||
#[clap(long)]
|
|
||||||
gateway: Option<String>,
|
|
||||||
|
|
||||||
/// Force register gateway. WARNING: this will overwrite any existing keys for the given id,
|
|
||||||
/// potentially causing loss of access.
|
|
||||||
#[clap(long)]
|
|
||||||
force_register_gateway: bool,
|
|
||||||
|
|
||||||
/// Comma separated list of rest endpoints of the validators
|
|
||||||
#[clap(long)]
|
|
||||||
validators: Option<String>,
|
|
||||||
|
|
||||||
/// Whether to not start the websocket
|
|
||||||
#[clap(long)]
|
|
||||||
disable_socket: bool,
|
|
||||||
|
|
||||||
/// Port for the socket (if applicable) to listen on in all subsequent runs
|
|
||||||
#[clap(short, long)]
|
|
||||||
port: Option<u16>,
|
|
||||||
|
|
||||||
/// Mostly debug-related option to increase default traffic rate so that you would not need to
|
|
||||||
/// modify config post init
|
|
||||||
#[clap(long, hidden = true)]
|
|
||||||
fastmode: bool,
|
|
||||||
|
|
||||||
/// Set this client to work in a enabled credentials mode that would attempt to use gateway
|
|
||||||
/// with bandwidth credential requirement. If this value is set, --eth-endpoint and
|
|
||||||
/// --eth-private_key don't need to be set.
|
|
||||||
#[cfg(all(feature = "eth", not(feature = "coconut")))]
|
|
||||||
#[clap(long, conflicts_with_all = &["eth-endpoint", "eth-private-key"])]
|
|
||||||
enabled_credentials_mode: bool,
|
|
||||||
|
|
||||||
/// URL of an Ethereum full node that we want to use for getting bandwidth tokens from ERC20
|
|
||||||
/// tokens. If you don't want to set this value, use --enabled-credentials-mode instead
|
|
||||||
#[cfg(all(feature = "eth", not(feature = "coconut")))]
|
|
||||||
#[clap(
|
|
||||||
long,
|
|
||||||
default_value_if("enabled-credentials-mode", None, Some(DEFAULT_ETH_ENDPOINT))
|
|
||||||
)]
|
|
||||||
eth_endpoint: String,
|
|
||||||
|
|
||||||
/// Ethereum private key used for obtaining bandwidth tokens from ERC20 tokens. If you don't
|
|
||||||
/// want to set this value, use --enabled-credentials-mode instead")
|
|
||||||
#[cfg(all(feature = "eth", not(feature = "coconut")))]
|
|
||||||
#[clap(
|
|
||||||
long,
|
|
||||||
default_value_if("enabled-credentials-mode", None, Some(DEFAULT_ETH_PRIVATE_KEY))
|
|
||||||
)]
|
|
||||||
eth_private_key: String,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<Init> for OverrideConfig {
|
pub async fn execute(matches: ArgMatches<'static>) {
|
||||||
fn from(init_config: Init) -> Self {
|
|
||||||
OverrideConfig {
|
|
||||||
validators: init_config.validators,
|
|
||||||
disable_socket: init_config.disable_socket,
|
|
||||||
port: init_config.port,
|
|
||||||
fastmode: init_config.fastmode,
|
|
||||||
|
|
||||||
#[cfg(all(feature = "eth", not(feature = "coconut")))]
|
|
||||||
enabled_credentials_mode: init_config.enabled_credentials_mode,
|
|
||||||
|
|
||||||
#[cfg(all(feature = "eth", not(feature = "coconut")))]
|
|
||||||
eth_private_key: Some(init_config.eth_private_key),
|
|
||||||
|
|
||||||
#[cfg(all(feature = "eth", not(feature = "coconut")))]
|
|
||||||
eth_endpoint: Some(init_config.eth_endpoint),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) async fn execute(args: &Init) {
|
|
||||||
println!("Initialising client...");
|
println!("Initialising client...");
|
||||||
|
|
||||||
let id = &args.id;
|
let id = matches.value_of("id").unwrap(); // required for now
|
||||||
|
|
||||||
let already_init = Config::default_config_file_path(Some(id)).exists();
|
let already_init = Config::default_config_file_path(Some(id)).exists();
|
||||||
if already_init {
|
if already_init {
|
||||||
@@ -107,7 +95,7 @@ pub(crate) async fn execute(args: &Init) {
|
|||||||
|
|
||||||
// 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 = matches.is_present("force-register-gateway");
|
||||||
|
|
||||||
// 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).
|
||||||
@@ -115,11 +103,14 @@ pub(crate) async fn execute(args: &Init) {
|
|||||||
let register_gateway = !already_init || user_wants_force_register;
|
let register_gateway = !already_init || user_wants_force_register;
|
||||||
|
|
||||||
// Attempt to use a user-provided gateway, if possible
|
// Attempt to use a user-provided gateway, if possible
|
||||||
let user_chosen_gateway_id = args.gateway.as_deref();
|
let user_chosen_gateway_id = matches.value_of("gateway");
|
||||||
|
|
||||||
let mut config = Config::new(id);
|
let mut config = Config::new(id);
|
||||||
let override_config_fields = OverrideConfig::from(args.clone());
|
|
||||||
config = override_config(config, override_config_fields);
|
config = override_config(config, &matches);
|
||||||
|
if matches.is_present("fastmode") {
|
||||||
|
config.get_base_mut().set_high_default_traffic_volume();
|
||||||
|
}
|
||||||
|
|
||||||
let gateway = setup_gateway(id, register_gateway, user_chosen_gateway_id, &config).await;
|
let gateway = setup_gateway(id, register_gateway, user_chosen_gateway_id, &config).await;
|
||||||
config.get_base_mut().with_gateway_endpoint(gateway);
|
config.get_base_mut().with_gateway_endpoint(gateway);
|
||||||
|
|||||||
@@ -2,10 +2,14 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
|
||||||
use crate::client::config::{Config, SocketType};
|
use crate::client::config::{Config, SocketType};
|
||||||
use clap::{Parser, Subcommand};
|
use clap::ArgMatches;
|
||||||
use network_defaults::DEFAULT_NETWORK;
|
|
||||||
use url::Url;
|
use url::Url;
|
||||||
|
|
||||||
|
pub(crate) const ENABLED_CREDENTIALS_MODE_ARG_NAME: &str = "enabled-credentials-mode";
|
||||||
|
#[cfg(not(feature = "coconut"))]
|
||||||
|
pub(crate) const ETH_ENDPOINT_ARG_NAME: &str = "eth_endpoint";
|
||||||
|
#[cfg(not(feature = "coconut"))]
|
||||||
|
pub(crate) const ETH_PRIVATE_KEY_ARG_NAME: &str = "eth_private_key";
|
||||||
#[cfg(not(feature = "coconut"))]
|
#[cfg(not(feature = "coconut"))]
|
||||||
pub(crate) const DEFAULT_ETH_ENDPOINT: &str =
|
pub(crate) const DEFAULT_ETH_ENDPOINT: &str =
|
||||||
"https://rinkeby.infura.io/v3/00000000000000000000000000000000";
|
"https://rinkeby.infura.io/v3/00000000000000000000000000000000";
|
||||||
@@ -17,86 +21,6 @@ pub(crate) mod init;
|
|||||||
pub(crate) mod run;
|
pub(crate) mod run;
|
||||||
pub(crate) mod upgrade;
|
pub(crate) mod upgrade;
|
||||||
|
|
||||||
fn long_version() -> String {
|
|
||||||
format!(
|
|
||||||
r#"
|
|
||||||
{:<20}{}
|
|
||||||
{:<20}{}
|
|
||||||
{:<20}{}
|
|
||||||
{:<20}{}
|
|
||||||
{:<20}{}
|
|
||||||
{:<20}{}
|
|
||||||
{:<20}{}
|
|
||||||
{:<20}{}
|
|
||||||
{:<20}{}
|
|
||||||
"#,
|
|
||||||
"Build Timestamp:",
|
|
||||||
env!("VERGEN_BUILD_TIMESTAMP"),
|
|
||||||
"Build Version:",
|
|
||||||
env!("VERGEN_BUILD_SEMVER"),
|
|
||||||
"Commit SHA:",
|
|
||||||
env!("VERGEN_GIT_SHA"),
|
|
||||||
"Commit Date:",
|
|
||||||
env!("VERGEN_GIT_COMMIT_TIMESTAMP"),
|
|
||||||
"Commit Branch:",
|
|
||||||
env!("VERGEN_GIT_BRANCH"),
|
|
||||||
"rustc Version:",
|
|
||||||
env!("VERGEN_RUSTC_SEMVER"),
|
|
||||||
"rustc Channel:",
|
|
||||||
env!("VERGEN_RUSTC_CHANNEL"),
|
|
||||||
"cargo Profile:",
|
|
||||||
env!("VERGEN_CARGO_PROFILE"),
|
|
||||||
"Network:",
|
|
||||||
DEFAULT_NETWORK
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn long_version_static() -> &'static str {
|
|
||||||
Box::leak(long_version().into_boxed_str())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Parser)]
|
|
||||||
#[clap(author = "Nymtech", version, long_version = long_version_static(), about)]
|
|
||||||
pub(crate) struct Cli {
|
|
||||||
#[clap(subcommand)]
|
|
||||||
command: Commands,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Subcommand)]
|
|
||||||
pub(crate) enum Commands {
|
|
||||||
/// Initialise a Nym client. Do this first!
|
|
||||||
Init(init::Init),
|
|
||||||
/// Run the Nym client with provided configuration client optionally overriding set parameters
|
|
||||||
Run(run::Run),
|
|
||||||
/// Try to upgrade the client
|
|
||||||
Upgrade(upgrade::Upgrade),
|
|
||||||
}
|
|
||||||
|
|
||||||
// Configuration that can be overridden.
|
|
||||||
pub(crate) struct OverrideConfig {
|
|
||||||
validators: Option<String>,
|
|
||||||
disable_socket: bool,
|
|
||||||
port: Option<u16>,
|
|
||||||
fastmode: bool,
|
|
||||||
|
|
||||||
#[cfg(all(feature = "eth", not(feature = "coconut")))]
|
|
||||||
enabled_credentials_mode: bool,
|
|
||||||
|
|
||||||
#[cfg(all(feature = "eth", not(feature = "coconut")))]
|
|
||||||
eth_private_key: Option<String>,
|
|
||||||
|
|
||||||
#[cfg(all(feature = "eth", not(feature = "coconut")))]
|
|
||||||
eth_endpoint: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) async fn execute(args: &Cli) {
|
|
||||||
match &args.command {
|
|
||||||
Commands::Init(m) => init::execute(m).await,
|
|
||||||
Commands::Run(m) => run::execute(m).await,
|
|
||||||
Commands::Upgrade(m) => upgrade::execute(m),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn parse_validators(raw: &str) -> Vec<Url> {
|
fn parse_validators(raw: &str) -> Vec<Url> {
|
||||||
raw.split(',')
|
raw.split(',')
|
||||||
.map(|raw_validator| {
|
.map(|raw_validator| {
|
||||||
@@ -108,58 +32,45 @@ fn parse_validators(raw: &str) -> Vec<Url> {
|
|||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn override_config(mut config: Config, args: OverrideConfig) -> Config {
|
pub(crate) fn override_config(mut config: Config, matches: &ArgMatches<'_>) -> Config {
|
||||||
if let Some(raw_validators) = args.validators {
|
if let Some(raw_validators) = matches.value_of("validators") {
|
||||||
config
|
config
|
||||||
.get_base_mut()
|
.get_base_mut()
|
||||||
.set_custom_validator_apis(parse_validators(&raw_validators));
|
.set_custom_validator_apis(parse_validators(raw_validators));
|
||||||
}
|
}
|
||||||
|
|
||||||
if args.disable_socket {
|
if matches.is_present("disable-socket") {
|
||||||
config = config.with_socket(SocketType::None);
|
config = config.with_socket(SocketType::None);
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(port) = args.port {
|
if let Some(port) = matches.value_of("port").map(str::parse) {
|
||||||
config = config.with_port(port);
|
if let Err(err) = port {
|
||||||
|
// if port was overridden, it must be parsable
|
||||||
|
panic!("Invalid port value provided - {:?}", err);
|
||||||
|
}
|
||||||
|
config = config.with_port(port.unwrap());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(all(not(feature = "eth"), not(feature = "coconut")))]
|
#[cfg(not(feature = "coconut"))]
|
||||||
{
|
if let Some(eth_endpoint) = matches.value_of(ETH_ENDPOINT_ARG_NAME) {
|
||||||
|
config.get_base_mut().with_eth_endpoint(eth_endpoint);
|
||||||
|
} else if !cfg!(feature = "eth") {
|
||||||
config
|
config
|
||||||
.get_base_mut()
|
.get_base_mut()
|
||||||
.with_eth_endpoint(DEFAULT_ETH_ENDPOINT.to_string());
|
.with_eth_endpoint(DEFAULT_ETH_ENDPOINT);
|
||||||
|
}
|
||||||
|
#[cfg(not(feature = "coconut"))]
|
||||||
|
if let Some(eth_private_key) = matches.value_of(ETH_PRIVATE_KEY_ARG_NAME) {
|
||||||
|
config.get_base_mut().with_eth_private_key(eth_private_key);
|
||||||
|
} else if !cfg!(feature = "eth") {
|
||||||
config
|
config
|
||||||
.get_base_mut()
|
.get_base_mut()
|
||||||
.with_eth_private_key(DEFAULT_ETH_PRIVATE_KEY.to_string());
|
.with_eth_private_key(DEFAULT_ETH_PRIVATE_KEY);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(all(feature = "eth", not(feature = "coconut")))]
|
if matches.is_present(ENABLED_CREDENTIALS_MODE_ARG_NAME) {
|
||||||
{
|
config.get_base_mut().with_disabled_credentials(false)
|
||||||
if args.enabled_credentials_mode {
|
|
||||||
config.get_base_mut().with_disabled_credentials(false)
|
|
||||||
}
|
|
||||||
if let Some(eth_endpoint) = args.eth_endpoint {
|
|
||||||
config.get_base_mut().with_eth_endpoint(eth_endpoint);
|
|
||||||
}
|
|
||||||
if let Some(eth_private_key) = args.eth_private_key {
|
|
||||||
config.get_base_mut().with_eth_private_key(eth_private_key);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if args.fastmode {
|
|
||||||
config.get_base_mut().set_high_default_traffic_volume();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
config
|
config
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use clap::CommandFactory;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn verify_cli() {
|
|
||||||
Cli::command().debug_assert();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,77 +1,68 @@
|
|||||||
// 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
|
||||||
|
|
||||||
use crate::{
|
use crate::client::config::Config;
|
||||||
client::{config::Config, NymClient},
|
use crate::client::NymClient;
|
||||||
commands::{override_config, OverrideConfig},
|
use crate::commands::override_config;
|
||||||
|
#[cfg(feature = "eth")]
|
||||||
|
#[cfg(not(feature = "coconut"))]
|
||||||
|
use crate::commands::{
|
||||||
|
ENABLED_CREDENTIALS_MODE_ARG_NAME, ETH_ENDPOINT_ARG_NAME, ETH_PRIVATE_KEY_ARG_NAME,
|
||||||
};
|
};
|
||||||
|
use clap::{App, Arg, ArgMatches};
|
||||||
use clap::Args;
|
|
||||||
use config::NymConfig;
|
use config::NymConfig;
|
||||||
use log::*;
|
use log::*;
|
||||||
use version_checker::is_minor_version_compatible;
|
use version_checker::is_minor_version_compatible;
|
||||||
|
|
||||||
#[derive(Args, Clone)]
|
pub fn command_args<'a, 'b>() -> clap::App<'a, 'b> {
|
||||||
pub(crate) struct Run {
|
let app = App::new("run")
|
||||||
/// Id of the nym-mixnet-client we want to run.
|
.about("Run the Nym client with provided configuration client optionally overriding set parameters")
|
||||||
#[clap(long)]
|
.arg(Arg::with_name("id")
|
||||||
id: String,
|
.long("id")
|
||||||
|
.help("Id of the nym-mixnet-client we want to run.")
|
||||||
|
.takes_value(true)
|
||||||
|
.required(true)
|
||||||
|
)
|
||||||
|
// the rest of arguments are optional, they are used to override settings in config file
|
||||||
|
.arg(Arg::with_name("validators")
|
||||||
|
.long("validators")
|
||||||
|
.help("Comma separated list rest rest endpoints of the validators")
|
||||||
|
.takes_value(true),
|
||||||
|
)
|
||||||
|
.arg(Arg::with_name("gateway")
|
||||||
|
.long("gateway")
|
||||||
|
.help("Id of the gateway we want to connect to. If overridden, it is user's responsibility to ensure prior registration happened")
|
||||||
|
.takes_value(true)
|
||||||
|
)
|
||||||
|
.arg(Arg::with_name("disable-socket")
|
||||||
|
.long("disable-socket")
|
||||||
|
.help("Whether to not start the websocket")
|
||||||
|
)
|
||||||
|
.arg(Arg::with_name("port")
|
||||||
|
.short("p")
|
||||||
|
.long("port")
|
||||||
|
.help("Port for the socket (if applicable) to listen on")
|
||||||
|
.takes_value(true)
|
||||||
|
);
|
||||||
|
#[cfg(feature = "eth")]
|
||||||
|
#[cfg(not(feature = "coconut"))]
|
||||||
|
let app = app
|
||||||
|
.arg(
|
||||||
|
Arg::with_name(ENABLED_CREDENTIALS_MODE_ARG_NAME)
|
||||||
|
.long(ENABLED_CREDENTIALS_MODE_ARG_NAME)
|
||||||
|
.help("Set this client to work in a enabled credentials mode that would attempt to use gateway with bandwidth credential requirement. If this value is set, --eth_endpoint and --eth_private_key don't need to be set.")
|
||||||
|
.conflicts_with_all(&[ETH_ENDPOINT_ARG_NAME, ETH_PRIVATE_KEY_ARG_NAME])
|
||||||
|
)
|
||||||
|
.arg(Arg::with_name(ETH_ENDPOINT_ARG_NAME)
|
||||||
|
.long(ETH_ENDPOINT_ARG_NAME)
|
||||||
|
.help("URL of an Ethereum full node that we want to use for getting bandwidth tokens from ERC20 tokens. If you don't want to set this value, use --testnet-mode instead")
|
||||||
|
.takes_value(true))
|
||||||
|
.arg(Arg::with_name(ETH_PRIVATE_KEY_ARG_NAME)
|
||||||
|
.long(ETH_PRIVATE_KEY_ARG_NAME)
|
||||||
|
.help("Ethereum private key used for obtaining bandwidth tokens from ERC20 tokens. If you don't want to set this value, use --testnet-mode instead")
|
||||||
|
.takes_value(true));
|
||||||
|
|
||||||
/// Comma separated list of rest endpoints of the validators
|
app
|
||||||
#[clap(long)]
|
|
||||||
validators: Option<String>,
|
|
||||||
|
|
||||||
/// Id of the gateway we want to connect to. If overridden, it is user's responsibility to
|
|
||||||
/// ensure prior registration happened
|
|
||||||
#[clap(long)]
|
|
||||||
gateway: Option<String>,
|
|
||||||
|
|
||||||
/// Whether to not start the websocket
|
|
||||||
#[clap(long)]
|
|
||||||
disable_socket: bool,
|
|
||||||
|
|
||||||
/// Port for the socket to listen on
|
|
||||||
#[clap(short, long)]
|
|
||||||
port: Option<u16>,
|
|
||||||
|
|
||||||
/// Set this client to work in a enabled credentials mode that would attempt to use gateway
|
|
||||||
/// with bandwidth credential requirement. If this value is set, --eth-endpoint and
|
|
||||||
/// --eth-private-key don't need to be set.
|
|
||||||
#[cfg(all(feature = "eth", not(feature = "coconut")))]
|
|
||||||
#[clap(long, conflicts_with_all = &["eth-endpoint", "eth-private-key"])]
|
|
||||||
enabled_credentials_mode: bool,
|
|
||||||
|
|
||||||
/// URL of an Ethereum full node that we want to use for getting bandwidth tokens from ERC20
|
|
||||||
/// tokens. If you don't want to set this value, use --enabled-credentials-mode instead
|
|
||||||
#[cfg(all(feature = "eth", not(feature = "coconut")))]
|
|
||||||
#[clap(long)]
|
|
||||||
eth_endpoint: Option<String>,
|
|
||||||
|
|
||||||
/// Ethereum private key used for obtaining bandwidth tokens from ERC20 tokens. If you don't
|
|
||||||
/// want to set this value, use --enabled-credentials-mode instead")
|
|
||||||
#[cfg(all(feature = "eth", not(feature = "coconut")))]
|
|
||||||
#[clap(long)]
|
|
||||||
eth_private_key: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<Run> for OverrideConfig {
|
|
||||||
fn from(run_config: Run) -> Self {
|
|
||||||
OverrideConfig {
|
|
||||||
validators: run_config.validators,
|
|
||||||
disable_socket: run_config.disable_socket,
|
|
||||||
port: run_config.port,
|
|
||||||
fastmode: false,
|
|
||||||
|
|
||||||
#[cfg(all(feature = "eth", not(feature = "coconut")))]
|
|
||||||
enabled_credentials_mode: run_config.enabled_credentials_mode,
|
|
||||||
|
|
||||||
#[cfg(all(feature = "eth", not(feature = "coconut")))]
|
|
||||||
eth_private_key: run_config.eth_private_key,
|
|
||||||
|
|
||||||
#[cfg(all(feature = "eth", not(feature = "coconut")))]
|
|
||||||
eth_endpoint: run_config.eth_endpoint,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// this only checks compatibility between config the binary. It does not take into consideration
|
// this only checks compatibility between config the binary. It does not take into consideration
|
||||||
@@ -93,8 +84,8 @@ fn version_check(cfg: &Config) -> bool {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) async fn execute(args: &Run) {
|
pub async fn execute(matches: ArgMatches<'static>) {
|
||||||
let id = &args.id;
|
let id = matches.value_of("id").unwrap();
|
||||||
|
|
||||||
let mut config = match Config::load_from_file(Some(id)) {
|
let mut config = match Config::load_from_file(Some(id)) {
|
||||||
Ok(cfg) => cfg,
|
Ok(cfg) => cfg,
|
||||||
@@ -104,8 +95,7 @@ pub(crate) async fn execute(args: &Run) {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let override_config_fields = OverrideConfig::from(args.clone());
|
config = override_config(config, &matches);
|
||||||
config = override_config(config, override_config_fields);
|
|
||||||
|
|
||||||
if !version_check(&config) {
|
if !version_check(&config) {
|
||||||
error!("failed the local version check");
|
error!("failed the local version check");
|
||||||
|
|||||||
@@ -2,13 +2,12 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
|
||||||
use crate::client::config::{Config, MISSING_VALUE};
|
use crate::client::config::{Config, MISSING_VALUE};
|
||||||
|
use clap::{App, Arg, ArgMatches};
|
||||||
use config::{defaults::default_api_endpoints, NymConfig};
|
use config::defaults::default_api_endpoints;
|
||||||
use version_checker::Version;
|
use config::NymConfig;
|
||||||
|
|
||||||
use clap::Args;
|
|
||||||
use std::fmt::Display;
|
use std::fmt::Display;
|
||||||
use std::process;
|
use std::process;
|
||||||
|
use version_checker::Version;
|
||||||
|
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
fn fail_upgrade<D1: Display, D2: Display>(from_version: D1, to_version: D2) -> ! {
|
fn fail_upgrade<D1: Display, D2: Display>(from_version: D1, to_version: D2) -> ! {
|
||||||
@@ -50,11 +49,14 @@ fn unsupported_upgrade(current_version: &Version, config_version: &Version) -> !
|
|||||||
process::exit(1)
|
process::exit(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Args, Clone)]
|
pub fn command_args<'a, 'b>() -> App<'a, 'b> {
|
||||||
pub(crate) struct Upgrade {
|
App::new("upgrade").about("Try to upgrade the client").arg(
|
||||||
/// Id of the nym-client we want to upgrade
|
Arg::with_name("id")
|
||||||
#[clap(long)]
|
.long("id")
|
||||||
id: String,
|
.help("Id of the nym-client we want to upgrade")
|
||||||
|
.takes_value(true)
|
||||||
|
.required(true),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn parse_config_version(config: &Config) -> Version {
|
fn parse_config_version(config: &Config) -> Version {
|
||||||
@@ -93,7 +95,7 @@ fn parse_package_version() -> Version {
|
|||||||
|
|
||||||
fn minor_0_12_upgrade(
|
fn minor_0_12_upgrade(
|
||||||
mut config: Config,
|
mut config: Config,
|
||||||
_matches: &Upgrade,
|
_matches: &ArgMatches<'_>,
|
||||||
config_version: &Version,
|
config_version: &Version,
|
||||||
package_version: &Version,
|
package_version: &Version,
|
||||||
) -> Config {
|
) -> Config {
|
||||||
@@ -129,7 +131,7 @@ fn minor_0_12_upgrade(
|
|||||||
config
|
config
|
||||||
}
|
}
|
||||||
|
|
||||||
fn do_upgrade(mut config: Config, args: &Upgrade, package_version: &Version) {
|
fn do_upgrade(mut config: Config, matches: &ArgMatches<'_>, package_version: &Version) {
|
||||||
loop {
|
loop {
|
||||||
let config_version = parse_config_version(&config);
|
let config_version = parse_config_version(&config);
|
||||||
|
|
||||||
@@ -141,7 +143,7 @@ fn do_upgrade(mut config: Config, args: &Upgrade, package_version: &Version) {
|
|||||||
config = match config_version.major {
|
config = match config_version.major {
|
||||||
0 => match config_version.minor {
|
0 => match config_version.minor {
|
||||||
9 | 10 => outdated_upgrade(&config_version, package_version),
|
9 | 10 => outdated_upgrade(&config_version, package_version),
|
||||||
11 => minor_0_12_upgrade(config, args, &config_version, package_version),
|
11 => minor_0_12_upgrade(config, matches, &config_version, package_version),
|
||||||
_ => unsupported_upgrade(&config_version, package_version),
|
_ => unsupported_upgrade(&config_version, package_version),
|
||||||
},
|
},
|
||||||
_ => unsupported_upgrade(&config_version, package_version),
|
_ => unsupported_upgrade(&config_version, package_version),
|
||||||
@@ -149,10 +151,10 @@ fn do_upgrade(mut config: Config, args: &Upgrade, package_version: &Version) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn execute(args: &Upgrade) {
|
pub fn execute(matches: &ArgMatches<'_>) {
|
||||||
let package_version = parse_package_version();
|
let package_version = parse_package_version();
|
||||||
|
|
||||||
let id = &args.id;
|
let id = matches.value_of("id").unwrap();
|
||||||
|
|
||||||
let existing_config = Config::load_from_file(Some(id)).unwrap_or_else(|err| {
|
let existing_config = Config::load_from_file(Some(id)).unwrap_or_else(|err| {
|
||||||
eprintln!("failed to load existing config file! - {:?}", err);
|
eprintln!("failed to load existing config file! - {:?}", err);
|
||||||
@@ -165,5 +167,5 @@ pub(crate) fn execute(args: &Upgrade) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// here be upgrade path to 0.9.X and beyond based on version number from config
|
// here be upgrade path to 0.9.X and beyond based on version number from config
|
||||||
do_upgrade(existing_config, args, &package_version)
|
do_upgrade(existing_config, matches, &package_version)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
// 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
|
||||||
|
|
||||||
use clap::{crate_version, Parser};
|
use clap::{crate_version, App, ArgMatches};
|
||||||
|
use network_defaults::DEFAULT_NETWORK;
|
||||||
|
|
||||||
pub mod client;
|
pub mod client;
|
||||||
pub mod commands;
|
pub mod commands;
|
||||||
@@ -13,8 +14,30 @@ async fn main() {
|
|||||||
setup_logging();
|
setup_logging();
|
||||||
println!("{}", banner());
|
println!("{}", banner());
|
||||||
|
|
||||||
let args = commands::Cli::parse();
|
let arg_matches = App::new("Nym Client")
|
||||||
commands::execute(&args).await;
|
.version(crate_version!())
|
||||||
|
.long_version(&*long_version())
|
||||||
|
.author("Nymtech")
|
||||||
|
.about("Implementation of the Nym Client")
|
||||||
|
.subcommand(commands::init::command_args())
|
||||||
|
.subcommand(commands::run::command_args())
|
||||||
|
.subcommand(commands::upgrade::command_args())
|
||||||
|
.get_matches();
|
||||||
|
|
||||||
|
execute(arg_matches).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn execute(matches: ArgMatches<'static>) {
|
||||||
|
match matches.subcommand() {
|
||||||
|
("init", Some(m)) => commands::init::execute(m.clone()).await,
|
||||||
|
("run", Some(m)) => commands::run::execute(m.clone()).await,
|
||||||
|
("upgrade", Some(m)) => commands::upgrade::execute(m),
|
||||||
|
_ => println!("{}", usage()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn usage() -> &'static str {
|
||||||
|
"usage: --help to see available options.\n\n"
|
||||||
}
|
}
|
||||||
|
|
||||||
fn banner() -> String {
|
fn banner() -> String {
|
||||||
@@ -34,6 +57,40 @@ fn banner() -> String {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn long_version() -> String {
|
||||||
|
format!(
|
||||||
|
r#"
|
||||||
|
{:<20}{}
|
||||||
|
{:<20}{}
|
||||||
|
{:<20}{}
|
||||||
|
{:<20}{}
|
||||||
|
{:<20}{}
|
||||||
|
{:<20}{}
|
||||||
|
{:<20}{}
|
||||||
|
{:<20}{}
|
||||||
|
{:<20}{}
|
||||||
|
"#,
|
||||||
|
"Build Timestamp:",
|
||||||
|
env!("VERGEN_BUILD_TIMESTAMP"),
|
||||||
|
"Build Version:",
|
||||||
|
env!("VERGEN_BUILD_SEMVER"),
|
||||||
|
"Commit SHA:",
|
||||||
|
env!("VERGEN_GIT_SHA"),
|
||||||
|
"Commit Date:",
|
||||||
|
env!("VERGEN_GIT_COMMIT_TIMESTAMP"),
|
||||||
|
"Commit Branch:",
|
||||||
|
env!("VERGEN_GIT_BRANCH"),
|
||||||
|
"rustc Version:",
|
||||||
|
env!("VERGEN_RUSTC_SEMVER"),
|
||||||
|
"rustc Channel:",
|
||||||
|
env!("VERGEN_RUSTC_CHANNEL"),
|
||||||
|
"cargo Profile:",
|
||||||
|
env!("VERGEN_CARGO_PROFILE"),
|
||||||
|
"Network:",
|
||||||
|
DEFAULT_NETWORK
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
fn setup_logging() {
|
fn setup_logging() {
|
||||||
let mut log_builder = pretty_env_logger::formatted_timed_builder();
|
let mut log_builder = pretty_env_logger::formatted_timed_builder();
|
||||||
if let Ok(s) = ::std::env::var("RUST_LOG") {
|
if let Ok(s) = ::std::env::var("RUST_LOG") {
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ use serde::{Deserialize, Serialize};
|
|||||||
use std::fmt;
|
use std::fmt;
|
||||||
|
|
||||||
// no need to go fancy here like we've done in other places.
|
// no need to go fancy here like we've done in other places.
|
||||||
#[derive(PartialEq, Eq, Clone, Serialize, Deserialize)]
|
#[derive(PartialEq, Clone, Serialize, Deserialize)]
|
||||||
pub struct Error {
|
pub struct Error {
|
||||||
pub kind: ErrorKind,
|
pub kind: ErrorKind,
|
||||||
pub message: String,
|
pub message: String,
|
||||||
@@ -30,7 +30,7 @@ impl Error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[repr(u8)]
|
#[repr(u8)]
|
||||||
#[derive(PartialEq, Eq, Clone, Serialize, Deserialize)]
|
#[derive(PartialEq, Clone, Serialize, Deserialize)]
|
||||||
pub enum ErrorKind {
|
pub enum ErrorKind {
|
||||||
/// The received request contained no data.
|
/// The received request contained no data.
|
||||||
EmptyRequest = 0x01,
|
EmptyRequest = 0x01,
|
||||||
|
|||||||
@@ -2,7 +2,6 @@
|
|||||||
name = "nym-socks5-client"
|
name = "nym-socks5-client"
|
||||||
version = "1.0.1"
|
version = "1.0.1"
|
||||||
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"
|
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
rust-version = "1.56"
|
rust-version = "1.56"
|
||||||
|
|
||||||
@@ -11,8 +10,8 @@ name = "nym_socks5"
|
|||||||
path = "src/lib.rs"
|
path = "src/lib.rs"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
clap = { version = "3.2.8", features = ["cargo", "derive"] }
|
clap = "2.33.0"
|
||||||
dirs = "4.0"
|
dirs = "3.0" # for determining default store directories in config
|
||||||
dotenv = "0.15.0"
|
dotenv = "0.15.0"
|
||||||
futures = "0.3"
|
futures = "0.3"
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
|
|||||||
@@ -89,7 +89,7 @@ impl Config {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Deserialize, PartialEq, Eq, Serialize)]
|
#[derive(Debug, Deserialize, PartialEq, Serialize)]
|
||||||
#[serde(deny_unknown_fields)]
|
#[serde(deny_unknown_fields)]
|
||||||
pub struct Socks5 {
|
pub struct Socks5 {
|
||||||
/// The port on which the client will be listening for incoming requests
|
/// The port on which the client will be listening for incoming requests
|
||||||
|
|||||||
@@ -287,15 +287,12 @@ impl NymClient {
|
|||||||
pub async fn run_and_listen(&mut self, mut receiver: Socks5ControlMessageReceiver) {
|
pub async fn run_and_listen(&mut self, mut receiver: Socks5ControlMessageReceiver) {
|
||||||
self.start().await;
|
self.start().await;
|
||||||
tokio::select! {
|
tokio::select! {
|
||||||
message = receiver.next() => {
|
message = receiver.next() => match message {
|
||||||
log::debug!("Received message: {:?}", message);
|
Some(Socks5ControlMessage::Stop) => {
|
||||||
match message {
|
log::info!("Received: {:?}", message);
|
||||||
Some(Socks5ControlMessage::Stop) => {
|
log::info!("Shutting down");
|
||||||
log::info!("Shutting down");
|
|
||||||
log::info!("Graceful shutdown of tasks not yet implemented, you might see (harmless) panics until then");
|
|
||||||
}
|
|
||||||
None => log::debug!("None"),
|
|
||||||
}
|
}
|
||||||
|
None => log::info!("none"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,100 +1,91 @@
|
|||||||
// 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
|
||||||
|
|
||||||
use clap::Args;
|
use clap::{App, Arg, ArgMatches};
|
||||||
use client_core::config::GatewayEndpoint;
|
use client_core::config::GatewayEndpoint;
|
||||||
use config::NymConfig;
|
use config::NymConfig;
|
||||||
|
|
||||||
use crate::{
|
use crate::client::config::Config;
|
||||||
client::config::Config,
|
use crate::commands::override_config;
|
||||||
commands::{override_config, OverrideConfig},
|
#[cfg(feature = "eth")]
|
||||||
|
#[cfg(not(feature = "coconut"))]
|
||||||
|
use crate::commands::{
|
||||||
|
DEFAULT_ETH_ENDPOINT, DEFAULT_ETH_PRIVATE_KEY, ENABLED_CREDENTIALS_MODE_ARG_NAME,
|
||||||
|
ETH_ENDPOINT_ARG_NAME, ETH_PRIVATE_KEY_ARG_NAME,
|
||||||
};
|
};
|
||||||
|
|
||||||
#[cfg(all(feature = "eth", not(feature = "coconut")))]
|
pub fn command_args<'a, 'b>() -> clap::App<'a, 'b> {
|
||||||
use crate::commands::{DEFAULT_ETH_ENDPOINT, DEFAULT_ETH_PRIVATE_KEY};
|
let app = App::new("init")
|
||||||
|
.about("Initialise a Nym client. Do this first!")
|
||||||
|
.arg(Arg::with_name("id")
|
||||||
|
.long("id")
|
||||||
|
.help("Id of the nym-mixnet-client we want to create config for.")
|
||||||
|
.takes_value(true)
|
||||||
|
.required(true)
|
||||||
|
)
|
||||||
|
.arg(Arg::with_name("provider")
|
||||||
|
.long("provider")
|
||||||
|
.help("Address of the socks5 provider to send messages to.")
|
||||||
|
.takes_value(true)
|
||||||
|
.required(true)
|
||||||
|
)
|
||||||
|
.arg(Arg::with_name("gateway")
|
||||||
|
.long("gateway")
|
||||||
|
.help("Id of the gateway we are going to connect to.")
|
||||||
|
.takes_value(true)
|
||||||
|
)
|
||||||
|
.arg(Arg::with_name("force-register-gateway")
|
||||||
|
.long("force-register-gateway")
|
||||||
|
.help("Force register gateway. WARNING: this will overwrite any existing keys for the given id, potentially causing loss of access.")
|
||||||
|
.takes_value(false)
|
||||||
|
)
|
||||||
|
.arg(Arg::with_name("validators")
|
||||||
|
.long("validators")
|
||||||
|
.help("Comma separated list of rest endpoints of the validators")
|
||||||
|
.takes_value(true),
|
||||||
|
)
|
||||||
|
.arg(Arg::with_name("port")
|
||||||
|
.short("p")
|
||||||
|
.long("port")
|
||||||
|
.help("Port for the socket to listen on in all subsequent runs")
|
||||||
|
.takes_value(true)
|
||||||
|
)
|
||||||
|
.arg(Arg::with_name("fastmode")
|
||||||
|
.long("fastmode")
|
||||||
|
.hidden(true) // this will prevent this flag from being displayed in `--help`
|
||||||
|
.help("Mostly debug-related option to increase default traffic rate so that you would not need to modify config post init")
|
||||||
|
);
|
||||||
|
#[cfg(feature = "eth")]
|
||||||
|
#[cfg(not(feature = "coconut"))]
|
||||||
|
let app = app
|
||||||
|
.arg(
|
||||||
|
Arg::with_name(ENABLED_CREDENTIALS_MODE_ARG_NAME)
|
||||||
|
.long(ENABLED_CREDENTIALS_MODE_ARG_NAME)
|
||||||
|
.help("Set this client to work in a enabled credentials mode that would attempt to use gateway with bandwidth credential requirement. If this value is set, --eth_endpoint and --eth_private_key don't need to be set.")
|
||||||
|
.conflicts_with_all(&[ETH_ENDPOINT_ARG_NAME, ETH_PRIVATE_KEY_ARG_NAME])
|
||||||
|
)
|
||||||
|
.arg(Arg::with_name(ETH_ENDPOINT_ARG_NAME)
|
||||||
|
.long(ETH_ENDPOINT_ARG_NAME)
|
||||||
|
.help("URL of an Ethereum full node that we want to use for getting bandwidth tokens from ERC20 tokens. If you don't want to set this value, use --testnet-mode instead")
|
||||||
|
.takes_value(true)
|
||||||
|
.default_value_if(ENABLED_CREDENTIALS_MODE_ARG_NAME, None, DEFAULT_ETH_ENDPOINT)
|
||||||
|
.required(true))
|
||||||
|
.arg(Arg::with_name(ETH_PRIVATE_KEY_ARG_NAME)
|
||||||
|
.long(ETH_PRIVATE_KEY_ARG_NAME)
|
||||||
|
.help("Ethereum private key used for obtaining bandwidth tokens from ERC20 tokens. If you don't want to set this value, use --testnet-mode instead")
|
||||||
|
.takes_value(true)
|
||||||
|
.default_value_if(ENABLED_CREDENTIALS_MODE_ARG_NAME, None, DEFAULT_ETH_PRIVATE_KEY)
|
||||||
|
.required(true)
|
||||||
|
);
|
||||||
|
|
||||||
#[derive(Args, Clone)]
|
app
|
||||||
pub(crate) struct Init {
|
|
||||||
/// Id of the nym-mixnet-client we want to create config for.
|
|
||||||
#[clap(long)]
|
|
||||||
id: String,
|
|
||||||
|
|
||||||
/// Address of the socks5 provider to send messages to.
|
|
||||||
#[clap(long)]
|
|
||||||
provider: String,
|
|
||||||
|
|
||||||
/// Id of the gateway we are going to connect to.
|
|
||||||
#[clap(long)]
|
|
||||||
gateway: Option<String>,
|
|
||||||
|
|
||||||
/// Force register gateway. WARNING: this will overwrite any existing keys for the given id,
|
|
||||||
/// potentially causing loss of access.
|
|
||||||
#[clap(long)]
|
|
||||||
force_register_gateway: bool,
|
|
||||||
|
|
||||||
/// Comma separated list of rest endpoints of the validators
|
|
||||||
#[clap(long)]
|
|
||||||
validators: Option<String>,
|
|
||||||
|
|
||||||
/// Port for the socket to listen on in all subsequent runs
|
|
||||||
#[clap(short, long)]
|
|
||||||
port: Option<u16>,
|
|
||||||
|
|
||||||
/// Mostly debug-related option to increase default traffic rate so that you would not need to
|
|
||||||
/// modify config post init
|
|
||||||
#[clap(long, hidden = true)]
|
|
||||||
fastmode: bool,
|
|
||||||
|
|
||||||
/// Set this client to work in a enabled credentials mode that would attempt to use gateway
|
|
||||||
/// with bandwidth credential requirement. If this value is set, --eth-endpoint and
|
|
||||||
/// --eth-private_key don't need to be set.
|
|
||||||
#[cfg(all(feature = "eth", not(feature = "coconut")))]
|
|
||||||
#[clap(long, conflicts_with_all = &["eth-endpoint", "eth-private-key"])]
|
|
||||||
enabled_credentials_mode: bool,
|
|
||||||
|
|
||||||
/// URL of an Ethereum full node that we want to use for getting bandwidth tokens from ERC20
|
|
||||||
/// tokens. If you don't want to set this value, use --enabled-credentials-mode instead
|
|
||||||
#[cfg(all(feature = "eth", not(feature = "coconut")))]
|
|
||||||
#[clap(
|
|
||||||
long,
|
|
||||||
default_value_if("enabled-credentials-mode", None, Some(DEFAULT_ETH_ENDPOINT))
|
|
||||||
)]
|
|
||||||
eth_endpoint: String,
|
|
||||||
|
|
||||||
/// Ethereum private key used for obtaining bandwidth tokens from ERC20 tokens. If you don't
|
|
||||||
/// want to set this value, use --enabled-credentials-mode instead")
|
|
||||||
#[cfg(all(feature = "eth", not(feature = "coconut")))]
|
|
||||||
#[clap(
|
|
||||||
long,
|
|
||||||
default_value_if("enabled-credentials-mode", None, Some(DEFAULT_ETH_PRIVATE_KEY))
|
|
||||||
)]
|
|
||||||
eth_private_key: String,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<Init> for OverrideConfig {
|
pub async fn execute(matches: ArgMatches<'static>) {
|
||||||
fn from(init_config: Init) -> Self {
|
|
||||||
OverrideConfig {
|
|
||||||
validators: init_config.validators,
|
|
||||||
port: init_config.port,
|
|
||||||
fastmode: init_config.fastmode,
|
|
||||||
|
|
||||||
#[cfg(all(feature = "eth", not(feature = "coconut")))]
|
|
||||||
enabled_credentials_mode: init_config.enabled_credentials_mode,
|
|
||||||
|
|
||||||
#[cfg(all(feature = "eth", not(feature = "coconut")))]
|
|
||||||
eth_private_key: Some(init_config.eth_private_key),
|
|
||||||
|
|
||||||
#[cfg(all(feature = "eth", not(feature = "coconut")))]
|
|
||||||
eth_endpoint: Some(init_config.eth_endpoint),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) async fn execute(args: &Init) {
|
|
||||||
println!("Initialising client...");
|
println!("Initialising client...");
|
||||||
|
|
||||||
let id = &args.id;
|
let id = matches.value_of("id").unwrap(); // required for now
|
||||||
let provider_address = &args.provider;
|
let provider_address = matches.value_of("provider").unwrap();
|
||||||
|
|
||||||
let already_init = Config::default_config_file_path(Some(id)).exists();
|
let already_init = Config::default_config_file_path(Some(id)).exists();
|
||||||
if already_init {
|
if already_init {
|
||||||
@@ -107,7 +98,7 @@ pub(crate) async fn execute(args: &Init) {
|
|||||||
|
|
||||||
// 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 = matches.is_present("force-register-gateway");
|
||||||
|
|
||||||
// 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).
|
||||||
@@ -115,11 +106,14 @@ pub(crate) async fn execute(args: &Init) {
|
|||||||
let register_gateway = !already_init || user_wants_force_register;
|
let register_gateway = !already_init || user_wants_force_register;
|
||||||
|
|
||||||
// Attempt to use a user-provided gateway, if possible
|
// Attempt to use a user-provided gateway, if possible
|
||||||
let user_chosen_gateway_id = args.gateway.as_deref();
|
let user_chosen_gateway_id = matches.value_of("gateway");
|
||||||
|
|
||||||
let mut config = Config::new(id, provider_address);
|
let mut config = Config::new(id, provider_address);
|
||||||
let override_config_fields = OverrideConfig::from(args.clone());
|
|
||||||
config = override_config(config, override_config_fields);
|
config = override_config(config, &matches);
|
||||||
|
if matches.is_present("fastmode") {
|
||||||
|
config.get_base_mut().set_high_default_traffic_volume();
|
||||||
|
}
|
||||||
|
|
||||||
let gateway = setup_gateway(id, register_gateway, user_chosen_gateway_id, &config).await;
|
let gateway = setup_gateway(id, register_gateway, user_chosen_gateway_id, &config).await;
|
||||||
config.get_base_mut().with_gateway_endpoint(gateway);
|
config.get_base_mut().with_gateway_endpoint(gateway);
|
||||||
|
|||||||
@@ -2,14 +2,18 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
|
||||||
use crate::client::config::Config;
|
use crate::client::config::Config;
|
||||||
use clap::{Parser, Subcommand};
|
use clap::ArgMatches;
|
||||||
use network_defaults::DEFAULT_NETWORK;
|
|
||||||
use url::Url;
|
use url::Url;
|
||||||
|
|
||||||
pub mod init;
|
pub mod init;
|
||||||
pub(crate) mod run;
|
pub(crate) mod run;
|
||||||
pub(crate) mod upgrade;
|
pub(crate) mod upgrade;
|
||||||
|
|
||||||
|
pub(crate) const ENABLED_CREDENTIALS_MODE_ARG_NAME: &str = "enabled-credentials-mode";
|
||||||
|
#[cfg(not(feature = "coconut"))]
|
||||||
|
pub(crate) const ETH_ENDPOINT_ARG_NAME: &str = "eth_endpoint";
|
||||||
|
#[cfg(not(feature = "coconut"))]
|
||||||
|
pub(crate) const ETH_PRIVATE_KEY_ARG_NAME: &str = "eth_private_key";
|
||||||
#[cfg(not(feature = "coconut"))]
|
#[cfg(not(feature = "coconut"))]
|
||||||
pub(crate) const DEFAULT_ETH_ENDPOINT: &str =
|
pub(crate) const DEFAULT_ETH_ENDPOINT: &str =
|
||||||
"https://rinkeby.infura.io/v3/00000000000000000000000000000000";
|
"https://rinkeby.infura.io/v3/00000000000000000000000000000000";
|
||||||
@@ -17,85 +21,6 @@ pub(crate) const DEFAULT_ETH_ENDPOINT: &str =
|
|||||||
pub(crate) const DEFAULT_ETH_PRIVATE_KEY: &str =
|
pub(crate) const DEFAULT_ETH_PRIVATE_KEY: &str =
|
||||||
"0000000000000000000000000000000000000000000000000000000000000001";
|
"0000000000000000000000000000000000000000000000000000000000000001";
|
||||||
|
|
||||||
fn long_version() -> String {
|
|
||||||
format!(
|
|
||||||
r#"
|
|
||||||
{:<20}{}
|
|
||||||
{:<20}{}
|
|
||||||
{:<20}{}
|
|
||||||
{:<20}{}
|
|
||||||
{:<20}{}
|
|
||||||
{:<20}{}
|
|
||||||
{:<20}{}
|
|
||||||
{:<20}{}
|
|
||||||
{:<20}{}
|
|
||||||
"#,
|
|
||||||
"Build Timestamp:",
|
|
||||||
env!("VERGEN_BUILD_TIMESTAMP"),
|
|
||||||
"Build Version:",
|
|
||||||
env!("VERGEN_BUILD_SEMVER"),
|
|
||||||
"Commit SHA:",
|
|
||||||
env!("VERGEN_GIT_SHA"),
|
|
||||||
"Commit Date:",
|
|
||||||
env!("VERGEN_GIT_COMMIT_TIMESTAMP"),
|
|
||||||
"Commit Branch:",
|
|
||||||
env!("VERGEN_GIT_BRANCH"),
|
|
||||||
"rustc Version:",
|
|
||||||
env!("VERGEN_RUSTC_SEMVER"),
|
|
||||||
"rustc Channel:",
|
|
||||||
env!("VERGEN_RUSTC_CHANNEL"),
|
|
||||||
"cargo Profile:",
|
|
||||||
env!("VERGEN_CARGO_PROFILE"),
|
|
||||||
"Network:",
|
|
||||||
DEFAULT_NETWORK
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn long_version_static() -> &'static str {
|
|
||||||
Box::leak(long_version().into_boxed_str())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Parser)]
|
|
||||||
#[clap(author = "Nymtech", version, long_version = long_version_static(), about)]
|
|
||||||
pub(crate) struct Cli {
|
|
||||||
#[clap(subcommand)]
|
|
||||||
command: Commands,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Subcommand)]
|
|
||||||
pub(crate) enum Commands {
|
|
||||||
/// Initialise a Nym client. Do this first!
|
|
||||||
Init(init::Init),
|
|
||||||
/// Run the Nym client with provided configuration client optionally overriding set parameters
|
|
||||||
Run(run::Run),
|
|
||||||
/// Try to upgrade the client
|
|
||||||
Upgrade(upgrade::Upgrade),
|
|
||||||
}
|
|
||||||
|
|
||||||
// Configuration that can be overridden.
|
|
||||||
pub(crate) struct OverrideConfig {
|
|
||||||
validators: Option<String>,
|
|
||||||
port: Option<u16>,
|
|
||||||
fastmode: bool,
|
|
||||||
|
|
||||||
#[cfg(all(feature = "eth", not(feature = "coconut")))]
|
|
||||||
enabled_credentials_mode: bool,
|
|
||||||
|
|
||||||
#[cfg(all(feature = "eth", not(feature = "coconut")))]
|
|
||||||
eth_private_key: Option<String>,
|
|
||||||
|
|
||||||
#[cfg(all(feature = "eth", not(feature = "coconut")))]
|
|
||||||
eth_endpoint: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) async fn execute(args: &Cli) {
|
|
||||||
match &args.command {
|
|
||||||
Commands::Init(m) => init::execute(m).await,
|
|
||||||
Commands::Run(m) => run::execute(m).await,
|
|
||||||
Commands::Upgrade(m) => upgrade::execute(m),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn parse_validators(raw: &str) -> Vec<Url> {
|
fn parse_validators(raw: &str) -> Vec<Url> {
|
||||||
raw.split(',')
|
raw.split(',')
|
||||||
.map(|raw_validator| {
|
.map(|raw_validator| {
|
||||||
@@ -107,54 +32,41 @@ fn parse_validators(raw: &str) -> Vec<Url> {
|
|||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn override_config(mut config: Config, args: OverrideConfig) -> Config {
|
pub(crate) fn override_config(mut config: Config, matches: &ArgMatches<'_>) -> Config {
|
||||||
if let Some(raw_validators) = args.validators {
|
if let Some(raw_validators) = matches.value_of("validators") {
|
||||||
config
|
config
|
||||||
.get_base_mut()
|
.get_base_mut()
|
||||||
.set_custom_validator_apis(parse_validators(&raw_validators));
|
.set_custom_validator_apis(parse_validators(raw_validators));
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(port) = args.port {
|
if let Some(port) = matches.value_of("port").map(|port| port.parse::<u16>()) {
|
||||||
config = config.with_port(port);
|
if let Err(err) = port {
|
||||||
|
// if port was overridden, it must be parsable
|
||||||
|
panic!("Invalid port value provided - {:?}", err);
|
||||||
|
}
|
||||||
|
config = config.with_port(port.unwrap());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(all(not(feature = "eth"), not(feature = "coconut")))]
|
#[cfg(not(feature = "coconut"))]
|
||||||
{
|
if let Some(eth_endpoint) = matches.value_of(ETH_ENDPOINT_ARG_NAME) {
|
||||||
|
config.get_base_mut().with_eth_endpoint(eth_endpoint);
|
||||||
|
} else if !cfg!(feature = "eth") {
|
||||||
config
|
config
|
||||||
.get_base_mut()
|
.get_base_mut()
|
||||||
.with_eth_endpoint(DEFAULT_ETH_ENDPOINT.to_string());
|
.with_eth_endpoint(DEFAULT_ETH_ENDPOINT);
|
||||||
|
}
|
||||||
|
#[cfg(not(feature = "coconut"))]
|
||||||
|
if let Some(eth_private_key) = matches.value_of(ETH_PRIVATE_KEY_ARG_NAME) {
|
||||||
|
config.get_base_mut().with_eth_private_key(eth_private_key);
|
||||||
|
} else if !cfg!(feature = "eth") {
|
||||||
config
|
config
|
||||||
.get_base_mut()
|
.get_base_mut()
|
||||||
.with_eth_private_key(DEFAULT_ETH_PRIVATE_KEY.to_string());
|
.with_eth_private_key(DEFAULT_ETH_PRIVATE_KEY);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(all(feature = "eth", not(feature = "coconut")))]
|
if matches.is_present(ENABLED_CREDENTIALS_MODE_ARG_NAME) {
|
||||||
{
|
config.get_base_mut().with_disabled_credentials(false)
|
||||||
if args.enabled_credentials_mode {
|
|
||||||
config.get_base_mut().with_disabled_credentials(false)
|
|
||||||
}
|
|
||||||
if let Some(eth_endpoint) = args.eth_endpoint {
|
|
||||||
config.get_base_mut().with_eth_endpoint(eth_endpoint);
|
|
||||||
}
|
|
||||||
if let Some(eth_private_key) = args.eth_private_key {
|
|
||||||
config.get_base_mut().with_eth_private_key(eth_private_key);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if args.fastmode {
|
|
||||||
config.get_base_mut().set_high_default_traffic_volume();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
config
|
config
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use clap::CommandFactory;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn verify_cli() {
|
|
||||||
Cli::command().debug_assert();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,80 +1,74 @@
|
|||||||
// 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
|
||||||
|
|
||||||
use crate::{
|
use crate::client::config::Config;
|
||||||
client::{config::Config, NymClient},
|
use crate::client::NymClient;
|
||||||
commands::{override_config, OverrideConfig},
|
use crate::commands::override_config;
|
||||||
|
#[cfg(feature = "eth")]
|
||||||
|
#[cfg(not(feature = "coconut"))]
|
||||||
|
use crate::commands::{
|
||||||
|
ENABLED_CREDENTIALS_MODE_ARG_NAME, ETH_ENDPOINT_ARG_NAME, ETH_PRIVATE_KEY_ARG_NAME,
|
||||||
};
|
};
|
||||||
|
use clap::{App, Arg, ArgMatches};
|
||||||
use clap::Args;
|
|
||||||
use config::NymConfig;
|
use config::NymConfig;
|
||||||
use log::*;
|
use log::*;
|
||||||
use version_checker::is_minor_version_compatible;
|
use version_checker::is_minor_version_compatible;
|
||||||
|
|
||||||
#[derive(Args, Clone)]
|
pub fn command_args<'a, 'b>() -> clap::App<'a, 'b> {
|
||||||
pub(crate) struct Run {
|
let app = App::new("run")
|
||||||
/// Id of the nym-mixnet-client we want to run.
|
.about("Run the Nym client with provided configuration client optionally overriding set parameters")
|
||||||
#[clap(long)]
|
.arg(Arg::with_name("id")
|
||||||
id: String,
|
.long("id")
|
||||||
|
.help("Id of the nym-mixnet-client we want to run.")
|
||||||
|
.takes_value(true)
|
||||||
|
.required(true)
|
||||||
|
)
|
||||||
|
// the rest of arguments are optional, they are used to override settings in config file
|
||||||
|
.arg(Arg::with_name("config")
|
||||||
|
.long("config")
|
||||||
|
.help("Custom path to the nym-mixnet-client configuration file")
|
||||||
|
.takes_value(true)
|
||||||
|
)
|
||||||
|
.arg(Arg::with_name("provider")
|
||||||
|
.long("provider")
|
||||||
|
.help("Address of the socks5 provider to send messages to.")
|
||||||
|
.takes_value(true)
|
||||||
|
)
|
||||||
|
.arg(Arg::with_name("gateway")
|
||||||
|
.long("gateway")
|
||||||
|
.help("Id of the gateway we want to connect to. If overridden, it is user's responsibility to ensure prior registration happened")
|
||||||
|
.takes_value(true)
|
||||||
|
)
|
||||||
|
.arg(Arg::with_name("validators")
|
||||||
|
.long("validators")
|
||||||
|
.help("Comma separated list of rest endpoints of the validators")
|
||||||
|
.takes_value(true),
|
||||||
|
)
|
||||||
|
.arg(Arg::with_name("port")
|
||||||
|
.short("p")
|
||||||
|
.long("port")
|
||||||
|
.help("Port for the socket to listen on")
|
||||||
|
.takes_value(true)
|
||||||
|
);
|
||||||
|
#[cfg(feature = "eth")]
|
||||||
|
#[cfg(not(feature = "coconut"))]
|
||||||
|
let app = app
|
||||||
|
.arg(
|
||||||
|
Arg::with_name(ENABLED_CREDENTIALS_MODE_ARG_NAME)
|
||||||
|
.long(ENABLED_CREDENTIALS_MODE_ARG_NAME)
|
||||||
|
.help("Set this client to work in a disabled credentials mode that would attempt to use gateway without bandwidth credential requirement. If this value is set, --eth_endpoint and --eth_private_key don't need to be set.")
|
||||||
|
.conflicts_with_all(&[ETH_ENDPOINT_ARG_NAME, ETH_PRIVATE_KEY_ARG_NAME])
|
||||||
|
)
|
||||||
|
.arg(Arg::with_name(ETH_ENDPOINT_ARG_NAME)
|
||||||
|
.long(ETH_ENDPOINT_ARG_NAME)
|
||||||
|
.help("URL of an Ethereum full node that we want to use for getting bandwidth tokens from ERC20 tokens. If you don't want to set this value, use --testnet-mode instead")
|
||||||
|
.takes_value(true))
|
||||||
|
.arg(Arg::with_name(ETH_PRIVATE_KEY_ARG_NAME)
|
||||||
|
.long(ETH_PRIVATE_KEY_ARG_NAME)
|
||||||
|
.help("Ethereum private key used for obtaining bandwidth tokens from ERC20 tokens. If you don't want to set this value, use --testnet-mode instead")
|
||||||
|
.takes_value(true));
|
||||||
|
|
||||||
/// Custom path to the nym-mixnet-client configuration file
|
app
|
||||||
#[clap(long)]
|
|
||||||
config: Option<String>,
|
|
||||||
|
|
||||||
/// Address of the socks5 provider to send messages to.
|
|
||||||
#[clap(long)]
|
|
||||||
provider: Option<String>,
|
|
||||||
|
|
||||||
/// Id of the gateway we want to connect to. If overridden, it is user's responsibility to
|
|
||||||
/// ensure prior registration happened
|
|
||||||
#[clap(long)]
|
|
||||||
gateway: Option<String>,
|
|
||||||
|
|
||||||
/// Comma separated list of rest endpoints of the validators
|
|
||||||
#[clap(long)]
|
|
||||||
validators: Option<String>,
|
|
||||||
|
|
||||||
/// Port for the socket to listen on
|
|
||||||
#[clap(short, long)]
|
|
||||||
port: Option<u16>,
|
|
||||||
|
|
||||||
/// Set this client to work in a enabled credentials mode that would attempt to use gateway
|
|
||||||
/// with bandwidth credential requirement. If this value is set, --eth-endpoint and
|
|
||||||
/// --eth-private-key don't need to be set.
|
|
||||||
#[cfg(all(feature = "eth", not(feature = "coconut")))]
|
|
||||||
#[clap(long, conflicts_with_all = &["eth-endpoint", "eth-private-key"])]
|
|
||||||
enabled_credentials_mode: bool,
|
|
||||||
|
|
||||||
/// URL of an Ethereum full node that we want to use for getting bandwidth tokens from ERC20
|
|
||||||
/// tokens. If you don't want to set this value, use --enabled-credentials-mode instead
|
|
||||||
#[cfg(all(feature = "eth", not(feature = "coconut")))]
|
|
||||||
#[clap(long)]
|
|
||||||
eth_endpoint: Option<String>,
|
|
||||||
|
|
||||||
/// Ethereum private key used for obtaining bandwidth tokens from ERC20 tokens. If you don't
|
|
||||||
/// want to set this value, use --enabled-credentials-mode instead
|
|
||||||
#[cfg(all(feature = "eth", not(feature = "coconut")))]
|
|
||||||
#[clap(long)]
|
|
||||||
eth_private_key: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<Run> for OverrideConfig {
|
|
||||||
fn from(run_config: Run) -> Self {
|
|
||||||
OverrideConfig {
|
|
||||||
validators: run_config.validators,
|
|
||||||
port: run_config.port,
|
|
||||||
fastmode: false,
|
|
||||||
|
|
||||||
#[cfg(all(feature = "eth", not(feature = "coconut")))]
|
|
||||||
enabled_credentials_mode: run_config.enabled_credentials_mode,
|
|
||||||
|
|
||||||
#[cfg(all(feature = "eth", not(feature = "coconut")))]
|
|
||||||
eth_private_key: run_config.eth_private_key,
|
|
||||||
|
|
||||||
#[cfg(all(feature = "eth", not(feature = "coconut")))]
|
|
||||||
eth_endpoint: run_config.eth_endpoint,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// this only checks compatibility between config the binary. It does not take into consideration
|
// this only checks compatibility between config the binary. It does not take into consideration
|
||||||
@@ -82,13 +76,8 @@ impl From<Run> for OverrideConfig {
|
|||||||
fn version_check(cfg: &Config) -> bool {
|
fn version_check(cfg: &Config) -> bool {
|
||||||
let binary_version = env!("CARGO_PKG_VERSION");
|
let binary_version = env!("CARGO_PKG_VERSION");
|
||||||
let config_version = cfg.get_base().get_version();
|
let config_version = cfg.get_base().get_version();
|
||||||
if binary_version == config_version {
|
if binary_version != config_version {
|
||||||
true
|
warn!("The mixnode binary has different version than what is specified in config file! {} and {}", binary_version, config_version);
|
||||||
} else {
|
|
||||||
warn!(
|
|
||||||
"The mixnode binary has different version than what is specified in config file! {} and {}",
|
|
||||||
binary_version, config_version
|
|
||||||
);
|
|
||||||
if is_minor_version_compatible(binary_version, config_version) {
|
if is_minor_version_compatible(binary_version, config_version) {
|
||||||
info!("but they are still semver compatible. However, consider running the `upgrade` command");
|
info!("but they are still semver compatible. However, consider running the `upgrade` command");
|
||||||
true
|
true
|
||||||
@@ -96,11 +85,13 @@ fn version_check(cfg: &Config) -> bool {
|
|||||||
error!("and they are semver incompatible! - please run the `upgrade` command before attempting `run` again");
|
error!("and they are semver incompatible! - please run the `upgrade` command before attempting `run` again");
|
||||||
false
|
false
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) async fn execute(args: &Run) {
|
pub async fn execute(matches: ArgMatches<'static>) {
|
||||||
let id = &args.id;
|
let id = matches.value_of("id").unwrap();
|
||||||
|
|
||||||
let mut config = match Config::load_from_file(Some(id)) {
|
let mut config = match Config::load_from_file(Some(id)) {
|
||||||
Ok(cfg) => cfg,
|
Ok(cfg) => cfg,
|
||||||
@@ -110,8 +101,7 @@ pub(crate) async fn execute(args: &Run) {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let override_config_fields = OverrideConfig::from(args.clone());
|
config = override_config(config, &matches);
|
||||||
config = override_config(config, override_config_fields);
|
|
||||||
|
|
||||||
if !version_check(&config) {
|
if !version_check(&config) {
|
||||||
error!("failed the local version check");
|
error!("failed the local version check");
|
||||||
|
|||||||
@@ -2,13 +2,13 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
|
||||||
use crate::client::config::{Config, MISSING_VALUE};
|
use crate::client::config::{Config, MISSING_VALUE};
|
||||||
|
use clap::{App, Arg, ArgMatches};
|
||||||
use config::{defaults::default_api_endpoints, NymConfig};
|
use config::defaults::default_api_endpoints;
|
||||||
|
use config::NymConfig;
|
||||||
|
use std::fmt::Display;
|
||||||
|
use std::process;
|
||||||
use version_checker::Version;
|
use version_checker::Version;
|
||||||
|
|
||||||
use clap::Args;
|
|
||||||
use std::{fmt::Display, process};
|
|
||||||
|
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
fn fail_upgrade<D1: Display, D2: Display>(from_version: D1, to_version: D2) -> ! {
|
fn fail_upgrade<D1: Display, D2: Display>(from_version: D1, to_version: D2) -> ! {
|
||||||
print_failed_upgrade(from_version, to_version);
|
print_failed_upgrade(from_version, to_version);
|
||||||
@@ -49,11 +49,14 @@ fn unsupported_upgrade(current_version: &Version, config_version: &Version) -> !
|
|||||||
process::exit(1)
|
process::exit(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Args, Clone)]
|
pub fn command_args<'a, 'b>() -> App<'a, 'b> {
|
||||||
pub(crate) struct Upgrade {
|
App::new("upgrade").about("Try to upgrade the client").arg(
|
||||||
/// Id of the nym-client we want to upgrade
|
Arg::with_name("id")
|
||||||
#[clap(long)]
|
.long("id")
|
||||||
id: String,
|
.help("Id of the nym-client we want to upgrade")
|
||||||
|
.takes_value(true)
|
||||||
|
.required(true),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn parse_config_version(config: &Config) -> Version {
|
fn parse_config_version(config: &Config) -> Version {
|
||||||
@@ -92,7 +95,7 @@ fn parse_package_version() -> Version {
|
|||||||
|
|
||||||
fn minor_0_12_upgrade(
|
fn minor_0_12_upgrade(
|
||||||
mut config: Config,
|
mut config: Config,
|
||||||
_args: &Upgrade,
|
_matches: &ArgMatches<'_>,
|
||||||
config_version: &Version,
|
config_version: &Version,
|
||||||
package_version: &Version,
|
package_version: &Version,
|
||||||
) -> Config {
|
) -> Config {
|
||||||
@@ -128,30 +131,30 @@ fn minor_0_12_upgrade(
|
|||||||
config
|
config
|
||||||
}
|
}
|
||||||
|
|
||||||
fn do_upgrade(mut config: Config, args: &Upgrade, package_version: &Version) {
|
fn do_upgrade(mut config: Config, matches: &ArgMatches<'_>, package_version: Version) {
|
||||||
loop {
|
loop {
|
||||||
let config_version = parse_config_version(&config);
|
let config_version = parse_config_version(&config);
|
||||||
|
|
||||||
if &config_version == package_version {
|
if config_version == package_version {
|
||||||
println!("You're using the most recent version!");
|
println!("You're using the most recent version!");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
config = match config_version.major {
|
config = match config_version.major {
|
||||||
0 => match config_version.minor {
|
0 => match config_version.minor {
|
||||||
9 | 10 => outdated_upgrade(&config_version, package_version),
|
9 | 10 => outdated_upgrade(&config_version, &package_version),
|
||||||
11 => minor_0_12_upgrade(config, args, &config_version, package_version),
|
11 => minor_0_12_upgrade(config, matches, &config_version, &package_version),
|
||||||
_ => unsupported_upgrade(&config_version, package_version),
|
_ => unsupported_upgrade(&config_version, &package_version),
|
||||||
},
|
},
|
||||||
_ => unsupported_upgrade(&config_version, package_version),
|
_ => unsupported_upgrade(&config_version, &package_version),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn execute(args: &Upgrade) {
|
pub fn execute(matches: &ArgMatches<'_>) {
|
||||||
let package_version = parse_package_version();
|
let package_version = parse_package_version();
|
||||||
|
|
||||||
let id = &args.id;
|
let id = matches.value_of("id").unwrap();
|
||||||
|
|
||||||
let existing_config = Config::load_from_file(Some(id)).unwrap_or_else(|err| {
|
let existing_config = Config::load_from_file(Some(id)).unwrap_or_else(|err| {
|
||||||
eprintln!("failed to load existing config file! - {:?}", err);
|
eprintln!("failed to load existing config file! - {:?}", err);
|
||||||
@@ -164,5 +167,5 @@ pub(crate) fn execute(args: &Upgrade) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// here be upgrade path to 0.9.X and beyond based on version number from config
|
// here be upgrade path to 0.9.X and beyond based on version number from config
|
||||||
do_upgrade(existing_config, args, &package_version)
|
do_upgrade(existing_config, matches, package_version)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
// 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
|
||||||
|
|
||||||
use clap::{crate_version, Parser};
|
use clap::{crate_version, App, ArgMatches};
|
||||||
|
use network_defaults::DEFAULT_NETWORK;
|
||||||
|
|
||||||
pub mod client;
|
pub mod client;
|
||||||
mod commands;
|
mod commands;
|
||||||
@@ -13,8 +14,30 @@ async fn main() {
|
|||||||
setup_logging();
|
setup_logging();
|
||||||
println!("{}", banner());
|
println!("{}", banner());
|
||||||
|
|
||||||
let args = commands::Cli::parse();
|
let arg_matches = App::new("Nym Socks5 Proxy")
|
||||||
commands::execute(&args).await;
|
.version(env!("CARGO_PKG_VERSION"))
|
||||||
|
.author("Nymtech")
|
||||||
|
.long_version(&*long_version())
|
||||||
|
.about("A Socks5 localhost proxy that converts incoming messages to Sphinx and sends them to a Nym address")
|
||||||
|
.subcommand(commands::init::command_args())
|
||||||
|
.subcommand(commands::run::command_args())
|
||||||
|
.subcommand(commands::upgrade::command_args())
|
||||||
|
.get_matches();
|
||||||
|
|
||||||
|
execute(arg_matches).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn execute(matches: ArgMatches<'static>) {
|
||||||
|
match matches.subcommand() {
|
||||||
|
("init", Some(m)) => commands::init::execute(m.clone()).await,
|
||||||
|
("run", Some(m)) => commands::run::execute(m.clone()).await,
|
||||||
|
("upgrade", Some(m)) => commands::upgrade::execute(m),
|
||||||
|
_ => println!("{}", usage()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn usage() -> &'static str {
|
||||||
|
"usage: --help to see available options.\n\n"
|
||||||
}
|
}
|
||||||
|
|
||||||
fn banner() -> String {
|
fn banner() -> String {
|
||||||
@@ -34,6 +57,40 @@ fn banner() -> String {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn long_version() -> String {
|
||||||
|
format!(
|
||||||
|
r#"
|
||||||
|
{:<20}{}
|
||||||
|
{:<20}{}
|
||||||
|
{:<20}{}
|
||||||
|
{:<20}{}
|
||||||
|
{:<20}{}
|
||||||
|
{:<20}{}
|
||||||
|
{:<20}{}
|
||||||
|
{:<20}{}
|
||||||
|
{:<20}{}
|
||||||
|
"#,
|
||||||
|
"Build Timestamp:",
|
||||||
|
env!("VERGEN_BUILD_TIMESTAMP"),
|
||||||
|
"Build Version:",
|
||||||
|
env!("VERGEN_BUILD_SEMVER"),
|
||||||
|
"Commit SHA:",
|
||||||
|
env!("VERGEN_GIT_SHA"),
|
||||||
|
"Commit Date:",
|
||||||
|
env!("VERGEN_GIT_COMMIT_TIMESTAMP"),
|
||||||
|
"Commit Branch:",
|
||||||
|
env!("VERGEN_GIT_BRANCH"),
|
||||||
|
"rustc Version:",
|
||||||
|
env!("VERGEN_RUSTC_SEMVER"),
|
||||||
|
"rustc Channel:",
|
||||||
|
env!("VERGEN_RUSTC_CHANNEL"),
|
||||||
|
"cargo Profile:",
|
||||||
|
env!("VERGEN_CARGO_PROFILE"),
|
||||||
|
"Network:",
|
||||||
|
DEFAULT_NETWORK
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
fn setup_logging() {
|
fn setup_logging() {
|
||||||
let mut log_builder = pretty_env_logger::formatted_timed_builder();
|
let mut log_builder = pretty_env_logger::formatted_timed_builder();
|
||||||
if let Ok(s) = ::std::env::var("RUST_LOG") {
|
if let Ok(s) = ::std::env::var("RUST_LOG") {
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ pub(crate) enum AuthenticationMethods {
|
|||||||
NoMethods = 0xFF,
|
NoMethods = 0xFF,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
/// A socks5 user with a matching password.
|
/// A socks5 user with a matching password.
|
||||||
pub struct User {
|
pub struct User {
|
||||||
pub username: String,
|
pub username: String,
|
||||||
|
|||||||
@@ -1 +1 @@
|
|||||||
16
|
15.0.1
|
||||||
@@ -31,12 +31,9 @@
|
|||||||
"eslint-plugin-import": "^2.25.4",
|
"eslint-plugin-import": "^2.25.4",
|
||||||
"eslint-plugin-mocha": "^10.0.3",
|
"eslint-plugin-mocha": "^10.0.3",
|
||||||
"eslint-plugin-prettier": "^4.0.0",
|
"eslint-plugin-prettier": "^4.0.0",
|
||||||
"expect": "^28.1.3",
|
|
||||||
"mocha": "^10.0.0",
|
|
||||||
"prettier": "^2.5.1",
|
"prettier": "^2.5.1",
|
||||||
"typedoc": "^0.22.13",
|
"typedoc": "^0.22.13",
|
||||||
"ts-mocha": "^10.0.0",
|
"typescript": "^4.1.3"
|
||||||
"typescript": "^4.6.2"
|
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@cosmjs/cosmwasm-stargate": "^0.28.0",
|
"@cosmjs/cosmwasm-stargate": "^0.28.0",
|
||||||
|
|||||||
@@ -64,20 +64,23 @@ export default class ValidatorClient implements INymClient {
|
|||||||
|
|
||||||
readonly vestingContract: string;
|
readonly vestingContract: string;
|
||||||
|
|
||||||
readonly mainnetDenom = 'unym';
|
readonly mainnetDenom = "unym";
|
||||||
|
|
||||||
readonly mainnetPrefix = 'n';
|
readonly mainnetPrefix = "n";
|
||||||
|
|
||||||
private constructor(
|
private constructor(
|
||||||
client: SigningClient | QueryClient,
|
client: SigningClient | QueryClient,
|
||||||
prefix: string,
|
prefix: string,
|
||||||
mixnetContract: string,
|
mixnetContract: string,
|
||||||
vestingContract: string,
|
vestingContract: string
|
||||||
denom: string,
|
|
||||||
) {
|
) {
|
||||||
this.client = client;
|
this.client = client;
|
||||||
this.prefix = prefix;
|
this.prefix = prefix;
|
||||||
this.denom = `u${denom}`;
|
if (prefix == this.mainnetPrefix) {
|
||||||
|
this.denom = this.mainnetDenom;
|
||||||
|
} else {
|
||||||
|
this.denom = `u${prefix}`;
|
||||||
|
}
|
||||||
|
|
||||||
this.mixnetContract = mixnetContract;
|
this.mixnetContract = mixnetContract;
|
||||||
this.vestingContract = vestingContract;
|
this.vestingContract = vestingContract;
|
||||||
@@ -90,12 +93,11 @@ export default class ValidatorClient implements INymClient {
|
|||||||
prefix: string,
|
prefix: string,
|
||||||
mixnetContract: string,
|
mixnetContract: string,
|
||||||
vestingContract: string,
|
vestingContract: string,
|
||||||
denom: string,
|
|
||||||
): Promise<ValidatorClient> {
|
): Promise<ValidatorClient> {
|
||||||
const wallet = await ValidatorClient.buildWallet(mnemonic, prefix);
|
const wallet = await ValidatorClient.buildWallet(mnemonic, prefix);
|
||||||
|
|
||||||
const signingClient = await SigningClient.connectWithNymSigner(wallet, nymdUrl, validatorApiUrl, prefix, denom);
|
const signingClient = await SigningClient.connectWithNymSigner(wallet, nymdUrl, validatorApiUrl, prefix);
|
||||||
return new ValidatorClient(signingClient, prefix, mixnetContract, vestingContract, denom);
|
return new ValidatorClient(signingClient, prefix, mixnetContract, vestingContract);
|
||||||
}
|
}
|
||||||
|
|
||||||
static async connectForQuery(
|
static async connectForQuery(
|
||||||
@@ -104,10 +106,9 @@ export default class ValidatorClient implements INymClient {
|
|||||||
prefix: string,
|
prefix: string,
|
||||||
mixnetContract: string,
|
mixnetContract: string,
|
||||||
vestingContract: string,
|
vestingContract: string,
|
||||||
denom: string,
|
|
||||||
): Promise<ValidatorClient> {
|
): Promise<ValidatorClient> {
|
||||||
const queryClient = await QueryClient.connectWithNym(nymdUrl, validatorApiUrl);
|
const queryClient = await QueryClient.connectWithNym(nymdUrl, validatorApiUrl);
|
||||||
return new ValidatorClient(queryClient, prefix, mixnetContract, vestingContract, denom);
|
return new ValidatorClient(queryClient, prefix, mixnetContract, vestingContract);
|
||||||
}
|
}
|
||||||
|
|
||||||
public get address(): string {
|
public get address(): string {
|
||||||
@@ -456,4 +457,4 @@ export default class ValidatorClient implements INymClient {
|
|||||||
this.assertSigning();
|
this.assertSigning();
|
||||||
return (this.client as ISigningClient).updateContractStateParams(this.mixnetContract, newParams, fee, memo);
|
return (this.client as ISigningClient).updateContractStateParams(this.mixnetContract, newParams, fee, memo);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -221,12 +221,10 @@ export default class SigningClient extends SigningCosmWasmClient implements ISig
|
|||||||
nymdUrl: string,
|
nymdUrl: string,
|
||||||
validatorApiUrl: string,
|
validatorApiUrl: string,
|
||||||
prefix: string,
|
prefix: string,
|
||||||
denom: string,
|
|
||||||
): Promise<SigningClient> {
|
): Promise<SigningClient> {
|
||||||
const [{ address }] = await wallet.getAccounts();
|
const [{ address }] = await wallet.getAccounts();
|
||||||
const signerOptions: SigningCosmWasmClientOptions = {
|
const signerOptions: SigningCosmWasmClientOptions = {
|
||||||
prefix,
|
gasPrice: nymGasPrice(prefix),
|
||||||
gasPrice: nymGasPrice(denom),
|
|
||||||
};
|
};
|
||||||
const tmClient = await Tendermint34Client.connect(nymdUrl);
|
const tmClient = await Tendermint34Client.connect(nymdUrl);
|
||||||
return new SigningClient(address, validatorApiUrl, tmClient, wallet, signerOptions);
|
return new SigningClient(address, validatorApiUrl, tmClient, wallet, signerOptions);
|
||||||
|
|||||||
@@ -7,12 +7,13 @@ const mainnetDenom = 'nym';
|
|||||||
export function nymGasPrice(prefix: string): GasPrice {
|
export function nymGasPrice(prefix: string): GasPrice {
|
||||||
if (typeof prefix === 'string') {
|
if (typeof prefix === 'string') {
|
||||||
if (prefix === mainnetPrefix) {
|
if (prefix === mainnetPrefix) {
|
||||||
return GasPrice.fromString(`0.025u${mainnetDenom}`);
|
prefix = mainnetDenom;
|
||||||
}
|
}
|
||||||
return GasPrice.fromString(`0.025u${prefix}`); // TODO: ideally this ugly conversion shouldn't be hardcoded here.
|
return GasPrice.fromString(`0.025u${prefix}`); // TODO: ideally this ugly conversion shouldn't be hardcoded here.
|
||||||
}
|
}
|
||||||
|
else {
|
||||||
throw new Error(`${prefix} is not of type string`);
|
throw new Error(`${prefix} is not of type string`);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const downloadWasm = async (url: string): Promise<Uint8Array> => {
|
export const downloadWasm = async (url: string): Promise<Uint8Array> => {
|
||||||
|
|||||||
@@ -1,11 +0,0 @@
|
|||||||
import ValidatorClient from '../../dist';
|
|
||||||
import expect from 'expect';
|
|
||||||
|
|
||||||
describe('Query: balances', () => {
|
|
||||||
it('can query for an account balance', async () => {
|
|
||||||
const client = await ValidatorClient.connectForQuery(
|
|
||||||
'https://rpc.nyx.nodes.guru/', 'https://validator.nymtech.net/api/', 'n', 'n14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9sjyvg3g', 'n1nc5tatafv6eyq7llkr2gv50ff9e22mnf70qgjlv737ktmt4eswrq73f2nw', 'nym');
|
|
||||||
const balance = await client.getBalance('n10yyd98e2tuwu0f7ypz9dy3hhjw7v772q6287gy');
|
|
||||||
expect(Number.parseFloat(balance.amount)).toBeGreaterThan(0);
|
|
||||||
}).timeout(5000);
|
|
||||||
})
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
import ValidatorClient from '../../dist';
|
|
||||||
import expect from 'expect';
|
|
||||||
|
|
||||||
// TODO: implement for QA with .env for mnemonics
|
|
||||||
// describe('Sign: send', () => {
|
|
||||||
// it('can send tokens', async () => {
|
|
||||||
// const client = await ValidatorClient.connect(
|
|
||||||
// '<ADD MNEMONIC HERE>',
|
|
||||||
// 'https://rpc.nyx.nodes.guru/', 'https://validator.nymtech.net/api/', 'n', 'n14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9sjyvg3g', 'n1nc5tatafv6eyq7llkr2gv50ff9e22mnf70qgjlv737ktmt4eswrq73f2nw', 'nym');
|
|
||||||
// await client.send('<ADD ADDRESS HERE>')
|
|
||||||
// const balance = await client.getBalance('n10yyd98e2tuwu0f7ypz9dy3hhjw7v772q6287gy');
|
|
||||||
// expect(Number.parseFloat(balance.amount)).toBeGreaterThan(0);
|
|
||||||
// }).timeout(5000);
|
|
||||||
// })
|
|
||||||
@@ -5,8 +5,7 @@
|
|||||||
"esModuleInterop": true,
|
"esModuleInterop": true,
|
||||||
"strict": true,
|
"strict": true,
|
||||||
"declaration": true,
|
"declaration": true,
|
||||||
"outDir": "./dist",
|
"outDir": "./dist"
|
||||||
"skipLibCheck": true
|
|
||||||
},
|
},
|
||||||
"typedocOptions": {
|
"typedocOptions": {
|
||||||
"entryPoints": [
|
"entryPoints": [
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -5,7 +5,7 @@ use schemars::JsonSchema;
|
|||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
// Serializable structures for what we find in common/crypto
|
// Serializable structures for what we find in common/crypto
|
||||||
#[derive(Serialize, Deserialize, Copy, Clone, Debug, PartialEq, Eq, JsonSchema)]
|
#[derive(Serialize, Deserialize, Copy, Clone, Debug, PartialEq, JsonSchema)]
|
||||||
pub struct PublicKey([u8; 32]);
|
pub struct PublicKey([u8; 32]);
|
||||||
|
|
||||||
impl PublicKey {
|
impl PublicKey {
|
||||||
@@ -24,7 +24,7 @@ impl AsRef<[u8]> for PublicKey {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)]
|
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
|
||||||
pub struct Signature([u8; 32], [u8; 32]);
|
pub struct Signature([u8; 32], [u8; 32]);
|
||||||
|
|
||||||
impl Signature {
|
impl Signature {
|
||||||
|
|||||||
@@ -7,16 +7,16 @@ use serde::{Deserialize, Serialize};
|
|||||||
use crate::keys::PublicKey;
|
use crate::keys::PublicKey;
|
||||||
use crate::payment::LinkPaymentData;
|
use crate::payment::LinkPaymentData;
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)]
|
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
|
||||||
pub struct InstantiateMsg {}
|
pub struct InstantiateMsg {}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)]
|
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
|
||||||
#[serde(rename_all = "snake_case")]
|
#[serde(rename_all = "snake_case")]
|
||||||
pub enum ExecuteMsg {
|
pub enum ExecuteMsg {
|
||||||
LinkPayment { data: LinkPaymentData },
|
LinkPayment { data: LinkPaymentData },
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)]
|
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
|
||||||
#[serde(rename_all = "snake_case")]
|
#[serde(rename_all = "snake_case")]
|
||||||
pub enum QueryMsg {
|
pub enum QueryMsg {
|
||||||
GetPayments {
|
GetPayments {
|
||||||
@@ -25,6 +25,6 @@ pub enum QueryMsg {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)]
|
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
|
||||||
#[serde(rename_all = "snake_case")]
|
#[serde(rename_all = "snake_case")]
|
||||||
pub struct MigrateMsg {}
|
pub struct MigrateMsg {}
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ use serde::{Deserialize, Serialize};
|
|||||||
|
|
||||||
use crate::keys::{PublicKey, Signature};
|
use crate::keys::{PublicKey, Signature};
|
||||||
|
|
||||||
#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize, JsonSchema)]
|
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize, JsonSchema)]
|
||||||
pub struct Payment {
|
pub struct Payment {
|
||||||
verification_key: PublicKey,
|
verification_key: PublicKey,
|
||||||
gateway_identity: PublicKey,
|
gateway_identity: PublicKey,
|
||||||
@@ -27,7 +27,7 @@ impl Payment {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)]
|
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
|
||||||
pub struct LinkPaymentData {
|
pub struct LinkPaymentData {
|
||||||
pub verification_key: PublicKey,
|
pub verification_key: PublicKey,
|
||||||
pub gateway_identity: PublicKey,
|
pub gateway_identity: PublicKey,
|
||||||
@@ -51,7 +51,7 @@ impl LinkPaymentData {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize, JsonSchema)]
|
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize, JsonSchema)]
|
||||||
pub struct PagedPaymentResponse {
|
pub struct PagedPaymentResponse {
|
||||||
pub payments: Vec<Payment>,
|
pub payments: Vec<Payment>,
|
||||||
pub per_page: usize,
|
pub per_page: usize,
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ validator-api-requests = { path = "../../../validator-api/validator-api-requests
|
|||||||
async-trait = { version = "0.1.51", optional = true }
|
async-trait = { version = "0.1.51", optional = true }
|
||||||
bip39 = { version = "1", features = ["rand"], optional = true }
|
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 = { version = "0.7.0", features = ["rpc", "bip32", "cosmwasm"], 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 }
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ use crate::{validator_api, ValidatorClientError};
|
|||||||
use mixnet_contract_common::{GatewayBond, IdentityKeyRef, MixNodeBond};
|
use mixnet_contract_common::{GatewayBond, IdentityKeyRef, MixNodeBond};
|
||||||
use url::Url;
|
use url::Url;
|
||||||
use validator_api_requests::coconut::{
|
use validator_api_requests::coconut::{
|
||||||
BlindSignRequestBody, BlindedSignatureResponse, CosmosAddressResponse,
|
BlindSignRequestBody, BlindedSignatureResponse, ExecuteReleaseFundsRequestBody,
|
||||||
ProposeReleaseFundsRequestBody, ProposeReleaseFundsResponse, VerificationKeyResponse,
|
ProposeReleaseFundsRequestBody, ProposeReleaseFundsResponse, VerificationKeyResponse,
|
||||||
VerifyCredentialBody, VerifyCredentialResponse,
|
VerifyCredentialBody, VerifyCredentialResponse,
|
||||||
};
|
};
|
||||||
@@ -734,10 +734,6 @@ impl ApiClient {
|
|||||||
Ok(self.validator_api.get_coconut_verification_key().await?)
|
Ok(self.validator_api.get_coconut_verification_key().await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn get_cosmos_address(&self) -> Result<CosmosAddressResponse, ValidatorClientError> {
|
|
||||||
Ok(self.validator_api.get_cosmos_address().await?)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn verify_bandwidth_credential(
|
pub async fn verify_bandwidth_credential(
|
||||||
&self,
|
&self,
|
||||||
request_body: &VerifyCredentialBody,
|
request_body: &VerifyCredentialBody,
|
||||||
@@ -757,4 +753,14 @@ impl ApiClient {
|
|||||||
.propose_release_funds(request_body)
|
.propose_release_funds(request_body)
|
||||||
.await?)
|
.await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn execute_release_funds(
|
||||||
|
&self,
|
||||||
|
request_body: &ExecuteReleaseFundsRequestBody,
|
||||||
|
) -> Result<(), ValidatorClientError> {
|
||||||
|
Ok(self
|
||||||
|
.validator_api
|
||||||
|
.execute_release_funds(request_body)
|
||||||
|
.await?)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,14 +6,14 @@ use std::fmt;
|
|||||||
pub use cosmrs::Coin as CosmosCoin;
|
pub use cosmrs::Coin as CosmosCoin;
|
||||||
pub use cosmwasm_std::Coin as CosmWasmCoin;
|
pub use cosmwasm_std::Coin as CosmWasmCoin;
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Clone, Copy, Default, Debug, PartialEq, Eq)]
|
#[derive(Serialize, Deserialize, Clone, Copy, Default, Debug, PartialEq)]
|
||||||
pub struct MismatchedDenoms;
|
pub struct MismatchedDenoms;
|
||||||
|
|
||||||
// the reason the coin is created here as opposed to different place in the codebase is that
|
// the reason the coin is created here as opposed to different place in the codebase is that
|
||||||
// eventually we want to either publish the cosmwasm client separately or commit it to
|
// eventually we want to either publish the cosmwasm client separately or commit it to
|
||||||
// some other project, like cosmrs. Either way, in that case we can't really have
|
// some other project, like cosmrs. Either way, in that case we can't really have
|
||||||
// a dependency on an internal type
|
// a dependency on an internal type
|
||||||
#[derive(Serialize, Deserialize, Clone, Default, Debug, PartialEq, Eq)]
|
#[derive(Serialize, Deserialize, Clone, Default, Debug, PartialEq)]
|
||||||
pub struct Coin {
|
pub struct Coin {
|
||||||
pub amount: u128,
|
pub amount: u128,
|
||||||
pub denom: String,
|
pub denom: String,
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ use cosmrs::rpc::{self, HttpClient, Order};
|
|||||||
use cosmrs::tendermint::abci::Code as AbciCode;
|
use cosmrs::tendermint::abci::Code as AbciCode;
|
||||||
use cosmrs::tendermint::abci::Transaction;
|
use cosmrs::tendermint::abci::Transaction;
|
||||||
use cosmrs::tendermint::{abci, block, chain};
|
use cosmrs::tendermint::{abci, block, chain};
|
||||||
use cosmrs::{tx, AccountId, Coin as CosmosCoin, Tx};
|
use cosmrs::{tx, AccountId, Coin as CosmosCoin, Denom, Tx};
|
||||||
use prost::Message;
|
use prost::Message;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use std::convert::{TryFrom, TryInto};
|
use std::convert::{TryFrom, TryInto};
|
||||||
@@ -121,7 +121,7 @@ pub trait CosmWasmClient: rpc::Client {
|
|||||||
async fn get_balance(
|
async fn get_balance(
|
||||||
&self,
|
&self,
|
||||||
address: &AccountId,
|
address: &AccountId,
|
||||||
search_denom: String,
|
search_denom: Denom,
|
||||||
) -> Result<Option<Coin>, NymdError> {
|
) -> Result<Option<Coin>, NymdError> {
|
||||||
let path = Some("/cosmos.bank.v1beta1.Query/Balance".parse().unwrap());
|
let path = Some("/cosmos.bank.v1beta1.Query/Balance".parse().unwrap());
|
||||||
|
|
||||||
|
|||||||
@@ -12,9 +12,6 @@ use crate::nymd::{Coin, GasAdjustable, GasPrice, TxResponse};
|
|||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
use cosmrs::bank::MsgSend;
|
use cosmrs::bank::MsgSend;
|
||||||
use cosmrs::distribution::MsgWithdrawDelegatorReward;
|
use cosmrs::distribution::MsgWithdrawDelegatorReward;
|
||||||
use cosmrs::feegrant::{
|
|
||||||
AllowedMsgAllowance, BasicAllowance, MsgGrantAllowance, MsgRevokeAllowance,
|
|
||||||
};
|
|
||||||
use cosmrs::proto::cosmos::tx::signing::v1beta1::SignMode;
|
use cosmrs::proto::cosmos::tx::signing::v1beta1::SignMode;
|
||||||
use cosmrs::rpc::endpoint::broadcast;
|
use cosmrs::rpc::endpoint::broadcast;
|
||||||
use cosmrs::rpc::{Error as TendermintRpcError, HttpClient, HttpClientUrl, SimpleRequest};
|
use cosmrs::rpc::{Error as TendermintRpcError, HttpClient, HttpClientUrl, SimpleRequest};
|
||||||
@@ -26,7 +23,7 @@ use serde::Serialize;
|
|||||||
use sha2::Digest;
|
use sha2::Digest;
|
||||||
use sha2::Sha256;
|
use sha2::Sha256;
|
||||||
use std::convert::TryInto;
|
use std::convert::TryInto;
|
||||||
use std::time::{Duration, SystemTime};
|
use std::time::Duration;
|
||||||
|
|
||||||
const DEFAULT_BROADCAST_POLLING_RATE: Duration = Duration::from_secs(4);
|
const DEFAULT_BROADCAST_POLLING_RATE: Duration = Duration::from_secs(4);
|
||||||
const DEFAULT_BROADCAST_TIMEOUT: Duration = Duration::from_secs(60);
|
const DEFAULT_BROADCAST_TIMEOUT: Duration = Duration::from_secs(60);
|
||||||
@@ -423,63 +420,6 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
|
|||||||
.check_response()
|
.check_response()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(clippy::too_many_arguments)]
|
|
||||||
async fn grant_allowance(
|
|
||||||
&self,
|
|
||||||
granter: &AccountId,
|
|
||||||
grantee: &AccountId,
|
|
||||||
spend_limit: Vec<Coin>,
|
|
||||||
expiration: Option<SystemTime>,
|
|
||||||
allowed_messages: Vec<String>,
|
|
||||||
fee: Fee,
|
|
||||||
memo: impl Into<String> + Send + 'static,
|
|
||||||
) -> Result<TxResponse, NymdError> {
|
|
||||||
let basic_allowance = BasicAllowance {
|
|
||||||
spend_limit: spend_limit.into_iter().map(Into::into).collect(),
|
|
||||||
expiration,
|
|
||||||
}
|
|
||||||
.to_any()
|
|
||||||
.map_err(|_| NymdError::SerializationError("BasicAllowance".to_owned()))?;
|
|
||||||
|
|
||||||
let allowed_msg_allowance = AllowedMsgAllowance {
|
|
||||||
allowance: Some(basic_allowance),
|
|
||||||
allowed_messages,
|
|
||||||
}
|
|
||||||
.to_any()
|
|
||||||
.map_err(|_| NymdError::SerializationError("AllowedMsgAllowance".to_owned()))?;
|
|
||||||
|
|
||||||
let grant_allowance_msg = MsgGrantAllowance {
|
|
||||||
granter: granter.to_owned(),
|
|
||||||
grantee: grantee.to_owned(),
|
|
||||||
allowance: Some(allowed_msg_allowance),
|
|
||||||
}
|
|
||||||
.to_any()
|
|
||||||
.map_err(|_| NymdError::SerializationError("MsgGrantAllowance".to_owned()))?;
|
|
||||||
|
|
||||||
self.sign_and_broadcast(granter, vec![grant_allowance_msg], fee, memo)
|
|
||||||
.await?
|
|
||||||
.check_response()
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn revoke_allowance(
|
|
||||||
&self,
|
|
||||||
granter: &AccountId,
|
|
||||||
grantee: &AccountId,
|
|
||||||
fee: Fee,
|
|
||||||
memo: impl Into<String> + Send + 'static,
|
|
||||||
) -> Result<TxResponse, NymdError> {
|
|
||||||
let revoke_allowance_msg = MsgRevokeAllowance {
|
|
||||||
granter: granter.to_owned(),
|
|
||||||
grantee: grantee.to_owned(),
|
|
||||||
}
|
|
||||||
.to_any()
|
|
||||||
.map_err(|_| NymdError::SerializationError("MsgRevokeAllowance".to_owned()))?;
|
|
||||||
|
|
||||||
self.sign_and_broadcast(granter, vec![revoke_allowance_msg], fee, memo)
|
|
||||||
.await?
|
|
||||||
.check_response()
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn delegate_tokens(
|
async fn delegate_tokens(
|
||||||
&self,
|
&self,
|
||||||
delegator_address: &AccountId,
|
delegator_address: &AccountId,
|
||||||
@@ -574,10 +514,10 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
|
|||||||
let fee = match fee {
|
let fee = match fee {
|
||||||
Fee::Manual(fee) => fee,
|
Fee::Manual(fee) => fee,
|
||||||
Fee::Auto(multiplier) => auto_fee(multiplier).await?,
|
Fee::Auto(multiplier) => auto_fee(multiplier).await?,
|
||||||
Fee::PayerGranterAuto(auto_feegrant) => {
|
Fee::PayerGranterAuto(multiplier, payer, granter) => {
|
||||||
let mut fee = auto_fee(auto_feegrant.gas_adjustment).await?;
|
let mut fee = auto_fee(multiplier).await?;
|
||||||
fee.payer = auto_feegrant.payer;
|
fee.payer = payer;
|
||||||
fee.granter = auto_feegrant.granter;
|
fee.granter = granter;
|
||||||
fee
|
fee
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,11 +1,9 @@
|
|||||||
// 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
|
||||||
|
|
||||||
use crate::nymd::Coin;
|
|
||||||
use crate::nymd::Gas;
|
use crate::nymd::Gas;
|
||||||
use cosmrs::{tx, AccountId};
|
use cosmrs::{tx, AccountId};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use std::fmt::{Display, Formatter};
|
|
||||||
|
|
||||||
pub mod gas_price;
|
pub mod gas_price;
|
||||||
|
|
||||||
@@ -13,74 +11,11 @@ pub type GasAdjustment = f32;
|
|||||||
|
|
||||||
pub const DEFAULT_SIMULATED_GAS_MULTIPLIER: GasAdjustment = 1.3;
|
pub const DEFAULT_SIMULATED_GAS_MULTIPLIER: GasAdjustment = 1.3;
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
|
||||||
pub struct AutoFeeGrant {
|
|
||||||
pub gas_adjustment: Option<GasAdjustment>,
|
|
||||||
pub payer: Option<AccountId>,
|
|
||||||
pub granter: Option<AccountId>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Display for AutoFeeGrant {
|
|
||||||
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
|
||||||
if let Some(gas_adjustment) = self.gas_adjustment {
|
|
||||||
write!(f, "Feegrant in auto mode with {gas_adjustment} simulated multiplier with {:?} payer and {:?} granter", self.payer, self.granter)
|
|
||||||
} else {
|
|
||||||
write!(f, "Feegrant in auto mode with no custom simulated multiplier with {:?} payer and {:?} granter", self.payer, self.granter)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
pub enum Fee {
|
pub enum Fee {
|
||||||
Manual(#[serde(with = "sealed::TxFee")] tx::Fee),
|
Manual(#[serde(with = "sealed::TxFee")] tx::Fee),
|
||||||
Auto(Option<GasAdjustment>),
|
Auto(Option<GasAdjustment>),
|
||||||
PayerGranterAuto(AutoFeeGrant),
|
PayerGranterAuto(Option<GasAdjustment>, Option<AccountId>, Option<AccountId>),
|
||||||
}
|
|
||||||
|
|
||||||
impl Display for Fee {
|
|
||||||
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
|
||||||
match self {
|
|
||||||
Fee::Manual(fee) => {
|
|
||||||
write!(f, "Fee in manual mode with ")?;
|
|
||||||
for fee in &fee.amount {
|
|
||||||
write!(f, "{}{} paid in fees, ", fee.amount, fee.denom)?;
|
|
||||||
}
|
|
||||||
write!(f, "{} set as gas limit, ", fee.gas_limit)?;
|
|
||||||
if let Some(payer) = &fee.payer {
|
|
||||||
write!(f, "{payer} set as payer, ")?;
|
|
||||||
}
|
|
||||||
if let Some(granter) = &fee.granter {
|
|
||||||
write!(f, "{granter} set as granter")?;
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
Fee::Auto(Some(multiplier)) => {
|
|
||||||
write!(f, "Fee in auto mode with {multiplier} simulated multiplier")
|
|
||||||
}
|
|
||||||
Fee::Auto(None) => write!(f, "Fee in auto mode with no custom simulated multiplier"),
|
|
||||||
Fee::PayerGranterAuto(auto_feegrant) => write!(f, "{}", auto_feegrant),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Fee {
|
|
||||||
pub fn new_payer_granter_auto(
|
|
||||||
gas_adjustment: Option<GasAdjustment>,
|
|
||||||
payer: Option<AccountId>,
|
|
||||||
granter: Option<AccountId>,
|
|
||||||
) -> Self {
|
|
||||||
Fee::PayerGranterAuto(AutoFeeGrant {
|
|
||||||
gas_adjustment,
|
|
||||||
payer,
|
|
||||||
granter,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
pub fn try_get_manual_amount(&self) -> Option<Vec<Coin>> {
|
|
||||||
match self {
|
|
||||||
Fee::Manual(tx_fee) => Some(tx_fee.amount.iter().cloned().map(Into::into).collect()),
|
|
||||||
_ => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<tx::Fee> for Fee {
|
impl From<tx::Fee> for Fee {
|
||||||
|
|||||||
@@ -26,7 +26,6 @@ use mixnet_contract_common::{
|
|||||||
};
|
};
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
use std::convert::TryInto;
|
use std::convert::TryInto;
|
||||||
use std::time::SystemTime;
|
|
||||||
use vesting_contract_common::ExecuteMsg as VestingExecuteMsg;
|
use vesting_contract_common::ExecuteMsg as VestingExecuteMsg;
|
||||||
use vesting_contract_common::QueryMsg as VestingQueryMsg;
|
use vesting_contract_common::QueryMsg as VestingQueryMsg;
|
||||||
|
|
||||||
@@ -389,7 +388,7 @@ impl<C> NymdClient<C> {
|
|||||||
pub async fn get_balance(
|
pub async fn get_balance(
|
||||||
&self,
|
&self,
|
||||||
address: &AccountId,
|
address: &AccountId,
|
||||||
denom: String,
|
denom: Denom,
|
||||||
) -> Result<Option<Coin>, NymdError>
|
) -> Result<Option<Coin>, NymdError>
|
||||||
where
|
where
|
||||||
C: CosmWasmClient + Sync,
|
C: CosmWasmClient + Sync,
|
||||||
@@ -846,49 +845,6 @@ impl<C> NymdClient<C> {
|
|||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Grant a fee allowance from one address to another
|
|
||||||
pub async fn grant_allowance(
|
|
||||||
&self,
|
|
||||||
grantee: &AccountId,
|
|
||||||
spend_limit: Vec<Coin>,
|
|
||||||
expiration: Option<SystemTime>,
|
|
||||||
allowed_messages: Vec<String>,
|
|
||||||
memo: impl Into<String> + Send + 'static,
|
|
||||||
fee: Option<Fee>,
|
|
||||||
) -> Result<TxResponse, NymdError>
|
|
||||||
where
|
|
||||||
C: SigningCosmWasmClient + Sync,
|
|
||||||
{
|
|
||||||
let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier)));
|
|
||||||
self.client
|
|
||||||
.grant_allowance(
|
|
||||||
self.address(),
|
|
||||||
grantee,
|
|
||||||
spend_limit,
|
|
||||||
expiration,
|
|
||||||
allowed_messages,
|
|
||||||
fee,
|
|
||||||
memo,
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Revoke a fee allowance from one address to another
|
|
||||||
pub async fn revoke_allowance(
|
|
||||||
&self,
|
|
||||||
grantee: &AccountId,
|
|
||||||
memo: impl Into<String> + Send + 'static,
|
|
||||||
fee: Option<Fee>,
|
|
||||||
) -> Result<TxResponse, NymdError>
|
|
||||||
where
|
|
||||||
C: SigningCosmWasmClient + Sync,
|
|
||||||
{
|
|
||||||
let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier)));
|
|
||||||
self.client
|
|
||||||
.revoke_allowance(self.address(), grantee, fee, memo)
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn execute<M>(
|
pub async fn execute<M>(
|
||||||
&self,
|
&self,
|
||||||
contract_address: &AccountId,
|
contract_address: &AccountId,
|
||||||
|
|||||||
@@ -9,8 +9,8 @@ use std::collections::HashMap;
|
|||||||
use url::Url;
|
use url::Url;
|
||||||
use validator_api_requests::coconut::{
|
use validator_api_requests::coconut::{
|
||||||
BlindSignRequestBody, BlindedSignatureResponse, CosmosAddressResponse,
|
BlindSignRequestBody, BlindedSignatureResponse, CosmosAddressResponse,
|
||||||
ProposeReleaseFundsRequestBody, ProposeReleaseFundsResponse, VerificationKeyResponse,
|
ExecuteReleaseFundsRequestBody, ProposeReleaseFundsRequestBody, ProposeReleaseFundsResponse,
|
||||||
VerifyCredentialBody, VerifyCredentialResponse,
|
VerificationKeyResponse, VerifyCredentialBody, VerifyCredentialResponse,
|
||||||
};
|
};
|
||||||
use validator_api_requests::models::{
|
use validator_api_requests::models::{
|
||||||
CoreNodeStatusResponse, InclusionProbabilityResponse, MixNodeBondAnnotated,
|
CoreNodeStatusResponse, InclusionProbabilityResponse, MixNodeBondAnnotated,
|
||||||
@@ -422,6 +422,23 @@ impl Client {
|
|||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn execute_release_funds(
|
||||||
|
&self,
|
||||||
|
request_body: &ExecuteReleaseFundsRequestBody,
|
||||||
|
) -> Result<(), ValidatorAPIError> {
|
||||||
|
self.post_validator_api(
|
||||||
|
&[
|
||||||
|
routes::API_VERSION,
|
||||||
|
routes::COCONUT_ROUTES,
|
||||||
|
routes::BANDWIDTH,
|
||||||
|
routes::COCONUT_EXECUTE_RELEASE_FUNDS,
|
||||||
|
],
|
||||||
|
NO_PARAMS,
|
||||||
|
request_body,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// utility function that should solve the double slash problem in validator API forever.
|
// utility function that should solve the double slash problem in validator API forever.
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ pub const COCONUT_VERIFICATION_KEY: &str = "verification-key";
|
|||||||
pub const COCONUT_COSMOS_ADDRESS: &str = "cosmos-address";
|
pub const COCONUT_COSMOS_ADDRESS: &str = "cosmos-address";
|
||||||
pub const COCONUT_VERIFY_BANDWIDTH_CREDENTIAL: &str = "verify-bandwidth-credential";
|
pub const COCONUT_VERIFY_BANDWIDTH_CREDENTIAL: &str = "verify-bandwidth-credential";
|
||||||
pub const COCONUT_PROPOSE_RELEASE_FUNDS: &str = "propose-release-funds";
|
pub const COCONUT_PROPOSE_RELEASE_FUNDS: &str = "propose-release-funds";
|
||||||
|
pub const COCONUT_EXECUTE_RELEASE_FUNDS: &str = "execute-release-funds";
|
||||||
|
|
||||||
pub const STATUS_ROUTES: &str = "status";
|
pub const STATUS_ROUTES: &str = "status";
|
||||||
pub const MIXNODE: &str = "mixnode";
|
pub const MIXNODE: &str = "mixnode";
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ use error::CoconutInterfaceError;
|
|||||||
|
|
||||||
pub use nymcoconut::*;
|
pub use nymcoconut::*;
|
||||||
|
|
||||||
#[derive(Debug, Serialize, Deserialize, Getters, CopyGetters, Clone, PartialEq, Eq)]
|
#[derive(Debug, Serialize, Deserialize, Getters, CopyGetters, Clone, PartialEq)]
|
||||||
pub struct Credential {
|
pub struct Credential {
|
||||||
#[getset(get = "pub")]
|
#[getset(get = "pub")]
|
||||||
n_params: u32,
|
n_params: u32,
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
use schemars::JsonSchema;
|
use schemars::JsonSchema;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)]
|
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
|
||||||
pub struct DepositData {
|
pub struct DepositData {
|
||||||
deposit_info: String,
|
deposit_info: String,
|
||||||
identity_key: String,
|
identity_key: String,
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ use serde::{Deserialize, Serialize};
|
|||||||
|
|
||||||
use crate::deposit::DepositData;
|
use crate::deposit::DepositData;
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)]
|
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
|
||||||
pub struct InstantiateMsg {
|
pub struct InstantiateMsg {
|
||||||
pub multisig_addr: String,
|
pub multisig_addr: String,
|
||||||
pub pool_addr: String,
|
pub pool_addr: String,
|
||||||
@@ -20,10 +20,10 @@ pub enum ExecuteMsg {
|
|||||||
ReleaseFunds { funds: Coin },
|
ReleaseFunds { funds: Coin },
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)]
|
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
|
||||||
#[serde(rename_all = "snake_case")]
|
#[serde(rename_all = "snake_case")]
|
||||||
pub enum QueryMsg {}
|
pub enum QueryMsg {}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)]
|
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
|
||||||
#[serde(rename_all = "snake_case")]
|
#[serde(rename_all = "snake_case")]
|
||||||
pub struct MigrateMsg {}
|
pub struct MigrateMsg {}
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ name = "mixnet-contract-common"
|
|||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
authors = ["Jędrzej Stuczyński <andrew@nymtech.net>"]
|
authors = ["Jędrzej Stuczyński <andrew@nymtech.net>"]
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
rust-version = "1.62"
|
|
||||||
|
|
||||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||||
|
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ pub struct Delegation {
|
|||||||
pub node_identity: IdentityKey,
|
pub node_identity: IdentityKey,
|
||||||
pub amount: Coin,
|
pub amount: Coin,
|
||||||
pub block_height: u64,
|
pub block_height: u64,
|
||||||
pub proxy: Option<Addr>, // proxy address used to delegate the funds on behalf of another address
|
pub proxy: Option<Addr>, // proxy address used to delegate the funds on behalf of anouther address
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Eq for Delegation {}
|
impl Eq for Delegation {}
|
||||||
@@ -123,7 +123,7 @@ impl Display for Delegation {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize, JsonSchema)]
|
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize, JsonSchema)]
|
||||||
pub struct PagedMixDelegationsResponse {
|
pub struct PagedMixDelegationsResponse {
|
||||||
pub delegations: Vec<Delegation>,
|
pub delegations: Vec<Delegation>,
|
||||||
pub start_next_after: Option<(String, u64)>,
|
pub start_next_after: Option<(String, u64)>,
|
||||||
@@ -138,7 +138,7 @@ impl PagedMixDelegationsResponse {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize, JsonSchema)]
|
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize, JsonSchema)]
|
||||||
pub struct PagedDelegatorDelegationsResponse {
|
pub struct PagedDelegatorDelegationsResponse {
|
||||||
pub delegations: Vec<Delegation>,
|
pub delegations: Vec<Delegation>,
|
||||||
pub start_next_after: Option<IdentityKey>,
|
pub start_next_after: Option<IdentityKey>,
|
||||||
@@ -153,7 +153,7 @@ impl PagedDelegatorDelegationsResponse {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize, JsonSchema)]
|
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize, JsonSchema)]
|
||||||
pub struct PagedAllDelegationsResponse {
|
pub struct PagedAllDelegationsResponse {
|
||||||
pub delegations: Vec<Delegation>,
|
pub delegations: Vec<Delegation>,
|
||||||
pub start_next_after: Option<(IdentityKey, Vec<u8>, u64)>,
|
pub start_next_after: Option<(IdentityKey, Vec<u8>, u64)>,
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ use serde::{Deserialize, Serialize};
|
|||||||
use std::cmp::Ordering;
|
use std::cmp::Ordering;
|
||||||
use std::fmt::Display;
|
use std::fmt::Display;
|
||||||
|
|
||||||
#[derive(Clone, Debug, Deserialize, PartialEq, Eq, PartialOrd, Serialize, JsonSchema)]
|
#[derive(Clone, Debug, Deserialize, PartialEq, PartialOrd, Serialize, JsonSchema)]
|
||||||
pub struct Gateway {
|
pub struct Gateway {
|
||||||
pub host: String,
|
pub host: String,
|
||||||
pub mix_port: u16,
|
pub mix_port: u16,
|
||||||
|
|||||||
@@ -59,7 +59,7 @@ pub(crate) mod string_rfc3339_offset_date_time {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq, PartialOrd, Serialize)]
|
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, PartialOrd, Serialize)]
|
||||||
pub struct Interval {
|
pub struct Interval {
|
||||||
id: u32,
|
id: u32,
|
||||||
#[serde(with = "string_rfc3339_offset_date_time")]
|
#[serde(with = "string_rfc3339_offset_date_time")]
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ use std::fmt::Display;
|
|||||||
feature = "generate-ts",
|
feature = "generate-ts",
|
||||||
ts(export_to = "ts-packages/types/src/types/rust/RewardedSetNodeStatus.ts")
|
ts(export_to = "ts-packages/types/src/types/rust/RewardedSetNodeStatus.ts")
|
||||||
)]
|
)]
|
||||||
#[derive(Clone, Copy, Debug, Deserialize, Serialize, JsonSchema, PartialEq, Eq)]
|
#[derive(Clone, Copy, Debug, Deserialize, Serialize, JsonSchema, PartialEq)]
|
||||||
pub enum RewardedSetNodeStatus {
|
pub enum RewardedSetNodeStatus {
|
||||||
Active,
|
Active,
|
||||||
Standby,
|
Standby,
|
||||||
@@ -37,16 +37,6 @@ pub enum DelegationEvent {
|
|||||||
Undelegate(PendingUndelegate),
|
Undelegate(PendingUndelegate),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl DelegationEvent {
|
|
||||||
pub fn delegation_amount(&self) -> Option<Coin> {
|
|
||||||
match self {
|
|
||||||
DelegationEvent::Delegate(delegation) => Some(delegation.amount.clone()),
|
|
||||||
// I think it would be nice to also expose an amount here to know how much we're undelegating
|
|
||||||
DelegationEvent::Undelegate(_) => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, Deserialize, Serialize, JsonSchema)]
|
#[derive(Clone, Debug, Deserialize, Serialize, JsonSchema)]
|
||||||
pub struct PendingUndelegate {
|
pub struct PendingUndelegate {
|
||||||
mix_identity: IdentityKey,
|
mix_identity: IdentityKey,
|
||||||
@@ -116,7 +106,7 @@ impl PendingUndelegate {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, Deserialize, PartialEq, Eq, PartialOrd, Serialize, JsonSchema)]
|
#[derive(Clone, Debug, Deserialize, PartialEq, PartialOrd, Serialize, JsonSchema)]
|
||||||
pub struct MixNode {
|
pub struct MixNode {
|
||||||
pub host: String,
|
pub host: String,
|
||||||
pub mix_port: u16,
|
pub mix_port: u16,
|
||||||
@@ -255,7 +245,7 @@ impl DelegatorRewardParams {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, JsonSchema, PartialEq, Eq, Serialize, Deserialize, Copy)]
|
#[derive(Debug, Clone, JsonSchema, PartialEq, Serialize, Deserialize, Copy)]
|
||||||
pub struct StoredNodeRewardResult {
|
pub struct StoredNodeRewardResult {
|
||||||
reward: Uint128,
|
reward: Uint128,
|
||||||
|
|
||||||
|
|||||||
@@ -7,12 +7,12 @@ use crate::{Gateway, IdentityKey, MixNode};
|
|||||||
use schemars::JsonSchema;
|
use schemars::JsonSchema;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)]
|
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
|
||||||
pub struct InstantiateMsg {
|
pub struct InstantiateMsg {
|
||||||
pub rewarding_validator_address: String,
|
pub rewarding_validator_address: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)]
|
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
|
||||||
#[serde(rename_all = "snake_case")]
|
#[serde(rename_all = "snake_case")]
|
||||||
pub enum ExecuteMsg {
|
pub enum ExecuteMsg {
|
||||||
UpdateRewardingValidatorAddress {
|
UpdateRewardingValidatorAddress {
|
||||||
@@ -112,7 +112,7 @@ pub enum ExecuteMsg {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)]
|
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
|
||||||
#[serde(rename_all = "snake_case")]
|
#[serde(rename_all = "snake_case")]
|
||||||
pub enum QueryMsg {
|
pub enum QueryMsg {
|
||||||
GetCurrentOperatorCost {},
|
GetCurrentOperatorCost {},
|
||||||
@@ -205,6 +205,6 @@ pub enum QueryMsg {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)]
|
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
|
||||||
#[serde(rename_all = "snake_case")]
|
#[serde(rename_all = "snake_case")]
|
||||||
pub struct MigrateMsg {}
|
pub struct MigrateMsg {}
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ use cosmwasm_std::Uint128;
|
|||||||
use schemars::JsonSchema;
|
use schemars::JsonSchema;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
#[derive(Debug, Clone, JsonSchema, PartialEq, Eq, Serialize, Deserialize, Copy)]
|
#[derive(Debug, Clone, JsonSchema, PartialEq, Serialize, Deserialize, Copy)]
|
||||||
pub struct NodeEpochRewards {
|
pub struct NodeEpochRewards {
|
||||||
params: NodeRewardParams,
|
params: NodeRewardParams,
|
||||||
result: StoredNodeRewardResult,
|
result: StoredNodeRewardResult,
|
||||||
@@ -105,7 +105,7 @@ impl NodeEpochRewards {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, JsonSchema, PartialEq, Eq, Serialize, Deserialize, Copy)]
|
#[derive(Debug, Clone, JsonSchema, PartialEq, Serialize, Deserialize, Copy)]
|
||||||
pub struct EpochRewardParams {
|
pub struct EpochRewardParams {
|
||||||
epoch_reward_pool: Uint128,
|
epoch_reward_pool: Uint128,
|
||||||
rewarded_set_size: Uint128,
|
rewarded_set_size: Uint128,
|
||||||
@@ -175,7 +175,7 @@ impl EpochRewardParams {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, JsonSchema, PartialEq, Eq, Serialize, Deserialize, Copy)]
|
#[derive(Debug, Clone, JsonSchema, PartialEq, Serialize, Deserialize, Copy)]
|
||||||
pub struct NodeRewardParams {
|
pub struct NodeRewardParams {
|
||||||
reward_blockstamp: u64,
|
reward_blockstamp: u64,
|
||||||
uptime: Uint128,
|
uptime: Uint128,
|
||||||
@@ -208,7 +208,7 @@ impl NodeRewardParams {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, JsonSchema, PartialEq, Eq, Serialize, Deserialize, Copy)]
|
#[derive(Debug, Clone, JsonSchema, PartialEq, Serialize, Deserialize, Copy)]
|
||||||
pub struct RewardParams {
|
pub struct RewardParams {
|
||||||
pub epoch: EpochRewardParams,
|
pub epoch: EpochRewardParams,
|
||||||
pub node: NodeRewardParams,
|
pub node: NodeRewardParams,
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ impl LayerDistribution {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)]
|
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
|
||||||
pub struct ContractStateParams {
|
pub struct ContractStateParams {
|
||||||
// so currently interval_length is being unused and validator API performs rewarding
|
// so currently interval_length is being unused and validator API performs rewarding
|
||||||
// based on its own interval length config value. I guess that's fine for time being
|
// based on its own interval length config value. I guess that's fine for time being
|
||||||
@@ -72,7 +72,7 @@ impl Display for ContractStateParams {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Default, Debug, Serialize, Deserialize, PartialEq, Eq)]
|
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
|
||||||
pub struct RewardingResult {
|
pub struct RewardingResult {
|
||||||
pub node_reward: Uint128,
|
pub node_reward: Uint128,
|
||||||
}
|
}
|
||||||
@@ -124,21 +124,21 @@ pub type IdentityKey = String;
|
|||||||
pub type IdentityKeyRef<'a> = &'a str;
|
pub type IdentityKeyRef<'a> = &'a str;
|
||||||
pub type SphinxKey = String;
|
pub type SphinxKey = String;
|
||||||
|
|
||||||
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq, JsonSchema)]
|
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, JsonSchema)]
|
||||||
pub struct PagedRewardedSetResponse {
|
pub struct PagedRewardedSetResponse {
|
||||||
pub identities: Vec<(IdentityKey, RewardedSetNodeStatus)>,
|
pub identities: Vec<(IdentityKey, RewardedSetNodeStatus)>,
|
||||||
pub start_next_after: Option<IdentityKey>,
|
pub start_next_after: Option<IdentityKey>,
|
||||||
pub at_height: u64,
|
pub at_height: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize, JsonSchema)]
|
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize, JsonSchema)]
|
||||||
pub struct RewardedSetUpdateDetails {
|
pub struct RewardedSetUpdateDetails {
|
||||||
pub refresh_rate_blocks: u64,
|
pub refresh_rate_blocks: u64,
|
||||||
pub last_refreshed_block: u64,
|
pub last_refreshed_block: u64,
|
||||||
pub current_height: u64,
|
pub current_height: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize, JsonSchema)]
|
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize, JsonSchema)]
|
||||||
pub struct IntervalRewardedSetHeightsResponse {
|
pub struct IntervalRewardedSetHeightsResponse {
|
||||||
pub interval_id: u32,
|
pub interval_id: u32,
|
||||||
pub heights: Vec<u64>,
|
pub heights: Vec<u64>,
|
||||||
|
|||||||
@@ -44,7 +44,7 @@ pub enum ExecuteMsg {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// We can also add this as a cw3 extension
|
// We can also add this as a cw3 extension
|
||||||
#[derive(Serialize, Deserialize, Clone, PartialEq, Eq, JsonSchema, Debug)]
|
#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)]
|
||||||
#[serde(rename_all = "snake_case")]
|
#[serde(rename_all = "snake_case")]
|
||||||
pub enum QueryMsg {
|
pub enum QueryMsg {
|
||||||
/// Return ThresholdResponse
|
/// Return ThresholdResponse
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ pub fn one_ucoin() -> Coin {
|
|||||||
feature = "generate-ts",
|
feature = "generate-ts",
|
||||||
ts(export_to = "ts-packages/types/src/types/rust/Period.ts")
|
ts(export_to = "ts-packages/types/src/types/rust/Period.ts")
|
||||||
)]
|
)]
|
||||||
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Clone, JsonSchema)]
|
#[derive(Debug, PartialEq, Serialize, Deserialize, Clone, JsonSchema)]
|
||||||
pub enum Period {
|
pub enum Period {
|
||||||
Before,
|
Before,
|
||||||
In(usize),
|
In(usize),
|
||||||
@@ -28,8 +28,8 @@ pub enum Period {
|
|||||||
|
|
||||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
|
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
|
||||||
pub struct PledgeData {
|
pub struct PledgeData {
|
||||||
pub amount: Coin,
|
amount: Coin,
|
||||||
pub block_time: Timestamp,
|
block_time: Timestamp,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl PledgeData {
|
impl PledgeData {
|
||||||
@@ -48,9 +48,9 @@ impl PledgeData {
|
|||||||
|
|
||||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
|
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
|
||||||
pub struct OriginalVestingResponse {
|
pub struct OriginalVestingResponse {
|
||||||
pub amount: Coin,
|
amount: Coin,
|
||||||
pub number_of_periods: usize,
|
number_of_periods: usize,
|
||||||
pub period_duration: u64,
|
period_duration: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl OriginalVestingResponse {
|
impl OriginalVestingResponse {
|
||||||
|
|||||||
@@ -3,17 +3,17 @@ use mixnet_contract_common::{Gateway, IdentityKey, MixNode};
|
|||||||
use schemars::JsonSchema;
|
use schemars::JsonSchema;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)]
|
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
|
||||||
#[serde(rename_all = "snake_case")]
|
#[serde(rename_all = "snake_case")]
|
||||||
pub struct InitMsg {
|
pub struct InitMsg {
|
||||||
pub mixnet_contract_address: String,
|
pub mixnet_contract_address: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)]
|
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
|
||||||
#[serde(rename_all = "snake_case")]
|
#[serde(rename_all = "snake_case")]
|
||||||
pub struct MigrateMsg {}
|
pub struct MigrateMsg {}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema, Default)]
|
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema, Default)]
|
||||||
pub struct VestingSpecification {
|
pub struct VestingSpecification {
|
||||||
start_time: Option<u64>,
|
start_time: Option<u64>,
|
||||||
period_seconds: Option<u64>,
|
period_seconds: Option<u64>,
|
||||||
@@ -118,7 +118,7 @@ pub enum ExecuteMsg {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)]
|
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
|
||||||
#[serde(rename_all = "snake_case")]
|
#[serde(rename_all = "snake_case")]
|
||||||
pub enum QueryMsg {
|
pub enum QueryMsg {
|
||||||
LockedCoins {
|
LockedCoins {
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ edition = "2021"
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
bls12_381 = { version = "0.5", default-features = false, features = ["pairings", "alloc", "experimental"] }
|
bls12_381 = { version = "0.5", default-features = false, features = ["pairings", "alloc", "experimental"] }
|
||||||
cosmrs = { git = "https://github.com/neacsu/cosmos-rust", branch = "neacsu/feegrant_support", optional = true }
|
cosmrs = { version = "0.7.0", optional = true }
|
||||||
thiserror = "1.0"
|
thiserror = "1.0"
|
||||||
url = "2.2"
|
url = "2.2"
|
||||||
|
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ use std::ops::Neg;
|
|||||||
use zeroize::Zeroize;
|
use zeroize::Zeroize;
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
#[cfg_attr(test, derive(Clone, PartialEq, Eq))]
|
#[cfg_attr(test, derive(Clone, PartialEq))]
|
||||||
pub struct Ciphertexts {
|
pub struct Ciphertexts {
|
||||||
pub rr: [G1Projective; NUM_CHUNKS],
|
pub rr: [G1Projective; NUM_CHUNKS],
|
||||||
pub ss: [G1Projective; NUM_CHUNKS],
|
pub ss: [G1Projective; NUM_CHUNKS],
|
||||||
|
|||||||
@@ -335,7 +335,7 @@ pub fn keygen(params: &Params, mut rng: impl RngCore) -> (DecryptionKey, PublicK
|
|||||||
(dk, key_with_proof)
|
(dk, key_with_proof)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||||
pub struct PublicKey(pub(crate) G1Projective);
|
pub struct PublicKey(pub(crate) G1Projective);
|
||||||
|
|
||||||
impl PublicKey {
|
impl PublicKey {
|
||||||
@@ -345,7 +345,7 @@ impl PublicKey {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
#[cfg_attr(test, derive(PartialEq, Eq))]
|
#[cfg_attr(test, derive(PartialEq))]
|
||||||
pub struct PublicKeyWithProof {
|
pub struct PublicKeyWithProof {
|
||||||
pub(crate) key: PublicKey,
|
pub(crate) key: PublicKey,
|
||||||
pub(crate) proof: ProofOfDiscreteLog,
|
pub(crate) proof: ProofOfDiscreteLog,
|
||||||
|
|||||||
@@ -243,7 +243,7 @@ impl Zeroize for Tau {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd)]
|
#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
|
||||||
pub struct Epoch(EpochStore);
|
pub struct Epoch(EpochStore);
|
||||||
|
|
||||||
impl Epoch {
|
impl Epoch {
|
||||||
|
|||||||
@@ -68,7 +68,7 @@ impl<'a> Instance<'a> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
#[cfg_attr(test, derive(Clone, PartialEq, Eq))]
|
#[cfg_attr(test, derive(Clone, PartialEq))]
|
||||||
pub struct ProofOfChunking {
|
pub struct ProofOfChunking {
|
||||||
y0: G1Projective,
|
y0: G1Projective,
|
||||||
bb: Vec<G1Projective>,
|
bb: Vec<G1Projective>,
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ const DISCRETE_LOG_DOMAIN: &[u8] =
|
|||||||
b"NYM_COCONUT_NIDKG_V01_CS01_WITH_BLS12381_XMD:SHA-256_SSWU_RO_PROOF_DISCRETE_LOG";
|
b"NYM_COCONUT_NIDKG_V01_CS01_WITH_BLS12381_XMD:SHA-256_SSWU_RO_PROOF_DISCRETE_LOG";
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
#[cfg_attr(test, derive(PartialEq, Eq))]
|
#[cfg_attr(test, derive(PartialEq))]
|
||||||
pub struct ProofOfDiscreteLog {
|
pub struct ProofOfDiscreteLog {
|
||||||
pub(crate) rand_commitment: G1Projective,
|
pub(crate) rand_commitment: G1Projective,
|
||||||
pub(crate) response: Scalar,
|
pub(crate) response: Scalar,
|
||||||
|
|||||||
@@ -77,7 +77,7 @@ impl<'a> Instance<'a> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
#[cfg_attr(test, derive(Clone, PartialEq, Eq))]
|
#[cfg_attr(test, derive(Clone, PartialEq))]
|
||||||
pub struct ProofOfSecretSharing {
|
pub struct ProofOfSecretSharing {
|
||||||
ff: G1Projective,
|
ff: G1Projective,
|
||||||
aa: G2Projective,
|
aa: G2Projective,
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ use std::collections::BTreeMap;
|
|||||||
use zeroize::Zeroize;
|
use zeroize::Zeroize;
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
#[cfg_attr(test, derive(PartialEq, Eq))]
|
#[cfg_attr(test, derive(PartialEq))]
|
||||||
pub struct Dealing {
|
pub struct Dealing {
|
||||||
pub public_coefficients: PublicCoefficients,
|
pub public_coefficients: PublicCoefficients,
|
||||||
pub ciphertexts: Ciphertexts,
|
pub ciphertexts: Ciphertexts,
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ use rand_core::RngCore;
|
|||||||
use std::ops::{Add, Index, IndexMut};
|
use std::ops::{Add, Index, IndexMut};
|
||||||
use zeroize::Zeroize;
|
use zeroize::Zeroize;
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
pub struct PublicCoefficients {
|
pub struct PublicCoefficients {
|
||||||
pub(crate) coefficients: Vec<G2Projective>,
|
pub(crate) coefficients: Vec<G2Projective>,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
use config::defaults::DEFAULT_NETWORK;
|
use config::defaults::DEFAULT_NETWORK;
|
||||||
use subtle_encoding::bech32;
|
use subtle_encoding::bech32;
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
pub enum Bech32Error {
|
pub enum Bech32Error {
|
||||||
DecodeFailed(String),
|
DecodeFailed(String),
|
||||||
WrongPrefix(String),
|
WrongPrefix(String),
|
||||||
|
|||||||
@@ -100,10 +100,8 @@ impl Network {
|
|||||||
pub fn statistics_service_url(&self) -> &str {
|
pub fn statistics_service_url(&self) -> &str {
|
||||||
match self {
|
match self {
|
||||||
Network::MAINNET => crate::mainnet::STATISTICS_SERVICE_DOMAIN_ADDRESS,
|
Network::MAINNET => crate::mainnet::STATISTICS_SERVICE_DOMAIN_ADDRESS,
|
||||||
Network::SANDBOX => crate::mainnet::STATISTICS_SERVICE_DOMAIN_ADDRESS,
|
_ => {
|
||||||
Network::QA => crate::mainnet::STATISTICS_SERVICE_DOMAIN_ADDRESS,
|
panic!("statistics service url is only available for mainnet!")
|
||||||
Network::CUSTOM { .. } => {
|
|
||||||
panic!("statistics service url is unavailable for a custom network")
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -267,7 +267,7 @@ impl DenomDetails {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Serialize, Deserialize, Hash, Clone, PartialEq, Eq)]
|
#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
|
||||||
pub struct DenomDetailsOwned {
|
pub struct DenomDetailsOwned {
|
||||||
pub base: String,
|
pub base: String,
|
||||||
pub display: String,
|
pub display: String,
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ pub(crate) const _ETH_ERC20_CONTRACT_ADDRESS: [u8; 20] =
|
|||||||
hex_literal::hex!("0000000000000000000000000000000000000000");
|
hex_literal::hex!("0000000000000000000000000000000000000000");
|
||||||
pub(crate) const REWARDING_VALIDATOR_ADDRESS: &str = "n10yyd98e2tuwu0f7ypz9dy3hhjw7v772q6287gy";
|
pub(crate) const REWARDING_VALIDATOR_ADDRESS: &str = "n10yyd98e2tuwu0f7ypz9dy3hhjw7v772q6287gy";
|
||||||
|
|
||||||
pub(crate) const STATISTICS_SERVICE_DOMAIN_ADDRESS: &str = "http://127.0.0.1:8090";
|
pub(crate) const STATISTICS_SERVICE_DOMAIN_ADDRESS: &str = "http://mainnet-stats.nymte.ch:8090";
|
||||||
pub(crate) fn validators() -> Vec<ValidatorDetails> {
|
pub(crate) fn validators() -> Vec<ValidatorDetails> {
|
||||||
vec![ValidatorDetails::new(
|
vec![ValidatorDetails::new(
|
||||||
"https://rpc.nyx.nodes.guru/",
|
"https://rpc.nyx.nodes.guru/",
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ pub(crate) const _ETH_ERC20_CONTRACT_ADDRESS: [u8; 20] =
|
|||||||
hex_literal::hex!("0000000000000000000000000000000000000000");
|
hex_literal::hex!("0000000000000000000000000000000000000000");
|
||||||
pub(crate) const REWARDING_VALIDATOR_ADDRESS: &str = "n1tfzd4qz3a45u8p4mr5zmzv66457uwjgcl05jdq";
|
pub(crate) const REWARDING_VALIDATOR_ADDRESS: &str = "n1tfzd4qz3a45u8p4mr5zmzv66457uwjgcl05jdq";
|
||||||
|
|
||||||
pub(crate) const STATISTICS_SERVICE_DOMAIN_ADDRESS: &str = "http://0.0.0.0";
|
pub(crate) const STATISTICS_SERVICE_DOMAIN_ADDRESS: &str = "";
|
||||||
pub(crate) fn validators() -> Vec<ValidatorDetails> {
|
pub(crate) fn validators() -> Vec<ValidatorDetails> {
|
||||||
vec![ValidatorDetails::new(
|
vec![ValidatorDetails::new(
|
||||||
"https://qa-validator.nymtech.net",
|
"https://qa-validator.nymtech.net",
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ pub(crate) const _ETH_ERC20_CONTRACT_ADDRESS: [u8; 20] =
|
|||||||
hex_literal::hex!("E8883BAeF3869e14E4823F46662e81D4F7d2A81F");
|
hex_literal::hex!("E8883BAeF3869e14E4823F46662e81D4F7d2A81F");
|
||||||
pub(crate) const REWARDING_VALIDATOR_ADDRESS: &str = "nymt1jh0s6qu6tuw9ut438836mmn7f3f2wencrnmdj4";
|
pub(crate) const REWARDING_VALIDATOR_ADDRESS: &str = "nymt1jh0s6qu6tuw9ut438836mmn7f3f2wencrnmdj4";
|
||||||
|
|
||||||
pub(crate) const STATISTICS_SERVICE_DOMAIN_ADDRESS: &str = "http://0.0.0.0";
|
pub(crate) const STATISTICS_SERVICE_DOMAIN_ADDRESS: &str = "";
|
||||||
pub(crate) fn validators() -> Vec<ValidatorDetails> {
|
pub(crate) fn validators() -> Vec<ValidatorDetails> {
|
||||||
vec![ValidatorDetails::new(
|
vec![ValidatorDetails::new(
|
||||||
"https://sandbox-validator.nymtech.net",
|
"https://sandbox-validator.nymtech.net",
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ pub type EphemeralKey = Scalar;
|
|||||||
|
|
||||||
/// Two G1 points representing ElGamal ciphertext
|
/// Two G1 points representing ElGamal ciphertext
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
#[cfg_attr(test, derive(PartialEq, Eq))]
|
#[cfg_attr(test, derive(PartialEq))]
|
||||||
pub struct Ciphertext(pub(crate) G1Projective, pub(crate) G1Projective);
|
pub struct Ciphertext(pub(crate) G1Projective, pub(crate) G1Projective);
|
||||||
|
|
||||||
impl TryFrom<&[u8]> for Ciphertext {
|
impl TryFrom<&[u8]> for Ciphertext {
|
||||||
@@ -73,7 +73,7 @@ impl Ciphertext {
|
|||||||
|
|
||||||
/// PrivateKey used in the ElGamal encryption scheme to recover the plaintext
|
/// PrivateKey used in the ElGamal encryption scheme to recover the plaintext
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
#[cfg_attr(test, derive(PartialEq, Eq))]
|
#[cfg_attr(test, derive(PartialEq))]
|
||||||
pub struct PrivateKey(pub(crate) Scalar);
|
pub struct PrivateKey(pub(crate) Scalar);
|
||||||
|
|
||||||
impl PrivateKey {
|
impl PrivateKey {
|
||||||
@@ -121,7 +121,7 @@ impl Base58 for PrivateKey {}
|
|||||||
// TODO: perhaps be more explicit and apart from gamma also store generator and group order?
|
// TODO: perhaps be more explicit and apart from gamma also store generator and group order?
|
||||||
/// PublicKey used in the ElGamal encryption scheme to produce the ciphertext
|
/// PublicKey used in the ElGamal encryption scheme to produce the ciphertext
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
#[cfg_attr(test, derive(PartialEq, Eq))]
|
#[cfg_attr(test, derive(PartialEq))]
|
||||||
pub struct PublicKey(G1Projective);
|
pub struct PublicKey(G1Projective);
|
||||||
|
|
||||||
impl PublicKey {
|
impl PublicKey {
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ use crate::Attribute;
|
|||||||
type ChallengeDigest = Sha256;
|
type ChallengeDigest = Sha256;
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
#[cfg_attr(test, derive(PartialEq, Eq))]
|
#[cfg_attr(test, derive(PartialEq))]
|
||||||
pub struct ProofCmCs {
|
pub struct ProofCmCs {
|
||||||
challenge: Scalar,
|
challenge: Scalar,
|
||||||
response_opening: Scalar,
|
response_opening: Scalar,
|
||||||
@@ -327,7 +327,7 @@ impl ProofCmCs {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, PartialEq, Eq)]
|
#[derive(Debug, PartialEq)]
|
||||||
pub struct ProofKappaZeta {
|
pub struct ProofKappaZeta {
|
||||||
// c
|
// c
|
||||||
challenge: Scalar,
|
challenge: Scalar,
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ use crate::utils::{hash_g1, try_deserialize_g1_projective};
|
|||||||
// TODO NAMING: double check this one
|
// TODO NAMING: double check this one
|
||||||
// Lambda
|
// Lambda
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
#[cfg_attr(test, derive(PartialEq, Eq))]
|
#[cfg_attr(test, derive(PartialEq))]
|
||||||
pub struct BlindSignRequest {
|
pub struct BlindSignRequest {
|
||||||
// cm
|
// cm
|
||||||
commitment: G1Projective,
|
commitment: G1Projective,
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ use crate::utils::{
|
|||||||
use crate::Base58;
|
use crate::Base58;
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
#[cfg_attr(test, derive(PartialEq, Eq))]
|
#[cfg_attr(test, derive(PartialEq))]
|
||||||
pub struct SecretKey {
|
pub struct SecretKey {
|
||||||
pub(crate) x: Scalar,
|
pub(crate) x: Scalar,
|
||||||
pub(crate) ys: Vec<Scalar>,
|
pub(crate) ys: Vec<Scalar>,
|
||||||
@@ -114,7 +114,7 @@ impl Base58 for SecretKey {}
|
|||||||
|
|
||||||
// TODO: perhaps change points to affine representation
|
// TODO: perhaps change points to affine representation
|
||||||
// to make verification slightly more efficient?
|
// to make verification slightly more efficient?
|
||||||
#[derive(Debug, PartialEq, Eq, Clone)]
|
#[derive(Debug, PartialEq, Clone)]
|
||||||
pub struct VerificationKey {
|
pub struct VerificationKey {
|
||||||
// TODO add gen2 as per the paper or imply it from the fact library is using bls381?
|
// TODO add gen2 as per the paper or imply it from the fact library is using bls381?
|
||||||
pub(crate) alpha: G2Projective,
|
pub(crate) alpha: G2Projective,
|
||||||
@@ -351,7 +351,7 @@ impl Bytable for VerificationKey {
|
|||||||
impl Base58 for VerificationKey {}
|
impl Base58 for VerificationKey {}
|
||||||
|
|
||||||
#[derive(Debug, Serialize, Deserialize)]
|
#[derive(Debug, Serialize, Deserialize)]
|
||||||
#[cfg_attr(test, derive(PartialEq, Eq))]
|
#[cfg_attr(test, derive(PartialEq))]
|
||||||
pub struct KeyPair {
|
pub struct KeyPair {
|
||||||
secret_key: SecretKey,
|
secret_key: SecretKey,
|
||||||
verification_key: VerificationKey,
|
verification_key: VerificationKey,
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ pub mod verification;
|
|||||||
pub type SignerIndex = u64;
|
pub type SignerIndex = u64;
|
||||||
|
|
||||||
// (h, s)
|
// (h, s)
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||||
pub struct Signature(pub(crate) G1Projective, pub(crate) G1Projective);
|
pub struct Signature(pub(crate) G1Projective, pub(crate) G1Projective);
|
||||||
|
|
||||||
pub type PartialSignature = Signature;
|
pub type PartialSignature = Signature;
|
||||||
@@ -103,7 +103,7 @@ impl Bytable for Signature {
|
|||||||
impl Base58 for Signature {}
|
impl Base58 for Signature {}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
#[cfg_attr(test, derive(PartialEq, Eq))]
|
#[cfg_attr(test, derive(PartialEq))]
|
||||||
pub struct BlindedSignature(G1Projective, G1Projective);
|
pub struct BlindedSignature(G1Projective, G1Projective);
|
||||||
|
|
||||||
impl Bytable for BlindedSignature {
|
impl Bytable for BlindedSignature {
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ use crate::Attribute;
|
|||||||
|
|
||||||
// TODO NAMING: this whole thing
|
// TODO NAMING: this whole thing
|
||||||
// Theta
|
// Theta
|
||||||
#[derive(Debug, PartialEq, Eq)]
|
#[derive(Debug, PartialEq)]
|
||||||
pub struct Theta {
|
pub struct Theta {
|
||||||
// blinded_message (kappa)
|
// blinded_message (kappa)
|
||||||
pub blinded_message: G2Projective,
|
pub blinded_message: G2Projective,
|
||||||
|
|||||||
@@ -45,7 +45,7 @@ pub mod set;
|
|||||||
/// Both of those concepts as well as their structures, i.e. `Set` and `Fragment`
|
/// Both of those concepts as well as their structures, i.e. `Set` and `Fragment`
|
||||||
/// are further explained in the respective files.
|
/// are further explained in the respective files.
|
||||||
|
|
||||||
#[derive(PartialEq, Eq, Debug)]
|
#[derive(PartialEq, Debug)]
|
||||||
pub enum ChunkingError {
|
pub enum ChunkingError {
|
||||||
InvalidPayloadLengthError,
|
InvalidPayloadLengthError,
|
||||||
TooBigMessageToSplit,
|
TooBigMessageToSplit,
|
||||||
|
|||||||
@@ -46,7 +46,7 @@ impl FramedSphinxPacket {
|
|||||||
// Contains any metadata that might be useful for sending between mix nodes.
|
// Contains any metadata that might be useful for sending between mix nodes.
|
||||||
// TODO: in theory all those data could be put in a single `u8` by setting appropriate bits,
|
// TODO: in theory all those data could be put in a single `u8` by setting appropriate bits,
|
||||||
// but would that really be worth it?
|
// but would that really be worth it?
|
||||||
#[derive(Debug, Default, PartialEq, Eq, Copy, Clone)]
|
#[derive(Debug, Default, PartialEq, Copy, Clone)]
|
||||||
pub struct Header {
|
pub struct Header {
|
||||||
/// Represents type and consequently size of the included SphinxPacket.
|
/// Represents type and consequently size of the included SphinxPacket.
|
||||||
pub(crate) packet_size: PacketSize,
|
pub(crate) packet_size: PacketSize,
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ use std::convert::TryFrom;
|
|||||||
pub struct InvalidPacketMode;
|
pub struct InvalidPacketMode;
|
||||||
|
|
||||||
#[repr(u8)]
|
#[repr(u8)]
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||||
pub enum PacketMode {
|
pub enum PacketMode {
|
||||||
/// Represents 'normal' packet sent through the network that should be delayed by an appropriate
|
/// Represents 'normal' packet sent through the network that should be delayed by an appropriate
|
||||||
/// value at each hop.
|
/// value at each hop.
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ const EXTENDED_PACKET_SIZE: usize = HEADER_SIZE + PAYLOAD_OVERHEAD_SIZE + 32 * 1
|
|||||||
pub struct InvalidPacketSize;
|
pub struct InvalidPacketSize;
|
||||||
|
|
||||||
#[repr(u8)]
|
#[repr(u8)]
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||||
pub enum PacketSize {
|
pub enum PacketSize {
|
||||||
// for example instant messaging use case
|
// for example instant messaging use case
|
||||||
RegularPacket = 1,
|
RegularPacket = 1,
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
use std::cmp::Ordering;
|
use std::cmp::Ordering;
|
||||||
|
|
||||||
#[derive(Debug, PartialEq, Eq)]
|
#[derive(Debug, PartialEq)]
|
||||||
pub enum MessageError {
|
pub enum MessageError {
|
||||||
NoData,
|
NoData,
|
||||||
IndexTooShort,
|
IndexTooShort,
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
use crate::ConnectionId;
|
use crate::ConnectionId;
|
||||||
|
|
||||||
#[derive(Debug, PartialEq, Eq)]
|
#[derive(Debug, PartialEq)]
|
||||||
pub enum ResponseError {
|
pub enum ResponseError {
|
||||||
ConnectionIdTooShort,
|
ConnectionIdTooShort,
|
||||||
NoData,
|
NoData,
|
||||||
|
|||||||
@@ -18,4 +18,4 @@ sqlx = { version = "0.5", features = ["runtime-tokio-rustls", "chrono"]}
|
|||||||
thiserror = "1"
|
thiserror = "1"
|
||||||
tokio = { version = "1.19.1", features = [ "time" ] }
|
tokio = { version = "1.19.1", features = [ "time" ] }
|
||||||
|
|
||||||
network-defaults = { path = "../network-defaults" }
|
network-defaults = { path = "../network-defaults" }
|
||||||
@@ -34,12 +34,16 @@ pub enum StatsData {
|
|||||||
|
|
||||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||||
pub struct StatsGatewayData {
|
pub struct StatsGatewayData {
|
||||||
|
pub gateway_id: String,
|
||||||
pub inbox_count: u32,
|
pub inbox_count: u32,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl StatsGatewayData {
|
impl StatsGatewayData {
|
||||||
pub fn new(inbox_count: u32) -> Self {
|
pub fn new(gateway_id: String, inbox_count: u32) -> Self {
|
||||||
StatsGatewayData { inbox_count }
|
StatsGatewayData {
|
||||||
|
gateway_id,
|
||||||
|
inbox_count,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ url = "2.2"
|
|||||||
ts-rs = "6.1.2"
|
ts-rs = "6.1.2"
|
||||||
|
|
||||||
cosmwasm-std = "1.0.0-beta8"
|
cosmwasm-std = "1.0.0-beta8"
|
||||||
cosmrs = { git = "https://github.com/neacsu/cosmos-rust", branch = "neacsu/feegrant_support" }
|
cosmrs = "0.7.0"
|
||||||
|
|
||||||
validator-client = { path = "../../common/client-libs/validator-client", features = [
|
validator-client = { path = "../../common/client-libs/validator-client", features = [
|
||||||
"nymd-client",
|
"nymd-client",
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
use crate::currency::{CurrencyDenom, DecCoin};
|
use crate::currency::{CurrencyDenom, MajorCurrencyAmount};
|
||||||
use config::defaults::DenomDetails;
|
|
||||||
use schemars::JsonSchema;
|
use schemars::JsonSchema;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
@@ -10,20 +9,17 @@ use serde::{Deserialize, Serialize};
|
|||||||
)]
|
)]
|
||||||
#[derive(Serialize, Deserialize, JsonSchema)]
|
#[derive(Serialize, Deserialize, JsonSchema)]
|
||||||
pub struct Account {
|
pub struct Account {
|
||||||
|
pub contract_address: String,
|
||||||
pub client_address: String,
|
pub client_address: String,
|
||||||
pub base_mix_denom: String,
|
pub denom: CurrencyDenom,
|
||||||
|
|
||||||
// this should get refactored to just use a String, but for now it's fine as it reduces headache
|
|
||||||
// for others
|
|
||||||
pub display_mix_denom: CurrencyDenom,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Account {
|
impl Account {
|
||||||
pub fn new(client_address: String, mix_denom: DenomDetails) -> Self {
|
pub fn new(contract_address: String, client_address: String, denom: CurrencyDenom) -> Self {
|
||||||
Account {
|
Account {
|
||||||
|
contract_address,
|
||||||
client_address,
|
client_address,
|
||||||
base_mix_denom: mix_denom.base.to_owned(),
|
denom,
|
||||||
display_mix_denom: mix_denom.display.parse().unwrap_or_default(),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -57,15 +53,6 @@ pub struct AccountEntry {
|
|||||||
)]
|
)]
|
||||||
#[derive(Serialize, Deserialize)]
|
#[derive(Serialize, Deserialize)]
|
||||||
pub struct Balance {
|
pub struct Balance {
|
||||||
pub amount: DecCoin,
|
pub amount: MajorCurrencyAmount,
|
||||||
pub printable_balance: String,
|
pub printable_balance: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Balance {
|
|
||||||
pub fn new(amount: DecCoin) -> Self {
|
|
||||||
Balance {
|
|
||||||
printable_balance: amount.to_string(),
|
|
||||||
amount,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
+379
-408
@@ -1,29 +1,24 @@
|
|||||||
use crate::error::TypesError;
|
use crate::error::TypesError;
|
||||||
use config::defaults::all::Network;
|
use cosmrs::Denom as CosmosDenom;
|
||||||
use config::defaults::{DenomDetails, DenomDetailsOwned};
|
use cosmwasm_std::Coin as CosmWasmCoin;
|
||||||
use cosmwasm_std::Fraction;
|
|
||||||
use cosmwasm_std::{Decimal, Uint128};
|
use cosmwasm_std::{Decimal, Uint128};
|
||||||
use schemars::JsonSchema;
|
use schemars::JsonSchema;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use std::cmp::Ordering;
|
|
||||||
use std::collections::HashMap;
|
|
||||||
use std::convert::TryFrom;
|
use std::convert::TryFrom;
|
||||||
use std::fmt::{Display, Formatter};
|
use std::fmt::{Display, Formatter};
|
||||||
|
use std::ops::{Add, Mul};
|
||||||
|
use std::str::FromStr;
|
||||||
use strum::{Display, EnumString, EnumVariantNames};
|
use strum::{Display, EnumString, EnumVariantNames};
|
||||||
use validator_client::nymd::Coin;
|
use validator_client::nymd::{Coin, CosmosCoin};
|
||||||
|
|
||||||
#[cfg(feature = "generate-ts")]
|
|
||||||
use ts_rs::{Dependency, TS};
|
|
||||||
|
|
||||||
#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))]
|
#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))]
|
||||||
#[cfg_attr(
|
#[cfg_attr(
|
||||||
feature = "generate-ts",
|
feature = "generate-ts",
|
||||||
ts(export_to = "ts-packages/types/src/types/rust/CurrencyDenom.ts")
|
ts(export_to = "ts-packages/types/src/types/rust/CurrencyDenom.ts")
|
||||||
)]
|
)]
|
||||||
#[cfg_attr(feature = "generate-ts", ts(rename_all = "lowercase"))]
|
#[cfg_attr(feature = "generate-ts", ts(rename_all = "UPPERCASE"))]
|
||||||
#[derive(
|
#[derive(
|
||||||
Display,
|
Display,
|
||||||
Default,
|
|
||||||
Serialize,
|
Serialize,
|
||||||
Deserialize,
|
Deserialize,
|
||||||
Clone,
|
Clone,
|
||||||
@@ -31,15 +26,12 @@ use ts_rs::{Dependency, TS};
|
|||||||
EnumString,
|
EnumString,
|
||||||
EnumVariantNames,
|
EnumVariantNames,
|
||||||
PartialEq,
|
PartialEq,
|
||||||
Eq,
|
|
||||||
JsonSchema,
|
JsonSchema,
|
||||||
)]
|
)]
|
||||||
#[serde(rename_all = "lowercase")]
|
#[serde(rename_all = "UPPERCASE")]
|
||||||
#[strum(serialize_all = "lowercase")]
|
#[strum(serialize_all = "UPPERCASE")]
|
||||||
|
// TODO: this shouldn't be an enum...
|
||||||
pub enum CurrencyDenom {
|
pub enum CurrencyDenom {
|
||||||
#[strum(ascii_case_insensitive)]
|
|
||||||
#[default]
|
|
||||||
Unknown,
|
|
||||||
#[strum(ascii_case_insensitive)]
|
#[strum(ascii_case_insensitive)]
|
||||||
Nym,
|
Nym,
|
||||||
#[strum(ascii_case_insensitive)]
|
#[strum(ascii_case_insensitive)]
|
||||||
@@ -50,469 +42,448 @@ pub enum CurrencyDenom {
|
|||||||
Nyxt,
|
Nyxt,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub type Denom = String;
|
impl CurrencyDenom {
|
||||||
|
pub fn parse(value: &str) -> Result<CurrencyDenom, TypesError> {
|
||||||
#[derive(Debug, Default)]
|
let mut denom = value.to_string();
|
||||||
pub struct RegisteredCoins(HashMap<Denom, CoinMetadata>);
|
if denom.starts_with('u') {
|
||||||
|
denom = denom[1..].to_string();
|
||||||
impl RegisteredCoins {
|
|
||||||
pub fn default_denoms(network: Network) -> Self {
|
|
||||||
let mut network_coins = HashMap::new();
|
|
||||||
network_coins.insert(network.mix_denom().base, network.mix_denom().into());
|
|
||||||
network_coins.insert(network.stake_denom().base, network.stake_denom().into());
|
|
||||||
RegisteredCoins(network_coins)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn insert(&mut self, denom: Denom, metadata: CoinMetadata) -> Option<CoinMetadata> {
|
|
||||||
self.0.insert(denom, metadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn remove(&mut self, denom: &Denom) -> Option<CoinMetadata> {
|
|
||||||
self.0.remove(denom)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn attempt_convert_to_base_coin(&self, coin: DecCoin) -> Result<Coin, TypesError> {
|
|
||||||
// check if this is already in the base denom
|
|
||||||
if self.0.contains_key(&coin.denom) {
|
|
||||||
// if we're converting a base DecCoin it CANNOT fail, unless somebody is providing
|
|
||||||
// bullshit data on purpose : )
|
|
||||||
return coin.try_into();
|
|
||||||
} else {
|
|
||||||
// TODO: this kinda suggests we may need a better data structure
|
|
||||||
for registered_coin in self.0.values() {
|
|
||||||
if let Some(exponent) = registered_coin.get_exponent(&coin.denom) {
|
|
||||||
let amount = try_convert_decimal_to_u128(coin.try_scale_up_value(exponent)?)?;
|
|
||||||
return Ok(Coin::new(amount, ®istered_coin.base));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
Err(TypesError::UnknownCoinDenom(coin.denom))
|
match CurrencyDenom::from_str(&denom) {
|
||||||
}
|
Ok(res) => Ok(res),
|
||||||
|
Err(_e) => Err(TypesError::InvalidDenom(value.to_string())),
|
||||||
pub fn attempt_convert_to_display_dec_coin(&self, coin: Coin) -> Result<DecCoin, TypesError> {
|
|
||||||
for registered_coin in self.0.values() {
|
|
||||||
if let Some(exponent) = registered_coin.get_exponent(&coin.denom) {
|
|
||||||
// if this fails it means we haven't registered our display denom which honestly should never be the case
|
|
||||||
// unless somebody is rocking their own custom network
|
|
||||||
let display_exponent = registered_coin
|
|
||||||
.get_exponent(®istered_coin.display)
|
|
||||||
.ok_or_else(|| TypesError::UnknownCoinDenom(coin.denom.clone()))?;
|
|
||||||
|
|
||||||
return match exponent.cmp(&display_exponent) {
|
|
||||||
Ordering::Greater => {
|
|
||||||
// we need to scale up, unlikely to ever be needed but included for completion sake,
|
|
||||||
// for example if we decided to created knym with exponent 9 and wanted to convert to nym with exponent 6
|
|
||||||
Ok(DecCoin::new_scaled_up(
|
|
||||||
coin.amount,
|
|
||||||
®istered_coin.display,
|
|
||||||
exponent - display_exponent,
|
|
||||||
)?)
|
|
||||||
}
|
|
||||||
// we're already in the display denom
|
|
||||||
Ordering::Equal => Ok(coin.into()),
|
|
||||||
Ordering::Less => {
|
|
||||||
// we need to scale down, the most common case, for example we're in base unym with exponent 0 and want to convert to nym with exponent 6
|
|
||||||
Ok(DecCoin::new_scaled_down(
|
|
||||||
coin.amount,
|
|
||||||
®istered_coin.display,
|
|
||||||
display_exponent - exponent,
|
|
||||||
)?)
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Err(TypesError::UnknownCoinDenom(coin.denom))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO: should this live here?
|
|
||||||
// attempts to replicate cosmos-sdk's coin metadata
|
|
||||||
// https://docs.cosmos.network/master/architecture/adr-024-coin-metadata.html
|
|
||||||
// this way we could more easily handle multiple coin types simultaneously (like nym/nyx/nymt/nyx + local currencies)
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub struct DenomUnit {
|
|
||||||
pub denom: Denom,
|
|
||||||
pub exponent: u32,
|
|
||||||
// pub aliases: Vec<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl DenomUnit {
|
|
||||||
pub fn new(denom: Denom, exponent: u32) -> Self {
|
|
||||||
DenomUnit { denom, exponent }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub struct CoinMetadata {
|
|
||||||
pub denom_units: Vec<DenomUnit>,
|
|
||||||
pub base: Denom,
|
|
||||||
pub display: Denom,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl CoinMetadata {
|
|
||||||
pub fn new(denom_units: Vec<DenomUnit>, base: Denom, display: Denom) -> Self {
|
|
||||||
CoinMetadata {
|
|
||||||
denom_units,
|
|
||||||
base,
|
|
||||||
display,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub fn get_exponent(&self, denom: &str) -> Option<u32> {
|
impl TryFrom<CosmosDenom> for CurrencyDenom {
|
||||||
self.denom_units
|
type Error = TypesError;
|
||||||
.iter()
|
|
||||||
.find(|denom_unit| denom_unit.denom == denom)
|
fn try_from(value: CosmosDenom) -> Result<Self, Self::Error> {
|
||||||
.map(|denom_unit| denom_unit.exponent)
|
CurrencyDenom::parse(&value.to_string())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<DenomDetails> for CoinMetadata {
|
#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))]
|
||||||
fn from(denom_details: DenomDetails) -> Self {
|
#[cfg_attr(
|
||||||
CoinMetadata::new(
|
feature = "generate-ts",
|
||||||
vec![
|
ts(export_to = "ts-packages/types/src/types/rust/CurrencyStringMajorAmount.ts")
|
||||||
DenomUnit::new(denom_details.base.into(), 0),
|
)]
|
||||||
DenomUnit::new(denom_details.display.into(), denom_details.display_exponent),
|
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
|
||||||
],
|
pub struct MajorAmountString(String); // see https://github.com/Aleph-Alpha/ts-rs/issues/51 for exporting type aliases
|
||||||
denom_details.base.into(),
|
|
||||||
denom_details.display.into(),
|
#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))]
|
||||||
)
|
#[cfg_attr(
|
||||||
}
|
feature = "generate-ts",
|
||||||
|
ts(export_to = "ts-packages/types/src/types/rust/Currency.ts")
|
||||||
|
)]
|
||||||
|
// #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
|
||||||
|
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
|
||||||
|
pub struct MajorCurrencyAmount {
|
||||||
|
// temporarly going back to original impl to speed up merge
|
||||||
|
pub amount: MajorAmountString,
|
||||||
|
pub denom: CurrencyDenom,
|
||||||
|
// // temporary...
|
||||||
|
// #[cfg_attr(feature = "generate-ts", ts(skip))]
|
||||||
|
// pub coin: Coin,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<DenomDetailsOwned> for CoinMetadata {
|
// impl JsonSchema for MajorCurrencyAmount {
|
||||||
fn from(denom_details: DenomDetailsOwned) -> Self {
|
// fn schema_name() -> String {
|
||||||
CoinMetadata::new(
|
// todo!()
|
||||||
vec![
|
// }
|
||||||
DenomUnit::new(denom_details.base.clone(), 0),
|
//
|
||||||
DenomUnit::new(
|
// fn json_schema(gen: &mut SchemaGenerator) -> Schema {
|
||||||
denom_details.display.clone(),
|
// todo!()
|
||||||
denom_details.display_exponent,
|
// }
|
||||||
),
|
// }
|
||||||
],
|
|
||||||
denom_details.base,
|
|
||||||
denom_details.display,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// tries to semi-replicate cosmos-sdk's DecCoin for being able to handle tokens with decimal amounts
|
// tries to semi-replicate cosmos-sdk's DecCoin for being able to handle tokens with decimal amounts
|
||||||
// https://github.com/cosmos/cosmos-sdk/blob/v0.45.4/types/dec_coin.go
|
// https://github.com/cosmos/cosmos-sdk/blob/v0.45.4/types/dec_coin.go
|
||||||
#[derive(Serialize, Deserialize, Clone, Debug, Eq, PartialEq, JsonSchema)]
|
|
||||||
pub struct DecCoin {
|
pub struct DecCoin {
|
||||||
pub denom: Denom,
|
//
|
||||||
// Decimal is already serialized to string and using string in its schema, so lets also go straight to string for ts_rs
|
|
||||||
// todo: is `Decimal` the correct type to use? Do we want to depend on cosmwasm_std here?
|
|
||||||
pub amount: Decimal,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// I had to implement it manually to correctly set dependencies
|
impl MajorCurrencyAmount {
|
||||||
#[cfg(feature = "generate-ts")]
|
pub fn new(amount: &str, denom: CurrencyDenom) -> MajorCurrencyAmount {
|
||||||
impl TS for DecCoin {
|
MajorCurrencyAmount {
|
||||||
const EXPORT_TO: Option<&'static str> = Some("ts-packages/types/src/types/rust/DecCoin.ts");
|
amount: MajorAmountString(amount.to_string()),
|
||||||
|
denom,
|
||||||
fn decl() -> String {
|
|
||||||
format!("type {} = {};", Self::name(), Self::inline())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn name() -> String {
|
|
||||||
"DecCoin".into()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn inline() -> String {
|
|
||||||
"{ denom: CurrencyDenom, amount: string }".into()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn dependencies() -> Vec<Dependency> {
|
|
||||||
vec![Dependency::from_ty::<CurrencyDenom>()
|
|
||||||
.expect("TS was incorrectly defined on `CurrencyDenom`")]
|
|
||||||
}
|
|
||||||
|
|
||||||
fn transparent() -> bool {
|
|
||||||
false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl DecCoin {
|
|
||||||
pub fn new_base<S: Into<String>>(amount: impl Into<Uint128>, denom: S) -> Self {
|
|
||||||
DecCoin {
|
|
||||||
denom: denom.into(),
|
|
||||||
amount: Decimal::from_atomics(amount, 0).unwrap(),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn zero<S: Into<String>>(denom: S) -> Self {
|
pub fn zero(denom: &CurrencyDenom) -> MajorCurrencyAmount {
|
||||||
DecCoin {
|
MajorCurrencyAmount::new("0", denom.clone())
|
||||||
denom: denom.into(),
|
|
||||||
amount: Decimal::zero(),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
//
|
||||||
|
// pub fn from_cosmrs_coin(coin: &CosmosCoin) -> Result<MajorCurrencyAmount, TypesError> {
|
||||||
|
// MajorCurrencyAmount::from_cosmrs_decimal_and_denom(coin.amount, coin.denom.to_string())
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// pub fn from_minor_uint128_and_denom(
|
||||||
|
// amount_minor: Uint128,
|
||||||
|
// denom_minor: &str,
|
||||||
|
// ) -> Result<MajorCurrencyAmount, TypesError> {
|
||||||
|
// MajorCurrencyAmount::from_minor_decimal_and_denom(
|
||||||
|
// Decimal::from_atomics(amount_minor, 0)?,
|
||||||
|
// denom_minor,
|
||||||
|
// )
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// pub fn from_minor_decimal_and_denom(
|
||||||
|
// amount_minor: Decimal,
|
||||||
|
// denom_minor: &str,
|
||||||
|
// ) -> Result<MajorCurrencyAmount, TypesError> {
|
||||||
|
// if !(denom_minor.starts_with('u') || denom_minor.starts_with('U')) {
|
||||||
|
// return Err(TypesError::InvalidDenom(denom_minor.to_string()));
|
||||||
|
// }
|
||||||
|
// let major = amount_minor / Uint128::from(1_000_000u64);
|
||||||
|
// if let Ok(denom) = CurrencyDenom::from_str(&denom_minor[1..].to_string()) {
|
||||||
|
// return Ok(MajorCurrencyAmount {
|
||||||
|
// amount: MajorAmountString(major.to_string()),
|
||||||
|
// denom,
|
||||||
|
// });
|
||||||
|
// }
|
||||||
|
// Err(TypesError::InvalidDenom(denom_minor.to_string()))
|
||||||
|
// }
|
||||||
|
// pub fn from_decimal_and_denom(
|
||||||
|
// amount: Decimal,
|
||||||
|
// denom: String,
|
||||||
|
// ) -> Result<MajorCurrencyAmount, TypesError> {
|
||||||
|
// if denom.starts_with('u') || denom.starts_with('U') {
|
||||||
|
// return MajorCurrencyAmount::from_minor_decimal_and_denom(amount, &denom);
|
||||||
|
// }
|
||||||
|
// if let Ok(denom) = CurrencyDenom::from_str(denom.as_str()) {
|
||||||
|
// return Ok(MajorCurrencyAmount {
|
||||||
|
// amount: MajorAmountString(amount.to_string()),
|
||||||
|
// denom,
|
||||||
|
// });
|
||||||
|
// }
|
||||||
|
// Err(TypesError::InvalidDenom(denom))
|
||||||
|
// }
|
||||||
|
// pub fn from_cosmrs_decimal_and_denom(
|
||||||
|
// amount: CosmosDecimal,
|
||||||
|
// denom: String,
|
||||||
|
// ) -> Result<MajorCurrencyAmount, TypesError> {
|
||||||
|
// if denom.starts_with('u') || denom.starts_with('U') {
|
||||||
|
// return match Decimal::from_str(&amount.to_string()) {
|
||||||
|
// Ok(amount) => MajorCurrencyAmount::from_minor_decimal_and_denom(amount, &denom),
|
||||||
|
// Err(_e) => Err(TypesError::InvalidAmount(amount.to_string())),
|
||||||
|
// };
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// if let Ok(denom) = CurrencyDenom::from_str(denom.as_str()) {
|
||||||
|
// return Ok(MajorCurrencyAmount {
|
||||||
|
// amount: MajorAmountString(amount.to_string()),
|
||||||
|
// denom,
|
||||||
|
// });
|
||||||
|
// }
|
||||||
|
// Err(TypesError::InvalidDenom(denom))
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// pub fn into_cosmos_coin(self) -> CosmosCoin {
|
||||||
|
// self.coin.into()
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// pub fn to_minor_uint128(&self) -> Result<Uint128, TypesError> {
|
||||||
|
// if self.amount.0.contains('.') {
|
||||||
|
// // has a decimal point (Cosmos assumes "." is the decimal separator)
|
||||||
|
// let parts = self.amount.0.split('.');
|
||||||
|
// let str = parts.collect_vec();
|
||||||
|
// if str.is_empty() || str.len() > 2 {
|
||||||
|
// return Err(TypesError::InvalidAmount("Amount is invalid".to_string()));
|
||||||
|
// }
|
||||||
|
// if str.len() == 2 {
|
||||||
|
// // has a decimal, so check decimal places first
|
||||||
|
// if str[1].len() > 6 {
|
||||||
|
// return Err(TypesError::InvalidDenom(
|
||||||
|
// "Amount is invalid, only 6 decimal places of precision are allowed"
|
||||||
|
// .to_string(),
|
||||||
|
// ));
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// // so multiple whole part by 1e6 and add decimal part
|
||||||
|
// let whole_part = Uint128::from_str(str[0])? * Uint128::from(1_000_000u64);
|
||||||
|
//
|
||||||
|
// // TODO: has Rust got anything that deals with fixed point values, or parsing from format strings? Leading zeroes are causing issues
|
||||||
|
// return match format!("0.{}", str[1]).parse::<f64>() {
|
||||||
|
// Ok(decimal_part_float) => {
|
||||||
|
// // this makes an assumption that 6 decimal places of f64 can never lose precision
|
||||||
|
// let truncated = (decimal_part_float * 1_000_000.).trunc() as u32;
|
||||||
|
// let decimal_part = Uint128::from(truncated);
|
||||||
|
// let sum = whole_part + decimal_part;
|
||||||
|
// Ok(sum)
|
||||||
|
// }
|
||||||
|
// Err(_e) => Err(TypesError::InvalidAmount(
|
||||||
|
// "Amount decimal part is invalid".to_string(),
|
||||||
|
// )),
|
||||||
|
// };
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// let major = Uint128::from_str(&self.amount.0)?;
|
||||||
|
// let scaled = major * Uint128::new(1_000_000u128);
|
||||||
|
// Ok(scaled)
|
||||||
|
// }
|
||||||
|
|
||||||
pub fn new_scaled_up<S: Into<String>>(
|
// pub fn denom_to_string(&self) -> String {
|
||||||
base_amount: impl Into<Uint128>,
|
// self.denom.to_string()
|
||||||
denom: S,
|
// }
|
||||||
exponent: u32,
|
|
||||||
) -> Result<Self, TypesError> {
|
|
||||||
let base_amount = Decimal::from_atomics(base_amount, 0).unwrap();
|
|
||||||
Ok(DecCoin {
|
|
||||||
denom: denom.into(),
|
|
||||||
amount: try_scale_up_decimal(base_amount, exponent)?,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn new_scaled_down<S: Into<String>>(
|
|
||||||
base_amount: impl Into<Uint128>,
|
|
||||||
denom: S,
|
|
||||||
exponent: u32,
|
|
||||||
) -> Result<Self, TypesError> {
|
|
||||||
let base_amount = Decimal::from_atomics(base_amount, 0).unwrap();
|
|
||||||
Ok(DecCoin {
|
|
||||||
denom: denom.into(),
|
|
||||||
amount: try_scale_down_decimal(base_amount, exponent)?,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn try_scale_down_value(&self, exponent: u32) -> Result<Decimal, TypesError> {
|
|
||||||
try_scale_down_decimal(self.amount, exponent)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn try_scale_up_value(&self, exponent: u32) -> Result<Decimal, TypesError> {
|
|
||||||
try_scale_up_decimal(self.amount, exponent)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: should thoese live here?
|
impl Display for MajorCurrencyAmount {
|
||||||
pub fn try_scale_down_decimal(dec: Decimal, exponent: u32) -> Result<Decimal, TypesError> {
|
|
||||||
let rhs = 10u128
|
|
||||||
.checked_pow(exponent)
|
|
||||||
.ok_or(TypesError::UnsupportedExponent(exponent))?;
|
|
||||||
let denominator = dec
|
|
||||||
.denominator()
|
|
||||||
.checked_mul(rhs.into())
|
|
||||||
.map_err(|_| TypesError::UnsupportedExponent(exponent))?;
|
|
||||||
|
|
||||||
Ok(Decimal::from_ratio(dec.numerator(), denominator))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn try_scale_up_decimal(dec: Decimal, exponent: u32) -> Result<Decimal, TypesError> {
|
|
||||||
let rhs = 10u128
|
|
||||||
.checked_pow(exponent)
|
|
||||||
.ok_or(TypesError::UnsupportedExponent(exponent))?;
|
|
||||||
let denominator = dec
|
|
||||||
.denominator()
|
|
||||||
.checked_div(rhs.into())
|
|
||||||
.map_err(|_| TypesError::UnsupportedExponent(exponent))?;
|
|
||||||
|
|
||||||
Ok(Decimal::from_ratio(dec.numerator(), denominator))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn try_convert_decimal_to_u128(dec: Decimal) -> Result<u128, TypesError> {
|
|
||||||
let whole = dec.numerator() / dec.denominator();
|
|
||||||
|
|
||||||
// unwrap is fine as we're not dividing by zero here
|
|
||||||
let fractional = (dec.numerator()).checked_rem(dec.denominator()).unwrap();
|
|
||||||
|
|
||||||
// we cannot convert as we'd lose our decimal places
|
|
||||||
// (for example if somebody attempted to represent our gas price (WHICH YOU SHOULDN'T DO) as DecCoin)
|
|
||||||
if fractional != Uint128::zero() {
|
|
||||||
return Err(TypesError::LossyCoinConversion);
|
|
||||||
}
|
|
||||||
Ok(whole.u128())
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Display for DecCoin {
|
|
||||||
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
||||||
write!(f, "{} {}", self.amount, self.denom)
|
write!(f, "{} {}", self.amount.0, self.denom)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<Coin> for DecCoin {
|
// TODO: cleanup after merge
|
||||||
|
impl From<CosmosCoin> for MajorCurrencyAmount {
|
||||||
|
fn from(c: CosmosCoin) -> Self {
|
||||||
|
MajorCurrencyAmount::from(Coin::from(c))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<CosmWasmCoin> for MajorCurrencyAmount {
|
||||||
|
fn from(c: CosmWasmCoin) -> Self {
|
||||||
|
MajorCurrencyAmount::from(Coin::from(c))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<Coin> for MajorCurrencyAmount {
|
||||||
fn from(coin: Coin) -> Self {
|
fn from(coin: Coin) -> Self {
|
||||||
DecCoin::new_base(coin.amount, coin.denom)
|
// current assumption: MajorCurrencyAmount is represented as decimal with 6 decimal points
|
||||||
|
// unwrap is fine as we haven't exceeded decimal range since our coins are at max 1B in value
|
||||||
|
// (this is a weak assumption, but for solving this merge conflict it's good enough temporary workaround)
|
||||||
|
let amount = Decimal::from_atomics(coin.amount, 6).unwrap();
|
||||||
|
MajorCurrencyAmount {
|
||||||
|
amount: MajorAmountString(amount.to_string()),
|
||||||
|
denom: CurrencyDenom::parse(&coin.denom).expect("this will go away after the merge..."),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// this conversion assumes same denomination
|
// temporary...
|
||||||
impl TryFrom<DecCoin> for Coin {
|
impl From<MajorCurrencyAmount> for CosmosCoin {
|
||||||
type Error = TypesError;
|
fn from(c: MajorCurrencyAmount) -> CosmosCoin {
|
||||||
|
let c: Coin = c.into();
|
||||||
|
c.into()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn try_from(value: DecCoin) -> Result<Self, Self::Error> {
|
impl From<MajorCurrencyAmount> for CosmWasmCoin {
|
||||||
Ok(Coin {
|
fn from(c: MajorCurrencyAmount) -> CosmWasmCoin {
|
||||||
amount: try_convert_decimal_to_u128(value.try_scale_down_value(0)?)?,
|
let c: Coin = c.into();
|
||||||
denom: value.denom,
|
c.into()
|
||||||
})
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<MajorCurrencyAmount> for Coin {
|
||||||
|
fn from(c: MajorCurrencyAmount) -> Coin {
|
||||||
|
let decimal: Decimal = c
|
||||||
|
.amount
|
||||||
|
.0
|
||||||
|
.parse()
|
||||||
|
.expect("stringified amount should have been a valid decimal");
|
||||||
|
|
||||||
|
// again, temporary
|
||||||
|
let exp = Uint128::new(1000000);
|
||||||
|
let val = decimal.mul(exp);
|
||||||
|
|
||||||
|
// again, terrible assumption for denom, but it works temporarily...
|
||||||
|
Coin {
|
||||||
|
amount: val.u128(),
|
||||||
|
denom: format!("u{}", c.denom).to_lowercase(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Add for MajorCurrencyAmount {
|
||||||
|
type Output = Self;
|
||||||
|
|
||||||
|
fn add(self, rhs: Self) -> Self::Output {
|
||||||
|
// again, temporary workaround to help with merge
|
||||||
|
(Coin::from(self).try_add(&Coin::from(rhs)))
|
||||||
|
.expect("provided coins had different denoms")
|
||||||
|
.into()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod test {
|
mod test {
|
||||||
use super::*;
|
use super::*;
|
||||||
use std::convert::TryFrom;
|
use cosmrs::Coin as CosmosCoin;
|
||||||
|
use cosmrs::Decimal as CosmosDecimal;
|
||||||
|
use cosmrs::Denom as CosmosDenom;
|
||||||
|
use cosmwasm_std::Coin as CosmWasmCoin;
|
||||||
|
use cosmwasm_std::Decimal as CosmWasmDecimal;
|
||||||
|
use serde_json::json;
|
||||||
|
use std::str::FromStr;
|
||||||
use std::string::ToString;
|
use std::string::ToString;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn dec_value_scale_down() {
|
fn json_to_major_currency_amount() {
|
||||||
let dec = DecCoin {
|
let nym = json!({
|
||||||
denom: "foo".to_string(),
|
"amount": "1",
|
||||||
amount: "1234007000".parse().unwrap(),
|
"denom": "NYM"
|
||||||
};
|
});
|
||||||
|
let nymt = json!({
|
||||||
|
"amount": "1",
|
||||||
|
"denom": "NYMT"
|
||||||
|
});
|
||||||
|
|
||||||
|
let test_nym_amount = MajorCurrencyAmount::new("1", CurrencyDenom::Nym);
|
||||||
|
let test_nymt_amount = MajorCurrencyAmount::new("1", CurrencyDenom::Nymt);
|
||||||
|
|
||||||
|
let nym_amount = serde_json::from_value::<MajorCurrencyAmount>(nym).unwrap();
|
||||||
|
let nymt_amount = serde_json::from_value::<MajorCurrencyAmount>(nymt).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(nym_amount, test_nym_amount);
|
||||||
|
assert_eq!(nymt_amount, test_nymt_amount);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn minor_amount_json_to_major_currency_amount() {
|
||||||
|
let one_micro_nym = json!({
|
||||||
|
"amount": "0.000001",
|
||||||
|
"denom": "NYM"
|
||||||
|
});
|
||||||
|
|
||||||
|
let expected_nym_amount = MajorCurrencyAmount::new("0.000001", CurrencyDenom::Nym);
|
||||||
|
let actual_nym_amount =
|
||||||
|
serde_json::from_value::<MajorCurrencyAmount>(one_micro_nym).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(expected_nym_amount, actual_nym_amount);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn denom_from_str() {
|
||||||
|
assert_eq!(CurrencyDenom::from_str("nym").unwrap(), CurrencyDenom::Nym);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
"1234007000".parse::<Decimal>().unwrap(),
|
CurrencyDenom::from_str("nymt").unwrap(),
|
||||||
dec.try_scale_down_value(0).unwrap()
|
CurrencyDenom::Nymt
|
||||||
);
|
);
|
||||||
|
assert_eq!(CurrencyDenom::from_str("NYM").unwrap(), CurrencyDenom::Nym);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
"123400700".parse::<Decimal>().unwrap(),
|
CurrencyDenom::from_str("NYMT").unwrap(),
|
||||||
dec.try_scale_down_value(1).unwrap()
|
CurrencyDenom::Nymt
|
||||||
);
|
);
|
||||||
|
assert_eq!(CurrencyDenom::from_str("NyM").unwrap(), CurrencyDenom::Nym);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
"12340070".parse::<Decimal>().unwrap(),
|
CurrencyDenom::from_str("NYmt").unwrap(),
|
||||||
dec.try_scale_down_value(2).unwrap()
|
CurrencyDenom::Nymt
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
"123400.7".parse::<Decimal>().unwrap(),
|
|
||||||
dec.try_scale_down_value(4).unwrap()
|
|
||||||
);
|
);
|
||||||
|
|
||||||
let dec = DecCoin {
|
assert!(matches!(
|
||||||
denom: "foo".to_string(),
|
CurrencyDenom::from_str("foo").unwrap_err(),
|
||||||
amount: "10000000000".parse().unwrap(),
|
strum::ParseError::VariantNotFound,
|
||||||
};
|
));
|
||||||
|
|
||||||
|
// denominations must all be major
|
||||||
|
assert!(matches!(
|
||||||
|
CurrencyDenom::from_str("unym").unwrap_err(),
|
||||||
|
strum::ParseError::VariantNotFound,
|
||||||
|
));
|
||||||
|
assert!(matches!(
|
||||||
|
CurrencyDenom::from_str("unymt").unwrap_err(),
|
||||||
|
strum::ParseError::VariantNotFound,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn to_string() {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
"100".parse::<Decimal>().unwrap(),
|
MajorCurrencyAmount::new("1", CurrencyDenom::Nym).to_string(),
|
||||||
dec.try_scale_down_value(8).unwrap()
|
"1 NYM"
|
||||||
);
|
);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
"1".parse::<Decimal>().unwrap(),
|
MajorCurrencyAmount::new("1", CurrencyDenom::Nymt).to_string(),
|
||||||
dec.try_scale_down_value(10).unwrap()
|
"1 NYMT"
|
||||||
);
|
);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
"0.01".parse::<Decimal>().unwrap(),
|
MajorCurrencyAmount::new("1000000000000", CurrencyDenom::Nym).to_string(),
|
||||||
dec.try_scale_down_value(12).unwrap()
|
"1000000000000 NYM"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn dec_value_scale_up() {
|
fn minor_coin_to_major_currency() {
|
||||||
let dec = DecCoin {
|
let cosmos_coin = CosmosCoin {
|
||||||
denom: "foo".to_string(),
|
amount: CosmosDecimal::from(1u64),
|
||||||
amount: "1234.56".parse().unwrap(),
|
denom: CosmosDenom::from_str("unym").unwrap(),
|
||||||
};
|
};
|
||||||
|
let c = MajorCurrencyAmount::from(cosmos_coin);
|
||||||
|
assert_eq!(c, MajorCurrencyAmount::new("0.000001", CurrencyDenom::Nym));
|
||||||
|
}
|
||||||
|
|
||||||
assert_eq!(
|
#[test]
|
||||||
"1234.56".parse::<Decimal>().unwrap(),
|
fn minor_cosmwasm_coin_to_major_currency() {
|
||||||
dec.try_scale_up_value(0).unwrap()
|
let coin = CosmWasmCoin {
|
||||||
);
|
amount: Uint128::from(1u64),
|
||||||
assert_eq!(
|
denom: "unym".to_string(),
|
||||||
"12345.6".parse::<Decimal>().unwrap(),
|
|
||||||
dec.try_scale_up_value(1).unwrap()
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
"123456".parse::<Decimal>().unwrap(),
|
|
||||||
dec.try_scale_up_value(2).unwrap()
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
"1234560".parse::<Decimal>().unwrap(),
|
|
||||||
dec.try_scale_up_value(3).unwrap()
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
"12345600".parse::<Decimal>().unwrap(),
|
|
||||||
dec.try_scale_up_value(4).unwrap()
|
|
||||||
);
|
|
||||||
|
|
||||||
let dec = DecCoin {
|
|
||||||
denom: "foo".to_string(),
|
|
||||||
amount: "0.00000123".parse().unwrap(),
|
|
||||||
};
|
};
|
||||||
|
println!(
|
||||||
assert_eq!(
|
"from_atomics = {}",
|
||||||
"0.0000123".parse::<Decimal>().unwrap(),
|
CosmWasmDecimal::from_atomics(coin.amount, 6).unwrap()
|
||||||
dec.try_scale_up_value(1).unwrap()
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
"0.000123".parse::<Decimal>().unwrap(),
|
|
||||||
dec.try_scale_up_value(2).unwrap()
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
"123".parse::<Decimal>().unwrap(),
|
|
||||||
dec.try_scale_up_value(8).unwrap()
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
"1230".parse::<Decimal>().unwrap(),
|
|
||||||
dec.try_scale_up_value(9).unwrap()
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
"12300".parse::<Decimal>().unwrap(),
|
|
||||||
dec.try_scale_up_value(10).unwrap()
|
|
||||||
);
|
);
|
||||||
|
let c: MajorCurrencyAmount = coin.into();
|
||||||
|
assert_eq!(c, MajorCurrencyAmount::new("0.000001", CurrencyDenom::Nym));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn coin_to_dec_coin() {
|
fn minor_cosmwasm_coin_to_major_currency_2() {
|
||||||
let coin = Coin::new(123, "foo");
|
let coin = CosmWasmCoin {
|
||||||
let dec = DecCoin::from(coin.clone());
|
amount: Uint128::from(1_000_000u64),
|
||||||
assert_eq!(coin.denom, dec.denom);
|
denom: "unym".to_string(),
|
||||||
assert_eq!(dec.amount, Decimal::from_atomics(coin.amount, 0).unwrap());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn dec_coin_to_coin() {
|
|
||||||
let dec = DecCoin {
|
|
||||||
denom: "foo".to_string(),
|
|
||||||
amount: "123".parse().unwrap(),
|
|
||||||
};
|
};
|
||||||
let coin = Coin::try_from(dec.clone()).unwrap();
|
println!(
|
||||||
assert_eq!(dec.denom, coin.denom);
|
"from_atomics = {:?}",
|
||||||
assert_eq!(coin.amount, 123u128);
|
CosmWasmDecimal::from_atomics(coin.amount, 6)
|
||||||
|
.unwrap()
|
||||||
|
.to_string()
|
||||||
|
);
|
||||||
|
let c: MajorCurrencyAmount = coin.into();
|
||||||
|
assert_eq!(c, MajorCurrencyAmount::new("1", CurrencyDenom::Nym));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn converting_to_display() {
|
fn major_currency_to_minor_cosmos_coin() {
|
||||||
let reg = RegisteredCoins::default_denoms(Network::MAINNET);
|
let expected_cosmos_coin = CosmosCoin {
|
||||||
let values = vec![
|
amount: CosmosDecimal::from(1u64),
|
||||||
(1u128, "0.000001"),
|
denom: CosmosDenom::from_str("unym").unwrap(),
|
||||||
(10u128, "0.00001"),
|
};
|
||||||
(100u128, "0.0001"),
|
let c = MajorCurrencyAmount::new("0.000001", CurrencyDenom::Nym);
|
||||||
(1000u128, "0.001"),
|
let minor_cosmos_coin = c.into();
|
||||||
(10000u128, "0.01"),
|
assert_eq!(expected_cosmos_coin, minor_cosmos_coin);
|
||||||
(100000u128, "0.1"),
|
assert_eq!("unym", minor_cosmos_coin.denom.to_string());
|
||||||
(1000000u128, "1"),
|
|
||||||
(1234567u128, "1.234567"),
|
|
||||||
(123456700u128, "123.4567"),
|
|
||||||
];
|
|
||||||
|
|
||||||
for (raw, expected) in values {
|
|
||||||
let coin = Coin::new(raw, Network::MAINNET.mix_denom().base);
|
|
||||||
let display = reg.attempt_convert_to_display_dec_coin(coin).unwrap();
|
|
||||||
assert_eq!(Network::MAINNET.mix_denom().display, display.denom);
|
|
||||||
assert_eq!(expected, display.amount.to_string());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn converting_to_base() {
|
fn major_currency_to_minor_cosmos_coin_2() {
|
||||||
let reg = RegisteredCoins::default_denoms(Network::MAINNET);
|
let expected_cosmos_coin = CosmosCoin {
|
||||||
let values = vec![
|
amount: CosmosDecimal::from(1000000u64),
|
||||||
(1u128, "0.000001"),
|
denom: CosmosDenom::from_str("unym").unwrap(),
|
||||||
(10u128, "0.00001"),
|
};
|
||||||
(100u128, "0.0001"),
|
let c = MajorCurrencyAmount::new("1", CurrencyDenom::Nym);
|
||||||
(1000u128, "0.001"),
|
let minor_cosmos_coin = c.into();
|
||||||
(10000u128, "0.01"),
|
assert_eq!(expected_cosmos_coin, minor_cosmos_coin);
|
||||||
(100000u128, "0.1"),
|
assert_eq!("unym", minor_cosmos_coin.denom.to_string());
|
||||||
(1000000u128, "1"),
|
}
|
||||||
(1234567u128, "1.234567"),
|
|
||||||
(123456700u128, "123.4567"),
|
|
||||||
];
|
|
||||||
|
|
||||||
for (expected, raw_display) in values {
|
#[test]
|
||||||
let coin = DecCoin {
|
fn minor_cosmos_coin_to_major_currency_string() {
|
||||||
denom: Network::MAINNET.mix_denom().display.into(),
|
// check minor cosmos coin is converted to major value
|
||||||
amount: raw_display.parse().unwrap(),
|
let cosmos_coin = CosmosCoin {
|
||||||
};
|
amount: CosmosDecimal::from(1u64),
|
||||||
let base = reg.attempt_convert_to_base_coin(coin).unwrap();
|
denom: CosmosDenom::from_str("unym").unwrap(),
|
||||||
assert_eq!(Network::MAINNET.mix_denom().base, base.denom);
|
};
|
||||||
assert_eq!(expected, base.amount);
|
let c = MajorCurrencyAmount::from(cosmos_coin);
|
||||||
}
|
assert_eq!(c.to_string(), "0.000001 NYM");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn denom_to_string() {
|
||||||
|
let c = MajorCurrencyAmount::new("1", CurrencyDenom::Nym);
|
||||||
|
let denom = c.denom.to_string();
|
||||||
|
assert_eq!(denom, "NYM".to_string());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+112
-47
@@ -1,36 +1,48 @@
|
|||||||
use crate::currency::{DecCoin, RegisteredCoins};
|
use schemars::JsonSchema;
|
||||||
use crate::error::TypesError;
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
use log::error;
|
||||||
use mixnet_contract_common::mixnode::DelegationEvent as ContractDelegationEvent;
|
use mixnet_contract_common::mixnode::DelegationEvent as ContractDelegationEvent;
|
||||||
use mixnet_contract_common::mixnode::PendingUndelegate as ContractPendingUndelegate;
|
use mixnet_contract_common::mixnode::PendingUndelegate as ContractPendingUndelegate;
|
||||||
use mixnet_contract_common::Delegation as MixnetContractDelegation;
|
use mixnet_contract_common::Delegation as MixnetContractDelegation;
|
||||||
use schemars::JsonSchema;
|
|
||||||
use serde::{Deserialize, Serialize};
|
use crate::currency::MajorCurrencyAmount;
|
||||||
|
use crate::error::TypesError;
|
||||||
|
|
||||||
#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))]
|
#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))]
|
||||||
#[cfg_attr(
|
#[cfg_attr(
|
||||||
feature = "generate-ts",
|
feature = "generate-ts",
|
||||||
ts(export_to = "ts-packages/types/src/types/rust/Delegation.ts")
|
ts(export_to = "ts-packages/types/src/types/rust/Delegation.ts")
|
||||||
)]
|
)]
|
||||||
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq, JsonSchema)]
|
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, JsonSchema)]
|
||||||
pub struct Delegation {
|
pub struct Delegation {
|
||||||
pub owner: String,
|
pub owner: String,
|
||||||
pub node_identity: String,
|
pub node_identity: String,
|
||||||
pub amount: DecCoin,
|
pub amount: MajorCurrencyAmount,
|
||||||
pub block_height: u64,
|
pub block_height: u64,
|
||||||
pub proxy: Option<String>, // proxy address used to delegate the funds on behalf of another address
|
pub proxy: Option<String>, // proxy address used to delegate the funds on behalf of another address
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Delegation {
|
impl TryFrom<MixnetContractDelegation> for Delegation {
|
||||||
pub fn from_mixnet_contract(
|
type Error = TypesError;
|
||||||
delegation: MixnetContractDelegation,
|
|
||||||
reg: &RegisteredCoins,
|
fn try_from(value: MixnetContractDelegation) -> Result<Self, Self::Error> {
|
||||||
) -> Result<Self, TypesError> {
|
let MixnetContractDelegation {
|
||||||
|
owner,
|
||||||
|
node_identity,
|
||||||
|
amount,
|
||||||
|
block_height,
|
||||||
|
proxy,
|
||||||
|
} = value;
|
||||||
|
|
||||||
|
let amount: MajorCurrencyAmount = amount.into();
|
||||||
|
|
||||||
Ok(Delegation {
|
Ok(Delegation {
|
||||||
owner: delegation.owner.to_string(),
|
owner: owner.into_string(),
|
||||||
node_identity: delegation.node_identity,
|
node_identity,
|
||||||
amount: reg.attempt_convert_to_display_dec_coin(delegation.amount.into())?,
|
amount,
|
||||||
block_height: delegation.block_height,
|
block_height,
|
||||||
proxy: delegation.proxy.map(|d| d.to_string()),
|
proxy: proxy.map(|p| p.into_string()),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -40,9 +52,9 @@ impl Delegation {
|
|||||||
feature = "generate-ts",
|
feature = "generate-ts",
|
||||||
ts(export_to = "ts-packages/types/src/types/rust/DelegationRecord.ts")
|
ts(export_to = "ts-packages/types/src/types/rust/DelegationRecord.ts")
|
||||||
)]
|
)]
|
||||||
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq, JsonSchema)]
|
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, JsonSchema)]
|
||||||
pub struct DelegationRecord {
|
pub struct DelegationRecord {
|
||||||
pub amount: DecCoin,
|
pub amount: MajorCurrencyAmount,
|
||||||
pub block_height: u64,
|
pub block_height: u64,
|
||||||
pub delegated_on_iso_datetime: String,
|
pub delegated_on_iso_datetime: String,
|
||||||
pub uses_vesting_contract_tokens: bool,
|
pub uses_vesting_contract_tokens: bool,
|
||||||
@@ -57,16 +69,16 @@ pub struct DelegationRecord {
|
|||||||
pub struct DelegationWithEverything {
|
pub struct DelegationWithEverything {
|
||||||
pub owner: String,
|
pub owner: String,
|
||||||
pub node_identity: String,
|
pub node_identity: String,
|
||||||
pub amount: DecCoin,
|
pub amount: MajorCurrencyAmount,
|
||||||
pub total_delegation: Option<DecCoin>,
|
pub total_delegation: Option<MajorCurrencyAmount>,
|
||||||
pub pledge_amount: Option<DecCoin>,
|
pub pledge_amount: Option<MajorCurrencyAmount>,
|
||||||
pub block_height: u64,
|
pub block_height: u64,
|
||||||
pub delegated_on_iso_datetime: String,
|
pub delegated_on_iso_datetime: String,
|
||||||
pub profit_margin_percent: Option<u8>,
|
pub profit_margin_percent: Option<u8>,
|
||||||
pub avg_uptime_percent: Option<u8>,
|
pub avg_uptime_percent: Option<u8>,
|
||||||
pub stake_saturation: Option<f32>,
|
pub stake_saturation: Option<f32>,
|
||||||
pub uses_vesting_contract_tokens: bool,
|
pub uses_vesting_contract_tokens: bool,
|
||||||
pub accumulated_rewards: Option<DecCoin>,
|
pub accumulated_rewards: Option<MajorCurrencyAmount>,
|
||||||
pub pending_events: Vec<DelegationEvent>,
|
pub pending_events: Vec<DelegationEvent>,
|
||||||
pub history: Vec<DelegationRecord>,
|
pub history: Vec<DelegationRecord>,
|
||||||
}
|
}
|
||||||
@@ -76,11 +88,38 @@ pub struct DelegationWithEverything {
|
|||||||
feature = "generate-ts",
|
feature = "generate-ts",
|
||||||
ts(export_to = "ts-packages/types/src/types/rust/DelegationResult.ts")
|
ts(export_to = "ts-packages/types/src/types/rust/DelegationResult.ts")
|
||||||
)]
|
)]
|
||||||
#[derive(Serialize, Deserialize, JsonSchema, Clone, PartialEq, Eq, Debug)]
|
#[derive(Serialize, Deserialize, JsonSchema, Clone, PartialEq, Debug)]
|
||||||
pub struct DelegationResult {
|
pub struct DelegationResult {
|
||||||
source_address: String,
|
source_address: String,
|
||||||
target_address: String,
|
target_address: String,
|
||||||
amount: Option<DecCoin>,
|
amount: Option<MajorCurrencyAmount>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DelegationResult {
|
||||||
|
pub fn new(
|
||||||
|
source_address: &str,
|
||||||
|
target_address: &str,
|
||||||
|
amount: Option<MajorCurrencyAmount>,
|
||||||
|
) -> DelegationResult {
|
||||||
|
DelegationResult {
|
||||||
|
source_address: source_address.to_string(),
|
||||||
|
target_address: target_address.to_string(),
|
||||||
|
amount,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TryFrom<MixnetContractDelegation> for DelegationResult {
|
||||||
|
type Error = TypesError;
|
||||||
|
|
||||||
|
fn try_from(delegation: MixnetContractDelegation) -> Result<Self, Self::Error> {
|
||||||
|
let amount: MajorCurrencyAmount = delegation.amount.clone().into();
|
||||||
|
Ok(DelegationResult {
|
||||||
|
source_address: delegation.owner().to_string(),
|
||||||
|
target_address: delegation.node_identity(),
|
||||||
|
amount: Some(amount),
|
||||||
|
})
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))]
|
#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))]
|
||||||
@@ -88,7 +127,7 @@ pub struct DelegationResult {
|
|||||||
feature = "generate-ts",
|
feature = "generate-ts",
|
||||||
ts(export_to = "ts-packages/types/src/types/rust/DelegationEventKind.ts")
|
ts(export_to = "ts-packages/types/src/types/rust/DelegationEventKind.ts")
|
||||||
)]
|
)]
|
||||||
#[derive(Clone, Deserialize, Serialize, PartialEq, Eq, JsonSchema, Debug)]
|
#[derive(Clone, Deserialize, Serialize, PartialEq, JsonSchema, Debug)]
|
||||||
pub enum DelegationEventKind {
|
pub enum DelegationEventKind {
|
||||||
Delegate,
|
Delegate,
|
||||||
Undelegate,
|
Undelegate,
|
||||||
@@ -99,39 +138,41 @@ pub enum DelegationEventKind {
|
|||||||
feature = "generate-ts",
|
feature = "generate-ts",
|
||||||
ts(export_to = "ts-packages/types/src/types/rust/DelegationEvent.ts")
|
ts(export_to = "ts-packages/types/src/types/rust/DelegationEvent.ts")
|
||||||
)]
|
)]
|
||||||
#[derive(Clone, Deserialize, Serialize, PartialEq, Eq, JsonSchema, Debug)]
|
#[derive(Clone, Deserialize, Serialize, PartialEq, JsonSchema, Debug)]
|
||||||
pub struct DelegationEvent {
|
pub struct DelegationEvent {
|
||||||
pub kind: DelegationEventKind,
|
pub kind: DelegationEventKind,
|
||||||
pub node_identity: String,
|
pub node_identity: String,
|
||||||
pub address: String,
|
pub address: String,
|
||||||
pub amount: Option<DecCoin>,
|
pub amount: Option<MajorCurrencyAmount>,
|
||||||
pub block_height: u64,
|
pub block_height: u64,
|
||||||
pub proxy: Option<String>,
|
pub proxy: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl DelegationEvent {
|
impl TryFrom<ContractDelegationEvent> for DelegationEvent {
|
||||||
pub fn from_mixnet_contract(
|
type Error = TypesError;
|
||||||
event: ContractDelegationEvent,
|
|
||||||
reg: &RegisteredCoins,
|
fn try_from(event: ContractDelegationEvent) -> Result<Self, Self::Error> {
|
||||||
) -> Result<Self, TypesError> {
|
match event {
|
||||||
Ok(match event {
|
ContractDelegationEvent::Delegate(delegation) => {
|
||||||
ContractDelegationEvent::Delegate(delegation) => DelegationEvent {
|
let amount: MajorCurrencyAmount = delegation.amount.into();
|
||||||
kind: DelegationEventKind::Delegate,
|
Ok(DelegationEvent {
|
||||||
block_height: delegation.block_height,
|
kind: DelegationEventKind::Delegate,
|
||||||
address: delegation.owner.into_string(),
|
block_height: delegation.block_height,
|
||||||
node_identity: delegation.node_identity,
|
address: delegation.owner.into_string(),
|
||||||
amount: Some(reg.attempt_convert_to_display_dec_coin(delegation.amount.into())?),
|
node_identity: delegation.node_identity,
|
||||||
proxy: delegation.proxy.map(|p| p.into_string()),
|
amount: Some(amount),
|
||||||
},
|
proxy: delegation.proxy.map(|p| p.into_string()),
|
||||||
ContractDelegationEvent::Undelegate(pending_undelegate) => DelegationEvent {
|
})
|
||||||
|
}
|
||||||
|
ContractDelegationEvent::Undelegate(pending_undelegate) => Ok(DelegationEvent {
|
||||||
kind: DelegationEventKind::Undelegate,
|
kind: DelegationEventKind::Undelegate,
|
||||||
block_height: pending_undelegate.block_height(),
|
block_height: pending_undelegate.block_height(),
|
||||||
address: pending_undelegate.delegate().into_string(),
|
address: pending_undelegate.delegate().into_string(),
|
||||||
node_identity: pending_undelegate.mix_identity(),
|
node_identity: pending_undelegate.mix_identity(),
|
||||||
amount: None,
|
amount: None,
|
||||||
proxy: pending_undelegate.proxy().map(|p| p.into_string()),
|
proxy: pending_undelegate.proxy().map(|p| p.into_string()),
|
||||||
},
|
}),
|
||||||
})
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -140,7 +181,7 @@ impl DelegationEvent {
|
|||||||
feature = "generate-ts",
|
feature = "generate-ts",
|
||||||
ts(export_to = "ts-packages/types/src/types/rust/PendingUndelegate.ts")
|
ts(export_to = "ts-packages/types/src/types/rust/PendingUndelegate.ts")
|
||||||
)]
|
)]
|
||||||
#[derive(Deserialize, Serialize, PartialEq, Eq, JsonSchema, Clone, Debug)]
|
#[derive(Deserialize, Serialize, PartialEq, JsonSchema, Clone, Debug)]
|
||||||
pub struct PendingUndelegate {
|
pub struct PendingUndelegate {
|
||||||
mix_identity: String,
|
mix_identity: String,
|
||||||
delegate: String,
|
delegate: String,
|
||||||
@@ -159,6 +200,30 @@ impl From<ContractPendingUndelegate> for PendingUndelegate {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn from_contract_delegation_events(
|
||||||
|
events: Vec<ContractDelegationEvent>,
|
||||||
|
) -> Result<Vec<DelegationEvent>, TypesError> {
|
||||||
|
let (events, errors): (Vec<_>, Vec<_>) = events
|
||||||
|
.into_iter()
|
||||||
|
.map(|delegation_event| delegation_event.try_into())
|
||||||
|
.partition(Result::is_ok);
|
||||||
|
|
||||||
|
if errors.is_empty() {
|
||||||
|
let events = events
|
||||||
|
.into_iter()
|
||||||
|
.filter_map(|e| e.ok())
|
||||||
|
.collect::<Vec<DelegationEvent>>();
|
||||||
|
return Ok(events);
|
||||||
|
}
|
||||||
|
let errors = errors
|
||||||
|
.into_iter()
|
||||||
|
.filter_map(|e| e.err())
|
||||||
|
.collect::<Vec<TypesError>>();
|
||||||
|
|
||||||
|
error!("Failed to convert delegations: {:?}", errors);
|
||||||
|
Err(TypesError::DelegationsInvalid)
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))]
|
#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))]
|
||||||
#[cfg_attr(
|
#[cfg_attr(
|
||||||
feature = "generate-ts",
|
feature = "generate-ts",
|
||||||
@@ -167,6 +232,6 @@ impl From<ContractPendingUndelegate> for PendingUndelegate {
|
|||||||
#[derive(Deserialize, Serialize)]
|
#[derive(Deserialize, Serialize)]
|
||||||
pub struct DelegationsSummaryResponse {
|
pub struct DelegationsSummaryResponse {
|
||||||
pub delegations: Vec<DelegationWithEverything>,
|
pub delegations: Vec<DelegationWithEverything>,
|
||||||
pub total_delegations: DecCoin,
|
pub total_delegations: MajorCurrencyAmount,
|
||||||
pub total_rewards: DecCoin,
|
pub total_rewards: MajorCurrencyAmount,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ use thiserror::Error;
|
|||||||
use validator_client::validator_api::error::ValidatorAPIError;
|
use validator_client::validator_api::error::ValidatorAPIError;
|
||||||
use validator_client::{nymd::error::NymdError, ValidatorClientError};
|
use validator_client::{nymd::error::NymdError, ValidatorClientError};
|
||||||
|
|
||||||
// TODO: ask @MS why this even exists
|
|
||||||
#[derive(Error, Debug)]
|
#[derive(Error, Debug)]
|
||||||
pub enum TypesError {
|
pub enum TypesError {
|
||||||
#[error("{source}")]
|
#[error("{source}")]
|
||||||
@@ -64,12 +63,6 @@ pub enum TypesError {
|
|||||||
InvalidGatewayBond(),
|
InvalidGatewayBond(),
|
||||||
#[error("Invalid delegations")]
|
#[error("Invalid delegations")]
|
||||||
DelegationsInvalid,
|
DelegationsInvalid,
|
||||||
#[error("Attempted to use too huge currency exponent ({0})")]
|
|
||||||
UnsupportedExponent(u32),
|
|
||||||
#[error("Attempted to convert coin that would have resulted in loss of precision")]
|
|
||||||
LossyCoinConversion,
|
|
||||||
#[error("The provided coin has an unknown denomination - {0}")]
|
|
||||||
UnknownCoinDenom(String),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Serialize for TypesError {
|
impl Serialize for TypesError {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
use crate::currency::DecCoin;
|
use crate::currency::MajorCurrencyAmount;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use validator_client::nymd::Fee;
|
use validator_client::nymd::Fee;
|
||||||
|
|
||||||
@@ -8,16 +8,10 @@ use ts_rs::{Dependency, TS};
|
|||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
pub struct FeeDetails {
|
pub struct FeeDetails {
|
||||||
// expected to be used by the wallet in order to display detailed fee information to the user
|
// expected to be used by the wallet in order to display detailed fee information to the user
|
||||||
pub amount: Option<DecCoin>,
|
pub amount: Option<MajorCurrencyAmount>,
|
||||||
pub fee: Fee,
|
pub fee: Fee,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl FeeDetails {
|
|
||||||
pub fn new(amount: Option<DecCoin>, fee: Fee) -> Self {
|
|
||||||
FeeDetails { amount, fee }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(feature = "generate-ts")]
|
#[cfg(feature = "generate-ts")]
|
||||||
impl TS for FeeDetails {
|
impl TS for FeeDetails {
|
||||||
const EXPORT_TO: Option<&'static str> = Some("ts-packages/types/src/types/rust/FeeDetails.ts");
|
const EXPORT_TO: Option<&'static str> = Some("ts-packages/types/src/types/rust/FeeDetails.ts");
|
||||||
@@ -31,12 +25,13 @@ impl TS for FeeDetails {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn inline() -> String {
|
fn inline() -> String {
|
||||||
"{ amount: DecCoin | null, fee: Fee }".into()
|
"{ amount: MajorCurrencyAmount | null, fee: Fee }".into()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn dependencies() -> Vec<Dependency> {
|
fn dependencies() -> Vec<Dependency> {
|
||||||
vec![
|
vec![
|
||||||
Dependency::from_ty::<DecCoin>().expect("TS was incorrectly defined on `DecCoin`"),
|
Dependency::from_ty::<MajorCurrencyAmount>()
|
||||||
|
.expect("TS was incorrectly defined on `CurrencyDenom`"),
|
||||||
Dependency::from_ty::<ts_type_helpers::Fee>()
|
Dependency::from_ty::<ts_type_helpers::Fee>()
|
||||||
.expect("TS was incorrectly defined on `ts_type_helpers::Fee`"),
|
.expect("TS was incorrectly defined on `ts_type_helpers::Fee`"),
|
||||||
]
|
]
|
||||||
|
|||||||
+60
-26
@@ -1,29 +1,48 @@
|
|||||||
|
use crate::currency::MajorCurrencyAmount;
|
||||||
|
use crate::error::TypesError;
|
||||||
use cosmrs::tx::Gas as CosmrsGas;
|
use cosmrs::tx::Gas as CosmrsGas;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use validator_client::nymd::cosmwasm_client::types::GasInfo as ValidatorClientGasInfo;
|
use validator_client::nymd::cosmwasm_client::types::GasInfo as ValidatorClientGasInfo;
|
||||||
|
use validator_client::nymd::GasPrice;
|
||||||
|
|
||||||
#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))]
|
#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))]
|
||||||
#[cfg_attr(
|
#[cfg_attr(
|
||||||
feature = "generate-ts",
|
feature = "generate-ts",
|
||||||
ts(export_to = "ts-packages/types/src/types/rust/Gas.ts")
|
ts(export_to = "ts-packages/types/src/types/rust/Gas.ts")
|
||||||
)]
|
)]
|
||||||
#[derive(Deserialize, Serialize, Copy, Clone, Debug)]
|
#[derive(Deserialize, Serialize, Clone)]
|
||||||
pub struct Gas {
|
pub struct Gas {
|
||||||
/// units of gas used
|
/// units of gas used
|
||||||
pub gas_units: u64,
|
pub gas_units: u64,
|
||||||
|
//
|
||||||
|
// /// gas units converted to fee as major coin amount
|
||||||
|
// pub amount: MajorCurrencyAmount,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Gas {
|
impl Gas {
|
||||||
pub fn from_u64(value: u64) -> Gas {
|
pub fn from_cosmrs_gas(value: CosmrsGas, _denom_minor: &str) -> Result<Gas, TypesError> {
|
||||||
Gas { gas_units: value }
|
Ok(Gas {
|
||||||
}
|
gas_units: value.value(),
|
||||||
}
|
})
|
||||||
|
|
||||||
impl From<CosmrsGas> for Gas {
|
// // TODO: use simulator struct to do conversion to fee
|
||||||
fn from(gas: CosmrsGas) -> Self {
|
// let value_u128 = Uint128::from(value.value());
|
||||||
Gas {
|
// let amount = Decimal::new(value_u128) * Decimal::from_str("0.0025")?;
|
||||||
gas_units: gas.value(),
|
// Ok(Gas {
|
||||||
}
|
// gas_units: value.value(),
|
||||||
|
// amount: MajorCurrencyAmount::from_minor_decimal_and_denom(amount, denom_minor)?,
|
||||||
|
// })
|
||||||
|
}
|
||||||
|
pub fn from_u64(value: u64, _denom_minor: &str) -> Result<Gas, TypesError> {
|
||||||
|
Ok(Gas { gas_units: value })
|
||||||
|
// todo!()
|
||||||
|
// // TODO: use simulator struct to do conversion to fee
|
||||||
|
// let value_u128 = Uint128::from(value);
|
||||||
|
// let amount = Decimal::new(value_u128) * Decimal::from_str("0.0025")?;
|
||||||
|
// Ok(Gas {
|
||||||
|
// gas_units: value,
|
||||||
|
// amount: MajorCurrencyAmount::from_minor_decimal_and_denom(amount, denom_minor)?,
|
||||||
|
// })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -32,29 +51,44 @@ impl From<CosmrsGas> for Gas {
|
|||||||
feature = "generate-ts",
|
feature = "generate-ts",
|
||||||
ts(export_to = "ts-packages/types/src/types/rust/GasInfo.ts")
|
ts(export_to = "ts-packages/types/src/types/rust/GasInfo.ts")
|
||||||
)]
|
)]
|
||||||
#[derive(Deserialize, Serialize, Copy, Clone, Debug)]
|
#[derive(Deserialize, Serialize, Debug)]
|
||||||
pub struct GasInfo {
|
pub struct GasInfo {
|
||||||
/// GasWanted is the maximum units of work we allow this tx to perform.
|
/// GasWanted is the maximum units of work we allow this tx to perform.
|
||||||
pub gas_wanted: Gas,
|
pub gas_wanted: u64,
|
||||||
|
|
||||||
/// GasUsed is the amount of gas actually consumed.
|
/// GasUsed is the amount of gas actually consumed.
|
||||||
pub gas_used: Gas,
|
pub gas_used: u64,
|
||||||
}
|
|
||||||
|
|
||||||
impl From<ValidatorClientGasInfo> for GasInfo {
|
/// gas units converted to fee as major coin amount
|
||||||
fn from(info: ValidatorClientGasInfo) -> Self {
|
pub fee: MajorCurrencyAmount,
|
||||||
GasInfo {
|
|
||||||
gas_wanted: info.gas_wanted.into(),
|
|
||||||
gas_used: info.gas_used.into(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl GasInfo {
|
impl GasInfo {
|
||||||
pub fn from_u64(gas_wanted: u64, gas_used: u64) -> GasInfo {
|
pub fn from_validator_client_gas_info(
|
||||||
GasInfo {
|
value: ValidatorClientGasInfo,
|
||||||
gas_wanted: Gas::from_u64(gas_wanted),
|
denom_minor: &str,
|
||||||
gas_used: Gas::from_u64(gas_used),
|
) -> Result<GasInfo, TypesError> {
|
||||||
}
|
// terrible workaround, but I don't want to break the current flow (just yet)
|
||||||
|
let gas_price = GasPrice::new_with_default_price(denom_minor)?;
|
||||||
|
let fee = (&gas_price) * value.gas_used;
|
||||||
|
Ok(GasInfo {
|
||||||
|
gas_wanted: value.gas_wanted.value(),
|
||||||
|
gas_used: value.gas_used.value(),
|
||||||
|
fee: fee.into(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
pub fn from_u64(
|
||||||
|
gas_wanted: u64,
|
||||||
|
gas_used: u64,
|
||||||
|
denom_minor: &str,
|
||||||
|
) -> Result<GasInfo, TypesError> {
|
||||||
|
// terrible workaround, but I don't want to break the current flow (just yet)
|
||||||
|
let gas_price = GasPrice::new_with_default_price(denom_minor)?;
|
||||||
|
let fee = (&gas_price) * CosmrsGas::from(gas_used);
|
||||||
|
Ok(GasInfo {
|
||||||
|
gas_wanted,
|
||||||
|
gas_used,
|
||||||
|
fee: fee.into(),
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+35
-12
@@ -1,4 +1,4 @@
|
|||||||
use crate::currency::{DecCoin, RegisteredCoins};
|
use crate::currency::MajorCurrencyAmount;
|
||||||
use crate::error::TypesError;
|
use crate::error::TypesError;
|
||||||
use mixnet_contract_common::{
|
use mixnet_contract_common::{
|
||||||
Gateway as MixnetContractGateway, GatewayBond as MixnetContractGatewayBond,
|
Gateway as MixnetContractGateway, GatewayBond as MixnetContractGatewayBond,
|
||||||
@@ -11,7 +11,7 @@ use serde::{Deserialize, Serialize};
|
|||||||
feature = "generate-ts",
|
feature = "generate-ts",
|
||||||
ts(export_to = "ts-packages/types/src/types/rust/Gateway.ts")
|
ts(export_to = "ts-packages/types/src/types/rust/Gateway.ts")
|
||||||
)]
|
)]
|
||||||
#[derive(Clone, Debug, Deserialize, PartialEq, Eq, PartialOrd, Serialize, JsonSchema)]
|
#[derive(Clone, Debug, Deserialize, PartialEq, PartialOrd, Serialize, JsonSchema)]
|
||||||
pub struct Gateway {
|
pub struct Gateway {
|
||||||
pub host: String,
|
pub host: String,
|
||||||
pub mix_port: u16,
|
pub mix_port: u16,
|
||||||
@@ -52,9 +52,9 @@ impl From<MixnetContractGateway> for Gateway {
|
|||||||
feature = "generate-ts",
|
feature = "generate-ts",
|
||||||
ts(export_to = "ts-packages/types/src/types/rust/GatewayBond.ts")
|
ts(export_to = "ts-packages/types/src/types/rust/GatewayBond.ts")
|
||||||
)]
|
)]
|
||||||
#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize, JsonSchema)]
|
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize, JsonSchema)]
|
||||||
pub struct GatewayBond {
|
pub struct GatewayBond {
|
||||||
pub pledge_amount: DecCoin,
|
pub pledge_amount: MajorCurrencyAmount,
|
||||||
pub owner: String,
|
pub owner: String,
|
||||||
pub block_height: u64,
|
pub block_height: u64,
|
||||||
pub gateway: Gateway,
|
pub gateway: Gateway,
|
||||||
@@ -63,15 +63,38 @@ pub struct GatewayBond {
|
|||||||
|
|
||||||
impl GatewayBond {
|
impl GatewayBond {
|
||||||
pub fn from_mixnet_contract_gateway_bond(
|
pub fn from_mixnet_contract_gateway_bond(
|
||||||
bond: MixnetContractGatewayBond,
|
bond: Option<MixnetContractGatewayBond>,
|
||||||
reg: &RegisteredCoins,
|
) -> Result<Option<GatewayBond>, TypesError> {
|
||||||
) -> Result<GatewayBond, TypesError> {
|
match bond {
|
||||||
|
Some(bond) => {
|
||||||
|
let bond: GatewayBond = bond.try_into()?;
|
||||||
|
Ok(Some(bond))
|
||||||
|
}
|
||||||
|
None => Ok(None),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TryFrom<MixnetContractGatewayBond> for GatewayBond {
|
||||||
|
type Error = TypesError;
|
||||||
|
|
||||||
|
fn try_from(value: MixnetContractGatewayBond) -> Result<Self, Self::Error> {
|
||||||
|
let MixnetContractGatewayBond {
|
||||||
|
pledge_amount,
|
||||||
|
owner,
|
||||||
|
block_height,
|
||||||
|
gateway,
|
||||||
|
proxy,
|
||||||
|
} = value;
|
||||||
|
|
||||||
|
let pledge_amount: MajorCurrencyAmount = pledge_amount.into();
|
||||||
|
|
||||||
Ok(GatewayBond {
|
Ok(GatewayBond {
|
||||||
pledge_amount: reg.attempt_convert_to_display_dec_coin(bond.pledge_amount.into())?,
|
pledge_amount,
|
||||||
owner: bond.owner.to_string(),
|
owner: owner.into_string(),
|
||||||
block_height: bond.block_height,
|
block_height,
|
||||||
gateway: bond.gateway.into(),
|
gateway: gateway.into(),
|
||||||
proxy: bond.proxy.map(|p| p.into_string()),
|
proxy: proxy.map(|p| p.into_string()),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+56
-28
@@ -1,18 +1,18 @@
|
|||||||
use crate::currency::{DecCoin, RegisteredCoins};
|
use crate::currency::MajorCurrencyAmount;
|
||||||
use crate::error::TypesError;
|
use crate::error::TypesError;
|
||||||
use mixnet_contract_common::{
|
use mixnet_contract_common::{
|
||||||
MixNode as MixnetContractMixNode, MixNodeBond as MixnetContractMixNodeBond,
|
Coin as CosmWasmCoin, MixNode as MixnetContractMixNode,
|
||||||
|
MixNodeBond as MixnetContractMixNodeBond,
|
||||||
};
|
};
|
||||||
use schemars::JsonSchema;
|
use schemars::JsonSchema;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use validator_client::nymd::Coin;
|
|
||||||
|
|
||||||
#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))]
|
#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))]
|
||||||
#[cfg_attr(
|
#[cfg_attr(
|
||||||
feature = "generate-ts",
|
feature = "generate-ts",
|
||||||
ts(export_to = "ts-packages/types/src/types/rust/Mixnode.ts")
|
ts(export_to = "ts-packages/types/src/types/rust/Mixnode.ts")
|
||||||
)]
|
)]
|
||||||
#[derive(Clone, Debug, Deserialize, PartialEq, Eq, PartialOrd, Serialize, JsonSchema)]
|
#[derive(Clone, Debug, Deserialize, PartialEq, PartialOrd, Serialize, JsonSchema)]
|
||||||
pub struct MixNode {
|
pub struct MixNode {
|
||||||
pub host: String,
|
pub host: String,
|
||||||
pub mix_port: u16,
|
pub mix_port: u16,
|
||||||
@@ -56,41 +56,69 @@ impl From<MixnetContractMixNode> for MixNode {
|
|||||||
feature = "generate-ts",
|
feature = "generate-ts",
|
||||||
ts(export_to = "ts-packages/types/src/types/rust/MixNodeBond.ts")
|
ts(export_to = "ts-packages/types/src/types/rust/MixNodeBond.ts")
|
||||||
)]
|
)]
|
||||||
#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize, JsonSchema)]
|
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize, JsonSchema)]
|
||||||
pub struct MixNodeBond {
|
pub struct MixNodeBond {
|
||||||
pub pledge_amount: DecCoin,
|
pub pledge_amount: MajorCurrencyAmount,
|
||||||
pub total_delegation: DecCoin,
|
pub total_delegation: MajorCurrencyAmount,
|
||||||
pub owner: String,
|
pub owner: String,
|
||||||
pub layer: String,
|
pub layer: String,
|
||||||
pub block_height: u64,
|
pub block_height: u64,
|
||||||
pub mix_node: MixNode,
|
pub mix_node: MixNode,
|
||||||
pub proxy: Option<String>,
|
pub proxy: Option<String>,
|
||||||
pub accumulated_rewards: Option<DecCoin>,
|
pub accumulated_rewards: Option<MajorCurrencyAmount>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl MixNodeBond {
|
impl MixNodeBond {
|
||||||
pub fn from_mixnet_contract_mixnode_bond(
|
pub fn from_mixnet_contract_mixnode_bond(
|
||||||
bond: MixnetContractMixNodeBond,
|
bond: Option<MixnetContractMixNodeBond>,
|
||||||
reg: &RegisteredCoins,
|
) -> Result<Option<MixNodeBond>, TypesError> {
|
||||||
) -> Result<MixNodeBond, TypesError> {
|
match bond {
|
||||||
let denom = bond.pledge_amount.denom.clone();
|
Some(bond) => {
|
||||||
|
let bond: MixNodeBond = bond.try_into()?;
|
||||||
|
Ok(Some(bond))
|
||||||
|
}
|
||||||
|
None => Ok(None),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TryFrom<MixnetContractMixNodeBond> for MixNodeBond {
|
||||||
|
type Error = TypesError;
|
||||||
|
|
||||||
|
fn try_from(value: MixnetContractMixNodeBond) -> Result<Self, Self::Error> {
|
||||||
|
let MixnetContractMixNodeBond {
|
||||||
|
pledge_amount,
|
||||||
|
total_delegation,
|
||||||
|
owner,
|
||||||
|
layer,
|
||||||
|
block_height,
|
||||||
|
mix_node,
|
||||||
|
proxy,
|
||||||
|
accumulated_rewards,
|
||||||
|
} = value;
|
||||||
|
|
||||||
|
if pledge_amount.denom != total_delegation.denom {
|
||||||
|
return Err(TypesError::InvalidDenom(
|
||||||
|
"The pledge and delegation denominations do not match".to_string(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
let denom = total_delegation.denom.clone();
|
||||||
|
|
||||||
|
let pledge_amount: MajorCurrencyAmount = pledge_amount.into();
|
||||||
|
let total_delegation: MajorCurrencyAmount = total_delegation.into();
|
||||||
|
let accumulated_rewards: Option<MajorCurrencyAmount> =
|
||||||
|
accumulated_rewards.map(|r| CosmWasmCoin::new(r.u128(), denom).into());
|
||||||
|
|
||||||
Ok(MixNodeBond {
|
Ok(MixNodeBond {
|
||||||
pledge_amount: reg.attempt_convert_to_display_dec_coin(bond.pledge_amount.into())?,
|
pledge_amount,
|
||||||
total_delegation: reg
|
total_delegation,
|
||||||
.attempt_convert_to_display_dec_coin(bond.total_delegation.into())?,
|
owner: owner.into_string(),
|
||||||
owner: bond.owner.into_string(),
|
layer: layer.into(),
|
||||||
layer: bond.layer.into(),
|
block_height,
|
||||||
block_height: bond.block_height,
|
mix_node: mix_node.into(),
|
||||||
mix_node: bond.mix_node.into(),
|
proxy: proxy.map(|p| p.into_string()),
|
||||||
proxy: bond.proxy.map(|p| p.to_string()),
|
accumulated_rewards,
|
||||||
accumulated_rewards: bond
|
|
||||||
.accumulated_rewards
|
|
||||||
.map(|reward| {
|
|
||||||
// here we're making an assumption that rewards always use the same denom as the pledge
|
|
||||||
// (which I think is a reasonable assumption)
|
|
||||||
reg.attempt_convert_to_display_dec_coin(Coin::new(reward.u128(), denom))
|
|
||||||
})
|
|
||||||
.transpose()?,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
use crate::currency::DecCoin;
|
use crate::currency::MajorCurrencyAmount;
|
||||||
use crate::error::TypesError;
|
use crate::error::TypesError;
|
||||||
use crate::gas::{Gas, GasInfo};
|
use crate::gas::GasInfo;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use validator_client::nymd::cosmwasm_client::types::ExecuteResult;
|
use validator_client::nymd::cosmwasm_client::types::ExecuteResult;
|
||||||
use validator_client::nymd::TxResponse;
|
use validator_client::nymd::TxResponse;
|
||||||
@@ -15,23 +15,31 @@ pub struct SendTxResult {
|
|||||||
pub block_height: u64,
|
pub block_height: u64,
|
||||||
pub code: u32,
|
pub code: u32,
|
||||||
pub details: TransactionDetails,
|
pub details: TransactionDetails,
|
||||||
pub gas_used: Gas,
|
pub gas_used: u64,
|
||||||
pub gas_wanted: Gas,
|
pub gas_wanted: u64,
|
||||||
pub tx_hash: String,
|
pub tx_hash: String,
|
||||||
pub fee: Option<DecCoin>,
|
// pub fee: MajorCurrencyAmount,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl SendTxResult {
|
impl SendTxResult {
|
||||||
pub fn new(t: TxResponse, details: TransactionDetails, fee: Option<DecCoin>) -> SendTxResult {
|
pub fn new(
|
||||||
SendTxResult {
|
t: TxResponse,
|
||||||
|
details: TransactionDetails,
|
||||||
|
_denom_minor: &str,
|
||||||
|
) -> Result<SendTxResult, TypesError> {
|
||||||
|
Ok(SendTxResult {
|
||||||
block_height: t.height.value(),
|
block_height: t.height.value(),
|
||||||
code: t.tx_result.code.value(),
|
code: t.tx_result.code.value(),
|
||||||
details,
|
details,
|
||||||
gas_used: t.tx_result.gas_used.into(),
|
gas_used: t.tx_result.gas_used.value(),
|
||||||
gas_wanted: t.tx_result.gas_wanted.into(),
|
gas_wanted: t.tx_result.gas_wanted.value(),
|
||||||
tx_hash: t.hash.to_string(),
|
tx_hash: t.hash.to_string(),
|
||||||
fee,
|
// that is completely wrong: fee is what you told the validator to use beforehand
|
||||||
}
|
// fee: MajorCurrencyAmount::from_decimal_and_denom(
|
||||||
|
// Decimal::new(Uint128::from(t.tx_result.gas_used.value())),
|
||||||
|
// denom_minor.to_string(),
|
||||||
|
// )?,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -42,21 +50,11 @@ impl SendTxResult {
|
|||||||
)]
|
)]
|
||||||
#[derive(Deserialize, Serialize, Debug)]
|
#[derive(Deserialize, Serialize, Debug)]
|
||||||
pub struct TransactionDetails {
|
pub struct TransactionDetails {
|
||||||
pub amount: DecCoin,
|
pub amount: MajorCurrencyAmount,
|
||||||
pub from_address: String,
|
pub from_address: String,
|
||||||
pub to_address: String,
|
pub to_address: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl TransactionDetails {
|
|
||||||
pub fn new(amount: DecCoin, from_address: String, to_address: String) -> Self {
|
|
||||||
TransactionDetails {
|
|
||||||
amount,
|
|
||||||
from_address,
|
|
||||||
to_address,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))]
|
#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))]
|
||||||
#[cfg_attr(
|
#[cfg_attr(
|
||||||
feature = "generate-ts",
|
feature = "generate-ts",
|
||||||
@@ -68,16 +66,18 @@ pub struct TransactionExecuteResult {
|
|||||||
pub data_json: String,
|
pub data_json: String,
|
||||||
pub transaction_hash: String,
|
pub transaction_hash: String,
|
||||||
pub gas_info: GasInfo,
|
pub gas_info: GasInfo,
|
||||||
pub fee: Option<DecCoin>,
|
pub fee: MajorCurrencyAmount,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl TransactionExecuteResult {
|
impl TransactionExecuteResult {
|
||||||
pub fn from_execute_result(
|
pub fn from_execute_result(
|
||||||
value: ExecuteResult,
|
value: ExecuteResult,
|
||||||
fee: Option<DecCoin>,
|
denom_minor: &str,
|
||||||
) -> Result<TransactionExecuteResult, TypesError> {
|
) -> Result<TransactionExecuteResult, TypesError> {
|
||||||
|
let gas_info = GasInfo::from_validator_client_gas_info(value.gas_info, denom_minor)?;
|
||||||
|
let fee = gas_info.fee.clone();
|
||||||
Ok(TransactionExecuteResult {
|
Ok(TransactionExecuteResult {
|
||||||
gas_info: value.gas_info.into(),
|
gas_info,
|
||||||
transaction_hash: value.transaction_hash.to_string(),
|
transaction_hash: value.transaction_hash.to_string(),
|
||||||
data_json: ::serde_json::to_string_pretty(&value.data)?,
|
data_json: ::serde_json::to_string_pretty(&value.data)?,
|
||||||
logs_json: ::serde_json::to_string_pretty(&value.logs)?,
|
logs_json: ::serde_json::to_string_pretty(&value.logs)?,
|
||||||
@@ -97,24 +97,30 @@ pub struct RpcTransactionResponse {
|
|||||||
pub tx_result_json: String,
|
pub tx_result_json: String,
|
||||||
pub block_height: u64,
|
pub block_height: u64,
|
||||||
pub transaction_hash: String,
|
pub transaction_hash: String,
|
||||||
pub gas_used: Gas,
|
pub gas_info: GasInfo,
|
||||||
pub gas_wanted: Gas,
|
// pub fee: MajorCurrencyAmount,
|
||||||
pub fee: Option<DecCoin>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl RpcTransactionResponse {
|
impl RpcTransactionResponse {
|
||||||
pub fn from_tx_response(
|
pub fn from_tx_response(
|
||||||
t: &TxResponse,
|
value: &TxResponse,
|
||||||
fee: Option<DecCoin>,
|
denom_minor: &str,
|
||||||
) -> Result<RpcTransactionResponse, TypesError> {
|
) -> Result<RpcTransactionResponse, TypesError> {
|
||||||
Ok(RpcTransactionResponse {
|
Ok(RpcTransactionResponse {
|
||||||
index: t.index,
|
index: value.index,
|
||||||
gas_used: t.tx_result.gas_used.into(),
|
gas_info: GasInfo::from_u64(
|
||||||
gas_wanted: t.tx_result.gas_wanted.into(),
|
value.tx_result.gas_wanted.value(),
|
||||||
transaction_hash: t.hash.to_string(),
|
value.tx_result.gas_used.value(),
|
||||||
tx_result_json: ::serde_json::to_string_pretty(&t.tx_result)?,
|
denom_minor,
|
||||||
block_height: t.height.value(),
|
)?,
|
||||||
fee,
|
transaction_hash: value.hash.to_string(),
|
||||||
|
tx_result_json: ::serde_json::to_string_pretty(&value.tx_result)?,
|
||||||
|
block_height: value.height.value(),
|
||||||
|
// wrong
|
||||||
|
// fee: MajorCurrencyAmount::from_decimal_and_denom(
|
||||||
|
// Decimal::new(Uint128::from(value.tx_result.gas_used.value())),
|
||||||
|
// denom_minor.to_string(),
|
||||||
|
// )?,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user