Compare commits

..

4 Commits

Author SHA1 Message Date
Jędrzej Stuczyński 2cc99b486e being VERY explicit about loading coconut keys 2023-12-14 10:09:52 +00:00
Jędrzej Stuczyński 556d980c01 fixed node indexing 2023-12-14 09:27:39 +00:00
Jędrzej Stuczyński b86ae7520e hardcoded migration data 2023-12-14 09:05:47 +00:00
Jędrzej Stuczyński 43da0e3aa7 ignore dkg 2023-12-14 08:30:49 +00:00
781 changed files with 19784 additions and 15184 deletions
-21
View File
@@ -1,21 +0,0 @@
name: ci-cargo-deny
on: [workflow_dispatch]
jobs:
cargo-deny:
runs-on: ubuntu-22.04
strategy:
matrix:
checks:
# - advisories
- licenses
- bans sources
continue-on-error: ${{ matrix.checks == 'licenses' }}
steps:
- uses: actions/checkout@v3
- uses: EmbarkStudios/cargo-deny-action@v1
with:
log-level: warn
command: check ${{ matrix.checks }}
argument: --all-features
-3
View File
@@ -17,9 +17,6 @@ jobs:
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v2
- name: install yarn in root
run: cd ../.. yarn install
- name: Install npm - name: Install npm
run: npm install run: npm install
+40
View File
@@ -0,0 +1,40 @@
name: ci-nym-vpn-ui-js
on:
workflow_dispatch:
pull_request:
paths:
- 'nym-vpn/ui/src/**'
- 'nym-vpn/ui/package.json'
- 'nym-vpn/ui/index.html'
jobs:
check:
runs-on: custom-linux
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Install Node
uses: actions/setup-node@v3
with:
node-version: 18
- name: Install Yarn
run: npm install -g yarn
- name: Install dependencies
working-directory: nym-vpn/ui
run: yarn
- name: Type-check
working-directory: nym-vpn/ui
run: yarn typecheck
- name: Check lint
working-directory: nym-vpn/ui
run: yarn lint
- name: Check formatting
working-directory: nym-vpn/ui
run: yarn fmt:check
# - name: Run tests
# working-directory: nym-vpn/ui
# run: yarn test
- name: Check build
working-directory: nym-vpn/ui
run: yarn build
+63
View File
@@ -0,0 +1,63 @@
name: ci-nym-vpn-ui-rust
on:
workflow_dispatch:
pull_request:
paths:
- 'nym-vpn/ui/src-tauri/**'
jobs:
build:
runs-on: custom-linux
env:
CARGO_TERM_COLOR: always
CARGOTOML_PATH: ./nym-vpn/ui/src-tauri/Cargo.toml
steps:
- name: Install Dependencies (Linux)
run: sudo apt-get update && sudo apt-get -y install libwebkit2gtk-4.0-dev build-essential curl wget libssl-dev libgtk-3-dev squashfs-tools libayatana-appindicator3-dev
continue-on-error: true
- name: Checkout
uses: actions/checkout@v4
- name: Install rust toolchain
uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: stable
override: true
components: rustfmt, clippy
- name: Prepare build
run: mkdir nym-vpn/ui/dist
- name: Build
uses: actions-rs/cargo@v1
with:
command: build
args: --manifest-path ${{ env.CARGOTOML_PATH }} --features custom-protocol
# - name: Run all tests
# uses: actions-rs/cargo@v1
# with:
# command: test
# args: --manifest-path ${{ env.CARGOTOML_PATH }}
- name: Check formatting
uses: actions-rs/cargo@v1
with:
command: fmt
args: --manifest-path ${{ env.CARGOTOML_PATH }} --all -- --check
- name: Annotate with clippy checks
uses: actions-rs/clippy-check@v1
continue-on-error: true
with:
token: ${{ secrets.GITHUB_TOKEN }}
args: --manifest-path ${{ env.CARGOTOML_PATH }} --all-features
- name: Clippy
uses: actions-rs/cargo@v1
with:
command: clippy
args: --manifest-path ${{ env.CARGOTOML_PATH }} --all-features --all-targets -- -D warnings
-1
View File
@@ -9,7 +9,6 @@
target target
.env .env
.env.dev .env.dev
envs/devnet.env
/.vscode/settings.json /.vscode/settings.json
validator/.vscode validator/.vscode
sample-configs/validator-config.toml sample-configs/validator-config.toml
Generated
+295 -270
View File
@@ -661,22 +661,6 @@ dependencies = [
"syn 2.0.38", "syn 2.0.38",
] ]
[[package]]
name = "async-tungstenite"
version = "0.23.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a1e9efbe14612da0a19fb983059a0b621e9cf6225d7018ecab4f9988215540dc"
dependencies = [
"futures-io",
"futures-util",
"log",
"pin-project-lite 0.2.13",
"rustls-native-certs",
"tokio",
"tokio-rustls 0.24.1",
"tungstenite",
]
[[package]] [[package]]
name = "asynchronous-codec" name = "asynchronous-codec"
version = "0.6.2" version = "0.6.2"
@@ -690,6 +674,15 @@ dependencies = [
"pin-project-lite 0.2.13", "pin-project-lite 0.2.13",
] ]
[[package]]
name = "atoi"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "616896e05fc0e2649463a93a15183c6a16bf03413a7af88ef1285ddedfa9cda5"
dependencies = [
"num-traits",
]
[[package]] [[package]]
name = "atoi" name = "atoi"
version = "1.0.0" version = "1.0.0"
@@ -994,13 +987,27 @@ checksum = "8d696c370c750c948ada61c69a0ee2cbbb9c50b1019ddb86d9317157a99c2cae"
[[package]] [[package]]
name = "bls12_381" name = "bls12_381"
version = "0.8.0" version = "0.5.0"
source = "git+https://github.com/jstuczyn/bls12_381?branch=feature/gt-serialization-0.8.0#c4543fde7d02efea6ecfcf22e14476ddb516b483" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "54757888b09a69be70b5ec303e382a74227392086ba808cb01eeca29233a2397"
dependencies = [ dependencies = [
"digest 0.9.0", "digest 0.9.0",
"ff 0.13.0", "ff 0.10.1",
"group 0.13.0", "group 0.10.0",
"pairing", "pairing 0.20.0",
"rand_core 0.6.4",
"subtle 2.4.1",
]
[[package]]
name = "bls12_381"
version = "0.6.0"
source = "git+https://github.com/jstuczyn/bls12_381?branch=gt-serialisation#10fb6f700bfda17c8475af3bfd31e3fec15f2278"
dependencies = [
"digest 0.9.0",
"ff 0.11.1",
"group 0.11.0",
"pairing 0.21.0",
"rand_core 0.6.4", "rand_core 0.6.4",
"subtle 2.4.1", "subtle 2.4.1",
"zeroize", "zeroize",
@@ -1559,26 +1566,6 @@ version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "28c122c3980598d243d63d9a704629a2d748d101f278052ff068be5a4423ab6f" checksum = "28c122c3980598d243d63d9a704629a2d748d101f278052ff068be5a4423ab6f"
[[package]]
name = "const_format"
version = "0.2.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3a214c7af3d04997541b18d432afaff4c455e79e2029079647e72fc2bd27673"
dependencies = [
"const_format_proc_macros",
]
[[package]]
name = "const_format_proc_macros"
version = "0.2.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c7f6ff08fd20f4f299298a28e2dfa8a8ba1036e6cd2460ac1de7b425d76f2500"
dependencies = [
"proc-macro2",
"quote",
"unicode-xid",
]
[[package]] [[package]]
name = "constant_time_eq" name = "constant_time_eq"
version = "0.3.0" version = "0.3.0"
@@ -1649,16 +1636,6 @@ dependencies = [
"tendermint-proto", "tendermint-proto",
] ]
[[package]]
name = "cosmos-sdk-proto"
version = "0.20.0"
source = "git+https://github.com/jstuczyn/cosmos-rust?branch=nym-temp/all-validator-features#41ed4631e146268b0300033c8bbb993d79a49f58"
dependencies = [
"prost 0.12.1",
"prost-types 0.12.1",
"tendermint-proto",
]
[[package]] [[package]]
name = "cosmrs" name = "cosmrs"
version = "0.15.0" version = "0.15.0"
@@ -1666,26 +1643,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47126f5364df9387b9d8559dcef62e99010e1d4098f39eb3f7ee4b5c254e40ea" checksum = "47126f5364df9387b9d8559dcef62e99010e1d4098f39eb3f7ee4b5c254e40ea"
dependencies = [ dependencies = [
"bip32", "bip32",
"cosmos-sdk-proto 0.20.0 (registry+https://github.com/rust-lang/crates.io-index)", "cosmos-sdk-proto",
"ecdsa 0.16.8",
"eyre",
"k256",
"rand_core 0.6.4",
"serde",
"serde_json",
"signature 2.1.0",
"subtle-encoding",
"tendermint",
"thiserror",
]
[[package]]
name = "cosmrs"
version = "0.15.0"
source = "git+https://github.com/jstuczyn/cosmos-rust?branch=nym-temp/all-validator-features#41ed4631e146268b0300033c8bbb993d79a49f58"
dependencies = [
"bip32",
"cosmos-sdk-proto 0.20.0 (git+https://github.com/jstuczyn/cosmos-rust?branch=nym-temp/all-validator-features)",
"ecdsa 0.16.8", "ecdsa 0.16.8",
"eyre", "eyre",
"k256", "k256",
@@ -1803,15 +1761,30 @@ dependencies = [
"toml 0.5.11", "toml 0.5.11",
] ]
[[package]]
name = "crc"
version = "2.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "49fc9a695bca7f35f5f4c15cddc84415f66a74ea78eef08e90c5024f2b540e23"
dependencies = [
"crc-catalog 1.1.1",
]
[[package]] [[package]]
name = "crc" name = "crc"
version = "3.0.1" version = "3.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "86ec7a15cbe22e59248fc7eadb1907dab5ba09372595da4d73dd805ed4417dfe" checksum = "86ec7a15cbe22e59248fc7eadb1907dab5ba09372595da4d73dd805ed4417dfe"
dependencies = [ dependencies = [
"crc-catalog", "crc-catalog 2.2.0",
] ]
[[package]]
name = "crc-catalog"
version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ccaeedb56da03b09f598226e25e80088cb4cd25f316e6e4df7d695f0feeb1403"
[[package]] [[package]]
name = "crc-catalog" name = "crc-catalog"
version = "2.2.0" version = "2.2.0"
@@ -2241,16 +2214,6 @@ dependencies = [
"darling_macro 0.14.4", "darling_macro 0.14.4",
] ]
[[package]]
name = "darling"
version = "0.20.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0209d94da627ab5605dcccf08bb18afa5009cfbef48d8a8b7d7bdbc79be25c5e"
dependencies = [
"darling_core 0.20.3",
"darling_macro 0.20.3",
]
[[package]] [[package]]
name = "darling_core" name = "darling_core"
version = "0.13.4" version = "0.13.4"
@@ -2279,20 +2242,6 @@ dependencies = [
"syn 1.0.109", "syn 1.0.109",
] ]
[[package]]
name = "darling_core"
version = "0.20.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "177e3443818124b357d8e76f53be906d60937f0d3a90773a664fa63fa253e621"
dependencies = [
"fnv",
"ident_case",
"proc-macro2",
"quote",
"strsim",
"syn 2.0.38",
]
[[package]] [[package]]
name = "darling_macro" name = "darling_macro"
version = "0.13.4" version = "0.13.4"
@@ -2315,17 +2264,6 @@ dependencies = [
"syn 1.0.109", "syn 1.0.109",
] ]
[[package]]
name = "darling_macro"
version = "0.20.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "836a9bbc7ad63342d6d6e7b815ccab164bc77a2d95d84bc3117a8c0d5c98e2d5"
dependencies = [
"darling_core 0.20.3",
"quote",
"syn 2.0.38",
]
[[package]] [[package]]
name = "dashmap" name = "dashmap"
version = "5.5.3" version = "5.5.3"
@@ -2640,6 +2578,12 @@ version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fea41bba32d969b513997752735605054bc0dfa92b4c56bf1189f2e174be7a10" checksum = "fea41bba32d969b513997752735605054bc0dfa92b4c56bf1189f2e174be7a10"
[[package]]
name = "dotenv"
version = "0.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77c90badedccf4105eca100756a0b1289e191f6fcbdadd3cee1d2f614f97da8f"
[[package]] [[package]]
name = "dotenvy" name = "dotenvy"
version = "0.15.7" version = "0.15.7"
@@ -2835,6 +2779,26 @@ dependencies = [
"syn 1.0.109", "syn 1.0.109",
] ]
[[package]]
name = "enum-iterator"
version = "1.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "45a0ac4aeb3a18f92eaf09c6bb9b3ac30ff61ca95514fc58cbead1c9a6bf5401"
dependencies = [
"enum-iterator-derive",
]
[[package]]
name = "enum-iterator-derive"
version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eecf8589574ce9b895052fa12d69af7a233f99e6107f5cb8dd1044f2a17bfdcb"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.38",
]
[[package]] [[package]]
name = "env_logger" name = "env_logger"
version = "0.7.1" version = "0.7.1"
@@ -3031,9 +2995,9 @@ dependencies = [
[[package]] [[package]]
name = "eyre" name = "eyre"
version = "0.6.11" version = "0.6.8"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6267a1fa6f59179ea4afc8e50fd8612a3cc60bc858f786ff877a4a8cb042799" checksum = "4c2b6b5a29c02cdc822728b7d7b8ae1bab3e3b05d44522770ddd49722eeac7eb"
dependencies = [ dependencies = [
"indenter", "indenter",
"once_cell", "once_cell",
@@ -3066,6 +3030,26 @@ version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "25cbce373ec4653f1a01a31e8a5e5ec0c622dc27ff9c4e6606eefef5cbbed4a5" checksum = "25cbce373ec4653f1a01a31e8a5e5ec0c622dc27ff9c4e6606eefef5cbbed4a5"
[[package]]
name = "ff"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d0f40b2dcd8bc322217a5f6559ae5f9e9d1de202a2ecee2e9eafcbece7562a4f"
dependencies = [
"rand_core 0.6.4",
"subtle 2.4.1",
]
[[package]]
name = "ff"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "131655483be284720a17d74ff97592b8e76576dc25563148601df2d7c9080924"
dependencies = [
"rand_core 0.6.4",
"subtle 2.4.1",
]
[[package]] [[package]]
name = "ff" name = "ff"
version = "0.12.1" version = "0.12.1"
@@ -3082,7 +3066,6 @@ version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ded41244b729663b1e574f1b4fb731469f69f79c17667b5d776b16cda0479449" checksum = "ded41244b729663b1e574f1b4fb731469f69f79c17667b5d776b16cda0479449"
dependencies = [ dependencies = [
"bitvec",
"rand_core 0.6.4", "rand_core 0.6.4",
"subtle 2.4.1", "subtle 2.4.1",
] ]
@@ -3536,6 +3519,30 @@ dependencies = [
"web-sys", "web-sys",
] ]
[[package]]
name = "group"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c363a5301b8f153d80747126a04b3c82073b9fe3130571a9d170cacdeaf7912"
dependencies = [
"byteorder",
"ff 0.10.1",
"rand_core 0.6.4",
"subtle 2.4.1",
]
[[package]]
name = "group"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bc5ac374b108929de78460075f3dc439fa66df9d8fc77e8f12caa5165fcf0c89"
dependencies = [
"byteorder",
"ff 0.11.1",
"rand_core 0.6.4",
"subtle 2.4.1",
]
[[package]] [[package]]
name = "group" name = "group"
version = "0.12.1" version = "0.12.1"
@@ -4279,15 +4286,6 @@ dependencies = [
"either", "either",
] ]
[[package]]
name = "itertools"
version = "0.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "25db6b064527c5d482d0423354fcd07a89a2dfe07b67892e62411946db7f07b0"
dependencies = [
"either",
]
[[package]] [[package]]
name = "itoa" name = "itoa"
version = "1.0.9" version = "1.0.9"
@@ -5914,15 +5912,6 @@ dependencies = [
"libc", "libc",
] ]
[[package]]
name = "num_threads"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2819ce041d2ee131036f4fc9d6ae7ae125a3a40e97ba64d04fe799ad9dabbb44"
dependencies = [
"libc",
]
[[package]] [[package]]
name = "nym-api" name = "nym-api"
version = "1.1.34" version = "1.1.34"
@@ -5948,7 +5937,6 @@ dependencies = [
"futures-util", "futures-util",
"getset", "getset",
"humantime-serde", "humantime-serde",
"itertools 0.12.0",
"lazy_static", "lazy_static",
"log", "log",
"nym-api-requests", "nym-api-requests",
@@ -5991,7 +5979,7 @@ dependencies = [
"serde", "serde",
"serde_derive", "serde_derive",
"serde_json", "serde_json",
"sqlx", "sqlx 0.6.3",
"tap", "tap",
"tempfile", "tempfile",
"thiserror", "thiserror",
@@ -6009,16 +5997,14 @@ name = "nym-api-requests"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"bs58 0.4.0", "bs58 0.4.0",
"cosmrs 0.15.0 (git+https://github.com/jstuczyn/cosmos-rust?branch=nym-temp/all-validator-features)", "cosmrs",
"cosmwasm-std", "cosmwasm-std",
"getset", "getset",
"nym-coconut-interface", "nym-coconut-interface",
"nym-crypto",
"nym-mixnet-contract-common", "nym-mixnet-contract-common",
"nym-node-requests", "nym-node-requests",
"schemars", "schemars",
"serde", "serde",
"tendermint",
"ts-rs", "ts-rs",
] ]
@@ -6036,7 +6022,6 @@ dependencies = [
"rand 0.7.3", "rand 0.7.3",
"thiserror", "thiserror",
"url", "url",
"zeroize",
] ]
[[package]] [[package]]
@@ -6067,7 +6052,7 @@ name = "nym-bity-integration"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"cosmrs 0.15.0 (git+https://github.com/jstuczyn/cosmos-rust?branch=nym-temp/all-validator-features)", "cosmrs",
"eyre", "eyre",
"k256", "k256",
"nym-cli-commands", "nym-cli-commands",
@@ -6112,7 +6097,7 @@ dependencies = [
"cfg-if", "cfg-if",
"clap 4.4.7", "clap 4.4.7",
"comfy-table", "comfy-table",
"cosmrs 0.15.0 (git+https://github.com/jstuczyn/cosmos-rust?branch=nym-temp/all-validator-features)", "cosmrs",
"cosmwasm-std", "cosmwasm-std",
"cw-utils", "cw-utils",
"handlebars", "handlebars",
@@ -6219,7 +6204,7 @@ dependencies = [
"serde", "serde",
"serde_json", "serde_json",
"sha2 0.10.8", "sha2 0.10.8",
"sqlx", "sqlx 0.6.3",
"tap", "tap",
"tempfile", "tempfile",
"thiserror", "thiserror",
@@ -6272,14 +6257,14 @@ dependencies = [
name = "nym-coconut" name = "nym-coconut"
version = "0.5.0" version = "0.5.0"
dependencies = [ dependencies = [
"bls12_381", "bls12_381 0.6.0",
"bs58 0.4.0", "bs58 0.4.0",
"criterion", "criterion",
"digest 0.9.0", "digest 0.9.0",
"doc-comment", "doc-comment",
"ff 0.13.0", "ff 0.11.1",
"getrandom 0.2.10", "getrandom 0.2.10",
"group 0.13.0", "group 0.11.0",
"itertools 0.10.5", "itertools 0.10.5",
"nym-dkg", "nym-dkg",
"nym-pemstore", "nym-pemstore",
@@ -6289,7 +6274,6 @@ dependencies = [
"serde_derive", "serde_derive",
"sha2 0.9.9", "sha2 0.9.9",
"thiserror", "thiserror",
"zeroize",
] ]
[[package]] [[package]]
@@ -6356,7 +6340,7 @@ version = "0.1.0"
dependencies = [ dependencies = [
"async-trait", "async-trait",
"log", "log",
"sqlx", "sqlx 0.5.13",
"thiserror", "thiserror",
"tokio", "tokio",
] ]
@@ -6380,8 +6364,8 @@ dependencies = [
name = "nym-credentials" name = "nym-credentials"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"bls12_381", "bls12_381 0.5.0",
"cosmrs 0.15.0 (git+https://github.com/jstuczyn/cosmos-rust?branch=nym-temp/all-validator-features)", "cosmrs",
"log", "log",
"nym-api-requests", "nym-api-requests",
"nym-coconut-interface", "nym-coconut-interface",
@@ -6389,7 +6373,6 @@ dependencies = [
"nym-validator-client", "nym-validator-client",
"rand 0.7.3", "rand 0.7.3",
"thiserror", "thiserror",
"zeroize",
] ]
[[package]] [[package]]
@@ -6423,11 +6406,11 @@ name = "nym-dkg"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"bitvec", "bitvec",
"bls12_381", "bls12_381 0.6.0",
"bs58 0.4.0", "bs58 0.4.0",
"criterion", "criterion",
"ff 0.13.0", "ff 0.11.1",
"group 0.13.0", "group 0.11.0",
"lazy_static", "lazy_static",
"nym-contracts-common", "nym-contracts-common",
"nym-pemstore", "nym-pemstore",
@@ -6543,7 +6526,7 @@ dependencies = [
"rand 0.8.5", "rand 0.8.5",
"serde", "serde",
"serde_json", "serde_json",
"sqlx", "sqlx 0.5.13",
"subtle-encoding", "subtle-encoding",
"thiserror", "thiserror",
"tokio", "tokio",
@@ -6740,6 +6723,7 @@ dependencies = [
"nym-types", "nym-types",
"nym-validator-client", "nym-validator-client",
"opentelemetry", "opentelemetry",
"pretty_env_logger",
"rand 0.7.3", "rand 0.7.3",
"serde", "serde",
"serde_json", "serde_json",
@@ -6864,7 +6848,7 @@ dependencies = [
"reqwest", "reqwest",
"serde", "serde",
"serde_json", "serde_json",
"sqlx", "sqlx 0.6.3",
"tap", "tap",
"tempfile", "tempfile",
"thiserror", "thiserror",
@@ -6885,7 +6869,7 @@ dependencies = [
"pretty_env_logger", "pretty_env_logger",
"rocket", "rocket",
"serde", "serde",
"sqlx", "sqlx 0.5.13",
"thiserror", "thiserror",
"tokio", "tokio",
] ]
@@ -7393,7 +7377,7 @@ dependencies = [
"reqwest", "reqwest",
"serde", "serde",
"serde_json", "serde_json",
"sqlx", "sqlx 0.5.13",
"thiserror", "thiserror",
"tokio", "tokio",
] ]
@@ -7468,7 +7452,7 @@ name = "nym-types"
version = "1.0.0" version = "1.0.0"
dependencies = [ dependencies = [
"base64 0.21.4", "base64 0.21.4",
"cosmrs 0.15.0 (git+https://github.com/jstuczyn/cosmos-rust?branch=nym-temp/all-validator-features)", "cosmrs",
"cosmwasm-std", "cosmwasm-std",
"eyre", "eyre",
"hmac 0.12.1", "hmac 0.12.1",
@@ -7502,7 +7486,7 @@ dependencies = [
"bip32", "bip32",
"bip39", "bip39",
"colored", "colored",
"cosmrs 0.15.0 (git+https://github.com/jstuczyn/cosmos-rust?branch=nym-temp/all-validator-features)", "cosmrs",
"cosmwasm-std", "cosmwasm-std",
"cw-controllers", "cw-controllers",
"cw-utils", "cw-utils",
@@ -7544,40 +7528,6 @@ dependencies = [
"zeroize", "zeroize",
] ]
[[package]]
name = "nym-validator-rewarder"
version = "0.1.0"
dependencies = [
"anyhow",
"bip39",
"clap 4.4.7",
"cosmwasm-std",
"futures",
"humantime 2.1.0",
"humantime-serde",
"nym-bin-common",
"nym-coconut",
"nym-coconut-bandwidth-contract-common",
"nym-coconut-dkg-common",
"nym-config",
"nym-credentials",
"nym-crypto",
"nym-network-defaults",
"nym-task",
"nym-validator-client",
"nyxd-scraper",
"serde",
"serde_with",
"sha2 0.10.8",
"sqlx",
"thiserror",
"time",
"tokio",
"tracing",
"url",
"zeroize",
]
[[package]] [[package]]
name = "nym-vesting-contract-common" name = "nym-vesting-contract-common"
version = "0.7.0" version = "0.7.0"
@@ -7596,7 +7546,7 @@ dependencies = [
name = "nym-wallet-types" name = "nym-wallet-types"
version = "1.0.0" version = "1.0.0"
dependencies = [ dependencies = [
"cosmrs 0.15.0 (registry+https://github.com/rust-lang/crates.io-index)", "cosmrs",
"cosmwasm-std", "cosmwasm-std",
"hex-literal", "hex-literal",
"nym-config", "nym-config",
@@ -7674,28 +7624,6 @@ dependencies = [
"url", "url",
] ]
[[package]]
name = "nyxd-scraper"
version = "0.1.0"
dependencies = [
"async-trait",
"const_format",
"cosmrs 0.15.0 (git+https://github.com/jstuczyn/cosmos-rust?branch=nym-temp/all-validator-features)",
"eyre",
"futures",
"nym-bin-common",
"sha2 0.10.8",
"sqlx",
"tendermint",
"tendermint-rpc",
"thiserror",
"tokio",
"tokio-stream",
"tokio-util",
"tracing",
"url",
]
[[package]] [[package]]
name = "object" name = "object"
version = "0.32.1" version = "0.32.1"
@@ -7761,9 +7689,9 @@ checksum = "624a8340c38c1b80fd549087862da4ba43e08858af025b236e509b6649fc13d5"
[[package]] [[package]]
name = "openssl" name = "openssl"
version = "0.10.62" version = "0.10.57"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8cde4d2d9200ad5909f8dac647e29482e07c3a35de8a13fce7c9c7747ad9f671" checksum = "bac25ee399abb46215765b1cb35bc0212377e58a061560d8b29b024fd0430e7c"
dependencies = [ dependencies = [
"bitflags 2.4.1", "bitflags 2.4.1",
"cfg-if", "cfg-if",
@@ -7802,9 +7730,9 @@ dependencies = [
[[package]] [[package]]
name = "openssl-sys" name = "openssl-sys"
version = "0.9.98" version = "0.9.93"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c1665caf8ab2dc9aef43d1c0023bd904633a6a05cb30b0ad59bec2ae986e57a7" checksum = "db4d56a4c0478783083cfafcc42493dd4a981d41669da64b4572a2a089b51b1d"
dependencies = [ dependencies = [
"cc", "cc",
"libc", "libc",
@@ -7954,11 +7882,20 @@ dependencies = [
[[package]] [[package]]
name = "pairing" name = "pairing"
version = "0.23.0" version = "0.20.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "81fec4625e73cf41ef4bb6846cafa6d44736525f442ba45e407c4a000a13996f" checksum = "7de9d09263c9966e8196fe0380c9dbbc7ea114b5cf371ba29004bc1f9c6db7f3"
dependencies = [ dependencies = [
"group 0.13.0", "group 0.10.0",
]
[[package]]
name = "pairing"
version = "0.21.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2e415e349a3006dd7d9482cdab1c980a845bed1377777d768cb693a44540b42"
dependencies = [
"group 0.11.0",
] ]
[[package]] [[package]]
@@ -9853,9 +9790,9 @@ dependencies = [
[[package]] [[package]]
name = "serde_json" name = "serde_json"
version = "1.0.108" version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d1c7e3eac408d115102c4c24ad393e0821bb3a5df4d506a80f85f7a742a526b" checksum = "6b420ce6e3d8bd882e9b243c6eed35dbc9a6110c9769e74b584e0d68d1f20c65"
dependencies = [ dependencies = [
"itoa", "itoa",
"ryu", "ryu",
@@ -9904,35 +9841,6 @@ dependencies = [
"serde", "serde",
] ]
[[package]]
name = "serde_with"
version = "3.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "64cd236ccc1b7a29e7e2739f27c0b2dd199804abc4290e32f59f3b68d6405c23"
dependencies = [
"base64 0.21.4",
"chrono",
"hex",
"indexmap 1.9.3",
"indexmap 2.0.2",
"serde",
"serde_json",
"serde_with_macros",
"time",
]
[[package]]
name = "serde_with_macros"
version = "3.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "93634eb5f75a2323b16de4748022ac4297f9e76b6dced2be287a099f41b5e788"
dependencies = [
"darling 0.20.3",
"proc-macro2",
"quote",
"syn 2.0.38",
]
[[package]] [[package]]
name = "serde_yaml" name = "serde_yaml"
version = "0.9.25" version = "0.9.25"
@@ -10251,6 +10159,17 @@ dependencies = [
"der 0.7.8", "der 0.7.8",
] ]
[[package]]
name = "sqlformat"
version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4b7922be017ee70900be125523f38bdd644f4f06a1b16e8fa5a8ee8c34bffd4"
dependencies = [
"itertools 0.10.5",
"nom",
"unicode_categories",
]
[[package]] [[package]]
name = "sqlformat" name = "sqlformat"
version = "0.2.2" version = "0.2.2"
@@ -10262,14 +10181,70 @@ dependencies = [
"unicode_categories", "unicode_categories",
] ]
[[package]]
name = "sqlx"
version = "0.5.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "551873805652ba0d912fec5bbb0f8b4cdd96baf8e2ebf5970e5671092966019b"
dependencies = [
"sqlx-core 0.5.13",
"sqlx-macros 0.5.13",
]
[[package]] [[package]]
name = "sqlx" name = "sqlx"
version = "0.6.3" version = "0.6.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8de3b03a925878ed54a954f621e64bf55a3c1bd29652d0d1a17830405350188" checksum = "f8de3b03a925878ed54a954f621e64bf55a3c1bd29652d0d1a17830405350188"
dependencies = [ dependencies = [
"sqlx-core", "sqlx-core 0.6.3",
"sqlx-macros", "sqlx-macros 0.6.3",
]
[[package]]
name = "sqlx-core"
version = "0.5.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e48c61941ccf5ddcada342cd59e3e5173b007c509e1e8e990dafc830294d9dc5"
dependencies = [
"ahash 0.7.6",
"atoi 0.4.0",
"bitflags 1.3.2",
"byteorder",
"bytes",
"chrono",
"crc 2.1.0",
"crossbeam-queue",
"either",
"event-listener",
"flume",
"futures-channel",
"futures-core",
"futures-executor",
"futures-intrusive",
"futures-util",
"hashlink 0.7.0",
"hex",
"indexmap 1.9.3",
"itoa",
"libc",
"libsqlite3-sys",
"log",
"memchr",
"once_cell",
"paste",
"percent-encoding",
"rustls 0.19.1",
"sha2 0.10.8",
"smallvec",
"sqlformat 0.1.8",
"sqlx-rt 0.5.13",
"stringprep",
"thiserror",
"tokio-stream",
"url",
"webpki 0.21.4",
"webpki-roots 0.21.1",
] ]
[[package]] [[package]]
@@ -10279,12 +10254,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fa8241483a83a3f33aa5fff7e7d9def398ff9990b2752b6c6112b83c6d246029" checksum = "fa8241483a83a3f33aa5fff7e7d9def398ff9990b2752b6c6112b83c6d246029"
dependencies = [ dependencies = [
"ahash 0.7.6", "ahash 0.7.6",
"atoi", "atoi 1.0.0",
"bitflags 1.3.2", "bitflags 1.3.2",
"byteorder", "byteorder",
"bytes", "bytes",
"chrono", "chrono",
"crc", "crc 3.0.1",
"crossbeam-queue", "crossbeam-queue",
"dotenvy", "dotenvy",
"either", "either",
@@ -10310,16 +10285,34 @@ dependencies = [
"rustls-pemfile", "rustls-pemfile",
"sha2 0.10.8", "sha2 0.10.8",
"smallvec", "smallvec",
"sqlformat", "sqlformat 0.2.2",
"sqlx-rt", "sqlx-rt 0.6.3",
"stringprep", "stringprep",
"thiserror", "thiserror",
"time",
"tokio-stream", "tokio-stream",
"url", "url",
"webpki-roots 0.22.6", "webpki-roots 0.22.6",
] ]
[[package]]
name = "sqlx-macros"
version = "0.5.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bc0fba2b0cae21fc00fe6046f8baa4c7fcb49e379f0f592b04696607f69ed2e1"
dependencies = [
"dotenv",
"either",
"heck 0.4.1",
"once_cell",
"proc-macro2",
"quote",
"sha2 0.10.8",
"sqlx-core 0.5.13",
"sqlx-rt 0.5.13",
"syn 1.0.109",
"url",
]
[[package]] [[package]]
name = "sqlx-macros" name = "sqlx-macros"
version = "0.6.3" version = "0.6.3"
@@ -10333,12 +10326,23 @@ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"sha2 0.10.8", "sha2 0.10.8",
"sqlx-core", "sqlx-core 0.6.3",
"sqlx-rt", "sqlx-rt 0.6.3",
"syn 1.0.109", "syn 1.0.109",
"url", "url",
] ]
[[package]]
name = "sqlx-rt"
version = "0.5.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4db708cd3e459078f85f39f96a00960bd841f66ee2a669e90bf36907f5a79aae"
dependencies = [
"once_cell",
"tokio",
"tokio-rustls 0.22.0",
]
[[package]] [[package]]
name = "sqlx-rt" name = "sqlx-rt"
version = "0.6.3" version = "0.6.3"
@@ -10471,7 +10475,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7e94b1ec00bad60e6410e058b52f1c66de3dc5fe4d62d09b3e52bb7d3b73e25" checksum = "a7e94b1ec00bad60e6410e058b52f1c66de3dc5fe4d62d09b3e52bb7d3b73e25"
dependencies = [ dependencies = [
"base64 0.13.1", "base64 0.13.1",
"crc", "crc 3.0.1",
"lazy_static", "lazy_static",
"md-5", "md-5",
"rand 0.8.5", "rand 0.8.5",
@@ -10705,7 +10709,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dfbf0a4753b46a190f367337e0163d0b552a2674a6bac54e74f9f2cdcde2969b" checksum = "dfbf0a4753b46a190f367337e0163d0b552a2674a6bac54e74f9f2cdcde2969b"
dependencies = [ dependencies = [
"async-trait", "async-trait",
"async-tungstenite",
"bytes", "bytes",
"flex-error", "flex-error",
"futures", "futures",
@@ -10817,8 +10820,6 @@ dependencies = [
"deranged", "deranged",
"itoa", "itoa",
"js-sys", "js-sys",
"libc",
"num_threads",
"powerfmt", "powerfmt",
"serde", "serde",
"time-core", "time-core",
@@ -10916,6 +10917,17 @@ dependencies = [
"tokio", "tokio",
] ]
[[package]]
name = "tokio-rustls"
version = "0.22.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bc6844de72e57df1980054b38be3a9f4702aba4858be64dd700181a8a6d0e1b6"
dependencies = [
"rustls 0.19.1",
"tokio",
"webpki 0.21.4",
]
[[package]] [[package]]
name = "tokio-rustls" name = "tokio-rustls"
version = "0.23.4" version = "0.23.4"
@@ -11002,16 +11014,16 @@ dependencies = [
[[package]] [[package]]
name = "tokio-util" name = "tokio-util"
version = "0.7.10" version = "0.7.9"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5419f34732d9eb6ee4c3578b7989078579b7f039cbbb9ca2c4da015749371e15" checksum = "1d68074620f57a0b21594d9735eb2e98ab38b17f80d3fcb189fca266771ca60d"
dependencies = [ dependencies = [
"bytes", "bytes",
"futures-core", "futures-core",
"futures-io", "futures-io",
"futures-sink", "futures-sink",
"futures-util", "futures-util",
"hashbrown 0.14.1", "hashbrown 0.12.3",
"pin-project-lite 0.2.13", "pin-project-lite 0.2.13",
"slab", "slab",
"tokio", "tokio",
@@ -11451,7 +11463,6 @@ dependencies = [
"log", "log",
"native-tls", "native-tls",
"rand 0.8.5", "rand 0.8.5",
"rustls 0.21.7",
"sha1", "sha1",
"thiserror", "thiserror",
"url", "url",
@@ -11769,13 +11780,18 @@ checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
[[package]] [[package]]
name = "vergen" name = "vergen"
version = "8.2.6" version = "7.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1290fd64cc4e7d3c9b07d7f333ce0ce0007253e32870e632624835cc80b83939" checksum = "447f9238a4553957277b3ee09d80babeae0811f1b3baefb093de1c0448437a37"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"cfg-if",
"enum-iterator",
"getset",
"git2",
"rustc_version 0.4.0", "rustc_version 0.4.0",
"rustversion", "rustversion",
"thiserror",
"time", "time",
] ]
@@ -12061,6 +12077,15 @@ dependencies = [
"untrusted 0.9.0", "untrusted 0.9.0",
] ]
[[package]]
name = "webpki-roots"
version = "0.21.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aabe153544e473b775453675851ecc86863d2a81d786d741f6b76778f2a48940"
dependencies = [
"webpki 0.21.4",
]
[[package]] [[package]]
name = "webpki-roots" name = "webpki-roots"
version = "0.22.6" version = "0.22.6"
@@ -12180,7 +12205,7 @@ checksum = "465a03cc11e9a7d7b4f9f99870558fe37a102b65b93f8045392fef7c67b39e80"
dependencies = [ dependencies = [
"arc-swap", "arc-swap",
"async-trait", "async-trait",
"crc", "crc 3.0.1",
"log", "log",
"rand 0.8.5", "rand 0.8.5",
"serde", "serde",
@@ -12231,7 +12256,7 @@ dependencies = [
"arc-swap", "arc-swap",
"async-trait", "async-trait",
"bytes", "bytes",
"crc", "crc 3.0.1",
"log", "log",
"rand 0.8.5", "rand 0.8.5",
"thiserror", "thiserror",
+2 -19
View File
@@ -67,7 +67,6 @@ members = [
"common/nymsphinx/params", "common/nymsphinx/params",
"common/nymsphinx/routing", "common/nymsphinx/routing",
"common/nymsphinx/types", "common/nymsphinx/types",
"common/nyxd-scraper",
"common/pemstore", "common/pemstore",
"common/socks5-client-core", "common/socks5-client-core",
"common/socks5/proxy-helpers", "common/socks5/proxy-helpers",
@@ -102,7 +101,6 @@ members = [
"nym-node", "nym-node",
"nym-node/nym-node-requests", "nym-node/nym-node-requests",
"nym-outfox", "nym-outfox",
"nym-validator-rewarder",
"tools/internal/ssl-inject", "tools/internal/ssl-inject",
"tools/internal/sdk-version-bump", "tools/internal/sdk-version-bump",
"tools/nym-cli", "tools/nym-cli",
@@ -125,7 +123,6 @@ default-members = [
"nym-api", "nym-api",
"tools/nymvisor", "tools/nymvisor",
"explorer-api", "explorer-api",
"nym-validator-rewarder",
] ]
exclude = ["explorer", "contracts", "nym-wallet", "nym-connect/mobile/src-tauri", "nym-connect/desktop", "nym-vpn/ui/src-tauri", "cpu-cycles"] exclude = ["explorer", "contracts", "nym-wallet", "nym-connect/mobile/src-tauri", "nym-connect/desktop", "nym-vpn/ui/src-tauri", "cpu-cycles"]
@@ -162,12 +159,10 @@ reqwest = "0.11.22"
schemars = "0.8.1" schemars = "0.8.1"
serde = "1.0.152" serde = "1.0.152"
serde_json = "1.0.91" serde_json = "1.0.91"
sqlx = "0.6.3"
tap = "1.0.1" tap = "1.0.1"
time = "0.3.30" time = "0.3.30"
thiserror = "1.0.48" thiserror = "1.0.48"
tokio = "1.33.0" tokio = "1.24.1"
tokio-util = "0.7.10"
tokio-tungstenite = "0.20.1" tokio-tungstenite = "0.20.1"
tracing = "0.1.37" tracing = "0.1.37"
tungstenite = { version = "0.20.1", default-features = false } tungstenite = { version = "0.20.1", default-features = false }
@@ -177,14 +172,6 @@ utoipa-swagger-ui = "3.1.5"
url = "2.4" url = "2.4"
zeroize = "1.6.0" zeroize = "1.6.0"
# coconut/DKG related
# unfortunately until https://github.com/zkcrypto/bls12_381/issues/10 is resolved, we have to rely on the fork
# as we need to be able to serialize Gt so that we could create the lookup table for baby-step-giant-step algorithm
bls12_381 = { git = "https://github.com/jstuczyn/bls12_381", branch ="feature/gt-serialization-0.8.0" }
group = "0.13.0"
ff = "0.13.0"
# cosmwasm-related # cosmwasm-related
cosmwasm-derive = "=1.3.0" cosmwasm-derive = "=1.3.0"
cosmwasm-schema = "=1.3.0" cosmwasm-schema = "=1.3.0"
@@ -203,11 +190,7 @@ cw-controllers = { version = "=1.1.0" }
# cosmrs-related # cosmrs-related
bip32 = "0.5.1" bip32 = "0.5.1"
cosmrs = "=0.15.0"
# temporarily using a fork again (yay.) because we need staking and slashing support
cosmrs = { git = "https://github.com/jstuczyn/cosmos-rust", branch ="nym-temp/all-validator-features" }
#cosmrs = { git = "https://github.com/jstuczyn/cosmos-rust", branch = "nym-temp/all-validator-features" } # unfortuntely we need a fork by yours truly to get the staking support
tendermint = "0.34" # same version as used by cosmrs
tendermint-rpc = "0.34" # same version as used by cosmrs tendermint-rpc = "0.34" # same version as used by cosmrs
prost = "0.12" prost = "0.12"
-70
View File
@@ -1,70 +0,0 @@
<html>
<head>
<style>
@media (prefers-color-scheme: dark) {
body {
background: #333;
color: white;
}
a {
color: skyblue;
}
}
.container {
font-family: sans-serif;
max-width: 800px;
margin: 0 auto;
}
.intro {
text-align: center;
}
.licenses-list {
list-style-type: none;
margin: 0;
padding: 0;
}
.license-used-by {
margin-top: -10px;
}
.license-text {
max-height: 200px;
overflow-y: scroll;
white-space: pre-wrap;
}
</style>
</head>
<body>
<main class="container">
<div class="intro">
<h1>Third Party Licenses</h1>
<p>This page lists the licenses of the projects used in cargo-about.</p>
</div>
<h2>Overview of licenses:</h2>
<ul class="licenses-overview">
{{#each overview}}
<li><a href="#{{id}}">{{name}}</a> ({{count}})</li>
{{/each}}
</ul>
<h2>All license text:</h2>
<ul class="licenses-list">
{{#each licenses}}
<li class="license">
<h3 id="{{id}}">{{name}}</h3>
<h4>Used by:</h4>
<ul class="license-used-by">
{{#each used_by}}
<li><a href="{{#if crate.repository}} {{crate.repository}} {{else}} https://crates.io/crates/{{crate.name}} {{/if}}">{{crate.name}} {{crate.version}}</a></li>
{{/each}}
</ul>
<pre class="license-text">{{text}}</pre>
</li>
{{/each}}
</ul>
</main>
</body>
</html>
-19
View File
@@ -1,19 +0,0 @@
private = { ignore = true }
accepted = [
"0BSD",
"Apache-2.0",
"BSD-2-Clause",
"BSD-3-Clause",
"CC0-1.0",
"ISC",
"MIT",
"MPL-2.0",
"Unicode-DFS-2016",
"OpenSSL",
]
workarounds = [
"ring",
"rustls",
]
-1
View File
@@ -5,7 +5,6 @@ authors = ["Dave Hrycyszyn <futurechimp@users.noreply.github.com>", "Jędrzej St
description = "Implementation of the Nym Client" description = "Implementation of the Nym Client"
edition = "2021" edition = "2021"
rust-version = "1.65" rust-version = "1.65"
license.workspace = true
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@@ -1667,9 +1667,9 @@
} }
}, },
"node_modules/follow-redirects": { "node_modules/follow-redirects": {
"version": "1.15.4", "version": "1.14.9",
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.4.tgz", "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.14.9.tgz",
"integrity": "sha512-Cr4D/5wlrb0z9dgERpUL3LrmPKVDsETIJhaCMeDfuFYcqa5bldGV6wBsAN6X/vxlXQtFBMrXdXxdL8CbDTGniw==", "integrity": "sha512-MQDfihBQYMcyy5dhRDJUHcw7lb2Pv/TuE6xP1vyraLukNDHKbDxDNaOE3NbCAdKQApno+GPRyo1YAp89yCjK4w==",
"dev": true, "dev": true,
"funding": [ "funding": [
{ {
@@ -5800,9 +5800,9 @@
} }
}, },
"follow-redirects": { "follow-redirects": {
"version": "1.15.4", "version": "1.14.9",
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.4.tgz", "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.14.9.tgz",
"integrity": "sha512-Cr4D/5wlrb0z9dgERpUL3LrmPKVDsETIJhaCMeDfuFYcqa5bldGV6wBsAN6X/vxlXQtFBMrXdXxdL8CbDTGniw==", "integrity": "sha512-MQDfihBQYMcyy5dhRDJUHcw7lb2Pv/TuE6xP1vyraLukNDHKbDxDNaOE3NbCAdKQApno+GPRyo1YAp89yCjK4w==",
"dev": true "dev": true
}, },
"forwarded": { "forwarded": {
@@ -3,7 +3,6 @@ name = "nym-client-websocket-requests"
version = "0.1.0" version = "0.1.0"
authors = ["Jędrzej Stuczyński <andrew@nymtech.net>"] authors = ["Jędrzej Stuczyński <andrew@nymtech.net>"]
edition = "2021" edition = "2021"
license.workspace = true
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
-1
View File
@@ -5,7 +5,6 @@ authors = ["Dave Hrycyszyn <futurechimp@users.noreply.github.com>"]
description = "A SOCKS5 localhost proxy that converts incoming messages to Sphinx and sends them to a Nym address" description = "A SOCKS5 localhost proxy that converts incoming messages to Sphinx and sends them to a Nym address"
edition = "2021" edition = "2021"
rust-version = "1.56" rust-version = "1.56"
license.workspace = true
[dependencies] [dependencies]
clap = { workspace = true, features = ["cargo", "derive"] } clap = { workspace = true, features = ["cargo", "derive"] }
-4
View File
@@ -1,4 +0,0 @@
module.exports = {
ConfigHandler: require('./config/configHandler.ts'),
RestClient: require('./restClient/RestClient.ts')
};
-1
View File
@@ -2,7 +2,6 @@
name = "async-file-watcher" name = "async-file-watcher"
version = "0.1.0" version = "0.1.0"
edition = "2021" edition = "2021"
license.workspace = true
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
-2
View File
@@ -2,7 +2,6 @@
name = "nym-bandwidth-controller" name = "nym-bandwidth-controller"
version = "0.1.0" version = "0.1.0"
edition = "2021" edition = "2021"
license.workspace = true
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@@ -11,7 +10,6 @@ bip39 = { workspace = true }
rand = "0.7.3" rand = "0.7.3"
thiserror = { workspace = true } thiserror = { workspace = true }
url = { workspace = true } url = { workspace = true }
zeroize = { workspace = true }
nym-coconut-interface = { path = "../coconut-interface" } nym-coconut-interface = { path = "../coconut-interface" }
nym-credential-storage = { path = "../credential-storage" } nym-credential-storage = { path = "../credential-storage" }
+15 -12
View File
@@ -2,9 +2,9 @@
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
use crate::error::BandwidthControllerError; use crate::error::BandwidthControllerError;
use nym_coconut_interface::Base58; use nym_coconut_interface::{Base58, Parameters};
use nym_credential_storage::storage::Storage; use nym_credential_storage::storage::Storage;
use nym_credentials::coconut::bandwidth::BandwidthVoucher; use nym_credentials::coconut::bandwidth::{BandwidthVoucher, TOTAL_ATTRIBUTES};
use nym_credentials::coconut::utils::obtain_aggregate_signature; use nym_credentials::coconut::utils::obtain_aggregate_signature;
use nym_crypto::asymmetric::{encryption, identity}; use nym_crypto::asymmetric::{encryption, identity};
use nym_network_defaults::VOUCHER_INFO; use nym_network_defaults::VOUCHER_INFO;
@@ -12,8 +12,10 @@ use nym_validator_client::coconut::all_coconut_api_clients;
use nym_validator_client::nyxd::contract_traits::CoconutBandwidthSigningClient; use nym_validator_client::nyxd::contract_traits::CoconutBandwidthSigningClient;
use nym_validator_client::nyxd::contract_traits::DkgQueryClient; use nym_validator_client::nyxd::contract_traits::DkgQueryClient;
use nym_validator_client::nyxd::Coin; use nym_validator_client::nyxd::Coin;
use nym_validator_client::nyxd::Hash;
use rand::rngs::OsRng; use rand::rngs::OsRng;
use state::State; use state::{KeyPair, State};
use std::str::FromStr;
pub mod state; pub mod state;
@@ -22,29 +24,30 @@ where
C: CoconutBandwidthSigningClient + Sync, C: CoconutBandwidthSigningClient + Sync,
{ {
let mut rng = OsRng; let mut rng = OsRng;
let signing_key = identity::PrivateKey::new(&mut rng); let signing_keypair = KeyPair::from(identity::KeyPair::new(&mut rng));
let encryption_key = encryption::PrivateKey::new(&mut rng); let encryption_keypair = KeyPair::from(encryption::KeyPair::new(&mut rng));
let params = BandwidthVoucher::default_parameters(); let params = Parameters::new(TOTAL_ATTRIBUTES).unwrap();
let voucher_value = amount.amount.to_string(); let voucher_value = amount.amount.to_string();
let tx_hash = client let tx_hash = client
.deposit( .deposit(
amount, amount,
String::from(VOUCHER_INFO), String::from(VOUCHER_INFO),
signing_key.public_key().to_base58_string(), signing_keypair.public_key.clone(),
encryption_key.public_key().to_base58_string(), encryption_keypair.public_key.clone(),
None, None,
) )
.await? .await?
.transaction_hash; .transaction_hash
.to_string();
let voucher = BandwidthVoucher::new( let voucher = BandwidthVoucher::new(
&params, &params,
voucher_value, voucher_value,
VOUCHER_INFO.to_string(), VOUCHER_INFO.to_string(),
tx_hash, Hash::from_str(&tx_hash).map_err(|_| BandwidthControllerError::InvalidTxHash)?,
signing_key, identity::PrivateKey::from_base58_string(&signing_keypair.private_key)?,
encryption_key, encryption::PrivateKey::from_base58_string(&encryption_keypair.private_key)?,
); );
let state = State { voucher, params }; let state = State { voucher, params };
@@ -2,7 +2,32 @@
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
use nym_coconut_interface::Parameters; use nym_coconut_interface::Parameters;
use nym_credentials::coconut::bandwidth::BandwidthVoucher; use nym_credentials::coconut::bandwidth::{BandwidthVoucher, TOTAL_ATTRIBUTES};
use nym_crypto::asymmetric::{encryption, identity};
pub(crate) struct KeyPair {
pub public_key: String,
pub private_key: String,
}
impl From<identity::KeyPair> for KeyPair {
fn from(kp: identity::KeyPair) -> Self {
Self {
public_key: kp.public_key().to_base58_string(),
private_key: kp.private_key().to_base58_string(),
}
}
}
impl From<encryption::KeyPair> for KeyPair {
fn from(kp: encryption::KeyPair) -> Self {
Self {
public_key: kp.public_key().to_base58_string(),
private_key: kp.private_key().to_base58_string(),
}
}
}
pub struct State { pub struct State {
pub voucher: BandwidthVoucher, pub voucher: BandwidthVoucher,
@@ -13,7 +38,7 @@ impl State {
pub fn new(voucher: BandwidthVoucher) -> Self { pub fn new(voucher: BandwidthVoucher) -> Self {
State { State {
voucher, voucher,
params: BandwidthVoucher::default_parameters(), params: Parameters::new(TOTAL_ATTRIBUTES).unwrap(),
} }
} }
} }
+6 -9
View File
@@ -7,7 +7,6 @@ use nym_credential_storage::storage::Storage;
use nym_validator_client::coconut::all_coconut_api_clients; use nym_validator_client::coconut::all_coconut_api_clients;
use nym_validator_client::nyxd::contract_traits::DkgQueryClient; use nym_validator_client::nyxd::contract_traits::DkgQueryClient;
use std::str::FromStr; use std::str::FromStr;
use zeroize::Zeroizing;
use { use {
nym_coconut_interface::Base58, nym_coconut_interface::Base58,
nym_credentials::coconut::{ nym_credentials::coconut::{
@@ -47,12 +46,10 @@ impl<C, St: Storage> BandwidthController<C, St> {
let voucher_value = u64::from_str(&bandwidth_credential.voucher_value) let voucher_value = u64::from_str(&bandwidth_credential.voucher_value)
.map_err(|_| StorageError::InconsistentData)?; .map_err(|_| StorageError::InconsistentData)?;
let voucher_info = bandwidth_credential.voucher_info.clone(); let voucher_info = bandwidth_credential.voucher_info.clone();
let serial_number = Zeroizing::new(nym_coconut_interface::Attribute::try_from_bs58( let serial_number =
bandwidth_credential.serial_number, nym_coconut_interface::Attribute::try_from_bs58(bandwidth_credential.serial_number)?;
)?); let binding_number =
let binding_number = Zeroizing::new(nym_coconut_interface::Attribute::try_from_bs58( nym_coconut_interface::Attribute::try_from_bs58(bandwidth_credential.binding_number)?;
bandwidth_credential.binding_number,
)?);
let signature = let signature =
nym_coconut_interface::Signature::try_from_bs58(bandwidth_credential.signature)?; nym_coconut_interface::Signature::try_from_bs58(bandwidth_credential.signature)?;
let epoch_id = u64::from_str(&bandwidth_credential.epoch_id) let epoch_id = u64::from_str(&bandwidth_credential.epoch_id)
@@ -67,8 +64,8 @@ impl<C, St: Storage> BandwidthController<C, St> {
prepare_for_spending( prepare_for_spending(
voucher_value, voucher_value,
voucher_info, voucher_info,
&serial_number, serial_number,
&binding_number, binding_number,
epoch_id, epoch_id,
&signature, &signature,
&verification_key, &verification_key,
+1 -2
View File
@@ -35,10 +35,9 @@ opentelemetry = { version = "0.19.0", optional = true, features = ["rt-tokio"] }
[build-dependencies] [build-dependencies]
vergen = { version = "=8.2.6", default-features = false, features = [ vergen = { version = "=7.4.3", default-features = false, features = [
"build", "build",
"git", "git",
"gitcl",
"rustc", "rustc",
"cargo", "cargo",
] } ] }
+7 -8
View File
@@ -1,14 +1,13 @@
// Copyright 2023 - Nym Technologies SA <contact@nymtech.net> // Copyright 2023 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
use vergen::EmitBuilder; use vergen::{vergen, Config};
fn main() { fn main() {
EmitBuilder::builder() let mut config = Config::default();
.all_build() if std::env::var("DOCS_RS").is_ok() {
.all_git() // If we don't have access to git information, such as in a docs.rs build, don't error
.all_rustc() *config.git_mut().skip_if_error_mut() = true;
.all_cargo() }
.emit() vergen(config).expect("failed to extract build metadata");
.expect("failed to extract build metadata");
} }
+10 -10
View File
@@ -40,9 +40,9 @@ pub struct BinaryBuildInformation {
/// Provides the rustc channel that was used for the build, for example `nightly`. /// Provides the rustc channel that was used for the build, for example `nightly`.
pub rustc_channel: &'static str, pub rustc_channel: &'static str,
// VERGEN_CARGO_DEBUG // VERGEN_CARGO_PROFILE
/// Provides the cargo debug mode that was used for the build. /// Provides the cargo profile that was used for the build, for example `debug`.
pub cargo_debug: &'static str, pub cargo_profile: &'static str,
} }
impl BinaryBuildInformation { impl BinaryBuildInformation {
@@ -57,7 +57,7 @@ impl BinaryBuildInformation {
commit_branch: env!("VERGEN_GIT_BRANCH"), commit_branch: env!("VERGEN_GIT_BRANCH"),
rustc_version: env!("VERGEN_RUSTC_SEMVER"), rustc_version: env!("VERGEN_RUSTC_SEMVER"),
rustc_channel: env!("VERGEN_RUSTC_CHANNEL"), rustc_channel: env!("VERGEN_RUSTC_CHANNEL"),
cargo_debug: env!("VERGEN_CARGO_DEBUG"), cargo_profile: env!("VERGEN_CARGO_PROFILE"),
} }
} }
@@ -71,7 +71,7 @@ impl BinaryBuildInformation {
commit_branch: self.commit_branch.to_owned(), commit_branch: self.commit_branch.to_owned(),
rustc_version: self.rustc_version.to_owned(), rustc_version: self.rustc_version.to_owned(),
rustc_channel: self.rustc_channel.to_owned(), rustc_channel: self.rustc_channel.to_owned(),
cargo_debug: self.cargo_debug.to_owned(), cargo_profile: self.cargo_profile.to_owned(),
} }
} }
@@ -115,9 +115,9 @@ pub struct BinaryBuildInformationOwned {
/// Provides the rustc channel that was used for the build, for example `nightly`. /// Provides the rustc channel that was used for the build, for example `nightly`.
pub rustc_channel: String, pub rustc_channel: String,
// VERGEN_CARGO_DEBUG // VERGEN_CARGO_PROFILE
/// Provides the cargo debug mode that was used for the build. /// Provides the cargo profile that was used for the build, for example `debug`.
pub cargo_debug: String, pub cargo_profile: String,
} }
impl Display for BinaryBuildInformationOwned { impl Display for BinaryBuildInformationOwned {
@@ -151,8 +151,8 @@ impl Display for BinaryBuildInformationOwned {
self.rustc_version, self.rustc_version,
"rustc Channel:", "rustc Channel:",
self.rustc_channel, self.rustc_channel,
"cargo Debug:", "cargo Profile:",
self.cargo_debug, self.cargo_profile,
) )
} }
} }
+2 -3
View File
@@ -4,7 +4,6 @@ version = "1.1.15"
authors = ["Dave Hrycyszyn <futurechimp@users.noreply.github.com>"] authors = ["Dave Hrycyszyn <futurechimp@users.noreply.github.com>"]
edition = "2021" edition = "2021"
rust-version = "1.66" rust-version = "1.66"
license.workspace = true
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@@ -59,7 +58,7 @@ features = ["time"]
version = "0.20.1" version = "0.20.1"
[target."cfg(not(target_arch = \"wasm32\"))".dependencies.sqlx] [target."cfg(not(target_arch = \"wasm32\"))".dependencies.sqlx]
workspace = true version = "0.6.2"
features = ["runtime-tokio-rustls", "sqlite", "macros", "migrate"] features = ["runtime-tokio-rustls", "sqlite", "macros", "migrate"]
optional = true optional = true
@@ -90,7 +89,7 @@ tempfile = "3.1.0"
[build-dependencies] [build-dependencies]
tokio = { workspace = true, features = ["rt-multi-thread", "macros"] } tokio = { workspace = true, features = ["rt-multi-thread", "macros"] }
sqlx = { workspace = true, features = ["runtime-tokio-rustls", "sqlite", "macros", "migrate"] } sqlx = { version = "0.6.2", features = ["runtime-tokio-rustls", "sqlite", "macros", "migrate"] }
[features] [features]
default = [] default = []
@@ -1,8 +1,6 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net> // Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
#![allow(unused_imports)]
use std::time::Duration; use std::time::Duration;
pub use wasmtimer::{std::Instant, tokio::*}; pub use wasmtimer::{std::Instant, tokio::*};
@@ -127,9 +127,7 @@ impl ActionController {
.insert(frag_id, (Arc::new(pending_ack), None)) .insert(frag_id, (Arc::new(pending_ack), None))
.is_some() .is_some()
{ {
// This used to be a panic, however since we've seen this actually happen in the panic!("Tried to insert duplicate pending ack")
// wild, let's not take the whole client (and possibly gateway) down because of it.
error!("Tried to insert duplicate pending ack! This should not be possible!")
} }
} }
} }
@@ -3,7 +3,6 @@ name = "nym-gateway-client"
version = "0.1.0" version = "0.1.0"
authors = ["Jędrzej Stuczyński <andrew@nymtech.net>"] authors = ["Jędrzej Stuczyński <andrew@nymtech.net>"]
edition = "2021" edition = "2021"
license.workspace = true
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+2 -3
View File
@@ -3,15 +3,14 @@ name = "nym-mixnet-client"
version = "0.1.0" version = "0.1.0"
authors = ["Jedrzej Stuczynski <andrew@nymtech.net>"] authors = ["Jedrzej Stuczynski <andrew@nymtech.net>"]
edition = "2021" edition = "2021"
license.workspace = true
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
futures = { workspace = true } futures = { workspace = true }
log = { workspace = true } log = { workspace = true }
tokio = { workspace = true, features = ["time", "net", "rt"] } tokio = { version = "1.24.1", features = ["time", "net", "rt"] }
tokio-util = { workspace = true, features = ["codec"] } tokio-util = { version = "0.7.4", features = ["codec"] }
# internal # internal
nym-sphinx = { path = "../../nymsphinx" } nym-sphinx = { path = "../../nymsphinx" }
@@ -4,7 +4,6 @@ version = "0.1.0"
authors = ["Jędrzej Stuczyński <andrew@nymtech.net>"] authors = ["Jędrzej Stuczyński <andrew@nymtech.net>"]
edition = "2021" edition = "2021"
rust-version = "1.56" rust-version = "1.56"
license.workspace = true
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@@ -42,14 +42,6 @@ pub struct Config {
nyxd_config: nyxd::Config, nyxd_config: nyxd::Config,
} }
impl TryFrom<NymNetworkDetails> for Config {
type Error = ValidatorClientError;
fn try_from(value: NymNetworkDetails) -> Result<Self, Self::Error> {
Config::try_from_nym_network_details(&value)
}
}
impl Config { impl Config {
pub fn try_from_nym_network_details( pub fn try_from_nym_network_details(
details: &NymNetworkDetails, details: &NymNetworkDetails,
@@ -5,24 +5,16 @@ use crate::nym_api::error::NymAPIError;
use crate::nym_api::routes::{CORE_STATUS_COUNT, SINCE_ARG}; use crate::nym_api::routes::{CORE_STATUS_COUNT, SINCE_ARG};
use async_trait::async_trait; use async_trait::async_trait;
use http_api_client::{ApiClient, NO_PARAMS}; use http_api_client::{ApiClient, NO_PARAMS};
pub use nym_api_requests::{ use nym_api_requests::coconut::{
coconut::{ BlindSignRequestBody, BlindedSignatureResponse, VerifyCredentialBody, VerifyCredentialResponse,
models::{ };
EpochCredentialsResponse, IssuedCredential, IssuedCredentialBody, use nym_api_requests::models::{
IssuedCredentialResponse, IssuedCredentialsResponse, ComputeRewardEstParam, DescribedGateway, GatewayBondAnnotated, GatewayCoreStatusResponse,
}, GatewayStatusReportResponse, GatewayUptimeHistoryResponse, InclusionProbabilityResponse,
BlindSignRequestBody, BlindedSignatureResponse, CredentialsRequestBody, MixNodeBondAnnotated, MixnodeCoreStatusResponse, MixnodeStatusReportResponse,
VerifyCredentialBody, VerifyCredentialResponse, MixnodeStatusResponse, MixnodeUptimeHistoryResponse, RewardEstimationResponse,
}, StakeSaturationResponse, UptimeResponse,
models::{
ComputeRewardEstParam, DescribedGateway, GatewayBondAnnotated, GatewayCoreStatusResponse,
GatewayStatusReportResponse, GatewayUptimeHistoryResponse, InclusionProbabilityResponse,
MixNodeBondAnnotated, MixnodeCoreStatusResponse, MixnodeStatusReportResponse,
MixnodeStatusResponse, MixnodeUptimeHistoryResponse, RewardEstimationResponse,
StakeSaturationResponse, UptimeResponse,
},
}; };
pub use nym_coconut_dkg_common::types::EpochId;
use nym_mixnet_contract_common::mixnode::MixNodeDetails; use nym_mixnet_contract_common::mixnode::MixNodeDetails;
use nym_mixnet_contract_common::{GatewayBond, IdentityKeyRef, MixId}; use nym_mixnet_contract_common::{GatewayBond, IdentityKeyRef, MixId};
use nym_name_service_common::response::NamesListResponse; use nym_name_service_common::response::NamesListResponse;
@@ -407,60 +399,6 @@ pub trait NymApiClientExt: ApiClient {
.await .await
} }
async fn epoch_credentials(
&self,
dkg_epoch: EpochId,
) -> Result<EpochCredentialsResponse, NymAPIError> {
self.get_json(
&[
routes::API_VERSION,
routes::COCONUT_ROUTES,
routes::BANDWIDTH,
routes::COCONUT_EPOCH_CREDENTIALS,
&dkg_epoch.to_string(),
],
NO_PARAMS,
)
.await
}
async fn issued_credential(
&self,
credential_id: i64,
) -> Result<IssuedCredentialResponse, NymAPIError> {
self.get_json(
&[
routes::API_VERSION,
routes::COCONUT_ROUTES,
routes::BANDWIDTH,
routes::COCONUT_ISSUED_CREDENTIAL,
&credential_id.to_string(),
],
NO_PARAMS,
)
.await
}
async fn issued_credentials(
&self,
credential_ids: Vec<i64>,
) -> Result<IssuedCredentialsResponse, NymAPIError> {
self.post_json(
&[
routes::API_VERSION,
routes::COCONUT_ROUTES,
routes::BANDWIDTH,
routes::COCONUT_ISSUED_CREDENTIALS,
],
NO_PARAMS,
&CredentialsRequestBody {
credential_ids,
pagination: None,
},
)
.await
}
async fn get_service_providers(&self) -> Result<ServicesListResponse, NymAPIError> { async fn get_service_providers(&self) -> Result<ServicesListResponse, NymAPIError> {
log::trace!("Getting service providers"); log::trace!("Getting service providers");
self.get_json(&[routes::API_VERSION, routes::SERVICE_PROVIDERS], NO_PARAMS) self.get_json(&[routes::API_VERSION, routes::SERVICE_PROVIDERS], NO_PARAMS)
@@ -17,9 +17,6 @@ pub const BANDWIDTH: &str = "bandwidth";
pub const COCONUT_BLIND_SIGN: &str = "blind-sign"; pub const COCONUT_BLIND_SIGN: &str = "blind-sign";
pub const COCONUT_VERIFY_BANDWIDTH_CREDENTIAL: &str = "verify-bandwidth-credential"; pub const COCONUT_VERIFY_BANDWIDTH_CREDENTIAL: &str = "verify-bandwidth-credential";
pub const COCONUT_EPOCH_CREDENTIALS: &str = "epoch-credentials";
pub const COCONUT_ISSUED_CREDENTIAL: &str = "issued-credential";
pub const COCONUT_ISSUED_CREDENTIALS: &str = "issued-credentials";
pub const STATUS_ROUTES: &str = "status"; pub const STATUS_ROUTES: &str = "status";
pub const MIXNODE: &str = "mixnode"; pub const MIXNODE: &str = "mixnode";
@@ -8,8 +8,6 @@ use cosmwasm_std::{Fraction, Uint128};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::fmt; use std::fmt;
use std::ops::Div; use std::ops::Div;
use std::str::FromStr;
use thiserror::Error;
#[derive(Serialize, Deserialize, Clone, Copy, Default, Debug, PartialEq, Eq)] #[derive(Serialize, Deserialize, Clone, Copy, Default, Debug, PartialEq, Eq)]
pub struct MismatchedDenoms; pub struct MismatchedDenoms;
@@ -128,37 +126,6 @@ impl From<CosmWasmCoin> for Coin {
} }
} }
// unfortunately cosmwasm didn't re-export this correct so we just redefine its
#[derive(Error, Debug, PartialEq, Eq)]
pub enum CoinFromStrError {
#[error("Missing denominator")]
MissingDenom,
#[error("Missing amount or non-digit characters in amount")]
MissingAmount,
#[error("Invalid amount: {0}")]
InvalidAmount(#[from] std::num::ParseIntError),
}
impl FromStr for Coin {
type Err = CoinFromStrError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let pos = s
.find(|c: char| !c.is_ascii_digit())
.ok_or(CoinFromStrError::MissingDenom)?;
let (amount, denom) = s.split_at(pos);
if amount.is_empty() {
return Err(CoinFromStrError::MissingAmount);
}
Ok(Coin {
amount: amount.parse::<u128>()?,
denom: denom.to_string(),
})
}
}
pub trait CoinConverter { pub trait CoinConverter {
type Target; type Target;
@@ -32,7 +32,7 @@ pub trait CoconutBandwidthSigningClient {
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NyxdError> { ) -> Result<ExecuteResult, NyxdError> {
let req = CoconutBandwidthExecuteMsg::DepositFunds { let req = CoconutBandwidthExecuteMsg::DepositFunds {
data: DepositData::new(info, verification_key, encryption_key), data: DepositData::new(info.to_string(), verification_key, encryption_key),
}; };
self.execute_coconut_bandwidth_contract( self.execute_coconut_bandwidth_contract(
fee, fee,
@@ -7,12 +7,12 @@ use crate::nyxd::error::NyxdError;
use crate::nyxd::CosmWasmClient; use crate::nyxd::CosmWasmClient;
use async_trait::async_trait; use async_trait::async_trait;
use cosmrs::AccountId; use cosmrs::AccountId;
use nym_coconut_dkg_common::{ use nym_coconut_dkg_common::dealer::{
dealer::{ContractDealing, DealerDetailsResponse, PagedDealerResponse, PagedDealingsResponse}, ContractDealing, DealerDetailsResponse, PagedDealerResponse, PagedDealingsResponse,
msg::QueryMsg as DkgQueryMsg,
types::{DealerDetails, Epoch, EpochId, InitialReplacementData},
verification_key::{ContractVKShare, PagedVKSharesResponse},
}; };
use nym_coconut_dkg_common::msg::QueryMsg as DkgQueryMsg;
use nym_coconut_dkg_common::types::{DealerDetails, Epoch, EpochId, InitialReplacementData};
use nym_coconut_dkg_common::verification_key::{ContractVKShare, PagedVKSharesResponse};
use serde::Deserialize; use serde::Deserialize;
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))] #[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
@@ -6,8 +6,8 @@ use crate::nyxd::error::NyxdError;
use crate::nyxd::CosmWasmClient; use crate::nyxd::CosmWasmClient;
use async_trait::async_trait; use async_trait::async_trait;
use cw3::{ use cw3::{
ProposalListResponse, ProposalResponse, VoteListResponse, VoteResponse, VoterDetail, ProposalListResponse, ProposalResponse, VoteListResponse, VoteResponse, VoterListResponse,
VoterListResponse, VoterResponse, VoterResponse,
}; };
use cw_utils::ThresholdResponse; use cw_utils::ThresholdResponse;
use nym_multisig_contract_common::msg::QueryMsg as MultisigQueryMsg; use nym_multisig_contract_common::msg::QueryMsg as MultisigQueryMsg;
@@ -114,26 +114,6 @@ pub trait PagedMultisigQueryClient: MultisigQueryClient {
Ok(proposals) Ok(proposals)
} }
async fn get_all_voters(&self) -> Result<Vec<VoterDetail>, NyxdError> {
let mut voters = Vec::new();
let mut start_after = None;
loop {
let mut paged_response = self.list_voters(start_after.take(), None).await?;
let last_voter = paged_response.voters.last().map(|prop| prop.addr.clone());
voters.append(&mut paged_response.voters);
if let Some(start_after_res) = last_voter {
start_after = Some(start_after_res)
} else {
break;
}
}
Ok(voters)
}
} }
#[async_trait] #[async_trait]
@@ -52,6 +52,10 @@ use wasmtimer::tokio::sleep;
pub const DEFAULT_BROADCAST_POLLING_RATE: Duration = Duration::from_secs(4); pub const DEFAULT_BROADCAST_POLLING_RATE: Duration = Duration::from_secs(4);
pub const DEFAULT_BROADCAST_TIMEOUT: Duration = Duration::from_secs(60); pub const DEFAULT_BROADCAST_TIMEOUT: Duration = Duration::from_secs(60);
#[cfg(feature = "http-client")]
#[async_trait]
impl CosmWasmClient for cosmrs::rpc::HttpClient {}
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))] #[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)] #[cfg_attr(not(target_arch = "wasm32"), async_trait)]
pub trait CosmWasmClient: TendermintRpcClient { pub trait CosmWasmClient: TendermintRpcClient {
@@ -518,7 +522,3 @@ pub trait CosmWasmClient: TendermintRpcClient {
res.try_into() res.try_into()
} }
} }
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl<T> CosmWasmClient for T where T: TendermintRpcClient {}
@@ -425,7 +425,7 @@ where
amount: amount.into_iter().map(Into::into).collect(), amount: amount.into_iter().map(Into::into).collect(),
} }
.to_any() .to_any()
.map_err(|_| NyxdError::SerializationError("MsgSend".to_owned())) .map_err(|_| NyxdError::SerializationError("MsgExecuteContract".to_owned()))
}) })
.collect::<Result<_, _>>()?; .collect::<Result<_, _>>()?;
@@ -1,7 +1,7 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net> // Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
use crate::nyxd::cosmwasm_client::client_traits::SigningCosmWasmClient; use crate::nyxd::cosmwasm_client::client_traits::{CosmWasmClient, SigningCosmWasmClient};
use crate::nyxd::error::NyxdError; use crate::nyxd::error::NyxdError;
use crate::nyxd::{Config, GasPrice, Hash, Height}; use crate::nyxd::{Config, GasPrice, Hash, Height};
use crate::rpc::TendermintRpcClient; use crate::rpc::TendermintRpcClient;
@@ -26,7 +26,6 @@ use cosmrs::rpc::{HttpClient, HttpClientUrl};
pub mod client_traits; pub mod client_traits;
mod helpers; mod helpers;
pub mod logs; pub mod logs;
pub mod module_traits;
pub mod types; pub mod types;
#[derive(Debug)] #[derive(Debug)]
@@ -330,6 +329,14 @@ where
} }
} }
#[async_trait]
impl<C, S> CosmWasmClient for MaybeSigningClient<C, S>
where
C: TendermintRpcClient + Send + Sync,
S: Send + Sync,
{
}
#[async_trait] #[async_trait]
impl<C, S> SigningCosmWasmClient for MaybeSigningClient<C, S> impl<C, S> SigningCosmWasmClient for MaybeSigningClient<C, S>
where where
@@ -1,8 +0,0 @@
// Copyright 2023 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
pub mod slashing;
pub mod staking;
pub use staking::query::StakingQueryClient;
// pub use slashing::query
@@ -1,4 +0,0 @@
// Copyright 2023 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
pub mod query;
@@ -1,2 +0,0 @@
// Copyright 2023 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
@@ -1,8 +0,0 @@
// Copyright 2023 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
pub mod query;
pub use cosmrs::staking::{
QueryHistoricalInfoResponse, QueryValidatorResponse, QueryValidatorsResponse, Validator,
};
@@ -1,78 +0,0 @@
// Copyright 2023 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use super::{QueryHistoricalInfoResponse, QueryValidatorResponse, QueryValidatorsResponse};
use crate::nyxd::error::NyxdError;
use crate::nyxd::{CosmWasmClient, PageRequest};
use async_trait::async_trait;
use cosmrs::proto::cosmos::staking::v1beta1::{
QueryHistoricalInfoRequest as ProtoQueryHistoricalInfoRequest,
QueryHistoricalInfoResponse as ProtoQueryHistoricalInfoResponse,
QueryValidatorRequest as ProtoQueryValidatorRequest,
QueryValidatorResponse as ProtoQueryValidatorResponse,
QueryValidatorsRequest as ProtoQueryValidatorsRequest,
QueryValidatorsResponse as ProtoQueryValidatorsResponse,
};
use cosmrs::staking::{QueryHistoricalInfoRequest, QueryValidatorRequest, QueryValidatorsRequest};
use cosmrs::AccountId;
// TODO: change trait restriction from `CosmWasmClient` to `TendermintRpcClient`
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
pub trait StakingQueryClient: CosmWasmClient {
async fn historical_info(&self, height: i64) -> Result<QueryHistoricalInfoResponse, NyxdError> {
let path = Some("/cosmos.staking.v1beta1.Query/HistoricalInfo".to_owned());
let req = QueryHistoricalInfoRequest { height };
let res = self
.make_abci_query::<ProtoQueryHistoricalInfoRequest, ProtoQueryHistoricalInfoResponse>(
path,
req.into(),
)
.await?;
Ok(res.try_into()?)
}
async fn validator(
&self,
validator_addr: AccountId,
) -> Result<QueryValidatorResponse, NyxdError> {
let path = Some("/cosmos.staking.v1beta1.Query/Validator".to_owned());
let req = QueryValidatorRequest { validator_addr };
let res = self
.make_abci_query::<ProtoQueryValidatorRequest, ProtoQueryValidatorResponse>(
path,
req.into(),
)
.await?;
Ok(res.try_into()?)
}
async fn validators(
&self,
status: String,
pagination: Option<PageRequest>,
) -> Result<QueryValidatorsResponse, NyxdError> {
let path = Some("/cosmos.staking.v1beta1.Query/Validators".to_owned());
let req = QueryValidatorsRequest { status, pagination };
let res = self
.make_abci_query::<ProtoQueryValidatorsRequest, ProtoQueryValidatorsResponse>(
path,
req.into(),
)
.await?;
Ok(res.try_into()?)
}
}
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl<T> StakingQueryClient for T where T: CosmWasmClient {}
@@ -1,13 +0,0 @@
// Copyright 2023 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::nyxd::TxResponse;
pub fn find_tx_attribute(tx: &TxResponse, event_type: &str, attribute_key: &str) -> Option<String> {
let event = tx.tx_result.events.iter().find(|e| e.kind == event_type)?;
let attribute = event
.attributes
.iter()
.find(|attr| attr.key == attribute_key)?;
Some(attribute.value.clone())
}
@@ -29,41 +29,31 @@ use tendermint_rpc::endpoint::*;
use tendermint_rpc::{Error as TendermintRpcError, Order}; use tendermint_rpc::{Error as TendermintRpcError, Order};
use url::Url; use url::Url;
pub use crate::nyxd::{ pub use crate::nyxd::cosmwasm_client::client_traits::{CosmWasmClient, SigningCosmWasmClient};
cosmwasm_client::{ pub use crate::nyxd::fee::Fee;
client_traits::{CosmWasmClient, SigningCosmWasmClient},
module_traits::{self, StakingQueryClient},
},
fee::Fee,
};
pub use crate::rpc::TendermintRpcClient; pub use crate::rpc::TendermintRpcClient;
pub use coin::Coin; pub use coin::Coin;
pub use cosmrs::{ pub use cosmrs::bank::MsgSend;
bank::MsgSend, pub use cosmrs::tendermint::abci::{
bip32, response::DeliverTx, types::ExecTxResult, Event, EventAttribute,
crypto::PublicKey,
query::{PageRequest, PageResponse},
tendermint::{
abci::{response::DeliverTx, types::ExecTxResult, Event, EventAttribute},
block::Height,
hash::{self, Algorithm, Hash},
validator::Info as TendermintValidatorInfo,
Time as TendermintTime,
},
tx::{self, Msg},
AccountId, Any, Coin as CosmosCoin, Denom, Gas,
}; };
pub use cosmrs::tendermint::block::Height;
pub use cosmrs::tendermint::hash::{self, Algorithm, Hash};
pub use cosmrs::tendermint::validator::Info as TendermintValidatorInfo;
pub use cosmrs::tendermint::Time as TendermintTime;
pub use cosmrs::tx::Msg;
pub use cosmrs::tx::{self};
pub use cosmrs::Coin as CosmosCoin;
pub use cosmrs::Gas;
pub use cosmrs::{bip32, AccountId, Denom};
pub use cosmwasm_std::Coin as CosmWasmCoin; pub use cosmwasm_std::Coin as CosmWasmCoin;
pub use cw2;
pub use cw3;
pub use cw4;
pub use cw_controllers;
pub use fee::{gas_price::GasPrice, GasAdjustable, GasAdjustment}; pub use fee::{gas_price::GasPrice, GasAdjustable, GasAdjustment};
pub use tendermint_rpc::{ pub use tendermint_rpc::{
endpoint::{tx::Response as TxResponse, validators::Response as ValidatorResponse}, endpoint::{tx::Response as TxResponse, validators::Response as ValidatorResponse},
query::Query, query::Query,
Paging, Request, Response, SimpleRequest, Paging,
}; };
pub use tendermint_rpc::{Request, Response, SimpleRequest};
#[cfg(feature = "http-client")] #[cfg(feature = "http-client")]
use crate::http_client; use crate::http_client;
@@ -77,7 +67,6 @@ pub mod contract_traits;
pub mod cosmwasm_client; pub mod cosmwasm_client;
pub mod error; pub mod error;
pub mod fee; pub mod fee;
pub mod helpers;
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Config { pub struct Config {
@@ -103,14 +92,6 @@ impl Config {
} }
} }
impl TryFrom<NymNetworkDetails> for Config {
type Error = NyxdError;
fn try_from(value: NymNetworkDetails) -> Result<Self, Self::Error> {
Config::try_from_nym_network_details(&value)
}
}
#[derive(Debug)] #[derive(Debug)]
pub struct NyxdClient<C, S = NoSigner> { pub struct NyxdClient<C, S = NoSigner> {
client: MaybeSigningClient<C, S>, client: MaybeSigningClient<C, S>,
@@ -742,7 +723,7 @@ where
where where
H: Into<Height> + Send, H: Into<Height> + Send,
{ {
TendermintRpcClient::validators(&self.client, height, paging).await self.client.validators(height, paging).await
} }
async fn latest_consensus_params( async fn latest_consensus_params(
@@ -817,6 +798,14 @@ where
} }
} }
#[async_trait]
impl<C, S> CosmWasmClient for NyxdClient<C, S>
where
C: TendermintRpcClient + Send + Sync,
S: Send + Sync,
{
}
impl<C, S> OfflineSigner for NyxdClient<C, S> impl<C, S> OfflineSigner for NyxdClient<C, S>
where where
S: OfflineSigner, S: OfflineSigner,
-1
View File
@@ -3,7 +3,6 @@ name = "nym-coconut-interface"
version = "0.1.0" version = "0.1.0"
edition = "2021" edition = "2021"
description = "Crutch library until there is proper SerDe support for coconut structs" description = "Crutch library until there is proper SerDe support for coconut structs"
license.workspace = true
[dependencies] [dependencies]
bs58 = "0.4.0" bs58 = "0.4.0"
+10 -12
View File
@@ -21,14 +21,10 @@ pub use nym_coconut::{
pub struct Credential { pub struct Credential {
#[getset(get = "pub")] #[getset(get = "pub")]
n_params: u32, n_params: u32,
#[getset(get = "pub")] #[getset(get = "pub")]
theta: Theta, theta: Theta,
voucher_value: u64, voucher_value: u64,
voucher_info: String, voucher_info: String,
#[getset(get = "pub")] #[getset(get = "pub")]
epoch_id: u64, epoch_id: u64,
} }
@@ -68,12 +64,14 @@ impl Credential {
pub fn verify(&self, verification_key: &VerificationKey) -> bool { pub fn verify(&self, verification_key: &VerificationKey) -> bool {
let params = Parameters::new(self.n_params).unwrap(); let params = Parameters::new(self.n_params).unwrap();
let public_attributes = [
let hashed_value = hash_to_scalar(self.voucher_value.to_string()); self.voucher_value.to_string().as_bytes(),
let hashed_info = hash_to_scalar(&self.voucher_info); self.voucher_info.as_bytes(),
let public_attributes = &[&hashed_value, &hashed_info]; ]
.iter()
nym_coconut::verify_credential(&params, verification_key, &self.theta, public_attributes) .map(hash_to_scalar)
.collect::<Vec<Attribute>>();
nym_coconut::verify_credential(&params, verification_key, &self.theta, &public_attributes)
} }
pub fn as_bytes(&self) -> Vec<u8> { pub fn as_bytes(&self) -> Vec<u8> {
@@ -182,8 +180,8 @@ mod tests {
&params, &params,
&verification_key, &verification_key,
&signature, &signature,
&serial_number, serial_number,
&binding_number, binding_number,
) )
.unwrap(); .unwrap();
let credential = Credential::new(4, theta, voucher_value, voucher_info, 42); let credential = Credential::new(4, theta, voucher_value, voucher_info, 42);
-1
View File
@@ -3,7 +3,6 @@ name = "nym-cli-commands"
version = "1.0.0" version = "1.0.0"
authors.workspace = true authors.workspace = true
edition = "2021" edition = "2021"
license.workspace = true
[dependencies] [dependencies]
anyhow = { workspace = true } anyhow = { workspace = true }
@@ -26,10 +26,6 @@ pub struct Args {
} }
pub async fn execute(args: Args, client: SigningClient) -> anyhow::Result<()> { pub async fn execute(args: Args, client: SigningClient) -> anyhow::Result<()> {
if args.amount == 0 {
bail!("did not specify credential amount")
}
let loaded = CommonConfigsWrapper::try_load(args.client_config)?; let loaded = CommonConfigsWrapper::try_load(args.client_config)?;
if let Ok(id) = loaded.try_get_id() { if let Ok(id) = loaded.try_get_id() {
+1 -2
View File
@@ -3,7 +3,6 @@ name = "nym-config"
version = "0.1.0" version = "0.1.0"
authors = ["Jedrzej Stuczynski <andrew@nymtech.net>"] authors = ["Jedrzej Stuczynski <andrew@nymtech.net>"]
edition = "2021" edition = "2021"
license.workspace = true
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@@ -18,4 +17,4 @@ url = { workspace = true }
nym-network-defaults = { path = "../network-defaults" } nym-network-defaults = { path = "../network-defaults" }
[features] [features]
default = ["dirs"] default = ["dirs"]
+1 -1
View File
@@ -73,7 +73,7 @@ where
P: AsRef<Path>, P: AsRef<Path>,
{ {
let path = path.as_ref(); let path = path.as_ref();
log::info!("saving config file to {}", path.display()); log::debug!("trying to save config file to {}", path.display());
if let Some(parent) = path.parent() { if let Some(parent) = path.parent() {
create_dir_all(parent)?; create_dir_all(parent)?;
@@ -2,7 +2,6 @@
name = "nym-coconut-bandwidth-contract-common" name = "nym-coconut-bandwidth-contract-common"
version = "0.1.0" version = "0.1.0"
edition = "2021" edition = "2021"
license.workspace = true
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@@ -13,4 +12,4 @@ cw2 = { workspace = true, optional = true }
nym-multisig-contract-common = { path = "../multisig-contract" } nym-multisig-contract-common = { path = "../multisig-contract" }
[features] [features]
schema = ["cw2"] schema = ["cw2"]
@@ -4,9 +4,6 @@
// event types // event types
pub const DEPOSITED_FUNDS_EVENT_TYPE: &str = "deposited-funds"; pub const DEPOSITED_FUNDS_EVENT_TYPE: &str = "deposited-funds";
// a 'wasm-' prefix is added to all cosmwasm events
pub const COSMWASM_DEPOSITED_FUNDS_EVENT_TYPE: &str = "wasm-deposited-funds";
// attributes that are used in multiple places // attributes that are used in multiple places
pub const DEPOSIT_VALUE: &str = "deposit-value"; pub const DEPOSIT_VALUE: &str = "deposit-value";
pub const DEPOSIT_INFO: &str = "deposit-info"; pub const DEPOSIT_INFO: &str = "deposit-info";
@@ -2,7 +2,6 @@
name = "nym-coconut-dkg-common" name = "nym-coconut-dkg-common"
version = "0.1.0" version = "0.1.0"
edition = "2021" edition = "2021"
license.workspace = true
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@@ -15,4 +14,4 @@ contracts-common = { path = "../contracts-common", package = "nym-contracts-comm
nym-multisig-contract-common = { path = "../multisig-contract" } nym-multisig-contract-common = { path = "../multisig-contract" }
[features] [features]
schema = [] schema = []
@@ -174,19 +174,17 @@ impl Display for EpochState {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self { match self {
EpochState::PublicKeySubmission { resharing } => { EpochState::PublicKeySubmission { resharing } => {
write!(f, "PublicKeySubmission (resharing: {resharing})") write!(f, "PublicKeySubmission with resharing {resharing}")
}
EpochState::DealingExchange { resharing } => {
write!(f, "DealingExchange (resharing: {resharing})")
} }
EpochState::DealingExchange { resharing } => write!(f, "DealingExchange {resharing}"),
EpochState::VerificationKeySubmission { resharing } => { EpochState::VerificationKeySubmission { resharing } => {
write!(f, "VerificationKeySubmission (resharing: {resharing})") write!(f, "VerificationKeySubmission with resharing {resharing}")
} }
EpochState::VerificationKeyValidation { resharing } => { EpochState::VerificationKeyValidation { resharing } => {
write!(f, "VerificationKeyValidation (resharing: {resharing})") write!(f, "VerificationKeyValidation with resharing {resharing}")
} }
EpochState::VerificationKeyFinalization { resharing } => { EpochState::VerificationKeyFinalization { resharing } => {
write!(f, "VerificationKeyFinalization (resharing: {resharing})") write!(f, "VerificationKeyFinalization with resharing {resharing}")
} }
EpochState::InProgress => write!(f, "InProgress"), EpochState::InProgress => write!(f, "InProgress"),
} }
@@ -2,7 +2,6 @@
name = "nym-ephemera-common" name = "nym-ephemera-common"
version = "0.1.0" version = "0.1.0"
edition = "2021" edition = "2021"
license.workspace = true
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@@ -14,4 +13,4 @@ cw-utils = { workspace = true }
contracts-common = { path = "../contracts-common", package = "nym-contracts-common" } contracts-common = { path = "../contracts-common", package = "nym-contracts-common" }
[features] [features]
schema = [] schema = []
@@ -2,7 +2,6 @@
name = "nym-group-contract-common" name = "nym-group-contract-common"
version = "0.1.0" version = "0.1.0"
edition = "2021" edition = "2021"
license.workspace = true
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@@ -2,7 +2,6 @@
name = "nym-multisig-contract-common" name = "nym-multisig-contract-common"
version = "0.1.0" version = "0.1.0"
edition = "2021" edition = "2021"
license.workspace = true
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@@ -2,7 +2,6 @@
name = "nym-name-service-common" name = "nym-name-service-common"
version = "0.1.0" version = "0.1.0"
edition = "2021" edition = "2021"
license.workspace = true
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@@ -17,4 +16,4 @@ serde = { workspace = true, features = ["derive"] }
thiserror = { workspace = true } thiserror = { workspace = true }
[features] [features]
schema = ["cw2"] schema = ["cw2"]
@@ -2,7 +2,6 @@
name = "nym-service-provider-directory-common" name = "nym-service-provider-directory-common"
version = "0.1.0" version = "0.1.0"
edition = "2021" edition = "2021"
license.workspace = true
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@@ -16,4 +15,4 @@ nym-contracts-common = { path = "../contracts-common", version = "0.5.0" }
thiserror = { workspace = true } thiserror = { workspace = true }
[features] [features]
schema = ["cw2"] schema = ["cw2"]
+3 -4
View File
@@ -2,7 +2,6 @@
name = "nym-credential-storage" name = "nym-credential-storage"
version = "0.1.0" version = "0.1.0"
edition = "2021" edition = "2021"
license.workspace = true
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@@ -14,14 +13,14 @@ thiserror = { workspace = true }
tokio = { version = "1.24.1", features = ["sync"]} tokio = { version = "1.24.1", features = ["sync"]}
[target."cfg(not(target_arch = \"wasm32\"))".dependencies.sqlx] [target."cfg(not(target_arch = \"wasm32\"))".dependencies.sqlx]
workspace = true version = "0.5"
features = ["runtime-tokio-rustls", "sqlite", "macros", "migrate"] features = ["runtime-tokio-rustls", "sqlite", "macros", "migrate"]
[target."cfg(not(target_arch = \"wasm32\"))".dependencies.tokio] [target."cfg(not(target_arch = \"wasm32\"))".dependencies.tokio]
workspace = true version = "1.24.1"
features = [ "rt-multi-thread", "net", "signal", "fs" ] features = [ "rt-multi-thread", "net", "signal", "fs" ]
[build-dependencies] [build-dependencies]
sqlx = { workspace = true, features = ["runtime-tokio-rustls", "sqlite", "macros", "migrate"] } sqlx = { version = "0.5", features = ["runtime-tokio-rustls", "sqlite", "macros", "migrate"] }
tokio = { version = "1.24.1", features = ["rt-multi-thread", "macros"] } tokio = { version = "1.24.1", features = ["rt-multi-thread", "macros"] }
-1
View File
@@ -2,7 +2,6 @@
name = "nym-credential-utils" name = "nym-credential-utils"
version = "0.1.0" version = "0.1.0"
edition = "2021" edition = "2021"
license.workspace = true
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+2 -4
View File
@@ -2,20 +2,18 @@
name = "nym-credentials" name = "nym-credentials"
version = "0.1.0" version = "0.1.0"
edition = "2021" edition = "2021"
license.workspace = true
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
bls12_381 = { workspace = true, default-features = false, features = ["pairings", "alloc", "experimental"] } bls12_381 = { version = "0.5", default-features = false, features = ["pairings", "alloc", "experimental"] }
cosmrs = { workspace = true } cosmrs = { workspace = true }
thiserror = { workspace = true } thiserror = { workspace = true }
log = { workspace = true } log = { workspace = true }
zeroize = { workspace = true }
# I guess temporarily until we get serde support in coconut up and running # I guess temporarily until we get serde support in coconut up and running
nym-coconut-interface = { path = "../coconut-interface" } nym-coconut-interface = { path = "../coconut-interface" }
nym-crypto = { path = "../crypto", features = ["rand", "asymmetric"] } nym-crypto = { path = "../crypto", features = ["rand", "asymmetric", "symmetric", "hashing"] }
nym-api-requests = { path = "../../nym-api/nym-api-requests" } nym-api-requests = { path = "../../nym-api/nym-api-requests" }
nym-validator-client = { path = "../client-libs/validator-client", default-features = false } nym-validator-client = { path = "../client-libs/validator-client", default-features = false }
+51 -93
View File
@@ -13,60 +13,38 @@ use nym_coconut_interface::{
PrivateAttribute, PublicAttribute, Signature, VerificationKey, PrivateAttribute, PublicAttribute, Signature, VerificationKey,
}; };
use nym_crypto::asymmetric::{encryption, identity}; use nym_crypto::asymmetric::{encryption, identity};
use zeroize::{Zeroize, ZeroizeOnDrop};
use super::utils::prepare_credential_for_spending; use super::utils::prepare_credential_for_spending;
use crate::error::Error; use crate::error::Error;
#[derive(Zeroize, ZeroizeOnDrop)] pub const PUBLIC_ATTRIBUTES: u32 = 2;
pub const PRIVATE_ATTRIBUTES: u32 = 2;
pub const TOTAL_ATTRIBUTES: u32 = PUBLIC_ATTRIBUTES + PRIVATE_ATTRIBUTES;
pub struct BandwidthVoucher { pub struct BandwidthVoucher {
// private attributes // a random secret value generated by the client used for double-spending detection
/// a random secret value generated by the client used for double-spending detection
serial_number: PrivateAttribute, serial_number: PrivateAttribute,
// a random secret value generated by the client used to bind multiple credentials together
/// a random secret value generated by the client used to bind multiple credentials together
binding_number: PrivateAttribute, binding_number: PrivateAttribute,
// the value (e.g., bandwidth) encoded in this voucher
// public atttributes: voucher_value: PublicAttribute,
/// the plain text value (e.g., bandwidth) encoded in this voucher // the plain text value (e.g., bandwidth) encoded in this voucher
// TODO: in another PR change the value from `"1000"` to `"1000unym"`
voucher_value_plain: String, voucher_value_plain: String,
// a field with public information, e.g., type of voucher, interval etc.
/// the plain text information voucher_info: PublicAttribute,
// the plain text information
voucher_info_plain: String, voucher_info_plain: String,
// the hash of the deposit transaction
/// the precomputed value (e.g., bandwidth) encoded in this voucher
_voucher_value_prehashed: PublicAttribute,
/// the precomputed field with public information, e.g., type of voucher, interval etc.
_voucher_info_prehashed: PublicAttribute,
/// the hash of the deposit transaction
#[zeroize(skip)]
tx_hash: Hash, tx_hash: Hash,
// base58 encoded private key ensuring the depositer requested these attributes
/// base58 encoded private key ensuring the depositer requested these attributes
signing_key: identity::PrivateKey, signing_key: identity::PrivateKey,
// base58 encoded private key ensuring only this client receives the signature share
/// base58 encoded private key ensuring only this client receives the signature share encryption_key: encryption::PrivateKey,
unused_ed25519: encryption::PrivateKey,
pedersen_commitments_openings: Vec<Attribute>, pedersen_commitments_openings: Vec<Attribute>,
#[zeroize(skip)]
blind_sign_request: BlindSignRequest, blind_sign_request: BlindSignRequest,
} }
impl BandwidthVoucher { impl BandwidthVoucher {
pub const PUBLIC_ATTRIBUTES: u32 = 2;
pub const PRIVATE_ATTRIBUTES: u32 = 2;
pub const ENCODED_ATTRIBUTES: u32 = 4;
pub fn default_parameters() -> Parameters {
// safety: the unwrap is fine here as Self::ENCODED_ATTRIBUTES is non-zero
Parameters::new(Self::ENCODED_ATTRIBUTES).unwrap()
}
pub fn new( pub fn new(
params: &Parameters, params: &Parameters,
voucher_value: String, voucher_value: String,
@@ -79,26 +57,24 @@ impl BandwidthVoucher {
let binding_number = params.random_scalar(); let binding_number = params.random_scalar();
let voucher_value_plain = voucher_value.clone(); let voucher_value_plain = voucher_value.clone();
let voucher_info_plain = voucher_info.clone(); let voucher_info_plain = voucher_info.clone();
let voucher_value = hash_to_scalar(voucher_value.as_bytes());
let _voucher_value_prehashed = hash_to_scalar(voucher_value); let voucher_info = hash_to_scalar(voucher_info.as_bytes());
let _voucher_info_prehashed = hash_to_scalar(voucher_info);
let (pedersen_commitments_openings, blind_sign_request) = prepare_blind_sign( let (pedersen_commitments_openings, blind_sign_request) = prepare_blind_sign(
params, params,
&[&serial_number, &binding_number], &[serial_number, binding_number],
&[&_voucher_value_prehashed, &_voucher_info_prehashed], &[voucher_value, voucher_info],
) )
.unwrap(); .unwrap();
BandwidthVoucher { BandwidthVoucher {
serial_number, serial_number,
binding_number, binding_number,
_voucher_value_prehashed, voucher_value,
voucher_value_plain, voucher_value_plain,
_voucher_info_prehashed, voucher_info,
voucher_info_plain, voucher_info_plain,
tx_hash, tx_hash,
signing_key, signing_key,
unused_ed25519: encryption_key, encryption_key,
pedersen_commitments_openings, pedersen_commitments_openings,
blind_sign_request, blind_sign_request,
} }
@@ -111,7 +87,7 @@ impl BandwidthVoucher {
let voucher_info_plain_b = self.voucher_info_plain.as_bytes(); let voucher_info_plain_b = self.voucher_info_plain.as_bytes();
let tx_hash_b = self.tx_hash.as_bytes(); let tx_hash_b = self.tx_hash.as_bytes();
let signing_key_b = self.signing_key.to_bytes(); let signing_key_b = self.signing_key.to_bytes();
let encryption_key_b = self.unused_ed25519.to_bytes(); let encryption_key_b = self.encryption_key.to_bytes();
let blind_sign_request_b = self.blind_sign_request.to_bytes(); let blind_sign_request_b = self.blind_sign_request.to_bytes();
let mut ret = Vec::new(); let mut ret = Vec::new();
@@ -195,13 +171,13 @@ impl BandwidthVoucher {
bytes[var_length_pointer..var_length_pointer + voucher_value_plain_no].to_vec(), bytes[var_length_pointer..var_length_pointer + voucher_value_plain_no].to_vec(),
) )
.or_else(utf_err)?; .or_else(utf_err)?;
let _voucher_value_prehashed = hash_to_scalar(&voucher_value_plain); let voucher_value = hash_to_scalar(&voucher_value_plain);
var_length_pointer += voucher_value_plain_no; var_length_pointer += voucher_value_plain_no;
let voucher_info_plain = String::from_utf8( let voucher_info_plain = String::from_utf8(
bytes[var_length_pointer..var_length_pointer + voucher_info_plain_no].to_vec(), bytes[var_length_pointer..var_length_pointer + voucher_info_plain_no].to_vec(),
) )
.or_else(utf_err)?; .or_else(utf_err)?;
let _voucher_info_prehashed = hash_to_scalar(&voucher_info_plain); let voucher_info = hash_to_scalar(&voucher_info_plain);
var_length_pointer += voucher_info_plain_no; var_length_pointer += voucher_info_plain_no;
let blind_sign_request = BlindSignRequest::from_bytes( let blind_sign_request = BlindSignRequest::from_bytes(
&bytes[var_length_pointer..var_length_pointer + blind_sign_request_no], &bytes[var_length_pointer..var_length_pointer + blind_sign_request_no],
@@ -220,43 +196,36 @@ impl BandwidthVoucher {
Ok(Self { Ok(Self {
serial_number, serial_number,
binding_number, binding_number,
_voucher_value_prehashed, voucher_value,
voucher_value_plain, voucher_value_plain,
_voucher_info_prehashed, voucher_info,
voucher_info_plain, voucher_info_plain,
tx_hash, tx_hash,
signing_key, signing_key,
unused_ed25519: encryption_key, encryption_key,
pedersen_commitments_openings, pedersen_commitments_openings,
blind_sign_request, blind_sign_request,
}) })
} }
/// Check if the plain values correspond to the PublicAttributes /// Check if the plain values correspond to the PublicAttributes
pub fn verify_against_plain(values: &[&PublicAttribute], plain_values: &[String]) -> bool { pub fn verify_against_plain(values: &[PublicAttribute], plain_values: &[String]) -> bool {
values.len() == 2 values.len() == 2
&& plain_values.len() == 2 && plain_values.len() == 2
&& values[0] == &hash_to_scalar(&plain_values[0]) && values[0] == hash_to_scalar(&plain_values[0])
&& values[1] == &hash_to_scalar(&plain_values[1]) && values[1] == hash_to_scalar(&plain_values[1])
} }
pub fn tx_hash(&self) -> Hash { pub fn tx_hash(&self) -> &Hash {
self.tx_hash &self.tx_hash
} }
pub fn get_public_attributes(&self) -> Vec<&PublicAttribute> { pub fn get_public_attributes(&self) -> Vec<PublicAttribute> {
vec![ vec![self.voucher_value, self.voucher_info]
&self._voucher_value_prehashed,
&self._voucher_info_prehashed,
]
}
pub fn identity_key(&self) -> &identity::PrivateKey {
&self.signing_key
} }
pub fn encryption_key(&self) -> &encryption::PrivateKey { pub fn encryption_key(&self) -> &encryption::PrivateKey {
&self.unused_ed25519 &self.encryption_key
} }
pub fn pedersen_commitments_openings(&self) -> &Vec<Attribute> { pub fn pedersen_commitments_openings(&self) -> &Vec<Attribute> {
@@ -278,32 +247,27 @@ impl BandwidthVoucher {
] ]
} }
pub fn get_private_attributes(&self) -> Vec<&PrivateAttribute> { pub fn get_private_attributes(&self) -> Vec<PrivateAttribute> {
vec![&self.serial_number, &self.binding_number] vec![self.serial_number, self.binding_number]
} }
pub fn signable_plaintext(request: &BlindSignRequest, tx_hash: Hash) -> Vec<u8> { pub fn sign(&self, request: &BlindSignRequest) -> identity::Signature {
let mut message = request.to_bytes(); let mut message = request.to_bytes();
message.extend_from_slice(tx_hash.as_bytes()); message.extend_from_slice(self.tx_hash.to_string().as_bytes());
message self.signing_key.sign(&message)
}
pub fn sign(&self) -> identity::Signature {
let message = Self::signable_plaintext(&self.blind_sign_request, self.tx_hash);
self.signing_key.sign(message)
} }
} }
pub fn prepare_for_spending( pub fn prepare_for_spending(
voucher_value: u64, voucher_value: u64,
voucher_info: String, voucher_info: String,
serial_number: &PrivateAttribute, serial_number: PrivateAttribute,
binding_number: &PrivateAttribute, binding_number: PrivateAttribute,
epoch_id: u64, epoch_id: u64,
signature: &Signature, signature: &Signature,
verification_key: &VerificationKey, verification_key: &VerificationKey,
) -> Result<Credential, Error> { ) -> Result<Credential, Error> {
let params = Parameters::new(BandwidthVoucher::ENCODED_ATTRIBUTES)?; let params = Parameters::new(TOTAL_ATTRIBUTES)?;
prepare_credential_for_spending( prepare_credential_for_spending(
&params, &params,
@@ -352,30 +316,24 @@ mod test {
let deserialized_voucher = BandwidthVoucher::try_from_bytes(&bytes).unwrap(); let deserialized_voucher = BandwidthVoucher::try_from_bytes(&bytes).unwrap();
assert_eq!(voucher.serial_number, deserialized_voucher.serial_number); assert_eq!(voucher.serial_number, deserialized_voucher.serial_number);
assert_eq!(voucher.binding_number, deserialized_voucher.binding_number); assert_eq!(voucher.binding_number, deserialized_voucher.binding_number);
assert_eq!(voucher.voucher_value, deserialized_voucher.voucher_value);
assert_eq!( assert_eq!(
voucher.voucher_value_plain, voucher.voucher_value_plain,
deserialized_voucher.voucher_value_plain deserialized_voucher.voucher_value_plain
); );
assert_eq!(voucher.voucher_info, deserialized_voucher.voucher_info);
assert_eq!( assert_eq!(
voucher.voucher_info_plain, voucher.voucher_info_plain,
deserialized_voucher.voucher_info_plain deserialized_voucher.voucher_info_plain
); );
assert_eq!(
voucher._voucher_value_prehashed,
deserialized_voucher._voucher_value_prehashed
);
assert_eq!(
voucher._voucher_info_prehashed,
deserialized_voucher._voucher_info_prehashed
);
assert_eq!(voucher.tx_hash, deserialized_voucher.tx_hash); assert_eq!(voucher.tx_hash, deserialized_voucher.tx_hash);
assert_eq!( assert_eq!(
voucher.signing_key.to_string(), voucher.signing_key.to_string(),
deserialized_voucher.signing_key.to_string() deserialized_voucher.signing_key.to_string()
); );
assert_eq!( assert_eq!(
voucher.unused_ed25519.to_string(), voucher.encryption_key.to_string(),
deserialized_voucher.unused_ed25519.to_string() deserialized_voucher.encryption_key.to_string()
); );
assert_eq!( assert_eq!(
voucher.pedersen_commitments_openings, voucher.pedersen_commitments_openings,
@@ -413,11 +371,11 @@ mod test {
] ]
)); ));
assert!(!BandwidthVoucher::verify_against_plain( assert!(!BandwidthVoucher::verify_against_plain(
&[voucher.get_public_attributes()[0], &Attribute::one()], &[voucher.get_public_attributes()[0], Attribute::one()],
&voucher.get_public_attributes_plain() &voucher.get_public_attributes_plain()
)); ));
assert!(!BandwidthVoucher::verify_against_plain( assert!(!BandwidthVoucher::verify_against_plain(
&[&Attribute::one(), voucher.get_public_attributes()[1]], &[Attribute::one(), voucher.get_public_attributes()[1]],
&voucher.get_public_attributes_plain() &voucher.get_public_attributes_plain()
)); ));
assert!(BandwidthVoucher::verify_against_plain( assert!(BandwidthVoucher::verify_against_plain(
+1
View File
@@ -2,4 +2,5 @@
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
pub mod bandwidth; pub mod bandwidth;
pub mod params;
pub mod utils; pub mod utils;
+15
View File
@@ -0,0 +1,15 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use nym_crypto::aes::Aes128;
use nym_crypto::blake3;
use nym_crypto::ctr;
type Aes128Ctr = ctr::Ctr64LE<Aes128>;
/// Hashing algorithm used during hkdf for ephemeral shared key generation per blinded signature
/// response encryption.
pub type NymApiCredentialHkdfAlgorithm = blake3::Hasher;
/// Encryption algorithm used for end-to-end encryption of blinded signature response
pub type NymApiCredentialEncryptionAlgorithm = Aes128Ctr;
+39 -22
View File
@@ -1,14 +1,18 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net> // Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
use crate::coconut::bandwidth::BandwidthVoucher; use crate::coconut::bandwidth::{BandwidthVoucher, PRIVATE_ATTRIBUTES, PUBLIC_ATTRIBUTES};
use crate::coconut::params::{NymApiCredentialEncryptionAlgorithm, NymApiCredentialHkdfAlgorithm};
use crate::error::Error; use crate::error::Error;
use log::{debug, warn}; use log::{debug, warn};
use nym_api_requests::coconut::BlindSignRequestBody; use nym_api_requests::coconut::BlindSignRequestBody;
use nym_coconut_interface::{ use nym_coconut_interface::{
aggregate_signature_shares, aggregate_verification_keys, prove_bandwidth_credential, Attribute, aggregate_signature_shares, aggregate_verification_keys, prove_bandwidth_credential, Attribute,
Credential, Parameters, Signature, SignatureShare, VerificationKey, BlindedSignature, Credential, Parameters, Signature, SignatureShare, VerificationKey,
}; };
use nym_crypto::asymmetric::encryption::PublicKey;
use nym_crypto::shared_key::recompute_shared_key;
use nym_crypto::symmetric::stream_cipher;
use nym_validator_client::client::CoconutApiClient; use nym_validator_client::client::CoconutApiClient;
pub async fn obtain_aggregate_verification_key( pub async fn obtain_aggregate_verification_key(
@@ -32,34 +36,47 @@ pub async fn obtain_aggregate_verification_key(
async fn obtain_partial_credential( async fn obtain_partial_credential(
params: &Parameters, params: &Parameters,
voucher: &BandwidthVoucher, attributes: &BandwidthVoucher,
client: &nym_validator_client::client::NymApiClient, client: &nym_validator_client::client::NymApiClient,
validator_vk: &VerificationKey, validator_vk: &VerificationKey,
) -> Result<Signature, Error> { ) -> Result<Signature, Error> {
let public_attributes_plain = voucher.get_public_attributes_plain(); let public_attributes = attributes.get_public_attributes();
let blind_sign_request = voucher.blind_sign_request(); let public_attributes_plain = attributes.get_public_attributes_plain();
let request_signature = voucher.sign(); let private_attributes = attributes.get_private_attributes();
let blind_sign_request = attributes.blind_sign_request();
let blind_sign_request_body = BlindSignRequestBody::new( let blind_sign_request_body = BlindSignRequestBody::new(
blind_sign_request.clone(), blind_sign_request,
voucher.tx_hash(), attributes.tx_hash().to_string(),
request_signature, attributes.sign(blind_sign_request).to_base58_string(),
&public_attributes,
public_attributes_plain, public_attributes_plain,
(public_attributes.len() + private_attributes.len()) as u32,
); );
let response = client.blind_sign(&blind_sign_request_body).await?; let response = client.blind_sign(&blind_sign_request_body).await?;
let encrypted_signature = response.encrypted_signature;
let remote_key = PublicKey::from_bytes(&response.remote_key)?;
let blinded_signature = response.blinded_signature; let encryption_key = recompute_shared_key::<
NymApiCredentialEncryptionAlgorithm,
NymApiCredentialHkdfAlgorithm,
>(&remote_key, attributes.encryption_key());
let zero_iv = stream_cipher::zero_iv::<NymApiCredentialEncryptionAlgorithm>();
let blinded_signature_bytes = stream_cipher::decrypt::<NymApiCredentialEncryptionAlgorithm>(
&encryption_key,
&zero_iv,
&encrypted_signature,
);
let public_attributes = voucher.get_public_attributes(); let blinded_signature = BlindedSignature::from_bytes(&blinded_signature_bytes)?;
let private_attributes = voucher.get_private_attributes();
let unblinded_signature = blinded_signature.unblind_and_verify( let unblinded_signature = blinded_signature.unblind(
params, params,
validator_vk, validator_vk,
&private_attributes, &private_attributes,
&public_attributes, &public_attributes,
&blind_sign_request.get_commitment_hash(), &blind_sign_request.get_commitment_hash(),
voucher.pedersen_commitments_openings(), attributes.pedersen_commitments_openings(),
)?; )?;
Ok(unblinded_signature) Ok(unblinded_signature)
@@ -67,13 +84,16 @@ async fn obtain_partial_credential(
pub async fn obtain_aggregate_signature( pub async fn obtain_aggregate_signature(
params: &Parameters, params: &Parameters,
voucher: &BandwidthVoucher, attributes: &BandwidthVoucher,
coconut_api_clients: &[CoconutApiClient], coconut_api_clients: &[CoconutApiClient],
threshold: u64, threshold: u64,
) -> Result<Signature, Error> { ) -> Result<Signature, Error> {
if coconut_api_clients.is_empty() { if coconut_api_clients.is_empty() {
return Err(Error::NoValidatorsAvailable); return Err(Error::NoValidatorsAvailable);
} }
let public_attributes = attributes.get_public_attributes();
let private_attributes = attributes.get_private_attributes();
let mut shares = Vec::with_capacity(coconut_api_clients.len()); let mut shares = Vec::with_capacity(coconut_api_clients.len());
let validators_partial_vks: Vec<_> = coconut_api_clients let validators_partial_vks: Vec<_> = coconut_api_clients
.iter() .iter()
@@ -94,7 +114,7 @@ pub async fn obtain_aggregate_signature(
match obtain_partial_credential( match obtain_partial_credential(
params, params,
voucher, attributes,
&coconut_api_client.api_client, &coconut_api_client.api_client,
&coconut_api_client.verification_key, &coconut_api_client.verification_key,
) )
@@ -116,9 +136,6 @@ pub async fn obtain_aggregate_signature(
return Err(Error::NotEnoughShares); return Err(Error::NotEnoughShares);
} }
let public_attributes = voucher.get_public_attributes();
let private_attributes = voucher.get_private_attributes();
let mut attributes = Vec::with_capacity(private_attributes.len() + public_attributes.len()); let mut attributes = Vec::with_capacity(private_attributes.len() + public_attributes.len());
attributes.extend_from_slice(&private_attributes); attributes.extend_from_slice(&private_attributes);
attributes.extend_from_slice(&public_attributes); attributes.extend_from_slice(&public_attributes);
@@ -133,8 +150,8 @@ pub fn prepare_credential_for_spending(
params: &Parameters, params: &Parameters,
voucher_value: u64, voucher_value: u64,
voucher_info: String, voucher_info: String,
serial_number: &Attribute, serial_number: Attribute,
binding_number: &Attribute, binding_number: Attribute,
epoch_id: u64, epoch_id: u64,
signature: &Signature, signature: &Signature,
verification_key: &VerificationKey, verification_key: &VerificationKey,
@@ -148,7 +165,7 @@ pub fn prepare_credential_for_spending(
)?; )?;
Ok(Credential::new( Ok(Credential::new(
BandwidthVoucher::ENCODED_ATTRIBUTES, PUBLIC_ATTRIBUTES + PRIVATE_ATTRIBUTES,
theta, theta,
voucher_value, voucher_value,
voucher_info, voucher_info,
@@ -201,17 +201,6 @@ impl<'a> From<&'a PrivateKey> for PublicKey {
} }
impl PrivateKey { impl PrivateKey {
#[cfg(feature = "rand")]
pub fn new<R: RngCore + CryptoRng>(rng: &mut R) -> Self {
let x25519_secret = x25519_dalek::StaticSecret::new(rng);
PrivateKey(x25519_secret)
}
pub fn public_key(&self) -> PublicKey {
self.into()
}
pub fn to_bytes(&self) -> [u8; PRIVATE_KEY_SIZE] { pub fn to_bytes(&self) -> [u8; PRIVATE_KEY_SIZE] {
self.0.to_bytes() self.0.to_bytes()
} }
+3 -23
View File
@@ -5,14 +5,13 @@ pub use ed25519_dalek::ed25519::signature::Signature as SignatureTrait;
pub use ed25519_dalek::SignatureError; pub use ed25519_dalek::SignatureError;
pub use ed25519_dalek::{Verifier, PUBLIC_KEY_LENGTH, SECRET_KEY_LENGTH, SIGNATURE_LENGTH}; pub use ed25519_dalek::{Verifier, PUBLIC_KEY_LENGTH, SECRET_KEY_LENGTH, SIGNATURE_LENGTH};
use nym_pemstore::traits::{PemStorableKey, PemStorableKeyPair}; use nym_pemstore::traits::{PemStorableKey, PemStorableKeyPair};
#[cfg(feature = "sphinx")]
use nym_sphinx_types::{DestinationAddressBytes, DESTINATION_ADDRESS_LENGTH};
use std::fmt::{self, Display, Formatter}; use std::fmt::{self, Display, Formatter};
use std::str::FromStr; use std::str::FromStr;
use thiserror::Error; use thiserror::Error;
use zeroize::{Zeroize, ZeroizeOnDrop}; use zeroize::{Zeroize, ZeroizeOnDrop};
#[cfg(feature = "sphinx")]
use nym_sphinx_types::{DestinationAddressBytes, DESTINATION_ADDRESS_LENGTH};
#[cfg(feature = "rand")] #[cfg(feature = "rand")]
use rand::{CryptoRng, RngCore}; use rand::{CryptoRng, RngCore};
#[cfg(feature = "serde")] #[cfg(feature = "serde")]
@@ -225,17 +224,6 @@ impl<'a> From<&'a PrivateKey> for PublicKey {
} }
impl PrivateKey { impl PrivateKey {
#[cfg(feature = "rand")]
pub fn new<R: RngCore + CryptoRng>(rng: &mut R) -> Self {
let ed25519_secret = ed25519_dalek::SecretKey::generate(rng);
PrivateKey(ed25519_secret)
}
pub fn public_key(&self) -> PublicKey {
self.into()
}
pub fn to_bytes(&self) -> [u8; SECRET_KEY_LENGTH] { pub fn to_bytes(&self) -> [u8; SECRET_KEY_LENGTH] {
self.0.to_bytes() self.0.to_bytes()
} }
@@ -307,7 +295,7 @@ impl PemStorableKey for PrivateKey {
} }
} }
#[derive(Copy, Clone, Debug, Eq, PartialEq)] #[derive(Copy, Clone, Debug)]
pub struct Signature(ed25519_dalek::Signature); pub struct Signature(ed25519_dalek::Signature);
impl Signature { impl Signature {
@@ -331,14 +319,6 @@ impl Signature {
} }
} }
impl FromStr for Signature {
type Err = Ed25519RecoveryError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Signature::from_base58_string(s)
}
}
#[cfg(feature = "serde")] #[cfg(feature = "serde")]
impl Serialize for Signature { impl Serialize for Signature {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+3 -4
View File
@@ -3,7 +3,6 @@ name = "nym-dkg"
version = "0.1.0" version = "0.1.0"
edition = "2021" edition = "2021"
resolver = "2" resolver = "2"
license.workspace = true
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@@ -12,7 +11,7 @@ bitvec = "1.0.0"
# unfortunately until https://github.com/zkcrypto/bls12_381/issues/10 is resolved, we have to rely on the fork # unfortunately until https://github.com/zkcrypto/bls12_381/issues/10 is resolved, we have to rely on the fork
# as we need to be able to serialize Gt so that we could create the lookup table for baby-step-giant-step algorithm # as we need to be able to serialize Gt so that we could create the lookup table for baby-step-giant-step algorithm
bls12_381 = { workspace = true, default-features = false, features = ["alloc", "pairings", "experimental", "zeroize"] } bls12_381 = { git = "https://github.com/jstuczyn/bls12_381", branch ="gt-serialisation", default-features = false, features = ["alloc", "pairings", "experimental", "zeroize"] }
nym-contracts-common = { path = "../cosmwasm-smart-contracts/contracts-common", optional = true } nym-contracts-common = { path = "../cosmwasm-smart-contracts/contracts-common", optional = true }
bs58 = "0.4" bs58 = "0.4"
@@ -30,11 +29,11 @@ zeroize = { workspace = true, features = ["zeroize_derive"] }
nym-pemstore = { path = "../pemstore" } nym-pemstore = { path = "../pemstore" }
[dependencies.group] [dependencies.group]
workspace = true version = "0.11"
default-features = false default-features = false
[dependencies.ff] [dependencies.ff]
workspace = true version = "0.11"
default-features = false default-features = false
[dev-dependencies] [dev-dependencies]
-1
View File
@@ -2,7 +2,6 @@
name = "nym-execute" name = "nym-execute"
version = "0.1.0" version = "0.1.0"
edition = "2021" edition = "2021"
license.workspace = true
[lib] [lib]
proc-macro = true proc-macro = true
-63
View File
@@ -81,15 +81,6 @@ ExitPolicy accept6 *6:119
ExitPolicy accept *4:120 ExitPolicy accept *4:120
ExitPolicy reject6 [FC00::]/7:* ExitPolicy reject6 [FC00::]/7:*
# Portless
ExitPolicy accept *:0
ExitPolicy accept *4:0
ExitPolicy accept *6:0
ExitPolicy reject *:0
ExitPolicy reject *4:0
ExitPolicy reject *6:0
#ExitPolicy accept *:8080 #and another comment here #ExitPolicy accept *:8080 #and another comment here
ExitPolicy reject FE80:0000:0000:0000:0202:B3FF:FE1E:8329:* ExitPolicy reject FE80:0000:0000:0000:0202:B3FF:FE1E:8329:*
@@ -193,60 +184,6 @@ ExitPolicy reject *:*
}, },
); );
// ExitPolicy accept *:0
expected.push(
Accept,
AddressPortPattern {
ip_pattern: IpPattern::Star,
ports: PortRange::new_zero(),
},
);
// ExitPolicy accept *4:0
expected.push(
Accept,
AddressPortPattern {
ip_pattern: IpPattern::V4Star,
ports: PortRange::new_zero(),
},
);
// ExitPolicy accept *6:0
expected.push(
Accept,
AddressPortPattern {
ip_pattern: IpPattern::V6Star,
ports: PortRange::new_zero(),
},
);
// ExitPolicy reject *:0
expected.push(
Reject,
AddressPortPattern {
ip_pattern: IpPattern::Star,
ports: PortRange::new_zero(),
},
);
// ExitPolicy reject *4:0
expected.push(
Reject,
AddressPortPattern {
ip_pattern: IpPattern::V4Star,
ports: PortRange::new_zero(),
},
);
// ExitPolicy reject *6:0
expected.push(
Reject,
AddressPortPattern {
ip_pattern: IpPattern::V6Star,
ports: PortRange::new_zero(),
},
);
// ExitPolicy FE80:0000:0000:0000:0202:B3FF:FE1E:8329:* // ExitPolicy FE80:0000:0000:0000:0202:B3FF:FE1E:8329:*
expected.push( expected.push(
Reject, Reject,
+14 -37
View File
@@ -264,13 +264,7 @@ mod stringified_ip_pattern {
impl AddressPortPattern { impl AddressPortPattern {
/// Return true iff this pattern matches a given address and port. /// Return true iff this pattern matches a given address and port.
pub fn matches(&self, addr: &IpAddr, port: u16) -> bool { pub fn matches(&self, addr: &IpAddr, port: u16) -> bool {
// For backward compatibility, we treat port 0 as a wildcard until all gateways have self.ip_pattern.matches(addr) && self.ports.contains(port)
// upgraded, at which point we can add *:0 to the policy list.
if port == 0 {
self.ip_pattern.matches(addr)
} else {
self.ip_pattern.matches(addr) && self.ports.contains(port)
}
} }
/// As matches, but accept a SocketAddr. /// As matches, but accept a SocketAddr.
@@ -401,9 +395,19 @@ fn parse_addr(s: &str) -> Result<IpAddr, PolicyError> {
}) })
} }
/// Helper: try to parse a port making sure it's non-zero
fn parse_port(s: &str) -> Result<u16, PolicyError> { fn parse_port(s: &str) -> Result<u16, PolicyError> {
s.parse::<u16>() let port = s
.map_err(|_| PolicyError::InvalidPort { raw: s.to_string() }) .parse::<u16>()
.map_err(|_| PolicyError::InvalidPort { raw: s.to_string() })?;
if port == 0 {
Err(PolicyError::InvalidPort {
raw: port.to_string(),
})
} else {
Ok(port)
}
} }
impl FromStr for IpPattern { impl FromStr for IpPattern {
@@ -490,10 +494,6 @@ impl PortRange {
PortRange::new_unchecked(1, 65535) PortRange::new_unchecked(1, 65535)
} }
pub fn new_zero() -> Self {
PortRange { start: 0, end: 0 }
}
/// Create a new PortRange. /// Create a new PortRange.
/// ///
/// The Portrange contains all ports between `start` and `end` inclusive. /// The Portrange contains all ports between `start` and `end` inclusive.
@@ -574,7 +574,6 @@ mod test {
check("marzipan:80"); check("marzipan:80");
check("1.2.3.4:90-80"); check("1.2.3.4:90-80");
check("1.2.3.4:0-80");
check("1.2.3.4/100:8888"); check("1.2.3.4/100:8888");
check("[1.2.3.4]/16:80"); check("[1.2.3.4]/16:80");
check("[::1]/130:8888"); check("[::1]/130:8888");
@@ -613,22 +612,6 @@ mod test {
check("0.0.0.0/0:*", &["127.0.0.1:80"], &["[f00b::]:80"]); check("0.0.0.0/0:*", &["127.0.0.1:80"], &["[f00b::]:80"]);
check("[::]/0:*", &["[f00b::]:80"], &["127.0.0.1:80"]); check("[::]/0:*", &["[f00b::]:80"], &["127.0.0.1:80"]);
check(
"*:0",
&["1.2.3.4:0", "[::1]:0", "9.0.0.0:0"],
&["1.2.3.4:443", "[::1]:500", "9.0.0.0:80", "[::1]:80"],
);
check(
"*4:0",
&["1.2.3.4:0", "9.0.0.0:0"],
&["1.2.3.4:443", "9.0.0.0:80", "[::1]:0", "[::1]:80"],
);
check(
"*6:0",
&["[::1]:0"],
&["[::1]:80", "1.2.3.4:0", "1.2.3.4:443"],
);
} }
#[test] #[test]
@@ -637,7 +620,6 @@ mod test {
policy.push(AddressPolicyAction::Accept, "*:443".parse()?); policy.push(AddressPolicyAction::Accept, "*:443".parse()?);
policy.push(AddressPolicyAction::Accept, "[::1]:80".parse()?); policy.push(AddressPolicyAction::Accept, "[::1]:80".parse()?);
policy.push(AddressPolicyAction::Reject, "*:80".parse()?); policy.push(AddressPolicyAction::Reject, "*:80".parse()?);
policy.push(AddressPolicyAction::Accept, "*:0".parse()?);
let policy = policy; // drop mut let policy = policy; // drop mut
assert!(policy assert!(policy
@@ -658,9 +640,6 @@ mod test {
assert!(policy assert!(policy
.allows_sockaddr(&"127.0.0.1:66".parse().unwrap()) .allows_sockaddr(&"127.0.0.1:66".parse().unwrap())
.is_none()); .is_none());
assert!(policy
.allows_sockaddr(&"127.0.0.1:0".parse().unwrap())
.unwrap());
Ok(()) Ok(())
} }
@@ -693,6 +672,7 @@ mod test {
assert_eq!("*".parse::<PortRange>().unwrap(), PortRange::new_all()); assert_eq!("*".parse::<PortRange>().unwrap(), PortRange::new_all());
assert!("hello".parse::<PortRange>().is_err()); assert!("hello".parse::<PortRange>().is_err());
assert!("0".parse::<PortRange>().is_err());
assert!("65536".parse::<PortRange>().is_err()); assert!("65536".parse::<PortRange>().is_err());
assert!("65537".parse::<PortRange>().is_err()); assert!("65537".parse::<PortRange>().is_err());
assert!("1-2-3".parse::<PortRange>().is_err()); assert!("1-2-3".parse::<PortRange>().is_err());
@@ -700,9 +680,6 @@ mod test {
assert!("1-".parse::<PortRange>().is_err()); assert!("1-".parse::<PortRange>().is_err());
assert!("-2".parse::<PortRange>().is_err()); assert!("-2".parse::<PortRange>().is_err());
assert!("-".parse::<PortRange>().is_err()); assert!("-".parse::<PortRange>().is_err());
assert_eq!("0".parse::<PortRange>().unwrap(), PortRange::new_zero(),);
assert!("0-1".parse::<PortRange>().is_err());
} }
#[test] #[test]
+1 -2
View File
@@ -2,7 +2,6 @@
name = "ledger" name = "ledger"
version = "0.1.0" version = "0.1.0"
edition = "2021" edition = "2021"
license.workspace = true
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@@ -11,4 +10,4 @@ bip32 = "0.5.1"
k256 = { workspace = true } k256 = { workspace = true }
ledger-transport = "0.10.0" ledger-transport = "0.10.0"
ledger-transport-hid = "0.10.0" ledger-transport-hid = "0.10.0"
thiserror = { workspace = true } thiserror = { workspace = true }
+1 -2
View File
@@ -3,7 +3,6 @@ name = "nym-mixnode-common"
version = "0.1.0" version = "0.1.0"
authors = ["Jędrzej Stuczyński <andrew@nymtech.net>"] authors = ["Jędrzej Stuczyński <andrew@nymtech.net>"]
edition = "2021" edition = "2021"
license.workspace = true
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@@ -21,7 +20,7 @@ tokio = { version = "1.24.1", features = [
"net", "net",
"io-util", "io-util",
] } ] }
tokio-util = { workspace = true, features = ["codec"] } tokio-util = { version = "0.7.4", features = ["codec"] }
url = { workspace = true } url = { workspace = true }
thiserror = { workspace = true } thiserror = { workspace = true }
+3 -3
View File
@@ -108,13 +108,13 @@ impl ConnectionHandler {
let reply_packet = match maybe_echo_packet { let reply_packet = match maybe_echo_packet {
Some(Ok(echo_packet)) => self.handle_echo_packet(echo_packet), Some(Ok(echo_packet)) => self.handle_echo_packet(echo_packet),
Some(Err(err)) => { Some(Err(err)) => {
debug!( error!(
"The socket connection got corrupted with error: {err}. Closing the socket", "The socket connection got corrupted with error: {err}. Closing the socket",
); );
return; return;
} }
None => { None => {
debug!("The socket connection got terminated by the remote!"); error!("The socket connection got terminated by the remote!");
return; return;
} }
}; };
@@ -125,7 +125,7 @@ impl ConnectionHandler {
.write_all(reply_packet.to_bytes().as_ref()) .write_all(reply_packet.to_bytes().as_ref())
.await .await
{ {
debug!( error!(
"Failed to write reply packet back to the sender - {}. Closing the socket on our end", "Failed to write reply packet back to the sender - {}. Closing the socket on our end",
err err
); );
+1 -13
View File
@@ -111,7 +111,6 @@ impl NymNetworkDetails {
.with_additional_validator_endpoint(ValidatorDetails::new( .with_additional_validator_endpoint(ValidatorDetails::new(
var(var_names::NYXD).expect("nyxd validator not set"), var(var_names::NYXD).expect("nyxd validator not set"),
Some(var(var_names::NYM_API).expect("nym api not set")), Some(var(var_names::NYM_API).expect("nym api not set")),
get_optional_env(var_names::NYXD_WEBSOCKET),
)) ))
.with_mixnet_contract(Some( .with_mixnet_contract(Some(
var(var_names::MIXNET_CONTRACT_ADDRESS).expect("mixnet contract not set"), var(var_names::MIXNET_CONTRACT_ADDRESS).expect("mixnet contract not set"),
@@ -341,9 +340,6 @@ impl DenomDetailsOwned {
pub struct ValidatorDetails { pub struct ValidatorDetails {
// it is assumed those values are always valid since they're being provided in our defaults file // it is assumed those values are always valid since they're being provided in our defaults file
pub nyxd_url: String, pub nyxd_url: String,
//
pub websocket_url: Option<String>,
// Right now api_url is optional as we are not running the api reliably on all validators // Right now api_url is optional as we are not running the api reliably on all validators
// however, later on it should be a mandatory field // however, later on it should be a mandatory field
pub api_url: Option<String>, pub api_url: Option<String>,
@@ -351,10 +347,9 @@ pub struct ValidatorDetails {
} }
impl ValidatorDetails { impl ValidatorDetails {
pub fn new<S: Into<String>>(nyxd_url: S, api_url: Option<S>, websocket_url: Option<S>) -> Self { pub fn new<S: Into<String>>(nyxd_url: S, api_url: Option<S>) -> Self {
ValidatorDetails { ValidatorDetails {
nyxd_url: nyxd_url.into(), nyxd_url: nyxd_url.into(),
websocket_url: websocket_url.map(Into::into),
api_url: api_url.map(Into::into), api_url: api_url.map(Into::into),
} }
} }
@@ -362,7 +357,6 @@ impl ValidatorDetails {
pub fn new_nyxd_only<S: Into<String>>(nyxd_url: S) -> Self { pub fn new_nyxd_only<S: Into<String>>(nyxd_url: S) -> Self {
ValidatorDetails { ValidatorDetails {
nyxd_url: nyxd_url.into(), nyxd_url: nyxd_url.into(),
websocket_url: None,
api_url: None, api_url: None,
} }
} }
@@ -378,12 +372,6 @@ impl ValidatorDetails {
.as_ref() .as_ref()
.map(|url| url.parse().expect("the provided api url is invalid!")) .map(|url| url.parse().expect("the provided api url is invalid!"))
} }
pub fn websocket_url(&self) -> Option<Url> {
self.websocket_url
.as_ref()
.map(|url| url.parse().expect("the provided websocket url is invalid!"))
}
} }
fn fix_deprecated_environmental_variables() { fn fix_deprecated_environmental_variables() {
+1 -15
View File
@@ -3,7 +3,6 @@
use crate::var_names; use crate::var_names;
use crate::{DenomDetails, ValidatorDetails}; use crate::{DenomDetails, ValidatorDetails};
use std::str::FromStr;
pub const NETWORK_NAME: &str = "mainnet"; pub const NETWORK_NAME: &str = "mainnet";
@@ -26,7 +25,6 @@ pub const REWARDING_VALIDATOR_ADDRESS: &str = "n10yyd98e2tuwu0f7ypz9dy3hhjw7v772
pub 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 NYXD_URL: &str = "https://rpc.nymtech.net"; pub const NYXD_URL: &str = "https://rpc.nymtech.net";
pub const NYM_API: &str = "https://validator.nymtech.net/api/"; pub const NYM_API: &str = "https://validator.nymtech.net/api/";
pub const NYXD_WS: &str = "wss://rpc.nymtech.net/websocket";
pub const EXPLORER_API: &str = "https://explorer.nymtech.net/api/"; pub const EXPLORER_API: &str = "https://explorer.nymtech.net/api/";
// I'm making clippy mad on purpose, because that url HAS TO be updated and deployed before merging // I'm making clippy mad on purpose, because that url HAS TO be updated and deployed before merging
@@ -34,11 +32,7 @@ pub const EXIT_POLICY_URL: &str =
"https://nymtech.net/.wellknown/network-requester/exit-policy.txt"; "https://nymtech.net/.wellknown/network-requester/exit-policy.txt";
pub(crate) fn validators() -> Vec<ValidatorDetails> { pub(crate) fn validators() -> Vec<ValidatorDetails> {
vec![ValidatorDetails::new( vec![ValidatorDetails::new(NYXD_URL, Some(NYM_API))]
NYXD_URL,
Some(NYM_API),
Some(NYXD_WS),
)]
} }
const DEFAULT_SUFFIX: &str = "_MAINNET_DEFAULT"; const DEFAULT_SUFFIX: &str = "_MAINNET_DEFAULT";
@@ -66,12 +60,6 @@ pub fn read_var_if_not_default(var: &str) -> Option<String> {
} }
} }
pub fn read_parsed_var_if_not_default<T: FromStr>(var: &str) -> Option<Result<T, T::Err>> {
read_var_if_not_default(var)
.as_deref()
.map(FromStr::from_str)
}
pub fn export_to_env() { pub fn export_to_env() {
set_var_to_default(var_names::CONFIGURED, "true"); set_var_to_default(var_names::CONFIGURED, "true");
set_var_to_default(var_names::NETWORK_NAME, NETWORK_NAME); set_var_to_default(var_names::NETWORK_NAME, NETWORK_NAME);
@@ -116,7 +104,6 @@ pub fn export_to_env() {
); );
set_var_to_default(var_names::NYXD, NYXD_URL); set_var_to_default(var_names::NYXD, NYXD_URL);
set_var_to_default(var_names::NYM_API, NYM_API); set_var_to_default(var_names::NYM_API, NYM_API);
set_var_to_default(var_names::NYXD_WEBSOCKET, NYXD_WS);
set_var_to_default(var_names::EXPLORER_API, EXPLORER_API); set_var_to_default(var_names::EXPLORER_API, EXPLORER_API);
set_var_to_default(var_names::EXIT_POLICY_URL, EXIT_POLICY_URL); set_var_to_default(var_names::EXIT_POLICY_URL, EXIT_POLICY_URL);
} }
@@ -165,7 +152,6 @@ pub fn export_to_env_if_not_set() {
); );
set_var_conditionally_to_default(var_names::NYXD, NYXD_URL); set_var_conditionally_to_default(var_names::NYXD, NYXD_URL);
set_var_conditionally_to_default(var_names::NYM_API, NYM_API); set_var_conditionally_to_default(var_names::NYM_API, NYM_API);
set_var_conditionally_to_default(var_names::NYXD_WEBSOCKET, NYXD_WS);
set_var_conditionally_to_default(var_names::EXPLORER_API, EXPLORER_API); set_var_conditionally_to_default(var_names::EXPLORER_API, EXPLORER_API);
set_var_conditionally_to_default(var_names::EXIT_POLICY_URL, EXIT_POLICY_URL); set_var_conditionally_to_default(var_names::EXIT_POLICY_URL, EXIT_POLICY_URL);
} }
-1
View File
@@ -26,7 +26,6 @@ pub const SERVICE_PROVIDER_DIRECTORY_CONTRACT_ADDRESS: &str =
pub const NAME_SERVICE_CONTRACT_ADDRESS: &str = "NAME_SERVICE_CONTRACT_ADDRESS"; pub const NAME_SERVICE_CONTRACT_ADDRESS: &str = "NAME_SERVICE_CONTRACT_ADDRESS";
pub const NYXD: &str = "NYXD"; pub const NYXD: &str = "NYXD";
pub const NYM_API: &str = "NYM_API"; pub const NYM_API: &str = "NYM_API";
pub const NYXD_WEBSOCKET: &str = "NYXD_WS";
pub const EXPLORER_API: &str = "EXPLORER_API"; pub const EXPLORER_API: &str = "EXPLORER_API";
pub const EXIT_POLICY_URL: &str = "EXIT_POLICY"; pub const EXIT_POLICY_URL: &str = "EXIT_POLICY";
-1
View File
@@ -2,7 +2,6 @@
name = "nym-node-tester-utils" name = "nym-node-tester-utils"
version = "0.1.0" version = "0.1.0"
edition = "2021" edition = "2021"
license.workspace = true
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@@ -3,7 +3,6 @@ name = "nym-nonexhaustive-delayqueue"
version = "0.1.0" version = "0.1.0"
authors = ["Jędrzej Stuczyński <andrew@nymtech.net>"] authors = ["Jędrzej Stuczyński <andrew@nymtech.net>"]
edition = "2021" edition = "2021"
license.workspace = true
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+3 -7
View File
@@ -3,12 +3,11 @@ name = "nym-coconut"
version = "0.5.0" version = "0.5.0"
authors = ["Jedrzej Stuczynski <andrew@nymtech.net>", "Ania Piotrowska <ania@nymtech.net>"] authors = ["Jedrzej Stuczynski <andrew@nymtech.net>", "Ania Piotrowska <ania@nymtech.net>"]
edition = "2021" edition = "2021"
license.workspace = true
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
bls12_381 = { workspace = true, default-features = false, features = ["pairings", "alloc", "experimental"] } bls12_381 = { git = "https://github.com/jstuczyn/bls12_381", branch ="gt-serialisation", default-features = false, features = ["pairings", "alloc", "experimental"] }
itertools = "0.10" itertools = "0.10"
digest = "0.9" digest = "0.9"
rand = "0.8" rand = "0.8"
@@ -17,17 +16,16 @@ serde = { workspace = true }
serde_derive = "1.0" serde_derive = "1.0"
bs58 = "0.4.0" bs58 = "0.4.0"
sha2 = "0.9" sha2 = "0.9"
zeroize = { workspace = true, optional = true }
nym-dkg = { path = "../dkg" } nym-dkg = { path = "../dkg" }
nym-pemstore = { path = "../pemstore" } nym-pemstore = { path = "../pemstore" }
[dependencies.ff] [dependencies.ff]
workspace = true version = "0.11"
default-features = false default-features = false
[dependencies.group] [dependencies.group]
workspace = true version = "0.11"
default-features = false default-features = false
[dev-dependencies] [dev-dependencies]
@@ -40,9 +38,7 @@ name = "benchmarks"
harness = false harness = false
[features] [features]
key-zeroize = ["zeroize", "bls12_381/zeroize"]
default = [] default = []
[target.'cfg(target_env = "wasm32-unknown-unknown")'.dependencies] [target.'cfg(target_env = "wasm32-unknown-unknown")'.dependencies]
getrandom = { version="0.2", features=["js"] } getrandom = { version="0.2", features=["js"] }
+14 -14
View File
@@ -7,7 +7,7 @@ use ff::Field;
use group::{Curve, Group}; use group::{Curve, Group};
use nym_coconut::{ use nym_coconut::{
aggregate_signature_shares, aggregate_verification_keys, blind_sign, prepare_blind_sign, aggregate_signature_shares, aggregate_verification_keys, blind_sign, prepare_blind_sign,
prove_bandwidth_credential, random_scalars_refs, setup, ttp_keygen, verify_credential, prove_bandwidth_credential, setup, ttp_keygen, verify_credential,
verify_partial_blind_signature, Attribute, BlindedSignature, Parameters, Signature, verify_partial_blind_signature, Attribute, BlindedSignature, Parameters, Signature,
SignatureShare, VerificationKey, SignatureShare, VerificationKey,
}; };
@@ -66,8 +66,8 @@ fn unblind_and_aggregate(
params: &Parameters, params: &Parameters,
blinded_signatures: &[BlindedSignature], blinded_signatures: &[BlindedSignature],
partial_verification_keys: &[VerificationKey], partial_verification_keys: &[VerificationKey],
private_attributes: &[&Attribute], private_attributes: &[Attribute],
public_attributes: &[&Attribute], public_attributes: &[Attribute],
commitment_hash: &G1Projective, commitment_hash: &G1Projective,
pedersen_commitments_openings: &[Scalar], pedersen_commitments_openings: &[Scalar],
verification_key: &VerificationKey, verification_key: &VerificationKey,
@@ -78,7 +78,7 @@ fn unblind_and_aggregate(
.zip(partial_verification_keys.iter()) .zip(partial_verification_keys.iter())
.map(|(signature, partial_verification_key)| { .map(|(signature, partial_verification_key)| {
signature signature
.unblind_and_verify( .unblind(
params, params,
partial_verification_key, partial_verification_key,
private_attributes, private_attributes,
@@ -171,10 +171,10 @@ fn bench_coconut(c: &mut Criterion) {
let params = setup(case.num_public_attrs + case.num_private_attrs).unwrap(); let params = setup(case.num_public_attrs + case.num_private_attrs).unwrap();
random_scalars_refs!(public_attributes, params, case.num_public_attrs as usize); let public_attributes = params.n_random_scalars(case.num_public_attrs as usize);
let serial_number = params.random_scalar(); let serial_number = params.random_scalar();
let binding_number = params.random_scalar(); let binding_number = params.random_scalar();
let private_attributes = vec![&serial_number, &binding_number]; let private_attributes = vec![serial_number, binding_number];
// The prepare blind sign is performed by the user // The prepare blind sign is performed by the user
let (pedersen_commitments_openings, blind_sign_request) = let (pedersen_commitments_openings, blind_sign_request) =
@@ -213,7 +213,7 @@ fn bench_coconut(c: &mut Criterion) {
b.iter(|| { b.iter(|| {
blind_sign( blind_sign(
&params, &params,
keypair.secret_key(), &keypair.secret_key(),
&blind_sign_request, &blind_sign_request,
&public_attributes, &public_attributes,
) )
@@ -228,7 +228,7 @@ fn bench_coconut(c: &mut Criterion) {
for keypair in coconut_keypairs.iter() { for keypair in coconut_keypairs.iter() {
let blinded_signature = blind_sign( let blinded_signature = blind_sign(
&params, &params,
keypair.secret_key(), &keypair.secret_key(),
&blind_sign_request, &blind_sign_request,
&public_attributes, &public_attributes,
) )
@@ -238,7 +238,7 @@ fn bench_coconut(c: &mut Criterion) {
let verification_keys: Vec<VerificationKey> = coconut_keypairs let verification_keys: Vec<VerificationKey> = coconut_keypairs
.iter() .iter()
.map(|keypair| keypair.verification_key().clone()) .map(|keypair| keypair.verification_key())
.collect(); .collect();
// verify a random partial blind signature // verify a random partial blind signature
@@ -255,7 +255,7 @@ fn bench_coconut(c: &mut Criterion) {
b.iter(|| { b.iter(|| {
verify_partial_blind_signature( verify_partial_blind_signature(
&params, &params,
blind_sign_request.get_private_attributes_pedersen_commitments(), &blind_sign_request,
&public_attributes, &public_attributes,
random_blind_signature, random_blind_signature,
partial_verification_key, partial_verification_key,
@@ -310,8 +310,8 @@ fn bench_coconut(c: &mut Criterion) {
&params, &params,
&aggr_verification_key, &aggr_verification_key,
&aggregated_signature, &aggregated_signature,
&serial_number, serial_number,
&binding_number, binding_number,
) )
.unwrap(); .unwrap();
@@ -329,8 +329,8 @@ fn bench_coconut(c: &mut Criterion) {
&params, &params,
&aggr_verification_key, &aggr_verification_key,
&aggregated_signature, &aggregated_signature,
&serial_number, serial_number,
&binding_number, binding_number,
) )
.unwrap() .unwrap()
}) })
+13 -34
View File
@@ -34,10 +34,7 @@ impl TryFrom<&[u8]> for Ciphertext {
))); )));
} }
// safety: we just checked for the length so the unwraps are fine
#[allow(clippy::unwrap_used)]
let c1_bytes: &[u8; 48] = &bytes[..48].try_into().unwrap(); let c1_bytes: &[u8; 48] = &bytes[..48].try_into().unwrap();
#[allow(clippy::unwrap_used)]
let c2_bytes: &[u8; 48] = &bytes[48..].try_into().unwrap(); let c2_bytes: &[u8; 48] = &bytes[48..].try_into().unwrap();
let c1 = try_deserialize_g1_projective( let c1 = try_deserialize_g1_projective(
@@ -115,16 +112,7 @@ impl Bytable for PrivateKey {
} }
fn try_from_byte_slice(slice: &[u8]) -> Result<Self> { fn try_from_byte_slice(slice: &[u8]) -> Result<Self> {
let received = slice.len(); PrivateKey::from_bytes(slice.try_into().unwrap())
let Ok(arr) = slice.try_into() else {
return Err(CoconutError::UnexpectedArrayLength {
typ: "elgamal::PrivateKey".to_string(),
received,
expected: 32,
});
};
PrivateKey::from_bytes(arr)
} }
} }
@@ -157,36 +145,21 @@ impl PublicKey {
} }
pub fn to_bytes(&self) -> [u8; 48] { pub fn to_bytes(&self) -> [u8; 48] {
self.0.to_affine().to_compressed() self.to_byte_vec().try_into().unwrap()
} }
pub fn from_bytes(bytes: &[u8; 48]) -> Result<PublicKey> { pub fn from_bytes(bytes: &[u8; 48]) -> Result<PublicKey> {
try_deserialize_g1_projective( Ok(PublicKey::try_from(bytes.to_vec().as_slice()).unwrap())
bytes,
CoconutError::Deserialization(
"Failed to deserialize compressed ElGamal public key".to_string(),
),
)
.map(PublicKey)
} }
} }
impl Bytable for PublicKey { impl Bytable for PublicKey {
fn to_byte_vec(&self) -> Vec<u8> { fn to_byte_vec(&self) -> Vec<u8> {
self.to_bytes().into() self.0.to_affine().to_compressed().into()
} }
fn try_from_byte_slice(slice: &[u8]) -> Result<Self> { fn try_from_byte_slice(slice: &[u8]) -> Result<Self> {
let received = slice.len(); Ok(PublicKey::from_bytes(slice.try_into().unwrap()).unwrap())
let Ok(arr) = slice.try_into() else {
return Err(CoconutError::UnexpectedArrayLength {
typ: "elgamal::PublicKey".to_string(),
received,
expected: 48,
});
};
PublicKey::from_bytes(arr)
} }
} }
@@ -194,7 +167,13 @@ impl TryFrom<&[u8]> for PublicKey {
type Error = CoconutError; type Error = CoconutError;
fn try_from(slice: &[u8]) -> Result<PublicKey> { fn try_from(slice: &[u8]) -> Result<PublicKey> {
PublicKey::try_from_byte_slice(slice) try_deserialize_g1_projective(
slice.try_into().unwrap(),
CoconutError::Deserialization(
"Failed to deserialize compressed ElGamal public key".to_string(),
),
)
.map(PublicKey)
} }
} }
@@ -246,7 +225,7 @@ pub fn elgamal_keygen(params: &Parameters) -> ElGamalKeyPair {
pub fn compute_attribute_encryption( pub fn compute_attribute_encryption(
params: &Parameters, params: &Parameters,
private_attributes: &[&Attribute], private_attributes: &[Attribute],
pub_key: &PublicKey, pub_key: &PublicKey,
commitment_hash: G1Projective, commitment_hash: G1Projective,
) -> (Vec<Ciphertext>, Vec<EphemeralKey>) { ) -> (Vec<Ciphertext>, Vec<EphemeralKey>) {
-16
View File
@@ -50,20 +50,4 @@ pub enum CoconutError {
modulus: usize, modulus: usize,
object: String, object: String,
}, },
#[error("received an array of unexpected size for deserialization of {typ}. got {received} but expected {expected}")]
UnexpectedArrayLength {
typ: String,
received: usize,
expected: usize,
},
#[error("failed to decode the base58 representation: {0}")]
Base58DecodingFailure(#[from] bs58::decode::Error),
#[error("failed to deserialize scalar from the received bytes - it might not have been canonically encoded")]
ScalarDeserializationFailure,
#[error("failed to deserialize G1Projective point from the received bytes - it might not have been canonically encoded")]
G1ProjectiveDeserializationFailure,
} }
+16 -5
View File
@@ -1,9 +1,11 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net> // Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
#![warn(clippy::expect_used)] use std::convert::TryInto;
#![warn(clippy::unwrap_used)]
use bls12_381::Scalar;
pub use crate::traits::Bytable;
pub use elgamal::elgamal_keygen; pub use elgamal::elgamal_keygen;
pub use elgamal::ElGamalKeyPair; pub use elgamal::ElGamalKeyPair;
pub use elgamal::PublicKey; pub use elgamal::PublicKey;
@@ -28,7 +30,6 @@ pub use scheme::BlindedSignature;
pub use scheme::Signature; pub use scheme::Signature;
pub use scheme::SignatureShare; pub use scheme::SignatureShare;
pub use traits::Base58; pub use traits::Base58;
pub use traits::Bytable;
pub use utils::hash_to_scalar; pub use utils::hash_to_scalar;
pub mod elgamal; pub mod elgamal;
@@ -40,8 +41,18 @@ pub mod tests;
mod traits; mod traits;
mod utils; mod utils;
pub type Attribute = bls12_381::Scalar; pub type Attribute = Scalar;
pub type PrivateAttribute = Attribute; pub type PrivateAttribute = Attribute;
pub type PublicAttribute = Attribute; pub type PublicAttribute = Attribute;
pub use bls12_381::G1Projective; impl Bytable for Attribute {
fn to_byte_vec(&self) -> Vec<u8> {
self.to_bytes().to_vec()
}
fn try_from_byte_slice(slice: &[u8]) -> Result<Self, CoconutError> {
Ok(Attribute::from_bytes(slice.try_into().unwrap()).unwrap())
}
}
impl Base58 for Attribute {}
+26 -38
View File
@@ -91,8 +91,8 @@ impl ProofCmCs {
commitment_opening: &Scalar, commitment_opening: &Scalar,
commitments: &[G1Projective], commitments: &[G1Projective],
pedersen_commitments_openings: &[Scalar], pedersen_commitments_openings: &[Scalar],
private_attributes: &[&Attribute], private_attributes: &[Attribute],
public_attributes: &[&Attribute], public_attributes: &[Attribute],
) -> Self { ) -> Self {
// note: this is only called from `prepare_blind_sign` that already checks // note: this is only called from `prepare_blind_sign` that already checks
// whether private attributes are non-empty and whether we don't have too many // whether private attributes are non-empty and whether we don't have too many
@@ -162,8 +162,11 @@ impl ProofCmCs {
&challenge, &challenge,
&pedersen_commitments_openings.iter().collect::<Vec<_>>(), &pedersen_commitments_openings.iter().collect::<Vec<_>>(),
); );
let response_attributes = let response_attributes = produce_responses(
produce_responses(&witness_attributes, &challenge, private_attributes); &witness_attributes,
&challenge,
&private_attributes.iter().collect::<Vec<_>>(),
);
ProofCmCs { ProofCmCs {
challenge, challenge,
@@ -178,7 +181,7 @@ impl ProofCmCs {
params: &Parameters, params: &Parameters,
commitment: &G1Projective, commitment: &G1Projective,
commitments: &[G1Projective], commitments: &[G1Projective],
public_attributes: &[&Attribute], public_attributes: &[Attribute],
) -> bool { ) -> bool {
if self.response_attributes.len() != commitments.len() { if self.response_attributes.len() != commitments.len() {
return false; return false;
@@ -200,7 +203,7 @@ impl ProofCmCs {
- public_attributes - public_attributes
.iter() .iter()
.zip(params.gen_hs().iter().skip(self.response_attributes.len())) .zip(params.gen_hs().iter().skip(self.response_attributes.len()))
.map(|(&pub_attr, hs)| hs * pub_attr) .map(|(pub_attr, hs)| hs * pub_attr)
.sum::<G1Projective>()) .sum::<G1Projective>())
* self.challenge * self.challenge
+ g1 * self.response_opening + g1 * self.response_opening
@@ -277,12 +280,8 @@ impl ProofCmCs {
} }
let mut idx = 0; let mut idx = 0;
// safety: bound checked + constant offset
#[allow(clippy::unwrap_used)]
let challenge_bytes = bytes[idx..idx + 32].try_into().unwrap(); let challenge_bytes = bytes[idx..idx + 32].try_into().unwrap();
idx += 32; idx += 32;
// safety: bound checked + constant offset
#[allow(clippy::unwrap_used)]
let response_opening_bytes = bytes[idx..idx + 32].try_into().unwrap(); let response_opening_bytes = bytes[idx..idx + 32].try_into().unwrap();
idx += 32; idx += 32;
@@ -298,8 +297,6 @@ impl ProofCmCs {
), ),
)?; )?;
// safety: bound checked + constant offset
#[allow(clippy::unwrap_used)]
let ro_len = u64::from_le_bytes(bytes[idx..idx + 8].try_into().unwrap()); let ro_len = u64::from_le_bytes(bytes[idx..idx + 8].try_into().unwrap());
idx += 8; idx += 8;
if bytes[idx..].len() < ro_len as usize * 32 + 8 { if bytes[idx..].len() < ro_len as usize * 32 + 8 {
@@ -316,8 +313,6 @@ impl ProofCmCs {
CoconutError::Deserialization("Failed to deserialize openings response".to_string()), CoconutError::Deserialization("Failed to deserialize openings response".to_string()),
)?; )?;
// safety: bound checked + constant offset
#[allow(clippy::unwrap_used)]
let rm_len = u64::from_le_bytes(bytes[ro_end..ro_end + 8].try_into().unwrap()); let rm_len = u64::from_le_bytes(bytes[ro_end..ro_end + 8].try_into().unwrap());
let response_attributes = try_deserialize_scalar_vec( let response_attributes = try_deserialize_scalar_vec(
rm_len, rm_len,
@@ -467,7 +462,7 @@ impl ProofKappaZeta {
pub(crate) fn from_bytes(bytes: &[u8]) -> Result<Self> { pub(crate) fn from_bytes(bytes: &[u8]) -> Result<Self> {
// at the very minimum there must be a single attribute being proven // at the very minimum there must be a single attribute being proven
if bytes.len() != 128 { if bytes.len() < 32 * 4 || (bytes.len()) % 32 != 0 {
return Err(CoconutError::DeserializationInvalidLength { return Err(CoconutError::DeserializationInvalidLength {
actual: bytes.len(), actual: bytes.len(),
modulus_target: bytes.len(), modulus_target: bytes.len(),
@@ -477,32 +472,24 @@ impl ProofKappaZeta {
}); });
} }
// safety: bound checked + constant offset
#[allow(clippy::unwrap_used)]
let challenge_bytes = bytes[..32].try_into().unwrap(); let challenge_bytes = bytes[..32].try_into().unwrap();
let challenge = try_deserialize_scalar( let challenge = try_deserialize_scalar(
&challenge_bytes, &challenge_bytes,
CoconutError::Deserialization("Failed to deserialize challenge".to_string()), CoconutError::Deserialization("Failed to deserialize challenge".to_string()),
)?; )?;
// safety: bound checked + constant offset
#[allow(clippy::unwrap_used)]
let serial_number_bytes = &bytes[32..64].try_into().unwrap(); let serial_number_bytes = &bytes[32..64].try_into().unwrap();
let response_serial_number = try_deserialize_scalar( let response_serial_number = try_deserialize_scalar(
serial_number_bytes, serial_number_bytes,
CoconutError::Deserialization("failed to deserialize the serial number".to_string()), CoconutError::Deserialization("failed to deserialize the serial number".to_string()),
)?; )?;
// safety: bound checked + constant offset
#[allow(clippy::unwrap_used)]
let binding_number_bytes = &bytes[64..96].try_into().unwrap(); let binding_number_bytes = &bytes[64..96].try_into().unwrap();
let response_binding_number = try_deserialize_scalar( let response_binding_number = try_deserialize_scalar(
binding_number_bytes, binding_number_bytes,
CoconutError::Deserialization("failed to deserialize the binding number".to_string()), CoconutError::Deserialization("failed to deserialize the binding number".to_string()),
)?; )?;
// safety: bound checked + constant offset
#[allow(clippy::unwrap_used)]
let blinder_bytes = bytes[96..].try_into().unwrap(); let blinder_bytes = bytes[96..].try_into().unwrap();
let response_blinder = try_deserialize_scalar( let response_blinder = try_deserialize_scalar(
&blinder_bytes, &blinder_bytes,
@@ -525,13 +512,14 @@ impl ProofKappaZeta {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use group::Group;
use rand::thread_rng;
use crate::scheme::keygen::keygen; use crate::scheme::keygen::keygen;
use crate::scheme::setup::setup; use crate::scheme::setup::setup;
use crate::scheme::verification::{compute_kappa, compute_zeta}; use crate::scheme::verification::{compute_kappa, compute_zeta};
use crate::tests::helpers::random_scalars_refs;
use group::Group; use super::*;
use rand::thread_rng;
#[test] #[test]
fn proof_cm_cs_bytes_roundtrip() { fn proof_cm_cs_bytes_roundtrip() {
@@ -542,7 +530,7 @@ mod tests {
let r = params.random_scalar(); let r = params.random_scalar();
let cms: [G1Projective; 1] = [G1Projective::random(&mut rng)]; let cms: [G1Projective; 1] = [G1Projective::random(&mut rng)];
let rs = params.n_random_scalars(1); let rs = params.n_random_scalars(1);
random_scalars_refs!(private_attributes, params, 1); let private_attributes = params.n_random_scalars(1);
// 0 public 1 private // 0 public 1 private
let pi_s = ProofCmCs::construct(&params, &cm, &r, &cms, &rs, &private_attributes, &[]); let pi_s = ProofCmCs::construct(&params, &cm, &r, &cms, &rs, &private_attributes, &[]);
@@ -558,7 +546,7 @@ mod tests {
G1Projective::random(&mut rng), G1Projective::random(&mut rng),
]; ];
let rs = params.n_random_scalars(2); let rs = params.n_random_scalars(2);
random_scalars_refs!(private_attributes, params, 2); let private_attributes = params.n_random_scalars(2);
// 0 public 2 privates // 0 public 2 privates
let pi_s = ProofCmCs::construct(&params, &cm, &r, &cms, &rs, &private_attributes, &[]); let pi_s = ProofCmCs::construct(&params, &cm, &r, &cms, &rs, &private_attributes, &[]);
@@ -574,20 +562,20 @@ mod tests {
let keypair = keygen(&params); let keypair = keygen(&params);
// we don't care about 'correctness' of the proof. only whether we can correctly recover it from bytes // we don't care about 'correctness' of the proof. only whether we can correctly recover it from bytes
let serial_number = &params.random_scalar(); let serial_number = params.random_scalar();
let binding_number = &params.random_scalar(); let binding_number = params.random_scalar();
let private_attributes = vec![serial_number, binding_number]; let private_attributes = vec![serial_number, binding_number];
let r = params.random_scalar(); let r = params.random_scalar();
let kappa = compute_kappa(&params, keypair.verification_key(), &private_attributes, r); let kappa = compute_kappa(&params, &keypair.verification_key(), &private_attributes, r);
let zeta = compute_zeta(&params, serial_number); let zeta = compute_zeta(&params, serial_number);
// 0 public 2 private // 0 public 2 private
let pi_v = ProofKappaZeta::construct( let pi_v = ProofKappaZeta::construct(
&params, &params,
keypair.verification_key(), &keypair.verification_key(),
serial_number, &serial_number,
binding_number, &binding_number,
&r, &r,
&kappa, &kappa,
&zeta, &zeta,
@@ -604,9 +592,9 @@ mod tests {
let pi_v = ProofKappaZeta::construct( let pi_v = ProofKappaZeta::construct(
&params, &params,
keypair.verification_key(), &keypair.verification_key(),
serial_number, &serial_number,
binding_number, &binding_number,
&r, &r,
&kappa, &kappa,
&zeta, &zeta,
+15 -35
View File
@@ -83,7 +83,7 @@ pub fn aggregate_verification_keys(
pub fn aggregate_signatures( pub fn aggregate_signatures(
params: &Parameters, params: &Parameters,
verification_key: &VerificationKey, verification_key: &VerificationKey,
attributes: &[&Attribute], attributes: &[Attribute],
signatures: &[PartialSignature], signatures: &[PartialSignature],
indices: Option<&[SignerIndex]>, indices: Option<&[SignerIndex]>,
) -> Result<Signature> { ) -> Result<Signature> {
@@ -100,7 +100,7 @@ pub fn aggregate_signatures(
let tmp = attributes let tmp = attributes
.iter() .iter()
.zip(verification_key.beta_g2.iter()) .zip(verification_key.beta_g2.iter())
.map(|(&attr, beta_i)| beta_i * attr) .map(|(attr, beta_i)| beta_i * attr)
.sum::<G2Projective>(); .sum::<G2Projective>();
if !check_bilinear_pairing( if !check_bilinear_pairing(
@@ -119,7 +119,7 @@ pub fn aggregate_signatures(
pub fn aggregate_signature_shares( pub fn aggregate_signature_shares(
params: &Parameters, params: &Parameters,
verification_key: &VerificationKey, verification_key: &VerificationKey,
attributes: &[&Attribute], attributes: &[Attribute],
shares: &[SignatureShare], shares: &[SignatureShare],
) -> Result<Signature> { ) -> Result<Signature> {
let (signatures, indices): (Vec<_>, Vec<_>) = shares let (signatures, indices): (Vec<_>, Vec<_>) = shares
@@ -138,13 +138,13 @@ pub fn aggregate_signature_shares(
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use bls12_381::G1Projective;
use group::Group;
use crate::scheme::issuance::sign; use crate::scheme::issuance::sign;
use crate::scheme::keygen::ttp_keygen; use crate::scheme::keygen::ttp_keygen;
use crate::scheme::setup::Parameters; use crate::scheme::setup::Parameters;
use crate::scheme::verification::verify; use crate::scheme::verification::verify;
use crate::tests::helpers::random_scalars_refs;
use bls12_381::G1Projective;
use group::Group;
use super::*; use super::*;
@@ -155,7 +155,7 @@ mod tests {
let vks = keypairs let vks = keypairs
.into_iter() .into_iter()
.map(|keypair| keypair.verification_key().clone()) .map(|keypair| keypair.verification_key())
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let aggr_vk1 = aggregate_verification_keys(&vks[..3], Some(&[1, 2, 3])).unwrap(); let aggr_vk1 = aggregate_verification_keys(&vks[..3], Some(&[1, 2, 3])).unwrap();
@@ -212,18 +212,13 @@ mod tests {
#[test] #[test]
fn signature_aggregation_works_for_any_subset_of_signatures() { fn signature_aggregation_works_for_any_subset_of_signatures() {
let mut params = Parameters::new(2).unwrap(); let mut params = Parameters::new(2).unwrap();
random_scalars_refs!(attributes, params, 2); let attributes = params.n_random_scalars(2);
let keypairs = ttp_keygen(&params, 3, 5).unwrap(); let keypairs = ttp_keygen(&params, 3, 5).unwrap();
let (sks, vks): (Vec<_>, Vec<_>) = keypairs let (sks, vks): (Vec<_>, Vec<_>) = keypairs
.into_iter() .into_iter()
.map(|keypair| { .map(|keypair| (keypair.secret_key(), keypair.verification_key()))
(
keypair.secret_key().clone(),
keypair.verification_key().clone(),
)
})
.unzip(); .unzip();
let sigs = sks let sigs = sks
@@ -317,17 +312,12 @@ mod tests {
fn signature_aggregation_doesnt_work_for_empty_set_of_signatures() { fn signature_aggregation_doesnt_work_for_empty_set_of_signatures() {
let signatures: Vec<Signature> = vec![]; let signatures: Vec<Signature> = vec![];
let params = Parameters::new(2).unwrap(); let params = Parameters::new(2).unwrap();
random_scalars_refs!(attributes, params, 2); let attributes = params.n_random_scalars(2);
let keypairs = ttp_keygen(&params, 3, 5).unwrap(); let keypairs = ttp_keygen(&params, 3, 5).unwrap();
let (_, vks): (Vec<_>, Vec<_>) = keypairs let (_, vks): (Vec<_>, Vec<_>) = keypairs
.into_iter() .into_iter()
.map(|keypair| { .map(|keypair| (keypair.secret_key(), keypair.verification_key()))
(
keypair.secret_key().clone(),
keypair.verification_key().clone(),
)
})
.unzip(); .unzip();
let aggr_vk_all = aggregate_verification_keys(&vks, None).unwrap(); let aggr_vk_all = aggregate_verification_keys(&vks, None).unwrap();
@@ -340,16 +330,11 @@ mod tests {
fn signature_aggregation_doesnt_work_if_indices_have_invalid_length() { fn signature_aggregation_doesnt_work_if_indices_have_invalid_length() {
let signatures = vec![random_signature()]; let signatures = vec![random_signature()];
let params = Parameters::new(2).unwrap(); let params = Parameters::new(2).unwrap();
random_scalars_refs!(attributes, params, 2); let attributes = params.n_random_scalars(2);
let keypairs = ttp_keygen(&params, 3, 5).unwrap(); let keypairs = ttp_keygen(&params, 3, 5).unwrap();
let (_, vks): (Vec<_>, Vec<_>) = keypairs let (_, vks): (Vec<_>, Vec<_>) = keypairs
.into_iter() .into_iter()
.map(|keypair| { .map(|keypair| (keypair.secret_key(), keypair.verification_key()))
(
keypair.secret_key().clone(),
keypair.verification_key().clone(),
)
})
.unzip(); .unzip();
let aggr_vk_all = aggregate_verification_keys(&vks, None).unwrap(); let aggr_vk_all = aggregate_verification_keys(&vks, None).unwrap();
@@ -371,16 +356,11 @@ mod tests {
fn signature_aggregation_doesnt_work_for_non_unique_indices() { fn signature_aggregation_doesnt_work_for_non_unique_indices() {
let signatures = vec![random_signature(), random_signature()]; let signatures = vec![random_signature(), random_signature()];
let params = Parameters::new(2).unwrap(); let params = Parameters::new(2).unwrap();
random_scalars_refs!(attributes, params, 2); let attributes = params.n_random_scalars(2);
let keypairs = ttp_keygen(&params, 3, 5).unwrap(); let keypairs = ttp_keygen(&params, 3, 5).unwrap();
let (_, vks): (Vec<_>, Vec<_>) = keypairs let (_, vks): (Vec<_>, Vec<_>) = keypairs
.into_iter() .into_iter()
.map(|keypair| { .map(|keypair| (keypair.secret_key(), keypair.verification_key()))
(
keypair.secret_key().clone(),
keypair.verification_key().clone(),
)
})
.unzip(); .unzip();
let aggr_vk_all = aggregate_verification_keys(&vks, None).unwrap(); let aggr_vk_all = aggregate_verification_keys(&vks, None).unwrap();
@@ -25,8 +25,6 @@ impl TryFrom<&[u8]> for BlindedSerialNumber {
)); ));
} }
// safety: we've just made a check for 96 bytes
#[allow(clippy::unwrap_used)]
let inner = try_deserialize_g2_projective( let inner = try_deserialize_g2_projective(
&bytes.try_into().unwrap(), &bytes.try_into().unwrap(),
CoconutError::Deserialization( CoconutError::Deserialization(
+41 -58
View File
@@ -54,8 +54,6 @@ impl TryFrom<&[u8]> for BlindSignRequest {
let commitment_bytes_len = 48; let commitment_bytes_len = 48;
let commitment_hash_bytes_len = 48; let commitment_hash_bytes_len = 48;
// safety: we made bound check and we're using constant offest
#[allow(clippy::unwrap_used)]
let cm_bytes = bytes[..j + commitment_bytes_len].try_into().unwrap(); let cm_bytes = bytes[..j + commitment_bytes_len].try_into().unwrap();
let commitment = try_deserialize_g1_projective( let commitment = try_deserialize_g1_projective(
&cm_bytes, &cm_bytes,
@@ -65,8 +63,6 @@ impl TryFrom<&[u8]> for BlindSignRequest {
)?; )?;
j += commitment_bytes_len; j += commitment_bytes_len;
// safety: we made bound check and we're using constant offest
#[allow(clippy::unwrap_used)]
let cm_hash_bytes = bytes[j..j + commitment_hash_bytes_len].try_into().unwrap(); let cm_hash_bytes = bytes[j..j + commitment_hash_bytes_len].try_into().unwrap();
let commitment_hash = try_deserialize_g1_projective( let commitment_hash = try_deserialize_g1_projective(
&cm_hash_bytes, &cm_hash_bytes,
@@ -76,8 +72,6 @@ impl TryFrom<&[u8]> for BlindSignRequest {
)?; )?;
j += commitment_hash_bytes_len; j += commitment_hash_bytes_len;
// safety: we made bound check and we're using constant offest
#[allow(clippy::unwrap_used)]
let c_len = u64::from_le_bytes(bytes[j..j + 8].try_into().unwrap()); let c_len = u64::from_le_bytes(bytes[j..j + 8].try_into().unwrap());
j += 8; j += 8;
if bytes[j..].len() < c_len as usize * 48 { if bytes[j..].len() < c_len as usize * 48 {
@@ -92,14 +86,6 @@ impl TryFrom<&[u8]> for BlindSignRequest {
let start = j + i * 48; let start = j + i * 48;
let end = start + 48; let end = start + 48;
if bytes.len() < end {
return Err(CoconutError::Deserialization(
"Failed to deserialize compressed commitment".to_string(),
));
}
// safety: we made bound check and we're using constant offest
#[allow(clippy::unwrap_used)]
let private_attributes_commitment_bytes = bytes[start..end].try_into().unwrap(); let private_attributes_commitment_bytes = bytes[start..end].try_into().unwrap();
let private_attributes_commitment = try_deserialize_g1_projective( let private_attributes_commitment = try_deserialize_g1_projective(
&private_attributes_commitment_bytes, &private_attributes_commitment_bytes,
@@ -151,7 +137,7 @@ impl Bytable for BlindSignRequest {
impl Base58 for BlindSignRequest {} impl Base58 for BlindSignRequest {}
impl BlindSignRequest { impl BlindSignRequest {
fn verify_proof(&self, params: &Parameters, public_attributes: &[&Attribute]) -> bool { fn verify_proof(&self, params: &Parameters, public_attributes: &[Attribute]) -> bool {
self.pi_s.verify( self.pi_s.verify(
params, params,
&self.commitment, &self.commitment,
@@ -164,8 +150,8 @@ impl BlindSignRequest {
self.commitment_hash self.commitment_hash
} }
pub fn get_private_attributes_pedersen_commitments(&self) -> &[G1Projective] { pub fn get_private_attributes_pedersen_commitments(&self) -> Vec<G1Projective> {
&self.private_attributes_commitments self.private_attributes_commitments.clone()
} }
pub fn to_bytes(&self) -> Vec<u8> { pub fn to_bytes(&self) -> Vec<u8> {
@@ -175,16 +161,12 @@ impl BlindSignRequest {
pub fn from_bytes(bytes: &[u8]) -> Result<BlindSignRequest> { pub fn from_bytes(bytes: &[u8]) -> Result<BlindSignRequest> {
BlindSignRequest::try_from(bytes) BlindSignRequest::try_from(bytes)
} }
pub fn num_private_attributes(&self) -> usize {
self.private_attributes_commitments.len()
}
} }
pub fn compute_attributes_commitment( pub fn compute_attributes_commitment(
params: &Parameters, params: &Parameters,
private_attributes: &[&Attribute], private_attributes: &[Attribute],
public_attributes: &[&Attribute], public_attributes: &[Attribute],
hs: &[G1Affine], hs: &[G1Affine],
) -> (Scalar, G1Projective) { ) -> (Scalar, G1Projective) {
let commitment_opening = params.random_scalar(); let commitment_opening = params.random_scalar();
@@ -205,7 +187,7 @@ pub fn compute_attributes_commitment(
pub fn compute_pedersen_commitments_for_private_attributes( pub fn compute_pedersen_commitments_for_private_attributes(
params: &Parameters, params: &Parameters,
private_attributes: &[&Attribute], private_attributes: &[Attribute],
h: &G1Projective, h: &G1Projective,
) -> (Vec<Scalar>, Vec<G1Projective>) { ) -> (Vec<Scalar>, Vec<G1Projective>) {
// Generate openings for Pedersen commitment for each private attribute // Generate openings for Pedersen commitment for each private attribute
@@ -215,13 +197,13 @@ pub fn compute_pedersen_commitments_for_private_attributes(
let pedersen_commitments = commitments_openings let pedersen_commitments = commitments_openings
.iter() .iter()
.zip(private_attributes.iter()) .zip(private_attributes.iter())
.map(|(o_j, &m_j)| params.gen1() * o_j + h * m_j) .map(|(o_j, m_j)| params.gen1() * o_j + h * m_j)
.collect::<Vec<_>>(); .collect::<Vec<_>>();
(commitments_openings, pedersen_commitments) (commitments_openings, pedersen_commitments)
} }
pub fn compute_hash(commitment: G1Projective, public_attributes: &[&Attribute]) -> G1Projective { pub fn compute_hash(commitment: G1Projective, public_attributes: &[Attribute]) -> G1Projective {
let mut buff = Vec::new(); let mut buff = Vec::new();
buff.extend_from_slice(commitment.to_bytes().as_ref()); buff.extend_from_slice(commitment.to_bytes().as_ref());
for attr in public_attributes { for attr in public_attributes {
@@ -233,8 +215,8 @@ pub fn compute_hash(commitment: G1Projective, public_attributes: &[&Attribute])
/// Builds cryptographic material required for blind sign. /// Builds cryptographic material required for blind sign.
pub fn prepare_blind_sign( pub fn prepare_blind_sign(
params: &Parameters, params: &Parameters,
private_attributes: &[&Attribute], private_attributes: &[Attribute],
public_attributes: &[&Attribute], public_attributes: &[Attribute],
) -> Result<(Vec<Scalar>, BlindSignRequest)> { ) -> Result<(Vec<Scalar>, BlindSignRequest)> {
if private_attributes.is_empty() { if private_attributes.is_empty() {
return Err(CoconutError::Issuance( return Err(CoconutError::Issuance(
@@ -289,7 +271,7 @@ pub fn blind_sign(
params: &Parameters, params: &Parameters,
signing_secret_key: &SecretKey, signing_secret_key: &SecretKey,
blind_sign_request: &BlindSignRequest, blind_sign_request: &BlindSignRequest,
public_attributes: &[&Attribute], public_attributes: &[Attribute],
) -> Result<BlindedSignature> { ) -> Result<BlindedSignature> {
let num_private = blind_sign_request.private_attributes_commitments.len(); let num_private = blind_sign_request.private_attributes_commitments.len();
let hs = params.gen_hs(); let hs = params.gen_hs();
@@ -322,7 +304,7 @@ pub fn blind_sign(
let signed_public = h * public_attributes let signed_public = h * public_attributes
.iter() .iter()
.zip(signing_secret_key.ys.iter().skip(num_private)) .zip(signing_secret_key.ys.iter().skip(num_private))
.map(|(&attr, yi)| attr * yi) .map(|(attr, yi)| attr * yi)
.sum::<Scalar>(); .sum::<Scalar>();
// h ^ x + c[0] ^ y[0] + ... c[m] ^ y[m] + h ^ (pub_m[0] * y[m + 1] + ... + pub_m[n] * y[m + n]) // h ^ x + c[0] ^ y[0] + ... c[m] ^ y[m] + h ^ (pub_m[0] * y[m + 1] + ... + pub_m[n] * y[m + n])
@@ -362,12 +344,12 @@ pub fn blind_sign(
/// The function returns `true` if the partial blind signature is valid, and `false` otherwise. /// The function returns `true` if the partial blind signature is valid, and `false` otherwise.
pub fn verify_partial_blind_signature( pub fn verify_partial_blind_signature(
params: &Parameters, params: &Parameters,
private_attribute_commitments: &[G1Projective], blind_sign_request: &BlindSignRequest,
public_attributes: &[&Attribute], public_attributes: &[Attribute],
blind_sig: &BlindedSignature, blind_sig: &BlindedSignature,
partial_verification_key: &VerificationKey, partial_verification_key: &VerificationKey,
) -> bool { ) -> bool {
let num_private_attributes = private_attribute_commitments.len(); let num_private_attributes = blind_sign_request.private_attributes_commitments.len();
if num_private_attributes + public_attributes.len() > partial_verification_key.beta_g2.len() { if num_private_attributes + public_attributes.len() > partial_verification_key.beta_g2.len() {
return false; return false;
} }
@@ -388,7 +370,8 @@ pub fn verify_partial_blind_signature(
]; ];
// for each private attribute, add (cm_i, beta_i) to the miller terms // for each private attribute, add (cm_i, beta_i) to the miller terms
for (private_attr_commit, beta_g2) in private_attribute_commitments for (private_attr_commit, beta_g2) in blind_sign_request
.private_attributes_commitments
.iter() .iter()
.zip(&partial_verification_key.beta_g2) .zip(&partial_verification_key.beta_g2)
{ {
@@ -400,7 +383,7 @@ pub fn verify_partial_blind_signature(
} }
// for each public attribute, add (s^pub_j, beta_{priv + j}) to the miller terms // for each public attribute, add (s^pub_j, beta_{priv + j}) to the miller terms
for (&pub_attr, beta_g2) in public_attributes.iter().zip( for (pub_attr, beta_g2) in public_attributes.iter().zip(
partial_verification_key partial_verification_key
.beta_g2 .beta_g2
.iter() .iter()
@@ -421,7 +404,7 @@ pub fn verify_partial_blind_signature(
// is equivalent to checking e(a, b) • e(c, d)^{-1} == id // is equivalent to checking e(a, b) • e(c, d)^{-1} == id
// and thus to e(a, b) • e(c^{-1}, d) == id // and thus to e(a, b) • e(c^{-1}, d) == id
// //
// compute e(c^{-1}, g2) • e(s, alpha) • e(cm_0, beta_0) • e(cm_i, beta_i) • (s^pub_0, beta_{i+1}) (s^pub_j, beta_{i + j}) // compute e(c^1, g2) • e(s, alpha) • e(cm_0, beta_0) • e(cm_i, beta_i) • (s^pub_0, beta_{i+1}) (s^pub_j, beta_{i + j})
multi_miller_loop(&terms_refs) multi_miller_loop(&terms_refs)
.final_exponentiation() .final_exponentiation()
.is_identity() .is_identity()
@@ -432,7 +415,7 @@ pub fn verify_partial_blind_signature(
pub fn sign( pub fn sign(
params: &mut Parameters, params: &mut Parameters,
secret_key: &SecretKey, secret_key: &SecretKey,
public_attributes: &[&Attribute], public_attributes: &[Attribute],
) -> Result<Signature> { ) -> Result<Signature> {
if public_attributes.len() > secret_key.ys.len() { if public_attributes.len() > secret_key.ys.len() {
return Err(CoconutError::IssuanceMaxAttributes { return Err(CoconutError::IssuanceMaxAttributes {
@@ -446,7 +429,7 @@ pub fn sign(
// (the python implementation hashes string representation of all attributes onto the curve, // (the python implementation hashes string representation of all attributes onto the curve,
// but I think the same can be achieved by just summing the attributes thus avoiding the unnecessary // but I think the same can be achieved by just summing the attributes thus avoiding the unnecessary
// transformation. If I'm wrong, please correct me.) // transformation. If I'm wrong, please correct me.)
let attributes_sum = public_attributes.iter().copied().sum::<Scalar>(); let attributes_sum = public_attributes.iter().sum::<Scalar>();
let h = hash_g1((params.gen1() * attributes_sum).to_bytes()); let h = hash_g1((params.gen1() * attributes_sum).to_bytes());
// x + m0 * y0 + m1 * y1 + ... mn * yn // x + m0 * y0 + m1 * y1 + ... mn * yn
@@ -454,7 +437,7 @@ pub fn sign(
+ public_attributes + public_attributes
.iter() .iter()
.zip(secret_key.ys.iter()) .zip(secret_key.ys.iter())
.map(|(&m_i, y_i)| m_i * y_i) .map(|(m_i, y_i)| m_i * y_i)
.sum::<Scalar>(); .sum::<Scalar>();
let sig2 = h * exponent; let sig2 = h * exponent;
@@ -465,14 +448,13 @@ pub fn sign(
mod tests { mod tests {
use super::*; use super::*;
use crate::scheme::keygen::keygen; use crate::scheme::keygen::keygen;
use crate::tests::helpers::random_scalars_refs;
#[test] #[test]
fn blind_sign_request_bytes_roundtrip() { fn blind_sign_request_bytes_roundtrip() {
// 0 public and 1 private attribute // 0 public and 1 private attribute
let params = Parameters::new(1).unwrap(); let params = Parameters::new(1).unwrap();
random_scalars_refs!(private_attributes, params, 1); let private_attributes = params.n_random_scalars(1);
random_scalars_refs!(public_attributes, params, 0); let public_attributes = params.n_random_scalars(0);
let (_commitments_openings, lambda) = let (_commitments_openings, lambda) =
prepare_blind_sign(&params, &private_attributes, &public_attributes).unwrap(); prepare_blind_sign(&params, &private_attributes, &public_attributes).unwrap();
@@ -485,8 +467,8 @@ mod tests {
// 2 public and 2 private attributes // 2 public and 2 private attributes
let params = Parameters::new(4).unwrap(); let params = Parameters::new(4).unwrap();
random_scalars_refs!(private_attributes, params, 2); let private_attributes = params.n_random_scalars(2);
random_scalars_refs!(public_attributes, params, 2); let public_attributes = params.n_random_scalars(2);
let (_commitments_openings, lambda) = let (_commitments_openings, lambda) =
prepare_blind_sign(&params, &private_attributes, &public_attributes).unwrap(); prepare_blind_sign(&params, &private_attributes, &public_attributes).unwrap();
@@ -501,8 +483,8 @@ mod tests {
#[test] #[test]
fn successful_verify_partial_blind_signature() { fn successful_verify_partial_blind_signature() {
let params = Parameters::new(4).unwrap(); let params = Parameters::new(4).unwrap();
random_scalars_refs!(private_attributes, params, 2); let private_attributes = params.n_random_scalars(2);
random_scalars_refs!(public_attributes, params, 2); let public_attributes = params.n_random_scalars(2);
let (_commitments_openings, request) = let (_commitments_openings, request) =
prepare_blind_sign(&params, &private_attributes, &public_attributes).unwrap(); prepare_blind_sign(&params, &private_attributes, &public_attributes).unwrap();
@@ -510,7 +492,7 @@ mod tests {
let validator_keypair = keygen(&params); let validator_keypair = keygen(&params);
let blind_sig = blind_sign( let blind_sig = blind_sign(
&params, &params,
validator_keypair.secret_key(), &validator_keypair.secret_key(),
&request, &request,
&public_attributes, &public_attributes,
) )
@@ -518,38 +500,39 @@ mod tests {
assert!(verify_partial_blind_signature( assert!(verify_partial_blind_signature(
&params, &params,
&request.private_attributes_commitments, &request,
&public_attributes, &public_attributes,
&blind_sig, &blind_sig,
validator_keypair.verification_key() &validator_keypair.verification_key()
)); ));
} }
#[test] #[test]
fn successful_verify_partial_blind_signature_no_public_attributes() { fn successful_verify_partial_blind_signature_no_public_attributes() {
let params = Parameters::new(4).unwrap(); let params = Parameters::new(4).unwrap();
random_scalars_refs!(private_attributes, params, 2); let private_attributes = params.n_random_scalars(2);
let (_commitments_openings, request) = let (_commitments_openings, request) =
prepare_blind_sign(&params, &private_attributes, &[]).unwrap(); prepare_blind_sign(&params, &private_attributes, &[]).unwrap();
let validator_keypair = keygen(&params); let validator_keypair = keygen(&params);
let blind_sig = blind_sign(&params, validator_keypair.secret_key(), &request, &[]).unwrap(); let blind_sig =
blind_sign(&params, &validator_keypair.secret_key(), &request, &[]).unwrap();
assert!(verify_partial_blind_signature( assert!(verify_partial_blind_signature(
&params, &params,
&request.private_attributes_commitments, &request,
&[], &[],
&blind_sig, &blind_sig,
validator_keypair.verification_key() &validator_keypair.verification_key()
)); ));
} }
#[test] #[test]
fn fail_verify_partial_blind_signature_with_wrong_key() { fn fail_verify_partial_blind_signature_with_wrong_key() {
let params = Parameters::new(4).unwrap(); let params = Parameters::new(4).unwrap();
random_scalars_refs!(private_attributes, params, 2); let private_attributes = params.n_random_scalars(2);
random_scalars_refs!(public_attributes, params, 2); let public_attributes = params.n_random_scalars(2);
let (_commitments_openings, request) = let (_commitments_openings, request) =
prepare_blind_sign(&params, &private_attributes, &public_attributes).unwrap(); prepare_blind_sign(&params, &private_attributes, &public_attributes).unwrap();
@@ -558,7 +541,7 @@ mod tests {
let validator2_keypair = keygen(&params); let validator2_keypair = keygen(&params);
let blind_sig = blind_sign( let blind_sig = blind_sign(
&params, &params,
validator_keypair.secret_key(), &validator_keypair.secret_key(),
&request, &request,
&public_attributes, &public_attributes,
) )
@@ -567,10 +550,10 @@ mod tests {
// this assertion should fail, as we try to verify with a wrong validator key // this assertion should fail, as we try to verify with a wrong validator key
assert!(!verify_partial_blind_signature( assert!(!verify_partial_blind_signature(
&params, &params,
&request.private_attributes_commitments, &request,
&public_attributes, &public_attributes,
&blind_sig, &blind_sig,
validator2_keypair.verification_key() &validator2_keypair.verification_key()
),); ),);
} }
} }
+7 -36
View File
@@ -23,12 +23,8 @@ use crate::utils::{
}; };
use crate::Base58; use crate::Base58;
#[derive(Debug)] #[derive(Debug, Clone)]
#[cfg_attr(test, derive(PartialEq, Eq, Clone))] #[cfg_attr(test, derive(PartialEq, Eq))]
#[cfg_attr(
feature = "key-zeroize",
derive(zeroize::Zeroize, zeroize::ZeroizeOnDrop)
)]
pub struct SecretKey { pub struct SecretKey {
pub(crate) x: Scalar, pub(crate) x: Scalar,
pub(crate) ys: Vec<Scalar>, pub(crate) ys: Vec<Scalar>,
@@ -66,9 +62,7 @@ impl TryFrom<&[u8]> for SecretKey {
} }
// this conversion will not fail as we are taking the same length of data // this conversion will not fail as we are taking the same length of data
#[allow(clippy::unwrap_used)]
let x_bytes: [u8; 32] = bytes[..32].try_into().unwrap(); let x_bytes: [u8; 32] = bytes[..32].try_into().unwrap();
#[allow(clippy::unwrap_used)]
let ys_len = u64::from_le_bytes(bytes[32..40].try_into().unwrap()); let ys_len = u64::from_le_bytes(bytes[32..40].try_into().unwrap());
let actual_ys_len = (bytes.len() - 40) / 32; let actual_ys_len = (bytes.len() - 40) / 32;
@@ -103,10 +97,6 @@ impl SecretKey {
(self.x, self.ys.clone()) (self.x, self.ys.clone())
} }
pub fn size(&self) -> usize {
self.ys.len()
}
/// Derive verification key using this secret key. /// Derive verification key using this secret key.
pub fn verification_key(&self, params: &Parameters) -> VerificationKey { pub fn verification_key(&self, params: &Parameters) -> VerificationKey {
let g1 = params.gen1(); let g1 = params.gen1();
@@ -151,10 +141,6 @@ impl Base58 for SecretKey {}
// TODO: perhaps change points to affine representation // TODO: perhaps change points to affine representation
// to make verification slightly more efficient? // to make verification slightly more efficient?
#[derive(Debug, PartialEq, Eq, Clone)] #[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(
feature = "key-zeroize",
derive(zeroize::Zeroize, zeroize::ZeroizeOnDrop)
)]
pub struct VerificationKey { pub struct VerificationKey {
// TODO add gen2 as per the paper or imply it from the fact library is using bls381? // TODO add gen2 as per the paper or imply it from the fact library is using bls381?
pub(crate) alpha: G2Projective, pub(crate) alpha: G2Projective,
@@ -194,9 +180,7 @@ impl TryFrom<&[u8]> for VerificationKey {
} }
// this conversion will not fail as we are taking the same length of data // this conversion will not fail as we are taking the same length of data
#[allow(clippy::unwrap_used)]
let alpha_bytes: [u8; 96] = bytes[..96].try_into().unwrap(); let alpha_bytes: [u8; 96] = bytes[..96].try_into().unwrap();
#[allow(clippy::unwrap_used)]
let betas_len = u64::from_le_bytes(bytes[96..104].try_into().unwrap()); let betas_len = u64::from_le_bytes(bytes[96..104].try_into().unwrap());
let actual_betas_len = (bytes.len() - 104) / (96 + 48); let actual_betas_len = (bytes.len() - 104) / (96 + 48);
@@ -220,8 +204,6 @@ impl TryFrom<&[u8]> for VerificationKey {
for i in 0..betas_len { for i in 0..betas_len {
let start = (104 + i * 48) as usize; let start = (104 + i * 48) as usize;
let end = start + 48; let end = start + 48;
// we're using a constant 48 byte offset (which is the size of G1 compressed) so unwrap is fine
#[allow(clippy::unwrap_used)]
let beta_i_bytes = bytes[start..end].try_into().unwrap(); let beta_i_bytes = bytes[start..end].try_into().unwrap();
let beta_i = try_deserialize_g1_projective( let beta_i = try_deserialize_g1_projective(
&beta_i_bytes, &beta_i_bytes,
@@ -238,8 +220,6 @@ impl TryFrom<&[u8]> for VerificationKey {
for i in 0..betas_len { for i in 0..betas_len {
let start = (beta_g1_end + i * 96) as usize; let start = (beta_g1_end + i * 96) as usize;
let end = start + 96; let end = start + 96;
// we're using a constant 96 byte offset (which is the size of G2 compressed) so unwrap is fine
#[allow(clippy::unwrap_used)]
let beta_i_bytes = bytes[start..end].try_into().unwrap(); let beta_i_bytes = bytes[start..end].try_into().unwrap();
let beta_i = try_deserialize_g2_projective( let beta_i = try_deserialize_g2_projective(
&beta_i_bytes, &beta_i_bytes,
@@ -412,11 +392,7 @@ impl Bytable for VerificationKey {
impl Base58 for VerificationKey {} impl Base58 for VerificationKey {}
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
#[cfg_attr(test, derive(PartialEq, Eq, Clone))] #[cfg_attr(test, derive(PartialEq, Eq))]
#[cfg_attr(
feature = "key-zeroize",
derive(zeroize::Zeroize, zeroize::ZeroizeOnDrop)
)]
pub struct KeyPair { pub struct KeyPair {
secret_key: SecretKey, secret_key: SecretKey,
verification_key: VerificationKey, verification_key: VerificationKey,
@@ -453,12 +429,12 @@ impl KeyPair {
} }
} }
pub fn secret_key(&self) -> &SecretKey { pub fn secret_key(&self) -> SecretKey {
&self.secret_key self.secret_key.clone()
} }
pub fn verification_key(&self) -> &VerificationKey { pub fn verification_key(&self) -> VerificationKey {
&self.verification_key self.verification_key.clone()
} }
pub fn to_bytes(&self) -> Vec<u8> { pub fn to_bytes(&self) -> Vec<u8> {
@@ -512,8 +488,6 @@ impl TryFrom<&[u8]> for KeyPair {
}); });
} }
// safety: we made bound check and we're using constant offest
#[allow(clippy::unwrap_used)]
let secret_key_len = let secret_key_len =
u64::from_le_bytes(bytes[header_len..header_len + 8].try_into().unwrap()) as usize; u64::from_le_bytes(bytes[header_len..header_len + 8].try_into().unwrap()) as usize;
let secret_key_start = header_len + 8; let secret_key_start = header_len + 8;
@@ -529,8 +503,6 @@ impl TryFrom<&[u8]> for KeyPair {
}); });
} }
// safety: we made bound check
#[allow(clippy::unwrap_used)]
let verification_key_len = u64::from_le_bytes( let verification_key_len = u64::from_le_bytes(
bytes[secret_key_start + secret_key_len..secret_key_start + secret_key_len + 8] bytes[secret_key_start + secret_key_len..secret_key_start + secret_key_len + 8]
.try_into() .try_into()
@@ -543,7 +515,6 @@ impl TryFrom<&[u8]> for KeyPair {
)?; )?;
let consumed_bytes = verification_key_start + verification_key_len; let consumed_bytes = verification_key_start + verification_key_len;
let index = if consumed_bytes < bytes.len() && [consumed_bytes..].len() == 8 { let index = if consumed_bytes < bytes.len() && [consumed_bytes..].len() == 8 {
#[allow(clippy::unwrap_used)]
Some(u64::from_le_bytes( Some(u64::from_le_bytes(
bytes[consumed_bytes..consumed_bytes + 8] bytes[consumed_bytes..consumed_bytes + 8]
.try_into() .try_into()
+97 -143
View File
@@ -44,10 +44,7 @@ impl TryFrom<&[u8]> for Signature {
))); )));
} }
// safety: we just checked for the length so the unwraps are fine
#[allow(clippy::expect_used)]
let sig1_bytes: &[u8; 48] = &bytes[..48].try_into().expect("Slice size != 48"); let sig1_bytes: &[u8; 48] = &bytes[..48].try_into().expect("Slice size != 48");
#[allow(clippy::expect_used)]
let sig2_bytes: &[u8; 48] = &bytes[48..].try_into().expect("Slice size != 48"); let sig2_bytes: &[u8; 48] = &bytes[48..].try_into().expect("Slice size != 48");
let sig1 = try_deserialize_g1_projective( let sig1 = try_deserialize_g1_projective(
@@ -91,45 +88,6 @@ impl Signature {
pub fn from_bytes(bytes: &[u8]) -> Result<Signature> { pub fn from_bytes(bytes: &[u8]) -> Result<Signature> {
Signature::try_from(bytes) Signature::try_from(bytes)
} }
pub fn verify(
&self,
params: &Parameters,
partial_verification_key: &VerificationKey,
private_attributes: &[&Attribute],
public_attributes: &[&Attribute],
commitment_hash: &G1Projective,
) -> Result<()> {
// Verify the commitment hash
if !(commitment_hash == &self.0) {
return Err(CoconutError::Verification(
"Verification of commitment hash from signature failed".to_string(),
));
}
let alpha = partial_verification_key.alpha;
let signed_attributes = private_attributes
.iter()
.chain(public_attributes.iter())
.zip(partial_verification_key.beta_g2.iter())
.map(|(&attr, beta_i)| beta_i * attr)
.sum::<G2Projective>();
// Verify the signature share
if !check_bilinear_pairing(
&self.0.to_affine(),
&G2Prepared::from((alpha + signed_attributes).to_affine()),
&self.1.to_affine(),
params.prepared_miller_g2(),
) {
return Err(CoconutError::Unblind(
"Verification of signature share failed".to_string(),
));
}
Ok(())
}
} }
impl Bytable for Signature { impl Bytable for Signature {
@@ -144,7 +102,8 @@ impl Bytable for Signature {
impl Base58 for Signature {} impl Base58 for Signature {}
#[derive(Debug, PartialEq, Eq)] #[derive(Debug)]
#[cfg_attr(test, derive(PartialEq, Eq))]
pub struct BlindedSignature(G1Projective, G1Projective); pub struct BlindedSignature(G1Projective, G1Projective);
impl Bytable for BlindedSignature { impl Bytable for BlindedSignature {
@@ -170,10 +129,7 @@ impl TryFrom<&[u8]> for BlindedSignature {
))); )));
} }
// safety: we just checked for the length so the unwraps are fine
#[allow(clippy::expect_used)]
let h_bytes: &[u8; 48] = &bytes[..48].try_into().expect("Slice size != 48"); let h_bytes: &[u8; 48] = &bytes[..48].try_into().expect("Slice size != 48");
#[allow(clippy::expect_used)]
let sig_bytes: &[u8; 48] = &bytes[48..].try_into().expect("Slice size != 48"); let sig_bytes: &[u8; 48] = &bytes[48..].try_into().expect("Slice size != 48");
let h = try_deserialize_g1_projective( let h = try_deserialize_g1_projective(
@@ -192,12 +148,24 @@ impl TryFrom<&[u8]> for BlindedSignature {
impl BlindedSignature { impl BlindedSignature {
pub fn unblind( pub fn unblind(
&self, &self,
params: &Parameters,
partial_verification_key: &VerificationKey, partial_verification_key: &VerificationKey,
private_attributes: &[Attribute],
public_attributes: &[Attribute],
commitment_hash: &G1Projective,
pedersen_commitments_openings: &[Scalar], pedersen_commitments_openings: &[Scalar],
) -> Result<Signature> { ) -> Result<Signature> {
// parse the signature // parse the signature
let h = &self.0; let h = &self.0;
let c = &self.1; let c = &self.1;
// Verify the commitment hash
if !(commitment_hash == h) {
return Err(CoconutError::Unblind(
"Verification of commitment hash from signature failed".to_string(),
));
}
let blinding_removers = partial_verification_key let blinding_removers = partial_verification_key
.beta_g1 .beta_g1
.iter() .iter()
@@ -207,27 +175,28 @@ impl BlindedSignature {
let unblinded_c = c - blinding_removers; let unblinded_c = c - blinding_removers;
Ok(Signature(*h, unblinded_c)) let alpha = partial_verification_key.alpha;
}
pub fn unblind_and_verify( let signed_attributes = private_attributes
&self, .iter()
params: &Parameters, .chain(public_attributes.iter())
partial_verification_key: &VerificationKey, .zip(partial_verification_key.beta_g2.iter())
private_attributes: &[&Attribute], .map(|(attr, beta_i)| beta_i * attr)
public_attributes: &[&Attribute], .sum::<G2Projective>();
commitment_hash: &G1Projective,
pedersen_commitments_openings: &[Scalar], // Verify the signature share
) -> Result<Signature> { if !check_bilinear_pairing(
let unblinded = self.unblind(partial_verification_key, pedersen_commitments_openings)?; &h.to_affine(),
unblinded.verify( &G2Prepared::from((alpha + signed_attributes).to_affine()),
params, &unblinded_c.to_affine(),
partial_verification_key, params.prepared_miller_g2(),
private_attributes, ) {
public_attributes, return Err(CoconutError::Unblind(
commitment_hash, "Verification of signature share failed".to_string(),
)?; ));
Ok(unblinded) }
Ok(Signature(*h, unblinded_c))
} }
pub fn to_bytes(&self) -> [u8; 96] { pub fn to_bytes(&self) -> [u8; 96] {
@@ -268,25 +237,25 @@ impl SignatureShare {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*;
use crate::hash_to_scalar; use crate::hash_to_scalar;
use crate::scheme::aggregation::{aggregate_signatures, aggregate_verification_keys}; use crate::scheme::aggregation::{aggregate_signatures, aggregate_verification_keys};
use crate::scheme::issuance::{blind_sign, compute_hash, prepare_blind_sign, sign}; use crate::scheme::issuance::{blind_sign, compute_hash, prepare_blind_sign, sign};
use crate::scheme::keygen::{keygen, ttp_keygen}; use crate::scheme::keygen::{keygen, ttp_keygen};
use crate::scheme::verification::{prove_bandwidth_credential, verify, verify_credential}; use crate::scheme::verification::{prove_bandwidth_credential, verify, verify_credential};
use crate::tests::helpers::random_scalars_refs;
use super::*;
#[test] #[test]
fn unblind_returns_error_if_integrity_check_on_commitment_hash_fails() { fn unblind_returns_error_if_integrity_check_on_commitment_hash_fails() {
let params = Parameters::new(2).unwrap(); let params = Parameters::new(2).unwrap();
random_scalars_refs!(private_attributes, params, 2); let private_attributes = params.n_random_scalars(2_usize);
let (_commitments_openings, lambda) = let (_commitments_openings, lambda) =
prepare_blind_sign(&params, &private_attributes, &[]).unwrap(); prepare_blind_sign(&params, &private_attributes, &[]).unwrap();
let keypair1 = keygen(&params); let keypair1 = keygen(&params);
let sig1 = blind_sign(&params, keypair1.secret_key(), &lambda, &[]).unwrap(); let sig1 = blind_sign(&params, &keypair1.secret_key(), &lambda, &[]).unwrap();
let wrong_commitment_opening = params.random_scalar(); let wrong_commitment_opening = params.random_scalar();
let wrong_commitment = params.gen1() * wrong_commitment_opening; let wrong_commitment = params.gen1() * wrong_commitment_opening;
@@ -294,9 +263,9 @@ mod tests {
let wrong_commitments_openings = params.n_random_scalars(private_attributes.len()); let wrong_commitments_openings = params.n_random_scalars(private_attributes.len());
assert!(sig1 assert!(sig1
.unblind_and_verify( .unblind(
&params, &params,
keypair1.verification_key(), &keypair1.verification_key(),
&private_attributes, &private_attributes,
&[], &[],
&fake_commitment_hash, &fake_commitment_hash,
@@ -308,23 +277,20 @@ mod tests {
#[test] #[test]
fn unblind_returns_error_if_signature_verification_fails() { fn unblind_returns_error_if_signature_verification_fails() {
let params = Parameters::new(2).unwrap(); let params = Parameters::new(2).unwrap();
let p = [hash_to_scalar("Attribute1"), hash_to_scalar("Attribute2")]; let private_attributes = vec![hash_to_scalar("Attribute1"), hash_to_scalar("Attribute2")];
let private_attributes = vec![&p[0], &p[1]]; let private_attributes2 = vec![hash_to_scalar("Attribute3"), hash_to_scalar("Attribute4")];
let p2 = [hash_to_scalar("Attribute3"), hash_to_scalar("Attribute4")];
let private_attributes2 = vec![&p2[0], &p2[1]];
let (commitments_openings, lambda) = let (commitments_openings, lambda) =
prepare_blind_sign(&params, &private_attributes, &[]).unwrap(); prepare_blind_sign(&params, &private_attributes, &[]).unwrap();
let keypair1 = keygen(&params); let keypair1 = keygen(&params);
let sig1 = blind_sign(&params, keypair1.secret_key(), &lambda, &[]).unwrap(); let sig1 = blind_sign(&params, &keypair1.secret_key(), &lambda, &[]).unwrap();
assert!(sig1 assert!(sig1
.unblind_and_verify( .unblind(
&params, &params,
keypair1.verification_key(), &keypair1.verification_key(),
&private_attributes2, &private_attributes2,
&[], &[],
&lambda.get_commitment_hash(), &lambda.get_commitment_hash(),
@@ -338,7 +304,7 @@ mod tests {
let params = Parameters::new(2).unwrap(); let params = Parameters::new(2).unwrap();
let serial_number = params.random_scalar(); let serial_number = params.random_scalar();
let binding_number = params.random_scalar(); let binding_number = params.random_scalar();
let private_attributes = vec![&serial_number, &binding_number]; let private_attributes = vec![serial_number, binding_number];
let keypair1 = keygen(&params); let keypair1 = keygen(&params);
let keypair2 = keygen(&params); let keypair2 = keygen(&params);
@@ -346,11 +312,11 @@ mod tests {
let (commitments_openings, lambda) = let (commitments_openings, lambda) =
prepare_blind_sign(&params, &private_attributes, &[]).unwrap(); prepare_blind_sign(&params, &private_attributes, &[]).unwrap();
let sig1 = blind_sign(&params, keypair1.secret_key(), &lambda, &[]) let sig1 = blind_sign(&params, &keypair1.secret_key(), &lambda, &[])
.unwrap() .unwrap()
.unblind_and_verify( .unblind(
&params, &params,
keypair1.verification_key(), &keypair1.verification_key(),
&private_attributes, &private_attributes,
&[], &[],
&lambda.get_commitment_hash(), &lambda.get_commitment_hash(),
@@ -358,11 +324,11 @@ mod tests {
) )
.unwrap(); .unwrap();
let sig2 = blind_sign(&params, keypair2.secret_key(), &lambda, &[]) let sig2 = blind_sign(&params, &keypair2.secret_key(), &lambda, &[])
.unwrap() .unwrap()
.unblind_and_verify( .unblind(
&params, &params,
keypair2.verification_key(), &keypair2.verification_key(),
&private_attributes, &private_attributes,
&[], &[],
&lambda.get_commitment_hash(), &lambda.get_commitment_hash(),
@@ -372,39 +338,39 @@ mod tests {
let theta1 = prove_bandwidth_credential( let theta1 = prove_bandwidth_credential(
&params, &params,
keypair1.verification_key(), &keypair1.verification_key(),
&sig1, &sig1,
&serial_number, serial_number,
&binding_number, binding_number,
) )
.unwrap(); .unwrap();
let theta2 = prove_bandwidth_credential( let theta2 = prove_bandwidth_credential(
&params, &params,
keypair2.verification_key(), &keypair2.verification_key(),
&sig2, &sig2,
&serial_number, serial_number,
&binding_number, binding_number,
) )
.unwrap(); .unwrap();
assert!(verify_credential( assert!(verify_credential(
&params, &params,
keypair1.verification_key(), &keypair1.verification_key(),
&theta1, &theta1,
&[], &[],
)); ));
assert!(verify_credential( assert!(verify_credential(
&params, &params,
keypair2.verification_key(), &keypair2.verification_key(),
&theta2, &theta2,
&[], &[],
)); ));
assert!(!verify_credential( assert!(!verify_credential(
&params, &params,
keypair1.verification_key(), &keypair1.verification_key(),
&theta2, &theta2,
&[], &[],
)); ));
@@ -413,30 +379,30 @@ mod tests {
#[test] #[test]
fn verification_on_two_public_attributes() { fn verification_on_two_public_attributes() {
let mut params = Parameters::new(2).unwrap(); let mut params = Parameters::new(2).unwrap();
random_scalars_refs!(attributes, params, 2); let attributes = params.n_random_scalars(2);
let keypair1 = keygen(&params); let keypair1 = keygen(&params);
let keypair2 = keygen(&params); let keypair2 = keygen(&params);
let sig1 = sign(&mut params, keypair1.secret_key(), &attributes).unwrap(); let sig1 = sign(&mut params, &keypair1.secret_key(), &attributes).unwrap();
let sig2 = sign(&mut params, keypair2.secret_key(), &attributes).unwrap(); let sig2 = sign(&mut params, &keypair2.secret_key(), &attributes).unwrap();
assert!(verify( assert!(verify(
&params, &params,
keypair1.verification_key(), &keypair1.verification_key(),
&attributes, &attributes,
&sig1, &sig1,
)); ));
assert!(!verify( assert!(!verify(
&params, &params,
keypair2.verification_key(), &keypair2.verification_key(),
&attributes, &attributes,
&sig1, &sig1,
)); ));
assert!(!verify( assert!(!verify(
&params, &params,
keypair1.verification_key(), &keypair1.verification_key(),
&attributes, &attributes,
&sig2, &sig2,
)); ));
@@ -445,11 +411,10 @@ mod tests {
#[test] #[test]
fn verification_on_two_public_and_two_private_attributes() { fn verification_on_two_public_and_two_private_attributes() {
let params = Parameters::new(4).unwrap(); let params = Parameters::new(4).unwrap();
random_scalars_refs!(public_attributes, params, 2); let public_attributes = params.n_random_scalars(2);
let serial_number = params.random_scalar(); let serial_number = params.random_scalar();
let binding_number = params.random_scalar(); let binding_number = params.random_scalar();
let private_attributes = vec![&serial_number, &binding_number]; let private_attributes = vec![serial_number, binding_number];
let keypair1 = keygen(&params); let keypair1 = keygen(&params);
let keypair2 = keygen(&params); let keypair2 = keygen(&params);
@@ -457,11 +422,11 @@ mod tests {
let (commitments_openings, lambda) = let (commitments_openings, lambda) =
prepare_blind_sign(&params, &private_attributes, &public_attributes).unwrap(); prepare_blind_sign(&params, &private_attributes, &public_attributes).unwrap();
let sig1 = blind_sign(&params, keypair1.secret_key(), &lambda, &public_attributes) let sig1 = blind_sign(&params, &keypair1.secret_key(), &lambda, &public_attributes)
.unwrap() .unwrap()
.unblind_and_verify( .unblind(
&params, &params,
keypair1.verification_key(), &keypair1.verification_key(),
&private_attributes, &private_attributes,
&public_attributes, &public_attributes,
&lambda.get_commitment_hash(), &lambda.get_commitment_hash(),
@@ -469,11 +434,11 @@ mod tests {
) )
.unwrap(); .unwrap();
let sig2 = blind_sign(&params, keypair2.secret_key(), &lambda, &public_attributes) let sig2 = blind_sign(&params, &keypair2.secret_key(), &lambda, &public_attributes)
.unwrap() .unwrap()
.unblind_and_verify( .unblind(
&params, &params,
keypair2.verification_key(), &keypair2.verification_key(),
&private_attributes, &private_attributes,
&public_attributes, &public_attributes,
&lambda.get_commitment_hash(), &lambda.get_commitment_hash(),
@@ -483,39 +448,39 @@ mod tests {
let theta1 = prove_bandwidth_credential( let theta1 = prove_bandwidth_credential(
&params, &params,
keypair1.verification_key(), &keypair1.verification_key(),
&sig1, &sig1,
&serial_number, serial_number,
&binding_number, binding_number,
) )
.unwrap(); .unwrap();
let theta2 = prove_bandwidth_credential( let theta2 = prove_bandwidth_credential(
&params, &params,
keypair2.verification_key(), &keypair2.verification_key(),
&sig2, &sig2,
&serial_number, serial_number,
&binding_number, binding_number,
) )
.unwrap(); .unwrap();
assert!(verify_credential( assert!(verify_credential(
&params, &params,
keypair1.verification_key(), &keypair1.verification_key(),
&theta1, &theta1,
&public_attributes, &public_attributes,
)); ));
assert!(verify_credential( assert!(verify_credential(
&params, &params,
keypair2.verification_key(), &keypair2.verification_key(),
&theta2, &theta2,
&public_attributes, &public_attributes,
)); ));
assert!(!verify_credential( assert!(!verify_credential(
&params, &params,
keypair1.verification_key(), &keypair1.verification_key(),
&theta2, &theta2,
&public_attributes, &public_attributes,
)); ));
@@ -524,11 +489,10 @@ mod tests {
#[test] #[test]
fn verification_on_two_public_and_two_private_attributes_from_two_signers() { fn verification_on_two_public_and_two_private_attributes_from_two_signers() {
let params = Parameters::new(4).unwrap(); let params = Parameters::new(4).unwrap();
random_scalars_refs!(public_attributes, params, 2); let public_attributes = params.n_random_scalars(2);
let serial_number = params.random_scalar(); let serial_number = params.random_scalar();
let binding_number = params.random_scalar(); let binding_number = params.random_scalar();
let private_attributes = vec![&serial_number, &binding_number]; let private_attributes = vec![serial_number, binding_number];
let keypairs = ttp_keygen(&params, 2, 3).unwrap(); let keypairs = ttp_keygen(&params, 2, 3).unwrap();
@@ -538,11 +502,11 @@ mod tests {
let sigs = keypairs let sigs = keypairs
.iter() .iter()
.map(|keypair| { .map(|keypair| {
blind_sign(&params, keypair.secret_key(), &lambda, &public_attributes) blind_sign(&params, &keypair.secret_key(), &lambda, &public_attributes)
.unwrap() .unwrap()
.unblind_and_verify( .unblind(
&params, &params,
keypair.verification_key(), &keypair.verification_key(),
&private_attributes, &private_attributes,
&public_attributes, &public_attributes,
&lambda.get_commitment_hash(), &lambda.get_commitment_hash(),
@@ -554,7 +518,7 @@ mod tests {
let vks = keypairs let vks = keypairs
.into_iter() .into_iter()
.map(|keypair| keypair.verification_key().clone()) .map(|keypair| keypair.verification_key())
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let mut attributes = Vec::with_capacity(private_attributes.len() + public_attributes.len()); let mut attributes = Vec::with_capacity(private_attributes.len() + public_attributes.len());
@@ -566,14 +530,9 @@ mod tests {
aggregate_signatures(&params, &aggr_vk, &attributes, &sigs[..2], Some(&[1, 2])) aggregate_signatures(&params, &aggr_vk, &attributes, &sigs[..2], Some(&[1, 2]))
.unwrap(); .unwrap();
let theta = prove_bandwidth_credential( let theta =
&params, prove_bandwidth_credential(&params, &aggr_vk, &aggr_sig, serial_number, binding_number)
&aggr_vk, .unwrap();
&aggr_sig,
&serial_number,
&binding_number,
)
.unwrap();
assert!(verify_credential( assert!(verify_credential(
&params, &params,
@@ -588,14 +547,9 @@ mod tests {
aggregate_signatures(&params, &aggr_vk, &attributes, &sigs[1..], Some(&[2, 3])) aggregate_signatures(&params, &aggr_vk, &attributes, &sigs[1..], Some(&[2, 3]))
.unwrap(); .unwrap();
let theta = prove_bandwidth_credential( let theta =
&params, prove_bandwidth_credential(&params, &aggr_vk, &aggr_sig, serial_number, binding_number)
&aggr_vk, .unwrap();
&aggr_sig,
&serial_number,
&binding_number,
)
.unwrap();
assert!(verify_credential( assert!(verify_credential(
&params, &params,
+18 -26
View File
@@ -43,8 +43,6 @@ impl TryFrom<&[u8]> for Theta {
)); ));
} }
// safety: we just checked for the length so the unwraps are fine
#[allow(clippy::unwrap_used)]
let blinded_message_bytes = bytes[..96].try_into().unwrap(); let blinded_message_bytes = bytes[..96].try_into().unwrap();
let blinded_message = try_deserialize_g2_projective( let blinded_message = try_deserialize_g2_projective(
&blinded_message_bytes, &blinded_message_bytes,
@@ -53,8 +51,6 @@ impl TryFrom<&[u8]> for Theta {
), ),
)?; )?;
// safety: we just checked for the length so the unwraps are fine
#[allow(clippy::unwrap_used)]
let blinded_serial_number_bytes = bytes[96..192].try_into().unwrap(); let blinded_serial_number_bytes = bytes[96..192].try_into().unwrap();
let blinded_serial_number = try_deserialize_g2_projective( let blinded_serial_number = try_deserialize_g2_projective(
&blinded_serial_number_bytes, &blinded_serial_number_bytes,
@@ -134,7 +130,7 @@ impl Base58 for Theta {}
pub fn compute_kappa( pub fn compute_kappa(
params: &Parameters, params: &Parameters,
verification_key: &VerificationKey, verification_key: &VerificationKey,
private_attributes: &[&Attribute], private_attributes: &[Attribute],
blinding_factor: Scalar, blinding_factor: Scalar,
) -> G2Projective { ) -> G2Projective {
params.gen2() * blinding_factor params.gen2() * blinding_factor
@@ -142,11 +138,11 @@ pub fn compute_kappa(
+ private_attributes + private_attributes
.iter() .iter()
.zip(verification_key.beta_g2.iter()) .zip(verification_key.beta_g2.iter())
.map(|(&priv_attr, beta_i)| beta_i * priv_attr) .map(|(priv_attr, beta_i)| beta_i * priv_attr)
.sum::<G2Projective>() .sum::<G2Projective>()
} }
pub fn compute_zeta(params: &Parameters, serial_number: &Attribute) -> G2Projective { pub fn compute_zeta(params: &Parameters, serial_number: Attribute) -> G2Projective {
params.gen2() * serial_number params.gen2() * serial_number
} }
@@ -154,8 +150,8 @@ pub fn prove_bandwidth_credential(
params: &Parameters, params: &Parameters,
verification_key: &VerificationKey, verification_key: &VerificationKey,
signature: &Signature, signature: &Signature,
serial_number: &Attribute, serial_number: Attribute,
binding_number: &Attribute, binding_number: Attribute,
) -> Result<Theta> { ) -> Result<Theta> {
if verification_key.beta_g2.len() < 2 { if verification_key.beta_g2.len() < 2 {
return Err( return Err(
@@ -175,7 +171,7 @@ pub fn prove_bandwidth_credential(
// Thus, we need kappa which allows us to verify sigma'. In particular, // Thus, we need kappa which allows us to verify sigma'. In particular,
// kappa is computed on m as input, but thanks to the use or random value r, // kappa is computed on m as input, but thanks to the use or random value r,
// it does not reveal any information about m. // it does not reveal any information about m.
let private_attributes = [serial_number, binding_number]; let private_attributes = vec![serial_number, binding_number];
let blinded_message = compute_kappa( let blinded_message = compute_kappa(
params, params,
verification_key, verification_key,
@@ -189,8 +185,8 @@ pub fn prove_bandwidth_credential(
let pi_v = ProofKappaZeta::construct( let pi_v = ProofKappaZeta::construct(
params, params,
verification_key, verification_key,
serial_number, &serial_number,
binding_number, &binding_number,
&sign_blinding_factor, &sign_blinding_factor,
&blinded_message, &blinded_message,
&blinded_serial_number, &blinded_serial_number,
@@ -225,10 +221,7 @@ pub fn check_vk_pairing(
if values_len == 0 || values_len - 1 != vk.beta_g1.len() || values_len - 1 != vk.beta_g2.len() { if values_len == 0 || values_len - 1 != vk.beta_g1.len() || values_len - 1 != vk.beta_g2.len() {
return false; return false;
} }
if vk.alpha != *dkg_values.last().unwrap() {
// safety: we made an explicit check for if the length of the slice is 0, thus unwrap here is fine
#[allow(clippy::unwrap_used)]
if &vk.alpha != *dkg_values.last().as_ref().unwrap() {
return false; return false;
} }
if dkg_values if dkg_values
@@ -256,7 +249,7 @@ pub fn verify_credential(
params: &Parameters, params: &Parameters,
verification_key: &VerificationKey, verification_key: &VerificationKey,
theta: &Theta, theta: &Theta,
public_attributes: &[&Attribute], public_attributes: &[Attribute],
) -> bool { ) -> bool {
if public_attributes.len() + theta.pi_v.private_attributes_len() if public_attributes.len() + theta.pi_v.private_attributes_len()
> verification_key.beta_g2.len() > verification_key.beta_g2.len()
@@ -279,7 +272,7 @@ pub fn verify_credential(
.iter() .iter()
.skip(theta.pi_v.private_attributes_len()), .skip(theta.pi_v.private_attributes_len()),
) )
.map(|(&pub_attr, beta_i)| beta_i * pub_attr) .map(|(pub_attr, beta_i)| beta_i * pub_attr)
.sum::<G2Projective>(); .sum::<G2Projective>();
theta.blinded_message + signed_public_attributes theta.blinded_message + signed_public_attributes
@@ -298,14 +291,14 @@ pub fn verify_credential(
pub fn verify( pub fn verify(
params: &Parameters, params: &Parameters,
verification_key: &VerificationKey, verification_key: &VerificationKey,
public_attributes: &[&Attribute], public_attributes: &[Attribute],
sig: &Signature, sig: &Signature,
) -> bool { ) -> bool {
let kappa = (verification_key.alpha let kappa = (verification_key.alpha
+ public_attributes + public_attributes
.iter() .iter()
.zip(verification_key.beta_g2.iter()) .zip(verification_key.beta_g2.iter())
.map(|(&m_i, b_i)| b_i * m_i) .map(|(m_i, b_i)| b_i * m_i)
.sum::<G2Projective>()) .sum::<G2Projective>())
.to_affine(); .to_affine();
@@ -327,11 +320,10 @@ mod tests {
#[test] #[test]
fn vk_pairing() { fn vk_pairing() {
let params = setup(2).unwrap(); let params = setup(2).unwrap();
let keypair = keygen(&params); let vk = keygen(&params).verification_key();
let vk = keypair.verification_key();
let mut dkg_values = vk.beta_g2.clone(); let mut dkg_values = vk.beta_g2.clone();
dkg_values.push(vk.alpha); dkg_values.push(vk.alpha);
assert!(check_vk_pairing(&params, &dkg_values, vk)); assert!(check_vk_pairing(&params, &dkg_values, &vk));
} }
#[test] #[test]
@@ -348,10 +340,10 @@ mod tests {
let theta = prove_bandwidth_credential( let theta = prove_bandwidth_credential(
&params, &params,
keypair.verification_key(), &keypair.verification_key(),
&signature, &signature,
&serial_number, serial_number,
&binding_number, binding_number,
) )
.unwrap(); .unwrap();
+4 -5
View File
@@ -1,7 +1,6 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net> // Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
use crate::random_scalars_refs;
use crate::tests::helpers::tests::generate_dkg_keys; use crate::tests::helpers::tests::generate_dkg_keys;
use crate::{ use crate::{
aggregate_verification_keys, setup, tests::helpers::*, ttp_keygen, verify_credential, aggregate_verification_keys, setup, tests::helpers::*, ttp_keygen, verify_credential,
@@ -13,14 +12,14 @@ fn keygen() -> Result<(), CoconutError> {
let params = setup(5)?; let params = setup(5)?;
let node_indices = vec![15u64, 248, 33521]; let node_indices = vec![15u64, 248, 33521];
random_scalars_refs!(public_attributes, params, 2); let public_attributes = params.n_random_scalars(2);
// generate_keys // generate_keys
let coconut_keypairs = ttp_keygen(&params, 2, 3)?; let coconut_keypairs = ttp_keygen(&params, 2, 3)?;
let verification_keys: Vec<VerificationKey> = coconut_keypairs let verification_keys: Vec<VerificationKey> = coconut_keypairs
.iter() .iter()
.map(|keypair| keypair.verification_key().clone()) .map(|keypair| keypair.verification_key())
.collect(); .collect();
// aggregate verification keys // aggregate verification keys
@@ -51,14 +50,14 @@ fn dkg() -> Result<(), CoconutError> {
let params = setup(5)?; let params = setup(5)?;
let node_indices = vec![15u64, 248, 33521]; let node_indices = vec![15u64, 248, 33521];
random_scalars_refs!(public_attributes, params, 2); let public_attributes = params.n_random_scalars(2);
// generate_keys // generate_keys
let coconut_keypairs = generate_dkg_keys(5, &node_indices); let coconut_keypairs = generate_dkg_keys(5, &node_indices);
let verification_keys: Vec<VerificationKey> = coconut_keypairs let verification_keys: Vec<VerificationKey> = coconut_keypairs
.iter() .iter()
.map(|keypair| keypair.verification_key().clone()) .map(|keypair| keypair.verification_key())
.collect(); .collect();
// aggregate verification keys // aggregate verification keys
+7 -22
View File
@@ -5,17 +5,15 @@ use crate::*;
use itertools::izip; use itertools::izip;
use std::fmt::Debug; use std::fmt::Debug;
// unwraps are fine in the test code
#[allow(clippy::unwrap_used)]
pub fn theta_from_keys_and_attributes( pub fn theta_from_keys_and_attributes(
params: &Parameters, params: &Parameters,
coconut_keypairs: &Vec<KeyPair>, coconut_keypairs: &Vec<KeyPair>,
indices: &[scheme::SignerIndex], indices: &[scheme::SignerIndex],
public_attributes: &[&PublicAttribute], public_attributes: &Vec<PublicAttribute>,
) -> Result<Theta, CoconutError> { ) -> Result<Theta, CoconutError> {
let serial_number = params.random_scalar(); let serial_number = params.random_scalar();
let binding_number = params.random_scalar(); let binding_number = params.random_scalar();
let private_attributes = vec![&serial_number, &binding_number]; let private_attributes = vec![serial_number, binding_number];
// generate commitment // generate commitment
let (commitments_openings, blind_sign_request) = let (commitments_openings, blind_sign_request) =
@@ -23,7 +21,7 @@ pub fn theta_from_keys_and_attributes(
let verification_keys: Vec<VerificationKey> = coconut_keypairs let verification_keys: Vec<VerificationKey> = coconut_keypairs
.iter() .iter()
.map(|keypair| keypair.verification_key().clone()) .map(|keypair| keypair.verification_key())
.collect(); .collect();
// aggregate verification keys // aggregate verification keys
@@ -35,7 +33,7 @@ pub fn theta_from_keys_and_attributes(
for keypair in coconut_keypairs { for keypair in coconut_keypairs {
let blinded_signature = blind_sign( let blinded_signature = blind_sign(
params, params,
keypair.secret_key(), &keypair.secret_key(),
&blind_sign_request, &blind_sign_request,
public_attributes, public_attributes,
)?; )?;
@@ -51,7 +49,7 @@ pub fn theta_from_keys_and_attributes(
.map(|(idx, s, vk)| { .map(|(idx, s, vk)| {
( (
*idx, *idx,
s.unblind_and_verify( s.unblind(
params, params,
vk, vk,
&private_attributes, &private_attributes,
@@ -83,15 +81,13 @@ pub fn theta_from_keys_and_attributes(
params, params,
&verification_key, &verification_key,
&signature, &signature,
&serial_number, serial_number,
&binding_number, binding_number,
)?; )?;
Ok(theta) Ok(theta)
} }
// unwraps are fine in the test code
#[allow(clippy::unwrap_used)]
pub fn transpose_matrix<T: Debug>(matrix: Vec<Vec<T>>) -> Vec<Vec<T>> { pub fn transpose_matrix<T: Debug>(matrix: Vec<Vec<T>>) -> Vec<Vec<T>> {
if matrix.is_empty() { if matrix.is_empty() {
return vec![]; return vec![];
@@ -108,17 +104,6 @@ pub fn transpose_matrix<T: Debug>(matrix: Vec<Vec<T>>) -> Vec<Vec<T>> {
.collect::<Vec<_>>() .collect::<Vec<_>>()
} }
#[macro_export]
macro_rules! random_scalars_refs {
( $x: ident, $params: expr, $n: expr ) => {
let _vec = $params.n_random_scalars($n);
#[allow(clippy::map_identity)]
let $x = _vec.iter().collect::<Vec<_>>();
};
}
pub use random_scalars_refs;
#[cfg(test)] #[cfg(test)]
pub mod tests { pub mod tests {
use super::*; use super::*;
+1 -68
View File
@@ -1,13 +1,4 @@
// Copyright 2021-2023 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
#![warn(clippy::expect_used)]
#![warn(clippy::unwrap_used)]
use crate::CoconutError; use crate::CoconutError;
use bls12_381::{G1Affine, G1Projective, Scalar};
use group::GroupEncoding;
use std::convert::TryInto;
pub trait Bytable pub trait Bytable
where where
@@ -23,67 +14,9 @@ where
Self: Bytable, Self: Bytable,
{ {
fn try_from_bs58<S: AsRef<str>>(x: S) -> Result<Self, CoconutError> { fn try_from_bs58<S: AsRef<str>>(x: S) -> Result<Self, CoconutError> {
let bs58_decoded = &bs58::decode(x.as_ref()).into_vec()?; Self::try_from_byte_slice(&bs58::decode(x.as_ref()).into_vec().unwrap())
Self::try_from_byte_slice(bs58_decoded)
} }
fn to_bs58(&self) -> String { fn to_bs58(&self) -> String {
bs58::encode(self.to_byte_vec()).into_string() bs58::encode(self.to_byte_vec()).into_string()
} }
} }
impl Bytable for Scalar {
fn to_byte_vec(&self) -> Vec<u8> {
self.to_bytes().to_vec()
}
fn try_from_byte_slice(slice: &[u8]) -> Result<Self, CoconutError> {
let received = slice.len();
let Ok(arr) = slice.try_into() else {
return Err(CoconutError::UnexpectedArrayLength {
typ: "Scalar".to_string(),
received,
expected: 32,
});
};
let maybe_scalar = Scalar::from_bytes(arr);
if maybe_scalar.is_none().into() {
Err(CoconutError::ScalarDeserializationFailure)
} else {
// safety: this unwrap is fine as we've just checked the element is not none
#[allow(clippy::unwrap_used)]
Ok(maybe_scalar.unwrap())
}
}
}
impl Base58 for Scalar {}
impl Bytable for G1Projective {
fn to_byte_vec(&self) -> Vec<u8> {
self.to_bytes().as_ref().to_vec()
}
fn try_from_byte_slice(slice: &[u8]) -> Result<Self, CoconutError> {
let received = slice.len();
let arr: Result<[u8; 48], _> = slice.try_into();
let Ok(bytes) = arr else {
return Err(CoconutError::UnexpectedArrayLength {
typ: "G1Projective".to_string(),
received,
expected: 48,
});
};
let maybe_g1 = G1Affine::from_compressed(&bytes);
if maybe_g1.is_none().into() {
Err(CoconutError::G1ProjectiveDeserializationFailure)
} else {
// safety: this unwrap is fine as we've just checked the element is not none
#[allow(clippy::unwrap_used)]
Ok(maybe_g1.unwrap().into())
}
}
}
impl Base58 for G1Projective {}
-3
View File
@@ -34,7 +34,6 @@ impl Polynomial {
// just return the last term of the polynomial // just return the last term of the polynomial
} else if x.is_zero().into() { } else if x.is_zero().into() {
// we checked that coefficients are not empty so unwrap here is fine // we checked that coefficients are not empty so unwrap here is fine
#[allow(clippy::unwrap_used)]
*self.coefficients.first().unwrap() *self.coefficients.first().unwrap()
} else { } else {
self.coefficients self.coefficients
@@ -149,8 +148,6 @@ pub(crate) fn try_deserialize_scalar_vec(
let mut out = Vec::with_capacity(expected_len as usize); let mut out = Vec::with_capacity(expected_len as usize);
for i in 0..expected_len as usize { for i in 0..expected_len as usize {
// we just checked we have exactly the amount of bytes we need and thus the unwrap is fine
#[allow(clippy::unwrap_used)]
let s_bytes = bytes[i * 32..(i + 1) * 32].try_into().unwrap(); let s_bytes = bytes[i * 32..(i + 1) * 32].try_into().unwrap();
let s = match Into::<Option<Scalar>>::into(Scalar::from_bytes(&s_bytes)) { let s = match Into::<Option<Scalar>>::into(Scalar::from_bytes(&s_bytes)) {
None => return Err(err), None => return Err(err),
+1 -1
View File
@@ -9,7 +9,7 @@ repository = { workspace = true }
[dependencies] [dependencies]
bytes = "1.0" bytes = "1.0"
tokio-util = { workspace = true, features = ["codec"] } tokio-util = { version = "0.7.4", features = ["codec"] }
thiserror = { workspace = true } thiserror = { workspace = true }
nym-sphinx-types = { path = "../types", features = ["sphinx", "outfox"] } nym-sphinx-types = { path = "../types", features = ["sphinx", "outfox"] }
-37
View File
@@ -1,37 +0,0 @@
[package]
name = "nyxd-scraper"
version = "0.1.0"
authors.workspace = true
repository.workspace = true
homepage.workspace = true
documentation.workspace = true
edition.workspace = true
license.workspace = true
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
async-trait.workspace = true
const_format = "0.2.32"
cosmrs.workspace = true
eyre = "0.6.9"
futures.workspace = true
sha2 = "0.10.8"
sqlx = { workspace = true, features = ["runtime-tokio-rustls", "sqlite", "macros", "migrate", "time"] }
tendermint.workspace = true
tendermint-rpc = { workspace = true, features = ["websocket-client", "http-client"] }
thiserror.workspace = true
tokio = { workspace = true, features = ["full"] }
tokio-stream = "0.1.14"
tokio-util = { version = "0.7.10", features = ["rt"]}
tracing.workspace = true
url.workspace = true
# TEMP
nym-bin-common = { path = "../bin-common", features = ["basic_tracing"]}
[build-dependencies]
sqlx = { workspace = true, features = ["runtime-tokio-rustls", "sqlite", "macros", "migrate"] }
tokio = { workspace = true, features = ["rt-multi-thread", "macros"] }
-28
View File
@@ -1,28 +0,0 @@
// Copyright 2023 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
#[tokio::main]
async fn main() {
use sqlx::{Connection, SqliteConnection};
use std::env;
let out_dir = env::var("OUT_DIR").unwrap();
let database_path = format!("{out_dir}/scraper-example.sqlite");
let mut conn = SqliteConnection::connect(&format!("sqlite://{database_path}?mode=rwc"))
.await
.expect("Failed to create SQLx database connection");
sqlx::migrate!("./sql_migrations")
.run(&mut conn)
.await
.expect("Failed to perform SQLx migrations");
#[cfg(target_family = "unix")]
println!("cargo:rustc-env=DATABASE_URL=sqlite://{}", &database_path);
#[cfg(target_family = "windows")]
// for some strange reason we need to add a leading `/` to the windows path even though it's
// not a valid windows path... but hey, it works...
println!("cargo:rustc-env=DATABASE_URL=sqlite:///{}", &database_path);
}

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