Compare commits

...

187 Commits

Author SHA1 Message Date
farbanas 59185f3b87 merge resolve 2023-01-17 13:41:56 +01:00
durch c708a7cc12 Merge branch 'release/v1.1.6' of https://github.com/nymtech/nym into release/v1.1.6 2023-01-17 13:39:56 +01:00
durch ea35a37d4c Replace println with eprintln! 2023-01-17 13:39:49 +01:00
farbanas e40d25a97b nym-validator-api -> nym-api 2023-01-17 13:33:30 +01:00
farbanas cf903aa2e5 updated changelogs 2023-01-17 13:30:31 +01:00
farbanas 0a2e0d6a8f bump version for release 2023-01-17 13:17:15 +01:00
Jędrzej Stuczyński ea68d42886 bugfix: set default value for nym-api (and nyxd) for clients (#2822)
* setting default urls in client config

* using the same environmental variable for verloc
2023-01-17 10:27:55 +01:00
farbanas 65ed611c24 fix: changelog cleanup and added a UNRELEASED section 2023-01-16 16:00:58 +01:00
Gala f305901a18 Changing the explorers guru link (#2820) 2023-01-16 15:27:44 +01:00
Jess 645cb88074 Update CHANGELOG.md 2023-01-16 12:42:51 +00:00
Jędrzej Stuczyński 6b96e474f7 made most of cli boolean arguments optional (#2819)
so that if not provided, they would not overwrite config values
2023-01-16 12:52:29 +01:00
Fouad 4854e929ed link to the ng mixnet explorer for account info (#2823) 2023-01-12 12:33:28 +01:00
Fouad 5f88517e1d Feature/nym connect gateway performance (#2824)
* set up ui for gateway performance in nym-connect

remove duplicated imports

* set and reset (when necessary) gateway performance

* remove unneeded useEffect

* remove log
2023-01-12 10:47:58 +01:00
Fouad c7d8f3af97 Feature/nym connect gateway performance (#2815)
* set up ui for gateway performance in nym-connect

* reset gateway performance state periodically

* remove duplicated imports

* set and reset (when necessary) gateway performance

* align gateway performance text left
2023-01-11 14:19:59 +01:00
Gala 1e84f87bf5 Revert "Changing the explorers guru link"
This reverts commit 70ae45b6c9.
2023-01-11 13:33:26 +01:00
Gala 70ae45b6c9 Changing the explorers guru link 2023-01-11 12:59:16 +01:00
Bogdan-Ștefan Neacşu 8d3aea969e Handle case when changed value is 42 (#2808) 2023-01-10 15:01:57 +02:00
farbanas 96444509d0 fix: updated changelog for binaries with the version of the release 2023-01-10 13:53:02 +01:00
farbanas 078ca0b0d1 Merge resolve 2023-01-10 13:52:00 +01:00
farbanas aab91e424e Merge resolve 2023-01-10 13:48:04 +01:00
farbanas 273dc41559 feat: update changelogs 2023-01-10 13:43:09 +01:00
farbanas 61bc74148f Update versions 2023-01-10 13:10:24 +01:00
Jędrzej Stuczyński 5b14eecf82 bugfix: for Default config impl generate fresh mnemonic over using a hardcoded one (#2806) 2023-01-10 10:39:58 +00:00
Fran Arbanas 30110aff65 Merge pull request #1827 from nymtech/feat/nym-cli-cosmwasm-generate-init-message
nym-cli generate instantiate message for mixnet and vesting contracts
2023-01-09 19:54:28 +01:00
farbanas 1954c49ac2 merge resolve 2023-01-09 19:38:16 +01:00
farbanas 70328ba114 merge resolve 2023-01-09 19:30:25 +01:00
farbanas c43b2dc117 merge resolve 2023-01-09 16:03:42 +01:00
Drazen Urch 4a8a9096dd Save to JSON in addition to printing (#1864)
* Save to JSON in addition to printing

* Save node details to json for mixnode

* Remove Cargo.locks

* Cli ergonomics

* Json output for gateway
2023-01-09 12:51:21 +01:00
Jędrzej Stuczyński 88d813b9c1 Feature/optional set trait (#2773)
* Defined OptionalSet trait

* extended the trait to handle environment

* sample implementation for the gateway

* implementation for mixnode

* Added the same feature to nym-api config + made some config types stricter

* fixed compilation and linter issues

* keeping track of parsing error

* attempt at using the trait for the client configs

* Streamlined more arguments

* Removed deprecation on setters

* fixed incorrect test constructor

* missed rebase fixes
2023-01-06 18:13:25 +00:00
Pierre Dommerc e181a1cfb1 feat(wallet-buy): pass wallet address as url param (#2780) 2023-01-06 09:38:30 +01:00
Dave Hrycyszyn 29091aab8e Feature/rename nymd to nyxd (#2696)
* Renaming all instances of nymd to nyxd

* Might as well get the changelogs too

* Making it clearer that an ApiClient is a NymApiClient

* Lining up config templates with struct keys on gateway

* Changed the last references to validator_urls to nyxd_urls

* Fixed up a few type errors after refactoring

* Changed the changelog

* Fixed typo in changelog

* Further instances of renaming 'nymd' + introducing additional clap aliases

* updated environmental variables and allowed usage of deprecated variants

* missing occurences of coconut-locked environmental variables

Co-authored-by: Jędrzej Stuczyński <jedrzej.stuczynski@gmail.com>
2023-01-05 15:35:47 +00:00
Pierre Dommerc fdbe3a1f6a fix(explorer,explorer-api): mixnode location (#2763)
* chore(explorer-api): remove useless route (/terms)

* feat(explorer-api-geoip): add coordinates lat&lon

* fix(explorer): mixnode location

* fix: typo

* fix: clippy
2023-01-05 15:53:15 +01:00
Jędrzej Stuczyński 5f4926dd49 feature: use clap derive for nym-api + use stricter validation for other binaries (#2772)
* fixed all uses of deprecated clap methods

* updated all uses of clap to 4.0

* unified obtaining build information

* moved around the imports

* Moved all nym-api arguments to ApiArgs and simplified parsing

* Using common shutdown signal code

* Using clap for parsing Vec<Url>

* stricter validation of socks5-client arguments

* ibid for the native client

* ibid for the gateway

* ibid for the mixnode

* clippy
2023-01-05 10:32:57 +00:00
dependabot[bot] 1f132a4eaa build(deps): bump got and nodemon (#1624)
Bumps [got](https://github.com/sindresorhus/got) and [nodemon](https://github.com/remy/nodemon). These dependencies needed to be updated together.

Removes `got`

Updates `nodemon` from 2.0.12 to 2.0.19
- [Release notes](https://github.com/remy/nodemon/releases)
- [Commits](https://github.com/remy/nodemon/compare/v2.0.12...v2.0.19)

---
updated-dependencies:
- dependency-name: got
  dependency-type: indirect
- dependency-name: nodemon
  dependency-type: direct:production
...

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-01-05 10:21:05 +00:00
dependabot[bot] 097d2d51cc build(deps): bump undici, hardhat and @nomiclabs/hardhat-etherscan (#1634)
Bumps [undici](https://github.com/nodejs/undici), [hardhat](https://github.com/nomiclabs/hardhat) and [@nomiclabs/hardhat-etherscan](https://github.com/nomiclabs/hardhat). These dependencies needed to be updated together.

Updates `undici` from 4.16.0 to 5.10.0
- [Release notes](https://github.com/nodejs/undici/releases)
- [Commits](https://github.com/nodejs/undici/compare/v4.16.0...v5.10.0)

Updates `hardhat` from 2.9.2 to 2.11.2
- [Release notes](https://github.com/nomiclabs/hardhat/releases)
- [Commits](https://github.com/nomiclabs/hardhat/compare/hardhat@2.9.2...hardhat@2.11.2)

Updates `@nomiclabs/hardhat-etherscan` from 3.0.3 to 3.1.0
- [Release notes](https://github.com/nomiclabs/hardhat/releases)
- [Commits](https://github.com/nomiclabs/hardhat/compare/@nomiclabs/hardhat-etherscan@3.0.3...@nomiclabs/hardhat-etherscan@3.1.0)

---
updated-dependencies:
- dependency-name: undici
  dependency-type: indirect
- dependency-name: hardhat
  dependency-type: direct:development
- dependency-name: "@nomiclabs/hardhat-etherscan"
  dependency-type: direct:development
...

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-01-05 10:20:56 +00:00
dependabot[bot] a2078d997b Bump loader-utils from 1.4.0 to 1.4.2 (#1763)
Bumps [loader-utils](https://github.com/webpack/loader-utils) from 1.4.0 to 1.4.2.
- [Release notes](https://github.com/webpack/loader-utils/releases)
- [Changelog](https://github.com/webpack/loader-utils/blob/v1.4.2/CHANGELOG.md)
- [Commits](https://github.com/webpack/loader-utils/compare/v1.4.0...v1.4.2)

---
updated-dependencies:
- dependency-name: loader-utils
  dependency-type: indirect
...

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-01-05 10:20:37 +00:00
dependabot[bot] 558d4b899d Bump deep-object-diff from 1.1.7 to 1.1.9 (#1765)
Bumps [deep-object-diff](https://github.com/mattphillips/deep-object-diff) from 1.1.7 to 1.1.9.
- [Release notes](https://github.com/mattphillips/deep-object-diff/releases)
- [Commits](https://github.com/mattphillips/deep-object-diff/commits)

---
updated-dependencies:
- dependency-name: deep-object-diff
  dependency-type: indirect
...

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-01-05 10:20:24 +00:00
dependabot[bot] 4fcb98e839 Bump decode-uri-component in /contracts/basic-bandwidth-generation (#1838)
Bumps [decode-uri-component](https://github.com/SamVerschueren/decode-uri-component) from 0.2.0 to 0.2.2.
- [Release notes](https://github.com/SamVerschueren/decode-uri-component/releases)
- [Commits](https://github.com/SamVerschueren/decode-uri-component/compare/v0.2.0...v0.2.2)

---
updated-dependencies:
- dependency-name: decode-uri-component
  dependency-type: indirect
...

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-01-05 10:20:11 +00:00
dependabot[bot] 702bb202a3 Bump decode-uri-component from 0.2.0 to 0.2.2 (#1840)
Bumps [decode-uri-component](https://github.com/SamVerschueren/decode-uri-component) from 0.2.0 to 0.2.2.
- [Release notes](https://github.com/SamVerschueren/decode-uri-component/releases)
- [Commits](https://github.com/SamVerschueren/decode-uri-component/compare/v0.2.0...v0.2.2)

---
updated-dependencies:
- dependency-name: decode-uri-component
  dependency-type: indirect
...

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-01-05 10:19:59 +00:00
dependabot[bot] 71ff2c04a0 Bump express in /clients/native/examples/js-examples/websocket (#1849)
Bumps [express](https://github.com/expressjs/express) from 4.17.1 to 4.18.2.
- [Release notes](https://github.com/expressjs/express/releases)
- [Changelog](https://github.com/expressjs/express/blob/master/History.md)
- [Commits](https://github.com/expressjs/express/compare/4.17.1...4.18.2)

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

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-01-05 10:19:46 +00:00
dependabot[bot] cb30384eaf Bump qs and express in /clients/native/examples/js-examples/websocket (#1850)
Bumps [qs](https://github.com/ljharb/qs) and [express](https://github.com/expressjs/express). These dependencies needed to be updated together.

Updates `qs` from 6.7.0 to 6.11.0
- [Release notes](https://github.com/ljharb/qs/releases)
- [Changelog](https://github.com/ljharb/qs/blob/main/CHANGELOG.md)
- [Commits](https://github.com/ljharb/qs/compare/v6.7.0...v6.11.0)

Updates `express` from 4.17.1 to 4.18.2
- [Release notes](https://github.com/expressjs/express/releases)
- [Changelog](https://github.com/expressjs/express/blob/master/History.md)
- [Commits](https://github.com/expressjs/express/compare/4.17.1...4.18.2)

---
updated-dependencies:
- dependency-name: qs
  dependency-type: indirect
- dependency-name: express
  dependency-type: indirect
...

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-01-05 10:19:38 +00:00
dependabot[bot] e911c2fbc0 Bump qs and express in /clients/webassembly/js-example (#1851)
Bumps [qs](https://github.com/ljharb/qs) and [express](https://github.com/expressjs/express). These dependencies needed to be updated together.

Updates `qs` from 6.7.0 to 6.11.0
- [Release notes](https://github.com/ljharb/qs/releases)
- [Changelog](https://github.com/ljharb/qs/blob/main/CHANGELOG.md)
- [Commits](https://github.com/ljharb/qs/compare/v6.7.0...v6.11.0)

Updates `express` from 4.17.1 to 4.18.2
- [Release notes](https://github.com/expressjs/express/releases)
- [Changelog](https://github.com/expressjs/express/blob/master/History.md)
- [Commits](https://github.com/expressjs/express/compare/4.17.1...4.18.2)

---
updated-dependencies:
- dependency-name: qs
  dependency-type: indirect
- dependency-name: express
  dependency-type: indirect
...

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-01-05 10:19:27 +00:00
dependabot[bot] bb005a39f5 Bump qs, body-parser and express (#1852)
Bumps [qs](https://github.com/ljharb/qs), [qs](https://github.com/ljharb/qs), [body-parser](https://github.com/expressjs/body-parser) and [express](https://github.com/expressjs/express). These dependencies needed to be updated together.

Updates `qs` from 6.10.1 to 6.11.0
- [Release notes](https://github.com/ljharb/qs/releases)
- [Changelog](https://github.com/ljharb/qs/blob/main/CHANGELOG.md)
- [Commits](https://github.com/ljharb/qs/compare/v6.10.1...v6.11.0)

Updates `qs` from 6.5.2 to 6.11.0
- [Release notes](https://github.com/ljharb/qs/releases)
- [Changelog](https://github.com/ljharb/qs/blob/main/CHANGELOG.md)
- [Commits](https://github.com/ljharb/qs/compare/v6.10.1...v6.11.0)

Updates `body-parser` from 1.19.0 to 1.20.1
- [Release notes](https://github.com/expressjs/body-parser/releases)
- [Changelog](https://github.com/expressjs/body-parser/blob/master/HISTORY.md)
- [Commits](https://github.com/expressjs/body-parser/compare/1.19.0...1.20.1)

Updates `express` from 4.17.1 to 4.18.2
- [Release notes](https://github.com/expressjs/express/releases)
- [Changelog](https://github.com/expressjs/express/blob/master/History.md)
- [Commits](https://github.com/expressjs/express/compare/4.17.1...4.18.2)

---
updated-dependencies:
- dependency-name: qs
  dependency-type: indirect
- dependency-name: qs
  dependency-type: indirect
- dependency-name: body-parser
  dependency-type: indirect
- dependency-name: express
  dependency-type: indirect
...

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-01-05 10:19:19 +00:00
dependabot[bot] ea72c37083 Bump express in /contracts/basic-bandwidth-generation (#1853)
Bumps [express](https://github.com/expressjs/express) from 4.17.1 to 4.18.2.
- [Release notes](https://github.com/expressjs/express/releases)
- [Changelog](https://github.com/expressjs/express/blob/master/History.md)
- [Commits](https://github.com/expressjs/express/compare/4.17.1...4.18.2)

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

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-01-05 10:19:10 +00:00
dependabot[bot] a24dd8b9bc build(deps): bump json5 from 2.2.1 to 2.2.3 in /nym-api/tests (#2768)
Bumps [json5](https://github.com/json5/json5) from 2.2.1 to 2.2.3.
- [Release notes](https://github.com/json5/json5/releases)
- [Changelog](https://github.com/json5/json5/blob/main/CHANGELOG.md)
- [Commits](https://github.com/json5/json5/compare/v2.2.1...v2.2.3)

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

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-01-05 10:11:01 +00:00
dependabot[bot] b006c01397 build(deps): bump json5 from 2.2.1 to 2.2.3 in /testnet-faucet (#2769)
Bumps [json5](https://github.com/json5/json5) from 2.2.1 to 2.2.3.
- [Release notes](https://github.com/json5/json5/releases)
- [Changelog](https://github.com/json5/json5/blob/main/CHANGELOG.md)
- [Commits](https://github.com/json5/json5/compare/v2.2.1...v2.2.3)

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

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-01-05 10:10:38 +00:00
dependabot[bot] f7f2a51458 build(deps): bump json5 from 1.0.1 to 1.0.2 (#2770)
Bumps [json5](https://github.com/json5/json5) from 1.0.1 to 1.0.2.
- [Release notes](https://github.com/json5/json5/releases)
- [Changelog](https://github.com/json5/json5/blob/main/CHANGELOG.md)
- [Commits](https://github.com/json5/json5/compare/v1.0.1...v1.0.2)

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

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-01-05 10:10:04 +00:00
Jon Häggblad 408396c900 client-core: remove generic parameter for ClientCoreError (#2765)
* client-core: remove generic parameter for ClientCoreError

* fix compilation
2023-01-04 15:41:11 +01:00
Jędrzej Stuczyński a97c913bb1 Fixed missing feature lock for coconut-exlusive fields (#2767) 2023-01-04 14:00:55 +00:00
Jędrzej Stuczyński dba5a9caef Renamed 'nym-validator-api' package name to 'nym-api' (#2766) 2023-01-04 13:00:37 +00:00
Pierre Dommerc 3e39573feb feat(wallet-buy): pass wallet address as url param (#2752) 2023-01-04 13:26:09 +01:00
Jędrzej Stuczyński ac312e9109 feature: standarise arguments (#2762)
* Renamed "address" argument in "sign" command to "wallet-address"

* Ability to optionally describe mixnode with command line arguments

* renamed 'validators' arguments to 'nym-apis' in mixnode binary

* cleaned up gateway validator-related url arguments

* fixup! Renamed "address" argument in "sign" command to "wallet-address"

* renamed 'use_anonymous_sender_tag' to 'use_anonymous_replies'

* 'nymd_endpoints => 'nymd_validators'

* more consistency for nymd_validators and nym_apis urls arguments

* updated changelog
2023-01-04 09:59:08 +00:00
Jędrzej Stuczyński 8a2a7dc0ce bugfix: don't start rewarding unless rewarding.enabled is explicitly set to true (#2753)
* start rewarded set updater based on config flag

* removed dead code annotation

* updated changelog
2023-01-04 09:44:32 +00:00
Fouad 5b15ed6f15 merge resolve 2022-12-22 15:48:40 +01:00
Fouad 9684b7ffbd merge resolve 2022-12-22 15:45:02 +01:00
Fouad 0628565684 Feature/node settings apy playground (#1677) (#2738)
* initial ui for test my node

use svg for node path

add stories for test my node

* add initial rewards calculation

* update validation for rewards playground

* init playground with default values

* get node uptime

* get mixnode reward estimation

* calculate saturation

calculate stake saturation

* Make ComputeRewardEstParam derive Debug

* set active set to be always true

Co-authored-by: Jon Häggblad <jon.haggblad@gmail.com>

Co-authored-by: Jon Häggblad <jon.haggblad@gmail.com>
2022-12-22 15:33:27 +01:00
Gala 57703af642 Merge pull request #2746 from nymtech/revert-1519-339-net-switch-bttn
Revert "NE: Switch button to change the explorer network"
2022-12-22 14:21:24 +01:00
Gala 9dd4c5d871 Revert "NE: Switch button to change the explorer network" 2022-12-22 14:20:21 +01:00
farbanas 4813cf6c18 feat: release v1.1.5 of nym-wallet 2022-12-22 12:14:01 +01:00
farbanas 29f48efe49 feat: release v1.1.5 of nym-wallet 2022-12-22 12:13:44 +01:00
farbanas 280ac34115 feat: release v1.1.5 of nym-wallet 2022-12-22 12:12:46 +01:00
benedetta davico 83b76c6b37 Merge pull request #1519 from nymtech/339-net-switch-bttn
NE: Switch button to change the explorer network
2022-12-22 11:23:00 +01:00
Gala 4120234155 fix build problem 2022-12-22 11:09:55 +01:00
Gala 42b444ddf8 Merge branch '339-net-switch-bttn' of github.com:nymtech/nym into 339-net-switch-bttn 2022-12-22 10:55:03 +01:00
Gala acd832d8e5 cleaning 2022-12-22 10:54:26 +01:00
Gala 75a726ebbe some styles 2022-12-22 10:54:12 +01:00
Gala b9fbab6024 adding button on mov nav and make it smaller 2022-12-22 10:54:12 +01:00
Gala 06ed8716a1 adding a switch between networks 2022-12-22 10:54:12 +01:00
benedetta davico beddd3dcee Merge pull request #2742 from nymtech/feat/2130-tables-update-rebase
Feat/2130 tables update rebase
2022-12-22 10:37:53 +01:00
Drazen Urch bdc285dbbb Add numeric family ids to explorer-api (#2707) 2022-12-21 23:37:32 +01:00
benedetta davico 4d02dfb899 Merge pull request #2741 from nymtech/fix/explorer-gateway-bond-decimals
fix(explorer): set gateway bond 6 decimals
2022-12-21 18:10:47 +01:00
Gala 80d6cb5c12 last small touch 2022-12-21 17:34:26 +01:00
Gala 7422ab69ba Merge branch 'feat/2130-tables-update-rebase' of github.com:nymtech/nym into feat/2130-tables-update-rebase 2022-12-21 17:30:26 +01:00
Gala 60c8185bea cleaning 2022-12-21 17:26:34 +01:00
Gala 9d3c7c0be8 refactor from PR request 2022-12-21 17:26:34 +01:00
Gala d6048fae52 refactor 2022-12-21 17:26:22 +01:00
Gala ddb7b0e872 delegations layout and tooltip when delegate with vesting 2022-12-21 17:26:22 +01:00
Gala 4995dde705 bond table changes 2022-12-21 17:25:09 +01:00
Gala 63bfe4246f fix parameters settings layout 2022-12-21 17:24:23 +01:00
Gala 4654b360e0 cleaning 2022-12-21 17:23:52 +01:00
Gala 7c5c19986a refactor from PR request 2022-12-21 17:23:52 +01:00
Gala 46edca0bd4 refactor 2022-12-21 17:23:52 +01:00
Gala b03a1f922d refactor 2022-12-21 17:23:52 +01:00
Gala 9616c90433 delegations layout and tooltip when delegate with vesting 2022-12-21 17:23:52 +01:00
Gala ea49f0a265 delegations table changes wip 2022-12-21 17:23:52 +01:00
Gala 2470c8b9b5 tidying up 2022-12-21 17:23:52 +01:00
Gala 7d001965ec change date order to dd/mm/yy 2022-12-21 17:22:26 +01:00
Gala 11b1089d83 removing epoch on settings and fixing divider position 2022-12-21 17:22:26 +01:00
Gala 52699d7598 bond table changes 2022-12-21 17:21:51 +01:00
benedetta davico 87443dd624 Merge pull request #2743 from nymtech/feat/2161-ne-gate-version
Feat/2161 ne gate version
2022-12-21 15:25:07 +01:00
benedetta davico a02a1b0385 Merge pull request #2728 from nymtech/feat/2722-ne-ui
make fields match button height
2022-12-21 15:09:32 +01:00
Gala e0f2fa6705 fix indentation 2022-12-21 14:45:14 +01:00
Gala 7949b07213 Merge branch 'feat/2161-ne-gate-version' of github.com:nymtech/nym into feat/2161-ne-gate-version 2022-12-21 14:07:16 +01:00
Gala bd20fd0b1f remove console log 2022-12-21 14:06:32 +01:00
Gala 57d3d6fd0f sdding version number on the gateways list and details 2022-12-21 14:06:32 +01:00
Gala 06eff652dd wip adding gt version 2022-12-21 14:06:32 +01:00
Gala 246decac4a remove console log 2022-12-21 14:01:53 +01:00
Gala a14ae298ae sdding version number on the gateways list and details 2022-12-21 13:59:23 +01:00
Gala 43188051d3 Merge branch 'feat/2130-tables-update-rebase' of github.com:nymtech/nym into feat/2130-tables-update-rebase 2022-12-21 12:48:46 +01:00
Gala 8aa15fa467 fix parameters settings layout 2022-12-21 12:41:12 +01:00
benedetta davico f77b037ef7 Merge pull request #2704 from nymtech/feature/nym-connect-display-info
NymConnect - Display service info in tooltip **1.1.5 Release**
2022-12-21 12:39:44 +01:00
Gala 75dbc5d790 Merge branch 'release/v1.1.5' into feat/2130-tables-update-rebase 2022-12-21 12:20:42 +01:00
Gala e6bcd706ff cleaning 2022-12-21 12:03:46 +01:00
Gala 9a077a0928 refactor from PR request 2022-12-21 12:03:46 +01:00
Gala 11fd42e187 refactor 2022-12-21 12:03:46 +01:00
Gala 6e499e5996 refactor 2022-12-21 12:03:46 +01:00
Gala f98cc73a1f delegations layout and tooltip when delegate with vesting 2022-12-21 12:03:46 +01:00
Gala db9bf4d3fa delegations table changes wip 2022-12-21 12:03:46 +01:00
Gala b30628529d tidying up 2022-12-21 12:03:46 +01:00
Gala 3be615f74f change date order to dd/mm/yy 2022-12-21 12:03:46 +01:00
Gala a8ccd2ec17 removing epoch on settings and fixing divider position 2022-12-21 12:03:46 +01:00
Gala 2d71caf50a bond table changes 2022-12-21 12:03:46 +01:00
Gala 4d08d62fc2 wip adding gt version 2022-12-21 11:54:41 +01:00
pierre 40e5595d65 fix(explorer): set gateway bond 6 decimals 2022-12-21 11:46:12 +01:00
Gala 6780d58a98 cleaning 2022-12-21 11:19:50 +01:00
Gala ccbf06f179 refactor from PR request 2022-12-21 11:19:50 +01:00
Gala e6ecf71cc3 refactor 2022-12-21 11:19:50 +01:00
Gala c66312ee96 refactor 2022-12-21 11:19:50 +01:00
Gala 808802aeb4 delegations layout and tooltip when delegate with vesting 2022-12-21 11:19:50 +01:00
Gala fb38f24e5c delegations table changes wip 2022-12-21 11:19:50 +01:00
Gala 65f148a5ad tidying up 2022-12-21 11:19:50 +01:00
Gala 2bcdc5d11e change date order to dd/mm/yy 2022-12-21 11:19:50 +01:00
Gala 5ecb03ffe9 removing epoch on settings and fixing divider position 2022-12-21 11:19:50 +01:00
Gala 8505989dad bond table changes 2022-12-21 11:19:50 +01:00
benedetta davico ed5e865db7 Merge pull request #2718 from nymtech/feature/wallet-epoch-time-in-unbond-modal
Add epoch info to unbond modal **1.1.5 Release**
2022-12-21 10:37:38 +01:00
benedetta davico ea3194e0c3 Merge pull request #2720 from nymtech/feature/wallet-fix-parameter-input-layout
Fix param input layout **1.1.5 Release**
2022-12-21 10:24:05 +01:00
Gala 190bff4ffe Merge branch 'release/v1.1.5' of github.com:nymtech/nym into release/v1.1.5 2022-12-21 10:21:23 +01:00
fmtabbara c509555d15 fix param input layout 2022-12-21 09:22:01 +01:00
fmtabbara f0d66fdd88 add epoch info to unbond modal 2022-12-21 09:19:39 +01:00
fmtabbara 14847d01b7 remove console.log 2022-12-21 09:17:38 +01:00
fmtabbara f4711902bd display service info in tooltip
trim provider address
2022-12-21 09:17:38 +01:00
Jędrzej Stuczyński 32ad93c57e Feature/multi surb transmission lanes (#2723)
* Preserve information about original transmission lanes when buffering reply packets

* Attempting to send partial data in 'handle_send_reply' if we don't have enough surbs immediately

* Display logging of reply surb request target

* promoted reply_controller to a directory

* moved channels and messages to separate file

* simplifications due to rust 1.66

* Using a shoarthand for obtaining connection_id

* made TransmissionBuffer generic

* Moved transmissaion buffer to a higher level directory + defined wasm helpers

* Using transmission buffer in reply controller

* Using the pending replies size in lane lenghts queries

* fixed an out of bounds use of fragments

* Fixed dropped channel in getting lane queue length

* Fixed an edge case failure for reply retransmissions

* measuring (and logging) time it takes to obtain lane lenghts

* decreased logging level

* Removed non-wasm lock on total_size
2022-12-20 19:38:49 +00:00
farbanas c4a68dbbe6 chore: formatting 2022-12-20 15:28:51 +01:00
fmtabbara 1140503eba merge 1.1.4 to develop 2022-12-20 13:49:10 +00:00
farbanas d92d6877a4 Merge branch 'release/v1.1.4' 2022-12-20 12:33:46 +01:00
farbanas b9fed9f455 updating changelogs 2022-12-20 12:33:20 +01:00
farbanas 5e45f7d3a5 updating changelogs 2022-12-20 12:28:13 +01:00
farbanas 1133acd8bd update nym-connect and nym-wallet version 2022-12-20 12:14:05 +01:00
farbanas 08e6f3c4b7 update binaries version 2022-12-20 12:10:21 +01:00
farbanas 0ed546b739 fix: remove clear all settings button 2022-12-20 12:04:24 +01:00
Drazen Urch b4f2233d2b Outfox and Lion (#2730) 2022-12-20 11:29:28 +01:00
Mark Sinclair d8369eb4c9 Test and earn
- add logging and clear local storage menu items
- bump nym-connect version
- add app version number
- add reset trigger when clearing SP storage
- bump tauri version (nym-connect and nym-wallet)
- fix webpack config for prod builds
- new selector for services, with an advanced section for service providers
2022-12-19 18:18:08 +00:00
fmtabbara db3d379219 update buy NYM text 2022-12-19 15:07:49 +00:00
Gala a746738d48 make fields match button height 2022-12-19 13:40:26 +01:00
Jon Häggblad c67f0fb7f8 Merge remote-tracking branch 'origin/release/v1.1.4' into develop 2022-12-19 12:39:11 +01:00
Fouad 7c12a3422c Feature/node settings apy playground (#1677)
* initial ui for test my node

use svg for node path

add stories for test my node

* add initial rewards calculation

* update validation for rewards playground

* init playground with default values

* get node uptime

* get mixnode reward estimation

* calculate saturation

calculate stake saturation

* Make ComputeRewardEstParam derive Debug

* set active set to be always true

Co-authored-by: Jon Häggblad <jon.haggblad@gmail.com>
2022-12-19 11:22:51 +00:00
Gala f047209baf Merge pull request #2691 from nymtech/2129-buy-2-secc
ui and copy changes
2022-12-19 10:43:03 +01:00
Gala cc5a69d4f1 Merge branch 'release/v1.1.4' into 2129-buy-2-secc 2022-12-19 10:40:01 +01:00
Gala 776d27a899 Merge pull request #2694 from nymtech/2687-remove-warning
remove warning error message
2022-12-19 10:35:25 +01:00
Gala 829dbb1695 Merge pull request #2689 from nymtech/2139-buy-secc-1
adding bity icon and wallet address
2022-12-19 10:33:47 +01:00
Jon Häggblad 52156e0c38 validator-client: fix typo in error message 2022-12-19 09:22:30 +01:00
Jon Häggblad 901275fd63 wallet: rewrite some abci errors on the fly (#2716)
* wallet: rewrite some abci errors on the fly

* changelog: update

* Tidy
2022-12-19 09:22:25 +01:00
Jon Häggblad 6c4f0bc2f4 validator-client: fix typo in error message 2022-12-19 09:12:33 +01:00
Jon Häggblad 052a9a71c2 client: tweak shutdown order (#2724)
* clients: slightly tweak shutdown

* tweak log
2022-12-16 17:03:39 +01:00
Jon Häggblad da094f0208 wallet: rewrite some abci errors on the fly (#2716)
* wallet: rewrite some abci errors on the fly

* changelog: update

* Tidy
2022-12-16 12:02:23 +01:00
Bogdan-Ștefan Neacşu 254302ec38 Feature/auto dkg advance (#2714)
* Add dkg epoch

* Make epoch state advancement dependent only on time

* Nym api tries advancing the dkg epoch state

* Update the time table a bit

It still needs to be changed before production, as the sign-up timeframe
needs to be something like a few days.

* Update changelog

* Fix tests

* Fix clippy after rustc update
2022-12-16 12:21:39 +02:00
Jon Häggblad a0a73421d0 fix clippy for new rustc 2022-12-16 11:19:53 +01:00
Jon Häggblad b7be48a1b3 Merge remote-tracking branch 'origin/release/v1.1.4' into develop 2022-12-16 11:09:31 +01:00
Jon Häggblad 870c4f73a8 socks5: send additional status messages available for the frontend (#2715)
* socks5: send network-requester error in status channel

* Minor tidy

* task-manager: send status msg to indicate ready

* changelog: add note

* coconut/tests: fix clippy for rustc 1.66
2022-12-16 00:24:45 +01:00
Jon Häggblad c2c883e840 client: create websocket handler builder (#2700)
* client: create websocket handler builder

* rustfmt
2022-12-16 00:23:58 +01:00
Jędrzej Stuczyński 4d7e21e0f2 fix: ignore corrupted surb storage and instead create fresh one (#2711)
* checking for correct surb  metadata on db load

* archiving corrupted database on load and attempting to start fresh session instead

* checking for data corruption by looking at flush timestamp

* Moving public import to separate section
2022-12-15 15:45:54 +00:00
Jędrzej Stuczyński c0ffbb0cb2 Fix multi-surb backwards compatibility in pre 1.1.4 client config files (#2703)
* Defaulting to 'false' value for 'send_anonymously' in socks5 config if not present

* Created method to change all empty core client config fields to their default values

* Using default values for surb reply storage in 'run' command if left unset
2022-12-15 11:21:40 +00:00
Bogdan-Ștefan Neacşu 5e600de932 Modify wasm specific make targets (#2693) 2022-12-15 12:22:43 +02:00
farbanas 70fcb8c046 feat: added the rest of the generators, updated some fields based on PR comments 2022-12-15 10:07:19 +01:00
Gala 80c81fa3d7 using a plain string 2022-12-14 14:52:33 +01:00
Gala 27e6539e98 remove message only for gateways 2022-12-14 14:48:49 +01:00
Gala a2d10d9956 remove warning error message 2022-12-14 14:12:16 +01:00
Gala 142a2bb26b copy 2022-12-14 13:05:54 +01:00
Gala 677d8c7fce text size 2022-12-14 12:30:10 +01:00
Gala 3563ad67b2 ui and copy changes 2022-12-14 12:21:36 +01:00
Gala c11a4c23fa adding bity icon and wallet address 2022-12-14 11:16:08 +01:00
farbanas ce676c2bb5 Merge branch 'release/v1.1.3' 2022-12-13 15:18:49 +01:00
farbanas a096f9d54e Merge branch 'release/v1.1.3' 2022-12-13 13:24:01 +01:00
farbanas d9b6823106 Merge branch 'release/v1.1.2' 2022-12-07 12:37:14 +01:00
farbanas 89bcb5649b changed ubuntu-latest on GH actions to ubuntu-20.04 2022-12-06 17:23:08 +01:00
farbanas 53444cf55a fix: rewarding denom was unyxt by default, it should be unymt 2022-12-05 13:22:21 +01:00
farbanas f2e460a96b chore: import cleanup 2022-12-01 12:17:46 +01:00
farbanas b5b7b7255b feat: add vesting contract instatiate message generation 2022-12-01 11:41:03 +01:00
farbanas 894a46688a chore: formatting 2022-12-01 10:21:00 +01:00
farbanas 5d3550a569 fix: remove the debug output for instantiate message as it incorrectly escapes strings 2022-12-01 10:16:36 +01:00
farbanas b43dab4f83 chore: added a couple of debug messages to parseOptionalAccount 2022-11-30 17:24:25 +01:00
farbanas 1bdb58571d feat: refactor cosmwasm nym-cli command a bit to support multiple tiers. Add a generator for mixnet contract instantiate messages 2022-11-30 16:01:35 +01:00
Gala a74a99d81d cleaning 2022-08-10 16:38:56 +02:00
Gala c09d3af92f Merge branch 'develop' into 340-ne-content 2022-08-10 16:35:38 +02:00
Gala 76773c58d7 some styles 2022-08-10 16:34:30 +02:00
Gala fd90175e87 adding button on mov nav and make it smaller 2022-08-10 15:43:42 +02:00
Gala 0eb859467e adding a switch between networks 2022-08-10 15:09:44 +02:00
496 changed files with 14701 additions and 14544 deletions
+1 -1
View File
@@ -14,7 +14,7 @@ GEOIPUPDATE_LICENSE_KEY=xxx
# List of space-separated database edition IDs. Edition IDs may
# consist of letters, digits, and dashes. For example, GeoIP2-City
# would download the GeoIP2 City database (GeoIP2-City).
GEOIPUPDATE_EDITION_IDS=GeoLite2-Country
GEOIPUPDATE_EDITION_IDS=GeoLite2-City
# The number of hours between geoipupdate runs. If this is not set
# or is set to 0, geoipupdate will run once and exit.
GEOIPUPDATE_FREQUENCY=72
+2 -2
View File
@@ -60,7 +60,7 @@ jobs:
target/release/nym-gateway
target/release/nym-mixnode
target/release/nym-socks5-client
target/release/nym-validator-api
target/release/nym-api
target/release/nym-network-requester
target/release/nym-network-statistics
target/release/nym-cli
@@ -75,7 +75,7 @@ jobs:
target/release/nym-gateway
target/release/nym-mixnode
target/release/nym-socks5-client
target/release/nym-validator-api
target/release/nym-api
target/release/nym-network-requester
target/release/nym-network-statistics
target/release/nym-cli
+3 -1
View File
@@ -38,4 +38,6 @@ validator-config
validator-api-config.toml
dist
storybook-static
envs/qwerty.env
envs/qwerty.env
Cargo.lock
nym-connect/Cargo.lock
+7 -5
View File
@@ -1,6 +1,8 @@
{
"mainnet":[{
"nymd_url":"https://rpc.nyx.nodes.guru/",
"api_url":"https://api.nyx.nodes.guru/"
}]
}
"mainnet": [
{
"nyxd_url": "https://rpc.nyx.nodes.guru/",
"api_url": "https://api.nyx.nodes.guru/"
}
]
}
+86 -40
View File
@@ -2,22 +2,74 @@
Post 1.0.0 release, the changelog format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
## [v1.1.6] (2023-01-17)
### Added
### Changed
- all-binaries: improved error logging ([#2686])
- native client: bring shutdown logic up to the same level as socks5-client
- streamline override_config functions -> there's a lot of duplicate if statements everywhere ([#2774])
- clean-up nym-api startup arguments/flags to use clap 3 and its macro-derived arguments ([#2772])
- renamed all references to validator_api to nym_api
- renamed all references to nymd to nyxd ([#2696])
- all-binaries: standarised argument names (note: old names should still be accepted) ([#2762]
[#2686]: https://github.com/nymtech/nym/pull/2686
### Fixed
- nym-api: should now correctly use `rewarding.enabled` config flag ([#2753])
[#2696]: https://github.com/nymtech/nym/pull/2696
[#2753]: https://github.com/nymtech/nym/pull/2753
[#2762]: https://github.com/nymtech/nym/pull/2762
[#2772]: https://github.com/nymtech/nym/pull/2772
[#2774]: https://github.com/nymtech/nym/pull/2774
## [v1.1.5] (2023-01-10)
### Added
### Changed
## [v1.1.5] (2023-01-10)
### Added
- socks5: send status message for service ready, and network-requester error response in https://github.com/nymtech/nym/pull/2715
### Changed
- all-binaries: improved error logging in https://github.com/nymtech/nym/pull/2686
- native client: bring shutdown logic up to the same level as socks5-client in https://github.com/nymtech/nym/pull/2695
- nym-api, coconut-dkg contract: automatic, time-based dkg epoch state advancement in https://github.com/nymtech/nym/pull/2670
- DKG resharing unit test by @neacsu in https://github.com/nymtech/nym/pull/2668
- Renaming validator-api to nym-api by @futurechimp in https://github.com/nymtech/nym/pull/1863
- Modify wasm specific make targets by @neacsu in https://github.com/nymtech/nym/pull/2693
- client: create websocket handler builder by @octol in https://github.com/nymtech/nym/pull/2700
- Outfox and Lion by @durch in https://github.com/nymtech/nym/pull/2730
- Feature/multi surb transmission lanes by @jstuczyn in https://github.com/nymtech/nym/pull/2723
## [v1.1.4] (2022-12-20)
This release adds multiple Single Use Reply Blocks (SURBs) to allow arbitrarily-sized anonymized replies.
At the moment this is turned off by default, but available for use by application developers.
We will need to wait for network-requesters to upgrade to this new release, after which multi-SURB anonymization will become the default setting for the SOCKS proxy clients.
The release also include some additional work for distributed key generation in the Coconut signing authority nodes.
### Changed
- Feature/dkg contract threshold by @neacsu in https://github.com/nymtech/nym/pull/1885
- Multi-surbs by @jstuczyn in https://github.com/nymtech/nym/pull/2667
- Fix multi-surb backwards compatibility in pre 1.1.4 client config files by @jstuczyn in https://github.com/nymtech/nym/pull/2703
- fix: ignore corrupted surb storage and instead create fresh one by @jstuczyn in https://github.com/nymtech/nym/pull/2711
- socks5: rework waiting in inbound.rs by @octol in https://github.com/nymtech/nym/pull/1880
## [v1.1.3] (2022-12-13)
### Changed
- validator-api: can recover from shutdown during DKG process ([#1872])
- clients: deduplicate gateway inititialization, part of work towards a rust-sdk
- clients: deduplicate gateway initialization, part of work towards a rust-sdk
- clients: keep all transmission lanes going at all times by making priority probabilistic
- clients: ability to use multi-reply SURBs to send arbitrarily long messages fully anonymously whilst requesting additional reply blocks whenever they're about to run out ([#1796], [#1801], [#1804], [#1835], [#1858], [#1883]))
@@ -25,7 +77,7 @@ Post 1.0.0 release, the changelog format is based on [Keep a Changelog](https://
- network-requester: fix bug where websocket connection disconnect resulted in success error code
- clients: fix a few panics handling the gateway-client
- mixnode, gateway, validator-api: Use mainnet values as defaults for URLs and mixnet contract ([#1884])
- mixnode, gateway, validator-api: Use mainnet values as defaults for URLs and mixnet contract ([#1884])
- socks5: fixed bug where connections sometimes where closed too early
- clients: improve message logging when received message fails to get reconstructed ([#1803])
@@ -45,7 +97,7 @@ Post 1.0.0 release, the changelog format is based on [Keep a Changelog](https://
- gateway: Renamed flag from `enabled/disabled_credentials_mode` to `only-coconut-credentials`
- "Family" feature for node families + layers
- Initial coconut functionality including credentials and distributed key generation
- Initial coconut functionality including credentials and distributed key generation
## [v1.1.1](https://github.com/nymtech/nym/tree/v1.1.1) (2022-11-29)
@@ -81,7 +133,6 @@ Post 1.0.0 release, the changelog format is based on [Keep a Changelog](https://
[#1786]: https://github.com/nymtech/nym/pull/1786
[#1805]: https://github.com/nymtech/nym/pull/1805
## [v1.1.0](https://github.com/nymtech/nym/tree/v1.1.0) (2022-11-09)
### Added
@@ -93,7 +144,7 @@ Post 1.0.0 release, the changelog format is based on [Keep a Changelog](https://
- native-client/socks5-client/wasm-client: `use_extended_packet_size` Debug config option to make the client use 'ExtendedPacketSize' for its traffic (32kB as opposed to 2kB in 1.0.2) ([#1671])
- network-requester: added additional Blockstream Green wallet endpoint to `example.allowed.list` ([#1611])
- validator-api: add `interval_operating_cost` and `profit_margin_percent` to compute reward estimation endpoint
- validator-client: added `query_contract_smart` and `query_contract_raw` on `NymdClient` ([#1558])
- validator-client: added `query_contract_smart` and `query_contract_raw` on `NyxdClient` ([#1558])
- wasm-client: uses updated wasm-compatible `client-core` so that it's now capable of packet retransmission, cover traffic and poisson delay (among other things!) ([#1673])
### Fixed
@@ -108,7 +159,7 @@ Post 1.0.0 release, the changelog format is based on [Keep a Changelog](https://
- gateway-client: will attempt to read now as many as 8 websocket messages at once, assuming they're already available on the socket ([#1669])
- moved `Percent` struct to `contracts-common`, change affects explorer-api
- socks5 client: graceful shutdown should fix error on disconnect in nym-connect ([#1591])
- validator-api: changed error serialization on `inclusion_probability`, `stake-saturation` and `reward-estimation` endpoints to provide more accurate information ([#1681])
- validator-api: changed error serialization on `inclusion_probability`, `stake-saturation` and `reward-estimation` endpoints to provide more accurate information ([#1681])
- validator-client: made `fee` argument optional for `execute` and `execute_multiple` ([#1541])
- wasm-client: fixed build errors on MacOS and changed example JS code to use mainnet ([#1585])
- validator-api: changes to internal SQL schema due to the mixnet contract revamp ([#1472])
@@ -136,7 +187,6 @@ Post 1.0.0 release, the changelog format is based on [Keep a Changelog](https://
[#1724]: https://github.com/nymtech/nym/pull/1724
[#1725]: https://github.com/nymtech/nym/pull/1725
## [nym-binaries-1.0.2](https://github.com/nymtech/nym/tree/nym-binaries-1.0.2)
### Added
@@ -189,9 +239,8 @@ Post 1.0.0 release, the changelog format is based on [Keep a Changelog](https://
- All binaries and cosmwasm blobs are configured at runtime now; binaries are configured using environment variables or .env files and contracts keep the configuration parameters in storage ([#1463])
- gateway, network-statistics: include gateway id in the sent statistical data ([#1478])
- network explorer: tweak how active set probability is shown ([#1503])
- validator-api: rewarder set update fails without panicking on possible nymd queries ([#1520])
- network-requester, socks5 client (nym-connect): send and receive respectively a message error to be displayed about filter check failure ([#1576])
- validator-api: rewarder set update fails without panicking on possible nyxd queries ([#1520])
- network-requester, socks5 client (nym-connect): send and receive respectively a message error to be displayed about filter check failure ([#1576])
[#1249]: https://github.com/nymtech/nym/pull/1249
[#1256]: https://github.com/nymtech/nym/pull/1256
@@ -285,9 +334,9 @@ Post 1.0.0 release, the changelog format is based on [Keep a Changelog](https://
- Bump minimist from 1.2.5 to 1.2.6 in /clients/tauri-client [\#1163](https://github.com/nymtech/nym/pull/1163) ([dependabot[bot]](https://github.com/apps/dependabot))
- Bump minimist from 1.2.5 to 1.2.6 in /clients/webassembly/js-example [\#1162](https://github.com/nymtech/nym/pull/1162) ([dependabot[bot]](https://github.com/apps/dependabot))
- Bump minimist from 1.2.5 to 1.2.6 in /clients/native/examples/js-examples/websocket [\#1160](https://github.com/nymtech/nym/pull/1160) ([dependabot[bot]](https://github.com/apps/dependabot))
- Bump minimist from 1.2.5 to 1.2.6 in /docker/typescript\_client/upload\_contract [\#1159](https://github.com/nymtech/nym/pull/1159) ([dependabot[bot]](https://github.com/apps/dependabot))
- Bump minimist from 1.2.5 to 1.2.6 in /docker/typescript_client/upload_contract [\#1159](https://github.com/nymtech/nym/pull/1159) ([dependabot[bot]](https://github.com/apps/dependabot))
- Feature/vesting full [\#1158](https://github.com/nymtech/nym/pull/1158) ([fmtabbara](https://github.com/fmtabbara))
- get\_current\_epoch tauri [\#1156](https://github.com/nymtech/nym/pull/1156) ([durch](https://github.com/durch))
- get_current_epoch tauri [\#1156](https://github.com/nymtech/nym/pull/1156) ([durch](https://github.com/durch))
- Cleanup [\#1155](https://github.com/nymtech/nym/pull/1155) ([durch](https://github.com/durch))
- Feature flag reward payments [\#1154](https://github.com/nymtech/nym/pull/1154) ([durch](https://github.com/durch))
- Add Query endpoints for calculating rewards [\#1152](https://github.com/nymtech/nym/pull/1152) ([durch](https://github.com/durch))
@@ -296,7 +345,7 @@ Post 1.0.0 release, the changelog format is based on [Keep a Changelog](https://
- wallet: use Urls rather than Strings for validator urls [\#1148](https://github.com/nymtech/nym/pull/1148) ([octol](https://github.com/octol))
- Change accumulated reward to Option, migrate delegations [\#1147](https://github.com/nymtech/nym/pull/1147) ([durch](https://github.com/durch))
- wallet: fetch validators url remotely if available [\#1146](https://github.com/nymtech/nym/pull/1146) ([octol](https://github.com/octol))
- Fix delegated\_free calculation [\#1145](https://github.com/nymtech/nym/pull/1145) ([durch](https://github.com/durch))
- Fix delegated_free calculation [\#1145](https://github.com/nymtech/nym/pull/1145) ([durch](https://github.com/durch))
- Update Nym wallet dependencies to use `ts-packages` [\#1144](https://github.com/nymtech/nym/pull/1144) ([mmsinclair](https://github.com/mmsinclair))
- wallet: try validators one by one if available [\#1143](https://github.com/nymtech/nym/pull/1143) ([octol](https://github.com/octol))
- Update Network Explorer Packages and add mix node identity key copy [\#1142](https://github.com/nymtech/nym/pull/1142) ([mmsinclair](https://github.com/mmsinclair))
@@ -336,14 +385,13 @@ Post 1.0.0 release, the changelog format is based on [Keep a Changelog](https://
- feature/pedersen-commitments [\#1048](https://github.com/nymtech/nym/pull/1048) ([danielementary](https://github.com/danielementary))
- Feature/reuse init owner [\#970](https://github.com/nymtech/nym/pull/970) ([neacsu](https://github.com/neacsu))
## [v0.12.1](https://github.com/nymtech/nym/tree/v0.12.1) (2021-12-23)
[Full Changelog](https://github.com/nymtech/nym/compare/v0.12.0...v0.12.1)
**Implemented enhancements:**
- Add version check to binaries [\#967](https://github.com/nymtech/nym/issues/967)
- Add version check to binaries [\#967](https://github.com/nymtech/nym/issues/967)
**Fixed bugs:**
@@ -373,7 +421,7 @@ Post 1.0.0 release, the changelog format is based on [Keep a Changelog](https://
- Bugfix/remove mixnode bonding overwrite [\#917](https://github.com/nymtech/nym/pull/917) ([jstuczyn](https://github.com/jstuczyn))
- Fixes crash condition in validator API when calculating last day uptime [\#909](https://github.com/nymtech/nym/pull/909) ([jstuczyn](https://github.com/jstuczyn))
- Bugfix/monitor initial values wait [\#907](https://github.com/nymtech/nym/pull/907) ([jstuczyn](https://github.com/jstuczyn))
- Bug fix: Network Explorer: Add freegeoip API key and split out tasks for country distributions [\#806](https://github.com/nymtech/nym/pull/806) ([mmsinclair](https://github.com/mmsinclair))
- Bug fix: Network Explorer: Add freegeoip API key and split out tasks for country distributions [\#806](https://github.com/nymtech/nym/pull/806) ([mmsinclair](https://github.com/mmsinclair))
- Explorer API: port test now split out address resolution and add units tests [\#755](https://github.com/nymtech/nym/pull/755) ([mmsinclair](https://github.com/mmsinclair))
**Closed issues:**
@@ -388,7 +436,7 @@ Post 1.0.0 release, the changelog format is based on [Keep a Changelog](https://
- help!!! [\#712](https://github.com/nymtech/nym/issues/712)
- UX feature request: show all delegated nodes in wallet [\#711](https://github.com/nymtech/nym/issues/711)
- UX feature request: add current balance on wallet pages [\#710](https://github.com/nymtech/nym/issues/710)
- got sign issue from bot [\#709](https://github.com/nymtech/nym/issues/709)
- got sign issue from bot [\#709](https://github.com/nymtech/nym/issues/709)
- As a wallet user, I would like to be able to log out of the wallet [\#706](https://github.com/nymtech/nym/issues/706)
- As a wallet user, I would like to have a "receive" page where I can see my own wallet address [\#705](https://github.com/nymtech/nym/issues/705)
- Update native client/socks client/mixnode/gateway `upgrade` command [\#689](https://github.com/nymtech/nym/issues/689)
@@ -398,7 +446,7 @@ Post 1.0.0 release, the changelog format is based on [Keep a Changelog](https://
- nym-socks5-client crash after opening Keybase team "Browse all channels" [\#494](https://github.com/nymtech/nym/issues/494)
- Mixed Content problem [\#400](https://github.com/nymtech/nym/issues/400)
- Gateway disk quota [\#137](https://github.com/nymtech/nym/issues/137)
- Simplify message encapsulation with regards to topology [\#127](https://github.com/nymtech/nym/issues/127)
- Simplify message encapsulation with regards to topology [\#127](https://github.com/nymtech/nym/issues/127)
- Create constants for cli argument names [\#115](https://github.com/nymtech/nym/issues/115)
- Using Blake3 as a hash function [\#103](https://github.com/nymtech/nym/issues/103)
- Validator should decide which layer a node is in [\#86](https://github.com/nymtech/nym/issues/86)
@@ -454,10 +502,10 @@ Post 1.0.0 release, the changelog format is based on [Keep a Changelog](https://
- Feature/pre cosmrs updates [\#935](https://github.com/nymtech/nym/pull/935) ([jstuczyn](https://github.com/jstuczyn))
- Feature/client on behalf [\#934](https://github.com/nymtech/nym/pull/934) ([neacsu](https://github.com/neacsu))
- Webpack wallet prod configuration [\#933](https://github.com/nymtech/nym/pull/933) ([tommyv1987](https://github.com/tommyv1987))
- Adding tx\_hash to wallet response [\#932](https://github.com/nymtech/nym/pull/932) ([futurechimp](https://github.com/futurechimp))
- Adding tx_hash to wallet response [\#932](https://github.com/nymtech/nym/pull/932) ([futurechimp](https://github.com/futurechimp))
- Release/1.0.0 pre1 [\#931](https://github.com/nymtech/nym/pull/931) ([durch](https://github.com/durch))
- Feature/identity verification [\#930](https://github.com/nymtech/nym/pull/930) ([jstuczyn](https://github.com/jstuczyn))
- Move cleaned up smart contracts to main code repo [\#929](https://github.com/nymtech/nym/pull/929) ([mfahampshire](https://github.com/mfahampshire))
- Move cleaned up smart contracts to main code repo [\#929](https://github.com/nymtech/nym/pull/929) ([mfahampshire](https://github.com/mfahampshire))
- Feature/mixnet contract further adjustments [\#928](https://github.com/nymtech/nym/pull/928) ([jstuczyn](https://github.com/jstuczyn))
- typo copy change for nodemap [\#926](https://github.com/nymtech/nym/pull/926) ([Aid19801](https://github.com/Aid19801))
- Feature/UI enhancements for Desktop Wallet [\#925](https://github.com/nymtech/nym/pull/925) ([fmtabbara](https://github.com/fmtabbara))
@@ -470,7 +518,7 @@ Post 1.0.0 release, the changelog format is based on [Keep a Changelog](https://
- Feature/faucet page react [\#911](https://github.com/nymtech/nym/pull/911) ([fmtabbara](https://github.com/fmtabbara))
- Feature/mixnet contract refactor [\#910](https://github.com/nymtech/nym/pull/910) ([futurechimp](https://github.com/futurechimp))
- Update README.md [\#905](https://github.com/nymtech/nym/pull/905) ([tommyv1987](https://github.com/tommyv1987))
- BUG: Bond cell denom [\#904](https://github.com/nymtech/nym/pull/904) ([Aid19801](https://github.com/Aid19801))
- BUG: Bond cell denom [\#904](https://github.com/nymtech/nym/pull/904) ([Aid19801](https://github.com/Aid19801))
- Explorer UI tests missing data-testid [\#903](https://github.com/nymtech/nym/pull/903) ([tommyv1987](https://github.com/tommyv1987))
- Fix up Nym-Wallet README.md [\#899](https://github.com/nymtech/nym/pull/899) ([tommyv1987](https://github.com/tommyv1987))
- Feature/batch delegator rewarding [\#898](https://github.com/nymtech/nym/pull/898) ([jstuczyn](https://github.com/jstuczyn))
@@ -488,7 +536,7 @@ Post 1.0.0 release, the changelog format is based on [Keep a Changelog](https://
- Reverted gateway registration handshake to its 0.11.0 version [\#882](https://github.com/nymtech/nym/pull/882) ([jstuczyn](https://github.com/jstuczyn))
- Network Explorer [\#881](https://github.com/nymtech/nym/pull/881) ([mmsinclair](https://github.com/mmsinclair))
- Feature/rewarding interval updates [\#880](https://github.com/nymtech/nym/pull/880) ([jstuczyn](https://github.com/jstuczyn))
- Put client\_address and id in the correct order [\#875](https://github.com/nymtech/nym/pull/875) ([neacsu](https://github.com/neacsu))
- Put client_address and id in the correct order [\#875](https://github.com/nymtech/nym/pull/875) ([neacsu](https://github.com/neacsu))
- remove gateway selection on delegation and undelegation pages [\#873](https://github.com/nymtech/nym/pull/873) ([fmtabbara](https://github.com/fmtabbara))
- Set MSRV on all binaries to 1.56 [\#872](https://github.com/nymtech/nym/pull/872) ([jstuczyn](https://github.com/jstuczyn))
- add native window items \(copy/paste\) via tauri [\#871](https://github.com/nymtech/nym/pull/871) ([fmtabbara](https://github.com/fmtabbara))
@@ -504,7 +552,7 @@ Post 1.0.0 release, the changelog format is based on [Keep a Changelog](https://
- Overflow checks in release [\#846](https://github.com/nymtech/nym/pull/846) ([jstuczyn](https://github.com/jstuczyn))
- fix delegate success overflow [\#842](https://github.com/nymtech/nym/pull/842) ([fmtabbara](https://github.com/fmtabbara))
- Feature NYM wallet webdriverio test [\#841](https://github.com/nymtech/nym/pull/841) ([tommyv1987](https://github.com/tommyv1987))
- Update nym\_wallet.yml [\#840](https://github.com/nymtech/nym/pull/840) ([tommyv1987](https://github.com/tommyv1987))
- Update nym_wallet.yml [\#840](https://github.com/nymtech/nym/pull/840) ([tommyv1987](https://github.com/tommyv1987))
- Feature/vouchers [\#837](https://github.com/nymtech/nym/pull/837) ([aniampio](https://github.com/aniampio))
- Apply readable ids to elements on Nym Wallet [\#836](https://github.com/nymtech/nym/pull/836) ([tommyv1987](https://github.com/tommyv1987))
- Feature/removal of monitor good nodes [\#833](https://github.com/nymtech/nym/pull/833) ([jstuczyn](https://github.com/jstuczyn))
@@ -528,8 +576,8 @@ Post 1.0.0 release, the changelog format is based on [Keep a Changelog](https://
- Created getters for AccountData [\#787](https://github.com/nymtech/nym/pull/787) ([jstuczyn](https://github.com/jstuczyn))
- Feature/migrate hidden delegations [\#786](https://github.com/nymtech/nym/pull/786) ([neacsu](https://github.com/neacsu))
- Feature/persistent gateway storage [\#784](https://github.com/nymtech/nym/pull/784) ([jstuczyn](https://github.com/jstuczyn))
- Replaced unwrap\_or\_else with unwrap\_or\_default [\#780](https://github.com/nymtech/nym/pull/780) ([jstuczyn](https://github.com/jstuczyn))
- Add block\_height method to Delegation [\#778](https://github.com/nymtech/nym/pull/778) ([durch](https://github.com/durch))
- Replaced unwrap_or_else with unwrap_or_default [\#780](https://github.com/nymtech/nym/pull/780) ([jstuczyn](https://github.com/jstuczyn))
- Add block_height method to Delegation [\#778](https://github.com/nymtech/nym/pull/778) ([durch](https://github.com/durch))
- Make fee helpers public [\#777](https://github.com/nymtech/nym/pull/777) ([durch](https://github.com/durch))
- re-enable bonding [\#776](https://github.com/nymtech/nym/pull/776) ([fmtabbara](https://github.com/fmtabbara))
- Explorer-api: add API resource to show the delegations for each mix node [\#774](https://github.com/nymtech/nym/pull/774) ([mmsinclair](https://github.com/mmsinclair))
@@ -538,14 +586,14 @@ Post 1.0.0 release, the changelog format is based on [Keep a Changelog](https://
- Adding deps for building the Tauri wallet under Ubuntu [\#770](https://github.com/nymtech/nym/pull/770) ([futurechimp](https://github.com/futurechimp))
- remove alert [\#767](https://github.com/nymtech/nym/pull/767) ([fmtabbara](https://github.com/fmtabbara))
- Feature/consumable bandwidth [\#766](https://github.com/nymtech/nym/pull/766) ([neacsu](https://github.com/neacsu))
- Update coconut-rs and use hash\_to\_scalar from there [\#765](https://github.com/nymtech/nym/pull/765) ([neacsu](https://github.com/neacsu))
- Update coconut-rs and use hash_to_scalar from there [\#765](https://github.com/nymtech/nym/pull/765) ([neacsu](https://github.com/neacsu))
- Feature/active sets [\#764](https://github.com/nymtech/nym/pull/764) ([jstuczyn](https://github.com/jstuczyn))
- add app alert banner [\#762](https://github.com/nymtech/nym/pull/762) ([fmtabbara](https://github.com/fmtabbara))
- Updated cosmos-sdk [\#761](https://github.com/nymtech/nym/pull/761) ([jstuczyn](https://github.com/jstuczyn))
- Feature/bond blockstamp [\#760](https://github.com/nymtech/nym/pull/760) ([neacsu](https://github.com/neacsu))
- Feature/revert migration code [\#759](https://github.com/nymtech/nym/pull/759) ([neacsu](https://github.com/neacsu))
- Bump next from 11.1.0 to 11.1.1 in /wallet-web [\#758](https://github.com/nymtech/nym/pull/758) ([dependabot[bot]](https://github.com/apps/dependabot))
- Add block\_height in the Delegation structure as well [\#757](https://github.com/nymtech/nym/pull/757) ([neacsu](https://github.com/neacsu))
- Add block_height in the Delegation structure as well [\#757](https://github.com/nymtech/nym/pull/757) ([neacsu](https://github.com/neacsu))
- Feature/add blockstamp [\#756](https://github.com/nymtech/nym/pull/756) ([neacsu](https://github.com/neacsu))
- NetworkMonitorBuilder - starting the monitor after rocket has launched [\#754](https://github.com/nymtech/nym/pull/754) ([jstuczyn](https://github.com/jstuczyn))
- Enabled validators api argument [\#753](https://github.com/nymtech/nym/pull/753) ([jstuczyn](https://github.com/jstuczyn))
@@ -557,21 +605,21 @@ Post 1.0.0 release, the changelog format is based on [Keep a Changelog](https://
- Feature/more reliable uptime calculation [\#747](https://github.com/nymtech/nym/pull/747) ([jstuczyn](https://github.com/jstuczyn))
- Update template toml key [\#746](https://github.com/nymtech/nym/pull/746) ([neacsu](https://github.com/neacsu))
- Feature/cred after handshake [\#745](https://github.com/nymtech/nym/pull/745) ([neacsu](https://github.com/neacsu))
- Reinstate the POST method blind\_sign [\#744](https://github.com/nymtech/nym/pull/744) ([neacsu](https://github.com/neacsu))
- Reinstate the POST method blind_sign [\#744](https://github.com/nymtech/nym/pull/744) ([neacsu](https://github.com/neacsu))
- explorer-api: add pending field to port check response [\#742](https://github.com/nymtech/nym/pull/742) ([mmsinclair](https://github.com/mmsinclair))
- Feature/use delegation rates [\#741](https://github.com/nymtech/nym/pull/741) ([neacsu](https://github.com/neacsu))
- Feature/copy to clipboard [\#740](https://github.com/nymtech/nym/pull/740) ([fmtabbara](https://github.com/fmtabbara))
- Feature/update wallet with stake rates [\#739](https://github.com/nymtech/nym/pull/739) ([neacsu](https://github.com/neacsu))
- Add stake reward rates and bump version of client [\#738](https://github.com/nymtech/nym/pull/738) ([neacsu](https://github.com/neacsu))
- Bump next from 10.1.3 to 11.1.0 in /wallet-web [\#737](https://github.com/nymtech/nym/pull/737) ([dependabot[bot]](https://github.com/apps/dependabot))
- Feature/nymd client integration [\#736](https://github.com/nymtech/nym/pull/736) ([jstuczyn](https://github.com/jstuczyn))
- Feature/nyxd client integration [\#736](https://github.com/nymtech/nym/pull/736) ([jstuczyn](https://github.com/jstuczyn))
- Bug/fix parking lot on wasm [\#735](https://github.com/nymtech/nym/pull/735) ([neacsu](https://github.com/neacsu))
- Explorer API: add new HTTP resource to decorate mix nodes with geoip locations [\#734](https://github.com/nymtech/nym/pull/734) ([mmsinclair](https://github.com/mmsinclair))
- Feature/completing nymd client api [\#732](https://github.com/nymtech/nym/pull/732) ([jstuczyn](https://github.com/jstuczyn))
- Feature/completing nyxd client api [\#732](https://github.com/nymtech/nym/pull/732) ([jstuczyn](https://github.com/jstuczyn))
- Explorer API - add port check and node description/stats proxy [\#731](https://github.com/nymtech/nym/pull/731) ([mmsinclair](https://github.com/mmsinclair))
- Feature/nymd client fee handling [\#730](https://github.com/nymtech/nym/pull/730) ([jstuczyn](https://github.com/jstuczyn))
- Feature/nyxd client fee handling [\#730](https://github.com/nymtech/nym/pull/730) ([jstuczyn](https://github.com/jstuczyn))
- Update DelegationCheck.tsx [\#725](https://github.com/nymtech/nym/pull/725) ([jessgess](https://github.com/jessgess))
- Rust nymd/cosmwasm client [\#724](https://github.com/nymtech/nym/pull/724) ([jstuczyn](https://github.com/jstuczyn))
- Rust nyxd/cosmwasm client [\#724](https://github.com/nymtech/nym/pull/724) ([jstuczyn](https://github.com/jstuczyn))
- Removed wasm feature bypassing cyclic dependencies [\#723](https://github.com/nymtech/nym/pull/723) ([jstuczyn](https://github.com/jstuczyn))
- Updated used sphinx dependency to the most recent revision [\#722](https://github.com/nymtech/nym/pull/722) ([jstuczyn](https://github.com/jstuczyn))
- update state management and validation [\#721](https://github.com/nymtech/nym/pull/721) ([fmtabbara](https://github.com/fmtabbara))
@@ -590,10 +638,8 @@ Post 1.0.0 release, the changelog format is based on [Keep a Changelog](https://
- Bond and delegation alerts [\#698](https://github.com/nymtech/nym/pull/698) ([fmtabbara](https://github.com/fmtabbara))
- Bugfix/network monitor version check [\#697](https://github.com/nymtech/nym/pull/697) ([jstuczyn](https://github.com/jstuczyn))
- Feature/other containers [\#692](https://github.com/nymtech/nym/pull/692) ([neacsu](https://github.com/neacsu))
- Using validator API instead of nymd [\#690](https://github.com/nymtech/nym/pull/690) ([futurechimp](https://github.com/futurechimp))
- Using validator API instead of nyxd [\#690](https://github.com/nymtech/nym/pull/690) ([futurechimp](https://github.com/futurechimp))
- Hang coconut issuance off the validator-api [\#679](https://github.com/nymtech/nym/pull/679) ([durch](https://github.com/durch))
- Update hmac and blake3 [\#673](https://github.com/nymtech/nym/pull/673) ([durch](https://github.com/durch))
\* *This Changelog was automatically generated by [github_changelog_generator](https://github.com/github-changelog-generator/github-changelog-generator)*
\* _This Changelog was automatically generated by [github_changelog_generator](https://github.com/github-changelog-generator/github-changelog-generator)_
Generated
+171 -23
View File
@@ -23,6 +23,16 @@ dependencies = [
"generic-array 0.14.5",
]
[[package]]
name = "aead"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c192eb8f11fc081b0fe4259ba5af04217d4e0faddd02417310a927911abd7c8"
dependencies = [
"crypto-common",
"generic-array 0.14.5",
]
[[package]]
name = "aes"
version = "0.7.5"
@@ -53,7 +63,7 @@ version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df5f85a83a7d8b0442b6aa7b504b8212c1733da07b98aae43d4bc21b2cb3cdf6"
dependencies = [
"aead",
"aead 0.4.3",
"aes 0.7.5",
"cipher 0.3.0",
"ctr 0.8.0",
@@ -81,6 +91,12 @@ dependencies = [
"memchr",
]
[[package]]
name = "anes"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299"
[[package]]
name = "ansi_term"
version = "0.12.1"
@@ -443,6 +459,12 @@ dependencies = [
"rustc_version 0.4.0",
]
[[package]]
name = "cast"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5"
[[package]]
name = "cc"
version = "1.0.73"
@@ -474,6 +496,30 @@ dependencies = [
"keystream",
]
[[package]]
name = "chacha20"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c7fc89c7c5b9e7a02dfe45cd2367bae382f9ed31c61ca8debe5f827c420a2f08"
dependencies = [
"cfg-if 1.0.0",
"cipher 0.4.3",
"cpufeatures",
]
[[package]]
name = "chacha20poly1305"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35"
dependencies = [
"aead 0.5.1",
"chacha20",
"cipher 0.4.3",
"poly1305",
"zeroize",
]
[[package]]
name = "chrono"
version = "0.4.19"
@@ -488,6 +534,33 @@ dependencies = [
"winapi",
]
[[package]]
name = "ciborium"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b0c137568cc60b904a7724001b35ce2630fd00d5d84805fbb608ab89509d788f"
dependencies = [
"ciborium-io",
"ciborium-ll",
"serde",
]
[[package]]
name = "ciborium-io"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "346de753af073cc87b52b2083a506b38ac176a44cfb05497b622e27be899b369"
[[package]]
name = "ciborium-ll"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "213030a2b5a4e0c0892b6652260cf6ccac84827b83a85a534e178e3906c4cf1b"
dependencies = [
"ciborium-io",
"half",
]
[[package]]
name = "cipher"
version = "0.3.0"
@@ -505,6 +578,7 @@ checksum = "d1873270f8f7942c191139cb8a40fd228da6c3fd2fc376d7e92d47aa14aeb59e"
dependencies = [
"crypto-common",
"inout",
"zeroize",
]
[[package]]
@@ -586,7 +660,7 @@ dependencies = [
[[package]]
name = "client-core"
version = "1.1.3"
version = "1.1.5"
dependencies = [
"async-trait",
"client-connections",
@@ -980,9 +1054,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1604dafd25fba2fe2d5895a9da139f8dc9b319a5fe5354ca137cbbce4e178d10"
dependencies = [
"atty",
"cast",
"cast 0.2.7",
"clap 2.34.0",
"criterion-plot",
"criterion-plot 0.4.4",
"csv",
"itertools",
"lazy_static",
@@ -999,13 +1073,49 @@ dependencies = [
"walkdir",
]
[[package]]
name = "criterion"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7c76e09c1aae2bc52b3d2f29e13c6572553b30c4aa1b8a49fd70de6412654cb"
dependencies = [
"anes",
"atty",
"cast 0.3.0",
"ciborium",
"clap 3.2.8",
"criterion-plot 0.5.0",
"itertools",
"lazy_static",
"num-traits",
"oorandom",
"plotters",
"rayon",
"regex",
"serde",
"serde_derive",
"serde_json",
"tinytemplate",
"walkdir",
]
[[package]]
name = "criterion-plot"
version = "0.4.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d00996de9f2f7559f7f4dc286073197f83e92256a59ed395f9aac01fe717da57"
dependencies = [
"cast",
"cast 0.2.7",
"itertools",
]
[[package]]
name = "criterion-plot"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6b50826342786a51a89e2da3a28f1c32b06e387201bc2d19791f622c673706b1"
dependencies = [
"cast 0.3.0",
"itertools",
]
@@ -1134,11 +1244,12 @@ dependencies = [
[[package]]
name = "crypto-common"
version = "0.1.3"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57952ca27b5e3606ff4dd79b0020231aaf9d6aa76dc05fd30137538c50bd3ce8"
checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3"
dependencies = [
"generic-array 0.14.5",
"rand_core 0.6.3",
"typenum",
]
@@ -1466,7 +1577,7 @@ dependencies = [
"bitvec",
"bls12_381 0.6.0",
"bs58",
"criterion",
"criterion 0.3.5",
"ff 0.11.0",
"group 0.11.0",
"lazy_static",
@@ -1651,7 +1762,7 @@ dependencies = [
[[package]]
name = "explorer-api"
version = "1.1.1"
version = "1.1.2"
dependencies = [
"chrono",
"clap 3.2.8",
@@ -1698,9 +1809,9 @@ checksum = "e88a8acf291dafb59c2d96e8f59828f3838bb1a70398823ade51a84de6a6deed"
[[package]]
name = "fastrand"
version = "1.7.0"
version = "1.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3fcf0cee53519c866c09b5de1f6c56ff9d647101f81c1964fa632e148896cdf"
checksum = "a7a407cfaa3385c4ae6b23e84623d48c2798d06e3e6a1878f7f59f17b3f86499"
dependencies = [
"instant",
]
@@ -3123,7 +3234,7 @@ dependencies = [
[[package]]
name = "nym-cli"
version = "1.1.3"
version = "1.1.5"
dependencies = [
"anyhow",
"base64",
@@ -3177,7 +3288,7 @@ dependencies = [
[[package]]
name = "nym-client"
version = "1.1.3"
version = "1.1.5"
dependencies = [
"clap 3.2.8",
"client-connections",
@@ -3216,7 +3327,7 @@ dependencies = [
[[package]]
name = "nym-gateway"
version = "1.1.3"
version = "1.1.5"
dependencies = [
"anyhow",
"async-trait",
@@ -3263,7 +3374,7 @@ dependencies = [
[[package]]
name = "nym-mixnode"
version = "1.1.3"
version = "1.1.5"
dependencies = [
"anyhow",
"bs58",
@@ -3305,7 +3416,7 @@ dependencies = [
[[package]]
name = "nym-network-requester"
version = "1.1.3"
version = "1.1.5"
dependencies = [
"async-trait",
"clap 3.2.8",
@@ -3337,7 +3448,7 @@ dependencies = [
[[package]]
name = "nym-network-statistics"
version = "1.1.3"
version = "1.1.5"
dependencies = [
"dirs",
"log",
@@ -3351,9 +3462,25 @@ dependencies = [
"tokio",
]
[[package]]
name = "nym-outfox"
version = "0.1.0"
dependencies = [
"blake3",
"chacha20",
"chacha20poly1305",
"criterion 0.4.0",
"curve25519-dalek",
"fastrand",
"getrandom 0.2.6",
"rayon",
"thiserror",
"zeroize",
]
[[package]]
name = "nym-socks5-client"
version = "1.1.3"
version = "1.1.5"
dependencies = [
"clap 3.2.8",
"client-connections",
@@ -3420,7 +3547,7 @@ dependencies = [
[[package]]
name = "nym-validator-api"
version = "1.1.3"
version = "1.1.5"
dependencies = [
"anyhow",
"async-trait",
@@ -3509,7 +3636,7 @@ dependencies = [
"bincode",
"bls12_381 0.6.0",
"bs58",
"criterion",
"criterion 0.3.5",
"digest 0.9.0",
"dkg",
"doc-comment",
@@ -4021,6 +4148,17 @@ dependencies = [
"plotters-backend",
]
[[package]]
name = "poly1305"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf"
dependencies = [
"cpufeatures",
"opaque-debug 0.3.0",
"universal-hash 0.5.0",
]
[[package]]
name = "polyval"
version = "0.5.3"
@@ -4030,7 +4168,7 @@ dependencies = [
"cfg-if 1.0.0",
"cpufeatures",
"opaque-debug 0.3.0",
"universal-hash",
"universal-hash 0.4.1",
]
[[package]]
@@ -6388,6 +6526,16 @@ dependencies = [
"subtle 2.4.1",
]
[[package]]
name = "universal-hash"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d3160b73c9a19f7e2939a2fdad446c57c1bbbbf4d919d3213ff1267a580d8b5"
dependencies = [
"crypto-common",
"subtle 2.4.1",
]
[[package]]
name = "untrusted"
version = "0.7.1"
@@ -6911,9 +7059,9 @@ checksum = "09041cd90cf85f7f8b2df60c646f853b7f535ce68f85244eb6731cf89fa498ec"
[[package]]
name = "zeroize"
version = "1.4.3"
version = "1.5.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d68d9dcec5f9b43a30d38c49f91dfedfaac384cb8f085faca366c26207dd1619"
checksum = "c394b5bd0c6f669e7275d9c20aa90ae064cb22e75a1cad54e1b34088034b149f"
dependencies = [
"zeroize_derive",
]
+2
View File
@@ -30,6 +30,7 @@ members = [
"common/coconut-interface",
"common/commands",
"common/config",
"common/build-information",
"common/cosmwasm-smart-contracts/coconut-bandwidth-contract",
"common/cosmwasm-smart-contracts/coconut-dkg",
"common/cosmwasm-smart-contracts/contracts-common",
@@ -76,6 +77,7 @@ members = [
"service-providers/network-statistics",
"nym-api",
"nym-api/nym-api-requests",
"nym-outfox",
"tools/nym-cli",
"tools/ts-rs-cli"
]
+1 -4
View File
@@ -28,7 +28,7 @@ clippy-coconut:
cargo clippy --workspace --features coconut -- -D warnings
clippy-wasm:
cargo clippy --workspace --features wasm -- -D warnings
cargo clippy --manifest-path clients/webassembly/Cargo.toml --target wasm32-unknown-unknown --workspace -- -D warnings
clippy-all-contracts:
@@ -49,9 +49,6 @@ test-main:
test-coconut:
cargo test --workspace --features coconut
test-wasm:
cargo test --workspace --features wasm
test-main-expensive:
cargo test --workspace -- --ignored
+2 -1
View File
@@ -1,8 +1,9 @@
[package]
name = "client-core"
version = "1.1.3"
version = "1.1.6"
authors = ["Dave Hrycyszyn <futurechimp@users.noreply.github.com>"]
edition = "2021"
rust-version = "1.66"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@@ -230,7 +230,7 @@ where
mixnet_message_sender: MixnetMessageSender,
ack_sender: AcknowledgementSender,
shutdown: TaskClient,
) -> Result<GatewayClient, ClientCoreError<B>> {
) -> Result<GatewayClient, ClientCoreError> {
let gateway_id = self.gateway_config.gateway_id.clone();
if gateway_id.is_empty() {
return Err(ClientCoreError::GatewayIdUnknown);
@@ -285,7 +285,7 @@ where
refresh_rate: Duration,
topology_accessor: TopologyAccessor,
shutdown: TaskClient,
) -> Result<(), ClientCoreError<B>> {
) -> Result<(), ClientCoreError> {
let topology_refresher_config = TopologyRefresherConfig::new(
nym_api_urls,
refresh_rate,
@@ -328,12 +328,17 @@ where
async fn setup_persistent_reply_storage(
backend: B,
shutdown: TaskClient,
) -> Result<CombinedReplyStorage, ClientCoreError<B>> {
) -> Result<CombinedReplyStorage, ClientCoreError>
where
<B as ReplyStorageBackend>::StorageError: Sync + Send,
{
let persistent_storage = PersistentReplyStorage::new(backend);
let mem_store = persistent_storage
.load_state_from_backend()
.await
.map_err(|err| ClientCoreError::SurbStorageError { source: err })?;
.map_err(|err| ClientCoreError::SurbStorageError {
source: Box::new(err),
})?;
let store_clone = mem_store.clone();
spawn_future(async move {
@@ -345,7 +350,10 @@ where
Ok(mem_store)
}
pub async fn start_base(mut self) -> Result<BaseClient, ClientCoreError<B>> {
pub async fn start_base(mut self) -> Result<BaseClient, ClientCoreError>
where
<B as ReplyStorageBackend>::StorageError: Sync + Send,
{
info!("Starting nym client");
// channels for inter-component communication
// TODO: make the channels be internally created by the relevant components
@@ -371,7 +379,7 @@ where
// channels responsible for dealing with reply-related fun
let (reply_controller_sender, reply_controller_receiver) =
reply_controller::new_control_channels();
reply_controller::requests::new_control_channels();
let self_address = self.as_mix_recipient();
@@ -437,7 +445,7 @@ where
input_receiver,
sphinx_message_sender.clone(),
reply_storage,
reply_controller_sender,
reply_controller_sender.clone(),
reply_controller_receiver,
shared_lane_queue_lengths.clone(),
client_connection_rx,
@@ -471,6 +479,7 @@ where
received_buffer_request_sender,
},
},
reply_controller_sender,
task_manager,
})
}
@@ -480,5 +489,8 @@ pub struct BaseClient {
pub client_input: ClientInputStatus,
pub client_output: ClientOutputStatus,
// it feels very wrong to put this channel here, but I can't think of any other way of passing it to the native client
pub reply_controller_sender: ReplyControllerSender,
pub task_manager: TaskManager,
}
@@ -8,11 +8,66 @@ use crate::config::DebugConfig;
use crate::error::ClientCoreError;
use log::{error, info};
use std::path::Path;
use std::{fs, io};
use time::OffsetDateTime;
async fn setup_fresh_backend<P: AsRef<Path>>(
db_path: P,
debug_config: &DebugConfig,
) -> Result<fs_backend::Backend, ClientCoreError> {
info!("creating fresh surb database");
let mut storage_backend = match fs_backend::Backend::init(db_path).await {
Ok(backend) => backend,
Err(err) => {
error!("failed to setup persistent storage backend for our reply needs: {err}");
return Err(ClientCoreError::SurbStorageError {
source: Box::new(err),
});
}
};
// while I kinda hate that we're going to be creating `CombinedReplyStorage` twice,
// it will only be happening on the very first run and in practice won't incur huge
// costs since the storage is going to be empty
let mem_store = CombinedReplyStorage::new(
debug_config.minimum_reply_surb_storage_threshold,
debug_config.maximum_reply_surb_storage_threshold,
);
storage_backend
.init_fresh(&mem_store)
.await
.map_err(|err| ClientCoreError::SurbStorageError {
source: Box::new(err),
})?;
Ok(storage_backend)
}
fn archive_corrupted_database<P: AsRef<Path>>(db_path: P) -> io::Result<()> {
let db_path = db_path.as_ref();
debug_assert!(db_path.exists());
let now = OffsetDateTime::now_utc().unix_timestamp();
let suffix = format!("_{now}.corrupted");
let new_extension =
if let Some(existing_extension) = db_path.extension().and_then(|ext| ext.to_str()) {
format!("{existing_extension}.{}", suffix)
} else {
suffix
};
let mut renamed = db_path.to_owned();
renamed.set_extension(new_extension);
fs::rename(db_path, renamed)
}
pub async fn setup_fs_reply_surb_backend<P: AsRef<Path>>(
db_path: P,
debug_config: &DebugConfig,
) -> Result<fs_backend::Backend, ClientCoreError<fs_backend::Backend>> {
) -> Result<fs_backend::Backend, ClientCoreError> {
// if the database file doesnt exist, initialise fresh storage, otherwise attempt to load the existing one
let db_path = db_path.as_ref();
if db_path.exists() {
@@ -20,32 +75,13 @@ pub async fn setup_fs_reply_surb_backend<P: AsRef<Path>>(
match fs_backend::Backend::try_load(db_path).await {
Ok(backend) => Ok(backend),
Err(err) => {
error!("failed to setup persistent storage backend for our reply needs: {err}");
Err(ClientCoreError::SurbStorageError { source: err })
error!("failed to setup persistent storage backend for our reply needs: {err}. We're going to create a fresh database instead. This behaviour might change in the future");
archive_corrupted_database(db_path)?;
setup_fresh_backend(db_path, debug_config).await
}
}
} else {
info!("creating fresh surb database");
let mut storage_backend = match fs_backend::Backend::init(db_path).await {
Ok(backend) => backend,
Err(err) => {
error!("failed to setup persistent storage backend for our reply needs: {err}");
return Err(ClientCoreError::SurbStorageError { source: err });
}
};
// while I kinda hate that we're going to be creating `CombinedReplyStorage` twice,
// it will only be happening on the very first run and in practice won't incur huge
// costs since the storage is going to be empty
let mem_store = CombinedReplyStorage::new(
debug_config.minimum_reply_surb_storage_threshold,
debug_config.maximum_reply_surb_storage_threshold,
);
storage_backend
.init_fresh(&mem_store)
.await
.map_err(|err| ClientCoreError::SurbStorageError { source: err })?;
Ok(storage_backend)
setup_fresh_backend(db_path, debug_config).await
}
}
@@ -0,0 +1,14 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
#[cfg(not(target_arch = "wasm32"))]
mod non_wasm;
#[cfg(target_arch = "wasm32")]
mod wasm;
#[cfg(not(target_arch = "wasm32"))]
pub use non_wasm::*;
#[cfg(target_arch = "wasm32")]
pub use wasm::*;
@@ -0,0 +1,13 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
pub use tokio::time::*;
pub type IntervalStream = tokio_stream::wrappers::IntervalStream;
pub(crate) fn get_time_now() -> Instant {
Instant::now()
}
pub(crate) fn new_interval_stream(polling_rate: Duration) -> IntervalStream {
tokio_stream::wrappers::IntervalStream::new(tokio::time::interval(polling_rate))
}
@@ -0,0 +1,16 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use std::time::Duration;
use wasm_timer;
pub use wasm_timer::*;
pub type IntervalStream = gloo_timers::future::IntervalStream;
pub(crate) fn get_time_now() -> Instant {
wasm_timer::Instant::now()
}
pub(crate) fn new_interval_stream(polling_rate: Duration) -> IntervalStream {
gloo_timers::future::IntervalStream::new(polling_rate.as_millis() as u32)
}
+2
View File
@@ -3,6 +3,7 @@
pub mod base_client;
pub mod cover_traffic_stream;
pub(crate) mod helpers;
pub mod inbound_messages;
pub mod key_manager;
pub mod mix_traffic;
@@ -10,3 +11,4 @@ pub mod real_messages_control;
pub mod received_buffer;
pub mod replies;
pub mod topology_control;
pub(crate) mod transmission_buffer;
@@ -149,7 +149,7 @@ where
break;
}
},
_ = shutdown.recv_with_delay() => {
_ = shutdown.recv() => {
log::trace!("RetransmissionRequestListener: Received shutdown");
}
}
@@ -20,6 +20,7 @@ use nymsphinx::params::{PacketSize, DEFAULT_NUM_MIX_HOPS};
use nymsphinx::preparer::{MessagePreparer, PreparedFragment};
use nymsphinx::Delay;
use rand::{CryptoRng, Rng};
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use thiserror::Error;
@@ -278,7 +279,7 @@ where
reply_surb: ReplySurb,
amount: u32,
) -> Result<(), SurbWrappedPreparationError> {
debug!("requesting {amount} reply SURBs from {from:?}");
debug!("requesting {amount} reply SURBs from {from}");
let surbs_request =
ReplyMessage::new_surb_request_message(self.config.sender_address, amount);
@@ -294,19 +295,11 @@ where
)))
}
// the only difference between this method and `try_send_reply_chunks` is that
// here we are not creating acks as acks are already in memory waiting to get cleared.
// we are only updating their existing delays
pub(crate) async fn try_send_retransmission_reply_chunks(
pub(crate) async fn send_retransmission_reply_chunks(
&mut self,
fragments: Vec<Fragment>,
reply_surbs: Vec<ReplySurb>,
prepared_fragments: Vec<PreparedFragment>,
lane: TransmissionLane,
) -> Result<(), SurbWrappedPreparationError> {
let prepared_fragments = self
.prepare_reply_chunks_for_sending(fragments.clone(), reply_surbs)
.await?;
) {
let mut real_messages = Vec::with_capacity(prepared_fragments.len());
for prepared in prepared_fragments {
@@ -315,33 +308,58 @@ where
}
self.forward_messages(real_messages, lane).await;
Ok(())
}
pub(crate) async fn try_send_reply_chunks(
pub(crate) async fn try_send_reply_chunks_on_lane(
&mut self,
target: AnonymousSenderTag,
fragments: Vec<Fragment>,
reply_surbs: Vec<ReplySurb>,
lane: TransmissionLane,
) -> Result<(), SurbWrappedPreparationError> {
// TODO: technically this is performing an unnecessary cloning, but in the grand scheme of things
// is it really that bad?
self.try_send_reply_chunks(
target,
fragments.into_iter().map(|f| (lane, f)).collect(),
reply_surbs,
)
.await
}
pub(crate) async fn try_send_reply_chunks(
&mut self,
target: AnonymousSenderTag,
fragments: Vec<(TransmissionLane, Fragment)>,
reply_surbs: Vec<ReplySurb>,
) -> Result<(), SurbWrappedPreparationError> {
let prepared_fragments = self
.prepare_reply_chunks_for_sending(fragments.clone(), reply_surbs)
.prepare_reply_chunks_for_sending(
fragments.iter().map(|(_, f)| f.clone()).collect(),
reply_surbs,
)
.await?;
let mut pending_acks = Vec::with_capacity(fragments.len());
let mut real_messages = Vec::with_capacity(fragments.len());
let mut to_forward: HashMap<_, Vec<_>> = HashMap::new();
for (raw, prepared) in fragments.into_iter().zip(prepared_fragments.into_iter()) {
let lane = raw.0;
let fragment = raw.1;
let real_message = RealMessage::new(prepared.mix_packet, prepared.fragment_identifier);
let delay = prepared.total_delay;
let pending_ack = PendingAcknowledgement::new_anonymous(raw, delay, target, false);
let pending_ack = PendingAcknowledgement::new_anonymous(fragment, delay, target, false);
real_messages.push(real_message);
let entry = to_forward.entry(lane).or_default();
entry.push(real_message);
pending_acks.push(pending_ack);
}
self.forward_messages(real_messages, lane).await;
for (lane, real_messages) in to_forward {
self.forward_messages(real_messages, lane).await;
}
self.insert_pending_acks(pending_acks);
Ok(())
}
@@ -467,7 +485,7 @@ where
Ok(prepared_fragment)
}
async fn prepare_reply_chunks_for_sending(
pub(crate) async fn prepare_reply_chunks_for_sending(
&mut self,
fragments: Vec<Fragment>,
reply_surbs: Vec<ReplySurb>,
@@ -1,9 +1,11 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use self::sending_delay_controller::SendingDelayController;
use crate::client::mix_traffic::BatchMixMessageSender;
use crate::client::real_messages_control::acknowledgement_control::SentPacketNotificationSender;
use crate::client::topology_control::TopologyAccessor;
use crate::client::transmission_buffer::TransmissionBuffer;
use client_connections::{
ConnectionCommand, ConnectionCommandReceiver, ConnectionId, LaneQueueLengths, TransmissionLane,
};
@@ -29,22 +31,7 @@ use tokio::time;
#[cfg(target_arch = "wasm32")]
use wasm_timer;
use self::{
sending_delay_controller::SendingDelayController, transmission_buffer::TransmissionBuffer,
};
mod sending_delay_controller;
mod transmission_buffer;
#[cfg(not(target_arch = "wasm32"))]
fn get_time_now() -> time::Instant {
time::Instant::now()
}
#[cfg(target_arch = "wasm32")]
fn get_time_now() -> wasm_timer::Instant {
wasm_timer::Instant::now()
}
/// Configurable parameters of the `OutQueueControl`
pub(crate) struct Config {
@@ -135,7 +122,7 @@ where
/// Buffer containing all incoming real messages keyed by transmission lane, that we will send
/// out to the mixnet.
transmission_buffer: TransmissionBuffer,
transmission_buffer: TransmissionBuffer<RealMessage>,
/// Incoming channel for being notified of closed connections, so that we can close lanes
/// corresponding to connections. To avoid sending traffic unnecessary
@@ -162,6 +149,10 @@ impl From<PreparedFragment> for RealMessage {
}
impl RealMessage {
pub(crate) fn packet_size(&self) -> usize {
self.mix_packet.sphinx_packet().len()
}
pub(crate) fn new(mix_packet: MixPacket, fragment_id: FragmentIdentifier) -> Self {
RealMessage {
mix_packet,
@@ -207,7 +198,7 @@ where
real_receiver,
rng,
topology_access,
transmission_buffer: Default::default(),
transmission_buffer: TransmissionBuffer::new(),
client_connection_rx,
lane_queue_lengths,
}
@@ -328,7 +319,9 @@ where
fn pop_next_message(&mut self) -> Option<RealMessage> {
// Pop the next message from the transmission buffer
let (lane, real_next) = self.transmission_buffer.pop_next_message_at_random()?;
let (lane, real_next) = self
.transmission_buffer
.pop_next_message_at_random(&mut self.rng)?;
// Update the published queue length
let lane_length = self.transmission_buffer.lane_length(&lane);
@@ -1,14 +1,9 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use super::get_time_now;
use crate::client::helpers::{get_time_now, Instant};
use std::time::Duration;
#[cfg(not(target_arch = "wasm32"))]
use tokio::time;
#[cfg(target_arch = "wasm32")]
use wasm_timer;
// The minimum time between increasing the average delay between packets. If we hit the ceiling in
// the available buffer space we want to take somewhat swift action, but we still need to give a
// short time to give the channel a chance reduce pressure.
@@ -39,19 +34,11 @@ pub(crate) struct SendingDelayController {
lower_bound: u32,
/// To make sure we don't change the multiplier to fast, we limit a change to some duration
#[cfg(not(target_arch = "wasm32"))]
time_when_changed: time::Instant,
#[cfg(target_arch = "wasm32")]
time_when_changed: wasm_timer::Instant,
time_when_changed: Instant,
/// If we have a long enough time without any backpressure detected we try reducing the sending
/// delay multiplier
#[cfg(not(target_arch = "wasm32"))]
time_when_backpressure_detected: time::Instant,
#[cfg(target_arch = "wasm32")]
time_when_backpressure_detected: wasm_timer::Instant,
time_when_backpressure_detected: Instant,
}
impl Default for SendingDelayController {
@@ -4,8 +4,8 @@
use crate::client::real_messages_control::acknowledgement_control::PendingAcknowledgement;
use crate::client::real_messages_control::message_handler::{MessageHandler, PreparationError};
use crate::client::replies::reply_storage::CombinedReplyStorage;
use client_connections::TransmissionLane;
use futures::channel::mpsc;
use client_connections::{ConnectionId, TransmissionLane};
use futures::channel::oneshot;
use futures::StreamExt;
use log::{debug, error, info, trace, warn};
use nymsphinx::addressing::clients::Recipient;
@@ -15,116 +15,16 @@ use nymsphinx::chunking::fragment::{Fragment, FragmentIdentifier};
use rand::{CryptoRng, Rng};
use std::cmp::{max, min};
use std::collections::btree_map::Entry;
use std::collections::{BTreeMap, HashMap, VecDeque};
use std::collections::{BTreeMap, HashMap};
use std::sync::{Arc, Weak};
use std::time::Duration;
use time::OffsetDateTime;
#[cfg(not(target_arch = "wasm32"))]
type IntervalStream = tokio_stream::wrappers::IntervalStream;
use crate::client::helpers::new_interval_stream;
use crate::client::transmission_buffer::TransmissionBuffer;
pub(crate) use requests::{ReplyControllerMessage, ReplyControllerReceiver, ReplyControllerSender};
#[cfg(target_arch = "wasm32")]
type IntervalStream = gloo_timers::future::IntervalStream;
pub(crate) fn new_control_channels() -> (ReplyControllerSender, ReplyControllerReceiver) {
let (tx, rx) = mpsc::unbounded();
(tx.into(), rx)
}
#[derive(Debug, Clone)]
pub(crate) struct ReplyControllerSender(mpsc::UnboundedSender<ReplyControllerMessage>);
impl From<mpsc::UnboundedSender<ReplyControllerMessage>> for ReplyControllerSender {
fn from(inner: mpsc::UnboundedSender<ReplyControllerMessage>) -> Self {
ReplyControllerSender(inner)
}
}
impl ReplyControllerSender {
pub(crate) fn send_retransmission_data(
&self,
recipient: AnonymousSenderTag,
timed_out_ack: Weak<PendingAcknowledgement>,
extra_surb_request: bool,
) {
self.0
.unbounded_send(ReplyControllerMessage::RetransmitReply {
recipient,
timed_out_ack,
extra_surb_request,
})
.expect("ReplyControllerReceiver has died!")
}
pub(crate) fn send_reply(
&self,
recipient: AnonymousSenderTag,
message: Vec<u8>,
lane: TransmissionLane,
) {
self.0
.unbounded_send(ReplyControllerMessage::SendReply {
recipient,
message,
lane,
})
.expect("ReplyControllerReceiver has died!")
}
pub(crate) fn send_additional_surbs(
&self,
sender_tag: AnonymousSenderTag,
reply_surbs: Vec<ReplySurb>,
from_surb_request: bool,
) {
self.0
.unbounded_send(ReplyControllerMessage::AdditionalSurbs {
sender_tag,
reply_surbs,
from_surb_request,
})
.expect("ReplyControllerReceiver has died!")
}
pub(crate) fn send_additional_surbs_request(&self, recipient: Recipient, amount: u32) {
self.0
.unbounded_send(ReplyControllerMessage::AdditionalSurbsRequest {
recipient: Box::new(recipient),
amount,
})
.expect("ReplyControllerReceiver has died!")
}
}
pub(crate) type ReplyControllerReceiver = mpsc::UnboundedReceiver<ReplyControllerMessage>;
#[derive(Debug)]
pub(crate) enum ReplyControllerMessage {
RetransmitReply {
recipient: AnonymousSenderTag,
timed_out_ack: Weak<PendingAcknowledgement>,
extra_surb_request: bool,
},
SendReply {
recipient: AnonymousSenderTag,
message: Vec<u8>,
lane: TransmissionLane,
},
AdditionalSurbs {
sender_tag: AnonymousSenderTag,
reply_surbs: Vec<ReplySurb>,
from_surb_request: bool,
},
// Should this also be handled in here? it's technically a completely different side of the pipe
// let's see how it works when combined, might split it before creating PR
AdditionalSurbsRequest {
recipient: Box<Recipient>,
amount: u32,
},
}
pub mod requests;
pub struct Config {
min_surb_request_size: u32,
@@ -172,7 +72,7 @@ pub struct ReplyController<R> {
// of surbs required to send the message through
// expected_reliability: f32,
request_receiver: ReplyControllerReceiver,
pending_replies: HashMap<AnonymousSenderTag, VecDeque<Fragment>>,
pending_replies: HashMap<AnonymousSenderTag, TransmissionBuffer<Fragment>>,
/// Retransmission packets that have already timed out and are waiting for additional reply SURBs
/// so that they could be sent back to the network. Once we receive more SURBs, we should send them ASAP.
@@ -204,17 +104,28 @@ where
}
}
/// Inserts the pending replies into the BACK of the queue fn insert_pending_replies<V: Into<VecDeque<Fragment>>>(
fn insert_pending_replies<V: Into<VecDeque<Fragment>>>(
fn insert_pending_replies<I: IntoIterator<Item = Fragment>>(
&mut self,
recipient: &AnonymousSenderTag,
fragments: V,
fragments: I,
lane: TransmissionLane,
) {
if let Some(existing) = self.pending_replies.get_mut(recipient) {
existing.append(&mut fragments.into())
} else {
self.pending_replies.insert(*recipient, fragments.into());
}
self.pending_replies
.entry(*recipient)
.or_insert_with(TransmissionBuffer::new)
.store(&lane, fragments)
}
fn re_insert_pending_replies(
&mut self,
recipient: &AnonymousSenderTag,
fragments: Vec<(TransmissionLane, Fragment)>,
) {
// the buffer should ALWAYS exist at this point, if it doesn't, it's a bug...
self.pending_replies
.entry(*recipient)
.or_insert_with(TransmissionBuffer::new)
.store_multiple(fragments)
}
fn re_insert_pending_retransmission(
@@ -244,7 +155,7 @@ where
let pending_queue_size = self
.pending_replies
.get(target)
.map(|pending_queue| pending_queue.len())
.map(|pending_queue| pending_queue.total_size())
.unwrap_or_default();
let retransmission_queue = self
@@ -299,43 +210,62 @@ where
}
trace!("handling reply to {:?}", recipient_tag);
let fragments = self.message_handler.split_reply_message(data);
let mut fragments = self.message_handler.split_reply_message(data);
let total_size = fragments.len();
trace!("This reply requires {:?} SURBs", total_size);
let required_surbs = fragments.len();
trace!("This reply requires {:?} SURBs", required_surbs);
// TODO: edge case:
// we're making a lot of requests and have to request a lot of surbs
// (but at some point we run out of surbs for surb requests)
let (surbs, _surbs_left) = self
let available_surbs = self
.full_reply_storage
.surbs_storage_ref()
.get_reply_surbs(&recipient_tag, required_surbs);
.available_surbs(&recipient_tag);
let min_surbs_threshold = self
.full_reply_storage
.surbs_storage_ref()
.min_surb_threshold();
if let Some(reply_surbs) = surbs {
if let Err(err) = self
.message_handler
.try_send_reply_chunks(recipient_tag, fragments, reply_surbs, lane)
.await
{
let err = err.return_unused_surbs(
self.full_reply_storage.surbs_storage_ref(),
&recipient_tag,
);
warn!("failed to send reply to {:?} - {err}", recipient_tag);
// TODO: should we buffer that data to try again?
}
let max_to_send = if available_surbs > min_surbs_threshold {
min(fragments.len(), available_surbs - min_surbs_threshold)
} else {
// we don't have enough surbs for this reply
self.insert_pending_replies(&recipient_tag, fragments);
0
};
if self.should_request_more_surbs(&recipient_tag) {
self.request_reply_surbs_for_queue_clearing(recipient_tag)
.await;
if max_to_send > 0 {
let (surbs, _surbs_left) = self
.full_reply_storage
.surbs_storage_ref()
.get_reply_surbs(&recipient_tag, max_to_send);
if let Some(reply_surbs) = surbs {
let to_send = fragments.drain(..max_to_send).collect::<Vec<_>>();
if let Err(err) = self
.message_handler
.try_send_reply_chunks_on_lane(
recipient_tag,
to_send.clone(),
reply_surbs,
lane,
)
.await
{
let err = err.return_unused_surbs(
self.full_reply_storage.surbs_storage_ref(),
&recipient_tag,
);
warn!("failed to send reply to {recipient_tag}: {err}");
self.insert_pending_replies(&recipient_tag, to_send, lane);
}
}
}
// if there's leftover data we didn't send because we didn't have enough (or any) surbs - buffer it
if !fragments.is_empty() {
self.insert_pending_replies(&recipient_tag, fragments, lane);
}
if self.should_request_more_surbs(&recipient_tag) {
self.request_reply_surbs_for_queue_clearing(recipient_tag)
.await;
}
}
async fn request_additional_reply_surbs(
@@ -398,35 +328,18 @@ where
};
let mut to_take = Vec::new();
let mut to_remove = Vec::new();
// TODO: once rust 1.66.0 is stabilised on 15.12.22, just change it to
// `.pop_front()` to directly take ownership
for (k, data) in pending.iter() {
let upgraded = match data.upgrade() {
Some(upgraded) => upgraded,
None => {
// we got the ack while the data was waiting in the queue
to_remove.push(*k);
continue;
while to_take.len() < max_to_clear {
if let Some((_, data)) = pending.pop_first() {
// no need to do anything if we failed to upgrade the reference,
// it means we got the ack while the data was waiting in the queue
if let Some(upgraded) = data.upgrade() {
to_take.push(upgraded)
}
};
to_take.push(upgraded);
// we have taken as many entries as we could have
if to_take.len() >= max_to_clear {
} else {
// our map is empty!
break;
}
// TODO: use if upgraded.is_extra_surb_request() to bypass the limit
}
for ack in &to_take {
pending.remove(&ack.inner_fragment_identifier());
}
for id in to_remove {
pending.remove(&id);
}
if to_take.is_empty() {
@@ -447,46 +360,47 @@ where
let to_send_vec = to_take.iter().map(|ack| ack.fragment_data()).collect();
if let Err(err) = self
let prepared_fragments = match self
.message_handler
.try_send_retransmission_reply_chunks(
to_send_vec,
surbs_for_reply,
TransmissionLane::Retransmission,
)
.prepare_reply_chunks_for_sending(to_send_vec, surbs_for_reply)
.await
{
let err = err.return_unused_surbs(self.full_reply_storage.surbs_storage_ref(), &target);
self.re_insert_pending_retransmission(&target, to_take);
Ok(prepared) => prepared,
Err(err) => {
let err =
err.return_unused_surbs(self.full_reply_storage.surbs_storage_ref(), &target);
self.re_insert_pending_retransmission(&target, to_take);
warn!(
"failed to clear pending retransmission queue for {:?} - {err}",
target
);
}
warn!(
"failed to clear pending retransmission queue for {:?} - {err}",
target
);
return;
}
};
// we can't fail at this point, so drop all references to acks so that timer updates wouldn't blow up
drop(to_take);
self.message_handler
.send_retransmission_reply_chunks(prepared_fragments, TransmissionLane::Retransmission)
.await;
}
fn pop_at_most_pending_replies(
&mut self,
from: &AnonymousSenderTag,
amount: usize,
) -> Option<VecDeque<Fragment>> {
) -> Option<Vec<(TransmissionLane, Fragment)>> {
// if possible, pop all pending replies, if not, pop only entries for which we'd have a reply surb
let total = self.pending_replies.get(from)?.len();
let total = self.pending_replies.get(from)?.total_size();
trace!("pending queue has {total} elements");
if total == 0 {
return None;
}
if total < amount {
self.pending_replies.remove(from)
} else {
Some(
self.pending_replies
.get_mut(from)?
.drain(..amount)
.collect(),
)
}
self.pending_replies
.get_mut(from)?
.pop_at_most_n_next_messages_at_random(amount)
}
async fn try_clear_pending_queue(&mut self, target: AnonymousSenderTag) {
@@ -510,9 +424,9 @@ where
// we're guaranteed to not get more entries than we have reply surbs for
if let Some(to_send) = self.pop_at_most_pending_replies(&target, max_to_clear) {
let to_send_vec = to_send.iter().cloned().collect::<Vec<_>>();
let to_send_clone = to_send.clone();
if to_send_vec.is_empty() {
if to_send_clone.is_empty() {
panic!(
"please let the devs know if you ever see this message (reply_controller.rs)"
);
@@ -521,27 +435,22 @@ where
let (surbs_for_reply, _) = self
.full_reply_storage
.surbs_storage_ref()
.get_reply_surbs(&target, to_send_vec.len());
.get_reply_surbs(&target, to_send_clone.len());
let Some(surbs_for_reply) = surbs_for_reply else {
error!("somehow different task has stolen our reply surbs! - this should have been impossible");
self.insert_pending_replies(&target, to_send);
self.re_insert_pending_replies(&target, to_send);
return;
};
if let Err(err) = self
.message_handler
.try_send_reply_chunks(
target,
to_send_vec,
surbs_for_reply,
TransmissionLane::General,
)
.try_send_reply_chunks(target, to_send_clone, surbs_for_reply)
.await
{
let err =
err.return_unused_surbs(self.full_reply_storage.surbs_storage_ref(), &target);
self.insert_pending_replies(&target, to_send);
self.re_insert_pending_replies(&target, to_send);
warn!("failed to clear pending queue for {:?} - {err}", target);
}
} else {
@@ -712,6 +621,30 @@ where
}
}
// to be honest this doesn't make a lot of sense in the context of `connection_id`,
// it should really be asked per tag
fn handle_lane_queue_length(
&self,
connection_id: ConnectionId,
response_channel: oneshot::Sender<usize>,
) {
// TODO: if we ever have duplicate ids for different senders, it means our rng is super weak
// thus I don't think we have to worry about it?
let lane = TransmissionLane::ConnectionId(connection_id);
for buf in self.pending_replies.values() {
if let Some(length) = buf.lane_length(&lane) {
if response_channel.send(length).is_err() {
error!("the requester for lane queue length has dropped the response channel!")
}
return;
}
}
// make sure that if we didn't find that lane, we reply with 0
if response_channel.send(0).is_err() {
error!("the requester for lane queue length has dropped the response channel!")
}
}
async fn handle_request(&mut self, request: ReplyControllerMessage) {
match request {
ReplyControllerMessage::RetransmitReply {
@@ -735,19 +668,26 @@ where
self.handle_received_surbs(sender_tag, reply_surbs, from_surb_request)
.await
}
ReplyControllerMessage::LaneQueueLength {
connection_id,
response_channel,
} => self.handle_lane_queue_length(connection_id, response_channel),
ReplyControllerMessage::AdditionalSurbsRequest { recipient, amount } => {
self.handle_surb_request(*recipient, amount).await
}
}
}
// TODO: modify this method to more accurately determine the amount of surbs it needs to request
// it should take into consideration the average latency, sending rate and queue size.
// it should request as many surbs as it takes to saturate its sending rate before next batch arrives
async fn request_reply_surbs_for_queue_clearing(&mut self, target: AnonymousSenderTag) {
trace!("requesting surbs for queues clearing");
let pending_queue_size = self
.pending_replies
.get(&target)
.map(|pending_queue| pending_queue.len())
.map(|pending_queue| pending_queue.total_size())
.unwrap_or_default();
let retransmission_queue = self
@@ -787,7 +727,7 @@ where
}
let Some(last_received) = self.full_reply_storage.surbs_storage_ref().surbs_last_received_at(pending_reply_target) else {
error!("we have {} pending replies for {pending_reply_target}, but we somehow never received any reply surbs from them!", vals.len());
error!("we have {} pending replies for {pending_reply_target}, but we somehow never received any reply surbs from them!", vals.total_size());
to_remove.push(*pending_reply_target);
continue;
};
@@ -883,23 +823,20 @@ where
}
}
fn create_interval_stream(polling_rate: Duration) -> IntervalStream {
#[cfg(not(target_arch = "wasm32"))]
return tokio_stream::wrappers::IntervalStream::new(tokio::time::interval(polling_rate));
#[cfg(target_arch = "wasm32")]
return gloo_timers::future::IntervalStream::new(polling_rate.as_millis() as u32);
}
// #[cfg(not(target_arch = "wasm32"))]
// async fn log_status(&self) {
// todo!()
// }
pub(crate) async fn run_with_shutdown(&mut self, mut shutdown: task::TaskClient) {
debug!("Started ReplyController with graceful shutdown support");
let polling_rate = Duration::from_secs(5);
let mut stale_inspection = Self::create_interval_stream(polling_rate);
let mut stale_inspection = new_interval_stream(polling_rate);
// this is in the order of hours/days so we don't have to poll it that often
let polling_rate = Duration::from_secs(self.config.max_reply_surb_age.as_secs() / 10);
let mut invalidation_inspection = Self::create_interval_stream(polling_rate);
let mut invalidation_inspection = new_interval_stream(polling_rate);
while !shutdown.is_shutdown() {
tokio::select! {
@@ -0,0 +1,136 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::client::real_messages_control::acknowledgement_control::PendingAcknowledgement;
use client_connections::{ConnectionId, TransmissionLane};
use futures::channel::{mpsc, oneshot};
use log::error;
use nymsphinx::addressing::clients::Recipient;
use nymsphinx::anonymous_replies::requests::AnonymousSenderTag;
use nymsphinx::anonymous_replies::ReplySurb;
use std::sync::Weak;
pub(crate) fn new_control_channels() -> (ReplyControllerSender, ReplyControllerReceiver) {
let (tx, rx) = mpsc::unbounded();
(tx.into(), rx)
}
#[derive(Debug, Clone)]
pub struct ReplyControllerSender(mpsc::UnboundedSender<ReplyControllerMessage>);
impl From<mpsc::UnboundedSender<ReplyControllerMessage>> for ReplyControllerSender {
fn from(inner: mpsc::UnboundedSender<ReplyControllerMessage>) -> Self {
ReplyControllerSender(inner)
}
}
impl ReplyControllerSender {
pub(crate) fn send_retransmission_data(
&self,
recipient: AnonymousSenderTag,
timed_out_ack: Weak<PendingAcknowledgement>,
extra_surb_request: bool,
) {
self.0
.unbounded_send(ReplyControllerMessage::RetransmitReply {
recipient,
timed_out_ack,
extra_surb_request,
})
.expect("ReplyControllerReceiver has died!")
}
pub(crate) fn send_reply(
&self,
recipient: AnonymousSenderTag,
message: Vec<u8>,
lane: TransmissionLane,
) {
self.0
.unbounded_send(ReplyControllerMessage::SendReply {
recipient,
message,
lane,
})
.expect("ReplyControllerReceiver has died!")
}
pub(crate) fn send_additional_surbs(
&self,
sender_tag: AnonymousSenderTag,
reply_surbs: Vec<ReplySurb>,
from_surb_request: bool,
) {
self.0
.unbounded_send(ReplyControllerMessage::AdditionalSurbs {
sender_tag,
reply_surbs,
from_surb_request,
})
.expect("ReplyControllerReceiver has died!")
}
pub(crate) fn send_additional_surbs_request(&self, recipient: Recipient, amount: u32) {
self.0
.unbounded_send(ReplyControllerMessage::AdditionalSurbsRequest {
recipient: Box::new(recipient),
amount,
})
.expect("ReplyControllerReceiver has died!")
}
pub async fn get_lane_queue_length(&self, connection_id: ConnectionId) -> usize {
let (response_tx, response_rx) = oneshot::channel();
self.0
.unbounded_send(ReplyControllerMessage::LaneQueueLength {
connection_id,
response_channel: response_tx,
})
.expect("ReplyControllerReceiver has died!");
match response_rx.await {
Ok(length) => length,
Err(_) => {
error!("The reply controller has dropped our response channel!");
// TODO: should we panic here instead? this message implies something weird and unrecoverable has happened
0
}
}
}
}
pub(crate) type ReplyControllerReceiver = mpsc::UnboundedReceiver<ReplyControllerMessage>;
#[derive(Debug)]
pub(crate) enum ReplyControllerMessage {
RetransmitReply {
recipient: AnonymousSenderTag,
timed_out_ack: Weak<PendingAcknowledgement>,
extra_surb_request: bool,
},
SendReply {
recipient: AnonymousSenderTag,
message: Vec<u8>,
lane: TransmissionLane,
},
AdditionalSurbs {
sender_tag: AnonymousSenderTag,
reply_surbs: Vec<ReplySurb>,
from_surb_request: bool,
},
// this one doesn't belong here either...
LaneQueueLength {
connection_id: ConnectionId,
response_channel: oneshot::Sender<usize>,
},
// Should this also be handled in here? it's technically a completely different side of the pipe
// let's see how it works when combined, might split it before creating PR
AdditionalSurbsRequest {
recipient: Box<Recipient>,
amount: u32,
},
}
@@ -1,7 +1,6 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
pub use self::error::StorageError;
use crate::client::replies::reply_storage::backend::fs_backend::manager::StorageManager;
use crate::client::replies::reply_storage::backend::fs_backend::models::{
ReplySurbStorageMetadata, StoredReplyKey, StoredReplySurb, StoredSenderTag, StoredSurbSender,
@@ -17,6 +16,8 @@ use std::fs;
use std::path::{Path, PathBuf};
use time::OffsetDateTime;
pub use self::error::StorageError;
mod error;
mod manager;
mod models;
@@ -66,6 +67,12 @@ impl Backend {
return Err(StorageError::IncompleteDataFlush);
}
let last_flush_timestamp = manager.get_previous_flush_timestamp().await?;
if last_flush_timestamp == 0 {
// either this client has been running since 1970 or the flush failed
return Err(StorageError::IncompleteDataFlush);
}
// the process has gone down without full graceful shutdown,
// meaning the database doesn't contain valid data anymore
// so we have to purge it
@@ -75,7 +82,12 @@ impl Backend {
manager.delete_all_reply_keys().await?;
}
let last_flush_timestamp = manager.get_previous_flush_timestamp().await?;
if let Err(err) = manager.get_reply_surb_storage_metadata().await {
// we can't recover here, we HAVE TO initialise fresh (because we don't know correct starting metadata)
error!("it seems the client has been shutdown gracefully - we're missing valid surb data dump. the existing database cannot be used");
return Err(err.into());
}
let last_flush = match OffsetDateTime::from_unix_timestamp(last_flush_timestamp) {
Ok(last_flush) => last_flush,
Err(err) => {
@@ -152,7 +152,7 @@ impl TopologyRefresherConfig {
}
pub struct TopologyRefresher {
validator_client: validator_client::client::ApiClient,
validator_client: validator_client::client::NymApiClient,
client_version: String,
nym_api_urls: Vec<Url>,
@@ -168,7 +168,9 @@ impl TopologyRefresher {
cfg.nym_api_urls.shuffle(&mut thread_rng());
TopologyRefresher {
validator_client: validator_client::client::ApiClient::new(cfg.nym_api_urls[0].clone()),
validator_client: validator_client::client::NymApiClient::new(
cfg.nym_api_urls[0].clone(),
),
client_version: cfg.client_version,
nym_api_urls: cfg.nym_api_urls,
topology_accessor,
@@ -1,38 +1,57 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::client::helpers::{get_time_now, Instant};
use crate::client::real_messages_control::real_traffic_stream::RealMessage;
use client_connections::TransmissionLane;
use nymsphinx::chunking::fragment::Fragment;
use rand::{seq::SliceRandom, Rng};
use std::{
collections::{HashMap, HashSet, VecDeque},
time::Duration,
};
#[cfg(not(target_arch = "wasm32"))]
use tokio::time;
#[cfg(target_arch = "wasm32")]
use wasm_timer;
use super::{get_time_now, RealMessage};
// The number of lanes included in the oldest set. Used when we need to prioritize traffic.
const OLDEST_LANE_SET_SIZE: usize = 4;
// As a way of prune connections we also check for timeouts.
const MSG_CONSIDERED_STALE_AFTER_SECS: u64 = 10 * 60;
#[derive(Default)]
pub(crate) struct TransmissionBuffer {
buffer: HashMap<TransmissionLane, LaneBufferEntry>,
pub(crate) trait SizedData {
fn data_size(&self) -> usize;
}
impl TransmissionBuffer {
impl SizedData for RealMessage {
fn data_size(&self) -> usize {
self.packet_size()
}
}
impl SizedData for Fragment {
fn data_size(&self) -> usize {
// note that raw `Fragment` is smaller than sphinx packet payload
// as it doesn't include surb-ack or the [shared] key materials
self.payload_size()
}
}
#[derive(Default)]
pub(crate) struct TransmissionBuffer<T> {
buffer: HashMap<TransmissionLane, LaneBufferEntry<T>>,
}
impl<T> TransmissionBuffer<T> {
pub(crate) fn new() -> Self {
TransmissionBuffer {
buffer: HashMap::new(),
}
}
#[allow(unused)]
pub(crate) fn is_empty(&self) -> bool {
self.buffer.is_empty()
}
pub(crate) fn remove(&mut self, lane: &TransmissionLane) -> Option<LaneBufferEntry> {
pub(crate) fn remove(&mut self, lane: &TransmissionLane) -> Option<LaneBufferEntry<T>> {
self.buffer.remove(lane)
}
@@ -57,20 +76,22 @@ impl TransmissionBuffer {
.collect()
}
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn total_size(&self) -> usize {
self.buffer.values().map(LaneBufferEntry::len).sum()
}
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn total_size_in_bytes(&self) -> usize {
pub(crate) fn total_size_in_bytes(&self) -> usize
where
T: SizedData,
{
self.buffer
.values()
.map(|lane_buffer_entry| {
lane_buffer_entry
.real_messages
.items
.iter()
.map(|real_message| real_message.mix_packet.sphinx_packet().len())
.map(|item| item.data_size())
.sum::<usize>()
})
.sum()
@@ -92,42 +113,51 @@ impl TransmissionBuffer {
.collect()
}
pub(crate) fn store(&mut self, lane: &TransmissionLane, real_messages: Vec<RealMessage>) {
pub(crate) fn store<I: IntoIterator<Item = T>>(&mut self, lane: &TransmissionLane, items: I) {
if let Some(lane_buffer_entry) = self.buffer.get_mut(lane) {
lane_buffer_entry.append(real_messages);
lane_buffer_entry.extend(items);
} else {
self.buffer
.insert(*lane, LaneBufferEntry::new(real_messages));
.insert(*lane, LaneBufferEntry::new(items.into_iter().collect()));
}
}
fn pick_random_lane(&self) -> Option<&TransmissionLane> {
let lanes: Vec<&TransmissionLane> = self.buffer.keys().collect();
lanes.choose(&mut rand::thread_rng()).copied()
pub(crate) fn store_multiple(&mut self, items: Vec<(TransmissionLane, T)>) {
for (lane, item) in items {
self.buffer
.entry(lane)
.or_insert_with(LaneBufferEntry::new_empty)
.push_item(item)
}
}
fn pick_random_small_lane(&self) -> Option<&TransmissionLane> {
fn pick_random_lane<R: Rng + ?Sized>(&self, rng: &mut R) -> Option<&TransmissionLane> {
let lanes: Vec<&TransmissionLane> = self.buffer.keys().collect();
lanes.choose(rng).copied()
}
fn pick_random_small_lane<R: Rng + ?Sized>(&self, rng: &mut R) -> Option<&TransmissionLane> {
let lanes: Vec<&TransmissionLane> = self
.buffer
.iter()
.filter(|(_, v)| v.is_small())
.map(|(k, _)| k)
.collect();
lanes.choose(&mut rand::thread_rng()).copied()
lanes.choose(rng).copied()
}
// 2/3 chance to pick from the old lanes
fn pick_random_old_lane(&self) -> Option<TransmissionLane> {
fn pick_random_old_lane<R: Rng + ?Sized>(&self, rng: &mut R) -> Option<TransmissionLane> {
let rand = &mut rand::thread_rng();
if rand.gen_ratio(2, 3) {
let lanes = self.get_oldest_set();
lanes.choose(rand).copied()
} else {
self.pick_random_lane().copied()
self.pick_random_lane(rng).copied()
}
}
fn pop_front_from_lane(&mut self, lane: &TransmissionLane) -> Option<RealMessage> {
fn pop_front_from_lane(&mut self, lane: &TransmissionLane) -> Option<T> {
let real_msgs_queued = self.buffer.get_mut(lane)?;
let real_next = real_msgs_queued.pop_front()?;
real_msgs_queued.messages_transmitted += 1;
@@ -137,19 +167,48 @@ impl TransmissionBuffer {
Some(real_next)
}
pub(crate) fn pop_next_message_at_random(&mut self) -> Option<(TransmissionLane, RealMessage)> {
pub(crate) fn pop_at_most_n_next_messages_at_random(
&mut self,
n: usize,
) -> Option<Vec<(TransmissionLane, T)>> {
// let start = Instant::now();
if self.buffer.is_empty() {
return None;
}
let rng = &mut rand::thread_rng();
let mut items = Vec::with_capacity(n);
while items.len() < n {
let Some(next) = self.pop_next_message_at_random(rng) else {
break
};
items.push(next)
}
// todo!("time time taken");
Some(items)
}
pub(crate) fn pop_next_message_at_random<R: Rng + ?Sized>(
&mut self,
// turns out the caller always have access to some rng, so no point in instantiating new one
rng: &mut R,
) -> Option<(TransmissionLane, T)> {
if self.buffer.is_empty() {
return None;
}
// Very basic heuristic where we prioritize according to small lanes first, the older lanes
// to try to finish lanes when possible, then the rest.
let lane = if let Some(small_lane) = self.pick_random_small_lane() {
let lane = if let Some(small_lane) = self.pick_random_small_lane(rng) {
*small_lane
} else if let Some(old_lane) = self.pick_random_old_lane() {
} else if let Some(old_lane) = self.pick_random_old_lane(rng) {
old_lane
} else {
*self.pick_random_lane()?
*self.pick_random_lane(rng)?
};
let msg = self.pop_front_from_lane(&lane)?;
@@ -171,35 +230,46 @@ impl TransmissionBuffer {
}
}
pub(crate) struct LaneBufferEntry {
pub real_messages: VecDeque<RealMessage>,
pub(crate) struct LaneBufferEntry<T> {
pub items: VecDeque<T>,
pub messages_transmitted: usize,
#[cfg(not(target_arch = "wasm32"))]
pub time_for_last_activity: time::Instant,
#[cfg(target_arch = "wasm32")]
pub time_for_last_activity: wasm_timer::Instant,
pub time_for_last_activity: Instant,
}
impl LaneBufferEntry {
fn new(real_messages: Vec<RealMessage>) -> Self {
impl<T> LaneBufferEntry<T> {
fn new_empty() -> Self {
LaneBufferEntry {
real_messages: real_messages.into(),
items: VecDeque::new(),
messages_transmitted: 0,
time_for_last_activity: get_time_now(),
}
}
fn append(&mut self, real_messages: Vec<RealMessage>) {
self.real_messages.append(&mut real_messages.into());
fn new(items: VecDeque<T>) -> Self {
LaneBufferEntry {
items,
messages_transmitted: 0,
time_for_last_activity: get_time_now(),
}
}
fn push_item(&mut self, item: T) {
self.items.push_back(item);
// I'm not updating time here on purpose. This method is called just after `new_empty`,
// where the time is already set. Furthermore, this method is called there multiple times at once
}
fn extend<I: IntoIterator<Item = T>>(&mut self, items: I) {
self.items.extend(items);
self.time_for_last_activity = get_time_now();
}
fn pop_front(&mut self) -> Option<RealMessage> {
self.real_messages.pop_front()
fn pop_front(&mut self) -> Option<T> {
self.items.pop_front()
}
fn is_small(&self) -> bool {
self.real_messages.len() < 100
self.items.len() < 100
}
fn is_stale(&self) -> bool {
@@ -208,10 +278,10 @@ impl LaneBufferEntry {
}
fn len(&self) -> usize {
self.real_messages.len()
self.items.len()
}
fn is_empty(&self) -> bool {
self.real_messages.is_empty()
self.items.is_empty()
}
}
+87 -22
View File
@@ -1,7 +1,8 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use config::{NymConfig, DB_FILE_NAME};
use config::defaults::NymNetworkDetails;
use config::{NymConfig, OptionalSet, DB_FILE_NAME};
use nymsphinx::params::PacketSize;
use serde::{Deserialize, Serialize};
use std::marker::PhantomData;
@@ -70,12 +71,15 @@ pub struct Config<T> {
#[serde(default)]
debug: DebugConfig,
}
impl<T> ClientCoreConfigTrait for Config<T> {
fn get_gateway_endpoint(&self) -> &GatewayEndpointConfig {
&self.client.gateway_endpoint
}
}
impl<T> OptionalSet for Config<T> where T: NymConfig {}
impl<T> Config<T> {
pub fn new<S: Into<String>>(id: S) -> Self
where
@@ -88,16 +92,28 @@ impl<T> Config<T> {
where
T: NymConfig,
{
let id = id.into();
self.client.id = id.into();
self.set_empty_fields_to_defaults();
self
}
pub fn set_empty_fields_to_defaults(&mut self) -> bool
where
T: NymConfig,
{
let id = &self.client.id;
let mut changes_made = false;
// identity key setting
if self.client.private_identity_key_file.as_os_str().is_empty() {
changes_made = true;
self.client.private_identity_key_file =
self::Client::<T>::default_private_identity_key_file(&id);
self::Client::<T>::default_private_identity_key_file(id);
}
if self.client.public_identity_key_file.as_os_str().is_empty() {
changes_made = true;
self.client.public_identity_key_file =
self::Client::<T>::default_public_identity_key_file(&id);
self::Client::<T>::default_public_identity_key_file(id);
}
// encryption key setting
@@ -107,8 +123,9 @@ impl<T> Config<T> {
.as_os_str()
.is_empty()
{
changes_made = true;
self.client.private_encryption_key_file =
self::Client::<T>::default_private_encryption_key_file(&id);
self::Client::<T>::default_private_encryption_key_file(id);
}
if self
.client
@@ -116,36 +133,40 @@ impl<T> Config<T> {
.as_os_str()
.is_empty()
{
changes_made = true;
self.client.public_encryption_key_file =
self::Client::<T>::default_public_encryption_key_file(&id);
self::Client::<T>::default_public_encryption_key_file(id);
}
// shared gateway key setting
if self.client.gateway_shared_key_file.as_os_str().is_empty() {
changes_made = true;
self.client.gateway_shared_key_file =
self::Client::<T>::default_gateway_shared_key_file(&id);
self::Client::<T>::default_gateway_shared_key_file(id);
}
// ack key setting
if self.client.ack_key_file.as_os_str().is_empty() {
self.client.ack_key_file = self::Client::<T>::default_ack_key_file(&id);
changes_made = true;
self.client.ack_key_file = self::Client::<T>::default_ack_key_file(id);
}
if self.client.reply_surb_database_path.as_os_str().is_empty() {
changes_made = true;
self.client.reply_surb_database_path =
self::Client::<T>::default_reply_surb_database_path(&id);
self::Client::<T>::default_reply_surb_database_path(id);
}
if self.client.database_path.as_os_str().is_empty() {
self.client.database_path = self::Client::<T>::default_database_path(&id);
changes_made = true;
self.client.database_path = self::Client::<T>::default_database_path(id);
}
self.client.id = id;
self
changes_made
}
pub fn with_disabled_credentials(&mut self, disabled_credentials_mode: bool) {
pub fn with_disabled_credentials(mut self, disabled_credentials_mode: bool) -> Self {
self.client.disabled_credentials_mode = disabled_credentials_mode;
self
}
pub fn with_gateway_endpoint(&mut self, gateway_endpoint: GatewayEndpointConfig) {
@@ -156,14 +177,31 @@ impl<T> Config<T> {
self.client.gateway_endpoint.gateway_id = id.into();
}
pub fn set_custom_validators(&mut self, validator_urls: Vec<Url>) {
self.client.validator_urls = validator_urls;
pub fn with_custom_nyxd(mut self, urls: Vec<Url>) -> Self {
self.client.nyxd_urls = urls;
self
}
pub fn set_custom_nyxd(&mut self, nyxd_urls: Vec<Url>) {
self.client.nyxd_urls = nyxd_urls;
}
pub fn with_custom_nym_apis(mut self, nym_api_urls: Vec<Url>) -> Self {
self.client.nym_api_urls = nym_api_urls;
self
}
pub fn set_custom_nym_apis(&mut self, nym_api_urls: Vec<Url>) {
self.client.nym_api_urls = nym_api_urls;
}
pub fn with_high_default_traffic_volume(mut self, enabled: bool) -> Self {
if enabled {
self.set_high_default_traffic_volume();
}
self
}
pub fn set_high_default_traffic_volume(&mut self) {
self.debug.average_packet_delay = Duration::from_millis(10);
// basically don't really send cover messages
@@ -172,6 +210,13 @@ impl<T> Config<T> {
self.debug.message_sending_average_delay = Duration::from_millis(4);
}
pub fn with_disabled_cover_traffic(mut self, disabled: bool) -> Self {
if disabled {
self.set_no_cover_traffic()
}
self
}
pub fn set_no_cover_traffic(&mut self) {
self.debug.disable_loop_cover_traffic_stream = true;
self.debug.disable_main_poisson_packet_distribution = true;
@@ -218,7 +263,7 @@ impl<T> Config<T> {
}
pub fn get_validator_endpoints(&self) -> Vec<Url> {
self.client.validator_urls.clone()
self.client.nyxd_urls.clone()
}
pub fn get_nym_api_endpoints(&self) -> Vec<Url> {
@@ -404,9 +449,9 @@ pub struct Client<T> {
#[serde(default)]
disabled_credentials_mode: bool,
/// Addresses to nymd validators via which the client can communicate with the chain.
#[serde(default)]
validator_urls: Vec<Url>,
/// Addresses to nyxd validators via which the client can communicate with the chain.
#[serde(alias = "validator_urls")]
nyxd_urls: Vec<Url>,
/// Addresses to APIs running on validator from which the client gets the view of the network.
#[serde(alias = "validator_api_urls")]
@@ -439,6 +484,10 @@ pub struct Client<T> {
database_path: PathBuf,
/// Path to the persistent store for received reply surbs, unused encryption keys and used sender tags.
// this was set to use #[serde(default)] for the purposes of compatibility for multi-surbs introduced in 1.1.4.
// if you're reading this message and we have already introduced some breaking changes, feel free
// to remove that attribute since at this point the client configs should have gotten regenerated
#[serde(default)]
reply_surb_database_path: PathBuf,
/// nym_home_directory specifies absolute path to the home nym Clients directory.
@@ -451,13 +500,29 @@ pub struct Client<T> {
impl<T: NymConfig> Default for Client<T> {
fn default() -> Self {
let network = NymNetworkDetails::new_mainnet();
let nyxd_urls = network
.endpoints
.iter()
.map(|validator| validator.nyxd_url())
.collect();
let nym_api_urls = network
.endpoints
.iter()
.filter_map(|validator| validator.api_url())
.collect::<Vec<_>>();
if nym_api_urls.is_empty() {
panic!("we do not have any default nym-api urls available!")
}
// there must be explicit checks for whether id is not empty later
Client {
version: env!("CARGO_PKG_VERSION").to_string(),
id: "".to_string(),
disabled_credentials_mode: true,
validator_urls: vec![],
nym_api_urls: vec![],
nyxd_urls,
nym_api_urls,
private_identity_key_file: Default::default(),
public_identity_key_file: Default::default(),
private_encryption_key_file: Default::default(),
+4 -3
View File
@@ -1,14 +1,13 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::client::replies::reply_storage::ReplyStorageBackend;
use crypto::asymmetric::identity::Ed25519RecoveryError;
use gateway_client::error::GatewayClientError;
use topology::NymTopologyError;
use validator_client::ValidatorClientError;
#[derive(thiserror::Error, Debug)]
pub enum ClientCoreError<B: ReplyStorageBackend> {
pub enum ClientCoreError {
#[error("I/O error: {0}")]
IoError(#[from] std::io::Error),
@@ -40,7 +39,9 @@ pub enum ClientCoreError<B: ReplyStorageBackend> {
InsufficientNetworkTopology(#[from] NymTopologyError),
#[error("experienced a failure with our reply surb persistent storage: {source}")]
SurbStorageError { source: B::StorageError },
SurbStorageError {
source: Box<dyn std::error::Error + Send + Sync>,
},
#[error("The gateway id is invalid - {0}")]
UnableToCreatePublicKeyFromGatewayId(Ed25519RecoveryError),
+7 -15
View File
@@ -1,7 +1,6 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::client::replies::reply_storage::ReplyStorageBackend;
use crate::{
client::key_manager::KeyManager,
config::{persistence::key_pathfinder::ClientKeyPathfinder, Config},
@@ -17,17 +16,14 @@ use tap::TapFallible;
use topology::{filter::VersionFilterable, gateway};
use url::Url;
pub(super) async fn query_gateway_details<B>(
pub(super) async fn query_gateway_details(
validator_servers: Vec<Url>,
chosen_gateway_id: Option<String>,
) -> Result<gateway::Node, ClientCoreError<B>>
where
B: ReplyStorageBackend,
{
) -> Result<gateway::Node, ClientCoreError> {
let nym_api = validator_servers
.choose(&mut thread_rng())
.ok_or(ClientCoreError::ListOfNymApisIsEmpty)?;
let validator_client = validator_client::client::ApiClient::new(nym_api.clone());
let validator_client = validator_client::client::NymApiClient::new(nym_api.clone());
log::trace!("Fetching list of gateways from: {}", nym_api);
let gateways = validator_client.get_cached_gateways().await?;
@@ -55,13 +51,10 @@ where
}
}
async fn register_with_gateway<B>(
async fn register_with_gateway(
gateway: &gateway::Node,
our_identity: Arc<identity::KeyPair>,
) -> Result<Arc<SharedKeys>, ClientCoreError<B>>
where
B: ReplyStorageBackend,
{
) -> Result<Arc<SharedKeys>, ClientCoreError> {
let timeout = Duration::from_millis(1500);
let mut gateway_client = GatewayClient::new_init(
gateway.clients_address(),
@@ -81,13 +74,12 @@ where
Ok(shared_keys)
}
pub(super) async fn register_with_gateway_and_store_keys<T, B>(
pub(super) async fn register_with_gateway_and_store_keys<T>(
gateway_details: gateway::Node,
config: &Config<T>,
) -> Result<(), ClientCoreError<B>>
) -> Result<(), ClientCoreError>
where
T: NymConfig,
B: ReplyStorageBackend,
{
let mut rng = OsRng;
let mut key_manager = KeyManager::new(&mut rng);
+15 -28
View File
@@ -12,7 +12,6 @@ use tap::TapFallible;
use config::NymConfig;
use crypto::asymmetric::{encryption, identity};
use crate::client::replies::reply_storage::ReplyStorageBackend;
use crate::{
config::{
persistence::key_pathfinder::ClientKeyPathfinder, ClientCoreConfigTrait, Config,
@@ -63,13 +62,13 @@ impl Display for InitResults {
/// Convenience function for setting up the gateway for a client. Depending on the arguments given
/// it will do the sensible thing.
pub async fn setup_gateway<B, C, T>(
pub async fn setup_gateway<C, T>(
register_gateway: bool,
// TODO: this should get refactored to instead take Option<identity::PublicKey>
user_chosen_gateway_id: Option<String>,
config: &Config<T>,
) -> Result<GatewayEndpointConfig, ClientCoreError<B>>
) -> Result<GatewayEndpointConfig, ClientCoreError>
where
B: ReplyStorageBackend,
C: NymConfig + ClientCoreConfigTrait,
T: NymConfig,
{
@@ -79,19 +78,18 @@ where
} else if let Some(user_chosen_gateway_id) = user_chosen_gateway_id {
config_gateway_with_existing_keys(user_chosen_gateway_id, config).await
} else {
reuse_existing_gateway_config::<B, C>(&id)
reuse_existing_gateway_config::<C>(&id)
}
}
/// Get the gateway details by querying the validator-api. Either pick one at random or use
/// the chosen one if it's among the available ones.
/// Saves keys to disk, specified by the paths in `config`.
pub async fn register_with_gateway<B, T>(
pub async fn register_with_gateway<T>(
user_chosen_gateway_id: Option<String>,
config: &Config<T>,
) -> Result<GatewayEndpointConfig, ClientCoreError<B>>
) -> Result<GatewayEndpointConfig, ClientCoreError>
where
B: ReplyStorageBackend,
T: NymConfig,
{
println!("Configuring gateway");
@@ -111,12 +109,11 @@ where
/// create any keys.
/// This assumes that the user knows what they are doing, and that the existing keys are valid for
/// the gateway being used
pub async fn config_gateway_with_existing_keys<B, T>(
pub async fn config_gateway_with_existing_keys<T>(
user_chosen_gateway_id: String,
config: &Config<T>,
) -> Result<GatewayEndpointConfig, ClientCoreError<B>>
) -> Result<GatewayEndpointConfig, ClientCoreError>
where
B: ReplyStorageBackend,
T: NymConfig,
{
println!("Using gateway provided by user, keeping existing keys");
@@ -127,11 +124,8 @@ where
}
/// Read and reuse the existing gateway configuration from a file that was generate earlier.
pub fn reuse_existing_gateway_config<B, T>(
id: &str,
) -> Result<GatewayEndpointConfig, ClientCoreError<B>>
pub fn reuse_existing_gateway_config<T>(id: &str) -> Result<GatewayEndpointConfig, ClientCoreError>
where
B: ReplyStorageBackend,
T: NymConfig + ClientCoreConfigTrait,
{
println!("Not registering gateway, will reuse existing config and keys");
@@ -150,19 +144,15 @@ where
}
/// Get the client address by loading the keys from stored files.
pub fn get_client_address_from_stored_keys<B, T>(
pub fn get_client_address_from_stored_keys<T>(
config: &Config<T>,
) -> Result<Recipient, ClientCoreError<B>>
) -> Result<Recipient, ClientCoreError>
where
T: config::NymConfig,
B: ReplyStorageBackend,
{
fn load_identity_keys<B>(
fn load_identity_keys(
pathfinder: &ClientKeyPathfinder,
) -> Result<identity::KeyPair, ClientCoreError<B>>
where
B: ReplyStorageBackend,
{
) -> Result<identity::KeyPair, ClientCoreError> {
let identity_keypair: identity::KeyPair =
pemstore::load_keypair(&pemstore::KeyPairPath::new(
pathfinder.private_identity_key().to_owned(),
@@ -172,12 +162,9 @@ where
Ok(identity_keypair)
}
fn load_sphinx_keys<B>(
fn load_sphinx_keys(
pathfinder: &ClientKeyPathfinder,
) -> Result<encryption::KeyPair, ClientCoreError<B>>
where
B: ReplyStorageBackend,
{
) -> Result<encryption::KeyPair, ClientCoreError> {
let sphinx_keypair: encryption::KeyPair =
pemstore::load_keypair(&pemstore::KeyPairPath::new(
pathfinder.private_encryption_key().to_owned(),
+2 -2
View File
@@ -8,7 +8,7 @@ edition = "2021"
[dependencies]
bip39 = "1.0.1"
cfg-if = "0.1"
clap = { version = "3.2", features = ["cargo", "derive"] }
clap = { version = "4.0", features = ["cargo", "derive"] }
rand = "0.7.3"
serde = { version = "1.0", features = ["derive"] }
thiserror = "1.0"
@@ -23,7 +23,7 @@ credential-storage = { path = "../../common/credential-storage" }
crypto = { path = "../../common/crypto", features = ["rand", "asymmetric", "symmetric", "aes", "hashing"] }
network-defaults = { path = "../../common/network-defaults" }
pemstore = { path = "../../common/pemstore" }
validator-client = { path = "../../common/client-libs/validator-client", features = ["nymd-client"] }
validator-client = { path = "../../common/client-libs/validator-client", features = ["nyxd-client"] }
[features]
coconut = ["credentials/coconut"]
+11 -11
View File
@@ -6,27 +6,27 @@ use bip39::Mnemonic;
use network_defaults::{NymNetworkDetails, VOUCHER_INFO};
use std::str::FromStr;
use url::Url;
use validator_client::nymd;
use validator_client::nymd::traits::CoconutBandwidthSigningClient;
use validator_client::nymd::{Coin, Fee, NymdClient, SigningNymdClient};
use validator_client::nyxd;
use validator_client::nyxd::traits::CoconutBandwidthSigningClient;
use validator_client::nyxd::{Coin, Fee, NyxdClient, SigningNyxdClient};
pub(crate) struct Client {
nymd_client: NymdClient<SigningNymdClient>,
nyxd_client: NyxdClient<SigningNyxdClient>,
mix_denom_base: String,
}
impl Client {
pub fn new(nymd_url: &str, mnemonic: &str) -> Self {
let nymd_url = Url::from_str(nymd_url).unwrap();
pub fn new(nyxd_url: &str, mnemonic: &str) -> Self {
let nyxd_url = Url::from_str(nyxd_url).unwrap();
let mnemonic = Mnemonic::from_str(mnemonic).unwrap();
let network_details = NymNetworkDetails::new_from_env();
let config = nymd::Config::try_from_nym_network_details(&network_details)
let config = nyxd::Config::try_from_nym_network_details(&network_details)
.expect("failed to construct valid validator client config with the provided network");
let nymd_client =
NymdClient::connect_with_mnemonic(config, nymd_url.as_ref(), mnemonic, None).unwrap();
let nyxd_client =
NyxdClient::connect_with_mnemonic(config, nyxd_url.as_ref(), mnemonic, None).unwrap();
Client {
nymd_client,
nyxd_client,
mix_denom_base: network_details.chain_details.mix_denom.base,
}
}
@@ -40,7 +40,7 @@ impl Client {
) -> Result<String> {
let amount = Coin::new(amount as u128, self.mix_denom_base.clone());
Ok(self
.nymd_client
.nyxd_client
.deposit(
amount,
String::from(VOUCHER_INFO),
+5 -5
View File
@@ -13,7 +13,7 @@ use credentials::coconut::bandwidth::{BandwidthVoucher, TOTAL_ATTRIBUTES};
use credentials::coconut::utils::obtain_aggregate_signature;
use crypto::asymmetric::{encryption, identity};
use network_defaults::{NymNetworkDetails, VOUCHER_INFO};
use validator_client::nymd::tx::Hash;
use validator_client::nyxd::tx::Hash;
use validator_client::{CoconutApiClient, Config};
use crate::client::Client;
@@ -38,9 +38,9 @@ pub(crate) struct Run {
#[clap(long)]
pub(crate) client_home_directory: std::path::PathBuf,
/// The nymd URL that should be used
/// The nyxd URL that should be used
#[clap(long)]
pub(crate) nymd_url: String,
pub(crate) nyxd_url: String,
/// A mnemonic for the account that buys the credential
#[clap(long)]
@@ -51,12 +51,12 @@ pub(crate) struct Run {
pub(crate) amount: u64,
}
pub(crate) async fn deposit(nymd_url: &str, mnemonic: &str, amount: u64) -> Result<State> {
pub(crate) async fn deposit(nyxd_url: &str, mnemonic: &str, amount: u64) -> Result<State> {
let mut rng = OsRng;
let signing_keypair = KeyPair::from(identity::KeyPair::new(&mut rng));
let encryption_keypair = KeyPair::from(encryption::KeyPair::new(&mut rng));
let client = Client::new(nymd_url, mnemonic);
let client = Client::new(nyxd_url, mnemonic);
let tx_hash = client
.deposit(
amount,
+3 -3
View File
@@ -7,15 +7,15 @@ use credential_storage::error::StorageError;
use credentials::error::Error as CredentialError;
use crypto::asymmetric::encryption::KeyRecoveryError;
use crypto::asymmetric::identity::Ed25519RecoveryError;
use validator_client::nymd::error::NymdError;
use validator_client::nyxd::error::NyxdError;
use validator_client::ValidatorClientError;
pub type Result<T> = std::result::Result<T, CredentialClientError>;
#[derive(Error, Debug)]
pub enum CredentialClientError {
#[error("Nymd error: {0}")]
Nymd(#[from] NymdError),
#[error("Nyxd error: {0}")]
Nyxd(#[from] NyxdError),
#[error("Validator client error: {0}")]
ValidatorClientError(#[from] ValidatorClientError),
+4 -4
View File
@@ -31,7 +31,7 @@ cfg_if::cfg_if! {
#[tokio::main]
async fn main() -> Result<()> {
let args = Cli::parse();
setup_env(args.config_env_file.clone());
setup_env(args.config_env_file.as_ref());
let bin_name = "nym-credential-client";
match args.command {
@@ -39,11 +39,11 @@ cfg_if::cfg_if! {
let db_path = r.client_home_directory.join(DATA_DIR).join(DB_FILE_NAME);
let shared_storage = credential_storage::initialise_storage(db_path).await;
let state = deposit(&r.nymd_url, &r.mnemonic, r.amount).await?;
let state = deposit(&r.nyxd_url, &r.mnemonic, r.amount).await?;
get_credential(&state, shared_storage).await?;
}
Command::Completions(c) => c.generate(&mut crate::Cli::into_app(), bin_name),
Command::GenerateFigSpec => fig_generate(&mut crate::Cli::into_app(), bin_name)
Command::Completions(c) => c.generate(&mut crate::Cli::command(), bin_name),
Command::GenerateFigSpec => fig_generate(&mut crate::Cli::command(), bin_name)
}
Ok(())
+5 -6
View File
@@ -1,6 +1,6 @@
[package]
name = "nym-client"
version = "1.1.3"
version = "1.1.6"
authors = ["Dave Hrycyszyn <futurechimp@users.noreply.github.com>", "Jędrzej Stuczyński <andrew@nymtech.net>"]
description = "Implementation of the Nym Client"
edition = "2021"
@@ -20,8 +20,9 @@ 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
url = "2.2"
clap = { version = "3.2", features = ["cargo", "derive"] }
clap = { version = "4.0", features = ["cargo", "derive"] }
dirs = "4.0"
lazy_static = "1.4.0"
log = "0.4" # self explanatory
pretty_env_logger = "0.4" # for formatting log messages
rand = { version = "0.7.3", features = ["wasm-bindgen"] } # rng-related traits + some rng implementation to use
@@ -33,6 +34,7 @@ tokio = { version = "1.21.2", features = ["rt-multi-thread", "net", "signal"] }
tokio-tungstenite = "0.14" # websocket
## internal
build-information = { path = "../../common/build-information" }
client-core = { path = "../client-core", features = ["fs-surb-storage"] }
client-connections = { path = "../../common/client-connections" }
coconut-interface = { path = "../../common/coconut-interface", optional = true }
@@ -49,7 +51,7 @@ nymsphinx = { path = "../../common/nymsphinx" }
pemstore = { path = "../../common/pemstore" }
task = { path = "../../common/task" }
topology = { path = "../../common/topology" }
validator-client = { path = "../../common/client-libs/validator-client", features = ["nymd-client"] }
validator-client = { path = "../../common/client-libs/validator-client", features = ["nyxd-client"] }
version-checker = { path = "../../common/version-checker" }
websocket-requests = { path = "websocket-requests" }
@@ -58,6 +60,3 @@ coconut = ["coconut-interface", "credentials", "credentials/coconut", "gateway-r
[dev-dependencies]
serde_json = "1.0" # for the "textsend" example
[build-dependencies]
vergen = { version = "5", default-features = false, features = ["build", "git", "rustc", "cargo"] }
-8
View File
@@ -1,8 +0,0 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use vergen::{vergen, Config};
fn main() {
vergen(Config::default()).expect("failed to extract build metadata")
}
File diff suppressed because it is too large Load Diff
+58 -2
View File
@@ -2,12 +2,15 @@
// SPDX-License-Identifier: Apache-2.0
use crate::client::config::template::config_template;
pub use client_core::config::Config as BaseConfig;
pub use client_core::config::MISSING_VALUE;
use client_core::config::{ClientCoreConfigTrait, Config as BaseConfig, DebugConfig};
use client_core::config::{ClientCoreConfigTrait, DebugConfig};
use config::defaults::DEFAULT_WEBSOCKET_LISTENING_PORT;
use config::NymConfig;
use config::{NymConfig, OptionalSet};
use serde::{Deserialize, Serialize};
use std::fmt::Debug;
use std::path::PathBuf;
use std::str::FromStr;
mod template;
@@ -92,6 +95,15 @@ impl Config {
self
}
pub fn with_disabled_socket(mut self, disabled: bool) -> Self {
if disabled {
self.socket.socket_type = SocketType::None;
} else {
self.socket.socket_type = SocketType::WebSocket;
}
self
}
pub fn with_port(mut self, port: u16) -> Self {
self.socket.listening_port = port;
self
@@ -121,6 +133,50 @@ impl Config {
pub fn get_listening_port(&self) -> u16 {
self.socket.listening_port
}
// poor man's 'builder' method
pub fn with_base<F, T>(mut self, f: F, val: T) -> Self
where
F: Fn(BaseConfig<Self>, T) -> BaseConfig<Self>,
{
self.base = f(self.base, val);
self
}
// helper methods to use `OptionalSet` trait. Those are defined due to very... ehm. 'specific' structure of this config
// (plz, lets refactor it)
pub fn with_optional_ext<F, T>(mut self, f: F, val: Option<T>) -> Self
where
F: Fn(BaseConfig<Self>, T) -> BaseConfig<Self>,
{
self.base = self.base.with_optional(f, val);
self
}
pub fn with_optional_env_ext<F, T>(mut self, f: F, val: Option<T>, env_var: &str) -> Self
where
F: Fn(BaseConfig<Self>, T) -> BaseConfig<Self>,
T: FromStr,
<T as FromStr>::Err: Debug,
{
self.base = self.base.with_optional_env(f, val, env_var);
self
}
pub fn with_optional_custom_env_ext<F, T, G>(
mut self,
f: F,
val: Option<T>,
env_var: &str,
parser: G,
) -> Self
where
F: Fn(BaseConfig<Self>, T) -> BaseConfig<Self>,
G: Fn(&str) -> T,
{
self.base = self.base.with_optional_custom_env(f, val, env_var, parser);
self
}
}
#[derive(Debug, Deserialize, PartialEq, Eq, Serialize)]
+3 -3
View File
@@ -23,9 +23,9 @@ id = '{{ client.id }}'
# to claim bandwidth without presenting bandwidth credentials.
disabled_credentials_mode = {{ client.disabled_credentials_mode }}
# Addresses to nymd validators via which the client can communicate with the chain.
validator_urls = [
{{#each client.validator_urls }}
# Addresses to nyxd validators via which the client can communicate with the chain.
nyxd_urls = [
{{#each client.nyxd_urls }}
'{{this}}',
{{/each}}
]
+10 -6
View File
@@ -13,6 +13,7 @@ use client_core::client::base_client::{
use client_core::client::inbound_messages::InputMessage;
use client_core::client::key_manager::KeyManager;
use client_core::client::received_buffer::{ReceivedBufferMessage, ReconstructedMessagesReceiver};
use client_core::client::replies::reply_controller::requests::ReplyControllerSender;
use client_core::config::persistence::key_pathfinder::ClientKeyPathfinder;
use futures::channel::mpsc;
use gateway_client::bandwidth::BandwidthController;
@@ -51,18 +52,18 @@ impl SocketClient {
let mut client_config =
validator_client::Config::try_from_nym_network_details(&details)
.expect("failed to construct validator client config");
let nymd_url = config
let nyxd_url = config
.get_base()
.get_validator_endpoints()
.pop()
.expect("No nymd validator endpoint provided");
.expect("No nyxd validator endpoint provided");
let api_url = config
.get_base()
.get_nym_api_endpoints()
.pop()
.expect("No validator api endpoint provided");
// overwrite env configuration with config URLs
client_config = client_config.with_urls(nymd_url, api_url);
client_config = client_config.with_urls(nyxd_url, api_url);
let client = validator_client::Client::new_query(client_config)
.expect("Could not construct query client");
let coconut_api_clients =
@@ -86,7 +87,8 @@ impl SocketClient {
config: &Config,
client_input: ClientInput,
client_output: ClientOutput,
self_address: Recipient,
self_address: &Recipient,
reply_controller_sender: ReplyControllerSender,
shutdown: task::TaskClient,
) {
info!("Starting websocket listener...");
@@ -101,12 +103,13 @@ impl SocketClient {
received_buffer_request_sender,
} = client_output;
let websocket_handler = websocket::Handler::new(
let websocket_handler = websocket::HandlerBuilder::new(
input_sender,
connection_command_sender,
received_buffer_request_sender,
self_address,
shared_lane_queue_lengths,
reply_controller_sender,
);
websocket::Listener::new(config.get_listening_port()).start(websocket_handler, shutdown);
@@ -153,7 +156,8 @@ impl SocketClient {
&self.config,
client_input,
client_output,
self_address,
&self_address,
started_client.reply_controller_sender,
started_client.task_manager.subscribe(),
);
+21 -17
View File
@@ -8,6 +8,7 @@ use crate::{
};
use clap::Args;
use config::NymConfig;
use crypto::asymmetric::identity;
use nymsphinx::addressing::clients::Recipient;
use serde::Serialize;
use std::fmt::Display;
@@ -21,24 +22,26 @@ pub(crate) struct Init {
/// Id of the gateway we are going to connect to.
#[clap(long)]
gateway: Option<String>,
gateway: Option<identity::PublicKey>,
/// 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 nymd validators
#[clap(long)]
nymd_validators: Option<String>,
/// Comma separated list of rest endpoints of the nyxd validators
#[cfg(feature = "coconut")]
#[clap(long, alias = "nymd_validators", value_delimiter = ',')]
nyxd_urls: Option<Vec<url::Url>>,
/// Comma separated list of rest endpoints of the API validators
#[clap(long)]
api_validators: Option<String>,
#[clap(long, alias = "api_validators", value_delimiter = ',')]
// the alias here is included for backwards compatibility (1.1.4 and before)
nym_apis: Option<Vec<url::Url>>,
/// Whether to not start the websocket
#[clap(long)]
disable_socket: bool,
disable_socket: Option<bool>,
/// Port for the socket (if applicable) to listen on in all subsequent runs
#[clap(short, long)]
@@ -46,18 +49,18 @@ pub(crate) struct Init {
/// Mostly debug-related option to increase default traffic rate so that you would not need to
/// modify config post init
#[clap(long, hidden = true)]
#[clap(long, hide = true)]
fastmode: bool,
/// Disable loop cover traffic and the Poisson rate limiter (for debugging only)
#[clap(long, hidden = true)]
#[clap(long, hide = true)]
no_cover: bool,
/// Set this client to work in a enabled credentials mode that would attempt to use gateway
/// with bandwidth credential requirement.
#[cfg(feature = "coconut")]
#[clap(long)]
enabled_credentials_mode: bool,
enabled_credentials_mode: Option<bool>,
/// Save a summary of the initialization to a json file
#[clap(long)]
@@ -67,13 +70,14 @@ pub(crate) struct Init {
impl From<Init> for OverrideConfig {
fn from(init_config: Init) -> Self {
OverrideConfig {
nymd_validators: init_config.nymd_validators,
api_validators: init_config.api_validators,
nym_apis: init_config.nym_apis,
disable_socket: init_config.disable_socket,
port: init_config.port,
fastmode: init_config.fastmode,
no_cover: init_config.no_cover,
#[cfg(feature = "coconut")]
nyxd_urls: init_config.nyxd_urls,
#[cfg(feature = "coconut")]
enabled_credentials_mode: init_config.enabled_credentials_mode,
}
@@ -127,16 +131,16 @@ pub(crate) async fn execute(args: &Init) -> Result<(), ClientError> {
let register_gateway = !already_init || user_wants_force_register;
// Attempt to use a user-provided gateway, if possible
let user_chosen_gateway_id = args.gateway.clone();
let user_chosen_gateway_id = args.gateway;
// Load and potentially override config
let mut config = override_config(Config::new(id), OverrideConfig::from(args.clone()));
// Setup gateway by either registering a new one, or creating a new config from the selected
// one but with keys kept, or reusing the gateway configuration.
let gateway = client_core::init::setup_gateway::<_, Config, _>(
let gateway = client_core::init::setup_gateway::<Config, _>(
register_gateway,
user_chosen_gateway_id,
user_chosen_gateway_id.map(|id| id.to_base58_string()),
config.get_base(),
)
.await
@@ -152,14 +156,14 @@ pub(crate) async fn execute(args: &Init) -> Result<(), ClientError> {
let address = client_core::init::get_client_address_from_stored_keys(config.get_base())?;
let init_results = InitResults::new(&config, &address);
println!("{}", init_results);
println!("{init_results}");
// Output summary to a json file, if specified
if args.output_json {
client_core::init::output_to_json(&init_results, "client_init_results.json");
}
println!("\nThe address of this client is: {}\n", address);
println!("\nThe address of this client is: {address}\n");
Ok(())
}
+42 -83
View File
@@ -1,54 +1,31 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// Copyright 2021-2023 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use std::error::Error;
use crate::client::config::{Config, SocketType};
use crate::client::config::{BaseConfig, Config};
use build_information::BinaryBuildInformation;
use clap::CommandFactory;
use clap::{Parser, Subcommand};
use completions::{fig_generate, ArgShell};
use config::OptionalSet;
use lazy_static::lazy_static;
use std::error::Error;
pub(crate) mod init;
pub(crate) mod run;
pub(crate) mod upgrade;
fn long_version() -> String {
format!(
r#"
{:<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"),
)
lazy_static! {
pub static ref PRETTY_BUILD_INFORMATION: String =
BinaryBuildInformation::new(env!("CARGO_PKG_VERSION")).pretty_print();
}
fn long_version_static() -> &'static str {
Box::leak(long_version().into_boxed_str())
// Helper for passing LONG_VERSION to clap
fn pretty_build_info_static() -> &'static str {
&PRETTY_BUILD_INFORMATION
}
#[derive(Parser)]
#[clap(author = "Nymtech", version, long_version = long_version_static(), about)]
#[clap(author = "Nymtech", version, long_version = pretty_build_info_static(), about)]
pub(crate) struct Cli {
/// Path pointing to an env file that configures the client.
#[clap(short, long)]
@@ -76,15 +53,16 @@ pub(crate) enum Commands {
// Configuration that can be overridden.
pub(crate) struct OverrideConfig {
nymd_validators: Option<String>,
api_validators: Option<String>,
disable_socket: bool,
nym_apis: Option<Vec<url::Url>>,
disable_socket: Option<bool>,
port: Option<u16>,
fastmode: bool,
no_cover: bool,
#[cfg(feature = "coconut")]
enabled_credentials_mode: bool,
nyxd_urls: Option<Vec<url::Url>>,
#[cfg(feature = "coconut")]
enabled_credentials_mode: Option<bool>,
}
pub(crate) async fn execute(args: &Cli) -> Result<(), Box<dyn Error + Send + Sync>> {
@@ -94,57 +72,38 @@ pub(crate) async fn execute(args: &Cli) -> Result<(), Box<dyn Error + Send + Syn
Commands::Init(m) => init::execute(m).await?,
Commands::Run(m) => run::execute(m).await?,
Commands::Upgrade(m) => upgrade::execute(m),
Commands::Completions(s) => s.generate(&mut Cli::into_app(), bin_name),
Commands::GenerateFigSpec => fig_generate(&mut Cli::into_app(), bin_name),
Commands::Completions(s) => s.generate(&mut Cli::command(), bin_name),
Commands::GenerateFigSpec => fig_generate(&mut Cli::command(), bin_name),
}
Ok(())
}
pub(crate) fn override_config(mut config: Config, args: OverrideConfig) -> Config {
if let Some(raw_validators) = args.nymd_validators {
config
.get_base_mut()
.set_custom_validators(config::parse_validators(&raw_validators));
} else if std::env::var(network_defaults::var_names::CONFIGURED).is_ok() {
let raw_validators = std::env::var(network_defaults::var_names::NYMD_VALIDATOR)
.expect("nymd validator not set");
config
.get_base_mut()
.set_custom_validators(config::parse_validators(&raw_validators));
}
if let Some(raw_validators) = args.api_validators {
config
.get_base_mut()
.set_custom_nym_apis(config::parse_validators(&raw_validators));
} else if std::env::var(network_defaults::var_names::CONFIGURED).is_ok() {
let raw_validators = std::env::var(network_defaults::var_names::API_VALIDATOR)
.expect("api validator not set");
config
.get_base_mut()
.set_custom_nym_apis(config::parse_validators(&raw_validators));
}
if args.disable_socket {
config = config.with_socket(SocketType::None);
}
if let Some(port) = args.port {
config = config.with_port(port);
}
config = config
.with_optional(Config::with_disabled_socket, args.disable_socket)
.with_base(BaseConfig::with_high_default_traffic_volume, args.fastmode)
.with_base(BaseConfig::with_disabled_cover_traffic, args.no_cover)
.with_optional(Config::with_port, args.port)
.with_optional_custom_env_ext(
BaseConfig::with_custom_nym_apis,
args.nym_apis,
network_defaults::var_names::NYM_API,
config::parse_urls,
);
#[cfg(feature = "coconut")]
{
if args.enabled_credentials_mode {
config.get_base_mut().with_disabled_credentials(false)
}
}
if args.fastmode {
config.get_base_mut().set_high_default_traffic_volume();
}
if args.no_cover {
config.get_base_mut().set_no_cover_traffic();
config = config
.with_optional_custom_env_ext(
BaseConfig::with_custom_nyxd,
args.nyxd_urls,
network_defaults::var_names::NYXD,
config::parse_urls,
)
.with_optional_ext(
BaseConfig::with_disabled_credentials,
args.enabled_credentials_mode.map(|b| !b),
);
}
config
+22 -13
View File
@@ -1,4 +1,4 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// Copyright 2021-2023 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use std::error::Error;
@@ -11,6 +11,7 @@ use crate::{
use clap::Args;
use config::NymConfig;
use crypto::asymmetric::identity;
use log::*;
use version_checker::is_minor_version_compatible;
@@ -20,22 +21,24 @@ pub(crate) struct Run {
#[clap(long)]
id: String,
/// Comma separated list of rest endpoints of the nymd validators
#[clap(long)]
nymd_validators: Option<String>,
/// Comma separated list of rest endpoints of the nyxd validators
#[cfg(feature = "coconut")]
#[clap(long, alias = "nymd_validators", value_delimiter = ',')]
nyxd_urls: Option<Vec<url::Url>>,
/// Comma separated list of rest endpoints of the API validators
#[clap(long)]
api_validators: Option<String>,
#[clap(long, alias = "api_validators", value_delimiter = ',')]
// the alias here is included for backwards compatibility (1.1.4 and before)
nym_apis: Option<Vec<url::Url>>,
/// 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>,
gateway: Option<identity::PublicKey>,
/// Whether to not start the websocket
#[clap(long)]
disable_socket: bool,
disable_socket: Option<bool>,
/// Port for the socket to listen on
#[clap(short, long)]
@@ -43,29 +46,31 @@ pub(crate) struct Run {
/// Mostly debug-related option to increase default traffic rate so that you would not need to
/// modify config post init
#[clap(long, hidden = true)]
#[clap(long, hide = true)]
fastmode: bool,
/// Disable loop cover traffic and the Poisson rate limiter (for debugging only)
#[clap(long, hidden = true)]
#[clap(long, hide = true)]
no_cover: bool,
/// Set this client to work in a enabled credentials mode that would attempt to use gateway
/// with bandwidth credential requirement.
#[cfg(feature = "coconut")]
#[clap(long)]
enabled_credentials_mode: bool,
enabled_credentials_mode: Option<bool>,
}
impl From<Run> for OverrideConfig {
fn from(run_config: Run) -> Self {
OverrideConfig {
nymd_validators: run_config.nymd_validators,
api_validators: run_config.api_validators,
nym_apis: run_config.nym_apis,
disable_socket: run_config.disable_socket,
port: run_config.port,
fastmode: run_config.fastmode,
no_cover: run_config.no_cover,
#[cfg(feature = "coconut")]
nyxd_urls: run_config.nyxd_urls,
#[cfg(feature = "coconut")]
enabled_credentials_mode: run_config.enabled_credentials_mode,
}
@@ -105,6 +110,10 @@ pub(crate) async fn execute(args: &Run) -> Result<(), Box<dyn Error + Send + Syn
let override_config_fields = OverrideConfig::from(args.clone());
config = override_config(config, override_config_fields);
if config.get_base_mut().set_empty_fields_to_defaults() {
warn!("some of the core config options were left unset. the default values are going to get used instead.");
}
if !version_check(&config) {
error!("failed the local version check");
return Err(Box::new(ClientError::FailedLocalVersionCheck));
+1 -2
View File
@@ -1,4 +1,3 @@
use client_core::client::replies::reply_storage::fs_backend;
use client_core::error::ClientCoreError;
#[derive(thiserror::Error, Debug)]
@@ -7,7 +6,7 @@ pub enum ClientError {
IoError(#[from] std::io::Error),
#[error("client-core error: {0}")]
ClientCoreError(#[from] ClientCoreError<fs_backend::Backend>),
ClientCoreError(#[from] ClientCoreError),
#[error("Failed to load config for: {0}")]
FailedToLoadConfig(String),
+1 -1
View File
@@ -18,7 +18,7 @@ async fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
println!("{}", banner());
let args = commands::Cli::parse();
setup_env(args.config_env_file.clone());
setup_env(args.config_env_file.as_ref());
commands::execute(&args).await
}
+93 -100
View File
@@ -2,8 +2,9 @@
// SPDX-License-Identifier: Apache-2.0
use client_connections::{
ConnectionCommand, ConnectionCommandSender, LaneQueueLengths, TransmissionLane,
ConnectionCommand, ConnectionCommandSender, ConnectionId, LaneQueueLengths, TransmissionLane,
};
use client_core::client::replies::reply_controller::requests::ReplyControllerSender;
use client_core::client::{
inbound_messages::{InputMessage, InputMessageSender},
received_buffer::{
@@ -16,7 +17,9 @@ use log::*;
use nymsphinx::addressing::clients::Recipient;
use nymsphinx::anonymous_replies::requests::AnonymousSenderTag;
use nymsphinx::receiver::ReconstructedMessage;
use std::time::Duration;
use tokio::net::TcpStream;
use tokio::time::Instant;
use tokio_tungstenite::{
accept_async,
tungstenite::{protocol::Message as WsMessage, Error as WsError},
@@ -35,53 +38,36 @@ impl Default for ReceivedResponseType {
}
}
pub(crate) struct Handler {
pub(crate) struct HandlerBuilder {
msg_input: InputMessageSender,
client_connection_tx: ConnectionCommandSender,
buffer_requester: ReceivedBufferRequestSender,
self_full_address: Recipient,
socket: Option<WebSocketStream<TcpStream>>,
received_response_type: ReceivedResponseType,
lane_queue_lengths: LaneQueueLengths,
is_active: bool,
reply_controller_sender: ReplyControllerSender,
}
impl Drop for Handler {
fn drop(&mut self) {
if self.is_active
&& self
.buffer_requester
.unbounded_send(ReceivedBufferMessage::ReceiverDisconnect)
.is_err()
{
error!("we failed to disconnect the receiver from the buffer! presumably the shutdown procedure has been initiated!")
}
}
}
impl Handler {
impl HandlerBuilder {
pub(crate) fn new(
msg_input: InputMessageSender,
client_connection_tx: ConnectionCommandSender,
buffer_requester: ReceivedBufferRequestSender,
self_full_address: Recipient,
self_full_address: &Recipient,
lane_queue_lengths: LaneQueueLengths,
reply_controller_sender: ReplyControllerSender,
) -> Self {
Handler {
Self {
msg_input,
client_connection_tx,
buffer_requester,
self_full_address,
socket: None,
received_response_type: Default::default(),
self_full_address: *self_full_address,
lane_queue_lengths,
is_active: false,
reply_controller_sender,
}
}
// Used to use handler on a new connection, which initially is `None`
// TODO: make sure we only ever have one active handler
pub fn create_active_handler(&self) -> Self {
pub fn create_active_handler(&self) -> Handler {
Handler {
msg_input: self.msg_input.clone(),
client_connection_tx: self.client_connection_tx.clone(),
@@ -90,9 +76,76 @@ impl Handler {
socket: None,
received_response_type: Default::default(),
lane_queue_lengths: self.lane_queue_lengths.clone(),
is_active: true,
reply_controller_sender: self.reply_controller_sender.clone(),
}
}
}
pub(crate) struct Handler {
msg_input: InputMessageSender,
client_connection_tx: ConnectionCommandSender,
buffer_requester: ReceivedBufferRequestSender,
self_full_address: Recipient,
socket: Option<WebSocketStream<TcpStream>>,
received_response_type: ReceivedResponseType,
lane_queue_lengths: LaneQueueLengths,
reply_controller_sender: ReplyControllerSender,
}
impl Drop for Handler {
fn drop(&mut self) {
if self
.buffer_requester
.unbounded_send(ReceivedBufferMessage::ReceiverDisconnect)
.is_err()
{
error!("we failed to disconnect the receiver from the buffer! presumably the shutdown procedure has been initiated!")
}
}
}
impl Handler {
async fn get_lane_queue_length(&self, connection_id: ConnectionId) -> Option<ServerResponse> {
let req_start = Instant::now();
// get the base queue length
// Note that this does _NOT_ take into account the packets that have been received but not
// yet reach `OutQueueControl`, so it might be a tad low.
let conn_lane = TransmissionLane::ConnectionId(connection_id);
let Ok(base_length) = self
.lane_queue_lengths
.lock()
.map(|guard| guard.get(&conn_lane).unwrap_or_default()) else {
// I'd argue we should panic here as this error it not recoverable
error!("The lane queue length lock is poisoned!!");
return None
};
// get the number of pending replies waiting for reply surbs
let reply_queue_length = self
.reply_controller_sender
.get_lane_queue_length(connection_id)
.await;
let queue_length = base_length + reply_queue_length;
let time_taken = req_start.elapsed();
let msg =
format!("it took {time_taken:?} to get lane length for connection {connection_id}. The length is: {queue_length} = {base_length} (already queued up) + {reply_queue_length} (waiting for reply SURBs)");
if time_taken > Duration::from_millis(1) {
info!("{msg}");
} else if time_taken > Duration::from_millis(10) {
warn!("{msg}");
} else if time_taken > Duration::from_millis(50) {
error!("{msg}");
}
Some(ServerResponse::LaneQueueLength {
lane: connection_id,
queue_length,
})
}
async fn handle_send(
&mut self,
@@ -118,27 +171,11 @@ impl Handler {
.expect("InputMessageReceiver has stopped receiving!");
// Only reply back with a `LaneQueueLength` if the sender providided a connection id
let connection_id = match lane {
TransmissionLane::General
| TransmissionLane::ReplySurbRequest
| TransmissionLane::Retransmission
| TransmissionLane::AdditionalReplySurbs => return None,
TransmissionLane::ConnectionId(id) => id,
let TransmissionLane::ConnectionId(connection_id) = lane else {
return None
};
// on receiving a send, we reply back the current lane queue length for that connection id.
// Note that this does _NOT_ take into account the packets that have been received but not
// yet reach `OutQueueControl`, so it might be a tad low.
if let Ok(lane_queue_lengths) = self.lane_queue_lengths.lock() {
let queue_length = lane_queue_lengths.get(&lane).unwrap_or(0);
return Some(ServerResponse::LaneQueueLength {
lane: connection_id,
queue_length,
});
}
log::warn!("Failed to get the lane queue length lock, not responding back with the current queue length");
None
self.get_lane_queue_length(connection_id).await
}
async fn handle_send_anonymous(
@@ -165,27 +202,11 @@ impl Handler {
.expect("InputMessageReceiver has stopped receiving!");
// Only reply back with a `LaneQueueLength` if the sender providided a connection id
let connection_id = match lane {
TransmissionLane::General
| TransmissionLane::ReplySurbRequest
| TransmissionLane::Retransmission
| TransmissionLane::AdditionalReplySurbs => return None,
TransmissionLane::ConnectionId(id) => id,
let TransmissionLane::ConnectionId(connection_id) = lane else {
return None
};
// on receiving a send, we reply back the current lane queue length for that connection id.
// Note that this does _NOT_ take into account the packets that have been received but not
// yet reach `OutQueueControl`, so it might be a tad low.
if let Ok(lane_queue_lengths) = self.lane_queue_lengths.lock() {
let queue_length = lane_queue_lengths.get(&lane).unwrap_or(0);
return Some(ServerResponse::LaneQueueLength {
lane: connection_id,
queue_length,
});
}
log::warn!("Failed to get the lane queue length lock, not responding back with the current queue length");
None
self.get_lane_queue_length(connection_id).await
}
async fn handle_reply(
@@ -208,27 +229,11 @@ impl Handler {
.expect("InputMessageReceiver has stopped receiving!");
// Only reply back with a `LaneQueueLength` if the sender providided a connection id
let connection_id = match lane {
TransmissionLane::General
| TransmissionLane::ReplySurbRequest
| TransmissionLane::Retransmission
| TransmissionLane::AdditionalReplySurbs => return None,
TransmissionLane::ConnectionId(id) => id,
let TransmissionLane::ConnectionId(connection_id) = lane else {
return None
};
// on receiving a send, we reply back the current lane queue length for that connection id.
// Note that this does _NOT_ take into account the packets that have been received but not
// yet reach `OutQueueControl`, so it might be a tad low.
if let Ok(lane_queue_lengths) = self.lane_queue_lengths.lock() {
let queue_length = lane_queue_lengths.get(&lane).unwrap_or(0);
return Some(ServerResponse::LaneQueueLength {
lane: connection_id,
queue_length,
});
}
log::warn!("Failed to get the lane queue length lock, not responding back with the current queue length");
None
self.get_lane_queue_length(connection_id).await
}
fn handle_self_address(&self) -> ServerResponse {
@@ -242,20 +247,8 @@ impl Handler {
None
}
fn handle_get_lane_queue_length(&self, connection_id: u64) -> Option<ServerResponse> {
let Ok(lane_queue_lengths) = self.lane_queue_lengths.lock() else {
log::warn!(
"Failed to get the lane queue length lock, not responding back with the current queue length"
);
return None;
};
let lane = TransmissionLane::ConnectionId(connection_id);
let queue_length = lane_queue_lengths.get(&lane).unwrap_or(0);
Some(ServerResponse::LaneQueueLength {
lane: connection_id,
queue_length,
})
async fn handle_get_lane_queue_length(&self, connection_id: u64) -> Option<ServerResponse> {
self.get_lane_queue_length(connection_id).await
}
async fn handle_request(&mut self, request: ClientRequest) -> Option<ServerResponse> {
@@ -284,7 +277,7 @@ impl Handler {
ClientRequest::SelfAddress => Some(self.handle_self_address()),
ClientRequest::ClosedConnection(id) => self.handle_closed_connection(id),
ClientRequest::GetLaneQueueLength(id) => self.handle_get_lane_queue_length(id),
ClientRequest::GetLaneQueueLength(id) => self.handle_get_lane_queue_length(id).await,
}
}
+7 -3
View File
@@ -1,7 +1,7 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use super::handler::Handler;
use super::handler::HandlerBuilder;
use log::*;
use std::{net::SocketAddr, process, sync::Arc};
use tokio::io::AsyncWriteExt;
@@ -32,7 +32,7 @@ impl Listener {
}
}
pub(crate) async fn run(&mut self, handler: Handler, mut task_client: task::TaskClient) {
pub(crate) async fn run(&mut self, handler: HandlerBuilder, mut task_client: task::TaskClient) {
let tcp_listener = match tokio::net::TcpListener::bind(self.address).await {
Ok(listener) => listener,
Err(err) => {
@@ -100,7 +100,11 @@ impl Listener {
log::debug!("Websocket listener: Exiting");
}
pub(crate) fn start(mut self, handler: Handler, shutdown: task::TaskClient) -> JoinHandle<()> {
pub(crate) fn start(
mut self,
handler: HandlerBuilder,
shutdown: task::TaskClient,
) -> JoinHandle<()> {
info!("Running websocket on {:?}", self.address.to_string());
tokio::spawn(async move { self.run(handler, shutdown).await })
+1 -1
View File
@@ -1,7 +1,7 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
pub(crate) use handler::Handler;
pub(crate) use handler::HandlerBuilder;
pub(crate) use listener::Listener;
pub(crate) mod handler;
+5 -6
View File
@@ -1,6 +1,6 @@
[package]
name = "nym-socks5-client"
version = "1.1.3"
version = "1.1.5"
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"
@@ -11,9 +11,10 @@ name = "nym_socks5"
path = "src/lib.rs"
[dependencies]
clap = { version = "3.2", features = ["cargo", "derive"] }
clap = { version = "4.0", features = ["cargo", "derive"] }
dirs = "4.0"
futures = "0.3"
lazy_static = "1.4.0"
log = "0.4"
pin-project = "1.0"
pretty_env_logger = "0.4"
@@ -26,6 +27,7 @@ tokio = { version = "1.21.2", features = ["rt-multi-thread", "net", "signal"] }
url = "2.2"
# internal
build-information = { path = "../../common/build-information" }
client-core = { path = "../client-core", features = ["fs-surb-storage"] }
client-connections = { path = "../../common/client-connections" }
coconut-interface = { path = "../../common/coconut-interface", optional = true }
@@ -45,12 +47,9 @@ proxy-helpers = { path = "../../common/socks5/proxy-helpers" }
socks5-requests = { path = "../../common/socks5/requests" }
task = { path = "../../common/task" }
topology = { path = "../../common/topology" }
validator-client = { path = "../../common/client-libs/validator-client", features = ["nymd-client"] }
validator-client = { path = "../../common/client-libs/validator-client", features = ["nyxd-client"] }
version-checker = { path = "../../common/version-checker" }
[features]
coconut = ["coconut-interface", "credentials", "gateway-requests/coconut", "gateway-client/coconut", "credentials/coconut", "client-core/coconut"]
eth = []
[build-dependencies]
vergen = { version = "5", default-features = false, features = ["build", "git", "rustc", "cargo"] }
-8
View File
@@ -1,8 +0,0 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use vergen::{vergen, Config};
fn main() {
vergen(Config::default()).expect("failed to extract build metadata")
}
+50 -2
View File
@@ -2,13 +2,16 @@
// SPDX-License-Identifier: Apache-2.0
use crate::client::config::template::config_template;
pub use client_core::config::Config as BaseConfig;
pub use client_core::config::MISSING_VALUE;
use client_core::config::{ClientCoreConfigTrait, Config as BaseConfig, DebugConfig};
use client_core::config::{ClientCoreConfigTrait, DebugConfig};
use config::defaults::DEFAULT_SOCKS5_LISTENING_PORT;
use config::NymConfig;
use config::{NymConfig, OptionalSet};
use nymsphinx::addressing::clients::Recipient;
use serde::{Deserialize, Serialize};
use std::fmt::Debug;
use std::path::PathBuf;
use std::str::FromStr;
mod template;
@@ -127,6 +130,50 @@ impl Config {
pub fn get_per_request_surbs(&self) -> u32 {
self.socks5_debug.per_request_surbs
}
// poor man's 'builder' method
pub fn with_base<F, T>(mut self, f: F, val: T) -> Self
where
F: Fn(BaseConfig<Self>, T) -> BaseConfig<Self>,
{
self.base = f(self.base, val);
self
}
// helper methods to use `OptionalSet` trait. Those are defined due to very... ehm. 'specific' structure of this config
// (plz, lets refactor it)
pub fn with_optional_ext<F, T>(mut self, f: F, val: Option<T>) -> Self
where
F: Fn(BaseConfig<Self>, T) -> BaseConfig<Self>,
{
self.base = self.base.with_optional(f, val);
self
}
pub fn with_optional_env_ext<F, T>(mut self, f: F, val: Option<T>, env_var: &str) -> Self
where
F: Fn(BaseConfig<Self>, T) -> BaseConfig<Self>,
T: FromStr,
<T as FromStr>::Err: Debug,
{
self.base = self.base.with_optional_env(f, val, env_var);
self
}
pub fn with_optional_custom_env_ext<F, T, G>(
mut self,
f: F,
val: Option<T>,
env_var: &str,
parser: G,
) -> Self
where
F: Fn(BaseConfig<Self>, T) -> BaseConfig<Self>,
G: Fn(&str) -> T,
{
self.base = self.base.with_optional_custom_env(f, val, env_var, parser);
self
}
}
#[derive(Debug, Deserialize, PartialEq, Eq, Serialize)]
@@ -143,6 +190,7 @@ pub struct Socks5 {
/// slower and consume nearly double the bandwidth as it will require sending reply SURBs.
///
/// Note that some service providers might not support this.
#[serde(default)]
send_anonymously: bool,
}
+3 -3
View File
@@ -23,9 +23,9 @@ id = '{{ client.id }}'
# to claim bandwidth without presenting bandwidth credentials.
disabled_credentials_mode = {{ client.disabled_credentials_mode }}
# Addresses to nymd validators via which the client can communicate with the chain.
validator_urls = [
{{#each client.validator_urls }}
# Addresses to nyxd validators via which the client can communicate with the chain.
nyxd_urls = [
{{#each client.nyxd_urls }}
'{{this}}',
{{/each}}
]
+4 -4
View File
@@ -60,18 +60,18 @@ impl NymClient {
let mut client_config =
validator_client::Config::try_from_nym_network_details(&details)
.expect("failed to construct validator client config");
let nymd_url = config
let nyxd_url = config
.get_base()
.get_validator_endpoints()
.pop()
.expect("No nymd validator endpoint provided");
.expect("No nyxd validator endpoint provided");
let api_url = config
.get_base()
.get_nym_api_endpoints()
.pop()
.expect("No validator api endpoint provided");
// overwrite env configuration with config URLs
client_config = client_config.with_urls(nymd_url, api_url);
client_config = client_config.with_urls(nyxd_url, api_url);
let client = validator_client::Client::new_query(client_config)
.expect("Could not construct query client");
let coconut_api_clients =
@@ -166,7 +166,7 @@ impl NymClient {
let mut shutdown = self.start().await?;
// Listen to status messages from task, that we forward back to the caller
shutdown.start_status_listener(sender);
shutdown.start_status_listener(sender).await;
let res = tokio::select! {
biased;
+25 -19
View File
@@ -8,6 +8,7 @@ use crate::{
};
use clap::Args;
use config::NymConfig;
use crypto::asymmetric::identity;
use nymsphinx::addressing::clients::Recipient;
use serde::Serialize;
use std::fmt::Display;
@@ -21,32 +22,35 @@ pub(crate) struct Init {
/// Address of the socks5 provider to send messages to.
#[clap(long)]
provider: String,
provider: Recipient,
/// Specifies whether this client is going to use an anonymous sender tag for communication with the service provider.
/// While this is going to hide its actual address information, it will make the actual communication
/// slower and consume nearly double the bandwidth as it will require sending reply SURBs.
///
/// Note that some service providers might not support this.
#[clap(long)]
use_anonymous_sender_tag: bool,
// the alias here is included for backwards compatibility (1.1.4 and before)
#[clap(long, alias = "use_anonymous_sender_tag")]
use_reply_surbs: Option<bool>,
/// Id of the gateway we are going to connect to.
#[clap(long)]
gateway: Option<String>,
gateway: Option<identity::PublicKey>,
/// 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 nymd validators
#[clap(long)]
nymd_validators: Option<String>,
/// Comma separated list of rest endpoints of the nyxd validators
#[cfg(feature = "coconut")]
#[clap(long, alias = "nymd_validators", value_delimiter = ',')]
nyxd_urls: Option<Vec<url::Url>>,
/// Comma separated list of rest endpoints of the API validators
#[clap(long)]
api_validators: Option<String>,
#[clap(long, alias = "api_validators", value_delimiter = ',')]
// the alias here is included for backwards compatibility (1.1.4 and before)
nym_apis: Option<Vec<url::Url>>,
/// Port for the socket to listen on in all subsequent runs
#[clap(short, long)]
@@ -54,18 +58,18 @@ pub(crate) struct Init {
/// Mostly debug-related option to increase default traffic rate so that you would not need to
/// modify config post init
#[clap(long, hidden = true)]
#[clap(long, hide = true)]
fastmode: bool,
/// Disable loop cover traffic and the Poisson rate limiter (for debugging only)
#[clap(long, hidden = true)]
#[clap(long, hide = true)]
no_cover: bool,
/// Set this client to work in a enabled credentials mode that would attempt to use gateway
/// with bandwidth credential requirement.
#[cfg(feature = "coconut")]
#[clap(long)]
enabled_credentials_mode: bool,
enabled_credentials_mode: Option<bool>,
/// Save a summary of the initialization to a json file
#[clap(long)]
@@ -75,12 +79,14 @@ pub(crate) struct Init {
impl From<Init> for OverrideConfig {
fn from(init_config: Init) -> Self {
OverrideConfig {
nymd_validators: init_config.nymd_validators,
api_validators: init_config.api_validators,
nym_apis: init_config.nym_apis,
port: init_config.port,
use_anonymous_sender_tag: init_config.use_anonymous_sender_tag,
use_anonymous_replies: init_config.use_reply_surbs,
fastmode: init_config.fastmode,
no_cover: init_config.no_cover,
#[cfg(feature = "coconut")]
nyxd_urls: init_config.nyxd_urls,
#[cfg(feature = "coconut")]
enabled_credentials_mode: init_config.enabled_credentials_mode,
}
@@ -135,19 +141,19 @@ pub(crate) async fn execute(args: &Init) -> Result<(), Socks5ClientError> {
let register_gateway = !already_init || user_wants_force_register;
// Attempt to use a user-provided gateway, if possible
let user_chosen_gateway_id = args.gateway.clone();
let user_chosen_gateway_id = args.gateway;
// Load and potentially override config
let mut config = override_config(
Config::new(id, provider_address),
Config::new(id, &provider_address.to_string()),
OverrideConfig::from(args.clone()),
);
// Setup gateway by either registering a new one, or creating a new config from the selected
// one but with keys kept, or reusing the gateway configuration.
let gateway = client_core::init::setup_gateway::<_, Config, _>(
let gateway = client_core::init::setup_gateway::<Config, _>(
register_gateway,
user_chosen_gateway_id,
user_chosen_gateway_id.map(|id| id.to_base58_string()),
config.get_base(),
)
.await
+42 -80
View File
@@ -1,55 +1,31 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// Copyright 2021-2023 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use std::error::Error;
use crate::client::config::Config;
use crate::client::config::{BaseConfig, Config};
use build_information::BinaryBuildInformation;
use clap::CommandFactory;
use clap::{Parser, Subcommand};
use completions::{fig_generate, ArgShell};
use config::parse_validators;
use config::OptionalSet;
use lazy_static::lazy_static;
use std::error::Error;
pub mod init;
pub(crate) mod run;
pub(crate) mod upgrade;
fn long_version() -> String {
format!(
r#"
{:<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"),
)
lazy_static! {
pub static ref PRETTY_BUILD_INFORMATION: String =
BinaryBuildInformation::new(env!("CARGO_PKG_VERSION")).pretty_print();
}
fn long_version_static() -> &'static str {
Box::leak(long_version().into_boxed_str())
// Helper for passing LONG_VERSION to clap
fn pretty_build_info_static() -> &'static str {
&PRETTY_BUILD_INFORMATION
}
#[derive(Parser)]
#[clap(author = "Nymtech", version, long_version = long_version_static(), about)]
#[clap(author = "Nymtech", version, long_version = pretty_build_info_static(), about)]
pub(crate) struct Cli {
/// Path pointing to an env file that configures the client.
#[clap(short, long)]
@@ -79,15 +55,16 @@ pub(crate) enum Commands {
// Configuration that can be overridden.
pub(crate) struct OverrideConfig {
nymd_validators: Option<String>,
api_validators: Option<String>,
nym_apis: Option<Vec<url::Url>>,
port: Option<u16>,
use_anonymous_sender_tag: bool,
use_anonymous_replies: Option<bool>,
fastmode: bool,
no_cover: bool,
#[cfg(feature = "coconut")]
enabled_credentials_mode: bool,
nyxd_urls: Option<Vec<url::Url>>,
#[cfg(feature = "coconut")]
enabled_credentials_mode: Option<bool>,
}
pub(crate) async fn execute(args: &Cli) -> Result<(), Box<dyn Error + Send + Sync>> {
@@ -97,53 +74,38 @@ pub(crate) async fn execute(args: &Cli) -> Result<(), Box<dyn Error + Send + Syn
Commands::Init(m) => init::execute(m).await?,
Commands::Run(m) => run::execute(m).await?,
Commands::Upgrade(m) => upgrade::execute(m),
Commands::Completions(s) => s.generate(&mut Cli::into_app(), bin_name),
Commands::GenerateFigSpec => fig_generate(&mut Cli::into_app(), bin_name),
Commands::Completions(s) => s.generate(&mut Cli::command(), bin_name),
Commands::GenerateFigSpec => fig_generate(&mut Cli::command(), bin_name),
}
Ok(())
}
pub(crate) fn override_config(mut config: Config, args: OverrideConfig) -> Config {
if let Some(raw_validators) = args.nymd_validators {
config
.get_base_mut()
.set_custom_validators(parse_validators(&raw_validators));
} else if let Ok(raw_validators) = std::env::var(network_defaults::var_names::NYMD_VALIDATOR) {
config
.get_base_mut()
.set_custom_validators(parse_validators(&raw_validators));
}
if let Some(raw_validators) = args.api_validators {
config
.get_base_mut()
.set_custom_nym_apis(parse_validators(&raw_validators));
} else if let Ok(raw_validators) = std::env::var(network_defaults::var_names::API_VALIDATOR) {
config
.get_base_mut()
.set_custom_nym_apis(parse_validators(&raw_validators));
}
if args.use_anonymous_sender_tag {
config = config.with_anonymous_replies(true)
}
if let Some(port) = args.port {
config = config.with_port(port);
}
config = config
.with_base(BaseConfig::with_high_default_traffic_volume, args.fastmode)
.with_base(BaseConfig::with_disabled_cover_traffic, args.no_cover)
.with_optional(Config::with_anonymous_replies, args.use_anonymous_replies)
.with_optional(Config::with_port, args.port)
.with_optional_custom_env_ext(
BaseConfig::with_custom_nym_apis,
args.nym_apis,
network_defaults::var_names::NYM_API,
config::parse_urls,
);
#[cfg(feature = "coconut")]
{
if args.enabled_credentials_mode {
config.get_base_mut().with_disabled_credentials(false)
}
}
if args.fastmode {
config.get_base_mut().set_high_default_traffic_volume();
}
if args.no_cover {
config.get_base_mut().set_no_cover_traffic();
config = config
.with_optional_custom_env_ext(
BaseConfig::with_custom_nyxd,
args.nyxd_urls,
network_defaults::var_names::NYXD,
config::parse_urls,
)
.with_optional_ext(
BaseConfig::with_disabled_credentials,
args.enabled_credentials_mode.map(|b| !b),
);
}
config
+25 -15
View File
@@ -9,7 +9,9 @@ use crate::{
use clap::Args;
use config::NymConfig;
use crypto::asymmetric::identity;
use log::*;
use nymsphinx::addressing::clients::Recipient;
use version_checker::is_minor_version_compatible;
#[derive(Args, Clone)]
@@ -27,25 +29,27 @@ pub(crate) struct Run {
/// slower and consume nearly double the bandwidth as it will require sending reply SURBs.
///
/// Note that some service providers might not support this.
#[clap(long)]
use_anonymous_sender_tag: bool,
// the alias here is included for backwards compatibility (1.1.4 and before)
#[clap(long, alias = "use_anonymous_sender_tag")]
use_anonymous_replies: Option<bool>,
/// Address of the socks5 provider to send messages to.
#[clap(long)]
provider: Option<String>,
provider: Option<Recipient>,
/// 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>,
gateway: Option<identity::PublicKey>,
/// Comma separated list of rest endpoints of the nymd validators
#[clap(long)]
nymd_validators: Option<String>,
/// Comma separated list of rest endpoints of the nyxd validators
#[cfg(feature = "coconut")]
#[clap(long, alias = "nymd_validators", value_delimiter = ',')]
nyxd_urls: Option<Vec<url::Url>>,
/// Comma separated list of rest endpoints of the Nym APIs
#[clap(long)]
nym_apis: Option<String>,
#[clap(long, value_delimiter = ',')]
nym_apis: Option<Vec<url::Url>>,
/// Port for the socket to listen on
#[clap(short, long)]
@@ -53,29 +57,31 @@ pub(crate) struct Run {
/// Mostly debug-related option to increase default traffic rate so that you would not need to
/// modify config post init
#[clap(long, hidden = true)]
#[clap(long, hide = true)]
fastmode: bool,
/// Disable loop cover traffic and the Poisson rate limiter (for debugging only)
#[clap(long, hidden = true)]
#[clap(long, hide = true)]
no_cover: bool,
/// Set this client to work in a enabled credentials mode that would attempt to use gateway
/// with bandwidth credential requirement.
#[cfg(feature = "coconut")]
#[clap(long)]
enabled_credentials_mode: bool,
enabled_credentials_mode: Option<bool>,
}
impl From<Run> for OverrideConfig {
fn from(run_config: Run) -> Self {
OverrideConfig {
nymd_validators: run_config.nymd_validators,
api_validators: run_config.nym_apis,
nym_apis: run_config.nym_apis,
port: run_config.port,
use_anonymous_sender_tag: run_config.use_anonymous_sender_tag,
use_anonymous_replies: run_config.use_anonymous_replies,
fastmode: run_config.fastmode,
no_cover: run_config.no_cover,
#[cfg(feature = "coconut")]
nyxd_urls: run_config.nyxd_urls,
#[cfg(feature = "coconut")]
enabled_credentials_mode: run_config.enabled_credentials_mode,
}
@@ -120,6 +126,10 @@ pub(crate) async fn execute(args: &Run) -> Result<(), Box<dyn std::error::Error
let override_config_fields = OverrideConfig::from(args.clone());
config = override_config(config, override_config_fields);
if config.get_base_mut().set_empty_fields_to_defaults() {
warn!("some of the core config options were left unset. the default values are going to get used instead.");
}
if !version_check(&config) {
error!("failed the local version check");
return Err(Box::new(Socks5ClientError::FailedLocalVersionCheck));
+8 -2
View File
@@ -1,6 +1,6 @@
use crate::socks::types::SocksProxyError;
use client_core::client::replies::reply_storage::fs_backend;
use client_core::error::ClientCoreError;
use socks5_requests::ConnectionId;
#[derive(thiserror::Error, Debug)]
pub enum Socks5ClientError {
@@ -8,7 +8,7 @@ pub enum Socks5ClientError {
IoError(#[from] std::io::Error),
#[error("client-core error: {0}")]
ClientCoreError(#[from] ClientCoreError<fs_backend::Backend>),
ClientCoreError(#[from] ClientCoreError),
#[error("SOCKS proxy error")]
SocksProxyError(SocksProxyError),
@@ -21,4 +21,10 @@ pub enum Socks5ClientError {
#[error("Fail to bind address")]
FailToBindAddress,
#[error("Network requester: connection id {connection_id}: {error}")]
NetworkRequesterError {
connection_id: ConnectionId,
error: String,
},
}
+1 -1
View File
@@ -18,7 +18,7 @@ async fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
println!("{}", banner());
let args = commands::Cli::parse();
setup_env(args.config_env_file.clone());
setup_env(args.config_env_file.as_ref());
commands::execute(&args).await
}
+20 -9
View File
@@ -11,6 +11,8 @@ use proxy_helpers::connection_controller::{ControllerCommand, ControllerSender};
use socks5_requests::Message;
use task::TaskClient;
use crate::error::Socks5ClientError;
pub(crate) struct MixnetResponseListener {
buffer_requester: ReceivedBufferRequestSender,
mix_response_receiver: ReconstructedMessagesReceiver,
@@ -52,7 +54,10 @@ impl MixnetResponseListener {
}
}
async fn on_message(&self, reconstructed_message: ReconstructedMessage) {
fn on_message(
&self,
reconstructed_message: ReconstructedMessage,
) -> Result<(), Socks5ClientError> {
let raw_message = reconstructed_message.message;
if reconstructed_message.sender_tag.is_some() {
warn!("this message was sent anonymously - it couldn't have come from the service provider");
@@ -61,11 +66,11 @@ impl MixnetResponseListener {
let response = match Message::try_from_bytes(&raw_message) {
Err(err) => {
warn!("failed to parse received response - {err}");
return;
return Ok(());
}
Ok(Message::Request(_)) => {
warn!("unexpected request");
return;
return Ok(());
}
Ok(Message::Response(data)) => data,
Ok(Message::NetworkRequesterResponse(r)) => {
@@ -73,7 +78,10 @@ impl MixnetResponseListener {
"Network requester failed on connection id {} with error: {}",
r.connection_id, r.network_requester_error
);
return;
return Err(Socks5ClientError::NetworkRequesterError {
connection_id: r.connection_id,
error: r.network_requester_error,
});
}
};
@@ -84,18 +92,21 @@ impl MixnetResponseListener {
response.is_closed,
))
.unwrap();
Ok(())
}
pub(crate) async fn run(&mut self) {
while !self.shutdown.is_shutdown() {
tokio::select! {
received_responses = self.mix_response_receiver.next() => match received_responses {
Some(received_responses) => {
received_responses = self.mix_response_receiver.next() => {
if let Some(received_responses) = received_responses {
for reconstructed_message in received_responses {
self.on_message(reconstructed_message).await;
if let Err(err) = self.on_message(reconstructed_message) {
self.shutdown.send_status_msg(Box::new(err));
}
}
},
None => {
} else {
log::trace!("MixnetResponseListener: Stopping since channel closed");
break;
}
+14 -14
View File
@@ -85,7 +85,7 @@ export default class ValidatorClient implements INymClient {
static async connect(
mnemonic: string,
nymdUrl: string,
nyxdUrl: string,
nymApiUrl: string,
prefix: string,
mixnetContract: string,
@@ -94,19 +94,19 @@ export default class ValidatorClient implements INymClient {
): Promise<ValidatorClient> {
const wallet = await ValidatorClient.buildWallet(mnemonic, prefix);
const signingClient = await SigningClient.connectWithNymSigner(wallet, nymdUrl, nymApiUrl, prefix, denom);
const signingClient = await SigningClient.connectWithNymSigner(wallet, nyxdUrl, nymApiUrl, prefix, denom);
return new ValidatorClient(signingClient, prefix, mixnetContract, vestingContract, denom);
}
static async connectForQuery(
nymdUrl: string,
nyxdUrl: string,
nymApiUrl: string,
prefix: string,
mixnetContract: string,
vestingContract: string,
denom: string,
): Promise<ValidatorClient> {
const queryClient = await QueryClient.connectWithNym(nymdUrl, nymApiUrl);
const queryClient = await QueryClient.connectWithNym(nyxdUrl, nymApiUrl);
return new ValidatorClient(queryClient, prefix, mixnetContract, vestingContract, denom);
}
@@ -191,11 +191,11 @@ export default class ValidatorClient implements INymClient {
return this.client.getIntervalRewardPercent(this.mixnetContract);
}
public async getAllNymdMixnodes(): Promise<MixNodeBond[]> {
public async getAllNyxdMixnodes(): Promise<MixNodeBond[]> {
let mixNodes: MixNodeBond[] = [];
const limit = 50;
let startAfter;
for (;;) {
for (; ;) {
// eslint-disable-next-line no-await-in-loop
const pagedResponse: PagedMixnodeResponse = await this.client.getMixNodesPaged(this.mixnetContract, limit);
mixNodes = mixNodes.concat(pagedResponse.nodes);
@@ -209,11 +209,11 @@ export default class ValidatorClient implements INymClient {
return mixNodes;
}
public async getAllNymdGateways(): Promise<GatewayBond[]> {
public async getAllNyxdGateways(): Promise<GatewayBond[]> {
let gateways: GatewayBond[] = [];
const limit = 50;
let startAfter;
for (;;) {
for (; ;) {
// eslint-disable-next-line no-await-in-loop
const pagedResponse: PagedGatewayResponse = await this.client.getGatewaysPaged(this.mixnetContract, limit);
gateways = gateways.concat(pagedResponse.nodes);
@@ -232,11 +232,11 @@ export default class ValidatorClient implements INymClient {
*
* @param mixIdentity identity of the node to which the delegation was sent
*/
public async getAllNymdSingleMixnodeDelegations(mixIdentity: string): Promise<Delegation[]> {
public async getAllNyxdSingleMixnodeDelegations(mixIdentity: string): Promise<Delegation[]> {
let delegations: Delegation[] = [];
const limit = 250;
let startAfter;
for (;;) {
for (; ;) {
// eslint-disable-next-line no-await-in-loop
const pagedResponse: PagedMixDelegationsResponse = await this.client.getMixNodeDelegationsPaged(
this.mixnetContract,
@@ -255,11 +255,11 @@ export default class ValidatorClient implements INymClient {
return delegations;
}
public async getAllNymdDelegatorDelegations(delegator: string): Promise<Delegation[]> {
public async getAllNyxdDelegatorDelegations(delegator: string): Promise<Delegation[]> {
let delegations: Delegation[] = [];
const limit = 250;
let startAfter;
for (;;) {
for (; ;) {
// eslint-disable-next-line no-await-in-loop
const pagedResponse: PagedDelegatorDelegationsResponse = await this.client.getDelegatorDelegationsPaged(
this.mixnetContract,
@@ -278,11 +278,11 @@ export default class ValidatorClient implements INymClient {
return delegations;
}
public async getAllNymdNetworkDelegations(): Promise<Delegation[]> {
public async getAllNyxdNetworkDelegations(): Promise<Delegation[]> {
let delegations: Delegation[] = [];
const limit = 250;
let startAfter;
for (;;) {
for (; ;) {
// eslint-disable-next-line no-await-in-loop
const pagedResponse: PagedAllDelegationsResponse = await this.client.getAllNetworkDelegationsPaged(
this.mixnetContract,
@@ -5,7 +5,7 @@
import { JsonObject } from '@cosmjs/cosmwasm-stargate';
// eslint-disable-next-line import/no-cycle
import { INymdQuery } from './query-client';
import { INyxdQuery } from './query-client';
import {
ContractStateParams,
Delegation,
@@ -25,7 +25,7 @@ interface SmartContractQuery {
queryContractSmart(address: string, queryMsg: Record<string, unknown>): Promise<JsonObject>;
}
export default class NymdQuerier implements INymdQuery {
export default class NyxdQuerier implements INyxdQuery {
client: SmartContractQuery;
constructor(client: SmartContractQuery) {
+23 -23
View File
@@ -12,7 +12,7 @@ import {
} from '@cosmjs/stargate';
import { Code, CodeDetails, Contract, ContractCodeHistoryEntry } from '@cosmjs/cosmwasm-stargate/build/cosmwasmclient';
// eslint-disable-next-line import/no-cycle
import NymdQuerier from './nymd-querier';
import NyxdQuerier from './nyxd-querier';
import {
ContractStateParams,
Delegation,
@@ -52,7 +52,7 @@ export interface ICosmWasmQuery {
queryContractSmart(address: string, queryMsg: Record<string, unknown>): Promise<JsonObject>;
}
export interface INymdQuery {
export interface INyxdQuery {
// nym-specific implemented inside NymQuerier
getContractVersion(mixnetContractAddress: string): Promise<MixnetContractVersion>;
@@ -93,46 +93,46 @@ export interface INymdQuery {
): Promise<RewardingStatus>;
}
export interface IQueryClient extends ICosmWasmQuery, INymdQuery, INymApiQuery { }
export interface IQueryClient extends ICosmWasmQuery, INyxdQuery, INymApiQuery { }
export default class QueryClient extends CosmWasmClient implements IQueryClient {
private nymdQuerier: NymdQuerier;
private nyxdQuerier: NyxdQuerier;
private nymApiQuerier: NymApiQuerier;
private constructor(tmClient: Tendermint34Client, nymApiUrl: string) {
super(tmClient);
this.nymdQuerier = new NymdQuerier(this);
this.nyxdQuerier = new NyxdQuerier(this);
this.nymApiQuerier = new NymApiQuerier(nymApiUrl);
}
public static async connectWithNym(nymdUrl: string, nymApiUrl: string): Promise<QueryClient> {
const tmClient = await Tendermint34Client.connect(nymdUrl);
public static async connectWithNym(nyxdUrl: string, nymApiUrl: string): Promise<QueryClient> {
const tmClient = await Tendermint34Client.connect(nyxdUrl);
return new QueryClient(tmClient, nymApiUrl);
}
getContractVersion(mixnetContractAddress: string): Promise<MixnetContractVersion> {
return this.nymdQuerier.getContractVersion(mixnetContractAddress);
return this.nyxdQuerier.getContractVersion(mixnetContractAddress);
}
getMixNodesPaged(mixnetContractAddress: string, limit?: number, startAfter?: string): Promise<PagedMixnodeResponse> {
return this.nymdQuerier.getMixNodesPaged(mixnetContractAddress, limit, startAfter);
return this.nyxdQuerier.getMixNodesPaged(mixnetContractAddress, limit, startAfter);
}
getGatewaysPaged(mixnetContractAddress: string, limit?: number, startAfter?: string): Promise<PagedGatewayResponse> {
return this.nymdQuerier.getGatewaysPaged(mixnetContractAddress, limit, startAfter);
return this.nyxdQuerier.getGatewaysPaged(mixnetContractAddress, limit, startAfter);
}
ownsMixNode(mixnetContractAddress: string, address: string): Promise<MixOwnershipResponse> {
return this.nymdQuerier.ownsMixNode(mixnetContractAddress, address);
return this.nyxdQuerier.ownsMixNode(mixnetContractAddress, address);
}
ownsGateway(mixnetContractAddress: string, address: string): Promise<GatewayOwnershipResponse> {
return this.nymdQuerier.ownsGateway(mixnetContractAddress, address);
return this.nyxdQuerier.ownsGateway(mixnetContractAddress, address);
}
getStateParams(mixnetContractAddress: string): Promise<ContractStateParams> {
return this.nymdQuerier.getStateParams(mixnetContractAddress);
return this.nyxdQuerier.getStateParams(mixnetContractAddress);
}
getAllNetworkDelegationsPaged(
@@ -140,7 +140,7 @@ export default class QueryClient extends CosmWasmClient implements IQueryClient
limit?: number,
startAfter?: [string, string],
): Promise<PagedAllDelegationsResponse> {
return this.nymdQuerier.getAllNetworkDelegationsPaged(mixnetContractAddress, limit, startAfter);
return this.nyxdQuerier.getAllNetworkDelegationsPaged(mixnetContractAddress, limit, startAfter);
}
getMixNodeDelegationsPaged(
@@ -149,7 +149,7 @@ export default class QueryClient extends CosmWasmClient implements IQueryClient
limit?: number,
startAfter?: string,
): Promise<PagedMixDelegationsResponse> {
return this.nymdQuerier.getMixNodeDelegationsPaged(mixnetContractAddress, mixIdentity, limit, startAfter);
return this.nyxdQuerier.getMixNodeDelegationsPaged(mixnetContractAddress, mixIdentity, limit, startAfter);
}
getDelegatorDelegationsPaged(
@@ -158,31 +158,31 @@ export default class QueryClient extends CosmWasmClient implements IQueryClient
limit?: number,
startAfter?: string,
): Promise<PagedDelegatorDelegationsResponse> {
return this.nymdQuerier.getDelegatorDelegationsPaged(mixnetContractAddress, delegator, limit, startAfter);
return this.nyxdQuerier.getDelegatorDelegationsPaged(mixnetContractAddress, delegator, limit, startAfter);
}
getDelegationDetails(mixnetContractAddress: string, mixIdentity: string, delegator: string): Promise<Delegation> {
return this.nymdQuerier.getDelegationDetails(mixnetContractAddress, mixIdentity, delegator);
return this.nyxdQuerier.getDelegationDetails(mixnetContractAddress, mixIdentity, delegator);
}
getLayerDistribution(mixnetContractAddress: string): Promise<LayerDistribution> {
return this.nymdQuerier.getLayerDistribution(mixnetContractAddress);
return this.nyxdQuerier.getLayerDistribution(mixnetContractAddress);
}
getRewardPool(mixnetContractAddress: string): Promise<string> {
return this.nymdQuerier.getRewardPool(mixnetContractAddress);
return this.nyxdQuerier.getRewardPool(mixnetContractAddress);
}
getCirculatingSupply(mixnetContractAddress: string): Promise<string> {
return this.nymdQuerier.getCirculatingSupply(mixnetContractAddress);
return this.nyxdQuerier.getCirculatingSupply(mixnetContractAddress);
}
getIntervalRewardPercent(mixnetContractAddress: string): Promise<number> {
return this.nymdQuerier.getIntervalRewardPercent(mixnetContractAddress);
return this.nyxdQuerier.getIntervalRewardPercent(mixnetContractAddress);
}
getSybilResistancePercent(mixnetContractAddress: string): Promise<number> {
return this.nymdQuerier.getSybilResistancePercent(mixnetContractAddress);
return this.nyxdQuerier.getSybilResistancePercent(mixnetContractAddress);
}
getRewardingStatus(
@@ -190,7 +190,7 @@ export default class QueryClient extends CosmWasmClient implements IQueryClient
mixIdentity: string,
rewardingIntervalNonce: number,
): Promise<RewardingStatus> {
return this.nymdQuerier.getRewardingStatus(mixnetContractAddress, mixIdentity, rewardingIntervalNonce);
return this.nyxdQuerier.getRewardingStatus(mixnetContractAddress, mixIdentity, rewardingIntervalNonce);
}
getCachedGateways(): Promise<GatewayBond[]> {
+21 -21
View File
@@ -14,7 +14,7 @@ import { ChangeAdminResult } from '@cosmjs/cosmwasm-stargate/build/signingcosmwa
import { TxRaw } from 'cosmjs-types/cosmos/tx/v1beta1/tx';
import { nymGasPrice } from './stargate-helper';
import { IQueryClient } from './query-client';
import NymdQuerier from './nymd-querier';
import NyxdQuerier from './nyxd-querier';
import {
ContractStateParams,
Delegation,
@@ -197,7 +197,7 @@ export interface ISigningClient extends IQueryClient, ICosmWasmSigning, INymSign
}
export default class SigningClient extends SigningCosmWasmClient implements ISigningClient {
private nymdQuerier: NymdQuerier;
private nyxdQuerier: NyxdQuerier;
private nymApiQuerier: NymApiQuerier;
@@ -212,13 +212,13 @@ export default class SigningClient extends SigningCosmWasmClient implements ISig
) {
super(tmClient, wallet, signerOptions);
this.clientAddress = clientAddress;
this.nymdQuerier = new NymdQuerier(this);
this.nyxdQuerier = new NyxdQuerier(this);
this.nymApiQuerier = new NymApiQuerier(nymApiUrl);
}
public static async connectWithNymSigner(
wallet: DirectSecp256k1HdWallet,
nymdUrl: string,
nyxdUrl: string,
nymApiUrl: string,
prefix: string,
denom: string,
@@ -228,34 +228,34 @@ export default class SigningClient extends SigningCosmWasmClient implements ISig
prefix,
gasPrice: nymGasPrice(denom),
};
const tmClient = await Tendermint34Client.connect(nymdUrl);
const tmClient = await Tendermint34Client.connect(nyxdUrl);
return new SigningClient(address, nymApiUrl, tmClient, wallet, signerOptions);
}
// query related:
getContractVersion(mixnetContractAddress: string): Promise<MixnetContractVersion> {
return this.nymdQuerier.getContractVersion(mixnetContractAddress);
return this.nyxdQuerier.getContractVersion(mixnetContractAddress);
}
getMixNodesPaged(mixnetContractAddress: string, limit?: number, startAfter?: string): Promise<PagedMixnodeResponse> {
return this.nymdQuerier.getMixNodesPaged(mixnetContractAddress, limit, startAfter);
return this.nyxdQuerier.getMixNodesPaged(mixnetContractAddress, limit, startAfter);
}
getGatewaysPaged(mixnetContractAddress: string, limit?: number, startAfter?: string): Promise<PagedGatewayResponse> {
return this.nymdQuerier.getGatewaysPaged(mixnetContractAddress, limit, startAfter);
return this.nyxdQuerier.getGatewaysPaged(mixnetContractAddress, limit, startAfter);
}
ownsMixNode(mixnetContractAddress: string, address: string): Promise<MixOwnershipResponse> {
return this.nymdQuerier.ownsMixNode(mixnetContractAddress, address);
return this.nyxdQuerier.ownsMixNode(mixnetContractAddress, address);
}
ownsGateway(mixnetContractAddress: string, address: string): Promise<GatewayOwnershipResponse> {
return this.nymdQuerier.ownsGateway(mixnetContractAddress, address);
return this.nyxdQuerier.ownsGateway(mixnetContractAddress, address);
}
getStateParams(mixnetContractAddress: string): Promise<ContractStateParams> {
return this.nymdQuerier.getStateParams(mixnetContractAddress);
return this.nyxdQuerier.getStateParams(mixnetContractAddress);
}
getAllNetworkDelegationsPaged(
@@ -263,7 +263,7 @@ export default class SigningClient extends SigningCosmWasmClient implements ISig
limit?: number,
startAfter?: [string, string],
): Promise<PagedAllDelegationsResponse> {
return this.nymdQuerier.getAllNetworkDelegationsPaged(mixnetContractAddress, limit, startAfter);
return this.nyxdQuerier.getAllNetworkDelegationsPaged(mixnetContractAddress, limit, startAfter);
}
getMixNodeDelegationsPaged(
@@ -272,7 +272,7 @@ export default class SigningClient extends SigningCosmWasmClient implements ISig
limit?: number,
startAfter?: string,
): Promise<PagedMixDelegationsResponse> {
return this.nymdQuerier.getMixNodeDelegationsPaged(mixnetContractAddress, mixIdentity, limit, startAfter);
return this.nyxdQuerier.getMixNodeDelegationsPaged(mixnetContractAddress, mixIdentity, limit, startAfter);
}
getDelegatorDelegationsPaged(
@@ -281,31 +281,31 @@ export default class SigningClient extends SigningCosmWasmClient implements ISig
limit?: number,
startAfter?: string,
): Promise<PagedDelegatorDelegationsResponse> {
return this.nymdQuerier.getDelegatorDelegationsPaged(mixnetContractAddress, delegator, limit, startAfter);
return this.nyxdQuerier.getDelegatorDelegationsPaged(mixnetContractAddress, delegator, limit, startAfter);
}
getDelegationDetails(mixnetContractAddress: string, mixIdentity: string, delegator: string): Promise<Delegation> {
return this.nymdQuerier.getDelegationDetails(mixnetContractAddress, mixIdentity, delegator);
return this.nyxdQuerier.getDelegationDetails(mixnetContractAddress, mixIdentity, delegator);
}
getLayerDistribution(mixnetContractAddress: string): Promise<LayerDistribution> {
return this.nymdQuerier.getLayerDistribution(mixnetContractAddress);
return this.nyxdQuerier.getLayerDistribution(mixnetContractAddress);
}
getRewardPool(mixnetContractAddress: string): Promise<string> {
return this.nymdQuerier.getRewardPool(mixnetContractAddress);
return this.nyxdQuerier.getRewardPool(mixnetContractAddress);
}
getCirculatingSupply(mixnetContractAddress: string): Promise<string> {
return this.nymdQuerier.getCirculatingSupply(mixnetContractAddress);
return this.nyxdQuerier.getCirculatingSupply(mixnetContractAddress);
}
getIntervalRewardPercent(mixnetContractAddress: string): Promise<number> {
return this.nymdQuerier.getIntervalRewardPercent(mixnetContractAddress);
return this.nyxdQuerier.getIntervalRewardPercent(mixnetContractAddress);
}
getSybilResistancePercent(mixnetContractAddress: string): Promise<number> {
return this.nymdQuerier.getSybilResistancePercent(mixnetContractAddress);
return this.nyxdQuerier.getSybilResistancePercent(mixnetContractAddress);
}
getRewardingStatus(
@@ -313,7 +313,7 @@ export default class SigningClient extends SigningCosmWasmClient implements ISig
mixIdentity: string,
rewardingIntervalNonce: number,
): Promise<RewardingStatus> {
return this.nymdQuerier.getRewardingStatus(mixnetContractAddress, mixIdentity, rewardingIntervalNonce);
return this.nyxdQuerier.getRewardingStatus(mixnetContractAddress, mixIdentity, rewardingIntervalNonce);
}
getCachedGateways(): Promise<GatewayBond[]> {
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -6,7 +6,7 @@ use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub async fn get_gateway(api_server: String, preferred: Option<String>) -> GatewayEndpointConfig {
let validator_client = validator_client::client::ApiClient::new(api_server.parse().unwrap());
let validator_client = validator_client::client::NymApiClient::new(api_server.parse().unwrap());
let gateways = match validator_client.get_cached_gateways().await {
Err(err) => panic!("failed to obtain list of all gateways - {err}"),
+11
View File
@@ -0,0 +1,11 @@
[package]
name = "build-information"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
[build-dependencies]
vergen = { version = "7", default-features = false, features = ["build", "git", "rustc", "cargo"] }
@@ -1,4 +1,4 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// Copyright 2023 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use vergen::{vergen, Config};
+86
View File
@@ -0,0 +1,86 @@
// Copyright 2023 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
// TODO: at a later date this crate should probably also expose `ContractBuildInformation`
// and be used by our smart contracts
pub struct BinaryBuildInformation {
// VERGEN_BUILD_TIMESTAMP
/// Provides the build timestamp, for example `2021-02-23T20:14:46.558472672+00:00`.
pub build_timestamp: &'static str,
// VERGEN_BUILD_SEMVER
/// Provides the build version, for example `0.1.0-9-g46f83e1`.
pub build_version: &'static str,
// VERGEN_GIT_SHA
/// Provides the hash of the commit that was used for the build, for example `46f83e112520533338245862d366f6a02cef07d4`.
pub commit_sha: &'static str,
// VERGEN_GIT_COMMIT_TIMESTAMP
/// Provides the timestamp of the commit that was used for the build, for example `2021-02-23T08:08:02-05:00`.
pub commit_timestamp: &'static str,
// VERGEN_GIT_BRANCH
/// Provides the name of the git branch that was used for the build, for example `master`.
pub commit_branch: &'static str,
// VERGEN_RUSTC_SEMVER
/// Provides the rustc version that was used for the build, for example `1.52.0-nightly`.
pub rustc_version: &'static str,
// VERGEN_RUSTC_CHANNEL
/// Provides the rustc channel that was used for the build, for example `nightly`.
pub rustc_channel: &'static str,
// VERGEN_CARGO_PROFILE
/// Provides the cargo profile that was used for the build, for example `debug`.
pub cargo_profile: &'static str,
}
impl BinaryBuildInformation {
// explicitly require the build_version to be passed as it's binary specific
pub const fn new(build_version: &'static str) -> Self {
BinaryBuildInformation {
build_timestamp: env!("VERGEN_BUILD_TIMESTAMP"),
build_version,
commit_sha: env!("VERGEN_GIT_SHA"),
commit_timestamp: 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"),
}
}
pub fn pretty_print(&self) -> String {
format!(
r#"
{:<20}{}
{:<20}{}
{:<20}{}
{:<20}{}
{:<20}{}
{:<20}{}
{:<20}{}
{:<20}{}
"#,
"Build Timestamp:",
self.build_timestamp,
"Build Version:",
self.build_version,
"Commit SHA:",
self.commit_sha,
"Commit Date:",
self.commit_timestamp,
"Commit Branch:",
self.commit_branch,
"rustc Version:",
self.rustc_version,
"rustc Channel:",
self.rustc_channel,
"cargo Profile:",
self.cargo_profile,
)
}
}
+1 -2
View File
@@ -1,9 +1,8 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use std::collections::HashMap;
use futures::channel::mpsc;
use std::collections::HashMap;
pub type ConnectionId = u64;
@@ -27,6 +27,7 @@ nymsphinx = { path = "../../nymsphinx" }
pemstore = { path = "../../pemstore" }
validator-client = { path = "../validator-client", optional = true }
task = { path = "../../task" }
serde = { version = "1.0", features = ["derive"]}
[dependencies.tungstenite]
@@ -31,7 +31,7 @@ coconut-interface = { path = "../../coconut-interface" }
network-defaults = { path = "../../network-defaults" }
nym-api-requests = { path = "../../../nym-api/nym-api-requests", features = ["coconut"] }
# required for nymd-client
# required for nyxd-client
# at some point it might be possible to make it wasm-compatible
# perhaps after https://github.com/cosmos/cosmos-rust/pull/97 is resolved (and tendermint-rs is updated)
async-trait = { version = "0.1.51", optional = true }
@@ -50,7 +50,7 @@ execute = { path = "../../execute" }
ts-rs = "6.1.2"
[features]
nymd-client = [
nyxd-client = [
"async-trait",
"bip39",
"config",
@@ -15,41 +15,41 @@ use nym_api_requests::models::{
RewardEstimationResponse, StakeSaturationResponse,
};
#[cfg(feature = "nymd-client")]
use crate::nymd::traits::{DkgQueryClient, MixnetQueryClient, MultisigQueryClient};
#[cfg(feature = "nymd-client")]
use crate::nymd::{self, CosmWasmClient, NymdClient, QueryNymdClient, SigningNymdClient};
#[cfg(feature = "nymd-client")]
#[cfg(feature = "nyxd-client")]
use crate::nyxd::traits::{DkgQueryClient, MixnetQueryClient, MultisigQueryClient};
#[cfg(feature = "nyxd-client")]
use crate::nyxd::{self, CosmWasmClient, NyxdClient, QueryNyxdClient, SigningNyxdClient};
#[cfg(feature = "nyxd-client")]
use coconut_dkg_common::{
dealer::ContractDealing, types::DealerDetails, verification_key::ContractVKShare,
};
#[cfg(feature = "nymd-client")]
#[cfg(feature = "nyxd-client")]
use coconut_interface::Base58;
#[cfg(feature = "nymd-client")]
#[cfg(feature = "nyxd-client")]
use cw3::ProposalResponse;
#[cfg(feature = "nymd-client")]
#[cfg(feature = "nyxd-client")]
use mixnet_contract_common::{
families::{Family, FamilyHead},
mixnode::MixNodeBond,
pending_events::{PendingEpochEvent, PendingIntervalEvent},
Delegation, IdentityKey, RewardedSetNodeStatus, UnbondedMixnode,
};
#[cfg(feature = "nymd-client")]
#[cfg(feature = "nyxd-client")]
use network_defaults::NymNetworkDetails;
#[cfg(feature = "nymd-client")]
#[cfg(feature = "nyxd-client")]
use nym_api_requests::models::MixNodeBondAnnotated;
#[cfg(feature = "nymd-client")]
#[cfg(feature = "nyxd-client")]
use std::str::FromStr;
use url::Url;
#[cfg(feature = "nymd-client")]
#[cfg(feature = "nyxd-client")]
#[must_use]
#[derive(Debug, Clone)]
pub struct Config {
api_url: Url,
nymd_url: Url,
nyxd_url: Url,
nymd_config: nymd::Config,
nyxd_config: nyxd::Config,
mixnode_page_limit: Option<u32>,
gateway_page_limit: Option<u32>,
@@ -60,7 +60,7 @@ pub struct Config {
proposals_page_limit: Option<u32>,
}
#[cfg(feature = "nymd-client")]
#[cfg(feature = "nyxd-client")]
impl Config {
pub fn try_from_nym_network_details(
details: &NymNetworkDetails,
@@ -78,11 +78,11 @@ impl Config {
Ok(Config {
api_url: api_url.pop().unwrap(),
nymd_url: details.endpoints[0]
.nymd_url
nyxd_url: details.endpoints[0]
.nyxd_url
.parse()
.map_err(ValidatorClientError::MalformedUrlProvided)?,
nymd_config: nymd::Config::try_from_nym_network_details(details)?,
nyxd_config: nyxd::Config::try_from_nym_network_details(details)?,
mixnode_page_limit: None,
gateway_page_limit: None,
mixnode_delegations_page_limit: None,
@@ -95,14 +95,14 @@ impl Config {
// TODO: this method shouldn't really exist as all information should be included immediately
// via `from_nym_network_details`, but it's here for, you guessed it, legacy compatibility
pub fn with_urls(mut self, nymd_url: Url, api_url: Url) -> Self {
self.nymd_url = nymd_url;
pub fn with_urls(mut self, nyxd_url: Url, api_url: Url) -> Self {
self.nyxd_url = nyxd_url;
self.api_url = api_url;
self
}
pub fn with_nymd_url(mut self, nymd_url: Url) -> Self {
self.nymd_url = nymd_url;
pub fn with_nyxd_url(mut self, nyxd_url: Url) -> Self {
self.nyxd_url = nyxd_url;
self
}
@@ -127,7 +127,7 @@ impl Config {
}
}
#[cfg(feature = "nymd-client")]
#[cfg(feature = "nyxd-client")]
pub struct Client<C> {
// TODO: we really shouldn't be storing a mnemonic here, but removing it would be
// non-trivial amount of work and it's out of scope of the current branch
@@ -143,19 +143,19 @@ pub struct Client<C> {
// ideally they would have been read-only, but unfortunately rust doesn't have such features
pub nym_api: nym_api::Client,
pub nymd: NymdClient<C>,
pub nyxd: NyxdClient<C>,
}
#[cfg(feature = "nymd-client")]
impl Client<SigningNymdClient> {
#[cfg(feature = "nyxd-client")]
impl Client<SigningNyxdClient> {
pub fn new_signing(
config: Config,
mnemonic: bip39::Mnemonic,
) -> Result<Client<SigningNymdClient>, ValidatorClientError> {
) -> Result<Client<SigningNyxdClient>, ValidatorClientError> {
let nym_api_client = nym_api::Client::new(config.api_url.clone());
let nymd_client = NymdClient::connect_with_mnemonic(
config.nymd_config.clone(),
config.nymd_url.as_str(),
let nyxd_client = NyxdClient::connect_with_mnemonic(
config.nyxd_config.clone(),
config.nyxd_url.as_str(),
mnemonic.clone(),
None,
)?;
@@ -170,13 +170,13 @@ impl Client<SigningNymdClient> {
verification_key_page_limit: config.verification_key_page_limit,
proposals_page_limit: config.proposals_page_limit,
nym_api: nym_api_client,
nymd: nymd_client,
nyxd: nyxd_client,
})
}
pub fn change_nymd(&mut self, new_endpoint: Url) -> Result<(), ValidatorClientError> {
self.nymd = NymdClient::connect_with_mnemonic(
self.nymd.current_config().clone(),
pub fn change_nyxd(&mut self, new_endpoint: Url) -> Result<(), ValidatorClientError> {
self.nyxd = NyxdClient::connect_with_mnemonic(
self.nyxd.current_config().clone(),
new_endpoint.as_ref(),
self.mnemonic.clone().unwrap(),
None,
@@ -184,17 +184,17 @@ impl Client<SigningNymdClient> {
Ok(())
}
pub fn set_nymd_simulated_gas_multiplier(&mut self, multiplier: f32) {
self.nymd.set_simulated_gas_multiplier(multiplier)
pub fn set_nyxd_simulated_gas_multiplier(&mut self, multiplier: f32) {
self.nyxd.set_simulated_gas_multiplier(multiplier)
}
}
#[cfg(feature = "nymd-client")]
impl Client<QueryNymdClient> {
pub fn new_query(config: Config) -> Result<Client<QueryNymdClient>, ValidatorClientError> {
#[cfg(feature = "nyxd-client")]
impl Client<QueryNyxdClient> {
pub fn new_query(config: Config) -> Result<Client<QueryNyxdClient>, ValidatorClientError> {
let nym_api_client = nym_api::Client::new(config.api_url.clone());
let nymd_client =
NymdClient::connect(config.nymd_config.clone(), config.nymd_url.as_str())?;
let nyxd_client =
NyxdClient::connect(config.nyxd_config.clone(), config.nyxd_url.as_str())?;
Ok(Client {
mnemonic: None,
@@ -206,29 +206,29 @@ impl Client<QueryNymdClient> {
verification_key_page_limit: config.verification_key_page_limit,
proposals_page_limit: config.proposals_page_limit,
nym_api: nym_api_client,
nymd: nymd_client,
nyxd: nyxd_client,
})
}
pub fn change_nymd(&mut self, new_endpoint: Url) -> Result<(), ValidatorClientError> {
self.nymd = NymdClient::connect(self.nymd.current_config().clone(), new_endpoint.as_ref())?;
pub fn change_nyxd(&mut self, new_endpoint: Url) -> Result<(), ValidatorClientError> {
self.nyxd = NyxdClient::connect(self.nyxd.current_config().clone(), new_endpoint.as_ref())?;
Ok(())
}
}
// nymd wrappers
#[cfg(feature = "nymd-client")]
// nyxd wrappers
#[cfg(feature = "nyxd-client")]
impl<C> Client<C> {
// use case: somebody initialised client without a contract in order to upload and initialise one
// and now they want to actually use it without making new client
pub fn set_mixnet_contract_address(&mut self, mixnet_contract_address: cosmrs::AccountId) {
self.nymd
self.nyxd
.set_mixnet_contract_address(mixnet_contract_address)
}
pub fn get_mixnet_contract_address(&self) -> cosmrs::AccountId {
self.nymd.mixnet_contract_address().clone()
self.nyxd.mixnet_contract_address().clone()
}
pub async fn get_all_node_families(&self) -> Result<Vec<Family>, ValidatorClientError>
@@ -240,7 +240,7 @@ impl<C> Client<C> {
loop {
let paged_response = self
.nymd
.nyxd
.get_all_node_families_paged(start_after.take(), None)
.await?;
families.extend(paged_response.families);
@@ -266,7 +266,7 @@ impl<C> Client<C> {
loop {
let paged_response = self
.nymd
.nyxd
.get_all_family_members_paged(start_after.take(), None)
.await?;
members.extend(paged_response.members);
@@ -282,7 +282,7 @@ impl<C> Client<C> {
}
// basically handles paging for us
pub async fn get_all_nymd_rewarded_set_mixnodes(
pub async fn get_all_nyxd_rewarded_set_mixnodes(
&self,
) -> Result<Vec<(MixId, RewardedSetNodeStatus)>, ValidatorClientError>
where
@@ -293,7 +293,7 @@ impl<C> Client<C> {
loop {
let mut paged_response = self
.nymd
.nyxd
.get_rewarded_set_paged(start_after.take(), self.rewarded_set_page_limit)
.await?;
identities.append(&mut paged_response.nodes);
@@ -308,7 +308,7 @@ impl<C> Client<C> {
Ok(identities)
}
pub async fn get_all_nymd_mixnode_bonds(&self) -> Result<Vec<MixNodeBond>, ValidatorClientError>
pub async fn get_all_nyxd_mixnode_bonds(&self) -> Result<Vec<MixNodeBond>, ValidatorClientError>
where
C: CosmWasmClient + Sync + Send,
{
@@ -316,7 +316,7 @@ impl<C> Client<C> {
let mut start_after = None;
loop {
let mut paged_response = self
.nymd
.nyxd
.get_mixnode_bonds_paged(self.mixnode_page_limit, start_after.take())
.await?;
mixnodes.append(&mut paged_response.nodes);
@@ -331,7 +331,7 @@ impl<C> Client<C> {
Ok(mixnodes)
}
pub async fn get_all_nymd_mixnodes_detailed(
pub async fn get_all_nyxd_mixnodes_detailed(
&self,
) -> Result<Vec<MixNodeDetails>, ValidatorClientError>
where
@@ -341,7 +341,7 @@ impl<C> Client<C> {
let mut start_after = None;
loop {
let mut paged_response = self
.nymd
.nyxd
.get_mixnodes_detailed_paged(self.mixnode_page_limit, start_after.take())
.await?;
mixnodes.append(&mut paged_response.nodes);
@@ -356,7 +356,7 @@ impl<C> Client<C> {
Ok(mixnodes)
}
pub async fn get_all_nymd_unbonded_mixnodes(
pub async fn get_all_nyxd_unbonded_mixnodes(
&self,
) -> Result<Vec<(MixId, UnbondedMixnode)>, ValidatorClientError>
where
@@ -366,7 +366,7 @@ impl<C> Client<C> {
let mut start_after = None;
loop {
let mut paged_response = self
.nymd
.nyxd
.get_unbonded_paged(self.mixnode_page_limit, start_after.take())
.await?;
mixnodes.append(&mut paged_response.nodes);
@@ -381,7 +381,7 @@ impl<C> Client<C> {
Ok(mixnodes)
}
pub async fn get_all_nymd_unbonded_mixnodes_by_owner(
pub async fn get_all_nyxd_unbonded_mixnodes_by_owner(
&self,
owner: &cosmrs::AccountId,
) -> Result<Vec<(MixId, UnbondedMixnode)>, ValidatorClientError>
@@ -392,7 +392,7 @@ impl<C> Client<C> {
let mut start_after = None;
loop {
let mut paged_response = self
.nymd
.nyxd
.get_unbonded_by_owner_paged(owner, self.mixnode_page_limit, start_after.take())
.await?;
mixnodes.append(&mut paged_response.nodes);
@@ -407,7 +407,7 @@ impl<C> Client<C> {
Ok(mixnodes)
}
pub async fn get_all_nymd_unbonded_mixnodes_by_identity(
pub async fn get_all_nyxd_unbonded_mixnodes_by_identity(
&self,
identity_key: String,
) -> Result<Vec<(MixId, UnbondedMixnode)>, ValidatorClientError>
@@ -418,7 +418,7 @@ impl<C> Client<C> {
let mut start_after = None;
loop {
let mut paged_response = self
.nymd
.nyxd
.get_unbonded_by_identity_paged(
identity_key.clone(),
self.mixnode_page_limit,
@@ -437,7 +437,7 @@ impl<C> Client<C> {
Ok(mixnodes)
}
pub async fn get_all_nymd_gateways(&self) -> Result<Vec<GatewayBond>, ValidatorClientError>
pub async fn get_all_nyxd_gateways(&self) -> Result<Vec<GatewayBond>, ValidatorClientError>
where
C: CosmWasmClient + Sync + Send,
{
@@ -445,7 +445,7 @@ impl<C> Client<C> {
let mut start_after = None;
loop {
let mut paged_response = self
.nymd
.nyxd
.get_gateways_paged(start_after.take(), self.gateway_page_limit)
.await?;
gateways.append(&mut paged_response.nodes);
@@ -460,7 +460,7 @@ impl<C> Client<C> {
Ok(gateways)
}
pub async fn get_all_nymd_single_mixnode_delegations(
pub async fn get_all_nyxd_single_mixnode_delegations(
&self,
mix_id: MixId,
) -> Result<Vec<Delegation>, ValidatorClientError>
@@ -471,7 +471,7 @@ impl<C> Client<C> {
let mut start_after = None;
loop {
let mut paged_response = self
.nymd
.nyxd
.get_mixnode_delegations_paged(
mix_id,
start_after.take(),
@@ -501,7 +501,7 @@ impl<C> Client<C> {
let mut start_after = None;
loop {
let mut paged_response = self
.nymd
.nyxd
.get_delegator_delegations_paged(
delegation_owner.to_string(),
start_after.take(),
@@ -528,7 +528,7 @@ impl<C> Client<C> {
let mut start_after = None;
loop {
let mut paged_response = self
.nymd
.nyxd
.get_all_network_delegations_paged(
start_after.take(),
self.mixnode_delegations_page_limit,
@@ -546,7 +546,7 @@ impl<C> Client<C> {
Ok(delegations)
}
pub async fn get_all_nymd_pending_epoch_events(
pub async fn get_all_nyxd_pending_epoch_events(
&self,
) -> Result<Vec<PendingEpochEvent>, ValidatorClientError>
where
@@ -557,7 +557,7 @@ impl<C> Client<C> {
loop {
let mut paged_response = self
.nymd
.nyxd
.get_pending_epoch_events_paged(start_after.take(), self.rewarded_set_page_limit)
.await?;
events.append(&mut paged_response.events);
@@ -572,7 +572,7 @@ impl<C> Client<C> {
Ok(events)
}
pub async fn get_all_nymd_pending_interval_events(
pub async fn get_all_nyxd_pending_interval_events(
&self,
) -> Result<Vec<PendingIntervalEvent>, ValidatorClientError>
where
@@ -583,7 +583,7 @@ impl<C> Client<C> {
loop {
let mut paged_response = self
.nymd
.nyxd
.get_pending_interval_events_paged(start_after.take(), self.rewarded_set_page_limit)
.await?;
events.append(&mut paged_response.events);
@@ -598,7 +598,7 @@ impl<C> Client<C> {
Ok(events)
}
pub async fn get_all_nymd_current_dealers(
pub async fn get_all_nyxd_current_dealers(
&self,
) -> Result<Vec<DealerDetails>, ValidatorClientError>
where
@@ -608,7 +608,7 @@ impl<C> Client<C> {
let mut start_after = None;
loop {
let mut paged_response = self
.nymd
.nyxd
.get_current_dealers_paged(start_after.take(), self.dealers_page_limit)
.await?;
dealers.append(&mut paged_response.dealers);
@@ -623,7 +623,7 @@ impl<C> Client<C> {
Ok(dealers)
}
pub async fn get_all_nymd_past_dealers(
pub async fn get_all_nyxd_past_dealers(
&self,
) -> Result<Vec<DealerDetails>, ValidatorClientError>
where
@@ -633,7 +633,7 @@ impl<C> Client<C> {
let mut start_after = None;
loop {
let mut paged_response = self
.nymd
.nyxd
.get_past_dealers_paged(start_after.take(), self.dealers_page_limit)
.await?;
dealers.append(&mut paged_response.dealers);
@@ -648,7 +648,7 @@ impl<C> Client<C> {
Ok(dealers)
}
pub async fn get_all_nymd_epoch_dealings(
pub async fn get_all_nyxd_epoch_dealings(
&self,
idx: usize,
) -> Result<Vec<ContractDealing>, ValidatorClientError>
@@ -659,7 +659,7 @@ impl<C> Client<C> {
let mut start_after = None;
loop {
let mut paged_response = self
.nymd
.nyxd
.get_dealings_paged(idx, start_after.take(), self.dealers_page_limit)
.await?;
dealings.append(&mut paged_response.dealings);
@@ -674,7 +674,7 @@ impl<C> Client<C> {
Ok(dealings)
}
pub async fn get_all_nymd_verification_key_shares(
pub async fn get_all_nyxd_verification_key_shares(
&self,
) -> Result<Vec<ContractVKShare>, ValidatorClientError>
where
@@ -684,7 +684,7 @@ impl<C> Client<C> {
let mut start_after = None;
loop {
let mut paged_response = self
.nymd
.nyxd
.get_vk_shares_paged(start_after.take(), self.verification_key_page_limit)
.await?;
shares.append(&mut paged_response.shares);
@@ -699,7 +699,7 @@ impl<C> Client<C> {
Ok(shares)
}
pub async fn get_all_nymd_proposals(
pub async fn get_all_nyxd_proposals(
&self,
) -> Result<Vec<ProposalResponse>, ValidatorClientError>
where
@@ -710,7 +710,7 @@ impl<C> Client<C> {
loop {
let mut paged_response = self
.nymd
.nyxd
.list_proposals(start_after.take(), self.proposals_page_limit)
.await?;
@@ -729,7 +729,7 @@ impl<C> Client<C> {
}
// validator-api wrappers
#[cfg(feature = "nymd-client")]
#[cfg(feature = "nyxd-client")]
impl<C> Client<C> {
pub fn change_nym_api(&mut self, new_endpoint: Url) {
self.nym_api.change_url(new_endpoint)
@@ -783,23 +783,23 @@ impl<C> Client<C> {
#[derive(Clone)]
pub struct CoconutApiClient {
pub api_client: ApiClient,
pub api_client: NymApiClient,
pub verification_key: VerificationKey,
pub node_id: NodeIndex,
#[cfg(feature = "nymd-client")]
#[cfg(feature = "nyxd-client")]
pub cosmos_address: cosmrs::AccountId,
}
#[cfg(feature = "nymd-client")]
#[cfg(feature = "nyxd-client")]
impl CoconutApiClient {
pub async fn all_coconut_api_clients<C>(
nymd_client: &Client<C>,
nyxd_client: &Client<C>,
) -> Result<Vec<Self>, ValidatorClientError>
where
C: CosmWasmClient + Sync + Send,
{
Ok(nymd_client
.get_all_nymd_verification_key_shares()
Ok(nyxd_client
.get_all_nyxd_verification_key_shares()
.await?
.into_iter()
.filter_map(Self::try_from)
@@ -812,7 +812,7 @@ impl CoconutApiClient {
if let Ok(verification_key) = VerificationKey::try_from_bs58(&share.share) {
if let Ok(cosmos_address) = cosmrs::AccountId::from_str(share.owner.as_str()) {
return Some(CoconutApiClient {
api_client: ApiClient::new(url_address),
api_client: NymApiClient::new(url_address),
verification_key,
node_id: share.node_index,
cosmos_address,
@@ -826,17 +826,17 @@ impl CoconutApiClient {
}
#[derive(Clone)]
pub struct ApiClient {
pub struct NymApiClient {
pub nym_api_client: nym_api::Client,
// TODO: perhaps if we really need it at some (currently I don't see any reasons for it)
// we could re-implement the communication with the REST API on port 1317
}
impl ApiClient {
impl NymApiClient {
pub fn new(api_url: Url) -> Self {
let nym_api_client = nym_api::Client::new(api_url);
ApiClient { nym_api_client }
NymApiClient { nym_api_client }
}
pub fn change_nym_api(&mut self, new_endpoint: Url) {
@@ -1,8 +1,8 @@
use crate::nymd::error::NymdError;
use crate::nymd::{Config as ClientConfig, NymdClient, QueryNymdClient};
use crate::ApiClient;
use crate::nyxd::error::NyxdError;
use crate::nyxd::{Config as ClientConfig, NyxdClient, QueryNyxdClient};
use crate::NymApiClient;
use crate::nymd::traits::MixnetQueryClient;
use crate::nyxd::traits::MixnetQueryClient;
use colored::Colorize;
use core::fmt;
use itertools::Itertools;
@@ -16,9 +16,9 @@ use url::Url;
const MAX_URLS_TESTED: usize = 200;
const CONNECTION_TEST_TIMEOUT_SEC: u64 = 2;
// Run connection tests for all specified nymd and api urls. These are all run concurrently.
/// Run connection tests for all specified nyxd and api urls. These are all run concurrently.
pub async fn run_validator_connection_test<H: BuildHasher + 'static>(
nymd_urls: impl Iterator<Item = (NymNetworkDetails, Url)>,
nyxd_urls: impl Iterator<Item = (NymNetworkDetails, Url)>,
api_urls: impl Iterator<Item = (NymNetworkDetails, Url)>,
mixnet_contract_address: HashMap<NymNetworkDetails, cosmrs::AccountId, H>,
) -> (
@@ -27,7 +27,7 @@ pub async fn run_validator_connection_test<H: BuildHasher + 'static>(
) {
// Setup all the clients for the connection tests
let connection_test_clients =
setup_connection_tests(nymd_urls, api_urls, mixnet_contract_address);
setup_connection_tests(nyxd_urls, api_urls, mixnet_contract_address);
// Run all tests concurrently
let connection_results = futures::future::join_all(
@@ -40,28 +40,28 @@ pub async fn run_validator_connection_test<H: BuildHasher + 'static>(
// Seperate and collect results into HashMaps
(
extract_and_collect_results_into_map(&connection_results, &UrlType::Nymd),
extract_and_collect_results_into_map(&connection_results, &UrlType::Api),
extract_and_collect_results_into_map(&connection_results, &UrlType::Nyxd),
extract_and_collect_results_into_map(&connection_results, &UrlType::NymApi),
)
}
fn setup_connection_tests<H: BuildHasher + 'static>(
nymd_urls: impl Iterator<Item = (NymNetworkDetails, Url)>,
nyxd_urls: impl Iterator<Item = (NymNetworkDetails, Url)>,
api_urls: impl Iterator<Item = (NymNetworkDetails, Url)>,
mixnet_contract_address: HashMap<NymNetworkDetails, cosmrs::AccountId, H>,
) -> impl Iterator<Item = ClientForConnectionTest> {
let nymd_connection_test_clients = nymd_urls.filter_map(move |(network, url)| {
let nyxd_connection_test_clients = nyxd_urls.filter_map(move |(network, url)| {
let address = mixnet_contract_address
.get(&network)
.expect("No configured contract address")
.clone();
let config = ClientConfig::try_from_nym_network_details(&network)
.expect("failed to create valid nymd client config");
.expect("failed to create valid nyxd client config");
if let Ok(mut client) = NymdClient::<QueryNymdClient>::connect(config, url.as_str()) {
if let Ok(mut client) = NyxdClient::<QueryNyxdClient>::connect(config, url.as_str()) {
// possibly redundant, but lets just leave it here
client.set_mixnet_contract_address(address);
Some(ClientForConnectionTest::Nymd(
Some(ClientForConnectionTest::Nyxd(
network,
url,
Box::new(client),
@@ -72,10 +72,10 @@ fn setup_connection_tests<H: BuildHasher + 'static>(
});
let api_connection_test_clients = api_urls.map(|(network, url)| {
ClientForConnectionTest::Api(network, url.clone(), ApiClient::new(url))
ClientForConnectionTest::Api(network, url.clone(), NymApiClient::new(url))
});
nymd_connection_test_clients.chain(api_connection_test_clients)
nyxd_connection_test_clients.chain(api_connection_test_clients)
}
fn extract_and_collect_results_into_map(
@@ -92,10 +92,10 @@ fn extract_and_collect_results_into_map(
.into_group_map()
}
async fn test_nymd_connection(
async fn test_nyxd_connection(
network: NymNetworkDetails,
url: &Url,
client: &NymdClient<QueryNymdClient>,
client: &NyxdClient<QueryNyxdClient>,
) -> ConnectionResult {
let result = match timeout(
Duration::from_secs(CONNECTION_TEST_TIMEOUT_SEC),
@@ -103,48 +103,48 @@ async fn test_nymd_connection(
)
.await
{
Ok(Err(NymdError::TendermintError(e))) => {
Ok(Err(NyxdError::TendermintError(e))) => {
// If we get a tendermint-rpc error, we classify the node as not contactable
log::debug!("Checking: nymd_url: {url}: {}: {}", "failed".red(), e);
log::debug!("Checking: nyxd url: {url}: {}: {}", "failed".red(), e);
false
}
Ok(Err(NymdError::AbciError(code, log))) => {
Ok(Err(NyxdError::AbciError { code, log, .. })) => {
// We accept the mixnet contract not found as ok from a connection standpoint. This happens
// for example on a pre-launch network.
log::debug!(
"Checking: nymd_url: {url}: {}, but with abci error: {code}: {log}",
"Checking: nyxd url: {url}: {}, but with abci error: {code}: {log}",
"success".green()
);
code == 18
}
Ok(Err(error @ NymdError::NoContractAddressAvailable)) => {
log::debug!("Checking: nymd_url: {url}: {}: {error}", "failed".red());
Ok(Err(error @ NyxdError::NoContractAddressAvailable)) => {
log::debug!("Checking: nyxd url: {url}: {}: {error}", "failed".red());
false
}
Ok(Err(e)) => {
// For any other error, we're optimistic and just try anyway.
log::debug!(
"Checking: nymd_url: {url}: {}, but with error: {e}",
"Checking: nyxd_url: {url}: {}, but with error: {e}",
"success".green()
);
true
}
Ok(Ok(_)) => {
log::debug!("Checking: nymd_url: {url}: {}", "success".green());
log::debug!("Checking: nyxd_url: {url}: {}", "success".green());
true
}
Err(e) => {
log::debug!("Checking: nymd_url: {url}: {}: {e}", "failed".red());
log::debug!("Checking: nyxd_url: {url}: {}: {e}", "failed".red());
false
}
};
ConnectionResult::Nymd(network, url.clone(), result)
ConnectionResult::Nyxd(network, url.clone(), result)
}
async fn test_api_connection(
async fn test_nym_api_connection(
network: NymNetworkDetails,
url: &Url,
client: &ApiClient,
client: &NymApiClient,
) -> ConnectionResult {
let result = match timeout(
Duration::from_secs(CONNECTION_TEST_TIMEOUT_SEC),
@@ -169,18 +169,18 @@ async fn test_api_connection(
}
enum ClientForConnectionTest {
Nymd(NymNetworkDetails, Url, Box<NymdClient<QueryNymdClient>>),
Api(NymNetworkDetails, Url, ApiClient),
Nyxd(NymNetworkDetails, Url, Box<NyxdClient<QueryNyxdClient>>),
Api(NymNetworkDetails, Url, NymApiClient),
}
impl ClientForConnectionTest {
async fn run_connection_check(self) -> ConnectionResult {
match self {
ClientForConnectionTest::Nymd(network, ref url, ref client) => {
test_nymd_connection(network, url, client).await
ClientForConnectionTest::Nyxd(network, ref url, ref client) => {
test_nyxd_connection(network, url, client).await
}
ClientForConnectionTest::Api(network, ref url, ref client) => {
test_api_connection(network, url, client).await
test_nym_api_connection(network, url, client).await
}
}
}
@@ -188,37 +188,37 @@ impl ClientForConnectionTest {
#[derive(Debug, PartialEq, Eq)]
enum UrlType {
Nymd,
Api,
Nyxd,
NymApi,
}
impl fmt::Display for UrlType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
UrlType::Nymd => write!(f, "nymd"),
UrlType::Api => write!(f, "api"),
UrlType::Nyxd => write!(f, "nyxd"),
UrlType::NymApi => write!(f, "api"),
}
}
}
#[derive(Debug)]
enum ConnectionResult {
Nymd(NymNetworkDetails, Url, bool),
Nyxd(NymNetworkDetails, Url, bool),
Api(NymNetworkDetails, Url, bool),
}
impl ConnectionResult {
fn result(&self) -> (&NymNetworkDetails, &Url, &bool) {
match self {
ConnectionResult::Nymd(network, url, result)
ConnectionResult::Nyxd(network, url, result)
| ConnectionResult::Api(network, url, result) => (network, url, result),
}
}
fn url_type(&self) -> UrlType {
match self {
ConnectionResult::Nymd(..) => UrlType::Nymd,
ConnectionResult::Api(..) => UrlType::Api,
ConnectionResult::Nyxd(..) => UrlType::Nyxd,
ConnectionResult::Api(..) => UrlType::NymApi,
}
}
}
@@ -15,9 +15,9 @@ pub enum ValidatorClientError {
#[error("One of the provided URLs was malformed - {0}")]
MalformedUrlProvided(#[from] url::ParseError),
#[cfg(feature = "nymd-client")]
#[error("There was an issue with the Nymd client - {0}")]
NymdError(#[from] crate::nymd::error::NymdError),
#[cfg(feature = "nyxd-client")]
#[error("There was an issue with the Nyxd client - {0}")]
NyxdError(#[from] crate::nyxd::error::NyxdError),
#[error("No validator API url has been provided")]
NoAPIUrlAvailable,
@@ -2,17 +2,17 @@
// SPDX-License-Identifier: Apache-2.0
pub mod client;
#[cfg(feature = "nymd-client")]
#[cfg(feature = "nyxd-client")]
pub mod connection_tester;
mod error;
pub mod nym_api;
#[cfg(feature = "nymd-client")]
pub mod nymd;
#[cfg(feature = "nyxd-client")]
pub mod nyxd;
#[cfg(feature = "nymd-client")]
pub use crate::client::{ApiClient, CoconutApiClient};
#[cfg(feature = "nyxd-client")]
pub use crate::client::{CoconutApiClient, NymApiClient};
pub use crate::error::ValidatorClientError;
pub use nym_api_requests::*;
#[cfg(feature = "nymd-client")]
#[cfg(feature = "nyxd-client")]
pub use client::{Client, Config};
@@ -9,10 +9,11 @@ use nym_api_requests::coconut::{
BlindSignRequestBody, BlindedSignatureResponse, VerifyCredentialBody, VerifyCredentialResponse,
};
use nym_api_requests::models::{
GatewayCoreStatusResponse, GatewayStatusReportResponse, GatewayUptimeHistoryResponse,
InclusionProbabilityResponse, MixNodeBondAnnotated, MixnodeCoreStatusResponse,
MixnodeStatusReportResponse, MixnodeStatusResponse, MixnodeUptimeHistoryResponse, RequestError,
RewardEstimationResponse, StakeSaturationResponse, UptimeResponse,
ComputeRewardEstParam, GatewayCoreStatusResponse, GatewayStatusReportResponse,
GatewayUptimeHistoryResponse, InclusionProbabilityResponse, MixNodeBondAnnotated,
MixnodeCoreStatusResponse, MixnodeStatusReportResponse, MixnodeStatusResponse,
MixnodeUptimeHistoryResponse, RequestError, RewardEstimationResponse, StakeSaturationResponse,
UptimeResponse,
};
use reqwest::Response;
use serde::{Deserialize, Serialize};
@@ -361,6 +362,25 @@ impl Client {
.await
}
pub async fn compute_mixnode_reward_estimation(
&self,
mix_id: MixId,
request_body: &ComputeRewardEstParam,
) -> Result<RewardEstimationResponse, NymAPIError> {
self.post_nym_api(
&[
routes::API_VERSION,
routes::STATUS_ROUTES,
routes::MIXNODE,
&mix_id.to_string(),
routes::COMPUTE_REWARD_ESTIMATION,
],
NO_PARAMS,
request_body,
)
.await
}
pub async fn get_mixnode_stake_saturation(
&self,
mix_id: MixId,
@@ -28,6 +28,7 @@ pub const STATUS: &str = "status";
pub const REPORT: &str = "report";
pub const HISTORY: &str = "history";
pub const REWARD_ESTIMATION: &str = "reward-estimation";
pub const COMPUTE_REWARD_ESTIMATION: &str = "compute-reward-estimation";
pub const AVG_UPTIME: &str = "avg_uptime";
pub const STAKE_SATURATION: &str = "stake-saturation";
pub const INCLUSION_CHANCE: &str = "inclusion-probability";
@@ -1,13 +1,14 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::nymd::coin::Coin;
use crate::nymd::cosmwasm_client::helpers::{create_pagination, next_page_key};
use crate::nymd::cosmwasm_client::types::{
use crate::nyxd;
use crate::nyxd::coin::Coin;
use crate::nyxd::cosmwasm_client::helpers::{create_pagination, next_page_key};
use crate::nyxd::cosmwasm_client::types::{
Account, Code, CodeDetails, Contract, ContractCodeHistoryEntry, ContractCodeId,
SequenceResponse, SimulateResponse,
};
use crate::nymd::error::NymdError;
use crate::nyxd::error::NyxdError;
use async_trait::async_trait;
use cosmrs::proto::cosmos::auth::v1beta1::{QueryAccountRequest, QueryAccountResponse};
use cosmrs::proto::cosmos::bank::v1beta1::{
@@ -23,7 +24,6 @@ use cosmrs::rpc::endpoint::broadcast;
use cosmrs::rpc::endpoint::tx::Response as TxResponse;
use cosmrs::rpc::query::Query;
use cosmrs::rpc::{self, HttpClient, Order};
use cosmrs::tendermint::abci::Code as AbciCode;
use cosmrs::tendermint::abci::Transaction;
use cosmrs::tendermint::{abci, block, chain};
use cosmrs::{tx, AccountId, Coin as CosmosCoin, Tx};
@@ -57,7 +57,7 @@ pub trait CosmWasmClient: rpc::Client {
&self,
path: Option<abci::Path>,
req: Req,
) -> Result<Res, NymdError>
) -> Result<Res, NyxdError>
where
Req: Message,
Res: Message + Default,
@@ -66,25 +66,21 @@ pub trait CosmWasmClient: rpc::Client {
req.encode(&mut buf)?;
let res = self.abci_query(path, buf, None, false).await?;
let res_success = nyxd::error::parse_abci_query_result(res)?;
match res.code {
AbciCode::Err(code) => return Err(NymdError::AbciError(code, res.log)),
AbciCode::Ok => (),
}
Ok(Res::decode(res.value.as_ref())?)
Ok(Res::decode(res_success.value.as_ref())?)
}
async fn get_chain_id(&self) -> Result<chain::Id, NymdError> {
async fn get_chain_id(&self) -> Result<chain::Id, NyxdError> {
Ok(self.status().await?.node_info.network)
}
async fn get_height(&self) -> Result<block::Height, NymdError> {
async fn get_height(&self) -> Result<block::Height, NyxdError> {
Ok(self.status().await?.sync_info.latest_block_height)
}
// TODO: the return type should probably be changed to a non-proto, type-safe Account alternative
async fn get_account(&self, address: &AccountId) -> Result<Option<Account>, NymdError> {
async fn get_account(&self, address: &AccountId) -> Result<Option<Account>, NyxdError> {
let path = Some("/cosmos.auth.v1beta1.Query/Account".parse().unwrap());
let req = QueryAccountRequest {
@@ -98,11 +94,11 @@ pub trait CosmWasmClient: rpc::Client {
res.account.map(TryFrom::try_from).transpose()
}
async fn get_sequence(&self, address: &AccountId) -> Result<SequenceResponse, NymdError> {
async fn get_sequence(&self, address: &AccountId) -> Result<SequenceResponse, NyxdError> {
let account = self
.get_account(address)
.await?
.ok_or_else(|| NymdError::NonExistentAccountError(address.clone()))?;
.ok_or_else(|| NyxdError::NonExistentAccountError(address.clone()))?;
let base_account = account.try_get_base_account()?;
Ok(SequenceResponse {
@@ -111,7 +107,7 @@ pub trait CosmWasmClient: rpc::Client {
})
}
async fn get_block(&self, height: Option<u32>) -> Result<BlockResponse, NymdError> {
async fn get_block(&self, height: Option<u32>) -> Result<BlockResponse, NyxdError> {
match height {
Some(height) => self.block(height).await.map_err(|err| err.into()),
None => self.latest_block().await.map_err(|err| err.into()),
@@ -122,7 +118,7 @@ pub trait CosmWasmClient: rpc::Client {
&self,
address: &AccountId,
search_denom: String,
) -> Result<Option<Coin>, NymdError> {
) -> Result<Option<Coin>, NyxdError> {
let path = Some("/cosmos.bank.v1beta1.Query/Balance".parse().unwrap());
let req = QueryBalanceRequest {
@@ -137,10 +133,10 @@ pub trait CosmWasmClient: rpc::Client {
res.balance
.map(|proto| CosmosCoin::try_from(proto).map(Into::into))
.transpose()
.map_err(|_| NymdError::SerializationError("Coin".to_owned()))
.map_err(|_| NyxdError::SerializationError("Coin".to_owned()))
}
async fn get_all_balances(&self, address: &AccountId) -> Result<Vec<Coin>, NymdError> {
async fn get_all_balances(&self, address: &AccountId) -> Result<Vec<Coin>, NyxdError> {
let path = Some("/cosmos.bank.v1beta1.Query/AllBalances".parse().unwrap());
let mut raw_balances = Vec::new();
@@ -168,10 +164,10 @@ pub trait CosmWasmClient: rpc::Client {
.into_iter()
.map(|proto| CosmosCoin::try_from(proto).map(Into::into))
.collect::<Result<_, _>>()
.map_err(|_| NymdError::SerializationError("Coins".to_owned()))
.map_err(|_| NyxdError::SerializationError("Coins".to_owned()))
}
async fn get_total_supply(&self) -> Result<Vec<Coin>, NymdError> {
async fn get_total_supply(&self) -> Result<Vec<Coin>, NyxdError> {
let path = Some("/cosmos.bank.v1beta1.Query/TotalSupply".parse().unwrap());
let mut supply = Vec::new();
@@ -196,14 +192,14 @@ pub trait CosmWasmClient: rpc::Client {
.into_iter()
.map(|proto| CosmosCoin::try_from(proto).map(Into::into))
.collect::<Result<_, _>>()
.map_err(|_| NymdError::SerializationError("Coins".to_owned()))
.map_err(|_| NyxdError::SerializationError("Coins".to_owned()))
}
async fn get_tx(&self, id: tx::Hash) -> Result<TxResponse, NymdError> {
async fn get_tx(&self, id: tx::Hash) -> Result<TxResponse, NyxdError> {
Ok(self.tx(id, false).await?)
}
async fn search_tx(&self, query: Query) -> Result<Vec<TxResponse>, NymdError> {
async fn search_tx(&self, query: Query) -> Result<Vec<TxResponse>, NyxdError> {
// according to https://docs.tendermint.com/master/rpc/#/Info/tx_search
// the maximum entries per page is 100 and the default is 30
// so let's attempt to use the maximum
@@ -238,7 +234,7 @@ pub trait CosmWasmClient: rpc::Client {
async fn broadcast_tx_async(
&self,
tx: Transaction,
) -> Result<broadcast::tx_async::Response, NymdError> {
) -> Result<broadcast::tx_async::Response, NyxdError> {
Ok(rpc::Client::broadcast_tx_async(self, tx).await?)
}
@@ -246,7 +242,7 @@ pub trait CosmWasmClient: rpc::Client {
async fn broadcast_tx_sync(
&self,
tx: Transaction,
) -> Result<broadcast::tx_sync::Response, NymdError> {
) -> Result<broadcast::tx_sync::Response, NyxdError> {
Ok(rpc::Client::broadcast_tx_sync(self, tx).await?)
}
@@ -254,16 +250,16 @@ pub trait CosmWasmClient: rpc::Client {
async fn broadcast_tx_commit(
&self,
tx: Transaction,
) -> Result<broadcast::tx_commit::Response, NymdError> {
) -> Result<broadcast::tx_commit::Response, NyxdError> {
Ok(rpc::Client::broadcast_tx_commit(self, tx).await?)
}
async fn broadcast_tx(&self, tx: Transaction) -> Result<TxResponse, NymdError> {
async fn broadcast_tx(&self, tx: Transaction) -> Result<TxResponse, NyxdError> {
let broadcasted = CosmWasmClient::broadcast_tx_sync(self, tx).await?;
if broadcasted.code.is_err() {
let code_val = broadcasted.code.value();
return Err(NymdError::BroadcastTxErrorDeliverTx {
return Err(NyxdError::BroadcastTxErrorDeliverTx {
hash: broadcasted.hash,
height: None,
code: code_val,
@@ -280,7 +276,7 @@ pub trait CosmWasmClient: rpc::Client {
broadcasted.hash
);
if tokio::time::Instant::now().duration_since(start) >= self.broadcast_timeout() {
return Err(NymdError::BroadcastTimeout {
return Err(NyxdError::BroadcastTimeout {
hash: tx_hash,
timeout: self.broadcast_timeout(),
});
@@ -294,7 +290,7 @@ pub trait CosmWasmClient: rpc::Client {
}
}
async fn get_codes(&self) -> Result<Vec<Code>, NymdError> {
async fn get_codes(&self) -> Result<Vec<Code>, NyxdError> {
let path = Some("/cosmwasm.wasm.v1.Query/Codes".parse().unwrap());
let mut raw_codes = Vec::new();
@@ -321,7 +317,7 @@ pub trait CosmWasmClient: rpc::Client {
.collect::<Result<_, _>>()
}
async fn get_code_details(&self, code_id: ContractCodeId) -> Result<CodeDetails, NymdError> {
async fn get_code_details(&self, code_id: ContractCodeId) -> Result<CodeDetails, NyxdError> {
let path = Some("/cosmwasm.wasm.v1.Query/Code".parse().unwrap());
let req = QueryCodeRequest { code_id };
@@ -333,10 +329,10 @@ pub trait CosmWasmClient: rpc::Client {
if let Some(code_info) = res.code_info {
Ok(CodeDetails::new(code_info.try_into()?, res.data))
} else {
Err(NymdError::NoCodeInformation(code_id))
Err(NyxdError::NoCodeInformation(code_id))
}
}
async fn get_contracts(&self, code_id: ContractCodeId) -> Result<Vec<AccountId>, NymdError> {
async fn get_contracts(&self, code_id: ContractCodeId) -> Result<Vec<AccountId>, NyxdError> {
let path = Some("/cosmwasm.wasm.v1.Query/ContractsByCode".parse().unwrap());
let mut raw_contracts = Vec::new();
@@ -364,10 +360,10 @@ pub trait CosmWasmClient: rpc::Client {
.iter()
.map(|raw| raw.parse())
.collect::<Result<_, _>>()
.map_err(|_| NymdError::DeserializationError("Contract addresses".to_owned()))
.map_err(|_| NyxdError::DeserializationError("Contract addresses".to_owned()))
}
async fn get_contract(&self, address: &AccountId) -> Result<Contract, NymdError> {
async fn get_contract(&self, address: &AccountId) -> Result<Contract, NyxdError> {
let path = Some("/cosmwasm.wasm.v1.Query/ContractInfo".parse().unwrap());
let req = QueryContractInfoRequest {
@@ -382,17 +378,17 @@ pub trait CosmWasmClient: rpc::Client {
if let Some(contract_info) = res.contract_info {
let address = response_address
.parse()
.map_err(|_| NymdError::MalformedAccountAddress(response_address))?;
.map_err(|_| NyxdError::MalformedAccountAddress(response_address))?;
Ok(Contract::new(address, contract_info.try_into()?))
} else {
Err(NymdError::NoContractInformation(address.clone()))
Err(NyxdError::NoContractInformation(address.clone()))
}
}
async fn get_contract_code_history(
&self,
address: &AccountId,
) -> Result<Vec<ContractCodeHistoryEntry>, NymdError> {
) -> Result<Vec<ContractCodeHistoryEntry>, NyxdError> {
let path = Some("/cosmwasm.wasm.v1.Query/ContractHistory".parse().unwrap());
let mut raw_entries = Vec::new();
@@ -426,7 +422,7 @@ pub trait CosmWasmClient: rpc::Client {
&self,
address: &AccountId,
query_data: Vec<u8>,
) -> Result<Vec<u8>, NymdError> {
) -> Result<Vec<u8>, NyxdError> {
let path = Some("/cosmwasm.wasm.v1.Query/RawContractState".parse().unwrap());
let req = QueryRawContractStateRequest {
@@ -445,7 +441,7 @@ pub trait CosmWasmClient: rpc::Client {
&self,
address: &AccountId,
query_msg: &M,
) -> Result<T, NymdError>
) -> Result<T, NyxdError>
where
M: ?Sized + Serialize + Sync,
for<'a> T: Deserialize<'a>,
@@ -482,7 +478,7 @@ pub trait CosmWasmClient: rpc::Client {
&self,
tx: Option<Tx>,
tx_bytes: Vec<u8>,
) -> Result<SimulateResponse, NymdError> {
) -> Result<SimulateResponse, NyxdError> {
let path = Some("/cosmos.tx.v1beta1.Service/Simulate".parse().unwrap());
let req = SimulateRequest {
@@ -1,7 +1,7 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::nymd::error::NymdError;
use crate::nyxd::error::NyxdError;
use cosmrs::proto::cosmos::base::query::v1beta1::{PageRequest, PageResponse};
use cosmrs::proto::cosmos::base::v1beta1::Coin as ProtoCoin;
use cosmrs::rpc::endpoint::broadcast;
@@ -11,13 +11,13 @@ use flate2::Compression;
use std::io::Write;
pub(crate) trait CheckResponse: Sized {
fn check_response(self) -> Result<Self, NymdError>;
fn check_response(self) -> Result<Self, NyxdError>;
}
impl CheckResponse for broadcast::tx_commit::Response {
fn check_response(self) -> Result<Self, NymdError> {
fn check_response(self) -> Result<Self, NyxdError> {
if self.check_tx.code.is_err() {
return Err(NymdError::BroadcastTxErrorCheckTx {
return Err(NyxdError::BroadcastTxErrorCheckTx {
hash: self.hash,
height: Some(self.height),
code: self.check_tx.code.value(),
@@ -26,7 +26,7 @@ impl CheckResponse for broadcast::tx_commit::Response {
}
if self.deliver_tx.code.is_err() {
return Err(NymdError::BroadcastTxErrorDeliverTx {
return Err(NyxdError::BroadcastTxErrorDeliverTx {
hash: self.hash,
height: Some(self.height),
code: self.deliver_tx.code.value(),
@@ -38,10 +38,10 @@ impl CheckResponse for broadcast::tx_commit::Response {
}
}
impl CheckResponse for crate::nymd::TxResponse {
fn check_response(self) -> Result<Self, NymdError> {
impl CheckResponse for crate::nyxd::TxResponse {
fn check_response(self) -> Result<Self, NyxdError> {
if self.tx_result.code.is_err() {
return Err(NymdError::BroadcastTxErrorDeliverTx {
return Err(NyxdError::BroadcastTxErrorDeliverTx {
hash: self.hash,
height: Some(self.height),
code: self.tx_result.code.value(),
@@ -53,13 +53,13 @@ impl CheckResponse for crate::nymd::TxResponse {
}
}
pub(crate) fn compress_wasm_code(code: &[u8]) -> Result<Vec<u8>, NymdError> {
pub(crate) fn compress_wasm_code(code: &[u8]) -> Result<Vec<u8>, NyxdError> {
// using compression level 9, same as cosmjs, that optimises for size
let mut encoder = GzEncoder::new(Vec::new(), Compression::best());
encoder
.write_all(code)
.map_err(NymdError::WasmCompressionError)?;
encoder.finish().map_err(NymdError::WasmCompressionError)
.map_err(NyxdError::WasmCompressionError)?;
encoder.finish().map_err(NyxdError::WasmCompressionError)
}
pub(crate) fn create_pagination(key: Vec<u8>) -> PageRequest {
@@ -84,11 +84,11 @@ pub(crate) fn next_page_key(pagination_info: Option<PageResponse>) -> Option<Vec
None
}
pub(crate) fn parse_proto_coin_vec(value: Vec<ProtoCoin>) -> Result<Vec<Coin>, NymdError> {
pub(crate) fn parse_proto_coin_vec(value: Vec<ProtoCoin>) -> Result<Vec<Coin>, NyxdError> {
value
.into_iter()
.map(|proto_coin| {
Coin::try_from(&proto_coin).map_err(|_| NymdError::MalformedCoin {
Coin::try_from(&proto_coin).map_err(|_| NyxdError::MalformedCoin {
coin_representation: format!("{:?}", proto_coin),
})
})
@@ -1,7 +1,7 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::nymd::error::NymdError;
use crate::nyxd::error::NyxdError;
use cosmrs::tendermint::abci;
use itertools::Itertools;
use serde::{Deserialize, Serialize};
@@ -39,17 +39,17 @@ pub fn find_attribute<'a>(
}
// those two functions were separated so that the internal logic could actually be tested
fn parse_raw_str_logs(raw: &str) -> Result<Vec<Log>, NymdError> {
let logs: Vec<Log> = serde_json::from_str(raw).map_err(|_| NymdError::MalformedLogString)?;
fn parse_raw_str_logs(raw: &str) -> Result<Vec<Log>, NyxdError> {
let logs: Vec<Log> = serde_json::from_str(raw).map_err(|_| NyxdError::MalformedLogString)?;
if logs.len() != logs.iter().unique_by(|log| log.msg_index).count() {
// this check is only here because I don't yet fully understand raw log string generation and
// the fact the first entry does not seem to have `msg_index` defined on it.
return Err(NymdError::MalformedLogString);
return Err(NyxdError::MalformedLogString);
}
Ok(logs)
}
pub fn parse_raw_logs(raw: abci::Log) -> Result<Vec<Log>, NymdError> {
pub fn parse_raw_logs(raw: abci::Log) -> Result<Vec<Log>, NyxdError> {
parse_raw_str_logs(raw.as_ref())
}
@@ -1,9 +1,9 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::nymd::error::NymdError;
use crate::nymd::wallet::DirectSecp256k1HdWallet;
use crate::nymd::GasPrice;
use crate::nyxd::error::NyxdError;
use crate::nyxd::wallet::DirectSecp256k1HdWallet;
use crate::nyxd::GasPrice;
use cosmrs::rpc::{Error as TendermintRpcError, HttpClient, HttpClientUrl};
use std::convert::TryInto;
@@ -13,7 +13,7 @@ pub mod logs;
pub mod signing_client;
pub mod types;
pub fn connect<U>(endpoint: U) -> Result<HttpClient, NymdError>
pub fn connect<U>(endpoint: U) -> Result<HttpClient, NyxdError>
where
U: TryInto<HttpClientUrl, Error = TendermintRpcError>,
{
@@ -25,7 +25,7 @@ pub fn connect_with_signer<U: Clone>(
endpoint: U,
signer: DirectSecp256k1HdWallet,
gas_price: GasPrice,
) -> Result<signing_client::Client, NymdError>
) -> Result<signing_client::Client, NyxdError>
where
U: TryInto<HttpClientUrl, Error = TendermintRpcError>,
{
@@ -1,14 +1,14 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::nymd::cosmwasm_client::client::CosmWasmClient;
use crate::nymd::cosmwasm_client::helpers::{compress_wasm_code, CheckResponse};
use crate::nymd::cosmwasm_client::logs::{self, parse_raw_logs};
use crate::nymd::cosmwasm_client::types::*;
use crate::nymd::error::NymdError;
use crate::nymd::fee::{Fee, DEFAULT_SIMULATED_GAS_MULTIPLIER};
use crate::nymd::wallet::DirectSecp256k1HdWallet;
use crate::nymd::{Coin, GasAdjustable, GasPrice, TxResponse};
use crate::nyxd::cosmwasm_client::client::CosmWasmClient;
use crate::nyxd::cosmwasm_client::helpers::{compress_wasm_code, CheckResponse};
use crate::nyxd::cosmwasm_client::logs::{self, parse_raw_logs};
use crate::nyxd::cosmwasm_client::types::*;
use crate::nyxd::error::NyxdError;
use crate::nyxd::fee::{Fee, DEFAULT_SIMULATED_GAS_MULTIPLIER};
use crate::nyxd::wallet::DirectSecp256k1HdWallet;
use crate::nyxd::{Coin, GasAdjustable, GasPrice, TxResponse};
use async_trait::async_trait;
use cosmrs::bank::MsgSend;
use cosmrs::distribution::MsgWithdrawDelegatorReward;
@@ -74,7 +74,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
signer_address: &AccountId,
messages: Vec<Any>,
memo: impl Into<String> + Send + 'static,
) -> Result<SimulateResponse, NymdError> {
) -> Result<SimulateResponse, NyxdError> {
let public_key = self.signer_public_key(signer_address);
let sequence_response = self.get_sequence(signer_address).await?;
@@ -102,7 +102,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
wasm_code: Vec<u8>,
fee: Fee,
memo: impl Into<String> + Send + 'static,
) -> Result<UploadResult, NymdError> {
) -> Result<UploadResult, NyxdError> {
let compressed = compress_wasm_code(&wasm_code)?;
let compressed_size = compressed.len();
let compressed_checksum = Sha256::digest(&compressed).to_vec();
@@ -115,7 +115,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
instantiate_permission: Default::default(),
}
.to_any()
.map_err(|_| NymdError::SerializationError("MsgStoreCode".to_owned()))?;
.map_err(|_| NyxdError::SerializationError("MsgStoreCode".to_owned()))?;
let tx_res = self
.sign_and_broadcast(sender_address, vec![upload_msg], fee, memo)
@@ -161,7 +161,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
fee: Fee,
memo: impl Into<String> + Send + 'static,
mut options: Option<InstantiateOptions>,
) -> Result<InstantiateResult, NymdError>
) -> Result<InstantiateResult, NyxdError>
where
M: ?Sized + Serialize + Sync,
{
@@ -176,7 +176,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
funds: options.map(|options| options.funds).unwrap_or_default(),
}
.to_any()
.map_err(|_| NymdError::SerializationError("MsgInstantiateContract".to_owned()))?;
.map_err(|_| NyxdError::SerializationError("MsgInstantiateContract".to_owned()))?;
let tx_res = self
.sign_and_broadcast(sender_address, vec![init_msg], fee, memo)
@@ -211,14 +211,14 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
new_admin: &AccountId,
fee: Fee,
memo: impl Into<String> + Send + 'static,
) -> Result<ChangeAdminResult, NymdError> {
) -> Result<ChangeAdminResult, NyxdError> {
let change_admin_msg = cosmwasm::MsgUpdateAdmin {
sender: sender_address.clone(),
new_admin: new_admin.clone(),
contract: contract_address.clone(),
}
.to_any()
.map_err(|_| NymdError::SerializationError("MsgUpdateAdmin".to_owned()))?;
.map_err(|_| NyxdError::SerializationError("MsgUpdateAdmin".to_owned()))?;
let tx_res = self
.sign_and_broadcast(sender_address, vec![change_admin_msg], fee, memo)
@@ -240,13 +240,13 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
contract_address: &AccountId,
fee: Fee,
memo: impl Into<String> + Send + 'static,
) -> Result<ChangeAdminResult, NymdError> {
) -> Result<ChangeAdminResult, NyxdError> {
let change_admin_msg = cosmwasm::MsgClearAdmin {
sender: sender_address.clone(),
contract: contract_address.clone(),
}
.to_any()
.map_err(|_| NymdError::SerializationError("MsgClearAdmin".to_owned()))?;
.map_err(|_| NyxdError::SerializationError("MsgClearAdmin".to_owned()))?;
let tx_res = self
.sign_and_broadcast(sender_address, vec![change_admin_msg], fee, memo)
@@ -270,7 +270,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
fee: Fee,
msg: &M,
memo: impl Into<String> + Send + 'static,
) -> Result<MigrateResult, NymdError>
) -> Result<MigrateResult, NyxdError>
where
M: ?Sized + Serialize + Sync,
{
@@ -281,7 +281,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
msg: serde_json::to_vec(msg)?,
}
.to_any()
.map_err(|_| NymdError::SerializationError("MsgMigrateContract".to_owned()))?;
.map_err(|_| NyxdError::SerializationError("MsgMigrateContract".to_owned()))?;
let tx_res = self
.sign_and_broadcast(sender_address, vec![migrate_msg], fee, memo)
@@ -305,7 +305,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
fee: Fee,
memo: impl Into<String> + Send + 'static,
funds: Vec<Coin>,
) -> Result<ExecuteResult, NymdError>
) -> Result<ExecuteResult, NyxdError>
where
M: ?Sized + Serialize + Sync,
{
@@ -316,7 +316,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
funds: funds.into_iter().map(Into::into).collect(),
}
.to_any()
.map_err(|_| NymdError::SerializationError("MsgExecuteContract".to_owned()))?;
.map_err(|_| NyxdError::SerializationError("MsgExecuteContract".to_owned()))?;
let tx_res = self
.sign_and_broadcast(sender_address, vec![execute_msg], fee, memo)
@@ -340,7 +340,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
msgs: I,
fee: Fee,
memo: impl Into<String> + Send + 'static,
) -> Result<ExecuteResult, NymdError>
) -> Result<ExecuteResult, NyxdError>
where
I: IntoIterator<Item = (M, Vec<Coin>)> + Send,
M: Serialize,
@@ -355,7 +355,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
funds: funds.into_iter().map(Into::into).collect(),
}
.to_any()
.map_err(|_| NymdError::SerializationError("MsgExecuteContract".to_owned()))
.map_err(|_| NyxdError::SerializationError("MsgExecuteContract".to_owned()))
})
.collect::<Result<_, _>>()?;
@@ -381,14 +381,14 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
amount: Vec<Coin>,
fee: Fee,
memo: impl Into<String> + Send + 'static,
) -> Result<TxResponse, NymdError> {
) -> Result<TxResponse, NyxdError> {
let send_msg = MsgSend {
from_address: sender_address.clone(),
to_address: recipient_address.clone(),
amount: amount.into_iter().map(Into::into).collect(),
}
.to_any()
.map_err(|_| NymdError::SerializationError("MsgSend".to_owned()))?;
.map_err(|_| NyxdError::SerializationError("MsgSend".to_owned()))?;
self.sign_and_broadcast(sender_address, vec![send_msg], fee, memo)
.await?
@@ -401,7 +401,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
msgs: I,
fee: Fee,
memo: impl Into<String> + Send + 'static,
) -> Result<TxResponse, NymdError>
) -> Result<TxResponse, NyxdError>
where
I: IntoIterator<Item = (AccountId, Vec<Coin>)> + Send,
{
@@ -414,7 +414,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
amount: amount.into_iter().map(Into::into).collect(),
}
.to_any()
.map_err(|_| NymdError::SerializationError("MsgExecuteContract".to_owned()))
.map_err(|_| NyxdError::SerializationError("MsgExecuteContract".to_owned()))
})
.collect::<Result<_, _>>()?;
@@ -433,20 +433,20 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
allowed_messages: Vec<String>,
fee: Fee,
memo: impl Into<String> + Send + 'static,
) -> Result<TxResponse, NymdError> {
) -> Result<TxResponse, NyxdError> {
let basic_allowance = BasicAllowance {
spend_limit: spend_limit.into_iter().map(Into::into).collect(),
expiration,
}
.to_any()
.map_err(|_| NymdError::SerializationError("BasicAllowance".to_owned()))?;
.map_err(|_| NyxdError::SerializationError("BasicAllowance".to_owned()))?;
let allowed_msg_allowance = AllowedMsgAllowance {
allowance: Some(basic_allowance),
allowed_messages,
}
.to_any()
.map_err(|_| NymdError::SerializationError("AllowedMsgAllowance".to_owned()))?;
.map_err(|_| NyxdError::SerializationError("AllowedMsgAllowance".to_owned()))?;
let grant_allowance_msg = MsgGrantAllowance {
granter: granter.to_owned(),
@@ -454,7 +454,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
allowance: Some(allowed_msg_allowance),
}
.to_any()
.map_err(|_| NymdError::SerializationError("MsgGrantAllowance".to_owned()))?;
.map_err(|_| NyxdError::SerializationError("MsgGrantAllowance".to_owned()))?;
self.sign_and_broadcast(granter, vec![grant_allowance_msg], fee, memo)
.await?
@@ -467,13 +467,13 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
grantee: &AccountId,
fee: Fee,
memo: impl Into<String> + Send + 'static,
) -> Result<TxResponse, NymdError> {
) -> Result<TxResponse, NyxdError> {
let revoke_allowance_msg = MsgRevokeAllowance {
granter: granter.to_owned(),
grantee: grantee.to_owned(),
}
.to_any()
.map_err(|_| NymdError::SerializationError("MsgRevokeAllowance".to_owned()))?;
.map_err(|_| NyxdError::SerializationError("MsgRevokeAllowance".to_owned()))?;
self.sign_and_broadcast(granter, vec![revoke_allowance_msg], fee, memo)
.await?
@@ -487,14 +487,14 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
amount: Coin,
fee: Fee,
memo: impl Into<String> + Send + 'static,
) -> Result<TxResponse, NymdError> {
) -> Result<TxResponse, NyxdError> {
let delegate_msg = MsgDelegate {
delegator_address: delegator_address.to_owned(),
validator_address: validator_address.to_owned(),
amount: amount.into(),
}
.to_any()
.map_err(|_| NymdError::SerializationError("MsgDelegate".to_owned()))?;
.map_err(|_| NyxdError::SerializationError("MsgDelegate".to_owned()))?;
self.sign_and_broadcast(delegator_address, vec![delegate_msg], fee, memo)
.await?
@@ -508,14 +508,14 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
amount: Coin,
fee: Fee,
memo: impl Into<String> + Send + 'static,
) -> Result<TxResponse, NymdError> {
) -> Result<TxResponse, NyxdError> {
let undelegate_msg = MsgUndelegate {
delegator_address: delegator_address.to_owned(),
validator_address: validator_address.to_owned(),
amount: amount.into(),
}
.to_any()
.map_err(|_| NymdError::SerializationError("MsgUndelegate".to_owned()))?;
.map_err(|_| NyxdError::SerializationError("MsgUndelegate".to_owned()))?;
self.sign_and_broadcast(delegator_address, vec![undelegate_msg], fee, memo)
.await?
@@ -528,13 +528,13 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
validator_address: &AccountId,
fee: Fee,
memo: impl Into<String> + Send + 'static,
) -> Result<TxResponse, NymdError> {
) -> Result<TxResponse, NyxdError> {
let withdraw_msg = MsgWithdrawDelegatorReward {
delegator_address: delegator_address.to_owned(),
validator_address: validator_address.to_owned(),
}
.to_any()
.map_err(|_| NymdError::SerializationError("MsgWithdrawDelegatorReward".to_owned()))?;
.map_err(|_| NyxdError::SerializationError("MsgWithdrawDelegatorReward".to_owned()))?;
self.sign_and_broadcast(delegator_address, vec![withdraw_msg], fee, memo)
.await?
@@ -549,7 +549,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
messages: &[Any],
fee: Fee,
memo: &String,
) -> Result<tx::Fee, NymdError> {
) -> Result<tx::Fee, NyxdError> {
let auto_fee = |multiplier: Option<f32>| async move {
debug!("Trying to simulate gas costs...");
// from what I've seen in manual testing, gas estimation does not exist if transaction
@@ -558,7 +558,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
.simulate(signer_address, messages.to_vec(), memo.clone())
.await?
.gas_info
.ok_or(NymdError::GasEstimationFailure)?
.ok_or(NyxdError::GasEstimationFailure)?
.gas_used;
let multiplier = multiplier.unwrap_or(DEFAULT_SIMULATED_GAS_MULTIPLIER);
@@ -569,7 +569,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
debug!("Final gas limit used: {}", gas);
let fee = self.gas_price() * gas;
Ok::<tx::Fee, NymdError>(tx::Fee::from_amount_and_gas(fee, gas))
Ok::<tx::Fee, NyxdError>(tx::Fee::from_amount_and_gas(fee, gas))
};
let fee = match fee {
Fee::Manual(fee) => fee,
@@ -592,7 +592,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
messages: Vec<Any>,
fee: Fee,
memo: impl Into<String> + Send + 'static,
) -> Result<broadcast::tx_async::Response, NymdError> {
) -> Result<broadcast::tx_async::Response, NyxdError> {
let memo = memo.into();
let fee = self
.determine_transaction_fee(signer_address, &messages, fee, &memo)
@@ -600,7 +600,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
let tx_raw = self.sign(signer_address, messages, fee, memo).await?;
let tx_bytes = tx_raw
.to_bytes()
.map_err(|_| NymdError::SerializationError("Tx".to_owned()))?;
.map_err(|_| NyxdError::SerializationError("Tx".to_owned()))?;
CosmWasmClient::broadcast_tx_async(self, tx_bytes.into()).await
}
@@ -612,7 +612,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
messages: Vec<Any>,
fee: Fee,
memo: impl Into<String> + Send + 'static,
) -> Result<broadcast::tx_sync::Response, NymdError> {
) -> Result<broadcast::tx_sync::Response, NyxdError> {
let memo = memo.into();
let fee = self
.determine_transaction_fee(signer_address, &messages, fee, &memo)
@@ -620,7 +620,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
let tx_raw = self.sign(signer_address, messages, fee, memo).await?;
let tx_bytes = tx_raw
.to_bytes()
.map_err(|_| NymdError::SerializationError("Tx".to_owned()))?;
.map_err(|_| NyxdError::SerializationError("Tx".to_owned()))?;
CosmWasmClient::broadcast_tx_sync(self, tx_bytes.into()).await
}
@@ -632,7 +632,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
messages: Vec<Any>,
fee: Fee,
memo: impl Into<String> + Send + 'static,
) -> Result<broadcast::tx_commit::Response, NymdError> {
) -> Result<broadcast::tx_commit::Response, NyxdError> {
let memo = memo.into();
let fee = self
.determine_transaction_fee(signer_address, &messages, fee, &memo)
@@ -641,7 +641,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
let tx_raw = self.sign(signer_address, messages, fee, memo).await?;
let tx_bytes = tx_raw
.to_bytes()
.map_err(|_| NymdError::SerializationError("Tx".to_owned()))?;
.map_err(|_| NyxdError::SerializationError("Tx".to_owned()))?;
CosmWasmClient::broadcast_tx_commit(self, tx_bytes.into()).await
}
@@ -653,7 +653,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
messages: Vec<Any>,
fee: Fee,
memo: impl Into<String> + Send + 'static,
) -> Result<TxResponse, NymdError> {
) -> Result<TxResponse, NyxdError> {
let memo = memo.into();
let fee = self
.determine_transaction_fee(signer_address, &messages, fee, &memo)
@@ -662,7 +662,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
let tx_raw = self.sign(signer_address, messages, fee, memo).await?;
let tx_bytes = tx_raw
.to_bytes()
.map_err(|_| NymdError::SerializationError("Tx".to_owned()))?;
.map_err(|_| NyxdError::SerializationError("Tx".to_owned()))?;
self.broadcast_tx(tx_bytes.into()).await
}
@@ -674,12 +674,12 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
fee: tx::Fee,
memo: impl Into<String> + Send + 'static,
signer_data: SignerData,
) -> Result<tx::Raw, NymdError> {
) -> Result<tx::Raw, NyxdError> {
let signer_accounts = self.signer().try_derive_accounts()?;
let account_from_signer = signer_accounts
.iter()
.find(|account| &account.address == signer_address)
.ok_or_else(|| NymdError::SigningAccountNotFound(signer_address.clone()))?;
.ok_or_else(|| NyxdError::SigningAccountNotFound(signer_address.clone()))?;
// TODO: WTF HOW IS TIMEOUT_HEIGHT SUPPOSED TO GET DETERMINED?
// IT DOESNT EXIST IN COSMJS!!
@@ -691,7 +691,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
SignerInfo::single_direct(Some(account_from_signer.public_key), signer_data.sequence);
let auth_info = signer_info.auth_info(fee);
// ideally I'd prefer to have the entire error put into the NymdError::SigningFailure
// ideally I'd prefer to have the entire error put into the NyxdError::SigningFailure
// but I'm super hesitant to trying to downcast the eyre::Report to cosmrs::error::Error
let sign_doc = SignDoc::new(
&tx_body,
@@ -699,7 +699,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
&signer_data.chain_id,
signer_data.account_number,
)
.map_err(|_| NymdError::SigningFailure)?;
.map_err(|_| NyxdError::SigningFailure)?;
self.signer()
.sign_direct_with_account(account_from_signer, sign_doc)
@@ -711,7 +711,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
messages: Vec<Any>,
fee: tx::Fee,
memo: impl Into<String> + Send + 'static,
) -> Result<tx::Raw, NymdError> {
) -> Result<tx::Raw, NyxdError> {
// TODO: Future optimisation: rather than grabbing current account_number and sequence
// on every sign request -> just keep them cached on the struct and increment as required
let sequence_response = self.get_sequence(signer_address).await?;
@@ -742,7 +742,7 @@ impl Client {
endpoint: U,
signer: DirectSecp256k1HdWallet,
gas_price: GasPrice,
) -> Result<Self, NymdError>
) -> Result<Self, NyxdError>
where
U: TryInto<HttpClientUrl, Error = TendermintRpcError>,
{
@@ -3,9 +3,9 @@
// TODO: There's a significant argument to pull those out of the package and make a PR on https://github.com/cosmos/cosmos-rust/
use crate::nymd::cosmwasm_client::helpers::parse_proto_coin_vec;
use crate::nymd::cosmwasm_client::logs::Log;
use crate::nymd::error::NymdError;
use crate::nyxd::cosmwasm_client::helpers::parse_proto_coin_vec;
use crate::nyxd::cosmwasm_client::logs::Log;
use crate::nyxd::error::NyxdError;
use cosmrs::crypto::PublicKey;
use cosmrs::proto::cosmos::auth::v1beta1::{
BaseAccount as ProtoBaseAccount, ModuleAccount as ProtoModuleAccount,
@@ -57,19 +57,19 @@ pub struct BaseAccount {
}
impl TryFrom<ProtoBaseAccount> for BaseAccount {
type Error = NymdError;
type Error = NyxdError;
fn try_from(value: ProtoBaseAccount) -> Result<Self, Self::Error> {
let address: AccountId = value
.address
.parse()
.map_err(|_| NymdError::MalformedAccountAddress(value.address.clone()))?;
.map_err(|_| NyxdError::MalformedAccountAddress(value.address.clone()))?;
let pubkey = value
.pub_key
.map(PublicKey::try_from)
.transpose()
.map_err(|_| NymdError::InvalidPublicKey(address.clone()))?;
.map_err(|_| NyxdError::InvalidPublicKey(address.clone()))?;
Ok(BaseAccount {
address,
@@ -89,7 +89,7 @@ pub struct ModuleAccount {
}
impl TryFrom<ProtoModuleAccount> for ModuleAccount {
type Error = NymdError;
type Error = NyxdError;
fn try_from(value: ProtoModuleAccount) -> Result<Self, Self::Error> {
let base_account = value.base_account.map(TryFrom::try_from).transpose()?;
@@ -114,7 +114,7 @@ pub struct BaseVestingAccount {
}
impl TryFrom<ProtoBaseVestingAccount> for BaseVestingAccount {
type Error = NymdError;
type Error = NyxdError;
fn try_from(value: ProtoBaseVestingAccount) -> Result<Self, Self::Error> {
let base_account = value.base_account.map(TryFrom::try_from).transpose()?;
@@ -142,7 +142,7 @@ pub struct ContinuousVestingAccount {
}
impl TryFrom<ProtoContinuousVestingAccount> for ContinuousVestingAccount {
type Error = NymdError;
type Error = NyxdError;
fn try_from(value: ProtoContinuousVestingAccount) -> Result<Self, Self::Error> {
let base_vesting_account = value
@@ -166,7 +166,7 @@ pub struct DelayedVestingAccount {
}
impl TryFrom<ProtoDelayedVestingAccount> for DelayedVestingAccount {
type Error = NymdError;
type Error = NyxdError;
fn try_from(value: ProtoDelayedVestingAccount) -> Result<Self, Self::Error> {
let base_vesting_account = value
@@ -188,7 +188,7 @@ pub struct Period {
}
impl TryFrom<ProtoPeriod> for Period {
type Error = NymdError;
type Error = NyxdError;
fn try_from(value: ProtoPeriod) -> Result<Self, Self::Error> {
Ok(Period {
@@ -208,7 +208,7 @@ pub struct PeriodicVestingAccount {
}
impl TryFrom<ProtoPeriodicVestingAccount> for PeriodicVestingAccount {
type Error = NymdError;
type Error = NyxdError;
fn try_from(value: ProtoPeriodicVestingAccount) -> Result<Self, Self::Error> {
let base_vesting_account = value
@@ -239,7 +239,7 @@ pub struct PermanentLockedAccount {
}
impl TryFrom<ProtoPermanentLockedAccount> for PermanentLockedAccount {
type Error = NymdError;
type Error = NyxdError;
fn try_from(value: ProtoPermanentLockedAccount) -> Result<Self, Self::Error> {
let base_vesting_account = value
@@ -265,43 +265,43 @@ pub enum Account {
}
impl Account {
pub fn try_get_base_account(&self) -> Result<&BaseAccount, NymdError> {
pub fn try_get_base_account(&self) -> Result<&BaseAccount, NyxdError> {
match self {
Account::Base(acc) => Ok(acc),
Account::Module(acc) => acc
.base_account
.as_ref()
.ok_or(NymdError::NoBaseAccountInformationAvailable),
.ok_or(NyxdError::NoBaseAccountInformationAvailable),
Account::BaseVesting(acc) => acc
.base_account
.as_ref()
.ok_or(NymdError::NoBaseAccountInformationAvailable),
.ok_or(NyxdError::NoBaseAccountInformationAvailable),
Account::ContinuousVesting(acc) => acc
.base_vesting_account
.as_ref()
.and_then(|vesting_acc| vesting_acc.base_account.as_ref())
.ok_or(NymdError::NoBaseAccountInformationAvailable),
.ok_or(NyxdError::NoBaseAccountInformationAvailable),
Account::DelayedVesting(acc) => acc
.base_vesting_account
.as_ref()
.and_then(|vesting_acc| vesting_acc.base_account.as_ref())
.ok_or(NymdError::NoBaseAccountInformationAvailable),
.ok_or(NyxdError::NoBaseAccountInformationAvailable),
Account::PeriodicVesting(acc) => acc
.base_vesting_account
.as_ref()
.and_then(|vesting_acc| vesting_acc.base_account.as_ref())
.ok_or(NymdError::NoBaseAccountInformationAvailable),
.ok_or(NyxdError::NoBaseAccountInformationAvailable),
Account::PermanentLockedVesting(acc) => acc
.base_vesting_account
.as_ref()
.and_then(|vesting_acc| vesting_acc.base_account.as_ref())
.ok_or(NymdError::NoBaseAccountInformationAvailable),
.ok_or(NyxdError::NoBaseAccountInformationAvailable),
}
}
}
impl TryFrom<Any> for Account {
type Error = NymdError;
type Error = NyxdError;
fn try_from(raw_account: Any) -> Result<Self, Self::Error> {
match raw_account.type_url.as_ref() {
@@ -328,7 +328,7 @@ impl TryFrom<Any> for Account {
ProtoPermanentLockedAccount::decode(raw_account.value.as_ref())?.try_into()?,
))
}
_ => Err(NymdError::UnsupportedAccountType {
_ => Err(NyxdError::UnsupportedAccountType {
type_url: raw_account.type_url,
}),
}
@@ -347,7 +347,7 @@ pub struct Code {
}
impl TryFrom<CodeInfoResponse> for Code {
type Error = NymdError;
type Error = NyxdError;
fn try_from(value: CodeInfoResponse) -> Result<Self, Self::Error> {
let CodeInfoResponse {
@@ -358,7 +358,7 @@ impl TryFrom<CodeInfoResponse> for Code {
let creator = creator
.parse()
.map_err(|_| NymdError::MalformedAccountAddress(creator))?;
.map_err(|_| NyxdError::MalformedAccountAddress(creator))?;
Ok(Code {
code_id,
@@ -391,7 +391,7 @@ pub(crate) struct ContractInfo {
}
impl TryFrom<ProtoContractInfo> for ContractInfo {
type Error = NymdError;
type Error = NyxdError;
fn try_from(value: ProtoContractInfo) -> Result<Self, Self::Error> {
let ProtoContractInfo {
@@ -408,7 +408,7 @@ impl TryFrom<ProtoContractInfo> for ContractInfo {
Some(
admin
.parse()
.map_err(|_| NymdError::MalformedAccountAddress(admin))?,
.map_err(|_| NyxdError::MalformedAccountAddress(admin))?,
)
};
@@ -416,7 +416,7 @@ impl TryFrom<ProtoContractInfo> for ContractInfo {
code_id,
creator: creator
.parse()
.map_err(|_| NymdError::MalformedAccountAddress(creator))?,
.map_err(|_| NyxdError::MalformedAccountAddress(creator))?,
admin,
label,
})
@@ -466,14 +466,14 @@ pub struct ContractCodeHistoryEntry {
}
impl TryFrom<ProtoContractCodeHistoryEntry> for ContractCodeHistoryEntry {
type Error = NymdError;
type Error = NyxdError;
fn try_from(value: ProtoContractCodeHistoryEntry) -> Result<Self, Self::Error> {
let operation = match ContractCodeHistoryOperationType::from_i32(value.operation)
.ok_or(NymdError::InvalidContractHistoryOperation)?
.ok_or(NyxdError::InvalidContractHistoryOperation)?
{
ContractCodeHistoryOperationType::Unspecified => {
return Err(NymdError::InvalidContractHistoryOperation)
return Err(NyxdError::InvalidContractHistoryOperation)
}
ContractCodeHistoryOperationType::Init => ContractCodeHistoryEntryOperation::Init,
ContractCodeHistoryOperationType::Genesis => ContractCodeHistoryEntryOperation::Genesis,
@@ -484,7 +484,7 @@ impl TryFrom<ProtoContractCodeHistoryEntry> for ContractCodeHistoryEntry {
operation,
code_id: value.code_id,
msg_json: String::from_utf8(value.msg)
.map_err(|_| NymdError::DeserializationError("Contract history msg".to_owned()))?,
.map_err(|_| NyxdError::DeserializationError("Contract history msg".to_owned()))?,
})
}
}
@@ -532,7 +532,7 @@ pub struct AbciResult {
}
impl TryFrom<ProtoAbciResult> for AbciResult {
type Error = NymdError;
type Error = NyxdError;
fn try_from(value: ProtoAbciResult) -> Result<Self, Self::Error> {
let mut events = Vec::with_capacity(value.events.len());
@@ -543,9 +543,9 @@ impl TryFrom<ProtoAbciResult> for AbciResult {
let mut attributes = Vec::with_capacity(proto_event.attributes.len());
for proto_attribute in proto_event.attributes.into_iter() {
let stringified_ked = String::from_utf8(proto_attribute.key)
.map_err(|_| NymdError::DeserializationError("EventAttributeKey".to_owned()))?;
.map_err(|_| NyxdError::DeserializationError("EventAttributeKey".to_owned()))?;
let stringified_value = String::from_utf8(proto_attribute.value)
.map_err(|_| NymdError::DeserializationError("EventAttributeKey".to_owned()))?;
.map_err(|_| NyxdError::DeserializationError("EventAttributeKey".to_owned()))?;
attributes.push(abci::tag::Tag {
key: stringified_ked.parse().unwrap(),
@@ -574,7 +574,7 @@ pub struct SimulateResponse {
}
impl TryFrom<ProtoSimulateResponse> for SimulateResponse {
type Error = NymdError;
type Error = NyxdError;
fn try_from(value: ProtoSimulateResponse) -> Result<Self, Self::Error> {
Ok(SimulateResponse {
@@ -1,20 +1,27 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::nymd::cosmwasm_client::types::ContractCodeId;
use cosmrs::tendermint::{abci, block};
use cosmrs::{bip32, tx, AccountId};
use std::io;
use std::time::Duration;
use crate::nyxd::cosmwasm_client::types::ContractCodeId;
use cosmrs::{
bip32,
rpc::endpoint::abci_query::AbciQuery,
tendermint::{
abci::{self, Code as AbciCode},
block,
},
tx, AccountId,
};
use thiserror::Error;
pub use cosmrs::rpc::error::{
Error as TendermintRpcError, ErrorDetail as TendermintRpcErrorDetail,
use std::{io, time::Duration};
pub use cosmrs::rpc::{
error::{Error as TendermintRpcError, ErrorDetail as TendermintRpcErrorDetail},
response_error::{Code, ResponseError},
};
pub use cosmrs::rpc::response_error::{Code, ResponseError};
#[derive(Debug, Error)]
pub enum NymdError {
pub enum NyxdError {
#[error("No contract address is available to perform the call")]
NoContractAddressAvailable,
@@ -110,8 +117,12 @@ pub enum NymdError {
#[error("Failed to estimate gas price for the transaction")]
GasEstimationFailure,
#[error("Abci query failed with code {0} - {1}")]
AbciError(u32, abci::Log),
#[error("Abci query failed with code {code} - {log}")]
AbciError {
code: u32,
log: abci::Log,
pretty_log: Option<String>,
},
#[error("Unsupported account type: {type_url}")]
UnsupportedAccountType { type_url: String },
@@ -135,10 +146,36 @@ pub enum NymdError {
UnexpectedBech32Prefix { got: String, expected: String },
}
impl NymdError {
// The purpose of parsing the abci query result is that we want to generate the `pretty_log` if
// possible.
pub fn parse_abci_query_result(query_result: AbciQuery) -> Result<AbciQuery, NyxdError> {
match query_result.code {
AbciCode::Ok => Ok(query_result),
AbciCode::Err(code) => Err(NyxdError::AbciError {
code,
log: query_result.log.clone(),
pretty_log: try_parse_abci_log(&query_result.log),
}),
}
}
// Some of the error strings returned by the query are a bit too technical to present to the
// enduser. So we special case some commonly encountered errors.
fn try_parse_abci_log(log: &abci::Log) -> Option<String> {
if log
.value()
.contains("Maximum amount of locked coins has already been pledged")
{
Some("Maximum amount of locked tokens has alredy been used. You can only use up to 10% of your locked tokens for bonding and delegating.".to_string())
} else {
None
}
}
impl NyxdError {
pub fn is_tendermint_response_timeout(&self) -> bool {
match &self {
NymdError::TendermintError(TendermintRpcError(
NyxdError::TendermintError(TendermintRpcError(
TendermintRpcErrorDetail::Response(err),
_,
)) => {
@@ -165,7 +202,7 @@ impl NymdError {
pub fn is_tendermint_response_duplicate(&self) -> bool {
match &self {
NymdError::TendermintError(TendermintRpcError(
NyxdError::TendermintError(TendermintRpcError(
TendermintRpcErrorDetail::Response(err),
_,
)) => {
@@ -1,7 +1,7 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::nymd::error::NymdError;
use crate::nyxd::error::NyxdError;
use config::defaults;
use cosmrs::tx::Gas;
use cosmrs::Coin;
@@ -55,7 +55,7 @@ impl<'a> Mul<Gas> for &'a GasPrice {
}
impl FromStr for GasPrice {
type Err = NymdError;
type Err = NyxdError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let possible_amount = s
@@ -65,7 +65,7 @@ impl FromStr for GasPrice {
let amount_len = possible_amount.len();
let amount = possible_amount
.parse()
.map_err(|_| NymdError::MalformedGasPrice)?;
.map_err(|_| NyxdError::MalformedGasPrice)?;
let possible_denom = s.chars().skip(amount_len).collect::<String>();
let denom = possible_denom.trim().to_string();
@@ -74,7 +74,7 @@ impl FromStr for GasPrice {
}
impl GasPrice {
pub fn new_with_default_price(denom: &str) -> Result<Self, NymdError> {
pub fn new_with_default_price(denom: &str) -> Result<Self, NyxdError> {
format!("{}{}", defaults::GAS_PRICE_AMOUNT, denom).parse()
}
}
@@ -1,8 +1,8 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::nymd::Coin;
use crate::nymd::Gas;
use crate::nyxd::Coin;
use crate::nyxd::Gas;
use cosmrs::{tx, AccountId};
use serde::{Deserialize, Serialize};
use std::fmt::{Display, Formatter};
@@ -1,14 +1,14 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::nymd::cosmwasm_client::signing_client;
use crate::nymd::cosmwasm_client::types::{
use crate::nyxd::cosmwasm_client::signing_client;
use crate::nyxd::cosmwasm_client::types::{
Account, ChangeAdminResult, ContractCodeId, ExecuteResult, InstantiateOptions,
InstantiateResult, MigrateResult, SequenceResponse, SimulateResponse, UploadResult,
};
use crate::nymd::error::NymdError;
use crate::nymd::fee::DEFAULT_SIMULATED_GAS_MULTIPLIER;
use crate::nymd::wallet::DirectSecp256k1HdWallet;
use crate::nyxd::error::NyxdError;
use crate::nyxd::fee::DEFAULT_SIMULATED_GAS_MULTIPLIER;
use crate::nyxd::wallet::DirectSecp256k1HdWallet;
use cosmrs::cosmwasm;
use cosmrs::rpc::endpoint::block::Response as BlockResponse;
use cosmrs::rpc::query::Query;
@@ -16,20 +16,21 @@ use cosmrs::rpc::Error as TendermintRpcError;
use cosmrs::rpc::HttpClientUrl;
use cosmrs::tx::Msg;
use execute::execute;
use log::debug;
use network_defaults::{ChainDetails, NymNetworkDetails};
use serde::{Deserialize, Serialize};
use std::convert::TryInto;
use std::time::SystemTime;
use vesting_contract_common::ExecuteMsg as VestingExecuteMsg;
pub use crate::nymd::cosmwasm_client::client::CosmWasmClient;
pub use crate::nymd::cosmwasm_client::signing_client::SigningCosmWasmClient;
pub use crate::nymd::fee::Fee;
pub use crate::nyxd::cosmwasm_client::client::CosmWasmClient;
pub use crate::nyxd::cosmwasm_client::signing_client::SigningCosmWasmClient;
pub use crate::nyxd::fee::Fee;
pub use coin::Coin;
pub use cosmrs::bank::MsgSend;
pub use cosmrs::rpc::endpoint::tx::Response as TxResponse;
pub use cosmrs::rpc::endpoint::validators::Response as ValidatorResponse;
pub use cosmrs::rpc::HttpClient as QueryNymdClient;
pub use cosmrs::rpc::HttpClient as QueryNyxdClient;
pub use cosmrs::rpc::Paging;
pub use cosmrs::tendermint::abci::responses::{DeliverTx, Event};
pub use cosmrs::tendermint::abci::tag::Tag;
@@ -43,7 +44,7 @@ pub use cosmrs::{bip32, AccountId, Decimal, Denom};
pub use cosmwasm_std::Coin as CosmWasmCoin;
pub use fee::{gas_price::GasPrice, GasAdjustable, GasAdjustment};
use mixnet_contract_common::MixId;
pub use signing_client::Client as SigningNymdClient;
pub use signing_client::Client as SigningNyxdClient;
pub use traits::{VestingQueryClient, VestingSigningClient};
use vesting_contract_common::PledgeCap;
@@ -74,13 +75,16 @@ impl Config {
fn parse_optional_account(
raw: Option<&String>,
expected_prefix: &str,
) -> Result<Option<AccountId>, NymdError> {
) -> Result<Option<AccountId>, NyxdError> {
if let Some(address) = raw {
debug!("Raw address:{:?}", raw);
debug!("Expected prefix:{:?}", expected_prefix);
let parsed: AccountId = address
.parse()
.map_err(|_| NymdError::MalformedAccountAddress(address.clone()))?;
.map_err(|_| NyxdError::MalformedAccountAddress(address.clone()))?;
debug!("Parsed prefix:{:?}", parsed);
if parsed.prefix() != expected_prefix {
Err(NymdError::UnexpectedBech32Prefix {
Err(NyxdError::UnexpectedBech32Prefix {
got: parsed.prefix().into(),
expected: expected_prefix.into(),
})
@@ -92,7 +96,7 @@ impl Config {
}
}
pub fn try_from_nym_network_details(details: &NymNetworkDetails) -> Result<Self, NymdError> {
pub fn try_from_nym_network_details(details: &NymNetworkDetails) -> Result<Self, NyxdError> {
let prefix = &details.chain_details.bech32_account_prefix;
Ok(Config {
chain_details: details.chain_details.clone(),
@@ -128,20 +132,20 @@ impl Config {
}
#[derive(Debug)]
pub struct NymdClient<C> {
pub struct NyxdClient<C> {
client: C,
config: Config,
client_address: Option<Vec<AccountId>>,
simulated_gas_multiplier: f32,
}
impl NymdClient<QueryNymdClient> {
pub fn connect<U>(config: Config, endpoint: U) -> Result<NymdClient<QueryNymdClient>, NymdError>
impl NyxdClient<QueryNyxdClient> {
pub fn connect<U>(config: Config, endpoint: U) -> Result<NyxdClient<QueryNyxdClient>, NyxdError>
where
U: TryInto<HttpClientUrl, Error = TendermintRpcError>,
{
Ok(NymdClient {
client: QueryNymdClient::new(endpoint)?,
Ok(NyxdClient {
client: QueryNyxdClient::new(endpoint)?,
config,
client_address: None,
simulated_gas_multiplier: DEFAULT_SIMULATED_GAS_MULTIPLIER,
@@ -149,7 +153,7 @@ impl NymdClient<QueryNymdClient> {
}
}
impl NymdClient<SigningNymdClient> {
impl NyxdClient<SigningNyxdClient> {
// maybe the wallet could be made into a generic, but for now, let's just have this one implementation
pub fn connect_with_signer<U: Clone>(
config: Config,
@@ -157,7 +161,7 @@ impl NymdClient<SigningNymdClient> {
endpoint: U,
signer: DirectSecp256k1HdWallet,
gas_price: Option<GasPrice>,
) -> Result<NymdClient<SigningNymdClient>, NymdError>
) -> Result<NyxdClient<SigningNyxdClient>, NyxdError>
where
U: TryInto<HttpClientUrl, Error = TendermintRpcError>,
{
@@ -169,8 +173,8 @@ impl NymdClient<SigningNymdClient> {
.collect();
let gas_price = gas_price.unwrap_or(GasPrice::new_with_default_price(&denom)?);
Ok(NymdClient {
client: SigningNymdClient::connect_with_signer(endpoint, signer, gas_price)?,
Ok(NyxdClient {
client: SigningNyxdClient::connect_with_signer(endpoint, signer, gas_price)?,
config,
client_address: Some(client_address),
simulated_gas_multiplier: DEFAULT_SIMULATED_GAS_MULTIPLIER,
@@ -182,7 +186,7 @@ impl NymdClient<SigningNymdClient> {
endpoint: U,
mnemonic: bip39::Mnemonic,
gas_price: Option<GasPrice>,
) -> Result<NymdClient<SigningNymdClient>, NymdError>
) -> Result<NyxdClient<SigningNyxdClient>, NyxdError>
where
U: TryInto<HttpClientUrl, Error = TendermintRpcError>,
{
@@ -196,8 +200,8 @@ impl NymdClient<SigningNymdClient> {
.collect();
let gas_price = gas_price.unwrap_or(GasPrice::new_with_default_price(denom)?);
Ok(NymdClient {
client: SigningNymdClient::connect_with_signer(endpoint, wallet, gas_price)?,
Ok(NyxdClient {
client: SigningNyxdClient::connect_with_signer(endpoint, wallet, gas_price)?,
config,
client_address: Some(client_address),
simulated_gas_multiplier: DEFAULT_SIMULATED_GAS_MULTIPLIER,
@@ -205,7 +209,7 @@ impl NymdClient<SigningNymdClient> {
}
}
impl<C> NymdClient<C> {
impl<C> NyxdClient<C> {
pub fn current_config(&self) -> &Config {
&self.config
}
@@ -234,7 +238,7 @@ impl<C> NymdClient<C> {
self.config.multisig_contract_address = Some(address);
}
// TODO: this should get changed into Result<&AccountId, NymdError> (or Option<&AccountId> in future commits
// TODO: this should get changed into Result<&AccountId, NyxdError> (or Option<&AccountId> in future commits
// note: what unwrap is doing here is just moving a failure that would have normally
// occurred in `connect` when attempting to parse an empty address,
// so it's not introducing new source of failure (just moves it)
@@ -242,7 +246,7 @@ impl<C> NymdClient<C> {
self.config.mixnet_contract_address.as_ref().unwrap()
}
// TODO: this should get changed into Result<&AccountId, NymdError> (or Option<&AccountId> in future commits
// TODO: this should get changed into Result<&AccountId, NyxdError> (or Option<&AccountId> in future commits
// note: what unwrap is doing here is just moving a failure that would have normally
// occurred in `connect` when attempting to parse an empty address,
// so it's not introducing new source of failure (just moves it)
@@ -250,7 +254,7 @@ impl<C> NymdClient<C> {
self.config.vesting_contract_address.as_ref().unwrap()
}
// TODO: this should get changed into Result<&AccountId, NymdError> (or Option<&AccountId> in future commits
// TODO: this should get changed into Result<&AccountId, NyxdError> (or Option<&AccountId> in future commits
// note: what unwrap is doing here is just moving a failure that would have normally
// occurred in `connect` when attempting to parse an empty address,
// so it's not introducing new source of failure (just moves it)
@@ -261,7 +265,7 @@ impl<C> NymdClient<C> {
.unwrap()
}
// TODO: this should get changed into Result<&AccountId, NymdError> (or Option<&AccountId> in future commits
// TODO: this should get changed into Result<&AccountId, NyxdError> (or Option<&AccountId> in future commits
// note: what unwrap is doing here is just moving a failure that would have normally
// occurred in `connect` when attempting to parse an empty address,
// so it's not introducing new source of failure (just moves it)
@@ -272,7 +276,7 @@ impl<C> NymdClient<C> {
.unwrap()
}
// TODO: this should get changed into Result<&AccountId, NymdError> (or Option<&AccountId> in future commits
// TODO: this should get changed into Result<&AccountId, NyxdError> (or Option<&AccountId> in future commits
// note: what unwrap is doing here is just moving a failure that would have normally
// occurred in `connect` when attempting to parse an empty address,
// so it's not introducing new source of failure (just moves it)
@@ -280,7 +284,7 @@ impl<C> NymdClient<C> {
self.config.multisig_contract_address.as_ref().unwrap()
}
// TODO: this should get changed into Result<&AccountId, NymdError> (or Option<&AccountId> in future commits
// TODO: this should get changed into Result<&AccountId, NyxdError> (or Option<&AccountId> in future commits
// note: what unwrap is doing here is just moving a failure that would have normally
// occurred in `connect` when attempting to parse an empty address,
// so it's not introducing new source of failure (just moves it)
@@ -296,7 +300,7 @@ impl<C> NymdClient<C> {
&self,
contract: &AccountId,
query_msg: &M,
) -> Result<T, NymdError>
) -> Result<T, NyxdError>
where
C: CosmWasmClient + Sync,
M: ?Sized + Serialize + Sync,
@@ -309,7 +313,7 @@ impl<C> NymdClient<C> {
&self,
contract: &AccountId,
query_data: Vec<u8>,
) -> Result<Vec<u8>, NymdError>
) -> Result<Vec<u8>, NyxdError>
where
C: CosmWasmClient + Sync,
{
@@ -321,7 +325,7 @@ impl<C> NymdClient<C> {
contract_address: &AccountId,
msg: &M,
funds: Vec<Coin>,
) -> Result<cosmwasm::MsgExecuteContract, NymdError>
) -> Result<cosmwasm::MsgExecuteContract, NyxdError>
where
C: SigningCosmWasmClient,
M: ?Sized + Serialize,
@@ -366,7 +370,7 @@ impl<C> NymdClient<C> {
// CHAIN QUERIES
pub async fn account_sequence(&self) -> Result<SequenceResponse, NymdError>
pub async fn account_sequence(&self) -> Result<SequenceResponse, NyxdError>
where
C: SigningCosmWasmClient + Sync,
{
@@ -376,7 +380,7 @@ impl<C> NymdClient<C> {
pub async fn get_account_details(
&self,
address: &AccountId,
) -> Result<Option<Account>, NymdError>
) -> Result<Option<Account>, NyxdError>
where
C: CosmWasmClient + Sync,
{
@@ -386,7 +390,7 @@ impl<C> NymdClient<C> {
pub async fn get_account_public_key(
&self,
address: &AccountId,
) -> Result<Option<cosmrs::crypto::PublicKey>, NymdError>
) -> Result<Option<cosmrs::crypto::PublicKey>, NyxdError>
where
C: CosmWasmClient + Sync,
{
@@ -398,7 +402,7 @@ impl<C> NymdClient<C> {
Ok(None)
}
pub async fn get_current_block_timestamp(&self) -> Result<TendermintTime, NymdError>
pub async fn get_current_block_timestamp(&self) -> Result<TendermintTime, NyxdError>
where
C: CosmWasmClient + Sync,
{
@@ -408,21 +412,21 @@ impl<C> NymdClient<C> {
pub async fn get_block_timestamp(
&self,
height: Option<u32>,
) -> Result<TendermintTime, NymdError>
) -> Result<TendermintTime, NyxdError>
where
C: CosmWasmClient + Sync,
{
Ok(self.client.get_block(height).await?.block.header.time)
}
pub async fn get_block(&self, height: Option<u32>) -> Result<BlockResponse, NymdError>
pub async fn get_block(&self, height: Option<u32>) -> Result<BlockResponse, NyxdError>
where
C: CosmWasmClient + Sync,
{
self.client.get_block(height).await
}
pub async fn get_current_block_height(&self) -> Result<Height, NymdError>
pub async fn get_current_block_height(&self) -> Result<Height, NyxdError>
where
C: CosmWasmClient + Sync,
{
@@ -434,7 +438,7 @@ impl<C> NymdClient<C> {
/// # Arguments
///
/// * `height`: height of the block for which we want to obtain the hash.
pub async fn get_block_hash(&self, height: u32) -> Result<hash::Hash, NymdError>
pub async fn get_block_hash(&self, height: u32) -> Result<hash::Hash, NyxdError>
where
C: CosmWasmClient + Sync,
{
@@ -448,7 +452,7 @@ impl<C> NymdClient<C> {
&self,
height: u64,
paging: Paging,
) -> Result<ValidatorResponse, NymdError>
) -> Result<ValidatorResponse, NyxdError>
where
C: CosmWasmClient + Sync,
{
@@ -459,42 +463,42 @@ impl<C> NymdClient<C> {
&self,
address: &AccountId,
denom: String,
) -> Result<Option<Coin>, NymdError>
) -> Result<Option<Coin>, NyxdError>
where
C: CosmWasmClient + Sync,
{
self.client.get_balance(address, denom).await
}
pub async fn get_all_balances(&self, address: &AccountId) -> Result<Vec<Coin>, NymdError>
pub async fn get_all_balances(&self, address: &AccountId) -> Result<Vec<Coin>, NyxdError>
where
C: CosmWasmClient + Sync,
{
self.client.get_all_balances(address).await
}
pub async fn get_tx(&self, id: tx::Hash) -> Result<TxResponse, NymdError>
pub async fn get_tx(&self, id: tx::Hash) -> Result<TxResponse, NyxdError>
where
C: CosmWasmClient + Sync,
{
self.client.get_tx(id).await
}
pub async fn search_tx(&self, query: Query) -> Result<Vec<TxResponse>, NymdError>
pub async fn search_tx(&self, query: Query) -> Result<Vec<TxResponse>, NyxdError>
where
C: CosmWasmClient + Sync,
{
self.client.search_tx(query).await
}
pub async fn get_total_supply(&self) -> Result<Vec<Coin>, NymdError>
pub async fn get_total_supply(&self) -> Result<Vec<Coin>, NyxdError>
where
C: CosmWasmClient + Sync,
{
self.client.get_total_supply().await
}
pub async fn simulate<I, M>(&self, messages: I) -> Result<SimulateResponse, NymdError>
pub async fn simulate<I, M>(&self, messages: I) -> Result<SimulateResponse, NyxdError>
where
C: SigningCosmWasmClient + Sync,
I: IntoIterator<Item = M> + Send,
@@ -508,7 +512,7 @@ impl<C> NymdClient<C> {
.map(|msg| msg.into_any())
.collect::<Result<Vec<_>, _>>()
.map_err(|_| {
NymdError::SerializationError("custom simulate messages".to_owned())
NyxdError::SerializationError("custom simulate messages".to_owned())
})?,
"simulating execution of transactions",
)
@@ -522,7 +526,7 @@ impl<C> NymdClient<C> {
amount: Vec<Coin>,
memo: impl Into<String> + Send + 'static,
fee: Option<Fee>,
) -> Result<TxResponse, NymdError>
) -> Result<TxResponse, NyxdError>
where
C: SigningCosmWasmClient + Sync,
{
@@ -538,7 +542,7 @@ impl<C> NymdClient<C> {
msgs: Vec<(AccountId, Vec<Coin>)>,
memo: impl Into<String> + Send + 'static,
fee: Option<Fee>,
) -> Result<TxResponse, NymdError>
) -> Result<TxResponse, NyxdError>
where
C: SigningCosmWasmClient + Sync,
{
@@ -557,7 +561,7 @@ impl<C> NymdClient<C> {
allowed_messages: Vec<String>,
memo: impl Into<String> + Send + 'static,
fee: Option<Fee>,
) -> Result<TxResponse, NymdError>
) -> Result<TxResponse, NyxdError>
where
C: SigningCosmWasmClient + Sync,
{
@@ -581,7 +585,7 @@ impl<C> NymdClient<C> {
grantee: &AccountId,
memo: impl Into<String> + Send + 'static,
fee: Option<Fee>,
) -> Result<TxResponse, NymdError>
) -> Result<TxResponse, NyxdError>
where
C: SigningCosmWasmClient + Sync,
{
@@ -598,7 +602,7 @@ impl<C> NymdClient<C> {
fee: Option<Fee>,
memo: impl Into<String> + Send + 'static,
funds: Vec<Coin>,
) -> Result<ExecuteResult, NymdError>
) -> Result<ExecuteResult, NyxdError>
where
C: SigningCosmWasmClient + Sync,
M: ?Sized + Serialize + Sync,
@@ -615,7 +619,7 @@ impl<C> NymdClient<C> {
msgs: I,
fee: Option<Fee>,
memo: impl Into<String> + Send + 'static,
) -> Result<ExecuteResult, NymdError>
) -> Result<ExecuteResult, NyxdError>
where
C: SigningCosmWasmClient + Sync,
I: IntoIterator<Item = (M, Vec<Coin>)> + Send,
@@ -632,7 +636,7 @@ impl<C> NymdClient<C> {
wasm_code: Vec<u8>,
memo: impl Into<String> + Send + 'static,
fee: Option<Fee>,
) -> Result<UploadResult, NymdError>
) -> Result<UploadResult, NyxdError>
where
C: SigningCosmWasmClient + Sync,
{
@@ -650,7 +654,7 @@ impl<C> NymdClient<C> {
memo: impl Into<String> + Send + 'static,
options: Option<InstantiateOptions>,
fee: Option<Fee>,
) -> Result<InstantiateResult, NymdError>
) -> Result<InstantiateResult, NyxdError>
where
C: SigningCosmWasmClient + Sync,
M: ?Sized + Serialize + Sync,
@@ -667,7 +671,7 @@ impl<C> NymdClient<C> {
new_admin: &AccountId,
memo: impl Into<String> + Send + 'static,
fee: Option<Fee>,
) -> Result<ChangeAdminResult, NymdError>
) -> Result<ChangeAdminResult, NyxdError>
where
C: SigningCosmWasmClient + Sync,
{
@@ -682,7 +686,7 @@ impl<C> NymdClient<C> {
contract_address: &AccountId,
memo: impl Into<String> + Send + 'static,
fee: Option<Fee>,
) -> Result<ChangeAdminResult, NymdError>
) -> Result<ChangeAdminResult, NyxdError>
where
C: SigningCosmWasmClient + Sync,
{
@@ -699,7 +703,7 @@ impl<C> NymdClient<C> {
msg: &M,
memo: impl Into<String> + Send + 'static,
fee: Option<Fee>,
) -> Result<MigrateResult, NymdError>
) -> Result<MigrateResult, NyxdError>
where
C: SigningCosmWasmClient + Sync,
M: ?Sized + Serialize + Sync,
@@ -1,8 +1,8 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::nymd::error::NymdError;
use crate::nymd::{CosmWasmClient, NymdClient};
use crate::nyxd::error::NyxdError;
use crate::nyxd::{CosmWasmClient, NyxdClient};
use coconut_bandwidth_contract_common::msg::QueryMsg;
use coconut_bandwidth_contract_common::spend_credential::SpendCredentialResponse;
@@ -14,15 +14,15 @@ pub trait CoconutBandwidthQueryClient {
async fn get_spent_credential(
&self,
blinded_serial_number: String,
) -> Result<SpendCredentialResponse, NymdError>;
) -> Result<SpendCredentialResponse, NyxdError>;
}
#[async_trait]
impl<C: CosmWasmClient + Sync + Send> CoconutBandwidthQueryClient for NymdClient<C> {
impl<C: CosmWasmClient + Sync + Send> CoconutBandwidthQueryClient for NyxdClient<C> {
async fn get_spent_credential(
&self,
blinded_serial_number: String,
) -> Result<SpendCredentialResponse, NymdError> {
) -> Result<SpendCredentialResponse, NyxdError> {
let request = QueryMsg::GetSpentCredential {
blinded_serial_number,
};
@@ -1,10 +1,10 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
pub use crate::nymd::cosmwasm_client::signing_client::SigningCosmWasmClient;
use crate::nymd::cosmwasm_client::types::ExecuteResult;
use crate::nymd::error::NymdError;
use crate::nymd::{Coin, Fee, NymdClient};
pub use crate::nyxd::cosmwasm_client::signing_client::SigningCosmWasmClient;
use crate::nyxd::cosmwasm_client::types::ExecuteResult;
use crate::nyxd::error::NyxdError;
use crate::nyxd::{Coin, Fee, NyxdClient};
use coconut_bandwidth_contract_common::spend_credential::SpendCredentialData;
use coconut_bandwidth_contract_common::{deposit::DepositData, msg::ExecuteMsg};
@@ -19,18 +19,18 @@ pub trait CoconutBandwidthSigningClient {
verification_key: String,
encryption_key: String,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError>;
) -> Result<ExecuteResult, NyxdError>;
async fn spend_credential(
&self,
funds: Coin,
blinded_serial_number: String,
gateway_cosmos_address: String,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError>;
) -> Result<ExecuteResult, NyxdError>;
}
#[async_trait]
impl<C: SigningCosmWasmClient + Sync + Send> CoconutBandwidthSigningClient for NymdClient<C> {
impl<C: SigningCosmWasmClient + Sync + Send> CoconutBandwidthSigningClient for NyxdClient<C> {
async fn deposit(
&self,
amount: Coin,
@@ -38,7 +38,7 @@ impl<C: SigningCosmWasmClient + Sync + Send> CoconutBandwidthSigningClient for N
verification_key: String,
encryption_key: String,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier)));
let req = ExecuteMsg::DepositFunds {
data: DepositData::new(info.to_string(), verification_key, encryption_key),
@@ -60,7 +60,7 @@ impl<C: SigningCosmWasmClient + Sync + Send> CoconutBandwidthSigningClient for N
blinded_serial_number: String,
gateway_cosmos_address: String,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier)));
let req = ExecuteMsg::SpendCredential {
data: SpendCredentialData::new(
@@ -1,61 +1,61 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::nymd::error::NymdError;
use crate::nymd::{CosmWasmClient, NymdClient};
use crate::nyxd::error::NyxdError;
use crate::nyxd::{CosmWasmClient, NyxdClient};
use async_trait::async_trait;
use coconut_dkg_common::dealer::{
DealerDetailsResponse, PagedDealerResponse, PagedDealingsResponse,
};
use coconut_dkg_common::msg::QueryMsg as DkgQueryMsg;
use coconut_dkg_common::types::EpochState;
use coconut_dkg_common::types::Epoch;
use coconut_dkg_common::verification_key::PagedVKSharesResponse;
use cosmrs::AccountId;
#[async_trait]
pub trait DkgQueryClient {
async fn get_current_epoch_state(&self) -> Result<EpochState, NymdError>;
async fn get_current_epoch_threshold(&self) -> Result<Option<u64>, NymdError>;
async fn get_current_epoch(&self) -> Result<Epoch, NyxdError>;
async fn get_current_epoch_threshold(&self) -> Result<Option<u64>, NyxdError>;
async fn get_dealer_details(
&self,
address: &AccountId,
) -> Result<DealerDetailsResponse, NymdError>;
) -> Result<DealerDetailsResponse, NyxdError>;
async fn get_current_dealers_paged(
&self,
start_after: Option<String>,
page_limit: Option<u32>,
) -> Result<PagedDealerResponse, NymdError>;
) -> Result<PagedDealerResponse, NyxdError>;
async fn get_past_dealers_paged(
&self,
start_after: Option<String>,
page_limit: Option<u32>,
) -> Result<PagedDealerResponse, NymdError>;
) -> Result<PagedDealerResponse, NyxdError>;
async fn get_dealings_paged(
&self,
idx: usize,
start_after: Option<String>,
page_limit: Option<u32>,
) -> Result<PagedDealingsResponse, NymdError>;
) -> Result<PagedDealingsResponse, NyxdError>;
async fn get_vk_shares_paged(
&self,
start_after: Option<String>,
page_limit: Option<u32>,
) -> Result<PagedVKSharesResponse, NymdError>;
) -> Result<PagedVKSharesResponse, NyxdError>;
}
#[async_trait]
impl<C> DkgQueryClient for NymdClient<C>
impl<C> DkgQueryClient for NyxdClient<C>
where
C: CosmWasmClient + Send + Sync,
{
async fn get_current_epoch_state(&self) -> Result<EpochState, NymdError> {
async fn get_current_epoch(&self) -> Result<Epoch, NyxdError> {
let request = DkgQueryMsg::GetCurrentEpochState {};
self.client
.query_contract_smart(self.coconut_dkg_contract_address(), &request)
.await
}
async fn get_current_epoch_threshold(&self) -> Result<Option<u64>, NymdError> {
async fn get_current_epoch_threshold(&self) -> Result<Option<u64>, NyxdError> {
let request = DkgQueryMsg::GetCurrentEpochThreshold {};
self.client
.query_contract_smart(self.coconut_dkg_contract_address(), &request)
@@ -64,7 +64,7 @@ where
async fn get_dealer_details(
&self,
address: &AccountId,
) -> Result<DealerDetailsResponse, NymdError> {
) -> Result<DealerDetailsResponse, NyxdError> {
let request = DkgQueryMsg::GetDealerDetails {
dealer_address: address.to_string(),
};
@@ -77,7 +77,7 @@ where
&self,
start_after: Option<String>,
page_limit: Option<u32>,
) -> Result<PagedDealerResponse, NymdError> {
) -> Result<PagedDealerResponse, NyxdError> {
let request = DkgQueryMsg::GetCurrentDealers {
start_after,
limit: page_limit,
@@ -91,7 +91,7 @@ where
&self,
start_after: Option<String>,
page_limit: Option<u32>,
) -> Result<PagedDealerResponse, NymdError> {
) -> Result<PagedDealerResponse, NyxdError> {
let request = DkgQueryMsg::GetPastDealers {
start_after,
limit: page_limit,
@@ -106,7 +106,7 @@ where
idx: usize,
start_after: Option<String>,
page_limit: Option<u32>,
) -> Result<PagedDealingsResponse, NymdError> {
) -> Result<PagedDealingsResponse, NyxdError> {
let request = DkgQueryMsg::GetDealing {
idx: idx as u64,
limit: page_limit,
@@ -121,7 +121,7 @@ where
&self,
start_after: Option<String>,
page_limit: Option<u32>,
) -> Result<PagedVKSharesResponse, NymdError> {
) -> Result<PagedVKSharesResponse, NyxdError> {
let request = DkgQueryMsg::GetVerificationKeys {
limit: page_limit,
start_after,
@@ -1,9 +1,9 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::nymd::cosmwasm_client::types::ExecuteResult;
use crate::nymd::error::NymdError;
use crate::nymd::{Fee, NymdClient, SigningCosmWasmClient};
use crate::nyxd::cosmwasm_client::types::ExecuteResult;
use crate::nyxd::error::NyxdError;
use crate::nyxd::{Fee, NyxdClient, SigningCosmWasmClient};
use async_trait::async_trait;
use coconut_dkg_common::msg::ExecuteMsg as DkgExecuteMsg;
use coconut_dkg_common::types::EncodedBTEPublicKeyWithProof;
@@ -12,37 +12,53 @@ use contracts_common::dealings::ContractSafeBytes;
#[async_trait]
pub trait DkgSigningClient {
async fn advance_dkg_epoch_state(&self, fee: Option<Fee>) -> Result<ExecuteResult, NyxdError>;
async fn register_dealer(
&self,
bte_key: EncodedBTEPublicKeyWithProof,
announce_address: String,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError>;
) -> Result<ExecuteResult, NyxdError>;
async fn submit_dealing_bytes(
&self,
commitment: ContractSafeBytes,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError>;
) -> Result<ExecuteResult, NyxdError>;
async fn submit_verification_key_share(
&self,
share: VerificationKeyShare,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError>;
) -> Result<ExecuteResult, NyxdError>;
}
#[async_trait]
impl<C> DkgSigningClient for NymdClient<C>
impl<C> DkgSigningClient for NyxdClient<C>
where
C: SigningCosmWasmClient + Send + Sync,
{
async fn advance_dkg_epoch_state(&self, fee: Option<Fee>) -> Result<ExecuteResult, NyxdError> {
let req = DkgExecuteMsg::AdvanceEpochState {};
self.client
.execute(
self.address(),
self.coconut_dkg_contract_address(),
&req,
fee.unwrap_or_default(),
"advancing DKG state",
vec![],
)
.await
}
async fn register_dealer(
&self,
bte_key: EncodedBTEPublicKeyWithProof,
announce_address: String,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
let req = DkgExecuteMsg::RegisterDealer {
bte_key_with_proof: bte_key,
announce_address,
@@ -64,7 +80,7 @@ where
&self,
dealing_bytes: ContractSafeBytes,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
let req = DkgExecuteMsg::CommitDealing { dealing_bytes };
self.client
@@ -83,7 +99,7 @@ where
&self,
share: VerificationKeyShare,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
let req = DkgExecuteMsg::CommitVerificationKeyShare { share };
self.client
@@ -1,9 +1,9 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
pub use crate::nymd::cosmwasm_client::client::CosmWasmClient;
use crate::nymd::error::NymdError;
use crate::nymd::NymdClient;
pub use crate::nyxd::cosmwasm_client::client::CosmWasmClient;
use crate::nyxd::error::NyxdError;
use crate::nyxd::NyxdClient;
use async_trait::async_trait;
use cosmrs::AccountId;
use mixnet_contract_common::delegation::{MixNodeDelegationResponse, OwnerProxySubKey};
@@ -29,38 +29,38 @@ use serde::Deserialize;
#[async_trait]
pub trait MixnetQueryClient {
async fn query_mixnet_contract<T>(&self, query: MixnetQueryMsg) -> Result<T, NymdError>
async fn query_mixnet_contract<T>(&self, query: MixnetQueryMsg) -> Result<T, NyxdError>
where
for<'a> T: Deserialize<'a>;
// state/sys-params-related
async fn get_mixnet_contract_version(&self) -> Result<ContractBuildInformation, NymdError> {
async fn get_mixnet_contract_version(&self) -> Result<ContractBuildInformation, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetContractVersion {})
.await
}
async fn get_rewarding_validator_address(&self) -> Result<AccountId, NymdError> {
async fn get_rewarding_validator_address(&self) -> Result<AccountId, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetRewardingValidatorAddress {})
.await
}
async fn get_mixnet_contract_settings(&self) -> Result<ContractStateParams, NymdError> {
async fn get_mixnet_contract_settings(&self) -> Result<ContractStateParams, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetStateParams {})
.await
}
async fn get_mixnet_contract_state(&self) -> Result<ContractState, NymdError> {
async fn get_mixnet_contract_state(&self) -> Result<ContractState, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetState {})
.await
}
async fn get_rewarding_parameters(&self) -> Result<RewardingParams, NymdError> {
async fn get_rewarding_parameters(&self) -> Result<RewardingParams, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetRewardingParams {})
.await
}
async fn get_current_interval_details(&self) -> Result<CurrentIntervalResponse, NymdError> {
async fn get_current_interval_details(&self) -> Result<CurrentIntervalResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetCurrentIntervalDetails {})
.await
}
@@ -69,7 +69,7 @@ pub trait MixnetQueryClient {
&self,
start_after: Option<MixId>,
limit: Option<u32>,
) -> Result<PagedRewardedSetResponse, NymdError> {
) -> Result<PagedRewardedSetResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetRewardedSet { limit, start_after })
.await
}
@@ -78,7 +78,7 @@ pub trait MixnetQueryClient {
&self,
start_after: Option<String>,
limit: Option<u32>,
) -> Result<PagedFamiliesResponse, NymdError> {
) -> Result<PagedFamiliesResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetAllFamiliesPaged { limit, start_after })
.await
}
@@ -87,7 +87,7 @@ pub trait MixnetQueryClient {
&self,
start_after: Option<String>,
limit: Option<u32>,
) -> Result<PagedMembersResponse, NymdError> {
) -> Result<PagedMembersResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetAllMembersPaged { limit, start_after })
.await
}
@@ -98,7 +98,7 @@ pub trait MixnetQueryClient {
&self,
limit: Option<u32>,
start_after: Option<MixId>,
) -> Result<PagedMixnodeBondsResponse, NymdError> {
) -> Result<PagedMixnodeBondsResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetMixNodeBonds { limit, start_after })
.await
}
@@ -107,7 +107,7 @@ pub trait MixnetQueryClient {
&self,
limit: Option<u32>,
start_after: Option<MixId>,
) -> Result<PagedMixnodesDetailsResponse, NymdError> {
) -> Result<PagedMixnodesDetailsResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetMixNodesDetailed { limit, start_after })
.await
}
@@ -116,7 +116,7 @@ pub trait MixnetQueryClient {
&self,
limit: Option<u32>,
start_after: Option<MixId>,
) -> Result<PagedUnbondedMixnodesResponse, NymdError> {
) -> Result<PagedUnbondedMixnodesResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetUnbondedMixNodes { limit, start_after })
.await
}
@@ -126,7 +126,7 @@ pub trait MixnetQueryClient {
owner: &AccountId,
limit: Option<u32>,
start_after: Option<MixId>,
) -> Result<PagedUnbondedMixnodesResponse, NymdError> {
) -> Result<PagedUnbondedMixnodesResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetUnbondedMixNodesByOwner {
owner: owner.to_string(),
limit,
@@ -140,7 +140,7 @@ pub trait MixnetQueryClient {
identity_key: String,
limit: Option<u32>,
start_after: Option<MixId>,
) -> Result<PagedUnbondedMixnodesResponse, NymdError> {
) -> Result<PagedUnbondedMixnodesResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetUnbondedMixNodesByIdentityKey {
identity_key,
limit,
@@ -152,7 +152,7 @@ pub trait MixnetQueryClient {
async fn get_owned_mixnode(
&self,
address: &AccountId,
) -> Result<MixOwnershipResponse, NymdError> {
) -> Result<MixOwnershipResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetOwnedMixnode {
address: address.to_string(),
})
@@ -162,7 +162,7 @@ pub trait MixnetQueryClient {
async fn get_mixnode_details(
&self,
mix_id: MixId,
) -> Result<MixnodeDetailsResponse, NymdError> {
) -> Result<MixnodeDetailsResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetMixnodeDetails { mix_id })
.await
}
@@ -170,7 +170,7 @@ pub trait MixnetQueryClient {
async fn get_mixnode_rewarding_details(
&self,
mix_id: MixId,
) -> Result<MixnodeRewardingDetailsResponse, NymdError> {
) -> Result<MixnodeRewardingDetailsResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetMixnodeRewardingDetails { mix_id })
.await
}
@@ -178,7 +178,7 @@ pub trait MixnetQueryClient {
async fn get_mixnode_stake_saturation(
&self,
mix_id: MixId,
) -> Result<StakeSaturationResponse, NymdError> {
) -> Result<StakeSaturationResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetStakeSaturation { mix_id })
.await
}
@@ -186,12 +186,12 @@ pub trait MixnetQueryClient {
async fn get_unbonded_mixnode_information(
&self,
mix_id: MixId,
) -> Result<UnbondedMixnodeResponse, NymdError> {
) -> Result<UnbondedMixnodeResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetUnbondedMixNodeInformation { mix_id })
.await
}
async fn get_layer_distribution(&self) -> Result<LayerDistribution, NymdError> {
async fn get_layer_distribution(&self) -> Result<LayerDistribution, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetLayerDistribution {})
.await
}
@@ -202,7 +202,7 @@ pub trait MixnetQueryClient {
&self,
start_after: Option<IdentityKey>,
limit: Option<u32>,
) -> Result<PagedGatewayResponse, NymdError> {
) -> Result<PagedGatewayResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetGateways { start_after, limit })
.await
}
@@ -211,7 +211,7 @@ pub trait MixnetQueryClient {
async fn get_gateway_bond(
&self,
identity: IdentityKey,
) -> Result<GatewayBondResponse, NymdError> {
) -> Result<GatewayBondResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetGatewayBond { identity })
.await
}
@@ -220,7 +220,7 @@ pub trait MixnetQueryClient {
async fn get_owned_gateway(
&self,
address: &AccountId,
) -> Result<GatewayOwnershipResponse, NymdError> {
) -> Result<GatewayOwnershipResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetOwnedGateway {
address: address.to_string(),
})
@@ -235,7 +235,7 @@ pub trait MixnetQueryClient {
mix_id: MixId,
start_after: Option<String>,
limit: Option<u32>,
) -> Result<PagedMixNodeDelegationsResponse, NymdError> {
) -> Result<PagedMixNodeDelegationsResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetMixnodeDelegations {
mix_id,
start_after,
@@ -250,7 +250,7 @@ pub trait MixnetQueryClient {
delegator: String,
start_after: Option<(MixId, OwnerProxySubKey)>,
limit: Option<u32>,
) -> Result<PagedDelegatorDelegationsResponse, NymdError> {
) -> Result<PagedDelegatorDelegationsResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetDelegatorDelegations {
delegator,
start_after,
@@ -265,7 +265,7 @@ pub trait MixnetQueryClient {
mix_id: MixId,
delegator: &AccountId,
proxy: Option<String>,
) -> Result<MixNodeDelegationResponse, NymdError> {
) -> Result<MixNodeDelegationResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetDelegationDetails {
mix_id,
delegator: delegator.to_string(),
@@ -279,7 +279,7 @@ pub trait MixnetQueryClient {
&self,
start_after: Option<delegation::StorageKey>,
limit: Option<u32>,
) -> Result<PagedAllDelegationsResponse, NymdError> {
) -> Result<PagedAllDelegationsResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetAllDelegations { start_after, limit })
.await
}
@@ -288,7 +288,7 @@ pub trait MixnetQueryClient {
async fn get_pending_operator_reward(
&self,
operator: &AccountId,
) -> Result<PendingRewardResponse, NymdError> {
) -> Result<PendingRewardResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetPendingOperatorReward {
address: operator.to_string(),
})
@@ -298,7 +298,7 @@ pub trait MixnetQueryClient {
async fn get_pending_mixnode_operator_reward(
&self,
mix_id: MixId,
) -> Result<PendingRewardResponse, NymdError> {
) -> Result<PendingRewardResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetPendingMixNodeOperatorReward { mix_id })
.await
}
@@ -308,7 +308,7 @@ pub trait MixnetQueryClient {
delegator: &AccountId,
mix_id: MixId,
proxy: Option<String>,
) -> Result<PendingRewardResponse, NymdError> {
) -> Result<PendingRewardResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetPendingDelegatorReward {
address: delegator.to_string(),
mix_id,
@@ -322,7 +322,7 @@ pub trait MixnetQueryClient {
&self,
mix_id: MixId,
estimated_performance: Performance,
) -> Result<EstimatedCurrentEpochRewardResponse, NymdError> {
) -> Result<EstimatedCurrentEpochRewardResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetEstimatedCurrentEpochOperatorReward {
mix_id,
estimated_performance,
@@ -337,7 +337,7 @@ pub trait MixnetQueryClient {
mix_id: MixId,
proxy: Option<String>,
estimated_performance: Performance,
) -> Result<EstimatedCurrentEpochRewardResponse, NymdError> {
) -> Result<EstimatedCurrentEpochRewardResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetEstimatedCurrentEpochDelegatorReward {
address: delegator.to_string(),
mix_id,
@@ -353,7 +353,7 @@ pub trait MixnetQueryClient {
&self,
start_after: Option<EpochEventId>,
limit: Option<u32>,
) -> Result<PendingEpochEventsResponse, NymdError> {
) -> Result<PendingEpochEventsResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetPendingEpochEvents { start_after, limit })
.await
}
@@ -362,7 +362,7 @@ pub trait MixnetQueryClient {
&self,
start_after: Option<IntervalEventId>,
limit: Option<u32>,
) -> Result<PendingIntervalEventsResponse, NymdError> {
) -> Result<PendingIntervalEventsResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetPendingIntervalEvents { start_after, limit })
.await
}
@@ -370,21 +370,21 @@ pub trait MixnetQueryClient {
async fn get_mixnode_details_by_identity(
&self,
mix_identity: IdentityKey,
) -> Result<Option<MixNodeDetails>, NymdError> {
) -> Result<Option<MixNodeDetails>, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetBondedMixnodeDetailsByIdentity {
mix_identity,
})
.await
}
async fn get_node_family_by_label(&self, label: &str) -> Result<Option<Family>, NymdError> {
async fn get_node_family_by_label(&self, label: &str) -> Result<Option<Family>, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetFamilyByLabel {
label: label.to_string(),
})
.await
}
async fn get_node_family_by_head(&self, head: &str) -> Result<Option<Family>, NymdError> {
async fn get_node_family_by_head(&self, head: &str) -> Result<Option<Family>, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetFamilyByHead {
head: head.to_string(),
})
@@ -393,11 +393,11 @@ pub trait MixnetQueryClient {
}
#[async_trait]
impl<C> MixnetQueryClient for NymdClient<C>
impl<C> MixnetQueryClient for NyxdClient<C>
where
C: CosmWasmClient + Sync + Send,
{
async fn query_mixnet_contract<T>(&self, query: MixnetQueryMsg) -> Result<T, NymdError>
async fn query_mixnet_contract<T>(&self, query: MixnetQueryMsg) -> Result<T, NyxdError>
where
for<'a> T: Deserialize<'a>,
{
@@ -412,10 +412,10 @@ impl<C> MixnetQueryClient for crate::Client<C>
where
C: CosmWasmClient + Sync + Send,
{
async fn query_mixnet_contract<T>(&self, query: MixnetQueryMsg) -> Result<T, NymdError>
async fn query_mixnet_contract<T>(&self, query: MixnetQueryMsg) -> Result<T, NyxdError>
where
for<'a> T: Deserialize<'a>,
{
self.nymd.query_mixnet_contract(query).await
self.nyxd.query_mixnet_contract(query).await
}
}
@@ -1,11 +1,11 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::nymd::coin::Coin;
pub use crate::nymd::cosmwasm_client::client::CosmWasmClient;
use crate::nymd::cosmwasm_client::types::ExecuteResult;
use crate::nymd::error::NymdError;
use crate::nymd::{Fee, NymdClient, SigningCosmWasmClient};
use crate::nyxd::coin::Coin;
pub use crate::nyxd::cosmwasm_client::client::CosmWasmClient;
use crate::nyxd::cosmwasm_client::types::ExecuteResult;
use crate::nyxd::error::NyxdError;
use crate::nyxd::{Fee, NyxdClient, SigningCosmWasmClient};
use async_trait::async_trait;
use cosmrs::AccountId;
use mixnet_contract_common::mixnode::{MixNodeConfigUpdate, MixNodeCostParams};
@@ -21,7 +21,7 @@ pub trait MixnetSigningClient {
fee: Option<Fee>,
msg: MixnetExecuteMsg,
funds: Vec<Coin>,
) -> Result<ExecuteResult, NymdError>;
) -> Result<ExecuteResult, NyxdError>;
// state/sys-params-related
@@ -29,7 +29,7 @@ pub trait MixnetSigningClient {
&self,
address: AccountId,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::UpdateRewardingValidatorAddress {
@@ -44,7 +44,7 @@ pub trait MixnetSigningClient {
&self,
updated_parameters: ContractStateParams,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::UpdateContractStateParams { updated_parameters },
@@ -58,7 +58,7 @@ pub trait MixnetSigningClient {
active_set_size: u32,
force_immediately: bool,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::UpdateActiveSetSize {
@@ -75,7 +75,7 @@ pub trait MixnetSigningClient {
updated_params: IntervalRewardingParamsUpdate,
force_immediately: bool,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::UpdateRewardingParams {
@@ -93,7 +93,7 @@ pub trait MixnetSigningClient {
epoch_duration_secs: u64,
force_immediately: bool,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::UpdateIntervalConfig {
@@ -111,7 +111,7 @@ pub trait MixnetSigningClient {
new_rewarded_set: Vec<LayerAssignment>,
expected_active_set_size: u32,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::AdvanceCurrentEpoch {
@@ -127,7 +127,7 @@ pub trait MixnetSigningClient {
&self,
limit: Option<u32>,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::ReconcileEpochEvents { limit },
@@ -142,7 +142,7 @@ pub trait MixnetSigningClient {
owner_signature: String,
label: String,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::CreateFamily {
@@ -160,7 +160,7 @@ pub trait MixnetSigningClient {
owner_signature: String,
label: String,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::CreateFamilyOnBehalf {
@@ -178,7 +178,7 @@ pub trait MixnetSigningClient {
signature: String,
family_head: String,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::JoinFamily {
@@ -196,7 +196,7 @@ pub trait MixnetSigningClient {
signature: String,
family_head: String,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::JoinFamilyOnBehalf {
@@ -214,7 +214,7 @@ pub trait MixnetSigningClient {
signature: String,
family_head: String,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::LeaveFamily {
@@ -232,7 +232,7 @@ pub trait MixnetSigningClient {
signature: String,
family_head: String,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::LeaveFamilyOnBehalf {
@@ -250,7 +250,7 @@ pub trait MixnetSigningClient {
signature: String,
member: String,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::KickFamilyMember { signature, member },
@@ -265,7 +265,7 @@ pub trait MixnetSigningClient {
signature: String,
member: String,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::KickFamilyMemberOnBehalf {
@@ -286,7 +286,7 @@ pub trait MixnetSigningClient {
owner_signature: String,
pledge: Coin,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::BondMixnode {
@@ -307,7 +307,7 @@ pub trait MixnetSigningClient {
owner_signature: String,
pledge: Coin,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::BondMixnodeOnBehalf {
@@ -325,7 +325,7 @@ pub trait MixnetSigningClient {
&self,
additional_pledge: Coin,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::PledgeMore {},
@@ -339,7 +339,7 @@ pub trait MixnetSigningClient {
owner: AccountId,
additional_pledge: Coin,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::PledgeMoreOnBehalf {
@@ -350,7 +350,7 @@ pub trait MixnetSigningClient {
.await
}
async fn unbond_mixnode(&self, fee: Option<Fee>) -> Result<ExecuteResult, NymdError> {
async fn unbond_mixnode(&self, fee: Option<Fee>) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(fee, MixnetExecuteMsg::UnbondMixnode {}, vec![])
.await
}
@@ -359,7 +359,7 @@ pub trait MixnetSigningClient {
&self,
owner: AccountId,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::UnbondMixnodeOnBehalf {
@@ -374,7 +374,7 @@ pub trait MixnetSigningClient {
&self,
new_costs: MixNodeCostParams,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::UpdateMixnodeCostParams { new_costs },
@@ -388,7 +388,7 @@ pub trait MixnetSigningClient {
owner: AccountId,
new_costs: MixNodeCostParams,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::UpdateMixnodeCostParamsOnBehalf {
@@ -404,7 +404,7 @@ pub trait MixnetSigningClient {
&self,
new_config: MixNodeConfigUpdate,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::UpdateMixnodeConfig { new_config },
@@ -418,7 +418,7 @@ pub trait MixnetSigningClient {
owner: AccountId,
new_config: MixNodeConfigUpdate,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::UpdateMixnodeConfigOnBehalf {
@@ -438,7 +438,7 @@ pub trait MixnetSigningClient {
owner_signature: String,
pledge: Coin,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::BondGateway {
@@ -457,7 +457,7 @@ pub trait MixnetSigningClient {
owner_signature: String,
pledge: Coin,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::BondGatewayOnBehalf {
@@ -470,7 +470,7 @@ pub trait MixnetSigningClient {
.await
}
async fn unbond_gateway(&self, fee: Option<Fee>) -> Result<ExecuteResult, NymdError> {
async fn unbond_gateway(&self, fee: Option<Fee>) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(fee, MixnetExecuteMsg::UnbondGateway {}, vec![])
.await
}
@@ -479,7 +479,7 @@ pub trait MixnetSigningClient {
&self,
owner: AccountId,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::UnbondGatewayOnBehalf {
@@ -497,7 +497,7 @@ pub trait MixnetSigningClient {
mix_id: MixId,
amount: Coin,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::DelegateToMixnode { mix_id },
@@ -512,7 +512,7 @@ pub trait MixnetSigningClient {
mix_id: MixId,
amount: Coin,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::DelegateToMixnodeOnBehalf {
@@ -528,7 +528,7 @@ pub trait MixnetSigningClient {
&self,
mix_id: MixId,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::UndelegateFromMixnode { mix_id },
@@ -542,7 +542,7 @@ pub trait MixnetSigningClient {
delegate: AccountId,
mix_id: MixId,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::UndelegateFromMixnodeOnBehalf {
@@ -561,7 +561,7 @@ pub trait MixnetSigningClient {
mix_id: MixId,
performance: Performance,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::RewardMixnode {
@@ -573,7 +573,7 @@ pub trait MixnetSigningClient {
.await
}
async fn withdraw_operator_reward(&self, fee: Option<Fee>) -> Result<ExecuteResult, NymdError> {
async fn withdraw_operator_reward(&self, fee: Option<Fee>) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(fee, MixnetExecuteMsg::WithdrawOperatorReward {}, vec![])
.await
}
@@ -582,7 +582,7 @@ pub trait MixnetSigningClient {
&self,
owner: AccountId,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::WithdrawOperatorRewardOnBehalf {
@@ -597,7 +597,7 @@ pub trait MixnetSigningClient {
&self,
mix_id: MixId,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::WithdrawDelegatorReward { mix_id },
@@ -611,7 +611,7 @@ pub trait MixnetSigningClient {
owner: AccountId,
mix_id: MixId,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::WithdrawDelegatorRewardOnBehalf {
@@ -625,7 +625,7 @@ pub trait MixnetSigningClient {
}
#[async_trait]
impl<C> MixnetSigningClient for NymdClient<C>
impl<C> MixnetSigningClient for NyxdClient<C>
where
C: SigningCosmWasmClient + Sync + Send,
{
@@ -634,7 +634,7 @@ where
fee: Option<Fee>,
msg: MixnetExecuteMsg,
funds: Vec<Coin>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier)));
let memo = msg.default_memo();
self.client
@@ -660,7 +660,7 @@ where
fee: Option<Fee>,
msg: MixnetExecuteMsg,
funds: Vec<Coin>,
) -> Result<ExecuteResult, NymdError> {
self.nymd.execute_mixnet_contract(fee, msg, funds).await
) -> Result<ExecuteResult, NyxdError> {
self.nyxd.execute_mixnet_contract(fee, msg, funds).await
}
}
@@ -1,8 +1,8 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::nymd::error::NymdError;
use crate::nymd::{CosmWasmClient, NymdClient};
use crate::nyxd::error::NyxdError;
use crate::nyxd::{CosmWasmClient, NyxdClient};
use cw3::{ProposalListResponse, ProposalResponse};
use multisig_contract_common::msg::QueryMsg;
@@ -11,17 +11,17 @@ use async_trait::async_trait;
#[async_trait]
pub trait MultisigQueryClient {
async fn get_proposal(&self, proposal_id: u64) -> Result<ProposalResponse, NymdError>;
async fn get_proposal(&self, proposal_id: u64) -> Result<ProposalResponse, NyxdError>;
async fn list_proposals(
&self,
start_after: Option<u64>,
limit: Option<u32>,
) -> Result<ProposalListResponse, NymdError>;
) -> Result<ProposalListResponse, NyxdError>;
}
#[async_trait]
impl<C: CosmWasmClient + Sync + Send> MultisigQueryClient for NymdClient<C> {
async fn get_proposal(&self, proposal_id: u64) -> Result<ProposalResponse, NymdError> {
impl<C: CosmWasmClient + Sync + Send> MultisigQueryClient for NyxdClient<C> {
async fn get_proposal(&self, proposal_id: u64) -> Result<ProposalResponse, NyxdError> {
let request = QueryMsg::Proposal { proposal_id };
self.client
.query_contract_smart(self.multisig_contract_address(), &request)
@@ -32,7 +32,7 @@ impl<C: CosmWasmClient + Sync + Send> MultisigQueryClient for NymdClient<C> {
&self,
start_after: Option<u64>,
limit: Option<u32>,
) -> Result<ProposalListResponse, NymdError> {
) -> Result<ProposalListResponse, NyxdError> {
let request = QueryMsg::ListProposals { start_after, limit };
self.client
.query_contract_smart(self.multisig_contract_address(), &request)
@@ -1,10 +1,10 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
pub use crate::nymd::cosmwasm_client::signing_client::SigningCosmWasmClient;
use crate::nymd::cosmwasm_client::types::ExecuteResult;
use crate::nymd::error::NymdError;
use crate::nymd::{Fee, NymdClient};
pub use crate::nyxd::cosmwasm_client::signing_client::SigningCosmWasmClient;
use crate::nyxd::cosmwasm_client::types::ExecuteResult;
use crate::nyxd::error::NyxdError;
use crate::nyxd::{Fee, NyxdClient};
use coconut_bandwidth_contract_common::msg::ExecuteMsg as CoconutBandwidthExecuteMsg;
use cw3::Vote;
@@ -21,31 +21,31 @@ pub trait MultisigSigningClient {
blinded_serial_number: String,
voucher_value: u128,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError>;
) -> Result<ExecuteResult, NyxdError>;
async fn vote_proposal(
&self,
proposal_id: u64,
yes: bool,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError>;
) -> Result<ExecuteResult, NyxdError>;
async fn execute_proposal(
&self,
proposal_id: u64,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError>;
) -> Result<ExecuteResult, NyxdError>;
}
#[async_trait]
impl<C: SigningCosmWasmClient + Sync + Send> MultisigSigningClient for NymdClient<C> {
impl<C: SigningCosmWasmClient + Sync + Send> MultisigSigningClient for NyxdClient<C> {
async fn propose_release_funds(
&self,
title: String,
blinded_serial_number: String,
voucher_value: u128,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier)));
let release_funds_req = CoconutBandwidthExecuteMsg::ReleaseFunds {
funds: Coin::new(
@@ -81,7 +81,7 @@ impl<C: SigningCosmWasmClient + Sync + Send> MultisigSigningClient for NymdClien
proposal_id: u64,
vote_yes: bool,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier)));
let vote = if vote_yes { Vote::Yes } else { Vote::No };
let req = ExecuteMsg::Vote { proposal_id, vote };
@@ -101,7 +101,7 @@ impl<C: SigningCosmWasmClient + Sync + Send> MultisigSigningClient for NymdClien
&self,
proposal_id: u64,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier)));
let req = ExecuteMsg::Execute { proposal_id };
self.client
@@ -1,10 +1,10 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::nymd::coin::Coin;
pub use crate::nymd::cosmwasm_client::client::CosmWasmClient;
use crate::nymd::error::NymdError;
use crate::nymd::NymdClient;
use crate::nyxd::coin::Coin;
pub use crate::nyxd::cosmwasm_client::client::CosmWasmClient;
use crate::nyxd::error::NyxdError;
use crate::nyxd::NyxdClient;
use async_trait::async_trait;
use contracts_common::ContractBuildInformation;
use cosmwasm_std::{Coin as CosmWasmCoin, Timestamp};
@@ -18,11 +18,11 @@ use vesting_contract_common::{
#[async_trait]
pub trait VestingQueryClient {
async fn query_vesting_contract<T>(&self, query: VestingQueryMsg) -> Result<T, NymdError>
async fn query_vesting_contract<T>(&self, query: VestingQueryMsg) -> Result<T, NyxdError>
where
for<'a> T: Deserialize<'a>;
async fn get_vesting_contract_version(&self) -> Result<ContractBuildInformation, NymdError> {
async fn get_vesting_contract_version(&self) -> Result<ContractBuildInformation, NyxdError> {
self.query_vesting_contract(VestingQueryMsg::GetContractVersion {})
.await
}
@@ -31,72 +31,72 @@ pub trait VestingQueryClient {
&self,
address: &str,
block_time: Option<Timestamp>,
) -> Result<Coin, NymdError>;
) -> Result<Coin, NyxdError>;
async fn spendable_coins(
&self,
vesting_account_address: &str,
block_time: Option<Timestamp>,
) -> Result<Coin, NymdError>;
) -> Result<Coin, NyxdError>;
async fn vested_coins(
&self,
vesting_account_address: &str,
block_time: Option<Timestamp>,
) -> Result<Coin, NymdError>;
) -> Result<Coin, NyxdError>;
async fn vesting_coins(
&self,
vesting_account_address: &str,
block_time: Option<Timestamp>,
) -> Result<Coin, NymdError>;
) -> Result<Coin, NyxdError>;
async fn vesting_start_time(
&self,
vesting_account_address: &str,
) -> Result<Timestamp, NymdError>;
) -> Result<Timestamp, NyxdError>;
async fn vesting_end_time(&self, vesting_account_address: &str)
-> Result<Timestamp, NymdError>;
-> Result<Timestamp, NyxdError>;
async fn original_vesting(
&self,
vesting_account_address: &str,
) -> Result<OriginalVestingResponse, NymdError>;
) -> Result<OriginalVestingResponse, NyxdError>;
async fn delegated_free(
&self,
vesting_account_address: &str,
block_time: Option<Timestamp>,
) -> Result<Coin, NymdError>;
) -> Result<Coin, NyxdError>;
async fn delegated_vesting(
&self,
vesting_account_address: &str,
block_time: Option<Timestamp>,
) -> Result<Coin, NymdError>;
) -> Result<Coin, NyxdError>;
async fn get_account(&self, address: &str) -> Result<Account, NymdError>;
async fn get_mixnode_pledge(&self, address: &str) -> Result<Option<PledgeData>, NymdError>;
async fn get_gateway_pledge(&self, address: &str) -> Result<Option<PledgeData>, NymdError>;
async fn get_account(&self, address: &str) -> Result<Account, NyxdError>;
async fn get_mixnode_pledge(&self, address: &str) -> Result<Option<PledgeData>, NyxdError>;
async fn get_gateway_pledge(&self, address: &str) -> Result<Option<PledgeData>, NyxdError>;
async fn get_current_vesting_period(
&self,
vesting_account_address: &str,
) -> Result<Period, NymdError>;
) -> Result<Period, NyxdError>;
async fn get_delegation_timestamps(
&self,
address: &str,
mix_id: MixId,
) -> Result<DelegationTimesResponse, NymdError>;
) -> Result<DelegationTimesResponse, NyxdError>;
async fn get_all_vesting_delegations_paged(
&self,
start_after: Option<(u32, MixId, u64)>,
limit: Option<u32>,
) -> Result<AllDelegationsResponse, NymdError>;
) -> Result<AllDelegationsResponse, NyxdError>;
async fn get_all_vesting_delegations(&self) -> Result<Vec<VestingDelegation>, NymdError> {
async fn get_all_vesting_delegations(&self) -> Result<Vec<VestingDelegation>, NyxdError> {
let mut delegations = Vec::new();
let mut start_after = None;
loop {
@@ -117,8 +117,8 @@ pub trait VestingQueryClient {
}
#[async_trait]
impl<C: CosmWasmClient + Sync + Send> VestingQueryClient for NymdClient<C> {
async fn query_vesting_contract<T>(&self, query: VestingQueryMsg) -> Result<T, NymdError>
impl<C: CosmWasmClient + Sync + Send> VestingQueryClient for NyxdClient<C> {
async fn query_vesting_contract<T>(&self, query: VestingQueryMsg) -> Result<T, NyxdError>
where
for<'a> T: Deserialize<'a>,
{
@@ -131,7 +131,7 @@ impl<C: CosmWasmClient + Sync + Send> VestingQueryClient for NymdClient<C> {
&self,
vesting_account_address: &str,
block_time: Option<Timestamp>,
) -> Result<Coin, NymdError> {
) -> Result<Coin, NyxdError> {
let request = VestingQueryMsg::LockedCoins {
vesting_account_address: vesting_account_address.to_string(),
block_time,
@@ -146,7 +146,7 @@ impl<C: CosmWasmClient + Sync + Send> VestingQueryClient for NymdClient<C> {
&self,
vesting_account_address: &str,
block_time: Option<Timestamp>,
) -> Result<Coin, NymdError> {
) -> Result<Coin, NyxdError> {
let request = VestingQueryMsg::SpendableCoins {
vesting_account_address: vesting_account_address.to_string(),
block_time,
@@ -160,7 +160,7 @@ impl<C: CosmWasmClient + Sync + Send> VestingQueryClient for NymdClient<C> {
&self,
vesting_account_address: &str,
block_time: Option<Timestamp>,
) -> Result<Coin, NymdError> {
) -> Result<Coin, NyxdError> {
let request = VestingQueryMsg::GetVestedCoins {
vesting_account_address: vesting_account_address.to_string(),
block_time,
@@ -174,7 +174,7 @@ impl<C: CosmWasmClient + Sync + Send> VestingQueryClient for NymdClient<C> {
&self,
vesting_account_address: &str,
block_time: Option<Timestamp>,
) -> Result<Coin, NymdError> {
) -> Result<Coin, NyxdError> {
let request = VestingQueryMsg::GetVestingCoins {
vesting_account_address: vesting_account_address.to_string(),
block_time,
@@ -188,7 +188,7 @@ impl<C: CosmWasmClient + Sync + Send> VestingQueryClient for NymdClient<C> {
async fn vesting_start_time(
&self,
vesting_account_address: &str,
) -> Result<Timestamp, NymdError> {
) -> Result<Timestamp, NyxdError> {
let request = VestingQueryMsg::GetStartTime {
vesting_account_address: vesting_account_address.to_string(),
};
@@ -200,7 +200,7 @@ impl<C: CosmWasmClient + Sync + Send> VestingQueryClient for NymdClient<C> {
async fn vesting_end_time(
&self,
vesting_account_address: &str,
) -> Result<Timestamp, NymdError> {
) -> Result<Timestamp, NyxdError> {
let request = VestingQueryMsg::GetEndTime {
vesting_account_address: vesting_account_address.to_string(),
};
@@ -212,7 +212,7 @@ impl<C: CosmWasmClient + Sync + Send> VestingQueryClient for NymdClient<C> {
async fn original_vesting(
&self,
vesting_account_address: &str,
) -> Result<OriginalVestingResponse, NymdError> {
) -> Result<OriginalVestingResponse, NyxdError> {
let request = VestingQueryMsg::GetOriginalVesting {
vesting_account_address: vesting_account_address.to_string(),
};
@@ -225,7 +225,7 @@ impl<C: CosmWasmClient + Sync + Send> VestingQueryClient for NymdClient<C> {
&self,
vesting_account_address: &str,
block_time: Option<Timestamp>,
) -> Result<Coin, NymdError> {
) -> Result<Coin, NyxdError> {
let request = VestingQueryMsg::GetDelegatedFree {
vesting_account_address: vesting_account_address.to_string(),
block_time,
@@ -241,7 +241,7 @@ impl<C: CosmWasmClient + Sync + Send> VestingQueryClient for NymdClient<C> {
&self,
vesting_account_address: &str,
block_time: Option<Timestamp>,
) -> Result<Coin, NymdError> {
) -> Result<Coin, NyxdError> {
let request = VestingQueryMsg::GetDelegatedVesting {
vesting_account_address: vesting_account_address.to_string(),
block_time,
@@ -252,7 +252,7 @@ impl<C: CosmWasmClient + Sync + Send> VestingQueryClient for NymdClient<C> {
.map(Into::into)
}
async fn get_account(&self, address: &str) -> Result<Account, NymdError> {
async fn get_account(&self, address: &str) -> Result<Account, NyxdError> {
let request = VestingQueryMsg::GetAccount {
address: address.to_string(),
};
@@ -260,7 +260,7 @@ impl<C: CosmWasmClient + Sync + Send> VestingQueryClient for NymdClient<C> {
.query_contract_smart(self.vesting_contract_address(), &request)
.await
}
async fn get_mixnode_pledge(&self, address: &str) -> Result<Option<PledgeData>, NymdError> {
async fn get_mixnode_pledge(&self, address: &str) -> Result<Option<PledgeData>, NyxdError> {
let request = VestingQueryMsg::GetMixnode {
address: address.to_string(),
};
@@ -268,7 +268,7 @@ impl<C: CosmWasmClient + Sync + Send> VestingQueryClient for NymdClient<C> {
.query_contract_smart(self.vesting_contract_address(), &request)
.await
}
async fn get_gateway_pledge(&self, address: &str) -> Result<Option<PledgeData>, NymdError> {
async fn get_gateway_pledge(&self, address: &str) -> Result<Option<PledgeData>, NyxdError> {
let request = VestingQueryMsg::GetGateway {
address: address.to_string(),
};
@@ -277,7 +277,7 @@ impl<C: CosmWasmClient + Sync + Send> VestingQueryClient for NymdClient<C> {
.await
}
async fn get_current_vesting_period(&self, address: &str) -> Result<Period, NymdError> {
async fn get_current_vesting_period(&self, address: &str) -> Result<Period, NyxdError> {
let request = VestingQueryMsg::GetCurrentVestingPeriod {
address: address.to_string(),
};
@@ -290,7 +290,7 @@ impl<C: CosmWasmClient + Sync + Send> VestingQueryClient for NymdClient<C> {
&self,
address: &str,
mix_id: MixId,
) -> Result<DelegationTimesResponse, NymdError> {
) -> Result<DelegationTimesResponse, NyxdError> {
let request = VestingQueryMsg::GetDelegationTimes {
address: address.to_string(),
mix_id,
@@ -304,7 +304,7 @@ impl<C: CosmWasmClient + Sync + Send> VestingQueryClient for NymdClient<C> {
&self,
start_after: Option<(u32, MixId, u64)>,
limit: Option<u32>,
) -> Result<AllDelegationsResponse, NymdError> {
) -> Result<AllDelegationsResponse, NyxdError> {
let request = VestingQueryMsg::GetAllDelegations { start_after, limit };
self.client
.query_contract_smart(self.vesting_contract_address(), &request)
@@ -1,10 +1,10 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
pub use crate::nymd::cosmwasm_client::signing_client::SigningCosmWasmClient;
use crate::nymd::cosmwasm_client::types::ExecuteResult;
use crate::nymd::error::NymdError;
use crate::nymd::{Coin, Fee, NymdClient};
pub use crate::nyxd::cosmwasm_client::signing_client::SigningCosmWasmClient;
use crate::nyxd::cosmwasm_client::types::ExecuteResult;
use crate::nyxd::error::NyxdError;
use crate::nyxd::{Coin, Fee, NyxdClient};
use async_trait::async_trait;
use mixnet_contract_common::mixnode::{MixNodeConfigUpdate, MixNodeCostParams};
use mixnet_contract_common::{Gateway, MixId, MixNode};
@@ -18,25 +18,25 @@ pub trait VestingSigningClient {
fee: Option<Fee>,
msg: VestingExecuteMsg,
funds: Vec<Coin>,
) -> Result<ExecuteResult, NymdError>;
) -> Result<ExecuteResult, NyxdError>;
async fn vesting_update_mixnode_cost_params(
&self,
new_costs: MixNodeCostParams,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError>;
) -> Result<ExecuteResult, NyxdError>;
async fn vesting_update_mixnode_config(
&self,
new_config: MixNodeConfigUpdate,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError>;
) -> Result<ExecuteResult, NyxdError>;
async fn update_mixnet_address(
&self,
address: &str,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError>;
) -> Result<ExecuteResult, NyxdError>;
async fn vesting_bond_gateway(
&self,
@@ -44,16 +44,16 @@ pub trait VestingSigningClient {
owner_signature: &str,
pledge: Coin,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError>;
) -> Result<ExecuteResult, NyxdError>;
async fn vesting_unbond_gateway(&self, fee: Option<Fee>) -> Result<ExecuteResult, NymdError>;
async fn vesting_unbond_gateway(&self, fee: Option<Fee>) -> Result<ExecuteResult, NyxdError>;
async fn vesting_track_unbond_gateway(
&self,
owner: &str,
amount: Coin,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError>;
) -> Result<ExecuteResult, NyxdError>;
async fn vesting_bond_mixnode(
&self,
@@ -62,13 +62,13 @@ pub trait VestingSigningClient {
owner_signature: &str,
pledge: Coin,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError>;
) -> Result<ExecuteResult, NyxdError>;
async fn vesting_pledge_more(
&self,
additional_pledge: Coin,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_vesting_contract(
fee,
VestingExecuteMsg::PledgeMore {
@@ -79,20 +79,20 @@ pub trait VestingSigningClient {
.await
}
async fn vesting_unbond_mixnode(&self, fee: Option<Fee>) -> Result<ExecuteResult, NymdError>;
async fn vesting_unbond_mixnode(&self, fee: Option<Fee>) -> Result<ExecuteResult, NyxdError>;
async fn vesting_track_unbond_mixnode(
&self,
owner: &str,
amount: Coin,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError>;
) -> Result<ExecuteResult, NyxdError>;
async fn withdraw_vested_coins(
&self,
amount: Coin,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError>;
) -> Result<ExecuteResult, NyxdError>;
async fn vesting_track_undelegation(
&self,
@@ -100,20 +100,20 @@ pub trait VestingSigningClient {
mix_id: MixId,
amount: Coin,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError>;
) -> Result<ExecuteResult, NyxdError>;
async fn vesting_delegate_to_mixnode(
&self,
mix_id: MixId,
amount: Coin,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError>;
) -> Result<ExecuteResult, NyxdError>;
async fn vesting_undelegate_from_mixnode(
&self,
mix_id: MixId,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError>;
) -> Result<ExecuteResult, NyxdError>;
async fn create_periodic_vesting_account(
&self,
@@ -123,17 +123,17 @@ pub trait VestingSigningClient {
amount: Coin,
cap: Option<PledgeCap>,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError>;
) -> Result<ExecuteResult, NyxdError>;
}
#[async_trait]
impl<C: SigningCosmWasmClient + Sync + Send> VestingSigningClient for NymdClient<C> {
impl<C: SigningCosmWasmClient + Sync + Send> VestingSigningClient for NyxdClient<C> {
async fn execute_vesting_contract(
&self,
fee: Option<Fee>,
msg: VestingExecuteMsg,
funds: Vec<Coin>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier)));
let memo = msg.name().to_string();
self.client
@@ -152,7 +152,7 @@ impl<C: SigningCosmWasmClient + Sync + Send> VestingSigningClient for NymdClient
&self,
new_costs: MixNodeCostParams,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_vesting_contract(
fee,
VestingExecuteMsg::UpdateMixnodeCostParams { new_costs },
@@ -165,7 +165,7 @@ impl<C: SigningCosmWasmClient + Sync + Send> VestingSigningClient for NymdClient
&self,
new_config: MixNodeConfigUpdate,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier)));
let req = VestingExecuteMsg::UpdateMixnodeConfig { new_config };
self.client
@@ -184,7 +184,7 @@ impl<C: SigningCosmWasmClient + Sync + Send> VestingSigningClient for NymdClient
&self,
address: &str,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier)));
let req = VestingExecuteMsg::UpdateMixnetAddress {
address: address.to_string(),
@@ -207,7 +207,7 @@ impl<C: SigningCosmWasmClient + Sync + Send> VestingSigningClient for NymdClient
owner_signature: &str,
pledge: Coin,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier)));
let req = VestingExecuteMsg::BondGateway {
gateway,
@@ -226,7 +226,7 @@ impl<C: SigningCosmWasmClient + Sync + Send> VestingSigningClient for NymdClient
.await
}
async fn vesting_unbond_gateway(&self, fee: Option<Fee>) -> Result<ExecuteResult, NymdError> {
async fn vesting_unbond_gateway(&self, fee: Option<Fee>) -> Result<ExecuteResult, NyxdError> {
let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier)));
let req = VestingExecuteMsg::UnbondGateway {};
self.client
@@ -246,7 +246,7 @@ impl<C: SigningCosmWasmClient + Sync + Send> VestingSigningClient for NymdClient
owner: &str,
amount: Coin,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier)));
let req = VestingExecuteMsg::TrackUnbondGateway {
owner: owner.to_string(),
@@ -271,7 +271,7 @@ impl<C: SigningCosmWasmClient + Sync + Send> VestingSigningClient for NymdClient
owner_signature: &str,
pledge: Coin,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_vesting_contract(
fee,
VestingExecuteMsg::BondMixnode {
@@ -285,7 +285,7 @@ impl<C: SigningCosmWasmClient + Sync + Send> VestingSigningClient for NymdClient
.await
}
async fn vesting_unbond_mixnode(&self, fee: Option<Fee>) -> Result<ExecuteResult, NymdError> {
async fn vesting_unbond_mixnode(&self, fee: Option<Fee>) -> Result<ExecuteResult, NyxdError> {
let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier)));
let req = VestingExecuteMsg::UnbondMixnode {};
self.client
@@ -305,7 +305,7 @@ impl<C: SigningCosmWasmClient + Sync + Send> VestingSigningClient for NymdClient
owner: &str,
amount: Coin,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier)));
let req = VestingExecuteMsg::TrackUnbondMixnode {
owner: owner.to_string(),
@@ -327,7 +327,7 @@ impl<C: SigningCosmWasmClient + Sync + Send> VestingSigningClient for NymdClient
&self,
amount: Coin,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier)));
let req = VestingExecuteMsg::WithdrawVestedCoins {
amount: amount.into(),
@@ -350,7 +350,7 @@ impl<C: SigningCosmWasmClient + Sync + Send> VestingSigningClient for NymdClient
mix_id: MixId,
amount: Coin,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_vesting_contract(
fee,
VestingExecuteMsg::TrackUndelegation {
@@ -368,7 +368,7 @@ impl<C: SigningCosmWasmClient + Sync + Send> VestingSigningClient for NymdClient
mix_id: MixId,
amount: Coin,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_vesting_contract(
fee,
VestingExecuteMsg::DelegateToMixnode {
@@ -384,7 +384,7 @@ impl<C: SigningCosmWasmClient + Sync + Send> VestingSigningClient for NymdClient
&self,
mix_id: MixId,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_vesting_contract(
fee,
VestingExecuteMsg::UndelegateFromMixnode { mix_id },
@@ -401,7 +401,7 @@ impl<C: SigningCosmWasmClient + Sync + Send> VestingSigningClient for NymdClient
amount: Coin,
cap: Option<PledgeCap>,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier)));
let req = VestingExecuteMsg::CreateAccount {
owner_address: owner_address.to_string(),
@@ -1,7 +1,7 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::nymd::error::NymdError;
use crate::nyxd::error::NyxdError;
use config::defaults;
use cosmrs::bip32::{DerivationPath, XPrv};
use cosmrs::crypto::secp256k1::{Signature, SigningKey};
@@ -62,16 +62,16 @@ impl DirectSecp256k1HdWallet {
}
/// Restores a wallet from the given BIP39 mnemonic using default options.
pub fn from_mnemonic(prefix: &str, mnemonic: bip39::Mnemonic) -> Result<Self, NymdError> {
pub fn from_mnemonic(prefix: &str, mnemonic: bip39::Mnemonic) -> Result<Self, NyxdError> {
DirectSecp256k1HdWalletBuilder::new(prefix).build(mnemonic)
}
pub fn generate(prefix: &str, word_count: usize) -> Result<Self, NymdError> {
pub fn generate(prefix: &str, word_count: usize) -> Result<Self, NyxdError> {
let mneomonic = bip39::Mnemonic::generate(word_count)?;
Self::from_mnemonic(prefix, mneomonic)
}
fn derive_keypair(&self, hd_path: &DerivationPath) -> Result<Secp256k1Keypair, NymdError> {
fn derive_keypair(&self, hd_path: &DerivationPath) -> Result<Secp256k1Keypair, NyxdError> {
let extended_private_key = XPrv::derive_from_path(self.seed, hd_path)?;
let private_key: SigningKey = extended_private_key.into();
@@ -80,7 +80,7 @@ impl DirectSecp256k1HdWallet {
Ok((private_key, public_key))
}
pub fn try_derive_accounts(&self) -> Result<Vec<AccountData>, NymdError> {
pub fn try_derive_accounts(&self) -> Result<Vec<AccountData>, NyxdError> {
let mut accounts = Vec::with_capacity(self.accounts.len());
for derivation_info in &self.accounts {
let keypair = self.derive_keypair(&derivation_info.hd_path)?;
@@ -89,7 +89,7 @@ impl DirectSecp256k1HdWallet {
let address = keypair
.1
.account_id(&derivation_info.prefix)
.map_err(|_| NymdError::AccountDerivationError)?;
.map_err(|_| NyxdError::AccountDerivationError)?;
accounts.push(AccountData {
address,
@@ -109,36 +109,36 @@ impl DirectSecp256k1HdWallet {
&self,
signer: &AccountData,
message: &[u8],
) -> Result<Signature, NymdError> {
) -> Result<Signature, NyxdError> {
signer
.private_key
.sign(message)
.map_err(|_| NymdError::SigningFailure)
.map_err(|_| NyxdError::SigningFailure)
}
pub fn sign_direct_with_account(
&self,
signer: &AccountData,
sign_doc: SignDoc,
) -> Result<tx::Raw, NymdError> {
// ideally I'd prefer to have the entire error put into the NymdError::SigningFailure
) -> Result<tx::Raw, NyxdError> {
// ideally I'd prefer to have the entire error put into the NyxdError::SigningFailure
// but I'm super hesitant to trying to downcast the eyre::Report to cosmrs::error::Error
sign_doc
.sign(&signer.private_key)
.map_err(|_| NymdError::SigningFailure)
.map_err(|_| NyxdError::SigningFailure)
}
pub fn sign_direct(
&self,
signer_address: &AccountId,
sign_doc: SignDoc,
) -> Result<tx::Raw, NymdError> {
) -> Result<tx::Raw, NyxdError> {
// I hate deriving accounts at every sign here so much : (
let accounts = self.try_derive_accounts()?;
let account = accounts
.iter()
.find(|account| &account.address == signer_address)
.ok_or_else(|| NymdError::SigningAccountNotFound(signer_address.clone()))?;
.ok_or_else(|| NyxdError::SigningAccountNotFound(signer_address.clone()))?;
self.sign_direct_with_account(account, sign_doc)
}
@@ -185,7 +185,7 @@ impl DirectSecp256k1HdWalletBuilder {
self
}
pub fn build(self, mnemonic: bip39::Mnemonic) -> Result<DirectSecp256k1HdWallet, NymdError> {
pub fn build(self, mnemonic: bip39::Mnemonic) -> Result<DirectSecp256k1HdWallet, NyxdError> {
let seed = mnemonic.to_seed(&self.bip39_password);
let prefix = self.prefix;
let accounts = self
+6 -2
View File
@@ -10,7 +10,8 @@ bip39 = "1.0.1"
bs58 = "0.4"
comfy-table = "6.0.0"
cfg-if = "1.0.0"
clap = { version = "3.2", features = ["derive"] }
clap = { version = "4.0", features = ["derive"] }
cw-utils = { version = "0.13.4" }
handlebars = "3.0.1"
humantime-serde = "1.0"
k256 = { version = "0.10", features = ["ecdsa", "sha256"] }
@@ -27,7 +28,10 @@ tap = "1"
cosmrs = { git = "https://github.com/neacsu/cosmos-rust", branch = "neacsu/feegrant_support" }
cosmwasm-std = { version = "1.0.0" }
validator-client = { path = "../client-libs/validator-client", features = ["nymd-client"] }
validator-client = { path = "../client-libs/validator-client", features = ["nyxd-client"] }
network-defaults = { path = "../network-defaults" }
mixnet-contract-common = { path = "../cosmwasm-smart-contracts/mixnet-contract" }
vesting-contract-common = { path = "../cosmwasm-smart-contracts/vesting-contract" }
coconut-bandwidth-contract-common = { path = "../cosmwasm-smart-contracts/coconut-bandwidth-contract" }
coconut-dkg-common = { path = "../cosmwasm-smart-contracts/coconut-dkg" }
multisig-contract-common = { path = "../cosmwasm-smart-contracts/multisig-contract" }

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