Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 4f9b1d72b4 | |||
| 51db3d0d5d |
@@ -16,7 +16,7 @@ jobs:
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Get version from cargo.toml
|
||||
uses: mikefarah/yq@v4.47.1
|
||||
uses: mikefarah/yq@v4.45.4
|
||||
id: get_version
|
||||
with:
|
||||
cmd: yq -oy '.package.version' ${{ env.WORKING_DIRECTORY }}/Cargo.toml
|
||||
|
||||
@@ -16,7 +16,7 @@ jobs:
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Get version from cargo.toml
|
||||
uses: mikefarah/yq@v4.47.1
|
||||
uses: mikefarah/yq@v4.45.4
|
||||
id: get_version
|
||||
with:
|
||||
cmd: yq -oy '.package.version' ${{ env.WORKING_DIRECTORY }}/Cargo.toml
|
||||
|
||||
@@ -6,7 +6,7 @@ jobs:
|
||||
greeting:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/first-interaction@v3
|
||||
- uses: actions/first-interaction@v1
|
||||
with:
|
||||
repo-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
issue-message: 'Thank you for raising this issue'
|
||||
|
||||
@@ -31,7 +31,7 @@ jobs:
|
||||
- name: Check out repository code
|
||||
uses: actions/checkout@v4
|
||||
- name: Download report from previous job
|
||||
uses: actions/download-artifact@v5
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: report
|
||||
path: .github/workflows/support-files/notifications
|
||||
|
||||
@@ -25,7 +25,7 @@ jobs:
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Install Java
|
||||
uses: actions/setup-java@v5
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: "temurin"
|
||||
java-version: "17"
|
||||
@@ -91,7 +91,7 @@ jobs:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
- name: Download binary artifact
|
||||
uses: actions/download-artifact@v5
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: nyms5-apk-arch64
|
||||
path: apk
|
||||
|
||||
@@ -26,7 +26,7 @@ jobs:
|
||||
git config --global user.name "Lawrence Stalder"
|
||||
|
||||
- name: Get version from cargo.toml
|
||||
uses: mikefarah/yq@v4.47.1
|
||||
uses: mikefarah/yq@v4.45.4
|
||||
id: get_version
|
||||
with:
|
||||
cmd: yq -oy '.package.version' ${{ env.WORKING_DIRECTORY }}/nym-credential-proxy/Cargo.toml
|
||||
|
||||
@@ -26,7 +26,7 @@ jobs:
|
||||
git config --global user.name "Lawrence Stalder"
|
||||
|
||||
- name: Get version from cargo.toml
|
||||
uses: mikefarah/yq@v4.47.1
|
||||
uses: mikefarah/yq@v4.45.4
|
||||
id: get_version
|
||||
with:
|
||||
cmd: yq -oy '.package.version' ${{ env.WORKING_DIRECTORY }}/Cargo.toml
|
||||
|
||||
@@ -26,7 +26,7 @@ jobs:
|
||||
git config --global user.name "Lawrence Stalder"
|
||||
|
||||
- name: Get version from cargo.toml
|
||||
uses: mikefarah/yq@v4.47.1
|
||||
uses: mikefarah/yq@v4.45.4
|
||||
id: get_version
|
||||
with:
|
||||
cmd: yq -oy '.package.version' ${{ env.WORKING_DIRECTORY }}/nym-network-monitor/Cargo.toml
|
||||
|
||||
@@ -34,22 +34,18 @@ jobs:
|
||||
- name: Get version from cargo.toml
|
||||
id: get_version
|
||||
run: |
|
||||
VERSION=$(yq -oy '.package.version' ${{ env.WORKING_DIRECTORY }}/Cargo.toml)
|
||||
echo "result=$VERSION" >> $GITHUB_OUTPUT
|
||||
yq -oy '.package.version' ${{ env.WORKING_DIRECTORY }}/Cargo.toml
|
||||
|
||||
- name: Set GIT_TAG variable
|
||||
run: echo "GIT_TAG=${{ env.WORKING_DIRECTORY }}-${{ steps.get_version.outputs.result }}" >> $GITHUB_ENV
|
||||
|
||||
- name: Initialise RELEASE_TAG
|
||||
run: echo "RELEASE_TAG=" >> $GITHUB_ENV
|
||||
|
||||
- name: Set RELEASE_TAG for release
|
||||
- name: Set RELEASE_TAG variable
|
||||
if: github.event.inputs.release_image == 'true'
|
||||
run: echo "RELEASE_TAG=golden-" >> $GITHUB_ENV
|
||||
|
||||
|
||||
- name: Set IMAGE_NAME_AND_TAGS variable
|
||||
run: echo "IMAGE_NAME_AND_TAGS=${{ env.CONTAINER_NAME }}:${{ env.RELEASE_TAG }}${{ steps.get_version.outputs.result }}" >> $GITHUB_ENV
|
||||
|
||||
|
||||
- name: New env vars
|
||||
run: echo "RELEASE_TAG='$RELEASE_TAG' GIT_TAG='$GIT_TAG' IMAGE_NAME_AND_TAGS='$IMAGE_NAME_AND_TAGS'"
|
||||
|
||||
@@ -69,6 +65,6 @@ jobs:
|
||||
|
||||
- name: BuildAndPushImageOnHarbor
|
||||
run: |
|
||||
docker build -f ${{ env.WORKING_DIRECTORY }}/Dockerfile-pg . -t harbor.nymte.ch/nym/${{ env.IMAGE_NAME_AND_TAGS }} -t harbor.nymte.ch/nym/${{ env.CONTAINER_NAME }}:latest
|
||||
docker build -f ${{ env.WORKING_DIRECTORY }}/Dockerfile . -t harbor.nymte.ch/nym/${{ env.IMAGE_NAME_AND_TAGS }} -t harbor.nymte.ch/nym/${{ env.CONTAINER_NAME }}:latest
|
||||
docker push harbor.nymte.ch/nym/${{ env.CONTAINER_NAME }} --all-tags
|
||||
|
||||
|
||||
@@ -26,7 +26,7 @@ jobs:
|
||||
git config --global user.name "Lawrence Stalder"
|
||||
|
||||
- name: Get version from cargo.toml
|
||||
uses: mikefarah/yq@v4.47.1
|
||||
uses: mikefarah/yq@v4.45.4
|
||||
id: get_version
|
||||
with:
|
||||
cmd: yq -oy '.package.version' ${{ env.WORKING_DIRECTORY }}/nym-api/Cargo.toml
|
||||
|
||||
@@ -26,7 +26,7 @@ jobs:
|
||||
git config --global user.name "Lawrence Stalder"
|
||||
|
||||
- name: Get version from cargo.toml
|
||||
uses: mikefarah/yq@v4.47.1
|
||||
uses: mikefarah/yq@v4.45.4
|
||||
id: get_version
|
||||
with:
|
||||
cmd: yq -oy '.package.version' ${{ env.WORKING_DIRECTORY }}/Cargo.toml
|
||||
|
||||
@@ -26,7 +26,7 @@ jobs:
|
||||
git config --global user.name "Lawrence Stalder"
|
||||
|
||||
- name: Get version from cargo.toml
|
||||
uses: mikefarah/yq@v4.47.1
|
||||
uses: mikefarah/yq@v4.45.4
|
||||
id: get_version
|
||||
with:
|
||||
cmd: yq -oy '.package.version' ${{ env.WORKING_DIRECTORY }}/Cargo.toml
|
||||
|
||||
@@ -26,7 +26,7 @@ jobs:
|
||||
git config --global user.name "Lawrence Stalder"
|
||||
|
||||
- name: Get version from cargo.toml
|
||||
uses: mikefarah/yq@v4.47.1
|
||||
uses: mikefarah/yq@v4.45.4
|
||||
id: get_version
|
||||
with:
|
||||
cmd: yq -oy '.package.version' ${{ env.WORKING_DIRECTORY }}/Cargo.toml
|
||||
|
||||
@@ -26,7 +26,7 @@ jobs:
|
||||
git config --global user.name "Lawrence Stalder"
|
||||
|
||||
- name: Get version from cargo.toml
|
||||
uses: mikefarah/yq@v4.47.1
|
||||
uses: mikefarah/yq@v4.45.4
|
||||
id: get_version
|
||||
with:
|
||||
cmd: yq -oy '.package.version' ${{ env.WORKING_DIRECTORY }}/Cargo.toml
|
||||
|
||||
Generated
+70
-138
@@ -1345,7 +1345,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "117725a109d387c937a1533ce01b450cbde6b88abceea8473c4d7a85853cda3c"
|
||||
dependencies = [
|
||||
"lazy_static",
|
||||
"windows-sys 0.48.0",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1368,6 +1368,19 @@ dependencies = [
|
||||
"crossbeam-utils",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "console"
|
||||
version = "0.15.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "054ccb5b10f9f2cbf51eb355ca1d05c2d279ce1804688d0db74b4733a5aeafd8"
|
||||
dependencies = [
|
||||
"encode_unicode",
|
||||
"libc",
|
||||
"once_cell",
|
||||
"unicode-width 0.2.1",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "console"
|
||||
version = "0.16.0"
|
||||
@@ -1885,7 +1898,7 @@ dependencies = [
|
||||
"openssl-probe",
|
||||
"openssl-sys",
|
||||
"schannel",
|
||||
"socket2 0.5.10",
|
||||
"socket2",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
@@ -2357,7 +2370,7 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"cosmwasm-std",
|
||||
"quote",
|
||||
"syn 2.0.104",
|
||||
"syn 1.0.109",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3479,7 +3492,7 @@ dependencies = [
|
||||
"httpdate",
|
||||
"itoa",
|
||||
"pin-project-lite",
|
||||
"socket2 0.5.10",
|
||||
"socket2",
|
||||
"tokio",
|
||||
"tower-service",
|
||||
"tracing",
|
||||
@@ -3569,7 +3582,7 @@ dependencies = [
|
||||
"libc",
|
||||
"percent-encoding",
|
||||
"pin-project-lite",
|
||||
"socket2 0.5.10",
|
||||
"socket2",
|
||||
"tokio",
|
||||
"tower-service",
|
||||
"tracing",
|
||||
@@ -3814,13 +3827,26 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "indicatif"
|
||||
version = "0.17.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "183b3088984b400f4cfac3620d5e076c84da5364016b4f49473de574b2586235"
|
||||
dependencies = [
|
||||
"console 0.15.11",
|
||||
"number_prefix",
|
||||
"portable-atomic",
|
||||
"unicode-width 0.2.1",
|
||||
"web-time",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "indicatif"
|
||||
version = "0.18.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "70a646d946d06bedbbc4cac4c218acf4bbf2d87757a784857025f4d447e4e1cd"
|
||||
dependencies = [
|
||||
"console",
|
||||
"console 0.16.0",
|
||||
"portable-atomic",
|
||||
"unicode-width 0.2.1",
|
||||
"unit-prefix",
|
||||
@@ -3921,7 +3947,7 @@ version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b58db92f96b720de98181bbbe63c831e87005ab460c1bf306eb2622b4707997f"
|
||||
dependencies = [
|
||||
"socket2 0.5.10",
|
||||
"socket2",
|
||||
"widestring",
|
||||
"windows-sys 0.48.0",
|
||||
"winreg",
|
||||
@@ -3960,7 +3986,7 @@ checksum = "e04d7f318608d35d4b61ddd75cbdaee86b023ebe2bd5a66ee0915f0bf93095a9"
|
||||
dependencies = [
|
||||
"hermit-abi",
|
||||
"libc",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4493,9 +4519,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "mock_instant"
|
||||
version = "0.6.0"
|
||||
version = "0.5.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dce6dd36094cac388f119d2e9dc82dc730ef91c32a6222170d630e5414b956e6"
|
||||
checksum = "4e1d4c44418358edcac6e1d9ce59cea7fb38052429c7704033f1196f0c179e6a"
|
||||
|
||||
[[package]]
|
||||
name = "moka"
|
||||
@@ -4791,6 +4817,12 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "number_prefix"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "830b246a0e5f20af87141b25c173cd1b609bd7779a4617d6ec582abaf90870f3"
|
||||
|
||||
[[package]]
|
||||
name = "nym-api"
|
||||
version = "1.1.64"
|
||||
@@ -4831,7 +4863,6 @@ dependencies = [
|
||||
"nym-ecash-signer-check",
|
||||
"nym-ecash-time",
|
||||
"nym-gateway-client",
|
||||
"nym-http-api-client",
|
||||
"nym-http-api-common",
|
||||
"nym-mixnet-contract-common",
|
||||
"nym-node-requests",
|
||||
@@ -5043,7 +5074,6 @@ dependencies = [
|
||||
"nym-crypto",
|
||||
"nym-ecash-contract-common",
|
||||
"nym-ecash-time",
|
||||
"nym-http-api-client",
|
||||
"nym-id",
|
||||
"nym-mixnet-contract-common",
|
||||
"nym-multisig-contract-common",
|
||||
@@ -5132,7 +5162,6 @@ dependencies = [
|
||||
"nym-http-api-client",
|
||||
"nym-id",
|
||||
"nym-mixnet-client",
|
||||
"nym-mixnet-contract-common",
|
||||
"nym-network-defaults",
|
||||
"nym-nonexhaustive-delayqueue",
|
||||
"nym-pemstore",
|
||||
@@ -5182,7 +5211,6 @@ dependencies = [
|
||||
name = "nym-client-core-gateways-storage"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-trait",
|
||||
"cosmrs",
|
||||
"nym-crypto",
|
||||
@@ -5201,7 +5229,6 @@ dependencies = [
|
||||
name = "nym-client-core-surb-storage"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-trait",
|
||||
"dashmap",
|
||||
"nym-crypto",
|
||||
@@ -5344,7 +5371,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "nym-credential-proxy"
|
||||
version = "0.1.8"
|
||||
version = "0.1.7"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"axum 0.7.9",
|
||||
@@ -5362,7 +5389,6 @@ dependencies = [
|
||||
"nym-credentials-interface",
|
||||
"nym-crypto",
|
||||
"nym-ecash-contract-common",
|
||||
"nym-ecash-signer-check",
|
||||
"nym-http-api-common",
|
||||
"nym-network-defaults",
|
||||
"nym-validator-client",
|
||||
@@ -5413,7 +5439,6 @@ dependencies = [
|
||||
name = "nym-credential-storage"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-trait",
|
||||
"bincode",
|
||||
"log",
|
||||
@@ -5485,7 +5510,6 @@ dependencies = [
|
||||
"nym-crypto",
|
||||
"nym-ecash-contract-common",
|
||||
"nym-ecash-time",
|
||||
"nym-http-api-client",
|
||||
"nym-network-defaults",
|
||||
"nym-serde-helpers",
|
||||
"nym-validator-client",
|
||||
@@ -5585,7 +5609,6 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"nym-ecash-signer-check-types",
|
||||
"nym-http-api-client",
|
||||
"nym-network-defaults",
|
||||
"nym-validator-client",
|
||||
"semver 1.0.26",
|
||||
@@ -5618,6 +5641,14 @@ dependencies = [
|
||||
"time",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nym-execute"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"quote",
|
||||
"syn 1.0.109",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nym-exit-policy"
|
||||
version = "0.1.0"
|
||||
@@ -5687,7 +5718,6 @@ dependencies = [
|
||||
"nym-types",
|
||||
"nym-validator-client",
|
||||
"nym-wireguard",
|
||||
"nym-wireguard-private-metadata-server",
|
||||
"nym-wireguard-types",
|
||||
"rand 0.8.5",
|
||||
"serde",
|
||||
@@ -5777,7 +5807,6 @@ dependencies = [
|
||||
name = "nym-gateway-stats-storage"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"nym-node-metrics",
|
||||
"nym-sphinx",
|
||||
"nym-statistics-common",
|
||||
@@ -5793,7 +5822,6 @@ dependencies = [
|
||||
name = "nym-gateway-storage"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-trait",
|
||||
"bincode",
|
||||
"defguard_wireguard_rs",
|
||||
@@ -5850,13 +5878,10 @@ dependencies = [
|
||||
"mime",
|
||||
"nym-bin-common",
|
||||
"nym-http-api-common",
|
||||
"nym-network-defaults",
|
||||
"once_cell",
|
||||
"reqwest 0.12.22",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"serde_plain",
|
||||
"serde_yaml",
|
||||
"thiserror 2.0.12",
|
||||
"tokio",
|
||||
"tracing",
|
||||
@@ -6113,8 +6138,6 @@ dependencies = [
|
||||
"nym-client-core",
|
||||
"nym-crypto",
|
||||
"nym-gateway-requests",
|
||||
"nym-http-api-client",
|
||||
"nym-mixnet-contract-common",
|
||||
"nym-network-defaults",
|
||||
"nym-sdk",
|
||||
"nym-sphinx",
|
||||
@@ -6211,7 +6234,7 @@ dependencies = [
|
||||
"hkdf",
|
||||
"human-repr",
|
||||
"humantime-serde",
|
||||
"indicatif",
|
||||
"indicatif 0.17.11",
|
||||
"ipnetwork",
|
||||
"lioness",
|
||||
"nym-bin-common",
|
||||
@@ -6327,7 +6350,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "nym-node-status-api"
|
||||
version = "3.3.1"
|
||||
version = "3.3.0"
|
||||
dependencies = [
|
||||
"ammonia",
|
||||
"anyhow",
|
||||
@@ -6582,7 +6605,6 @@ dependencies = [
|
||||
"nym-credentials-interface",
|
||||
"nym-crypto",
|
||||
"nym-gateway-requests",
|
||||
"nym-http-api-client",
|
||||
"nym-network-defaults",
|
||||
"nym-ordered-buffer",
|
||||
"nym-service-providers-common",
|
||||
@@ -6793,12 +6815,10 @@ dependencies = [
|
||||
name = "nym-sphinx-addressing"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bincode",
|
||||
"nym-crypto",
|
||||
"nym-sphinx-types",
|
||||
"rand 0.8.5",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.12",
|
||||
]
|
||||
|
||||
@@ -7158,7 +7178,6 @@ dependencies = [
|
||||
"nym-credentials-interface",
|
||||
"nym-crypto",
|
||||
"nym-ecash-time",
|
||||
"nym-http-api-client",
|
||||
"nym-network-defaults",
|
||||
"nym-pemstore",
|
||||
"nym-serde-helpers",
|
||||
@@ -7188,9 +7207,7 @@ dependencies = [
|
||||
"bytes",
|
||||
"futures",
|
||||
"humantime",
|
||||
"nym-api-requests",
|
||||
"nym-crypto",
|
||||
"nym-http-api-client",
|
||||
"nym-task",
|
||||
"nym-validator-client",
|
||||
"rand 0.8.5",
|
||||
@@ -7293,68 +7310,6 @@ dependencies = [
|
||||
"x25519-dalek",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nym-wireguard-private-metadata-client"
|
||||
version = "1.0.0"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"nym-http-api-client",
|
||||
"nym-wireguard-private-metadata-shared",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nym-wireguard-private-metadata-server"
|
||||
version = "1.0.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-trait",
|
||||
"axum 0.7.9",
|
||||
"futures",
|
||||
"nym-credential-verification",
|
||||
"nym-credentials-interface",
|
||||
"nym-http-api-common",
|
||||
"nym-wireguard",
|
||||
"nym-wireguard-private-metadata-shared",
|
||||
"tokio",
|
||||
"tokio-util",
|
||||
"tower-http 0.5.2",
|
||||
"utoipa",
|
||||
"utoipa-swagger-ui",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nym-wireguard-private-metadata-shared"
|
||||
version = "1.0.0"
|
||||
dependencies = [
|
||||
"axum 0.7.9",
|
||||
"bincode",
|
||||
"nym-credentials-interface",
|
||||
"schemars 0.8.22",
|
||||
"serde",
|
||||
"thiserror 2.0.12",
|
||||
"utoipa",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nym-wireguard-private-metadata-tests"
|
||||
version = "1.0.0"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"axum 0.7.9",
|
||||
"nym-credential-verification",
|
||||
"nym-credentials-interface",
|
||||
"nym-http-api-client",
|
||||
"nym-http-api-common",
|
||||
"nym-wireguard",
|
||||
"nym-wireguard-private-metadata-client",
|
||||
"nym-wireguard-private-metadata-server",
|
||||
"nym-wireguard-private-metadata-shared",
|
||||
"tokio",
|
||||
"tower-http 0.5.2",
|
||||
"utoipa",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nym-wireguard-types"
|
||||
version = "0.1.0"
|
||||
@@ -7435,7 +7390,6 @@ dependencies = [
|
||||
name = "nyxd-scraper"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-trait",
|
||||
"const_format",
|
||||
"cosmrs",
|
||||
@@ -8227,7 +8181,7 @@ dependencies = [
|
||||
"quinn-udp",
|
||||
"rustc-hash",
|
||||
"rustls 0.23.29",
|
||||
"socket2 0.5.10",
|
||||
"socket2",
|
||||
"thiserror 2.0.12",
|
||||
"tokio",
|
||||
"tracing",
|
||||
@@ -8264,9 +8218,9 @@ dependencies = [
|
||||
"cfg_aliases",
|
||||
"libc",
|
||||
"once_cell",
|
||||
"socket2 0.5.10",
|
||||
"socket2",
|
||||
"tracing",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -8750,7 +8704,7 @@ dependencies = [
|
||||
"errno",
|
||||
"libc",
|
||||
"linux-raw-sys 0.4.15",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -9259,15 +9213,6 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_plain"
|
||||
version = "1.0.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9ce1fc6db65a611022b23a0dec6975d63fb80a302cb3388835ff02c097258d50"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_repr"
|
||||
version = "0.1.20"
|
||||
@@ -9481,9 +9426,9 @@ checksum = "56199f7ddabf13fe5074ce809e7d3f42b42ae711800501b5b16ea82ad029c39d"
|
||||
|
||||
[[package]]
|
||||
name = "slab"
|
||||
version = "0.4.11"
|
||||
version = "0.4.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7a2ae44ef20feb57a68b23d846850f861394c2e02dc425a50098ae8c90267589"
|
||||
checksum = "04dc19736151f35336d325007ac991178d504a119863a2fcb3758cdb5e52c50d"
|
||||
|
||||
[[package]]
|
||||
name = "sluice"
|
||||
@@ -9559,16 +9504,6 @@ dependencies = [
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "socket2"
|
||||
version = "0.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "233504af464074f9d066d7b5416c5f9b894a5862a6506e306f7b816cdd6f1807"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sphinx-packet"
|
||||
version = "0.6.0"
|
||||
@@ -10053,7 +9988,7 @@ dependencies = [
|
||||
"getrandom 0.3.3",
|
||||
"once_cell",
|
||||
"rustix 1.0.8",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -10177,11 +10112,11 @@ dependencies = [
|
||||
"bip39",
|
||||
"bs58",
|
||||
"clap",
|
||||
"console",
|
||||
"console 0.15.11",
|
||||
"cw-utils",
|
||||
"dkg-bypass-contract",
|
||||
"humantime",
|
||||
"indicatif",
|
||||
"indicatif 0.17.11",
|
||||
"nym-bin-common",
|
||||
"nym-coconut-dkg-common",
|
||||
"nym-compact-ecash",
|
||||
@@ -10190,7 +10125,6 @@ dependencies = [
|
||||
"nym-crypto",
|
||||
"nym-ecash-contract-common",
|
||||
"nym-group-contract-common",
|
||||
"nym-http-api-client",
|
||||
"nym-mixnet-contract-common",
|
||||
"nym-multisig-contract-common",
|
||||
"nym-pemstore",
|
||||
@@ -10362,9 +10296,9 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
|
||||
|
||||
[[package]]
|
||||
name = "tokio"
|
||||
version = "1.47.1"
|
||||
version = "1.46.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "89e49afdadebb872d3145a5638b59eb0691ea23e46ca484037cfab3b76b95038"
|
||||
checksum = "0cc3a2344dafbe23a245241fe8b09735b521110d30fcefbbd5feb1797ca35d17"
|
||||
dependencies = [
|
||||
"backtrace",
|
||||
"bytes",
|
||||
@@ -10375,10 +10309,10 @@ dependencies = [
|
||||
"pin-project-lite",
|
||||
"signal-hook-registry",
|
||||
"slab",
|
||||
"socket2 0.6.0",
|
||||
"socket2",
|
||||
"tokio-macros",
|
||||
"tracing",
|
||||
"windows-sys 0.59.0",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -10412,7 +10346,7 @@ dependencies = [
|
||||
"postgres-protocol",
|
||||
"postgres-types",
|
||||
"rand 0.9.2",
|
||||
"socket2 0.5.10",
|
||||
"socket2",
|
||||
"tokio",
|
||||
"tokio-util",
|
||||
"whoami",
|
||||
@@ -10588,7 +10522,7 @@ dependencies = [
|
||||
"percent-encoding",
|
||||
"pin-project",
|
||||
"prost",
|
||||
"socket2 0.5.10",
|
||||
"socket2",
|
||||
"tokio",
|
||||
"tokio-stream",
|
||||
"tower 0.4.13",
|
||||
@@ -10739,7 +10673,7 @@ version = "0.3.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8c714cc8fc46db04fcfddbd274c6ef59bebb1b435155984e7c6e89c3ce66f200"
|
||||
dependencies = [
|
||||
"indicatif",
|
||||
"indicatif 0.18.0",
|
||||
"tracing",
|
||||
"tracing-core",
|
||||
"tracing-subscriber",
|
||||
@@ -11313,7 +11247,6 @@ dependencies = [
|
||||
"clap",
|
||||
"comfy-table",
|
||||
"nym-bin-common",
|
||||
"nym-http-api-client",
|
||||
"nym-network-defaults",
|
||||
"nym-validator-client",
|
||||
"serde",
|
||||
@@ -11544,7 +11477,6 @@ dependencies = [
|
||||
"nym-credential-storage",
|
||||
"nym-crypto",
|
||||
"nym-gateway-client",
|
||||
"nym-http-api-client",
|
||||
"nym-sphinx",
|
||||
"nym-sphinx-acknowledgements",
|
||||
"nym-statistics-common",
|
||||
@@ -11737,7 +11669,7 @@ version = "0.1.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf221c93e13a30d793f7645a0e7762c55d169dbb0a49671918a2319d289b10bb"
|
||||
dependencies = [
|
||||
"windows-sys 0.48.0",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
+7
-11
@@ -53,6 +53,7 @@ members = [
|
||||
"common/ecash-signer-check",
|
||||
"common/ecash-signer-check-types",
|
||||
"common/ecash-time",
|
||||
"common/execute",
|
||||
"common/exit-policy",
|
||||
"common/gateway-requests",
|
||||
"common/gateway-stats-storage",
|
||||
@@ -101,10 +102,6 @@ members = [
|
||||
"common/wasm/storage",
|
||||
"common/wasm/utils",
|
||||
"common/wireguard",
|
||||
"common/wireguard-private-metadata/client",
|
||||
"common/wireguard-private-metadata/server",
|
||||
"common/wireguard-private-metadata/shared",
|
||||
"common/wireguard-private-metadata/tests",
|
||||
"common/wireguard-types",
|
||||
"common/zulip-client",
|
||||
"documentation/autodoc",
|
||||
@@ -172,7 +169,7 @@ default-members = [
|
||||
"tools/nymvisor",
|
||||
]
|
||||
|
||||
exclude = ["explorer", "contracts", "nym-wallet", "cpu-cycles"]
|
||||
exclude = ["contracts", "nym-wallet", "cpu-cycles"]
|
||||
|
||||
[workspace.package]
|
||||
authors = ["Nym Technologies SA"]
|
||||
@@ -181,7 +178,7 @@ homepage = "https://nymtech.net"
|
||||
documentation = "https://nymtech.net"
|
||||
edition = "2021"
|
||||
license = "Apache-2.0"
|
||||
rust-version = "1.81"
|
||||
rust-version = "1.80"
|
||||
readme = "README.md"
|
||||
|
||||
[workspace.dependencies]
|
||||
@@ -222,7 +219,7 @@ clap_complete = "4.5"
|
||||
clap_complete_fig = "4.5"
|
||||
colored = "2.2"
|
||||
comfy-table = "7.1.4"
|
||||
console = "0.16.0"
|
||||
console = "0.15.11"
|
||||
console-subscriber = "0.4.1"
|
||||
console_error_panic_hook = "0.1"
|
||||
const-str = "0.5.6"
|
||||
@@ -269,7 +266,7 @@ humantime = "2.2.0"
|
||||
humantime-serde = "1.1.1"
|
||||
hyper = "1.6.0"
|
||||
hyper-util = "0.1"
|
||||
indicatif = "0.18.0"
|
||||
indicatif = "0.17.11"
|
||||
inquire = "0.6.2"
|
||||
ip_network = "0.4.1"
|
||||
ipnetwork = "0.20"
|
||||
@@ -317,7 +314,6 @@ serde_json_path = "0.7.2"
|
||||
serde_repr = "0.1"
|
||||
serde_with = "3.9.0"
|
||||
serde_yaml = "0.9.25"
|
||||
serde_plain = "1.0.2"
|
||||
sha2 = "0.10.9"
|
||||
si-scale = "0.2.3"
|
||||
snow = "0.9.6"
|
||||
@@ -326,14 +322,14 @@ sqlx = "0.8.6"
|
||||
strum = "0.27.2"
|
||||
strum_macros = "0.27.2"
|
||||
subtle-encoding = "0.5"
|
||||
syn = "2"
|
||||
syn = "1"
|
||||
sysinfo = "0.37.0"
|
||||
tap = "1.0.1"
|
||||
tar = "0.4.44"
|
||||
tempfile = "3.20"
|
||||
thiserror = "2.0"
|
||||
time = "0.3.41"
|
||||
tokio = "1.47"
|
||||
tokio = "1.45"
|
||||
tokio-postgres = "0.7"
|
||||
tokio-stream = "0.1.17"
|
||||
tokio-test = "0.4.4"
|
||||
|
||||
@@ -13,7 +13,7 @@ use nym_credentials_interface::{
|
||||
};
|
||||
use nym_ecash_time::Date;
|
||||
use nym_validator_client::coconut::all_ecash_api_clients;
|
||||
use nym_validator_client::nym_api::{EpochId, NymApiClientExt};
|
||||
use nym_validator_client::nym_api::EpochId;
|
||||
use nym_validator_client::nyxd::contract_traits::DkgQueryClient;
|
||||
use nym_validator_client::EcashApiClient;
|
||||
use rand::prelude::SliceRandom;
|
||||
|
||||
@@ -53,7 +53,6 @@ nym-client-core-config-types = { path = "./config-types", features = [
|
||||
nym-client-core-surb-storage = { path = "./surb-storage" }
|
||||
nym-client-core-gateways-storage = { path = "./gateways-storage" }
|
||||
nym-ecash-time = { path = "../ecash-time" }
|
||||
nym-mixnet-contract-common = { path = "../cosmwasm-smart-contracts/mixnet-contract" }
|
||||
|
||||
[target."cfg(not(target_arch = \"wasm32\"))".dependencies]
|
||||
nym-mixnet-client = { path = "../client-libs/mixnet-client", default-features = false }
|
||||
|
||||
@@ -3,7 +3,6 @@ name = "nym-client-core-gateways-storage"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
@@ -27,7 +26,6 @@ features = ["runtime-tokio-rustls", "sqlite", "macros", "migrate", "time"]
|
||||
optional = true
|
||||
|
||||
[build-dependencies]
|
||||
anyhow = { workspace = true }
|
||||
tokio = { workspace = true, features = ["rt-multi-thread", "macros"] }
|
||||
sqlx = { workspace = true, features = [
|
||||
"runtime-tokio-rustls",
|
||||
|
||||
@@ -2,30 +2,23 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
async fn main() {
|
||||
#[cfg(feature = "fs-gateways-storage")]
|
||||
{
|
||||
use anyhow::Context;
|
||||
use sqlx::{Connection, SqliteConnection};
|
||||
use std::env;
|
||||
|
||||
let out_dir = env::var("OUT_DIR")?;
|
||||
let out_dir = env::var("OUT_DIR").unwrap();
|
||||
let database_path = format!("{out_dir}/gateways-storage-example.sqlite");
|
||||
|
||||
// remove the db file if it already existed from previous build
|
||||
// in case it was from a different branch
|
||||
if std::fs::exists(&database_path)? {
|
||||
std::fs::remove_file(&database_path)?;
|
||||
}
|
||||
|
||||
let mut conn = SqliteConnection::connect(&format!("sqlite://{database_path}?mode=rwc"))
|
||||
.await
|
||||
.context("Failed to create SQLx database connection")?;
|
||||
.expect("Failed to create SQLx database connection");
|
||||
|
||||
sqlx::migrate!("./fs_gateways_migrations")
|
||||
.run(&mut conn)
|
||||
.await
|
||||
.context("Failed to perform SQLx migrations")?;
|
||||
.expect("Failed to perform SQLx migrations");
|
||||
|
||||
#[cfg(target_family = "unix")]
|
||||
println!("cargo:rustc-env=DATABASE_URL=sqlite://{}", &database_path);
|
||||
@@ -35,6 +28,4 @@ async fn main() -> anyhow::Result<()> {
|
||||
// not a valid windows path... but hey, it works...
|
||||
println!("cargo:rustc-env=DATABASE_URL=sqlite:///{}", &database_path);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -57,7 +57,7 @@ use nym_task::{TaskClient, TaskHandle};
|
||||
use nym_topology::provider_trait::TopologyProvider;
|
||||
use nym_topology::HardcodedTopologyProvider;
|
||||
use nym_validator_client::nym_api::NymApiClientExt;
|
||||
use nym_validator_client::{nyxd::contract_traits::DkgQueryClient, UserAgent};
|
||||
use nym_validator_client::{nyxd::contract_traits::DkgQueryClient, NymApiClient, UserAgent};
|
||||
use rand::prelude::SliceRandom;
|
||||
use rand::rngs::OsRng;
|
||||
use rand::thread_rng;
|
||||
@@ -566,7 +566,7 @@ where
|
||||
custom_provider: Option<Box<dyn TopologyProvider + Send + Sync>>,
|
||||
config_topology: config::Topology,
|
||||
nym_api_urls: Vec<Url>,
|
||||
nym_api_client: nym_http_api_client::Client,
|
||||
nym_api_client: NymApiClient,
|
||||
) -> Box<dyn TopologyProvider + Send + Sync> {
|
||||
// if no custom provider was ... provided ..., create one using nym-api
|
||||
custom_provider.unwrap_or_else(|| {
|
||||
@@ -749,42 +749,21 @@ where
|
||||
setup_gateway(setup_method, key_store, details_store).await
|
||||
}
|
||||
|
||||
fn construct_nym_api_client(
|
||||
config: &Config,
|
||||
user_agent: Option<UserAgent>,
|
||||
) -> Result<nym_http_api_client::Client, ClientCoreError> {
|
||||
fn construct_nym_api_client(config: &Config, user_agent: Option<UserAgent>) -> NymApiClient {
|
||||
let mut nym_api_urls = config.get_nym_api_endpoints();
|
||||
nym_api_urls.shuffle(&mut thread_rng());
|
||||
|
||||
let mut builder =
|
||||
nym_http_api_client::Client::builder(nym_api_urls[0].clone()).map_err(|e| {
|
||||
ClientCoreError::NymApiQueryFailure {
|
||||
source:
|
||||
nym_validator_client::nym_api::error::NymAPIError::GenericRequestFailure(
|
||||
e.to_string(),
|
||||
),
|
||||
}
|
||||
})?;
|
||||
|
||||
if let Some(user_agent) = user_agent {
|
||||
builder = builder.with_user_agent(user_agent);
|
||||
NymApiClient::new_with_user_agent(nym_api_urls[0].clone(), user_agent)
|
||||
} else {
|
||||
NymApiClient::new(nym_api_urls[0].clone())
|
||||
}
|
||||
|
||||
builder = builder.with_bincode();
|
||||
|
||||
builder
|
||||
.build()
|
||||
.map_err(|e| ClientCoreError::NymApiQueryFailure {
|
||||
source: nym_validator_client::nym_api::error::NymAPIError::GenericRequestFailure(
|
||||
e.to_string(),
|
||||
),
|
||||
})
|
||||
}
|
||||
|
||||
async fn determine_key_rotation_state(
|
||||
client: &nym_http_api_client::Client,
|
||||
client: &NymApiClient,
|
||||
) -> Result<KeyRotationConfig, ClientCoreError> {
|
||||
Ok(client.get_key_rotation_info().await?.into())
|
||||
Ok(client.nym_api.get_key_rotation_info().await?.into())
|
||||
}
|
||||
|
||||
pub async fn start_base(mut self) -> Result<BaseClient, ClientCoreError>
|
||||
@@ -851,7 +830,7 @@ where
|
||||
.dkg_query_client
|
||||
.map(|client| BandwidthController::new(credential_store, client));
|
||||
|
||||
let nym_api_client = Self::construct_nym_api_client(&self.config, self.user_agent.clone())?;
|
||||
let nym_api_client = Self::construct_nym_api_client(&self.config, self.user_agent.clone());
|
||||
let key_rotation_config = Self::determine_key_rotation_state(&nym_api_client).await?;
|
||||
|
||||
let topology_provider = Self::setup_topology_provider(
|
||||
|
||||
@@ -2,10 +2,8 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
use async_trait::async_trait;
|
||||
use nym_mixnet_contract_common::EpochRewardedSet;
|
||||
use nym_topology::provider_trait::{ToTopologyMetadata, TopologyProvider};
|
||||
use nym_topology::NymTopology;
|
||||
use nym_validator_client::nym_api::NymApiClientExt;
|
||||
use rand::prelude::SliceRandom;
|
||||
use rand::thread_rng;
|
||||
use std::cmp::min;
|
||||
@@ -41,43 +39,30 @@ impl Config {
|
||||
pub struct NymApiTopologyProvider {
|
||||
config: Config,
|
||||
|
||||
validator_client: nym_http_api_client::Client,
|
||||
validator_client: nym_validator_client::client::NymApiClient,
|
||||
nym_api_urls: Vec<Url>,
|
||||
currently_used_api: usize,
|
||||
use_bincode: bool,
|
||||
}
|
||||
|
||||
impl NymApiTopologyProvider {
|
||||
pub fn new(
|
||||
config: impl Into<Config>,
|
||||
mut nym_api_urls: Vec<Url>,
|
||||
validator_client: nym_http_api_client::Client,
|
||||
mut validator_client: nym_validator_client::client::NymApiClient,
|
||||
) -> Self {
|
||||
nym_api_urls.shuffle(&mut thread_rng());
|
||||
let mut provider = NymApiTopologyProvider {
|
||||
validator_client.change_nym_api(nym_api_urls[0].clone());
|
||||
|
||||
NymApiTopologyProvider {
|
||||
config: config.into(),
|
||||
validator_client,
|
||||
nym_api_urls,
|
||||
currently_used_api: 0,
|
||||
use_bincode: true,
|
||||
};
|
||||
// Set all API URLs - the client will try them in order with automatic failover
|
||||
provider.validator_client.change_base_urls(
|
||||
provider
|
||||
.nym_api_urls
|
||||
.iter()
|
||||
.map(|u| u.clone().into())
|
||||
.collect(),
|
||||
);
|
||||
provider
|
||||
}
|
||||
}
|
||||
|
||||
pub fn disable_bincode(&mut self) {
|
||||
self.use_bincode = false;
|
||||
// Note: The unified client doesn't support toggling bincode after creation.
|
||||
// This would require recreating the client without bincode.
|
||||
// For now, we'll track the preference but it won't take effect.
|
||||
warn!("Disabling bincode on existing client is not currently supported");
|
||||
self.validator_client.use_bincode = false;
|
||||
}
|
||||
|
||||
fn use_next_nym_api(&mut self) {
|
||||
@@ -87,19 +72,8 @@ impl NymApiTopologyProvider {
|
||||
}
|
||||
|
||||
self.currently_used_api = (self.currently_used_api + 1) % self.nym_api_urls.len();
|
||||
|
||||
// Provide all URLs starting from the next one in rotation order
|
||||
// This enables automatic failover to other endpoints
|
||||
let rotated_urls: Vec<_> = self
|
||||
.nym_api_urls
|
||||
.iter()
|
||||
.cycle()
|
||||
.skip(self.currently_used_api)
|
||||
.take(self.nym_api_urls.len())
|
||||
.map(|u| u.clone().into())
|
||||
.collect();
|
||||
|
||||
self.validator_client.change_base_urls(rotated_urls)
|
||||
self.validator_client
|
||||
.change_nym_api(self.nym_api_urls[self.currently_used_api].clone())
|
||||
}
|
||||
|
||||
async fn get_current_compatible_topology(&mut self) -> Option<NymTopology> {
|
||||
@@ -125,13 +99,8 @@ impl NymApiTopologyProvider {
|
||||
.filter(|n| n.performance.round_to_integer() >= self.config.min_node_performance())
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let epoch_rewarded_set: EpochRewardedSet = rewarded_set.into();
|
||||
NymTopology::new(
|
||||
metadata.to_topology_metadata(),
|
||||
epoch_rewarded_set,
|
||||
Vec::new(),
|
||||
)
|
||||
.with_skimmed_nodes(&nodes_filtered)
|
||||
NymTopology::new(metadata.to_topology_metadata(), rewarded_set, Vec::new())
|
||||
.with_skimmed_nodes(&nodes_filtered)
|
||||
} else {
|
||||
// if we're not using extended topology, we're only getting active set mixnodes and gateways
|
||||
|
||||
@@ -179,13 +148,8 @@ impl NymApiTopologyProvider {
|
||||
}
|
||||
}
|
||||
|
||||
let epoch_rewarded_set: EpochRewardedSet = rewarded_set.into();
|
||||
NymTopology::new(
|
||||
metadata.to_topology_metadata(),
|
||||
epoch_rewarded_set,
|
||||
Vec::new(),
|
||||
)
|
||||
.with_skimmed_nodes(&nodes)
|
||||
NymTopology::new(metadata.to_topology_metadata(), rewarded_set, Vec::new())
|
||||
.with_skimmed_nodes(&nodes)
|
||||
};
|
||||
|
||||
if !topology.is_minimally_routable() {
|
||||
|
||||
@@ -7,8 +7,7 @@ use futures::{SinkExt, StreamExt};
|
||||
use nym_crypto::asymmetric::ed25519;
|
||||
use nym_gateway_client::GatewayClient;
|
||||
use nym_topology::node::RoutingNode;
|
||||
use nym_validator_client::client::{IdentityKeyRef, NymApiClientExt};
|
||||
use nym_validator_client::nym_nodes::SkimmedNodesWithMetadata;
|
||||
use nym_validator_client::client::IdentityKeyRef;
|
||||
use nym_validator_client::UserAgent;
|
||||
use rand::{seq::SliceRandom, Rng};
|
||||
#[cfg(unix)]
|
||||
@@ -84,48 +83,6 @@ struct GatewayWithLatency<'a, G: ConnectableGateway> {
|
||||
latency: Duration,
|
||||
}
|
||||
|
||||
// Helper to collect all pages of entry nodes - replicates NymApiClient's convenience method
|
||||
async fn get_all_basic_entry_nodes_with_metadata(
|
||||
client: &nym_http_api_client::Client,
|
||||
use_bincode: bool,
|
||||
) -> Result<SkimmedNodesWithMetadata, ClientCoreError> {
|
||||
// Get first page to obtain metadata
|
||||
let mut page = 0;
|
||||
let res = client
|
||||
.get_basic_entry_assigned_nodes_v2(false, Some(page), None, use_bincode)
|
||||
.await?;
|
||||
let mut nodes = res.nodes.data;
|
||||
let metadata = res.metadata;
|
||||
|
||||
if res.nodes.pagination.total == nodes.len() {
|
||||
return Ok(SkimmedNodesWithMetadata::new(nodes, metadata));
|
||||
}
|
||||
|
||||
page += 1;
|
||||
|
||||
// Collect remaining pages
|
||||
loop {
|
||||
let mut res = client
|
||||
.get_basic_entry_assigned_nodes_v2(false, Some(page), None, use_bincode)
|
||||
.await?;
|
||||
|
||||
if !metadata.consistency_check(&res.metadata) {
|
||||
return Err(ClientCoreError::ValidatorClientError(
|
||||
nym_validator_client::ValidatorClientError::InconsistentPagedMetadata,
|
||||
));
|
||||
}
|
||||
|
||||
nodes.append(&mut res.nodes.data);
|
||||
if nodes.len() < res.nodes.pagination.total {
|
||||
page += 1
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(SkimmedNodesWithMetadata::new(nodes, metadata))
|
||||
}
|
||||
|
||||
impl<'a, G: ConnectableGateway> GatewayWithLatency<'a, G> {
|
||||
fn new(gateway: &'a G, latency: Duration) -> Self {
|
||||
GatewayWithLatency { gateway, latency }
|
||||
@@ -142,30 +99,16 @@ pub async fn gateways_for_init<R: Rng>(
|
||||
let nym_api = nym_apis
|
||||
.choose(rng)
|
||||
.ok_or(ClientCoreError::ListOfNymApisIsEmpty)?;
|
||||
|
||||
// Use the unified HTTP client directly with optional user agent
|
||||
let mut builder = nym_http_api_client::Client::builder(nym_api.clone())
|
||||
.map_err(|e| {
|
||||
ClientCoreError::ValidatorClientError(
|
||||
nym_validator_client::ValidatorClientError::NymAPIError { source: e },
|
||||
)
|
||||
})?
|
||||
.with_bincode(); // Use bincode for better performance
|
||||
|
||||
if let Some(user_agent) = user_agent {
|
||||
builder = builder.with_user_agent(user_agent);
|
||||
}
|
||||
|
||||
let client = builder.build().map_err(|e| {
|
||||
ClientCoreError::ValidatorClientError(
|
||||
nym_validator_client::ValidatorClientError::NymAPIError { source: e },
|
||||
)
|
||||
})?;
|
||||
let client = if let Some(user_agent) = user_agent {
|
||||
nym_validator_client::client::NymApiClient::new_with_user_agent(nym_api.clone(), user_agent)
|
||||
} else {
|
||||
nym_validator_client::client::NymApiClient::new(nym_api.clone())
|
||||
};
|
||||
|
||||
tracing::debug!("Fetching list of gateways from: {nym_api}");
|
||||
|
||||
// Use our helper to handle pagination
|
||||
let gateways = get_all_basic_entry_nodes_with_metadata(&client, true)
|
||||
let gateways = client
|
||||
.get_all_basic_entry_assigned_nodes_with_metadata()
|
||||
.await?
|
||||
.nodes;
|
||||
info!("nym api reports {} gateways", gateways.len());
|
||||
|
||||
@@ -30,7 +30,6 @@ optional = true
|
||||
path = "../../../sqlx-pool-guard"
|
||||
|
||||
[build-dependencies]
|
||||
anyhow = { workspace = true }
|
||||
tokio = { workspace = true, features = ["rt-multi-thread", "macros"] }
|
||||
sqlx = { workspace = true, features = [
|
||||
"runtime-tokio-rustls",
|
||||
|
||||
@@ -2,24 +2,23 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
async fn main() {
|
||||
#[cfg(feature = "fs-surb-storage")]
|
||||
{
|
||||
use anyhow::Context;
|
||||
use sqlx::{Connection, SqliteConnection};
|
||||
use std::env;
|
||||
|
||||
let out_dir = env::var("OUT_DIR")?;
|
||||
let out_dir = env::var("OUT_DIR").unwrap();
|
||||
let database_path = format!("{out_dir}/fs-surbs-example.sqlite");
|
||||
|
||||
let mut conn = SqliteConnection::connect(&format!("sqlite://{database_path}?mode=rwc"))
|
||||
.await
|
||||
.context("Failed to create SQLx database connection")?;
|
||||
.expect("Failed to create SQLx database connection");
|
||||
|
||||
sqlx::migrate!("./fs_surbs_migrations")
|
||||
.run(&mut conn)
|
||||
.await
|
||||
.context("Failed to perform SQLx migrations")?;
|
||||
.expect("Failed to perform SQLx migrations");
|
||||
|
||||
#[cfg(target_family = "unix")]
|
||||
println!("cargo:rustc-env=DATABASE_URL=sqlite://{}", &database_path);
|
||||
@@ -29,6 +28,4 @@ async fn main() -> anyhow::Result<()> {
|
||||
// not a valid windows path... but hey, it works...
|
||||
println!("cargo:rustc-env=DATABASE_URL=sqlite:///{}", &database_path);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -5,8 +5,8 @@ use crate::nyxd::{self, NyxdClient};
|
||||
use crate::signing::direct_wallet::DirectSecp256k1HdWallet;
|
||||
use crate::signing::signer::{NoSigner, OfflineSigner};
|
||||
use crate::{
|
||||
DirectSigningReqwestRpcValidatorClient, QueryReqwestRpcValidatorClient, ReqwestRpcClient,
|
||||
ValidatorClientError,
|
||||
nym_api, DirectSigningReqwestRpcValidatorClient, QueryReqwestRpcValidatorClient,
|
||||
ReqwestRpcClient, ValidatorClientError,
|
||||
};
|
||||
use nym_api_requests::ecash::models::{
|
||||
AggregatedCoinIndicesSignatureResponse, AggregatedExpirationDateSignatureResponse,
|
||||
@@ -153,7 +153,7 @@ impl Config {
|
||||
pub struct Client<C, S = NoSigner> {
|
||||
// ideally they would have been read-only, but unfortunately rust doesn't have such features
|
||||
// #[deprecated(note = "please use `nym_api_client` instead")]
|
||||
pub nym_api: nym_http_api_client::Client,
|
||||
pub nym_api: nym_api::Client,
|
||||
// pub nym_api_client: NymApiClient,
|
||||
pub nyxd: NyxdClient<C, S>,
|
||||
}
|
||||
@@ -214,7 +214,7 @@ impl Client<ReqwestRpcClient> {
|
||||
|
||||
impl<C> Client<C> {
|
||||
pub fn new_with_rpc_client(config: Config, rpc_client: C) -> Self {
|
||||
let nym_api_client = nym_http_api_client::Client::new(config.api_url.clone(), None);
|
||||
let nym_api_client = nym_api::Client::new(config.api_url.clone(), None);
|
||||
|
||||
Client {
|
||||
nym_api: nym_api_client,
|
||||
@@ -228,7 +228,7 @@ impl<C, S> Client<C, S> {
|
||||
where
|
||||
S: OfflineSigner,
|
||||
{
|
||||
let nym_api_client = nym_http_api_client::Client::new(config.api_url.clone(), None);
|
||||
let nym_api_client = nym_api::Client::new(config.api_url.clone(), None);
|
||||
|
||||
Client {
|
||||
nym_api: nym_api_client,
|
||||
@@ -385,25 +385,38 @@ impl<C, S> Client<C, S> {
|
||||
}
|
||||
}
|
||||
|
||||
/// DEPRECATED: Use nym_http_api_client::Client with from_network() or with_bincode() instead
|
||||
#[deprecated(
|
||||
since = "1.2.0",
|
||||
note = "Use nym_http_api_client::Client::from_network() or ClientBuilder::with_bincode() instead"
|
||||
)]
|
||||
#[derive(Clone)]
|
||||
pub struct NymApiClient {
|
||||
pub use_bincode: bool,
|
||||
pub nym_api: nym_http_api_client::Client,
|
||||
pub nym_api: nym_api::Client,
|
||||
// TODO: perhaps if we really need it at some (currently I don't see any reasons for it)
|
||||
// we could re-implement the communication with the REST API on port 1317
|
||||
}
|
||||
|
||||
impl From<nym_api::Client> for NymApiClient {
|
||||
fn from(nym_api: nym_api::Client) -> Self {
|
||||
NymApiClient {
|
||||
use_bincode: false,
|
||||
nym_api,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// we have to allow the use of deprecated method here as they're calling the deprecated trait methods
|
||||
#[allow(deprecated)]
|
||||
impl NymApiClient {
|
||||
pub fn new(api_url: Url) -> Self {
|
||||
let nym_api = nym_api::Client::new(api_url, None);
|
||||
|
||||
NymApiClient {
|
||||
use_bincode: true,
|
||||
nym_api,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn new_with_timeout(api_url: Url, timeout: std::time::Duration) -> Self {
|
||||
let nym_api = nym_http_api_client::Client::new(api_url, Some(timeout));
|
||||
let nym_api = nym_api::Client::new(api_url, Some(timeout));
|
||||
|
||||
NymApiClient {
|
||||
use_bincode: true,
|
||||
@@ -418,10 +431,10 @@ impl NymApiClient {
|
||||
}
|
||||
|
||||
pub fn new_with_user_agent(api_url: Url, user_agent: impl Into<UserAgent>) -> Self {
|
||||
let nym_api = nym_http_api_client::Client::builder(api_url)
|
||||
let nym_api = nym_api::Client::builder::<_, ValidatorClientError>(api_url)
|
||||
.expect("invalid api url")
|
||||
.with_user_agent(user_agent.into())
|
||||
.build()
|
||||
.build::<ValidatorClientError>()
|
||||
.expect("failed to build nym api client");
|
||||
|
||||
NymApiClient {
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
|
||||
use crate::nyxd::contract_traits::{DkgQueryClient, PagedDkgQueryClient};
|
||||
use crate::nyxd::error::NyxdError;
|
||||
use crate::NymApiClient;
|
||||
use nym_coconut_dkg_common::types::{EpochId, NodeIndex};
|
||||
use nym_coconut_dkg_common::verification_key::ContractVKShare;
|
||||
use nym_compact_ecash::error::CompactEcashError;
|
||||
@@ -14,7 +15,7 @@ use url::Url;
|
||||
// TODO: it really doesn't feel like this should live in this crate.
|
||||
#[derive(Clone)]
|
||||
pub struct EcashApiClient {
|
||||
pub api_client: nym_http_api_client::Client,
|
||||
pub api_client: NymApiClient,
|
||||
pub verification_key: VerificationKeyAuth,
|
||||
pub node_id: NodeIndex,
|
||||
pub cosmos_address: cosmrs::AccountId,
|
||||
@@ -24,10 +25,10 @@ impl Display for EcashApiClient {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
||||
write!(
|
||||
f,
|
||||
"[id: {}] {} @ {:?}",
|
||||
"[id: {}] {} @ {}",
|
||||
self.node_id,
|
||||
self.cosmos_address,
|
||||
self.api_client.base_urls()
|
||||
self.api_client.api_url()
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -59,9 +60,6 @@ pub enum EcashApiError {
|
||||
source: CompactEcashError,
|
||||
},
|
||||
|
||||
#[error("failed to create API client: {0}")]
|
||||
ClientError(String),
|
||||
|
||||
#[error("the provided account address is malformed: {source}")]
|
||||
MalformedAccountAddress {
|
||||
#[from]
|
||||
@@ -91,13 +89,8 @@ impl TryFrom<ContractVKShare> for EcashApiClient {
|
||||
// In non-client applications this resolver can cause warning logs about H2 connection
|
||||
// failure. This indicates that the long lived https connection was closed by the remote
|
||||
// peer and the resolver will have to reconnect. It should not impact actual functionality
|
||||
let api_client = nym_http_api_client::Client::builder(url_address)
|
||||
.map_err(|e| EcashApiError::ClientError(e.to_string()))?
|
||||
.build()
|
||||
.map_err(|e| EcashApiError::ClientError(e.to_string()))?;
|
||||
|
||||
Ok(EcashApiClient {
|
||||
api_client,
|
||||
api_client: NymApiClient::new(url_address),
|
||||
verification_key: VerificationKeyAuth::try_from_bs58(&share.share)?,
|
||||
node_id: share.node_index,
|
||||
cosmos_address: share.owner.as_str().parse()?,
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
use crate::nym_api::NymApiClientExt;
|
||||
use crate::nyxd::contract_traits::MixnetQueryClient;
|
||||
use crate::nyxd::error::NyxdError;
|
||||
use crate::nyxd::Config as ClientConfig;
|
||||
use crate::{QueryHttpRpcNyxdClient, ValidatorClientError};
|
||||
use crate::{NymApiClient, QueryHttpRpcNyxdClient, ValidatorClientError};
|
||||
use colored::Colorize;
|
||||
use core::fmt;
|
||||
use itertools::Itertools;
|
||||
@@ -88,17 +87,8 @@ fn setup_connection_tests<H: BuildHasher + 'static>(
|
||||
}
|
||||
});
|
||||
|
||||
let api_connection_test_clients = api_urls.filter_map(|(network, url)| {
|
||||
match nym_http_api_client::Client::builder(url.clone()).and_then(|b| b.build()) {
|
||||
Ok(client) => Some(ClientForConnectionTest::Api(network, url, client)),
|
||||
Err(err) => {
|
||||
eprintln!(
|
||||
"Failed to create API client for {}: {err}",
|
||||
network.network_name
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
let api_connection_test_clients = api_urls.map(|(network, url)| {
|
||||
ClientForConnectionTest::Api(network, url.clone(), NymApiClient::new(url))
|
||||
});
|
||||
|
||||
nyxd_connection_test_clients.chain(api_connection_test_clients)
|
||||
@@ -170,7 +160,7 @@ async fn test_nyxd_connection(
|
||||
async fn test_nym_api_connection(
|
||||
network: NymNetworkDetails,
|
||||
url: &Url,
|
||||
client: &nym_http_api_client::Client,
|
||||
client: &NymApiClient,
|
||||
) -> ConnectionResult {
|
||||
let result = match timeout(
|
||||
Duration::from_secs(CONNECTION_TEST_TIMEOUT_SEC),
|
||||
@@ -196,7 +186,7 @@ async fn test_nym_api_connection(
|
||||
|
||||
enum ClientForConnectionTest {
|
||||
Nyxd(NymNetworkDetails, Url, Box<QueryHttpRpcNyxdClient>),
|
||||
Api(NymNetworkDetails, Url, nym_http_api_client::Client),
|
||||
Api(NymNetworkDetails, Url, NymApiClient),
|
||||
}
|
||||
|
||||
impl ClientForConnectionTest {
|
||||
|
||||
@@ -14,6 +14,7 @@ pub mod signing;
|
||||
pub use crate::error::ValidatorClientError;
|
||||
pub use crate::rpc::reqwest::ReqwestRpcClient;
|
||||
pub use crate::signing::direct_wallet::DirectSecp256k1HdWallet;
|
||||
pub use client::NymApiClient;
|
||||
pub use client::{Client, Config, EcashApiClient};
|
||||
pub use nym_api_requests::*;
|
||||
pub use nym_http_api_client::UserAgent;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// Copyright 2022-2023 - Nym Technologies SA <contact@nymtech.net>
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
use nym_api_requests::models::RequestError;
|
||||
use nym_http_api_client::HttpClientError;
|
||||
|
||||
pub type NymAPIError = HttpClientError;
|
||||
pub type NymAPIError = HttpClientError<RequestError>;
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
|
||||
use crate::nym_api::error::NymAPIError;
|
||||
use crate::nym_api::routes::{ecash, CORE_STATUS_COUNT, SINCE_ARG};
|
||||
use crate::nym_nodes::SkimmedNodesWithMetadata;
|
||||
use async_trait::async_trait;
|
||||
use nym_api_requests::ecash::models::{
|
||||
AggregatedCoinIndicesSignatureResponse, AggregatedExpirationDateSignatureResponse,
|
||||
@@ -38,7 +37,7 @@ pub use nym_api_requests::{
|
||||
MixnodeStatusResponse, MixnodeUptimeHistoryResponse, RewardEstimationResponse,
|
||||
StakeSaturationResponse, UptimeResponse,
|
||||
},
|
||||
nym_nodes::{CachedNodesResponse, SemiSkimmedNode, SemiSkimmedNodesWithMetadata, SkimmedNode},
|
||||
nym_nodes::{CachedNodesResponse, SemiSkimmedNode, SkimmedNode},
|
||||
NymNetworkDetailsResponse,
|
||||
};
|
||||
use nym_contracts_common::IdentityKey;
|
||||
@@ -50,8 +49,8 @@ use time::format_description::BorrowedFormatItem;
|
||||
use time::Date;
|
||||
use tracing::instrument;
|
||||
|
||||
use crate::ValidatorClientError;
|
||||
pub use nym_coconut_dkg_common::types::EpochId;
|
||||
pub use nym_http_api_client::Client;
|
||||
|
||||
pub mod error;
|
||||
pub mod routes;
|
||||
@@ -63,9 +62,6 @@ pub fn rfc_3339_date() -> Vec<BorrowedFormatItem<'static>> {
|
||||
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
|
||||
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
|
||||
pub trait NymApiClientExt: ApiClient {
|
||||
/// Get the current API URL being used by the client
|
||||
fn api_url(&self) -> &url::Url;
|
||||
|
||||
async fn health(&self) -> Result<ApiHealthResponse, NymAPIError> {
|
||||
self.get_json(
|
||||
&[
|
||||
@@ -245,156 +241,6 @@ pub trait NymApiClientExt: ApiClient {
|
||||
.await
|
||||
}
|
||||
|
||||
async fn get_current_rewarded_set(&self) -> Result<RewardedSetResponse, NymAPIError> {
|
||||
self.get_rewarded_set().await
|
||||
}
|
||||
|
||||
async fn get_all_basic_nodes_with_metadata(
|
||||
&self,
|
||||
) -> Result<SkimmedNodesWithMetadata, NymAPIError> {
|
||||
// unroll first loop iteration in order to obtain the metadata
|
||||
let mut page = 0;
|
||||
let res = self
|
||||
.get_basic_nodes_v2(false, Some(page), None, true)
|
||||
.await?;
|
||||
let mut nodes = res.nodes.data;
|
||||
let metadata = res.metadata;
|
||||
|
||||
if res.nodes.pagination.total == nodes.len() {
|
||||
return Ok(SkimmedNodesWithMetadata::new(nodes, metadata));
|
||||
}
|
||||
|
||||
page += 1;
|
||||
|
||||
loop {
|
||||
let mut res = self
|
||||
.get_basic_nodes_v2(false, Some(page), None, true)
|
||||
.await?;
|
||||
|
||||
if !metadata.consistency_check(&res.metadata) {
|
||||
// Create a custom error for inconsistent metadata
|
||||
return Err(NymAPIError::EndpointFailure {
|
||||
status: reqwest::StatusCode::INTERNAL_SERVER_ERROR,
|
||||
error: "Inconsistent paged metadata".to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
nodes.append(&mut res.nodes.data);
|
||||
if nodes.len() >= res.nodes.pagination.total {
|
||||
break;
|
||||
} else {
|
||||
page += 1
|
||||
}
|
||||
}
|
||||
|
||||
Ok(SkimmedNodesWithMetadata::new(nodes, metadata))
|
||||
}
|
||||
|
||||
async fn get_all_basic_active_mixing_assigned_nodes_with_metadata(
|
||||
&self,
|
||||
) -> Result<SkimmedNodesWithMetadata, NymAPIError> {
|
||||
// Get all mixing nodes that are in the active/rewarded set
|
||||
let mut page = 0;
|
||||
let res = self
|
||||
.get_basic_active_mixing_assigned_nodes_v2(false, Some(page), None, false)
|
||||
.await?;
|
||||
|
||||
let metadata = res.metadata;
|
||||
let mut nodes = res.nodes.data;
|
||||
|
||||
if res.nodes.pagination.total == nodes.len() {
|
||||
return Ok(SkimmedNodesWithMetadata::new(nodes, metadata));
|
||||
}
|
||||
|
||||
page += 1;
|
||||
|
||||
loop {
|
||||
let res = self
|
||||
.get_basic_active_mixing_assigned_nodes_v2(false, Some(page), None, false)
|
||||
.await?;
|
||||
|
||||
if !metadata.consistency_check(&res.metadata) {
|
||||
return Err(NymAPIError::EndpointFailure {
|
||||
status: reqwest::StatusCode::INTERNAL_SERVER_ERROR,
|
||||
error: "Inconsistent paged metadata".to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
nodes.append(&mut res.nodes.data.clone());
|
||||
|
||||
// Check if we've got all nodes
|
||||
if nodes.len() >= res.nodes.pagination.total {
|
||||
break;
|
||||
} else {
|
||||
page += 1;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(SkimmedNodesWithMetadata::new(nodes, metadata))
|
||||
}
|
||||
|
||||
async fn get_all_basic_entry_assigned_nodes_with_metadata(
|
||||
&self,
|
||||
) -> Result<SkimmedNodesWithMetadata, NymAPIError> {
|
||||
// Get all nodes that can act as entry gateways
|
||||
let mut page = 0;
|
||||
let res = self
|
||||
.get_basic_entry_assigned_nodes_v2(false, Some(page), None, false)
|
||||
.await?;
|
||||
|
||||
let metadata = res.metadata;
|
||||
let mut nodes = res.nodes.data;
|
||||
|
||||
if res.nodes.pagination.total == nodes.len() {
|
||||
return Ok(SkimmedNodesWithMetadata::new(nodes, metadata));
|
||||
}
|
||||
|
||||
page += 1;
|
||||
|
||||
loop {
|
||||
let res = self
|
||||
.get_basic_entry_assigned_nodes_v2(false, Some(page), None, false)
|
||||
.await?;
|
||||
|
||||
if !metadata.consistency_check(&res.metadata) {
|
||||
return Err(NymAPIError::EndpointFailure {
|
||||
status: reqwest::StatusCode::INTERNAL_SERVER_ERROR,
|
||||
error: "Inconsistent paged metadata".to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
nodes.append(&mut res.nodes.data.clone());
|
||||
|
||||
// Check if we've got all nodes
|
||||
if nodes.len() >= res.nodes.pagination.total {
|
||||
break;
|
||||
} else {
|
||||
page += 1;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(SkimmedNodesWithMetadata::new(nodes, metadata))
|
||||
}
|
||||
|
||||
async fn get_all_described_nodes(&self) -> Result<Vec<NymNodeDescription>, NymAPIError> {
|
||||
// TODO: deal with paging in macro or some helper function or something, because it's the same pattern everywhere
|
||||
let mut page = 0;
|
||||
let mut descriptions = Vec::new();
|
||||
|
||||
loop {
|
||||
let mut res = self.get_nodes_described(Some(page), None).await?;
|
||||
|
||||
descriptions.append(&mut res.data);
|
||||
if descriptions.len() < res.pagination.total {
|
||||
page += 1
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(descriptions)
|
||||
}
|
||||
|
||||
#[tracing::instrument(level = "debug", skip_all)]
|
||||
async fn get_nym_nodes(
|
||||
&self,
|
||||
@@ -422,25 +268,6 @@ pub trait NymApiClientExt: ApiClient {
|
||||
.await
|
||||
}
|
||||
|
||||
async fn get_all_bonded_nym_nodes(&self) -> Result<Vec<NymNodeDetails>, ValidatorClientError> {
|
||||
// TODO: deal with paging in macro or some helper function or something, because it's the same pattern everywhere
|
||||
let mut page = 0;
|
||||
let mut bonds = Vec::new();
|
||||
|
||||
loop {
|
||||
let mut res = self.get_nym_nodes(Some(page), None).await?;
|
||||
|
||||
bonds.append(&mut res.data);
|
||||
if bonds.len() < res.pagination.total {
|
||||
page += 1
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(bonds)
|
||||
}
|
||||
|
||||
#[deprecated]
|
||||
#[tracing::instrument(level = "debug", skip_all)]
|
||||
async fn get_basic_mixnodes(&self) -> Result<CachedNodesResponse<SkimmedNode>, NymAPIError> {
|
||||
@@ -1544,49 +1371,8 @@ pub trait NymApiClientExt: ApiClient {
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Method to change the base API URLs being used by the client
|
||||
fn change_base_urls(&mut self, urls: Vec<url::Url>);
|
||||
|
||||
/// Retrieve expanded information for all bonded nodes on the network
|
||||
async fn get_all_expanded_nodes(&self) -> Result<SemiSkimmedNodesWithMetadata, NymAPIError> {
|
||||
// Unroll the first iteration to get the metadata
|
||||
let mut page = 0;
|
||||
|
||||
let res = self.get_expanded_nodes(false, Some(page), None).await?;
|
||||
let mut nodes = res.nodes.data;
|
||||
let metadata = res.metadata;
|
||||
|
||||
if res.nodes.pagination.total == nodes.len() {
|
||||
return Ok(SemiSkimmedNodesWithMetadata::new(nodes, metadata));
|
||||
}
|
||||
|
||||
page += 1;
|
||||
|
||||
loop {
|
||||
let mut res = self.get_expanded_nodes(false, Some(page), None).await?;
|
||||
|
||||
nodes.append(&mut res.nodes.data);
|
||||
if nodes.len() < res.nodes.pagination.total {
|
||||
page += 1
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(SemiSkimmedNodesWithMetadata::new(nodes, metadata))
|
||||
}
|
||||
}
|
||||
|
||||
// Client is already nym_http_api_client::Client (re-exported above), so just one impl needed
|
||||
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
|
||||
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
|
||||
impl NymApiClientExt for nym_http_api_client::Client {
|
||||
fn api_url(&self) -> &url::Url {
|
||||
self.current_url().as_ref()
|
||||
}
|
||||
|
||||
fn change_base_urls(&mut self, urls: Vec<url::Url>) {
|
||||
self.change_base_urls(urls.into_iter().map(|u| u.into()).collect());
|
||||
}
|
||||
}
|
||||
impl NymApiClientExt for Client {}
|
||||
|
||||
@@ -38,7 +38,6 @@ cosmrs = { workspace = true }
|
||||
cosmwasm-std = { workspace = true }
|
||||
|
||||
nym-validator-client = { path = "../client-libs/validator-client" }
|
||||
nym-http-api-client = { path = "../http-api-client" }
|
||||
nym-bin-common = { path = "../../common/bin-common", features = ["output_format"] }
|
||||
nym-crypto = { path = "../../common/crypto", features = ["asymmetric"] }
|
||||
nym-network-defaults = { path = "../network-defaults" }
|
||||
|
||||
@@ -2,12 +2,12 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
use crate::context::errors::ContextError;
|
||||
pub use nym_http_api_client::Client as NymApiClient;
|
||||
use nym_network_defaults::{
|
||||
setup_env,
|
||||
var_names::{MIXNET_CONTRACT_ADDRESS, NYM_API, NYXD, VESTING_CONTRACT_ADDRESS},
|
||||
NymNetworkDetails,
|
||||
};
|
||||
pub use nym_validator_client::nym_api::Client as NymApiClient;
|
||||
use nym_validator_client::nyxd::{self, AccountId, NyxdClient};
|
||||
use nym_validator_client::{
|
||||
DirectSigningHttpRpcNyxdClient, DirectSigningHttpRpcValidatorClient, QueryHttpRpcNyxdClient,
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
use clap::{Args, Subcommand};
|
||||
|
||||
pub mod ecash;
|
||||
pub mod nyx;
|
||||
|
||||
#[derive(Debug, Args)]
|
||||
#[clap(args_conflicts_with_subcommands = true, subcommand_required = true)]
|
||||
@@ -17,6 +16,4 @@ pub struct Internal {
|
||||
pub enum InternalCommands {
|
||||
/// Ecash related internal commands
|
||||
Ecash(ecash::InternalEcash),
|
||||
|
||||
Nyx(nyx::InternalNyx),
|
||||
}
|
||||
|
||||
@@ -1,116 +0,0 @@
|
||||
// Copyright 2025 - Nym Technologies SA <contact@nymtech.net>
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
use crate::context::SigningClient;
|
||||
use anyhow::bail;
|
||||
use clap::Parser;
|
||||
use nym_mixnet_contract_common::nym_node::Role;
|
||||
use nym_mixnet_contract_common::reward_params::NodeRewardingParameters;
|
||||
use nym_mixnet_contract_common::{
|
||||
EpochRewardedSet, EpochState, NodeId, RewardingParams, RoleAssignment,
|
||||
};
|
||||
use nym_validator_client::nyxd::contract_traits::mixnet_query_client::MixnetQueryClientExt;
|
||||
use nym_validator_client::nyxd::contract_traits::{MixnetQueryClient, MixnetSigningClient};
|
||||
use rand::prelude::*;
|
||||
use rand::thread_rng;
|
||||
|
||||
#[derive(Debug, Parser)]
|
||||
pub struct Args {}
|
||||
|
||||
fn choose_new_nodes(
|
||||
params: &RewardingParams,
|
||||
rewarded_set: &EpochRewardedSet,
|
||||
role: Role,
|
||||
) -> Vec<NodeId> {
|
||||
let mut rng = thread_rng();
|
||||
|
||||
match role {
|
||||
Role::EntryGateway => rewarded_set
|
||||
.assignment
|
||||
.entry_gateways
|
||||
.choose_multiple(&mut rng, params.rewarded_set.entry_gateways as usize)
|
||||
.copied()
|
||||
.collect(),
|
||||
Role::Layer1 => rewarded_set
|
||||
.assignment
|
||||
.layer1
|
||||
.choose_multiple(&mut rng, params.rewarded_set.mixnodes as usize / 3)
|
||||
.copied()
|
||||
.collect(),
|
||||
Role::Layer2 => rewarded_set
|
||||
.assignment
|
||||
.layer2
|
||||
.choose_multiple(&mut rng, params.rewarded_set.mixnodes as usize / 3)
|
||||
.copied()
|
||||
.collect(),
|
||||
Role::Layer3 => rewarded_set
|
||||
.assignment
|
||||
.layer3
|
||||
.choose_multiple(&mut rng, params.rewarded_set.mixnodes as usize / 3)
|
||||
.copied()
|
||||
.collect(),
|
||||
Role::ExitGateway => rewarded_set
|
||||
.assignment
|
||||
.exit_gateways
|
||||
.choose_multiple(&mut rng, params.rewarded_set.exit_gateways as usize)
|
||||
.copied()
|
||||
.collect(),
|
||||
Role::Standby => rewarded_set
|
||||
.assignment
|
||||
.standby
|
||||
.choose_multiple(&mut rng, params.rewarded_set.standby as usize)
|
||||
.copied()
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn force_advance_epoch(_: Args, client: SigningClient) -> anyhow::Result<()> {
|
||||
let current_epoch = client.get_current_interval_details().await?;
|
||||
let epoch_status = client.get_current_epoch_status().await?;
|
||||
if epoch_status.being_advanced_by.as_str() != client.address().to_string() {
|
||||
bail!(
|
||||
"this client is not authorised to perform any epoch operations. we need {}",
|
||||
client.address()
|
||||
)
|
||||
}
|
||||
|
||||
let rewarding_params = client.get_rewarding_parameters().await?;
|
||||
let current_rewarded_set = client.get_rewarded_set().await?;
|
||||
|
||||
if !current_epoch.is_current_epoch_over {
|
||||
println!("the current epoch is not over yet - there's nothing to do")
|
||||
}
|
||||
|
||||
// is this most efficient? no. but it's simple
|
||||
loop {
|
||||
let epoch_status = client.get_current_epoch_status().await?;
|
||||
|
||||
match epoch_status.state {
|
||||
EpochState::InProgress => break,
|
||||
EpochState::Rewarding { final_node_id, .. } => {
|
||||
println!("rewarding {final_node_id} with big fat 0...");
|
||||
client
|
||||
.reward_node(
|
||||
final_node_id,
|
||||
NodeRewardingParameters::new(Default::default(), Default::default()),
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
EpochState::ReconcilingEvents => {
|
||||
println!("trying to reconcile events...");
|
||||
client.reconcile_epoch_events(None, None).await?;
|
||||
}
|
||||
EpochState::RoleAssignment { next } => {
|
||||
let nodes = choose_new_nodes(&rewarding_params, ¤t_rewarded_set, next);
|
||||
println!("assigning {nodes:?} as {next}");
|
||||
|
||||
client
|
||||
.assign_roles(RoleAssignment { role: next, nodes }, None)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
// Copyright 2025 - Nym Technologies SA <contact@nymtech.net>
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
use clap::{Args, Subcommand};
|
||||
|
||||
pub mod force_advance_epoch;
|
||||
|
||||
#[derive(Debug, Args)]
|
||||
#[clap(args_conflicts_with_subcommands = true, subcommand_required = true)]
|
||||
pub struct InternalNyx {
|
||||
#[clap(subcommand)]
|
||||
pub command: InternalNyxCommands,
|
||||
}
|
||||
|
||||
#[derive(Debug, Subcommand)]
|
||||
pub enum InternalNyxCommands {
|
||||
/// Attempt to force advance the current epoch
|
||||
ForceAdvanceEpoch(force_advance_epoch::Args),
|
||||
}
|
||||
@@ -3,7 +3,6 @@ name = "nym-credential-storage"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
@@ -34,7 +33,6 @@ features = ["rt-multi-thread", "net", "signal", "fs"]
|
||||
|
||||
|
||||
[build-dependencies]
|
||||
anyhow = { workspace = true }
|
||||
sqlx = { workspace = true, features = [
|
||||
"runtime-tokio-rustls",
|
||||
"sqlite",
|
||||
|
||||
@@ -3,29 +3,22 @@
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
use anyhow::Context;
|
||||
use sqlx::{Connection, SqliteConnection};
|
||||
use std::env;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
let out_dir = env::var("OUT_DIR")?;
|
||||
async fn main() {
|
||||
let out_dir = env::var("OUT_DIR").unwrap();
|
||||
let database_path = format!("{out_dir}/coconut-credential-example.sqlite");
|
||||
|
||||
// remove the db file if it already existed from previous build
|
||||
// in case it was from a different branch
|
||||
if std::fs::exists(&database_path)? {
|
||||
std::fs::remove_file(&database_path)?;
|
||||
}
|
||||
|
||||
let mut conn = SqliteConnection::connect(&format!("sqlite://{database_path}?mode=rwc"))
|
||||
.await
|
||||
.context("Failed to create SQLx database connection")?;
|
||||
.expect("Failed to create SQLx database connection");
|
||||
|
||||
sqlx::migrate!("./migrations")
|
||||
.run(&mut conn)
|
||||
.await
|
||||
.context("Failed to perform SQLx migrations")?;
|
||||
.expect("Failed to perform SQLx migrations");
|
||||
|
||||
#[cfg(target_family = "unix")]
|
||||
println!("cargo:rustc-env=DATABASE_URL=sqlite://{}", &database_path);
|
||||
@@ -34,6 +27,4 @@ async fn main() -> anyhow::Result<()> {
|
||||
// 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);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
+4
-4
@@ -110,14 +110,14 @@ FROM ecash_ticketbook;
|
||||
|
||||
-- 6. finally swap out the old tables
|
||||
-- drop old tables
|
||||
DROP TABLE expiration_date_signatures;
|
||||
DROP TABLE pending_issuance;
|
||||
DROP TABLE ecash_ticketbook;
|
||||
DROP TABLE expiration_date_signatures;
|
||||
|
||||
-- rename new tables
|
||||
ALTER TABLE expiration_date_signatures_new
|
||||
RENAME TO expiration_date_signatures;
|
||||
ALTER TABLE pending_issuance_new
|
||||
RENAME TO pending_issuance;
|
||||
ALTER TABLE ecash_ticketbook_new
|
||||
RENAME TO ecash_ticketbook;
|
||||
ALTER TABLE expiration_date_signatures_new
|
||||
RENAME TO expiration_date_signatures;
|
||||
RENAME TO ecash_ticketbook;
|
||||
@@ -14,7 +14,7 @@ use nym_api_requests::ecash::models::{BatchRedeemTicketsBody, VerifyEcashTicketB
|
||||
use nym_credentials_interface::Bandwidth;
|
||||
use nym_credentials_interface::{ClientTicket, TicketType};
|
||||
use nym_validator_client::coconut::EcashApiError;
|
||||
use nym_validator_client::nym_api::{EpochId, NymApiClientExt};
|
||||
use nym_validator_client::nym_api::EpochId;
|
||||
use nym_validator_client::nyxd::contract_traits::{
|
||||
EcashSigningClient, MultisigQueryClient, MultisigSigningClient, PagedMultisigQueryClient,
|
||||
};
|
||||
@@ -354,7 +354,7 @@ impl CredentialHandler {
|
||||
Err(err) => {
|
||||
error!("failed to send ticket {ticket_id} for verification to ecash signer '{client}': {err}. if we don't reach quorum, we'll retry later");
|
||||
Err(EcashTicketError::ApiFailure(EcashApiError::NymApi {
|
||||
source: nym_validator_client::ValidatorClientError::NymAPIError { source: err },
|
||||
source: err,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
use crate::ecash::traits::EcashManager;
|
||||
use async_trait::async_trait;
|
||||
use bandwidth_storage_manager::BandwidthStorageManager;
|
||||
use nym_credentials::ecash::utils::{cred_exp_date, ecash_today, EcashTime};
|
||||
use nym_credentials_interface::{Bandwidth, ClientTicket, TicketType};
|
||||
@@ -140,18 +139,3 @@ impl CredentialVerifier {
|
||||
.await)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait TicketVerifier {
|
||||
/// Verify that the ticket is valid and cryptographically correct.
|
||||
/// If the verification succeeds, also increase the bandwidth with the ticket's
|
||||
/// amount and return the latest available bandwidth
|
||||
async fn verify(&mut self) -> Result<i64>;
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl TicketVerifier for CredentialVerifier {
|
||||
async fn verify(&mut self) -> Result<i64> {
|
||||
self.verify().await
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,7 +22,6 @@ nym-ecash-time = { path = "../ecash-time", features = ["expiration"] }
|
||||
nym-credentials-interface = { path = "../credentials-interface" }
|
||||
nym-crypto = { path = "../crypto" }
|
||||
nym-api-requests = { path = "../../nym-api/nym-api-requests" }
|
||||
nym-http-api-client = { path = "../http-api-client" }
|
||||
nym-validator-client = { path = "../client-libs/validator-client", default-features = false }
|
||||
nym-ecash-contract-common = { path = "../cosmwasm-smart-contracts/ecash-contract" }
|
||||
nym-network-defaults = { path = "../network-defaults" }
|
||||
|
||||
@@ -15,7 +15,7 @@ use nym_credentials_interface::{
|
||||
use nym_crypto::asymmetric::ed25519;
|
||||
use nym_ecash_contract_common::deposit::DepositId;
|
||||
use nym_ecash_time::{ecash_default_expiration_date, ecash_today, EcashTime};
|
||||
use nym_validator_client::nym_api::{EpochId, NymApiClientExt};
|
||||
use nym_validator_client::nym_api::EpochId;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use time::Date;
|
||||
|
||||
@@ -108,7 +108,7 @@ impl IssuanceTicketBook {
|
||||
signing_request.withdrawal_request.clone(),
|
||||
self.deposit_id,
|
||||
request_signature,
|
||||
signing_request.ecash_pub_key,
|
||||
signing_request.ecash_pub_key.clone(),
|
||||
signing_request.expiration_date,
|
||||
signing_request.ticketbook_type,
|
||||
)
|
||||
@@ -116,7 +116,7 @@ impl IssuanceTicketBook {
|
||||
|
||||
pub async fn obtain_blinded_credential(
|
||||
&self,
|
||||
client: &nym_http_api_client::Client,
|
||||
client: &nym_validator_client::client::NymApiClient,
|
||||
request_body: &BlindSignRequestBody,
|
||||
) -> Result<BlindedSignature, Error> {
|
||||
let server_response = client.blind_sign(request_body).await?;
|
||||
@@ -179,7 +179,7 @@ impl IssuanceTicketBook {
|
||||
// ideally this would have been generic over credential type, but we really don't need secp256k1 keys for bandwidth vouchers
|
||||
pub async fn obtain_partial_ticketbook_credential(
|
||||
&self,
|
||||
client: &nym_http_api_client::Client,
|
||||
client: &nym_validator_client::client::NymApiClient,
|
||||
signer_index: u64,
|
||||
validator_vk: &VerificationKeyAuth,
|
||||
signing_data: CredentialSigningData,
|
||||
|
||||
@@ -10,7 +10,6 @@ use nym_credentials_interface::{
|
||||
VerificationKeyAuth, WalletSignatures,
|
||||
};
|
||||
use nym_validator_client::client::EcashApiClient;
|
||||
use nym_validator_client::nym_api::NymApiClientExt;
|
||||
|
||||
// so we wouldn't break all the existing imports
|
||||
pub use nym_ecash_time::{cred_exp_date, ecash_date_offset, ecash_today, EcashTime};
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
use crate::ecash::bandwidth::issued::CURRENT_SERIALIZATION_REVISION;
|
||||
use nym_credentials_interface::CompactEcashError;
|
||||
use nym_crypto::asymmetric::x25519::KeyRecoveryError;
|
||||
use nym_validator_client::{nym_api::error::NymAPIError, ValidatorClientError};
|
||||
use nym_validator_client::ValidatorClientError;
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
@@ -37,9 +37,6 @@ pub enum Error {
|
||||
#[error("Ran into a validator client error - {0}")]
|
||||
ValidatorClientError(#[from] ValidatorClientError),
|
||||
|
||||
#[error("Nym API request failed - {0}")]
|
||||
NymAPIError(#[from] NymAPIError),
|
||||
|
||||
#[error("Bandwidth operation overflowed. {0}")]
|
||||
BandwidthOverflow(String),
|
||||
|
||||
|
||||
@@ -22,7 +22,6 @@ url = { workspace = true }
|
||||
nym-validator-client = { path = "../client-libs/validator-client" }
|
||||
nym-network-defaults = { path = "../network-defaults" }
|
||||
nym-ecash-signer-check-types = { path = "../ecash-signer-check-types" }
|
||||
nym-http-api-client = { path = "../http-api-client" }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
// Copyright 2025 - Nym Technologies SA <contact@nymtech.net>
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
use crate::{LocalChainStatus, SignerCheckError, SigningStatus, TypedSignerResult};
|
||||
use crate::{LocalChainStatus, SigningStatus, TypedSignerResult};
|
||||
use nym_ecash_signer_check_types::dealer_information::RawDealerInformation;
|
||||
use nym_ecash_signer_check_types::status::{SignerStatus, SignerTestResult};
|
||||
use nym_validator_client::client::NymApiClientExt;
|
||||
use nym_validator_client::models::BinaryBuildInformationOwned;
|
||||
use nym_validator_client::nym_api::NymApiClientExt;
|
||||
use nym_validator_client::nyxd::contract_traits::dkg_query_client::{
|
||||
ContractVKShare, DealerDetails,
|
||||
};
|
||||
use nym_validator_client::NymApiClient;
|
||||
use std::time::Duration;
|
||||
use tracing::{error, warn};
|
||||
use url::Url;
|
||||
@@ -31,38 +32,37 @@ pub(crate) mod signing_status {
|
||||
}
|
||||
|
||||
struct ClientUnderTest {
|
||||
api_client: nym_http_api_client::Client,
|
||||
api_client: NymApiClient,
|
||||
build_info: Option<BinaryBuildInformationOwned>,
|
||||
}
|
||||
|
||||
impl ClientUnderTest {
|
||||
pub(crate) fn new(api_url: &Url) -> Result<Self, SignerCheckError> {
|
||||
// The builder should not fail with a valid URL that's already parsed
|
||||
// If it does fail, it's an internal error that we can't recover from
|
||||
let api_client = nym_http_api_client::Client::builder(api_url.clone())?.build()?;
|
||||
|
||||
Ok(ClientUnderTest {
|
||||
api_client,
|
||||
pub(crate) fn new(api_url: &Url) -> Self {
|
||||
ClientUnderTest {
|
||||
api_client: NymApiClient::new(api_url.clone()),
|
||||
build_info: None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn try_retrieve_build_information(&mut self) -> bool {
|
||||
match tokio::time::timeout(Duration::from_secs(5), self.api_client.build_information())
|
||||
.await
|
||||
match tokio::time::timeout(
|
||||
Duration::from_secs(5),
|
||||
self.api_client.nym_api.build_information(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(Ok(build_information)) => {
|
||||
self.build_info = Some(build_information);
|
||||
true
|
||||
}
|
||||
Ok(Err(err)) => {
|
||||
warn!("{}: failed to retrieve build information: {err}. the signer is most likely down", self.api_client.current_url());
|
||||
warn!("{}: failed to retrieve build information: {err}. the signer is most likely down", self.api_client.api_url());
|
||||
false
|
||||
}
|
||||
Err(_timeout) => {
|
||||
warn!(
|
||||
"{}: timed out while attempting to retrieve build information",
|
||||
self.api_client.current_url()
|
||||
self.api_client.api_url()
|
||||
);
|
||||
false
|
||||
}
|
||||
@@ -77,7 +77,7 @@ impl ClientUnderTest {
|
||||
.inspect_err(|err| {
|
||||
error!(
|
||||
"ecash signer '{}' reports invalid version {}: {err}",
|
||||
self.api_client.current_url(),
|
||||
self.api_client.api_url(),
|
||||
build_info.build_version
|
||||
)
|
||||
})
|
||||
@@ -121,14 +121,14 @@ impl ClientUnderTest {
|
||||
|
||||
// check if it supports the current query
|
||||
if self.supports_chain_status_query() {
|
||||
return match self.api_client.get_chain_blocks_status().await {
|
||||
return match self.api_client.nym_api.get_chain_blocks_status().await {
|
||||
Ok(status) => LocalChainStatus::Reachable {
|
||||
response: Box::new(status),
|
||||
},
|
||||
Err(err) => {
|
||||
warn!(
|
||||
"{}: failed to retrieve local chain status: {err}",
|
||||
self.api_client.current_url()
|
||||
self.api_client.api_url()
|
||||
);
|
||||
LocalChainStatus::Unreachable
|
||||
}
|
||||
@@ -136,14 +136,14 @@ impl ClientUnderTest {
|
||||
}
|
||||
|
||||
// fallback to the legacy query
|
||||
match self.api_client.get_chain_status().await {
|
||||
match self.api_client.nym_api.get_chain_status().await {
|
||||
Ok(status) => LocalChainStatus::ReachableLegacy {
|
||||
response: Box::new(status),
|
||||
},
|
||||
Err(err) => {
|
||||
warn!(
|
||||
"{}: failed to retrieve [legacy] local chain status: {err}",
|
||||
self.api_client.current_url()
|
||||
self.api_client.api_url()
|
||||
);
|
||||
LocalChainStatus::Unreachable
|
||||
}
|
||||
@@ -158,14 +158,14 @@ impl ClientUnderTest {
|
||||
|
||||
// check if it supports the current query
|
||||
if self.supports_signing_status_query() {
|
||||
return match self.api_client.get_signer_status().await {
|
||||
return match self.api_client.nym_api.get_signer_status().await {
|
||||
Ok(response) => SigningStatus::Reachable {
|
||||
response: Box::new(response),
|
||||
},
|
||||
Err(err) => {
|
||||
warn!(
|
||||
"{}: failed to retrieve signer chain status: {err}",
|
||||
self.api_client.current_url()
|
||||
self.api_client.api_url()
|
||||
);
|
||||
SigningStatus::Unreachable
|
||||
}
|
||||
@@ -173,14 +173,14 @@ impl ClientUnderTest {
|
||||
}
|
||||
|
||||
// fallback to the legacy query
|
||||
match self.api_client.get_signer_information().await {
|
||||
match self.api_client.nym_api.get_signer_information().await {
|
||||
Ok(status) => SigningStatus::ReachableLegacy {
|
||||
response: Box::new(status),
|
||||
},
|
||||
Err(err) => {
|
||||
warn!(
|
||||
"{}: failed to retrieve [legacy] signer chain status: {err}",
|
||||
self.api_client.current_url()
|
||||
self.api_client.api_url()
|
||||
);
|
||||
// NOTE: this might equally mean the signing is disabled
|
||||
SigningStatus::Unreachable
|
||||
@@ -201,13 +201,7 @@ pub(crate) async fn check_client(
|
||||
return SignerStatus::ProvidedInvalidDetails.with_details(dealer_information, dkg_epoch);
|
||||
};
|
||||
|
||||
let mut client = match ClientUnderTest::new(&parsed_information.announce_address) {
|
||||
Ok(client) => client,
|
||||
Err(err) => {
|
||||
error!("failed to create client instance: {err}");
|
||||
return SignerStatus::Unreachable.with_details(dealer_information, dkg_epoch);
|
||||
}
|
||||
};
|
||||
let mut client = ClientUnderTest::new(&parsed_information.announce_address);
|
||||
|
||||
// 8. check basic connection status - can you retrieve build information?
|
||||
if !client.try_retrieve_build_information().await {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
// Copyright 2025 - Nym Technologies SA <contact@nymtech.net>
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
use nym_http_api_client::HttpClientError;
|
||||
use nym_validator_client::nyxd::error::NyxdError;
|
||||
use thiserror::Error;
|
||||
|
||||
@@ -12,12 +11,6 @@ pub enum SignerCheckError {
|
||||
|
||||
#[error("failed to query the DKG contract: {source}")]
|
||||
DKGContractQueryFailure { source: NyxdError },
|
||||
|
||||
#[error("failed to build client: {source}")]
|
||||
HttpClient {
|
||||
#[from]
|
||||
source: HttpClientError,
|
||||
},
|
||||
}
|
||||
|
||||
impl SignerCheckError {
|
||||
|
||||
@@ -15,9 +15,6 @@ use nym_validator_client::ecash::models::EcashSignerStatusResponse;
|
||||
use nym_validator_client::models::{
|
||||
ChainBlocksStatusResponse, ChainStatusResponse, SignerInformationResponse,
|
||||
};
|
||||
use nym_validator_client::nyxd::contract_traits::dkg_query_client::{
|
||||
ContractVKShare, DealerDetails, Epoch,
|
||||
};
|
||||
|
||||
mod client_check;
|
||||
pub mod error;
|
||||
@@ -51,22 +48,7 @@ pub async fn check_signers(
|
||||
check_signers_with_client(&client).await
|
||||
}
|
||||
|
||||
pub struct DkgDetails {
|
||||
pub dkg_epoch: Epoch,
|
||||
pub threshold: Option<u64>,
|
||||
pub network_dealers: Vec<DealerDetails>,
|
||||
pub submitted_shared: HashMap<u64, ContractVKShare>,
|
||||
}
|
||||
|
||||
pub async fn check_signers_with_client<C>(client: &C) -> Result<SignersTestResult, SignerCheckError>
|
||||
where
|
||||
C: DkgQueryClient + Sync,
|
||||
{
|
||||
let dkg_details = dkg_details_with_client(client).await?;
|
||||
check_known_dealers(dkg_details).await
|
||||
}
|
||||
|
||||
pub async fn dkg_details_with_client<C>(client: &C) -> Result<DkgDetails, SignerCheckError>
|
||||
where
|
||||
C: DkgQueryClient + Sync,
|
||||
{
|
||||
@@ -97,31 +79,16 @@ where
|
||||
.map(|share| (share.node_index, share))
|
||||
.collect();
|
||||
|
||||
Ok(DkgDetails {
|
||||
dkg_epoch,
|
||||
threshold,
|
||||
network_dealers: dealers,
|
||||
submitted_shared: shares,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn check_known_dealers(
|
||||
dkg_details: DkgDetails,
|
||||
) -> Result<SignersTestResult, SignerCheckError> {
|
||||
// 6. for each dealer attempt to perform the checks
|
||||
let results = dkg_details
|
||||
.network_dealers
|
||||
let results = dealers
|
||||
.into_iter()
|
||||
.map(|d| {
|
||||
let share = dkg_details.submitted_shared.get(&d.assigned_index);
|
||||
check_client(d, dkg_details.dkg_epoch.epoch_id, share)
|
||||
let share = shares.get(&d.assigned_index);
|
||||
check_client(d, dkg_epoch.epoch_id, share)
|
||||
})
|
||||
.collect::<FuturesUnordered<_>>()
|
||||
.collect::<Vec<_>>()
|
||||
.await;
|
||||
|
||||
Ok(SignersTestResult {
|
||||
threshold: dkg_details.threshold,
|
||||
results,
|
||||
})
|
||||
Ok(SignersTestResult { threshold, results })
|
||||
}
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
[package]
|
||||
name = "nym-execute"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
license.workspace = true
|
||||
|
||||
[lib]
|
||||
proc-macro = true
|
||||
|
||||
[dependencies]
|
||||
syn = { workspace = true, features = ["full"] }
|
||||
quote = { workspace = true }
|
||||
@@ -0,0 +1,110 @@
|
||||
use proc_macro::TokenStream;
|
||||
use quote::quote;
|
||||
use syn::{
|
||||
parse_macro_input, Block, ExprMethodCall, FnArg, Ident, ItemFn, LitStr, ReturnType, Token,
|
||||
VisPublic, Visibility,
|
||||
};
|
||||
|
||||
#[proc_macro_attribute]
|
||||
pub fn execute(attr: TokenStream, item: TokenStream) -> TokenStream {
|
||||
let f = parse_macro_input!(item as ItemFn);
|
||||
let target = parse_macro_input!(attr as LitStr).value();
|
||||
|
||||
let cl = if target == "mixnet" {
|
||||
quote! {self.mixnet_contract_address()}
|
||||
} else if target == "vesting" {
|
||||
quote! {self.vesting_contract_address()}
|
||||
} else {
|
||||
panic!("Only `mixnet` and `vesting` targets are supported!")
|
||||
};
|
||||
let cl = proc_macro::TokenStream::from(cl);
|
||||
let cl = parse_macro_input!(cl as ExprMethodCall);
|
||||
|
||||
let orig_f = f.clone();
|
||||
let mut execute_f = f.clone();
|
||||
let mut simulate_f = f.clone();
|
||||
let name = f.sig.ident;
|
||||
let name_str = name.to_string();
|
||||
let call_args = f.sig.inputs.into_iter().filter_map(|arg| match arg {
|
||||
FnArg::Receiver(_) => None,
|
||||
FnArg::Typed(arg) => Some(arg.pat),
|
||||
});
|
||||
let execute_args = call_args.clone();
|
||||
let simulate_args = call_args;
|
||||
|
||||
execute_f.sig.asyncness = Some(Token));
|
||||
simulate_f.sig.asyncness = Some(Token));
|
||||
|
||||
execute_f.vis = Visibility::Public(VisPublic {
|
||||
pub_token: Token),
|
||||
});
|
||||
simulate_f.vis = Visibility::Public(VisPublic {
|
||||
pub_token: Token),
|
||||
});
|
||||
|
||||
execute_f.sig.ident = Ident::new(
|
||||
&format!("execute{}", execute_f.sig.ident),
|
||||
execute_f.sig.ident.span(),
|
||||
);
|
||||
|
||||
simulate_f.sig.ident = Ident::new(
|
||||
&format!("simulate{}", simulate_f.sig.ident),
|
||||
simulate_f.sig.ident.span(),
|
||||
);
|
||||
|
||||
let execute_output = quote! {
|
||||
-> Result<ExecuteResult, NyxdError>
|
||||
};
|
||||
let o_ts = proc_macro::TokenStream::from(execute_output);
|
||||
execute_f.sig.output = parse_macro_input!(o_ts as ReturnType);
|
||||
|
||||
let simulate_output = quote! {
|
||||
-> Result<SimulateResponse, NyxdError>
|
||||
};
|
||||
let o_ts = proc_macro::TokenStream::from(simulate_output);
|
||||
simulate_f.sig.output = parse_macro_input!(o_ts as ReturnType);
|
||||
|
||||
let simulate_block = quote! {
|
||||
{
|
||||
let (msg, _fee) = self.#name(#(#simulate_args),*);
|
||||
let msg = self.wrap_contract_execute_message(
|
||||
#cl,
|
||||
&msg,
|
||||
vec![],
|
||||
)?;
|
||||
|
||||
self.simulate(vec![msg]).await
|
||||
}
|
||||
};
|
||||
|
||||
let ts = proc_macro::TokenStream::from(simulate_block);
|
||||
simulate_f.block = Box::new(parse_macro_input!(ts as Block));
|
||||
|
||||
let execute_block = quote! {
|
||||
{
|
||||
let (req, fee) = self.#name(#(#execute_args),*);
|
||||
let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier)));
|
||||
self.client
|
||||
.execute(
|
||||
self.address(),
|
||||
#cl,
|
||||
&req,
|
||||
fee,
|
||||
#name_str,
|
||||
vec![],
|
||||
)
|
||||
.await
|
||||
}
|
||||
};
|
||||
|
||||
let ts = proc_macro::TokenStream::from(execute_block);
|
||||
execute_f.block = Box::new(parse_macro_input!(ts as Block));
|
||||
|
||||
let out = quote! {
|
||||
#orig_f
|
||||
#execute_f
|
||||
#simulate_f
|
||||
};
|
||||
|
||||
out.into()
|
||||
}
|
||||
@@ -89,7 +89,7 @@ mod tests {
|
||||
.unwrap();
|
||||
let blind_sig = issue(
|
||||
keypair.secret_key(),
|
||||
sig_req.ecash_pub_key,
|
||||
sig_req.ecash_pub_key.clone(),
|
||||
&sig_req.withdrawal_request,
|
||||
expiration_date.ecash_unix_timestamp(),
|
||||
issuance.ticketbook_type().encode(),
|
||||
|
||||
@@ -7,7 +7,6 @@ homepage.workspace = true
|
||||
documentation.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[dependencies]
|
||||
sqlx = { workspace = true, features = [
|
||||
@@ -28,7 +27,6 @@ nym-statistics-common = { path = "../statistics" }
|
||||
|
||||
|
||||
[build-dependencies]
|
||||
anyhow = { workspace = true }
|
||||
tokio = { workspace = true, features = ["rt-multi-thread", "macros"] }
|
||||
sqlx = { workspace = true, features = [
|
||||
"runtime-tokio-rustls",
|
||||
|
||||
@@ -1,29 +1,22 @@
|
||||
// Copyright 2024 - Nym Technologies SA <contact@nymtech.net>
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
use anyhow::Context;
|
||||
use sqlx::{Connection, SqliteConnection};
|
||||
use std::env;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
let out_dir = env::var("OUT_DIR")?;
|
||||
async fn main() {
|
||||
let out_dir = env::var("OUT_DIR").unwrap();
|
||||
let database_path = format!("{out_dir}/gateway-stats-example.sqlite");
|
||||
|
||||
// remove the db file if it already existed from previous build
|
||||
// in case it was from a different branch
|
||||
if std::fs::exists(&database_path)? {
|
||||
std::fs::remove_file(&database_path)?;
|
||||
}
|
||||
|
||||
let mut conn = SqliteConnection::connect(&format!("sqlite://{database_path}?mode=rwc"))
|
||||
.await
|
||||
.context("Failed to create SQLx database connection")?;
|
||||
.expect("Failed to create SQLx database connection");
|
||||
|
||||
sqlx::migrate!("./migrations")
|
||||
.run(&mut conn)
|
||||
.await
|
||||
.context("Failed to perform SQLx migrations")?;
|
||||
.expect("Failed to perform SQLx migrations");
|
||||
|
||||
#[cfg(target_family = "unix")]
|
||||
println!("cargo:rustc-env=DATABASE_URL=sqlite://{}", &database_path);
|
||||
@@ -32,6 +25,4 @@ async fn main() -> anyhow::Result<()> {
|
||||
// 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);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -7,7 +7,6 @@ homepage.workspace = true
|
||||
documentation.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[dependencies]
|
||||
async-trait = { workspace = true }
|
||||
@@ -32,7 +31,6 @@ nym-gateway-requests = { path = "../gateway-requests" }
|
||||
nym-sphinx = { path = "../nymsphinx" }
|
||||
|
||||
[build-dependencies]
|
||||
anyhow = { workspace = true }
|
||||
tokio = { workspace = true, features = ["rt-multi-thread", "macros"] }
|
||||
sqlx = { workspace = true, features = [
|
||||
"runtime-tokio-rustls",
|
||||
|
||||
@@ -1,29 +1,22 @@
|
||||
// Copyright 2023 - Nym Technologies SA <contact@nymtech.net>
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
use anyhow::Context;
|
||||
use sqlx::{Connection, SqliteConnection};
|
||||
use std::env;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
let out_dir = env::var("OUT_DIR")?;
|
||||
async fn main() {
|
||||
let out_dir = env::var("OUT_DIR").unwrap();
|
||||
let database_path = format!("{out_dir}/gateway-example.sqlite");
|
||||
|
||||
// remove the db file if it already existed from previous build
|
||||
// in case it was from a different branch
|
||||
if std::fs::exists(&database_path)? {
|
||||
std::fs::remove_file(&database_path)?;
|
||||
}
|
||||
|
||||
let mut conn = SqliteConnection::connect(&format!("sqlite://{database_path}?mode=rwc"))
|
||||
.await
|
||||
.context("Failed to create SQLx database connection")?;
|
||||
.expect("Failed to create SQLx database connection");
|
||||
|
||||
sqlx::migrate!("./migrations")
|
||||
.run(&mut conn)
|
||||
.await
|
||||
.context("Failed to perform SQLx migrations")?;
|
||||
.expect("Failed to perform SQLx migrations");
|
||||
|
||||
#[cfg(target_family = "unix")]
|
||||
println!("cargo:rustc-env=DATABASE_URL=sqlite://{}", &database_path);
|
||||
@@ -32,6 +25,4 @@ async fn main() -> anyhow::Result<()> {
|
||||
// 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);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -13,8 +13,6 @@ license.workspace = true
|
||||
[features]
|
||||
default=["tunneling"]
|
||||
tunneling=[]
|
||||
network-defaults = ["dep:nym-network-defaults"]
|
||||
force-ipv4 = []
|
||||
|
||||
[dependencies]
|
||||
async-trait = { workspace = true }
|
||||
@@ -25,8 +23,6 @@ url = { workspace = true }
|
||||
once_cell = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
serde_yaml = { workspace = true}
|
||||
serde_plain = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
itertools = { workspace = true }
|
||||
@@ -38,7 +34,6 @@ mime = { workspace = true }
|
||||
|
||||
nym-http-api-common = { path = "../http-api-common", default-features = false }
|
||||
nym-bin-common = { path = "../bin-common" }
|
||||
nym-network-defaults = { path = "../network-defaults", optional = true }
|
||||
|
||||
[target."cfg(not(target_arch = \"wasm32\"))".dependencies]
|
||||
hickory-resolver = { workspace = true, features = ["https-ring", "tls-ring", "webpki-roots"] }
|
||||
@@ -51,4 +46,3 @@ features = ["tokio"]
|
||||
[dev-dependencies]
|
||||
tokio = { workspace = true, features = ["rt", "macros"] }
|
||||
|
||||
|
||||
|
||||
@@ -54,14 +54,10 @@ impl Front {
|
||||
|
||||
#[derive(Debug, Default, PartialEq, Clone)]
|
||||
#[cfg(feature = "tunneling")]
|
||||
/// Policy for when to use domain fronting for HTTP requests.
|
||||
pub enum FrontPolicy {
|
||||
/// Always use domain fronting for all requests.
|
||||
Always,
|
||||
/// Only use domain fronting when retrying failed requests.
|
||||
OnRetry,
|
||||
#[default]
|
||||
/// Never use domain fronting.
|
||||
Off,
|
||||
}
|
||||
|
||||
@@ -100,14 +96,14 @@ mod tests {
|
||||
// Some(vec!["https://cdn77.com"]),
|
||||
// ).unwrap(); // cdn77
|
||||
|
||||
let client = ClientBuilder::new(url1)
|
||||
let client = ClientBuilder::new::<_, &str>(url1)
|
||||
.expect("bad url")
|
||||
.with_fronting(FrontPolicy::Always)
|
||||
.build()
|
||||
.build::<&str>()
|
||||
.expect("failed to build client");
|
||||
|
||||
let response = client
|
||||
.send_request::<_, (), &str, &str>(
|
||||
.send_request::<_, (), &str, &str, &str>(
|
||||
reqwest::Method::GET,
|
||||
&["api", "v1", "network", "details"],
|
||||
NO_PARAMS,
|
||||
|
||||
+102
-244
@@ -15,7 +15,7 @@
|
||||
//! # use url::Url;
|
||||
//! # use nym_http_api_client::{ApiClient, NO_PARAMS, HttpClientError};
|
||||
//!
|
||||
//! # type Err = HttpClientError;
|
||||
//! # type Err = HttpClientError<String>;
|
||||
//! # async fn run() -> Result<(), Err> {
|
||||
//! let url: Url = "https://nymvpn.com".parse()?;
|
||||
//! let client = nym_http_api_client::Client::new(url, None);
|
||||
@@ -114,7 +114,7 @@
|
||||
//! }
|
||||
//! }
|
||||
//!
|
||||
//! pub type SpecificAPIError = HttpClientError;
|
||||
//! pub type SpecificAPIError = HttpClientError<error::RequestError>;
|
||||
//!
|
||||
//! #[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
|
||||
//! #[cfg_attr(not(target_arch = "wasm32"), async_trait)]
|
||||
@@ -136,13 +136,12 @@
|
||||
//! ```
|
||||
#![warn(missing_docs)]
|
||||
|
||||
pub use reqwest::ClientBuilder as ReqwestClientBuilder;
|
||||
pub use reqwest::StatusCode;
|
||||
|
||||
use crate::path::RequestPath;
|
||||
use async_trait::async_trait;
|
||||
use bytes::Bytes;
|
||||
use http::header::{ACCEPT, CONTENT_TYPE};
|
||||
use http::header::CONTENT_TYPE;
|
||||
use http::HeaderMap;
|
||||
use itertools::Itertools;
|
||||
use mime::Mime;
|
||||
@@ -151,7 +150,6 @@ use reqwest::{RequestBuilder, Response};
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fmt::Display;
|
||||
use std::net::IpAddr;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::time::Duration;
|
||||
use thiserror::Error;
|
||||
@@ -159,13 +157,10 @@ use tracing::{debug, instrument, warn};
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use std::net::SocketAddr;
|
||||
use std::str::FromStr;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[cfg(feature = "tunneling")]
|
||||
mod fronted;
|
||||
#[cfg(feature = "tunneling")]
|
||||
pub use fronted::FrontPolicy;
|
||||
mod url;
|
||||
pub use url::{IntoUrl, Url};
|
||||
mod user_agent;
|
||||
@@ -196,46 +191,10 @@ pub type Params<'a, K, V> = &'a [(K, V)];
|
||||
/// Empty collection of HTTP Request Parameters.
|
||||
pub const NO_PARAMS: Params<'_, &'_ str, &'_ str> = &[];
|
||||
|
||||
/// Serialization format for API requests and responses
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum SerializationFormat {
|
||||
/// Use JSON serialization (default, always works)
|
||||
Json,
|
||||
/// Use bincode serialization (must be explicitly opted into)
|
||||
Bincode,
|
||||
/// Use YAML serialization
|
||||
Yaml,
|
||||
/// Use Text serialization
|
||||
Text,
|
||||
}
|
||||
|
||||
impl Display for SerializationFormat {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
SerializationFormat::Json => write!(f, "json"),
|
||||
SerializationFormat::Bincode => write!(f, "bincode"),
|
||||
SerializationFormat::Yaml => write!(f, "yaml"),
|
||||
SerializationFormat::Text => write!(f, "text"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl SerializationFormat {
|
||||
#[allow(missing_docs)]
|
||||
pub fn content_type(&self) -> String {
|
||||
match self {
|
||||
SerializationFormat::Json => "application/json".to_string(),
|
||||
SerializationFormat::Bincode => "application/bincode".to_string(),
|
||||
SerializationFormat::Yaml => "application/yaml".to_string(),
|
||||
SerializationFormat::Text => "text/plain".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The Errors that may occur when creating or using an HTTP client.
|
||||
#[derive(Debug, Error)]
|
||||
#[allow(missing_docs)]
|
||||
pub enum HttpClientError {
|
||||
pub enum HttpClientError<E: Display = String> {
|
||||
#[error("there was an issue with the REST request: {source}")]
|
||||
ReqwestClientError {
|
||||
#[from]
|
||||
@@ -264,23 +223,11 @@ pub enum HttpClientError {
|
||||
EmptyResponse { status: StatusCode },
|
||||
|
||||
#[error("failed to resolve request. status: '{status}', additional error message: {error}")]
|
||||
EndpointFailure { status: StatusCode, error: String },
|
||||
EndpointFailure { status: StatusCode, error: E },
|
||||
|
||||
#[error("failed to decode response body: {message} from {content}")]
|
||||
ResponseDecodeFailure { message: String, content: String },
|
||||
|
||||
#[error("Failed to encode bincode: {0}")]
|
||||
Bincode(#[from] bincode::Error),
|
||||
|
||||
#[error("Failed to json: {0}")]
|
||||
Json(#[from] serde_json::Error),
|
||||
|
||||
#[error("Failed to yaml: {0}")]
|
||||
Yaml(#[from] serde_yaml::Error),
|
||||
|
||||
#[error("Failed to plain: {0}")]
|
||||
Plain(#[from] serde_plain::Error),
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
#[error("the request has timed out")]
|
||||
RequestTimeout,
|
||||
@@ -322,8 +269,8 @@ pub trait ApiClientCore {
|
||||
method: reqwest::Method,
|
||||
path: P,
|
||||
params: Params<'_, K, V>,
|
||||
body: Option<&B>,
|
||||
) -> Result<RequestBuilder, HttpClientError>
|
||||
json_body: Option<&B>,
|
||||
) -> RequestBuilder
|
||||
where
|
||||
P: RequestPath,
|
||||
B: Serialize + ?Sized,
|
||||
@@ -349,8 +296,8 @@ pub trait ApiClientCore {
|
||||
&self,
|
||||
method: reqwest::Method,
|
||||
endpoint: S,
|
||||
body: Option<&B>,
|
||||
) -> Result<RequestBuilder, HttpClientError>
|
||||
json_body: Option<&B>,
|
||||
) -> RequestBuilder
|
||||
where
|
||||
B: Serialize + ?Sized,
|
||||
S: AsRef<str>,
|
||||
@@ -376,7 +323,7 @@ pub trait ApiClientCore {
|
||||
};
|
||||
let params: Vec<(String, String)> = standin_url.query_pairs().into_owned().collect();
|
||||
|
||||
self.create_request(method, path.as_slice(), ¶ms, body)
|
||||
self.create_request(method, path.as_slice(), ¶ms, json_body)
|
||||
}
|
||||
|
||||
/// Send a created HTTP request.
|
||||
@@ -384,23 +331,26 @@ pub trait ApiClientCore {
|
||||
/// A [`RequestBuilder`] can be created with [`ApiClientCore::create_request`] or
|
||||
/// [`ApiClientCore::create_request_endpoint`] or if absolutely necessary, using reqwest
|
||||
/// tooling directly.
|
||||
async fn send(&self, request: RequestBuilder) -> Result<Response, HttpClientError>;
|
||||
async fn send<E>(&self, request: RequestBuilder) -> Result<Response, HttpClientError<E>>
|
||||
where
|
||||
E: Display;
|
||||
|
||||
/// Create and send a created HTTP request.
|
||||
async fn send_request<P, B, K, V>(
|
||||
async fn send_request<P, B, K, V, E>(
|
||||
&self,
|
||||
method: reqwest::Method,
|
||||
path: P,
|
||||
params: Params<'_, K, V>,
|
||||
json_body: Option<&B>,
|
||||
) -> Result<Response, HttpClientError>
|
||||
) -> Result<Response, HttpClientError<E>>
|
||||
where
|
||||
P: RequestPath + Send + Sync,
|
||||
B: Serialize + ?Sized + Sync,
|
||||
K: AsRef<str> + Sync,
|
||||
V: AsRef<str> + Sync,
|
||||
E: Display,
|
||||
{
|
||||
let req = self.create_request(method, path, params, json_body)?;
|
||||
let req = self.create_request(method, path, params, json_body);
|
||||
self.send(req).await
|
||||
}
|
||||
}
|
||||
@@ -420,16 +370,16 @@ pub struct ClientBuilder {
|
||||
front: Option<fronted::Front>,
|
||||
|
||||
retry_limit: usize,
|
||||
serialization: SerializationFormat,
|
||||
}
|
||||
|
||||
impl ClientBuilder {
|
||||
/// Constructs a new `ClientBuilder`.
|
||||
///
|
||||
/// This is the same as `Client::builder()`.
|
||||
pub fn new<U>(url: U) -> Result<Self, HttpClientError>
|
||||
pub fn new<U, E>(url: U) -> Result<Self, HttpClientError<E>>
|
||||
where
|
||||
U: IntoUrl,
|
||||
E: Display,
|
||||
{
|
||||
let str_url = url.as_str();
|
||||
|
||||
@@ -445,50 +395,6 @@ impl ClientBuilder {
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a client builder from network details with sensible defaults
|
||||
#[cfg(feature = "network-defaults")]
|
||||
pub fn from_network(
|
||||
network: &nym_network_defaults::NymNetworkDetails,
|
||||
) -> Result<Self, HttpClientError> {
|
||||
let urls = network
|
||||
.nym_api_urls
|
||||
.as_ref()
|
||||
.ok_or_else(|| {
|
||||
HttpClientError::GenericRequestFailure(
|
||||
"No API URLs configured in network details".to_string(),
|
||||
)
|
||||
})?
|
||||
.iter()
|
||||
.map(|api_url| {
|
||||
// Convert ApiUrl to our Url type with fronting support
|
||||
let mut url = Url::parse(&api_url.url)?;
|
||||
|
||||
// Add fronting domains if available
|
||||
#[cfg(feature = "tunneling")]
|
||||
if let Some(ref front_hosts) = api_url.front_hosts {
|
||||
let fronts: Vec<String> = front_hosts
|
||||
.iter()
|
||||
.map(|host| format!("https://{}", host))
|
||||
.collect();
|
||||
url = Url::new(api_url.url.clone(), Some(fronts))
|
||||
.map_err(|e| HttpClientError::GenericRequestFailure(e.to_string()))?;
|
||||
}
|
||||
|
||||
Ok(url)
|
||||
})
|
||||
.collect::<Result<Vec<_>, HttpClientError>>()?;
|
||||
|
||||
let mut builder = Self::new_with_urls(urls);
|
||||
|
||||
// Enable domain fronting by default (on retry)
|
||||
#[cfg(feature = "tunneling")]
|
||||
{
|
||||
builder = builder.with_fronting(FrontPolicy::OnRetry);
|
||||
}
|
||||
|
||||
Ok(builder)
|
||||
}
|
||||
|
||||
/// Constructs a new http `ClientBuilder` from a valid url.
|
||||
pub fn new_with_urls(urls: Vec<Url>) -> Self {
|
||||
let urls = Self::check_urls(urls);
|
||||
@@ -496,8 +402,6 @@ impl ClientBuilder {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let reqwest_client_builder = reqwest::ClientBuilder::new();
|
||||
|
||||
warn!("FORCING IPv4 CONNECTIONS");
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let reqwest_client_builder = {
|
||||
// Note: I believe the manual enable calls for the compression methods are extra
|
||||
@@ -514,9 +418,6 @@ impl ClientBuilder {
|
||||
.zstd(true)
|
||||
};
|
||||
|
||||
#[cfg(feature = "force-ipv4")]
|
||||
let reqwest_client_builder = reqwest_client_builder.local_address(IpAddr::from_str("0.0.0.0").unwrap());
|
||||
|
||||
ClientBuilder {
|
||||
urls,
|
||||
timeout: None,
|
||||
@@ -527,7 +428,6 @@ impl ClientBuilder {
|
||||
front: None,
|
||||
|
||||
retry_limit: 0,
|
||||
serialization: SerializationFormat::Json,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -600,19 +500,11 @@ impl ClientBuilder {
|
||||
self
|
||||
}
|
||||
|
||||
/// Set the serialization format for API requests and responses
|
||||
pub fn with_serialization(mut self, format: SerializationFormat) -> Self {
|
||||
self.serialization = format;
|
||||
self
|
||||
}
|
||||
|
||||
/// Configure the client to use bincode serialization
|
||||
pub fn with_bincode(self) -> Self {
|
||||
self.with_serialization(SerializationFormat::Bincode)
|
||||
}
|
||||
|
||||
/// Returns a Client that uses this ClientBuilder configuration.
|
||||
pub fn build(self) -> Result<Client, HttpClientError> {
|
||||
pub fn build<E>(self) -> Result<Client, HttpClientError<E>>
|
||||
where
|
||||
E: Display,
|
||||
{
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let reqwest_client = self.reqwest_client_builder.build()?;
|
||||
|
||||
@@ -649,7 +541,6 @@ impl ClientBuilder {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
request_timeout: self.timeout.unwrap_or(DEFAULT_TIMEOUT),
|
||||
retry_limit: self.retry_limit,
|
||||
serialization: self.serialization,
|
||||
};
|
||||
|
||||
Ok(client)
|
||||
@@ -670,7 +561,6 @@ pub struct Client {
|
||||
request_timeout: Duration,
|
||||
|
||||
retry_limit: usize,
|
||||
serialization: SerializationFormat,
|
||||
}
|
||||
|
||||
impl Client {
|
||||
@@ -680,15 +570,16 @@ impl Client {
|
||||
// In order to prevent interference in API requests at the DNS phase we default to a resolver
|
||||
// that uses DoT and DoH.
|
||||
pub fn new(base_url: ::url::Url, timeout: Option<Duration>) -> Self {
|
||||
Self::new_url(base_url, timeout).expect(
|
||||
Self::new_url::<_, String>(base_url, timeout).expect(
|
||||
"we provided valid url and we were unwrapping previous construction errors anyway",
|
||||
)
|
||||
}
|
||||
|
||||
/// Attempt to create a new http client from a something that can be converted to a URL
|
||||
pub fn new_url<U>(url: U, timeout: Option<Duration>) -> Result<Self, HttpClientError>
|
||||
pub fn new_url<U, E>(url: U, timeout: Option<Duration>) -> Result<Self, HttpClientError<E>>
|
||||
where
|
||||
U: IntoUrl,
|
||||
E: Display,
|
||||
{
|
||||
let builder = Self::builder(url)?;
|
||||
match timeout {
|
||||
@@ -700,9 +591,10 @@ impl Client {
|
||||
/// Creates a [`ClientBuilder`] to configure a [`Client`].
|
||||
///
|
||||
/// This is the same as [`ClientBuilder::new()`].
|
||||
pub fn builder<U>(url: U) -> Result<ClientBuilder, HttpClientError>
|
||||
pub fn builder<U, E>(url: U) -> Result<ClientBuilder, HttpClientError<E>>
|
||||
where
|
||||
U: IntoUrl,
|
||||
E: Display,
|
||||
{
|
||||
ClientBuilder::new(url)
|
||||
}
|
||||
@@ -726,7 +618,6 @@ impl Client {
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
request_timeout: self.request_timeout,
|
||||
serialization: self.serialization,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -802,42 +693,26 @@ impl Client {
|
||||
/// this method. For example, if the client is configured to rotate hosts after each error, this
|
||||
/// method should be called after the host has been updated -- i.e. as part of the subsequent
|
||||
/// send.
|
||||
fn apply_hosts_to_req(&self, r: &mut reqwest::Request) -> (&str, Option<&str>) {
|
||||
fn apply_hosts_to_req(&self, r: &mut reqwest::Request) {
|
||||
let url = self.current_url();
|
||||
r.url_mut().set_host(url.host_str()).unwrap();
|
||||
|
||||
#[cfg(feature = "tunneling")]
|
||||
if let Some(ref front) = self.front {
|
||||
if front.is_enabled() {
|
||||
if let Some(front_host) = url.front_str() {
|
||||
if let Some(actual_host) = url.host_str() {
|
||||
tracing::debug!(
|
||||
"Domain fronting enabled: routing via CDN {} to actual host {}",
|
||||
front_host,
|
||||
actual_host
|
||||
);
|
||||
// this should never fail as we are transplanting the host from one url to another
|
||||
r.url_mut().set_host(url.front_str()).unwrap();
|
||||
|
||||
// this should never fail as we are transplanting the host from one url to another
|
||||
r.url_mut().set_host(Some(front_host)).unwrap();
|
||||
|
||||
let actual_host_header: HeaderValue =
|
||||
actual_host.parse().unwrap_or(HeaderValue::from_static(""));
|
||||
// If the map did have this key present, the new value is associated with the key
|
||||
// and all previous values are removed. (reqwest HeaderMap docs)
|
||||
_ = r
|
||||
.headers_mut()
|
||||
.insert(reqwest::header::HOST, actual_host_header);
|
||||
|
||||
return (url.as_str(), url.front_str());
|
||||
} else {
|
||||
warn!("Domain fronting is enabled, but no host_url is defined! Domain fronting WILL NOT WORK")
|
||||
}
|
||||
} else {
|
||||
warn!("Domain fronting is enabled, but no front_url is defined! Domain fronting WILL NOT WORK")
|
||||
}
|
||||
let actual_host: HeaderValue = url
|
||||
.host_str()
|
||||
.unwrap_or("")
|
||||
.parse()
|
||||
.unwrap_or(HeaderValue::from_static(""));
|
||||
// If the map did have this key present, the new value is associated with the key
|
||||
// and all previous values are removed. (reqwest HeaderMap docs)
|
||||
_ = r.headers_mut().insert(reqwest::header::HOST, actual_host);
|
||||
}
|
||||
}
|
||||
(url.as_str(), None)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -850,8 +725,8 @@ impl ApiClientCore for Client {
|
||||
method: reqwest::Method,
|
||||
path: P,
|
||||
params: Params<'_, K, V>,
|
||||
body: Option<&B>,
|
||||
) -> Result<RequestBuilder, HttpClientError>
|
||||
json_body: Option<&B>,
|
||||
) -> RequestBuilder
|
||||
where
|
||||
P: RequestPath,
|
||||
B: Serialize + ?Sized,
|
||||
@@ -867,35 +742,17 @@ impl ApiClientCore for Client {
|
||||
|
||||
let mut rb = RequestBuilder::from_parts(self.reqwest_client.clone(), req);
|
||||
|
||||
rb = rb
|
||||
.header(ACCEPT, self.serialization.content_type())
|
||||
.header(CONTENT_TYPE, self.serialization.content_type());
|
||||
|
||||
if let Some(body) = body {
|
||||
match self.serialization {
|
||||
SerializationFormat::Json => {
|
||||
rb = rb.json(body);
|
||||
}
|
||||
SerializationFormat::Bincode => {
|
||||
let body = bincode::serialize(body)?;
|
||||
rb = rb.body(body);
|
||||
}
|
||||
SerializationFormat::Yaml => {
|
||||
let mut body_bytes = Vec::new();
|
||||
serde_yaml::to_writer(&mut body_bytes, &body)?;
|
||||
rb = rb.body(body_bytes);
|
||||
}
|
||||
SerializationFormat::Text => {
|
||||
let body = serde_plain::to_string(&body)?.as_bytes().to_vec();
|
||||
rb = rb.body(body);
|
||||
}
|
||||
}
|
||||
if let Some(body) = json_body {
|
||||
rb = rb.json(body);
|
||||
}
|
||||
|
||||
Ok(rb)
|
||||
rb
|
||||
}
|
||||
|
||||
async fn send(&self, request: RequestBuilder) -> Result<Response, HttpClientError> {
|
||||
async fn send<E>(&self, request: RequestBuilder) -> Result<Response, HttpClientError<E>>
|
||||
where
|
||||
E: Display,
|
||||
{
|
||||
let mut attempts = 0;
|
||||
loop {
|
||||
// try_clone may fail if the body is a stream in which case using retries is not advised.
|
||||
@@ -911,7 +768,7 @@ impl ApiClientCore for Client {
|
||||
self.apply_hosts_to_req(&mut req);
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let response: Result<Response, HttpClientError> = {
|
||||
let response: Result<Response, HttpClientError<E>> = {
|
||||
Ok(wasmtimer::tokio::timeout(
|
||||
self.request_timeout,
|
||||
self.reqwest_client.execute(req),
|
||||
@@ -933,14 +790,7 @@ impl ApiClientCore for Client {
|
||||
if let Some(ref front) = self.front {
|
||||
// If fronting is set to be enabled on error, enable domain fronting as we
|
||||
// have encountered an error.
|
||||
let was_enabled = front.is_enabled();
|
||||
front.retry_enable();
|
||||
if !was_enabled && front.is_enabled() {
|
||||
tracing::info!(
|
||||
"Domain fronting activated after connection failure: {}",
|
||||
e
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if attempts < self.retry_limit {
|
||||
@@ -965,11 +815,7 @@ impl ApiClientCore for Client {
|
||||
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
|
||||
pub trait ApiClient: ApiClientCore {
|
||||
/// Create an HTTP GET Request with the provided path and parameters
|
||||
fn create_get_request<P, K, V>(
|
||||
&self,
|
||||
path: P,
|
||||
params: Params<'_, K, V>,
|
||||
) -> Result<RequestBuilder, HttpClientError>
|
||||
fn create_get_request<P, K, V>(&self, path: P, params: Params<'_, K, V>) -> RequestBuilder
|
||||
where
|
||||
P: RequestPath,
|
||||
K: AsRef<str>,
|
||||
@@ -984,7 +830,7 @@ pub trait ApiClient: ApiClientCore {
|
||||
path: P,
|
||||
params: Params<'_, K, V>,
|
||||
json_body: &B,
|
||||
) -> Result<RequestBuilder, HttpClientError>
|
||||
) -> RequestBuilder
|
||||
where
|
||||
P: RequestPath,
|
||||
B: Serialize + ?Sized,
|
||||
@@ -995,11 +841,7 @@ pub trait ApiClient: ApiClientCore {
|
||||
}
|
||||
|
||||
/// Create an HTTP DELETE Request with the provided path and parameters
|
||||
fn create_delete_request<P, K, V>(
|
||||
&self,
|
||||
path: P,
|
||||
params: Params<'_, K, V>,
|
||||
) -> Result<RequestBuilder, HttpClientError>
|
||||
fn create_delete_request<P, K, V>(&self, path: P, params: Params<'_, K, V>) -> RequestBuilder
|
||||
where
|
||||
P: RequestPath,
|
||||
K: AsRef<str>,
|
||||
@@ -1014,7 +856,7 @@ pub trait ApiClient: ApiClientCore {
|
||||
path: P,
|
||||
params: Params<'_, K, V>,
|
||||
json_body: &B,
|
||||
) -> Result<RequestBuilder, HttpClientError>
|
||||
) -> RequestBuilder
|
||||
where
|
||||
P: RequestPath,
|
||||
B: Serialize + ?Sized,
|
||||
@@ -1026,64 +868,68 @@ pub trait ApiClient: ApiClientCore {
|
||||
|
||||
/// Create and send an HTTP GET Request with the provided path and parameters
|
||||
#[instrument(level = "debug", skip_all, fields(path=?path))]
|
||||
async fn send_get_request<P, K, V>(
|
||||
async fn send_get_request<P, K, V, E>(
|
||||
&self,
|
||||
path: P,
|
||||
params: Params<'_, K, V>,
|
||||
) -> Result<Response, HttpClientError>
|
||||
) -> Result<Response, HttpClientError<E>>
|
||||
where
|
||||
P: RequestPath + Send + Sync,
|
||||
K: AsRef<str> + Sync,
|
||||
V: AsRef<str> + Sync,
|
||||
E: Display,
|
||||
{
|
||||
self.send_request(reqwest::Method::GET, path, params, None::<&()>)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Create and send an HTTP POST Request with the provided path, parameters, and json data
|
||||
async fn send_post_request<P, B, K, V>(
|
||||
async fn send_post_request<P, B, K, V, E>(
|
||||
&self,
|
||||
path: P,
|
||||
params: Params<'_, K, V>,
|
||||
json_body: &B,
|
||||
) -> Result<Response, HttpClientError>
|
||||
) -> Result<Response, HttpClientError<E>>
|
||||
where
|
||||
P: RequestPath + Send + Sync,
|
||||
B: Serialize + ?Sized + Sync,
|
||||
K: AsRef<str> + Sync,
|
||||
V: AsRef<str> + Sync,
|
||||
E: Display,
|
||||
{
|
||||
self.send_request(reqwest::Method::POST, path, params, Some(json_body))
|
||||
.await
|
||||
}
|
||||
|
||||
/// Create and send an HTTP DELETE Request with the provided path and parameters
|
||||
async fn send_delete_request<P, K, V>(
|
||||
async fn send_delete_request<P, K, V, E>(
|
||||
&self,
|
||||
path: P,
|
||||
params: Params<'_, K, V>,
|
||||
) -> Result<Response, HttpClientError>
|
||||
) -> Result<Response, HttpClientError<E>>
|
||||
where
|
||||
P: RequestPath + Send + Sync,
|
||||
K: AsRef<str> + Sync,
|
||||
V: AsRef<str> + Sync,
|
||||
E: Display,
|
||||
{
|
||||
self.send_request(reqwest::Method::DELETE, path, params, None::<&()>)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Create and send an HTTP PATCH Request with the provided path, parameters, and json data
|
||||
async fn send_patch_request<P, B, K, V>(
|
||||
async fn send_patch_request<P, B, K, V, E>(
|
||||
&self,
|
||||
path: P,
|
||||
params: Params<'_, K, V>,
|
||||
json_body: &B,
|
||||
) -> Result<Response, HttpClientError>
|
||||
) -> Result<Response, HttpClientError<E>>
|
||||
where
|
||||
P: RequestPath + Send + Sync,
|
||||
B: Serialize + ?Sized + Sync,
|
||||
K: AsRef<str> + Sync,
|
||||
V: AsRef<str> + Sync,
|
||||
E: Display,
|
||||
{
|
||||
self.send_request(reqwest::Method::PATCH, path, params, Some(json_body))
|
||||
.await
|
||||
@@ -1094,16 +940,17 @@ pub trait ApiClient: ApiClientCore {
|
||||
/// into the provided type `T`.
|
||||
#[instrument(level = "debug", skip_all, fields(path=?path))]
|
||||
// TODO: deprecate in favour of get_response that works based on mime type in the response
|
||||
async fn get_json<P, T, K, V>(
|
||||
async fn get_json<P, T, K, V, E>(
|
||||
&self,
|
||||
path: P,
|
||||
params: Params<'_, K, V>,
|
||||
) -> Result<T, HttpClientError>
|
||||
) -> Result<T, HttpClientError<E>>
|
||||
where
|
||||
P: RequestPath + Send + Sync,
|
||||
for<'a> T: Deserialize<'a>,
|
||||
K: AsRef<str> + Sync,
|
||||
V: AsRef<str> + Sync,
|
||||
E: Display + DeserializeOwned,
|
||||
{
|
||||
self.get_response(path, params).await
|
||||
}
|
||||
@@ -1111,16 +958,17 @@ pub trait ApiClient: ApiClientCore {
|
||||
/// 'get' data from the segment-defined path, e.g. `["api", "v1", "mixnodes"]`, with tuple
|
||||
/// defined key-value parameters, e.g. `[("since", "12345")]`. Attempt to parse the response
|
||||
/// into the provided type `T` based on the content type header
|
||||
async fn get_response<P, T, K, V>(
|
||||
async fn get_response<P, T, K, V, E>(
|
||||
&self,
|
||||
path: P,
|
||||
params: Params<'_, K, V>,
|
||||
) -> Result<T, HttpClientError>
|
||||
) -> Result<T, HttpClientError<E>>
|
||||
where
|
||||
P: RequestPath + Send + Sync,
|
||||
for<'a> T: Deserialize<'a>,
|
||||
K: AsRef<str> + Sync,
|
||||
V: AsRef<str> + Sync,
|
||||
E: Display + DeserializeOwned,
|
||||
{
|
||||
let res = self
|
||||
.send_request(reqwest::Method::GET, path, params, None::<&()>)
|
||||
@@ -1131,18 +979,19 @@ pub trait ApiClient: ApiClientCore {
|
||||
/// 'post' json data to the segment-defined path, e.g. `["api", "v1", "mixnodes"]`, with tuple
|
||||
/// defined key-value parameters, e.g. `[("since", "12345")]`. Attempt to parse the response
|
||||
/// into the provided type `T`.
|
||||
async fn post_json<P, B, T, K, V>(
|
||||
async fn post_json<P, B, T, K, V, E>(
|
||||
&self,
|
||||
path: P,
|
||||
params: Params<'_, K, V>,
|
||||
json_body: &B,
|
||||
) -> Result<T, HttpClientError>
|
||||
) -> Result<T, HttpClientError<E>>
|
||||
where
|
||||
P: RequestPath + Send + Sync,
|
||||
B: Serialize + ?Sized + Sync,
|
||||
for<'a> T: Deserialize<'a>,
|
||||
K: AsRef<str> + Sync,
|
||||
V: AsRef<str> + Sync,
|
||||
E: Display + DeserializeOwned,
|
||||
{
|
||||
let res = self
|
||||
.send_request(reqwest::Method::POST, path, params, Some(json_body))
|
||||
@@ -1153,16 +1002,17 @@ pub trait ApiClient: ApiClientCore {
|
||||
/// 'delete' json data from the segment-defined path, e.g. `["api", "v1", "mixnodes"]`, with
|
||||
/// tuple defined key-value parameters, e.g. `[("since", "12345")]`. Attempt to parse the
|
||||
/// response into the provided type `T`.
|
||||
async fn delete_json<P, T, K, V>(
|
||||
async fn delete_json<P, T, K, V, E>(
|
||||
&self,
|
||||
path: P,
|
||||
params: Params<'_, K, V>,
|
||||
) -> Result<T, HttpClientError>
|
||||
) -> Result<T, HttpClientError<E>>
|
||||
where
|
||||
P: RequestPath + Send + Sync,
|
||||
for<'a> T: Deserialize<'a>,
|
||||
K: AsRef<str> + Sync,
|
||||
V: AsRef<str> + Sync,
|
||||
E: Display + DeserializeOwned,
|
||||
{
|
||||
let res = self
|
||||
.send_request(reqwest::Method::DELETE, path, params, None::<&()>)
|
||||
@@ -1173,18 +1023,19 @@ pub trait ApiClient: ApiClientCore {
|
||||
/// 'patch' json data at the segment-defined path, e.g. `["api", "v1", "mixnodes"]`, with tuple
|
||||
/// defined key-value parameters, e.g. `[("since", "12345")]`. Attempt to parse the response
|
||||
/// into the provided type `T`.
|
||||
async fn patch_json<P, B, T, K, V>(
|
||||
async fn patch_json<P, B, T, K, V, E>(
|
||||
&self,
|
||||
path: P,
|
||||
params: Params<'_, K, V>,
|
||||
json_body: &B,
|
||||
) -> Result<T, HttpClientError>
|
||||
) -> Result<T, HttpClientError<E>>
|
||||
where
|
||||
P: RequestPath + Send + Sync,
|
||||
B: Serialize + ?Sized + Sync,
|
||||
for<'a> T: Deserialize<'a>,
|
||||
K: AsRef<str> + Sync,
|
||||
V: AsRef<str> + Sync,
|
||||
E: Display + DeserializeOwned,
|
||||
{
|
||||
let res = self
|
||||
.send_request(reqwest::Method::PATCH, path, params, Some(json_body))
|
||||
@@ -1194,59 +1045,62 @@ pub trait ApiClient: ApiClientCore {
|
||||
|
||||
/// `get` json data from the provided absolute endpoint, e.g. `"/api/v1/mixnodes?since=12345"`.
|
||||
/// Attempt to parse the response into the provided type `T`.
|
||||
async fn get_json_from<T, S>(&self, endpoint: S) -> Result<T, HttpClientError>
|
||||
async fn get_json_from<T, S, E>(&self, endpoint: S) -> Result<T, HttpClientError<E>>
|
||||
where
|
||||
for<'a> T: Deserialize<'a>,
|
||||
E: Display + DeserializeOwned,
|
||||
S: AsRef<str> + Sync + Send,
|
||||
{
|
||||
let req = self.create_request_endpoint(reqwest::Method::GET, endpoint, None::<&()>)?;
|
||||
let req = self.create_request_endpoint(reqwest::Method::GET, endpoint, None::<&()>);
|
||||
let res = self.send(req).await?;
|
||||
parse_response(res, false).await
|
||||
}
|
||||
|
||||
/// `post` json data to the provided absolute endpoint, e.g. `"/api/v1/mixnodes?since=12345"`.
|
||||
/// Attempt to parse the response into the provided type `T`.
|
||||
async fn post_json_data_to<B, T, S>(
|
||||
async fn post_json_data_to<B, T, S, E>(
|
||||
&self,
|
||||
endpoint: S,
|
||||
json_body: &B,
|
||||
) -> Result<T, HttpClientError>
|
||||
) -> Result<T, HttpClientError<E>>
|
||||
where
|
||||
B: Serialize + ?Sized + Sync,
|
||||
for<'a> T: Deserialize<'a>,
|
||||
E: Display + DeserializeOwned,
|
||||
S: AsRef<str> + Sync + Send,
|
||||
{
|
||||
let req = self.create_request_endpoint(reqwest::Method::POST, endpoint, Some(json_body))?;
|
||||
let req = self.create_request_endpoint(reqwest::Method::POST, endpoint, Some(json_body));
|
||||
let res = self.send(req).await?;
|
||||
parse_response(res, false).await
|
||||
}
|
||||
|
||||
/// `delete` json data from the provided absolute endpoint, e.g.
|
||||
/// `"/api/v1/mixnodes?since=12345"`. Attempt to parse the response into the provided type `T`.
|
||||
async fn delete_json_from<T, S>(&self, endpoint: S) -> Result<T, HttpClientError>
|
||||
async fn delete_json_from<T, S, E>(&self, endpoint: S) -> Result<T, HttpClientError<E>>
|
||||
where
|
||||
for<'a> T: Deserialize<'a>,
|
||||
E: Display + DeserializeOwned,
|
||||
S: AsRef<str> + Sync + Send,
|
||||
{
|
||||
let req = self.create_request_endpoint(reqwest::Method::DELETE, endpoint, None::<&()>)?;
|
||||
let req = self.create_request_endpoint(reqwest::Method::DELETE, endpoint, None::<&()>);
|
||||
let res = self.send(req).await?;
|
||||
parse_response(res, false).await
|
||||
}
|
||||
|
||||
/// `patch` json data at the provided absolute endpoint, e.g. `"/api/v1/mixnodes?since=12345"`.
|
||||
/// Attempt to parse the response into the provided type `T`.
|
||||
async fn patch_json_data_at<B, T, S>(
|
||||
async fn patch_json_data_at<B, T, S, E>(
|
||||
&self,
|
||||
endpoint: S,
|
||||
json_body: &B,
|
||||
) -> Result<T, HttpClientError>
|
||||
) -> Result<T, HttpClientError<E>>
|
||||
where
|
||||
B: Serialize + ?Sized + Sync,
|
||||
for<'a> T: Deserialize<'a>,
|
||||
E: Display + DeserializeOwned,
|
||||
S: AsRef<str> + Sync + Send,
|
||||
{
|
||||
let req =
|
||||
self.create_request_endpoint(reqwest::Method::PATCH, endpoint, Some(json_body))?;
|
||||
let req = self.create_request_endpoint(reqwest::Method::PATCH, endpoint, Some(json_body));
|
||||
let res = self.send(req).await?;
|
||||
parse_response(res, false).await
|
||||
}
|
||||
@@ -1302,9 +1156,10 @@ fn decode_as_text(bytes: &bytes::Bytes, headers: &HeaderMap) -> String {
|
||||
|
||||
/// Attempt to parse a response object from an HTTP response
|
||||
#[instrument(level = "debug", skip_all)]
|
||||
pub async fn parse_response<T>(res: Response, allow_empty: bool) -> Result<T, HttpClientError>
|
||||
pub async fn parse_response<T, E>(res: Response, allow_empty: bool) -> Result<T, HttpClientError<E>>
|
||||
where
|
||||
T: DeserializeOwned,
|
||||
E: DeserializeOwned + Display,
|
||||
{
|
||||
let status = res.status();
|
||||
tracing::trace!("Status: {} (success: {})", &status, status.is_success());
|
||||
@@ -1340,9 +1195,10 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
fn decode_as_json<T>(headers: &HeaderMap, content: Bytes) -> Result<T, HttpClientError>
|
||||
fn decode_as_json<T, E>(headers: &HeaderMap, content: Bytes) -> Result<T, HttpClientError<E>>
|
||||
where
|
||||
T: DeserializeOwned,
|
||||
E: DeserializeOwned + Display,
|
||||
{
|
||||
match serde_json::from_slice(&content) {
|
||||
Ok(data) => Ok(data),
|
||||
@@ -1356,9 +1212,10 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
fn decode_as_bincode<T>(headers: &HeaderMap, content: Bytes) -> Result<T, HttpClientError>
|
||||
fn decode_as_bincode<T, E>(headers: &HeaderMap, content: Bytes) -> Result<T, HttpClientError<E>>
|
||||
where
|
||||
T: DeserializeOwned,
|
||||
E: DeserializeOwned + Display,
|
||||
{
|
||||
use bincode::Options;
|
||||
|
||||
@@ -1375,9 +1232,10 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
fn decode_raw_response<T>(headers: &HeaderMap, content: Bytes) -> Result<T, HttpClientError>
|
||||
fn decode_raw_response<T, E>(headers: &HeaderMap, content: Bytes) -> Result<T, HttpClientError<E>>
|
||||
where
|
||||
T: DeserializeOwned,
|
||||
E: DeserializeOwned + Display,
|
||||
{
|
||||
// if content type header is missing, fallback to our old default, json
|
||||
let mime = try_get_mime_type(headers).unwrap_or(mime::APPLICATION_JSON);
|
||||
|
||||
@@ -95,10 +95,10 @@ async fn api_client_retry() -> Result<(), Box<dyn std::error::Error>> {
|
||||
"http://example.com/".parse()?,
|
||||
])
|
||||
.with_retries(3)
|
||||
.build()?;
|
||||
.build::<HttpClientError>()?;
|
||||
|
||||
let req = client.create_get_request(&["/"], NO_PARAMS).unwrap();
|
||||
let resp = client.send(req).await?;
|
||||
let req = client.create_get_request(&["/"], NO_PARAMS);
|
||||
let resp = client.send::<HttpClientError>(req).await?;
|
||||
|
||||
assert_eq!(resp.status(), 200);
|
||||
|
||||
@@ -111,7 +111,10 @@ async fn api_client_retry() -> Result<(), Box<dyn std::error::Error>> {
|
||||
#[test]
|
||||
fn host_updating() {
|
||||
let url = Url::new("http://example.com", None).unwrap();
|
||||
let mut client = ClientBuilder::new(url).unwrap().build().unwrap();
|
||||
let mut client = ClientBuilder::new::<_, &str>(url)
|
||||
.unwrap()
|
||||
.build::<&str>()
|
||||
.unwrap();
|
||||
|
||||
// check that the url is set correctly
|
||||
let current_url = client.current_url();
|
||||
@@ -168,10 +171,10 @@ fn host_updating() {
|
||||
#[cfg(feature = "tunneling")]
|
||||
fn fronted_host_updating() {
|
||||
let url = Url::new("http://example.com", Some(vec!["http://front1.com"])).unwrap();
|
||||
let mut client = ClientBuilder::new(url)
|
||||
let mut client = ClientBuilder::new::<_, &str>(url)
|
||||
.unwrap()
|
||||
.with_fronting(crate::fronted::FrontPolicy::Always)
|
||||
.build()
|
||||
.build::<&str>()
|
||||
.unwrap();
|
||||
|
||||
// check that the url is set correctly
|
||||
|
||||
@@ -47,8 +47,7 @@ pub mod nyx {
|
||||
pub mod wireguard {
|
||||
use std::net::{Ipv4Addr, Ipv6Addr};
|
||||
|
||||
pub const WG_TUNNEL_PORT: u16 = 51822;
|
||||
pub const WG_METADATA_PORT: u16 = 51830;
|
||||
pub const WG_PORT: u16 = 51822;
|
||||
|
||||
// The interface used to route traffic
|
||||
pub const WG_TUN_BASE_NAME: &str = "nymwg";
|
||||
|
||||
@@ -55,7 +55,6 @@ pub struct ApiUrl {
|
||||
pub front_hosts: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone)]
|
||||
pub struct ApiUrlConst<'a> {
|
||||
pub url: &'a str,
|
||||
pub front_hosts: Option<&'a [&'a str]>,
|
||||
@@ -189,14 +188,8 @@ impl NymNetworkDetails {
|
||||
),
|
||||
},
|
||||
nym_vpn_api_url: parse_optional_str(mainnet::NYM_VPN_API),
|
||||
nym_api_urls: Some(mainnet::NYM_APIS.iter().copied().map(Into::into).collect()),
|
||||
nym_vpn_api_urls: Some(
|
||||
mainnet::NYM_VPN_APIS
|
||||
.iter()
|
||||
.copied()
|
||||
.map(Into::into)
|
||||
.collect(),
|
||||
),
|
||||
nym_api_urls: None,
|
||||
nym_vpn_api_urls: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -319,9 +319,9 @@ mod tests {
|
||||
let sk = grp.random_scalar();
|
||||
let sk_user = SecretKeyUser { sk };
|
||||
let pk_user = sk_user.public_key();
|
||||
public_keys.push(pk_user);
|
||||
public_keys.push(pk_user.clone());
|
||||
}
|
||||
public_keys.push(user_keypair.public_key());
|
||||
public_keys.push(user_keypair.public_key().clone());
|
||||
|
||||
let (req, req_info) =
|
||||
withdrawal_request(user_keypair.secret_key(), expiration_date, t_type).unwrap();
|
||||
@@ -462,9 +462,9 @@ mod tests {
|
||||
let sk = grp.random_scalar();
|
||||
let sk_user = SecretKeyUser { sk };
|
||||
let pk_user = sk_user.public_key();
|
||||
public_keys.push(pk_user);
|
||||
public_keys.push(pk_user.clone());
|
||||
}
|
||||
public_keys.push(user_keypair.public_key());
|
||||
public_keys.push(user_keypair.public_key().clone());
|
||||
|
||||
let (req, req_info) =
|
||||
withdrawal_request(user_keypair.secret_key(), expiration_date, t_type).unwrap();
|
||||
|
||||
@@ -401,7 +401,7 @@ impl Bytable for SecretKeyUser {
|
||||
|
||||
impl Base58 for SecretKeyUser {}
|
||||
|
||||
#[derive(Debug, Eq, PartialEq, Clone, Copy, Serialize, Deserialize)]
|
||||
#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
|
||||
pub struct PublicKeyUser {
|
||||
pub(crate) pk: G1Projective,
|
||||
}
|
||||
@@ -554,7 +554,7 @@ impl KeyPairUser {
|
||||
}
|
||||
|
||||
pub fn public_key(&self) -> PublicKeyUser {
|
||||
self.public_key
|
||||
self.public_key.clone()
|
||||
}
|
||||
|
||||
pub fn to_bytes(&self) -> Vec<u8> {
|
||||
|
||||
@@ -16,6 +16,3 @@ thiserror = { workspace = true }
|
||||
[dev-dependencies]
|
||||
rand = { workspace = true }
|
||||
nym-crypto = { path = "../../crypto", features = ["rand"] }
|
||||
bincode = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
@@ -7,7 +7,7 @@
|
||||
use crate::nodes::{NodeIdentity, NODE_IDENTITY_SIZE};
|
||||
use nym_crypto::asymmetric::{ed25519, x25519};
|
||||
use nym_sphinx_types::Destination;
|
||||
use serde::de::{Error as SerdeError, SeqAccess, Unexpected, Visitor};
|
||||
use serde::de::{Error as SerdeError, Unexpected, Visitor};
|
||||
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||
use std::fmt::{self, Formatter};
|
||||
use std::str::FromStr;
|
||||
@@ -64,7 +64,7 @@ impl<'de> Deserialize<'de> for Recipient {
|
||||
{
|
||||
struct RecipientVisitor;
|
||||
|
||||
impl<'de> Visitor<'de> for RecipientVisitor {
|
||||
impl Visitor<'_> for RecipientVisitor {
|
||||
type Value = Recipient;
|
||||
|
||||
fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
||||
@@ -90,42 +90,6 @@ impl<'de> Deserialize<'de> for Recipient {
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
|
||||
where
|
||||
A: SeqAccess<'de>,
|
||||
{
|
||||
// if we know the size hint, check if it matches expectation,
|
||||
// otherwise return an error
|
||||
if let Some(size_hint) = seq.size_hint() {
|
||||
if size_hint != Recipient::LEN {
|
||||
return Err(SerdeError::invalid_length(size_hint, &self));
|
||||
}
|
||||
}
|
||||
|
||||
let mut recipient_bytes = [0u8; Recipient::LEN];
|
||||
|
||||
// clippy's suggestion is completely wrong and it iterates wrong sequence
|
||||
#[allow(clippy::needless_range_loop)]
|
||||
for i in 0..Recipient::LEN {
|
||||
let Some(elem) = seq.next_element::<u8>()? else {
|
||||
return Err(SerdeError::invalid_length(i + 1, &self));
|
||||
};
|
||||
recipient_bytes[i] = elem;
|
||||
}
|
||||
|
||||
// make sure there are no trailing bytes
|
||||
if seq.next_element::<u8>()?.is_some() {
|
||||
return Err(SerdeError::invalid_length(Recipient::LEN + 1, &self));
|
||||
}
|
||||
|
||||
Recipient::try_from_bytes(recipient_bytes).map_err(|_| {
|
||||
SerdeError::invalid_value(
|
||||
Unexpected::Other("At least one of the curve points was malformed"),
|
||||
&self,
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
deserializer.deserialize_bytes(RecipientVisitor)
|
||||
@@ -281,18 +245,6 @@ impl FromStr for Recipient {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn mock_recipient() -> Recipient {
|
||||
Recipient::try_from_bytes([
|
||||
67, 5, 132, 146, 3, 236, 116, 89, 254, 57, 131, 159, 69, 181, 55, 208, 12, 108, 136,
|
||||
83, 58, 76, 171, 195, 31, 98, 92, 64, 68, 53, 156, 184, 100, 189, 73, 3, 238, 103, 156,
|
||||
108, 124, 199, 42, 79, 172, 98, 81, 177, 182, 100, 167, 164, 74, 183, 199, 213, 162,
|
||||
173, 102, 112, 30, 159, 148, 66, 44, 75, 230, 182, 138, 114, 170, 163, 209, 82, 204,
|
||||
100, 118, 91, 57, 150, 212, 147, 151, 135, 148, 16, 213, 223, 182, 164, 242, 37, 40,
|
||||
73, 137, 228,
|
||||
])
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn string_conversion_works() {
|
||||
let mut rng = rand::thread_rng();
|
||||
@@ -356,40 +308,4 @@ mod tests {
|
||||
recovered_recipient.gateway.to_bytes()
|
||||
);
|
||||
}
|
||||
|
||||
// calls `visit_bytes`
|
||||
#[test]
|
||||
fn bincode_serialisation_works() {
|
||||
let recipient = mock_recipient();
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq)]
|
||||
struct MyStruct {
|
||||
recipient: Recipient,
|
||||
}
|
||||
let a = MyStruct { recipient };
|
||||
let s = bincode::serialize(&a).unwrap();
|
||||
|
||||
let b = bincode::deserialize(&s).unwrap();
|
||||
|
||||
assert_eq!(a, b);
|
||||
}
|
||||
|
||||
// calls `visit_seq`
|
||||
#[test]
|
||||
fn json_serialisation_works() {
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
let recipient = mock_recipient();
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq)]
|
||||
struct MyStruct {
|
||||
recipient: Recipient,
|
||||
}
|
||||
let a = MyStruct { recipient };
|
||||
let s = serde_json::to_string(&a).unwrap();
|
||||
|
||||
let b = serde_json::from_str(&s).unwrap();
|
||||
|
||||
assert_eq!(a, b);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -180,7 +180,6 @@ impl NymPacket {
|
||||
}
|
||||
|
||||
#[cfg(feature = "sphinx")]
|
||||
#[allow(unreachable_patterns)]
|
||||
pub fn sphinx_packet_ref(&self) -> Option<&SphinxPacket> {
|
||||
match self {
|
||||
NymPacket::Sphinx(packet) => Some(packet),
|
||||
@@ -189,7 +188,6 @@ impl NymPacket {
|
||||
}
|
||||
|
||||
#[cfg(feature = "sphinx")]
|
||||
#[allow(unreachable_patterns)]
|
||||
pub fn to_sphinx_packet(self) -> Option<SphinxPacket> {
|
||||
match self {
|
||||
NymPacket::Sphinx(packet) => Some(packet),
|
||||
|
||||
@@ -7,7 +7,6 @@ homepage.workspace = true
|
||||
documentation.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
@@ -37,6 +36,5 @@ url.workspace = true
|
||||
|
||||
|
||||
[build-dependencies]
|
||||
anyhow = { workspace = true }
|
||||
sqlx = { workspace = true, features = ["runtime-tokio-rustls", "sqlite", "macros", "migrate"] }
|
||||
tokio = { workspace = true, features = ["rt-multi-thread", "macros"] }
|
||||
|
||||
@@ -1,30 +1,22 @@
|
||||
// Copyright 2023 - Nym Technologies SA <contact@nymtech.net>
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
use anyhow::Context;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
async fn main() {
|
||||
use sqlx::{Connection, SqliteConnection};
|
||||
use std::env;
|
||||
|
||||
let out_dir = env::var("OUT_DIR")?;
|
||||
let out_dir = env::var("OUT_DIR").unwrap();
|
||||
let database_path = format!("{out_dir}/scraper-example.sqlite");
|
||||
|
||||
// remove the db file if it already existed from previous build
|
||||
// in case it was from a different branch
|
||||
if std::fs::exists(&database_path)? {
|
||||
std::fs::remove_file(&database_path)?;
|
||||
}
|
||||
|
||||
let mut conn = SqliteConnection::connect(&format!("sqlite://{database_path}?mode=rwc"))
|
||||
.await
|
||||
.context("Failed to create SQLx database connection")?;
|
||||
.expect("Failed to create SQLx database connection");
|
||||
|
||||
sqlx::migrate!("./sql_migrations")
|
||||
.run(&mut conn)
|
||||
.await
|
||||
.context("Failed to perform SQLx migrations")?;
|
||||
.expect("Failed to perform SQLx migrations");
|
||||
|
||||
#[cfg(target_family = "unix")]
|
||||
println!("cargo:rustc-env=DATABASE_URL=sqlite://{}", &database_path);
|
||||
@@ -33,6 +25,4 @@ async fn main() -> anyhow::Result<()> {
|
||||
// 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);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -25,5 +25,3 @@ url = { workspace = true }
|
||||
nym-crypto = { path = "../crypto", features = ["asymmetric"] }
|
||||
nym-task = { path = "../task" }
|
||||
nym-validator-client = { path = "../client-libs/validator-client" }
|
||||
nym-http-api-client = { path = "../http-api-client" }
|
||||
nym-api-requests = { path = "../../nym-api/nym-api-requests" }
|
||||
|
||||
@@ -10,7 +10,7 @@ use futures::StreamExt;
|
||||
use nym_crypto::asymmetric::ed25519;
|
||||
use nym_task::ShutdownToken;
|
||||
use nym_validator_client::models::NymNodeDescription;
|
||||
use nym_validator_client::nym_api::NymApiClientExt;
|
||||
use nym_validator_client::NymApiClient;
|
||||
use rand::prelude::SliceRandom;
|
||||
use rand::thread_rng;
|
||||
use std::net::SocketAddr;
|
||||
@@ -135,15 +135,10 @@ impl VerlocMeasurer {
|
||||
let mut api_endpoints = self.config.nym_api_urls.clone();
|
||||
api_endpoints.shuffle(&mut thread_rng());
|
||||
for api_endpoint in api_endpoints {
|
||||
let client = match nym_http_api_client::Client::builder(api_endpoint.clone())
|
||||
.and_then(|b| b.with_user_agent(self.config.user_agent.clone()).build())
|
||||
{
|
||||
Ok(c) => c,
|
||||
Err(err) => {
|
||||
warn!("failed to create client for {api_endpoint}: {err}");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let client = NymApiClient::new_with_user_agent(
|
||||
api_endpoint.clone(),
|
||||
self.config.user_agent.clone(),
|
||||
);
|
||||
match client.get_all_described_nodes().await {
|
||||
Ok(res) => return Some(res),
|
||||
Err(err) => {
|
||||
|
||||
@@ -34,7 +34,6 @@ nym-statistics-common = { path = "../../statistics" }
|
||||
nym-task = { path = "../../task" }
|
||||
nym-topology = { path = "../../topology", features = ["wasm-serde-types"] }
|
||||
nym-validator-client = { path = "../../client-libs/validator-client", default-features = false }
|
||||
nym-http-api-client = { path = "../../http-api-client" }
|
||||
wasm-utils = { path = "../utils" }
|
||||
wasm-storage = { path = "../storage" }
|
||||
|
||||
|
||||
@@ -37,12 +37,6 @@ pub enum WasmCoreError {
|
||||
source: ValidatorClientError,
|
||||
},
|
||||
|
||||
#[error("failed to query nym api: {source}")]
|
||||
NymApiQueryError {
|
||||
#[from]
|
||||
source: nym_validator_client::nym_api::error::NymAPIError,
|
||||
},
|
||||
|
||||
#[error("The provided wasm topology was invalid: {source}")]
|
||||
WasmTopologyError {
|
||||
#[from]
|
||||
|
||||
@@ -19,9 +19,9 @@ use nym_client_core::init::{
|
||||
use nym_sphinx::addressing::clients::Recipient;
|
||||
use nym_sphinx::anonymous_replies::requests::AnonymousSenderTag;
|
||||
use nym_topology::wasm_helpers::WasmFriendlyNymTopology;
|
||||
use nym_topology::{EpochRewardedSet, NymTopology, RoutingNode};
|
||||
use nym_topology::{NymTopology, RoutingNode};
|
||||
use nym_validator_client::client::IdentityKey;
|
||||
use nym_validator_client::{nym_api::NymApiClientExt, UserAgent};
|
||||
use nym_validator_client::{NymApiClient, UserAgent};
|
||||
use rand::thread_rng;
|
||||
use url::Url;
|
||||
use wasm_bindgen::prelude::wasm_bindgen;
|
||||
@@ -72,16 +72,7 @@ pub async fn current_network_topology_async(
|
||||
}
|
||||
};
|
||||
|
||||
let api_client = nym_http_api_client::Client::builder(url.clone())
|
||||
.map_err(|_err| WasmCoreError::MalformedUrl {
|
||||
raw: nym_api_url.to_string(),
|
||||
source: url::ParseError::EmptyHost,
|
||||
})?
|
||||
.build()
|
||||
.map_err(|_err| WasmCoreError::MalformedUrl {
|
||||
raw: nym_api_url.to_string(),
|
||||
source: url::ParseError::EmptyHost,
|
||||
})?;
|
||||
let api_client = NymApiClient::new(url);
|
||||
let rewarded_set = api_client.get_current_rewarded_set().await?;
|
||||
let mixnodes_res = api_client
|
||||
.get_all_basic_active_mixing_assigned_nodes_with_metadata()
|
||||
@@ -99,14 +90,9 @@ pub async fn current_network_topology_async(
|
||||
|
||||
let gateways = gateways_res.nodes;
|
||||
|
||||
let epoch_rewarded_set: EpochRewardedSet = rewarded_set.into();
|
||||
let topology = NymTopology::new(
|
||||
metadata.to_topology_metadata(),
|
||||
epoch_rewarded_set,
|
||||
Vec::new(),
|
||||
)
|
||||
.with_skimmed_nodes(&mixnodes)
|
||||
.with_skimmed_nodes(&gateways);
|
||||
let topology = NymTopology::new(metadata.to_topology_metadata(), rewarded_set, Vec::new())
|
||||
.with_skimmed_nodes(&mixnodes)
|
||||
.with_skimmed_nodes(&gateways);
|
||||
|
||||
Ok(topology.into())
|
||||
}
|
||||
|
||||
@@ -21,7 +21,6 @@ pub use nym_client_core::{
|
||||
pub use nym_gateway_client::{
|
||||
error::GatewayClientError, GatewayClient, GatewayClientConfig, GatewayConfig,
|
||||
};
|
||||
pub use nym_http_api_client::Client as ApiClient;
|
||||
pub use nym_sphinx::{
|
||||
addressing::{clients::Recipient, nodes::NodeIdentity},
|
||||
params::PacketType,
|
||||
@@ -30,6 +29,7 @@ pub use nym_sphinx::{
|
||||
pub use nym_statistics_common::clients::ClientStatsSender;
|
||||
pub use nym_task;
|
||||
pub use nym_topology::{HardcodedTopologyProvider, MixLayer, NymTopology, TopologyProvider};
|
||||
pub use nym_validator_client::nym_api::Client as ApiClient;
|
||||
pub use nym_validator_client::{DirectSigningReqwestRpcNyxdClient, QueryReqwestRpcNyxdClient};
|
||||
// TODO: that's a very nasty import path. it should come from contracts instead!
|
||||
pub use nym_validator_client::client::IdentityKey;
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
[package]
|
||||
name = "nym-wireguard-private-metadata-client"
|
||||
version = "1.0.0"
|
||||
authors.workspace = true
|
||||
repository.workspace = true
|
||||
homepage.workspace = true
|
||||
documentation.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
async-trait = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
nym-http-api-client = { path = "../../http-api-client" }
|
||||
nym-wireguard-private-metadata-shared = { path = "../shared" }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -1,53 +0,0 @@
|
||||
// Copyright 2025 - Nym Technologies SA <contact@nymtech.net>
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
use async_trait::async_trait;
|
||||
use tracing::instrument;
|
||||
|
||||
use nym_http_api_client::{ApiClient, Client, HttpClientError, NO_PARAMS};
|
||||
|
||||
use nym_wireguard_private_metadata_shared::{
|
||||
routes, Version, {Request, Response},
|
||||
};
|
||||
|
||||
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
|
||||
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
|
||||
pub trait WireguardMetadataApiClient: ApiClient {
|
||||
#[instrument(level = "debug", skip(self))]
|
||||
async fn version(&self) -> Result<Version, HttpClientError> {
|
||||
let version: u64 = self
|
||||
.get_json(
|
||||
&[routes::V1_API_VERSION, routes::BANDWIDTH, routes::VERSION],
|
||||
NO_PARAMS,
|
||||
)
|
||||
.await?;
|
||||
Ok(version.into())
|
||||
}
|
||||
|
||||
#[instrument(level = "debug", skip(self))]
|
||||
async fn available_bandwidth(
|
||||
&self,
|
||||
request_body: &Request,
|
||||
) -> Result<Response, HttpClientError> {
|
||||
self.post_json(
|
||||
&[routes::V1_API_VERSION, routes::BANDWIDTH, routes::AVAILABLE],
|
||||
NO_PARAMS,
|
||||
request_body,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[instrument(level = "debug", skip(self, request_body))]
|
||||
async fn topup_bandwidth(&self, request_body: &Request) -> Result<Response, HttpClientError> {
|
||||
self.post_json(
|
||||
&[routes::V1_API_VERSION, routes::BANDWIDTH, routes::TOPUP],
|
||||
NO_PARAMS,
|
||||
request_body,
|
||||
)
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
|
||||
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
|
||||
impl WireguardMetadataApiClient for Client {}
|
||||
@@ -1,43 +0,0 @@
|
||||
[package]
|
||||
name = "nym-wireguard-private-metadata-server"
|
||||
version = "1.0.0"
|
||||
authors.workspace = true
|
||||
repository.workspace = true
|
||||
homepage.workspace = true
|
||||
documentation.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
anyhow = { workspace = true }
|
||||
axum = { workspace = true, features = ["tokio", "macros"] }
|
||||
futures = { workspace = true }
|
||||
tokio = { workspace = true, features = ["rt-multi-thread", "net", "io-util"] }
|
||||
tokio-util = { workspace = true }
|
||||
tower-http = { workspace = true, features = [
|
||||
"cors",
|
||||
"trace",
|
||||
"compression-br",
|
||||
"compression-deflate",
|
||||
"compression-gzip",
|
||||
"compression-zstd",
|
||||
] }
|
||||
utoipa = { workspace = true, features = ["axum_extras", "time"] }
|
||||
utoipa-swagger-ui = { workspace = true, features = ["axum"] }
|
||||
|
||||
nym-credentials-interface = { path = "../../credentials-interface" }
|
||||
nym-credential-verification = { path = "../../credential-verification" }
|
||||
nym-http-api-common = { path = "../../http-api-common", features = [
|
||||
"middleware",
|
||||
"utoipa",
|
||||
"output",
|
||||
] }
|
||||
nym-wireguard = { path = "../../wireguard" }
|
||||
nym-wireguard-private-metadata-shared = { path = "../shared" }
|
||||
|
||||
[dev-dependencies]
|
||||
async-trait = { workspace = true }
|
||||
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -1,46 +0,0 @@
|
||||
// Copyright 2025 - Nym Technologies SA <contact@nymtech.net>
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use tokio::task::JoinHandle;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use nym_wireguard::WgApiWrapper;
|
||||
|
||||
pub(crate) mod openapi;
|
||||
pub(crate) mod router;
|
||||
pub(crate) mod state;
|
||||
|
||||
/// Shutdown goes 2 directions:
|
||||
/// 1. signal background tasks to gracefully finish
|
||||
/// 2. signal server itself
|
||||
///
|
||||
/// These are done through separate shutdown handles. Of course, shut down server
|
||||
/// AFTER you have shut down BG tasks (or past their grace period).
|
||||
#[allow(unused)]
|
||||
pub struct ShutdownHandles {
|
||||
axum_shutdown_button: CancellationToken,
|
||||
/// Tokio JoinHandle for axum server's task
|
||||
axum_join_handle: AxumJoinHandle,
|
||||
/// Wireguard API for kernel interactions
|
||||
wg_api: Arc<WgApiWrapper>,
|
||||
}
|
||||
|
||||
impl ShutdownHandles {
|
||||
/// Cancellation token is given to Axum server constructor. When the token
|
||||
/// receives a shutdown signal, Axum server will shut down gracefully.
|
||||
pub fn new(
|
||||
axum_join_handle: AxumJoinHandle,
|
||||
wg_api: Arc<WgApiWrapper>,
|
||||
axum_shutdown_button: CancellationToken,
|
||||
) -> Self {
|
||||
Self {
|
||||
axum_shutdown_button,
|
||||
axum_join_handle,
|
||||
wg_api,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type AxumJoinHandle = JoinHandle<std::io::Result<()>>;
|
||||
@@ -1,14 +0,0 @@
|
||||
// Copyright 2025 - Nym Technologies SA <contact@nymtech.net>
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
use utoipa::OpenApi;
|
||||
|
||||
use nym_wireguard_private_metadata_shared::{Request, Response};
|
||||
|
||||
#[derive(OpenApi)]
|
||||
#[openapi(
|
||||
info(title = "Nym Wireguard Private Metadata"),
|
||||
tags(),
|
||||
components(schemas(Request, Response))
|
||||
)]
|
||||
pub(crate) struct ApiDoc;
|
||||
@@ -1,101 +0,0 @@
|
||||
// Copyright 2025 - Nym Technologies SA <contact@nymtech.net>
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
use anyhow::anyhow;
|
||||
use axum::response::Redirect;
|
||||
use axum::routing::get;
|
||||
use axum::Router;
|
||||
use core::net::SocketAddr;
|
||||
use nym_http_api_common::middleware::logging::log_request_info;
|
||||
use tokio::net::TcpListener;
|
||||
use tokio_util::sync::WaitForCancellationFutureOwned;
|
||||
use tower_http::cors::CorsLayer;
|
||||
use utoipa::OpenApi;
|
||||
use utoipa_swagger_ui::SwaggerUi;
|
||||
|
||||
use crate::http::openapi::ApiDoc;
|
||||
use crate::http::state::AppState;
|
||||
use crate::network::bandwidth_routes;
|
||||
|
||||
/// Wrapper around `axum::Router` which ensures correct [order of layers][order].
|
||||
/// Add new routes as if you were working directly with `axum`.
|
||||
///
|
||||
/// Why? Middleware like logger, CORS, TLS which need to handle request before other
|
||||
/// layers should be added last. Using this builder pattern ensures that.
|
||||
///
|
||||
/// [order]: https://docs.rs/axum/latest/axum/middleware/index.html#ordering
|
||||
pub struct RouterBuilder {
|
||||
unfinished_router: Router<AppState>,
|
||||
}
|
||||
|
||||
impl RouterBuilder {
|
||||
/// All routes should be, if possible, added here. Exceptions are e.g.
|
||||
/// routes which are added conditionally in other places based on some `if`.
|
||||
pub fn with_default_routes() -> Self {
|
||||
let default_routes = Router::new()
|
||||
.merge(SwaggerUi::new("/swagger").url("/api-docs/openapi.json", ApiDoc::openapi()))
|
||||
.route("/", get(|| async { Redirect::to("/swagger") }))
|
||||
.nest("/v1", Router::new().nest("/bandwidth", bandwidth_routes()));
|
||||
Self {
|
||||
unfinished_router: default_routes,
|
||||
}
|
||||
}
|
||||
|
||||
/// Invoke this as late as possible before constructing HTTP server
|
||||
/// (after all routes were added).
|
||||
pub fn with_state(self, state: AppState) -> RouterWithState {
|
||||
RouterWithState {
|
||||
router: self.finalize_routes().with_state(state),
|
||||
}
|
||||
}
|
||||
|
||||
/// Middleware added here intercepts the request before it gets to other routes.
|
||||
fn finalize_routes(self) -> Router<AppState> {
|
||||
self.unfinished_router
|
||||
.layer(setup_cors())
|
||||
.layer(axum::middleware::from_fn(log_request_info))
|
||||
}
|
||||
}
|
||||
|
||||
fn setup_cors() -> CorsLayer {
|
||||
CorsLayer::new()
|
||||
.allow_origin(tower_http::cors::Any)
|
||||
.allow_methods([axum::http::Method::GET, axum::http::Method::POST])
|
||||
.allow_headers(tower_http::cors::Any)
|
||||
.allow_credentials(false)
|
||||
}
|
||||
|
||||
pub struct RouterWithState {
|
||||
pub router: Router,
|
||||
}
|
||||
|
||||
impl RouterWithState {
|
||||
pub async fn build_server(self, bind_address: &SocketAddr) -> anyhow::Result<ApiHttpServer> {
|
||||
let listener = tokio::net::TcpListener::bind(bind_address)
|
||||
.await
|
||||
.map_err(|err| anyhow!("Couldn't bind to address {} due to {}", bind_address, err))?;
|
||||
|
||||
Ok(ApiHttpServer {
|
||||
router: self.router,
|
||||
listener,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ApiHttpServer {
|
||||
router: Router,
|
||||
listener: TcpListener,
|
||||
}
|
||||
|
||||
impl ApiHttpServer {
|
||||
pub async fn run(self, receiver: WaitForCancellationFutureOwned) -> Result<(), std::io::Error> {
|
||||
// into_make_service_with_connect_info allows us to see client ip address
|
||||
axum::serve(
|
||||
self.listener,
|
||||
self.router
|
||||
.into_make_service_with_connect_info::<SocketAddr>(),
|
||||
)
|
||||
.with_graceful_shutdown(receiver)
|
||||
.await
|
||||
}
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
// Copyright 2025 - Nym Technologies SA <contact@nymtech.net>
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
use std::net::IpAddr;
|
||||
|
||||
use nym_credentials_interface::CredentialSpendingData;
|
||||
|
||||
use crate::transceiver::PeerControllerTransceiver;
|
||||
use nym_wireguard_private_metadata_shared::error::MetadataError;
|
||||
|
||||
#[derive(Clone, axum::extract::FromRef)]
|
||||
pub struct AppState {
|
||||
transceiver: PeerControllerTransceiver,
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
pub fn new(transceiver: PeerControllerTransceiver) -> Self {
|
||||
Self { transceiver }
|
||||
}
|
||||
|
||||
pub async fn available_bandwidth(&self, ip: IpAddr) -> Result<i64, MetadataError> {
|
||||
self.transceiver.query_bandwidth(ip).await
|
||||
}
|
||||
|
||||
// Top up with a credential and return the afterwards available bandwidth
|
||||
pub async fn topup_bandwidth(
|
||||
&self,
|
||||
ip: IpAddr,
|
||||
credential: CredentialSpendingData,
|
||||
) -> Result<i64, MetadataError> {
|
||||
self.transceiver
|
||||
.topup_bandwidth(ip, Box::new(credential))
|
||||
.await
|
||||
}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
// Copyright 2025 - Nym Technologies SA <contact@nymtech.net>
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
mod http;
|
||||
mod network;
|
||||
mod transceiver;
|
||||
|
||||
pub use http::{
|
||||
router::{ApiHttpServer, RouterBuilder, RouterWithState},
|
||||
state::AppState,
|
||||
ShutdownHandles,
|
||||
};
|
||||
pub use transceiver::PeerControllerTransceiver;
|
||||
@@ -1,111 +0,0 @@
|
||||
// Copyright 2025 - Nym Technologies SA <contact@nymtech.net>
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
use std::net::SocketAddr;
|
||||
|
||||
use axum::{
|
||||
extract::{ConnectInfo, Query, State},
|
||||
Json, Router,
|
||||
};
|
||||
use nym_http_api_common::{FormattedResponse, OutputParams};
|
||||
use nym_wireguard_private_metadata_shared::{
|
||||
interface::{RequestData, ResponseData},
|
||||
latest, AxumErrorResponse, AxumResult, Construct, Extract, Request, Response,
|
||||
};
|
||||
use tower_http::compression::CompressionLayer;
|
||||
|
||||
use crate::http::state::AppState;
|
||||
|
||||
pub(crate) fn bandwidth_routes() -> Router<AppState> {
|
||||
Router::new()
|
||||
.route("/version", axum::routing::get(version))
|
||||
.route("/available", axum::routing::post(available_bandwidth))
|
||||
.route("/topup", axum::routing::post(topup_bandwidth))
|
||||
.layer(CompressionLayer::new())
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
tag = "bandwidth",
|
||||
get,
|
||||
path = "/v1/bandwidth/version",
|
||||
responses(
|
||||
(status = 200, content(
|
||||
(Response = "application/bincode")
|
||||
))
|
||||
),
|
||||
)]
|
||||
async fn version(Query(output): Query<OutputParams>) -> AxumResult<FormattedResponse<u64>> {
|
||||
let output = output.output.unwrap_or_default();
|
||||
Ok(output.to_response(latest::VERSION.into()))
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
tag = "bandwidth",
|
||||
post,
|
||||
request_body = Request,
|
||||
path = "/v1/bandwidth/available",
|
||||
responses(
|
||||
(status = 200, content(
|
||||
(Response = "application/bincode")
|
||||
))
|
||||
),
|
||||
)]
|
||||
async fn available_bandwidth(
|
||||
ConnectInfo(addr): ConnectInfo<SocketAddr>,
|
||||
Query(output): Query<OutputParams>,
|
||||
State(state): State<AppState>,
|
||||
Json(request): Json<Request>,
|
||||
) -> AxumResult<FormattedResponse<Response>> {
|
||||
let output = output.output.unwrap_or_default();
|
||||
|
||||
let (RequestData::AvailableBandwidth(_), version) =
|
||||
request.extract().map_err(AxumErrorResponse::bad_request)?
|
||||
else {
|
||||
return Err(AxumErrorResponse::bad_request("incorrect request type"));
|
||||
};
|
||||
let available_bandwidth = state
|
||||
.available_bandwidth(addr.ip())
|
||||
.await
|
||||
.map_err(AxumErrorResponse::bad_request)?;
|
||||
let response = Response::construct(
|
||||
ResponseData::AvailableBandwidth(available_bandwidth),
|
||||
version,
|
||||
)
|
||||
.map_err(AxumErrorResponse::bad_request)?;
|
||||
|
||||
Ok(output.to_response(response))
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
tag = "bandwidth",
|
||||
post,
|
||||
request_body = Request,
|
||||
path = "/v1/bandwidth/topup",
|
||||
responses(
|
||||
(status = 200, content(
|
||||
(Response = "application/bincode")
|
||||
))
|
||||
),
|
||||
)]
|
||||
async fn topup_bandwidth(
|
||||
ConnectInfo(addr): ConnectInfo<SocketAddr>,
|
||||
Query(output): Query<OutputParams>,
|
||||
State(state): State<AppState>,
|
||||
Json(request): Json<Request>,
|
||||
) -> AxumResult<FormattedResponse<Response>> {
|
||||
let output = output.output.unwrap_or_default();
|
||||
|
||||
let (RequestData::TopUpBandwidth(credential), version) =
|
||||
request.extract().map_err(AxumErrorResponse::bad_request)?
|
||||
else {
|
||||
return Err(AxumErrorResponse::bad_request("incorrect request type"));
|
||||
};
|
||||
let available_bandwidth = state
|
||||
.topup_bandwidth(addr.ip(), *credential)
|
||||
.await
|
||||
.map_err(AxumErrorResponse::bad_request)?;
|
||||
let response = Response::construct(ResponseData::TopUpBandwidth(available_bandwidth), version)
|
||||
.map_err(AxumErrorResponse::bad_request)?;
|
||||
|
||||
Ok(output.to_response(response))
|
||||
}
|
||||
@@ -1,307 +0,0 @@
|
||||
// Copyright 2025 - Nym Technologies SA <contact@nymtech.net>
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
use std::net::IpAddr;
|
||||
|
||||
use futures::channel::oneshot;
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
use nym_credential_verification::ClientBandwidth;
|
||||
use nym_credentials_interface::CredentialSpendingData;
|
||||
use nym_wireguard::peer_controller::PeerControlRequest;
|
||||
use nym_wireguard_private_metadata_shared::error::MetadataError;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct PeerControllerTransceiver {
|
||||
request_tx: mpsc::Sender<PeerControlRequest>,
|
||||
}
|
||||
|
||||
impl PeerControllerTransceiver {
|
||||
pub fn new(request_tx: mpsc::Sender<PeerControlRequest>) -> Self {
|
||||
Self { request_tx }
|
||||
}
|
||||
|
||||
async fn get_client_bandwidth(&self, ip: IpAddr) -> Result<ClientBandwidth, MetadataError> {
|
||||
let (response_tx, response_rx) = oneshot::channel();
|
||||
let msg = PeerControlRequest::GetClientBandwidthByIp { ip, response_tx };
|
||||
self.request_tx
|
||||
.send(msg)
|
||||
.await
|
||||
.map_err(|_| MetadataError::PeerInteractionStopped)?;
|
||||
|
||||
response_rx
|
||||
.await
|
||||
.map_err(|_| MetadataError::NoResponse)?
|
||||
.map_err(|err| MetadataError::Unsuccessful {
|
||||
reason: err.to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) async fn query_bandwidth(&self, ip: IpAddr) -> Result<i64, MetadataError> {
|
||||
Ok(self.get_client_bandwidth(ip).await?.available().await)
|
||||
}
|
||||
|
||||
// Top up with a credential and return the afterwards available bandwidth
|
||||
pub(crate) async fn topup_bandwidth(
|
||||
&self,
|
||||
ip: IpAddr,
|
||||
credential: Box<CredentialSpendingData>,
|
||||
) -> Result<i64, MetadataError> {
|
||||
let (response_tx, response_rx) = oneshot::channel();
|
||||
let msg = PeerControlRequest::GetVerifierByIp {
|
||||
ip,
|
||||
credential,
|
||||
response_tx,
|
||||
};
|
||||
self.request_tx
|
||||
.send(msg)
|
||||
.await
|
||||
.map_err(|_| MetadataError::PeerInteractionStopped)?;
|
||||
|
||||
let mut verifier = response_rx
|
||||
.await
|
||||
.map_err(|_| MetadataError::NoResponse)?
|
||||
.map_err(|err| MetadataError::Unsuccessful {
|
||||
reason: err.to_string(),
|
||||
})?;
|
||||
let available_bandwidth =
|
||||
verifier
|
||||
.verify()
|
||||
.await
|
||||
.map_err(|err| MetadataError::CredentialVerification {
|
||||
message: err.to_string(),
|
||||
})?;
|
||||
|
||||
Ok(available_bandwidth)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests {
|
||||
use nym_credential_verification::TicketVerifier;
|
||||
use nym_wireguard::CONTROL_CHANNEL_SIZE;
|
||||
|
||||
use super::*;
|
||||
|
||||
pub(crate) const CREDENTIAL_BYTES: [u8; 1245] = [
|
||||
0, 0, 4, 133, 96, 179, 223, 185, 136, 23, 213, 166, 59, 203, 66, 69, 209, 181, 227, 254,
|
||||
16, 102, 98, 237, 59, 119, 170, 111, 31, 194, 51, 59, 120, 17, 115, 229, 79, 91, 11, 139,
|
||||
154, 2, 212, 23, 68, 70, 167, 3, 240, 54, 224, 171, 221, 1, 69, 48, 60, 118, 119, 249, 123,
|
||||
35, 172, 227, 131, 96, 232, 209, 187, 123, 4, 197, 102, 90, 96, 45, 125, 135, 140, 99, 1,
|
||||
151, 17, 131, 143, 157, 97, 107, 139, 232, 212, 87, 14, 115, 253, 255, 166, 167, 186, 43,
|
||||
90, 96, 173, 105, 120, 40, 10, 163, 250, 224, 214, 200, 178, 4, 160, 16, 130, 59, 76, 193,
|
||||
39, 240, 3, 101, 141, 209, 183, 226, 186, 207, 56, 210, 187, 7, 164, 240, 164, 205, 37, 81,
|
||||
184, 214, 193, 195, 90, 205, 238, 225, 195, 104, 12, 123, 203, 57, 233, 243, 215, 145, 195,
|
||||
196, 57, 38, 125, 172, 18, 47, 63, 165, 110, 219, 180, 40, 58, 116, 92, 254, 160, 98, 48,
|
||||
92, 254, 232, 107, 184, 80, 234, 60, 160, 235, 249, 76, 41, 38, 165, 28, 40, 136, 74, 48,
|
||||
166, 50, 245, 23, 201, 140, 101, 79, 93, 235, 128, 186, 146, 126, 180, 134, 43, 13, 186,
|
||||
19, 195, 48, 168, 201, 29, 216, 95, 176, 198, 132, 188, 64, 39, 212, 150, 32, 52, 53, 38,
|
||||
228, 199, 122, 226, 217, 75, 40, 191, 151, 48, 164, 242, 177, 79, 14, 122, 105, 151, 85,
|
||||
88, 199, 162, 17, 96, 103, 83, 178, 128, 9, 24, 30, 74, 108, 241, 85, 240, 166, 97, 241,
|
||||
85, 199, 11, 198, 226, 234, 70, 107, 145, 28, 208, 114, 51, 12, 234, 108, 101, 202, 112,
|
||||
48, 185, 22, 159, 67, 109, 49, 27, 149, 90, 109, 32, 226, 112, 7, 201, 208, 209, 104, 31,
|
||||
97, 134, 204, 145, 27, 181, 206, 181, 106, 32, 110, 136, 115, 249, 201, 111, 5, 245, 203,
|
||||
71, 121, 169, 126, 151, 178, 236, 59, 221, 195, 48, 135, 115, 6, 50, 227, 74, 97, 107, 107,
|
||||
213, 90, 2, 203, 154, 138, 47, 128, 52, 134, 128, 224, 51, 65, 240, 90, 8, 55, 175, 180,
|
||||
178, 204, 206, 168, 110, 51, 57, 189, 169, 48, 169, 136, 121, 99, 51, 170, 178, 214, 74, 1,
|
||||
96, 151, 167, 25, 173, 180, 171, 155, 10, 55, 142, 234, 190, 113, 90, 79, 80, 244, 71, 166,
|
||||
30, 235, 113, 150, 133, 1, 218, 17, 109, 111, 223, 24, 216, 177, 41, 2, 204, 65, 221, 212,
|
||||
207, 236, 144, 6, 65, 224, 55, 42, 1, 1, 161, 134, 118, 127, 111, 220, 110, 127, 240, 71,
|
||||
223, 129, 12, 93, 20, 220, 60, 56, 71, 146, 184, 95, 132, 69, 28, 56, 53, 192, 213, 22,
|
||||
119, 230, 152, 225, 182, 188, 163, 219, 37, 175, 247, 73, 14, 247, 38, 72, 243, 1, 48, 131,
|
||||
59, 8, 13, 96, 143, 185, 127, 241, 161, 217, 24, 149, 193, 40, 16, 30, 202, 151, 28, 119,
|
||||
240, 153, 101, 156, 61, 193, 72, 245, 199, 181, 12, 231, 65, 166, 67, 142, 121, 207, 202,
|
||||
58, 197, 113, 188, 248, 42, 124, 105, 48, 161, 241, 55, 209, 36, 194, 27, 63, 233, 144,
|
||||
189, 85, 117, 234, 9, 139, 46, 31, 206, 114, 95, 131, 29, 240, 13, 81, 142, 140, 133, 33,
|
||||
30, 41, 141, 37, 80, 217, 95, 221, 76, 115, 86, 201, 165, 51, 252, 9, 28, 209, 1, 48, 150,
|
||||
74, 248, 212, 187, 222, 66, 210, 3, 200, 19, 217, 171, 184, 42, 148, 53, 150, 57, 50, 6,
|
||||
227, 227, 62, 49, 42, 148, 148, 157, 82, 191, 58, 24, 34, 56, 98, 120, 89, 105, 176, 85,
|
||||
15, 253, 241, 41, 153, 195, 136, 1, 48, 142, 126, 213, 101, 223, 79, 133, 230, 105, 38,
|
||||
161, 149, 2, 21, 136, 150, 42, 72, 218, 85, 146, 63, 223, 58, 108, 186, 183, 248, 62, 20,
|
||||
47, 34, 113, 160, 177, 204, 181, 16, 24, 212, 224, 35, 84, 51, 168, 56, 136, 11, 1, 48,
|
||||
135, 242, 62, 149, 230, 178, 32, 224, 119, 26, 234, 163, 237, 224, 114, 95, 112, 140, 170,
|
||||
150, 96, 125, 136, 221, 180, 78, 18, 11, 12, 184, 2, 198, 217, 119, 43, 69, 4, 172, 109,
|
||||
55, 183, 40, 131, 172, 161, 88, 183, 101, 1, 48, 173, 216, 22, 73, 42, 255, 211, 93, 249,
|
||||
87, 159, 115, 61, 91, 55, 130, 17, 216, 60, 34, 122, 55, 8, 244, 244, 153, 151, 57, 5, 144,
|
||||
178, 55, 249, 64, 211, 168, 34, 148, 56, 89, 92, 203, 70, 124, 219, 152, 253, 165, 0, 32,
|
||||
203, 116, 63, 7, 240, 222, 82, 86, 11, 149, 167, 72, 224, 55, 190, 66, 201, 65, 168, 184,
|
||||
96, 47, 194, 241, 168, 124, 7, 74, 214, 250, 37, 76, 32, 218, 69, 122, 103, 215, 145, 169,
|
||||
24, 212, 229, 168, 106, 10, 144, 31, 13, 25, 178, 242, 250, 106, 159, 40, 48, 163, 165, 61,
|
||||
130, 57, 146, 4, 73, 32, 254, 233, 125, 135, 212, 29, 111, 4, 177, 114, 15, 210, 170, 82,
|
||||
108, 110, 62, 166, 81, 209, 106, 176, 156, 14, 133, 242, 60, 127, 120, 242, 28, 97, 0, 1,
|
||||
32, 103, 93, 109, 89, 240, 91, 1, 84, 150, 50, 206, 157, 203, 49, 220, 120, 234, 175, 234,
|
||||
150, 126, 225, 94, 163, 164, 199, 138, 114, 62, 99, 106, 112, 1, 32, 171, 40, 220, 82, 241,
|
||||
203, 76, 146, 111, 139, 182, 179, 237, 182, 115, 75, 128, 201, 107, 43, 214, 0, 135, 217,
|
||||
160, 68, 150, 232, 144, 114, 237, 98, 32, 30, 134, 232, 59, 93, 163, 253, 244, 13, 202, 52,
|
||||
147, 168, 83, 121, 123, 95, 21, 210, 209, 225, 223, 143, 49, 10, 205, 238, 1, 22, 83, 81,
|
||||
70, 1, 32, 26, 76, 6, 234, 160, 50, 139, 102, 161, 232, 155, 106, 130, 171, 226, 210, 233,
|
||||
178, 85, 247, 71, 123, 55, 53, 46, 67, 148, 137, 156, 207, 208, 107, 1, 32, 102, 31, 4, 98,
|
||||
110, 156, 144, 61, 229, 140, 198, 84, 196, 238, 128, 35, 131, 182, 137, 125, 241, 95, 69,
|
||||
131, 170, 27, 2, 144, 75, 72, 242, 102, 3, 32, 121, 80, 45, 173, 56, 65, 218, 27, 40, 251,
|
||||
197, 32, 169, 104, 123, 110, 90, 78, 153, 166, 38, 9, 129, 228, 99, 8, 1, 116, 142, 233,
|
||||
162, 69, 32, 216, 169, 159, 116, 95, 12, 63, 176, 195, 6, 183, 123, 135, 75, 61, 112, 106,
|
||||
83, 235, 176, 41, 27, 248, 48, 71, 165, 170, 12, 92, 103, 103, 81, 32, 58, 74, 75, 145,
|
||||
192, 94, 153, 69, 80, 128, 241, 3, 16, 117, 192, 86, 161, 103, 44, 174, 211, 196, 182, 124,
|
||||
55, 11, 107, 142, 49, 88, 6, 41, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
|
||||
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
|
||||
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 0, 37, 139, 240, 0, 0,
|
||||
0, 0, 0, 0, 0, 1,
|
||||
];
|
||||
|
||||
pub(crate) struct MockVerifier {
|
||||
ret: i64,
|
||||
}
|
||||
|
||||
impl MockVerifier {
|
||||
pub(crate) fn new(ret: i64) -> MockVerifier {
|
||||
Self { ret }
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl TicketVerifier for MockVerifier {
|
||||
async fn verify(&mut self) -> nym_credential_verification::Result<i64> {
|
||||
Ok(self.ret)
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn get_bandwidth() {
|
||||
let (request_tx, mut request_rx) = mpsc::channel(CONTROL_CHANNEL_SIZE);
|
||||
let transceiver = PeerControllerTransceiver::new(request_tx);
|
||||
|
||||
tokio::spawn(async move {
|
||||
match request_rx.recv().await.unwrap() {
|
||||
PeerControlRequest::GetClientBandwidthByIp { ip: _, response_tx } => {
|
||||
response_tx
|
||||
.send(Ok(ClientBandwidth::new(Default::default())))
|
||||
.ok();
|
||||
}
|
||||
_ => panic!("Not expected"),
|
||||
}
|
||||
});
|
||||
|
||||
let bw = transceiver
|
||||
.query_bandwidth("10.0.0.42".parse().unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(bw, 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stop_peer() {
|
||||
let (request_tx, request_rx) = mpsc::channel(CONTROL_CHANNEL_SIZE);
|
||||
let transceiver = PeerControllerTransceiver::new(request_tx);
|
||||
|
||||
drop(request_rx);
|
||||
let err = transceiver
|
||||
.query_bandwidth("10.0.0.42".parse().unwrap())
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(err, MetadataError::PeerInteractionStopped);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unresponsive_peer() {
|
||||
let (request_tx, mut request_rx) = mpsc::channel(CONTROL_CHANNEL_SIZE);
|
||||
let transceiver = PeerControllerTransceiver::new(request_tx);
|
||||
|
||||
tokio::spawn(async move {
|
||||
match request_rx.recv().await.unwrap() {
|
||||
PeerControlRequest::GetClientBandwidthByIp {
|
||||
ip: _,
|
||||
response_tx: _,
|
||||
} => {}
|
||||
_ => panic!("Not expected"),
|
||||
}
|
||||
});
|
||||
|
||||
let err = transceiver
|
||||
.query_bandwidth("10.0.0.42".parse().unwrap())
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(err, MetadataError::NoResponse);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unsuccessful_query_bandwidth() {
|
||||
let (request_tx, mut request_rx) = mpsc::channel(CONTROL_CHANNEL_SIZE);
|
||||
let transceiver = PeerControllerTransceiver::new(request_tx);
|
||||
|
||||
tokio::spawn(async move {
|
||||
match request_rx.recv().await.unwrap() {
|
||||
PeerControlRequest::GetClientBandwidthByIp { ip: _, response_tx } => {
|
||||
response_tx
|
||||
.send(Err(nym_wireguard::error::Error::Internal(
|
||||
"testing".to_owned(),
|
||||
)))
|
||||
.ok();
|
||||
}
|
||||
_ => panic!("Not expected"),
|
||||
}
|
||||
});
|
||||
|
||||
let ret = transceiver
|
||||
.query_bandwidth("10.0.0.42".parse().unwrap())
|
||||
.await;
|
||||
assert!(ret.is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn topup() {
|
||||
let (request_tx, mut request_rx) = mpsc::channel(CONTROL_CHANNEL_SIZE);
|
||||
let transceiver = PeerControllerTransceiver::new(request_tx);
|
||||
let credential = CredentialSpendingData::try_from_bytes(&CREDENTIAL_BYTES).unwrap();
|
||||
let verifier_bw = 42;
|
||||
|
||||
tokio::spawn(async move {
|
||||
match request_rx.recv().await.unwrap() {
|
||||
PeerControlRequest::GetVerifierByIp {
|
||||
ip: _,
|
||||
credential: _,
|
||||
response_tx,
|
||||
} => {
|
||||
response_tx
|
||||
.send(Ok(Box::new(MockVerifier::new(verifier_bw))))
|
||||
.ok();
|
||||
}
|
||||
_ => panic!("Not expected"),
|
||||
}
|
||||
});
|
||||
|
||||
let bw = transceiver
|
||||
.topup_bandwidth("10.0.0.42".parse().unwrap(), Box::new(credential))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(bw, verifier_bw);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unsuccessful_topup() {
|
||||
let (request_tx, mut request_rx) = mpsc::channel(CONTROL_CHANNEL_SIZE);
|
||||
let transceiver = PeerControllerTransceiver::new(request_tx);
|
||||
let credential = CredentialSpendingData::try_from_bytes(&CREDENTIAL_BYTES).unwrap();
|
||||
|
||||
tokio::spawn(async move {
|
||||
match request_rx.recv().await.unwrap() {
|
||||
PeerControlRequest::GetVerifierByIp {
|
||||
ip: _,
|
||||
credential: _,
|
||||
response_tx,
|
||||
} => {
|
||||
response_tx
|
||||
.send(Err(nym_wireguard::error::Error::Internal(
|
||||
"testing".to_owned(),
|
||||
)))
|
||||
.ok();
|
||||
}
|
||||
_ => panic!("Not expected"),
|
||||
}
|
||||
});
|
||||
|
||||
let ret = transceiver
|
||||
.topup_bandwidth("10.0.0.42".parse().unwrap(), Box::new(credential))
|
||||
.await;
|
||||
assert!(ret.is_err());
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
[package]
|
||||
name = "nym-wireguard-private-metadata-shared"
|
||||
version = "1.0.0"
|
||||
authors.workspace = true
|
||||
repository.workspace = true
|
||||
homepage.workspace = true
|
||||
documentation.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
axum = { workspace = true }
|
||||
bincode = { workspace = true }
|
||||
schemars = { workspace = true, features = ["preserve_order"] }
|
||||
serde = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
utoipa = { workspace = true }
|
||||
|
||||
nym-credentials-interface = { path = "../../credentials-interface" }
|
||||
|
||||
[features]
|
||||
testing = []
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -1,28 +0,0 @@
|
||||
// Copyright 2025 - Nym Technologies SA <contact@nymtech.net>
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum MetadataError {
|
||||
#[error("peers can't be interacted with anymore")]
|
||||
PeerInteractionStopped,
|
||||
|
||||
#[error("no response received")]
|
||||
NoResponse,
|
||||
|
||||
#[error("query was not successful: {reason}")]
|
||||
Unsuccessful { reason: String },
|
||||
|
||||
#[error("Models error: {message}")]
|
||||
Models { message: String },
|
||||
|
||||
#[error("Credential verification error: {message}")]
|
||||
CredentialVerification { message: String },
|
||||
}
|
||||
|
||||
impl From<crate::models::error::Error> for MetadataError {
|
||||
fn from(value: crate::models::error::Error) -> Self {
|
||||
Self::Models {
|
||||
message: value.to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
// Copyright 2025 - Nym Technologies SA <contact@nymtech.net>
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
pub mod error;
|
||||
mod models;
|
||||
pub mod routes;
|
||||
|
||||
#[cfg(feature = "testing")]
|
||||
pub use models::v0;
|
||||
pub use models::{
|
||||
error::Error as ModelError, interface, latest, v1, AxumErrorResponse, AxumResult, Construct,
|
||||
ErrorResponse, Extract, Request, Response, Version,
|
||||
};
|
||||
|
||||
fn make_bincode_serializer() -> impl bincode::Options {
|
||||
use bincode::Options;
|
||||
bincode::DefaultOptions::new()
|
||||
.with_big_endian()
|
||||
.with_varint_encoding()
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
// Copyright 2025 - Nym Technologies SA <contact@nymtech.net>
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
use crate::models::Version;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum Error {
|
||||
#[error(transparent)]
|
||||
Bincode(#[from] bincode::Error),
|
||||
|
||||
#[error("trying to deserialize from version {source_version:?} into {target_version:?}")]
|
||||
InvalidVersion {
|
||||
source_version: Version,
|
||||
target_version: Version,
|
||||
},
|
||||
|
||||
#[error(
|
||||
"trying to deserialize from query type {source_query_type} query type {target_query_type}"
|
||||
)]
|
||||
InvalidQueryType {
|
||||
source_query_type: String,
|
||||
target_query_type: String,
|
||||
},
|
||||
|
||||
#[error("update not possible from {from:?} to {to:?}")]
|
||||
UpdateNotPossible { from: Version, to: Version },
|
||||
|
||||
#[error("downgrade not possible from {from:?} to {to:?}")]
|
||||
DowngradeNotPossible { from: Version, to: Version },
|
||||
}
|
||||
@@ -1,145 +0,0 @@
|
||||
// Copyright 2025 - Nym Technologies SA <contact@nymtech.net>
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
use nym_credentials_interface::CredentialSpendingData;
|
||||
|
||||
#[cfg(feature = "testing")]
|
||||
use crate::models::v0;
|
||||
use crate::models::{v1, Construct, Extract, Request, Response, Version};
|
||||
|
||||
pub enum RequestData {
|
||||
AvailableBandwidth(()),
|
||||
TopUpBandwidth(Box<CredentialSpendingData>),
|
||||
}
|
||||
|
||||
impl From<super::latest::interface::RequestData> for RequestData {
|
||||
fn from(value: super::latest::interface::RequestData) -> Self {
|
||||
match value {
|
||||
super::latest::interface::RequestData::AvailableBandwidth(inner) => {
|
||||
Self::AvailableBandwidth(inner)
|
||||
}
|
||||
super::latest::interface::RequestData::TopUpBandwidth(credential_spending_data) => {
|
||||
Self::TopUpBandwidth(credential_spending_data)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<RequestData> for super::latest::interface::RequestData {
|
||||
fn from(value: RequestData) -> Self {
|
||||
match value {
|
||||
RequestData::AvailableBandwidth(inner) => Self::AvailableBandwidth(inner),
|
||||
RequestData::TopUpBandwidth(credential_spending_data) => {
|
||||
Self::TopUpBandwidth(credential_spending_data)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<super::latest::interface::ResponseData> for ResponseData {
|
||||
fn from(value: super::latest::interface::ResponseData) -> Self {
|
||||
match value {
|
||||
super::latest::interface::ResponseData::AvailableBandwidth(inner) => {
|
||||
Self::AvailableBandwidth(inner)
|
||||
}
|
||||
super::latest::interface::ResponseData::TopUpBandwidth(credential_spending_data) => {
|
||||
Self::TopUpBandwidth(credential_spending_data)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ResponseData> for super::latest::interface::ResponseData {
|
||||
fn from(value: ResponseData) -> Self {
|
||||
match value {
|
||||
ResponseData::AvailableBandwidth(inner) => Self::AvailableBandwidth(inner),
|
||||
ResponseData::TopUpBandwidth(credential_spending_data) => {
|
||||
Self::TopUpBandwidth(credential_spending_data)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Construct<RequestData> for Request {
|
||||
fn construct(info: RequestData, version: Version) -> Result<Self, super::error::Error> {
|
||||
match version {
|
||||
#[cfg(feature = "testing")]
|
||||
Version::V0 => {
|
||||
let translate_info = super::latest::interface::RequestData::from(info);
|
||||
let downgrade_info = v0::interface::RequestData::try_from(translate_info)?;
|
||||
let versioned_request = v0::VersionedRequest::construct(downgrade_info, version)?;
|
||||
Ok(versioned_request.try_into()?)
|
||||
}
|
||||
Version::V1 => {
|
||||
let versioned_request = v1::VersionedRequest::construct(info.into(), version)?;
|
||||
Ok(versioned_request.try_into()?)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Extract<RequestData> for Request {
|
||||
fn extract(&self) -> Result<(RequestData, Version), crate::models::Error> {
|
||||
match self.version {
|
||||
#[cfg(feature = "testing")]
|
||||
super::Version::V0 => {
|
||||
let versioned_request = v0::VersionedRequest::try_from(self.clone())?;
|
||||
let (request, version) = versioned_request.extract()?;
|
||||
|
||||
let upgrade_request = super::latest::interface::RequestData::try_from(request)?;
|
||||
|
||||
Ok((upgrade_request.into(), version))
|
||||
}
|
||||
super::Version::V1 => {
|
||||
let versioned_request = v1::VersionedRequest::try_from(self.clone())?;
|
||||
let (extracted, version) = versioned_request.extract()?;
|
||||
Ok((extracted.into(), version))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub enum ResponseData {
|
||||
AvailableBandwidth(i64),
|
||||
TopUpBandwidth(i64),
|
||||
}
|
||||
|
||||
impl Construct<ResponseData> for Response {
|
||||
fn construct(info: ResponseData, version: Version) -> Result<Self, super::error::Error> {
|
||||
match version {
|
||||
#[cfg(feature = "testing")]
|
||||
super::Version::V0 => {
|
||||
let translate_response = super::latest::interface::ResponseData::from(info);
|
||||
let downgrade_response = v0::interface::ResponseData::try_from(translate_response)?;
|
||||
let versioned_response =
|
||||
v0::VersionedResponse::construct(downgrade_response, version)?;
|
||||
Ok(versioned_response.try_into()?)
|
||||
}
|
||||
Version::V1 => {
|
||||
let versioned_response = v1::VersionedResponse::construct(info.into(), version)?;
|
||||
Ok(versioned_response.try_into()?)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Extract<ResponseData> for Response {
|
||||
fn extract(&self) -> Result<(ResponseData, Version), super::error::Error> {
|
||||
match self.version {
|
||||
#[cfg(feature = "testing")]
|
||||
super::Version::V0 => {
|
||||
let versioned_response = v0::VersionedResponse::try_from(self.clone())?;
|
||||
let (response, version) = versioned_response.extract()?;
|
||||
|
||||
let upgrade_response = super::latest::interface::ResponseData::try_from(response)?;
|
||||
|
||||
Ok((upgrade_response.into(), version))
|
||||
}
|
||||
super::Version::V1 => {
|
||||
let versioned_response = v1::VersionedResponse::try_from(self.clone())?;
|
||||
let (extracted, version) = versioned_response.extract()?;
|
||||
Ok((extracted.into(), version))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,175 +0,0 @@
|
||||
// Copyright 2025 - Nym Technologies SA <contact@nymtech.net>
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
use std::fmt::{Display, Formatter};
|
||||
|
||||
use axum::http::StatusCode;
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use utoipa::ToSchema;
|
||||
|
||||
pub(crate) mod error;
|
||||
pub mod interface;
|
||||
#[cfg(feature = "testing")]
|
||||
pub mod v0; // dummy version, only for filling boilerplate code for update/downgrade and testing
|
||||
pub mod v1;
|
||||
|
||||
pub use v1 as latest;
|
||||
|
||||
use crate::models::error::Error;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema, ToSchema)]
|
||||
pub enum Version {
|
||||
#[cfg(feature = "testing")]
|
||||
/// only used for testing purposes, don't include it in your matching arms
|
||||
V0,
|
||||
V1,
|
||||
}
|
||||
|
||||
impl From<u64> for Version {
|
||||
fn from(value: u64) -> Self {
|
||||
#[cfg(feature = "testing")]
|
||||
let zero_version = Version::V0;
|
||||
#[cfg(not(feature = "testing"))]
|
||||
let zero_version = latest::VERSION;
|
||||
match value {
|
||||
0 => zero_version,
|
||||
1 => Version::V1,
|
||||
_ => latest::VERSION, // if unknown, it means we're behind, so we can use the latest we know about
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Version> for u64 {
|
||||
fn from(value: Version) -> Self {
|
||||
// remember to modify the above match if you're bumping the version
|
||||
match value {
|
||||
#[cfg(feature = "testing")]
|
||||
Version::V0 => 0,
|
||||
Version::V1 => 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, ToSchema)]
|
||||
pub struct Request {
|
||||
pub version: Version,
|
||||
pub(crate) inner: Vec<u8>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Serialize, Deserialize, ToSchema)]
|
||||
pub struct Response {
|
||||
pub version: Version,
|
||||
pub(crate) inner: Vec<u8>,
|
||||
}
|
||||
|
||||
pub trait Extract<T> {
|
||||
fn extract(&self) -> Result<(T, Version), Error>;
|
||||
}
|
||||
|
||||
pub trait Construct<T>: Sized {
|
||||
fn construct(info: T, version: Version) -> Result<Self, Error>;
|
||||
}
|
||||
|
||||
pub type AxumResult<T> = Result<T, AxumErrorResponse>;
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, JsonSchema)]
|
||||
pub struct ErrorResponse {
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
impl Display for ErrorResponse {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
||||
self.message.fmt(f)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct AxumErrorResponse {
|
||||
message: ErrorResponse,
|
||||
status: StatusCode,
|
||||
}
|
||||
|
||||
impl AxumErrorResponse {
|
||||
pub fn bad_request(msg: impl Display) -> Self {
|
||||
Self {
|
||||
message: ErrorResponse {
|
||||
message: msg.to_string(),
|
||||
},
|
||||
status: StatusCode::BAD_REQUEST,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl axum::response::IntoResponse for AxumErrorResponse {
|
||||
fn into_response(self) -> axum::response::Response {
|
||||
(self.status, self.message.message.to_string()).into_response()
|
||||
}
|
||||
}
|
||||
|
||||
mod tests {
|
||||
#[allow(dead_code)]
|
||||
pub(crate) const CREDENTIAL_BYTES: [u8; 1245] = [
|
||||
0, 0, 4, 133, 96, 179, 223, 185, 136, 23, 213, 166, 59, 203, 66, 69, 209, 181, 227, 254,
|
||||
16, 102, 98, 237, 59, 119, 170, 111, 31, 194, 51, 59, 120, 17, 115, 229, 79, 91, 11, 139,
|
||||
154, 2, 212, 23, 68, 70, 167, 3, 240, 54, 224, 171, 221, 1, 69, 48, 60, 118, 119, 249, 123,
|
||||
35, 172, 227, 131, 96, 232, 209, 187, 123, 4, 197, 102, 90, 96, 45, 125, 135, 140, 99, 1,
|
||||
151, 17, 131, 143, 157, 97, 107, 139, 232, 212, 87, 14, 115, 253, 255, 166, 167, 186, 43,
|
||||
90, 96, 173, 105, 120, 40, 10, 163, 250, 224, 214, 200, 178, 4, 160, 16, 130, 59, 76, 193,
|
||||
39, 240, 3, 101, 141, 209, 183, 226, 186, 207, 56, 210, 187, 7, 164, 240, 164, 205, 37, 81,
|
||||
184, 214, 193, 195, 90, 205, 238, 225, 195, 104, 12, 123, 203, 57, 233, 243, 215, 145, 195,
|
||||
196, 57, 38, 125, 172, 18, 47, 63, 165, 110, 219, 180, 40, 58, 116, 92, 254, 160, 98, 48,
|
||||
92, 254, 232, 107, 184, 80, 234, 60, 160, 235, 249, 76, 41, 38, 165, 28, 40, 136, 74, 48,
|
||||
166, 50, 245, 23, 201, 140, 101, 79, 93, 235, 128, 186, 146, 126, 180, 134, 43, 13, 186,
|
||||
19, 195, 48, 168, 201, 29, 216, 95, 176, 198, 132, 188, 64, 39, 212, 150, 32, 52, 53, 38,
|
||||
228, 199, 122, 226, 217, 75, 40, 191, 151, 48, 164, 242, 177, 79, 14, 122, 105, 151, 85,
|
||||
88, 199, 162, 17, 96, 103, 83, 178, 128, 9, 24, 30, 74, 108, 241, 85, 240, 166, 97, 241,
|
||||
85, 199, 11, 198, 226, 234, 70, 107, 145, 28, 208, 114, 51, 12, 234, 108, 101, 202, 112,
|
||||
48, 185, 22, 159, 67, 109, 49, 27, 149, 90, 109, 32, 226, 112, 7, 201, 208, 209, 104, 31,
|
||||
97, 134, 204, 145, 27, 181, 206, 181, 106, 32, 110, 136, 115, 249, 201, 111, 5, 245, 203,
|
||||
71, 121, 169, 126, 151, 178, 236, 59, 221, 195, 48, 135, 115, 6, 50, 227, 74, 97, 107, 107,
|
||||
213, 90, 2, 203, 154, 138, 47, 128, 52, 134, 128, 224, 51, 65, 240, 90, 8, 55, 175, 180,
|
||||
178, 204, 206, 168, 110, 51, 57, 189, 169, 48, 169, 136, 121, 99, 51, 170, 178, 214, 74, 1,
|
||||
96, 151, 167, 25, 173, 180, 171, 155, 10, 55, 142, 234, 190, 113, 90, 79, 80, 244, 71, 166,
|
||||
30, 235, 113, 150, 133, 1, 218, 17, 109, 111, 223, 24, 216, 177, 41, 2, 204, 65, 221, 212,
|
||||
207, 236, 144, 6, 65, 224, 55, 42, 1, 1, 161, 134, 118, 127, 111, 220, 110, 127, 240, 71,
|
||||
223, 129, 12, 93, 20, 220, 60, 56, 71, 146, 184, 95, 132, 69, 28, 56, 53, 192, 213, 22,
|
||||
119, 230, 152, 225, 182, 188, 163, 219, 37, 175, 247, 73, 14, 247, 38, 72, 243, 1, 48, 131,
|
||||
59, 8, 13, 96, 143, 185, 127, 241, 161, 217, 24, 149, 193, 40, 16, 30, 202, 151, 28, 119,
|
||||
240, 153, 101, 156, 61, 193, 72, 245, 199, 181, 12, 231, 65, 166, 67, 142, 121, 207, 202,
|
||||
58, 197, 113, 188, 248, 42, 124, 105, 48, 161, 241, 55, 209, 36, 194, 27, 63, 233, 144,
|
||||
189, 85, 117, 234, 9, 139, 46, 31, 206, 114, 95, 131, 29, 240, 13, 81, 142, 140, 133, 33,
|
||||
30, 41, 141, 37, 80, 217, 95, 221, 76, 115, 86, 201, 165, 51, 252, 9, 28, 209, 1, 48, 150,
|
||||
74, 248, 212, 187, 222, 66, 210, 3, 200, 19, 217, 171, 184, 42, 148, 53, 150, 57, 50, 6,
|
||||
227, 227, 62, 49, 42, 148, 148, 157, 82, 191, 58, 24, 34, 56, 98, 120, 89, 105, 176, 85,
|
||||
15, 253, 241, 41, 153, 195, 136, 1, 48, 142, 126, 213, 101, 223, 79, 133, 230, 105, 38,
|
||||
161, 149, 2, 21, 136, 150, 42, 72, 218, 85, 146, 63, 223, 58, 108, 186, 183, 248, 62, 20,
|
||||
47, 34, 113, 160, 177, 204, 181, 16, 24, 212, 224, 35, 84, 51, 168, 56, 136, 11, 1, 48,
|
||||
135, 242, 62, 149, 230, 178, 32, 224, 119, 26, 234, 163, 237, 224, 114, 95, 112, 140, 170,
|
||||
150, 96, 125, 136, 221, 180, 78, 18, 11, 12, 184, 2, 198, 217, 119, 43, 69, 4, 172, 109,
|
||||
55, 183, 40, 131, 172, 161, 88, 183, 101, 1, 48, 173, 216, 22, 73, 42, 255, 211, 93, 249,
|
||||
87, 159, 115, 61, 91, 55, 130, 17, 216, 60, 34, 122, 55, 8, 244, 244, 153, 151, 57, 5, 144,
|
||||
178, 55, 249, 64, 211, 168, 34, 148, 56, 89, 92, 203, 70, 124, 219, 152, 253, 165, 0, 32,
|
||||
203, 116, 63, 7, 240, 222, 82, 86, 11, 149, 167, 72, 224, 55, 190, 66, 201, 65, 168, 184,
|
||||
96, 47, 194, 241, 168, 124, 7, 74, 214, 250, 37, 76, 32, 218, 69, 122, 103, 215, 145, 169,
|
||||
24, 212, 229, 168, 106, 10, 144, 31, 13, 25, 178, 242, 250, 106, 159, 40, 48, 163, 165, 61,
|
||||
130, 57, 146, 4, 73, 32, 254, 233, 125, 135, 212, 29, 111, 4, 177, 114, 15, 210, 170, 82,
|
||||
108, 110, 62, 166, 81, 209, 106, 176, 156, 14, 133, 242, 60, 127, 120, 242, 28, 97, 0, 1,
|
||||
32, 103, 93, 109, 89, 240, 91, 1, 84, 150, 50, 206, 157, 203, 49, 220, 120, 234, 175, 234,
|
||||
150, 126, 225, 94, 163, 164, 199, 138, 114, 62, 99, 106, 112, 1, 32, 171, 40, 220, 82, 241,
|
||||
203, 76, 146, 111, 139, 182, 179, 237, 182, 115, 75, 128, 201, 107, 43, 214, 0, 135, 217,
|
||||
160, 68, 150, 232, 144, 114, 237, 98, 32, 30, 134, 232, 59, 93, 163, 253, 244, 13, 202, 52,
|
||||
147, 168, 83, 121, 123, 95, 21, 210, 209, 225, 223, 143, 49, 10, 205, 238, 1, 22, 83, 81,
|
||||
70, 1, 32, 26, 76, 6, 234, 160, 50, 139, 102, 161, 232, 155, 106, 130, 171, 226, 210, 233,
|
||||
178, 85, 247, 71, 123, 55, 53, 46, 67, 148, 137, 156, 207, 208, 107, 1, 32, 102, 31, 4, 98,
|
||||
110, 156, 144, 61, 229, 140, 198, 84, 196, 238, 128, 35, 131, 182, 137, 125, 241, 95, 69,
|
||||
131, 170, 27, 2, 144, 75, 72, 242, 102, 3, 32, 121, 80, 45, 173, 56, 65, 218, 27, 40, 251,
|
||||
197, 32, 169, 104, 123, 110, 90, 78, 153, 166, 38, 9, 129, 228, 99, 8, 1, 116, 142, 233,
|
||||
162, 69, 32, 216, 169, 159, 116, 95, 12, 63, 176, 195, 6, 183, 123, 135, 75, 61, 112, 106,
|
||||
83, 235, 176, 41, 27, 248, 48, 71, 165, 170, 12, 92, 103, 103, 81, 32, 58, 74, 75, 145,
|
||||
192, 94, 153, 69, 80, 128, 241, 3, 16, 117, 192, 86, 161, 103, 44, 174, 211, 196, 182, 124,
|
||||
55, 11, 107, 142, 49, 88, 6, 41, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
|
||||
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
|
||||
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 0, 37, 139, 240, 0, 0,
|
||||
0, 0, 0, 0, 0, 1,
|
||||
];
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
// Copyright 2025 - Nym Technologies SA <contact@nymtech.net>
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
pub mod request;
|
||||
pub mod response;
|
||||
@@ -1,86 +0,0 @@
|
||||
// Copyright 2025 - Nym Technologies SA <contact@nymtech.net>
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
use bincode::Options;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{make_bincode_serializer, models::Request};
|
||||
|
||||
use super::super::{Error, QueryType, VersionedRequest};
|
||||
|
||||
#[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub struct InnerAvailableBandwidthRequest {}
|
||||
|
||||
impl TryFrom<VersionedRequest> for InnerAvailableBandwidthRequest {
|
||||
type Error = Error;
|
||||
|
||||
fn try_from(value: VersionedRequest) -> Result<Self, Self::Error> {
|
||||
match value.query_type {
|
||||
QueryType::AvailableBandwidth => {
|
||||
Ok(make_bincode_serializer().deserialize(&value.inner)?)
|
||||
}
|
||||
QueryType::TopupBandwidth => Err(Error::InvalidQueryType {
|
||||
source_query_type: value.query_type.to_string(),
|
||||
target_query_type: QueryType::AvailableBandwidth.to_string(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<InnerAvailableBandwidthRequest> for VersionedRequest {
|
||||
type Error = Error;
|
||||
|
||||
fn try_from(value: InnerAvailableBandwidthRequest) -> Result<Self, Self::Error> {
|
||||
Ok(Self {
|
||||
query_type: QueryType::AvailableBandwidth,
|
||||
inner: make_bincode_serializer().serialize(&value)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<Request> for InnerAvailableBandwidthRequest {
|
||||
type Error = crate::error::MetadataError;
|
||||
|
||||
fn try_from(value: Request) -> Result<Self, Self::Error> {
|
||||
VersionedRequest::try_from(value)?
|
||||
.try_into()
|
||||
.map_err(|err: Error| crate::error::MetadataError::Models {
|
||||
message: err.to_string(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<InnerAvailableBandwidthRequest> for Request {
|
||||
type Error = crate::error::MetadataError;
|
||||
|
||||
fn try_from(value: InnerAvailableBandwidthRequest) -> Result<Self, Self::Error> {
|
||||
VersionedRequest::try_from(value)?
|
||||
.try_into()
|
||||
.map_err(|err: Error| crate::error::MetadataError::Models {
|
||||
message: err.to_string(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn serde() {
|
||||
let req = InnerAvailableBandwidthRequest {};
|
||||
let ser = VersionedRequest::try_from(req).unwrap();
|
||||
assert_eq!(QueryType::AvailableBandwidth, ser.query_type);
|
||||
let de = InnerAvailableBandwidthRequest::try_from(ser).unwrap();
|
||||
assert_eq!(req, de);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_content() {
|
||||
let future_req = VersionedRequest {
|
||||
query_type: QueryType::AvailableBandwidth,
|
||||
inner: vec![],
|
||||
};
|
||||
assert!(InnerAvailableBandwidthRequest::try_from(future_req).is_ok());
|
||||
}
|
||||
}
|
||||
-86
@@ -1,86 +0,0 @@
|
||||
// Copyright 2025 - Nym Technologies SA <contact@nymtech.net>
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
use bincode::Options;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{make_bincode_serializer, models::Response};
|
||||
|
||||
use super::super::{Error, QueryType, VersionedResponse};
|
||||
|
||||
#[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub struct InnerAvailableBandwidthResponse {}
|
||||
|
||||
impl TryFrom<VersionedResponse> for InnerAvailableBandwidthResponse {
|
||||
type Error = Error;
|
||||
|
||||
fn try_from(value: VersionedResponse) -> Result<Self, Self::Error> {
|
||||
match value.query_type {
|
||||
QueryType::AvailableBandwidth => {
|
||||
Ok(make_bincode_serializer().deserialize(&value.inner)?)
|
||||
}
|
||||
QueryType::TopupBandwidth => Err(Error::InvalidQueryType {
|
||||
source_query_type: value.query_type.to_string(),
|
||||
target_query_type: QueryType::AvailableBandwidth.to_string(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<InnerAvailableBandwidthResponse> for VersionedResponse {
|
||||
type Error = Error;
|
||||
|
||||
fn try_from(value: InnerAvailableBandwidthResponse) -> Result<Self, Self::Error> {
|
||||
Ok(Self {
|
||||
query_type: QueryType::AvailableBandwidth,
|
||||
inner: make_bincode_serializer().serialize(&value)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<Response> for InnerAvailableBandwidthResponse {
|
||||
type Error = crate::error::MetadataError;
|
||||
|
||||
fn try_from(value: Response) -> Result<Self, Self::Error> {
|
||||
VersionedResponse::try_from(value)?
|
||||
.try_into()
|
||||
.map_err(|err: Error| crate::error::MetadataError::Models {
|
||||
message: err.to_string(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<InnerAvailableBandwidthResponse> for Response {
|
||||
type Error = crate::error::MetadataError;
|
||||
|
||||
fn try_from(value: InnerAvailableBandwidthResponse) -> Result<Self, Self::Error> {
|
||||
VersionedResponse::try_from(value)?
|
||||
.try_into()
|
||||
.map_err(|err: Error| crate::error::MetadataError::Models {
|
||||
message: err.to_string(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn serde() {
|
||||
let resp = InnerAvailableBandwidthResponse {};
|
||||
let ser = VersionedResponse::try_from(resp).unwrap();
|
||||
assert_eq!(QueryType::AvailableBandwidth, ser.query_type);
|
||||
let de = InnerAvailableBandwidthResponse::try_from(ser).unwrap();
|
||||
assert_eq!(resp, de);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_content() {
|
||||
let future_resp = VersionedResponse {
|
||||
query_type: QueryType::AvailableBandwidth,
|
||||
inner: vec![],
|
||||
};
|
||||
assert!(InnerAvailableBandwidthResponse::try_from(future_resp).is_ok());
|
||||
}
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
// Copyright 2025 - Nym Technologies SA <contact@nymtech.net>
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
use super::{
|
||||
available_bandwidth::{
|
||||
request::InnerAvailableBandwidthRequest, response::InnerAvailableBandwidthResponse,
|
||||
},
|
||||
topup_bandwidth::{request::InnerTopUpRequest, response::InnerTopUpResponse},
|
||||
QueryType, VersionedRequest, VersionedResponse, VERSION,
|
||||
};
|
||||
use crate::models::{error::Error, Construct, Extract, Version};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum RequestData {
|
||||
AvailableBandwidth(()),
|
||||
TopUpBandwidth(()),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum ResponseData {
|
||||
AvailableBandwidth(()),
|
||||
TopUpBandwidth(()),
|
||||
}
|
||||
|
||||
impl Construct<RequestData> for VersionedRequest {
|
||||
fn construct(info: RequestData, _version: Version) -> Result<Self, Error> {
|
||||
match info {
|
||||
RequestData::AvailableBandwidth(_) => Ok(InnerAvailableBandwidthRequest {}.try_into()?),
|
||||
RequestData::TopUpBandwidth(_) => Ok(InnerTopUpRequest {}.try_into()?),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Extract<RequestData> for VersionedRequest {
|
||||
fn extract(&self) -> Result<(RequestData, Version), Error> {
|
||||
match self.query_type {
|
||||
QueryType::AvailableBandwidth => {
|
||||
let _req = InnerAvailableBandwidthRequest::try_from(self.clone())?;
|
||||
Ok((RequestData::AvailableBandwidth(()), VERSION))
|
||||
}
|
||||
QueryType::TopupBandwidth => {
|
||||
let _req = InnerTopUpRequest::try_from(self.clone())?;
|
||||
Ok((RequestData::TopUpBandwidth(()), VERSION))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Construct<ResponseData> for VersionedResponse {
|
||||
fn construct(info: ResponseData, _version: Version) -> Result<Self, Error> {
|
||||
match info {
|
||||
ResponseData::AvailableBandwidth(()) => {
|
||||
Ok(InnerAvailableBandwidthResponse {}.try_into()?)
|
||||
}
|
||||
ResponseData::TopUpBandwidth(()) => Ok(InnerTopUpResponse {}.try_into()?),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Extract<ResponseData> for VersionedResponse {
|
||||
fn extract(&self) -> Result<(ResponseData, Version), Error> {
|
||||
match self.query_type {
|
||||
QueryType::AvailableBandwidth => {
|
||||
let _resp = InnerAvailableBandwidthResponse::try_from(self.clone())?;
|
||||
Ok((ResponseData::AvailableBandwidth(()), VERSION))
|
||||
}
|
||||
QueryType::TopupBandwidth => {
|
||||
let _resp = InnerTopUpResponse::try_from(self.clone())?;
|
||||
Ok((ResponseData::TopUpBandwidth(()), VERSION))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,175 +0,0 @@
|
||||
// Copyright 2025 - Nym Technologies SA <contact@nymtech.net>
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
use std::fmt::Display;
|
||||
|
||||
use bincode::Options;
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use utoipa::ToSchema;
|
||||
|
||||
use super::error::Error;
|
||||
use crate::{
|
||||
make_bincode_serializer,
|
||||
models::{Request, Response, Version},
|
||||
};
|
||||
|
||||
pub(crate) mod available_bandwidth;
|
||||
pub mod interface;
|
||||
pub(crate) mod topup_bandwidth;
|
||||
|
||||
pub const VERSION: Version = Version::V0;
|
||||
|
||||
pub use available_bandwidth::{
|
||||
request::InnerAvailableBandwidthRequest as AvailableBandwidthRequest,
|
||||
response::InnerAvailableBandwidthResponse as AvailableBandwidthResponse,
|
||||
};
|
||||
pub use topup_bandwidth::{
|
||||
request::InnerTopUpRequest as TopUpRequest, response::InnerTopUpResponse as TopUpResponse,
|
||||
};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema, ToSchema)]
|
||||
pub enum QueryType {
|
||||
AvailableBandwidth,
|
||||
TopupBandwidth,
|
||||
}
|
||||
|
||||
impl Display for QueryType {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{self:?}")
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, ToSchema)]
|
||||
pub struct VersionedRequest {
|
||||
query_type: QueryType,
|
||||
inner: Vec<u8>,
|
||||
}
|
||||
|
||||
impl TryFrom<VersionedRequest> for Request {
|
||||
type Error = Error;
|
||||
|
||||
fn try_from(value: VersionedRequest) -> Result<Self, Self::Error> {
|
||||
Ok(Request {
|
||||
version: VERSION,
|
||||
inner: make_bincode_serializer().serialize(&value)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<Request> for VersionedRequest {
|
||||
type Error = Error;
|
||||
|
||||
fn try_from(value: Request) -> Result<Self, Self::Error> {
|
||||
if value.version != VERSION {
|
||||
return Err(Error::InvalidVersion {
|
||||
source_version: value.version,
|
||||
target_version: VERSION,
|
||||
});
|
||||
}
|
||||
Ok(make_bincode_serializer().deserialize(&value.inner)?)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, ToSchema)]
|
||||
pub struct VersionedResponse {
|
||||
query_type: QueryType,
|
||||
inner: Vec<u8>,
|
||||
}
|
||||
|
||||
impl TryFrom<VersionedResponse> for Response {
|
||||
type Error = Error;
|
||||
|
||||
fn try_from(value: VersionedResponse) -> Result<Self, Self::Error> {
|
||||
Ok(Response {
|
||||
version: VERSION,
|
||||
inner: make_bincode_serializer().serialize(&value)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<Response> for VersionedResponse {
|
||||
type Error = Error;
|
||||
|
||||
fn try_from(value: Response) -> Result<Self, Self::Error> {
|
||||
if value.version != VERSION {
|
||||
return Err(Error::InvalidVersion {
|
||||
source_version: value.version,
|
||||
target_version: VERSION,
|
||||
});
|
||||
}
|
||||
Ok(make_bincode_serializer().deserialize(&value.inner)?)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use self::{
|
||||
available_bandwidth::{
|
||||
request::InnerAvailableBandwidthRequest, response::InnerAvailableBandwidthResponse,
|
||||
},
|
||||
topup_bandwidth::{request::InnerTopUpRequest, response::InnerTopUpResponse},
|
||||
};
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn serde_request_av_bw() {
|
||||
let req = VersionedRequest {
|
||||
query_type: QueryType::AvailableBandwidth,
|
||||
inner: make_bincode_serializer()
|
||||
.serialize(&InnerAvailableBandwidthRequest {})
|
||||
.unwrap(),
|
||||
};
|
||||
|
||||
let ser = Request::try_from(req.clone()).unwrap();
|
||||
assert_eq!(VERSION, ser.version);
|
||||
let de = VersionedRequest::try_from(ser).unwrap();
|
||||
assert_eq!(req, de);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serde_response_av_bw() {
|
||||
let resp = VersionedResponse {
|
||||
query_type: QueryType::AvailableBandwidth,
|
||||
inner: make_bincode_serializer()
|
||||
.serialize(&InnerAvailableBandwidthResponse {})
|
||||
.unwrap(),
|
||||
};
|
||||
|
||||
let ser = Response::try_from(resp.clone()).unwrap();
|
||||
assert_eq!(VERSION, ser.version);
|
||||
let de = VersionedResponse::try_from(ser).unwrap();
|
||||
assert_eq!(resp, de);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serde_request_topup() {
|
||||
let req = VersionedRequest {
|
||||
query_type: QueryType::TopupBandwidth,
|
||||
inner: make_bincode_serializer()
|
||||
.serialize(&InnerTopUpRequest {})
|
||||
.unwrap(),
|
||||
};
|
||||
|
||||
let ser = Request::try_from(req.clone()).unwrap();
|
||||
assert_eq!(VERSION, ser.version);
|
||||
let de = VersionedRequest::try_from(ser).unwrap();
|
||||
assert_eq!(req, de);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serde_response_topup() {
|
||||
let resp = VersionedResponse {
|
||||
query_type: QueryType::TopupBandwidth,
|
||||
inner: make_bincode_serializer()
|
||||
.serialize(&InnerTopUpResponse {})
|
||||
.unwrap(),
|
||||
};
|
||||
|
||||
let ser = Response::try_from(resp.clone()).unwrap();
|
||||
assert_eq!(VERSION, ser.version);
|
||||
let de = VersionedResponse::try_from(ser).unwrap();
|
||||
assert_eq!(resp, de);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
// Copyright 2025 - Nym Technologies SA <contact@nymtech.net>
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
pub mod request;
|
||||
pub mod response;
|
||||
@@ -1,84 +0,0 @@
|
||||
// Copyright 2025 - Nym Technologies SA <contact@nymtech.net>
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
use bincode::Options;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{make_bincode_serializer, models::Request};
|
||||
|
||||
use super::super::{Error, QueryType, VersionedRequest};
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
|
||||
pub struct InnerTopUpRequest {}
|
||||
|
||||
impl TryFrom<VersionedRequest> for InnerTopUpRequest {
|
||||
type Error = Error;
|
||||
|
||||
fn try_from(value: VersionedRequest) -> Result<Self, Self::Error> {
|
||||
match value.query_type {
|
||||
QueryType::TopupBandwidth => Ok(make_bincode_serializer().deserialize(&value.inner)?),
|
||||
QueryType::AvailableBandwidth => Err(Error::InvalidQueryType {
|
||||
source_query_type: value.query_type.to_string(),
|
||||
target_query_type: QueryType::TopupBandwidth.to_string(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<InnerTopUpRequest> for VersionedRequest {
|
||||
type Error = Error;
|
||||
|
||||
fn try_from(value: InnerTopUpRequest) -> Result<Self, Self::Error> {
|
||||
Ok(Self {
|
||||
query_type: QueryType::TopupBandwidth,
|
||||
inner: make_bincode_serializer().serialize(&value)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<Request> for InnerTopUpRequest {
|
||||
type Error = crate::error::MetadataError;
|
||||
|
||||
fn try_from(value: Request) -> Result<Self, Self::Error> {
|
||||
VersionedRequest::try_from(value)?
|
||||
.try_into()
|
||||
.map_err(|err: Error| crate::error::MetadataError::Models {
|
||||
message: err.to_string(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<InnerTopUpRequest> for Request {
|
||||
type Error = crate::error::MetadataError;
|
||||
|
||||
fn try_from(value: InnerTopUpRequest) -> Result<Self, Self::Error> {
|
||||
VersionedRequest::try_from(value)?
|
||||
.try_into()
|
||||
.map_err(|err: Error| crate::error::MetadataError::Models {
|
||||
message: err.to_string(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn serde() {
|
||||
let req = InnerTopUpRequest {};
|
||||
let ser = VersionedRequest::try_from(req.clone()).unwrap();
|
||||
assert_eq!(QueryType::TopupBandwidth, ser.query_type);
|
||||
let de = InnerTopUpRequest::try_from(ser).unwrap();
|
||||
assert_eq!(req, de);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_content() {
|
||||
let future_req = VersionedRequest {
|
||||
query_type: QueryType::TopupBandwidth,
|
||||
inner: vec![],
|
||||
};
|
||||
assert!(InnerTopUpRequest::try_from(future_req).is_ok());
|
||||
}
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
// Copyright 2025 - Nym Technologies SA <contact@nymtech.net>
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
use bincode::Options;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{make_bincode_serializer, models::Response};
|
||||
|
||||
use super::super::{Error, QueryType, VersionedResponse};
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
|
||||
pub struct InnerTopUpResponse {}
|
||||
|
||||
impl TryFrom<VersionedResponse> for InnerTopUpResponse {
|
||||
type Error = Error;
|
||||
|
||||
fn try_from(value: VersionedResponse) -> Result<Self, Self::Error> {
|
||||
match value.query_type {
|
||||
QueryType::TopupBandwidth => Ok(make_bincode_serializer().deserialize(&value.inner)?),
|
||||
QueryType::AvailableBandwidth => Err(Error::InvalidQueryType {
|
||||
source_query_type: value.query_type.to_string(),
|
||||
target_query_type: QueryType::TopupBandwidth.to_string(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<InnerTopUpResponse> for VersionedResponse {
|
||||
type Error = Error;
|
||||
|
||||
fn try_from(value: InnerTopUpResponse) -> Result<Self, Self::Error> {
|
||||
Ok(Self {
|
||||
query_type: QueryType::TopupBandwidth,
|
||||
inner: make_bincode_serializer().serialize(&value)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<Response> for InnerTopUpResponse {
|
||||
type Error = crate::error::MetadataError;
|
||||
|
||||
fn try_from(value: Response) -> Result<Self, Self::Error> {
|
||||
VersionedResponse::try_from(value)?
|
||||
.try_into()
|
||||
.map_err(|err: Error| crate::error::MetadataError::Models {
|
||||
message: err.to_string(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<InnerTopUpResponse> for Response {
|
||||
type Error = crate::error::MetadataError;
|
||||
|
||||
fn try_from(value: InnerTopUpResponse) -> Result<Self, Self::Error> {
|
||||
VersionedResponse::try_from(value)?
|
||||
.try_into()
|
||||
.map_err(|err: Error| crate::error::MetadataError::Models {
|
||||
message: err.to_string(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn serde() {
|
||||
let resp = InnerTopUpResponse {};
|
||||
let ser = VersionedResponse::try_from(resp.clone()).unwrap();
|
||||
assert_eq!(QueryType::TopupBandwidth, ser.query_type);
|
||||
let de = InnerTopUpResponse::try_from(ser).unwrap();
|
||||
assert_eq!(resp, de);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_content() {
|
||||
let future_resp = VersionedResponse {
|
||||
query_type: QueryType::TopupBandwidth,
|
||||
inner: vec![],
|
||||
};
|
||||
assert!(InnerTopUpResponse::try_from(future_resp).is_ok());
|
||||
}
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
// Copyright 2025 - Nym Technologies SA <contact@nymtech.net>
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
pub mod request;
|
||||
pub mod response;
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user