Compare commits

...

118 Commits

Author SHA1 Message Date
Fran Arbanas 4b0f3cc093 Merge pull request #1874 from nymtech/bug-fix/hide-display-mnemonic
Bug fix/hide display mnemonic
2022-12-13 15:17:29 +01:00
farbanas 5456b16e3b updated changelogs 2022-12-13 13:23:27 +01:00
farbanas 3b5eab5342 bumped everything by one patch version 2022-12-13 13:15:51 +01:00
Bogdan-Ștefan Neacşu 00f17c376a Use default mainnet values when nothing is specified (#1884) 2022-12-12 16:34:56 +02:00
Jon Häggblad 5283329914 changelog: fix wording 2022-12-09 22:35:37 +01:00
Jon Häggblad 29dd121282 clients: dont panic in base client gateway client handling (#1878)
* client-core: fix some panics related to gateway-client

* changelog: update

* fix
2022-12-09 21:43:37 +01:00
Jon Häggblad cd1d9d1a0d client: pick from old lanes probabilisticlly (#1877)
* Pick from old lanes probabilisticly

* changelog: update
2022-12-09 18:44:40 +01:00
Jon Häggblad b694e675e6 clients: further deduplicate init code (#1873)
* client-core: move init helpers to module

* WIP

* socks5: return error instead of terminate in init

* Extract out reuse_existing_gateway_config

* rustfmt

* Remove comment out code

* nym-connect: use setup_gateway

* Linebreak

* changelog: update

* Tweak log

* rustfmt
2022-12-09 16:12:30 +01:00
Jon Häggblad 39cb6f6ec0 network-requester: return error on socket close (#1876)
* network-requester: return error when the socket closes

* changelog: add note
2022-12-09 15:04:47 +01:00
fmtabbara 7a52124d53 content updates 2022-12-09 13:29:06 +00:00
fmtabbara 2ec5616453 text update 2022-12-09 13:07:59 +00:00
Bogdan-Ștefan Neacşu ebaf99fadb Feature/dkg state to disk (#1872)
* Add PersistentState

* Save and load state to/from disk

* If in progress, don't continually write the same state

* Fix tests and add serde one

* Update changelog

* Fix clippy
2022-12-09 13:00:27 +02:00
fmtabbara c534c4b91d remove fixed height for mnemonic input 2022-12-09 10:28:49 +00:00
Jon Häggblad 85515fe16e Client: dedup setup gateway during init (#1871)
* clients: dedup gateway setup logic

* nym-connect: extract out print_save_config
2022-12-08 22:59:11 +01:00
Jon Häggblad ec60966a85 Clients: save init results to JSON (#1865)
* clients: output results of init to json

* Remove leftover dbg

* Tidy

* Fix nym-connect
2022-12-08 19:39:11 +01:00
Jon Häggblad d1df407bac nym-connect: update Cargo.lock to 1.1.2 2022-12-08 16:58:41 +01:00
Bogdan-Ștefan Neacşu 9ff4051b0f Properly add consumed to table (#1870) 2022-12-08 17:47:41 +02:00
Fouad fea9ec0f9f use mix_id for account to get correct pending cost event (#1869)
* use mix_id for account to get correct pending cost event
2022-12-08 15:42:26 +00:00
Pierre Dommerc d48d094672 Wallet - Buy, copy changes (#1855) 2022-12-08 15:54:33 +01:00
Bogdan-Ștefan Neacşu e1b511e788 Feature/verify bte proof (#1866)
* Update lock file

* Include bte public key verification
2022-12-08 14:06:24 +02:00
Bogdan-Ștefan Neacşu 1500d27ce5 Feature/fix client multi cred consume (#1859)
* Mark consumed credentials in the db

* Add signature log

* Fix wasm mock Storage trait

* Fix clippy
2022-12-08 11:06:31 +02:00
Fouad a0eba073ec refresh balance after sending tokens (#1857) 2022-12-07 17:17:58 +00:00
Fouad 2c3e716ba1 introduce minimize button in custom title bar (#1843) 2022-12-07 17:17:30 +00:00
Bogdan-Ștefan Neacşu b76051832f Add ignore to dkg expensive tests (#1856) 2022-12-07 13:53:28 +02:00
farbanas c966680bba Merge branch 'release/v1.1.2' into develop 2022-12-07 12:36:55 +01:00
farbanas 7f7d30c9b5 docs: updated changelog for contracts release v1.1.2 and updated versions of mixnet and vesting contracts as well 2022-12-07 12:36:24 +01:00
farbanas b08dace119 changed ubuntu-latest on GH actions to ubuntu-20.04 2022-12-07 12:23:33 +01:00
Jon Häggblad 58255857e5 Merge remote-tracking branch 'origin/release/v1.1.2' into develop 2022-12-07 12:14:15 +01:00
fmtabbara bd1d88e9e8 fix display mnemonic bug 2022-12-07 10:40:43 +00:00
Raphaël Walther edf38e6356 Fixed URL to branch 2022-12-07 10:40:43 +01:00
Tommy Verrall e258f62a26 Update qa-qwerty.env 2022-12-07 08:11:11 +01:00
durch 940427776c Resolve merge conflicts 2022-12-06 20:30:57 +01:00
Dave Hrycyszyn 2f7d9254b8 Updated changelog for wallet 2022-12-06 19:13:08 +01:00
farbanas 67321d7d04 update nym-connect CHANGELOG 2022-12-06 19:13:07 +01:00
farbanas e38a20fb58 changed nym-connect version to 1.1.2 2022-12-06 19:12:30 +01:00
Dave Hrycyszyn 8e45e3e995 Modifying changelog for v1.1.2 2022-12-06 19:12:27 +01:00
farbanas 2f63d916b6 changed nym-connect version to 1.1.1 2022-12-06 19:12:07 +01:00
farbanas 0b465e1f09 update versions for platfrom, nym-connect and nym-wallet to v1.1.2 2022-12-06 19:12:02 +01:00
pierre f93aab2f5b fix(wallet): buy tutorial ui responsivness 2022-12-06 19:09:38 +01:00
pierre 7ff06cfe3e fix(wallet): typo 2022-12-06 19:09:38 +01:00
pierre 8c7e7dfcd1 fix(wallet): typo 2022-12-06 19:09:38 +01:00
pierre 31ca88fd7f refactor(wallet): clean code 2022-12-06 19:09:38 +01:00
pierre 51b29a9dcf feat(wallet): add link to nym exchange interface 2022-12-06 19:09:38 +01:00
pierre d58c2da463 feat(wallet-buy-nym): update signature modal ui 2022-12-06 19:09:38 +01:00
pierre 5644726a7b fix(wallet-buy-nym): signature output 2022-12-06 19:09:38 +01:00
pierre e9ba34ba52 feat(wallet-buy-nym): buy page new ui 2022-12-06 19:09:38 +01:00
pierre a33e848d6d Revert "feat(explorer-api): add route to fetch nym terms&cdts"
This reverts commit 876f752697d89061b1904e1ddd1d5bcb7045dc5c.
2022-12-06 19:09:38 +01:00
pierre 3da9d2944b feat(explorer-api): add route to fetch nym terms&cdts 2022-12-06 19:09:38 +01:00
pierre e2c9f69ab9 feat(wallet-buy): tutorial 2022-12-06 19:09:38 +01:00
pierre 8a21f183f9 feat(wallet): buy page bootstrap 2022-12-06 19:09:38 +01:00
Bogdan-Ștefan Neacșu cb2a89dceb Fix clippy 2022-12-06 19:09:38 +01:00
Bogdan-Ștefan Neacşu 502e23b42c Feature/simplify credential binary (#1841)
* Expose name of standard directories

* Use one command instead of two
2022-12-06 19:09:38 +01:00
Jon Häggblad 2676c68b77 nym-connect/changelog: add note about disconnect fix 2022-12-06 19:09:36 +01:00
Bogdan-Ștefan Neacşu c5252f348d Fix comment in configuration file (#1836) 2022-12-06 19:09:15 +01:00
Bogdan-Ștefan Neacşu bd8cea3ba3 Use better naming on gateway credential handling (#1834) 2022-12-06 19:09:13 +01:00
Jędrzej Stuczyński 7ddc8e80e6 Fixed layer distribution skewness check (#1766) 2022-12-06 19:08:10 +01:00
Drazen Urch 03a974ec34 Node family management (#1670)
* Family management messages

* Add family queries

* Add queries to client

* Layer assignment message

* Paged family queries, annotate mixnodes with family

* Add layer assignments to epoch operations

* Remove family layer peristence

* Add NotImplemented error for kick

Co-authored-by: Jędrzej Stuczyński <jedrzej.stuczynski@gmail.com>
2022-12-06 19:08:07 +01:00
Bogdan-Ștefan Neacşu 5c841de6ae Feature/dkg integration tests (#1815)
* DKG contract e2e test

* Refactor to the same format as other contracts

* Vk share tests

* State tests

* Dealings tests

* Dealer tests

* Api dkg tests

* Fix path to contract after refactor

* Fix test target clippy
2022-12-06 19:06:31 +01:00
Bogdan-Ștefan Neacşu 9a8218905e Use config URLs in clients before the env values (#1813) 2022-12-06 19:06:31 +01:00
Raphaël Walther f6fca0ad37 Corrected env variable name in workflows 2022-12-06 15:45:32 +01:00
Fouad 9a8c5c3708 Feature/wallet content updates (#1825)
* fix up balance screen

* fix up app bar and nym logo alignment

* fix up delegation action icon font weight

* fix up bond page
2022-12-06 14:11:04 +00:00
Dave Hrycyszyn c39afd0b65 Updated changelog for wallet 2022-12-06 13:58:59 +00:00
farbanas 31be7a6170 update nym-connect CHANGELOG 2022-12-06 14:42:12 +01:00
farbanas fee780489c changed nym-connect version to 1.1.2 2022-12-06 14:08:33 +01:00
Dave Hrycyszyn 957c6fbba0 Modifying changelog for v1.1.2 2022-12-06 13:04:31 +00:00
farbanas 7e56a7a8b2 changed nym-connect version to 1.1.1 2022-12-06 13:53:35 +01:00
farbanas b273df297a update versions for platfrom, nym-connect and nym-wallet to v1.1.2 2022-12-06 13:50:45 +01:00
Dave Hrycyszyn d4979c1f0a Merge branch 'feature/buy' into release/v1.1.2 2022-12-06 12:35:26 +00:00
Raphaël Walther 52136d727b Set explorer to use rpc.nymtech.net 2022-12-06 11:00:33 +01:00
Fouad edd5c363bb remove extra checks to display vesting schedule(#1826) 2022-12-06 09:37:11 +00:00
Bogdan-Ștefan Neacșu 1171f18399 Fix clippy 2022-12-06 10:48:32 +02:00
Jon Häggblad 028bee804b nym-connect: append error to failed message (#1839)
* nym-connect: append error to failed message

* changelog: add note
2022-12-05 15:58:59 +01:00
Bogdan-Ștefan Neacşu 2515646075 Feature/simplify credential binary (#1841)
* Expose name of standard directories

* Use one command instead of two
2022-12-05 16:58:36 +02:00
Jon Häggblad 74d34aeebc nym-connect/changelog: add note about disconnect fix 2022-12-05 14:53:05 +01:00
Jon Häggblad a16c566719 common/task: extract out spawn_with_report_error (#1837) 2022-12-05 14:44:44 +01:00
Bogdan-Ștefan Neacşu d495aefb0d Fix comment in configuration file (#1836) 2022-12-05 15:03:01 +02:00
Gala 667d5f3033 Merge pull request #1828 from nymtech/feat-508-bond-more
Feat 508 bond more
2022-12-05 13:13:57 +01:00
Bogdan-Ștefan Neacşu ce4fd0588c Use better naming on gateway credential handling (#1834) 2022-12-05 14:02:30 +02:00
Gala b51aac6047 Merge branch 'develop' into feat-508-bond-more 2022-12-05 12:18:13 +01:00
Gala a21be84833 adding a oversaturaded bonding more modal 2022-12-05 12:13:14 +01:00
Jon Häggblad 49f7c48b1b client: add --no-cover and update --fastmode (#1831) 2022-12-05 11:14:41 +01:00
Jędrzej Stuczyński 29c073d25c Fixed layer distribution skewness check (#1766) 2022-12-05 09:28:32 +00:00
Drazen Urch 7e3bc2d6bb Node family management (#1670)
* Family management messages

* Add family queries

* Add queries to client

* Layer assignment message

* Paged family queries, annotate mixnodes with family

* Add layer assignments to epoch operations

* Remove family layer peristence

* Add NotImplemented error for kick

Co-authored-by: Jędrzej Stuczyński <jedrzej.stuczynski@gmail.com>
2022-12-05 09:36:06 +01:00
Jon Häggblad 6943271942 validator-api: remove storage dependency in contract cache (#1685)
* validator-api: remove storage dependency in contract cache

* validator-client: update detailed routes

* contract_cache: forward to new endpoints for compat

* Move reward_estimate
2022-12-02 14:40:19 +01:00
Jon Häggblad a872b478d2 gateway-client: handle shutdown listener (#1829)
* WIP

* WIP: try another approach

* WIP

* Reworked

* Tidy

* fix
2022-12-02 12:36:06 +01:00
Jon Häggblad 11051ba929 validator-api: add missing shortform for --config-env-file (#1830) 2022-12-02 09:23:34 +01:00
Jon Häggblad 10e28c6e5c envs/mainnet: update to latest mixnet contract and nymd validator url 2022-12-01 23:09:37 +01:00
Gala 78af0bff71 amount error 2022-12-01 16:47:46 +01:00
pierre e15183029b fix(wallet): buy tutorial ui responsivness 2022-12-01 16:39:27 +01:00
pierre 39ab252941 fix(wallet): typo 2022-12-01 16:00:42 +01:00
Gala 3d2dee3e1c avoid mix tokens pools 2022-12-01 15:46:58 +01:00
pierre 4ccd4d258a fix(wallet): typo 2022-12-01 15:40:09 +01:00
Jon Häggblad ab4e39e1b3 Fix a few errors in socks5 client and network-requester (backport) (#1824)
* Fix two unwraps in socks5 and network-requester

* Make sure client task never sends shutdown signal
2022-12-01 14:25:59 +01:00
Jędrzej Stuczyński 66e5119114 Feature/pledge more (#1679)
* New transactions for increasing amount of pledged tokens

* unit tests

* Added an option to pledge extra tokens through the vesting contract

* Introduced wallet endpoints for new operations

* Using updated pledge cap in the vesting contract

* Changelog update
2022-12-01 12:51:32 +00:00
Gala 96c0256154 Merge branch 'develop' into feat-508-bond-more 2022-12-01 13:46:21 +01:00
Gala bf207abe55 logs removal 2022-12-01 13:25:32 +01:00
Gala 4069b0349d display details modal 2022-12-01 13:15:16 +01:00
Gala bca20e1dfd connecting to the back and making the requests work 2022-12-01 12:57:28 +01:00
Gala 1bc94d8fd4 Merge branch 'feature/pledge-more' into feat-508-bond-more 2022-12-01 11:47:44 +01:00
Gala a269bd8289 wip 2022-12-01 11:46:58 +01:00
Jon Häggblad eedf3d996a Merge remote-tracking branch 'origin/release/v1.1.1' into release/v1.1.3 2022-12-01 11:38:36 +01:00
Bogdan-Ștefan Neacşu 5d51f4dc71 Feature/dkg integration tests (#1815)
* DKG contract e2e test

* Refactor to the same format as other contracts

* Vk share tests

* State tests

* Dealings tests

* Dealer tests

* Api dkg tests

* Fix path to contract after refactor

* Fix test target clippy
2022-11-29 18:32:37 +02:00
Jędrzej Stuczyński bc25288d08 Using updated pledge cap in the vesting contract 2022-11-29 16:18:21 +00:00
Jędrzej Stuczyński 3a001e2f9f Introduced wallet endpoints for new operations 2022-11-29 16:08:55 +00:00
Jędrzej Stuczyński 09cad3c589 Added an option to pledge extra tokens through the vesting contract 2022-11-29 16:08:11 +00:00
Jędrzej Stuczyński ab0180c5ce unit tests 2022-11-29 16:08:11 +00:00
Jędrzej Stuczyński a77f364466 New transactions for increasing amount of pledged tokens 2022-11-29 16:03:54 +00:00
Jon Häggblad 9d60de0091 Merge remote-tracking branch 'origin/release/v1.1.2' into release/v1.1.3 2022-11-29 12:57:48 +01:00
Bogdan-Ștefan Neacşu ca7c5d80ce Use config URLs in clients before the env values (#1813) 2022-11-29 13:52:08 +02:00
pierre 731780993f refactor(wallet): clean code 2022-11-28 16:01:08 +01:00
pierre c02bcb460f feat(wallet): add link to nym exchange interface 2022-11-28 13:36:17 +01:00
pierre bdb6aa848e feat(wallet-buy-nym): update signature modal ui 2022-11-28 10:35:15 +01:00
pierre 32b535d67f fix(wallet-buy-nym): signature output 2022-11-28 10:35:15 +01:00
pierre 9e1109a577 feat(wallet-buy-nym): buy page new ui 2022-11-28 10:35:15 +01:00
pierre 247a7ba1dc Revert "feat(explorer-api): add route to fetch nym terms&cdts"
This reverts commit 876f752697d89061b1904e1ddd1d5bcb7045dc5c.
2022-11-28 10:35:15 +01:00
pierre 77d10358d4 feat(explorer-api): add route to fetch nym terms&cdts 2022-11-28 10:35:15 +01:00
pierre fb2a61bed3 feat(wallet-buy): tutorial 2022-11-28 10:35:15 +01:00
pierre 4c2c101e57 feat(wallet): buy page bootstrap 2022-11-28 10:35:15 +01:00
236 changed files with 6695 additions and 3680 deletions
+2 -2
View File
@@ -5,7 +5,7 @@ on:
- cron: '5 9 * * *'
jobs:
cargo-deny:
runs-on: ubuntu-latest
runs-on: ubuntu-20.04
steps:
- name: Checkout repository code
uses: actions/checkout@v2
@@ -26,7 +26,7 @@ jobs:
path: .github/workflows/support-files/notifications/deny.message
notification:
needs: cargo-deny
runs-on: ubuntu-latest
runs-on: ubuntu-20.04
steps:
- name: Check out repository code
uses: actions/checkout@v2
+1 -1
View File
@@ -1,6 +1,6 @@
[
{
"os":"ubuntu-latest",
"os":"ubuntu-20.04",
"rust":"stable",
"runOnEvent":"always"
},
+1 -1
View File
@@ -6,7 +6,7 @@ on:
jobs:
build:
runs-on: ubuntu-latest
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v2
+2 -2
View File
@@ -10,7 +10,7 @@ on:
jobs:
matrix_prep:
runs-on: ubuntu-latest
runs-on: ubuntu-20.04
outputs:
matrix: ${{ steps.set-matrix.outputs.matrix }}
steps:
@@ -24,7 +24,7 @@ jobs:
contracts:
# since it's going to be compiled into wasm, there's absolutely
# no point in running CI on different OS-es
runs-on: ubuntu-latest
runs-on: ubuntu-20.04
continue-on-error: ${{ matrix.rust == 'nightly' }}
needs: matrix_prep
strategy:
+1 -1
View File
@@ -13,7 +13,7 @@ jobs:
strategy:
fail-fast: false
matrix:
platform: [ubuntu-latest]
platform: [ubuntu-20.04]
runs-on: ${{ matrix.platform }}
steps:
+4 -4
View File
@@ -5,7 +5,7 @@ on:
- cron: '14 1 * * *'
jobs:
matrix_prep:
runs-on: ubuntu-latest
runs-on: ubuntu-20.04
outputs:
matrix: ${{ steps.set-matrix.outputs.matrix }}
steps:
@@ -25,7 +25,7 @@ jobs:
steps:
- name: Install Dependencies (Linux)
run: sudo apt-get update && sudo apt-get install libwebkit2gtk-4.0-dev build-essential curl wget libssl-dev libgtk-3-dev libudev-dev squashfs-tools
if: matrix.os == 'ubuntu-latest'
if: matrix.os == 'ubuntu-20.04'
- name: Check out repository code
uses: actions/checkout@v2
@@ -96,7 +96,7 @@ jobs:
- name: Reclaim some disk space
uses: actions-rs/cargo@v1
if: ${{ matrix.os == 'windows-latest' || matrix.os == 'ubuntu-latest' }}
if: ${{ matrix.os == 'windows-latest' || matrix.os == 'ubuntu-20.04' }}
with:
command: clean
@@ -160,7 +160,7 @@ jobs:
notification:
needs: build
runs-on: ubuntu-latest
runs-on: ubuntu-20.04
steps:
- name: Collect jobs status
uses: technote-space/workflow-conclusion-action@v2
@@ -1,6 +1,6 @@
[
{
"os":"ubuntu-latest",
"os":"ubuntu-20.04",
"rust":"stable",
"runOnEvent":"schedule"
},
@@ -17,7 +17,7 @@
},
{
"os":"ubuntu-latest",
"os":"ubuntu-20.04",
"rust":"beta",
"runOnEvent":"schedule"
},
@@ -33,7 +33,7 @@
},
{
"os":"ubuntu-latest",
"os":"ubuntu-20.04",
"rust":"nightly",
"runOnEvent":"schedule"
},
+6 -6
View File
@@ -5,7 +5,7 @@ on:
- cron: '14 2 * * *'
jobs:
matrix_prep:
runs-on: ubuntu-latest
runs-on: ubuntu-20.04
outputs:
matrix: ${{ steps.set-matrix.outputs.matrix }}
steps:
@@ -17,7 +17,7 @@ jobs:
inputFile: '.github/workflows/nightly_build_matrix_includes.json'
filter: '[?runOnEvent==`${{ github.event_name }}` || runOnEvent==`always`]'
get_release:
runs-on: ubuntu-latest
runs-on: ubuntu-20.04
needs: matrix_prep
outputs:
output1: ${{ steps.step2.outputs.latest_release }}
@@ -38,7 +38,7 @@ jobs:
steps:
- name: Install Dependencies (Linux)
run: sudo apt-get update && sudo apt-get install libwebkit2gtk-4.0-dev build-essential curl wget libssl-dev libgtk-3-dev libudev-dev squashfs-tools
if: matrix.os == 'ubuntu-latest'
if: matrix.os == 'ubuntu-20.04'
- name: Check out latest release branch
uses: actions/checkout@v3
@@ -111,7 +111,7 @@ jobs:
- name: Reclaim some disk space
uses: actions-rs/cargo@v1
if: ${{ matrix.os == 'windows-latest' || matrix.os == 'ubuntu-latest' }}
if: ${{ matrix.os == 'windows-latest' || matrix.os == 'ubuntu-20.04' }}
with:
command: clean
@@ -175,7 +175,7 @@ jobs:
notification:
needs: [build,get_release]
runs-on: ubuntu-latest
runs-on: ubuntu-20.04
steps:
- name: Collect jobs status
uses: technote-space/workflow-conclusion-action@v2
@@ -192,7 +192,7 @@ jobs:
NYM_PROJECT_NAME: "Nym nightly build on latest release"
GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}"
GIT_COMMIT_MESSAGE: "${{ github.event.head_commit.message }}"
GIT_BRANCH: "https://github.com/nymtech/nym/tree/${{needs.get_release.outputs.output1}}"
GIT_BRANCH_NAME: "${{needs.get_release.outputs.output1}}"
KEYBASE_NYMBOT_USERNAME: "${{ secrets.KEYBASE_NYMBOT_USERNAME }}"
KEYBASE_NYMBOT_PAPERKEY: "${{ secrets.KEYBASE_NYMBOT_PAPERKEY }}"
KEYBASE_NYMBOT_TEAM: "${{ secrets.KEYBASE_NYMBOT_TEAM }}"
+6 -6
View File
@@ -5,7 +5,7 @@ on:
- cron: '24 2 * * *'
jobs:
matrix_prep:
runs-on: ubuntu-latest
runs-on: ubuntu-20.04
outputs:
matrix: ${{ steps.set-matrix.outputs.matrix }}
steps:
@@ -17,7 +17,7 @@ jobs:
inputFile: '.github/workflows/nightly_build_matrix_includes.json'
filter: '[?runOnEvent==`${{ github.event_name }}` || runOnEvent==`always`]'
get_release:
runs-on: ubuntu-latest
runs-on: ubuntu-20.04
needs: matrix_prep
outputs:
output1: ${{ steps.step2.outputs.latest_release }}
@@ -38,7 +38,7 @@ jobs:
steps:
- name: Install Dependencies (Linux)
run: sudo apt-get update && sudo apt-get install libwebkit2gtk-4.0-dev build-essential curl wget libssl-dev libgtk-3-dev libudev-dev squashfs-tools
if: matrix.os == 'ubuntu-latest'
if: matrix.os == 'ubuntu-20.04'
- name: Check out latest release branch
uses: actions/checkout@v3
@@ -111,7 +111,7 @@ jobs:
- name: Reclaim some disk space
uses: actions-rs/cargo@v1
if: ${{ matrix.os == 'windows-latest' || matrix.os == 'ubuntu-latest' }}
if: ${{ matrix.os == 'windows-latest' || matrix.os == 'ubuntu-20.04' }}
with:
command: clean
@@ -175,7 +175,7 @@ jobs:
notification:
needs: [build,get_release]
runs-on: ubuntu-latest
runs-on: ubuntu-20.04
steps:
- name: Collect jobs status
uses: technote-space/workflow-conclusion-action@v2
@@ -192,7 +192,7 @@ jobs:
NYM_PROJECT_NAME: "Nym nightly build on latest release"
GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}"
GIT_COMMIT_MESSAGE: "${{ github.event.head_commit.message }}"
GIT_BRANCH: "https://github.com/nymtech/nym/tree/${{needs.get_release.outputs.output1}}"
GIT_BRANCH_NAME: "${{needs.get_release.outputs.output1}}"
KEYBASE_NYMBOT_USERNAME: "${{ secrets.KEYBASE_NYMBOT_USERNAME }}"
KEYBASE_NYMBOT_PAPERKEY: "${{ secrets.KEYBASE_NYMBOT_PAPERKEY }}"
KEYBASE_NYMBOT_TEAM: "${{ secrets.KEYBASE_NYMBOT_TEAM }}"
+1 -1
View File
@@ -13,7 +13,7 @@ jobs:
strategy:
fail-fast: false
matrix:
platform: [ubuntu-latest, windows-latest, macos-latest]
platform: [ubuntu-20.04, windows-latest, macos-latest]
runs-on: ${{ matrix.platform }}
steps:
@@ -13,7 +13,7 @@ jobs:
strategy:
fail-fast: false
matrix:
platform: [ubuntu-latest]
platform: [ubuntu-20.04]
runs-on: ${{ matrix.platform }}
steps:
+1 -1
View File
@@ -19,7 +19,7 @@ jobs:
strategy:
fail-fast: false
matrix:
platform: [ubuntu-latest]
platform: [ubuntu-20.04]
runs-on: ${{ matrix.platform }}
steps:
@@ -12,7 +12,7 @@ jobs:
strategy:
fail-fast: false
matrix:
platform: [ubuntu-latest]
platform: [ubuntu-20.04]
runs-on: ${{ matrix.platform }}
steps:
+1 -1
View File
@@ -12,7 +12,7 @@ jobs:
strategy:
fail-fast: false
matrix:
platform: [ubuntu-latest]
platform: [ubuntu-20.04]
runs-on: ${{ matrix.platform }}
steps:
- uses: actions/checkout@v2
+1 -1
View File
@@ -12,7 +12,7 @@ defaults:
jobs:
test:
name: wallet tests
runs-on: ubuntu-latest
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v2
@@ -85,7 +85,7 @@ async function getMessageBody(context) {
...
],
check_run_url: 'https://api.github.com/repos/nymtech/nym/check-runs/5182940024',
labels: [ 'ubuntu-latest' ],
labels: [ 'ubuntu-20.04' ],
runner_id: 1,
runner_name: 'Hosted Agent',
runner_group_id: 2,
+1 -1
View File
@@ -7,7 +7,7 @@ on:
jobs:
wasm:
runs-on: ubuntu-latest
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v2
+24 -3
View File
@@ -2,12 +2,33 @@
Post 1.0.0 release, the changelog format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## Unreleased
## [Unreleased]
### Added
## [v1.1.3] (2022-12-13)
- socks5-client/network-requester: add support for socks4a protocol
### Changed
- validator-api: can recover from shutdown during DKG process ([#1872])
- clients: deduplicate gateway inititialization, part of work towards a rust-sdk
- clients: keep all transmission lanes going at all times by making priority probabilistic
### Fixed
- 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])
[#1872]: https://github.com/nymtech/nym/pull/1872
[#1884]: https://github.com/nymtech/nym/pull/1884
## [v1.1.2]
### Changed
- 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
## [v1.1.1](https://github.com/nymtech/nym/tree/v1.1.1) (2022-11-29)
Generated
+18 -78
View File
@@ -586,7 +586,7 @@ dependencies = [
[[package]]
name = "client-core"
version = "1.1.1"
version = "1.1.2"
dependencies = [
"client-connections",
"config",
@@ -603,6 +603,7 @@ dependencies = [
"pemstore",
"rand 0.7.3",
"serde",
"serde_json",
"sled",
"tap",
"task",
@@ -924,7 +925,6 @@ dependencies = [
name = "credential"
version = "0.1.0"
dependencies = [
"async-trait",
"bip39",
"cfg-if 0.1.10",
"clap 3.2.8",
@@ -936,7 +936,6 @@ dependencies = [
"crypto",
"network-defaults",
"pemstore",
"pickledb",
"rand 0.7.3",
"serde",
"thiserror",
@@ -2670,7 +2669,7 @@ checksum = "fe435806c197dfeaa5efcded5e623c4b8230fd28fdf1e91e7a86e40ef2acbf90"
dependencies = [
"arrayref",
"no-std-compat",
"snafu 0.7.1",
"snafu",
]
[[package]]
@@ -2746,12 +2745,6 @@ dependencies = [
"vcpkg",
]
[[package]]
name = "linked-hash-map"
version = "0.5.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7fb9b38af92608140b86b693604b9ffcc5824240a484d1ecd4795bacb2fe88f3"
[[package]]
name = "lioness"
version = "0.1.2"
@@ -3123,7 +3116,7 @@ dependencies = [
[[package]]
name = "nym-cli"
version = "1.1.1"
version = "1.1.2"
dependencies = [
"anyhow",
"base64",
@@ -3177,7 +3170,7 @@ dependencies = [
[[package]]
name = "nym-client"
version = "1.1.1"
version = "1.1.2"
dependencies = [
"clap 3.2.8",
"client-connections",
@@ -3217,7 +3210,7 @@ dependencies = [
[[package]]
name = "nym-gateway"
version = "1.1.1"
version = "1.1.2"
dependencies = [
"anyhow",
"async-trait",
@@ -3264,7 +3257,7 @@ dependencies = [
[[package]]
name = "nym-mixnode"
version = "1.1.1"
version = "1.1.2"
dependencies = [
"anyhow",
"bs58",
@@ -3306,7 +3299,7 @@ dependencies = [
[[package]]
name = "nym-network-requester"
version = "1.1.1"
version = "1.1.2"
dependencies = [
"async-trait",
"clap 3.2.8",
@@ -3338,7 +3331,7 @@ dependencies = [
[[package]]
name = "nym-network-statistics"
version = "1.0.2"
version = "1.1.2"
dependencies = [
"dirs",
"log",
@@ -3354,7 +3347,7 @@ dependencies = [
[[package]]
name = "nym-socks5-client"
version = "1.1.1"
version = "1.1.2"
dependencies = [
"clap 3.2.8",
"client-connections",
@@ -3380,7 +3373,7 @@ dependencies = [
"proxy-helpers",
"rand 0.7.3",
"serde",
"snafu 0.6.10",
"serde_json",
"socks5-requests",
"tap",
"task",
@@ -3421,7 +3414,7 @@ dependencies = [
[[package]]
name = "nym-validator-api"
version = "1.1.1"
version = "1.1.2"
dependencies = [
"anyhow",
"async-trait",
@@ -3935,19 +3928,6 @@ dependencies = [
"indexmap",
]
[[package]]
name = "pickledb"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9161694d67f6c5163519d42be942ae36bbdb55f439460144f105bc4f9f7d1d61"
dependencies = [
"bincode",
"serde",
"serde_cbor",
"serde_json",
"serde_yaml",
]
[[package]]
name = "pin-project"
version = "1.0.10"
@@ -5026,9 +5006,9 @@ dependencies = [
[[package]]
name = "serde_json"
version = "1.0.83"
version = "1.0.89"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "38dd04e3c8279e75b31ef29dbdceebfe5ad89f4d0937213c53f7d49d01b3d5a7"
checksum = "020ff22c755c2ed3f8cf162dbb41a7268d934702f3ed3631656ea597e08fc3db"
dependencies = [
"itoa 1.0.1",
"ryu",
@@ -5058,18 +5038,6 @@ dependencies = [
"serde",
]
[[package]]
name = "serde_yaml"
version = "0.8.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4a521f2940385c165a24ee286aa8599633d162077a54bdcae2a6fd5a7bfa7a0"
dependencies = [
"indexmap",
"ryu",
"serde",
"yaml-rust",
]
[[package]]
name = "sha-1"
version = "0.8.2"
@@ -5228,16 +5196,6 @@ version = "1.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2dd574626839106c320a323308629dcb1acfc96e32a8cba364ddc61ac23ee83"
[[package]]
name = "snafu"
version = "0.6.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eab12d3c261b2308b0d80c26fffb58d17eba81a4be97890101f416b478c79ca7"
dependencies = [
"doc-comment",
"snafu-derive 0.6.10",
]
[[package]]
name = "snafu"
version = "0.7.1"
@@ -5245,18 +5203,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5177903bf45656592d9eb5c0e22f408fc023aae51dbe2088889b71633ba451f2"
dependencies = [
"doc-comment",
"snafu-derive 0.7.1",
]
[[package]]
name = "snafu-derive"
version = "0.6.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1508efa03c362e23817f96cde18abed596a25219a8b2c66e8db33c03543d315b"
dependencies = [
"proc-macro2",
"quote",
"syn",
"snafu-derive",
]
[[package]]
@@ -5700,6 +5647,8 @@ dependencies = [
"log",
"thiserror",
"tokio",
"wasm-bindgen",
"wasm-bindgen-futures",
]
[[package]]
@@ -6568,7 +6517,7 @@ checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f"
[[package]]
name = "vesting-contract"
version = "1.1.0"
version = "1.1.2"
dependencies = [
"contracts-common",
"cosmwasm-std",
@@ -6939,15 +6888,6 @@ dependencies = [
"zeroize",
]
[[package]]
name = "yaml-rust"
version = "0.4.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "56c1936c4cc7a1c9ab21a1ebb602eb942ba868cbd44a99cb7cdc5892335e1c85"
dependencies = [
"linked-hash-map",
]
[[package]]
name = "yansi"
version = "0.5.1"
+3 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "client-core"
version = "1.1.1"
version = "1.1.3"
authors = ["Dave Hrycyszyn <futurechimp@users.noreply.github.com>"]
edition = "2021"
@@ -13,11 +13,12 @@ humantime-serde = "1.0"
log = "0.4"
rand = { version = "0.7.3", features = ["wasm-bindgen"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0.89"
sled = { version = "0.34", optional = true }
tap = "1.0.1"
thiserror = "1.0.34"
url = { version ="2.2", features = ["serde"] }
tokio = { version = "1.21.2", features = ["time", "macros"]}
url = { version ="2.2", features = ["serde"] }
# internal
config = { path = "../../common/config" }
@@ -23,12 +23,11 @@ use gateway_client::{
AcknowledgementReceiver, AcknowledgementSender, GatewayClient, MixnetMessageReceiver,
MixnetMessageSender,
};
use log::info;
use log::{debug, info};
use nymsphinx::addressing::clients::Recipient;
use nymsphinx::addressing::nodes::NodeIdentity;
#[cfg(feature = "reply-surb")]
use std::path::PathBuf;
#[cfg(feature = "reply-surb")]
use tap::TapFallible;
use task::{ShutdownListener, ShutdownNotifier};
use url::Url;
@@ -236,22 +235,22 @@ impl<'a> BaseClientBuilder<'a> {
mixnet_message_sender: MixnetMessageSender,
ack_sender: AcknowledgementSender,
shutdown: ShutdownListener,
) -> GatewayClient {
) -> Result<GatewayClient, ClientCoreError> {
let gateway_id = self.gateway_config.gateway_id.clone();
if gateway_id.is_empty() {
panic!("The identity of the gateway is unknown - did you run `nym-client` init?")
return Err(ClientCoreError::GatewayIdUnknown);
}
let gateway_owner = self.gateway_config.gateway_owner.clone();
if gateway_owner.is_empty() {
panic!("The owner of the gateway is unknown - did you run `nym-client` init?")
return Err(ClientCoreError::GatewayOwnerUnknown);
}
let gateway_address = self.gateway_config.gateway_listener.clone();
if gateway_address.is_empty() {
panic!("The address of the gateway is unknown - did you run `nym-client` init?")
return Err(ClientCoreError::GatwayAddressUnknown);
}
let gateway_identity = identity::PublicKey::from_base58_string(gateway_id)
.expect("provided gateway id is invalid!");
.map_err(ClientCoreError::UnableToCreatePublicKeyFromGatewayId)?;
// disgusting wasm workaround since there's no key persistence there (nor `client init`)
let shared_key = if self.key_manager.gateway_key_set() {
@@ -270,7 +269,7 @@ impl<'a> BaseClientBuilder<'a> {
ack_sender,
self.debug_config.gateway_response_timeout,
self.bandwidth_controller.take(),
Some(shutdown),
shutdown,
);
gateway_client.set_disabled_credentials_mode(self.disabled_credentials);
@@ -278,9 +277,10 @@ impl<'a> BaseClientBuilder<'a> {
gateway_client
.authenticate_and_start()
.await
.expect("could not authenticate and start up the gateway connection");
gateway_client
.tap_err(|err| {
log::error!("Could not authenticate and start up the gateway connection - {err}")
})?;
Ok(gateway_client)
}
// future responsible for periodically polling directory server and updating
@@ -375,7 +375,7 @@ impl<'a> BaseClientBuilder<'a> {
let gateway_client = self
.start_gateway_client(mixnet_messages_sender, ack_sender, shutdown.subscribe())
.await;
.await?;
// The sphinx_message_sender is the transmitter for any component generating sphinx packets
// that are to be sent to the mixnet. They are used by cover traffic stream and real
@@ -412,8 +412,8 @@ impl<'a> BaseClientBuilder<'a> {
);
}
info!("Client startup finished!");
info!("The address of this client is: {}", self.as_mix_recipient());
debug!("Core client startup finished!");
debug!("The address of this client is: {}", self.as_mix_recipient());
Ok(BaseClient {
client_input: ClientInputStatus::AwaitingProducer {
@@ -191,7 +191,7 @@ impl LoopCoverTrafficStream<OsRng> {
// However it's still useful to alert the user that the gateway or the link to
// the gateway can't keep up. Either due to insufficient bandwidth on the
// client side, or that the gateway is overloaded.
log::warn!("Failed to send: gateway appears to not keep up");
log::warn!("Failed to send sphinx packet - gateway or connection to gatway can't keep up");
}
TrySendError::Closed(_) => {
log::warn!("Failed to send cover message - channel closed");
@@ -489,7 +489,7 @@ where
fn log_status_infrequent(&self) {
if self.sending_delay_controller.current_multiplier() > 1 {
log::warn!(
"Unable to send packets fast enough - sending delay multiplier set to: {}",
"Unable to send packets at the default rate - rate reduced by setting the delay multiplier set to: {}",
self.sending_delay_controller.current_multiplier()
);
}
@@ -2,7 +2,7 @@
// SPDX-License-Identifier: Apache-2.0
use client_connections::TransmissionLane;
use rand::seq::SliceRandom;
use rand::{seq::SliceRandom, Rng};
use std::{
collections::{HashMap, HashSet, VecDeque},
time::Duration,
@@ -116,9 +116,15 @@ impl TransmissionBuffer {
lanes.choose(&mut rand::thread_rng()).copied()
}
// 2/3 chance to pick from the old lanes
fn pick_random_old_lane(&self) -> Option<TransmissionLane> {
let lanes = self.get_oldest_set();
lanes.choose(&mut rand::thread_rng()).copied()
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()
}
}
fn pop_front_from_lane(&mut self, lane: &TransmissionLane) -> Option<RealMessage> {
@@ -187,13 +187,10 @@ impl TopologyRefresher {
/// # Arguments
///
/// * `topology`: active topology constructed from validator api data
/// * `mixnodes_count`: total number of active mixnodes
fn check_layer_distribution(
&self,
active_topology: &NymTopology,
mixnodes_count: usize,
) -> bool {
fn check_layer_distribution(&self, active_topology: &NymTopology) -> bool {
let mixes = active_topology.mixes();
let mixnodes_count = active_topology.num_mixnodes();
if active_topology.gateways().is_empty() {
return false;
}
@@ -258,11 +255,10 @@ impl TopologyRefresher {
Ok(gateways) => gateways,
};
let mixnodes_count = mixnodes.len();
let topology = nym_topology_from_detailed(mixnodes, gateways)
.filter_system_version(&self.client_version);
if !self.check_layer_distribution(&topology, mixnodes_count) {
if !self.check_layer_distribution(&topology) {
warn!("The current filtered active topology has extremely skewed layer distribution. It cannot be used.");
None
} else {
+21 -8
View File
@@ -1,7 +1,7 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use config::NymConfig;
use config::{NymConfig, DB_FILE_NAME};
use nymsphinx::params::PacketSize;
use serde::{Deserialize, Serialize};
use std::marker::PhantomData;
@@ -34,6 +34,10 @@ pub fn missing_string_value() -> String {
MISSING_VALUE.to_string()
}
pub trait ClientCoreConfigTrait {
fn get_gateway_endpoint(&self) -> &GatewayEndpointConfig;
}
#[derive(Debug, Clone, Deserialize, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Config<T> {
@@ -45,6 +49,12 @@ pub struct Config<T> {
debug: DebugConfig,
}
impl<T> ClientCoreConfigTrait for Config<T> {
fn get_gateway_endpoint(&self) -> &GatewayEndpointConfig {
&self.client.gateway_endpoint
}
}
impl<T> Config<T> {
pub fn new<S: Into<String>>(id: S) -> Self
where
@@ -141,8 +151,15 @@ impl<T> Config<T> {
pub fn set_high_default_traffic_volume(&mut self) {
self.debug.average_packet_delay = Duration::from_millis(10);
self.debug.loop_cover_traffic_average_delay = Duration::from_millis(2_000_000); // basically don't really send cover messages
self.debug.message_sending_average_delay = Duration::from_millis(4); // 250 "real" messages / s
// basically don't really send cover messages
self.debug.loop_cover_traffic_average_delay = Duration::from_millis(2_000_000);
// 250 "real" messages / s
self.debug.message_sending_average_delay = Duration::from_millis(4);
}
pub fn set_no_cover_traffic(&mut self) {
self.debug.disable_loop_cover_traffic_stream = true;
self.debug.disable_main_poisson_packet_distribution = true;
}
pub fn set_custom_version(&mut self, version: &str) {
@@ -213,10 +230,6 @@ impl<T> Config<T> {
&self.client.gateway_endpoint
}
pub fn get_gateway_endpoint(&self) -> &GatewayEndpointConfig {
&self.client.gateway_endpoint
}
pub fn get_database_path(&self) -> PathBuf {
self.client.database_path.clone()
}
@@ -426,7 +439,7 @@ impl<T: NymConfig> Client<T> {
T::default_data_directory(Some(id)).join("reply_key_store")
}
fn default_database_path(id: &str) -> PathBuf {
T::default_data_directory(Some(id)).join("db.sqlite")
T::default_data_directory(Some(id)).join(DB_FILE_NAME)
}
}
+12
View File
@@ -26,6 +26,8 @@ pub enum ClientCoreError {
NoGatewayWithId(String),
#[error("No gateways on network")]
NoGatewaysOnNetwork,
#[error("Failed to setup gateway")]
FailedToSetupGateway,
#[error("List of validator apis is empty")]
ListOfValidatorApisIsEmpty,
#[error("Could not load existing gateway configuration: {0}")]
@@ -33,6 +35,16 @@ pub enum ClientCoreError {
#[error("The current network topology seem to be insufficient to route any packets through")]
InsufficientNetworkTopology,
#[error("The gateway id is invalid - {0}")]
UnableToCreatePublicKeyFromGatewayId(Ed25519RecoveryError),
#[error("The identity of the gateway is unknwown - did you run init?")]
GatewayIdUnknown,
#[error("The owner of the gateway is unknown - did you run init?")]
GatewayOwnerUnknown,
#[error("The address of the gateway is unknown - did you run init?")]
GatwayAddressUnknown,
#[error("Unexpected exit")]
UnexpectedExit,
}
@@ -1,22 +1,14 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
//! Collection of initialization steps used by client implementations
use std::{sync::Arc, time::Duration};
use rand::{rngs::OsRng, seq::SliceRandom, thread_rng};
use tap::TapFallible;
use url::Url;
use config::NymConfig;
use crypto::asymmetric::{encryption, identity};
use crypto::asymmetric::identity;
use gateway_client::GatewayClient;
use gateway_requests::registration::handshake::SharedKeys;
use nymsphinx::addressing::clients::Recipient;
use nymsphinx::addressing::nodes::NodeIdentity;
use rand::rngs::OsRng;
use rand::seq::SliceRandom;
use rand::thread_rng;
use tap::TapFallible;
use topology::{filter::VersionFilterable, gateway};
use url::Url;
use crate::{
client::key_manager::KeyManager,
@@ -24,9 +16,9 @@ use crate::{
error::ClientCoreError,
};
pub async fn query_gateway_details(
pub(super) async fn query_gateway_details(
validator_servers: Vec<Url>,
chosen_gateway_id: Option<&str>,
chosen_gateway_id: Option<String>,
) -> Result<gateway::Node, ClientCoreError> {
let validator_api = validator_servers
.choose(&mut thread_rng())
@@ -59,7 +51,30 @@ pub async fn query_gateway_details(
}
}
pub async fn register_with_gateway_and_store_keys<T>(
async fn register_with_gateway(
gateway: &gateway::Node,
our_identity: Arc<identity::KeyPair>,
) -> Result<Arc<SharedKeys>, ClientCoreError> {
let timeout = Duration::from_millis(1500);
let mut gateway_client = GatewayClient::new_init(
gateway.clients_address(),
gateway.identity_key,
gateway.owner.clone(),
our_identity.clone(),
timeout,
);
gateway_client
.establish_connection()
.await
.tap_err(|_| log::warn!("Failed to establish connection with gateway!"))?;
let shared_keys = gateway_client
.perform_initial_authentication()
.await
.tap_err(|_| log::warn!("Failed to register with the gateway!"))?;
Ok(shared_keys)
}
pub(super) async fn register_with_gateway_and_store_keys<T>(
gateway_details: gateway::Node,
config: &Config<T>,
) -> Result<(), ClientCoreError>
@@ -78,71 +93,3 @@ where
.store_keys(&pathfinder)
.tap_err(|err| log::error!("Failed to generate keys: {err}"))?)
}
async fn register_with_gateway(
gateway: &gateway::Node,
our_identity: Arc<identity::KeyPair>,
) -> Result<Arc<SharedKeys>, ClientCoreError> {
let timeout = Duration::from_millis(1500);
let mut gateway_client = GatewayClient::new_init(
gateway.clients_address(),
gateway.identity_key,
gateway.owner.clone(),
our_identity.clone(),
timeout,
None,
);
gateway_client
.establish_connection()
.await
.tap_err(|_| log::warn!("Failed to establish connection with gateway!"))?;
let shared_keys = gateway_client
.perform_initial_authentication()
.await
.tap_err(|_| log::warn!("Failed to register with the gateway!"))?;
Ok(shared_keys)
}
pub fn show_address<T>(config: &Config<T>) -> Result<(), ClientCoreError>
where
T: config::NymConfig,
{
fn load_identity_keys(
pathfinder: &ClientKeyPathfinder,
) -> Result<identity::KeyPair, ClientCoreError> {
let identity_keypair: identity::KeyPair =
pemstore::load_keypair(&pemstore::KeyPairPath::new(
pathfinder.private_identity_key().to_owned(),
pathfinder.public_identity_key().to_owned(),
))
.tap_err(|_| log::error!("Failed to read stored identity key files"))?;
Ok(identity_keypair)
}
fn load_sphinx_keys(
pathfinder: &ClientKeyPathfinder,
) -> Result<encryption::KeyPair, ClientCoreError> {
let sphinx_keypair: encryption::KeyPair =
pemstore::load_keypair(&pemstore::KeyPairPath::new(
pathfinder.private_encryption_key().to_owned(),
pathfinder.public_encryption_key().to_owned(),
))
.tap_err(|_| log::error!("Failed to read stored sphinx key files"))?;
Ok(sphinx_keypair)
}
let pathfinder = ClientKeyPathfinder::new_from_config(config);
let identity_keypair = load_identity_keys(&pathfinder)?;
let sphinx_keypair = load_sphinx_keys(&pathfinder)?;
let client_recipient = Recipient::new(
*identity_keypair.public_key(),
*sphinx_keypair.public_key(),
// TODO: below only works under assumption that gateway address == gateway id
// (which currently is true)
NodeIdentity::from_base58_string(config.get_gateway_id())?,
);
println!("\nThe address of this client is: {}", client_recipient);
Ok(())
}
+191
View File
@@ -0,0 +1,191 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
//! Collection of initialization steps used by client implementations
use std::fmt::Display;
use nymsphinx::addressing::{clients::Recipient, nodes::NodeIdentity};
use serde::Serialize;
use tap::TapFallible;
use config::NymConfig;
use crypto::asymmetric::{encryption, identity};
use crate::{
config::{
persistence::key_pathfinder::ClientKeyPathfinder, ClientCoreConfigTrait, Config,
GatewayEndpointConfig,
},
error::ClientCoreError,
init::helpers::{query_gateway_details, register_with_gateway_and_store_keys},
};
mod helpers;
#[derive(Debug, Serialize)]
pub struct InitResults {
version: String,
id: String,
identity_key: String,
encryption_key: String,
gateway_id: String,
gateway_listener: String,
}
impl InitResults {
pub fn new<T>(config: &Config<T>, address: &Recipient) -> Self
where
T: NymConfig,
{
Self {
version: config.get_version().to_string(),
id: config.get_id(),
identity_key: address.identity().to_base58_string(),
encryption_key: address.encryption_key().to_base58_string(),
gateway_id: config.get_gateway_id(),
gateway_listener: config.get_gateway_listener(),
}
}
}
impl Display for InitResults {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
writeln!(f, "Version: {}", self.version)?;
writeln!(f, "ID: {}", self.id)?;
writeln!(f, "Identity key: {}", self.identity_key)?;
writeln!(f, "Encryption: {}", self.encryption_key)?;
writeln!(f, "Gateway ID: {}", self.gateway_id)?;
write!(f, "Gateway: {}", self.gateway_listener)
}
}
/// Convenience function for setting up the gateway for a client. Depending on the arguments given
/// it will do the sensible thing.
pub async fn setup_gateway<C: NymConfig + ClientCoreConfigTrait, T: NymConfig>(
register_gateway: bool,
user_chosen_gateway_id: Option<String>,
config: &Config<T>,
) -> Result<GatewayEndpointConfig, ClientCoreError> {
let id = config.get_id();
if register_gateway {
register_with_gateway(user_chosen_gateway_id, config).await
} else if let Some(user_chosen_gateway_id) = user_chosen_gateway_id {
config_gateway_with_existing_keys(user_chosen_gateway_id, config).await
} else {
reuse_existing_gateway_config::<C>(&id)
}
}
/// Get the gateway details by querying the validator-api. Either pick one at random or use
/// the chosen one if it's among the available ones.
/// Saves keys to disk, specified by the paths in `config`.
pub async fn register_with_gateway<T: NymConfig>(
user_chosen_gateway_id: Option<String>,
config: &Config<T>,
) -> Result<GatewayEndpointConfig, ClientCoreError> {
println!("Configuring gateway");
let gateway =
query_gateway_details(config.get_validator_api_endpoints(), user_chosen_gateway_id).await?;
log::debug!("Querying gateway gives: {}", gateway);
// Registering with gateway by setting up and writing shared keys to disk
log::trace!("Registering gateway");
register_with_gateway_and_store_keys(gateway.clone(), config).await?;
println!("Saved all generated keys");
Ok(gateway.into())
}
/// Set the gateway using the usual procedue of querying the validator-api, but don't register or
/// create any keys.
/// This assumes that the user knows what they are doing, and that the existing keys are valid for
/// the gateway being used
pub async fn config_gateway_with_existing_keys<T: NymConfig>(
user_chosen_gateway_id: String,
config: &Config<T>,
) -> Result<GatewayEndpointConfig, ClientCoreError> {
println!("Using gateway provided by user, keeping existing keys");
let gateway = query_gateway_details(
config.get_validator_api_endpoints(),
Some(user_chosen_gateway_id),
)
.await?;
log::debug!("Querying gateway gives: {}", gateway);
Ok(gateway.into())
}
/// Read and reuse the existing gateway configuration from a file that was generate earlier.
pub fn reuse_existing_gateway_config<T: NymConfig + ClientCoreConfigTrait>(
id: &str,
) -> Result<GatewayEndpointConfig, ClientCoreError> {
println!("Not registering gateway, will reuse existing config and keys");
T::load_from_file(Some(id))
.map(|existing_config| existing_config.get_gateway_endpoint().clone())
.map_err(|err| {
log::error!(
"Unable to configure gateway: {err}. \n
Seems like the client was already initialized but it was not possible to read \
the existing configuration file. \n
CAUTION: Consider backing up your gateway keys and try force gateway registration, or \
removing the existing configuration and starting over."
);
ClientCoreError::CouldNotLoadExistingGatewayConfiguration(err)
})
}
/// Get the client address by loading the keys from stored files.
pub fn get_client_address_from_stored_keys<T>(
config: &Config<T>,
) -> Result<Recipient, ClientCoreError>
where
T: config::NymConfig,
{
fn load_identity_keys(
pathfinder: &ClientKeyPathfinder,
) -> Result<identity::KeyPair, ClientCoreError> {
let identity_keypair: identity::KeyPair =
pemstore::load_keypair(&pemstore::KeyPairPath::new(
pathfinder.private_identity_key().to_owned(),
pathfinder.public_identity_key().to_owned(),
))
.tap_err(|_| log::error!("Failed to read stored identity key files"))?;
Ok(identity_keypair)
}
fn load_sphinx_keys(
pathfinder: &ClientKeyPathfinder,
) -> Result<encryption::KeyPair, ClientCoreError> {
let sphinx_keypair: encryption::KeyPair =
pemstore::load_keypair(&pemstore::KeyPairPath::new(
pathfinder.private_encryption_key().to_owned(),
pathfinder.public_encryption_key().to_owned(),
))
.tap_err(|_| log::error!("Failed to read stored sphinx key files"))?;
Ok(sphinx_keypair)
}
let pathfinder = ClientKeyPathfinder::new_from_config(config);
let identity_keypair = load_identity_keys(&pathfinder)?;
let sphinx_keypair = load_sphinx_keys(&pathfinder)?;
let client_recipient = Recipient::new(
*identity_keypair.public_key(),
*sphinx_keypair.public_key(),
// TODO: below only works under assumption that gateway address == gateway id
// (which currently is true)
NodeIdentity::from_base58_string(config.get_gateway_id())?,
);
Ok(client_recipient)
}
pub fn output_to_json<T: Serialize>(init_results: &T, output_file: &str) {
match std::fs::File::create(output_file) {
Ok(file) => match serde_json::to_writer_pretty(file, init_results) {
Ok(_) => println!("Saved: {}", output_file),
Err(err) => eprintln!("Could not save {}: {}", output_file, err),
},
Err(err) => eprintln!("Could not save {}: {}", output_file, err),
}
}
-2
View File
@@ -6,11 +6,9 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
async-trait = "0.1.52"
bip39 = "1.0.1"
cfg-if = "0.1"
clap = { version = "3.2", features = ["cargo", "derive"] }
pickledb = "0.4.1"
rand = "0.7.3"
serde = { version = "1.0", features = ["derive"] }
thiserror = "1.0"
+71 -164
View File
@@ -1,14 +1,12 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use async_trait::async_trait;
use clap::{Args, Subcommand};
use completions::ArgShell;
use pickledb::PickleDb;
use rand::rngs::OsRng;
use std::str::FromStr;
use coconut_interface::{Attribute, Base58, BlindSignRequest, Bytable, Parameters};
use coconut_interface::{Base58, Parameters};
use credential_storage::storage::Storage;
use credential_storage::PersistentStorage;
use credentials::coconut::bandwidth::{BandwidthVoucher, TOTAL_ATTRIBUTES};
@@ -20,16 +18,12 @@ use validator_client::{CoconutApiClient, Config};
use crate::client::Client;
use crate::error::{CredentialClientError, Result};
use crate::state::{KeyPair, RequestData, State};
use crate::state::{KeyPair, State};
#[derive(Subcommand)]
pub(crate) enum Commands {
/// Deposit funds for buying coconut credential
Deposit(Deposit),
/// Lists the tx hashes of previous deposits
ListDeposits(ListDeposits),
/// Get a credential for a given deposit
GetCredential(GetCredential),
pub(crate) enum Command {
/// Run the binary
Run(Run),
/// Generate shell completions
Completions(ArgShell),
@@ -38,169 +32,82 @@ pub(crate) enum Commands {
GenerateFigSpec,
}
#[async_trait]
pub(crate) trait Execute {
async fn execute(&self, db: &mut PickleDb, shared_storage: PersistentStorage) -> Result<()>;
}
#[derive(Args)]
pub(crate) struct Run {
/// Home directory of the client that is supposed to use the credential.
#[clap(long)]
pub(crate) client_home_directory: std::path::PathBuf,
#[derive(Args, Clone)]
pub(crate) struct Deposit {
/// The nymd URL that should be used
#[clap(long)]
nymd_url: String,
/// A mnemonic for the account that does the deposit
pub(crate) nymd_url: String,
/// A mnemonic for the account that buys the credential
#[clap(long)]
mnemonic: String,
/// The amount that needs to be deposited
pub(crate) mnemonic: String,
/// The amount of utokens the credential will hold
#[clap(long)]
amount: u64,
pub(crate) amount: u64,
}
#[async_trait]
impl Execute for Deposit {
async fn execute(&self, db: &mut PickleDb, _shared_storage: PersistentStorage) -> Result<()> {
let mut rng = OsRng;
let signing_keypair = KeyPair::from(identity::KeyPair::new(&mut rng));
let encryption_keypair = KeyPair::from(encryption::KeyPair::new(&mut rng));
pub(crate) async fn deposit(nymd_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(&self.nymd_url, &self.mnemonic);
let tx_hash = client
.deposit(
self.amount,
signing_keypair.public_key.clone(),
encryption_keypair.public_key.clone(),
None,
)
.await?;
let state = State {
amount: self.amount,
tx_hash: tx_hash.clone(),
signing_keypair,
encryption_keypair,
blind_request_data: None,
signature: None,
};
db.set(&tx_hash, &state).unwrap();
println!("{:?}", state);
Ok(())
}
}
#[derive(Args, Clone)]
pub(crate) struct ListDeposits {}
#[async_trait]
impl Execute for ListDeposits {
async fn execute(&self, db: &mut PickleDb, _shared_storage: PersistentStorage) -> Result<()> {
for kv in db.iter() {
println!("{:?}", kv.get_value::<State>());
}
Ok(())
}
}
#[derive(Args, Clone)]
pub(crate) struct GetCredential {
/// The hash of a successful deposit transaction
#[clap(long)]
tx_hash: String,
/// The nymd URL that should be used
#[clap(long)]
nymd_url: String,
/// If we want to get the signature without attaching a blind sign request; it is expected that
/// there is already a signature stored on the signer
#[clap(long, parse(from_flag))]
__no_request: bool,
}
#[async_trait]
impl Execute for GetCredential {
async fn execute(&self, db: &mut PickleDb, shared_storage: PersistentStorage) -> Result<()> {
let mut state = db
.get::<State>(&self.tx_hash)
.ok_or(CredentialClientError::NoDeposit)?;
let network_details = NymNetworkDetails::new_from_env();
let config = Config::try_from_nym_network_details(&network_details)?;
let client = validator_client::Client::new_query(config)?;
let coconut_api_clients = CoconutApiClient::all_coconut_api_clients(&client).await?;
let params = Parameters::new(TOTAL_ATTRIBUTES).unwrap();
let bandwidth_credential_attributes = if self.__no_request {
if let Some(blind_request_data) = state.blind_request_data {
let serial_number =
Attribute::try_from_byte_slice(&blind_request_data.serial_number)
.map_err(|_| CredentialClientError::CorruptedBlindSignRequest)?;
let binding_number =
Attribute::try_from_byte_slice(&blind_request_data.binding_number)
.map_err(|_| CredentialClientError::CorruptedBlindSignRequest)?;
let pedersen_commitments_openings = vec![
Attribute::try_from_byte_slice(&blind_request_data.first_attribute)
.map_err(|_| CredentialClientError::CorruptedBlindSignRequest)?,
Attribute::try_from_byte_slice(&blind_request_data.second_attribute)
.map_err(|_| CredentialClientError::CorruptedBlindSignRequest)?,
];
let blind_sign_request =
BlindSignRequest::from_bytes(blind_request_data.blind_sign_req.as_slice())
.map_err(|_| CredentialClientError::CorruptedBlindSignRequest)?;
BandwidthVoucher::new_with_blind_sign_req(
[serial_number, binding_number],
[&state.amount.to_string(), VOUCHER_INFO],
Hash::from_str(&self.tx_hash)
.map_err(|_| CredentialClientError::InvalidTxHash)?,
identity::PrivateKey::from_base58_string(&state.signing_keypair.private_key)?,
encryption::PrivateKey::from_base58_string(
&state.encryption_keypair.private_key,
)?,
pedersen_commitments_openings,
blind_sign_request,
)
} else {
return Err(CredentialClientError::NoLocalBlindSignRequest);
}
} else {
BandwidthVoucher::new(
&params,
state.amount.to_string(),
VOUCHER_INFO.to_string(),
Hash::from_str(&self.tx_hash).map_err(|_| CredentialClientError::InvalidTxHash)?,
identity::PrivateKey::from_base58_string(&state.signing_keypair.private_key)?,
encryption::PrivateKey::from_base58_string(&state.encryption_keypair.private_key)?,
)
};
// Back up the blind sign req data, in case of sporadic failures
state.blind_request_data = Some(RequestData::new(
bandwidth_credential_attributes.get_private_attributes(),
bandwidth_credential_attributes.pedersen_commitments_openings(),
bandwidth_credential_attributes.blind_sign_request(),
)?);
db.set(&self.tx_hash, &state).unwrap();
let signature = obtain_aggregate_signature(
&params,
&bandwidth_credential_attributes,
&coconut_api_clients,
let client = Client::new(nymd_url, mnemonic);
let tx_hash = client
.deposit(
amount,
signing_keypair.public_key.clone(),
encryption_keypair.public_key.clone(),
None,
)
.await?;
shared_storage
.insert_coconut_credential(
state.amount.to_string(),
VOUCHER_INFO.to_string(),
bandwidth_credential_attributes.get_private_attributes()[0].to_bs58(),
bandwidth_credential_attributes.get_private_attributes()[1].to_bs58(),
signature.to_bs58(),
)
.await?;
state.signature = Some(signature.to_bs58());
db.set(&self.tx_hash, &state).unwrap();
println!("Signature: {:?}", state.signature);
let state = State {
amount,
tx_hash,
signing_keypair,
encryption_keypair,
};
Ok(())
}
Ok(state)
}
pub(crate) async fn get_credential(state: &State, shared_storage: PersistentStorage) -> Result<()> {
let network_details = NymNetworkDetails::new_from_env();
let config = Config::try_from_nym_network_details(&network_details)?;
let client = validator_client::Client::new_query(config)?;
let coconut_api_clients = CoconutApiClient::all_coconut_api_clients(&client).await?;
let params = Parameters::new(TOTAL_ATTRIBUTES).unwrap();
let bandwidth_credential_attributes = BandwidthVoucher::new(
&params,
state.amount.to_string(),
VOUCHER_INFO.to_string(),
Hash::from_str(&state.tx_hash).map_err(|_| CredentialClientError::InvalidTxHash)?,
identity::PrivateKey::from_base58_string(&state.signing_keypair.private_key)?,
encryption::PrivateKey::from_base58_string(&state.encryption_keypair.private_key)?,
);
let signature = obtain_aggregate_signature(
&params,
&bandwidth_credential_attributes,
&coconut_api_clients,
)
.await?;
println!("Signature: {:?}", signature.to_bs58());
shared_storage
.insert_coconut_credential(
state.amount.to_string(),
VOUCHER_INFO.to_string(),
bandwidth_credential_attributes.get_private_attributes()[0].to_bs58(),
bandwidth_credential_attributes.get_private_attributes()[1].to_bs58(),
signature.to_bs58(),
)
.await?;
Ok(())
}
-12
View File
@@ -23,18 +23,6 @@ pub enum CredentialClientError {
#[error("Credential error: {0}")]
Credential(#[from] CredentialError),
#[error("No previous deposit with that tx hash")]
NoDeposit,
#[error("Wrong number of attributes")]
WrongAttributeNumber,
#[error("Could not find any backed up blind sign request data")]
NoLocalBlindSignRequest,
#[error("The local blind sign request data is corrupted")]
CorruptedBlindSignRequest,
#[error("The tx hash provided is not valid")]
InvalidTxHash,
+14 -32
View File
@@ -9,14 +9,13 @@ cfg_if::cfg_if! {
mod error;
mod state;
use commands::{Commands, Execute};
use error::Result;
use network_defaults::setup_env;
use clap::CommandFactory;
use completions::fig_generate;
use commands::*;
use config::{DATA_DIR, DB_FILE_NAME};
use clap::Parser;
use pickledb::{PickleDb, PickleDbDumpPolicy, SerializationMethod};
use clap::{CommandFactory, Parser};
#[derive(Parser)]
#[clap(author = "Nymtech", version, about)]
@@ -25,43 +24,26 @@ cfg_if::cfg_if! {
#[clap(short, long)]
pub(crate) config_env_file: Option<std::path::PathBuf>,
/// Path where the sqlite credental database will be located.
/// It should point to a $HOME/$CLIENT_ID/data/db.sqlite file of
/// the client that is supposed to use the credential.
#[clap(long)]
pub(crate) credential_db_path: std::path::PathBuf,
#[clap(subcommand)]
command: Commands,
pub(crate) command: Command,
}
#[tokio::main]
async fn main() -> Result<()> {
let args = Cli::parse();
setup_env(args.config_env_file.clone());
let shared_storage = credential_storage::initialise_storage(args.credential_db_path.clone()).await;
let mut db = match PickleDb::load(
"credential.db",
PickleDbDumpPolicy::AutoDump,
SerializationMethod::Json,
) {
Ok(db) => db,
Err(_) => PickleDb::new(
"credential.db",
PickleDbDumpPolicy::AutoDump,
SerializationMethod::Json,
),
};
let bin_name = "nym-credential-client";
match &args.command {
Commands::Deposit(m) => m.execute(&mut db, shared_storage).await?,
Commands::ListDeposits(m) => m.execute(&mut db, shared_storage).await?,
Commands::GetCredential(m) => m.execute(&mut db, shared_storage).await?,
Commands::Completions(s) => s.generate(&mut crate::Cli::into_app(), bin_name),
Commands::GenerateFigSpec => fig_generate(&mut crate::Cli::into_app(), bin_name)
match args.command {
Command::Run(r) => {
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?;
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)
}
Ok(())
-34
View File
@@ -1,13 +1,10 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use coconut_interface::{Attribute, BlindSignRequest, Bytable, PrivateAttribute};
use serde::{Deserialize, Serialize};
use crypto::asymmetric::{encryption, identity};
use crate::error::{CredentialClientError, Result};
#[derive(Clone, Debug, Deserialize, Serialize)]
pub(crate) struct KeyPair {
pub public_key: String,
@@ -38,35 +35,4 @@ pub(crate) struct State {
pub tx_hash: String,
pub signing_keypair: KeyPair,
pub encryption_keypair: KeyPair,
pub blind_request_data: Option<RequestData>,
pub signature: Option<String>,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub(crate) struct RequestData {
pub serial_number: Vec<u8>,
pub binding_number: Vec<u8>,
pub first_attribute: Vec<u8>,
pub second_attribute: Vec<u8>,
pub blind_sign_req: Vec<u8>,
}
impl RequestData {
pub fn new(
private_attributes: Vec<PrivateAttribute>,
attributes: &[Attribute],
blind_sign_request: &BlindSignRequest,
) -> Result<Self> {
if private_attributes.len() != 2 || attributes.len() != 2 {
Err(CredentialClientError::WrongAttributeNumber)
} else {
Ok(RequestData {
serial_number: private_attributes[0].to_byte_vec(),
binding_number: private_attributes[1].to_byte_vec(),
first_attribute: attributes[0].to_byte_vec(),
second_attribute: attributes[1].to_byte_vec(),
blind_sign_req: blind_sign_request.to_bytes(),
})
}
}
}
+3 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "nym-client"
version = "1.1.1"
version = "1.1.3"
authors = ["Dave Hrycyszyn <futurechimp@users.noreply.github.com>", "Jędrzej Stuczyński <andrew@nymtech.net>"]
description = "Implementation of the Nym Client"
edition = "2021"
@@ -26,7 +26,9 @@ 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
serde = { version = "1.0.104", features = ["derive"] } # for config serialization/deserialization
serde_json = "1.0"
sled = "0.34" # for storage of replySURB decryption keys
tap = "1.0.1"
thiserror = "1.0.34"
tokio = { version = "1.21.2", features = ["rt-multi-thread", "net", "signal"] } # async runtime
tokio-tungstenite = "0.14" # websocket
@@ -51,7 +53,6 @@ topology = { path = "../../common/topology" }
validator-client = { path = "../../common/client-libs/validator-client", features = ["nymd-client"] }
version-checker = { path = "../../common/version-checker" }
websocket-requests = { path = "websocket-requests" }
tap = "1.0.1"
[features]
coconut = ["coconut-interface", "credentials", "credentials/coconut", "gateway-requests/coconut", "gateway-client/coconut", "client-core/coconut"]
+8 -2
View File
@@ -2,8 +2,8 @@
// SPDX-License-Identifier: Apache-2.0
use crate::client::config::template::config_template;
use client_core::config::Config as BaseConfig;
pub use client_core::config::MISSING_VALUE;
use client_core::config::{ClientCoreConfigTrait, Config as BaseConfig};
use config::defaults::DEFAULT_WEBSOCKET_LISTENING_PORT;
use config::NymConfig;
use serde::{Deserialize, Serialize};
@@ -28,7 +28,7 @@ impl SocketType {
}
}
pub fn is_websocket(&self) -> bool {
pub fn is_websocket(self) -> bool {
matches!(self, SocketType::WebSocket)
}
}
@@ -73,6 +73,12 @@ impl NymConfig for Config {
}
}
impl ClientCoreConfigTrait for Config {
fn get_gateway_endpoint(&self) -> &client_core::config::GatewayEndpointConfig {
self.base.get_gateway_endpoint()
}
}
impl Config {
pub fn new<S: Into<String>>(id: S) -> Self {
Config {
+15 -2
View File
@@ -44,8 +44,21 @@ impl SocketClient {
#[cfg(feature = "coconut")]
let bandwidth_controller = {
let details = network_defaults::NymNetworkDetails::new_from_env();
let client_config = validator_client::Config::try_from_nym_network_details(&details)
.expect("failed to construct validator client config");
let mut client_config =
validator_client::Config::try_from_nym_network_details(&details)
.expect("failed to construct validator client config");
let nymd_url = config
.get_base()
.get_validator_endpoints()
.pop()
.expect("No nymd validator endpoint provided");
let api_url = config
.get_base()
.get_validator_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);
let client = validator_client::Client::new_query(client_config)
.expect("Could not construct query client");
let coconut_api_clients =
+73 -75
View File
@@ -1,13 +1,18 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use std::fmt::Display;
use clap::Args;
use client_core::{config::GatewayEndpointConfig, error::ClientCoreError};
use config::NymConfig;
use nymsphinx::addressing::clients::Recipient;
use serde::Serialize;
use tap::TapFallible;
use crate::{
client::config::Config,
commands::{override_config, OverrideConfig},
error::ClientError,
};
#[derive(Args, Clone)]
@@ -46,11 +51,19 @@ pub(crate) struct Init {
#[clap(long, hidden = true)]
fastmode: bool,
/// Disable loop cover traffic and the Poisson rate limiter (for debugging only)
#[clap(long, hidden = 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,
/// Save a summary of the initialization to a json file
#[clap(long)]
output_json: bool,
}
impl From<Init> for OverrideConfig {
@@ -61,6 +74,7 @@ impl From<Init> for OverrideConfig {
disable_socket: init_config.disable_socket,
port: init_config.port,
fastmode: init_config.fastmode,
no_cover: init_config.no_cover,
#[cfg(feature = "coconut")]
enabled_credentials_mode: init_config.enabled_credentials_mode,
@@ -68,7 +82,30 @@ impl From<Init> for OverrideConfig {
}
}
pub(crate) async fn execute(args: &Init) {
#[derive(Debug, Serialize)]
pub struct InitResults {
#[serde(flatten)]
client_core: client_core::init::InitResults,
client_listening_port: String,
}
impl InitResults {
fn new(config: &Config, address: &Recipient) -> Self {
Self {
client_core: client_core::init::InitResults::new(config.get_base(), address),
client_listening_port: config.get_listening_port().to_string(),
}
}
}
impl Display for InitResults {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
writeln!(f, "{}", self.client_core)?;
write!(f, "Client listening port: {}", self.client_listening_port)
}
}
pub(crate) async fn execute(args: &Init) -> Result<(), ClientError> {
println!("Initialising client...");
let id = &args.id;
@@ -92,25 +129,44 @@ pub(crate) async fn execute(args: &Init) {
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.as_deref();
let user_chosen_gateway_id = args.gateway.clone();
let mut config = Config::new(id);
let override_config_fields = OverrideConfig::from(args.clone());
config = override_config(config, override_config_fields);
// 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, _>(
register_gateway,
user_chosen_gateway_id,
config.get_base(),
)
.await
.tap_err(|err| eprintln!("Failed to setup gateway\nError: {err}"))?;
let gateway = setup_gateway(id, register_gateway, user_chosen_gateway_id, &config)
.await
.unwrap_or_else(|err| {
eprintln!("Failed to setup gateway\nError: {err}");
std::process::exit(1)
});
config.get_base_mut().with_gateway_endpoint(gateway);
let config_save_location = config.get_config_file_save_location();
config
.save_to_file(None)
.expect("Failed to save the config file");
config.save_to_file(None).tap_err(|_| {
log::error!("Failed to save the config file");
})?;
print_saved_config(&config);
let address = client_core::init::get_client_address_from_stored_keys(config.get_base())?;
let init_results = InitResults::new(&config, &address);
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);
Ok(())
}
fn print_saved_config(config: &Config) {
let config_save_location = config.get_config_file_save_location();
println!("Saved configuration file to {:?}", config_save_location);
println!("Using gateway: {}", config.get_base().get_gateway_id());
log::debug!("Gateway id: {}", config.get_base().get_gateway_id());
@@ -119,63 +175,5 @@ pub(crate) async fn execute(args: &Init) {
"Gateway listener: {}",
config.get_base().get_gateway_listener()
);
println!("Client configuration completed.");
client_core::init::show_address(config.get_base()).unwrap_or_else(|err| {
eprintln!("Failed to show address\nError: {err}");
std::process::exit(1)
});
}
async fn setup_gateway(
id: &str,
register: bool,
user_chosen_gateway_id: Option<&str>,
config: &Config,
) -> Result<GatewayEndpointConfig, ClientCoreError> {
if register {
// 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.
println!("Configuring gateway");
let gateway = client_core::init::query_gateway_details(
config.get_base().get_validator_api_endpoints(),
user_chosen_gateway_id,
)
.await?;
log::debug!("Querying gateway gives: {}", gateway);
// Registering with gateway by setting up and writing shared keys to disk
log::trace!("Registering gateway");
client_core::init::register_with_gateway_and_store_keys(gateway.clone(), config.get_base())
.await?;
println!("Saved all generated keys");
Ok(gateway.into())
} else if user_chosen_gateway_id.is_some() {
// Just set the config, don't register or create any keys
// This assumes that the user knows what they are doing, and that the existing keys are
// valid for the gateway being used
println!("Using gateway provided by user, keeping existing keys");
let gateway = client_core::init::query_gateway_details(
config.get_base().get_validator_api_endpoints(),
user_chosen_gateway_id,
)
.await?;
log::debug!("Querying gateway gives: {}", gateway);
Ok(gateway.into())
} else {
println!("Not registering gateway, will reuse existing config and keys");
let existing_config = Config::load_from_file(Some(id)).map_err(|err| {
log::error!(
"Unable to configure gateway: {err}. \n
Seems like the client was already initialized but it was not possible to read \
the existing configuration file. \n
CAUTION: Consider backing up your gateway keys and try force gateway registration, or \
removing the existing configuration and starting over."
);
ClientCoreError::CouldNotLoadExistingGatewayConfiguration(err)
})?;
Ok(existing_config.get_base().get_gateway_endpoint().clone())
}
println!("Client configuration completed.\n");
}
+6 -1
View File
@@ -80,6 +80,7 @@ pub(crate) struct OverrideConfig {
disable_socket: bool,
port: Option<u16>,
fastmode: bool,
no_cover: bool,
#[cfg(feature = "coconut")]
enabled_credentials_mode: bool,
@@ -89,7 +90,7 @@ pub(crate) async fn execute(args: &Cli) -> Result<(), ClientError> {
let bin_name = "nym-native-client";
match &args.command {
Commands::Init(m) => init::execute(m).await,
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),
@@ -141,6 +142,10 @@ pub(crate) fn override_config(mut config: Config, args: OverrideConfig) -> Confi
config.get_base_mut().set_high_default_traffic_volume();
}
if args.no_cover {
config.get_base_mut().set_no_cover_traffic();
}
config
}
+11 -1
View File
@@ -39,6 +39,15 @@ pub(crate) struct Run {
#[clap(short, long)]
port: Option<u16>,
/// Mostly debug-related option to increase default traffic rate so that you would not need to
/// modify config post init
#[clap(long, hidden = true)]
fastmode: bool,
/// Disable loop cover traffic and the Poisson rate limiter (for debugging only)
#[clap(long, hidden = 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")]
@@ -53,7 +62,8 @@ impl From<Run> for OverrideConfig {
api_validators: run_config.api_validators,
disable_socket: run_config.disable_socket,
port: run_config.port,
fastmode: false,
fastmode: run_config.fastmode,
no_cover: run_config.no_cover,
#[cfg(feature = "coconut")]
enabled_credentials_mode: run_config.enabled_credentials_mode,
}
+2
View File
@@ -2,6 +2,8 @@ use client_core::error::ClientCoreError;
#[derive(thiserror::Error, Debug)]
pub enum ClientError {
#[error("I/O error: {0}")]
IoError(#[from] std::io::Error),
#[error("client-core error: {0}")]
ClientCoreError(#[from] ClientCoreError),
+3 -3
View File
@@ -1,6 +1,6 @@
[package]
name = "nym-socks5-client"
version = "1.1.1"
version = "1.1.3"
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"
@@ -19,7 +19,8 @@ pin-project = "1.0"
pretty_env_logger = "0.4"
rand = { version = "0.7.3", features = ["wasm-bindgen"] }
serde = { version = "1.0", features = ["derive"] } # for config serialization/deserialization
snafu = "0.6"
serde_json = "1.0.89"
tap = "1.0.1"
thiserror = "1.0.34"
tokio = { version = "1.21.2", features = ["rt-multi-thread", "net", "signal"] }
url = "2.2"
@@ -46,7 +47,6 @@ task = { path = "../../common/task" }
topology = { path = "../../common/topology" }
validator-client = { path = "../../common/client-libs/validator-client", features = ["nymd-client"] }
version-checker = { path = "../../common/version-checker" }
tap = "1.0.1"
[features]
coconut = ["coconut-interface", "credentials", "gateway-requests/coconut", "gateway-client/coconut", "credentials/coconut", "client-core/coconut"]
+9 -1
View File
@@ -2,8 +2,8 @@
// SPDX-License-Identifier: Apache-2.0
use crate::client::config::template::config_template;
use client_core::config::Config as BaseConfig;
pub use client_core::config::MISSING_VALUE;
use client_core::config::{ClientCoreConfigTrait, Config as BaseConfig};
use config::defaults::DEFAULT_SOCKS5_LISTENING_PORT;
use config::NymConfig;
use nymsphinx::addressing::clients::Recipient;
@@ -52,6 +52,12 @@ impl NymConfig for Config {
}
}
impl ClientCoreConfigTrait for Config {
fn get_gateway_endpoint(&self) -> &client_core::config::GatewayEndpointConfig {
self.base.get_gateway_endpoint()
}
}
impl Config {
pub fn new<S: Into<String>>(id: S, provider_mix_address: S) -> Self {
Config {
@@ -60,11 +66,13 @@ impl Config {
}
}
#[must_use]
pub fn with_port(mut self, port: u16) -> Self {
self.socks5.listening_port = port;
self
}
#[must_use]
pub fn with_provider_mix_address(mut self, address: String) -> Self {
self.socks5.provider_mix_address = address;
self
+32 -32
View File
@@ -54,8 +54,21 @@ impl NymClient {
#[cfg(feature = "coconut")]
let bandwidth_controller = {
let details = network_defaults::NymNetworkDetails::new_from_env();
let client_config = validator_client::Config::try_from_nym_network_details(&details)
.expect("failed to construct validator client config");
let mut client_config =
validator_client::Config::try_from_nym_network_details(&details)
.expect("failed to construct validator client config");
let nymd_url = config
.get_base()
.get_validator_endpoints()
.pop()
.expect("No nymd validator endpoint provided");
let api_url = config
.get_base()
.get_validator_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);
let client = validator_client::Client::new_query(client_config)
.expect("Could not construct query client");
let coconut_api_clients =
@@ -80,7 +93,7 @@ impl NymClient {
client_input: ClientInput,
client_output: ClientOutput,
self_address: Recipient,
mut shutdown: ShutdownListener,
shutdown: ShutdownListener,
) {
info!("Starting socks5 listener...");
let auth_methods = vec![AuthenticationMethods::NoAuth as u8];
@@ -103,33 +116,23 @@ impl NymClient {
shared_lane_queue_lengths,
shutdown.clone(),
);
tokio::spawn(async move {
// Ideally we should have a fully fledged task manager to check for errors in all
// tasks.
// However, pragmatically, we start out by at least reporting errors for some of the
// tasks that interact with the outside world and can fail in normal operation, such as
// network issues.
// TODO: replace this by a generic solution, such as a task manager that stores all
// JoinHandles of all spawned tasks.
if let Err(res) = sphinx_socks
.serve(
input_sender,
received_buffer_request_sender,
connection_command_sender,
)
.await
{
shutdown.send_we_stopped(Box::new(res));
}
});
task::spawn_with_report_error(
async move {
sphinx_socks
.serve(
input_sender,
received_buffer_request_sender,
connection_command_sender,
)
.await
},
shutdown,
);
}
/// blocking version of `start` method. Will run forever (or until SIGINT is sent)
pub async fn run_forever(self) -> Result<(), Box<dyn Error + Send>> {
let mut shutdown = self
.start()
.await
.map_err(|err| Box::new(err) as Box<dyn Error + Send>)?;
pub async fn run_forever(self) -> Result<(), Box<dyn Error + Send + Sync>> {
let mut shutdown = self.start().await?;
let res = wait_for_signal_and_error(&mut shutdown).await;
@@ -147,12 +150,9 @@ impl NymClient {
pub async fn run_and_listen(
self,
mut receiver: Socks5ControlMessageReceiver,
) -> Result<(), Box<dyn Error + Send>> {
) -> Result<(), Box<dyn Error + Send + Sync>> {
// Start the main task
let mut shutdown = self
.start()
.await
.map_err(|err| Box::new(err) as Box<dyn Error + Send>)?;
let mut shutdown = self.start().await?;
let res = tokio::select! {
biased;
+76 -74
View File
@@ -1,13 +1,18 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use std::fmt::Display;
use clap::Args;
use client_core::{config::GatewayEndpointConfig, error::ClientCoreError};
use config::NymConfig;
use nymsphinx::addressing::clients::Recipient;
use serde::Serialize;
use tap::TapFallible;
use crate::{
client::config::Config,
commands::{override_config, OverrideConfig},
error::Socks5ClientError,
};
#[derive(Args, Clone)]
@@ -46,11 +51,19 @@ pub(crate) struct Init {
#[clap(long, hidden = true)]
fastmode: bool,
/// Disable loop cover traffic and the Poisson rate limiter (for debugging only)
#[clap(long, hidden = 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,
/// Save a summary of the initialization to a json file
#[clap(long)]
output_json: bool,
}
impl From<Init> for OverrideConfig {
@@ -60,13 +73,37 @@ impl From<Init> for OverrideConfig {
api_validators: init_config.api_validators,
port: init_config.port,
fastmode: init_config.fastmode,
no_cover: init_config.no_cover,
#[cfg(feature = "coconut")]
enabled_credentials_mode: init_config.enabled_credentials_mode,
}
}
}
pub(crate) async fn execute(args: &Init) {
#[derive(Debug, Serialize)]
pub struct InitResults {
#[serde(flatten)]
client_core: client_core::init::InitResults,
socks5_listening_port: String,
}
impl InitResults {
fn new(config: &Config, address: &Recipient) -> Self {
Self {
client_core: client_core::init::InitResults::new(config.get_base(), address),
socks5_listening_port: config.get_listening_port().to_string(),
}
}
}
impl Display for InitResults {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
writeln!(f, "{}", self.client_core)?;
write!(f, "SOCKS5 listening port: {}", self.socks5_listening_port)
}
}
pub(crate) async fn execute(args: &Init) -> Result<(), Socks5ClientError> {
println!("Initialising client...");
let id = &args.id;
@@ -91,25 +128,47 @@ pub(crate) async fn execute(args: &Init) {
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.as_deref();
let user_chosen_gateway_id = args.gateway.clone();
let mut config = Config::new(id, provider_address);
let override_config_fields = OverrideConfig::from(args.clone());
config = override_config(config, override_config_fields);
// Load and potentially override config
let mut config = override_config(
Config::new(id, provider_address),
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, _>(
register_gateway,
user_chosen_gateway_id,
config.get_base(),
)
.await
.tap_err(|err| eprintln!("Failed to setup gateway\nError: {err}"))?;
let gateway = setup_gateway(id, register_gateway, user_chosen_gateway_id, &config)
.await
.unwrap_or_else(|err| {
eprintln!("Failed to setup gateway\nError: {err}");
std::process::exit(1)
});
config.get_base_mut().with_gateway_endpoint(gateway);
let config_save_location = config.get_config_file_save_location();
config
.save_to_file(None)
.expect("Failed to save the config file");
config.save_to_file(None).tap_err(|_| {
log::error!("Failed to save the config file");
})?;
print_saved_config(&config);
let address = client_core::init::get_client_address_from_stored_keys(config.get_base())?;
let init_results = InitResults::new(&config, &address);
println!("{}", init_results);
// Output summary to a json file, if specified
if args.output_json {
client_core::init::output_to_json(&init_results, "socks5_client_init_results.json");
}
println!("\nThe address of this client is: {}\n", address);
Ok(())
}
fn print_saved_config(config: &Config) {
let config_save_location = config.get_config_file_save_location();
println!("Saved configuration file to {:?}", config_save_location);
println!("Using gateway: {}", config.get_base().get_gateway_id());
log::debug!("Gateway id: {}", config.get_base().get_gateway_id());
@@ -118,62 +177,5 @@ pub(crate) async fn execute(args: &Init) {
"Gateway listener: {}",
config.get_base().get_gateway_listener()
);
println!("Client configuration completed.");
client_core::init::show_address(config.get_base()).unwrap_or_else(|err| {
eprintln!("Failed to show address\nError: {err}");
std::process::exit(1)
});
}
async fn setup_gateway(
id: &str,
register: bool,
user_chosen_gateway_id: Option<&str>,
config: &Config,
) -> Result<GatewayEndpointConfig, ClientCoreError> {
if register {
// 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.
println!("Configuring gateway");
let gateway = client_core::init::query_gateway_details(
config.get_base().get_validator_api_endpoints(),
user_chosen_gateway_id,
)
.await?;
log::debug!("Querying gateway gives: {}", gateway);
// Registering with gateway by setting up and writing shared keys to disk
log::trace!("Registering gateway");
client_core::init::register_with_gateway_and_store_keys(gateway.clone(), config.get_base())
.await?;
println!("Saved all generated keys");
Ok(gateway.into())
} else if user_chosen_gateway_id.is_some() {
// Just set the config, don't register or create any keys
// This assumes that the user knows what they are doing, and that the existing keys are
// valid for the gateway being used
println!("Using gateway provided by user, keeping existing keys");
let gateway = client_core::init::query_gateway_details(
config.get_base().get_validator_api_endpoints(),
user_chosen_gateway_id,
)
.await?;
log::debug!("Querying gateway gives: {}", gateway);
Ok(gateway.into())
} else {
println!("Not registering gateway, will reuse existing config and keys");
let existing_config = Config::load_from_file(Some(id)).map_err(|err| {
log::error!(
"Unable to configure gateway: {err}. \n
Seems like the client was already initialized but it was not possible to read \
the existing configuration file. \n
CAUTION: Consider backing up your gateway keys and try force gateway registration, or \
removing the existing configuration and starting over."
);
ClientCoreError::CouldNotLoadExistingGatewayConfiguration(err)
})?;
Ok(existing_config.get_base().get_gateway_endpoint().clone())
}
println!("Client configuration completed.\n");
}
+7 -2
View File
@@ -83,16 +83,17 @@ pub(crate) struct OverrideConfig {
api_validators: Option<String>,
port: Option<u16>,
fastmode: bool,
no_cover: bool,
#[cfg(feature = "coconut")]
enabled_credentials_mode: bool,
}
pub(crate) async fn execute(args: &Cli) -> Result<(), Box<dyn Error + Send>> {
pub(crate) async fn execute(args: &Cli) -> Result<(), Box<dyn Error + Send + Sync>> {
let bin_name = "nym-socks5-client";
match &args.command {
Commands::Init(m) => init::execute(m).await,
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),
@@ -136,6 +137,10 @@ pub(crate) fn override_config(mut config: Config, args: OverrideConfig) -> Confi
config.get_base_mut().set_high_default_traffic_volume();
}
if args.no_cover {
config.get_base_mut().set_no_cover_traffic();
}
config
}
+12 -3
View File
@@ -43,6 +43,15 @@ pub(crate) struct Run {
#[clap(short, long)]
port: Option<u16>,
/// Mostly debug-related option to increase default traffic rate so that you would not need to
/// modify config post init
#[clap(long, hidden = true)]
fastmode: bool,
/// Disable loop cover traffic and the Poisson rate limiter (for debugging only)
#[clap(long, hidden = 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")]
@@ -56,8 +65,8 @@ impl From<Run> for OverrideConfig {
nymd_validators: run_config.nymd_validators,
api_validators: run_config.api_validators,
port: run_config.port,
fastmode: false,
fastmode: run_config.fastmode,
no_cover: run_config.no_cover,
#[cfg(feature = "coconut")]
enabled_credentials_mode: run_config.enabled_credentials_mode,
}
@@ -86,7 +95,7 @@ fn version_check(cfg: &Config) -> bool {
}
}
pub(crate) async fn execute(args: &Run) -> Result<(), Box<dyn std::error::Error + Send>> {
pub(crate) async fn execute(args: &Run) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let id = &args.id;
let mut config = match Config::load_from_file(Some(id)) {
+1 -1
View File
@@ -13,7 +13,7 @@ pub mod error;
pub mod socks;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error + Send>> {
async fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
setup_logging();
println!("{}", banner());
+11 -11
View File
@@ -1,5 +1,3 @@
use snafu::Snafu;
/// SOCKS4 Response codes
#[allow(dead_code)]
pub(crate) enum ResponseCodeV4 {
@@ -10,24 +8,26 @@ pub(crate) enum ResponseCodeV4 {
}
/// Possible SOCKS5 Response Codes
#[derive(Debug, Snafu)]
#[allow(dead_code)]
#[derive(Debug, thiserror::Error)]
pub(crate) enum ResponseCodeV5 {
#[error("SOCKS5 Server Success")]
Success = 0x00,
#[snafu(display("SOCKS5 Server Failure"))]
#[error("SOCKS5 Server Failure")]
Failure = 0x01,
#[snafu(display("SOCKS5 Rule failure"))]
#[error("SOCKS5 Rule failure")]
RuleFailure = 0x02,
#[snafu(display("network unreachable"))]
#[error("network unreachable")]
NetworkUnreachable = 0x03,
#[snafu(display("host unreachable"))]
#[error("host unreachable")]
HostUnreachable = 0x04,
#[snafu(display("connection refused"))]
#[error("connection refused")]
ConnectionRefused = 0x05,
#[snafu(display("TTL expired"))]
#[error("TTL expired")]
TtlExpired = 0x06,
#[snafu(display("Command not supported"))]
#[error("Command not supported")]
CommandNotSupported = 0x07,
#[snafu(display("Addr Type not supported"))]
#[error("Addr Type not supported")]
AddrTypeNotSupported = 0x08,
}
@@ -61,7 +61,7 @@ where
#[cfg(feature = "coconut")]
pub async fn prepare_coconut_credential(
&self,
) -> Result<coconut_interface::Credential, GatewayClientError> {
) -> Result<(coconut_interface::Credential, i64), GatewayClientError> {
let verification_key = obtain_aggregate_verification_key(&self.coconut_api_clients).await?;
let bandwidth_credential = self.storage.get_next_coconut_credential().await?;
let voucher_value = u64::from_str(&bandwidth_credential.voucher_value)
@@ -75,13 +75,21 @@ where
coconut_interface::Signature::try_from_bs58(bandwidth_credential.signature)?;
// the below would only be executed once we know where we want to spend it (i.e. which gateway and stuff)
Ok(prepare_for_spending(
voucher_value,
voucher_info,
serial_number,
binding_number,
&signature,
&verification_key,
)?)
Ok((
prepare_for_spending(
voucher_value,
voucher_info,
serial_number,
binding_number,
&signature,
&verification_key,
)?,
bandwidth_credential.id,
))
}
#[cfg(feature = "coconut")]
pub async fn consume_credential(&self, id: i64) -> Result<(), GatewayClientError> {
Ok(self.storage.consume_coconut_credential(id).await?)
}
}
+19 -39
View File
@@ -10,7 +10,7 @@ pub use crate::packet_router::{
use crate::socket_state::{PartiallyDelegated, SocketState};
use crate::{cleanup_socket_message, try_decrypt_binary_message};
use crypto::asymmetric::identity;
use futures::{FutureExt, SinkExt, StreamExt};
use futures::{SinkExt, StreamExt};
use gateway_requests::authentication::encrypted_address::EncryptedAddressBytes;
use gateway_requests::iv::IV;
use gateway_requests::registration::handshake::{client_handshake, SharedKeys};
@@ -67,9 +67,7 @@ pub struct GatewayClient {
reconnection_backoff: Duration,
/// Listen to shutdown messages.
// TODO: fix this
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
shutdown: Option<ShutdownListener>,
shutdown: ShutdownListener,
}
impl GatewayClient {
@@ -85,7 +83,7 @@ impl GatewayClient {
ack_sender: AcknowledgementSender,
response_timeout_duration: Duration,
bandwidth_controller: Option<BandwidthController<PersistentStorage>>,
shutdown: Option<ShutdownListener>,
shutdown: ShutdownListener,
) -> Self {
GatewayClient {
authenticated: false,
@@ -130,7 +128,6 @@ impl GatewayClient {
gateway_owner: String,
local_identity: Arc<identity::KeyPair>,
response_timeout_duration: Duration,
shutdown: Option<ShutdownListener>,
) -> Self {
use futures::channel::mpsc;
@@ -138,6 +135,7 @@ impl GatewayClient {
// perfectly fine here, because it's not meant to be used
let (ack_tx, _) = mpsc::unbounded();
let (mix_tx, _) = mpsc::unbounded();
let shutdown = ShutdownListener::dummy();
let packet_router = PacketRouter::new(ack_tx, mix_tx, shutdown.clone());
GatewayClient {
@@ -283,44 +281,19 @@ impl GatewayClient {
// technically the `wasm_timer` also works outside wasm, but unless required,
// I really prefer to just stick to tokio
#[cfg(target_arch = "wasm32")]
let timeout = wasm_timer::Delay::new(self.response_timeout_duration);
let mut fused_timeout = timeout.fuse();
let mut fused_stream = conn.fuse();
// Bit of an ugly workaround for selecting on an `Option` without having access to
// `tokio::select`
#[cfg(not(target_arch = "wasm32"))]
let shutdown = {
let m_shutdown = self.shutdown.clone();
async {
if let Some(mut s) = m_shutdown {
// TODO: fix this by marking as success _after_ the select
s.mark_as_success();
s.recv().await
} else {
std::future::pending::<()>().await
}
}
.fuse()
};
#[cfg(not(target_arch = "wasm32"))]
tokio::pin!(shutdown);
#[cfg(target_arch = "wasm32")]
let mut shutdown = std::future::pending::<()>().fuse();
let mut timeout = wasm_timer::Delay::new(self.response_timeout_duration);
loop {
futures::select! {
_ = shutdown => {
tokio::select! {
_ = self.shutdown.recv() => {
log::trace!("GatewayClient control response: Received shutdown");
log::debug!("GatewayClient control response: Exiting");
break Err(GatewayClientError::ConnectionClosedGatewayShutdown);
}
_ = &mut fused_timeout => {
_ = &mut timeout => {
break Err(GatewayClientError::Timeout);
}
msg = fused_stream.next() => {
msg = conn.next() => {
let ws_msg = match cleanup_socket_message(msg) {
Err(err) => break Err(err),
Ok(msg) => msg
@@ -614,7 +587,7 @@ impl GatewayClient {
let _gateway_owner = self.gateway_owner.clone();
#[cfg(feature = "coconut")]
let credential = self
let (credential, credential_id) = self
.bandwidth_controller
.as_ref()
.unwrap()
@@ -624,7 +597,15 @@ impl GatewayClient {
return self.try_claim_testnet_bandwidth().await;
#[cfg(feature = "coconut")]
return self.claim_coconut_bandwidth(credential).await;
{
self.claim_coconut_bandwidth(credential).await?;
self.bandwidth_controller
.as_ref()
.unwrap()
.consume_credential(credential_id)
.await?;
Ok(())
}
}
fn estimate_required_bandwidth(&self, packets: &[MixPacket]) -> i64 {
@@ -770,7 +751,6 @@ impl GatewayClient {
.as_ref()
.expect("no shared key present even though we're authenticated!"),
),
#[cfg(not(target_arch = "wasm32"))]
self.shutdown.clone(),
)
}
@@ -21,14 +21,14 @@ pub type AcknowledgementReceiver = mpsc::UnboundedReceiver<Vec<Vec<u8>>>;
pub struct PacketRouter {
ack_sender: AcknowledgementSender,
mixnet_message_sender: MixnetMessageSender,
shutdown: Option<ShutdownListener>,
shutdown: ShutdownListener,
}
impl PacketRouter {
pub fn new(
ack_sender: AcknowledgementSender,
mixnet_message_sender: MixnetMessageSender,
shutdown: Option<ShutdownListener>,
shutdown: ShutdownListener,
) -> Self {
PacketRouter {
ack_sender,
@@ -82,12 +82,10 @@ impl PacketRouter {
if !received_messages.is_empty() {
trace!("routing 'real'");
if let Err(err) = self.mixnet_message_sender.unbounded_send(received_messages) {
if let Some(shutdown) = &mut self.shutdown {
if shutdown.is_shutdown_poll() {
// This should ideally not happen, but it's ok
log::warn!("Failed to send mixnet message due to receiver task shutdown");
return Err(GatewayClientError::MixnetMsgSenderFailedToSend);
}
if self.shutdown.is_shutdown_poll() || self.shutdown.is_dummy() {
// This should ideally not happen, but it's ok
log::warn!("Failed to send mixnet message due to receiver task shutdown");
return Err(GatewayClientError::MixnetMsgSenderFailedToSend);
}
// This should never happen during ordinary operation the way it's currently used.
// Abort to be on the safe side
@@ -10,7 +10,6 @@ use futures::{SinkExt, StreamExt};
use gateway_requests::registration::handshake::SharedKeys;
use log::*;
use std::sync::Arc;
#[cfg(not(target_arch = "wasm32"))]
use task::ShutdownListener;
use tungstenite::Message;
@@ -85,7 +84,7 @@ impl PartiallyDelegated {
conn: WsConn,
packet_router: PacketRouter,
shared_key: Arc<SharedKeys>,
#[cfg(not(target_arch = "wasm32"))] shutdown: Option<ShutdownListener>,
mut shutdown: ShutdownListener,
) -> Self {
// when called for, it NEEDS TO yield back the stream so that we could merge it and
// read control request responses.
@@ -99,27 +98,9 @@ impl PartiallyDelegated {
let mut chunk_stream = (&mut stream).ready_chunks(8);
let mut packet_router = packet_router;
// Bit of an ugly workaround for selecting on an `Option` without having access to
// `tokio::select`
#[cfg(not(target_arch = "wasm32"))]
let shutdown = {
async {
if let Some(mut s) = shutdown {
s.recv().await
} else {
std::future::pending::<()>().await
}
}
};
#[cfg(not(target_arch = "wasm32"))]
tokio::pin!(shutdown);
#[cfg(target_arch = "wasm32")]
let mut shutdown = std::future::pending::<()>();
let ret_err = loop {
tokio::select! {
_ = &mut shutdown => {
_ = shutdown.recv() => {
log::trace!("GatewayClient listener: Received shutdown");
log::debug!("GatewayClient listener: Exiting");
return;
@@ -142,7 +123,10 @@ impl PartiallyDelegated {
if match ret_err {
Err(err) => stream_sender.send(Err(err)),
Ok(_) => stream_sender.send(Ok(stream)),
Ok(_) => {
shutdown.mark_as_success();
stream_sender.send(Ok(stream))
}
}
.is_err()
{
@@ -39,7 +39,7 @@ pub trait Storage: Send + Sync {
async fn get_next_coconut_credential(&self) -> Result<CoconutCredential, StorageError>;
async fn remove_coconut_credential(&self, id: i64) -> Result<(), StorageError>;
async fn consume_coconut_credential(&self, id: i64) -> Result<(), StorageError>;
}
#[async_trait]
@@ -59,7 +59,7 @@ impl Storage for PersistentStorage {
Err(StorageError::WasmNotSupported)
}
async fn remove_coconut_credential(&self, _id: i64) -> Result<(), StorageError> {
async fn consume_coconut_credential(&self, _id: i64) -> Result<(), StorageError> {
Err(StorageError::WasmNotSupported)
}
}
@@ -1,6 +1,5 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::{validator_api, ValidatorClientError};
use coconut_dkg_common::types::NodeIndex;
#[cfg(feature = "nymd-client")]
@@ -10,9 +9,10 @@ use coconut_dkg_common::{
#[cfg(feature = "nymd-client")]
use coconut_interface::Base58;
use coconut_interface::VerificationKey;
use mixnet_contract_common::families::{Family, FamilyHead};
use mixnet_contract_common::mixnode::MixNodeDetails;
use mixnet_contract_common::MixId;
use mixnet_contract_common::{GatewayBond, IdentityKeyRef};
use mixnet_contract_common::{IdentityKey, MixId};
#[cfg(feature = "nymd-client")]
use std::str::FromStr;
use validator_api_requests::coconut::{
@@ -220,6 +220,7 @@ impl Client<QueryNymdClient> {
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
.set_mixnet_contract_address(mixnet_contract_address)
@@ -229,6 +230,56 @@ impl<C> Client<C> {
self.nymd.mixnet_contract_address().clone()
}
pub async fn get_all_node_families(&self) -> Result<Vec<Family>, ValidatorClientError>
where
C: CosmWasmClient + Sync + Send,
{
let mut families = Vec::new();
let mut start_after = None;
loop {
let paged_response = self
.nymd
.get_all_node_families_paged(start_after.take(), None)
.await?;
families.extend(paged_response.families);
if let Some(start_after_res) = paged_response.start_next_after {
start_after = Some(start_after_res)
} else {
break;
}
}
Ok(families)
}
pub async fn get_all_family_members(
&self,
) -> Result<Vec<(IdentityKey, FamilyHead)>, ValidatorClientError>
where
C: CosmWasmClient + Sync + Send,
{
let mut members = Vec::new();
let mut start_after = None;
loop {
let paged_response = self
.nymd
.get_all_family_members_paged(start_after.take(), None)
.await?;
members.extend(paged_response.members);
if let Some(start_after_res) = paged_response.start_next_after {
start_after = Some(start_after_res)
} else {
break;
}
}
Ok(members)
}
// basically handles paging for us
pub async fn get_all_nymd_rewarded_set_mixnodes(
&self,
@@ -15,12 +15,12 @@ pub use coconut_dkg_common::event_attributes::*;
pub struct Log {
#[serde(default)]
// weird thing is that the first msg_index seems to always be undefined on the raw logs
msg_index: usize,
pub msg_index: usize,
// unless I'm missing something obvious, the "log" type in cosmjs is always an empty string
// and launchpad cosmos validator was setting it to what essentially is just the raw version of what
// we received (and we don't care about launchpad, we, as the time of writing this, work on the stargate)
// log: String,
events: Vec<cosmwasm_std::Event>,
pub events: Vec<cosmwasm_std::Event>,
}
/// Searches in logs for the first event of the given event type and in that event
@@ -7,6 +7,7 @@ use crate::nymd::NymdClient;
use async_trait::async_trait;
use cosmrs::AccountId;
use mixnet_contract_common::delegation::{MixNodeDelegationResponse, OwnerProxySubKey};
use mixnet_contract_common::families::Family;
use mixnet_contract_common::mixnode::{
MixNodeDetails, MixnodeRewardingDetailsResponse, PagedMixnodesDetailsResponse,
PagedUnbondedMixnodesResponse, StakeSaturationResponse, UnbondedMixnodeResponse,
@@ -20,9 +21,9 @@ use mixnet_contract_common::{
CurrentIntervalResponse, EpochEventId, GatewayBondResponse, GatewayOwnershipResponse,
IdentityKey, IntervalEventId, LayerDistribution, MixId, MixOwnershipResponse,
MixnodeDetailsResponse, PagedAllDelegationsResponse, PagedDelegatorDelegationsResponse,
PagedGatewayResponse, PagedMixNodeDelegationsResponse, PagedMixnodeBondsResponse,
PagedRewardedSetResponse, PendingEpochEventsResponse, PendingIntervalEventsResponse,
QueryMsg as MixnetQueryMsg,
PagedFamiliesResponse, PagedGatewayResponse, PagedMembersResponse,
PagedMixNodeDelegationsResponse, PagedMixnodeBondsResponse, PagedRewardedSetResponse,
PendingEpochEventsResponse, PendingIntervalEventsResponse, QueryMsg as MixnetQueryMsg,
};
use serde::Deserialize;
@@ -73,6 +74,24 @@ pub trait MixnetQueryClient {
.await
}
async fn get_all_node_families_paged(
&self,
start_after: Option<String>,
limit: Option<u32>,
) -> Result<PagedFamiliesResponse, NymdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetAllFamiliesPaged { limit, start_after })
.await
}
async fn get_all_family_members_paged(
&self,
start_after: Option<String>,
limit: Option<u32>,
) -> Result<PagedMembersResponse, NymdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetAllMembersPaged { limit, start_after })
.await
}
// mixnode-related:
async fn get_mixnode_bonds_paged(
@@ -357,6 +376,20 @@ pub trait MixnetQueryClient {
})
.await
}
async fn get_node_family_by_label(&self, label: &str) -> Result<Option<Family>, NymdError> {
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> {
self.query_mixnet_contract(MixnetQueryMsg::GetFamilyByHead {
head: head.to_string(),
})
.await
}
}
#[async_trait]
@@ -11,7 +11,7 @@ use cosmrs::AccountId;
use mixnet_contract_common::mixnode::{MixNodeConfigUpdate, MixNodeCostParams};
use mixnet_contract_common::reward_params::{IntervalRewardingParamsUpdate, Performance};
use mixnet_contract_common::{
ContractStateParams, ExecuteMsg as MixnetExecuteMsg, Gateway, MixId, MixNode,
ContractStateParams, ExecuteMsg as MixnetExecuteMsg, Gateway, LayerAssignment, MixId, MixNode,
};
#[async_trait]
@@ -108,7 +108,7 @@ pub trait MixnetSigningClient {
async fn advance_current_epoch(
&self,
new_rewarded_set: Vec<MixId>,
new_rewarded_set: Vec<LayerAssignment>,
expected_active_set_size: u32,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
@@ -136,6 +136,147 @@ pub trait MixnetSigningClient {
.await
}
// family related
async fn create_family(
&self,
owner_signature: String,
label: String,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::CreateFamily {
owner_signature,
label,
},
vec![],
)
.await
}
async fn create_family_on_behalf(
&self,
owner_address: String,
owner_signature: String,
label: String,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::CreateFamilyOnBehalf {
owner_address,
owner_signature,
label,
},
vec![],
)
.await
}
async fn join_family(
&self,
signature: String,
family_head: String,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::JoinFamily {
signature,
family_head,
},
vec![],
)
.await
}
async fn join_family_on_behalf(
&self,
member_address: String,
signature: String,
family_head: String,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::JoinFamilyOnBehalf {
member_address,
signature,
family_head,
},
vec![],
)
.await
}
async fn leave_family(
&self,
signature: String,
family_head: String,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::LeaveFamily {
signature,
family_head,
},
vec![],
)
.await
}
async fn leave_family_on_behalf(
&self,
member_address: String,
signature: String,
family_head: String,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::LeaveFamilyOnBehalf {
member_address,
signature,
family_head,
},
vec![],
)
.await
}
async fn kick_family_member(
&self,
signature: String,
member: String,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::KickFamilyMember { signature, member },
vec![],
)
.await
}
async fn kick_family_member_on_behalf(
&self,
head_address: String,
signature: String,
member: String,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::KickFamilyMemberOnBehalf {
head_address,
signature,
member,
},
vec![],
)
.await
}
// mixnode-related:
async fn bond_mixnode(
@@ -136,7 +136,12 @@ impl Client {
&self,
) -> Result<Vec<MixNodeBondAnnotated>, ValidatorAPIError> {
self.query_validator_api(
&[routes::API_VERSION, routes::MIXNODES, routes::DETAILED],
&[
routes::API_VERSION,
routes::STATUS,
routes::MIXNODES,
routes::DETAILED,
],
NO_PARAMS,
)
.await
@@ -161,6 +166,7 @@ impl Client {
self.query_validator_api(
&[
routes::API_VERSION,
routes::STATUS,
routes::MIXNODES,
routes::ACTIVE,
routes::DETAILED,
@@ -252,6 +258,7 @@ impl Client {
self.query_validator_api(
&[
routes::API_VERSION,
routes::STATUS,
routes::MIXNODES,
routes::REWARDED,
routes::DETAILED,
+12 -8
View File
@@ -11,6 +11,10 @@ use std::{fs, io};
pub mod defaults;
pub const CONFIG_DIR: &str = "config";
pub const DATA_DIR: &str = "data";
pub const DB_FILE_NAME: &str = "db.sqlite";
pub trait NymConfig: Default + Serialize + DeserializeOwned {
fn template() -> &'static str;
@@ -23,17 +27,17 @@ pub trait NymConfig: Default + Serialize + DeserializeOwned {
// default, most probable, implementations; can be easily overridden where required
fn default_config_directory(id: Option<&str>) -> PathBuf {
if let Some(id) = id {
Self::default_root_directory().join(id).join("config")
Self::default_root_directory().join(id).join(CONFIG_DIR)
} else {
Self::default_root_directory().join("config")
Self::default_root_directory().join(CONFIG_DIR)
}
}
fn default_data_directory(id: Option<&str>) -> PathBuf {
if let Some(id) = id {
Self::default_root_directory().join(id).join("data")
Self::default_root_directory().join(id).join(DATA_DIR)
} else {
Self::default_root_directory().join("data")
Self::default_root_directory().join(DATA_DIR)
}
}
@@ -47,17 +51,17 @@ pub trait NymConfig: Default + Serialize + DeserializeOwned {
fn try_default_config_directory(id: Option<&str>) -> Option<PathBuf> {
if let Some(id) = id {
Self::try_default_root_directory().map(|d| d.join(id).join("config"))
Self::try_default_root_directory().map(|d| d.join(id).join(CONFIG_DIR))
} else {
Self::try_default_root_directory().map(|d| d.join("config"))
Self::try_default_root_directory().map(|d| d.join(CONFIG_DIR))
}
}
fn try_default_data_directory(id: Option<&str>) -> Option<PathBuf> {
if let Some(id) = id {
Self::try_default_root_directory().map(|d| d.join(id).join("data"))
Self::try_default_root_directory().map(|d| d.join(id).join(DATA_DIR))
} else {
Self::try_default_root_directory().map(|d| d.join("data"))
Self::try_default_root_directory().map(|d| d.join(DATA_DIR))
}
}
@@ -15,7 +15,7 @@ pub const MAX_DISPLAY_SIZE: usize = 128;
// TODO: if we are to use this for different types, it might make sense to introduce something like
// CommitmentTypeId field on the below for distinguishing different ones. it would somehow become part of the trait
#[derive(Debug, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, JsonSchema)]
pub struct ContractSafeBytes(Vec<u8>);
pub struct ContractSafeBytes(pub Vec<u8>);
impl Deref for ContractSafeBytes {
type Target = Vec<u8>;
@@ -1,7 +1,7 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::MixId;
use crate::{IdentityKey, MixId};
use cosmwasm_std::{Addr, Coin, Decimal};
use thiserror::Error;
@@ -133,4 +133,40 @@ pub enum MixnetContractError {
#[error("Mixnode {mix_id} appears multiple times in the provided rewarded set update!")]
DuplicateRewardedSetNode { mix_id: MixId },
#[error("Family with head {head} does not exist!")]
FamilyDoesNotExist { head: String },
#[error("Family with label '{0}' already exists")]
FamilyWithLabelExists(String),
#[error("Invalid layer expected 1, 2 or 3, got {0}")]
InvalidLayer(u8),
#[error("Head already has a family")]
FamilyCanHaveOnlyOne,
#[error("Already member of family {0}")]
AlreadyMemberOfFamily(String),
#[error("Can't join own family, family head {head}, member {member}")]
CantJoinOwnFamily {
head: IdentityKey,
member: IdentityKey,
},
#[error("Can't leave own family, family head {head}, member {member}")]
CantLeaveOwnFamily {
head: IdentityKey,
member: IdentityKey,
},
#[error("{member} is not a member of family {head}")]
NotAMember {
head: IdentityKey,
member: IdentityKey,
},
#[error("Feature is not yet implemented")]
NotImplemented,
}
@@ -0,0 +1,63 @@
use crate::{IdentityKey, IdentityKeyRef};
use cosmwasm_std::Addr;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))]
#[cfg_attr(
feature = "generate-ts",
ts(export_to = "ts-packages/types/src/types/rust/NodeFamily.ts")
)]
#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq, JsonSchema)]
pub struct Family {
head: FamilyHead,
proxy: Option<String>,
label: String,
}
#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))]
#[cfg_attr(
feature = "generate-ts",
ts(export_to = "ts-packages/types/src/types/rust/NodeFamilyHead.ts")
)]
#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq, JsonSchema)]
pub struct FamilyHead(IdentityKey);
impl FamilyHead {
pub fn new(identity: IdentityKeyRef<'_>) -> Self {
FamilyHead(identity.to_string())
}
pub fn identity(&self) -> IdentityKeyRef<'_> {
&self.0
}
}
impl Family {
pub fn new(head: FamilyHead, proxy: Option<Addr>, label: &str) -> Self {
Family {
head,
proxy: proxy.map(|p| p.to_string()),
label: label.to_string(),
}
}
#[allow(dead_code)]
pub fn head(&self) -> &FamilyHead {
&self.head
}
pub fn head_identity(&self) -> IdentityKeyRef<'_> {
self.head.identity()
}
#[allow(dead_code)]
pub fn proxy(&self) -> Option<&String> {
self.proxy.as_ref()
}
#[allow(dead_code)]
pub fn label(&self) -> &str {
&self.label
}
}
@@ -8,6 +8,7 @@ mod constants;
pub mod delegation;
pub mod error;
pub mod events;
pub mod families;
pub mod gateway;
pub mod helpers;
mod interval;
@@ -36,7 +36,6 @@ impl RewardedSetNodeStatus {
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize, JsonSchema)]
pub struct MixNodeDetails {
pub bond_information: MixNodeBond,
pub rewarding_details: MixNodeRewarding,
}
@@ -579,6 +578,29 @@ impl From<Layer> for String {
}
}
impl TryFrom<u8> for Layer {
type Error = MixnetContractError;
fn try_from(i: u8) -> Result<Layer, MixnetContractError> {
match i {
1 => Ok(Layer::One),
2 => Ok(Layer::Two),
3 => Ok(Layer::Three),
_ => Err(MixnetContractError::InvalidLayer(i)),
}
}
}
impl From<Layer> for u8 {
fn from(layer: Layer) -> u8 {
match layer {
Layer::One => 1,
Layer::Two => 2,
Layer::Three => 3,
}
}
}
#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))]
#[cfg_attr(
feature = "generate-ts",
@@ -8,7 +8,7 @@ use crate::mixnode::{MixNodeConfigUpdate, MixNodeCostParams};
use crate::reward_params::{
IntervalRewardParams, IntervalRewardingParamsUpdate, Performance, RewardingParams,
};
use crate::{delegation, ContractStateParams, MixId, Percent};
use crate::{delegation, ContractStateParams, Layer, LayerAssignment, MixId, Percent};
use crate::{Gateway, IdentityKey, MixNode};
use cosmwasm_std::Decimal;
use schemars::JsonSchema;
@@ -73,6 +73,51 @@ impl InitialRewardingParams {
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ExecuteMsg {
AssignNodeLayer {
mix_id: MixId,
layer: Layer,
},
// Families
/// Only owner of the node can crate the family with node as head
CreateFamily {
owner_signature: String,
label: String,
},
/// Family head needs to sign the joining node IdentityKey
JoinFamily {
signature: String,
family_head: IdentityKey,
},
LeaveFamily {
signature: String,
family_head: IdentityKey,
},
KickFamilyMember {
signature: String,
member: IdentityKey,
},
CreateFamilyOnBehalf {
owner_address: String,
owner_signature: String,
label: String,
},
/// Family head needs to sign the joining node IdentityKey
JoinFamilyOnBehalf {
member_address: String,
signature: String,
family_head: IdentityKey,
},
LeaveFamilyOnBehalf {
member_address: String,
signature: String,
family_head: IdentityKey,
},
KickFamilyMemberOnBehalf {
head_address: String,
signature: String,
member: IdentityKey,
},
// state/sys-params-related
UpdateRewardingValidatorAddress {
address: String,
@@ -94,7 +139,8 @@ pub enum ExecuteMsg {
force_immediately: bool,
},
AdvanceCurrentEpoch {
new_rewarded_set: Vec<MixId>,
new_rewarded_set: Vec<LayerAssignment>,
// families_in_layer: HashMap<String, Layer>,
expected_active_set_size: u32,
},
ReconcileEpochEvents {
@@ -194,6 +240,29 @@ pub enum ExecuteMsg {
impl ExecuteMsg {
pub fn default_memo(&self) -> String {
match self {
ExecuteMsg::AssignNodeLayer { mix_id, layer } => {
format!("assigning mix {} for layer {:?}", mix_id, layer)
}
ExecuteMsg::CreateFamily { .. } => "crating node family with".to_string(),
ExecuteMsg::JoinFamily { family_head, .. } => {
format!("joining family {}", family_head)
}
ExecuteMsg::LeaveFamily { family_head, .. } => {
format!("leaving family {}", family_head)
}
ExecuteMsg::KickFamilyMember { member, .. } => {
format!("kicking {} from family", member)
}
ExecuteMsg::CreateFamilyOnBehalf { .. } => "crating node family with".to_string(),
ExecuteMsg::JoinFamilyOnBehalf { family_head, .. } => {
format!("joining family {}", family_head)
}
ExecuteMsg::LeaveFamilyOnBehalf { family_head, .. } => {
format!("leaving family {}", family_head)
}
ExecuteMsg::KickFamilyMemberOnBehalf { member, .. } => {
format!("kicking {} from family", member)
}
ExecuteMsg::UpdateRewardingValidatorAddress { address } => {
format!("updating rewarding validator to {}", address)
}
@@ -286,6 +355,27 @@ impl ExecuteMsg {
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum QueryMsg {
// families
GetAllFamiliesPaged {
limit: Option<u32>,
start_after: Option<String>,
},
GetAllMembersPaged {
limit: Option<u32>,
start_after: Option<String>,
},
GetFamilyByHead {
head: String,
},
GetFamilyByLabel {
label: String,
},
GetFamilyMembersByHead {
head: String,
},
GetFamilyMembersByLabel {
label: String,
},
// state/sys-params-related
GetContractVersion {},
GetRewardingValidatorAddress {},
@@ -340,7 +430,6 @@ pub enum QueryMsg {
mix_identity: IdentityKey,
},
GetLayerDistribution {},
// gateway-related:
GetGateways {
start_after: Option<IdentityKey>,
@@ -2,6 +2,7 @@
// SPDX-License-Identifier: Apache-2.0
use crate::error::MixnetContractError;
use crate::families::{Family, FamilyHead};
use crate::{Layer, RewardedSetNodeStatus};
use cosmwasm_std::Addr;
use cosmwasm_std::Coin;
@@ -21,6 +22,27 @@ pub type BlockHeight = u64;
pub type EpochEventId = u32;
pub type IntervalEventId = u32;
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Serialize, Deserialize, Debug, Clone, JsonSchema, PartialEq)]
pub struct LayerAssignment {
mix_id: MixId,
layer: Layer,
}
impl LayerAssignment {
pub fn new(mix_id: MixId, layer: Layer) -> Self {
LayerAssignment { mix_id, layer }
}
pub fn mix_id(&self) -> MixId {
self.mix_id
}
pub fn layer(&self) -> Layer {
self.layer
}
}
#[derive(Debug, Default, Serialize, Deserialize, Copy, Clone, Eq, PartialEq)]
pub struct LayerDistribution {
pub layer1: u64,
@@ -126,3 +148,15 @@ pub struct PagedRewardedSetResponse {
pub nodes: Vec<(MixId, RewardedSetNodeStatus)>,
pub start_next_after: Option<MixId>,
}
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq, JsonSchema)]
pub struct PagedFamiliesResponse {
pub families: Vec<Family>,
pub start_next_after: Option<String>,
}
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq, JsonSchema)]
pub struct PagedMembersResponse {
pub members: Vec<(IdentityKey, FamilyHead)>,
pub start_next_after: Option<String>,
}
@@ -1,7 +1,7 @@
use cosmwasm_std::{Coin, Timestamp};
use mixnet_contract_common::{
mixnode::{MixNodeConfigUpdate, MixNodeCostParams},
Gateway, MixId, MixNode,
Gateway, IdentityKey, MixId, MixNode,
};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
@@ -57,6 +57,25 @@ impl VestingSpecification {
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ExecuteMsg {
// Families
/// Only owner of the node can crate the family with node as head
CreateFamily {
owner_signature: String,
label: String,
},
/// Family head needs to sign the joining node IdentityKey
JoinFamily {
signature: String,
family_head: IdentityKey,
},
LeaveFamily {
signature: String,
family_head: IdentityKey,
},
KickFamilyMember {
signature: String,
member: IdentityKey,
},
TrackReward {
amount: Coin,
address: String,
@@ -134,6 +153,10 @@ pub enum ExecuteMsg {
impl ExecuteMsg {
pub fn name(&self) -> &str {
match self {
ExecuteMsg::CreateFamily { .. } => "VestingExecuteMsg::CreateFamily",
ExecuteMsg::JoinFamily { .. } => "VestingExecuteMsg::JoinFamily",
ExecuteMsg::LeaveFamily { .. } => "VestingExecuteMsg::LeaveFamily",
ExecuteMsg::KickFamilyMember { .. } => "VestingExecuteMsg::KickFamilyMember",
ExecuteMsg::TrackReward { .. } => "VestingExecuteMsg::TrackReward",
ExecuteMsg::ClaimOperatorReward { .. } => "VestingExecuteMsg::ClaimOperatorReward",
ExecuteMsg::ClaimDelegatorReward { .. } => "VestingExecuteMsg::ClaimDelegatorReward",
@@ -0,0 +1,16 @@
/*
* Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
* SPDX-License-Identifier: Apache-2.0
*/
DROP TABLE coconut_credentials;
CREATE TABLE coconut_credentials
(
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
voucher_value TEXT NOT NULL,
voucher_info TEXT NOT NULL,
serial_number TEXT NOT NULL,
binding_number TEXT NOT NULL,
signature TEXT NOT NULL UNIQUE,
consumed BOOLEAN NOT NULL
);
+16 -10
View File
@@ -36,8 +36,8 @@ impl CoconutCredentialManager {
signature: String,
) -> Result<(), sqlx::Error> {
sqlx::query!(
"INSERT INTO coconut_credentials(voucher_value, voucher_info, serial_number, binding_number, signature) VALUES (?, ?, ?, ?, ?)",
voucher_value, voucher_info, serial_number, binding_number, signature
"INSERT INTO coconut_credentials(voucher_value, voucher_info, serial_number, binding_number, signature, consumed) VALUES (?, ?, ?, ?, ?, ?)",
voucher_value, voucher_info, serial_number, binding_number, signature, false
)
.execute(&self.connection_pool)
.await?;
@@ -48,20 +48,26 @@ impl CoconutCredentialManager {
pub(crate) async fn get_next_coconut_credential(
&self,
) -> Result<CoconutCredential, sqlx::Error> {
sqlx::query_as!(CoconutCredential, "SELECT * FROM coconut_credentials")
.fetch_one(&self.connection_pool)
.await
sqlx::query_as!(
CoconutCredential,
"SELECT * FROM coconut_credentials WHERE NOT consumed"
)
.fetch_one(&self.connection_pool)
.await
}
/// Removes from the database the specified credential.
/// Consumes in the database the specified credential.
///
/// # Arguments
///
/// * `id`: Database id.
pub(crate) async fn remove_coconut_credential(&self, id: i64) -> Result<(), sqlx::Error> {
sqlx::query!("DELETE FROM coconut_credentials WHERE id = ?", id)
.execute(&self.connection_pool)
.await?;
pub(crate) async fn consume_coconut_credential(&self, id: i64) -> Result<(), sqlx::Error> {
sqlx::query!(
"UPDATE coconut_credentials SET consumed = TRUE WHERE id = ?",
id
)
.execute(&self.connection_pool)
.await?;
Ok(())
}
}
+2 -2
View File
@@ -93,9 +93,9 @@ impl Storage for PersistentStorage {
Ok(credential)
}
async fn remove_coconut_credential(&self, id: i64) -> Result<(), StorageError> {
async fn consume_coconut_credential(&self, id: i64) -> Result<(), StorageError> {
self.coconut_credential_manager
.remove_coconut_credential(id)
.consume_coconut_credential(id)
.await?;
Ok(())
+1
View File
@@ -9,4 +9,5 @@ pub struct CoconutCredential {
pub serial_number: String,
pub binding_number: String,
pub signature: String,
pub consumed: bool,
}
+3 -3
View File
@@ -25,10 +25,10 @@ pub trait Storage: Send + Sync {
/// Tries to retrieve one of the stored, unused credentials.
async fn get_next_coconut_credential(&self) -> Result<CoconutCredential, StorageError>;
/// Removes from the database the specified credential.
/// Marks as consumed in the database the specified credential.
///
/// # Arguments
///
/// * `signature`: Coconut credential in the form of a signature.
async fn remove_coconut_credential(&self, id: i64) -> Result<(), StorageError>;
/// * `id`: Id of the credential to be consumed.
async fn consume_coconut_credential(&self, id: i64) -> Result<(), StorageError>;
}
+1 -1
View File
@@ -53,7 +53,7 @@ impl PublicKey {
}
}
#[derive(Debug)]
#[derive(Clone, Debug)]
#[cfg_attr(test, derive(PartialEq, Eq))]
pub struct PublicKeyWithProof {
pub(crate) key: PublicKey,
@@ -13,7 +13,7 @@ use zeroize::Zeroize;
const DISCRETE_LOG_DOMAIN: &[u8] =
b"NYM_COCONUT_NIDKG_V01_CS01_WITH_BLS12381_XMD:SHA-256_SSWU_RO_PROOF_DISCRETE_LOG";
#[derive(Debug)]
#[derive(Clone, Debug)]
#[cfg_attr(test, derive(PartialEq, Eq))]
pub struct ProofOfDiscreteLog {
pub(crate) rand_commitment: G1Projective,
+72 -1
View File
@@ -9,19 +9,79 @@ use crate::interpolation::polynomial::{Polynomial, PublicCoefficients};
use crate::interpolation::{
perform_lagrangian_interpolation_at_origin, perform_lagrangian_interpolation_at_x,
};
use crate::utils::deserialize_g2;
use crate::{NodeIndex, Share, Threshold};
use bls12_381::{G2Projective, Scalar};
use group::GroupEncoding;
use rand_core::RngCore;
use std::collections::BTreeMap;
use zeroize::Zeroize;
#[derive(Debug)]
#[derive(Clone, Debug)]
#[cfg_attr(test, derive(PartialEq, Eq))]
pub struct RecoveredVerificationKeys {
pub recovered_master: G2Projective,
pub recovered_partials: Vec<G2Projective>,
}
impl RecoveredVerificationKeys {
pub fn to_bytes(&self) -> Vec<u8> {
let partials = self.recovered_partials.len();
let mut bytes = Vec::with_capacity(96 + 4 + 96 * partials);
bytes.extend_from_slice(self.recovered_master.to_bytes().as_ref());
bytes.extend_from_slice(&((partials as u32).to_be_bytes()));
for partial in &self.recovered_partials {
bytes.extend_from_slice(partial.to_bytes().as_ref());
}
bytes
}
pub fn try_from_bytes(b: &[u8]) -> Result<Self, DkgError> {
if b.len() < 96 + 4 {
return Err(DkgError::new_deserialization_failure(
"RecoveredVerificationKeys",
"insufficient number of bytes provided",
));
}
let recovered_master = deserialize_g2(&b[..96]).ok_or_else(|| {
DkgError::new_deserialization_failure(
"RecoveredVerificationKeys.recovered_master",
"invalid curve point",
)
})?;
let partials = u32::from_be_bytes([b[96], b[97], b[98], b[99]]) as usize;
let mut recovered_partials = Vec::with_capacity(partials);
if b.len() != 96 + 4 + 96 * partials {
return Err(DkgError::new_deserialization_failure(
"RecoveredVerificationKeys",
"insufficient number of bytes provided",
));
}
let mut i = 96 + 4;
for _ in 0..partials {
let partial = deserialize_g2(&b[i..i + 96]).ok_or_else(|| {
DkgError::new_deserialization_failure(
"RecoveredVerificationKeys.recovered_partials",
"invalid curve point",
)
})?;
recovered_partials.push(partial);
i += 96;
}
Ok(RecoveredVerificationKeys {
recovered_master,
recovered_partials,
})
}
}
#[derive(Debug)]
#[cfg_attr(test, derive(PartialEq, Eq))]
pub struct Dealing {
@@ -355,6 +415,17 @@ mod tests {
use crate::combine_shares;
use rand_core::SeedableRng;
#[test]
fn recovered_verification_keys_serde() {
let keys = RecoveredVerificationKeys {
recovered_master: Default::default(),
recovered_partials: vec![Default::default(), Default::default()],
};
let bytes = keys.to_bytes();
let recovered_keys = RecoveredVerificationKeys::try_from_bytes(&bytes).unwrap();
assert_eq!(keys, recovered_keys);
}
#[test]
#[ignore] // expensive test
fn recovering_partial_verification_keys() {
+2 -2
View File
@@ -9,7 +9,7 @@ pub(crate) const BECH32_PREFIX: &str = "n";
pub const MIX_DENOM: DenomDetails = DenomDetails::new("unym", "nym", 6);
pub const STAKE_DENOM: DenomDetails = DenomDetails::new("unyx", "nyx", 6);
pub(crate) const MIXNET_CONTRACT_ADDRESS: &str =
pub const MIXNET_CONTRACT_ADDRESS: &str =
"n17srjznxl9dvzdkpwpw24gg668wc73val88a6m5ajg6ankwvz9wtst0cznr";
pub(crate) const VESTING_CONTRACT_ADDRESS: &str =
"n1nc5tatafv6eyq7llkr2gv50ff9e22mnf70qgjlv737ktmt4eswrq73f2nw";
@@ -25,7 +25,7 @@ pub(crate) const _ETH_ERC20_CONTRACT_ADDRESS: [u8; 20] =
hex_literal::hex!("0000000000000000000000000000000000000000");
pub(crate) const REWARDING_VALIDATOR_ADDRESS: &str = "n10yyd98e2tuwu0f7ypz9dy3hhjw7v772q6287gy";
pub(crate) const STATISTICS_SERVICE_DOMAIN_ADDRESS: &str = "https://mainnet-stats.nymte.ch:8090/";
pub const STATISTICS_SERVICE_DOMAIN_ADDRESS: &str = "https://mainnet-stats.nymte.ch:8090/";
pub const NYMD_VALIDATOR: &str = "https://rpc.nymtech.net";
pub const API_VALIDATOR: &str = "https://validator.nymtech.net/api/";
pub(crate) fn validators() -> Vec<ValidatorDetails> {
+1
View File
@@ -45,6 +45,7 @@ fn keygen() -> Result<(), CoconutError> {
}
#[test]
#[ignore] // expensive test
fn dkg() -> Result<(), CoconutError> {
let params = setup(5)?;
let node_indices = vec![15u64, 248, 33521];
+6
View File
@@ -15,5 +15,11 @@ tokio = { version = "1.21.2", features = ["macros", "sync"] }
version = "1.21.2"
features = ["signal", "time"]
[target."cfg(target_arch = \"wasm32\")".dependencies.wasm-bindgen-futures]
version = "0.4"
[target."cfg(target_arch = \"wasm32\")".dependencies.wasm-bindgen]
version = "0.2.83"
[dev-dependencies]
tokio = { version = "1.21.2", features = ["rt-multi-thread", "net", "signal", "test-util", "macros"] }
+3
View File
@@ -4,7 +4,10 @@
pub mod shutdown;
#[cfg(not(target_arch = "wasm32"))]
pub mod signal;
pub mod spawn;
pub use shutdown::{ShutdownListener, ShutdownNotifier};
#[cfg(not(target_arch = "wasm32"))]
pub use signal::{wait_for_signal, wait_for_signal_and_error};
pub use spawn::spawn_with_report_error;
+82 -12
View File
@@ -3,7 +3,7 @@
use std::{error::Error, time::Duration};
use futures::FutureExt;
use futures::{future::pending, FutureExt};
use tokio::{
sync::{
mpsc,
@@ -14,7 +14,7 @@ use tokio::{
const DEFAULT_SHUTDOWN_TIMER_SECS: u64 = 5;
pub(crate) type SentError = Box<dyn Error + Send>;
pub(crate) type SentError = Box<dyn Error + Send + Sync>;
type ErrorSender = mpsc::UnboundedSender<SentError>;
type ErrorReceiver = mpsc::UnboundedReceiver<SentError>;
@@ -149,9 +149,8 @@ pub struct ShutdownListener {
// Also notify if we dropped without shutdown being registered
drop_error: ErrorSender,
// Sometimes it's necessary to clone and drop the shutdown listener during normal operation,
// for those situations we need to explicitly not drop (and trigger shutdown).
set_not_drop: bool,
// The current operating mode
mode: ShutdownListenerMode,
}
impl ShutdownListener {
@@ -168,15 +167,40 @@ impl ShutdownListener {
notify,
return_error,
drop_error,
set_not_drop: false,
mode: ShutdownListenerMode::Listening,
}
}
// Create a dummy that will never report that we should shutdown.
pub fn dummy() -> ShutdownListener {
let (_notify_tx, notify_rx) = watch::channel(());
let (task_halt_tx, _task_halt_rx) = mpsc::unbounded_channel();
let (task_drop_tx, _task_drop_rx) = mpsc::unbounded_channel();
ShutdownListener {
shutdown: false,
notify: notify_rx,
return_error: task_halt_tx,
drop_error: task_drop_tx,
mode: ShutdownListenerMode::Dummy,
}
}
pub fn is_dummy(&self) -> bool {
self.mode.is_dummy()
}
pub fn is_shutdown(&self) -> bool {
self.shutdown
if self.mode.is_dummy() {
false
} else {
self.shutdown
}
}
pub async fn recv(&mut self) {
if self.mode.is_dummy() {
return pending().await;
}
if self.shutdown {
return;
}
@@ -185,6 +209,9 @@ impl ShutdownListener {
}
pub async fn recv_timeout(&mut self) {
if self.mode.is_dummy() {
return pending().await;
}
#[cfg(not(target_arch = "wasm32"))]
tokio::time::timeout(Self::SHUTDOWN_TIMEOUT, self.recv())
.await
@@ -192,6 +219,9 @@ impl ShutdownListener {
}
pub fn is_shutdown_poll(&mut self) -> bool {
if self.mode.is_dummy() {
return false;
}
if self.shutdown {
return true;
}
@@ -210,21 +240,30 @@ impl ShutdownListener {
}
}
// This listener should to *not* notify the ShutdownNotifier to shutdown when dropped. For
// example when we clone the listener for a task handling connections, we often want to drop
// without signal failure.
pub fn mark_as_success(&mut self) {
self.mode.set_should_not_signal_on_drop();
}
pub fn send_we_stopped(&mut self, err: SentError) {
if self.mode.is_dummy() {
return;
}
log::trace!("Notifying we stopped: {:?}", err);
if self.return_error.send(err).is_err() {
log::error!("Failed to send back error message");
}
}
pub fn mark_as_success(&mut self) {
self.set_not_drop = true;
}
}
impl Drop for ShutdownListener {
fn drop(&mut self) {
if !self.set_not_drop && !self.is_shutdown_poll() {
if !self.mode.should_signal_on_drop() {
return;
}
if !self.is_shutdown_poll() {
log::trace!("Notifying stop on unexpected drop");
// If we can't send, well then there is not much to do
self.drop_error
@@ -234,6 +273,37 @@ impl Drop for ShutdownListener {
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
enum ShutdownListenerMode {
// Normal operations
Listening,
// Normal operations, but we don't report back if the we stop by getting dropped.
ListeningButDontReportHalt,
// Dummy mode, for when we don't do anything at all.
Dummy,
}
impl ShutdownListenerMode {
fn is_dummy(&self) -> bool {
self == &ShutdownListenerMode::Dummy
}
fn should_signal_on_drop(&self) -> bool {
match self {
ShutdownListenerMode::Listening => true,
ShutdownListenerMode::ListeningButDontReportHalt | ShutdownListenerMode::Dummy => false,
}
}
fn set_should_not_signal_on_drop(&mut self) {
use ShutdownListenerMode::{Dummy, Listening, ListeningButDontReportHalt};
*self = match &self {
ListeningButDontReportHalt | Listening => ListeningButDontReportHalt,
Dummy => Dummy,
};
}
}
#[cfg(test)]
mod tests {
use super::*;
+33
View File
@@ -0,0 +1,33 @@
use crate::ShutdownListener;
use std::future::Future;
#[cfg(target_arch = "wasm32")]
pub(crate) fn spawn<F>(future: F)
where
F: Future<Output = ()> + 'static,
{
wasm_bindgen_futures::spawn_local(future);
}
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn spawn<F>(future: F)
where
F: Future + Send + 'static,
F::Output: Send + 'static,
{
tokio::spawn(future);
}
pub fn spawn_with_report_error<F, T, E>(future: F, mut shutdown: ShutdownListener)
where
F: Future<Output = Result<T, E>> + Send + 'static,
T: 'static,
E: std::error::Error + Send + Sync + 'static,
{
let future_that_sends = async move {
if let Err(err) = future.await {
shutdown.send_we_stopped(Box::new(err));
}
};
spawn(future_that_sends);
}
+4
View File
@@ -84,6 +84,10 @@ impl NymTopology {
&self.mixes
}
pub fn num_mixnodes(&self) -> usize {
self.mixes.values().flat_map(|m| m.iter()).count()
}
pub fn mixes_as_vec(&self) -> Vec<mix::Node> {
let mut mixes: Vec<mix::Node> = vec![];
+1
View File
@@ -0,0 +1 @@
Cargo.lock
+6 -2
View File
@@ -1,10 +1,14 @@
## Unreleased
## Added
## [nym-contracts-v1.1.2](https://github.com/nymtech/nym/tree/nym-contracts-v1.1.2) (2022-12-07)
### Added
- Added migration code to the mixnet contract to allow updating stored vesting contract address to make it easier to deploy any future environments ([#1759],[#1769])
- Added an option to pledge additional tokens without the need to rebond minxode ([#1679])
- Added support for node families ([#1670])
[#1670]: https://github.com/nymtech/nym/pull/1670
[#1679]: https://github.com/nymtech/nym/pull/1679
[#1759]: https://github.com/nymtech/nym/pull/1759
[#1769]: https://github.com/nymtech/nym/pull/1769
@@ -95,4 +99,4 @@
[#1292]: https://github.com/nymtech/nym/pull/1292
[#1331]: https://github.com/nymtech/nym/pull/1331
[#1369]: https://github.com/nymtech/nym/pull/1369
[#1373]: https://github.com/nymtech/nym/pull/1373
[#1373]: https://github.com/nymtech/nym/pull/1373
-1783
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -25,7 +25,7 @@ impl<'a> IndexList<SpendCredential> for SpendCredentialIndex<'a> {
}
}
// gateways() is the storage access function.
// spent_credentials() is the storage access function.
pub(crate) fn spent_credentials<'a>(
) -> IndexedMap<'a, &'a str, SpendCredential, SpendCredentialIndex<'a>> {
let indexes = SpendCredentialIndex {
+5 -1
View File
@@ -19,4 +19,8 @@ cw4 = { version = "0.13.4" }
schemars = "0.8"
serde = { version = "1.0.103", default-features = false, features = ["derive"] }
thiserror = "1.0.23"
thiserror = "1.0.23"
[dev-dependencies]
cw-multi-test = { version = "0.13.4" }
cw4-group = { path = "../multisig/cw4-group" }
+264
View File
@@ -0,0 +1,264 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::dealers::queries::{
query_current_dealers_paged, query_dealer_details, query_past_dealers_paged,
};
use crate::dealers::transactions::try_add_dealer;
use crate::dealings::queries::query_dealings_paged;
use crate::dealings::transactions::try_commit_dealings;
use crate::epoch_state::queries::query_current_epoch_state;
use crate::epoch_state::storage::CURRENT_EPOCH_STATE;
use crate::epoch_state::transactions::advance_epoch_state;
use crate::error::ContractError;
use crate::state::{State, ADMIN, MULTISIG, STATE};
use crate::verification_key_shares::queries::query_vk_shares_paged;
use crate::verification_key_shares::transactions::try_commit_verification_key_share;
use crate::verification_key_shares::transactions::try_verify_verification_key_share;
use coconut_dkg_common::msg::{ExecuteMsg, InstantiateMsg, MigrateMsg, QueryMsg};
use coconut_dkg_common::types::EpochState;
use cosmwasm_std::{
entry_point, to_binary, Deps, DepsMut, Env, MessageInfo, QueryResponse, Response,
};
use cw4::Cw4Contract;
/// Instantiate the contract.
///
/// `deps` contains Storage, API and Querier
/// `env` contains block, message and contract info
/// `msg` is the contract initialization message, sort of like a constructor call.
#[entry_point]
pub fn instantiate(
mut deps: DepsMut<'_>,
_env: Env,
_info: MessageInfo,
msg: InstantiateMsg,
) -> Result<Response, ContractError> {
let admin_addr = deps.api.addr_validate(&msg.admin)?;
let multisig_addr = deps.api.addr_validate(&msg.multisig_addr)?;
ADMIN.set(deps.branch(), Some(admin_addr))?;
MULTISIG.set(deps.branch(), Some(multisig_addr.clone()))?;
let group_addr = Cw4Contract(deps.api.addr_validate(&msg.group_addr).map_err(|_| {
ContractError::InvalidGroup {
addr: msg.group_addr.clone(),
}
})?);
let state = State {
group_addr,
multisig_addr,
mix_denom: msg.mix_denom,
};
STATE.save(deps.storage, &state)?;
CURRENT_EPOCH_STATE.save(deps.storage, &EpochState::default())?;
Ok(Response::default())
}
/// Handle an incoming message
#[entry_point]
pub fn execute(
deps: DepsMut<'_>,
env: Env,
info: MessageInfo,
msg: ExecuteMsg,
) -> Result<Response, ContractError> {
match msg {
ExecuteMsg::RegisterDealer {
bte_key_with_proof,
announce_address,
} => try_add_dealer(deps, info, bte_key_with_proof, announce_address),
ExecuteMsg::CommitDealing { dealing_bytes } => {
try_commit_dealings(deps, info, dealing_bytes)
}
ExecuteMsg::CommitVerificationKeyShare { share } => {
try_commit_verification_key_share(deps, env, info, share)
}
ExecuteMsg::VerifyVerificationKeyShare { owner } => {
try_verify_verification_key_share(deps, info, owner)
}
ExecuteMsg::AdvanceEpochState {} => advance_epoch_state(deps, info),
}
}
#[entry_point]
pub fn query(deps: Deps<'_>, _env: Env, msg: QueryMsg) -> Result<QueryResponse, ContractError> {
let response = match msg {
QueryMsg::GetCurrentEpochState {} => to_binary(&query_current_epoch_state(deps.storage)?)?,
QueryMsg::GetDealerDetails { dealer_address } => {
to_binary(&query_dealer_details(deps, dealer_address)?)?
}
QueryMsg::GetCurrentDealers { limit, start_after } => {
to_binary(&query_current_dealers_paged(deps, start_after, limit)?)?
}
QueryMsg::GetPastDealers { limit, start_after } => {
to_binary(&query_past_dealers_paged(deps, start_after, limit)?)?
}
QueryMsg::GetDealing {
idx,
limit,
start_after,
} => to_binary(&query_dealings_paged(deps, idx, start_after, limit)?)?,
QueryMsg::GetVerificationKeys { limit, start_after } => {
to_binary(&query_vk_shares_paged(deps, start_after, limit)?)?
}
};
Ok(response)
}
#[entry_point]
pub fn migrate(_deps: DepsMut<'_>, _env: Env, _msg: MigrateMsg) -> Result<Response, ContractError> {
Ok(Default::default())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::support::tests::fixtures::{dealer_details_fixture, TEST_MIX_DENOM};
use crate::support::tests::helpers::{ADMIN_ADDRESS, MULTISIG_CONTRACT};
use coconut_dkg_common::dealer::DealerDetails;
use coconut_dkg_common::msg::ExecuteMsg::RegisterDealer;
use coconut_dkg_common::types::NodeIndex;
use cosmwasm_std::testing::{mock_dependencies, mock_env, mock_info};
use cosmwasm_std::{coins, Addr};
use cw4::Member;
use cw4_group::msg::InstantiateMsg as GroupInstantiateMsg;
use cw_multi_test::{App, AppBuilder, AppResponse, ContractWrapper, Executor};
fn instantiate_with_group(app: &mut App, members: &[Addr]) -> Addr {
let group_code_id = app.store_code(Box::new(ContractWrapper::new(
cw4_group::contract::execute,
cw4_group::contract::instantiate,
cw4_group::contract::query,
)));
let msg = GroupInstantiateMsg {
admin: Some(ADMIN_ADDRESS.to_string()),
members: members
.iter()
.map(|member| Member {
addr: member.to_string(),
weight: 10,
})
.collect(),
};
let group_contract_addr = app
.instantiate_contract(
group_code_id,
Addr::unchecked(ADMIN_ADDRESS),
&msg,
&[],
"group",
None,
)
.unwrap();
let coconut_dkg_code_id =
app.store_code(Box::new(ContractWrapper::new(execute, instantiate, query)));
let msg = InstantiateMsg {
group_addr: group_contract_addr.to_string(),
multisig_addr: MULTISIG_CONTRACT.to_string(),
admin: Addr::unchecked(ADMIN_ADDRESS).to_string(),
mix_denom: TEST_MIX_DENOM.to_string(),
};
app.instantiate_contract(
coconut_dkg_code_id,
Addr::unchecked(ADMIN_ADDRESS),
&msg,
&[],
"coconut dkg",
None,
)
.unwrap()
}
fn parse_node_index(res: AppResponse) -> NodeIndex {
res.events
.into_iter()
.find(|e| &e.ty == "wasm")
.unwrap()
.attributes
.into_iter()
.find(|attr| &attr.key == "node_index")
.unwrap()
.value
.parse::<u64>()
.unwrap()
}
#[test]
fn initialize_contract() {
let mut deps = mock_dependencies();
let env = mock_env();
let msg = InstantiateMsg {
group_addr: "group_addr".to_string(),
multisig_addr: "multisig_addr".to_string(),
admin: "admin".to_string(),
mix_denom: "nym".to_string(),
};
let info = mock_info("creator", &[]);
let res = instantiate(deps.as_mut(), env.clone(), info, msg);
assert!(res.is_ok())
}
#[test]
fn execute_add_dealer() {
let init_funds = coins(100, TEST_MIX_DENOM);
const MEMBER_SIZE: usize = 100;
let members: [Addr; MEMBER_SIZE] =
std::array::from_fn(|idx| Addr::unchecked(format!("member{}", idx)));
let mut app = AppBuilder::new().build(|router, _, storage| {
router
.bank
.init_balance(storage, &Addr::unchecked(ADMIN_ADDRESS), init_funds)
.unwrap();
});
let coconut_dkg_contract_addr = instantiate_with_group(&mut app, &members);
for (idx, member) in members.iter().enumerate() {
let res = app
.execute_contract(
member.clone(),
coconut_dkg_contract_addr.clone(),
&RegisterDealer {
bte_key_with_proof: "bte_key_with_proof".to_string(),
announce_address: "127.0.0.1:8000".to_string(),
},
&vec![],
)
.unwrap();
assert_eq!(parse_node_index(res), (idx + 1) as u64);
let err = app
.execute_contract(
member.clone(),
coconut_dkg_contract_addr.clone(),
&RegisterDealer {
bte_key_with_proof: "bte_key_with_proof".to_string(),
announce_address: "127.0.0.1:8000".to_string(),
},
&vec![],
)
.unwrap_err();
assert_eq!(ContractError::AlreadyADealer, err.downcast().unwrap());
}
let unauthorized_member = Addr::unchecked("not_a_member");
let err = app
.execute_contract(
unauthorized_member,
coconut_dkg_contract_addr.clone(),
&RegisterDealer {
bte_key_with_proof: "bte_key_with_proof".to_string(),
announce_address: "127.0.0.1:8000".to_string(),
},
&vec![],
)
.unwrap_err();
assert_eq!(ContractError::Unauthorized, err.downcast().unwrap());
}
}
+164 -3
View File
@@ -10,7 +10,7 @@ fn query_dealers(
deps: Deps<'_>,
start_after: Option<String>,
limit: Option<u32>,
underlying_map: IndexedDealersMap<'_>,
underlying_map: &IndexedDealersMap<'_>,
) -> StdResult<PagedDealerResponse> {
let limit = limit
.unwrap_or(storage::DEALERS_PAGE_DEFAULT_LIMIT)
@@ -55,7 +55,7 @@ pub fn query_current_dealers_paged(
start_after: Option<String>,
limit: Option<u32>,
) -> StdResult<PagedDealerResponse> {
query_dealers(deps, start_after, limit, storage::current_dealers())
query_dealers(deps, start_after, limit, &storage::current_dealers())
}
pub fn query_past_dealers_paged(
@@ -63,5 +63,166 @@ pub fn query_past_dealers_paged(
start_after: Option<String>,
limit: Option<u32>,
) -> StdResult<PagedDealerResponse> {
query_dealers(deps, start_after, limit, storage::past_dealers())
query_dealers(deps, start_after, limit, &storage::past_dealers())
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
use crate::dealers::storage::{DEALERS_PAGE_DEFAULT_LIMIT, DEALERS_PAGE_MAX_LIMIT};
use crate::support::tests::fixtures::dealer_details_fixture;
use crate::support::tests::helpers::init_contract;
use cosmwasm_std::testing::mock_env;
use cosmwasm_std::{Addr, DepsMut};
fn fill_dealers(deps: DepsMut<'_>, mapping: &IndexedDealersMap<'_>, size: usize) {
for n in 0..size {
let dealer_details = dealer_details_fixture(n as u64);
mapping
.save(deps.storage, &dealer_details.address, &dealer_details)
.unwrap();
}
}
fn remove_dealers(deps: DepsMut<'_>, mapping: &IndexedDealersMap<'_>, size: usize) {
for n in 0..size {
let dealer_details = dealer_details_fixture(n as u64);
mapping
.remove(deps.storage, &dealer_details.address)
.unwrap();
}
}
#[test]
fn dealers_empty_on_init() {
let mut deps = init_contract();
let env = mock_env();
for mapping in [storage::current_dealers(), storage::past_dealers()] {
let page1 = query_dealers(deps.as_ref(), None, None, &mapping).unwrap();
assert_eq!(0, page1.dealers.len() as u32);
}
}
#[test]
fn dealers_paged_retrieval_obeys_limits() {
let mut deps = init_contract();
let env = mock_env();
let owner = Addr::unchecked("owner");
let limit = 2;
for mapping in [storage::current_dealers(), storage::past_dealers()] {
fill_dealers(deps.as_mut(), &mapping, 1000);
let page1 = query_dealers(deps.as_ref(), None, Option::from(limit), &mapping).unwrap();
assert_eq!(limit, page1.dealers.len() as u32);
remove_dealers(deps.as_mut(), &mapping, 1000);
}
}
#[test]
fn dealers_paged_retrieval_has_default_limit() {
let mut deps = init_contract();
let env = mock_env();
for mapping in [storage::current_dealers(), storage::past_dealers()] {
fill_dealers(deps.as_mut(), &mapping, 1000);
// query without explicitly setting a limit
let page1 = query_dealers(deps.as_ref(), None, None, &mapping).unwrap();
assert_eq!(DEALERS_PAGE_DEFAULT_LIMIT, page1.dealers.len() as u32);
remove_dealers(deps.as_mut(), &mapping, 1000);
}
}
#[test]
fn dealers_paged_retrieval_has_max_limit() {
let mut deps = init_contract();
let env = mock_env();
// query with a crazily high limit in an attempt to use too many resources
let crazy_limit = 1000 * DEALERS_PAGE_MAX_LIMIT;
for mapping in [storage::current_dealers(), storage::past_dealers()] {
fill_dealers(deps.as_mut(), &mapping, 1000);
let page1 =
query_dealers(deps.as_ref(), None, Option::from(crazy_limit), &mapping).unwrap();
// we default to a decent sized upper bound instead
let expected_limit = DEALERS_PAGE_MAX_LIMIT;
assert_eq!(expected_limit, page1.dealers.len() as u32);
remove_dealers(deps.as_mut(), &mapping, 1000);
}
}
#[test]
fn dealers_pagination_works() {
let mut deps = init_contract();
let env = mock_env();
let per_page = 2;
for mapping in [storage::current_dealers(), storage::past_dealers()] {
fill_dealers(deps.as_mut(), &mapping, 1);
let page1 =
query_dealers(deps.as_ref(), None, Option::from(per_page), &mapping).unwrap();
// page should have 1 result on it
assert_eq!(1, page1.dealers.len());
remove_dealers(deps.as_mut(), &mapping, 1);
}
for mapping in [storage::current_dealers(), storage::past_dealers()] {
fill_dealers(deps.as_mut(), &mapping, 2);
// page1 should have 2 results on it
let page1 =
query_dealers(deps.as_ref(), None, Option::from(per_page), &mapping).unwrap();
assert_eq!(2, page1.dealers.len());
remove_dealers(deps.as_mut(), &mapping, 2);
}
for mapping in [storage::current_dealers(), storage::past_dealers()] {
fill_dealers(deps.as_mut(), &mapping, 3);
// page1 still has 2 results
let page1 =
query_dealers(deps.as_ref(), None, Option::from(per_page), &mapping).unwrap();
assert_eq!(2, page1.dealers.len());
// retrieving the next page should start after the last key on this page
let start_after = page1.start_next_after.unwrap();
let page2 = query_dealers(
deps.as_ref(),
Option::from(start_after.to_string()),
Option::from(per_page),
&mapping,
)
.unwrap();
assert_eq!(1, page2.dealers.len());
remove_dealers(deps.as_mut(), &mapping, 3);
}
for mapping in [storage::current_dealers(), storage::past_dealers()] {
fill_dealers(deps.as_mut(), &mapping, 4);
let page1 =
query_dealers(deps.as_ref(), None, Option::from(per_page), &mapping).unwrap();
let start_after = page1.start_next_after.unwrap();
let page2 = query_dealers(
deps.as_ref(),
Option::from(start_after.to_string()),
Option::from(per_page),
&mapping,
)
.unwrap();
// now we have 2 pages, with 2 results on the second page
assert_eq!(2, page2.dealers.len());
remove_dealers(deps.as_mut(), &mapping, 4);
}
}
}
@@ -3,7 +3,8 @@
use crate::dealers::storage as dealers_storage;
use crate::epoch_state::utils::check_epoch_state;
use crate::{ContractError, State, STATE};
use crate::error::ContractError;
use crate::state::{State, STATE};
use coconut_dkg_common::types::{DealerDetails, EncodedBTEPublicKeyWithProof, EpochState};
use cosmwasm_std::{Addr, DepsMut, MessageInfo, Response};
@@ -64,3 +65,40 @@ pub fn try_add_dealer(
Ok(Response::new().add_attribute("node_index", node_index.to_string()))
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
use crate::epoch_state::transactions::advance_epoch_state;
use crate::support::tests::fixtures::dealer_details_fixture;
use crate::support::tests::helpers;
use crate::support::tests::helpers::ADMIN_ADDRESS;
use cosmwasm_std::testing::mock_info;
#[test]
fn invalid_state() {
let mut deps = helpers::init_contract();
let owner = Addr::unchecked("owner");
let info = mock_info(owner.as_str(), &[]);
let dealer_details = dealer_details_fixture(1);
let bte_key_with_proof = String::from("bte_key_with_proof");
let announce_address = String::from("localhost:8000");
advance_epoch_state(deps.as_mut(), mock_info(ADMIN_ADDRESS, &[])).unwrap();
let ret = try_add_dealer(
deps.as_mut(),
info.clone(),
bte_key_with_proof.clone(),
announce_address.clone(),
)
.unwrap_err();
assert_eq!(
ret,
ContractError::IncorrectEpochState {
current_state: EpochState::DealingExchange.to_string(),
expected_state: EpochState::default().to_string(),
}
);
}
}
@@ -43,3 +43,159 @@ pub fn query_dealings_paged(
start_next_after,
))
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
use crate::dealings::storage::{DEALINGS_PAGE_DEFAULT_LIMIT, DEALINGS_PAGE_MAX_LIMIT};
use crate::support::tests::fixtures::dealing_bytes_fixture;
use crate::support::tests::helpers::init_contract;
use cosmwasm_std::testing::mock_env;
use cosmwasm_std::{Addr, DepsMut};
fn fill_dealings(deps: DepsMut<'_>, size: usize) {
for n in 0..size {
let dealing_share = dealing_bytes_fixture();
let sender = Addr::unchecked(format!("owner{}", n));
for idx in 0..TOTAL_DEALINGS {
DEALINGS_BYTES[idx]
.save(deps.storage, &sender, &dealing_share)
.unwrap();
}
}
}
#[test]
fn empty_on_bad_idx() {
let mut deps = init_contract();
let env = mock_env();
fill_dealings(deps.as_mut(), 1000);
for idx in TOTAL_DEALINGS as u64..100 * TOTAL_DEALINGS as u64 {
let page1 = query_dealings_paged(deps.as_ref(), idx, None, None).unwrap();
assert_eq!(0, page1.dealings.len() as u32);
}
}
#[test]
fn dealings_empty_on_init() {
let deps = init_contract();
for idx in 0..TOTAL_DEALINGS as u64 {
let response = query_dealings_paged(deps.as_ref(), idx, None, Option::from(2)).unwrap();
assert_eq!(0, response.dealings.len());
}
}
#[test]
fn dealings_paged_retrieval_obeys_limits() {
let mut deps = init_contract();
let env = mock_env();
let limit = 2;
fill_dealings(deps.as_mut(), 1000);
for idx in 0..TOTAL_DEALINGS as u64 {
let page1 =
query_dealings_paged(deps.as_ref(), idx, None, Option::from(limit)).unwrap();
assert_eq!(limit, page1.dealings.len() as u32);
}
}
#[test]
fn dealings_paged_retrieval_has_default_limit() {
let mut deps = init_contract();
let env = mock_env();
fill_dealings(deps.as_mut(), 1000);
for idx in 0..TOTAL_DEALINGS as u64 {
// query without explicitly setting a limit
let page1 = query_dealings_paged(deps.as_ref(), idx, None, None).unwrap();
assert_eq!(DEALINGS_PAGE_DEFAULT_LIMIT, page1.dealings.len() as u32);
}
}
#[test]
fn dealings_paged_retrieval_has_max_limit() {
let mut deps = init_contract();
let env = mock_env();
fill_dealings(deps.as_mut(), 1000);
// query with a crazily high limit in an attempt to use too many resources
let crazy_limit = 1000 * DEALINGS_PAGE_MAX_LIMIT;
for idx in 0..TOTAL_DEALINGS as u64 {
let page1 =
query_dealings_paged(deps.as_ref(), idx, None, Option::from(crazy_limit)).unwrap();
// we default to a decent sized upper bound instead
let expected_limit = DEALINGS_PAGE_MAX_LIMIT;
assert_eq!(expected_limit, page1.dealings.len() as u32);
}
}
#[test]
fn dealings_pagination_works() {
let mut deps = init_contract();
let env = mock_env();
fill_dealings(deps.as_mut(), 1);
let per_page = 2;
for idx in 0..TOTAL_DEALINGS as u64 {
let page1 =
query_dealings_paged(deps.as_ref(), idx, None, Option::from(per_page)).unwrap();
// page should have 1 result on it
assert_eq!(1, page1.dealings.len());
}
// save another
fill_dealings(deps.as_mut(), 2);
for idx in 0..TOTAL_DEALINGS as u64 {
// page1 should have 2 results on it
let page1 =
query_dealings_paged(deps.as_ref(), idx, None, Option::from(per_page)).unwrap();
assert_eq!(2, page1.dealings.len());
}
fill_dealings(deps.as_mut(), 3);
for idx in 0..TOTAL_DEALINGS as u64 {
// page1 still has 2 results
let page1 =
query_dealings_paged(deps.as_ref(), idx, None, Option::from(per_page)).unwrap();
assert_eq!(2, page1.dealings.len());
// retrieving the next page should start after the last key on this page
let start_after = page1.start_next_after.unwrap();
let page2 = query_dealings_paged(
deps.as_ref(),
idx,
Option::from(start_after.to_string()),
Option::from(per_page),
)
.unwrap();
assert_eq!(1, page2.dealings.len());
}
fill_dealings(deps.as_mut(), 4);
for idx in 0..TOTAL_DEALINGS as u64 {
let page1 =
query_dealings_paged(deps.as_ref(), idx, None, Option::from(per_page)).unwrap();
let start_after = page1.start_next_after.unwrap();
let page2 = query_dealings_paged(
deps.as_ref(),
idx,
Option::from(start_after.to_string()),
Option::from(per_page),
)
.unwrap();
// now we have 2 pages, with 2 results on the second page
assert_eq!(2, page2.dealings.len());
}
}
}
@@ -4,7 +4,7 @@
use crate::dealers::storage as dealers_storage;
use crate::dealings::storage::DEALINGS_BYTES;
use crate::epoch_state::utils::check_epoch_state;
use crate::ContractError;
use crate::error::ContractError;
use coconut_dkg_common::types::{ContractSafeBytes, EpochState};
use cosmwasm_std::{DepsMut, MessageInfo, Response};
@@ -35,3 +35,65 @@ pub fn try_commit_dealings(
commitment: String::from("dealing"),
})
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
use crate::epoch_state::transactions::advance_epoch_state;
use crate::support::tests::fixtures::dealing_bytes_fixture;
use crate::support::tests::helpers;
use crate::support::tests::helpers::ADMIN_ADDRESS;
use coconut_dkg_common::dealer::DealerDetails;
use coconut_dkg_common::types::TOTAL_DEALINGS;
use cosmwasm_std::testing::mock_info;
use cosmwasm_std::Addr;
#[test]
fn invalid_commit_dealing() {
let mut deps = helpers::init_contract();
let owner = Addr::unchecked("owner");
let info = mock_info(owner.as_str(), &[]);
let dealing_bytes = dealing_bytes_fixture();
let ret =
try_commit_dealings(deps.as_mut(), info.clone(), dealing_bytes.clone()).unwrap_err();
assert_eq!(
ret,
ContractError::IncorrectEpochState {
current_state: EpochState::default().to_string(),
expected_state: EpochState::DealingExchange.to_string()
}
);
advance_epoch_state(deps.as_mut(), mock_info(ADMIN_ADDRESS, &[])).unwrap();
let ret =
try_commit_dealings(deps.as_mut(), info.clone(), dealing_bytes.clone()).unwrap_err();
assert_eq!(ret, ContractError::NotADealer);
let dealer_details = DealerDetails {
address: owner.clone(),
bte_public_key_with_proof: String::new(),
announce_address: String::new(),
assigned_index: 1,
};
dealers_storage::current_dealers()
.save(deps.as_mut().storage, &owner, &dealer_details)
.unwrap();
for dealings in DEALINGS_BYTES {
assert!(!dealings.has(deps.as_mut().storage, &owner));
let ret = try_commit_dealings(deps.as_mut(), info.clone(), dealing_bytes.clone());
assert!(ret.is_ok());
assert!(dealings.has(deps.as_mut().storage, &owner));
}
let ret =
try_commit_dealings(deps.as_mut(), info.clone(), dealing_bytes.clone()).unwrap_err();
assert_eq!(
ret,
ContractError::AlreadyCommitted {
commitment: String::from("dealing"),
}
);
}
}
@@ -3,4 +3,5 @@
pub mod queries;
pub mod storage;
pub mod transactions;
pub mod utils;
@@ -1,13 +1,28 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use super::storage;
use crate::ContractError;
use crate::epoch_state::storage::CURRENT_EPOCH_STATE;
use crate::error::ContractError;
use coconut_dkg_common::types::EpochState;
use cosmwasm_std::Storage;
pub(crate) fn query_current_epoch_state(
storage: &dyn Storage,
) -> Result<EpochState, ContractError> {
storage::current_epoch_state(storage)
CURRENT_EPOCH_STATE
.load(storage)
.map_err(|_| ContractError::EpochNotInitialised)
}
#[cfg(test)]
pub(crate) mod test {
use super::*;
use crate::support::tests::helpers::init_contract;
#[test]
fn query_state() {
let mut deps = init_contract();
let state = query_current_epoch_state(deps.as_mut().storage).unwrap();
assert_eq!(state, EpochState::PublicKeySubmission);
}
}
@@ -1,29 +1,7 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::{ContractError, ADMIN};
use coconut_dkg_common::types::EpochState;
use cosmwasm_std::{DepsMut, MessageInfo, Response, Storage};
use cw_storage_plus::Item;
pub(crate) const CURRENT_EPOCH_STATE: Item<'_, EpochState> = Item::new("current_epoch_state");
pub(crate) fn current_epoch_state(storage: &dyn Storage) -> Result<EpochState, ContractError> {
CURRENT_EPOCH_STATE
.load(storage)
.map_err(|_| ContractError::EpochNotInitialised)
}
pub(crate) fn advance_epoch_state(
deps: DepsMut<'_>,
info: MessageInfo,
) -> Result<Response, ContractError> {
ADMIN.assert_admin(deps.as_ref(), &info.sender)?;
CURRENT_EPOCH_STATE.update::<_, ContractError>(deps.storage, |mut epoch_state| {
// TODO: When defaulting to the first state, some action will probably need to be taken on the
// rest of the contract, as we're starting with a new set of signers
epoch_state = epoch_state.next().unwrap_or_default();
Ok(epoch_state)
})?;
Ok(Response::default())
}
@@ -0,0 +1,78 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::epoch_state::storage::CURRENT_EPOCH_STATE;
use crate::error::ContractError;
use crate::state::ADMIN;
use cosmwasm_std::{DepsMut, MessageInfo, Response};
pub(crate) fn advance_epoch_state(
deps: DepsMut<'_>,
info: MessageInfo,
) -> Result<Response, ContractError> {
ADMIN.assert_admin(deps.as_ref(), &info.sender)?;
CURRENT_EPOCH_STATE.update::<_, ContractError>(deps.storage, |mut epoch_state| {
// TODO: When defaulting to the first state, some action will probably need to be taken on the
// rest of the contract, as we're starting with a new set of signers
epoch_state = epoch_state.next().unwrap_or_default();
Ok(epoch_state)
})?;
Ok(Response::default())
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
use crate::support::tests::helpers::{init_contract, ADMIN_ADDRESS};
use coconut_dkg_common::types::EpochState;
use cosmwasm_std::testing::mock_info;
use cw_controllers::AdminError;
#[test]
fn advance_state() {
let mut deps = init_contract();
let info = mock_info("requester", &[]);
let admin_info = mock_info(ADMIN_ADDRESS, &[]);
assert_eq!(
advance_epoch_state(deps.as_mut(), info).unwrap_err(),
ContractError::Admin(AdminError::NotAdmin {})
);
advance_epoch_state(deps.as_mut(), admin_info.clone()).unwrap();
assert_eq!(
CURRENT_EPOCH_STATE.load(deps.as_mut().storage).unwrap(),
EpochState::DealingExchange
);
advance_epoch_state(deps.as_mut(), admin_info.clone()).unwrap();
assert_eq!(
CURRENT_EPOCH_STATE.load(deps.as_mut().storage).unwrap(),
EpochState::VerificationKeySubmission
);
advance_epoch_state(deps.as_mut(), admin_info.clone()).unwrap();
assert_eq!(
CURRENT_EPOCH_STATE.load(deps.as_mut().storage).unwrap(),
EpochState::VerificationKeyValidation
);
advance_epoch_state(deps.as_mut(), admin_info.clone()).unwrap();
assert_eq!(
CURRENT_EPOCH_STATE.load(deps.as_mut().storage).unwrap(),
EpochState::VerificationKeyFinalization
);
advance_epoch_state(deps.as_mut(), admin_info.clone()).unwrap();
assert_eq!(
CURRENT_EPOCH_STATE.load(deps.as_mut().storage).unwrap(),
EpochState::InProgress
);
advance_epoch_state(deps.as_mut(), admin_info.clone()).unwrap();
assert_eq!(
CURRENT_EPOCH_STATE.load(deps.as_mut().storage).unwrap(),
EpochState::PublicKeySubmission
);
}
}
+27 -1
View File
@@ -1,7 +1,8 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::{ContractError, CURRENT_EPOCH_STATE};
use crate::epoch_state::storage::CURRENT_EPOCH_STATE;
use crate::error::ContractError;
use coconut_dkg_common::types::EpochState;
use cosmwasm_std::Storage;
@@ -19,3 +20,28 @@ pub(crate) fn check_epoch_state(
Ok(())
}
}
#[cfg(test)]
pub(crate) mod test {
use super::*;
use crate::support::tests::helpers::init_contract;
#[test]
pub fn check_state() {
let mut deps = init_contract();
for fixed_state in EpochState::default().all_until(EpochState::InProgress) {
CURRENT_EPOCH_STATE
.save(deps.as_mut().storage, &fixed_state)
.unwrap();
for against_state in EpochState::default().all_until(EpochState::InProgress) {
let ret = check_epoch_state(deps.as_mut().storage, against_state);
if fixed_state == against_state {
assert!(ret.is_ok());
} else {
assert!(ret.is_err());
}
}
}
}
}
+1 -24
View File
@@ -1,7 +1,7 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use cosmwasm_std::{Addr, StdError, VerificationError};
use cosmwasm_std::StdError;
use cw_controllers::AdminError;
use thiserror::Error;
@@ -17,24 +17,6 @@ pub enum ContractError {
#[error("Group contract invalid address '{addr}'")]
InvalidGroup { addr: String },
#[error("No coin was sent for the deposit, you must send {denom}")]
NoDepositFound { denom: String },
#[error("Received multiple coin types")]
MultipleDenoms,
#[error("Wrong coin denomination, you must send {denom}")]
WrongDenom { denom: String },
#[error("Not enough funds sent for deposit. (received {received}, minimum {minimum})")]
InsufficientDeposit { received: u128, minimum: u128 },
#[error("Failed to perform ed25519 signature verification - {0}. This dealer will be temporarily blacklisted now.")]
Ed25519VerificationError(#[from] VerificationError),
#[error("Provided ed25519 signature did not verify correctly. This dealer will be temporarily blacklisted now.")]
InvalidEd25519Signature,
#[error("This potential dealer is not in the coconut signer group")]
Unauthorized,
@@ -52,11 +34,6 @@ pub enum ContractError {
expected_state: String,
},
// we should never ever see this error (famous last words in programming), therefore, I'd want to
// explicitly declare it so that when we ultimate do see it, it's gonna be more informative over "normal" panic
#[error("Somehow our validated address {address} is not using correct bech32 encoding")]
InvalidValidatedAddress { address: Addr },
#[error("This sender is not a dealer for the current epoch")]
NotADealer,
+3 -137
View File
@@ -1,146 +1,12 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::dealers::queries::{
query_current_dealers_paged, query_dealer_details, query_past_dealers_paged,
};
use crate::dealings::queries::query_dealings_paged;
use crate::epoch_state::queries::query_current_epoch_state;
use crate::error::ContractError;
use crate::state::{State, ADMIN, MULTISIG, STATE};
use crate::verification_key_shares::queries::query_vk_shares_paged;
use coconut_dkg_common::msg::{ExecuteMsg, InstantiateMsg, MigrateMsg, QueryMsg};
use coconut_dkg_common::types::EpochState;
use cosmwasm_std::{
entry_point, to_binary, Deps, DepsMut, Env, MessageInfo, QueryResponse, Response,
};
use cw4::Cw4Contract;
use epoch_state::storage::{advance_epoch_state, CURRENT_EPOCH_STATE};
mod constants;
pub mod contract;
mod dealers;
mod dealings;
mod epoch_state;
mod error;
pub mod error;
mod state;
mod support;
mod verification_key_shares;
/// Instantiate the contract.
///
/// `deps` contains Storage, API and Querier
/// `env` contains block, message and contract info
/// `msg` is the contract initialization message, sort of like a constructor call.
#[entry_point]
pub fn instantiate(
mut deps: DepsMut<'_>,
_env: Env,
_info: MessageInfo,
msg: InstantiateMsg,
) -> Result<Response, ContractError> {
let admin_addr = deps.api.addr_validate(&msg.admin)?;
let multisig_addr = deps.api.addr_validate(&msg.multisig_addr)?;
ADMIN.set(deps.branch(), Some(admin_addr))?;
MULTISIG.set(deps.branch(), Some(multisig_addr.clone()))?;
let group_addr = Cw4Contract(deps.api.addr_validate(&msg.group_addr).map_err(|_| {
ContractError::InvalidGroup {
addr: msg.group_addr.clone(),
}
})?);
let state = State {
group_addr,
multisig_addr,
mix_denom: msg.mix_denom,
};
STATE.save(deps.storage, &state)?;
CURRENT_EPOCH_STATE.save(deps.storage, &EpochState::default())?;
Ok(Response::default())
}
/// Handle an incoming message
#[entry_point]
pub fn execute(
deps: DepsMut<'_>,
env: Env,
info: MessageInfo,
msg: ExecuteMsg,
) -> Result<Response, ContractError> {
match msg {
ExecuteMsg::RegisterDealer {
bte_key_with_proof,
announce_address,
} => {
dealers::transactions::try_add_dealer(deps, info, bte_key_with_proof, announce_address)
}
ExecuteMsg::CommitDealing { dealing_bytes } => {
dealings::transactions::try_commit_dealings(deps, info, dealing_bytes)
}
ExecuteMsg::CommitVerificationKeyShare { share } => {
verification_key_shares::transactions::try_commit_verification_key_share(
deps, env, info, share,
)
}
ExecuteMsg::VerifyVerificationKeyShare { owner } => {
verification_key_shares::transactions::try_verify_verification_key_share(
deps, info, owner,
)
}
ExecuteMsg::AdvanceEpochState {} => advance_epoch_state(deps, info),
}
}
#[entry_point]
pub fn query(deps: Deps<'_>, _env: Env, msg: QueryMsg) -> Result<QueryResponse, ContractError> {
let response = match msg {
QueryMsg::GetCurrentEpochState {} => to_binary(&query_current_epoch_state(deps.storage)?)?,
QueryMsg::GetDealerDetails { dealer_address } => {
to_binary(&query_dealer_details(deps, dealer_address)?)?
}
QueryMsg::GetCurrentDealers { limit, start_after } => {
to_binary(&query_current_dealers_paged(deps, start_after, limit)?)?
}
QueryMsg::GetPastDealers { limit, start_after } => {
to_binary(&query_past_dealers_paged(deps, start_after, limit)?)?
}
QueryMsg::GetDealing {
idx,
limit,
start_after,
} => to_binary(&query_dealings_paged(deps, idx, start_after, limit)?)?,
QueryMsg::GetVerificationKeys { limit, start_after } => {
to_binary(&query_vk_shares_paged(deps, start_after, limit)?)?
}
};
Ok(response)
}
#[entry_point]
pub fn migrate(_deps: DepsMut<'_>, _env: Env, _msg: MigrateMsg) -> Result<Response, ContractError> {
Ok(Default::default())
}
#[cfg(test)]
mod tests {
use super::*;
use cosmwasm_std::testing::{mock_dependencies, mock_env, mock_info};
#[test]
fn initialize_contract() {
let mut deps = mock_dependencies();
let env = mock_env();
let msg = InstantiateMsg {
group_addr: "group_addr".to_string(),
multisig_addr: "multisig_addr".to_string(),
admin: "admin".to_string(),
mix_denom: "nym".to_string(),
};
let info = mock_info("creator", &[]);
let res = instantiate(deps.as_mut(), env.clone(), info, msg);
assert!(res.is_ok())
}
}

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