mirror of
https://github.com/serai-dex/serai.git
synced 2025-12-11 13:39:25 +00:00
Compare commits
165 Commits
ff-0.14
...
3c6e889732
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3c6e889732 | ||
|
|
354efc0192 | ||
|
|
e20058feae | ||
|
|
09f0714894 | ||
|
|
d3d539553c | ||
|
|
b08ae8e6a7 | ||
|
|
35db2924b4 | ||
|
|
bfff823bf7 | ||
|
|
352af85498 | ||
|
|
ecad89b269 | ||
|
|
48f5ed71d7 | ||
|
|
ed9cbdd8e0 | ||
|
|
0ac11defcc | ||
|
|
24e89316d5 | ||
|
|
3f03dac050 | ||
|
|
820b710928 | ||
|
|
88c7ae3e7d | ||
|
|
dd5e43760d | ||
|
|
776e417fd2 | ||
|
|
2f8ce15a92 | ||
|
|
af56304676 | ||
|
|
62a2c4f20e | ||
|
|
c69841710a | ||
|
|
3158590675 | ||
|
|
263d75d380 | ||
|
|
030185c7fc | ||
|
|
e2dc5db7aa | ||
|
|
90bc364f9f | ||
|
|
a4811c9a41 | ||
|
|
12cfa6b2a5 | ||
|
|
0c71b6fc4d | ||
|
|
ffe1b60a11 | ||
|
|
5526b8d439 | ||
|
|
beac35c119 | ||
|
|
62bb75e09a | ||
|
|
45bd376c08 | ||
|
|
da190759a9 | ||
|
|
f2d399ba1e | ||
|
|
220bcbc592 | ||
|
|
85949f4b04 | ||
|
|
2f833dec77 | ||
|
|
e3e41324c9 | ||
|
|
6ed7c5d65e | ||
|
|
9dddfd91c8 | ||
|
|
c24b694fb2 | ||
|
|
738babf7e9 | ||
|
|
33faa53b56 | ||
|
|
8c366107ae | ||
|
|
a7c77f8b5f | ||
|
|
da3095ed15 | ||
|
|
758d422595 | ||
|
|
9841061b49 | ||
|
|
4122a0135f | ||
|
|
b63ef32864 | ||
|
|
8be03a8fc2 | ||
|
|
677a2e5749 | ||
|
|
38bda1d586 | ||
|
|
2bc2ca6906 | ||
|
|
900a6612d7 | ||
|
|
17c1d5cd6b | ||
|
|
8a1b56a928 | ||
|
|
75964cf6da | ||
|
|
d407e35cee | ||
|
|
c8ef044acb | ||
|
|
ddbc32de4d | ||
|
|
e5ccfac19e | ||
|
|
432daae1d1 | ||
|
|
da3a85efe5 | ||
|
|
1e0240123d | ||
|
|
f6d4d1b084 | ||
|
|
1b37dd2951 | ||
|
|
f32e0609f1 | ||
|
|
ca85f9ba0c | ||
|
|
cfd1cb3a37 | ||
|
|
f2c13a0040 | ||
|
|
961f46bc04 | ||
|
|
2c4de3bab4 | ||
|
|
95c30720d2 | ||
|
|
ceede14f5c | ||
|
|
5e60ea9718 | ||
|
|
153f6f2f2f | ||
|
|
104c0d4492 | ||
|
|
7c8f13ab28 | ||
|
|
cb0deadf9a | ||
|
|
cb489f9cef | ||
|
|
cc662cb591 | ||
|
|
a8b8844e3f | ||
|
|
82b543ef75 | ||
|
|
72e80c1a3d | ||
|
|
b6edc94bcd | ||
|
|
cfce2b26e2 | ||
|
|
e87bbcda64 | ||
|
|
9f84adf8b3 | ||
|
|
3919cf55ae | ||
|
|
38dd8cb191 | ||
|
|
f2563d39cb | ||
|
|
15a9cbef40 | ||
|
|
078d6e51e5 | ||
|
|
6c33e18745 | ||
|
|
b743c9a43e | ||
|
|
0c2f2979a9 | ||
|
|
971951a1a6 | ||
|
|
92d9e908cb | ||
|
|
a32b97be88 | ||
|
|
e3809b2ff1 | ||
|
|
fd2d8b4f0a | ||
|
|
bc81614894 | ||
|
|
8df5aa2e2d | ||
|
|
b000740470 | ||
|
|
b9f554111d | ||
|
|
354c408e3e | ||
|
|
df3b60376a | ||
|
|
8d209c652e | ||
|
|
9ddad794b4 | ||
|
|
b934e484cc | ||
|
|
f8aee9b3c8 | ||
|
|
f51d77d26a | ||
|
|
0780deb643 | ||
|
|
75c38560f4 | ||
|
|
9f1c5268a5 | ||
|
|
35b113768b | ||
|
|
f2595c4939 | ||
|
|
8fcfa6d3d5 | ||
|
|
54c9d19726 | ||
|
|
25324c3cd5 | ||
|
|
ecb7df85b0 | ||
|
|
68c7acdbef | ||
|
|
8b60feed92 | ||
|
|
5c895efcd0 | ||
|
|
60e55656aa | ||
|
|
9536282418 | ||
|
|
8297d0679d | ||
|
|
d9f854b08a | ||
|
|
8aaf7f7dc6 | ||
|
|
ce447558ac | ||
|
|
fc850da30e | ||
|
|
d6f6cf1965 | ||
|
|
4438b51881 | ||
|
|
6ae0d9fad7 | ||
|
|
ad08b410a8 | ||
|
|
ec3cfd3ab7 | ||
|
|
01eb2daa0b | ||
|
|
885000f970 | ||
|
|
4be506414b | ||
|
|
1143d84e1d | ||
|
|
336922101f | ||
|
|
ffa033d978 | ||
|
|
23f986f57a | ||
|
|
bb726b58af | ||
|
|
387615705c | ||
|
|
c7f825a192 | ||
|
|
d363b1c173 | ||
|
|
d5077ae966 | ||
|
|
188fcc3cb4 | ||
|
|
cbab9486c6 | ||
|
|
a5f4c450c6 | ||
|
|
4f65a0b147 | ||
|
|
feb18d64a7 | ||
|
|
cb1e6535cb | ||
|
|
6b8cf6653a | ||
|
|
b426bfcfe8 | ||
|
|
21ce50ecf7 | ||
|
|
a4ceb2e756 | ||
|
|
b59b1f59dd | ||
|
|
eab5d9e64f |
2
.github/LICENSE
vendored
2
.github/LICENSE
vendored
@@ -1,6 +1,6 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2022-2023 Luke Parker
|
||||
Copyright (c) 2022-2025 Luke Parker
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
|
||||
2
.github/actions/bitcoin/action.yml
vendored
2
.github/actions/bitcoin/action.yml
vendored
@@ -12,7 +12,7 @@ runs:
|
||||
steps:
|
||||
- name: Bitcoin Daemon Cache
|
||||
id: cache-bitcoind
|
||||
uses: actions/cache@13aacd865c20de90d75de3b17ebe84f7a17d57d2
|
||||
uses: actions/cache@0400d5f644dc74513175e3cd8d07132dd4860809
|
||||
with:
|
||||
path: bitcoin.tar.gz
|
||||
key: bitcoind-${{ runner.os }}-${{ runner.arch }}-${{ inputs.version }}
|
||||
|
||||
37
.github/actions/build-dependencies/action.yml
vendored
37
.github/actions/build-dependencies/action.yml
vendored
@@ -7,13 +7,15 @@ runs:
|
||||
- name: Remove unused packages
|
||||
shell: bash
|
||||
run: |
|
||||
sudo apt remove -y "*msbuild*" "*powershell*" "*nuget*" "*bazel*" "*ansible*" "*terraform*" "*heroku*" "*aws*" azure-cli
|
||||
sudo apt remove -y "*powershell*" "*nuget*" "*bazel*" "*ansible*" "*terraform*" "*heroku*" "*aws*" azure-cli
|
||||
sudo apt remove -y "*nodejs*" "*npm*" "*yarn*" "*java*" "*kotlin*" "*golang*" "*swift*" "*julia*" "*fortran*" "*android*"
|
||||
sudo apt remove -y "*apache2*" "*nginx*" "*firefox*" "*chromium*" "*chrome*" "*edge*"
|
||||
|
||||
sudo apt remove -y --allow-remove-essential -f shim-signed *python3*
|
||||
# This removal command requires the prior removals due to unmet dependencies otherwise
|
||||
sudo apt remove -y "*qemu*" "*sql*" "*texinfo*" "*imagemagick*"
|
||||
sudo apt autoremove -y
|
||||
sudo apt clean
|
||||
docker system prune -a --volumes
|
||||
# Reinstall python3 as a general dependency of a functional operating system
|
||||
sudo apt install python3
|
||||
if: runner.os == 'Linux'
|
||||
|
||||
- name: Remove unused packages
|
||||
@@ -41,9 +43,34 @@ runs:
|
||||
- name: Install solc
|
||||
shell: bash
|
||||
run: |
|
||||
cargo install svm-rs
|
||||
cargo +1.89 install svm-rs --version =0.5.18
|
||||
svm install 0.8.26
|
||||
svm use 0.8.26
|
||||
|
||||
- name: Remove preinstalled Docker
|
||||
shell: bash
|
||||
run: |
|
||||
docker system prune -a --volumes
|
||||
sudo apt remove -y *docker*
|
||||
# Install uidmap which will be required for the explicitly installed Docker
|
||||
sudo apt install uidmap
|
||||
if: runner.os == 'Linux'
|
||||
|
||||
- name: Update system dependencies
|
||||
shell: bash
|
||||
run: |
|
||||
sudo apt update -y
|
||||
sudo apt upgrade -y
|
||||
sudo apt autoremove -y
|
||||
sudo apt clean
|
||||
if: runner.os == 'Linux'
|
||||
|
||||
- name: Install rootless Docker
|
||||
uses: docker/setup-docker-action@b60f85385d03ac8acfca6d9996982511d8620a19
|
||||
with:
|
||||
rootless: true
|
||||
set-host: true
|
||||
if: runner.os == 'Linux'
|
||||
|
||||
# - name: Cache Rust
|
||||
# uses: Swatinem/rust-cache@a95ba195448af2da9b00fb742d14ffaaf3c21f43
|
||||
|
||||
2
.github/actions/monero-wallet-rpc/action.yml
vendored
2
.github/actions/monero-wallet-rpc/action.yml
vendored
@@ -12,7 +12,7 @@ runs:
|
||||
steps:
|
||||
- name: Monero Wallet RPC Cache
|
||||
id: cache-monero-wallet-rpc
|
||||
uses: actions/cache@13aacd865c20de90d75de3b17ebe84f7a17d57d2
|
||||
uses: actions/cache@0400d5f644dc74513175e3cd8d07132dd4860809
|
||||
with:
|
||||
path: monero-wallet-rpc
|
||||
key: monero-wallet-rpc-${{ runner.os }}-${{ runner.arch }}-${{ inputs.version }}
|
||||
|
||||
2
.github/actions/monero/action.yml
vendored
2
.github/actions/monero/action.yml
vendored
@@ -12,7 +12,7 @@ runs:
|
||||
steps:
|
||||
- name: Monero Daemon Cache
|
||||
id: cache-monerod
|
||||
uses: actions/cache@13aacd865c20de90d75de3b17ebe84f7a17d57d2
|
||||
uses: actions/cache@0400d5f644dc74513175e3cd8d07132dd4860809
|
||||
with:
|
||||
path: /usr/bin/monerod
|
||||
key: monerod-${{ runner.os }}-${{ runner.arch }}-${{ inputs.version }}
|
||||
|
||||
2
.github/nightly-version
vendored
2
.github/nightly-version
vendored
@@ -1 +1 @@
|
||||
nightly-2025-02-01
|
||||
nightly-2025-08-01
|
||||
|
||||
14
.github/workflows/crypto-tests.yml
vendored
14
.github/workflows/crypto-tests.yml
vendored
@@ -32,13 +32,17 @@ jobs:
|
||||
-p dalek-ff-group \
|
||||
-p minimal-ed448 \
|
||||
-p ciphersuite \
|
||||
-p ciphersuite-kp256 \
|
||||
-p multiexp \
|
||||
-p schnorr-signatures \
|
||||
-p dleq \
|
||||
-p generalized-bulletproofs \
|
||||
-p generalized-bulletproofs-circuit-abstraction \
|
||||
-p ec-divisors \
|
||||
-p generalized-bulletproofs-ec-gadgets \
|
||||
-p prime-field \
|
||||
-p short-weierstrass \
|
||||
-p secq256k1 \
|
||||
-p embedwards25519 \
|
||||
-p dkg \
|
||||
-p dkg-recovery \
|
||||
-p dkg-dealer \
|
||||
-p dkg-musig \
|
||||
-p dkg-evrf \
|
||||
-p modular-frost \
|
||||
-p frost-schnorrkel
|
||||
|
||||
6
.github/workflows/daily-deny.yml
vendored
6
.github/workflows/daily-deny.yml
vendored
@@ -12,13 +12,13 @@ jobs:
|
||||
- uses: actions/checkout@3df4ab11eba7bda6032a0b82a6bb43b11571feac
|
||||
|
||||
- name: Advisory Cache
|
||||
uses: actions/cache@13aacd865c20de90d75de3b17ebe84f7a17d57d2
|
||||
uses: actions/cache@0400d5f644dc74513175e3cd8d07132dd4860809
|
||||
with:
|
||||
path: ~/.cargo/advisory-db
|
||||
key: rust-advisory-db
|
||||
|
||||
- name: Install cargo deny
|
||||
run: cargo install --locked cargo-deny
|
||||
run: cargo +1.89 install cargo-deny --version =0.18.3
|
||||
|
||||
- name: Run cargo deny
|
||||
run: cargo deny -L error --all-features check
|
||||
run: cargo deny -L error --all-features check --hide-inclusion-graph
|
||||
|
||||
105
.github/workflows/lint.yml
vendored
105
.github/workflows/lint.yml
vendored
@@ -26,7 +26,7 @@ jobs:
|
||||
uses: ./.github/actions/build-dependencies
|
||||
|
||||
- name: Install nightly rust
|
||||
run: rustup toolchain install ${{ steps.nightly.outputs.version }} --profile minimal -t wasm32-unknown-unknown -c clippy
|
||||
run: rustup toolchain install ${{ steps.nightly.outputs.version }} --profile minimal -t wasm32v1-none -c rust-src -c clippy
|
||||
|
||||
- name: Run Clippy
|
||||
run: cargo +${{ steps.nightly.outputs.version }} clippy --all-features --all-targets -- -D warnings -A clippy::items_after_test_module
|
||||
@@ -46,16 +46,16 @@ jobs:
|
||||
- uses: actions/checkout@3df4ab11eba7bda6032a0b82a6bb43b11571feac
|
||||
|
||||
- name: Advisory Cache
|
||||
uses: actions/cache@13aacd865c20de90d75de3b17ebe84f7a17d57d2
|
||||
uses: actions/cache@0400d5f644dc74513175e3cd8d07132dd4860809
|
||||
with:
|
||||
path: ~/.cargo/advisory-db
|
||||
key: rust-advisory-db
|
||||
|
||||
- name: Install cargo deny
|
||||
run: cargo install --locked cargo-deny
|
||||
run: cargo +1.89 install cargo-deny --version =0.18.3
|
||||
|
||||
- name: Run cargo deny
|
||||
run: cargo deny -L error --all-features check
|
||||
run: cargo deny -L error --all-features check --hide-inclusion-graph
|
||||
|
||||
fmt:
|
||||
runs-on: ubuntu-latest
|
||||
@@ -88,8 +88,101 @@ jobs:
|
||||
- uses: actions/checkout@3df4ab11eba7bda6032a0b82a6bb43b11571feac
|
||||
- name: Verify all dependencies are in use
|
||||
run: |
|
||||
cargo install cargo-machete
|
||||
cargo machete
|
||||
cargo +1.89 install cargo-machete --version =0.8.0
|
||||
cargo +1.89 machete
|
||||
|
||||
msrv:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@3df4ab11eba7bda6032a0b82a6bb43b11571feac
|
||||
- name: Verify claimed `rust-version`
|
||||
shell: bash
|
||||
run: |
|
||||
cargo +1.89 install cargo-msrv --version =0.18.4
|
||||
|
||||
function check_msrv {
|
||||
# We `cd` into the directory passed as the first argument, but will return to the
|
||||
# directory called from.
|
||||
return_to=$(pwd)
|
||||
echo "Checking $1"
|
||||
cd $1
|
||||
|
||||
# We then find the existing `rust-version` using `grep` (for the right line) and then a
|
||||
# regex (to strip to just the major and minor version).
|
||||
existing=$(cat ./Cargo.toml | grep "rust-version" | grep -Eo "[0-9]+\.[0-9]+")
|
||||
|
||||
# We then backup the `Cargo.toml`, allowing us to restore it after, saving time on future
|
||||
# MSRV checks (as they'll benefit from immediately exiting if the queried version is less
|
||||
# than the declared MSRV).
|
||||
mv ./Cargo.toml ./Cargo.toml.bak
|
||||
|
||||
# We then use an inverted (`-v`) grep to remove the existing `rust-version` from the
|
||||
# `Cargo.toml`, as required because else earlier versions of Rust won't even attempt to
|
||||
# compile this crate.
|
||||
cat ./Cargo.toml.bak | grep -v "rust-version" > Cargo.toml
|
||||
|
||||
# We then find the actual `rust-version` using `cargo-msrv` (again stripping to just the
|
||||
# major and minor version).
|
||||
actual=$(cargo msrv find --output-format minimal | grep -Eo "^[0-9]+\.[0-9]+")
|
||||
|
||||
# Finally, we compare the two.
|
||||
echo "Declared rust-version: $existing"
|
||||
echo "Actual rust-version: $actual"
|
||||
[ $existing == $actual ]
|
||||
result=$?
|
||||
|
||||
# Restore the original `Cargo.toml`.
|
||||
rm Cargo.toml
|
||||
mv ./Cargo.toml.bak ./Cargo.toml
|
||||
|
||||
# Return to the directory called from and return the result.
|
||||
cd $return_to
|
||||
return $result
|
||||
}
|
||||
|
||||
# Check each member of the workspace
|
||||
function check_workspace {
|
||||
# Get the members array from the workspace's `Cargo.toml`
|
||||
cargo_toml_lines=$(cat ./Cargo.toml | wc -l)
|
||||
members=$(cat Cargo.toml | grep "members\ \=\ \[" -m1 -A$cargo_toml_lines | grep "]" -m1 -B$cargo_toml_lines)
|
||||
# Parse out any comments, including comments post-fixed on the same line as an entry
|
||||
members=$(echo "$members" | grep -Ev "^[[:space:]]+#" | grep -Ev "^[[:space:]]?$" | awk -F',' '{print $1","}')
|
||||
# Prune `members = [` to `[` by replacing the first line with just `[`
|
||||
members=$(echo "$members" | sed "1s/.*/\[/")
|
||||
# Remove the trailing comma by replacing the last line's "," with ""
|
||||
members=$(echo "$members" | sed "$(($(echo "$members" | wc -l) - 1))s/\,//")
|
||||
# Correct the last line, which was malleated to "]," when pruning comments
|
||||
members=$(echo "$members" | sed "$(echo "$members" | wc -l)s/\]\,/\]/")
|
||||
|
||||
# Don't check the patches
|
||||
members=$(echo "$members" | grep -v "patches")
|
||||
# Don't check the following
|
||||
# Most of these are binaries, with the exception of the Substrate runtime which has a
|
||||
# bespoke build pipeline
|
||||
members=$(echo "$members" | grep -v "networks/ethereum/relayer\"")
|
||||
members=$(echo "$members" | grep -v "message-queue\"")
|
||||
members=$(echo "$members" | grep -v "processor/bin\"")
|
||||
members=$(echo "$members" | grep -v "processor/bitcoin\"")
|
||||
members=$(echo "$members" | grep -v "processor/ethereum\"")
|
||||
members=$(echo "$members" | grep -v "processor/monero\"")
|
||||
members=$(echo "$members" | grep -v "coordinator\"")
|
||||
members=$(echo "$members" | grep -v "substrate/runtime\"")
|
||||
members=$(echo "$members" | grep -v "substrate/node\"")
|
||||
members=$(echo "$members" | grep -v "orchestration\"")
|
||||
|
||||
# Don't check the tests
|
||||
members=$(echo "$members" | grep -v "mini\"")
|
||||
members=$(echo "$members" | grep -v "tests/")
|
||||
|
||||
echo $members | jq -r ".[]" | while read -r member; do
|
||||
check_msrv $member
|
||||
correct=$?
|
||||
if [ $correct -ne 0 ]; then
|
||||
return $correct
|
||||
fi
|
||||
done
|
||||
}
|
||||
check_workspace
|
||||
|
||||
slither:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
72
.github/workflows/monero-tests.yaml
vendored
72
.github/workflows/monero-tests.yaml
vendored
@@ -1,72 +0,0 @@
|
||||
name: Monero Tests
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- develop
|
||||
paths:
|
||||
- "networks/monero/**"
|
||||
- "processor/**"
|
||||
|
||||
pull_request:
|
||||
paths:
|
||||
- "networks/monero/**"
|
||||
- "processor/**"
|
||||
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
# Only run these once since they will be consistent regardless of any node
|
||||
unit-tests:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@3df4ab11eba7bda6032a0b82a6bb43b11571feac
|
||||
|
||||
- name: Test Dependencies
|
||||
uses: ./.github/actions/test-dependencies
|
||||
|
||||
- name: Run Unit Tests Without Features
|
||||
run: |
|
||||
GITHUB_CI=true RUST_BACKTRACE=1 cargo test --package monero-io --lib
|
||||
GITHUB_CI=true RUST_BACKTRACE=1 cargo test --package monero-generators --lib
|
||||
GITHUB_CI=true RUST_BACKTRACE=1 cargo test --package monero-primitives --lib
|
||||
GITHUB_CI=true RUST_BACKTRACE=1 cargo test --package monero-mlsag --lib
|
||||
GITHUB_CI=true RUST_BACKTRACE=1 cargo test --package monero-clsag --lib
|
||||
GITHUB_CI=true RUST_BACKTRACE=1 cargo test --package monero-borromean --lib
|
||||
GITHUB_CI=true RUST_BACKTRACE=1 cargo test --package monero-bulletproofs --lib
|
||||
GITHUB_CI=true RUST_BACKTRACE=1 cargo test --package monero-serai --lib
|
||||
GITHUB_CI=true RUST_BACKTRACE=1 cargo test --package monero-rpc --lib
|
||||
GITHUB_CI=true RUST_BACKTRACE=1 cargo test --package monero-simple-request-rpc --lib
|
||||
GITHUB_CI=true RUST_BACKTRACE=1 cargo test --package monero-address --lib
|
||||
GITHUB_CI=true RUST_BACKTRACE=1 cargo test --package monero-wallet --lib
|
||||
|
||||
# Doesn't run unit tests with features as the tests workflow will
|
||||
|
||||
integration-tests:
|
||||
runs-on: ubuntu-latest
|
||||
# Test against all supported protocol versions
|
||||
strategy:
|
||||
matrix:
|
||||
version: [v0.17.3.2, v0.18.3.4]
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@3df4ab11eba7bda6032a0b82a6bb43b11571feac
|
||||
|
||||
- name: Test Dependencies
|
||||
uses: ./.github/actions/test-dependencies
|
||||
with:
|
||||
monero-version: ${{ matrix.version }}
|
||||
|
||||
- name: Run Integration Tests Without Features
|
||||
run: |
|
||||
GITHUB_CI=true RUST_BACKTRACE=1 cargo test --package monero-serai --test '*'
|
||||
GITHUB_CI=true RUST_BACKTRACE=1 cargo test --package monero-simple-request-rpc --test '*'
|
||||
GITHUB_CI=true RUST_BACKTRACE=1 cargo test --package monero-wallet --test '*'
|
||||
|
||||
- name: Run Integration Tests
|
||||
# Don't run if the the tests workflow also will
|
||||
if: ${{ matrix.version != 'v0.18.3.4' }}
|
||||
run: |
|
||||
GITHUB_CI=true RUST_BACKTRACE=1 cargo test --package monero-serai --all-features --test '*'
|
||||
GITHUB_CI=true RUST_BACKTRACE=1 cargo test --package monero-simple-request-rpc --test '*'
|
||||
GITHUB_CI=true RUST_BACKTRACE=1 cargo test --package monero-wallet --all-features --test '*'
|
||||
259
.github/workflows/msrv.yml
vendored
259
.github/workflows/msrv.yml
vendored
@@ -1,259 +0,0 @@
|
||||
name: Weekly MSRV Check
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: "0 0 * * 0"
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
msrv-common:
|
||||
name: Run cargo msrv on common
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@3df4ab11eba7bda6032a0b82a6bb43b11571feac
|
||||
|
||||
- name: Install Build Dependencies
|
||||
uses: ./.github/actions/build-dependencies
|
||||
|
||||
- name: Install cargo msrv
|
||||
run: cargo install --locked cargo-msrv
|
||||
|
||||
- name: Run cargo msrv on common
|
||||
run: |
|
||||
cargo msrv verify --manifest-path common/zalloc/Cargo.toml
|
||||
cargo msrv verify --manifest-path common/std-shims/Cargo.toml
|
||||
cargo msrv verify --manifest-path common/env/Cargo.toml
|
||||
cargo msrv verify --manifest-path common/db/Cargo.toml
|
||||
cargo msrv verify --manifest-path common/task/Cargo.toml
|
||||
cargo msrv verify --manifest-path common/request/Cargo.toml
|
||||
cargo msrv verify --manifest-path common/patchable-async-sleep/Cargo.toml
|
||||
|
||||
msrv-crypto:
|
||||
name: Run cargo msrv on crypto
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@3df4ab11eba7bda6032a0b82a6bb43b11571feac
|
||||
|
||||
- name: Install Build Dependencies
|
||||
uses: ./.github/actions/build-dependencies
|
||||
|
||||
- name: Install cargo msrv
|
||||
run: cargo install --locked cargo-msrv
|
||||
|
||||
- name: Run cargo msrv on crypto
|
||||
run: |
|
||||
cargo msrv verify --manifest-path crypto/transcript/Cargo.toml
|
||||
|
||||
cargo msrv verify --manifest-path crypto/ff-group-tests/Cargo.toml
|
||||
cargo msrv verify --manifest-path crypto/dalek-ff-group/Cargo.toml
|
||||
cargo msrv verify --manifest-path crypto/ed448/Cargo.toml
|
||||
|
||||
cargo msrv verify --manifest-path crypto/multiexp/Cargo.toml
|
||||
|
||||
cargo msrv verify --manifest-path crypto/dleq/Cargo.toml
|
||||
cargo msrv verify --manifest-path crypto/ciphersuite/Cargo.toml
|
||||
cargo msrv verify --manifest-path crypto/schnorr/Cargo.toml
|
||||
|
||||
cargo msrv verify --manifest-path crypto/evrf/generalized-bulletproofs/Cargo.toml
|
||||
cargo msrv verify --manifest-path crypto/evrf/circuit-abstraction/Cargo.toml
|
||||
cargo msrv verify --manifest-path crypto/evrf/divisors/Cargo.toml
|
||||
cargo msrv verify --manifest-path crypto/evrf/ec-gadgets/Cargo.toml
|
||||
cargo msrv verify --manifest-path crypto/evrf/embedwards25519/Cargo.toml
|
||||
cargo msrv verify --manifest-path crypto/evrf/secq256k1/Cargo.toml
|
||||
|
||||
cargo msrv verify --manifest-path crypto/dkg/Cargo.toml
|
||||
cargo msrv verify --manifest-path crypto/frost/Cargo.toml
|
||||
cargo msrv verify --manifest-path crypto/schnorrkel/Cargo.toml
|
||||
|
||||
msrv-networks:
|
||||
name: Run cargo msrv on networks
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@3df4ab11eba7bda6032a0b82a6bb43b11571feac
|
||||
|
||||
- name: Install Build Dependencies
|
||||
uses: ./.github/actions/build-dependencies
|
||||
|
||||
- name: Install cargo msrv
|
||||
run: cargo install --locked cargo-msrv
|
||||
|
||||
- name: Run cargo msrv on networks
|
||||
run: |
|
||||
cargo msrv verify --manifest-path networks/bitcoin/Cargo.toml
|
||||
|
||||
cargo msrv verify --manifest-path networks/ethereum/build-contracts/Cargo.toml
|
||||
cargo msrv verify --manifest-path networks/ethereum/schnorr/Cargo.toml
|
||||
cargo msrv verify --manifest-path networks/ethereum/alloy-simple-request-transport/Cargo.toml
|
||||
cargo msrv verify --manifest-path networks/ethereum/relayer/Cargo.toml --features parity-db
|
||||
|
||||
cargo msrv verify --manifest-path networks/monero/io/Cargo.toml
|
||||
cargo msrv verify --manifest-path networks/monero/generators/Cargo.toml
|
||||
cargo msrv verify --manifest-path networks/monero/primitives/Cargo.toml
|
||||
cargo msrv verify --manifest-path networks/monero/ringct/mlsag/Cargo.toml
|
||||
cargo msrv verify --manifest-path networks/monero/ringct/clsag/Cargo.toml
|
||||
cargo msrv verify --manifest-path networks/monero/ringct/borromean/Cargo.toml
|
||||
cargo msrv verify --manifest-path networks/monero/ringct/bulletproofs/Cargo.toml
|
||||
cargo msrv verify --manifest-path networks/monero/Cargo.toml
|
||||
cargo msrv verify --manifest-path networks/monero/rpc/Cargo.toml
|
||||
cargo msrv verify --manifest-path networks/monero/rpc/simple-request/Cargo.toml
|
||||
cargo msrv verify --manifest-path networks/monero/wallet/address/Cargo.toml
|
||||
cargo msrv verify --manifest-path networks/monero/wallet/Cargo.toml
|
||||
cargo msrv verify --manifest-path networks/monero/verify-chain/Cargo.toml
|
||||
|
||||
msrv-message-queue:
|
||||
name: Run cargo msrv on message-queue
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@3df4ab11eba7bda6032a0b82a6bb43b11571feac
|
||||
|
||||
- name: Install Build Dependencies
|
||||
uses: ./.github/actions/build-dependencies
|
||||
|
||||
- name: Install cargo msrv
|
||||
run: cargo install --locked cargo-msrv
|
||||
|
||||
- name: Run cargo msrv on message-queue
|
||||
run: |
|
||||
cargo msrv verify --manifest-path message-queue/Cargo.toml --features parity-db
|
||||
|
||||
msrv-processor:
|
||||
name: Run cargo msrv on processor
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@3df4ab11eba7bda6032a0b82a6bb43b11571feac
|
||||
|
||||
- name: Install Build Dependencies
|
||||
uses: ./.github/actions/build-dependencies
|
||||
|
||||
- name: Install cargo msrv
|
||||
run: cargo install --locked cargo-msrv
|
||||
|
||||
- name: Run cargo msrv on processor
|
||||
run: |
|
||||
cargo msrv verify --manifest-path processor/view-keys/Cargo.toml
|
||||
|
||||
cargo msrv verify --manifest-path processor/primitives/Cargo.toml
|
||||
cargo msrv verify --manifest-path processor/messages/Cargo.toml
|
||||
|
||||
cargo msrv verify --manifest-path processor/scanner/Cargo.toml
|
||||
|
||||
cargo msrv verify --manifest-path processor/scheduler/primitives/Cargo.toml
|
||||
cargo msrv verify --manifest-path processor/scheduler/smart-contract/Cargo.toml
|
||||
cargo msrv verify --manifest-path processor/scheduler/utxo/primitives/Cargo.toml
|
||||
cargo msrv verify --manifest-path processor/scheduler/utxo/standard/Cargo.toml
|
||||
cargo msrv verify --manifest-path processor/scheduler/utxo/transaction-chaining/Cargo.toml
|
||||
|
||||
cargo msrv verify --manifest-path processor/key-gen/Cargo.toml
|
||||
cargo msrv verify --manifest-path processor/frost-attempt-manager/Cargo.toml
|
||||
cargo msrv verify --manifest-path processor/signers/Cargo.toml
|
||||
cargo msrv verify --manifest-path processor/bin/Cargo.toml --features parity-db
|
||||
|
||||
cargo msrv verify --manifest-path processor/bitcoin/Cargo.toml
|
||||
|
||||
cargo msrv verify --manifest-path processor/ethereum/primitives/Cargo.toml
|
||||
cargo msrv verify --manifest-path processor/ethereum/test-primitives/Cargo.toml
|
||||
cargo msrv verify --manifest-path processor/ethereum/erc20/Cargo.toml
|
||||
cargo msrv verify --manifest-path processor/ethereum/deployer/Cargo.toml
|
||||
cargo msrv verify --manifest-path processor/ethereum/router/Cargo.toml
|
||||
cargo msrv verify --manifest-path processor/ethereum/Cargo.toml
|
||||
|
||||
cargo msrv verify --manifest-path processor/monero/Cargo.toml
|
||||
|
||||
msrv-coordinator:
|
||||
name: Run cargo msrv on coordinator
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@3df4ab11eba7bda6032a0b82a6bb43b11571feac
|
||||
|
||||
- name: Install Build Dependencies
|
||||
uses: ./.github/actions/build-dependencies
|
||||
|
||||
- name: Install cargo msrv
|
||||
run: cargo install --locked cargo-msrv
|
||||
|
||||
- name: Run cargo msrv on coordinator
|
||||
run: |
|
||||
cargo msrv verify --manifest-path coordinator/tributary-sdk/tendermint/Cargo.toml
|
||||
cargo msrv verify --manifest-path coordinator/tributary-sdk/Cargo.toml
|
||||
cargo msrv verify --manifest-path coordinator/cosign/Cargo.toml
|
||||
cargo msrv verify --manifest-path coordinator/substrate/Cargo.toml
|
||||
cargo msrv verify --manifest-path coordinator/tributary/Cargo.toml
|
||||
cargo msrv verify --manifest-path coordinator/p2p/Cargo.toml
|
||||
cargo msrv verify --manifest-path coordinator/p2p/libp2p/Cargo.toml
|
||||
cargo msrv verify --manifest-path coordinator/Cargo.toml
|
||||
|
||||
msrv-substrate:
|
||||
name: Run cargo msrv on substrate
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@3df4ab11eba7bda6032a0b82a6bb43b11571feac
|
||||
|
||||
- name: Install Build Dependencies
|
||||
uses: ./.github/actions/build-dependencies
|
||||
|
||||
- name: Install cargo msrv
|
||||
run: cargo install --locked cargo-msrv
|
||||
|
||||
- name: Run cargo msrv on substrate
|
||||
run: |
|
||||
cargo msrv verify --manifest-path substrate/primitives/Cargo.toml
|
||||
|
||||
cargo msrv verify --manifest-path substrate/coins/primitives/Cargo.toml
|
||||
cargo msrv verify --manifest-path substrate/coins/pallet/Cargo.toml
|
||||
|
||||
cargo msrv verify --manifest-path substrate/dex/pallet/Cargo.toml
|
||||
|
||||
cargo msrv verify --manifest-path substrate/economic-security/pallet/Cargo.toml
|
||||
|
||||
cargo msrv verify --manifest-path substrate/genesis-liquidity/primitives/Cargo.toml
|
||||
cargo msrv verify --manifest-path substrate/genesis-liquidity/pallet/Cargo.toml
|
||||
|
||||
cargo msrv verify --manifest-path substrate/in-instructions/primitives/Cargo.toml
|
||||
cargo msrv verify --manifest-path substrate/in-instructions/pallet/Cargo.toml
|
||||
|
||||
cargo msrv verify --manifest-path substrate/validator-sets/pallet/Cargo.toml
|
||||
cargo msrv verify --manifest-path substrate/validator-sets/primitives/Cargo.toml
|
||||
|
||||
cargo msrv verify --manifest-path substrate/emissions/primitives/Cargo.toml
|
||||
cargo msrv verify --manifest-path substrate/emissions/pallet/Cargo.toml
|
||||
|
||||
cargo msrv verify --manifest-path substrate/signals/primitives/Cargo.toml
|
||||
cargo msrv verify --manifest-path substrate/signals/pallet/Cargo.toml
|
||||
|
||||
cargo msrv verify --manifest-path substrate/abi/Cargo.toml
|
||||
cargo msrv verify --manifest-path substrate/client/Cargo.toml
|
||||
|
||||
cargo msrv verify --manifest-path substrate/runtime/Cargo.toml
|
||||
cargo msrv verify --manifest-path substrate/node/Cargo.toml
|
||||
|
||||
msrv-orchestration:
|
||||
name: Run cargo msrv on orchestration
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@3df4ab11eba7bda6032a0b82a6bb43b11571feac
|
||||
|
||||
- name: Install Build Dependencies
|
||||
uses: ./.github/actions/build-dependencies
|
||||
|
||||
- name: Install cargo msrv
|
||||
run: cargo install --locked cargo-msrv
|
||||
|
||||
- name: Run cargo msrv on message-queue
|
||||
run: |
|
||||
cargo msrv verify --manifest-path orchestration/Cargo.toml
|
||||
|
||||
msrv-mini:
|
||||
name: Run cargo msrv on mini
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@3df4ab11eba7bda6032a0b82a6bb43b11571feac
|
||||
|
||||
- name: Install Build Dependencies
|
||||
uses: ./.github/actions/build-dependencies
|
||||
|
||||
- name: Install cargo msrv
|
||||
run: cargo install --locked cargo-msrv
|
||||
|
||||
- name: Run cargo msrv on mini
|
||||
run: |
|
||||
cargo msrv verify --manifest-path mini/Cargo.toml
|
||||
13
.github/workflows/networks-tests.yml
vendored
13
.github/workflows/networks-tests.yml
vendored
@@ -34,16 +34,3 @@ jobs:
|
||||
-p ethereum-schnorr-contract \
|
||||
-p alloy-simple-request-transport \
|
||||
-p serai-ethereum-relayer \
|
||||
-p monero-io \
|
||||
-p monero-generators \
|
||||
-p monero-primitives \
|
||||
-p monero-mlsag \
|
||||
-p monero-clsag \
|
||||
-p monero-borromean \
|
||||
-p monero-bulletproofs \
|
||||
-p monero-serai \
|
||||
-p monero-rpc \
|
||||
-p monero-simple-request-rpc \
|
||||
-p monero-address \
|
||||
-p monero-wallet \
|
||||
-p monero-serai-verify-chain
|
||||
|
||||
14
.github/workflows/no-std.yml
vendored
14
.github/workflows/no-std.yml
vendored
@@ -28,8 +28,18 @@ jobs:
|
||||
- name: Install Build Dependencies
|
||||
uses: ./.github/actions/build-dependencies
|
||||
|
||||
- name: Get nightly version to use
|
||||
id: nightly
|
||||
shell: bash
|
||||
run: echo "version=$(cat .github/nightly-version)" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Install RISC-V Toolchain
|
||||
run: sudo apt update && sudo apt install -y gcc-riscv64-unknown-elf gcc-multilib && rustup target add riscv32imac-unknown-none-elf
|
||||
run: |
|
||||
sudo apt update
|
||||
sudo apt install -y gcc-riscv64-unknown-elf gcc-multilib
|
||||
rustup toolchain install ${{ steps.nightly.outputs.version }} --profile minimal --component rust-src --target riscv32imac-unknown-none-elf
|
||||
|
||||
- name: Verify no-std builds
|
||||
run: CFLAGS=-I/usr/include cargo build --target riscv32imac-unknown-none-elf -p serai-no-std-tests
|
||||
run: |
|
||||
CFLAGS=-I/usr/include cargo +${{ steps.nightly.outputs.version }} build --target riscv32imac-unknown-none-elf -Z build-std=core -p serai-no-std-tests
|
||||
CFLAGS=-I/usr/include cargo +${{ steps.nightly.outputs.version }} build --target riscv32imac-unknown-none-elf -Z build-std=core,alloc -p serai-no-std-tests --features "alloc"
|
||||
|
||||
12
.github/workflows/pages.yml
vendored
12
.github/workflows/pages.yml
vendored
@@ -46,16 +46,16 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
uses: actions/checkout@3df4ab11eba7bda6032a0b82a6bb43b11571feac
|
||||
- name: Setup Ruby
|
||||
uses: ruby/setup-ruby@v1
|
||||
uses: ruby/setup-ruby@44511735964dcb71245e7e55f72539531f7bc0eb
|
||||
with:
|
||||
bundler-cache: true
|
||||
cache-version: 0
|
||||
working-directory: "${{ github.workspace }}/docs"
|
||||
- name: Setup Pages
|
||||
id: pages
|
||||
uses: actions/configure-pages@v3
|
||||
uses: actions/configure-pages@983d7736d9b0ae728b81ab479565c72886d7745b
|
||||
- name: Build with Jekyll
|
||||
run: cd ${{ github.workspace }}/docs && bundle exec jekyll build --baseurl "${{ steps.pages.outputs.base_path }}"
|
||||
env:
|
||||
@@ -69,12 +69,12 @@ jobs:
|
||||
uses: ./.github/actions/build-dependencies
|
||||
- name: Buld Rust docs
|
||||
run: |
|
||||
rustup toolchain install ${{ steps.nightly.outputs.version }} --profile minimal -t wasm32-unknown-unknown -c rust-docs
|
||||
rustup toolchain install ${{ steps.nightly.outputs.version }} --profile minimal -t wasm32v1-none -c rust-docs -c rust-src
|
||||
RUSTDOCFLAGS="--cfg docsrs" cargo +${{ steps.nightly.outputs.version }} doc --workspace --all-features
|
||||
mv target/doc docs/_site/rust
|
||||
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-pages-artifact@v3
|
||||
uses: actions/upload-pages-artifact@7b1f4a764d45c48632c6b24a0339c27f5614fb0b
|
||||
with:
|
||||
path: "docs/_site/"
|
||||
|
||||
@@ -88,4 +88,4 @@ jobs:
|
||||
steps:
|
||||
- name: Deploy to GitHub Pages
|
||||
id: deployment
|
||||
uses: actions/deploy-pages@v4
|
||||
uses: actions/deploy-pages@d6db90164ac5ed86f2b6aed7e0febac5b3c0c03e
|
||||
|
||||
6040
Cargo.lock
generated
6040
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
140
Cargo.toml
140
Cargo.toml
@@ -2,19 +2,18 @@
|
||||
resolver = "2"
|
||||
members = [
|
||||
# Version patches
|
||||
"patches/parking_lot_core",
|
||||
"patches/parking_lot",
|
||||
"patches/zstd",
|
||||
"patches/rocksdb",
|
||||
|
||||
# std patches
|
||||
"patches/matches",
|
||||
"patches/is-terminal",
|
||||
|
||||
# Rewrites/redirects
|
||||
"patches/option-ext",
|
||||
"patches/directories-next",
|
||||
|
||||
# monero-oxide expects ciphersuite, yet the ciphersuite in-tree here has breaking changes
|
||||
# This re-exports the in-tree ciphersuite _without_ changes breaking to monero-oxide
|
||||
# Not included in workspace to prevent having two crates with the same name (an error)
|
||||
# "patches/ciphersuite",
|
||||
|
||||
"common/std-shims",
|
||||
"common/zalloc",
|
||||
"common/patchable-async-sleep",
|
||||
@@ -29,19 +28,21 @@ members = [
|
||||
"crypto/dalek-ff-group",
|
||||
"crypto/ed448",
|
||||
"crypto/ciphersuite",
|
||||
"crypto/ciphersuite/kp256",
|
||||
|
||||
"crypto/multiexp",
|
||||
"crypto/schnorr",
|
||||
"crypto/dleq",
|
||||
|
||||
"crypto/evrf/secq256k1",
|
||||
"crypto/evrf/embedwards25519",
|
||||
"crypto/evrf/generalized-bulletproofs",
|
||||
"crypto/evrf/circuit-abstraction",
|
||||
"crypto/evrf/divisors",
|
||||
"crypto/evrf/ec-gadgets",
|
||||
"crypto/prime-field",
|
||||
"crypto/short-weierstrass",
|
||||
"crypto/secq256k1",
|
||||
"crypto/embedwards25519",
|
||||
|
||||
"crypto/dkg",
|
||||
"crypto/dkg/recovery",
|
||||
"crypto/dkg/dealer",
|
||||
"crypto/dkg/musig",
|
||||
"crypto/dkg/evrf",
|
||||
"crypto/frost",
|
||||
"crypto/schnorrkel",
|
||||
|
||||
@@ -52,20 +53,6 @@ members = [
|
||||
"networks/ethereum/alloy-simple-request-transport",
|
||||
"networks/ethereum/relayer",
|
||||
|
||||
"networks/monero/io",
|
||||
"networks/monero/generators",
|
||||
"networks/monero/primitives",
|
||||
"networks/monero/ringct/mlsag",
|
||||
"networks/monero/ringct/clsag",
|
||||
"networks/monero/ringct/borromean",
|
||||
"networks/monero/ringct/bulletproofs",
|
||||
"networks/monero",
|
||||
"networks/monero/rpc",
|
||||
"networks/monero/rpc/simple-request",
|
||||
"networks/monero/wallet/address",
|
||||
"networks/monero/wallet",
|
||||
"networks/monero/verify-chain",
|
||||
|
||||
"message-queue",
|
||||
|
||||
"processor/messages",
|
||||
@@ -103,31 +90,17 @@ members = [
|
||||
"coordinator",
|
||||
|
||||
"substrate/primitives",
|
||||
|
||||
"substrate/coins/primitives",
|
||||
"substrate/coins/pallet",
|
||||
|
||||
"substrate/dex/pallet",
|
||||
|
||||
"substrate/validator-sets/primitives",
|
||||
"substrate/validator-sets/pallet",
|
||||
|
||||
"substrate/genesis-liquidity/primitives",
|
||||
"substrate/genesis-liquidity/pallet",
|
||||
|
||||
"substrate/emissions/primitives",
|
||||
"substrate/emissions/pallet",
|
||||
|
||||
"substrate/economic-security/pallet",
|
||||
|
||||
"substrate/in-instructions/primitives",
|
||||
"substrate/in-instructions/pallet",
|
||||
|
||||
"substrate/signals/primitives",
|
||||
"substrate/signals/pallet",
|
||||
|
||||
"substrate/abi",
|
||||
|
||||
"substrate/coins",
|
||||
"substrate/validator-sets",
|
||||
"substrate/signals",
|
||||
"substrate/dex",
|
||||
"substrate/genesis-liquidity",
|
||||
"substrate/economic-security",
|
||||
"substrate/emissions",
|
||||
"substrate/in-instructions",
|
||||
|
||||
"substrate/runtime",
|
||||
"substrate/node",
|
||||
|
||||
@@ -147,56 +120,74 @@ members = [
|
||||
"tests/reproducible-runtime",
|
||||
]
|
||||
|
||||
[profile.dev.package]
|
||||
# Always compile Monero (and a variety of dependencies) with optimizations due
|
||||
# to the extensive operations required for Bulletproofs
|
||||
[profile.dev.package]
|
||||
subtle = { opt-level = 3 }
|
||||
|
||||
sha3 = { opt-level = 3 }
|
||||
blake2 = { opt-level = 3 }
|
||||
|
||||
ff = { opt-level = 3 }
|
||||
group = { opt-level = 3 }
|
||||
|
||||
crypto-bigint = { opt-level = 3 }
|
||||
secp256k1 = { opt-level = 3 }
|
||||
curve25519-dalek = { opt-level = 3 }
|
||||
dalek-ff-group = { opt-level = 3 }
|
||||
minimal-ed448 = { opt-level = 3 }
|
||||
|
||||
multiexp = { opt-level = 3 }
|
||||
|
||||
secq256k1 = { opt-level = 3 }
|
||||
embedwards25519 = { opt-level = 3 }
|
||||
generalized-bulletproofs = { opt-level = 3 }
|
||||
generalized-bulletproofs-circuit-abstraction = { opt-level = 3 }
|
||||
ec-divisors = { opt-level = 3 }
|
||||
generalized-bulletproofs-ec-gadgets = { opt-level = 3 }
|
||||
|
||||
dkg = { opt-level = 3 }
|
||||
|
||||
monero-generators = { opt-level = 3 }
|
||||
monero-borromean = { opt-level = 3 }
|
||||
monero-bulletproofs = { opt-level = 3 }
|
||||
monero-mlsag = { opt-level = 3 }
|
||||
monero-clsag = { opt-level = 3 }
|
||||
monero-oxide = { opt-level = 3 }
|
||||
|
||||
# Always compile the eVRF DKG tree with optimizations as well
|
||||
secp256k1 = { opt-level = 3 }
|
||||
secq256k1 = { opt-level = 3 }
|
||||
embedwards25519 = { opt-level = 3 }
|
||||
generalized-bulletproofs = { opt-level = 3 }
|
||||
generalized-bulletproofs-circuit-abstraction = { opt-level = 3 }
|
||||
generalized-bulletproofs-ec-gadgets = { opt-level = 3 }
|
||||
|
||||
# revm also effectively requires being built with optimizations
|
||||
revm = { opt-level = 3 }
|
||||
revm-bytecode = { opt-level = 3 }
|
||||
revm-context = { opt-level = 3 }
|
||||
revm-context-interface = { opt-level = 3 }
|
||||
revm-database = { opt-level = 3 }
|
||||
revm-database-interface = { opt-level = 3 }
|
||||
revm-handler = { opt-level = 3 }
|
||||
revm-inspector = { opt-level = 3 }
|
||||
revm-interpreter = { opt-level = 3 }
|
||||
revm-precompile = { opt-level = 3 }
|
||||
revm-primitives = { opt-level = 3 }
|
||||
revm-state = { opt-level = 3 }
|
||||
|
||||
[profile.release]
|
||||
panic = "unwind"
|
||||
overflow-checks = true
|
||||
|
||||
[patch.crates-io]
|
||||
# Dependencies from monero-oxide which originate from within our own tree
|
||||
std-shims = { path = "common/std-shims" }
|
||||
simple-request = { path = "common/request" }
|
||||
multiexp = { path = "crypto/multiexp" }
|
||||
flexible-transcript = { path = "crypto/transcript" }
|
||||
ciphersuite = { path = "patches/ciphersuite" }
|
||||
dalek-ff-group = { path = "crypto/dalek-ff-group" }
|
||||
minimal-ed448 = { path = "crypto/ed448" }
|
||||
modular-frost = { path = "crypto/frost" }
|
||||
|
||||
# https://github.com/rust-lang-nursery/lazy-static.rs/issues/201
|
||||
lazy_static = { git = "https://github.com/rust-lang-nursery/lazy-static.rs", rev = "5735630d46572f1e5377c8f2ba0f79d18f53b10c" }
|
||||
|
||||
parking_lot_core = { path = "patches/parking_lot_core" }
|
||||
parking_lot = { path = "patches/parking_lot" }
|
||||
# wasmtime pulls in an old version for this
|
||||
zstd = { path = "patches/zstd" }
|
||||
# Needed for WAL compression
|
||||
rocksdb = { path = "patches/rocksdb" }
|
||||
|
||||
# is-terminal now has an std-based solution with an equivalent API
|
||||
is-terminal = { path = "patches/is-terminal" }
|
||||
# So does matches
|
||||
matches = { path = "patches/matches" }
|
||||
|
||||
# directories-next was created because directories was unmaintained
|
||||
# directories-next is now unmaintained while directories is maintained
|
||||
# The directories author pulls in ridiculously pointless crates and prefers
|
||||
@@ -205,7 +196,16 @@ matches = { path = "patches/matches" }
|
||||
option-ext = { path = "patches/option-ext" }
|
||||
directories-next = { path = "patches/directories-next" }
|
||||
|
||||
# Patch to include `FromUniformBytes<64>` over Scalar
|
||||
k256 = { git = "https://github.com/kayabaNerve/elliptic-curves", rev = "4994c9ab163781a88cd4a49beae812a89a44e8c3" }
|
||||
p256 = { git = "https://github.com/kayabaNerve/elliptic-curves", rev = "4994c9ab163781a88cd4a49beae812a89a44e8c3" }
|
||||
|
||||
# https://github.com/RustCrypto/hybrid-array/issues/131
|
||||
hybrid-array = { git = "https://github.com/kayabaNerve/hybrid-array", rev = "8caa508976c93696a67f40734537c91be7cecd96" }
|
||||
|
||||
[workspace.lints.clippy]
|
||||
incompatible_msrv = "allow" # Manually verified with a GitHub workflow
|
||||
manual_is_multiple_of = "allow"
|
||||
unwrap_or_default = "allow"
|
||||
map_unwrap_or = "allow"
|
||||
needless_continue = "allow"
|
||||
|
||||
@@ -59,7 +59,6 @@ issued at the discretion of the Immunefi program managers.
|
||||
- [Website](https://serai.exchange/): https://serai.exchange/
|
||||
- [Immunefi](https://immunefi.com/bounty/serai/): https://immunefi.com/bounty/serai/
|
||||
- [Twitter](https://twitter.com/SeraiDEX): https://twitter.com/SeraiDEX
|
||||
- [Mastodon](https://cryptodon.lol/@serai): https://cryptodon.lol/@serai
|
||||
- [Discord](https://discord.gg/mpEUtJR3vz): https://discord.gg/mpEUtJR3vz
|
||||
- [Matrix](https://matrix.to/#/#serai:matrix.org): https://matrix.to/#/#serai:matrix.org
|
||||
- [Reddit](https://www.reddit.com/r/SeraiDEX/): https://www.reddit.com/r/SeraiDEX/
|
||||
|
||||
Binary file not shown.
@@ -1,427 +0,0 @@
|
||||
Attribution-ShareAlike 4.0 International
|
||||
|
||||
=======================================================================
|
||||
|
||||
Creative Commons Corporation ("Creative Commons") is not a law firm and
|
||||
does not provide legal services or legal advice. Distribution of
|
||||
Creative Commons public licenses does not create a lawyer-client or
|
||||
other relationship. Creative Commons makes its licenses and related
|
||||
information available on an "as-is" basis. Creative Commons gives no
|
||||
warranties regarding its licenses, any material licensed under their
|
||||
terms and conditions, or any related information. Creative Commons
|
||||
disclaims all liability for damages resulting from their use to the
|
||||
fullest extent possible.
|
||||
|
||||
Using Creative Commons Public Licenses
|
||||
|
||||
Creative Commons public licenses provide a standard set of terms and
|
||||
conditions that creators and other rights holders may use to share
|
||||
original works of authorship and other material subject to copyright
|
||||
and certain other rights specified in the public license below. The
|
||||
following considerations are for informational purposes only, are not
|
||||
exhaustive, and do not form part of our licenses.
|
||||
|
||||
Considerations for licensors: Our public licenses are
|
||||
intended for use by those authorized to give the public
|
||||
permission to use material in ways otherwise restricted by
|
||||
copyright and certain other rights. Our licenses are
|
||||
irrevocable. Licensors should read and understand the terms
|
||||
and conditions of the license they choose before applying it.
|
||||
Licensors should also secure all rights necessary before
|
||||
applying our licenses so that the public can reuse the
|
||||
material as expected. Licensors should clearly mark any
|
||||
material not subject to the license. This includes other CC-
|
||||
licensed material, or material used under an exception or
|
||||
limitation to copyright. More considerations for licensors:
|
||||
wiki.creativecommons.org/Considerations_for_licensors
|
||||
|
||||
Considerations for the public: By using one of our public
|
||||
licenses, a licensor grants the public permission to use the
|
||||
licensed material under specified terms and conditions. If
|
||||
the licensor's permission is not necessary for any reason--for
|
||||
example, because of any applicable exception or limitation to
|
||||
copyright--then that use is not regulated by the license. Our
|
||||
licenses grant only permissions under copyright and certain
|
||||
other rights that a licensor has authority to grant. Use of
|
||||
the licensed material may still be restricted for other
|
||||
reasons, including because others have copyright or other
|
||||
rights in the material. A licensor may make special requests,
|
||||
such as asking that all changes be marked or described.
|
||||
Although not required by our licenses, you are encouraged to
|
||||
respect those requests where reasonable. More considerations
|
||||
for the public:
|
||||
wiki.creativecommons.org/Considerations_for_licensees
|
||||
|
||||
=======================================================================
|
||||
|
||||
Creative Commons Attribution-ShareAlike 4.0 International Public
|
||||
License
|
||||
|
||||
By exercising the Licensed Rights (defined below), You accept and agree
|
||||
to be bound by the terms and conditions of this Creative Commons
|
||||
Attribution-ShareAlike 4.0 International Public License ("Public
|
||||
License"). To the extent this Public License may be interpreted as a
|
||||
contract, You are granted the Licensed Rights in consideration of Your
|
||||
acceptance of these terms and conditions, and the Licensor grants You
|
||||
such rights in consideration of benefits the Licensor receives from
|
||||
making the Licensed Material available under these terms and
|
||||
conditions.
|
||||
|
||||
|
||||
Section 1 -- Definitions.
|
||||
|
||||
a. Adapted Material means material subject to Copyright and Similar
|
||||
Rights that is derived from or based upon the Licensed Material
|
||||
and in which the Licensed Material is translated, altered,
|
||||
arranged, transformed, or otherwise modified in a manner requiring
|
||||
permission under the Copyright and Similar Rights held by the
|
||||
Licensor. For purposes of this Public License, where the Licensed
|
||||
Material is a musical work, performance, or sound recording,
|
||||
Adapted Material is always produced where the Licensed Material is
|
||||
synched in timed relation with a moving image.
|
||||
|
||||
b. Adapter's License means the license You apply to Your Copyright
|
||||
and Similar Rights in Your contributions to Adapted Material in
|
||||
accordance with the terms and conditions of this Public License.
|
||||
|
||||
c. BY-SA Compatible License means a license listed at
|
||||
creativecommons.org/compatiblelicenses, approved by Creative
|
||||
Commons as essentially the equivalent of this Public License.
|
||||
|
||||
d. Copyright and Similar Rights means copyright and/or similar rights
|
||||
closely related to copyright including, without limitation,
|
||||
performance, broadcast, sound recording, and Sui Generis Database
|
||||
Rights, without regard to how the rights are labeled or
|
||||
categorized. For purposes of this Public License, the rights
|
||||
specified in Section 2(b)(1)-(2) are not Copyright and Similar
|
||||
Rights.
|
||||
|
||||
e. Effective Technological Measures means those measures that, in the
|
||||
absence of proper authority, may not be circumvented under laws
|
||||
fulfilling obligations under Article 11 of the WIPO Copyright
|
||||
Treaty adopted on December 20, 1996, and/or similar international
|
||||
agreements.
|
||||
|
||||
f. Exceptions and Limitations means fair use, fair dealing, and/or
|
||||
any other exception or limitation to Copyright and Similar Rights
|
||||
that applies to Your use of the Licensed Material.
|
||||
|
||||
g. License Elements means the license attributes listed in the name
|
||||
of a Creative Commons Public License. The License Elements of this
|
||||
Public License are Attribution and ShareAlike.
|
||||
|
||||
h. Licensed Material means the artistic or literary work, database,
|
||||
or other material to which the Licensor applied this Public
|
||||
License.
|
||||
|
||||
i. Licensed Rights means the rights granted to You subject to the
|
||||
terms and conditions of this Public License, which are limited to
|
||||
all Copyright and Similar Rights that apply to Your use of the
|
||||
Licensed Material and that the Licensor has authority to license.
|
||||
|
||||
j. Licensor means the individual(s) or entity(ies) granting rights
|
||||
under this Public License.
|
||||
|
||||
k. Share means to provide material to the public by any means or
|
||||
process that requires permission under the Licensed Rights, such
|
||||
as reproduction, public display, public performance, distribution,
|
||||
dissemination, communication, or importation, and to make material
|
||||
available to the public including in ways that members of the
|
||||
public may access the material from a place and at a time
|
||||
individually chosen by them.
|
||||
|
||||
l. Sui Generis Database Rights means rights other than copyright
|
||||
resulting from Directive 96/9/EC of the European Parliament and of
|
||||
the Council of 11 March 1996 on the legal protection of databases,
|
||||
as amended and/or succeeded, as well as other essentially
|
||||
equivalent rights anywhere in the world.
|
||||
|
||||
m. You means the individual or entity exercising the Licensed Rights
|
||||
under this Public License. Your has a corresponding meaning.
|
||||
|
||||
|
||||
Section 2 -- Scope.
|
||||
|
||||
a. License grant.
|
||||
|
||||
1. Subject to the terms and conditions of this Public License,
|
||||
the Licensor hereby grants You a worldwide, royalty-free,
|
||||
non-sublicensable, non-exclusive, irrevocable license to
|
||||
exercise the Licensed Rights in the Licensed Material to:
|
||||
|
||||
a. reproduce and Share the Licensed Material, in whole or
|
||||
in part; and
|
||||
|
||||
b. produce, reproduce, and Share Adapted Material.
|
||||
|
||||
2. Exceptions and Limitations. For the avoidance of doubt, where
|
||||
Exceptions and Limitations apply to Your use, this Public
|
||||
License does not apply, and You do not need to comply with
|
||||
its terms and conditions.
|
||||
|
||||
3. Term. The term of this Public License is specified in Section
|
||||
6(a).
|
||||
|
||||
4. Media and formats; technical modifications allowed. The
|
||||
Licensor authorizes You to exercise the Licensed Rights in
|
||||
all media and formats whether now known or hereafter created,
|
||||
and to make technical modifications necessary to do so. The
|
||||
Licensor waives and/or agrees not to assert any right or
|
||||
authority to forbid You from making technical modifications
|
||||
necessary to exercise the Licensed Rights, including
|
||||
technical modifications necessary to circumvent Effective
|
||||
Technological Measures. For purposes of this Public License,
|
||||
simply making modifications authorized by this Section 2(a)
|
||||
(4) never produces Adapted Material.
|
||||
|
||||
5. Downstream recipients.
|
||||
|
||||
a. Offer from the Licensor -- Licensed Material. Every
|
||||
recipient of the Licensed Material automatically
|
||||
receives an offer from the Licensor to exercise the
|
||||
Licensed Rights under the terms and conditions of this
|
||||
Public License.
|
||||
|
||||
b. Additional offer from the Licensor -- Adapted Material.
|
||||
Every recipient of Adapted Material from You
|
||||
automatically receives an offer from the Licensor to
|
||||
exercise the Licensed Rights in the Adapted Material
|
||||
under the conditions of the Adapter's License You apply.
|
||||
|
||||
c. No downstream restrictions. You may not offer or impose
|
||||
any additional or different terms or conditions on, or
|
||||
apply any Effective Technological Measures to, the
|
||||
Licensed Material if doing so restricts exercise of the
|
||||
Licensed Rights by any recipient of the Licensed
|
||||
Material.
|
||||
|
||||
6. No endorsement. Nothing in this Public License constitutes or
|
||||
may be construed as permission to assert or imply that You
|
||||
are, or that Your use of the Licensed Material is, connected
|
||||
with, or sponsored, endorsed, or granted official status by,
|
||||
the Licensor or others designated to receive attribution as
|
||||
provided in Section 3(a)(1)(A)(i).
|
||||
|
||||
b. Other rights.
|
||||
|
||||
1. Moral rights, such as the right of integrity, are not
|
||||
licensed under this Public License, nor are publicity,
|
||||
privacy, and/or other similar personality rights; however, to
|
||||
the extent possible, the Licensor waives and/or agrees not to
|
||||
assert any such rights held by the Licensor to the limited
|
||||
extent necessary to allow You to exercise the Licensed
|
||||
Rights, but not otherwise.
|
||||
|
||||
2. Patent and trademark rights are not licensed under this
|
||||
Public License.
|
||||
|
||||
3. To the extent possible, the Licensor waives any right to
|
||||
collect royalties from You for the exercise of the Licensed
|
||||
Rights, whether directly or through a collecting society
|
||||
under any voluntary or waivable statutory or compulsory
|
||||
licensing scheme. In all other cases the Licensor expressly
|
||||
reserves any right to collect such royalties.
|
||||
|
||||
|
||||
Section 3 -- License Conditions.
|
||||
|
||||
Your exercise of the Licensed Rights is expressly made subject to the
|
||||
following conditions.
|
||||
|
||||
a. Attribution.
|
||||
|
||||
1. If You Share the Licensed Material (including in modified
|
||||
form), You must:
|
||||
|
||||
a. retain the following if it is supplied by the Licensor
|
||||
with the Licensed Material:
|
||||
|
||||
i. identification of the creator(s) of the Licensed
|
||||
Material and any others designated to receive
|
||||
attribution, in any reasonable manner requested by
|
||||
the Licensor (including by pseudonym if
|
||||
designated);
|
||||
|
||||
ii. a copyright notice;
|
||||
|
||||
iii. a notice that refers to this Public License;
|
||||
|
||||
iv. a notice that refers to the disclaimer of
|
||||
warranties;
|
||||
|
||||
v. a URI or hyperlink to the Licensed Material to the
|
||||
extent reasonably practicable;
|
||||
|
||||
b. indicate if You modified the Licensed Material and
|
||||
retain an indication of any previous modifications; and
|
||||
|
||||
c. indicate the Licensed Material is licensed under this
|
||||
Public License, and include the text of, or the URI or
|
||||
hyperlink to, this Public License.
|
||||
|
||||
2. You may satisfy the conditions in Section 3(a)(1) in any
|
||||
reasonable manner based on the medium, means, and context in
|
||||
which You Share the Licensed Material. For example, it may be
|
||||
reasonable to satisfy the conditions by providing a URI or
|
||||
hyperlink to a resource that includes the required
|
||||
information.
|
||||
|
||||
3. If requested by the Licensor, You must remove any of the
|
||||
information required by Section 3(a)(1)(A) to the extent
|
||||
reasonably practicable.
|
||||
|
||||
b. ShareAlike.
|
||||
|
||||
In addition to the conditions in Section 3(a), if You Share
|
||||
Adapted Material You produce, the following conditions also apply.
|
||||
|
||||
1. The Adapter's License You apply must be a Creative Commons
|
||||
license with the same License Elements, this version or
|
||||
later, or a BY-SA Compatible License.
|
||||
|
||||
2. You must include the text of, or the URI or hyperlink to, the
|
||||
Adapter's License You apply. You may satisfy this condition
|
||||
in any reasonable manner based on the medium, means, and
|
||||
context in which You Share Adapted Material.
|
||||
|
||||
3. You may not offer or impose any additional or different terms
|
||||
or conditions on, or apply any Effective Technological
|
||||
Measures to, Adapted Material that restrict exercise of the
|
||||
rights granted under the Adapter's License You apply.
|
||||
|
||||
|
||||
Section 4 -- Sui Generis Database Rights.
|
||||
|
||||
Where the Licensed Rights include Sui Generis Database Rights that
|
||||
apply to Your use of the Licensed Material:
|
||||
|
||||
a. for the avoidance of doubt, Section 2(a)(1) grants You the right
|
||||
to extract, reuse, reproduce, and Share all or a substantial
|
||||
portion of the contents of the database;
|
||||
|
||||
b. if You include all or a substantial portion of the database
|
||||
contents in a database in which You have Sui Generis Database
|
||||
Rights, then the database in which You have Sui Generis Database
|
||||
Rights (but not its individual contents) is Adapted Material,
|
||||
|
||||
including for purposes of Section 3(b); and
|
||||
c. You must comply with the conditions in Section 3(a) if You Share
|
||||
all or a substantial portion of the contents of the database.
|
||||
|
||||
For the avoidance of doubt, this Section 4 supplements and does not
|
||||
replace Your obligations under this Public License where the Licensed
|
||||
Rights include other Copyright and Similar Rights.
|
||||
|
||||
|
||||
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
|
||||
|
||||
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
|
||||
EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
|
||||
AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
|
||||
ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
|
||||
IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
|
||||
WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
|
||||
PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
|
||||
ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
|
||||
KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
|
||||
ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
|
||||
|
||||
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
|
||||
TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
|
||||
NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
|
||||
INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
|
||||
COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
|
||||
USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
|
||||
ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
|
||||
DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
|
||||
IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
|
||||
|
||||
c. The disclaimer of warranties and limitation of liability provided
|
||||
above shall be interpreted in a manner that, to the extent
|
||||
possible, most closely approximates an absolute disclaimer and
|
||||
waiver of all liability.
|
||||
|
||||
|
||||
Section 6 -- Term and Termination.
|
||||
|
||||
a. This Public License applies for the term of the Copyright and
|
||||
Similar Rights licensed here. However, if You fail to comply with
|
||||
this Public License, then Your rights under this Public License
|
||||
terminate automatically.
|
||||
|
||||
b. Where Your right to use the Licensed Material has terminated under
|
||||
Section 6(a), it reinstates:
|
||||
|
||||
1. automatically as of the date the violation is cured, provided
|
||||
it is cured within 30 days of Your discovery of the
|
||||
violation; or
|
||||
|
||||
2. upon express reinstatement by the Licensor.
|
||||
|
||||
For the avoidance of doubt, this Section 6(b) does not affect any
|
||||
right the Licensor may have to seek remedies for Your violations
|
||||
of this Public License.
|
||||
|
||||
c. For the avoidance of doubt, the Licensor may also offer the
|
||||
Licensed Material under separate terms or conditions or stop
|
||||
distributing the Licensed Material at any time; however, doing so
|
||||
will not terminate this Public License.
|
||||
|
||||
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
|
||||
License.
|
||||
|
||||
|
||||
Section 7 -- Other Terms and Conditions.
|
||||
|
||||
a. The Licensor shall not be bound by any additional or different
|
||||
terms or conditions communicated by You unless expressly agreed.
|
||||
|
||||
b. Any arrangements, understandings, or agreements regarding the
|
||||
Licensed Material not stated herein are separate from and
|
||||
independent of the terms and conditions of this Public License.
|
||||
|
||||
|
||||
Section 8 -- Interpretation.
|
||||
|
||||
a. For the avoidance of doubt, this Public License does not, and
|
||||
shall not be interpreted to, reduce, limit, restrict, or impose
|
||||
conditions on any use of the Licensed Material that could lawfully
|
||||
be made without permission under this Public License.
|
||||
|
||||
b. To the extent possible, if any provision of this Public License is
|
||||
deemed unenforceable, it shall be automatically reformed to the
|
||||
minimum extent necessary to make it enforceable. If the provision
|
||||
cannot be reformed, it shall be severed from this Public License
|
||||
without affecting the enforceability of the remaining terms and
|
||||
conditions.
|
||||
|
||||
c. No term or condition of this Public License will be waived and no
|
||||
failure to comply consented to unless expressly agreed to by the
|
||||
Licensor.
|
||||
|
||||
d. Nothing in this Public License constitutes or may be interpreted
|
||||
as a limitation upon, or waiver of, any privileges and immunities
|
||||
that apply to the Licensor or You, including from the legal
|
||||
processes of any jurisdiction or authority.
|
||||
|
||||
|
||||
=======================================================================
|
||||
|
||||
Creative Commons is not a party to its public
|
||||
licenses. Notwithstanding, Creative Commons may elect to apply one of
|
||||
its public licenses to material it publishes and in those instances
|
||||
will be considered the “Licensor.” The text of the Creative Commons
|
||||
public licenses is dedicated to the public domain under the CC0 Public
|
||||
Domain Dedication. Except for the limited purpose of indicating that
|
||||
material is shared under a Creative Commons public license or as
|
||||
otherwise permitted by the Creative Commons policies published at
|
||||
creativecommons.org/policies, Creative Commons does not authorize the
|
||||
use of the trademark "Creative Commons" or any other trademark or logo
|
||||
of Creative Commons without its prior written consent including,
|
||||
without limitation, in connection with any unauthorized modifications
|
||||
to any of its public licenses or any other arrangements,
|
||||
understandings, or agreements concerning use of licensed material. For
|
||||
the avoidance of doubt, this paragraph does not form part of the
|
||||
public licenses.
|
||||
|
||||
Creative Commons may be contacted at creativecommons.org.
|
||||
@@ -11,4 +11,4 @@ It is encompassing up to commit 4e0c58464fc4673623938335f06e2e9ea96ca8dd.
|
||||
|
||||
Please see
|
||||
https://github.com/trailofbits/publications/blob/30c4fa3ebf39ff8e4d23ba9567344ec9691697b5/reviews/2025-04-serai-dex-security-review.pdf
|
||||
for provenance.
|
||||
for the actual report.
|
||||
|
||||
@@ -7,7 +7,7 @@ repository = "https://github.com/serai-dex/serai/tree/develop/common/db"
|
||||
authors = ["Luke Parker <lukeparker5132@gmail.com>"]
|
||||
keywords = []
|
||||
edition = "2021"
|
||||
rust-version = "1.71"
|
||||
rust-version = "1.65"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
all-features = true
|
||||
@@ -18,7 +18,7 @@ workspace = true
|
||||
|
||||
[dependencies]
|
||||
parity-db = { version = "0.4", default-features = false, optional = true }
|
||||
rocksdb = { version = "0.23", default-features = false, features = ["zstd"], optional = true }
|
||||
rocksdb = { version = "0.24", default-features = false, features = ["zstd"], optional = true }
|
||||
|
||||
[features]
|
||||
parity-db = ["dep:parity-db"]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2022-2023 Luke Parker
|
||||
Copyright (c) 2022-2025 Luke Parker
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
|
||||
@@ -15,7 +15,7 @@ pub fn serai_db_key(
|
||||
///
|
||||
/// Creates a unit struct and a default implementation for the `key`, `get`, and `set`. The macro
|
||||
/// uses a syntax similar to defining a function. Parameters are concatenated to produce a key,
|
||||
/// they must be `scale` encodable. The return type is used to auto encode and decode the database
|
||||
/// they must be `borsh` serializable. The return type is used to auto (de)serialize the database
|
||||
/// value bytes using `borsh`.
|
||||
///
|
||||
/// # Arguments
|
||||
@@ -54,11 +54,10 @@ macro_rules! create_db {
|
||||
)?;
|
||||
impl$(<$($generic_name: $generic_type),+>)? $field_name$(<$($generic_name),+>)? {
|
||||
pub(crate) fn key($($arg: $arg_type),*) -> Vec<u8> {
|
||||
use scale::Encode;
|
||||
$crate::serai_db_key(
|
||||
stringify!($db_name).as_bytes(),
|
||||
stringify!($field_name).as_bytes(),
|
||||
($($arg),*).encode()
|
||||
&borsh::to_vec(&($($arg),*)).unwrap(),
|
||||
)
|
||||
}
|
||||
pub(crate) fn set(
|
||||
|
||||
2
common/env/Cargo.toml
vendored
2
common/env/Cargo.toml
vendored
@@ -7,7 +7,7 @@ repository = "https://github.com/serai-dex/serai/tree/develop/common/env"
|
||||
authors = ["Luke Parker <lukeparker5132@gmail.com>"]
|
||||
keywords = []
|
||||
edition = "2021"
|
||||
rust-version = "1.71"
|
||||
rust-version = "1.64"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
all-features = true
|
||||
|
||||
2
common/env/LICENSE
vendored
2
common/env/LICENSE
vendored
@@ -1,6 +1,6 @@
|
||||
AGPL-3.0-only license
|
||||
|
||||
Copyright (c) 2023 Luke Parker
|
||||
Copyright (c) 2023-2025 Luke Parker
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License Version 3 as
|
||||
|
||||
@@ -7,7 +7,7 @@ repository = "https://github.com/serai-dex/serai/tree/develop/common/patchable-a
|
||||
authors = ["Luke Parker <lukeparker5132@gmail.com>"]
|
||||
keywords = ["async", "sleep", "tokio", "smol", "async-std"]
|
||||
edition = "2021"
|
||||
rust-version = "1.71"
|
||||
rust-version = "1.70"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
all-features = true
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2024 Luke Parker
|
||||
Copyright (c) 2024-2025 Luke Parker
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2023 Luke Parker
|
||||
Copyright (c) 2023-2025 Luke Parker
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
[package]
|
||||
name = "std-shims"
|
||||
version = "0.1.1"
|
||||
version = "0.1.4"
|
||||
description = "A series of std shims to make alloc more feasible"
|
||||
license = "MIT"
|
||||
repository = "https://github.com/serai-dex/serai/tree/develop/common/std-shims"
|
||||
authors = ["Luke Parker <lukeparker5132@gmail.com>"]
|
||||
keywords = ["nostd", "no_std", "alloc", "io"]
|
||||
edition = "2021"
|
||||
rust-version = "1.80"
|
||||
rust-version = "1.65"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
all-features = true
|
||||
@@ -17,8 +17,9 @@ rustdoc-args = ["--cfg", "docsrs"]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
spin = { version = "0.9", default-features = false, features = ["use_ticket_mutex", "lazy"] }
|
||||
hashbrown = { version = "0.15", default-features = false, features = ["default-hasher", "inline-more"] }
|
||||
rustversion = { version = "1", default-features = false }
|
||||
spin = { version = "0.10", default-features = false, features = ["use_ticket_mutex", "once", "lazy"] }
|
||||
hashbrown = { version = "0.16", default-features = false, features = ["default-hasher", "inline-more"] }
|
||||
|
||||
[features]
|
||||
std = []
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2023 Luke Parker
|
||||
Copyright (c) 2023-2025 Luke Parker
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
|
||||
@@ -3,4 +3,9 @@
|
||||
A crate which passes through to std when the default `std` feature is enabled,
|
||||
yet provides a series of shims when it isn't.
|
||||
|
||||
`HashSet` and `HashMap` are provided via `hashbrown`.
|
||||
No guarantee of one-to-one parity is provided. The shims provided aim to be sufficient for the
|
||||
average case.
|
||||
|
||||
`HashSet` and `HashMap` are provided via `hashbrown`. Synchronization primitives are provided via
|
||||
`spin` (avoiding a requirement on `critical-section`).
|
||||
types are not guaranteed to be
|
||||
|
||||
@@ -11,3 +11,64 @@ pub mod io;
|
||||
pub use alloc::vec;
|
||||
pub use alloc::str;
|
||||
pub use alloc::string;
|
||||
|
||||
pub mod prelude {
|
||||
#[rustversion::before(1.73)]
|
||||
#[doc(hidden)]
|
||||
pub trait StdShimsDivCeil {
|
||||
fn div_ceil(self, rhs: Self) -> Self;
|
||||
}
|
||||
#[rustversion::before(1.73)]
|
||||
mod impl_divceil {
|
||||
use super::StdShimsDivCeil;
|
||||
impl StdShimsDivCeil for u8 {
|
||||
fn div_ceil(self, rhs: Self) -> Self {
|
||||
(self + (rhs - 1)) / rhs
|
||||
}
|
||||
}
|
||||
impl StdShimsDivCeil for u16 {
|
||||
fn div_ceil(self, rhs: Self) -> Self {
|
||||
(self + (rhs - 1)) / rhs
|
||||
}
|
||||
}
|
||||
impl StdShimsDivCeil for u32 {
|
||||
fn div_ceil(self, rhs: Self) -> Self {
|
||||
(self + (rhs - 1)) / rhs
|
||||
}
|
||||
}
|
||||
impl StdShimsDivCeil for u64 {
|
||||
fn div_ceil(self, rhs: Self) -> Self {
|
||||
(self + (rhs - 1)) / rhs
|
||||
}
|
||||
}
|
||||
impl StdShimsDivCeil for u128 {
|
||||
fn div_ceil(self, rhs: Self) -> Self {
|
||||
(self + (rhs - 1)) / rhs
|
||||
}
|
||||
}
|
||||
impl StdShimsDivCeil for usize {
|
||||
fn div_ceil(self, rhs: Self) -> Self {
|
||||
(self + (rhs - 1)) / rhs
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
#[rustversion::before(1.74)]
|
||||
#[doc(hidden)]
|
||||
pub trait StdShimsIoErrorOther {
|
||||
fn other<E>(error: E) -> Self
|
||||
where
|
||||
E: Into<Box<dyn std::error::Error + Send + Sync>>;
|
||||
}
|
||||
#[cfg(feature = "std")]
|
||||
#[rustversion::before(1.74)]
|
||||
impl StdShimsIoErrorOther for std::io::Error {
|
||||
fn other<E>(error: E) -> Self
|
||||
where
|
||||
E: Into<Box<dyn std::error::Error + Send + Sync>>,
|
||||
{
|
||||
std::io::Error::new(std::io::ErrorKind::Other, error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,7 +25,11 @@ mod mutex_shim {
|
||||
}
|
||||
pub use mutex_shim::{ShimMutex as Mutex, MutexGuard};
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
pub use std::sync::LazyLock;
|
||||
#[cfg(not(feature = "std"))]
|
||||
pub use spin::Lazy as LazyLock;
|
||||
#[rustversion::before(1.80)]
|
||||
#[cfg(feature = "std")]
|
||||
pub use spin::Lazy as LazyLock;
|
||||
#[rustversion::since(1.80)]
|
||||
#[cfg(feature = "std")]
|
||||
pub use std::sync::LazyLock;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
AGPL-3.0-only license
|
||||
|
||||
Copyright (c) 2022-2024 Luke Parker
|
||||
Copyright (c) 2022-2025 Luke Parker
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License Version 3 as
|
||||
|
||||
@@ -7,7 +7,9 @@ repository = "https://github.com/serai-dex/serai/tree/develop/common/zalloc"
|
||||
authors = ["Luke Parker <lukeparker5132@gmail.com>"]
|
||||
keywords = []
|
||||
edition = "2021"
|
||||
rust-version = "1.77"
|
||||
# This must be specified with the patch version, else Rust believes `1.77` < `1.77.0` and will
|
||||
# refuse to compile due to relying on versions introduced with `1.77.0`
|
||||
rust-version = "1.77.0"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
all-features = true
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2022-2023 Luke Parker
|
||||
Copyright (c) 2022-2025 Luke Parker
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
|
||||
@@ -8,7 +8,6 @@ authors = ["Luke Parker <lukeparker5132@gmail.com>"]
|
||||
keywords = []
|
||||
edition = "2021"
|
||||
publish = false
|
||||
rust-version = "1.81"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
all-features = true
|
||||
@@ -22,11 +21,15 @@ zeroize = { version = "^1.5", default-features = false, features = ["std"] }
|
||||
bitvec = { version = "1", default-features = false, features = ["std"] }
|
||||
rand_core = { version = "0.6", default-features = false, features = ["std"] }
|
||||
|
||||
blake2 = { version = "0.10", default-features = false, features = ["std"] }
|
||||
blake2 = { version = "0.11.0-rc.0", default-features = false, features = ["alloc"] }
|
||||
schnorrkel = { version = "0.11", default-features = false, features = ["std"] }
|
||||
|
||||
ciphersuite = { path = "../crypto/ciphersuite", default-features = false, features = ["std", "ristretto"] }
|
||||
dkg = { path = "../crypto/dkg", default-features = false, features = ["std"] }
|
||||
transcript = { package = "flexible-transcript", path = "../crypto/transcript", default-features = false, features = ["std", "recommended"] }
|
||||
dalek-ff-group = { path = "../crypto/dalek-ff-group", default-features = false, features = ["std"] }
|
||||
ciphersuite = { path = "../crypto/ciphersuite", default-features = false, features = ["std"] }
|
||||
schnorr = { package = "schnorr-signatures", path = "../crypto/schnorr", default-features = false, features = ["std", "aggregate"] }
|
||||
dkg = { package = "dkg-musig", path = "../crypto/dkg/musig", default-features = false, features = ["std"] }
|
||||
frost = { package = "modular-frost", path = "../crypto/frost" }
|
||||
frost-schnorrkel = { path = "../crypto/schnorrkel" }
|
||||
|
||||
hex = { version = "0.4", default-features = false, features = ["std"] }
|
||||
@@ -42,7 +45,7 @@ messages = { package = "serai-processor-messages", path = "../processor/messages
|
||||
message-queue = { package = "serai-message-queue", path = "../message-queue" }
|
||||
tributary-sdk = { path = "./tributary-sdk" }
|
||||
|
||||
serai-client = { path = "../substrate/client", default-features = false, features = ["serai", "borsh"] }
|
||||
serai-client = { path = "../substrate/client", default-features = false, features = ["serai"] }
|
||||
|
||||
log = { version = "0.4", default-features = false, features = ["std"] }
|
||||
env_logger = { version = "0.10", default-features = false, features = ["humantime"] }
|
||||
|
||||
@@ -8,7 +8,7 @@ authors = ["Luke Parker <lukeparker5132@gmail.com>"]
|
||||
keywords = []
|
||||
edition = "2021"
|
||||
publish = false
|
||||
rust-version = "1.81"
|
||||
rust-version = "1.85"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
all-features = true
|
||||
@@ -18,12 +18,12 @@ rustdoc-args = ["--cfg", "docsrs"]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
blake2 = { version = "0.10", default-features = false, features = ["std"] }
|
||||
blake2 = { version = "0.11.0-rc.0", default-features = false, features = ["alloc"] }
|
||||
schnorrkel = { version = "0.11", default-features = false, features = ["std"] }
|
||||
|
||||
scale = { package = "parity-scale-codec", version = "3", default-features = false, features = ["std", "derive"] }
|
||||
borsh = { version = "1", default-features = false, features = ["std", "derive", "de_strict_order"] }
|
||||
serai-client = { path = "../../substrate/client", default-features = false, features = ["serai", "borsh"] }
|
||||
serai-client = { path = "../../substrate/client", default-features = false, features = ["serai"] }
|
||||
|
||||
log = { version = "0.4", default-features = false, features = ["std"] }
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
AGPL-3.0-only license
|
||||
|
||||
Copyright (c) 2023-2024 Luke Parker
|
||||
Copyright (c) 2023-2025 Luke Parker
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License Version 3 as
|
||||
|
||||
@@ -155,7 +155,7 @@ impl<D: Db> ContinuallyRan for CosignIntendTask<D> {
|
||||
|
||||
// Tell each set of their expectation to cosign this block
|
||||
for set in global_session_info.sets {
|
||||
log::debug!("{:?} will be cosigning block #{block_number}", set);
|
||||
log::debug!("{set:?} will be cosigning block #{block_number}");
|
||||
IntendedCosigns::send(
|
||||
&mut txn,
|
||||
set,
|
||||
|
||||
@@ -8,7 +8,7 @@ authors = ["Luke Parker <lukeparker5132@gmail.com>"]
|
||||
keywords = []
|
||||
edition = "2021"
|
||||
publish = false
|
||||
rust-version = "1.81"
|
||||
rust-version = "1.85"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
all-features = true
|
||||
@@ -22,7 +22,7 @@ borsh = { version = "1", default-features = false, features = ["std", "derive",
|
||||
|
||||
serai-db = { path = "../../common/db", version = "0.1" }
|
||||
|
||||
serai-client = { path = "../../substrate/client", default-features = false, features = ["serai", "borsh"] }
|
||||
serai-client = { path = "../../substrate/client", default-features = false, features = ["serai"] }
|
||||
serai-cosign = { path = "../cosign" }
|
||||
tributary-sdk = { path = "../tributary-sdk" }
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ authors = ["Luke Parker <lukeparker5132@gmail.com>"]
|
||||
keywords = []
|
||||
edition = "2021"
|
||||
publish = false
|
||||
rust-version = "1.81"
|
||||
rust-version = "1.87"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
all-features = true
|
||||
@@ -23,13 +23,13 @@ async-trait = { version = "0.1", default-features = false }
|
||||
rand_core = { version = "0.6", default-features = false, features = ["std"] }
|
||||
|
||||
zeroize = { version = "^1.5", default-features = false, features = ["std"] }
|
||||
blake2 = { version = "0.10", default-features = false, features = ["std"] }
|
||||
blake2 = { version = "0.11.0-rc.0", default-features = false, features = ["alloc"] }
|
||||
schnorrkel = { version = "0.11", default-features = false, features = ["std"] }
|
||||
|
||||
hex = { version = "0.4", default-features = false, features = ["std"] }
|
||||
borsh = { version = "1", default-features = false, features = ["std", "derive", "de_strict_order"] }
|
||||
|
||||
serai-client = { path = "../../../substrate/client", default-features = false, features = ["serai", "borsh"] }
|
||||
serai-client = { path = "../../../substrate/client", default-features = false, features = ["serai"] }
|
||||
serai-cosign = { path = "../../cosign" }
|
||||
tributary-sdk = { path = "../../tributary-sdk" }
|
||||
|
||||
|
||||
@@ -3,13 +3,11 @@ use std::{boxed::Box, collections::HashMap};
|
||||
|
||||
use zeroize::Zeroizing;
|
||||
use rand_core::OsRng;
|
||||
use ciphersuite::{group::GroupEncoding, Ciphersuite, Ristretto};
|
||||
use ciphersuite::{group::GroupEncoding, Ciphersuite};
|
||||
use dalek_ff_group::Ristretto;
|
||||
use dkg::{Participant, musig};
|
||||
use frost_schnorrkel::{
|
||||
frost::{
|
||||
dkg::{Participant, musig::musig},
|
||||
FrostError,
|
||||
sign::*,
|
||||
},
|
||||
frost::{FrostError, sign::*},
|
||||
Schnorrkel,
|
||||
};
|
||||
|
||||
@@ -155,16 +153,15 @@ impl<CD: DbTrait, TD: DbTrait> ConfirmDkgTask<CD, TD> {
|
||||
db: &mut CD,
|
||||
set: ExternalValidatorSet,
|
||||
attempt: u32,
|
||||
key: &Zeroizing<<Ristretto as Ciphersuite>::F>,
|
||||
key: Zeroizing<<Ristretto as Ciphersuite>::F>,
|
||||
signer: &mut Option<Signer>,
|
||||
) {
|
||||
// Perform the preprocess
|
||||
let public_key = Ristretto::generator() * key.deref();
|
||||
let (machine, preprocess) = AlgorithmMachine::new(
|
||||
schnorrkel(),
|
||||
// We use a 1-of-1 Musig here as we don't know who will actually be in this Musig yet
|
||||
musig(&musig_context(set.into()), key, &[Ristretto::generator() * key.deref()])
|
||||
.unwrap()
|
||||
.into(),
|
||||
musig(musig_context(set.into()), key, &[public_key]).unwrap(),
|
||||
)
|
||||
.preprocess(&mut OsRng);
|
||||
// We take the preprocess so we can use it in a distinct machine with the actual Musig
|
||||
@@ -199,7 +196,7 @@ impl<CD: DbTrait, TD: DbTrait> ContinuallyRan for ConfirmDkgTask<CD, TD> {
|
||||
// If we were sent a key to set, create the signer for it
|
||||
if self.signer.is_none() && KeysToConfirm::get(&self.db, self.set.set).is_some() {
|
||||
// Create and publish the initial preprocess
|
||||
Self::preprocess(&mut self.db, self.set.set, 0, &self.key, &mut self.signer);
|
||||
Self::preprocess(&mut self.db, self.set.set, 0, self.key.clone(), &mut self.signer);
|
||||
|
||||
made_progress = true;
|
||||
}
|
||||
@@ -219,7 +216,13 @@ impl<CD: DbTrait, TD: DbTrait> ContinuallyRan for ConfirmDkgTask<CD, TD> {
|
||||
id: messages::sign::SignId { attempt, .. },
|
||||
} => {
|
||||
// Create and publish the preprocess for the specified attempt
|
||||
Self::preprocess(&mut self.db, self.set.set, attempt, &self.key, &mut self.signer);
|
||||
Self::preprocess(
|
||||
&mut self.db,
|
||||
self.set.set,
|
||||
attempt,
|
||||
self.key.clone(),
|
||||
&mut self.signer,
|
||||
);
|
||||
}
|
||||
messages::sign::CoordinatorMessage::Preprocesses {
|
||||
id: messages::sign::SignId { attempt, .. },
|
||||
@@ -258,9 +261,9 @@ impl<CD: DbTrait, TD: DbTrait> ContinuallyRan for ConfirmDkgTask<CD, TD> {
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let keys = musig(&musig_context(self.set.set.into()), &self.key, &musig_public_keys)
|
||||
.unwrap()
|
||||
.into();
|
||||
let keys =
|
||||
musig(musig_context(self.set.set.into()), self.key.clone(), &musig_public_keys)
|
||||
.unwrap();
|
||||
|
||||
// Rebuild the machine
|
||||
let (machine, preprocess_from_cache) =
|
||||
|
||||
@@ -4,9 +4,10 @@ use std::{sync::Arc, collections::HashMap, time::Instant};
|
||||
use zeroize::{Zeroize, Zeroizing};
|
||||
use rand_core::{RngCore, OsRng};
|
||||
|
||||
use dalek_ff_group::Ristretto;
|
||||
use ciphersuite::{
|
||||
group::{ff::PrimeField, GroupEncoding},
|
||||
Ciphersuite, Ristretto,
|
||||
Ciphersuite,
|
||||
};
|
||||
|
||||
use borsh::BorshDeserialize;
|
||||
|
||||
@@ -3,7 +3,8 @@ use std::sync::Arc;
|
||||
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use ciphersuite::{Ciphersuite, Ristretto};
|
||||
use ciphersuite::Ciphersuite;
|
||||
use dalek_ff_group::Ristretto;
|
||||
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
|
||||
@@ -4,7 +4,8 @@ use std::sync::Arc;
|
||||
use zeroize::Zeroizing;
|
||||
use rand_core::OsRng;
|
||||
use blake2::{digest::typenum::U32, Digest, Blake2s};
|
||||
use ciphersuite::{Ciphersuite, Ristretto};
|
||||
use ciphersuite::Ciphersuite;
|
||||
use dalek_ff_group::Ristretto;
|
||||
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
@@ -67,9 +68,7 @@ async fn provide_transaction<TD: DbTrait, P: P2p>(
|
||||
// advancing
|
||||
Err(ProvidedError::LocalMismatchesOnChain) => loop {
|
||||
log::error!(
|
||||
"Tributary {:?} was supposed to provide {:?} but peers disagree, halting Tributary",
|
||||
set,
|
||||
tx,
|
||||
"Tributary {set:?} was supposed to provide {tx:?} but peers disagree, halting Tributary",
|
||||
);
|
||||
// Print this every five minutes as this does need to be handled
|
||||
tokio::time::sleep(Duration::from_secs(5 * 60)).await;
|
||||
|
||||
@@ -8,7 +8,7 @@ authors = ["Luke Parker <lukeparker5132@gmail.com>"]
|
||||
keywords = []
|
||||
edition = "2021"
|
||||
publish = false
|
||||
rust-version = "1.81"
|
||||
rust-version = "1.85"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
all-features = true
|
||||
@@ -25,7 +25,7 @@ borsh = { version = "1", default-features = false, features = ["std", "derive",
|
||||
|
||||
dkg = { path = "../../crypto/dkg", default-features = false, features = ["std"] }
|
||||
|
||||
serai-client = { path = "../../substrate/client", version = "0.1", default-features = false, features = ["serai", "borsh"] }
|
||||
serai-client = { path = "../../substrate/client", version = "0.1", default-features = false, features = ["serai"] }
|
||||
|
||||
log = { version = "0.4", default-features = false, features = ["std"] }
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
AGPL-3.0-only license
|
||||
|
||||
Copyright (c) 2023-2024 Luke Parker
|
||||
Copyright (c) 2023-2025 Luke Parker
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License Version 3 as
|
||||
|
||||
@@ -6,7 +6,7 @@ license = "AGPL-3.0-only"
|
||||
repository = "https://github.com/serai-dex/serai/tree/develop/coordinator/tributary-sdk"
|
||||
authors = ["Luke Parker <lukeparker5132@gmail.com>"]
|
||||
edition = "2021"
|
||||
rust-version = "1.81"
|
||||
rust-version = "1.85"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
all-features = true
|
||||
@@ -24,11 +24,12 @@ zeroize = { version = "^1.5", default-features = false, features = ["std"] }
|
||||
rand = { version = "0.8", default-features = false, features = ["std"] }
|
||||
rand_chacha = { version = "0.3", default-features = false, features = ["std"] }
|
||||
|
||||
blake2 = { version = "0.10", default-features = false, features = ["std"] }
|
||||
blake2 = { version = "0.11.0-rc.0", default-features = false, features = ["alloc"] }
|
||||
transcript = { package = "flexible-transcript", path = "../../crypto/transcript", version = "0.3", default-features = false, features = ["std", "recommended"] }
|
||||
|
||||
ciphersuite = { package = "ciphersuite", path = "../../crypto/ciphersuite", version = "0.4", default-features = false, features = ["std", "ristretto"] }
|
||||
schnorr = { package = "schnorr-signatures", path = "../../crypto/schnorr", version = "0.5", default-features = false, features = ["std"] }
|
||||
ciphersuite = { path = "../../crypto/ciphersuite", version = "0.4", default-features = false, features = ["std"] }
|
||||
dalek-ff-group = { path = "../../crypto/dalek-ff-group", default-features = false, features = ["std"] }
|
||||
schnorr = { package = "schnorr-signatures", path = "../../crypto/schnorr", version = "0.5", default-features = false, features = ["std", "aggregate"] }
|
||||
|
||||
hex = { version = "0.4", default-features = false, features = ["std"] }
|
||||
log = { version = "0.4", default-features = false, features = ["std"] }
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
AGPL-3.0-only license
|
||||
|
||||
Copyright (c) 2023 Luke Parker
|
||||
Copyright (c) 2023-2025 Luke Parker
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License Version 3 as
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use std::collections::{VecDeque, HashSet};
|
||||
|
||||
use ciphersuite::{group::GroupEncoding, Ciphersuite, Ristretto};
|
||||
use dalek_ff_group::Ristretto;
|
||||
use ciphersuite::{group::GroupEncoding, Ciphersuite};
|
||||
|
||||
use serai_db::{Get, DbTxn, Db};
|
||||
|
||||
|
||||
@@ -3,7 +3,8 @@ use std::{sync::Arc, io};
|
||||
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use ciphersuite::{Ciphersuite, Ristretto};
|
||||
use ciphersuite::Ciphersuite;
|
||||
use dalek_ff_group::Ristretto;
|
||||
|
||||
use scale::Decode;
|
||||
use futures_channel::mpsc::UnboundedReceiver;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use ciphersuite::{Ciphersuite, Ristretto};
|
||||
use dalek_ff_group::Ristretto;
|
||||
use ciphersuite::Ciphersuite;
|
||||
|
||||
use serai_db::{DbTxn, Db};
|
||||
|
||||
|
||||
@@ -14,8 +14,9 @@ use ciphersuite::{
|
||||
GroupEncoding,
|
||||
ff::{Field, PrimeField},
|
||||
},
|
||||
Ciphersuite, Ristretto,
|
||||
Ciphersuite,
|
||||
};
|
||||
use dalek_ff_group::Ristretto;
|
||||
use schnorr::{
|
||||
SchnorrSignature,
|
||||
aggregate::{SchnorrAggregator, SchnorrAggregate},
|
||||
@@ -163,7 +164,6 @@ impl SignatureScheme for Validators {
|
||||
type AggregateSignature = Vec<u8>;
|
||||
type Signer = Arc<Signer>;
|
||||
|
||||
#[must_use]
|
||||
fn verify(&self, validator: Self::ValidatorId, msg: &[u8], sig: &Self::Signature) -> bool {
|
||||
if !self.weights.contains_key(&validator) {
|
||||
return false;
|
||||
@@ -196,7 +196,6 @@ impl SignatureScheme for Validators {
|
||||
aggregate.serialize()
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
fn verify_aggregate(
|
||||
&self,
|
||||
signers: &[Self::ValidatorId],
|
||||
|
||||
@@ -4,7 +4,8 @@ use scale::{Encode, Decode, IoReader};
|
||||
|
||||
use blake2::{Digest, Blake2s256};
|
||||
|
||||
use ciphersuite::{Ciphersuite, Ristretto};
|
||||
use dalek_ff_group::Ristretto;
|
||||
use ciphersuite::Ciphersuite;
|
||||
|
||||
use crate::{
|
||||
transaction::{Transaction, TransactionKind, TransactionError},
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
use std::{sync::Arc, io, collections::HashMap, fmt::Debug};
|
||||
|
||||
use blake2::{Digest, Blake2s256};
|
||||
|
||||
use dalek_ff_group::Ristretto;
|
||||
use ciphersuite::{
|
||||
group::{ff::Field, Group},
|
||||
Ciphersuite, Ristretto,
|
||||
Ciphersuite,
|
||||
};
|
||||
use schnorr::SchnorrSignature;
|
||||
|
||||
|
||||
@@ -10,7 +10,8 @@ use rand::rngs::OsRng;
|
||||
|
||||
use blake2::{Digest, Blake2s256};
|
||||
|
||||
use ciphersuite::{group::ff::Field, Ciphersuite, Ristretto};
|
||||
use dalek_ff_group::Ristretto;
|
||||
use ciphersuite::{group::ff::Field, Ciphersuite};
|
||||
|
||||
use serai_db::{DbTxn, Db, MemDb};
|
||||
|
||||
|
||||
@@ -3,7 +3,8 @@ use std::{sync::Arc, collections::HashMap};
|
||||
use zeroize::Zeroizing;
|
||||
use rand::{RngCore, rngs::OsRng};
|
||||
|
||||
use ciphersuite::{group::ff::Field, Ciphersuite, Ristretto};
|
||||
use dalek_ff_group::Ristretto;
|
||||
use ciphersuite::{group::ff::Field, Ciphersuite};
|
||||
|
||||
use tendermint::ext::Commit;
|
||||
|
||||
|
||||
@@ -6,9 +6,10 @@ use rand::{RngCore, CryptoRng, rngs::OsRng};
|
||||
|
||||
use blake2::{Digest, Blake2s256};
|
||||
|
||||
use dalek_ff_group::Ristretto;
|
||||
use ciphersuite::{
|
||||
group::{ff::Field, Group},
|
||||
Ciphersuite, Ristretto,
|
||||
Ciphersuite,
|
||||
};
|
||||
use schnorr::SchnorrSignature;
|
||||
|
||||
|
||||
@@ -2,7 +2,8 @@ use rand::rngs::OsRng;
|
||||
|
||||
use blake2::{Digest, Blake2s256};
|
||||
|
||||
use ciphersuite::{group::ff::Field, Ciphersuite, Ristretto};
|
||||
use dalek_ff_group::Ristretto;
|
||||
use ciphersuite::{group::ff::Field, Ciphersuite};
|
||||
|
||||
use crate::{
|
||||
ReadWrite,
|
||||
|
||||
@@ -3,7 +3,8 @@ use std::sync::Arc;
|
||||
use zeroize::Zeroizing;
|
||||
use rand::{RngCore, rngs::OsRng};
|
||||
|
||||
use ciphersuite::{Ristretto, Ciphersuite, group::ff::Field};
|
||||
use dalek_ff_group::Ristretto;
|
||||
use ciphersuite::{Ciphersuite, group::ff::Field};
|
||||
|
||||
use scale::Encode;
|
||||
|
||||
|
||||
@@ -8,8 +8,9 @@ use blake2::{Digest, Blake2b512};
|
||||
|
||||
use ciphersuite::{
|
||||
group::{Group, GroupEncoding},
|
||||
Ciphersuite, Ristretto,
|
||||
Ciphersuite,
|
||||
};
|
||||
use dalek_ff_group::Ristretto;
|
||||
use schnorr::SchnorrSignature;
|
||||
|
||||
use crate::{TRANSACTION_SIZE_LIMIT, ReadWrite};
|
||||
|
||||
@@ -6,7 +6,7 @@ license = "MIT"
|
||||
repository = "https://github.com/serai-dex/serai/tree/develop/coordinator/tendermint"
|
||||
authors = ["Luke Parker <lukeparker5132@gmail.com>"]
|
||||
edition = "2021"
|
||||
rust-version = "1.81"
|
||||
rust-version = "1.75"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
all-features = true
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2022-2023 Luke Parker
|
||||
Copyright (c) 2022-2025 Luke Parker
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
|
||||
@@ -114,7 +114,6 @@ impl<S: SignatureScheme> SignatureScheme for Arc<S> {
|
||||
self.as_ref().aggregate(validators, msg, sigs)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
fn verify_aggregate(
|
||||
&self,
|
||||
signers: &[Self::ValidatorId],
|
||||
|
||||
@@ -46,7 +46,6 @@ impl SignatureScheme for TestSignatureScheme {
|
||||
type AggregateSignature = Vec<[u8; 32]>;
|
||||
type Signer = TestSigner;
|
||||
|
||||
#[must_use]
|
||||
fn verify(&self, validator: u16, msg: &[u8], sig: &[u8; 32]) -> bool {
|
||||
(sig[.. 2] == validator.to_le_bytes()) && (sig[2 ..] == [msg, &[0; 30]].concat()[.. 30])
|
||||
}
|
||||
@@ -60,7 +59,6 @@ impl SignatureScheme for TestSignatureScheme {
|
||||
sigs.to_vec()
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
fn verify_aggregate(
|
||||
&self,
|
||||
signers: &[TestValidatorId],
|
||||
|
||||
@@ -8,7 +8,7 @@ authors = ["Luke Parker <lukeparker5132@gmail.com>"]
|
||||
keywords = []
|
||||
edition = "2021"
|
||||
publish = false
|
||||
rust-version = "1.81"
|
||||
rust-version = "1.85"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
all-features = true
|
||||
@@ -24,12 +24,13 @@ rand_core = { version = "0.6", default-features = false, features = ["std"] }
|
||||
scale = { package = "parity-scale-codec", version = "3", default-features = false, features = ["std", "derive"] }
|
||||
borsh = { version = "1", default-features = false, features = ["std", "derive", "de_strict_order"] }
|
||||
|
||||
blake2 = { version = "0.10", default-features = false, features = ["std"] }
|
||||
blake2 = { version = "0.11.0-rc.0", default-features = false, features = ["alloc"] }
|
||||
ciphersuite = { path = "../../crypto/ciphersuite", default-features = false, features = ["std"] }
|
||||
dalek-ff-group = { path = "../../crypto/dalek-ff-group", default-features = false, features = ["std"] }
|
||||
dkg = { path = "../../crypto/dkg", default-features = false, features = ["std"] }
|
||||
schnorr = { package = "schnorr-signatures", path = "../../crypto/schnorr", default-features = false, features = ["std"] }
|
||||
|
||||
serai-client = { path = "../../substrate/client", default-features = false, features = ["serai", "borsh"] }
|
||||
serai-client = { path = "../../substrate/client", default-features = false, features = ["serai"] }
|
||||
|
||||
serai-db = { path = "../../common/db" }
|
||||
serai-task = { path = "../../common/task", version = "0.1" }
|
||||
|
||||
@@ -253,7 +253,7 @@ impl<TD: Db, TDT: DbTxn, P: P2p> ScanBlock<'_, TD, TDT, P> {
|
||||
let signer = signer(signed);
|
||||
|
||||
// Check the participant voted to be removed actually exists
|
||||
if !self.validators.iter().any(|validator| *validator == participant) {
|
||||
if !self.validators.contains(&participant) {
|
||||
TributaryDb::fatal_slash(
|
||||
self.tributary_txn,
|
||||
self.set.set,
|
||||
|
||||
@@ -7,8 +7,9 @@ use rand_core::{RngCore, CryptoRng};
|
||||
use blake2::{digest::typenum::U32, Digest, Blake2b};
|
||||
use ciphersuite::{
|
||||
group::{ff::Field, Group, GroupEncoding},
|
||||
Ciphersuite, Ristretto,
|
||||
Ciphersuite,
|
||||
};
|
||||
use dalek_ff_group::Ristretto;
|
||||
use schnorr::SchnorrSignature;
|
||||
|
||||
use scale::Encode;
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
[package]
|
||||
name = "ciphersuite"
|
||||
version = "0.4.1"
|
||||
version = "0.4.2"
|
||||
description = "Ciphersuites built around ff/group"
|
||||
license = "MIT"
|
||||
repository = "https://github.com/serai-dex/serai/tree/develop/crypto/ciphersuite"
|
||||
authors = ["Luke Parker <lukeparker5132@gmail.com>"]
|
||||
keywords = ["ciphersuite", "ff", "group"]
|
||||
edition = "2021"
|
||||
rust-version = "1.80"
|
||||
rust-version = "1.85"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
all-features = true
|
||||
@@ -24,22 +24,12 @@ rand_core = { version = "0.6", default-features = false }
|
||||
zeroize = { version = "^1.5", default-features = false, features = ["derive"] }
|
||||
subtle = { version = "^2.4", default-features = false }
|
||||
|
||||
digest = { version = "0.10", default-features = false }
|
||||
digest = { version = "0.11.0-rc.0", default-features = false, features = ["block-api"] }
|
||||
transcript = { package = "flexible-transcript", path = "../transcript", version = "^0.3.2", default-features = false }
|
||||
sha2 = { version = "0.10", default-features = false, optional = true }
|
||||
sha3 = { version = "0.10", default-features = false, optional = true }
|
||||
|
||||
ff = { version = "0.13", default-features = false, features = ["bits"] }
|
||||
group = { version = "0.13", default-features = false }
|
||||
|
||||
dalek-ff-group = { path = "../dalek-ff-group", version = "0.4", default-features = false, optional = true }
|
||||
|
||||
elliptic-curve = { version = "0.13", default-features = false, features = ["hash2curve"], optional = true }
|
||||
p256 = { version = "^0.13.1", default-features = false, features = ["arithmetic", "bits", "hash2curve"], optional = true }
|
||||
k256 = { version = "^0.13.1", default-features = false, features = ["arithmetic", "bits", "hash2curve"], optional = true }
|
||||
|
||||
minimal-ed448 = { path = "../ed448", version = "0.4", default-features = false, optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
hex = { version = "0.4", default-features = false, features = ["std"] }
|
||||
|
||||
@@ -48,8 +38,10 @@ rand_core = { version = "0.6", default-features = false, features = ["std"] }
|
||||
ff-group-tests = { version = "0.13", path = "../ff-group-tests" }
|
||||
|
||||
[features]
|
||||
alloc = ["std-shims"]
|
||||
alloc = ["std-shims", "digest/alloc", "ff/alloc"]
|
||||
std = [
|
||||
"alloc",
|
||||
|
||||
"std-shims/std",
|
||||
|
||||
"rand_core/std",
|
||||
@@ -57,29 +49,9 @@ std = [
|
||||
"zeroize/std",
|
||||
"subtle/std",
|
||||
|
||||
"digest/std",
|
||||
"transcript/std",
|
||||
"sha2?/std",
|
||||
"sha3?/std",
|
||||
|
||||
"ff/std",
|
||||
|
||||
"dalek-ff-group?/std",
|
||||
|
||||
"elliptic-curve?/std",
|
||||
"p256?/std",
|
||||
"k256?/std",
|
||||
"minimal-ed448?/std",
|
||||
]
|
||||
|
||||
dalek = ["sha2", "dalek-ff-group"]
|
||||
ed25519 = ["dalek"]
|
||||
ristretto = ["dalek"]
|
||||
|
||||
kp256 = ["sha2", "elliptic-curve"]
|
||||
p256 = ["kp256", "dep:p256"]
|
||||
secp256k1 = ["kp256", "k256"]
|
||||
|
||||
ed448 = ["sha3", "minimal-ed448"]
|
||||
|
||||
default = ["std"]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2021-2023 Luke Parker
|
||||
Copyright (c) 2021-2025 Luke Parker
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
|
||||
@@ -17,9 +17,7 @@ Secp256k1 and P-256 are offered via [k256](https://crates.io/crates/k256) and
|
||||
[p256](https://crates.io/crates/p256), two libraries maintained by
|
||||
[RustCrypto](https://github.com/RustCrypto).
|
||||
|
||||
Their `hash_to_F` is the
|
||||
[IETF's hash to curve](https://www.ietf.org/archive/id/draft-irtf-cfrg-hash-to-curve-16.html),
|
||||
yet applied to their scalar field.
|
||||
Please see the [`ciphersuite-kp256`](https://docs.rs/ciphersuite-kp256) crate for more info.
|
||||
|
||||
### Ed25519/Ristretto
|
||||
|
||||
@@ -27,11 +25,7 @@ Ed25519/Ristretto are offered via
|
||||
[dalek-ff-group](https://crates.io/crates/dalek-ff-group), an ff/group wrapper
|
||||
around [curve25519-dalek](https://crates.io/crates/curve25519-dalek).
|
||||
|
||||
Their `hash_to_F` is the wide reduction of SHA2-512, as used in
|
||||
[RFC-8032](https://www.rfc-editor.org/rfc/rfc8032). This is also compliant with
|
||||
the draft
|
||||
[RFC-RISTRETTO](https://www.ietf.org/archive/id/draft-irtf-cfrg-ristretto255-decaf448-05.html).
|
||||
The domain-separation tag is naively prefixed to the message.
|
||||
Please see the [`dalek-ff-group`](https://docs.rs/dalek-ff-group) crate for more info.
|
||||
|
||||
### Ed448
|
||||
|
||||
@@ -39,6 +33,4 @@ Ed448 is offered via [minimal-ed448](https://crates.io/crates/minimal-ed448), an
|
||||
explicitly not recommended, unaudited, incomplete Ed448 implementation, limited
|
||||
to its prime-order subgroup.
|
||||
|
||||
Its `hash_to_F` is the wide reduction of SHAKE256, with a 114-byte output, as
|
||||
used in [RFC-8032](https://www.rfc-editor.org/rfc/rfc8032). The
|
||||
domain-separation tag is naively prefixed to the message.
|
||||
Please see the [`minimal-ed448`](https://docs.rs/minimal-ed448) crate for more info.
|
||||
|
||||
51
crypto/ciphersuite/kp256/Cargo.toml
Normal file
51
crypto/ciphersuite/kp256/Cargo.toml
Normal file
@@ -0,0 +1,51 @@
|
||||
[package]
|
||||
name = "ciphersuite-kp256"
|
||||
version = "0.4.0"
|
||||
description = "Ciphersuites built around ff/group"
|
||||
license = "MIT"
|
||||
repository = "https://github.com/serai-dex/serai/tree/develop/crypto/ciphersuite/kp256"
|
||||
authors = ["Luke Parker <lukeparker5132@gmail.com>"]
|
||||
keywords = ["ciphersuite", "ff", "group"]
|
||||
edition = "2021"
|
||||
rust-version = "1.85"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
all-features = true
|
||||
rustdoc-args = ["--cfg", "docsrs"]
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
rand_core = { version = "0.6", default-features = false }
|
||||
|
||||
zeroize = { version = "^1.5", default-features = false, features = ["derive"] }
|
||||
|
||||
sha2 = { version = "0.11.0-rc.0", default-features = false }
|
||||
|
||||
p256 = { version = "^0.13.1", default-features = false, features = ["arithmetic", "bits", "hash2curve"] }
|
||||
k256 = { version = "^0.13.1", default-features = false, features = ["arithmetic", "bits", "hash2curve"] }
|
||||
|
||||
ciphersuite = { path = "../", version = "0.4", default-features = false }
|
||||
|
||||
[dev-dependencies]
|
||||
hex = { version = "0.4", default-features = false, features = ["std"] }
|
||||
|
||||
rand_core = { version = "0.6", default-features = false, features = ["std"] }
|
||||
|
||||
ff-group-tests = { version = "0.13", path = "../../ff-group-tests" }
|
||||
|
||||
[features]
|
||||
alloc = ["ciphersuite/alloc"]
|
||||
std = [
|
||||
"rand_core/std",
|
||||
|
||||
"zeroize/std",
|
||||
|
||||
"p256/std",
|
||||
"k256/std",
|
||||
|
||||
"ciphersuite/std",
|
||||
]
|
||||
|
||||
default = ["std"]
|
||||
@@ -1,6 +1,6 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2023-2024 Luke Parker
|
||||
Copyright (c) 2021-2025 Luke Parker
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
3
crypto/ciphersuite/kp256/README.md
Normal file
3
crypto/ciphersuite/kp256/README.md
Normal file
@@ -0,0 +1,3 @@
|
||||
# Ciphersuite {k, p}256
|
||||
|
||||
SECP256k1 and P-256 Ciphersuites around k256 and p256.
|
||||
51
crypto/ciphersuite/kp256/src/lib.rs
Normal file
51
crypto/ciphersuite/kp256/src/lib.rs
Normal file
@@ -0,0 +1,51 @@
|
||||
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
|
||||
use zeroize::Zeroize;
|
||||
|
||||
use sha2::Sha512;
|
||||
|
||||
use ciphersuite::Ciphersuite;
|
||||
|
||||
pub use k256;
|
||||
pub use p256;
|
||||
|
||||
macro_rules! kp_curve {
|
||||
(
|
||||
$feature: literal,
|
||||
$lib: ident,
|
||||
|
||||
$Ciphersuite: ident,
|
||||
$ID: literal
|
||||
) => {
|
||||
impl Ciphersuite for $Ciphersuite {
|
||||
type F = $lib::Scalar;
|
||||
type G = $lib::ProjectivePoint;
|
||||
type H = Sha512;
|
||||
|
||||
const ID: &'static [u8] = $ID;
|
||||
|
||||
fn generator() -> Self::G {
|
||||
$lib::ProjectivePoint::GENERATOR
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// Ciphersuite for Secp256k1.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug, Zeroize)]
|
||||
pub struct Secp256k1;
|
||||
kp_curve!("secp256k1", k256, Secp256k1, b"secp256k1");
|
||||
#[test]
|
||||
fn test_secp256k1() {
|
||||
ff_group_tests::group::test_prime_group_bits::<_, k256::ProjectivePoint>(&mut rand_core::OsRng);
|
||||
}
|
||||
|
||||
/// Ciphersuite for P-256.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug, Zeroize)]
|
||||
pub struct P256;
|
||||
kp_curve!("p256", p256, P256, b"P-256");
|
||||
#[test]
|
||||
fn test_p256() {
|
||||
ff_group_tests::group::test_prime_group_bits::<_, p256::ProjectivePoint>(&mut rand_core::OsRng);
|
||||
}
|
||||
@@ -1,106 +0,0 @@
|
||||
use zeroize::Zeroize;
|
||||
|
||||
use sha2::{Digest, Sha512};
|
||||
|
||||
use group::Group;
|
||||
use dalek_ff_group::Scalar;
|
||||
|
||||
use crate::Ciphersuite;
|
||||
|
||||
macro_rules! dalek_curve {
|
||||
(
|
||||
$feature: literal,
|
||||
|
||||
$Ciphersuite: ident,
|
||||
$Point: ident,
|
||||
$ID: literal
|
||||
) => {
|
||||
use dalek_ff_group::$Point;
|
||||
|
||||
impl Ciphersuite for $Ciphersuite {
|
||||
type F = Scalar;
|
||||
type G = $Point;
|
||||
type H = Sha512;
|
||||
|
||||
const ID: &'static [u8] = $ID;
|
||||
|
||||
fn generator() -> Self::G {
|
||||
$Point::generator()
|
||||
}
|
||||
|
||||
fn reduce_512(mut scalar: [u8; 64]) -> Self::F {
|
||||
let res = Scalar::from_bytes_mod_order_wide(&scalar);
|
||||
scalar.zeroize();
|
||||
res
|
||||
}
|
||||
|
||||
fn hash_to_F(dst: &[u8], data: &[u8]) -> Self::F {
|
||||
Scalar::from_hash(Sha512::new_with_prefix(&[dst, data].concat()))
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// Ciphersuite for Ristretto.
|
||||
///
|
||||
/// hash_to_F is implemented with a naive concatenation of the dst and data, allowing transposition
|
||||
/// between the two. This means `dst: b"abc", data: b"def"`, will produce the same scalar as
|
||||
/// `dst: "abcdef", data: b""`. Please use carefully, not letting dsts be substrings of each other.
|
||||
#[cfg(any(test, feature = "ristretto"))]
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug, Zeroize)]
|
||||
pub struct Ristretto;
|
||||
#[cfg(any(test, feature = "ristretto"))]
|
||||
dalek_curve!("ristretto", Ristretto, RistrettoPoint, b"ristretto");
|
||||
#[cfg(any(test, feature = "ristretto"))]
|
||||
#[test]
|
||||
fn test_ristretto() {
|
||||
ff_group_tests::group::test_prime_group_bits::<_, RistrettoPoint>(&mut rand_core::OsRng);
|
||||
|
||||
assert_eq!(
|
||||
Ristretto::hash_to_F(
|
||||
b"FROST-RISTRETTO255-SHA512-v11nonce",
|
||||
&hex::decode(
|
||||
"\
|
||||
81800157bb554f299fe0b6bd658e4c4591d74168b5177bf55e8dceed59dc80c7\
|
||||
5c3430d391552f6e60ecdc093ff9f6f4488756aa6cebdbad75a768010b8f830e"
|
||||
)
|
||||
.unwrap()
|
||||
)
|
||||
.to_bytes()
|
||||
.as_ref(),
|
||||
&hex::decode("40f58e8df202b21c94f826e76e4647efdb0ea3ca7ae7e3689bc0cbe2e2f6660c").unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
/// Ciphersuite for Ed25519, inspired by RFC-8032.
|
||||
///
|
||||
/// hash_to_F is implemented with a naive concatenation of the dst and data, allowing transposition
|
||||
/// between the two. This means `dst: b"abc", data: b"def"`, will produce the same scalar as
|
||||
/// `dst: "abcdef", data: b""`. Please use carefully, not letting dsts be substrings of each other.
|
||||
#[cfg(feature = "ed25519")]
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug, Zeroize)]
|
||||
pub struct Ed25519;
|
||||
#[cfg(feature = "ed25519")]
|
||||
dalek_curve!("ed25519", Ed25519, EdwardsPoint, b"edwards25519");
|
||||
#[cfg(feature = "ed25519")]
|
||||
#[test]
|
||||
fn test_ed25519() {
|
||||
ff_group_tests::group::test_prime_group_bits::<_, EdwardsPoint>(&mut rand_core::OsRng);
|
||||
|
||||
// Ideally, a test vector from RFC-8032 (not FROST) would be here
|
||||
// Unfortunately, the IETF draft doesn't provide any vectors for the derived challenges
|
||||
assert_eq!(
|
||||
Ed25519::hash_to_F(
|
||||
b"FROST-ED25519-SHA512-v11nonce",
|
||||
&hex::decode(
|
||||
"\
|
||||
9d06a6381c7a4493929761a73692776772b274236fb5cfcc7d1b48ac3a9c249f\
|
||||
929dcc590407aae7d388761cddb0c0db6f5627aea8e217f4a033f2ec83d93509"
|
||||
)
|
||||
.unwrap()
|
||||
)
|
||||
.to_bytes()
|
||||
.as_ref(),
|
||||
&hex::decode("70652da3e8d7533a0e4b9e9104f01b48c396b5b553717784ed8d05c6a36b9609").unwrap()
|
||||
);
|
||||
}
|
||||
@@ -1,110 +0,0 @@
|
||||
use zeroize::Zeroize;
|
||||
|
||||
use digest::{
|
||||
typenum::U114, core_api::BlockSizeUser, Update, Output, OutputSizeUser, FixedOutput,
|
||||
ExtendableOutput, XofReader, HashMarker, Digest,
|
||||
};
|
||||
use sha3::Shake256;
|
||||
|
||||
use group::Group;
|
||||
use minimal_ed448::{Scalar, Point};
|
||||
|
||||
use crate::Ciphersuite;
|
||||
|
||||
/// Shake256, fixed to a 114-byte output, as used by Ed448.
|
||||
#[derive(Clone, Default)]
|
||||
pub struct Shake256_114(Shake256);
|
||||
impl BlockSizeUser for Shake256_114 {
|
||||
type BlockSize = <Shake256 as BlockSizeUser>::BlockSize;
|
||||
fn block_size() -> usize {
|
||||
Shake256::block_size()
|
||||
}
|
||||
}
|
||||
impl OutputSizeUser for Shake256_114 {
|
||||
type OutputSize = U114;
|
||||
fn output_size() -> usize {
|
||||
114
|
||||
}
|
||||
}
|
||||
impl Update for Shake256_114 {
|
||||
fn update(&mut self, data: &[u8]) {
|
||||
self.0.update(data);
|
||||
}
|
||||
fn chain(mut self, data: impl AsRef<[u8]>) -> Self {
|
||||
Update::update(&mut self, data.as_ref());
|
||||
self
|
||||
}
|
||||
}
|
||||
impl FixedOutput for Shake256_114 {
|
||||
fn finalize_fixed(self) -> Output<Self> {
|
||||
let mut res = Default::default();
|
||||
FixedOutput::finalize_into(self, &mut res);
|
||||
res
|
||||
}
|
||||
fn finalize_into(self, out: &mut Output<Self>) {
|
||||
let mut reader = self.0.finalize_xof();
|
||||
reader.read(out);
|
||||
}
|
||||
}
|
||||
impl HashMarker for Shake256_114 {}
|
||||
|
||||
/// Ciphersuite for Ed448, inspired by RFC-8032. This is not recommended for usage.
|
||||
///
|
||||
/// hash_to_F is implemented with a naive concatenation of the dst and data, allowing transposition
|
||||
/// between the two. This means `dst: b"abc", data: b"def"`, will produce the same scalar as
|
||||
/// `dst: "abcdef", data: b""`. Please use carefully, not letting dsts be substrings of each other.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug, Zeroize)]
|
||||
pub struct Ed448;
|
||||
impl Ciphersuite for Ed448 {
|
||||
type F = Scalar;
|
||||
type G = Point;
|
||||
type H = Shake256_114;
|
||||
|
||||
const ID: &'static [u8] = b"ed448";
|
||||
|
||||
fn generator() -> Self::G {
|
||||
Point::generator()
|
||||
}
|
||||
|
||||
fn reduce_512(mut scalar: [u8; 64]) -> Self::F {
|
||||
let res = Self::hash_to_F(b"Ciphersuite-reduce_512", &scalar);
|
||||
scalar.zeroize();
|
||||
res
|
||||
}
|
||||
|
||||
fn hash_to_F(dst: &[u8], data: &[u8]) -> Self::F {
|
||||
Scalar::wide_reduce(Self::H::digest([dst, data].concat()).as_ref().try_into().unwrap())
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ed448() {
|
||||
use ff::PrimeField;
|
||||
|
||||
ff_group_tests::group::test_prime_group_bits::<_, Point>(&mut rand_core::OsRng);
|
||||
|
||||
// Ideally, a test vector from RFC-8032 (not FROST) would be here
|
||||
// Unfortunately, the IETF draft doesn't provide any vectors for the derived challenges
|
||||
assert_eq!(
|
||||
Ed448::hash_to_F(
|
||||
b"FROST-ED448-SHAKE256-v11nonce",
|
||||
&hex::decode(
|
||||
"\
|
||||
89bf16040081ff2990336b200613787937ebe1f024b8cdff90eb6f1c741d91c1\
|
||||
4a2b2f5858a932ad3d3b18bd16e76ced3070d72fd79ae4402df201f5\
|
||||
25e754716a1bc1b87a502297f2a99d89ea054e0018eb55d39562fd01\
|
||||
00"
|
||||
)
|
||||
.unwrap()
|
||||
)
|
||||
.to_repr()
|
||||
.to_vec(),
|
||||
hex::decode(
|
||||
"\
|
||||
67a6f023e77361707c6e894c625e809e80f33fdb310810053ae29e28\
|
||||
e7011f3193b9020e73c183a98cc3a519160ed759376dd92c94831622\
|
||||
00"
|
||||
)
|
||||
.unwrap()
|
||||
);
|
||||
}
|
||||
@@ -1,192 +0,0 @@
|
||||
use zeroize::Zeroize;
|
||||
|
||||
use sha2::Sha256;
|
||||
|
||||
use group::ff::PrimeField;
|
||||
|
||||
use elliptic_curve::{
|
||||
generic_array::GenericArray,
|
||||
bigint::{NonZero, CheckedAdd, Encoding, U384, U512},
|
||||
hash2curve::{Expander, ExpandMsg, ExpandMsgXmd},
|
||||
};
|
||||
|
||||
use crate::Ciphersuite;
|
||||
|
||||
macro_rules! kp_curve {
|
||||
(
|
||||
$feature: literal,
|
||||
$lib: ident,
|
||||
|
||||
$Ciphersuite: ident,
|
||||
$ID: literal
|
||||
) => {
|
||||
impl Ciphersuite for $Ciphersuite {
|
||||
type F = $lib::Scalar;
|
||||
type G = $lib::ProjectivePoint;
|
||||
type H = Sha256;
|
||||
|
||||
const ID: &'static [u8] = $ID;
|
||||
|
||||
fn generator() -> Self::G {
|
||||
$lib::ProjectivePoint::GENERATOR
|
||||
}
|
||||
|
||||
fn reduce_512(scalar: [u8; 64]) -> Self::F {
|
||||
let mut modulus = [0; 64];
|
||||
modulus[32 ..].copy_from_slice(&(Self::F::ZERO - Self::F::ONE).to_bytes());
|
||||
let modulus = U512::from_be_slice(&modulus).checked_add(&U512::ONE).unwrap();
|
||||
|
||||
let mut wide =
|
||||
U512::from_be_bytes(scalar).rem(&NonZero::new(modulus).unwrap()).to_be_bytes();
|
||||
|
||||
let mut array = *GenericArray::from_slice(&wide[32 ..]);
|
||||
let res = $lib::Scalar::from_repr(array).unwrap();
|
||||
|
||||
wide.zeroize();
|
||||
array.zeroize();
|
||||
res
|
||||
}
|
||||
|
||||
fn hash_to_F(dst: &[u8], msg: &[u8]) -> Self::F {
|
||||
// While one of these two libraries does support directly hashing to the Scalar field, the
|
||||
// other doesn't. While that's probably an oversight, this is a universally working method
|
||||
|
||||
// This method is from
|
||||
// https://www.ietf.org/archive/id/draft-irtf-cfrg-hash-to-curve-16.html
|
||||
// Specifically, Section 5
|
||||
|
||||
// While that draft, overall, is intended for hashing to curves, that necessitates
|
||||
// detailing how to hash to a finite field. The draft comments that its mechanism for
|
||||
// doing so, which it uses to derive field elements, is also applicable to the scalar field
|
||||
|
||||
// The hash_to_field function is intended to provide unbiased values
|
||||
// In order to do so, a wide reduction from an extra k bits is applied, minimizing bias to
|
||||
// 2^-k
|
||||
// k is intended to be the bits of security of the suite, which is 128 for secp256k1 and
|
||||
// P-256
|
||||
const K: usize = 128;
|
||||
|
||||
// L is the amount of bytes of material which should be used in the wide reduction
|
||||
// The 256 is for the bit-length of the primes, rounded up to the nearest byte threshold
|
||||
// This is a simplification of the formula from the end of section 5
|
||||
const L: usize = (256 + K) / 8; // 48
|
||||
|
||||
// In order to perform this reduction, we need to use 48-byte numbers
|
||||
// First, convert the modulus to a 48-byte number
|
||||
// This is done by getting -1 as bytes, parsing it into a U384, and then adding back one
|
||||
let mut modulus = [0; L];
|
||||
// The byte repr of scalars will be 32 big-endian bytes
|
||||
// Set the lower 32 bytes of our 48-byte array accordingly
|
||||
modulus[16 ..].copy_from_slice(&(Self::F::ZERO - Self::F::ONE).to_bytes());
|
||||
// Use a checked_add + unwrap since this addition cannot fail (being a 32-byte value with
|
||||
// 48-bytes of space)
|
||||
// While a non-panicking saturating_add/wrapping_add could be used, they'd likely be less
|
||||
// performant
|
||||
let modulus = U384::from_be_slice(&modulus).checked_add(&U384::ONE).unwrap();
|
||||
|
||||
// The defined P-256 and secp256k1 ciphersuites both use expand_message_xmd
|
||||
let mut wide = U384::from_be_bytes({
|
||||
let mut bytes = [0; 48];
|
||||
ExpandMsgXmd::<Sha256>::expand_message(&[msg], &[dst], 48)
|
||||
.unwrap()
|
||||
.fill_bytes(&mut bytes);
|
||||
bytes
|
||||
})
|
||||
.rem(&NonZero::new(modulus).unwrap())
|
||||
.to_be_bytes();
|
||||
|
||||
// Now that this has been reduced back to a 32-byte value, grab the lower 32-bytes
|
||||
let mut array = *GenericArray::from_slice(&wide[16 ..]);
|
||||
let res = $lib::Scalar::from_repr(array).unwrap();
|
||||
|
||||
// Zeroize the temp values we can due to the possibility hash_to_F is being used for nonces
|
||||
wide.zeroize();
|
||||
array.zeroize();
|
||||
res
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn test_oversize_dst<C: Ciphersuite>() {
|
||||
use sha2::Digest;
|
||||
|
||||
// The draft specifies DSTs >255 bytes should be hashed into a 32-byte DST
|
||||
let oversize_dst = [0x00; 256];
|
||||
let actual_dst = Sha256::digest([b"H2C-OVERSIZE-DST-".as_ref(), &oversize_dst].concat());
|
||||
// Test the hash_to_F function handles this
|
||||
// If it didn't, these would return different values
|
||||
assert_eq!(C::hash_to_F(&oversize_dst, &[]), C::hash_to_F(&actual_dst, &[]));
|
||||
}
|
||||
|
||||
/// Ciphersuite for Secp256k1.
|
||||
///
|
||||
/// hash_to_F is implemented via the IETF draft for hash to curve's hash_to_field (v16).
|
||||
#[cfg(feature = "secp256k1")]
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug, Zeroize)]
|
||||
pub struct Secp256k1;
|
||||
#[cfg(feature = "secp256k1")]
|
||||
kp_curve!("secp256k1", k256, Secp256k1, b"secp256k1");
|
||||
#[cfg(feature = "secp256k1")]
|
||||
#[test]
|
||||
fn test_secp256k1() {
|
||||
ff_group_tests::group::test_prime_group_bits::<_, k256::ProjectivePoint>(&mut rand_core::OsRng);
|
||||
|
||||
// Ideally, a test vector from hash_to_field (not FROST) would be here
|
||||
// Unfortunately, the IETF draft only provides vectors for field elements, not scalars
|
||||
// Vectors have been requested in
|
||||
// https://github.com/cfrg/draft-irtf-cfrg-hash-to-curve/issues/343
|
||||
|
||||
assert_eq!(
|
||||
Secp256k1::hash_to_F(
|
||||
b"FROST-secp256k1-SHA256-v11nonce",
|
||||
&hex::decode(
|
||||
"\
|
||||
80cbea5e405d169999d8c4b30b755fedb26ab07ec8198cda4873ed8ce5e16773\
|
||||
08f89ffe80ac94dcb920c26f3f46140bfc7f95b493f8310f5fc1ea2b01f4254c"
|
||||
)
|
||||
.unwrap()
|
||||
)
|
||||
.to_repr()
|
||||
.iter()
|
||||
.copied()
|
||||
.collect::<Vec<_>>(),
|
||||
hex::decode("acc83278035223c1ba464e2d11bfacfc872b2b23e1041cf5f6130da21e4d8068").unwrap()
|
||||
);
|
||||
|
||||
test_oversize_dst::<Secp256k1>();
|
||||
}
|
||||
|
||||
/// Ciphersuite for P-256.
|
||||
///
|
||||
/// hash_to_F is implemented via the IETF draft for hash to curve's hash_to_field (v16).
|
||||
#[cfg(feature = "p256")]
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug, Zeroize)]
|
||||
pub struct P256;
|
||||
#[cfg(feature = "p256")]
|
||||
kp_curve!("p256", p256, P256, b"P-256");
|
||||
#[cfg(feature = "p256")]
|
||||
#[test]
|
||||
fn test_p256() {
|
||||
ff_group_tests::group::test_prime_group_bits::<_, p256::ProjectivePoint>(&mut rand_core::OsRng);
|
||||
|
||||
assert_eq!(
|
||||
P256::hash_to_F(
|
||||
b"FROST-P256-SHA256-v11nonce",
|
||||
&hex::decode(
|
||||
"\
|
||||
f4e8cf80aec3f888d997900ac7e3e349944b5a6b47649fc32186d2f1238103c6\
|
||||
0c9c1a0fe806c184add50bbdcac913dda73e482daf95dcb9f35dbb0d8a9f7731"
|
||||
)
|
||||
.unwrap()
|
||||
)
|
||||
.to_repr()
|
||||
.iter()
|
||||
.copied()
|
||||
.collect::<Vec<_>>(),
|
||||
hex::decode("f871dfcf6bcd199342651adc361b92c941cb6a0d8c8c1a3b91d79e2c1bf3722d").unwrap()
|
||||
);
|
||||
|
||||
test_oversize_dst::<P256>();
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
Ciphersuites for elliptic curves premised on ff/group.
|
||||
|
||||
This library, except for the not recommended Ed448 ciphersuite, was
|
||||
This library was
|
||||
[audited by Cypher Stack in March 2023](https://github.com/serai-dex/serai/raw/e1bb2c191b7123fd260d008e31656d090d559d21/audits/Cypher%20Stack%20crypto%20March%202023/Audit.pdf),
|
||||
culminating in commit
|
||||
[669d2dbffc1dafb82a09d9419ea182667115df06](https://github.com/serai-dex/serai/tree/669d2dbffc1dafb82a09d9419ea182667115df06).
|
||||
|
||||
@@ -3,7 +3,10 @@
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
|
||||
use core::fmt::Debug;
|
||||
#[cfg(any(feature = "alloc", feature = "std"))]
|
||||
#[cfg(feature = "alloc")]
|
||||
#[allow(unused_imports)]
|
||||
use std_shims::prelude::*;
|
||||
#[cfg(feature = "alloc")]
|
||||
use std_shims::io::{self, Read};
|
||||
|
||||
use rand_core::{RngCore, CryptoRng};
|
||||
@@ -11,7 +14,8 @@ use rand_core::{RngCore, CryptoRng};
|
||||
use zeroize::Zeroize;
|
||||
use subtle::ConstantTimeEq;
|
||||
|
||||
use digest::{core_api::BlockSizeUser, Digest, HashMarker};
|
||||
pub use digest;
|
||||
use digest::{array::ArraySize, block_api::BlockSizeUser, OutputSizeUser, Digest, HashMarker};
|
||||
use transcript::SecureDigest;
|
||||
|
||||
pub use group;
|
||||
@@ -20,27 +24,17 @@ use group::{
|
||||
Group, GroupOps,
|
||||
prime::PrimeGroup,
|
||||
};
|
||||
#[cfg(any(feature = "alloc", feature = "std"))]
|
||||
#[cfg(feature = "alloc")]
|
||||
use group::GroupEncoding;
|
||||
|
||||
#[cfg(feature = "dalek")]
|
||||
mod dalek;
|
||||
#[cfg(feature = "ristretto")]
|
||||
pub use dalek::Ristretto;
|
||||
#[cfg(feature = "ed25519")]
|
||||
pub use dalek::Ed25519;
|
||||
|
||||
#[cfg(feature = "kp256")]
|
||||
mod kp256;
|
||||
#[cfg(feature = "secp256k1")]
|
||||
pub use kp256::Secp256k1;
|
||||
#[cfg(feature = "p256")]
|
||||
pub use kp256::P256;
|
||||
|
||||
#[cfg(feature = "ed448")]
|
||||
mod ed448;
|
||||
#[cfg(feature = "ed448")]
|
||||
pub use ed448::*;
|
||||
pub trait FromUniformBytes<T> {
|
||||
fn from_uniform_bytes(bytes: &T) -> Self;
|
||||
}
|
||||
impl<const N: usize, F: group::ff::FromUniformBytes<N>> FromUniformBytes<[u8; N]> for F {
|
||||
fn from_uniform_bytes(bytes: &[u8; N]) -> Self {
|
||||
F::from_uniform_bytes(bytes)
|
||||
}
|
||||
}
|
||||
|
||||
/// Unified trait defining a ciphersuite around an elliptic curve.
|
||||
pub trait Ciphersuite:
|
||||
@@ -48,7 +42,10 @@ pub trait Ciphersuite:
|
||||
{
|
||||
/// Scalar field element type.
|
||||
// This is available via G::Scalar yet `C::G::Scalar` is ambiguous, forcing horrific accesses
|
||||
type F: PrimeField + PrimeFieldBits + Zeroize;
|
||||
type F: PrimeField
|
||||
+ PrimeFieldBits
|
||||
+ Zeroize
|
||||
+ FromUniformBytes<<<Self::H as OutputSizeUser>::OutputSize as ArraySize>::ArrayType<u8>>;
|
||||
/// Group element type.
|
||||
type G: Group<Scalar = Self::F> + GroupOps + PrimeGroup + Zeroize + ConstantTimeEq;
|
||||
/// Hash algorithm used with this curve.
|
||||
@@ -62,22 +59,10 @@ pub trait Ciphersuite:
|
||||
// While group does provide this in its API, privacy coins may want to use a custom basepoint
|
||||
fn generator() -> Self::G;
|
||||
|
||||
/// Reduce 512 bits into a uniform scalar.
|
||||
///
|
||||
/// If 512 bits is insufficient to perform a reduction into a uniform scalar, the ciphersuite
|
||||
/// will perform a hash to sample the necessary bits.
|
||||
fn reduce_512(scalar: [u8; 64]) -> Self::F;
|
||||
|
||||
/// Hash the provided domain-separation tag and message to a scalar. Ciphersuites MAY naively
|
||||
/// prefix the tag to the message, enabling transpotion between the two. Accordingly, this
|
||||
/// function should NOT be used in any scheme where one tag is a valid substring of another
|
||||
/// UNLESS the specific Ciphersuite is verified to handle the DST securely.
|
||||
///
|
||||
/// Verifying specific ciphersuites have secure tag handling is not recommended, due to it
|
||||
/// breaking the intended modularity of ciphersuites. Instead, component-specific tags with
|
||||
/// further purpose tags are recommended ("Schnorr-nonce", "Schnorr-chal").
|
||||
#[allow(non_snake_case)]
|
||||
fn hash_to_F(dst: &[u8], msg: &[u8]) -> Self::F;
|
||||
fn hash_to_F(data: &[u8]) -> Self::F {
|
||||
Self::F::from_uniform_bytes(&Self::H::digest(data).into())
|
||||
}
|
||||
|
||||
/// Generate a random non-zero scalar.
|
||||
#[allow(non_snake_case)]
|
||||
@@ -91,7 +76,7 @@ pub trait Ciphersuite:
|
||||
}
|
||||
|
||||
/// Read a canonical scalar from something implementing std::io::Read.
|
||||
#[cfg(any(feature = "alloc", feature = "std"))]
|
||||
#[cfg(feature = "alloc")]
|
||||
#[allow(non_snake_case)]
|
||||
fn read_F<R: Read>(reader: &mut R) -> io::Result<Self::F> {
|
||||
let mut encoding = <Self::F as PrimeField>::Repr::default();
|
||||
@@ -108,7 +93,7 @@ pub trait Ciphersuite:
|
||||
///
|
||||
/// The provided implementation is safe so long as `GroupEncoding::to_bytes` always returns a
|
||||
/// canonical serialization.
|
||||
#[cfg(any(feature = "alloc", feature = "std"))]
|
||||
#[cfg(feature = "alloc")]
|
||||
#[allow(non_snake_case)]
|
||||
fn read_G<R: Read>(reader: &mut R) -> io::Result<Self::G> {
|
||||
let mut encoding = <Self::G as GroupEncoding>::Repr::default();
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
[package]
|
||||
name = "dalek-ff-group"
|
||||
version = "0.4.1"
|
||||
version = "0.4.6"
|
||||
description = "ff/group bindings around curve25519-dalek"
|
||||
license = "MIT"
|
||||
repository = "https://github.com/serai-dex/serai/tree/develop/crypto/dalek-ff-group"
|
||||
authors = ["Luke Parker <lukeparker5132@gmail.com>"]
|
||||
keywords = ["curve25519", "ed25519", "ristretto", "dalek", "group"]
|
||||
edition = "2021"
|
||||
rust-version = "1.71"
|
||||
rust-version = "1.85"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
all-features = true
|
||||
@@ -17,26 +17,27 @@ rustdoc-args = ["--cfg", "docsrs"]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
rustversion = "1"
|
||||
|
||||
zeroize = { version = "^1.5", default-features = false, features = ["zeroize_derive"] }
|
||||
subtle = { version = "^2.4", default-features = false }
|
||||
|
||||
rand_core = { version = "0.6", default-features = false }
|
||||
|
||||
digest = { version = "0.10", default-features = false }
|
||||
sha2 = { version = "0.11.0-rc.0", default-features = false }
|
||||
|
||||
ff = { version = "0.13", default-features = false, features = ["bits"] }
|
||||
group = { version = "0.13", default-features = false }
|
||||
prime-field = { path = "../prime-field", default-features = false }
|
||||
ciphersuite = { version = "0.4.2", path = "../ciphersuite", default-features = false }
|
||||
|
||||
crypto-bigint = { version = "0.5", default-features = false, features = ["zeroize"] }
|
||||
|
||||
curve25519-dalek = { version = ">= 4.0, < 4.2", default-features = false, features = ["alloc", "zeroize", "digest", "group", "precomputed-tables"] }
|
||||
curve25519-dalek = { version = ">= 4.0, < 4.2", default-features = false, features = ["zeroize", "digest", "group", "precomputed-tables"] }
|
||||
|
||||
[dev-dependencies]
|
||||
hex = "0.4"
|
||||
rand_core = { version = "0.6", default-features = false, features = ["std"] }
|
||||
ff-group-tests = { path = "../ff-group-tests" }
|
||||
|
||||
[features]
|
||||
std = ["zeroize/std", "subtle/std", "rand_core/std", "digest/std"]
|
||||
alloc = ["zeroize/alloc", "digest/alloc", "prime-field/alloc", "ciphersuite/alloc", "curve25519-dalek/alloc"]
|
||||
std = ["alloc", "zeroize/std", "subtle/std", "rand_core/std", "digest/std", "prime-field/std", "ciphersuite/std"]
|
||||
default = ["std"]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2022-2023 Luke Parker
|
||||
Copyright (c) 2022-2025 Luke Parker
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
|
||||
49
crypto/dalek-ff-group/src/ciphersuite.rs
Normal file
49
crypto/dalek-ff-group/src/ciphersuite.rs
Normal file
@@ -0,0 +1,49 @@
|
||||
use zeroize::Zeroize;
|
||||
|
||||
use sha2::Sha512;
|
||||
|
||||
use ciphersuite::{group::Group, Ciphersuite};
|
||||
|
||||
use crate::Scalar;
|
||||
|
||||
macro_rules! dalek_curve {
|
||||
(
|
||||
$feature: literal,
|
||||
|
||||
$Ciphersuite: ident,
|
||||
$Point: ident,
|
||||
$ID: literal
|
||||
) => {
|
||||
use crate::$Point;
|
||||
|
||||
impl Ciphersuite for $Ciphersuite {
|
||||
type F = Scalar;
|
||||
type G = $Point;
|
||||
type H = Sha512;
|
||||
|
||||
const ID: &'static [u8] = $ID;
|
||||
|
||||
fn generator() -> Self::G {
|
||||
$Point::generator()
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// Ciphersuite for Ristretto.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug, Zeroize)]
|
||||
pub struct Ristretto;
|
||||
dalek_curve!("ristretto", Ristretto, RistrettoPoint, b"ristretto");
|
||||
#[test]
|
||||
fn test_ristretto() {
|
||||
ff_group_tests::group::test_prime_group_bits::<_, RistrettoPoint>(&mut rand_core::OsRng);
|
||||
}
|
||||
|
||||
/// Ciphersuite for Ed25519, inspired by RFC-8032.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug, Zeroize)]
|
||||
pub struct Ed25519;
|
||||
dalek_curve!("ed25519", Ed25519, EdwardsPoint, b"edwards25519");
|
||||
#[test]
|
||||
fn test_ed25519() {
|
||||
ff_group_tests::group::test_prime_group_bits::<_, EdwardsPoint>(&mut rand_core::OsRng);
|
||||
}
|
||||
@@ -1,359 +0,0 @@
|
||||
use core::{
|
||||
ops::{Add, AddAssign, Sub, SubAssign, Neg, Mul, MulAssign},
|
||||
iter::{Sum, Product},
|
||||
};
|
||||
|
||||
use zeroize::Zeroize;
|
||||
use rand_core::RngCore;
|
||||
|
||||
use subtle::{
|
||||
Choice, CtOption, ConstantTimeEq, ConstantTimeLess, ConditionallyNegatable,
|
||||
ConditionallySelectable,
|
||||
};
|
||||
|
||||
use crypto_bigint::{
|
||||
Integer, NonZero, Encoding, U256, U512,
|
||||
modular::constant_mod::{ResidueParams, Residue},
|
||||
impl_modulus,
|
||||
};
|
||||
|
||||
use group::ff::{Field, PrimeField, FieldBits, PrimeFieldBits};
|
||||
|
||||
use crate::{u8_from_bool, constant_time, math_op, math};
|
||||
|
||||
// 2 ** 255 - 19
|
||||
// Uses saturating_sub because checked_sub isn't available at compile time
|
||||
const MODULUS: U256 = U256::from_u8(1).shl_vartime(255).saturating_sub(&U256::from_u8(19));
|
||||
const WIDE_MODULUS: U512 = U256::ZERO.concat(&MODULUS);
|
||||
|
||||
impl_modulus!(
|
||||
FieldModulus,
|
||||
U256,
|
||||
// 2 ** 255 - 19
|
||||
"7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"
|
||||
);
|
||||
type ResidueType = Residue<FieldModulus, { FieldModulus::LIMBS }>;
|
||||
|
||||
/// A constant-time implementation of the Ed25519 field.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Default, Debug, Zeroize)]
|
||||
pub struct FieldElement(ResidueType);
|
||||
|
||||
// Square root of -1.
|
||||
// Formula from RFC-8032 (modp_sqrt_m1/sqrt8k5 z)
|
||||
// 2 ** ((MODULUS - 1) // 4) % MODULUS
|
||||
const SQRT_M1: FieldElement = FieldElement(
|
||||
ResidueType::new(&U256::from_u8(2))
|
||||
.pow(&MODULUS.saturating_sub(&U256::ONE).wrapping_div(&U256::from_u8(4))),
|
||||
);
|
||||
|
||||
// Constant useful in calculating square roots (RFC-8032 sqrt8k5's exponent used to calculate y)
|
||||
const MOD_3_8: FieldElement = FieldElement(ResidueType::new(
|
||||
&MODULUS.saturating_add(&U256::from_u8(3)).wrapping_div(&U256::from_u8(8)),
|
||||
));
|
||||
|
||||
// Constant useful in sqrt_ratio_i (sqrt(u / v))
|
||||
const MOD_5_8: FieldElement = FieldElement(ResidueType::sub(&MOD_3_8.0, &ResidueType::ONE));
|
||||
|
||||
fn reduce(x: U512) -> ResidueType {
|
||||
ResidueType::new(&U256::from_le_slice(
|
||||
&x.rem(&NonZero::new(WIDE_MODULUS).unwrap()).to_le_bytes()[.. 32],
|
||||
))
|
||||
}
|
||||
|
||||
constant_time!(FieldElement, ResidueType);
|
||||
math!(
|
||||
FieldElement,
|
||||
FieldElement,
|
||||
|x: ResidueType, y: ResidueType| x.add(&y),
|
||||
|x: ResidueType, y: ResidueType| x.sub(&y),
|
||||
|x: ResidueType, y: ResidueType| x.mul(&y)
|
||||
);
|
||||
|
||||
macro_rules! from_wrapper {
|
||||
($uint: ident) => {
|
||||
impl From<$uint> for FieldElement {
|
||||
fn from(a: $uint) -> FieldElement {
|
||||
Self(ResidueType::new(&U256::from(a)))
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
from_wrapper!(u8);
|
||||
from_wrapper!(u16);
|
||||
from_wrapper!(u32);
|
||||
from_wrapper!(u64);
|
||||
from_wrapper!(u128);
|
||||
|
||||
impl Neg for FieldElement {
|
||||
type Output = Self;
|
||||
fn neg(self) -> Self::Output {
|
||||
Self(self.0.neg())
|
||||
}
|
||||
}
|
||||
|
||||
impl Neg for &FieldElement {
|
||||
type Output = FieldElement;
|
||||
fn neg(self) -> Self::Output {
|
||||
(*self).neg()
|
||||
}
|
||||
}
|
||||
|
||||
impl Field for FieldElement {
|
||||
const ZERO: Self = Self(ResidueType::ZERO);
|
||||
const ONE: Self = Self(ResidueType::ONE);
|
||||
|
||||
fn random(mut rng: impl RngCore) -> Self {
|
||||
let mut bytes = [0; 64];
|
||||
rng.fill_bytes(&mut bytes);
|
||||
FieldElement(reduce(U512::from_le_bytes(bytes)))
|
||||
}
|
||||
|
||||
fn square(&self) -> Self {
|
||||
FieldElement(self.0.square())
|
||||
}
|
||||
fn double(&self) -> Self {
|
||||
FieldElement(self.0.add(&self.0))
|
||||
}
|
||||
|
||||
fn invert(&self) -> CtOption<Self> {
|
||||
const NEG_2: FieldElement =
|
||||
FieldElement(ResidueType::new(&MODULUS.saturating_sub(&U256::from_u8(2))));
|
||||
CtOption::new(self.pow(NEG_2), !self.is_zero())
|
||||
}
|
||||
|
||||
// RFC-8032 sqrt8k5
|
||||
fn sqrt(&self) -> CtOption<Self> {
|
||||
let tv1 = self.pow(MOD_3_8);
|
||||
let tv2 = tv1 * SQRT_M1;
|
||||
let candidate = Self::conditional_select(&tv2, &tv1, tv1.square().ct_eq(self));
|
||||
CtOption::new(candidate, candidate.square().ct_eq(self))
|
||||
}
|
||||
|
||||
fn sqrt_ratio(u: &FieldElement, v: &FieldElement) -> (Choice, FieldElement) {
|
||||
let i = SQRT_M1;
|
||||
|
||||
let u = *u;
|
||||
let v = *v;
|
||||
|
||||
let v3 = v.square() * v;
|
||||
let v7 = v3.square() * v;
|
||||
let mut r = (u * v3) * (u * v7).pow(MOD_5_8);
|
||||
|
||||
let check = v * r.square();
|
||||
let correct_sign = check.ct_eq(&u);
|
||||
let flipped_sign = check.ct_eq(&(-u));
|
||||
let flipped_sign_i = check.ct_eq(&((-u) * i));
|
||||
|
||||
r.conditional_assign(&(r * i), flipped_sign | flipped_sign_i);
|
||||
|
||||
let r_is_negative = r.is_odd();
|
||||
r.conditional_negate(r_is_negative);
|
||||
|
||||
(correct_sign | flipped_sign, r)
|
||||
}
|
||||
}
|
||||
|
||||
impl PrimeField for FieldElement {
|
||||
type Repr = [u8; 32];
|
||||
|
||||
// Big endian representation of the modulus
|
||||
const MODULUS: &'static str = "7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed";
|
||||
|
||||
const NUM_BITS: u32 = 255;
|
||||
const CAPACITY: u32 = 254;
|
||||
|
||||
const TWO_INV: Self = FieldElement(ResidueType::new(&U256::from_u8(2)).invert().0);
|
||||
|
||||
// This was calculated with the method from the ff crate docs
|
||||
// SageMath GF(modulus).primitive_element()
|
||||
const MULTIPLICATIVE_GENERATOR: Self = Self(ResidueType::new(&U256::from_u8(2)));
|
||||
// This was set per the specification in the ff crate docs
|
||||
// The number of leading zero bits in the little-endian bit representation of (modulus - 1)
|
||||
const S: u32 = 2;
|
||||
|
||||
// This was calculated via the formula from the ff crate docs
|
||||
// Self::MULTIPLICATIVE_GENERATOR ** ((modulus - 1) >> Self::S)
|
||||
const ROOT_OF_UNITY: Self = FieldElement(ResidueType::new(&U256::from_be_hex(
|
||||
"2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0",
|
||||
)));
|
||||
// Self::ROOT_OF_UNITY.invert()
|
||||
const ROOT_OF_UNITY_INV: Self = FieldElement(Self::ROOT_OF_UNITY.0.invert().0);
|
||||
|
||||
// This was calculated via the formula from the ff crate docs
|
||||
// Self::MULTIPLICATIVE_GENERATOR ** (2 ** Self::S)
|
||||
const DELTA: Self = FieldElement(ResidueType::new(&U256::from_be_hex(
|
||||
"0000000000000000000000000000000000000000000000000000000000000010",
|
||||
)));
|
||||
|
||||
fn from_repr(bytes: [u8; 32]) -> CtOption<Self> {
|
||||
let res = U256::from_le_bytes(bytes);
|
||||
CtOption::new(Self(ResidueType::new(&res)), res.ct_lt(&MODULUS))
|
||||
}
|
||||
fn to_repr(&self) -> [u8; 32] {
|
||||
self.0.retrieve().to_le_bytes()
|
||||
}
|
||||
|
||||
fn is_odd(&self) -> Choice {
|
||||
self.0.retrieve().is_odd()
|
||||
}
|
||||
|
||||
fn from_u128(num: u128) -> Self {
|
||||
Self::from(num)
|
||||
}
|
||||
}
|
||||
|
||||
impl PrimeFieldBits for FieldElement {
|
||||
type ReprBits = [u8; 32];
|
||||
|
||||
fn to_le_bits(&self) -> FieldBits<Self::ReprBits> {
|
||||
self.to_repr().into()
|
||||
}
|
||||
|
||||
fn char_le_bits() -> FieldBits<Self::ReprBits> {
|
||||
MODULUS.to_le_bytes().into()
|
||||
}
|
||||
}
|
||||
|
||||
impl FieldElement {
|
||||
/// Interpret the value as a little-endian integer, square it, and reduce it into a FieldElement.
|
||||
pub fn from_square(value: [u8; 32]) -> FieldElement {
|
||||
let value = U256::from_le_bytes(value);
|
||||
FieldElement(reduce(U512::from(value.mul_wide(&value))))
|
||||
}
|
||||
|
||||
/// Perform an exponentiation.
|
||||
pub fn pow(&self, other: FieldElement) -> FieldElement {
|
||||
let mut table = [FieldElement::ONE; 16];
|
||||
table[1] = *self;
|
||||
for i in 2 .. 16 {
|
||||
table[i] = table[i - 1] * self;
|
||||
}
|
||||
|
||||
let mut res = FieldElement::ONE;
|
||||
let mut bits = 0;
|
||||
for (i, mut bit) in other.to_le_bits().iter_mut().rev().enumerate() {
|
||||
bits <<= 1;
|
||||
let mut bit = u8_from_bool(&mut bit);
|
||||
bits |= bit;
|
||||
bit.zeroize();
|
||||
|
||||
if ((i + 1) % 4) == 0 {
|
||||
if i != 3 {
|
||||
for _ in 0 .. 4 {
|
||||
res *= res;
|
||||
}
|
||||
}
|
||||
|
||||
let mut scale_by = FieldElement::ONE;
|
||||
#[allow(clippy::needless_range_loop)]
|
||||
for i in 0 .. 16 {
|
||||
#[allow(clippy::cast_possible_truncation)] // Safe since 0 .. 16
|
||||
{
|
||||
scale_by = <_>::conditional_select(&scale_by, &table[i], bits.ct_eq(&(i as u8)));
|
||||
}
|
||||
}
|
||||
res *= scale_by;
|
||||
bits = 0;
|
||||
}
|
||||
}
|
||||
res
|
||||
}
|
||||
|
||||
/// The square root of u/v, as used for Ed25519 point decoding (RFC 8032 5.1.3) and within
|
||||
/// Ristretto (5.1 Extracting an Inverse Square Root).
|
||||
///
|
||||
/// The result is only a valid square root if the Choice is true.
|
||||
/// RFC 8032 simply fails if there isn't a square root, leaving any return value undefined.
|
||||
/// Ristretto explicitly returns 0 or sqrt((SQRT_M1 * u) / v).
|
||||
pub fn sqrt_ratio_i(u: FieldElement, v: FieldElement) -> (Choice, FieldElement) {
|
||||
let i = SQRT_M1;
|
||||
|
||||
let v3 = v.square() * v;
|
||||
let v7 = v3.square() * v;
|
||||
// Candidate root
|
||||
let mut r = (u * v3) * (u * v7).pow(MOD_5_8);
|
||||
|
||||
// 8032 3.1
|
||||
let check = v * r.square();
|
||||
let correct_sign = check.ct_eq(&u);
|
||||
// 8032 3.2 conditional
|
||||
let neg_u = -u;
|
||||
let flipped_sign = check.ct_eq(&neg_u);
|
||||
// Ristretto Step 5
|
||||
let flipped_sign_i = check.ct_eq(&(neg_u * i));
|
||||
|
||||
// 3.2 set
|
||||
r.conditional_assign(&(r * i), flipped_sign | flipped_sign_i);
|
||||
|
||||
// Always return the even root, per Ristretto
|
||||
// This doesn't break Ed25519 point decoding as that doesn't expect these steps to return a
|
||||
// specific root
|
||||
// Ed25519 points include a dedicated sign bit to determine which root to use, so at worst
|
||||
// this is a pointless inefficiency
|
||||
r.conditional_negate(r.is_odd());
|
||||
|
||||
(correct_sign | flipped_sign, r)
|
||||
}
|
||||
}
|
||||
|
||||
impl Sum<FieldElement> for FieldElement {
|
||||
fn sum<I: Iterator<Item = FieldElement>>(iter: I) -> FieldElement {
|
||||
let mut res = FieldElement::ZERO;
|
||||
for item in iter {
|
||||
res += item;
|
||||
}
|
||||
res
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Sum<&'a FieldElement> for FieldElement {
|
||||
fn sum<I: Iterator<Item = &'a FieldElement>>(iter: I) -> FieldElement {
|
||||
iter.copied().sum()
|
||||
}
|
||||
}
|
||||
|
||||
impl Product<FieldElement> for FieldElement {
|
||||
fn product<I: Iterator<Item = FieldElement>>(iter: I) -> FieldElement {
|
||||
let mut res = FieldElement::ONE;
|
||||
for item in iter {
|
||||
res *= item;
|
||||
}
|
||||
res
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Product<&'a FieldElement> for FieldElement {
|
||||
fn product<I: Iterator<Item = &'a FieldElement>>(iter: I) -> FieldElement {
|
||||
iter.copied().product()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_wide_modulus() {
|
||||
let mut wide = [0; 64];
|
||||
wide[.. 32].copy_from_slice(&MODULUS.to_le_bytes());
|
||||
assert_eq!(wide, WIDE_MODULUS.to_le_bytes());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sqrt_m1() {
|
||||
// Test equivalence against the known constant value
|
||||
const SQRT_M1_MAGIC: U256 =
|
||||
U256::from_be_hex("2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0");
|
||||
assert_eq!(SQRT_M1.0.retrieve(), SQRT_M1_MAGIC);
|
||||
|
||||
// Also test equivalence against the result of the formula from RFC-8032 (modp_sqrt_m1/sqrt8k5 z)
|
||||
// 2 ** ((MODULUS - 1) // 4) % MODULUS
|
||||
assert_eq!(
|
||||
SQRT_M1,
|
||||
FieldElement::from(2u8).pow(FieldElement(ResidueType::new(
|
||||
&(FieldElement::ZERO - FieldElement::ONE).0.retrieve().wrapping_div(&U256::from(4u8))
|
||||
)))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_field() {
|
||||
ff_group_tests::prime_field::test_prime_field_bits::<_, FieldElement>(&mut rand_core::OsRng);
|
||||
}
|
||||
@@ -29,22 +29,16 @@ use dalek::{
|
||||
};
|
||||
pub use constants::{ED25519_BASEPOINT_TABLE, RISTRETTO_BASEPOINT_TABLE};
|
||||
|
||||
use group::{
|
||||
ff::{Field, PrimeField, FieldBits, PrimeFieldBits},
|
||||
use ::ciphersuite::group::{
|
||||
ff::{Field, PrimeField, FieldBits, PrimeFieldBits, FromUniformBytes},
|
||||
Group, GroupEncoding,
|
||||
prime::PrimeGroup,
|
||||
};
|
||||
|
||||
mod field;
|
||||
pub use field::FieldElement;
|
||||
mod ciphersuite;
|
||||
pub use crate::ciphersuite::{Ed25519, Ristretto};
|
||||
|
||||
// Use black_box when possible
|
||||
#[rustversion::since(1.66)]
|
||||
use core::hint::black_box;
|
||||
#[rustversion::before(1.66)]
|
||||
fn black_box<T>(val: T) -> T {
|
||||
val
|
||||
}
|
||||
|
||||
fn u8_from_bool(bit_ref: &mut bool) -> u8 {
|
||||
let bit_ref = black_box(bit_ref);
|
||||
@@ -314,6 +308,12 @@ impl PrimeFieldBits for Scalar {
|
||||
}
|
||||
}
|
||||
|
||||
impl FromUniformBytes<64> for Scalar {
|
||||
fn from_uniform_bytes(bytes: &[u8; 64]) -> Self {
|
||||
Self::from_bytes_mod_order_wide(bytes)
|
||||
}
|
||||
}
|
||||
|
||||
impl Sum<Scalar> for Scalar {
|
||||
fn sum<I: Iterator<Item = Scalar>>(iter: I) -> Scalar {
|
||||
Self(DScalar::sum(iter))
|
||||
@@ -351,7 +351,12 @@ macro_rules! dalek_group {
|
||||
$BASEPOINT_POINT: ident,
|
||||
$BASEPOINT_TABLE: ident
|
||||
) => {
|
||||
/// Wrapper around the dalek Point type. For Ed25519, this is restricted to the prime subgroup.
|
||||
/// Wrapper around the dalek Point type.
|
||||
///
|
||||
/// All operations will be restricted to a prime-order subgroup (equivalent to the group itself
|
||||
/// in the case of Ristretto). The exposure of the internal element does allow bypassing this
|
||||
/// however, which may lead to undefined/computationally-unsafe behavior, and is entirely at
|
||||
/// the user's risk.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug, Zeroize)]
|
||||
pub struct $Point(pub $DPoint);
|
||||
deref_borrow!($Point, $DPoint);
|
||||
@@ -480,3 +485,30 @@ fn test_ed25519_group() {
|
||||
fn test_ristretto_group() {
|
||||
ff_group_tests::group::test_prime_group_bits::<_, RistrettoPoint>(&mut rand_core::OsRng);
|
||||
}
|
||||
|
||||
type ThirtyTwoArray = [u8; 32];
|
||||
prime_field::odd_prime_field_with_specific_repr!(
|
||||
FieldElement,
|
||||
"0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed",
|
||||
"02",
|
||||
false,
|
||||
crate::ThirtyTwoArray
|
||||
);
|
||||
|
||||
impl FieldElement {
|
||||
/// Create a FieldElement from a `crypto_bigint::U256`.
|
||||
///
|
||||
/// This will reduce the `U256` by the modulus, into a member of the field.
|
||||
#[deprecated]
|
||||
pub const fn from_u256(u256: &crypto_bigint::U256) -> Self {
|
||||
FieldElement::from(&prime_field::crypto_bigint::U256::from_words(*u256.as_words()))
|
||||
}
|
||||
|
||||
/// Create a `FieldElement` from the reduction of a 512-bit number.
|
||||
///
|
||||
/// The bytes are interpreted in little-endian format.
|
||||
#[deprecated]
|
||||
pub fn wide_reduce(value: [u8; 64]) -> Self {
|
||||
<FieldElement as ::ciphersuite::group::ff::FromUniformBytes<_>>::from_uniform_bytes(&value)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
[package]
|
||||
name = "dkg"
|
||||
version = "0.5.1"
|
||||
version = "0.6.1"
|
||||
description = "Distributed key generation over ff/group"
|
||||
license = "MIT"
|
||||
repository = "https://github.com/serai-dex/serai/tree/develop/crypto/dkg"
|
||||
authors = ["Luke Parker <lukeparker5132@gmail.com>"]
|
||||
keywords = ["dkg", "multisig", "threshold", "ff", "group"]
|
||||
edition = "2021"
|
||||
rust-version = "1.81"
|
||||
rust-version = "1.85"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
all-features = true
|
||||
@@ -17,82 +17,25 @@ rustdoc-args = ["--cfg", "docsrs"]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
zeroize = { version = "^1.5", default-features = false, features = ["zeroize_derive", "alloc"] }
|
||||
|
||||
thiserror = { version = "2", default-features = false }
|
||||
|
||||
rand_core = { version = "0.6", default-features = false }
|
||||
|
||||
zeroize = { version = "^1.5", default-features = false, features = ["zeroize_derive"] }
|
||||
|
||||
std-shims = { version = "0.1", path = "../../common/std-shims", default-features = false }
|
||||
|
||||
borsh = { version = "1", default-features = false, features = ["derive", "de_strict_order"], optional = true }
|
||||
|
||||
transcript = { package = "flexible-transcript", path = "../transcript", version = "^0.3.2", default-features = false, features = ["recommended"] }
|
||||
chacha20 = { version = "0.9", default-features = false, features = ["zeroize"] }
|
||||
|
||||
ciphersuite = { path = "../ciphersuite", version = "^0.4.1", default-features = false }
|
||||
multiexp = { path = "../multiexp", version = "0.4", default-features = false }
|
||||
|
||||
schnorr = { package = "schnorr-signatures", path = "../schnorr", version = "^0.5.1", default-features = false }
|
||||
dleq = { path = "../dleq", version = "^0.4.1", default-features = false }
|
||||
|
||||
# eVRF DKG dependencies
|
||||
generic-array = { version = "1", default-features = false, features = ["alloc"], optional = true }
|
||||
blake2 = { version = "0.10", default-features = false, features = ["std"], optional = true }
|
||||
rand_chacha = { version = "0.3", default-features = false, features = ["std"], optional = true }
|
||||
generalized-bulletproofs = { path = "../evrf/generalized-bulletproofs", default-features = false, optional = true }
|
||||
ec-divisors = { path = "../evrf/divisors", default-features = false, optional = true }
|
||||
generalized-bulletproofs-circuit-abstraction = { path = "../evrf/circuit-abstraction", optional = true }
|
||||
generalized-bulletproofs-ec-gadgets = { path = "../evrf/ec-gadgets", optional = true }
|
||||
|
||||
secq256k1 = { path = "../evrf/secq256k1", optional = true }
|
||||
embedwards25519 = { path = "../evrf/embedwards25519", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
rand_core = { version = "0.6", default-features = false, features = ["getrandom"] }
|
||||
rand = { version = "0.8", default-features = false, features = ["std"] }
|
||||
ciphersuite = { path = "../ciphersuite", default-features = false, features = ["ristretto"] }
|
||||
generalized-bulletproofs = { path = "../evrf/generalized-bulletproofs", features = ["tests"] }
|
||||
ec-divisors = { path = "../evrf/divisors", features = ["pasta"] }
|
||||
pasta_curves = { git = "https://github.com/kayabaNerve/pasta_curves", rev = "a46b5be95cacbff54d06aad8d3bbcba42e05d616" }
|
||||
ciphersuite = { path = "../ciphersuite", version = "^0.4.1", default-features = false, features = ["alloc"] }
|
||||
|
||||
[features]
|
||||
std = [
|
||||
"thiserror/std",
|
||||
|
||||
"rand_core/std",
|
||||
|
||||
"std-shims/std",
|
||||
|
||||
"borsh?/std",
|
||||
|
||||
"transcript/std",
|
||||
"chacha20/std",
|
||||
|
||||
"ciphersuite/std",
|
||||
"multiexp/std",
|
||||
"multiexp/batch",
|
||||
|
||||
"schnorr/std",
|
||||
"dleq/std",
|
||||
"dleq/serialize"
|
||||
]
|
||||
borsh = ["dep:borsh"]
|
||||
evrf = [
|
||||
"std",
|
||||
|
||||
"dep:generic-array",
|
||||
|
||||
"dep:blake2",
|
||||
"dep:rand_chacha",
|
||||
|
||||
"dep:generalized-bulletproofs",
|
||||
"dep:ec-divisors",
|
||||
"dep:generalized-bulletproofs-circuit-abstraction",
|
||||
"dep:generalized-bulletproofs-ec-gadgets",
|
||||
]
|
||||
evrf-secp256k1 = ["evrf", "ciphersuite/secp256k1", "secq256k1"]
|
||||
evrf-ed25519 = ["evrf", "ciphersuite/ed25519", "embedwards25519"]
|
||||
evrf-ristretto = ["evrf", "ciphersuite/ristretto", "embedwards25519"]
|
||||
tests = ["rand_core/getrandom"]
|
||||
default = ["std"]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2021-2023 Luke Parker
|
||||
Copyright (c) 2021-2025 Luke Parker
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
|
||||
@@ -1,16 +1,15 @@
|
||||
# Distributed Key Generation
|
||||
|
||||
A collection of implementations of various distributed key generation protocols.
|
||||
A crate implementing a type for keys, presumably the result of a distributed
|
||||
key generation protocol, and utilities from there.
|
||||
|
||||
All included protocols resolve into the provided `Threshold` types, intended to
|
||||
enable their modularity. Additional utilities around these types, such as
|
||||
promotion from one generator to another, are also provided.
|
||||
This crate used to host implementations of distributed key generation protocols
|
||||
as well (hence the name). Those have been smashed into their own crates, such
|
||||
as [`dkg-musig`](https://docs.rs/dkg-musig) and
|
||||
[`dkg-pedpop`](https://docs.rs/dkg-pedpop).
|
||||
|
||||
Currently, the only included protocol is the two-round protocol from the
|
||||
[FROST paper](https://eprint.iacr.org/2020/852).
|
||||
|
||||
This library was
|
||||
[audited by Cypher Stack in March 2023](https://github.com/serai-dex/serai/raw/e1bb2c191b7123fd260d008e31656d090d559d21/audits/Cypher%20Stack%20crypto%20March%202023/Audit.pdf),
|
||||
culminating in commit
|
||||
[669d2dbffc1dafb82a09d9419ea182667115df06](https://github.com/serai-dex/serai/tree/669d2dbffc1dafb82a09d9419ea182667115df06).
|
||||
Any subsequent changes have not undergone auditing.
|
||||
Before being smashed, this crate was [audited by Cypher Stack in March 2023](
|
||||
https://github.com/serai-dex/serai/raw/e1bb2c191b7123fd260d008e31656d090d559d21/audits/Cypher%20Stack%20crypto%20March%202023/Audit.pdf
|
||||
), culminating in commit [669d2dbffc1dafb82a09d9419ea182667115df06](
|
||||
https://github.com/serai-dex/serai/tree/669d2dbffc1dafb82a09d9419ea182667115df06
|
||||
). Any subsequent changes have not undergone auditing.
|
||||
|
||||
36
crypto/dkg/dealer/Cargo.toml
Normal file
36
crypto/dkg/dealer/Cargo.toml
Normal file
@@ -0,0 +1,36 @@
|
||||
[package]
|
||||
name = "dkg-dealer"
|
||||
version = "0.6.0"
|
||||
description = "Produce dkg::ThresholdKeys with a dealer key generation"
|
||||
license = "MIT"
|
||||
repository = "https://github.com/serai-dex/serai/tree/develop/crypto/dkg/dealer"
|
||||
authors = ["Luke Parker <lukeparker5132@gmail.com>"]
|
||||
keywords = ["dkg", "multisig", "threshold", "ff", "group"]
|
||||
edition = "2021"
|
||||
rust-version = "1.85"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
all-features = true
|
||||
rustdoc-args = ["--cfg", "docsrs"]
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
zeroize = { version = "^1.5", default-features = false }
|
||||
rand_core = { version = "0.6", default-features = false }
|
||||
|
||||
std-shims = { version = "0.1", path = "../../../common/std-shims", default-features = false }
|
||||
|
||||
ciphersuite = { path = "../../ciphersuite", version = "^0.4.1", default-features = false }
|
||||
dkg = { path = "../", version = "0.6", default-features = false }
|
||||
|
||||
[features]
|
||||
std = [
|
||||
"zeroize/std",
|
||||
"rand_core/std",
|
||||
"std-shims/std",
|
||||
"ciphersuite/std",
|
||||
"dkg/std",
|
||||
]
|
||||
default = ["std"]
|
||||
@@ -1,6 +1,6 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2024 Luke Parker
|
||||
Copyright (c) 2021-2025 Luke Parker
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
13
crypto/dkg/dealer/README.md
Normal file
13
crypto/dkg/dealer/README.md
Normal file
@@ -0,0 +1,13 @@
|
||||
# Distributed Key Generation - Dealer
|
||||
|
||||
This crate implements a dealer key generation protocol for the
|
||||
[`dkg`](https://docs.rs/dkg) crate's types. This provides a single point of
|
||||
failure when the key is being generated and is NOT recommended for use outside
|
||||
of tests.
|
||||
|
||||
This crate was originally part of (in some form) the `dkg` crate, which was
|
||||
[audited by Cypher Stack in March 2023](
|
||||
https://github.com/serai-dex/serai/raw/e1bb2c191b7123fd260d008e31656d090d559d21/audits/Cypher%20Stack%20crypto%20March%202023/Audit.pdf
|
||||
), culminating in commit [669d2dbffc1dafb82a09d9419ea182667115df06](
|
||||
https://github.com/serai-dex/serai/tree/669d2dbffc1dafb82a09d9419ea182667115df06
|
||||
). Any subsequent changes have not undergone auditing.
|
||||
68
crypto/dkg/dealer/src/lib.rs
Normal file
68
crypto/dkg/dealer/src/lib.rs
Normal file
@@ -0,0 +1,68 @@
|
||||
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
|
||||
#![doc = include_str!("../README.md")]
|
||||
#![no_std]
|
||||
|
||||
use core::ops::Deref;
|
||||
use std_shims::{vec::Vec, collections::HashMap};
|
||||
|
||||
use zeroize::{Zeroize, Zeroizing};
|
||||
use rand_core::{RngCore, CryptoRng};
|
||||
|
||||
use ciphersuite::{
|
||||
group::ff::{Field, PrimeField},
|
||||
Ciphersuite,
|
||||
};
|
||||
pub use dkg::*;
|
||||
|
||||
/// Create a key via a dealer key generation protocol.
|
||||
pub fn key_gen<R: RngCore + CryptoRng, C: Ciphersuite>(
|
||||
rng: &mut R,
|
||||
threshold: u16,
|
||||
participants: u16,
|
||||
) -> Result<HashMap<Participant, ThresholdKeys<C>>, DkgError> {
|
||||
let mut coefficients = Vec::with_capacity(usize::from(participants));
|
||||
// `.max(1)` so we always generate the 0th coefficient which we'll share
|
||||
for _ in 0 .. threshold.max(1) {
|
||||
coefficients.push(Zeroizing::new(C::F::random(&mut *rng)));
|
||||
}
|
||||
|
||||
fn polynomial<F: PrimeField + Zeroize>(
|
||||
coefficients: &[Zeroizing<F>],
|
||||
l: Participant,
|
||||
) -> Zeroizing<F> {
|
||||
let l = F::from(u64::from(u16::from(l)));
|
||||
// This should never be reached since Participant is explicitly non-zero
|
||||
assert!(l != F::ZERO, "zero participant passed to polynomial");
|
||||
let mut share = Zeroizing::new(F::ZERO);
|
||||
for (idx, coefficient) in coefficients.iter().rev().enumerate() {
|
||||
*share += coefficient.deref();
|
||||
if idx != (coefficients.len() - 1) {
|
||||
*share *= l;
|
||||
}
|
||||
}
|
||||
share
|
||||
}
|
||||
|
||||
let group_key = C::generator() * coefficients[0].deref();
|
||||
let mut secret_shares = HashMap::with_capacity(participants as usize);
|
||||
let mut verification_shares = HashMap::with_capacity(participants as usize);
|
||||
for i in 1 ..= participants {
|
||||
let i = Participant::new(i).expect("non-zero u16 wasn't a valid Participant index");
|
||||
let secret_share = polynomial(&coefficients, i);
|
||||
secret_shares.insert(i, secret_share.clone());
|
||||
verification_shares.insert(i, C::generator() * *secret_share);
|
||||
}
|
||||
|
||||
let mut res = HashMap::with_capacity(participants as usize);
|
||||
for (i, secret_share) in secret_shares {
|
||||
let keys = ThresholdKeys::new(
|
||||
ThresholdParams::new(threshold, participants, i)?,
|
||||
Interpolation::Lagrange,
|
||||
secret_share,
|
||||
verification_shares.clone(),
|
||||
)?;
|
||||
debug_assert_eq!(keys.group_key(), group_key);
|
||||
res.insert(i, keys);
|
||||
}
|
||||
Ok(res)
|
||||
}
|
||||
91
crypto/dkg/evrf/Cargo.toml
Normal file
91
crypto/dkg/evrf/Cargo.toml
Normal file
@@ -0,0 +1,91 @@
|
||||
[package]
|
||||
name = "dkg-evrf"
|
||||
version = "0.1.0"
|
||||
description = "Distributed key generation over ff/group"
|
||||
license = "MIT"
|
||||
repository = "https://github.com/serai-dex/serai/tree/develop/crypto/dkg/evrf"
|
||||
authors = ["Luke Parker <lukeparker5132@gmail.com>"]
|
||||
keywords = ["dkg", "multisig", "threshold", "ff", "group"]
|
||||
edition = "2021"
|
||||
rust-version = "1.89"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
all-features = true
|
||||
rustdoc-args = ["--cfg", "docsrs"]
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
thiserror = { version = "2", default-features = false }
|
||||
|
||||
rand_core = { version = "0.6", default-features = false, features = ["alloc"] }
|
||||
|
||||
zeroize = { version = "^1.5", default-features = false, features = ["alloc", "zeroize_derive"] }
|
||||
|
||||
std-shims = { version = "0.1", path = "../../../common/std-shims", default-features = false }
|
||||
|
||||
transcript = { package = "flexible-transcript", path = "../../transcript", version = "^0.3.2", default-features = false, features = ["recommended"] }
|
||||
|
||||
ciphersuite = { path = "../../ciphersuite", version = "^0.4.1", default-features = false, features = ["alloc"] }
|
||||
multiexp = { path = "../../multiexp", version = "0.4", default-features = false }
|
||||
|
||||
generic-array = { version = "1", default-features = false, features = ["alloc"] }
|
||||
blake2 = { version = "0.11.0-rc.0", default-features = false }
|
||||
rand_chacha = { version = "0.3", default-features = false }
|
||||
|
||||
generalized-bulletproofs = { git = "https://github.com/monero-oxide/monero-oxide", rev = "a6f8797007e768488568b821435cf5006517a962", default-features = false }
|
||||
ec-divisors = { git = "https://github.com/monero-oxide/monero-oxide", rev = "a6f8797007e768488568b821435cf5006517a962", default-features = false }
|
||||
generalized-bulletproofs-circuit-abstraction = { git = "https://github.com/monero-oxide/monero-oxide", rev = "a6f8797007e768488568b821435cf5006517a962", default-features = false }
|
||||
generalized-bulletproofs-ec-gadgets = { git = "https://github.com/monero-oxide/monero-oxide", rev = "a6f8797007e768488568b821435cf5006517a962", default-features = false }
|
||||
|
||||
dkg = { path = "..", default-features = false }
|
||||
|
||||
ciphersuite-kp256 = { path = "../../ciphersuite/kp256", default-features = false, features = ["alloc"], optional = true }
|
||||
secq256k1 = { path = "../../secq256k1", default-features = false, features = ["alloc"], optional = true }
|
||||
dalek-ff-group = { path = "../../dalek-ff-group", default-features = false, features = ["alloc"], optional = true }
|
||||
embedwards25519 = { path = "../../embedwards25519", default-features = false, features = ["alloc"], optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
rand_core = { version = "0.6", default-features = false, features = ["getrandom"] }
|
||||
rand = { version = "0.8", default-features = false, features = ["std"] }
|
||||
ciphersuite = { path = "../../ciphersuite", default-features = false, features = ["std"] }
|
||||
embedwards25519 = { path = "../../embedwards25519", default-features = false, features = ["std"] }
|
||||
dalek-ff-group = { path = "../../dalek-ff-group", default-features = false, features = ["std"] }
|
||||
generalized-bulletproofs = { git = "https://github.com/monero-oxide/monero-oxide", rev = "a6f8797007e768488568b821435cf5006517a962", features = ["tests"] }
|
||||
dkg-recovery = { path = "../recovery" }
|
||||
|
||||
[features]
|
||||
std = [
|
||||
"thiserror/std",
|
||||
|
||||
"rand_core/std",
|
||||
|
||||
"zeroize/std",
|
||||
"std-shims/std",
|
||||
|
||||
"transcript/std",
|
||||
|
||||
"ciphersuite/std",
|
||||
"multiexp/std",
|
||||
"multiexp/batch",
|
||||
|
||||
"rand_chacha/std",
|
||||
|
||||
"generalized-bulletproofs/std",
|
||||
"ec-divisors/std",
|
||||
"generalized-bulletproofs-circuit-abstraction/std",
|
||||
"generalized-bulletproofs-ec-gadgets/std",
|
||||
|
||||
"dkg/std",
|
||||
|
||||
"ciphersuite-kp256?/std",
|
||||
"secq256k1?/std",
|
||||
"dalek-ff-group?/std",
|
||||
"embedwards25519?/std",
|
||||
]
|
||||
secp256k1 = ["ciphersuite-kp256", "secq256k1"]
|
||||
ed25519 = ["dalek-ff-group", "embedwards25519"]
|
||||
ristretto = ["dalek-ff-group", "embedwards25519"]
|
||||
tests = ["rand_core/getrandom"]
|
||||
default = ["std"]
|
||||
@@ -1,6 +1,6 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2024 Luke Parker
|
||||
Copyright (c) 2021-2025 Luke Parker
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
50
crypto/dkg/evrf/README.md
Normal file
50
crypto/dkg/evrf/README.md
Normal file
@@ -0,0 +1,50 @@
|
||||
# eVRF DKG
|
||||
|
||||
The DKG from the [eVRF paper](https://eprint.iacr.org/2024/397), extended with
|
||||
Verifiable Encryption premised on the same methodology present in the eVRF
|
||||
paper.
|
||||
|
||||
The DDH-premised VRF is used, yet the different instantiation presented in
|
||||
section 6.4 premised on elliptic curve divisors. The one-round threshold DKG
|
||||
presented in section 4.2 is extended, with the following changes:
|
||||
|
||||
- Any threshold of `t` participants may complete the DKG. This allows an
|
||||
adversary to bias the resulting key by choosing the set of participants, yet
|
||||
offers a robust protocol. The caller is able to choose between robustness and
|
||||
a lack of bias by completing the DKG with just `t` messages or by waiting for
|
||||
all `n`. If the caller does opt for robustness, the caller must ensure
|
||||
participants agree on the subset of participants who actually participated.
|
||||
|
||||
- Communication of shares was prior defined as simply sending the share to the
|
||||
relevant participant, with no description of the channel. Now, a pair of
|
||||
ECDHs are performed on the embedded curve occurs (between the sender and the
|
||||
recipient's public key), whose `x` coordinates are summed for a random,
|
||||
uniform value (as an eVRF would). This value is used as a mask to encrypt the
|
||||
communicated secret share, with the zero-knowledge proof proving it's
|
||||
well-formed. This removes the need for a complaint round from the protocol,
|
||||
allowing it to truly complete (with all recipients holding valid shares) in
|
||||
just one round.
|
||||
|
||||
For a gist of the verifiable encryption scheme, please see
|
||||
https://gist.github.com/kayabaNerve/cfbde74b0660dfdf8dd55326d6ec33d7. Security
|
||||
proofs are currently being worked on.
|
||||
|
||||
---
|
||||
|
||||
This library relies on an implementation of Bulletproofs and various
|
||||
zero-knowledge gadgets. This library uses
|
||||
[`generalized-bulletproofs`](https://docs.rs/generalized-bulletproofs),
|
||||
[`generalized-bulletproofs-circuit-abstraction`](https://docs.rs/generalized-bulletproofs-circuit-abstraction),
|
||||
and
|
||||
[`generalized-bulletproofs-ec-gadgets`](https://docs.rs/generalized-bulletproofs-ec-gadgets)
|
||||
from the Monero project's FCMP++ codebase. These libraries have received the
|
||||
following audits in the past:
|
||||
- https://github.com/kayabaNerve/monero-oxide/tree/fcmp++/audits/generalized-bulletproofs
|
||||
- https://github.com/kayabaNerve/monero-oxide/tree/fcmp++/audits/fcmps
|
||||
|
||||
---
|
||||
|
||||
This library supports being run in no-std contexts with `alloc` when the `std`
|
||||
feature (on by default) is disabled. Due to the intensity of the ZK proofs,
|
||||
this isn't recommended, yet may be justified when _verifying_ posted proofs are
|
||||
correct.
|
||||
107
crypto/dkg/evrf/src/curves.rs
Normal file
107
crypto/dkg/evrf/src/curves.rs
Normal file
@@ -0,0 +1,107 @@
|
||||
#[allow(unused_imports)]
|
||||
use std_shims::prelude::*;
|
||||
use std_shims::vec::Vec;
|
||||
|
||||
use rand_core::SeedableRng;
|
||||
use rand_chacha::ChaCha20Rng;
|
||||
|
||||
use blake2::{
|
||||
digest::{
|
||||
array::{typenum::U32, Array},
|
||||
crypto_common::KeySizeUser,
|
||||
KeyInit, Mac,
|
||||
},
|
||||
Blake2sMac,
|
||||
};
|
||||
type Blake2s256Keyed = Blake2sMac<U32>;
|
||||
|
||||
use ciphersuite::{
|
||||
group::{ff::FromUniformBytes, GroupEncoding},
|
||||
Ciphersuite,
|
||||
};
|
||||
|
||||
use ec_divisors::DivisorCurve;
|
||||
use generalized_bulletproofs::Generators as BpGenerators;
|
||||
use generalized_bulletproofs_ec_gadgets::*;
|
||||
|
||||
/// A pair of curves to perform the eVRF with.
|
||||
pub trait Curves {
|
||||
/// The towering curve, for which the resulting key is on.
|
||||
type ToweringCurve: Ciphersuite<F: FromUniformBytes<64>>;
|
||||
/// The embedded curve which participants represent their public keys over.
|
||||
type EmbeddedCurve: Ciphersuite<
|
||||
G: DivisorCurve<FieldElement = <Self::ToweringCurve as Ciphersuite>::F>,
|
||||
>;
|
||||
/// The parameters to use the embedded curve with the discrete-log gadget.
|
||||
type EmbeddedCurveParameters: DiscreteLogParameters;
|
||||
}
|
||||
|
||||
/// Generators for an eVRF DKG.
|
||||
///
|
||||
/// These should be kept within a static. They're non-trivial to generate.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Generators<C: Curves>(pub(crate) BpGenerators<C::ToweringCurve>);
|
||||
|
||||
impl<C: Curves> Generators<C> {
|
||||
/// Create a new set of generators.
|
||||
///
|
||||
/// This is deterministic to the towering curve's (possibly truncated) ID and generator.
|
||||
pub fn new(max_threshold: u16, max_participants: u16) -> Generators<C> {
|
||||
let entropy = <Blake2s256Keyed as KeyInit>::new(&{
|
||||
let mut key = Array::<u8, <Blake2s256Keyed as KeySizeUser>::KeySize>::default();
|
||||
let key_len = key.len().min(<C::ToweringCurve as Ciphersuite>::ID.len());
|
||||
{
|
||||
let key: &mut [u8] = key.as_mut();
|
||||
key[.. key_len].copy_from_slice(&<C::ToweringCurve as Ciphersuite>::ID[.. key_len])
|
||||
}
|
||||
key
|
||||
})
|
||||
.chain_update(<C::ToweringCurve as Ciphersuite>::generator().to_bytes())
|
||||
.finalize()
|
||||
.into_bytes();
|
||||
let mut rng = ChaCha20Rng::from_seed(entropy.into());
|
||||
|
||||
let h = crate::sample_point::<C::ToweringCurve>(&mut rng);
|
||||
let generators =
|
||||
crate::Proof::<C>::generators_to_use(max_threshold.into(), max_participants.into());
|
||||
let mut g_bold = Vec::with_capacity(generators);
|
||||
let mut h_bold = Vec::with_capacity(generators);
|
||||
for _ in 0 .. generators {
|
||||
g_bold.push(crate::sample_point::<C::ToweringCurve>(&mut rng));
|
||||
h_bold.push(crate::sample_point::<C::ToweringCurve>(&mut rng));
|
||||
}
|
||||
Self(
|
||||
BpGenerators::new(<C::ToweringCurve as Ciphersuite>::generator(), h, g_bold, h_bold).unwrap(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Secp256k1, and an elliptic curve defined over its scalar field (secq256k1).
|
||||
#[cfg(feature = "secp256k1")]
|
||||
pub struct Secp256k1;
|
||||
#[cfg(feature = "secp256k1")]
|
||||
impl Curves for Secp256k1 {
|
||||
type ToweringCurve = ciphersuite_kp256::Secp256k1;
|
||||
type EmbeddedCurve = secq256k1::Secq256k1;
|
||||
type EmbeddedCurveParameters = secq256k1::Secq256k1;
|
||||
}
|
||||
|
||||
/// Ed25519, and an elliptic curve defined over its scalar field (embedwards25519).
|
||||
#[cfg(feature = "ed25519")]
|
||||
pub struct Ed25519;
|
||||
#[cfg(feature = "ed25519")]
|
||||
impl Curves for Ed25519 {
|
||||
type ToweringCurve = dalek_ff_group::Ed25519;
|
||||
type EmbeddedCurve = embedwards25519::Embedwards25519;
|
||||
type EmbeddedCurveParameters = embedwards25519::Embedwards25519;
|
||||
}
|
||||
|
||||
/// Ristretto, and an elliptic curve defined over its scalar field (embedwards25519).
|
||||
#[cfg(any(test, feature = "ristretto"))]
|
||||
pub struct Ristretto;
|
||||
#[cfg(any(test, feature = "ristretto"))]
|
||||
impl Curves for Ristretto {
|
||||
type ToweringCurve = dalek_ff_group::Ristretto;
|
||||
type EmbeddedCurve = embedwards25519::Embedwards25519;
|
||||
type EmbeddedCurveParameters = embedwards25519::Embedwards25519;
|
||||
}
|
||||
@@ -1,72 +1,12 @@
|
||||
/*
|
||||
We implement a DKG using an eVRF, as detailed in the eVRF paper. For the eVRF itself, we do not
|
||||
use a Paillier-based construction, nor the detailed construction premised on a Bulletproof.
|
||||
|
||||
For reference, the detailed construction premised on a Bulletproof involves two curves, notated
|
||||
here as `C` and `E`, where the scalar field of `C` is the field of `E`. Accordingly, Bulletproofs
|
||||
over `C` can efficiently perform group operations of points of curve `E`. Each participant has a
|
||||
private point (`P_i`) on curve `E` committed to over curve `C`. The eVRF selects a pair of
|
||||
scalars `a, b`, where the participant proves in-Bulletproof the points `A_i, B_i` are
|
||||
`a * P_i, b * P_i`. The eVRF proceeds to commit to `A_i.x + B_i.x` in a Pedersen Commitment.
|
||||
|
||||
Our eVRF uses
|
||||
[Generalized Bulletproofs](
|
||||
https://repo.getmonero.org/monero-project/ccs-proposals
|
||||
/uploads/a9baa50c38c6312efc0fea5c6a188bb9/gbp.pdf
|
||||
).
|
||||
This allows us much larger witnesses without growing the reference string, and enables us to
|
||||
efficiently sample challenges off in-circuit variables (via placing the variables in a vector
|
||||
commitment, then challenging from a transcript of the commitments). We proceed to use
|
||||
[elliptic curve divisors](
|
||||
https://repo.getmonero.org/-/project/54/
|
||||
uploads/eb1bf5b4d4855a3480c38abf895bd8e8/Veridise_Divisor_Proofs.pdf
|
||||
)
|
||||
(which require the ability to sample a challenge off in-circuit variables) to prove discrete
|
||||
logarithms efficiently.
|
||||
|
||||
This is done via having a private scalar (`p_i`) on curve `E`, not a private point, and
|
||||
publishing the public key for it (`P_i = p_i * G`, where `G` is a generator of `E`). The eVRF
|
||||
samples two points with unknown discrete logarithms `A, B`, and the circuit proves a Pedersen
|
||||
Commitment commits to `(p_i * A).x + (p_i * B).x`.
|
||||
|
||||
With the eVRF established, we now detail our other novel aspect. The eVRF paper expects secret
|
||||
shares to be sent to the other parties yet does not detail a precise way to do so. If we
|
||||
encrypted the secret shares with some stream cipher, each recipient would have to attest validity
|
||||
or accuse the sender of impropriety. We want an encryption scheme where anyone can verify the
|
||||
secret shares were encrypted properly, without additional info, efficiently.
|
||||
|
||||
Please note from the published commitments, it's possible to calculcate a commitment to the
|
||||
secret share each party should receive (`V_i`).
|
||||
|
||||
We have the sender sample two scalars per recipient, denoted `x_i, y_i` (where `i` is the
|
||||
recipient index). They perform the eVRF to prove a Pedersen Commitment commits to
|
||||
`z_i = (x_i * P_i).x + (y_i * P_i).x` and `x_i, y_i` are the discrete logarithms of `X_i, Y_i`
|
||||
over `G`. They then publish the encrypted share `s_i + z_i` and `X_i, Y_i`.
|
||||
|
||||
The recipient is able to decrypt the share via calculating
|
||||
`s_i - ((p_i * X_i).x + (p_i * Y_i).x)`.
|
||||
|
||||
To verify the secret share, we have the `F` terms of the Pedersen Commitments revealed (where
|
||||
`F, H` are generators of `C`, `F` is used for binding and `H` for blinding). This already needs
|
||||
to be done for the eVRF outputs used within the DKG, in order to obtain thecommitments to the
|
||||
coefficients. When we have the commitment `Z_i = ((p_i * A).x + (p_i * B).x) * F`, we simply
|
||||
check `s_i * F = Z_i + V_i`.
|
||||
|
||||
In order to open the Pedersen Commitments to their `F` terms, we transcript the commitments and
|
||||
the claimed openings, then assign random weights to each pair of `(commitment, opening). The
|
||||
prover proves knowledge of the discrete logarithm of the sum weighted commitments, minus the sum
|
||||
sum weighted openings, over `H`.
|
||||
|
||||
The benefit to this construction is that given an broadcast channel which is reliable and
|
||||
ordered, only `t` messages must be broadcast from honest parties in order to create a `t`-of-`n`
|
||||
multisig. If the encrypted secret shares were not verifiable, one would need at least `t + n`
|
||||
messages to ensure every participant has a correct dealing and can participate in future
|
||||
reconstructions of the secret. This would also require all `n` parties be online, whereas this is
|
||||
robust to threshold `t`.
|
||||
*/
|
||||
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
|
||||
#![doc = include_str!("../README.md")]
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
|
||||
use core::ops::Deref;
|
||||
use std::{
|
||||
#[allow(unused_imports)]
|
||||
use std_shims::prelude::*;
|
||||
use std_shims::{
|
||||
vec::Vec,
|
||||
io::{self, Read, Write},
|
||||
collections::{HashSet, HashMap},
|
||||
};
|
||||
@@ -85,35 +25,49 @@ use ciphersuite::{
|
||||
};
|
||||
use multiexp::multiexp_vartime;
|
||||
|
||||
use generalized_bulletproofs::{Generators, arithmetic_circuit_proof::*};
|
||||
use generalized_bulletproofs::arithmetic_circuit_proof::*;
|
||||
use ec_divisors::DivisorCurve;
|
||||
|
||||
use crate::{Participant, ThresholdParams, Interpolation, ThresholdCore, ThresholdKeys};
|
||||
pub use dkg::*;
|
||||
|
||||
pub(crate) mod proof;
|
||||
mod utils;
|
||||
pub(crate) use utils::*;
|
||||
|
||||
mod curves;
|
||||
pub use curves::*;
|
||||
|
||||
mod proof;
|
||||
use proof::*;
|
||||
pub use proof::{EvrfCurve, EvrfGenerators};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
/// Participation in the DKG.
|
||||
///
|
||||
/// `Participation` is meant to be broadcast to all other participants over an authenticated,
|
||||
/// reliable broadcast channel.
|
||||
#[derive(Clone, PartialEq, Eq, Debug)]
|
||||
pub struct Participation<C: Ciphersuite> {
|
||||
pub struct Participation<C: Curves> {
|
||||
proof: Vec<u8>,
|
||||
encrypted_secret_shares: HashMap<Participant, C::F>,
|
||||
encrypted_secret_shares: HashMap<Participant, <C::ToweringCurve as Ciphersuite>::F>,
|
||||
}
|
||||
|
||||
impl<C: Ciphersuite> Participation<C> {
|
||||
impl<C: Curves> Participation<C> {
|
||||
pub fn read<R: Read>(reader: &mut R, n: u16) -> io::Result<Self> {
|
||||
// Ban <32-bit platforms, allowing us to assume `u32` -> `usize` works
|
||||
const _NO_16_BIT_PLATFORMS: [(); (usize::BITS - u32::BITS) as usize] = [(); _];
|
||||
|
||||
// TODO: Replace `len` with some calculation deterministic to the params
|
||||
let mut len = [0; 4];
|
||||
reader.read_exact(&mut len)?;
|
||||
let len = usize::try_from(u32::from_le_bytes(len)).expect("<32-bit platform?");
|
||||
|
||||
// Don't allocate a buffer for the claimed length
|
||||
// Read chunks until we reach the claimed length
|
||||
// This means if we were told to read GB, we must actually be sent GB before allocating as such
|
||||
/*
|
||||
Don't allocate a buffer for the claimed length.
|
||||
|
||||
We read chunks of a fixed-length until we reach the claimed length, preventing an adversary
|
||||
from forcing us to allocate GB unless the proof is actually GB long.
|
||||
*/
|
||||
const CHUNK_SIZE: usize = 1024;
|
||||
let mut proof = Vec::with_capacity(len.min(CHUNK_SIZE));
|
||||
while proof.len() < len {
|
||||
@@ -124,8 +78,8 @@ impl<C: Ciphersuite> Participation<C> {
|
||||
}
|
||||
|
||||
let mut encrypted_secret_shares = HashMap::with_capacity(usize::from(n));
|
||||
for i in (1 ..= n).map(Participant) {
|
||||
encrypted_secret_shares.insert(i, C::read_F(reader)?);
|
||||
for i in Participant::iter().take(usize::from(n)) {
|
||||
encrypted_secret_shares.insert(i, <C::ToweringCurve as Ciphersuite>::read_F(reader)?);
|
||||
}
|
||||
|
||||
Ok(Self { proof, encrypted_secret_shares })
|
||||
@@ -134,113 +88,82 @@ impl<C: Ciphersuite> Participation<C> {
|
||||
pub fn write<W: Write>(&self, writer: &mut W) -> io::Result<()> {
|
||||
writer.write_all(&u32::try_from(self.proof.len()).unwrap().to_le_bytes())?;
|
||||
writer.write_all(&self.proof)?;
|
||||
for i in (1 ..= u16::try_from(self.encrypted_secret_shares.len())
|
||||
.expect("writing a Participation which has a n > u16::MAX"))
|
||||
.map(Participant)
|
||||
{
|
||||
for i in Participant::iter().take(self.encrypted_secret_shares.len()) {
|
||||
writer.write_all(self.encrypted_secret_shares[&i].to_repr().as_ref())?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn polynomial<F: PrimeField + Zeroize>(
|
||||
coefficients: &[Zeroizing<F>],
|
||||
l: Participant,
|
||||
) -> Zeroizing<F> {
|
||||
let l = F::from(u64::from(u16::from(l)));
|
||||
// This should never be reached since Participant is explicitly non-zero
|
||||
assert!(l != F::ZERO, "zero participant passed to polynomial");
|
||||
let mut share = Zeroizing::new(F::ZERO);
|
||||
for (idx, coefficient) in coefficients.iter().rev().enumerate() {
|
||||
*share += coefficient.deref();
|
||||
if idx != (coefficients.len() - 1) {
|
||||
*share *= l;
|
||||
}
|
||||
}
|
||||
share
|
||||
}
|
||||
|
||||
#[allow(clippy::type_complexity)]
|
||||
fn share_verification_statements<C: Ciphersuite>(
|
||||
rng: &mut (impl RngCore + CryptoRng),
|
||||
commitments: &[C::G],
|
||||
n: u16,
|
||||
encryption_commitments: &[C::G],
|
||||
encrypted_secret_shares: &HashMap<Participant, C::F>,
|
||||
) -> (C::F, Vec<(C::F, C::G)>) {
|
||||
debug_assert_eq!(usize::from(n), encryption_commitments.len());
|
||||
debug_assert_eq!(usize::from(n), encrypted_secret_shares.len());
|
||||
|
||||
let mut g_scalar = C::F::ZERO;
|
||||
let mut pairs = Vec::with_capacity(commitments.len() + encryption_commitments.len());
|
||||
for commitment in commitments {
|
||||
pairs.push((C::F::ZERO, *commitment));
|
||||
}
|
||||
|
||||
let mut weight;
|
||||
for (i, enc_share) in encrypted_secret_shares {
|
||||
let enc_commitment = encryption_commitments[usize::from(u16::from(*i)) - 1];
|
||||
|
||||
weight = C::F::random(&mut *rng);
|
||||
|
||||
// s_i F
|
||||
g_scalar += weight * enc_share;
|
||||
// - Z_i
|
||||
let weight = -weight;
|
||||
pairs.push((weight, enc_commitment));
|
||||
// - V_i
|
||||
{
|
||||
let i = C::F::from(u64::from(u16::from(*i)));
|
||||
// The first `commitments.len()` pairs are for the commitments
|
||||
(0 .. commitments.len()).fold(weight, |exp, j| {
|
||||
pairs[j].0 += exp;
|
||||
exp * i
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
(g_scalar, pairs)
|
||||
}
|
||||
|
||||
/// Errors from the eVRF DKG.
|
||||
#[derive(Clone, PartialEq, Eq, Debug, thiserror::Error)]
|
||||
pub enum EvrfError {
|
||||
#[error("n, the amount of participants, exceeded a u16")]
|
||||
TooManyParticipants,
|
||||
#[error("the threshold t wasn't in range 1 <= t <= n")]
|
||||
InvalidThreshold,
|
||||
pub enum Error {
|
||||
/// Too many participants were provided.
|
||||
#[error("{provided} participants provided, exceeding the limit of u16::MAX")]
|
||||
TooManyParticipants {
|
||||
/// The amount of provided participants.
|
||||
provided: usize,
|
||||
},
|
||||
|
||||
/// The threshold exceeded the amount of participants.
|
||||
#[error("invalid threshold (max {n}, got {t})")]
|
||||
InvalidThreshold {
|
||||
/// The specified threshold.
|
||||
t: u16,
|
||||
/// The specified total amount of participants.
|
||||
n: u16,
|
||||
},
|
||||
|
||||
/// A participant's public key was the identity point.
|
||||
#[error("a public key was the identity point")]
|
||||
PublicKeyWasIdentity,
|
||||
|
||||
/// Participating in a DKG we aren't present in.
|
||||
#[error("participating in a DKG we aren't a participant in")]
|
||||
NotAParticipant,
|
||||
|
||||
/// A participant which doesn't exist provided a participation.
|
||||
#[error("a participant with an unrecognized ID participated")]
|
||||
NonExistentParticipant,
|
||||
#[error("the passed in generators did not have enough generators for this DKG")]
|
||||
NotEnoughGenerators,
|
||||
|
||||
/// Insufficient amount of generators for this DKG.
|
||||
#[error("the passed in generators ({provided}) weren't enough for this DKG (needed {required})")]
|
||||
NotEnoughGenerators {
|
||||
/// The amount of generators provided.
|
||||
provided: usize,
|
||||
/// The amount of generators required.
|
||||
required: usize,
|
||||
},
|
||||
}
|
||||
|
||||
/// The result of calling EvrfDkg::verify.
|
||||
pub enum VerifyResult<C: EvrfCurve> {
|
||||
Valid(EvrfDkg<C>),
|
||||
/// The result of calling `Dkg::verify`.
|
||||
pub enum VerifyResult<C: Curves> {
|
||||
/// The DKG participations were valid.
|
||||
Valid(Dkg<C>),
|
||||
/// The DKG participants were invalid, identifying the faulty participants.
|
||||
Invalid(Vec<Participant>),
|
||||
/// Not enough participations were provided, yet no provided participations were faulty.
|
||||
NotEnoughParticipants,
|
||||
}
|
||||
|
||||
/// Struct to perform/verify the DKG with.
|
||||
/// Struct representing a DKG.
|
||||
#[derive(Debug)]
|
||||
pub struct EvrfDkg<C: EvrfCurve> {
|
||||
pub struct Dkg<C: Curves> {
|
||||
t: u16,
|
||||
n: u16,
|
||||
evrf_public_keys: Vec<<C::EmbeddedCurve as Ciphersuite>::G>,
|
||||
group_key: C::G,
|
||||
verification_shares: HashMap<Participant, C::G>,
|
||||
verification_shares: HashMap<Participant, <C::ToweringCurve as Ciphersuite>::G>,
|
||||
#[allow(clippy::type_complexity)]
|
||||
encrypted_secret_shares:
|
||||
HashMap<Participant, HashMap<Participant, ([<C::EmbeddedCurve as Ciphersuite>::G; 2], C::F)>>,
|
||||
encrypted_secret_shares: HashMap<
|
||||
Participant,
|
||||
HashMap<
|
||||
Participant,
|
||||
([<C::EmbeddedCurve as Ciphersuite>::G; 2], <C::ToweringCurve as Ciphersuite>::F),
|
||||
>,
|
||||
>,
|
||||
}
|
||||
|
||||
impl<C: EvrfCurve> EvrfDkg<C> {
|
||||
impl<C: Curves> Dkg<C> {
|
||||
// Form the initial transcript for the proofs.
|
||||
fn initial_transcript(
|
||||
invocation: [u8; 32],
|
||||
@@ -260,40 +183,37 @@ impl<C: EvrfCurve> EvrfDkg<C> {
|
||||
///
|
||||
/// The context MUST be unique across invocations. Reuse of context will lead to sharing
|
||||
/// prior-shared secrets.
|
||||
///
|
||||
/// Public keys are not allowed to be the identity point. This will error if any are.
|
||||
pub fn participate(
|
||||
rng: &mut (impl RngCore + CryptoRng),
|
||||
generators: &EvrfGenerators<C>,
|
||||
generators: &Generators<C>,
|
||||
context: [u8; 32],
|
||||
t: u16,
|
||||
evrf_public_keys: &[<C::EmbeddedCurve as Ciphersuite>::G],
|
||||
evrf_private_key: &Zeroizing<<C::EmbeddedCurve as Ciphersuite>::F>,
|
||||
) -> Result<Participation<C>, EvrfError> {
|
||||
let Ok(n) = u16::try_from(evrf_public_keys.len()) else { Err(EvrfError::TooManyParticipants)? };
|
||||
) -> Result<Participation<C>, Error> {
|
||||
let Ok(n) = u16::try_from(evrf_public_keys.len()) else {
|
||||
Err(Error::TooManyParticipants { provided: evrf_public_keys.len() })?
|
||||
};
|
||||
if (t == 0) || (t > n) {
|
||||
Err(EvrfError::InvalidThreshold)?;
|
||||
Err(Error::InvalidThreshold { t, n })?;
|
||||
}
|
||||
if evrf_public_keys.iter().any(|key| bool::from(key.is_identity())) {
|
||||
Err(EvrfError::PublicKeyWasIdentity)?;
|
||||
Err(Error::PublicKeyWasIdentity)?;
|
||||
};
|
||||
// This also checks the private key is not 0
|
||||
// This also ensures the private key is not 0, due to the prior check the identity point wasn't
|
||||
// present
|
||||
let evrf_public_key = <C::EmbeddedCurve as Ciphersuite>::generator() * evrf_private_key.deref();
|
||||
if !evrf_public_keys.iter().any(|key| *key == evrf_public_key) {
|
||||
Err(EvrfError::NotAParticipant)?;
|
||||
if !evrf_public_keys.contains(&evrf_public_key) {
|
||||
Err(Error::NotAParticipant)?;
|
||||
};
|
||||
|
||||
let transcript = Self::initial_transcript(context, evrf_public_keys, t);
|
||||
// Further bind to the participant index so each index gets unique generators
|
||||
// This allows reusing eVRF public keys as the prover
|
||||
// Bind to the participant
|
||||
let mut per_proof_transcript = Blake2s256::new();
|
||||
per_proof_transcript.update(transcript);
|
||||
per_proof_transcript.update(evrf_public_key.to_bytes());
|
||||
|
||||
// The above transcript is expected to be binding to all arguments here
|
||||
// The generators are constant to this ciphersuite's generator, and the parameters are
|
||||
// transcripted
|
||||
let EvrfProveResult { coefficients, encryption_masks, proof } = match Evrf::prove(
|
||||
let ProveResult { coefficients, encryption_keys, proof } = match Proof::<C>::prove(
|
||||
rng,
|
||||
&generators.0,
|
||||
per_proof_transcript.finalize().into(),
|
||||
@@ -302,29 +222,70 @@ impl<C: EvrfCurve> EvrfDkg<C> {
|
||||
evrf_private_key,
|
||||
) {
|
||||
Ok(res) => res,
|
||||
Err(AcError::NotEnoughGenerators) => Err(EvrfError::NotEnoughGenerators)?,
|
||||
Err(
|
||||
AcError::DifferingLrLengths |
|
||||
AcError::InconsistentAmountOfConstraints |
|
||||
AcError::ConstrainedNonExistentTerm |
|
||||
AcError::ConstrainedNonExistentCommitment |
|
||||
AcError::InconsistentWitness |
|
||||
AcError::Ip(_) |
|
||||
AcError::IncompleteProof,
|
||||
) => {
|
||||
panic!("failed to prove for the eVRF proof")
|
||||
}
|
||||
Err(AcProveError::IncorrectAmountOfGenerators) => Err(Error::NotEnoughGenerators {
|
||||
provided: generators.0.g_bold_slice().len(),
|
||||
required: Proof::<C>::generators_to_use(usize::from(t), evrf_public_keys.len()),
|
||||
})?,
|
||||
Err(AcProveError::InconsistentWitness) => panic!("failed to prove for the eVRF proof"),
|
||||
};
|
||||
|
||||
let mut encrypted_secret_shares = HashMap::with_capacity(usize::from(n));
|
||||
for (l, encryption_mask) in (1 ..= n).map(Participant).zip(encryption_masks) {
|
||||
let share = polynomial::<C::F>(&coefficients, l);
|
||||
encrypted_secret_shares.insert(l, *share + *encryption_mask);
|
||||
for (l, encryption_key) in Participant::iter().take(usize::from(n)).zip(encryption_keys) {
|
||||
let share = polynomial::<<C::ToweringCurve as Ciphersuite>::F>(&coefficients, l);
|
||||
encrypted_secret_shares.insert(l, *share + *encryption_key);
|
||||
}
|
||||
|
||||
Ok(Participation { proof, encrypted_secret_shares })
|
||||
}
|
||||
}
|
||||
|
||||
/// Batch-verifiable statements to verify encrypted secret shares.
|
||||
#[allow(clippy::type_complexity)]
|
||||
fn verifiable_encryption_statements<C: Curves>(
|
||||
rng: &mut (impl RngCore + CryptoRng),
|
||||
coefficients: &[<C::ToweringCurve as Ciphersuite>::G],
|
||||
encryption_key_commitments: &[<C::ToweringCurve as Ciphersuite>::G],
|
||||
encrypted_secret_shares: &HashMap<Participant, <C::ToweringCurve as Ciphersuite>::F>,
|
||||
) -> (
|
||||
<C::ToweringCurve as Ciphersuite>::F,
|
||||
Vec<(<C::ToweringCurve as Ciphersuite>::F, <C::ToweringCurve as Ciphersuite>::G)>,
|
||||
) {
|
||||
let mut g_scalar = <C::ToweringCurve as Ciphersuite>::F::ZERO;
|
||||
let mut pairs = Vec::with_capacity(coefficients.len() + encryption_key_commitments.len());
|
||||
|
||||
// Push on the commitments to the polynomial being secret-shared
|
||||
for coefficient in coefficients {
|
||||
// This uses `0` as we'll add to it later, given its fixed position
|
||||
pairs.push((<C::ToweringCurve as Ciphersuite>::F::ZERO, *coefficient));
|
||||
}
|
||||
|
||||
for (i, encrypted_secret_share) in encrypted_secret_shares {
|
||||
let encryption_key_commitment = encryption_key_commitments[usize::from(u16::from(*i)) - 1];
|
||||
|
||||
let weight = <C::ToweringCurve as Ciphersuite>::F::random(&mut *rng);
|
||||
|
||||
/*
|
||||
The encrypted secret share scaling `G`, minus the encryption key commitment, minus the
|
||||
ommitment to the secret share, should equal the identity point.
|
||||
|
||||
We actually subtract the encrypted share to optimize the amount of negations we perform.
|
||||
*/
|
||||
g_scalar -= weight * encrypted_secret_share;
|
||||
pairs.push((weight, encryption_key_commitment));
|
||||
// Calculate the commitment to the secret share via the commitments to the polynomial
|
||||
{
|
||||
let i = <C::ToweringCurve as Ciphersuite>::F::from(u64::from(u16::from(*i)));
|
||||
(0 .. coefficients.len()).fold(weight, |exp, j| {
|
||||
pairs[j].0 += exp;
|
||||
exp * i
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
(g_scalar, pairs)
|
||||
}
|
||||
|
||||
impl<C: Curves> Dkg<C> {
|
||||
/// Check if a batch of `Participation`s are valid.
|
||||
///
|
||||
/// If any `Participation` is invalid, the list of all invalid participants will be returned.
|
||||
@@ -336,22 +297,24 @@ impl<C: EvrfCurve> EvrfDkg<C> {
|
||||
/// participate.
|
||||
pub fn verify(
|
||||
rng: &mut (impl RngCore + CryptoRng),
|
||||
generators: &EvrfGenerators<C>,
|
||||
generators: &Generators<C>,
|
||||
context: [u8; 32],
|
||||
t: u16,
|
||||
evrf_public_keys: &[<C::EmbeddedCurve as Ciphersuite>::G],
|
||||
participations: &HashMap<Participant, Participation<C>>,
|
||||
) -> Result<VerifyResult<C>, EvrfError> {
|
||||
let Ok(n) = u16::try_from(evrf_public_keys.len()) else { Err(EvrfError::TooManyParticipants)? };
|
||||
) -> Result<VerifyResult<C>, Error> {
|
||||
let Ok(n) = u16::try_from(evrf_public_keys.len()) else {
|
||||
Err(Error::TooManyParticipants { provided: evrf_public_keys.len() })?
|
||||
};
|
||||
if (t == 0) || (t > n) {
|
||||
Err(EvrfError::InvalidThreshold)?;
|
||||
Err(Error::InvalidThreshold { t, n })?;
|
||||
}
|
||||
if evrf_public_keys.iter().any(|key| bool::from(key.is_identity())) {
|
||||
Err(EvrfError::PublicKeyWasIdentity)?;
|
||||
Err(Error::PublicKeyWasIdentity)?;
|
||||
};
|
||||
for i in participations.keys() {
|
||||
if u16::from(*i) > n {
|
||||
Err(EvrfError::NonExistentParticipant)?;
|
||||
Err(Error::NonExistentParticipant)?;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -360,7 +323,7 @@ impl<C: EvrfCurve> EvrfDkg<C> {
|
||||
|
||||
let transcript = Self::initial_transcript(context, evrf_public_keys, t);
|
||||
|
||||
let mut evrf_verifier = Generators::batch_verifier();
|
||||
let mut evrf_verifier = generalized_bulletproofs::Generators::batch_verifier();
|
||||
for (i, participation) in participations {
|
||||
let evrf_public_key = evrf_public_keys[usize::from(u16::from(*i)) - 1];
|
||||
|
||||
@@ -370,7 +333,7 @@ impl<C: EvrfCurve> EvrfDkg<C> {
|
||||
|
||||
// Clone the verifier so if this proof is faulty, it doesn't corrupt the verifier
|
||||
let mut verifier_clone = evrf_verifier.clone();
|
||||
let Ok(data) = Evrf::<C>::verify(
|
||||
let Ok(data) = Proof::<C>::verify(
|
||||
rng,
|
||||
&generators.0,
|
||||
&mut verifier_clone,
|
||||
@@ -396,8 +359,8 @@ impl<C: EvrfCurve> EvrfDkg<C> {
|
||||
if faulty.contains(i) {
|
||||
continue;
|
||||
}
|
||||
let mut evrf_verifier = Generators::batch_verifier();
|
||||
Evrf::<C>::verify(
|
||||
let mut evrf_verifier = generalized_bulletproofs::Generators::batch_verifier();
|
||||
Proof::<C>::verify(
|
||||
rng,
|
||||
&generators.0,
|
||||
&mut evrf_verifier,
|
||||
@@ -423,17 +386,13 @@ impl<C: EvrfCurve> EvrfDkg<C> {
|
||||
{
|
||||
let mut share_verification_statements_actual = HashMap::with_capacity(valid.len());
|
||||
if !{
|
||||
let mut g_scalar = C::F::ZERO;
|
||||
let mut g_scalar = <C::ToweringCurve as Ciphersuite>::F::ZERO;
|
||||
let mut pairs = Vec::with_capacity(valid.len() * (usize::from(t) + evrf_public_keys.len()));
|
||||
for (i, (encrypted_secret_shares, data)) in &valid {
|
||||
let (this_g_scalar, mut these_pairs) = share_verification_statements::<C>(
|
||||
let (this_g_scalar, mut these_pairs) = verifiable_encryption_statements::<C>(
|
||||
&mut *rng,
|
||||
&data.coefficients,
|
||||
evrf_public_keys
|
||||
.len()
|
||||
.try_into()
|
||||
.expect("n prior checked to be <= u16::MAX couldn't be converted to a u16"),
|
||||
&data.encryption_commitments,
|
||||
&data.encryption_key_commitments,
|
||||
encrypted_secret_shares,
|
||||
);
|
||||
// Queue this into our batch
|
||||
@@ -452,18 +411,22 @@ impl<C: EvrfCurve> EvrfDkg<C> {
|
||||
We calculcate verification shares as the sum of the encrypted scalars, minus their
|
||||
masks. This only does one scalar multiplication, and `1+t` point additions (with
|
||||
one negation), and is accordingly much cheaper than interpolating the commitments.
|
||||
This is only possible because already interpolated the commitments to verify the
|
||||
This is only possible because we already interpolated the commitments to verify the
|
||||
encrypted secret share.
|
||||
*/
|
||||
let sum_encrypted_secret_share =
|
||||
sum_encrypted_secret_shares.get(j).copied().unwrap_or(C::F::ZERO);
|
||||
let sum_mask = sum_masks.get(j).copied().unwrap_or(C::G::identity());
|
||||
let sum_encrypted_secret_share = sum_encrypted_secret_shares
|
||||
.get(j)
|
||||
.copied()
|
||||
.unwrap_or(<C::ToweringCurve as Ciphersuite>::F::ZERO);
|
||||
let sum_mask =
|
||||
sum_masks.get(j).copied().unwrap_or(<C::ToweringCurve as Ciphersuite>::G::identity());
|
||||
sum_encrypted_secret_shares.insert(*j, sum_encrypted_secret_share + enc_share);
|
||||
|
||||
let j_index = usize::from(u16::from(*j)) - 1;
|
||||
sum_masks.insert(*j, sum_mask + data.encryption_commitments[j_index]);
|
||||
sum_masks.insert(*j, sum_mask + data.encryption_key_commitments[j_index]);
|
||||
|
||||
formatted_encrypted_secret_shares.insert(*j, (data.ecdh_keys[j_index], *enc_share));
|
||||
formatted_encrypted_secret_shares
|
||||
.insert(*j, (data.ecdh_commitments[j_index], *enc_share));
|
||||
}
|
||||
all_encrypted_secret_shares.insert(*i, formatted_encrypted_secret_shares);
|
||||
}
|
||||
@@ -517,69 +480,74 @@ impl<C: EvrfCurve> EvrfDkg<C> {
|
||||
}
|
||||
}
|
||||
|
||||
// If we now have >= t participations, calculate the group key and verification shares
|
||||
|
||||
// The group key is the sum of the zero coefficients
|
||||
let group_key = valid.values().map(|(_, evrf_data)| evrf_data.coefficients[0]).sum::<C::G>();
|
||||
// If we now have >= t participations, output the result
|
||||
|
||||
// Calculate each user's verification share
|
||||
let mut verification_shares = HashMap::with_capacity(usize::from(n));
|
||||
for i in (1 ..= n).map(Participant) {
|
||||
verification_shares
|
||||
.insert(i, (C::generator() * sum_encrypted_secret_shares[&i]) - sum_masks[&i]);
|
||||
for i in Participant::iter().take(usize::from(n)) {
|
||||
verification_shares.insert(
|
||||
i,
|
||||
(<C::ToweringCurve as Ciphersuite>::generator() * sum_encrypted_secret_shares[&i]) -
|
||||
sum_masks[&i],
|
||||
);
|
||||
}
|
||||
|
||||
Ok(VerifyResult::Valid(EvrfDkg {
|
||||
Ok(VerifyResult::Valid(Dkg {
|
||||
t,
|
||||
n,
|
||||
evrf_public_keys: evrf_public_keys.to_vec(),
|
||||
group_key,
|
||||
verification_shares,
|
||||
encrypted_secret_shares: all_encrypted_secret_shares,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Retrieve keys from a successful DKG.
|
||||
///
|
||||
/// This will return _all_ keys belong to the participant.
|
||||
pub fn keys(
|
||||
&self,
|
||||
evrf_private_key: &Zeroizing<<C::EmbeddedCurve as Ciphersuite>::F>,
|
||||
) -> Vec<ThresholdKeys<C>> {
|
||||
) -> Vec<ThresholdKeys<C::ToweringCurve>> {
|
||||
let evrf_public_key = <C::EmbeddedCurve as Ciphersuite>::generator() * evrf_private_key.deref();
|
||||
let mut is = Vec::with_capacity(1);
|
||||
for (i, evrf_key) in self.evrf_public_keys.iter().enumerate() {
|
||||
for (i, evrf_key) in Participant::iter().zip(self.evrf_public_keys.iter()) {
|
||||
if *evrf_key == evrf_public_key {
|
||||
let i = u16::try_from(i).expect("n <= u16::MAX yet i > u16::MAX?");
|
||||
let i = Participant(1 + i);
|
||||
is.push(i);
|
||||
}
|
||||
}
|
||||
|
||||
let mut res = Vec::with_capacity(is.len());
|
||||
for i in is {
|
||||
let mut secret_share = Zeroizing::new(C::F::ZERO);
|
||||
let mut secret_share = Zeroizing::new(<C::ToweringCurve as Ciphersuite>::F::ZERO);
|
||||
for shares in self.encrypted_secret_shares.values() {
|
||||
let (ecdh_keys, enc_share) = shares[&i];
|
||||
let (ecdh_commitments, encrypted_secret_share) = shares[&i];
|
||||
|
||||
let mut ecdh = Zeroizing::new(C::F::ZERO);
|
||||
for point in ecdh_keys {
|
||||
let mut ecdh = Zeroizing::new(<C::ToweringCurve as Ciphersuite>::F::ZERO);
|
||||
for point in ecdh_commitments {
|
||||
let (mut x, mut y) =
|
||||
<C::EmbeddedCurve as Ciphersuite>::G::to_xy(point * evrf_private_key.deref()).unwrap();
|
||||
*ecdh += x;
|
||||
x.zeroize();
|
||||
y.zeroize();
|
||||
}
|
||||
*secret_share += enc_share - ecdh.deref();
|
||||
*secret_share += encrypted_secret_share - ecdh.deref();
|
||||
}
|
||||
debug_assert_eq!(
|
||||
self.verification_shares[&i],
|
||||
<C::ToweringCurve as Ciphersuite>::G::generator() * secret_share.deref()
|
||||
);
|
||||
|
||||
debug_assert_eq!(self.verification_shares[&i], C::generator() * secret_share.deref());
|
||||
|
||||
res.push(ThresholdKeys::from(ThresholdCore {
|
||||
params: ThresholdParams::new(self.t, self.n, i).unwrap(),
|
||||
interpolation: Interpolation::Lagrange,
|
||||
secret_share,
|
||||
group_key: self.group_key,
|
||||
verification_shares: self.verification_shares.clone(),
|
||||
}));
|
||||
res.push(
|
||||
ThresholdKeys::new(
|
||||
ThresholdParams::new(self.t, self.n, i).unwrap(),
|
||||
Interpolation::Lagrange,
|
||||
secret_share,
|
||||
self.verification_shares.clone(),
|
||||
)
|
||||
.unwrap(),
|
||||
);
|
||||
}
|
||||
|
||||
res
|
||||
}
|
||||
}
|
||||
684
crypto/dkg/evrf/src/proof/mod.rs
Normal file
684
crypto/dkg/evrf/src/proof/mod.rs
Normal file
@@ -0,0 +1,684 @@
|
||||
use core::{marker::PhantomData, ops::Deref, fmt};
|
||||
#[allow(unused_imports)]
|
||||
use std_shims::prelude::*;
|
||||
use std_shims::{vec, vec::Vec};
|
||||
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use rand_core::{RngCore, CryptoRng, SeedableRng};
|
||||
use rand_chacha::ChaCha20Rng;
|
||||
|
||||
use ciphersuite::{group::ff::Field, Ciphersuite};
|
||||
|
||||
use generalized_bulletproofs::{
|
||||
Generators, BatchVerifier, PedersenCommitment, PedersenVectorCommitment,
|
||||
transcript::{Transcript as ProverTranscript, VerifierTranscript},
|
||||
arithmetic_circuit_proof::*,
|
||||
};
|
||||
use generalized_bulletproofs_circuit_abstraction::{Transcript, Circuit as BpCircuit};
|
||||
|
||||
use ec_divisors::{DivisorCurve, ScalarDecomposition};
|
||||
use generalized_bulletproofs_ec_gadgets::{
|
||||
CurveSpec, DiscreteLogChallenge, ChallengedGenerator, EcDlogGadgets,
|
||||
};
|
||||
|
||||
use crate::Curves;
|
||||
|
||||
mod tape;
|
||||
use tape::*;
|
||||
|
||||
type EmbeddedPoint<C> = (
|
||||
<<<C as Curves>::EmbeddedCurve as Ciphersuite>::G as DivisorCurve>::FieldElement,
|
||||
<<<C as Curves>::EmbeddedCurve as Ciphersuite>::G as DivisorCurve>::FieldElement,
|
||||
);
|
||||
|
||||
#[allow(non_snake_case)]
|
||||
struct Circuit<
|
||||
'a,
|
||||
C: Curves,
|
||||
CG: Iterator<
|
||||
Item = ChallengedGenerator<<C::ToweringCurve as Ciphersuite>::F, C::EmbeddedCurveParameters>,
|
||||
>,
|
||||
> {
|
||||
curve_spec: &'a CurveSpec<<<C::EmbeddedCurve as Ciphersuite>::G as DivisorCurve>::FieldElement>,
|
||||
circuit: &'a mut BpCircuit<C::ToweringCurve>,
|
||||
challenge: DiscreteLogChallenge<<C::ToweringCurve as Ciphersuite>::F, C::EmbeddedCurveParameters>,
|
||||
challenged_G:
|
||||
ChallengedGenerator<<C::ToweringCurve as Ciphersuite>::F, C::EmbeddedCurveParameters>,
|
||||
challenged_generators: &'a mut CG,
|
||||
tape: Tape,
|
||||
pedersen_commitment_tape: PedersenCommitmentTape,
|
||||
}
|
||||
|
||||
impl<
|
||||
'a,
|
||||
C: Curves,
|
||||
CG: Iterator<
|
||||
Item = ChallengedGenerator<<C::ToweringCurve as Ciphersuite>::F, C::EmbeddedCurveParameters>,
|
||||
>,
|
||||
> Circuit<'a, C, CG>
|
||||
{
|
||||
/// Generate coefficients for secret-sharing via an eVRF.
|
||||
///
|
||||
/// This follows the methodology of Protocol 5 from the
|
||||
/// [eVRF paper](https://eprint.iacr.org/2024/397.pdf).
|
||||
fn coefficients(&mut self, evrf_public_key: EmbeddedPoint<C>, coefficients: usize) {
|
||||
/*
|
||||
Read the opening of the prover's eVRF public key, along with all the proofs for the eVRF.
|
||||
Each invocation of the eVRF requires performing _two_ Diffie-Hellmans against
|
||||
uniformly-sampled points.
|
||||
*/
|
||||
let mut point_with_dlogs = self.tape.read_points_with_common_dlog::<C>(1 + (2 * coefficients));
|
||||
|
||||
// Assert this discrete logarithm opens the prover's public key
|
||||
let point = self.circuit.discrete_log(
|
||||
self.curve_spec,
|
||||
point_with_dlogs.next().unwrap(),
|
||||
&self.challenge,
|
||||
&self.challenged_G,
|
||||
);
|
||||
self.circuit.equality(LinComb::from(point.x()), &LinComb::empty().constant(evrf_public_key.0));
|
||||
self.circuit.equality(LinComb::from(point.y()), &LinComb::empty().constant(evrf_public_key.1));
|
||||
|
||||
// Verify the eVRF invocations
|
||||
for _ in 0 .. coefficients {
|
||||
let mut lincomb = LinComb::empty();
|
||||
for challenged_generator in
|
||||
[self.challenged_generators.next().unwrap(), self.challenged_generators.next().unwrap()]
|
||||
{
|
||||
let point = self.circuit.discrete_log(
|
||||
self.curve_spec,
|
||||
point_with_dlogs.next().unwrap(),
|
||||
&self.challenge,
|
||||
&challenged_generator,
|
||||
);
|
||||
lincomb = lincomb.term(<C::ToweringCurve as Ciphersuite>::F::ONE, point.x());
|
||||
}
|
||||
/*
|
||||
Constrain the sum of the two `x` coordinates to be equal to the value committed to in a
|
||||
Pedersen commitment
|
||||
*/
|
||||
self.circuit.equality(
|
||||
lincomb,
|
||||
&LinComb::from(self.pedersen_commitment_tape.allocate_pedersen_commitment()),
|
||||
);
|
||||
}
|
||||
debug_assert!(point_with_dlogs.next().is_none());
|
||||
}
|
||||
|
||||
/// Sample an encryption key, proving it's correctly-formed and committed to within a Pedersen
|
||||
/// commitment.
|
||||
fn verifiable_encryption(&mut self, ecdh_commitments: &[EmbeddedPoint<C>; 2]) {
|
||||
// Read the public key used for this encryption
|
||||
let challenged_public_key = self.challenged_generators.next().unwrap();
|
||||
// We perform two separate ECDHs, the sum of their `x` coordinates being our encryption key
|
||||
let mut lincomb = LinComb::empty();
|
||||
for ecdh_commitment in ecdh_commitments {
|
||||
// We open the posted commitment to the ephemeral secret used, and the ECDH value
|
||||
let mut point_with_dlogs = self.tape.read_points_with_common_dlog::<C>(2);
|
||||
|
||||
let point = self.circuit.discrete_log(
|
||||
self.curve_spec,
|
||||
point_with_dlogs.next().unwrap(),
|
||||
&self.challenge,
|
||||
&self.challenged_G,
|
||||
);
|
||||
// Ensure this equals the publicly posted commitment
|
||||
self
|
||||
.circuit
|
||||
.equality(LinComb::from(point.x()), &LinComb::empty().constant(ecdh_commitment.0));
|
||||
self
|
||||
.circuit
|
||||
.equality(LinComb::from(point.y()), &LinComb::empty().constant(ecdh_commitment.1));
|
||||
|
||||
let point = self.circuit.discrete_log(
|
||||
self.curve_spec,
|
||||
point_with_dlogs.next().unwrap(),
|
||||
&self.challenge,
|
||||
&challenged_public_key,
|
||||
);
|
||||
lincomb = lincomb.term(<C::ToweringCurve as Ciphersuite>::F::ONE, point.x());
|
||||
debug_assert!(point_with_dlogs.next().is_none());
|
||||
}
|
||||
|
||||
// Require the encryption mask be successfully commited to within a Pedersen commitment
|
||||
self.circuit.equality(
|
||||
lincomb,
|
||||
&LinComb::from(self.pedersen_commitment_tape.allocate_pedersen_commitment()),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The result of proving.
|
||||
pub(super) struct ProveResult<C: Curves> {
|
||||
/// The coefficients for use in the DKG.
|
||||
pub(super) coefficients: Vec<Zeroizing<<C::ToweringCurve as Ciphersuite>::F>>,
|
||||
/// The masks to encrypt secret shares with.
|
||||
pub(super) encryption_keys: Vec<Zeroizing<<C::ToweringCurve as Ciphersuite>::F>>,
|
||||
/// The proof itself.
|
||||
pub(super) proof: Vec<u8>,
|
||||
}
|
||||
|
||||
pub(super) struct Verified<C: Curves> {
|
||||
/// The commitments to the coefficients used within the DKG.
|
||||
pub(super) coefficients: Vec<<C::ToweringCurve as Ciphersuite>::G>,
|
||||
/// The ephemeral public keys to perform ECDHs with
|
||||
pub(super) ecdh_commitments: Vec<[<C::EmbeddedCurve as Ciphersuite>::G; 2]>,
|
||||
/// The commitments to the masks used to encrypt secret shares with.
|
||||
pub(super) encryption_key_commitments: Vec<<C::ToweringCurve as Ciphersuite>::G>,
|
||||
}
|
||||
|
||||
impl<C: Curves> fmt::Debug for Verified<C> {
|
||||
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
fmt.debug_struct("Verified").finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
type GeneratorTable<C> = generalized_bulletproofs_ec_gadgets::GeneratorTable<
|
||||
<<<C as Curves>::EmbeddedCurve as Ciphersuite>::G as DivisorCurve>::FieldElement,
|
||||
<C as Curves>::EmbeddedCurveParameters,
|
||||
>;
|
||||
|
||||
pub(super) struct Proof<C>(PhantomData<C>);
|
||||
impl<C: Curves> Proof<C> {
|
||||
fn discrete_log_claims(coefficients: usize, participants: usize) -> usize {
|
||||
/*
|
||||
- 1 DLOG to prove the discrete logarithm corresponds to the eVRF public key
|
||||
- 2 DLOGs per coefficient in the secret-sharing polynomial
|
||||
- 2 DLOGs per each ECDH (one to open the commitment, one for the ECDH itself), with two ECDHs
|
||||
for each participant (with the sum of their `x` coordinates being uniform and used as the
|
||||
mask)
|
||||
*/
|
||||
const DLOGS_PER_COEFFICIENT: usize = 2;
|
||||
const ECDHS_PER_PARTICIPANT: usize = 2;
|
||||
const DLOGS_PER_ECDH: usize = 2;
|
||||
const DLOGS_PER_PARTICIPANT: usize = ECDHS_PER_PARTICIPANT * DLOGS_PER_ECDH;
|
||||
1 + (DLOGS_PER_COEFFICIENT * coefficients) + (DLOGS_PER_PARTICIPANT * participants)
|
||||
}
|
||||
|
||||
fn expected_multiplications(coefficients: usize, participants: usize) -> usize {
|
||||
const MULS_PER_DLOG: usize = 7;
|
||||
MULS_PER_DLOG * Self::discrete_log_claims(coefficients, participants)
|
||||
}
|
||||
|
||||
pub(crate) fn generators_to_use(coefficients: usize, participants: usize) -> usize {
|
||||
/*
|
||||
`expected_multiplications` may be as small as 16, which would create an excessive amount of
|
||||
vector commitments (as a vector commitment can only commit to as many variables as we have
|
||||
multiplications).
|
||||
|
||||
We require the actual amount of multiplications to be at least 2048 (even though that
|
||||
that 'wastes' thousands of multiplications) to ensure the bandwidth usage remains reasonable.
|
||||
*/
|
||||
Self::expected_multiplications(coefficients, participants).next_power_of_two().max(2048)
|
||||
}
|
||||
|
||||
fn variables_in_vector_commitments(coefficients: usize, participants: usize) -> usize {
|
||||
Tape::variables_for_points_with_common_dlog::<C>(1 + (2 * coefficients)) +
|
||||
(participants * 2 * Tape::variables_for_points_with_common_dlog::<C>(2))
|
||||
}
|
||||
|
||||
fn circuit(
|
||||
curve_spec: &CurveSpec<<<C::EmbeddedCurve as Ciphersuite>::G as DivisorCurve>::FieldElement>,
|
||||
evrf_public_key: EmbeddedPoint<C>,
|
||||
coefficients: usize,
|
||||
ecdh_commitments: &[[EmbeddedPoint<C>; 2]],
|
||||
generator_tables: &[&GeneratorTable<C>],
|
||||
circuit: &mut BpCircuit<C::ToweringCurve>,
|
||||
transcript: &mut impl Transcript,
|
||||
) {
|
||||
let participants = ecdh_commitments.len();
|
||||
let generators_to_use = Self::generators_to_use(coefficients, participants);
|
||||
|
||||
// Sample the challenge for all the discrete-logarithm claims
|
||||
let (challenge, challenged_generators) =
|
||||
circuit.discrete_log_challenge(transcript, curve_spec, generator_tables);
|
||||
|
||||
/*
|
||||
The generator tables, and the challenged generators, will have the following layout:
|
||||
- G
|
||||
- Generators for the eVRFs used to sample the coefficients
|
||||
- The participants' public keys, used for performing ECDHs with
|
||||
*/
|
||||
let mut challenged_generators = challenged_generators.into_iter();
|
||||
#[allow(non_snake_case)]
|
||||
let challenged_G = challenged_generators.next().unwrap();
|
||||
|
||||
let tape = Tape::new(generators_to_use);
|
||||
let pedersen_commitment_tape = PedersenCommitmentTape::new();
|
||||
|
||||
{
|
||||
let mut circuit = Circuit::<C, _> {
|
||||
curve_spec,
|
||||
circuit,
|
||||
challenge,
|
||||
challenged_G,
|
||||
challenged_generators: &mut challenged_generators,
|
||||
tape,
|
||||
pedersen_commitment_tape,
|
||||
};
|
||||
|
||||
circuit.coefficients(evrf_public_key, coefficients);
|
||||
|
||||
// Now execute the circuit for the ECDHs
|
||||
for ecdh_commitments in ecdh_commitments {
|
||||
circuit.verifiable_encryption(ecdh_commitments);
|
||||
}
|
||||
}
|
||||
|
||||
debug_assert_eq!(
|
||||
Self::expected_multiplications(coefficients, participants),
|
||||
circuit.muls(),
|
||||
"unexpected amount of multiplications actually used"
|
||||
);
|
||||
debug_assert!(
|
||||
challenged_generators.next().is_none(),
|
||||
"didn't consume all challenged generators"
|
||||
);
|
||||
}
|
||||
|
||||
/// Sample the points for the eVRF invocations used for the coefficients.
|
||||
fn sample_coefficients_evrf_points(
|
||||
seed: [u8; 32],
|
||||
coefficients: usize,
|
||||
) -> Vec<<C::EmbeddedCurve as Ciphersuite>::G> {
|
||||
let mut rng = ChaCha20Rng::from_seed(seed);
|
||||
let quantity = 2 * coefficients;
|
||||
let mut res = Vec::with_capacity(quantity);
|
||||
for _ in 0 .. quantity {
|
||||
res.push(crate::sample_point::<C::EmbeddedCurve>(&mut rng));
|
||||
}
|
||||
res
|
||||
}
|
||||
|
||||
/// Create the required tables for the generators.
|
||||
fn generator_tables(
|
||||
coefficients_evrf_points: &[<C::EmbeddedCurve as Ciphersuite>::G],
|
||||
participants: &[<<C as Curves>::EmbeddedCurve as Ciphersuite>::G],
|
||||
) -> Vec<GeneratorTable<C>> {
|
||||
let curve_spec = CurveSpec {
|
||||
a: <<C as Curves>::EmbeddedCurve as Ciphersuite>::G::a(),
|
||||
b: <<C as Curves>::EmbeddedCurve as Ciphersuite>::G::b(),
|
||||
};
|
||||
|
||||
let mut generator_tables =
|
||||
Vec::with_capacity(1 + coefficients_evrf_points.len() + participants.len());
|
||||
{
|
||||
let (x, y) =
|
||||
<C::EmbeddedCurve as Ciphersuite>::G::to_xy(<C::EmbeddedCurve as Ciphersuite>::generator())
|
||||
.unwrap();
|
||||
generator_tables.push(GeneratorTable::<C>::new(&curve_spec, x, y));
|
||||
}
|
||||
for generator in coefficients_evrf_points {
|
||||
let (x, y) = <C::EmbeddedCurve as Ciphersuite>::G::to_xy(*generator).unwrap();
|
||||
generator_tables.push(GeneratorTable::<C>::new(&curve_spec, x, y));
|
||||
}
|
||||
for generator in participants {
|
||||
let (x, y) = <C::EmbeddedCurve as Ciphersuite>::G::to_xy(*generator).unwrap();
|
||||
generator_tables.push(GeneratorTable::<C>::new(&curve_spec, x, y));
|
||||
}
|
||||
generator_tables
|
||||
}
|
||||
|
||||
pub(super) fn prove(
|
||||
rng: &mut (impl RngCore + CryptoRng),
|
||||
generators: &Generators<C::ToweringCurve>,
|
||||
transcript: [u8; 32],
|
||||
coefficients: usize,
|
||||
participant_public_keys: &[<<C as Curves>::EmbeddedCurve as Ciphersuite>::G],
|
||||
evrf_private_key: &Zeroizing<<<C as Curves>::EmbeddedCurve as Ciphersuite>::F>,
|
||||
) -> Result<ProveResult<C>, AcProveError> {
|
||||
let curve_spec = CurveSpec {
|
||||
a: <<C as Curves>::EmbeddedCurve as Ciphersuite>::G::a(),
|
||||
b: <<C as Curves>::EmbeddedCurve as Ciphersuite>::G::b(),
|
||||
};
|
||||
|
||||
let coefficients_evrf_points = Self::sample_coefficients_evrf_points(transcript, coefficients);
|
||||
let generator_tables =
|
||||
Self::generator_tables(&coefficients_evrf_points, participant_public_keys);
|
||||
|
||||
// Push a discrete logarithm onto the tape
|
||||
let discrete_log =
|
||||
|vector_commitment_tape: &mut Vec<_>,
|
||||
dlog: &ScalarDecomposition<<<C as Curves>::EmbeddedCurve as Ciphersuite>::F>| {
|
||||
for coefficient in dlog.decomposition() {
|
||||
vector_commitment_tape.push(<_>::from(*coefficient));
|
||||
}
|
||||
};
|
||||
|
||||
// Push a discrete-log claim onto the tape.
|
||||
//
|
||||
// Returns the point for which the claim was made.
|
||||
let discrete_log_claim =
|
||||
|vector_commitment_tape: &mut Vec<_>,
|
||||
dlog: &ScalarDecomposition<<<C as Curves>::EmbeddedCurve as Ciphersuite>::F>,
|
||||
generator: <<C as Curves>::EmbeddedCurve as Ciphersuite>::G| {
|
||||
{
|
||||
let divisor =
|
||||
Zeroizing::new(dlog.scalar_mul_divisor(generator).normalize_x_coefficient());
|
||||
vector_commitment_tape.push(divisor.zero_coefficient);
|
||||
for coefficient in divisor.x_coefficients.iter().skip(1) {
|
||||
vector_commitment_tape.push(*coefficient);
|
||||
}
|
||||
for coefficient in divisor.yx_coefficients.first().unwrap_or(&vec![]) {
|
||||
vector_commitment_tape.push(*coefficient);
|
||||
}
|
||||
vector_commitment_tape.push(
|
||||
divisor
|
||||
.y_coefficients
|
||||
.first()
|
||||
.copied()
|
||||
.unwrap_or(<C::ToweringCurve as Ciphersuite>::F::ZERO),
|
||||
);
|
||||
}
|
||||
|
||||
let dh = generator * dlog.scalar();
|
||||
let (x, y) = <C::EmbeddedCurve as Ciphersuite>::G::to_xy(dh).unwrap();
|
||||
vector_commitment_tape.push(x);
|
||||
vector_commitment_tape.push(y);
|
||||
(dh, (x, y))
|
||||
};
|
||||
|
||||
let mut vector_commitment_tape = Zeroizing::new(Vec::with_capacity(
|
||||
Self::variables_in_vector_commitments(coefficients, participant_public_keys.len()),
|
||||
));
|
||||
|
||||
// Handle the coefficients
|
||||
let mut coefficients = Vec::with_capacity(coefficients);
|
||||
let evrf_public_key = {
|
||||
let evrf_private_key =
|
||||
ScalarDecomposition::<<C::EmbeddedCurve as Ciphersuite>::F>::new(**evrf_private_key)
|
||||
.expect("eVRF private key was zero");
|
||||
|
||||
discrete_log(&mut vector_commitment_tape, &evrf_private_key);
|
||||
|
||||
// Push the divisor for proving that we're using the correct scalar
|
||||
let (_, evrf_public_key) = discrete_log_claim(
|
||||
&mut vector_commitment_tape,
|
||||
&evrf_private_key,
|
||||
<<C as Curves>::EmbeddedCurve as Ciphersuite>::generator(),
|
||||
);
|
||||
|
||||
// Push the divisor for each point we use in the eVRF
|
||||
for pair in coefficients_evrf_points.chunks(2) {
|
||||
let mut coefficient = Zeroizing::new(<C::ToweringCurve as Ciphersuite>::F::ZERO);
|
||||
for point in pair {
|
||||
let (_, (dh_x, _)) =
|
||||
discrete_log_claim(&mut vector_commitment_tape, &evrf_private_key, *point);
|
||||
*coefficient += dh_x;
|
||||
}
|
||||
coefficients.push(coefficient);
|
||||
}
|
||||
|
||||
evrf_public_key
|
||||
};
|
||||
|
||||
// Handle the verifiable encryption
|
||||
let mut encryption_keys = Vec::with_capacity(participant_public_keys.len());
|
||||
let mut ecdh_commitments = Vec::with_capacity(2 * participant_public_keys.len());
|
||||
let mut ecdh_commitments_xy = Vec::with_capacity(participant_public_keys.len());
|
||||
for participant_public_key in participant_public_keys {
|
||||
let mut ecdh_commitments_xy_i =
|
||||
[(<C::ToweringCurve as Ciphersuite>::F::ZERO, <C::ToweringCurve as Ciphersuite>::F::ZERO);
|
||||
2];
|
||||
let mut encryption_key = Zeroizing::new(<C::ToweringCurve as Ciphersuite>::F::ZERO);
|
||||
for ecdh_commitments_xy_i_j_dest in &mut ecdh_commitments_xy_i {
|
||||
let mut ecdh_ephemeral_secret;
|
||||
loop {
|
||||
ecdh_ephemeral_secret =
|
||||
Zeroizing::new(<C::EmbeddedCurve as Ciphersuite>::F::random(&mut *rng));
|
||||
// 0 would produce the identity, which isn't representable within the discrete-log proof.
|
||||
if bool::from(!ecdh_ephemeral_secret.is_zero()) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
let ecdh_ephemeral_secret =
|
||||
ScalarDecomposition::<<C::EmbeddedCurve as Ciphersuite>::F>::new(*ecdh_ephemeral_secret)
|
||||
.expect("ECDH ephemeral secret zero");
|
||||
discrete_log(&mut vector_commitment_tape, &ecdh_ephemeral_secret);
|
||||
|
||||
// Push a divisor for proving that we're using the correct scalar for the commitment
|
||||
let (ecdh_commitment, ecdh_commitment_xy_i_j) = discrete_log_claim(
|
||||
&mut vector_commitment_tape,
|
||||
&ecdh_ephemeral_secret,
|
||||
<<C as Curves>::EmbeddedCurve as Ciphersuite>::generator(),
|
||||
);
|
||||
ecdh_commitments.push(ecdh_commitment);
|
||||
*ecdh_commitments_xy_i_j_dest = ecdh_commitment_xy_i_j;
|
||||
// Push a divisor for the key we're performing the ECDH with
|
||||
let (_, (dh_x, _)) = discrete_log_claim(
|
||||
&mut vector_commitment_tape,
|
||||
&ecdh_ephemeral_secret,
|
||||
*participant_public_key,
|
||||
);
|
||||
*encryption_key += dh_x;
|
||||
}
|
||||
ecdh_commitments_xy.push(ecdh_commitments_xy_i);
|
||||
encryption_keys.push(encryption_key);
|
||||
}
|
||||
|
||||
// Convert the vector commitment tape into vector commitments
|
||||
let generators_to_use =
|
||||
Self::generators_to_use(coefficients.len(), participant_public_keys.len());
|
||||
debug_assert_eq!(
|
||||
Self::variables_in_vector_commitments(coefficients.len(), participant_public_keys.len()),
|
||||
vector_commitment_tape.len()
|
||||
);
|
||||
let mut vector_commitments =
|
||||
Vec::with_capacity(vector_commitment_tape.len().div_ceil(generators_to_use));
|
||||
for chunk in vector_commitment_tape.chunks(generators_to_use) {
|
||||
vector_commitments.push(PedersenVectorCommitment {
|
||||
g_values: chunk.into(),
|
||||
mask: <C::ToweringCurve as Ciphersuite>::F::random(&mut *rng),
|
||||
});
|
||||
}
|
||||
|
||||
// Create the Pedersen commitments
|
||||
let mut commitments = Vec::with_capacity(coefficients.len() + participant_public_keys.len());
|
||||
for coefficient in &coefficients {
|
||||
commitments.push(PedersenCommitment {
|
||||
value: **coefficient,
|
||||
mask: <C::ToweringCurve as Ciphersuite>::F::random(&mut *rng),
|
||||
});
|
||||
}
|
||||
for enc_mask in &encryption_keys {
|
||||
commitments.push(PedersenCommitment {
|
||||
value: **enc_mask,
|
||||
mask: <C::ToweringCurve as Ciphersuite>::F::random(&mut *rng),
|
||||
});
|
||||
}
|
||||
|
||||
let mut transcript = ProverTranscript::new(transcript);
|
||||
let commited_commitments = transcript.write_commitments(
|
||||
vector_commitments
|
||||
.iter()
|
||||
.map(|commitment| {
|
||||
commitment
|
||||
.commit(generators.g_bold_slice(), generators.h())
|
||||
.ok_or(AcProveError::IncorrectAmountOfGenerators)
|
||||
})
|
||||
.collect::<Result<_, _>>()?,
|
||||
commitments
|
||||
.iter()
|
||||
.map(|commitment| commitment.commit(generators.g(), generators.h()))
|
||||
.collect(),
|
||||
);
|
||||
for ecdh_commitment in ecdh_commitments {
|
||||
transcript.push_point(&ecdh_commitment);
|
||||
}
|
||||
|
||||
let mut circuit = BpCircuit::prove(vector_commitments, commitments.clone());
|
||||
Self::circuit(
|
||||
&curve_spec,
|
||||
evrf_public_key,
|
||||
coefficients.len(),
|
||||
&ecdh_commitments_xy,
|
||||
&generator_tables.iter().collect::<Vec<_>>(),
|
||||
&mut circuit,
|
||||
&mut transcript,
|
||||
);
|
||||
|
||||
let (statement, Some(witness)) = circuit
|
||||
.statement(
|
||||
generators.reduce(generators_to_use).ok_or(AcProveError::IncorrectAmountOfGenerators)?,
|
||||
commited_commitments,
|
||||
)
|
||||
.unwrap()
|
||||
else {
|
||||
panic!("proving yet wasn't yielded the witness");
|
||||
};
|
||||
statement.prove(&mut *rng, &mut transcript, witness).unwrap();
|
||||
|
||||
// Push the reveal onto the transcript
|
||||
for commitment in &commitments {
|
||||
transcript.push_point(&(generators.g() * commitment.value));
|
||||
}
|
||||
|
||||
// Prove the openings of the commitments were correct
|
||||
let mut x = Zeroizing::new(<C::ToweringCurve as Ciphersuite>::F::ZERO);
|
||||
for commitment in commitments {
|
||||
*x += commitment.mask * transcript.challenge::<C::ToweringCurve>();
|
||||
}
|
||||
|
||||
// Produce a Schnorr PoK for the weighted-sum of the Pedersen commitments' blinding factors
|
||||
let r = Zeroizing::new(<C::ToweringCurve as Ciphersuite>::F::random(&mut *rng));
|
||||
transcript.push_point(&(generators.h() * r.deref()));
|
||||
let c = transcript.challenge::<C::ToweringCurve>();
|
||||
transcript.push_scalar((c * x.deref()) + r.deref());
|
||||
|
||||
Ok(ProveResult { coefficients, encryption_keys, proof: transcript.complete() })
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn verify(
|
||||
rng: &mut (impl RngCore + CryptoRng),
|
||||
generators: &Generators<C::ToweringCurve>,
|
||||
verifier: &mut BatchVerifier<C::ToweringCurve>,
|
||||
transcript: [u8; 32],
|
||||
coefficients: usize,
|
||||
participant_public_keys: &[<<C as Curves>::EmbeddedCurve as Ciphersuite>::G],
|
||||
evrf_public_key: <<C as Curves>::EmbeddedCurve as Ciphersuite>::G,
|
||||
proof: &[u8],
|
||||
) -> Result<Verified<C>, ()> {
|
||||
let (mut transcript, ecdh_commitments, pedersen_commitments) = {
|
||||
let curve_spec = CurveSpec {
|
||||
a: <<C as Curves>::EmbeddedCurve as Ciphersuite>::G::a(),
|
||||
b: <<C as Curves>::EmbeddedCurve as Ciphersuite>::G::b(),
|
||||
};
|
||||
|
||||
let coefficients_evrf_points =
|
||||
Self::sample_coefficients_evrf_points(transcript, coefficients);
|
||||
let generator_tables =
|
||||
Self::generator_tables(&coefficients_evrf_points, participant_public_keys);
|
||||
|
||||
let generators_to_use = Self::generators_to_use(coefficients, participant_public_keys.len());
|
||||
|
||||
let mut transcript = VerifierTranscript::new(transcript, proof);
|
||||
|
||||
let vector_commitments =
|
||||
Self::variables_in_vector_commitments(coefficients, participant_public_keys.len())
|
||||
.div_ceil(generators_to_use);
|
||||
/*
|
||||
One commitment is used to commit to each coefficient of the secret-sharing polynomial, and
|
||||
one commitment is used to commit to each encryption key used to encrypt a secret share to
|
||||
its recipient.
|
||||
*/
|
||||
let pedersen_commitments = coefficients + participant_public_keys.len();
|
||||
let all_commitments =
|
||||
transcript.read_commitments(vector_commitments, pedersen_commitments).map_err(|_| ())?;
|
||||
let pedersen_commitments = all_commitments.V().to_vec();
|
||||
|
||||
// Read the commitments to the ephemeral secrets for the ECDHs
|
||||
let mut ecdh_commitments = Vec::with_capacity(participant_public_keys.len());
|
||||
let mut ecdh_commitments_xy = Vec::with_capacity(participant_public_keys.len());
|
||||
for _ in 0 .. participant_public_keys.len() {
|
||||
let ecdh_commitments_i = [
|
||||
transcript.read_point::<C::EmbeddedCurve>().map_err(|_| ())?,
|
||||
transcript.read_point::<C::EmbeddedCurve>().map_err(|_| ())?,
|
||||
];
|
||||
ecdh_commitments.push(ecdh_commitments_i);
|
||||
// This inherently bans using the identity point, as it won't have an affine representation
|
||||
ecdh_commitments_xy.push([
|
||||
<<C::EmbeddedCurve as Ciphersuite>::G as DivisorCurve>::to_xy(ecdh_commitments_i[0])
|
||||
.ok_or(())?,
|
||||
<<C::EmbeddedCurve as Ciphersuite>::G as DivisorCurve>::to_xy(ecdh_commitments_i[1])
|
||||
.ok_or(())?,
|
||||
]);
|
||||
}
|
||||
|
||||
let mut circuit = BpCircuit::verify();
|
||||
Self::circuit(
|
||||
&curve_spec,
|
||||
<C::EmbeddedCurve as Ciphersuite>::G::to_xy(evrf_public_key).ok_or(())?,
|
||||
coefficients,
|
||||
&ecdh_commitments_xy,
|
||||
&generator_tables.iter().collect::<Vec<_>>(),
|
||||
&mut circuit,
|
||||
&mut transcript,
|
||||
);
|
||||
|
||||
let (statement, None) = circuit
|
||||
.statement(generators.reduce(generators_to_use).ok_or(())?, all_commitments)
|
||||
.unwrap()
|
||||
else {
|
||||
panic!("verifying yet was yielded a witness");
|
||||
};
|
||||
|
||||
statement.verify(rng, verifier, &mut transcript).map_err(|_| ())?;
|
||||
|
||||
(transcript, ecdh_commitments, pedersen_commitments)
|
||||
};
|
||||
|
||||
// Read the openings for each of the Pedersen commitments
|
||||
let mut openings = Vec::with_capacity(pedersen_commitments.len());
|
||||
for _ in 0 .. pedersen_commitments.len() {
|
||||
openings.push(transcript.read_point::<C::ToweringCurve>().map_err(|_| ())?);
|
||||
}
|
||||
|
||||
/*
|
||||
Verify the openings of each of the Pedersen commitments.
|
||||
|
||||
We do this via verifying the prover knows an opening of their Pedersen commitment, minus the
|
||||
claimed opening, over the blinding generator. For efficiency, we take a random combination of
|
||||
all commitments/openings, solely requiring the prover know the single opening for the
|
||||
combination.
|
||||
*/
|
||||
{
|
||||
let (weighted_sum_commitments, weighted_sum_openings) = {
|
||||
let mut weighted_sum_commitments = Vec::with_capacity(pedersen_commitments.len());
|
||||
let mut weighted_sum_openings = Vec::with_capacity(pedersen_commitments.len());
|
||||
for (pedersen_commitment, opening) in pedersen_commitments.iter().zip(&openings) {
|
||||
let weight = transcript.challenge::<C::ToweringCurve>();
|
||||
weighted_sum_commitments.push((weight, *pedersen_commitment));
|
||||
weighted_sum_openings.push((weight, *opening));
|
||||
}
|
||||
(
|
||||
multiexp::multiexp_vartime(&weighted_sum_commitments),
|
||||
multiexp::multiexp_vartime(&weighted_sum_openings),
|
||||
)
|
||||
};
|
||||
#[allow(non_snake_case)]
|
||||
let A = weighted_sum_commitments - weighted_sum_openings;
|
||||
|
||||
// Schnorr signature
|
||||
#[allow(non_snake_case)]
|
||||
let R = transcript.read_point::<C::ToweringCurve>().map_err(|_| ())?;
|
||||
let c = transcript.challenge::<C::ToweringCurve>();
|
||||
let s = transcript.read_scalar::<C::ToweringCurve>().map_err(|_| ())?;
|
||||
|
||||
// Doesn't batch verify this as we can't access the internals of the GBP batch verifier
|
||||
if (R + (A * c)) != (generators.h() * s) {
|
||||
Err(())?;
|
||||
}
|
||||
}
|
||||
|
||||
if !transcript.complete().is_empty() {
|
||||
Err(())?
|
||||
};
|
||||
|
||||
let coefficients = openings[.. coefficients].to_vec();
|
||||
let encryption_key_commitments = openings[coefficients.len() ..].to_vec();
|
||||
Ok(Verified { coefficients, ecdh_commitments, encryption_key_commitments })
|
||||
}
|
||||
}
|
||||
106
crypto/dkg/evrf/src/proof/tape.rs
Normal file
106
crypto/dkg/evrf/src/proof/tape.rs
Normal file
@@ -0,0 +1,106 @@
|
||||
use core::marker::PhantomData;
|
||||
|
||||
use generic_array::{sequence::GenericSequence, ArrayLength, GenericArray};
|
||||
|
||||
use generalized_bulletproofs_circuit_abstraction::Variable;
|
||||
use generalized_bulletproofs_ec_gadgets::{DiscreteLogParameter, Divisor, PointWithDlog};
|
||||
|
||||
use crate::Curves;
|
||||
|
||||
/*
|
||||
For all variables we must commit to during the ZK proof, we place them on the 'tape'. The tape
|
||||
is a linear representation of every single variable committed to by the proof, from which we can
|
||||
read a collection of variables from/push a collection of variables onto. This offers an API
|
||||
similar to reading/writing to a byte stream, despite working with variables in a ZK proof.
|
||||
*/
|
||||
pub(super) struct Tape {
|
||||
generators: usize,
|
||||
current_position: usize,
|
||||
}
|
||||
impl Tape {
|
||||
// Construct a new tape.
|
||||
pub(super) fn new(generators: usize) -> Self {
|
||||
Self { generators, current_position: 0 }
|
||||
}
|
||||
|
||||
/// Read a Variable from the tape.
|
||||
fn read_one_from_tape(&mut self) -> Variable {
|
||||
let commitment = self.current_position / self.generators;
|
||||
let index = self.current_position % self.generators;
|
||||
let res = Variable::CG { commitment, index };
|
||||
self.current_position += 1;
|
||||
res
|
||||
}
|
||||
|
||||
/// Read a fixed-length array of variables from the tape.
|
||||
fn read_from_tape<N: ArrayLength>(&mut self) -> GenericArray<Variable, N> {
|
||||
GenericArray::<Variable, N>::generate(|_| self.read_one_from_tape())
|
||||
}
|
||||
|
||||
/// Read `PointWithDlog`s, which share a discrete logarithm, from the tape.
|
||||
pub(super) fn read_points_with_common_dlog<C: Curves>(
|
||||
&mut self,
|
||||
quantity: usize,
|
||||
) -> impl use<'_, C> + Iterator<Item = PointWithDlog<C::EmbeddedCurveParameters>> {
|
||||
/*
|
||||
The tape expects the format of:
|
||||
- Discrete logarithm
|
||||
- Divisor (zero coefficient, x coefficients, y x**i coefficients, y coefficient)
|
||||
- Point (x, y)
|
||||
Note the `x` coefficients are only from the power of two, and `i >= 1`.
|
||||
*/
|
||||
let dlog =
|
||||
self.read_from_tape::<<C::EmbeddedCurveParameters as DiscreteLogParameter>::ScalarBits>();
|
||||
|
||||
struct PointIterator<'a, C: Curves>(
|
||||
&'a mut Tape,
|
||||
GenericArray<Variable, <C::EmbeddedCurveParameters as DiscreteLogParameter>::ScalarBits>,
|
||||
PhantomData<C>,
|
||||
);
|
||||
impl<'a, C: Curves> Iterator for PointIterator<'a, C> {
|
||||
type Item = PointWithDlog<C::EmbeddedCurveParameters>;
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
let divisor = {
|
||||
let zero = self.0.read_one_from_tape();
|
||||
let x_from_power_of_2 = self.0.read_from_tape();
|
||||
let yx = self.0.read_from_tape();
|
||||
let y = self.0.read_one_from_tape();
|
||||
Divisor { zero, x_from_power_of_2, yx, y }
|
||||
};
|
||||
|
||||
let point = (
|
||||
// x coordinate
|
||||
self.0.read_one_from_tape(),
|
||||
// y coordinate
|
||||
self.0.read_one_from_tape(),
|
||||
);
|
||||
|
||||
Some(PointWithDlog { dlog: self.1.clone(), divisor, point })
|
||||
}
|
||||
}
|
||||
|
||||
PointIterator(self, dlog, PhantomData::<C>).take(quantity)
|
||||
}
|
||||
|
||||
/// The amount of variables the points with a common discrete logarithm will use on the tape.
|
||||
pub(super) fn variables_for_points_with_common_dlog<C: Curves>(quantity: usize) -> usize {
|
||||
let mut dummy_tape = Tape::new(usize::MAX);
|
||||
for _ in dummy_tape.read_points_with_common_dlog::<C>(quantity) {}
|
||||
dummy_tape.current_position
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) struct PedersenCommitmentTape {
|
||||
pedersen_commitments: usize,
|
||||
}
|
||||
impl PedersenCommitmentTape {
|
||||
pub(super) fn new() -> Self {
|
||||
Self { pedersen_commitments: 0 }
|
||||
}
|
||||
/// Allocate a Pedersen commitment.
|
||||
pub(super) fn allocate_pedersen_commitment(&mut self) -> Variable {
|
||||
let res = Variable::V(self.pedersen_commitments);
|
||||
self.pedersen_commitments += 1;
|
||||
res
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user