diff --git a/.github/workflows/blockchain-contracts-abi.yml b/.github/workflows/blockchain-contracts-abi.yml index 2bcdb3f..03d1cac 100644 --- a/.github/workflows/blockchain-contracts-abi.yml +++ b/.github/workflows/blockchain-contracts-abi.yml @@ -23,7 +23,7 @@ jobs: - name: Install rust uses: dtolnay/rust-toolchain@master with: - toolchain: '1.86' # keep in sync with rust/lit-node/rust-toolchain.toml + toolchain: '1.91' # keep in sync with rust/lit-node/rust-toolchain.toml components: rustfmt - name: Run Contract Updates diff --git a/.github/workflows/rust-lit-actions.yml b/.github/workflows/rust-lit-actions.yml index ce1b83d..3d4b135 100644 --- a/.github/workflows/rust-lit-actions.yml +++ b/.github/workflows/rust-lit-actions.yml @@ -40,7 +40,7 @@ jobs: - name: Install rust uses: dtolnay/rust-toolchain@master with: - toolchain: '1.86' # keep in sync with rust/lit-node/rust-toolchain.toml + toolchain: '1.91' # keep in sync with rust/lit-node/rust-toolchain.toml components: rustfmt clippy rust-src - name: Install tools uses: taiki-e/install-action@v2 diff --git a/.github/workflows/rust-lit-core.yml b/.github/workflows/rust-lit-core.yml index 59e7bb6..da83a51 100644 --- a/.github/workflows/rust-lit-core.yml +++ b/.github/workflows/rust-lit-core.yml @@ -40,7 +40,7 @@ jobs: - name: Install rust uses: dtolnay/rust-toolchain@master with: - toolchain: "1.86" # keep in sync with rust/lit-core/rust-toolchain.toml + toolchain: "1.91" # keep in sync with rust/lit-core/rust-toolchain.toml components: rustfmt clippy rust-src - name: Rust Cache uses: WarpBuilds/rust-cache@v2 diff --git a/.github/workflows/rust-lit-node-build-commit-hash.yml b/.github/workflows/rust-lit-node-build-commit-hash.yml index 976159f..a42ef45 100644 --- a/.github/workflows/rust-lit-node-build-commit-hash.yml +++ b/.github/workflows/rust-lit-node-build-commit-hash.yml @@ -48,7 +48,7 @@ jobs: - name: Install rust uses: dtolnay/rust-toolchain@master with: - toolchain: '1.86' # keep in sync with rust/lit-node/rust-toolchain.toml + toolchain: '1.91' # keep in sync with rust/lit-node/rust-toolchain.toml components: rustfmt rust-src - name: Build node run: cargo build --features lit-actions,testing diff --git a/.github/workflows/rust-lit-node-build.yml b/.github/workflows/rust-lit-node-build.yml index 489a41a..e504753 100644 --- a/.github/workflows/rust-lit-node-build.yml +++ b/.github/workflows/rust-lit-node-build.yml @@ -61,7 +61,7 @@ jobs: - name: Install rust uses: dtolnay/rust-toolchain@master with: - toolchain: '1.86' # keep in sync with rust/lit-node/lit-node/rust-toolchain.toml + toolchain: '1.91' # keep in sync with rust/lit-node/lit-node/rust-toolchain.toml components: rustfmt rust-src - name: Setup local files for testing run: make setup-local-files diff --git a/.github/workflows/rust-lit-node-clippy.yml b/.github/workflows/rust-lit-node-clippy.yml index 027674d..52b918a 100644 --- a/.github/workflows/rust-lit-node-clippy.yml +++ b/.github/workflows/rust-lit-node-clippy.yml @@ -53,7 +53,7 @@ jobs: - name: Install rust uses: dtolnay/rust-toolchain@master with: - toolchain: "1.86" # keep in sync with rust/lit-node/lit-node/rust-toolchain.toml + toolchain: "1.91" # keep in sync with rust/lit-node/lit-node/rust-toolchain.toml components: rustfmt clippy rust-src - name: Cargo fmt check run: cargo fmt -- --check diff --git a/.github/workflows/rust-lit-node-group-unit-and-integration-tests.yml b/.github/workflows/rust-lit-node-group-unit-and-integration-tests.yml index 2c2c61b..cef8485 100644 --- a/.github/workflows/rust-lit-node-group-unit-and-integration-tests.yml +++ b/.github/workflows/rust-lit-node-group-unit-and-integration-tests.yml @@ -78,7 +78,7 @@ jobs: - name: Install rust uses: dtolnay/rust-toolchain@master with: - toolchain: '1.86' # keep in sync with rust/lit-node/rust-toolchain.toml + toolchain: '1.91' # keep in sync with rust/lit-node/rust-toolchain.toml - name: Rust Cache uses: WarpBuilds/rust-cache@v2 with: @@ -201,7 +201,7 @@ jobs: - name: Install rust because the version upgrade tests do a recompile uses: dtolnay/rust-toolchain@master with: - toolchain: '1.86' # keep in sync with rust/lit-node/rust-toolchain.toml + toolchain: '1.91' # keep in sync with rust/lit-node/rust-toolchain.toml components: rust-src - name: Install nextest run: curl -LsSf https://get.nexte.st/latest/linux | tar zxf - -C "${CARGO_HOME:-$HOME/.cargo}/bin" diff --git a/.github/workflows/rust-lit-os.yml b/.github/workflows/rust-lit-os.yml index 0684b74..c42319b 100644 --- a/.github/workflows/rust-lit-os.yml +++ b/.github/workflows/rust-lit-os.yml @@ -43,7 +43,7 @@ jobs: - name: Install rust uses: dtolnay/rust-toolchain@master with: - toolchain: "1.86" # keep in sync with rust/lit-os/rust-toolchain.toml + toolchain: "1.91" # keep in sync with rust/lit-os/rust-toolchain.toml components: rustfmt clippy rust-src - name: Rust Cache uses: WarpBuilds/rust-cache@v2 diff --git a/blockchain/contracts/scripts/deploy_lit_node_contracts.js b/blockchain/contracts/scripts/deploy_lit_node_contracts.js index 499a91b..0a56d96 100644 --- a/blockchain/contracts/scripts/deploy_lit_node_contracts.js +++ b/blockchain/contracts/scripts/deploy_lit_node_contracts.js @@ -546,8 +546,8 @@ async function deployLitNodeContracts(deployNodeConfig) { monetaryValue: 0, completeIsolation: false, realms: [1], - curves: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], - counts: [1, 2, 2, 2, 2, 2, 2, 2, 2, 2], + curves: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], + counts: [1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2], recoveryPartyMembers: [], }; tx = await stakingContract.setKeySet(defaultKeysetConfig); diff --git a/blockchain/contracts/test/domain-wallets/DomainWalletRegistry.ts b/blockchain/contracts/test/domain-wallets/DomainWalletRegistry.ts index fbe97fc..0f6207f 100644 --- a/blockchain/contracts/test/domain-wallets/DomainWalletRegistry.ts +++ b/blockchain/contracts/test/domain-wallets/DomainWalletRegistry.ts @@ -204,8 +204,8 @@ describe('DomainWalletRegistry', function () { identifier: 'naga-keyset1', description: '', realms: [1], - curves: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], - counts: [1, 2, 2, 2, 2, 2, 2, 2, 2, 2], + curves: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], + counts: [1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2], recoveryPartyMembers: [], }); diff --git a/blockchain/contracts/test/lit-node/BackupRecovery.js b/blockchain/contracts/test/lit-node/BackupRecovery.js index bc90900..a6dcbc8 100644 --- a/blockchain/contracts/test/lit-node/BackupRecovery.js +++ b/blockchain/contracts/test/lit-node/BackupRecovery.js @@ -200,8 +200,8 @@ describe('BackupRecovery', function () { identifier: 'naga-keyset1', description: '', realms: [1], - curves: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], - counts: [1, 2, 2, 2, 2, 2, 2, 2, 2, 2], + curves: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], + counts: [1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2], recoveryPartyMembers: [], }); diff --git a/blockchain/contracts/test/lit-node/PKPHelper.js b/blockchain/contracts/test/lit-node/PKPHelper.js index 464914b..c0e202e 100644 --- a/blockchain/contracts/test/lit-node/PKPHelper.js +++ b/blockchain/contracts/test/lit-node/PKPHelper.js @@ -159,8 +159,8 @@ describe('PKPHelper', function () { identifier: 'naga-keyset1', description: '', realms: [1], - curves: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], - counts: [1, 2, 2, 2, 2, 2, 2, 2, 2, 2], + curves: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], + counts: [1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2], recoveryPartyMembers: [], }); diff --git a/blockchain/contracts/test/lit-node/PKPNFT.js b/blockchain/contracts/test/lit-node/PKPNFT.js index 0af6d78..6ef5329 100644 --- a/blockchain/contracts/test/lit-node/PKPNFT.js +++ b/blockchain/contracts/test/lit-node/PKPNFT.js @@ -170,8 +170,8 @@ describe('PKPNFT', function () { identifier: 'naga-keyset1', description: '', realms: [1], - curves: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], - counts: [1, 2, 2, 2, 2, 2, 2, 2, 2, 2], + curves: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], + counts: [1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2], recoveryPartyMembers: [], }); diff --git a/blockchain/contracts/test/lit-node/PKPPermissions.js b/blockchain/contracts/test/lit-node/PKPPermissions.js index 815e05e..5a71bd2 100644 --- a/blockchain/contracts/test/lit-node/PKPPermissions.js +++ b/blockchain/contracts/test/lit-node/PKPPermissions.js @@ -151,8 +151,8 @@ describe('PKPPermissions', function () { identifier: 'naga-keyset1', description: '', realms: [1], - curves: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], - counts: [1, 2, 2, 2, 2, 2, 2, 2, 2, 2], + curves: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], + counts: [1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2], recoveryPartyMembers: [], }); diff --git a/blockchain/contracts/test/lit-node/Staking.js b/blockchain/contracts/test/lit-node/Staking.js index 507b32a..0616570 100644 --- a/blockchain/contracts/test/lit-node/Staking.js +++ b/blockchain/contracts/test/lit-node/Staking.js @@ -168,8 +168,8 @@ describe('Staking', function () { identifier: 'naga-keyset1', description: '', realms: [1], - curves: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], - counts: [1, 2, 2, 2, 2, 2, 2, 2, 2, 2], + curves: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], + counts: [1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2], recoveryPartyMembers: [], }); diff --git a/rust/lit-core/Cargo.lock b/rust/lit-core/Cargo.lock index 8018719..3518a6e 100644 --- a/rust/lit-core/Cargo.lock +++ b/rust/lit-core/Cargo.lock @@ -1801,6 +1801,17 @@ dependencies = [ "constant_time_eq 0.1.5", ] +[[package]] +name = "blake2b_simd" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06e903a20b159e944f91ec8499fe1e55651480c541ea0a584f5d967c49ad9d99" +dependencies = [ + "arrayref", + "arrayvec 0.7.6", + "constant_time_eq 0.3.1", +] + [[package]] name = "blake2s_simd" version = "0.5.11" @@ -1962,25 +1973,15 @@ dependencies = [ [[package]] name = "bulletproofs" version = "4.0.0" -source = "git+https://github.com/LIT-Protocol/bulletproofs?rev=ddf11c2f593e71f24c9a3d64c56f62d82f2b5099#ddf11c2f593e71f24c9a3d64c56f62d82f2b5099" +source = "git+https://github.com/LIT-Protocol/bulletproofs.git?branch=pallas#2ee66a6e2770c73514942936950c0ca2dbbcd023" dependencies = [ "blake2", - "bls12_381_plus", - "blstrs_plus", "byteorder", - "curve25519-dalek-ml", "data-encoding", - "decaf377", "digest 0.10.7", - "ed448-goldilocks-plus", - "elliptic-curve", "elliptic-curve-tools", - "group", - "jubjub-plus", - "k256", + "lit-rust-crypto 0.6.0", "merlin", - "p256", - "p384", "rand 0.8.5", "rand_core 0.6.4", "serde", @@ -1988,7 +1989,6 @@ dependencies = [ "sha3 0.10.8", "subtle", "thiserror 2.0.14", - "vsss-rs 5.1.0", "zeroize", ] @@ -2664,25 +2664,22 @@ dependencies = [ [[package]] name = "criterion" -version = "0.5.1" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2b12d017a929603d80db1831cd3a24082f8137ce19c69e6447f54f5fc8d692f" +checksum = "e1c047a62b0cc3e145fa84415a3191f628e980b194c2755aa12300a4e6cbd928" dependencies = [ "anes", "cast", "ciborium", "clap 4.5.44", "criterion-plot", - "is-terminal", - "itertools 0.10.5", + "itertools 0.13.0", "num-traits", - "once_cell", "oorandom", "plotters", "rayon", "regex", "serde", - "serde_derive", "serde_json", "tinytemplate", "walkdir", @@ -2690,12 +2687,12 @@ dependencies = [ [[package]] name = "criterion-plot" -version = "0.5.0" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b50826342786a51a89e2da3a28f1c32b06e387201bc2d19791f622c673706b1" +checksum = "9b1bcc0dc7dfae599d84ad0b1a55f80cde8af3725da8313b528da95ef783e338" dependencies = [ "cast", - "itertools 0.10.5", + "itertools 0.13.0", ] [[package]] @@ -3030,13 +3027,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8d162beedaa69905488a8da94f5ac3edb4dd4788b732fadb7bd120b2625c1976" dependencies = [ "data-encoding", - "syn 2.0.104", + "syn 1.0.109", ] [[package]] -name = "decaf377" +name = "decaf377_plus" version = "0.10.1" -source = "git+https://github.com/LIT-Protocol/decaf377?rev=1c5755b2b90e1969d47ce89cf2d35078984a0ee5#1c5755b2b90e1969d47ce89cf2d35078984a0ee5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "209f730dfc5f9d877c7549bebc93ea0ef4fe2915b4dbf5ffebc11e8b4c17c740" dependencies = [ "ark-bls12-377", "ark-ec", @@ -3048,7 +3046,6 @@ dependencies = [ "cfg-if", "elliptic-curve", "frost-dkg", - "gennaro-dkg", "hashbrown 0.15.5", "hex", "num-bigint", @@ -4183,12 +4180,13 @@ dependencies = [ [[package]] name = "frost-dkg" -version = "0.3.3" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8176b54a998a04796e58b0ac3a6da08e5ab05aff5a7d92159619a652a29f63e8" +checksum = "00b59a575727037fbc977a68a2ace822b4b37f8f0647769946e307dc966ecfbb" dependencies = [ "elliptic-curve", "elliptic-curve-tools", + "hex", "merlin", "postcard", "rand_core 0.6.4", @@ -4458,24 +4456,6 @@ dependencies = [ "typenum", ] -[[package]] -name = "gennaro-dkg" -version = "1.0.0-rc6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "352f32caf0eb44d8f340f3bba63ca7a0dbeeb3e169a59bbb86ef40e0da10eec6" -dependencies = [ - "anyhow", - "elliptic-curve", - "elliptic-curve-tools", - "merlin", - "postcard", - "rand_chacha 0.3.1", - "rand_core 0.6.4", - "serde", - "thiserror 2.0.14", - "vsss-rs 5.1.0", -] - [[package]] name = "getrandom" version = "0.2.16" @@ -4684,44 +4664,18 @@ dependencies = [ [[package]] name = "hd-keys-curves-wasm" -version = "1.0.3" -source = "git+https://github.com/LIT-Protocol/hd-keys-curves-wasm.git?rev=5e0dcc1a6d8d08f2328d4716dca806db87f93748#5e0dcc1a6d8d08f2328d4716dca806db87f93748" -dependencies = [ - "digest 0.10.7", - "ecdsa", - "elliptic-curve", - "elliptic-curve-tools", - "getrandom 0.2.16", - "k256", - "p256", - "p384", - "sha2 0.10.9", - "subtle", -] - -[[package]] -name = "hd-keys-curves-wasm" -version = "1.0.3" -source = "git+https://github.com/LIT-Protocol/hd-keys-curves-wasm#5e0dcc1a6d8d08f2328d4716dca806db87f93748" +version = "1.0.5" +source = "git+https://github.com/LIT-Protocol/hd-keys-curves-wasm?branch=pallas#597a14b9cf4bafd4c778f1053ca4bbad0b3d249b" dependencies = [ "blake2", - "blsful", - "curve25519-dalek-ml", - "decaf377", "digest 0.10.7", "ecdsa", - "ed448-goldilocks-plus", - "elliptic-curve", "elliptic-curve-tools", "getrandom 0.2.16", - "jubjub-plus", - "k256", - "p256", - "p384", + "lit-rust-crypto 0.6.0", "sha2 0.10.9", "sha3 0.10.8", "subtle", - "vsss-rs 5.1.0", ] [[package]] @@ -4784,6 +4738,12 @@ dependencies = [ "serde", ] +[[package]] +name = "hex-literal" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6fe2267d4ed49bc07b63801559be28c718ea06c4738b7a03c94df7386d2cde46" + [[package]] name = "hidapi-rusb" version = "1.3.3" @@ -5515,6 +5475,15 @@ dependencies = [ "either", ] +[[package]] +name = "itertools" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" +dependencies = [ + "either", +] + [[package]] name = "itertools" version = "0.14.0" @@ -5592,9 +5561,9 @@ dependencies = [ [[package]] name = "jubjub-plus" -version = "0.10.8" +version = "0.10.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c2c5e88d1ac6a903e693287073860ea35299b200273d5c2bd9d7845ec39f319" +checksum = "e8cd4e5cd65bb1390238c9e2e7dc98078a7b146c9d0d080cf3a7b1ac0d2348ac" dependencies = [ "bitvec 1.0.1", "bls12_381_plus", @@ -5618,6 +5587,7 @@ dependencies = [ "cfg-if", "ecdsa", "elliptic-curve", + "hex-literal", "once_cell", "serdect 0.2.0", "sha2 0.10.9", @@ -5687,6 +5657,9 @@ name = "lazy_static" version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" +dependencies = [ + "spin 0.9.8", +] [[package]] name = "libc" @@ -5968,14 +5941,11 @@ dependencies = [ "criterion", "digest 0.10.7", "ecdsa", - "elliptic-curve", "elliptic-curve-tools", - "hd-keys-curves-wasm 1.0.3 (git+https://github.com/LIT-Protocol/hd-keys-curves-wasm.git?rev=5e0dcc1a6d8d08f2328d4716dca806db87f93748)", + "hd-keys-curves-wasm", "hex", - "k256", "lit-poly", - "p256", - "p384", + "lit-rust-crypto 0.6.0", "rand 0.8.5", "rand_chacha 0.3.1", "rstest", @@ -5984,7 +5954,6 @@ dependencies = [ "sha2 0.10.9", "subtle", "thiserror 2.0.14", - "vsss-rs 5.1.0", "zeroize", ] @@ -6011,23 +5980,15 @@ dependencies = [ name = "lit-node-core" version = "2.0.1" dependencies = [ - "blsful", - "curve25519-dalek-ml", - "decaf377", "ed25519-dalek", - "ed448-goldilocks-plus", "ethabi 16.0.0", "ethers", - "hd-keys-curves-wasm 1.0.3 (git+https://github.com/LIT-Protocol/hd-keys-curves-wasm)", + "hd-keys-curves-wasm", "hex", - "jubjub-plus", - "k256", - "p256", - "p384", + "lit-rust-crypto 0.6.0", "serde", "serde_json", "thiserror 2.0.14", - "vsss-rs 5.1.0", ] [[package]] @@ -6085,32 +6046,25 @@ dependencies = [ [[package]] name = "lit-recovery" -version = "0.2.0" +version = "0.3.0" dependencies = [ "arc-swap", "argon2", - "blsful", "bulletproofs", "byteorder", "ciborium", "clap 4.5.44", "colored", "cryptex", - "decaf377", "dirs 6.0.0", - "ed448-goldilocks-plus", - "elliptic-curve", "ethers", "generic-array 1.1.1", "glob", "hex", - "jubjub-plus", - "k256", "lit-blockchain", "lit-core", "lit-node-core", - "p256", - "p384", + "lit-rust-crypto 0.6.0", "path-clean", "rand 0.8.5", "reqwest 0.11.27", @@ -6126,25 +6080,57 @@ dependencies = [ "tiny-bip39", "tokio", "verifiable-share-encryption", - "vsss-rs 5.1.0", "winapi", ] [[package]] -name = "lit-vrf" -version = "0.2.0" +name = "lit-rust-crypto" +version = "0.5.0" +source = "git+https://github.com/LIT-Protocol/lit-rust-crypto?tag=0.5.0#0b3e4d5a9811ce151da83cab4835cf5631c9a5c3" dependencies = [ - "blake2", - "bulletproofs", + "bls12_381_plus", + "blsful", + "blstrs_plus", "curve25519-dalek-ml", - "decaf377", + "decaf377_plus", "ed448-goldilocks-plus", "elliptic-curve", - "elliptic-curve-tools", "jubjub-plus", "k256", "p256", "p384", + "pasta_curves_plus", + "vsss-rs 5.1.0", +] + +[[package]] +name = "lit-rust-crypto" +version = "0.6.0" +source = "git+https://github.com/LIT-Protocol/lit-rust-crypto?tag=0.6.0#9548fce521473f289ea1366249b782355e96507d" +dependencies = [ + "bls12_381_plus", + "blsful", + "blstrs_plus", + "curve25519-dalek-ml", + "decaf377_plus", + "ed448-goldilocks-plus", + "elliptic-curve", + "jubjub-plus", + "k256", + "p256", + "p384", + "pasta_curves_plus", + "vsss-rs 5.1.0", +] + +[[package]] +name = "lit-vrf" +version = "0.2.0" +dependencies = [ + "blake2", + "bulletproofs", + "elliptic-curve-tools", + "lit-rust-crypto 0.6.0", "rand 0.8.5", "rand_chacha 0.3.1", "rfc6979", @@ -6154,7 +6140,6 @@ dependencies = [ "sha2 0.10.9", "sha3 0.10.8", "thiserror 2.0.14", - "vsss-rs 5.1.0", ] [[package]] @@ -6481,7 +6466,7 @@ version = "0.11.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "567122ab6492f49b59def14ecc36e13e64dca4188196dd0cd41f9f3f979f3df6" dependencies = [ - "blake2b_simd", + "blake2b_simd 0.5.11", "blake2s_simd", "digest 0.9.0", "sha-1", @@ -7156,6 +7141,26 @@ dependencies = [ "subtle", ] +[[package]] +name = "pasta_curves_plus" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42e265b7ebdbfc61a8c0eeac79350cf3225cd390325dc91dd0edede5b6742d58" +dependencies = [ + "blake2", + "blake2b_simd 1.0.3", + "elliptic-curve", + "ff", + "frost-dkg", + "group", + "hex", + "lazy_static", + "rand 0.8.5", + "serde", + "static_assertions", + "subtle", +] + [[package]] name = "paste" version = "1.0.15" @@ -8434,21 +8439,20 @@ dependencies = [ [[package]] name = "rstest" -version = "0.24.0" +version = "0.26.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03e905296805ab93e13c1ec3a03f4b6c4f35e9498a3d5fa96dc626d22c03cd89" +checksum = "f5a3193c063baaa2a95a33f03035c8a72b83d97a54916055ba22d35ed3839d49" dependencies = [ "futures-timer", "futures-util", "rstest_macros", - "rustc_version 0.4.1", ] [[package]] name = "rstest_macros" -version = "0.24.0" +version = "0.26.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef0053bbffce09062bee4bcc499b0fbe7a57b879f1efe088d6d8d4c7adcdef9b" +checksum = "9c845311f0ff7951c5506121a9ad75aec44d083c31583b2ea5a30bcb0b0abba0" dependencies = [ "cfg-if", "glob", @@ -10819,13 +10823,14 @@ checksum = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191" [[package]] name = "verifiable-share-encryption" -version = "0.3.0" -source = "git+https://github.com/LIT-Protocol/verifiable-share-encryption?rev=7eddfbe736369db596d0f302c72f1d76b0fd332d#7eddfbe736369db596d0f302c72f1d76b0fd332d" +version = "0.4.0" +source = "git+https://github.com/LIT-Protocol/verifiable-share-encryption?branch=pallas#be0a4f548aa92897bd77d3ceca86ea2cec80fe07" dependencies = [ "anyhow", "bulletproofs", "data-encoding", "elliptic-curve-tools", + "lit-rust-crypto 0.5.0", "rand_core 0.6.4", "rayon", "serde", diff --git a/rust/lit-core/Cargo.toml b/rust/lit-core/Cargo.toml index d50e247..27d4c13 100644 --- a/rust/lit-core/Cargo.toml +++ b/rust/lit-core/Cargo.toml @@ -25,30 +25,23 @@ alloy = { version = "0.12.5", features = ["eip712", "sol-types"]} arc-swap = { version = "1.7" } async-std = { version = "1.13" } async-trait = { version = "0.1" } +bulletproofs = { git = "https://github.com/LIT-Protocol/bulletproofs.git", branch = "pallas" } bytes = { version = "1.10" } -curve25519-dalek = { package = "curve25519-dalek-ml", version="4.3.0", features = ["group", "serde", "rand_core"] } -decaf377 = { git = "https://github.com/LIT-Protocol/decaf377", rev = "1c5755b2b90e1969d47ce89cf2d35078984a0ee5", features = ["serde"] } derive_more = { version = "2", features = ["display"] } -ed448-goldilocks-plus = { version = "0.16", features = ["serde"] } -elliptic-curve = { version = "0.13", features = ["arithmetic", "serde"] } elliptic-curve-tools = { version = "0.1", features = ["std"] } ethers = { version = "2.0", features = ["abigen", "legacy"] } futures = { version = "0.3" } +generic-array = "=1.1.1" hex = "0.4" http-body-util = { version = "0.1.2" } hyper = { version = "1" } hyper-util = { version = "0.1", features = ["client-legacy", "server", "service"] } hyperlocal = { version = "0.9" } -jubjub = { package="jubjub-plus", version = "0.10", features = ["serde"] } -k256 = { version = "0.13", features = ["arithmetic", "hash2curve", "serde"] } -generic-array = "=1.1.1" once_cell = { version = "1.20" } opentelemetry = "0.24" opentelemetry-otlp = { version = "0.17", features = ["metrics"] } opentelemetry_sdk = { version = "0.24.1", features = ["rt-tokio", "metrics"] } opentelemetry-semantic-conventions = "0.15.0" -p256 = { version = "0.13", features = ["arithmetic", "hash2curve", "serde"] } -p384 = { version = "0.13", features = ["arithmetic", "hash2curve", "serde"] } rand = "0.8" rand_chacha = "0.3.1" reqwest = { version = "0.11.12", default-features = false, features = ["rustls-tls"] } @@ -61,5 +54,19 @@ thiserror = "2.0" tokio = { version = "1", features = ["full"] } tracing = { version = "0.1" } tracing-opentelemetry = { version = "0.25" } -vsss-rs = { version = "5.1", features = ["std"] } zeroize = { version = "1.8", features = ["derive"] } + +[workspace.dependencies.lit-rust-crypto] +git = "https://github.com/LIT-Protocol/lit-rust-crypto" +tag = "0.6.0" +features = [ + "arithmetic", + "hash2curve", + "serde", + "std", +] + +[workspace.dependencies.hd-keys-curves-wasm] +git = "https://github.com/LIT-Protocol/hd-keys-curves-wasm.git" +branch = "pallas" +default-features = false \ No newline at end of file diff --git a/rust/lit-core/lit-core/src/error/code.rs b/rust/lit-core/lit-core/src/error/code.rs index 0bb406a..b91c7be 100644 --- a/rust/lit-core/lit-core/src/error/code.rs +++ b/rust/lit-core/lit-core/src/error/code.rs @@ -14,7 +14,7 @@ use crate::types::Description; pub type ArcCode = Arc; pub trait Code: Display + Debug + Description { - fn code(&self) -> Cow; + fn code(&self) -> Cow<'_, str>; fn kind(&self) -> Option; fn http_status(&self) -> Option; } @@ -22,10 +22,10 @@ pub trait Code: Display + Debug + Description { #[allow(dead_code)] #[derive(Clone, Debug, Display, ErrorCode, Description)] pub(crate) enum EC { - /// A fatal error occured in the lit core system + /// A fatal error occurred in the lit core system #[code(kind = Unexpected, http_status = 500)] CoreFatal, - /// An unexpected internal server error occured. + /// An unexpected internal server error occurred. #[code(kind = Unexpected, http_status = 500)] CoreUnexpected, } @@ -67,7 +67,7 @@ impl Description for StaticCode { } impl Code for StaticCode { - fn code(&self) -> Cow { + fn code(&self) -> Cow<'_, str> { Cow::from(self.code.clone()) } diff --git a/rust/lit-core/lit-core/src/error/mod.rs b/rust/lit-core/lit-core/src/error/mod.rs index a716229..84e0555 100644 --- a/rust/lit-core/lit-core/src/error/mod.rs +++ b/rust/lit-core/lit-core/src/error/mod.rs @@ -785,7 +785,10 @@ mod tests { fn ec_description_test() { let code = EC::CoreFatal; - assert_eq!(code.description(), Some("A fatal error occured in the lit core system".into())); + assert_eq!( + code.description(), + Some("A fatal error occurred in the lit core system".into()) + ); assert_eq!(code.kind(), Some(Kind::Unexpected)); assert_eq!(code.http_status(), Some(500)); } diff --git a/rust/lit-core/lit-core/src/error/public.rs b/rust/lit-core/lit-core/src/error/public.rs index f5de504..9533314 100644 --- a/rust/lit-core/lit-core/src/error/public.rs +++ b/rust/lit-core/lit-core/src/error/public.rs @@ -180,7 +180,7 @@ mod tests { assert_eq!(public.error_kind, Kind::SevSnp); assert_eq!(public.error_code, Some("CoreFatal".into())); assert_eq!(public.status, 500); - assert_eq!(public.message, Some("A fatal error occured in the lit core system".into())); + assert_eq!(public.message, Some("A fatal error occurred in the lit core system".into())); assert_eq!(public.correlation_id, None); assert_eq!(public.details, Vec::::new()); @@ -202,7 +202,7 @@ mod tests { assert_eq!( json, - "{\"details\":[\"Some juicy details\",\"Some more\"],\"errorCode\":\"CoreFatal\",\"errorKind\":\"SevSnp\",\"message\":\"A fatal error occured in the lit core system\",\"status\":500}" + "{\"details\":[\"Some juicy details\",\"Some more\"],\"errorCode\":\"CoreFatal\",\"errorKind\":\"SevSnp\",\"message\":\"A fatal error occurred in the lit core system\",\"status\":500}" ); } @@ -241,7 +241,7 @@ mod tests { assert_eq!( format!("{:?}", new_err), - "upstream::Error { kind: SevSnp, code: CoreFatal, source: \"lit_core::PublicError { error_kind: SevSnp, error_code: \\\"CoreFatal\\\", message: \\\"A fatal error occured in the lit core system\\\", details: [\\\"Some juicy details\\\", \\\"Some more\\\"] }\" }" + "upstream::Error { kind: SevSnp, code: CoreFatal, source: \"lit_core::PublicError { error_kind: SevSnp, error_code: \\\"CoreFatal\\\", message: \\\"A fatal error occurred in the lit core system\\\", details: [\\\"Some juicy details\\\", \\\"Some more\\\"] }\" }" ); } } diff --git a/rust/lit-core/lit-fast-ecdsa/Cargo.toml b/rust/lit-core/lit-fast-ecdsa/Cargo.toml index 71dfdba..7dbe6d7 100644 --- a/rust/lit-core/lit-fast-ecdsa/Cargo.toml +++ b/rust/lit-core/lit-fast-ecdsa/Cargo.toml @@ -7,31 +7,27 @@ version = "0.2.0" [features] default = ["presign"] -presign = ["vsss-rs/std", "lit-poly"] +presign = ["lit-poly"] [dependencies] digest = "0.10" ecdsa = { version = "0.16", features = ["arithmetic", "digest", "hazmat"] } -elliptic-curve.workspace = true elliptic-curve-tools.workspace = true hex.workspace = true lit-poly = { git = "https://github.com/LIT-Protocol/lit-poly.git", optional = true } -hd-keys-curves-wasm = { git = "https://github.com/LIT-Protocol/hd-keys-curves-wasm.git", rev = "5e0dcc1a6d8d08f2328d4716dca806db87f93748", default-features = false, features = ["k256", "p256", "p384"] } +hd-keys-curves-wasm = { workspace = true, features = ["k256", "p256", "p384"] } +lit-rust-crypto = { workspace = true, features = ["k256", "p256", "p384", "serde", "vsss-rs"] } rand.workspace = true serde.workspace = true sha2.workspace = true subtle = "2.6" thiserror.workspace = true -vsss-rs.workspace = true zeroize.workspace = true [dev-dependencies] -criterion = "0.5" -k256.workspace = true -p256.workspace = true -p384.workspace = true +criterion = "0.7" rand_chacha.workspace = true -rstest = "0.24" +rstest = "0.26" serde_json.workspace = true [[bench]] diff --git a/rust/lit-core/lit-fast-ecdsa/benches/k256.rs b/rust/lit-core/lit-fast-ecdsa/benches/k256.rs index c9cd630..04a1c28 100644 --- a/rust/lit-core/lit-fast-ecdsa/benches/k256.rs +++ b/rust/lit-core/lit-fast-ecdsa/benches/k256.rs @@ -9,6 +9,7 @@ use lit_fast_ecdsa::{ SignatureShare, }; use lit_poly::DensePrimeField; +use lit_rust_crypto::k256; use rand::SeedableRng; use rand::seq::SliceRandom; use std::collections::BTreeSet; diff --git a/rust/lit-core/lit-fast-ecdsa/benches/p256.rs b/rust/lit-core/lit-fast-ecdsa/benches/p256.rs index c62b5ac..1d9de77 100644 --- a/rust/lit-core/lit-fast-ecdsa/benches/p256.rs +++ b/rust/lit-core/lit-fast-ecdsa/benches/p256.rs @@ -9,6 +9,7 @@ use lit_fast_ecdsa::{ SignatureShare, }; use lit_poly::DensePrimeField; +use lit_rust_crypto::p256; use rand::SeedableRng; use rand::seq::SliceRandom; use std::collections::BTreeSet; diff --git a/rust/lit-core/lit-fast-ecdsa/src/error.rs b/rust/lit-core/lit-fast-ecdsa/src/error.rs index da5c262..1fc3d37 100644 --- a/rust/lit-core/lit-fast-ecdsa/src/error.rs +++ b/rust/lit-core/lit-fast-ecdsa/src/error.rs @@ -1,3 +1,4 @@ +use lit_rust_crypto::vsss_rs; use thiserror::Error; /// Error type for this crate diff --git a/rust/lit-core/lit-fast-ecdsa/src/presign.rs b/rust/lit-core/lit-fast-ecdsa/src/presign.rs index 785abc2..9b95515 100644 --- a/rust/lit-core/lit-fast-ecdsa/src/presign.rs +++ b/rust/lit-core/lit-fast-ecdsa/src/presign.rs @@ -18,14 +18,14 @@ use ecdsa::{ elliptic_curve::{CurveArithmetic, Field, Group, group::GroupEncoding}, }; use hd_keys_curves_wasm::{HDDerivable, HDDeriver}; +use lit_rust_crypto::vsss_rs::{ + DefaultShare, IdentifierPrimeField, ShareVerifierGroup, ValuePrimeField, VecFeldmanVerifierSet, +}; use std::{ fmt::{self, Debug, Formatter}, ops::Add, }; use subtle::ConstantTimeEq; -use vsss_rs::{ - DefaultShare, IdentifierPrimeField, ShareVerifierGroup, ValuePrimeField, VecFeldmanVerifierSet, -}; use zeroize::ZeroizeOnDrop; use crate::utils::{calc_min_threshold, lagrange}; diff --git a/rust/lit-core/lit-fast-ecdsa/src/presign/data.rs b/rust/lit-core/lit-fast-ecdsa/src/presign/data.rs index b7fe5a8..9c303b5 100644 --- a/rust/lit-core/lit-fast-ecdsa/src/presign/data.rs +++ b/rust/lit-core/lit-fast-ecdsa/src/presign/data.rs @@ -416,6 +416,8 @@ mod tests { #[test] fn serde_tests() { + use lit_rust_crypto::k256; + let round_data = RoundPayload::Round1(Round1Payload { ordinal: 1, id: k256::Scalar::from(2u64), diff --git a/rust/lit-core/lit-fast-ecdsa/src/presign/round1.rs b/rust/lit-core/lit-fast-ecdsa/src/presign/round1.rs index 680dc5c..c1c1607 100644 --- a/rust/lit-core/lit-fast-ecdsa/src/presign/round1.rs +++ b/rust/lit-core/lit-fast-ecdsa/src/presign/round1.rs @@ -7,7 +7,7 @@ use ecdsa::{ }, }; use hd_keys_curves_wasm::HDDerivable; -use vsss_rs::{FeldmanVerifierSet, ParticipantIdGeneratorType, feldman}; +use lit_rust_crypto::vsss_rs::{FeldmanVerifierSet, ParticipantIdGeneratorType, feldman}; use super::*; use crate::*; diff --git a/rust/lit-core/lit-fast-ecdsa/src/tests/full.rs b/rust/lit-core/lit-fast-ecdsa/src/tests/full.rs index 40eaa2b..dd2903a 100644 --- a/rust/lit-core/lit-fast-ecdsa/src/tests/full.rs +++ b/rust/lit-core/lit-fast-ecdsa/src/tests/full.rs @@ -13,6 +13,7 @@ use ecdsa::{ }; use hd_keys_curves_wasm::{HDDerivable, HDDeriver}; use lit_poly::DensePrimeField; +use lit_rust_crypto::{k256, p256, p384}; use rand::seq::SliceRandom; use rstest::*; use std::{collections::HashMap, ops::Add, time::Instant}; diff --git a/rust/lit-core/lit-fast-ecdsa/src/tests/sign.rs b/rust/lit-core/lit-fast-ecdsa/src/tests/sign.rs index 2c0b3c3..14e7e04 100644 --- a/rust/lit-core/lit-fast-ecdsa/src/tests/sign.rs +++ b/rust/lit-core/lit-fast-ecdsa/src/tests/sign.rs @@ -4,8 +4,8 @@ use crate::{ }; use ecdsa::elliptic_curve::{NonZeroScalar, rand_core::SeedableRng}; use ecdsa::signature::Verifier; -use hd_keys_curves_wasm::k256; use lit_poly::DensePrimeField; +use lit_rust_crypto::k256; #[test] fn lowest_threshold_trusted_dealer() { diff --git a/rust/lit-core/lit-fast-ecdsa/src/utils.rs b/rust/lit-core/lit-fast-ecdsa/src/utils.rs index accbb8a..dc424e0 100644 --- a/rust/lit-core/lit-fast-ecdsa/src/utils.rs +++ b/rust/lit-core/lit-fast-ecdsa/src/utils.rs @@ -118,6 +118,8 @@ impl ParticipantList { #[test] fn test_lagrange() { + use lit_rust_crypto::k256; + let participants: [NonZeroScalar; 3] = [ NonZeroScalar::new(k256::Scalar::ONE).unwrap(), NonZeroScalar::new(k256::Scalar::from(2u32)).unwrap(), diff --git a/rust/lit-core/lit-logging/src/lib.rs b/rust/lit-core/lit-logging/src/lib.rs index 24d5bdf..a049949 100644 --- a/rust/lit-core/lit-logging/src/lib.rs +++ b/rust/lit-core/lit-logging/src/lib.rs @@ -116,7 +116,7 @@ impl fmt::Display for Padded { } } -pub fn colored_level(style: &mut Style, level: Level) -> StyledValue<&'static str> { +pub fn colored_level(style: &mut Style, level: Level) -> StyledValue<'_, &'static str> { match level { Level::Trace => style.set_color(Color::Magenta).value("TRACE"), Level::Debug => style.set_color(Color::Blue).value("DEBUG"), diff --git a/rust/lit-core/lit-observability/src/channels.rs b/rust/lit-core/lit-observability/src/channels.rs index f8a620c..311c0fd 100644 --- a/rust/lit-core/lit-observability/src/channels.rs +++ b/rust/lit-core/lit-observability/src/channels.rs @@ -55,7 +55,7 @@ where /// Send a value to the channel and inject tracing context into the metadata of the message. #[instrument(level = "debug", name = "traced_send_async", skip_all)] - pub fn send_async(&self, data: T) -> SendFut> { + pub fn send_async(&self, data: T) -> SendFut<'_, ChannelMsg> { // Inject tracing context into metadata. let mut metadata = HashMap::new(); let cx = tracing::Span::current().context(); @@ -130,7 +130,9 @@ where /// - recv span /// - consumer span /// - - pub async fn recv_async(&self) -> , tracing::Span)> as Future>::Output { + pub async fn recv_async( + &self, + ) -> , tracing::Span)> as Future>::Output { let recv_span = debug_span!("traced_recv_async"); let mut msg = self.inner.recv_async().instrument(recv_span.clone()).await?; diff --git a/rust/lit-core/lit-recovery/Cargo.toml b/rust/lit-core/lit-recovery/Cargo.toml index 9612806..359e5f3 100644 --- a/rust/lit-core/lit-recovery/Cargo.toml +++ b/rust/lit-core/lit-recovery/Cargo.toml @@ -1,31 +1,24 @@ [package] name = "lit-recovery" -version = "0.2.0" +version = "0.3.0" edition.workspace = true [dependencies] arc-swap = "1.7" argon2 = "0.5" -blsful = "3.0.0" ciborium = { version = "0.2.0" } clap = { version = "4", features = ["derive"] } colored = "3" cryptex = { version = "1.8.2", features = ["file"] } -decaf377.workspace = true dirs = "6" -elliptic-curve.workspace = true ethers.workspace = true glob = "0.3.1" hex.workspace = true -ed448-goldilocks-plus.workspace = true -jubjub.workspace = true -k256.workspace = true lit-node-core = { path = "../../lit-node/lit-node-core" } lit-blockchain = { path = "../lit-blockchain", default-features = false } lit-core = { path = "../lit-core", default-features = false } +lit-rust-crypto = { workspace = true, features = ["default", "blst", "serde"] } path-clean = "1" -p256.workspace = true -p384.workspace = true rand.workspace = true reqwest = { version = "0.11", features = ["json", "blocking"] } rusqlite = { version = "0.32", features = ["bundled-sqlcipher-vendored-openssl"] } @@ -39,13 +32,12 @@ soteria-rs = { version = "0.3.1", features = ["signing"] } thiserror.workspace = true tiny-bip39 = { version = "2.0", default-features = false } tokio.workspace = true -verifiable-share-encryption = { version = "0.3.0", git = "https://github.com/LIT-Protocol/verifiable-share-encryption", rev = "7eddfbe736369db596d0f302c72f1d76b0fd332d" } -vsss-rs = { workspace = true, features = ["curve25519"] } +verifiable-share-encryption = { git = "https://github.com/LIT-Protocol/verifiable-share-encryption", branch = "pallas" } generic-array.workspace = true [dependencies.bulletproofs] -version = "4.0.0" +workspace = true features = [ "std", "ristretto25519", @@ -58,9 +50,8 @@ features = [ "ed448", "jubjub", "decaf377", + "pasta", ] -git = "https://github.com/LIT-Protocol/bulletproofs" -rev = "ddf11c2f593e71f24c9a3d64c56f62d82f2b5099" [target.'cfg(target_os = "windows")'.dependencies] winapi = { version = "0.3", features = ["dpapi", "errhandlingapi", "wincred", "winerror"] } diff --git a/rust/lit-core/lit-recovery/src/auth.rs b/rust/lit-core/lit-recovery/src/auth.rs index 9c98d46..11f2a66 100644 --- a/rust/lit-core/lit-recovery/src/auth.rs +++ b/rust/lit-core/lit-recovery/src/auth.rs @@ -1,5 +1,5 @@ use crate::eth::*; -use bulletproofs::k256::ecdsa::SigningKey; +use lit_rust_crypto::k256::ecdsa::SigningKey; use serde::Serialize; /// Borrowed from https://github.com/LIT-Protocol/lit-assets/blob/develop/rust/lit-node/src/auth/auth_material.rs#L161 diff --git a/rust/lit-core/lit-recovery/src/chain_manager.rs b/rust/lit-core/lit-recovery/src/chain_manager.rs index d6fc909..97d3e95 100644 --- a/rust/lit-core/lit-recovery/src/chain_manager.rs +++ b/rust/lit-core/lit-recovery/src/chain_manager.rs @@ -5,7 +5,6 @@ use crate::{ config::RecoveryConfig, error::{Error, RecoveryResult}, }; -use bulletproofs::k256::{SecretKey, ecdsa::SigningKey}; use ethers::{ prelude::SignerMiddleware, providers::{Http, Provider}, @@ -17,6 +16,7 @@ use lit_blockchain::contracts::{ contract_resolver::ContractResolver, staking::{AddressMapping, Staking, Validator}, }; +use lit_rust_crypto::k256::{FieldBytes, SecretKey, ecdsa::SigningKey}; use reqwest::Url; @@ -47,7 +47,7 @@ impl ChainManager, Wallet>> { return Err(crate::Error::InvalidRequest(e.to_string())); } }; - let bytes = bulletproofs::k256::FieldBytes::from_slice(private_key); + let bytes = FieldBytes::from_slice(private_key); let sk = match SecretKey::from_bytes(bytes) { Ok(key) => key, Err(e) => { @@ -55,7 +55,7 @@ impl ChainManager, Wallet>> { } }; let chain_id = cfg.get_chain_id_or_default(); - let env = cfg.get_env_or_default(); + let env = cfg.get_env_or_default() as u8; println!("using chain id: {}", chain_id); println!("using contract resolver address: {}", resolver_address.clone()); @@ -261,7 +261,7 @@ fn _build_rpc_client(cfg: &RecoveryConfig) -> Result, Error> { }; let provider = Provider::new(Http::new_with_client(url, client)); - Ok(provider as Provider) + Ok(provider) } #[derive(Debug)] diff --git a/rust/lit-core/lit-recovery/src/config.rs b/rust/lit-core/lit-recovery/src/config.rs index be975e7..2c6d34f 100644 --- a/rust/lit-core/lit-recovery/src/config.rs +++ b/rust/lit-core/lit-recovery/src/config.rs @@ -2,12 +2,81 @@ use crate::{ consts::{ CONTRACT_CHRONICLE_CHAIN_ID, CONTRACT_CHRONICLE_RPC_URL, CONTRACT_RESOLVER_ENVIRONMENT, }, - error::RecoveryResult, + error::{Error, RecoveryResult}, }; use serde::{Deserialize, Serialize}; +use std::fmt::{self, Display, Formatter}; use std::io::Write; use std::path::PathBuf; +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Ord, PartialOrd)] +#[repr(u8)] +pub enum ChainEnvironment { + #[default] + Develop = 0, + Staging = 1, + Production = 2, +} + +impl Display for ChainEnvironment { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + write!( + f, + "{}", + match self { + ChainEnvironment::Develop => "develop", + ChainEnvironment::Staging => "staging", + ChainEnvironment::Production => "production", + } + ) + } +} + +impl std::str::FromStr for ChainEnvironment { + type Err = Error; + + fn from_str(s: &str) -> Result { + match s { + "develop" => Ok(ChainEnvironment::Develop), + "staging" => Ok(ChainEnvironment::Staging), + "production" => Ok(ChainEnvironment::Production), + _ => Err(Error::General(format!("invalid chain environment: {}", s))), + } + } +} + +impl TryFrom for ChainEnvironment { + type Error = Error; + + fn try_from(value: u8) -> Result { + match value { + 0 => Ok(ChainEnvironment::Develop), + 1 => Ok(ChainEnvironment::Staging), + 2 => Ok(ChainEnvironment::Production), + _ => Err(Error::General(format!("Invalid chain environment: {}", value))), + } + } +} + +impl serde::Serialize for ChainEnvironment { + fn serialize(&self, s: S) -> Result + where + S: serde::Serializer, + { + s.serialize_u8(*self as u8) + } +} + +impl<'de> serde::Deserialize<'de> for ChainEnvironment { + fn deserialize(d: D) -> Result + where + D: serde::Deserializer<'de>, + { + let c = u8::deserialize(d)?.try_into().map_err(serde::de::Error::custom)?; + Ok(c) + } +} + #[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)] pub struct RecoveryConfig { pub resolver_address: Option, @@ -16,24 +85,22 @@ pub struct RecoveryConfig { // 0 - develop // 1 - staging // 2 - production - pub environment: Option, + pub environment: Option, } impl TryFrom for RecoveryConfig { + type Error = Error; + fn try_from(value: String) -> Result { - let conf = - serde_json::from_str(value.as_str()).map_err(crate::error::Error::InvalidJsonFormat)?; + let conf = serde_json::from_str(value.as_str()).map_err(Error::InvalidJsonFormat)?; Ok(conf) } - - type Error = crate::error::Error; } impl RecoveryConfig { #[allow(dead_code)] fn from_slice(v: &[u8]) -> RecoveryResult { - let conf: RecoveryConfig = - serde_json::from_slice(v).map_err(crate::error::Error::InvalidJsonFormat)?; + let conf: RecoveryConfig = serde_json::from_slice(v).map_err(Error::InvalidJsonFormat)?; Ok(conf) } @@ -51,7 +118,7 @@ impl RecoveryConfig { if config_path.exists() { let conf = std::fs::read(config_path)?; if conf.is_empty() { - Err(crate::error::Error::General("Could not find config file on disk".to_string())) + Err(Error::General("Could not find config file on disk".to_string())) } else { let conf: RecoveryConfig = serde_json::from_slice(&conf)?; Ok(conf) @@ -59,9 +126,9 @@ impl RecoveryConfig { } else { let config = Self { resolver_address: None, - rpc_url: Some(crate::consts::CONTRACT_CHRONICLE_RPC_URL.into()), - chain_id: Some(crate::consts::CONTRACT_CHRONICLE_CHAIN_ID), - environment: Some(2), + rpc_url: Some(CONTRACT_CHRONICLE_RPC_URL.into()), + chain_id: Some(CONTRACT_CHRONICLE_CHAIN_ID), + environment: Some(ChainEnvironment::Production), }; let conf = serde_json::to_vec(&config)?; let mut fd = std::fs::File::create(config_path.clone())?; @@ -84,7 +151,9 @@ impl RecoveryConfig { println!("Failed to create config directory: {}", e); println!( "Current directory: {}", - std::env::current_dir().unwrap().display() + std::env::current_dir() + .expect("to know the current directory") + .display() ); return Err(e.into()); } @@ -111,23 +180,16 @@ impl RecoveryConfig { } pub fn get_rpc_url_or_default(&self) -> String { - match self.rpc_url.clone() { - Some(url) => url, - None => CONTRACT_CHRONICLE_RPC_URL.into(), - } + self.rpc_url.clone().unwrap_or_else(|| CONTRACT_CHRONICLE_RPC_URL.into()) } pub fn get_chain_id_or_default(&self) -> u64 { - match self.chain_id { - Some(id) => id, - None => CONTRACT_CHRONICLE_CHAIN_ID, - } + self.chain_id.unwrap_or_else(|| CONTRACT_CHRONICLE_CHAIN_ID) } - pub fn get_env_or_default(&self) -> u8 { - match self.environment { - Some(env) => env, - None => CONTRACT_RESOLVER_ENVIRONMENT, - } + pub fn get_env_or_default(&self) -> ChainEnvironment { + self.environment.unwrap_or_else(|| { + CONTRACT_RESOLVER_ENVIRONMENT.try_into().expect("invalid environment") + }) } } diff --git a/rust/lit-core/lit-recovery/src/consts.rs b/rust/lit-core/lit-recovery/src/consts.rs index a3313d7..1e1a013 100644 --- a/rust/lit-core/lit-recovery/src/consts.rs +++ b/rust/lit-core/lit-recovery/src/consts.rs @@ -31,6 +31,7 @@ pub const ED448: &str = "Ed448"; pub const JUBJUB: &str = "RedJubjub"; pub const DECAF377: &str = "RedDecaf377"; pub const BLS12381G1_SIGN: &str = "BLS12381G1Sign"; +pub const PALLAS: &str = "RedPallas"; pub const CONFIG_STORAGE: [&str; 2] = [concat!(".", env!("CARGO_PKG_NAME")), "config.json"]; @@ -46,4 +47,5 @@ pub const ED448_ENCRYPTION_KEY_FN: &str = "ed448_encryption_key"; pub const JUBJUB_ENCRYPTION_KEY_FN: &str = "jubjub_encryption_key"; pub const DECAF377_ENCRYPTION_KEY_FN: &str = "decaf377_encryption_key"; pub const BLS12381G1_ENCRYPTION_KEY_FN: &str = "bls12381g1_encryption_key"; +pub const PALLAS_ENCRYPTION_KEY_FN: &str = "pallas_encryption_key"; pub const SESSION_ID_FN: &str = "session_id"; diff --git a/rust/lit-core/lit-recovery/src/decryption.rs b/rust/lit-core/lit-recovery/src/decryption.rs index ffd371e..ef27db9 100644 --- a/rust/lit-core/lit-recovery/src/decryption.rs +++ b/rust/lit-core/lit-recovery/src/decryption.rs @@ -1,3 +1,4 @@ +use crate::config::ChainEnvironment; use crate::io::writer; use crate::{ LitRecovery, RecoveryConfig, @@ -10,8 +11,8 @@ use crate::{ shares::{COLUMN_ENCRYPTION_KEY, ShareData, ShareDatabase}, }; use bulletproofs::BulletproofCurveArithmetic; -use bulletproofs::vsss_rs::{DefaultShare, IdentifierPrimeField}; use ethers::types::H160; +use lit_rust_crypto::vsss_rs::{DefaultShare, IdentifierPrimeField}; use serde::Serialize; use serde::de::DeserializeOwned; use std::collections::HashMap; @@ -366,7 +367,7 @@ fn get_protocol(cfg: &RecoveryConfig) -> &str { // compute the value based on `env`: match cfg.get_env_or_default() { - 0 => "http", + ChainEnvironment::Develop => "http", _ => "https", } } diff --git a/rust/lit-core/lit-recovery/src/download.rs b/rust/lit-core/lit-recovery/src/download.rs index f7dea3d..088db05 100644 --- a/rust/lit-core/lit-recovery/src/download.rs +++ b/rust/lit-core/lit-recovery/src/download.rs @@ -1,13 +1,13 @@ -use bulletproofs::k256::{ - ecdsa::SigningKey, +use ethers::middleware::SignerMiddleware; +use ethers::providers::{Http, Provider}; +use ethers::signers::Wallet; +use lit_rust_crypto::{ elliptic_curve::{ Field, PrimeField, consts::U32, generic_array::GenericArray, group::GroupEncoding, ops::Reduce, point::AffineCoordinates, sec1::ToEncodedPoint, }, + k256::ecdsa::SigningKey, }; -use ethers::middleware::SignerMiddleware; -use ethers::providers::{Http, Provider}; -use ethers::signers::Wallet; use sha2::Digest; use std::io::Write; use std::time::{SystemTime, UNIX_EPOCH}; @@ -118,7 +118,7 @@ struct ContractProofK256 { impl ContractProofK256 { #[allow(dead_code)] pub fn generate(share: &[u8], participant_id: u8) -> RecoveryResult { - use bulletproofs::k256::*; + use lit_rust_crypto::k256::*; let mut repr = FieldBytes::default(); repr.copy_from_slice(share); @@ -200,7 +200,7 @@ struct ContractProofBls12381G1 { impl ContractProofBls12381G1 { #[allow(dead_code)] pub fn generate(share: &[u8], participant_id: u8) -> RecoveryResult { - use bulletproofs::blstrs_plus::*; + use lit_rust_crypto::blstrs_plus::*; let share_bytes = <[u8; 32]>::try_from(share).unwrap(); let share = Option::::from(Scalar::from_be_bytes(&share_bytes)) @@ -646,7 +646,7 @@ mod tests { #[ignore] #[test] fn test_contract_proof_k256() { - use bulletproofs::k256::*; + use lit_rust_crypto::k256::*; let share = Scalar::random(rand::rngs::OsRng); let res = ContractProofK256::generate(&share.to_bytes(), 1); @@ -666,7 +666,7 @@ mod tests { #[ignore] #[test] fn test_contract_proof_bls() { - use bulletproofs::blstrs_plus::*; + use lit_rust_crypto::blstrs_plus::*; let share = Scalar::random(rand::rngs::OsRng); let res = ContractProofBls12381G1::generate(&share.to_be_bytes(), 1); diff --git a/rust/lit-core/lit-recovery/src/eth.rs b/rust/lit-core/lit-recovery/src/eth.rs index eb52f09..5016a7e 100644 --- a/rust/lit-core/lit-recovery/src/eth.rs +++ b/rust/lit-core/lit-recovery/src/eth.rs @@ -1,4 +1,4 @@ -use bulletproofs::k256::ecdsa::{RecoveryId, Signature, SigningKey, VerifyingKey}; +use lit_rust_crypto::k256::ecdsa::{RecoveryId, Signature, SigningKey, VerifyingKey}; use sha3::{Keccak256, digest::Digest}; pub trait EthereumAddress { diff --git a/rust/lit-core/lit-recovery/src/lib.rs b/rust/lit-core/lit-recovery/src/lib.rs index 23d548c..c72ef18 100644 --- a/rust/lit-core/lit-recovery/src/lib.rs +++ b/rust/lit-core/lit-recovery/src/lib.rs @@ -1,10 +1,10 @@ use crate::args::Commands; use crate::chain_manager::ChainManager; -use crate::config::RecoveryConfig; +use crate::config::{ChainEnvironment, RecoveryConfig}; use crate::consts::{ ADMIN_CONTRACT_EMAIL, BLS12381G1, BLS12381G1_SIGN, DECAF377, ED448, ED25519, JUBJUB, KEYRING_DB_KEY_NAME, KEYRING_KEY_NAME, LIT_BACKUP_NAME_PATTERN, LIT_BACKUP_SUFFIX, - LIT_NODE_DELETE_SHARE_ENDPOINT, LIT_NODE_DOWNLOAD_SHARE_ENDPOINT, NISTP256, NISTP384, + LIT_NODE_DELETE_SHARE_ENDPOINT, LIT_NODE_DOWNLOAD_SHARE_ENDPOINT, NISTP256, NISTP384, PALLAS, RISTRETTO25519, SECP256K1, }; use crate::decryption::{ @@ -20,18 +20,22 @@ use crate::shares::{ }; use arc_swap::ArcSwap; use bip39::Mnemonic; -use blsful::inner_types::{Group, PrimeCurveAffine}; -use bulletproofs::bls12_381_plus::elliptic_curve::bigint::U512; -use bulletproofs::bls12_381_plus::elliptic_curve::ops::Reduce; -use bulletproofs::blstrs_plus::Bls12381G1; -use bulletproofs::{Decaf377, Ed25519, JubJub, Ristretto25519, jubjub}; +use bulletproofs::{Decaf377, Ed25519, JubJub, Ristretto25519}; use colored::Colorize; use cryptex::DynKeyRing; -use ed448_goldilocks_plus::Ed448; use hex::FromHex; -use k256::Secp256k1; -use k256::ecdsa::VerifyingKey; use lit_blockchain::contracts::backup_recovery::NextStateDownloadable; +use lit_rust_crypto::{ + blsful::inner_types::{G1Projective, Group, PrimeCurveAffine}, + blstrs_plus::Bls12381G1, + decaf377, + ed448_goldilocks::{self, Ed448}, + elliptic_curve::{bigint::U512, ops::Reduce}, + group::{GroupEncoding, cofactor::CofactorGroup}, + jubjub, + k256::{self, Secp256k1, ecdsa::VerifyingKey}, + p256, p384, pallas, vsss_rs, +}; use rand::{Rng, RngCore, rngs::OsRng}; use serde::de::DeserializeOwned; use std::collections::{BTreeMap, HashMap}; @@ -39,7 +43,6 @@ use std::path::PathBuf; use std::sync::Arc; use tokio::io::AsyncReadExt; use tokio::sync::Mutex; -use vsss_rs::elliptic_curve::group::GroupEncoding; pub mod args; pub mod auth; @@ -107,7 +110,7 @@ impl Default for LitRecovery { resolver_address: None, rpc_url: Some(consts::CONTRACT_CHRONICLE_RPC_URL.into()), chain_id: Some(consts::CONTRACT_CHRONICLE_CHAIN_ID), - environment: Some(2), // production is 2 + environment: Some(ChainEnvironment::Production), })), config_path: None, keyring_file: None, @@ -287,6 +290,7 @@ impl LitRecovery { (JUBJUB.to_string(), 8), (DECAF377.to_string(), 9), (BLS12381G1_SIGN.to_string(), 10), + (PALLAS.to_string(), 11), ] .into_iter() .collect::>(); @@ -543,12 +547,18 @@ impl LitRecovery { ) .await? } + PALLAS => { + generate_and_send_decryption_shares_to_nodes::( + self, ciphertext_file, encryption_key, + ) + .await? + } _ => { println!( "Key type not supported! Please use either [{}]", [ BLS12381G1, SECP256K1, NISTP256, NISTP384, ED25519, RISTRETTO25519, - ED448, JUBJUB, DECAF377 + ED448, JUBJUB, DECAF377, PALLAS, ] .join(", ") ); @@ -577,7 +587,7 @@ impl LitRecovery { resolver_address: Some(address.clone()), chain_id: Some(chain_id), rpc_url: Some(rpc_url.clone()), - environment: Some(env), + environment: Some(env.try_into().expect("a valid environment value")), ..config.as_ref().clone() }); @@ -658,12 +668,18 @@ impl LitRecovery { ) .await?; } + PALLAS => { + write_local_decrypt_share::( + self, ciphertext_file, encryption_key, share_file, output_share_file, + ) + .await?; + } _ => { println!( "Key type not supported! Please use either [{}]", [ BLS12381G1, SECP256K1, NISTP256, NISTP384, ED25519, RISTRETTO25519, - ED448, JUBJUB, DECAF377, BLS12381G1_SIGN, + ED448, JUBJUB, DECAF377, BLS12381G1_SIGN, PALLAS, ] .join(", ") ); @@ -720,7 +736,6 @@ impl LitRecovery { )?; } JUBJUB => { - use elliptic_curve::group::cofactor::CofactorGroup; // Jubjub uses a special generator for signing. Use this here pub const SPENDAUTHSIG_BASEPOINT_BYTES: [u8; 32] = [ 48, 181, 242, 170, 173, 50, 86, 48, 188, 221, 219, 206, 77, 103, 101, 109, @@ -748,12 +763,32 @@ impl LitRecovery { ciphertext_file, blinder, decrypted_share_files, output_file, None, )?; } + PALLAS => { + // Pallas uses a special generator for signing. Use this here + const SPENDAUTHSIG_BASEPOINT_BYTES: [u8; 32] = [ + 99, 201, 117, 184, 132, 114, 26, 141, 12, 161, 112, 123, 227, 12, 127, 12, + 95, 68, 95, 62, 124, 24, 141, 59, 6, 214, 241, 40, 179, 35, 85, 183, + ]; + let pt: pallas::Point = + pallas::Affine::from_bytes(&SPENDAUTHSIG_BASEPOINT_BYTES.into()) + .unwrap() + .into(); + + let blinder = read_blinder::(blinder, "pallas_blinder")?; + merge_decryption_shares::( + ciphertext_file, + blinder, + decrypted_share_files, + output_file, + Some(pt), + )?; + } _ => { println!( "Key type not supported! Please use either [{}]", [ BLS12381G1, SECP256K1, NISTP256, NISTP384, ED25519, RISTRETTO25519, - ED448, JUBJUB, DECAF377, BLS12381G1_SIGN, + ED448, JUBJUB, DECAF377, BLS12381G1_SIGN, PALLAS, ] .join(", ") ); @@ -847,16 +882,17 @@ impl LitRecovery { path.to_str().ok_or(Error::General("Failed to stringify path".into()))?; // Extract the tar files. - let mut bls_enc_key = blsful::inner_types::G1Projective::default(); + let mut bls_enc_key = G1Projective::default(); let mut secp256k1_enc_key = k256::AffinePoint::default(); let mut nistp256_enc_key = p256::AffinePoint::default(); let mut nistp384_enc_key = p384::AffinePoint::default(); let mut ed25519_enc_key = vsss_rs::curve25519::WrappedEdwards::default(); let mut ristretto25519_enc_key = vsss_rs::curve25519::WrappedRistretto::default(); - let mut ed448_enc_key = ed448_goldilocks_plus::EdwardsPoint::default(); + let mut ed448_enc_key = ed448_goldilocks::EdwardsPoint::default(); let mut jubjub_enc_key = jubjub::SubgroupPoint::IDENTITY; let mut decaf377_enc_key = decaf377::Element::IDENTITY; - let mut bls12381g1_sign_enc_key = blsful::inner_types::G1Projective::default(); + let mut bls12381g1_sign_enc_key = G1Projective::default(); + let mut pallas_enc_key = pallas::Point::default(); // extract each tar file, and check the public keys and session id // to ensure they match @@ -895,7 +931,7 @@ impl LitRecovery { bls_enc_key = read_from_disk(destination.clone(), consts::BLS_ENCRYPTION_KEY_FN).await?; } else { - let tmp_bls_enc_key: blsful::inner_types::G1Projective = + let tmp_bls_enc_key: G1Projective = read_from_disk(destination.clone(), consts::BLS_ENCRYPTION_KEY_FN).await?; if tmp_bls_enc_key != bls_enc_key { return Err(Error::General(format!( @@ -987,7 +1023,7 @@ impl LitRecovery { ed448_enc_key = read_from_disk(destination.clone(), consts::ED448_ENCRYPTION_KEY_FN).await?; } else { - let tmp_ed448_enc_key: ed448_goldilocks_plus::EdwardsPoint = + let tmp_ed448_enc_key: ed448_goldilocks::EdwardsPoint = read_from_disk(destination.clone(), consts::ED448_ENCRYPTION_KEY_FN).await?; if tmp_ed448_enc_key != ed448_enc_key { return Err(Error::General(format!( @@ -1033,7 +1069,7 @@ impl LitRecovery { read_from_disk(destination.clone(), consts::BLS12381G1_ENCRYPTION_KEY_FN) .await?; } else { - let tmp_bls12381g1_sign_enc_key: blsful::inner_types::G1Projective = + let tmp_bls12381g1_sign_enc_key: G1Projective = read_from_disk(destination.clone(), consts::BLS12381G1_ENCRYPTION_KEY_FN) .await?; if tmp_bls12381g1_sign_enc_key != bls12381g1_sign_enc_key { @@ -1045,6 +1081,21 @@ impl LitRecovery { ))); } } + if pallas_enc_key.is_identity().into() { + pallas_enc_key = + read_from_disk(destination.clone(), consts::PALLAS_ENCRYPTION_KEY_FN).await?; + } else { + let tmp_pallas_enc_key: pallas::Point = + read_from_disk(destination.clone(), consts::PALLAS_ENCRYPTION_KEY_FN).await?; + if tmp_pallas_enc_key != pallas_enc_key { + return Err(Error::General(format!( + "Pallas Encryption Key doesn't match the tar file {}. Expected '{}', Found in tar file '{}'", + file.display(), + hex::encode(tmp_pallas_enc_key.to_bytes()), + hex::encode(pallas_enc_key.to_bytes()), + ))); + } + } } // For each encrypted share in each encrypted folder, send decryption shares to the @@ -1060,6 +1111,7 @@ impl LitRecovery { println!("Total encrypted JubJub shares: {}", shares.jubjub.len()); println!("Total encrypted Decaf377 shares: {}", shares.decaf377.len()); println!("Total encrypted BLS12381G1_SIGN shares: {}", shares.bls12381g1_sign.len()); + println!("Total encrypted Pallas shares: {}", shares.pallas.len()); let mut upload_shares_by_staker_address = HashMap::new(); load_upload_shares::( @@ -1132,6 +1184,13 @@ impl LitRecovery { &mut upload_shares_by_staker_address, ) .await?; + load_upload_shares::( + self, + hex::encode(pallas_enc_key.to_bytes()), + &shares.pallas, + &mut upload_shares_by_staker_address, + ) + .await?; decryption::send_decryption_shares_to_nodes(self, &upload_shares_by_staker_address).await?; Ok(()) @@ -1149,6 +1208,7 @@ struct EncryptedKeyShares { jubjub: Vec, decaf377: Vec, bls12381g1_sign: Vec, + pallas: Vec, } fn fetch_tar_file_names(directory: PathBuf) -> RecoveryResult> { @@ -1167,6 +1227,7 @@ fn fetch_encrypted_key_share_paths(path: PathBuf) -> RecoveryResult RecoveryResult RecoveryResult bool { + (!pt.is_torsion_free() | pt.is_identity() | pt.is_small_order()).into() + } +} + +impl HashToCurve for Pallas { + fn hash_to_curve(msg: &Scalar) -> Point { + const DST: &str = "ECVRF-PALLAS-BLAKE2B512-SSWU_RO_\x0B"; + let bytes = msg.to_le_bytes(); + let hasher = Point::hash_to_curve(DST); + hasher(&bytes) + } +} + +impl NonceGeneration for Pallas { + fn generate_nonce(sk: &Scalar, alpha: &Scalar) -> Scalar { + let mut hasher = Blake2b512::default(); + hasher.update(&sk.to_le_bytes()); + let output = hasher.finalize_reset(); + hasher.update(&output[32..]); + hasher.update(&alpha.to_le_bytes()); + let bytes = hasher.finalize(); + Scalar::from_bytes_wide(&(bytes.into())) + } +} + +impl ChallengeGeneration for Pallas { + fn generate_challenge(points: &[Point]) -> Scalar { + const DST: &[u8] = b"ECVRF-PALLAS-BLAKE2B512-RO_CHALLENGE_GENERATION_"; + let mut hasher = Blake2b512::default(); + hasher.update(DST); + // Suite string + hasher.update([PALLAS_SUITE_STRING]); + // challenge_generation_domain_separator_front + hasher.update([0x02]); + + for point in points { + hasher.update(point.to_bytes()); + } + // challenge_generation_domain_separator_back + hasher.update([0x00]); + + let bytes = hasher.finalize(); + let ref_bytes = <&[u8; 64]>::try_from(bytes.as_slice()).unwrap(); + Scalar::from_bytes_wide(ref_bytes) + } +} + +impl ProofToHash for Pallas { + fn proof_to_hash(gamma: Point) -> Scalar { + const DST: &[u8] = b"ECVRF-PALLAS-BLAKE2B512-RO_PROOF_TO_HASH_"; + let mut hasher = Blake2b512::default(); + hasher.update(DST); + // Suite string + hasher.update([PALLAS_SUITE_STRING]); + // proof_to_hash_domain_separator_front + hasher.update([0x03]); + hasher.update(gamma.to_bytes()); + // proof_to_hash_domain_separator_back + hasher.update([0x00]); + + let bytes = hasher.finalize(); + let ref_bytes = <&[u8; 64]>::try_from(bytes.as_slice()).unwrap(); + Scalar::from_bytes_wide(ref_bytes) + } +} + +impl Coordinate for Pallas { + fn point_to_scalar(pt: Point) -> Scalar { + let mut bytes = [0u8; 64]; + bytes[..32].copy_from_slice(pt.to_bytes().as_ref()); + Scalar::from_bytes_wide(&bytes) + } +} + +impl VrfProver for Pallas {} +impl VrfVerifier for Pallas {} + +#[cfg(test)] +mod tests { + use super::*; + use lit_rust_crypto::ff::Field; + use rand::SeedableRng; + + #[test] + fn pallas_vrf() { + let mut rng = rand_chacha::ChaCha8Rng::from_seed([1u8; 32]); + + let sk = Scalar::random(&mut rng); + let message = Scalar::random(&mut rng); + let pk = Point::generator() * sk; + + let res = Pallas::vrf_prove(&sk, &message, None); + assert!(res.is_ok()); + let proof = res.unwrap(); + let res = Pallas::vrf_verify(pk, message, &proof, None); + assert!(res.is_ok()); + } + + #[test] + fn pallas_serde() { + let mut rng = rand_chacha::ChaCha8Rng::from_seed([1u8; 32]); + let sk = Scalar::random(&mut rng); + let message = Scalar::random(&mut rng); + + let proof = Pallas::vrf_prove(&sk, &message, None).unwrap(); + let proof_bytes = serde_bare::to_vec(&proof).expect("failed to serialize proof"); + let proof2: Proof = + serde_bare::from_slice(&proof_bytes).expect("failed to deserialize proof"); + assert_eq!(proof, proof2); + + let proof_json = serde_json::to_string(&proof).expect("failed to serialize proof"); + let proof2: Proof = + serde_json::from_str(&proof_json).expect("failed to deserialize proof"); + assert_eq!(proof, proof2); + } +} diff --git a/rust/lit-core/lit-vrf/src/impl/secp256k1.rs b/rust/lit-core/lit-vrf/src/impl/secp256k1.rs index be45639..60af52b 100644 --- a/rust/lit-core/lit-vrf/src/impl/secp256k1.rs +++ b/rust/lit-core/lit-vrf/src/impl/secp256k1.rs @@ -1,13 +1,10 @@ -use bulletproofs::group::Group; -use elliptic_curve::{ - PrimeField, - bigint::U256, - group::GroupEncoding, +use lit_rust_crypto::{ + elliptic_curve::{bigint::U256, ops::Reduce, point::AffineCoordinates}, + ff::PrimeField, + group::{Group, GroupEncoding}, hash2curve::{ExpandMsgXmd, GroupDigest}, - ops::Reduce, - point::AffineCoordinates, + k256::{ProjectivePoint, Scalar, Secp256k1}, }; -use k256::{ProjectivePoint, Scalar, Secp256k1}; use rfc6979::consts::U32; use crate::*; @@ -98,7 +95,7 @@ impl VrfVerifier for Secp256k1 {} #[cfg(test)] mod tests { use super::*; - use elliptic_curve::Field; + use lit_rust_crypto::ff::Field; use rand::SeedableRng; #[test] diff --git a/rust/lit-core/lit-vrf/src/models.rs b/rust/lit-core/lit-vrf/src/models.rs index b7b4cb8..593e89f 100644 --- a/rust/lit-core/lit-vrf/src/models.rs +++ b/rust/lit-core/lit-vrf/src/models.rs @@ -1,6 +1,8 @@ use crate::*; -use elliptic_curve::{Field, Group, PrimeField, group::GroupEncoding, subtle::Choice}; use elliptic_curve_tools::{group, prime_field, prime_field_vec}; +use lit_rust_crypto::elliptic_curve::{ + Field, Group, PrimeField, group::GroupEncoding, subtle::Choice, +}; use serde::{Deserialize, Serialize}; use std::{ collections::{BTreeSet, HashMap}, @@ -448,6 +450,7 @@ where mod tests { use super::*; use k256::{ProjectivePoint, Scalar, Secp256k1}; + use lit_rust_crypto::{k256, vsss_rs}; use rand::SeedableRng; use rand_chacha::ChaCha8Rng; use vsss_rs::{DefaultShare, IdentifierPrimeField, ValuePrimeField, shamir}; diff --git a/rust/lit-core/lit-vrf/src/traits/challenge_generation.rs b/rust/lit-core/lit-vrf/src/traits/challenge_generation.rs index 2c70094..4596a35 100644 --- a/rust/lit-core/lit-vrf/src/traits/challenge_generation.rs +++ b/rust/lit-core/lit-vrf/src/traits/challenge_generation.rs @@ -1,4 +1,4 @@ -use elliptic_curve::Group; +use lit_rust_crypto::group::Group; use crate::Handler; diff --git a/rust/lit-core/lit-vrf/src/traits/coordinate.rs b/rust/lit-core/lit-vrf/src/traits/coordinate.rs index ac8e21d..689d1f8 100644 --- a/rust/lit-core/lit-vrf/src/traits/coordinate.rs +++ b/rust/lit-core/lit-vrf/src/traits/coordinate.rs @@ -1,5 +1,5 @@ use crate::Handler; -use elliptic_curve::Group; +use lit_rust_crypto::group::Group; /// Trait for extracting the x coordinate of a point on the curve. pub trait Coordinate: Handler { diff --git a/rust/lit-core/lit-vrf/src/traits/handler.rs b/rust/lit-core/lit-vrf/src/traits/handler.rs index 2a25b4a..60876e5 100644 --- a/rust/lit-core/lit-vrf/src/traits/handler.rs +++ b/rust/lit-core/lit-vrf/src/traits/handler.rs @@ -1,4 +1,4 @@ -use elliptic_curve::{Group, group::GroupEncoding}; +use lit_rust_crypto::group::{Group, GroupEncoding}; /// Root trait to eliminate duplication in the other traits pub trait Handler { diff --git a/rust/lit-core/lit-vrf/src/traits/hash.rs b/rust/lit-core/lit-vrf/src/traits/hash.rs index 5a8de0c..886fee2 100644 --- a/rust/lit-core/lit-vrf/src/traits/hash.rs +++ b/rust/lit-core/lit-vrf/src/traits/hash.rs @@ -1,4 +1,4 @@ -use elliptic_curve::Group; +use lit_rust_crypto::group::Group; use crate::Handler; diff --git a/rust/lit-core/lit-vrf/src/traits/hash_to_curve.rs b/rust/lit-core/lit-vrf/src/traits/hash_to_curve.rs index e0d59a2..7aeacee 100644 --- a/rust/lit-core/lit-vrf/src/traits/hash_to_curve.rs +++ b/rust/lit-core/lit-vrf/src/traits/hash_to_curve.rs @@ -1,4 +1,4 @@ -use elliptic_curve::Group; +use lit_rust_crypto::group::Group; use crate::Handler; diff --git a/rust/lit-core/lit-vrf/src/traits/nonce_generation.rs b/rust/lit-core/lit-vrf/src/traits/nonce_generation.rs index c4eab5b..11ac9da 100644 --- a/rust/lit-core/lit-vrf/src/traits/nonce_generation.rs +++ b/rust/lit-core/lit-vrf/src/traits/nonce_generation.rs @@ -1,4 +1,4 @@ -use elliptic_curve::Group; +use lit_rust_crypto::group::Group; use crate::Handler; diff --git a/rust/lit-core/lit-vrf/src/traits/prover.rs b/rust/lit-core/lit-vrf/src/traits/prover.rs index d7a5a06..eda32cb 100644 --- a/rust/lit-core/lit-vrf/src/traits/prover.rs +++ b/rust/lit-core/lit-vrf/src/traits/prover.rs @@ -1,4 +1,4 @@ -use elliptic_curve::{Field, Group}; +use lit_rust_crypto::{ff::Field, group::Group}; use crate::{ ChallengeGeneration, Coordinate, HashToCurve, NonceGeneration, Proof, ProofToHash, VrfError, @@ -63,6 +63,7 @@ mod tests { use crate::VrfVerifier; use crate::utils::lagrange; use k256::{ProjectivePoint, Scalar, Secp256k1}; + use lit_rust_crypto::{k256, vsss_rs}; use rand::SeedableRng; use vsss_rs::{DefaultShare, IdentifierPrimeField, ValuePrimeField, shamir}; type SecretShare = DefaultShare, ValuePrimeField>; diff --git a/rust/lit-core/lit-vrf/src/traits/verifier.rs b/rust/lit-core/lit-vrf/src/traits/verifier.rs index a0cd83a..7e12508 100644 --- a/rust/lit-core/lit-vrf/src/traits/verifier.rs +++ b/rust/lit-core/lit-vrf/src/traits/verifier.rs @@ -1,4 +1,4 @@ -use elliptic_curve::{Field, Group, subtle::ConstantTimeEq}; +use lit_rust_crypto::elliptic_curve::{Field, Group, subtle::ConstantTimeEq}; use crate::{ ChallengeGeneration, Coordinate, HashToCurve, Proof, ProofToHash, VrfError, VrfResult, diff --git a/rust/lit-core/lit-vrf/src/utils.rs b/rust/lit-core/lit-vrf/src/utils.rs index 44d9ed1..5e15301 100644 --- a/rust/lit-core/lit-vrf/src/utils.rs +++ b/rust/lit-core/lit-vrf/src/utils.rs @@ -1,4 +1,4 @@ -use elliptic_curve::PrimeField; +use lit_rust_crypto::ff::PrimeField; pub fn lagrange(xi: F, participants: &[F]) -> F { let mut num = F::ONE; diff --git a/rust/lit-core/rust-toolchain.toml b/rust/lit-core/rust-toolchain.toml index c8969b5..657737a 100644 --- a/rust/lit-core/rust-toolchain.toml +++ b/rust/lit-core/rust-toolchain.toml @@ -1,3 +1,3 @@ [toolchain] -channel = "1.86" +channel = "1.91" components = ['rustfmt', 'rust-src', 'clippy'] diff --git a/rust/lit-node/Cargo.lock b/rust/lit-node/Cargo.lock index e021b0a..d02474f 100644 --- a/rust/lit-node/Cargo.lock +++ b/rust/lit-node/Cargo.lock @@ -577,7 +577,7 @@ dependencies = [ "alloy-rlp", "alloy-serde", "alloy-sol-types", - "itertools 0.14.0", + "itertools 0.13.0", "serde", "serde_json", "thiserror 2.0.16", @@ -2495,25 +2495,15 @@ dependencies = [ [[package]] name = "bulletproofs" version = "4.0.0" -source = "git+https://github.com/LIT-Protocol/bulletproofs?rev=ddf11c2f593e71f24c9a3d64c56f62d82f2b5099#ddf11c2f593e71f24c9a3d64c56f62d82f2b5099" +source = "git+https://github.com/LIT-Protocol/bulletproofs?branch=pallas#2ee66a6e2770c73514942936950c0ca2dbbcd023" dependencies = [ "blake2", - "bls12_381_plus", - "blstrs_plus", "byteorder", - "curve25519-dalek-ml", "data-encoding", - "decaf377 0.10.1 (git+https://github.com/LIT-Protocol/decaf377?rev=1c5755b2b90e1969d47ce89cf2d35078984a0ee5)", "digest 0.10.7", - "ed448-goldilocks-plus", - "elliptic-curve 0.13.8", "elliptic-curve-tools", - "group 0.13.0", - "jubjub-plus", - "k256 0.13.4", + "lit-rust-crypto", "merlin", - "p256", - "p384 0.13.1", "rand 0.8.5", "rand_core 0.6.4", "serde", @@ -2521,7 +2511,6 @@ dependencies = [ "sha3 0.10.8", "subtle", "thiserror 2.0.16", - "vsss-rs 5.1.0", "zeroize", ] @@ -4049,7 +4038,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8d162beedaa69905488a8da94f5ac3edb4dd4788b732fadb7bd120b2625c1976" dependencies = [ "data-encoding", - "syn 2.0.106", + "syn 1.0.109", ] [[package]] @@ -4121,35 +4110,28 @@ dependencies = [ ] [[package]] -name = "decaf377" -version = "0.10.1" -source = "git+https://github.com/LIT-Protocol/decaf377?rev=1c5755b2b90e1969d47ce89cf2d35078984a0ee5#1c5755b2b90e1969d47ce89cf2d35078984a0ee5" +name = "decaf377-rdsa" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "437967a34e0699b50b986a72ce6c4e2e5930bde85ec8f3749701f7e50d6d32b0" dependencies = [ - "ark-bls12-377", - "ark-ec", - "ark-ed-on-bls12-377", "ark-ff 0.4.2", "ark-serialize 0.4.2", - "ark-std 0.4.0", - "blake2", - "cfg-if 1.0.3", - "elliptic-curve 0.13.8", - "frost-dkg", - "gennaro-dkg", - "hashbrown 0.15.5", + "blake2b_simd 0.5.11", + "decaf377", + "digest 0.9.0", "hex", - "num-bigint", - "once_cell", "rand_core 0.6.4", - "serdect 0.3.0", - "subtle", + "serde", + "thiserror 1.0.69", "zeroize", ] [[package]] -name = "decaf377" +name = "decaf377_plus" version = "0.10.1" -source = "git+https://github.com/LIT-Protocol/decaf377.git#1c5755b2b90e1969d47ce89cf2d35078984a0ee5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "209f730dfc5f9d877c7549bebc93ea0ef4fe2915b4dbf5ffebc11e8b4c17c740" dependencies = [ "ark-bls12-377", "ark-ec", @@ -4161,34 +4143,16 @@ dependencies = [ "cfg-if 1.0.3", "elliptic-curve 0.13.8", "frost-dkg", - "gennaro-dkg", "hashbrown 0.15.5", "hex", "num-bigint", "once_cell", "rand_core 0.6.4", + "serdect 0.3.0", "subtle", "zeroize", ] -[[package]] -name = "decaf377-rdsa" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "437967a34e0699b50b986a72ce6c4e2e5930bde85ec8f3749701f7e50d6d32b0" -dependencies = [ - "ark-ff 0.4.2", - "ark-serialize 0.4.2", - "blake2b_simd 0.5.11", - "decaf377 0.10.1 (registry+https://github.com/rust-lang/crates.io-index)", - "digest 0.9.0", - "hex", - "rand_core 0.6.4", - "serde", - "thiserror 1.0.69", - "zeroize", -] - [[package]] name = "deno_ast" version = "0.45.1" @@ -7009,8 +6973,8 @@ dependencies = [ [[package]] name = "frost-core" -version = "2.1.0" -source = "git+https://github.com/LIT-Protocol/frost.git?branch=2.1.0#272dd53869e7c82f7d5c72af73b5801e84c7b52e" +version = "2.2.0" +source = "git+https://github.com/LIT-Protocol/frost.git?branch=2.2.0#613ae60ad77a8a5cf973c4a8c7be2c20e9b13d89" dependencies = [ "byteorder", "const-crc32-nostd", @@ -7032,26 +6996,23 @@ dependencies = [ [[package]] name = "frost-decaf377" -version = "2.1.0" -source = "git+https://github.com/LIT-Protocol/frost.git?branch=2.1.0#272dd53869e7c82f7d5c72af73b5801e84c7b52e" +version = "2.2.0" +source = "git+https://github.com/LIT-Protocol/frost.git?branch=2.2.0#613ae60ad77a8a5cf973c4a8c7be2c20e9b13d89" dependencies = [ "ark-serialize 0.4.2", "blake2b_simd 1.0.3", - "decaf377 0.10.1 (git+https://github.com/LIT-Protocol/decaf377.git)", - "document-features", "frost-core", "frost-rerandomized", - "group 0.13.0", + "lit-rust-crypto", "num-traits", "rand_core 0.6.4", - "sha2 0.10.9", ] [[package]] name = "frost-dkg" -version = "0.3.3" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8176b54a998a04796e58b0ac3a6da08e5ab05aff5a7d92159619a652a29f63e8" +checksum = "00b59a575727037fbc977a68a2ace822b4b37f8f0647769946e307dc966ecfbb" dependencies = [ "blake2", "blsful", @@ -7059,6 +7020,7 @@ dependencies = [ "ed448-goldilocks-plus", "elliptic-curve 0.13.8", "elliptic-curve-tools", + "hex", "jubjub-plus", "k256 0.13.4", "merlin", @@ -7075,34 +7037,34 @@ dependencies = [ [[package]] name = "frost-ed25519" -version = "2.1.0" -source = "git+https://github.com/LIT-Protocol/frost.git?branch=2.1.0#272dd53869e7c82f7d5c72af73b5801e84c7b52e" +version = "2.2.0" +source = "git+https://github.com/LIT-Protocol/frost.git?branch=2.2.0#613ae60ad77a8a5cf973c4a8c7be2c20e9b13d89" dependencies = [ - "curve25519-dalek-ml", "document-features", "frost-core", "frost-rerandomized", + "lit-rust-crypto", "rand_core 0.6.4", "sha2 0.10.9", ] [[package]] name = "frost-ed448" -version = "2.1.0" -source = "git+https://github.com/LIT-Protocol/frost.git?branch=2.1.0#272dd53869e7c82f7d5c72af73b5801e84c7b52e" +version = "2.2.0" +source = "git+https://github.com/LIT-Protocol/frost.git?branch=2.2.0#613ae60ad77a8a5cf973c4a8c7be2c20e9b13d89" dependencies = [ "document-features", - "ed448-goldilocks-plus", "frost-core", "frost-rerandomized", + "lit-rust-crypto", "rand_core 0.6.4", "sha3 0.10.8", ] [[package]] name = "frost-p256" -version = "2.1.0" -source = "git+https://github.com/LIT-Protocol/frost.git?branch=2.1.0#272dd53869e7c82f7d5c72af73b5801e84c7b52e" +version = "2.2.0" +source = "git+https://github.com/LIT-Protocol/frost.git?branch=2.2.0#613ae60ad77a8a5cf973c4a8c7be2c20e9b13d89" dependencies = [ "document-features", "frost-core", @@ -7114,8 +7076,8 @@ dependencies = [ [[package]] name = "frost-p384" -version = "2.1.0" -source = "git+https://github.com/LIT-Protocol/frost.git?branch=2.1.0#272dd53869e7c82f7d5c72af73b5801e84c7b52e" +version = "2.2.0" +source = "git+https://github.com/LIT-Protocol/frost.git?branch=2.2.0#613ae60ad77a8a5cf973c4a8c7be2c20e9b13d89" dependencies = [ "document-features", "frost-core", @@ -7127,23 +7089,34 @@ dependencies = [ [[package]] name = "frost-redjubjub" -version = "2.1.0" -source = "git+https://github.com/LIT-Protocol/frost.git?branch=2.1.0#272dd53869e7c82f7d5c72af73b5801e84c7b52e" +version = "2.2.0" +source = "git+https://github.com/LIT-Protocol/frost.git?branch=2.2.0#613ae60ad77a8a5cf973c4a8c7be2c20e9b13d89" dependencies = [ "blake2b_simd 1.0.3", "document-features", "frost-core", "frost-rerandomized", - "group 0.13.0", - "jubjub-plus", + "lit-rust-crypto", + "rand_core 0.6.4", +] + +[[package]] +name = "frost-redpallas" +version = "2.2.0" +source = "git+https://github.com/LIT-Protocol/frost.git?branch=2.2.0#613ae60ad77a8a5cf973c4a8c7be2c20e9b13d89" +dependencies = [ + "blake2b_simd 1.0.3", + "document-features", + "frost-core", + "frost-rerandomized", + "lit-rust-crypto", "rand_core 0.6.4", - "sha2 0.10.9", ] [[package]] name = "frost-rerandomized" -version = "2.1.0" -source = "git+https://github.com/LIT-Protocol/frost.git?branch=2.1.0#272dd53869e7c82f7d5c72af73b5801e84c7b52e" +version = "2.2.0" +source = "git+https://github.com/LIT-Protocol/frost.git?branch=2.2.0#613ae60ad77a8a5cf973c4a8c7be2c20e9b13d89" dependencies = [ "derive-getters", "document-features", @@ -7154,27 +7127,27 @@ dependencies = [ [[package]] name = "frost-ristretto255" -version = "2.1.0" -source = "git+https://github.com/LIT-Protocol/frost.git?branch=2.1.0#272dd53869e7c82f7d5c72af73b5801e84c7b52e" +version = "2.2.0" +source = "git+https://github.com/LIT-Protocol/frost.git?branch=2.2.0#613ae60ad77a8a5cf973c4a8c7be2c20e9b13d89" dependencies = [ - "curve25519-dalek-ml", "document-features", "frost-core", "frost-rerandomized", + "lit-rust-crypto", "rand_core 0.6.4", "sha2 0.10.9", ] [[package]] name = "frost-schnorrkel25519" -version = "2.1.0" -source = "git+https://github.com/LIT-Protocol/frost.git?branch=2.1.0#272dd53869e7c82f7d5c72af73b5801e84c7b52e" +version = "2.2.0" +source = "git+https://github.com/LIT-Protocol/frost.git?branch=2.2.0#613ae60ad77a8a5cf973c4a8c7be2c20e9b13d89" dependencies = [ "byte-strings", - "curve25519-dalek-ml", "document-features", "frost-core", "frost-rerandomized", + "lit-rust-crypto", "merlin", "rand_core 0.6.4", "schnorrkel", @@ -7182,8 +7155,8 @@ dependencies = [ [[package]] name = "frost-secp256k1" -version = "2.1.0" -source = "git+https://github.com/LIT-Protocol/frost.git?branch=2.1.0#272dd53869e7c82f7d5c72af73b5801e84c7b52e" +version = "2.2.0" +source = "git+https://github.com/LIT-Protocol/frost.git?branch=2.2.0#613ae60ad77a8a5cf973c4a8c7be2c20e9b13d89" dependencies = [ "document-features", "frost-core", @@ -7195,13 +7168,13 @@ dependencies = [ [[package]] name = "frost-taproot" -version = "2.1.0" -source = "git+https://github.com/LIT-Protocol/frost.git?branch=2.1.0#272dd53869e7c82f7d5c72af73b5801e84c7b52e" +version = "2.2.0" +source = "git+https://github.com/LIT-Protocol/frost.git?branch=2.2.0#613ae60ad77a8a5cf973c4a8c7be2c20e9b13d89" dependencies = [ "document-features", "frost-core", "frost-rerandomized", - "k256 0.13.4", + "lit-rust-crypto", "rand_core 0.6.4", "sha2 0.10.9", "signature 2.2.0", @@ -7516,24 +7489,6 @@ dependencies = [ "typenum", ] -[[package]] -name = "gennaro-dkg" -version = "1.0.0-rc6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "352f32caf0eb44d8f340f3bba63ca7a0dbeeb3e169a59bbb86ef40e0da10eec6" -dependencies = [ - "anyhow", - "elliptic-curve 0.13.8", - "elliptic-curve-tools", - "merlin", - "postcard", - "rand_chacha 0.3.1", - "rand_core 0.6.4", - "serde", - "thiserror 2.0.16", - "vsss-rs 5.1.0", -] - [[package]] name = "gethostname" version = "0.2.3" @@ -7932,51 +7887,32 @@ dependencies = [ [[package]] name = "hd-keys-curves-wasm" version = "1.0.3" -source = "git+https://github.com/LIT-Protocol/hd-keys-curves-wasm?rev=5e0dcc1a6d8d08f2328d4716dca806db87f93748#5e0dcc1a6d8d08f2328d4716dca806db87f93748" +source = "git+https://github.com/LIT-Protocol/hd-keys-curves-wasm.git#5e0dcc1a6d8d08f2328d4716dca806db87f93748" dependencies = [ - "blake2", - "blsful", - "curve25519-dalek-ml", - "decaf377 0.10.1 (git+https://github.com/LIT-Protocol/decaf377?rev=1c5755b2b90e1969d47ce89cf2d35078984a0ee5)", "digest 0.10.7", "ecdsa 0.16.9", - "ed448-goldilocks-plus", "elliptic-curve 0.13.8", - "elliptic-curve-tools", "getrandom 0.2.16", - "jubjub-plus", "k256 0.13.4", "p256", - "p384 0.13.1", "sha2 0.10.9", - "sha3 0.10.8", "subtle", - "vsss-rs 5.1.0", ] [[package]] name = "hd-keys-curves-wasm" -version = "1.0.3" -source = "git+https://github.com/LIT-Protocol/hd-keys-curves-wasm#5e0dcc1a6d8d08f2328d4716dca806db87f93748" +version = "1.0.5" +source = "git+https://github.com/LIT-Protocol/hd-keys-curves-wasm.git?branch=pallas#597a14b9cf4bafd4c778f1053ca4bbad0b3d249b" dependencies = [ "blake2", - "blsful", - "curve25519-dalek-ml", - "decaf377 0.10.1 (git+https://github.com/LIT-Protocol/decaf377?rev=1c5755b2b90e1969d47ce89cf2d35078984a0ee5)", "digest 0.10.7", "ecdsa 0.16.9", - "ed448-goldilocks-plus", - "elliptic-curve 0.13.8", "elliptic-curve-tools", "getrandom 0.2.16", - "jubjub-plus", - "k256 0.13.4", - "p256", - "p384 0.13.1", + "lit-rust-crypto", "sha2 0.10.9", "sha3 0.10.8", "subtle", - "vsss-rs 5.1.0", ] [[package]] @@ -9249,9 +9185,9 @@ dependencies = [ [[package]] name = "jubjub-plus" -version = "0.10.8" +version = "0.10.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c2c5e88d1ac6a903e693287073860ea35299b200273d5c2bd9d7845ec39f319" +checksum = "e8cd4e5cd65bb1390238c9e2e7dc98078a7b146c9d0d080cf3a7b1ac0d2348ac" dependencies = [ "bitvec 1.0.1", "bls12_381_plus", @@ -9298,6 +9234,7 @@ dependencies = [ "cfg-if 1.0.3", "ecdsa 0.16.9", "elliptic-curve 0.13.8", + "hex-literal", "once_cell", "serdect 0.2.0", "sha2 0.10.9", @@ -9905,7 +9842,7 @@ source = "git+https://github.com/LIT-Protocol/lit-ecdsa-wasm-combine?branch=0.2. dependencies = [ "console_error_panic_hook", "getrandom 0.2.16", - "hd-keys-curves-wasm 1.0.3 (git+https://github.com/LIT-Protocol/hd-keys-curves-wasm)", + "hd-keys-curves-wasm 1.0.3", "hex", "js-sys", "k256 0.13.4", @@ -9926,32 +9863,28 @@ version = "0.2.0" dependencies = [ "digest 0.10.7", "ecdsa 0.16.9", - "elliptic-curve 0.13.8", "elliptic-curve-tools", - "hd-keys-curves-wasm 1.0.3 (git+https://github.com/LIT-Protocol/hd-keys-curves-wasm?rev=5e0dcc1a6d8d08f2328d4716dca806db87f93748)", + "hd-keys-curves-wasm 1.0.5", "hex", "lit-poly", + "lit-rust-crypto", "rand 0.8.5", "serde", "sha2 0.10.9", "subtle", "thiserror 2.0.16", - "vsss-rs 5.1.0", "zeroize", ] [[package]] name = "lit-frost" -version = "0.3.0" -source = "git+https://github.com/LIT-Protocol/lit-frost.git#60ad81f1f637f7042bfee0fd8cc29cee74d754b1" +version = "0.4.0" +source = "git+https://github.com/LIT-Protocol/lit-frost.git?branch=pallas#38ecfb7d037138b16b1bac675e53fa4ab8e4d960" dependencies = [ "anyhow", "ark-serialize 0.4.2", - "curve25519-dalek-ml", - "decaf377 0.10.1 (git+https://github.com/LIT-Protocol/decaf377?rev=1c5755b2b90e1969d47ce89cf2d35078984a0ee5)", "decaf377-rdsa", "ed25519-dalek 2.2.0", - "ed448-goldilocks-plus", "frost-core", "frost-decaf377", "frost-ed25519", @@ -9959,16 +9892,14 @@ dependencies = [ "frost-p256", "frost-p384", "frost-redjubjub", + "frost-redpallas", "frost-ristretto255", "frost-schnorrkel25519", "frost-secp256k1", "frost-taproot", "getrandom 0.2.16", "hex", - "jubjub-plus", - "k256 0.13.4", - "p256", - "p384 0.13.1", + "lit-rust-crypto", "rand_core 0.6.4", "reddsa", "schnorrkel", @@ -9977,7 +9908,6 @@ dependencies = [ "sha2 0.10.9", "subtle", "thiserror 2.0.16", - "vsss-rs 5.1.0", "zeroize", ] @@ -10027,7 +9957,7 @@ dependencies = [ "rand_chacha 0.3.1", "rand_core 0.6.4", "reqwest 0.11.27", - "sdd 3.0.10", + "sdd 4.2.4", "serde", "serde_json", "serdect 0.3.0", @@ -10044,23 +9974,17 @@ dependencies = [ name = "lit-node-core" version = "2.0.1" dependencies = [ - "blsful", - "curve25519-dalek-ml", - "decaf377 0.10.1 (git+https://github.com/LIT-Protocol/decaf377?rev=1c5755b2b90e1969d47ce89cf2d35078984a0ee5)", "ed25519-dalek 2.2.0", - "ed448-goldilocks-plus", "ethabi 16.0.0", "ethers", - "hd-keys-curves-wasm 1.0.3 (git+https://github.com/LIT-Protocol/hd-keys-curves-wasm)", + "hd-keys-curves-wasm 1.0.5", "hex", - "jubjub-plus", - "k256 0.13.4", - "p256", - "p384 0.13.1", + "lit-rust-crypto", + "rand_chacha 0.3.1", + "rand_core 0.6.4", "serde", "serde_json", "thiserror 2.0.16", - "vsss-rs 5.1.0", ] [[package]] @@ -10148,32 +10072,25 @@ dependencies = [ [[package]] name = "lit-recovery" -version = "0.2.0" +version = "0.3.0" dependencies = [ "arc-swap", "argon2", - "blsful", "bulletproofs", "byteorder", "ciborium", "clap 4.5.46", "colored", "cryptex", - "decaf377 0.10.1 (git+https://github.com/LIT-Protocol/decaf377?rev=1c5755b2b90e1969d47ce89cf2d35078984a0ee5)", "dirs 6.0.0", - "ed448-goldilocks-plus", - "elliptic-curve 0.13.8", "ethers", "generic-array 1.1.1", "glob", "hex", - "jubjub-plus", - "k256 0.13.4", "lit-blockchain", "lit-core", "lit-node-core", - "p256", - "p384 0.13.1", + "lit-rust-crypto", "path-clean 1.0.1", "rand 0.8.5", "reqwest 0.11.27", @@ -10189,16 +10106,34 @@ dependencies = [ "tiny-bip39 2.0.0", "tokio", "verifiable-share-encryption", - "vsss-rs 5.1.0", "winapi", ] +[[package]] +name = "lit-rust-crypto" +version = "0.6.0" +source = "git+https://github.com/LIT-Protocol/lit-rust-crypto?tag=0.6.0#9548fce521473f289ea1366249b782355e96507d" +dependencies = [ + "bls12_381_plus", + "blsful", + "blstrs_plus", + "curve25519-dalek-ml", + "decaf377_plus", + "ed448-goldilocks-plus", + "elliptic-curve 0.13.8", + "jubjub-plus", + "k256 0.13.4", + "p256", + "p384 0.13.1", + "pasta_curves_plus", + "vsss-rs 5.1.0", +] + [[package]] name = "lit-sdk" version = "2.0.1" dependencies = [ "chrono", - "data-encoding", "ecdsa 0.16.9", "elliptic-curve-tools", "futures", @@ -10224,21 +10159,13 @@ version = "0.2.0" dependencies = [ "blake2", "bulletproofs", - "curve25519-dalek-ml", - "decaf377 0.10.1 (git+https://github.com/LIT-Protocol/decaf377?rev=1c5755b2b90e1969d47ce89cf2d35078984a0ee5)", - "ed448-goldilocks-plus", - "elliptic-curve 0.13.8", "elliptic-curve-tools", - "jubjub-plus", - "k256 0.13.4", - "p256", - "p384 0.13.1", + "lit-rust-crypto", "rfc6979 0.4.0", "serde", "sha2 0.10.9", "sha3 0.10.8", "thiserror 2.0.16", - "vsss-rs 5.1.0", ] [[package]] @@ -10253,26 +10180,19 @@ dependencies = [ "async-trait", "base64_light", "bech32 0.11.0", - "blsful", - "blstrs_plus", "bs58 0.5.1", "bulletproofs", - "cc", "chrono", "ciborium", "clap 4.5.46", "ctor", - "curve25519-dalek-ml", "data-encoding", - "decaf377 0.10.1 (git+https://github.com/LIT-Protocol/decaf377?rev=1c5755b2b90e1969d47ce89cf2d35078984a0ee5)", "derive_builder", "derive_more 2.0.1", "digest 0.10.7", "dotenv", "ecdsa 0.16.9", "ed25519-dalek 2.2.0", - "ed448-goldilocks-plus", - "elliptic-curve 0.13.8", "ethabi 16.0.0", "ethers", "flume", @@ -10280,7 +10200,6 @@ dependencies = [ "futures", "generic-array 1.1.1", "glob", - "hd-keys-curves-wasm 1.0.3 (git+https://github.com/LIT-Protocol/hd-keys-curves-wasm?rev=5e0dcc1a6d8d08f2328d4716dca806db87f93748)", "hex", "hex-literal", "indicatif 0.15.0", @@ -10288,8 +10207,6 @@ dependencies = [ "ipfs-hasher", "iri-string 0.6.0", "jsonpath-plus", - "jubjub-plus", - "k256 0.13.4", "lazy_static", "libaes", "libsecp256k1 0.7.1", @@ -10309,6 +10226,7 @@ dependencies = [ "lit-node-testnet", "lit-observability", "lit-recovery", + "lit-rust-crypto", "lit-sdk", "lit-vrf", "maplit", @@ -10320,8 +10238,6 @@ dependencies = [ "opentelemetry 0.24.0", "opentelemetry-semantic-conventions 0.15.0", "opentelemetry_sdk 0.24.1", - "p256", - "p384 0.13.1", "postcard", "pretty_assertions", "pretty_env_logger", @@ -10336,8 +10252,8 @@ dependencies = [ "rsa 0.7.0-pre", "rstest", "rusqlite", - "scc 2.4.0", - "sdd 3.0.10", + "scc 3.3.2", + "sdd 4.2.4", "semver 1.0.26", "serde", "serde_bare", @@ -10369,7 +10285,6 @@ dependencies = [ "utils", "verifiable-share-encryption", "visibility", - "vsss-rs 5.1.0", "web3", "webauthn-rs", "webauthn-rs-core", @@ -11957,6 +11872,26 @@ dependencies = [ "subtle", ] +[[package]] +name = "pasta_curves_plus" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42e265b7ebdbfc61a8c0eeac79350cf3225cd390325dc91dd0edede5b6742d58" +dependencies = [ + "blake2", + "blake2b_simd 1.0.3", + "elliptic-curve 0.13.8", + "ff 0.13.1", + "frost-dkg", + "group 0.13.0", + "hex", + "lazy_static", + "rand 0.8.5", + "serde", + "static_assertions", + "subtle", +] + [[package]] name = "paste" version = "1.0.15" @@ -12712,7 +12647,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "be769465445e8c1474e9c5dac2018218498557af32d9ed057325ec9a41ae81bf" dependencies = [ "heck 0.5.0", - "itertools 0.14.0", + "itertools 0.11.0", "log", "multimap", "once_cell", @@ -12732,7 +12667,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a56d757972c98b346a9b766e3f02746cde6dd1cd1d1d563472929fdd74bec4d" dependencies = [ "anyhow", - "itertools 0.14.0", + "itertools 0.11.0", "proc-macro2 1.0.101", "quote 1.0.40", "syn 2.0.106", @@ -12745,7 +12680,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9120690fafc389a67ba3803df527d0ec9cbbc9cc45e4cc20b332996dfb672425" dependencies = [ "anyhow", - "itertools 0.14.0", + "itertools 0.11.0", "proc-macro2 1.0.101", "quote 1.0.40", "syn 2.0.106", @@ -17869,8 +17804,8 @@ version = "1.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "97fee6b57c6a41524a810daee9286c02d7752c4253064d0b05472833a438f675" dependencies = [ - "cfg-if 1.0.3", - "rand 0.8.5", + "cfg-if 0.1.10", + "rand 0.7.3", "static_assertions", ] @@ -18344,13 +18279,14 @@ checksum = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191" [[package]] name = "verifiable-share-encryption" -version = "0.3.0" -source = "git+https://github.com/LIT-Protocol/verifiable-share-encryption?rev=7eddfbe736369db596d0f302c72f1d76b0fd332d#7eddfbe736369db596d0f302c72f1d76b0fd332d" +version = "0.4.0" +source = "git+https://github.com/LIT-Protocol/verifiable-share-encryption?branch=pallas#decd38dd09da1fbbfd18b3323e22ce681cd121cc" dependencies = [ "anyhow", "bulletproofs", "data-encoding", "elliptic-curve-tools", + "lit-rust-crypto", "rand_core 0.6.4", "rayon", "serde", diff --git a/rust/lit-node/Cargo.toml b/rust/lit-node/Cargo.toml index 5190dcd..f6d0ec8 100644 --- a/rust/lit-node/Cargo.toml +++ b/rust/lit-node/Cargo.toml @@ -27,14 +27,10 @@ edition = "2024" [workspace.dependencies] async-std = "1.13" async-trait = "0.1" -blsful = "3.0.0-pre8" -bulletproofs = { git = "https://github.com/LIT-Protocol/bulletproofs", rev = "ddf11c2f593e71f24c9a3d64c56f62d82f2b5099" } -curve25519-dalek = { package = "curve25519-dalek-ml", version="4.3.0", features = ["group", "serde", "rand_core"] } -data-encoding = "2.8" -decaf377 = { git = "https://github.com/LIT-Protocol/decaf377", rev = "1c5755b2b90e1969d47ce89cf2d35078984a0ee5", features = ["serde"] } +bulletproofs = { git = "https://github.com/LIT-Protocol/bulletproofs", branch = "pallas" } +data-encoding = "2.9" derive_more = { version = "2" , features = ["display"] } ed25519-dalek = { version = "2.2", features = ["rand_core"] } -ed448-goldilocks = { version = "0.16", package = "ed448-goldilocks-plus", features = ["serde"] } elliptic-curve = { version = "0.13", features = ["arithmetic", "serde"] } ethabi = "16.0.0" ethers = { version = "2.0.8", features = [ @@ -42,22 +38,41 @@ ethers = { version = "2.0.8", features = [ "legacy" ]} generic-array = "=1.1.1" +hd-keys-curves-wasm = { git = "https://github.com/LIT-Protocol/hd-keys-curves-wasm", branch = "pallas", default-features = false, features = ["bls", "k256", "p256", "p384", "curve25519", "ed448", "jubjub", "decaf377", "pasta"] } hex = "0.4" -jubjub = { package = "jubjub-plus", version = "0.10", features = ["serde"] } +lit-frost = { git = "https://github.com/LIT-Protocol/lit-frost.git", branch = "pallas" } reqwest = { version = "0.11.14", default-features = false, features = ["json", "rustls-tls", "stream"] } rand = "0.8" rand_core = "0.6" rand_chacha = "0.3.1" -sdd = "3" +scc = "3" +sdd = "4" sha2 = "0.10.9" sha3 = "0.10.8" serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" soteria-rs = { version = "0.3.1", features = ["serde", "elements"] } url = { version = "2", features = ["serde"] } -vsss-rs = { version = "5.1", features = ["curve25519"] } zeroize = { version = "1.8", features = ["derive"] } +[workspace.dependencies.lit-rust-crypto] +git = "https://github.com/LIT-Protocol/lit-rust-crypto" +tag = "0.6.0" +features = [ + "arithmetic", + "bits", + "ecdsa", + "ecdsa-core", + "digest", + "hash2curve", + "hex", + "rand_core", + "serde", + "sha", + "std", + "zeroize", +] + [patch.crates-io] # needed to force deno_crypto to use v0.7.0-pre and not v0.7.0-rc.0 which for some reason is missing a bunch of stuff from the -pre version rsa = { git = "https://github.com/RustCrypto/RSA", tag = "v0.7.0-pre" } diff --git a/rust/lit-node/lit-node-core/Cargo.toml b/rust/lit-node/lit-node-core/Cargo.toml index 0274d11..b44f9ab 100644 --- a/rust/lit-node/lit-node-core/Cargo.toml +++ b/rust/lit-node/lit-node-core/Cargo.toml @@ -7,22 +7,16 @@ edition.workspace = true default = [] [dependencies] -blsful.workspace = true -curve25519-dalek.workspace = true -decaf377.workspace = true ed25519-dalek.workspace = true -ed448-goldilocks.workspace = true ethabi.workspace = true ethers.workspace = true -hd-keys-curves-wasm = { git = "https://github.com/LIT-Protocol/hd-keys-curves-wasm", default-features = false, features = ["bls", "k256", "p256", "p384", "curve25519", "ed448", "jubjub", "decaf377"] } +hd-keys-curves-wasm.workspace = true hex.workspace = true -jubjub.workspace = true -k256 = { version = "0.13", features = ["ecdsa", "serde"] } -p256 = { version = "0.13", features = ["ecdsa", "serde"] } -p384 = { version = "0.13.1", features = ["ecdsa", "serde"] } +lit-rust-crypto.workspace = true serde.workspace = true serde_json.workspace = true thiserror = "2.0" -vsss-rs.workspace = true [dev-dependencies] +rand_chacha = "0.3.1" +rand_core = "0.6.4" \ No newline at end of file diff --git a/rust/lit-node/lit-node-core/src/lib.rs b/rust/lit-node/lit-node-core/src/lib.rs index 0b2f379..aa53a00 100644 --- a/rust/lit-node/lit-node-core/src/lib.rs +++ b/rust/lit-node/lit-node-core/src/lib.rs @@ -8,17 +8,7 @@ pub use error::*; pub use models::*; pub use traits::*; -pub use blsful; -pub use curve25519_dalek; -pub use decaf377; -pub use ed448_goldilocks; -pub use ed25519_dalek; -pub use ethabi; pub use ethers; pub use hd_keys_curves_wasm; pub use hex; -pub use jubjub; -pub use k256; -pub use p256; -pub use p384; -pub use vsss_rs; +pub use lit_rust_crypto; diff --git a/rust/lit-node/lit-node-core/src/models/auth_sig.rs b/rust/lit-node/lit-node-core/src/models/auth_sig.rs index 551a17e..b5744ab 100644 --- a/rust/lit-node/lit-node-core/src/models/auth_sig.rs +++ b/rust/lit-node/lit-node-core/src/models/auth_sig.rs @@ -106,15 +106,15 @@ impl JsonAuthSig { /// /// TODO: After a stabilization period, we should make our pattern matching /// stricter and perhaps turn this function to returning a core::Result. + #[allow(clippy::collapsible_if)] pub fn determine_auth_material_type( derived_via: &str, algo: &Option, ) -> AuthMaterialType { - if derived_via == AUTH_SIG_DERIVED_VIA_SESSION_SIG { - if let Some(algo) = algo { - if algo == AUTH_SIG_SESSION_SIG_ALGO { - return AuthMaterialType::SessionSig; - } + if let Some(algo) = algo { + if derived_via == AUTH_SIG_DERIVED_VIA_SESSION_SIG && algo == AUTH_SIG_SESSION_SIG_ALGO + { + return AuthMaterialType::SessionSig; } } @@ -124,11 +124,11 @@ impl JsonAuthSig { return AuthMaterialType::ContractSig; } - if derived_via == AUTH_SIG_DERIVED_VIA_BLS_NETWORK_SIG { - if let Some(algo) = algo { - if algo == AUTH_SIG_BLS_NETWORK_SIG_ALGO { - return AuthMaterialType::BLSNetworkSig; - } + if let Some(algo) = algo { + if derived_via == AUTH_SIG_DERIVED_VIA_BLS_NETWORK_SIG + && algo == AUTH_SIG_BLS_NETWORK_SIG_ALGO + { + return AuthMaterialType::BLSNetworkSig; } } diff --git a/rust/lit-node/lit-node-core/src/models/blinders.rs b/rust/lit-node/lit-node-core/src/models/blinders.rs index 06925ee..b699ae7 100644 --- a/rust/lit-node/lit-node-core/src/models/blinders.rs +++ b/rust/lit-node/lit-node-core/src/models/blinders.rs @@ -1,6 +1,9 @@ -use blsful::inner_types::Scalar; +use lit_rust_crypto::{ + blsful::inner_types::*, decaf377, ed448_goldilocks, elliptic_curve::subtle::Choice, jubjub, + k256, p256, p384, pallas, vsss_rs::curve25519, +}; + use serde::{Deserialize, Serialize}; -use vsss_rs::subtle::Choice; /// Blinders for the different curves for verifiable encryption #[derive(Clone, Copy, Debug, Default, Serialize, Deserialize)] @@ -9,12 +12,13 @@ pub struct Blinders { pub k256_blinder: Option, pub p256_blinder: Option, pub p384_blinder: Option, - pub ed25519_blinder: Option, - pub ristretto25519_blinder: Option, + pub ed25519_blinder: Option, + pub ristretto25519_blinder: Option, pub ed448_blinder: Option, pub jubjub_blinder: Option, pub decaf377_blinder: Option, pub bls12381g1_blinder: Option, + pub pallas_blinder: Option, } impl Blinders { @@ -29,11 +33,10 @@ impl Blinders { || self.jubjub_blinder.is_some() || self.decaf377_blinder.is_some() || self.bls12381g1_blinder.is_some() + || self.pallas_blinder.is_some() } pub fn any_blinders_invalid(&self) -> bool { - use blsful::inner_types::*; - let mut any = Choice::from(0u8); if let Some(bls_blinder) = &self.bls_blinder { any |= bls_blinder.is_zero(); @@ -62,6 +65,9 @@ impl Blinders { if let Some(bls12381g1_blinder) = &self.bls12381g1_blinder { any |= bls12381g1_blinder.is_zero(); } + if let Some(pallas_blinder) = &self.pallas_blinder { + any |= pallas_blinder.is_zero(); + } bool::from(any) } diff --git a/rust/lit-node/lit-node-core/src/models/curve_type.rs b/rust/lit-node/lit-node-core/src/models/curve_type.rs index 32d60ee..1449f42 100644 --- a/rust/lit-node/lit-node-core/src/models/curve_type.rs +++ b/rust/lit-node/lit-node-core/src/models/curve_type.rs @@ -20,10 +20,11 @@ pub enum CurveType { RedJubjub = 8, // RedJubjub RedDecaf377 = 9, // RedDecaf377 BLS12381G1 = 10, // Signatures in G2 while Public Keys in G1 + RedPallas = 11, // RedPallas } impl CurveType { - pub const NUM_USED_CURVES: usize = 10; + pub const NUM_USED_CURVES: usize = 11; pub const fn as_str(&self) -> &'static str { match self { @@ -37,6 +38,7 @@ impl CurveType { CurveType::RedJubjub => "RedJubjub", CurveType::RedDecaf377 => "RedDecaf377", CurveType::BLS12381G1 => "BLS12381G1Sign", + CurveType::RedPallas => "RedPallas", } } @@ -54,6 +56,7 @@ impl CurveType { RedJubjub, RedDecaf377, BLS12381G1, + RedPallas, ] .into_iter() } @@ -70,6 +73,7 @@ impl CurveType { Self::RedJubjub => 32, Self::RedDecaf377 => 32, Self::BLS12381G1 => 32, + Self::RedPallas => 32, } } @@ -85,6 +89,7 @@ impl CurveType { Self::RedJubjub => 32, Self::RedDecaf377 => 32, Self::BLS12381G1 => 48, + Self::RedPallas => 32, } } @@ -100,6 +105,7 @@ impl CurveType { CurveType::RedJubjub => b"redjubjub_XMD:BLAKE2B-512_ELL2_RO_NUL_VRF", CurveType::RedDecaf377 => b"decaf377_XMD:BLAKE2B-512_ELL2_RO_NUL_VRF", CurveType::BLS12381G1 => b"BLS12381G1_XMD:SHA-256_SSWU_RO_NUL_VRF", + CurveType::RedPallas => b"redpallas_XMD:BLAKE2B-512_SSWU_RO_NUL_VRF", } } @@ -115,6 +121,7 @@ impl CurveType { CurveType::RedJubjub => "jubjub", CurveType::RedDecaf377 => "decaf377", CurveType::BLS12381G1 => "bls12381g1", + CurveType::RedPallas => "pallas", } } @@ -143,6 +150,7 @@ impl FromStr for CurveType { "REDJUBJUB" => Ok(CurveType::RedJubjub), "REDDECAF377" => Ok(CurveType::RedDecaf377), "BLS12381G1SIGN" => Ok(CurveType::BLS12381G1), + "REDPALLAS" => Ok(CurveType::RedPallas), _ => CurveType::invalid(), } } @@ -164,6 +172,7 @@ impl TryFrom for CurveType { Ok(8) => Ok(CurveType::RedJubjub), Ok(9) => Ok(CurveType::RedDecaf377), Ok(10) => Ok(CurveType::BLS12381G1), + Ok(11) => Ok(CurveType::RedPallas), _ => CurveType::invalid(), } } @@ -183,6 +192,7 @@ impl TryFrom for CurveType { 8 => Ok(CurveType::RedJubjub), 9 => Ok(CurveType::RedDecaf377), 10 => Ok(CurveType::BLS12381G1), + 11 => Ok(CurveType::RedPallas), _ => CurveType::invalid(), } } diff --git a/rust/lit-node/lit-node-core/src/models/peer_id.rs b/rust/lit-node/lit-node-core/src/models/peer_id.rs index 8e4bc6e..7dd319f 100644 --- a/rust/lit-node/lit-node-core/src/models/peer_id.rs +++ b/rust/lit-node/lit-node-core/src/models/peer_id.rs @@ -1,6 +1,8 @@ use crate::{Error, Result}; -use blsful::vsss_rs::{ - self, +use lit_rust_crypto::{ + blsful::inner_types as bls, + curve25519_dalek, decaf377, + ed448_goldilocks::{self, sha3}, elliptic_curve::{ bigint::{ ArrayEncoding, ByteArray, Encoding, NonZero, Random, RandomMod, U256, U512, U768, U896, @@ -9,20 +11,15 @@ use blsful::vsss_rs::{ rand_core::{CryptoRng, RngCore}, scalar::FromUintUnchecked, }, -}; -use hd_keys_curves_wasm::{ - decaf377, - ed448_goldilocks_plus::{self, sha3}, jubjub, k256::{ self, sha2::{self, Digest}, }, - p256, p384, + p256, p384, pallas, vsss_rs, }; use serde::{Deserialize, Deserializer, Serialize, Serializer}; -use std::fmt; -use std::fmt::{Debug, Display, Formatter}; +use std::fmt::{self, Debug, Display, Formatter}; use std::hash::{Hash, Hasher}; use std::num::{NonZeroU8, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU128, NonZeroUsize}; use std::str::FromStr; @@ -160,7 +157,6 @@ impl From<&PeerId> for U256 { impl From for ethers::types::U256 { fn from(value: PeerId) -> Self { - use blsful::vsss_rs::elliptic_curve::bigint::Encoding; ethers::types::U256::from(value.0.to_be_bytes()) } } @@ -552,15 +548,15 @@ impl From for p384::NonZeroScalar { } } -impl From for ed448_goldilocks_plus::Scalar { +impl From for ed448_goldilocks::Scalar { fn from(value: PeerId) -> Self { use sha3::digest::{ExtendableOutput, Update}; let mut hasher = sha3::Shake128::default(); hasher.update(&value.0.to_be_byte_array()); let digest = hasher.finalize_boxed(114); - let wide_bytes = ed448_goldilocks_plus::WideScalarBytes::from_slice(digest.as_ref()); - >::reduce_bytes(wide_bytes) + let wide_bytes = ed448_goldilocks::WideScalarBytes::from_slice(digest.as_ref()); + >::reduce_bytes(wide_bytes) } } @@ -571,10 +567,10 @@ impl From for jubjub::Scalar { } } -impl From for blsful::inner_types::Scalar { +impl From for bls::Scalar { fn from(value: PeerId) -> Self { let digest = sha2::Sha512::digest(value.0.to_be_byte_array()); - >::reduce(U512::from_be_byte_array(digest)) + >::reduce(U512::from_be_byte_array(digest)) } } @@ -585,6 +581,14 @@ impl From for decaf377::Fr { } } +impl From for pallas::Scalar { + fn from(value: PeerId) -> Self { + let digest = sha2::Sha512::digest(value.0.to_be_byte_array()); + let n = U512::from_be_byte_array(digest); + Self::reduce(n) + } +} + impl FromPeerIdDirect for k256::Scalar { fn from_peer_id(peer_id: PeerId) -> Self { Self::from_uint_unchecked(*peer_id.0.as_ref()) @@ -654,13 +658,13 @@ impl FromPeerIdDirect for vsss_rs::curve25519::WrappedScalar { } } -impl FromPeerIdDirect for ed448_goldilocks_plus::Scalar { +impl FromPeerIdDirect for ed448_goldilocks::Scalar { fn from_peer_id(peer_id: PeerId) -> Self { Self::from_uint_unchecked(peer_id.0.as_ref().resize()) } } -impl FromPeerIdDirect for blsful::inner_types::Scalar { +impl FromPeerIdDirect for bls::Scalar { fn from_peer_id(peer_id: PeerId) -> Self { Self::from_uint_unchecked(peer_id.0.as_ref().resize()) } @@ -691,6 +695,12 @@ impl FromPeerIdDirect for decaf377::Fr { } } +impl FromPeerIdDirect for pallas::Scalar { + fn from_peer_id(peer_id: PeerId) -> Self { + Self::from_uint_unchecked(*peer_id.0.as_ref()) + } +} + impl PeerId { pub const ONE: Self = PeerId(NonZero::::ONE); pub const NOT_ASSIGNED: Self = PeerId(NonZero::::from_uint(U256::MAX)); @@ -762,3 +772,22 @@ fn test_parse_peer_id() { let peer_id2 = u256.try_into().unwrap(); assert_eq!(peer_id, peer_id2); } + +#[test] +fn test_into_scalar_pallas() { + use rand_core::SeedableRng; + + let rng = rand_chacha::ChaChaRng::seed_from_u64(0); + let peer_id = PeerId::random(rng); + let id: pallas::Scalar = peer_id.into(); + let limbs = id.to_raw(); + assert_eq!( + limbs, + [ + 0x3fd0ff79135bb946, + 0xcacf6941e56db2e4, + 0xa49547659cb1baa7, + 0x04e7181b6f5533de, + ] + ); +} diff --git a/rust/lit-node/lit-node-core/src/models/response.rs b/rust/lit-node/lit-node-core/src/models/response.rs index d4c057e..eba7646 100644 --- a/rust/lit-node/lit-node-core/src/models/response.rs +++ b/rust/lit-node/lit-node-core/src/models/response.rs @@ -1,5 +1,5 @@ use super::{DynamicPaymentItem, SignableOutput, SignedData, default_epoch}; -use blsful::{Bls12381G2Impl, SignatureShare}; +use lit_rust_crypto::blsful::{Bls12381G2Impl, SignatureShare}; use serde::{Deserialize, Serialize, de::DeserializeOwned}; use serde_json::Value; use std::collections::HashMap; diff --git a/rust/lit-node/lit-node-core/src/models/signing_scheme.rs b/rust/lit-node/lit-node-core/src/models/signing_scheme.rs index 091d8da..77ab36c 100644 --- a/rust/lit-node/lit-node-core/src/models/signing_scheme.rs +++ b/rust/lit-node/lit-node-core/src/models/signing_scheme.rs @@ -32,6 +32,7 @@ pub enum SigningScheme { SchnorrRedJubjubBlake2b512, SchnorrK256Taproot, SchnorrRedDecaf377Blake2b512, + SchnorrRedPallasBlake2b512, SchnorrkelSubstrate, Bls12381G1ProofOfPossession, } @@ -50,6 +51,7 @@ impl Display for SigningScheme { Self::SchnorrRistretto25519Sha512 => write!(f, "SchnorrRistretto25519Sha512"), Self::SchnorrEd448Shake256 => write!(f, "SchnorrEd448Shake256"), Self::SchnorrRedJubjubBlake2b512 => write!(f, "SchnorrRedJubjubBlake2b512"), + Self::SchnorrRedPallasBlake2b512 => write!(f, "SchnorrRedPallasBlake2b512"), Self::SchnorrK256Taproot => write!(f, "SchnorrK256Taproot"), Self::SchnorrRedDecaf377Blake2b512 => write!(f, "SchnorrRedDecaf377Blake2b512"), Self::SchnorrkelSubstrate => write!(f, "SchnorrkelSubstrate"), @@ -74,6 +76,7 @@ impl FromStr for SigningScheme { "SchnorrRistretto25519Sha512" => Ok(SigningScheme::SchnorrRistretto25519Sha512), "SchnorrEd448Shake256" => Ok(SigningScheme::SchnorrEd448Shake256), "SchnorrRedJubjubBlake2b512" => Ok(SigningScheme::SchnorrRedJubjubBlake2b512), + "SchnorrRedPallasBlake2b512" => Ok(SigningScheme::SchnorrRedPallasBlake2b512), "SchnorrK256Taproot" => Ok(SigningScheme::SchnorrK256Taproot), "SchnorrRedDecaf377Blake2b512" => Ok(SigningScheme::SchnorrRedDecaf377Blake2b512), "SchnorrkelSubstrate" => Ok(SigningScheme::SchnorrkelSubstrate), @@ -101,6 +104,7 @@ impl From for u8 { SigningScheme::SchnorrRedDecaf377Blake2b512 => 13, SigningScheme::SchnorrkelSubstrate => 14, SigningScheme::Bls12381G1ProofOfPossession => 15, + SigningScheme::SchnorrRedPallasBlake2b512 => 16, } } } @@ -125,6 +129,7 @@ impl TryFrom for SigningScheme { 13 => Ok(SigningScheme::SchnorrRedDecaf377Blake2b512), 14 => Ok(SigningScheme::SchnorrkelSubstrate), 15 => Ok(SigningScheme::Bls12381G1ProofOfPossession), + 16 => Ok(SigningScheme::SchnorrRedPallasBlake2b512), _ => Err(Error::Parse(format!("Invalid signing scheme: {}", value))), } } @@ -197,6 +202,10 @@ impl SigningScheme { SigningAlgorithm::Schnorr, SigningScheme::SchnorrkelSubstrate ) + | ( + SigningAlgorithm::Schnorr, + SigningScheme::SchnorrRedPallasBlake2b512 + ) ) } @@ -216,6 +225,7 @@ impl SigningScheme { | Self::SchnorrRistretto25519Sha512 | Self::SchnorrEd448Shake256 | Self::SchnorrRedJubjubBlake2b512 + | Self::SchnorrRedPallasBlake2b512 | Self::SchnorrRedDecaf377Blake2b512 | Self::SchnorrkelSubstrate => KeyFormatPreference::Compressed, Self::EcdsaK256Sha256 | Self::EcdsaP256Sha256 | Self::EcdsaP384Sha384 => { @@ -248,6 +258,7 @@ impl SigningScheme { } Self::SchnorrEd448Shake256 => CurveType::Ed448, Self::SchnorrRedJubjubBlake2b512 => CurveType::RedJubjub, + Self::SchnorrRedPallasBlake2b512 => CurveType::RedPallas, Self::SchnorrK256Taproot => CurveType::K256, Self::SchnorrRedDecaf377Blake2b512 => CurveType::RedDecaf377, Self::Bls12381G1ProofOfPossession => CurveType::BLS12381G1, @@ -278,6 +289,9 @@ impl SigningScheme { SigningScheme::SchnorrRedJubjubBlake2b512 => { b"LIT_HD_KEY_ID_REDJUBJUB_XMD:BLAKE2B-512_ELL2_RO_NUL_" } + SigningScheme::SchnorrRedPallasBlake2b512 => { + b"LIT_HD_KEY_ID_REDPALLAS_XMD:BLAKE2B-512_SSWU_RO_NUL_" + } SigningScheme::SchnorrRedDecaf377Blake2b512 => { b"LIT_HD_KEY_ID_DECAF377_XMD:BLAKE2B-512_ELL2_RO_NUL_" } @@ -296,6 +310,7 @@ impl SigningScheme { | Self::SchnorrRistretto25519Sha512 | Self::SchnorrEd448Shake256 | Self::SchnorrRedJubjubBlake2b512 + | Self::SchnorrRedPallasBlake2b512 | Self::SchnorrRedDecaf377Blake2b512 | Self::SchnorrkelSubstrate | Self::Bls12381 @@ -320,6 +335,7 @@ impl SigningScheme { Self::SchnorrRistretto25519Sha512 => "SchnorrRistretto25519Sha512", Self::SchnorrEd448Shake256 => "SchnorrEd448Shake256", Self::SchnorrRedJubjubBlake2b512 => "SchnorrRedJubjubBlake2b512", + Self::SchnorrRedPallasBlake2b512 => "SchnorrRedPallasBlake2b512", Self::SchnorrK256Taproot => "SchnorrK256Taproot", Self::SchnorrRedDecaf377Blake2b512 => "SchnorrRedDecaf377Blake2b512", Self::SchnorrkelSubstrate => "SchnorrkelSubstrate", diff --git a/rust/lit-node/lit-node-core/src/traits/encoding.rs b/rust/lit-node/lit-node-core/src/traits/encoding.rs index 6f2445b..13f22c1 100644 --- a/rust/lit-node/lit-node-core/src/traits/encoding.rs +++ b/rust/lit-node/lit-node-core/src/traits/encoding.rs @@ -6,6 +6,7 @@ mod k256; mod p256; mod p384; mod redjubjub; +mod redpallas; /// A trait for handling points in compressed form. pub trait CompressedBytes: Sized { diff --git a/rust/lit-node/lit-node-core/src/traits/encoding/bls.rs b/rust/lit-node/lit-node-core/src/traits/encoding/bls.rs index a748752..f7e159c 100644 --- a/rust/lit-node/lit-node-core/src/traits/encoding/bls.rs +++ b/rust/lit-node/lit-node-core/src/traits/encoding/bls.rs @@ -1,5 +1,5 @@ use super::{BeBytes, CompressedBytes, LeBytes}; -use blsful::inner_types::{G1Projective, G2Projective, Scalar}; +use lit_rust_crypto::blsful::inner_types::{G1Projective, G2Projective, Scalar}; impl CompressedBytes for G1Projective { fn to_compressed(&self) -> Vec { diff --git a/rust/lit-node/lit-node-core/src/traits/encoding/curve25519.rs b/rust/lit-node/lit-node-core/src/traits/encoding/curve25519.rs index d8040a6..effe37b 100644 --- a/rust/lit-node/lit-node-core/src/traits/encoding/curve25519.rs +++ b/rust/lit-node/lit-node-core/src/traits/encoding/curve25519.rs @@ -1,6 +1,8 @@ use super::{BeBytes, CompressedBytes, LeBytes}; -use blsful::inner_types::GroupEncoding; -use vsss_rs::{curve25519, curve25519_dalek}; +use lit_rust_crypto::{ + group::GroupEncoding, + vsss_rs::{curve25519, curve25519_dalek}, +}; // NOTE: There is no difference between compressed and uncompressed points for // this curve diff --git a/rust/lit-node/lit-node-core/src/traits/encoding/decaf377.rs b/rust/lit-node/lit-node-core/src/traits/encoding/decaf377.rs index 3630b0b..4414a1b 100644 --- a/rust/lit-node/lit-node-core/src/traits/encoding/decaf377.rs +++ b/rust/lit-node/lit-node-core/src/traits/encoding/decaf377.rs @@ -1,6 +1,5 @@ use super::{BeBytes, CompressedBytes, LeBytes}; -use hd_keys_curves_wasm::decaf377; -use vsss_rs::elliptic_curve::{PrimeField, group::GroupEncoding}; +use lit_rust_crypto::{decaf377, ff::PrimeField, group::GroupEncoding}; // NOTE: There is no difference between compressed and uncompressed points for // this curve diff --git a/rust/lit-node/lit-node-core/src/traits/encoding/ed448.rs b/rust/lit-node/lit-node-core/src/traits/encoding/ed448.rs index 80adcff..4db4bcf 100644 --- a/rust/lit-node/lit-node-core/src/traits/encoding/ed448.rs +++ b/rust/lit-node/lit-node-core/src/traits/encoding/ed448.rs @@ -1,6 +1,9 @@ use super::{BeBytes, CompressedBytes, LeBytes}; -use hd_keys_curves_wasm::ed448_goldilocks_plus::{EdwardsPoint, Scalar}; -use vsss_rs::elliptic_curve::{PrimeField, group::GroupEncoding}; +use lit_rust_crypto::{ + ed448_goldilocks::{EdwardsPoint, Scalar}, + ff::PrimeField, + group::GroupEncoding, +}; // NOTE: There is no difference between compressed and uncompressed points for // this curve diff --git a/rust/lit-node/lit-node-core/src/traits/encoding/k256.rs b/rust/lit-node/lit-node-core/src/traits/encoding/k256.rs index 33fb623..ae98b03 100644 --- a/rust/lit-node/lit-node-core/src/traits/encoding/k256.rs +++ b/rust/lit-node/lit-node-core/src/traits/encoding/k256.rs @@ -1,17 +1,19 @@ use super::{BeBytes, CompressedBytes, LeBytes}; -use hd_keys_curves_wasm::k256; -use vsss_rs::elliptic_curve::{ - PrimeField, - sec1::{EncodedPoint, FromEncodedPoint, ToEncodedPoint}, +use lit_rust_crypto::{ + elliptic_curve::sec1::{EncodedPoint, FromEncodedPoint, ToEncodedPoint}, + ff::PrimeField, + k256::{ + AffinePoint, FieldBytes, NonZeroScalar, ProjectivePoint, Scalar, Secp256k1, ecdsa, schnorr, + }, }; -impl CompressedBytes for k256::ProjectivePoint { +impl CompressedBytes for ProjectivePoint { fn to_compressed(&self) -> Vec { self.to_encoded_point(true).to_bytes().to_vec() } fn from_compressed(bytes: &[u8]) -> Option { - let pt = EncodedPoint::::from_bytes(bytes).ok()?; + let pt = EncodedPoint::::from_bytes(bytes).ok()?; Option::from(Self::from_encoded_point(&pt)) } fn to_uncompressed(&self) -> Vec { @@ -19,18 +21,18 @@ impl CompressedBytes for k256::ProjectivePoint { } fn from_uncompressed(bytes: &[u8]) -> Option { - let pt = EncodedPoint::::from_bytes(bytes).ok()?; + let pt = EncodedPoint::::from_bytes(bytes).ok()?; Option::from(Self::from_encoded_point(&pt)) } } -impl CompressedBytes for k256::AffinePoint { +impl CompressedBytes for AffinePoint { fn to_compressed(&self) -> Vec { self.to_encoded_point(true).to_bytes().to_vec() } fn from_compressed(bytes: &[u8]) -> Option { - let pt = EncodedPoint::::from_bytes(bytes).ok()?; + let pt = EncodedPoint::::from_bytes(bytes).ok()?; Option::from(Self::from_encoded_point(&pt)) } fn to_uncompressed(&self) -> Vec { @@ -38,18 +40,18 @@ impl CompressedBytes for k256::AffinePoint { } fn from_uncompressed(bytes: &[u8]) -> Option { - let pt = EncodedPoint::::from_bytes(bytes).ok()?; + let pt = EncodedPoint::::from_bytes(bytes).ok()?; Option::from(Self::from_encoded_point(&pt)) } } -impl CompressedBytes for k256::ecdsa::VerifyingKey { +impl CompressedBytes for ecdsa::VerifyingKey { fn to_compressed(&self) -> Vec { self.to_encoded_point(true).to_bytes().to_vec() } fn from_compressed(bytes: &[u8]) -> Option { - let pt = EncodedPoint::::from_bytes(bytes).ok()?; + let pt = EncodedPoint::::from_bytes(bytes).ok()?; Self::from_encoded_point(&pt).ok() } fn to_uncompressed(&self) -> Vec { @@ -57,18 +59,18 @@ impl CompressedBytes for k256::ecdsa::VerifyingKey { } fn from_uncompressed(bytes: &[u8]) -> Option { - let pt = EncodedPoint::::from_bytes(bytes).ok()?; + let pt = EncodedPoint::::from_bytes(bytes).ok()?; Self::from_encoded_point(&pt).ok() } } -impl CompressedBytes for k256::schnorr::VerifyingKey { +impl CompressedBytes for schnorr::VerifyingKey { fn to_compressed(&self) -> Vec { self.as_affine().to_encoded_point(true).to_bytes().to_vec() } fn from_compressed(bytes: &[u8]) -> Option { - let pt = EncodedPoint::::from_bytes(bytes).ok()?; + let pt = EncodedPoint::::from_bytes(bytes).ok()?; Self::from_bytes(pt.compress().as_bytes()).ok() } fn to_uncompressed(&self) -> Vec { @@ -76,66 +78,66 @@ impl CompressedBytes for k256::schnorr::VerifyingKey { } fn from_uncompressed(bytes: &[u8]) -> Option { - let pt = EncodedPoint::::from_bytes(bytes).ok()?; + let pt = EncodedPoint::::from_bytes(bytes).ok()?; Self::from_bytes(pt.compress().as_bytes()).ok() } } -impl BeBytes for k256::Scalar { +impl BeBytes for Scalar { fn to_be_bytes(&self) -> Vec { self.to_bytes().to_vec() } fn from_be_bytes(bytes: &[u8]) -> Option { - let mut repr = k256::FieldBytes::default(); + let mut repr = FieldBytes::default(); repr.copy_from_slice(bytes); Option::from(Self::from_repr(repr)) } } -impl LeBytes for k256::Scalar {} +impl LeBytes for Scalar {} -impl CompressedBytes for k256::Scalar { +impl CompressedBytes for Scalar { fn to_compressed(&self) -> Vec { self.to_bytes().to_vec() } fn from_compressed(bytes: &[u8]) -> Option { - let mut repr = k256::FieldBytes::default(); + let mut repr = FieldBytes::default(); repr.copy_from_slice(bytes); Option::from(Self::from_repr(repr)) } } -impl BeBytes for k256::NonZeroScalar { +impl BeBytes for NonZeroScalar { fn to_be_bytes(&self) -> Vec { self.to_bytes().to_vec() } fn from_be_bytes(bytes: &[u8]) -> Option { - let mut repr = k256::FieldBytes::default(); + let mut repr = FieldBytes::default(); repr.copy_from_slice(bytes); Option::from(Self::from_repr(repr)) } } -impl LeBytes for k256::NonZeroScalar {} +impl LeBytes for NonZeroScalar {} -impl BeBytes for k256::ecdsa::SigningKey { +impl BeBytes for ecdsa::SigningKey { fn to_be_bytes(&self) -> Vec { self.as_nonzero_scalar().to_be_bytes() } fn from_be_bytes(bytes: &[u8]) -> Option { - let mut repr = k256::FieldBytes::default(); + let mut repr = FieldBytes::default(); repr.copy_from_slice(bytes); Self::from_bytes(&repr).ok() } } -impl LeBytes for k256::ecdsa::SigningKey {} +impl LeBytes for ecdsa::SigningKey {} -impl BeBytes for k256::schnorr::SigningKey { +impl BeBytes for schnorr::SigningKey { fn to_be_bytes(&self) -> Vec { self.as_nonzero_scalar().to_be_bytes() } @@ -145,4 +147,4 @@ impl BeBytes for k256::schnorr::SigningKey { } } -impl LeBytes for k256::schnorr::SigningKey {} +impl LeBytes for schnorr::SigningKey {} diff --git a/rust/lit-node/lit-node-core/src/traits/encoding/p256.rs b/rust/lit-node/lit-node-core/src/traits/encoding/p256.rs index c7d6d49..c578755 100644 --- a/rust/lit-node/lit-node-core/src/traits/encoding/p256.rs +++ b/rust/lit-node/lit-node-core/src/traits/encoding/p256.rs @@ -1,17 +1,17 @@ use super::{BeBytes, CompressedBytes, LeBytes}; -use hd_keys_curves_wasm::p256; -use vsss_rs::elliptic_curve::{ - PrimeField, - sec1::{EncodedPoint, FromEncodedPoint, ToEncodedPoint}, +use lit_rust_crypto::{ + elliptic_curve::sec1::{EncodedPoint, FromEncodedPoint, ToEncodedPoint}, + ff::PrimeField, + p256::{AffinePoint, FieldBytes, NistP256, NonZeroScalar, ProjectivePoint, Scalar, ecdsa}, }; -impl CompressedBytes for p256::ProjectivePoint { +impl CompressedBytes for ProjectivePoint { fn to_compressed(&self) -> Vec { self.to_encoded_point(true).to_bytes().to_vec() } fn from_compressed(bytes: &[u8]) -> Option { - let pt = EncodedPoint::::from_bytes(bytes).ok()?; + let pt = EncodedPoint::::from_bytes(bytes).ok()?; Option::from(Self::from_encoded_point(&pt)) } @@ -20,18 +20,18 @@ impl CompressedBytes for p256::ProjectivePoint { } fn from_uncompressed(bytes: &[u8]) -> Option { - let pt = EncodedPoint::::from_bytes(bytes).ok()?; + let pt = EncodedPoint::::from_bytes(bytes).ok()?; Option::from(Self::from_encoded_point(&pt)) } } -impl CompressedBytes for p256::AffinePoint { +impl CompressedBytes for AffinePoint { fn to_compressed(&self) -> Vec { self.to_encoded_point(true).to_bytes().to_vec() } fn from_compressed(bytes: &[u8]) -> Option { - let pt = EncodedPoint::::from_bytes(bytes).ok()?; + let pt = EncodedPoint::::from_bytes(bytes).ok()?; Option::from(Self::from_encoded_point(&pt)) } @@ -40,18 +40,18 @@ impl CompressedBytes for p256::AffinePoint { } fn from_uncompressed(bytes: &[u8]) -> Option { - let pt = EncodedPoint::::from_bytes(bytes).ok()?; + let pt = EncodedPoint::::from_bytes(bytes).ok()?; Option::from(Self::from_encoded_point(&pt)) } } -impl CompressedBytes for p256::ecdsa::VerifyingKey { +impl CompressedBytes for ecdsa::VerifyingKey { fn to_compressed(&self) -> Vec { self.to_encoded_point(true).to_bytes().to_vec() } fn from_compressed(bytes: &[u8]) -> Option { - let pt = EncodedPoint::::from_bytes(bytes).ok()?; + let pt = EncodedPoint::::from_bytes(bytes).ok()?; Self::from_encoded_point(&pt).ok() } fn to_uncompressed(&self) -> Vec { @@ -59,61 +59,61 @@ impl CompressedBytes for p256::ecdsa::VerifyingKey { } fn from_uncompressed(bytes: &[u8]) -> Option { - let pt = EncodedPoint::::from_bytes(bytes).ok()?; + let pt = EncodedPoint::::from_bytes(bytes).ok()?; Self::from_encoded_point(&pt).ok() } } -impl BeBytes for p256::Scalar { +impl BeBytes for Scalar { fn to_be_bytes(&self) -> Vec { self.to_bytes().to_vec() } fn from_be_bytes(bytes: &[u8]) -> Option { - let mut repr = p256::FieldBytes::default(); + let mut repr = FieldBytes::default(); repr.copy_from_slice(bytes); Option::from(Self::from_repr(repr)) } } -impl LeBytes for p256::Scalar {} +impl LeBytes for Scalar {} -impl CompressedBytes for p256::Scalar { +impl CompressedBytes for Scalar { fn to_compressed(&self) -> Vec { self.to_bytes().to_vec() } fn from_compressed(bytes: &[u8]) -> Option { - let mut repr = p256::FieldBytes::default(); + let mut repr = FieldBytes::default(); repr.copy_from_slice(bytes); Option::from(Self::from_repr(repr)) } } -impl BeBytes for p256::NonZeroScalar { +impl BeBytes for NonZeroScalar { fn to_be_bytes(&self) -> Vec { self.to_bytes().to_vec() } fn from_be_bytes(bytes: &[u8]) -> Option { - let mut repr = p256::FieldBytes::default(); + let mut repr = FieldBytes::default(); repr.copy_from_slice(bytes); Option::from(Self::from_repr(repr)) } } -impl LeBytes for p256::NonZeroScalar {} +impl LeBytes for NonZeroScalar {} -impl BeBytes for p256::ecdsa::SigningKey { +impl BeBytes for ecdsa::SigningKey { fn to_be_bytes(&self) -> Vec { self.as_nonzero_scalar().to_be_bytes() } fn from_be_bytes(bytes: &[u8]) -> Option { - let mut repr = p256::FieldBytes::default(); + let mut repr = FieldBytes::default(); repr.copy_from_slice(bytes); Self::from_bytes(&repr).ok() } } -impl LeBytes for p256::ecdsa::SigningKey {} +impl LeBytes for ecdsa::SigningKey {} diff --git a/rust/lit-node/lit-node-core/src/traits/encoding/p384.rs b/rust/lit-node/lit-node-core/src/traits/encoding/p384.rs index 5d7ee31..14d772c 100644 --- a/rust/lit-node/lit-node-core/src/traits/encoding/p384.rs +++ b/rust/lit-node/lit-node-core/src/traits/encoding/p384.rs @@ -1,17 +1,17 @@ use super::{BeBytes, CompressedBytes, LeBytes}; -use hd_keys_curves_wasm::p384; -use vsss_rs::elliptic_curve::{ - PrimeField, - sec1::{EncodedPoint, FromEncodedPoint, ToEncodedPoint}, +use lit_rust_crypto::{ + elliptic_curve::sec1::{EncodedPoint, FromEncodedPoint, ToEncodedPoint}, + ff::PrimeField, + p384::{AffinePoint, FieldBytes, NistP384, NonZeroScalar, ProjectivePoint, Scalar, ecdsa}, }; -impl CompressedBytes for p384::ProjectivePoint { +impl CompressedBytes for ProjectivePoint { fn to_compressed(&self) -> Vec { self.to_encoded_point(true).to_bytes().to_vec() } fn from_compressed(bytes: &[u8]) -> Option { - let pt = EncodedPoint::::from_bytes(bytes).ok()?; + let pt = EncodedPoint::::from_bytes(bytes).ok()?; Option::from(Self::from_encoded_point(&pt)) } fn to_uncompressed(&self) -> Vec { @@ -19,18 +19,18 @@ impl CompressedBytes for p384::ProjectivePoint { } fn from_uncompressed(bytes: &[u8]) -> Option { - let pt = EncodedPoint::::from_bytes(bytes).ok()?; + let pt = EncodedPoint::::from_bytes(bytes).ok()?; Option::from(Self::from_encoded_point(&pt)) } } -impl CompressedBytes for p384::AffinePoint { +impl CompressedBytes for AffinePoint { fn to_compressed(&self) -> Vec { self.to_encoded_point(true).to_bytes().to_vec() } fn from_compressed(bytes: &[u8]) -> Option { - let pt = EncodedPoint::::from_bytes(bytes).ok()?; + let pt = EncodedPoint::::from_bytes(bytes).ok()?; Option::from(Self::from_encoded_point(&pt)) } fn to_uncompressed(&self) -> Vec { @@ -38,18 +38,18 @@ impl CompressedBytes for p384::AffinePoint { } fn from_uncompressed(bytes: &[u8]) -> Option { - let pt = EncodedPoint::::from_bytes(bytes).ok()?; + let pt = EncodedPoint::::from_bytes(bytes).ok()?; Option::from(Self::from_encoded_point(&pt)) } } -impl CompressedBytes for p384::ecdsa::VerifyingKey { +impl CompressedBytes for ecdsa::VerifyingKey { fn to_compressed(&self) -> Vec { self.to_encoded_point(true).to_bytes().to_vec() } fn from_compressed(bytes: &[u8]) -> Option { - let pt = EncodedPoint::::from_bytes(bytes).ok()?; + let pt = EncodedPoint::::from_bytes(bytes).ok()?; Self::from_encoded_point(&pt).ok() } fn to_uncompressed(&self) -> Vec { @@ -57,61 +57,61 @@ impl CompressedBytes for p384::ecdsa::VerifyingKey { } fn from_uncompressed(bytes: &[u8]) -> Option { - let pt = EncodedPoint::::from_bytes(bytes).ok()?; + let pt = EncodedPoint::::from_bytes(bytes).ok()?; Self::from_encoded_point(&pt).ok() } } -impl BeBytes for p384::Scalar { +impl BeBytes for Scalar { fn to_be_bytes(&self) -> Vec { self.to_bytes().to_vec() } fn from_be_bytes(bytes: &[u8]) -> Option { - let mut repr = p384::FieldBytes::default(); + let mut repr = FieldBytes::default(); repr.copy_from_slice(bytes); Option::from(Self::from_repr(repr)) } } -impl LeBytes for p384::Scalar {} +impl LeBytes for Scalar {} -impl CompressedBytes for p384::Scalar { +impl CompressedBytes for Scalar { fn to_compressed(&self) -> Vec { self.to_bytes().to_vec() } fn from_compressed(bytes: &[u8]) -> Option { - let mut repr = p384::FieldBytes::default(); + let mut repr = FieldBytes::default(); repr.copy_from_slice(bytes); Option::from(Self::from_repr(repr)) } } -impl BeBytes for p384::NonZeroScalar { +impl BeBytes for NonZeroScalar { fn to_be_bytes(&self) -> Vec { self.to_bytes().to_vec() } fn from_be_bytes(bytes: &[u8]) -> Option { - let mut repr = p384::FieldBytes::default(); + let mut repr = FieldBytes::default(); repr.copy_from_slice(bytes); Option::from(Self::from_repr(repr)) } } -impl LeBytes for p384::NonZeroScalar {} +impl LeBytes for NonZeroScalar {} -impl BeBytes for p384::ecdsa::SigningKey { +impl BeBytes for ecdsa::SigningKey { fn to_be_bytes(&self) -> Vec { self.as_nonzero_scalar().to_be_bytes() } fn from_be_bytes(bytes: &[u8]) -> Option { - let mut repr = p384::FieldBytes::default(); + let mut repr = FieldBytes::default(); repr.copy_from_slice(bytes); Self::from_bytes(&repr).ok() } } -impl LeBytes for p384::ecdsa::SigningKey {} +impl LeBytes for ecdsa::SigningKey {} diff --git a/rust/lit-node/lit-node-core/src/traits/encoding/redjubjub.rs b/rust/lit-node/lit-node-core/src/traits/encoding/redjubjub.rs index 116ca2f..bf0eda8 100644 --- a/rust/lit-node/lit-node-core/src/traits/encoding/redjubjub.rs +++ b/rust/lit-node/lit-node-core/src/traits/encoding/redjubjub.rs @@ -1,14 +1,17 @@ use super::{BeBytes, CompressedBytes, LeBytes}; -use hd_keys_curves_wasm::jubjub; -use vsss_rs::elliptic_curve::{PrimeField, group::GroupEncoding}; +use lit_rust_crypto::{ + ff::PrimeField, + group::GroupEncoding, + jubjub::{Scalar, SubgroupPoint}, +}; -impl CompressedBytes for jubjub::SubgroupPoint { +impl CompressedBytes for SubgroupPoint { fn to_compressed(&self) -> Vec { self.to_bytes().to_vec() } fn from_compressed(bytes: &[u8]) -> Option { - let mut repr = ::Repr::default(); + let mut repr = ::Repr::default(); if bytes.len() != repr.len() { return None; } @@ -17,7 +20,7 @@ impl CompressedBytes for jubjub::SubgroupPoint { } } -impl BeBytes for jubjub::Scalar { +impl BeBytes for Scalar { fn to_be_bytes(&self) -> Vec { let mut bytes = self.to_bytes(); bytes.reverse(); @@ -27,31 +30,31 @@ impl BeBytes for jubjub::Scalar { fn from_be_bytes(bytes: &[u8]) -> Option { let mut bytes = bytes.to_vec(); bytes.reverse(); - let mut repr = ::Repr::default(); + let mut repr = ::Repr::default(); repr.copy_from_slice(bytes.as_slice()); Option::from(Self::from_repr(repr)) } } -impl LeBytes for jubjub::Scalar { +impl LeBytes for Scalar { fn to_le_bytes(&self) -> Vec { self.to_bytes().to_vec() } fn from_le_bytes(bytes: &[u8]) -> Option { - let mut repr = ::Repr::default(); + let mut repr = ::Repr::default(); repr.copy_from_slice(bytes); Option::from(Self::from_repr(repr)) } } -impl CompressedBytes for jubjub::Scalar { +impl CompressedBytes for Scalar { fn to_compressed(&self) -> Vec { self.to_bytes().to_vec() } fn from_compressed(bytes: &[u8]) -> Option { - let mut repr = ::Repr::default(); + let mut repr = ::Repr::default(); repr.copy_from_slice(bytes); Option::from(Self::from_repr(repr)) } diff --git a/rust/lit-node/lit-node-core/src/traits/encoding/redpallas.rs b/rust/lit-node/lit-node-core/src/traits/encoding/redpallas.rs new file mode 100644 index 0000000..db5bee5 --- /dev/null +++ b/rust/lit-node/lit-node-core/src/traits/encoding/redpallas.rs @@ -0,0 +1,50 @@ +use super::{BeBytes, CompressedBytes, LeBytes}; +use lit_rust_crypto::{ + group::GroupEncoding, + pallas::{Point, Scalar}, +}; + +impl CompressedBytes for Point { + fn to_compressed(&self) -> Vec { + self.to_bytes().to_vec() + } + + fn from_compressed(bytes: &[u8]) -> Option { + let mut repr = ::Repr::default(); + if repr.len() != bytes.len() { + return None; + } + repr.copy_from_slice(bytes); + Option::from(Self::from_bytes(&repr)) + } +} + +impl BeBytes for Scalar { + fn to_be_bytes(&self) -> Vec { + self.to_be_bytes().to_vec() + } + + fn from_be_bytes(bytes: &[u8]) -> Option { + Option::from(Self::from_be_bytes(&bytes.try_into().ok()?)) + } +} + +impl LeBytes for Scalar { + fn to_le_bytes(&self) -> Vec { + self.to_le_bytes().to_vec() + } + + fn from_le_bytes(bytes: &[u8]) -> Option { + Option::from(Self::from_le_bytes(bytes.try_into().ok()?)) + } +} + +impl CompressedBytes for Scalar { + fn to_compressed(&self) -> Vec { + self.to_le_bytes().to_vec() + } + + fn from_compressed(bytes: &[u8]) -> Option { + Option::from(Self::from_le_bytes(bytes.try_into().ok()?)) + } +} diff --git a/rust/lit-node/lit-node/Cargo.toml b/rust/lit-node/lit-node/Cargo.toml index 2f4e302..3265720 100644 --- a/rust/lit-node/lit-node/Cargo.toml +++ b/rust/lit-node/lit-node/Cargo.toml @@ -36,17 +36,13 @@ async-std.workspace = true async-trait.workspace = true base64_light = "0.1" bech32 = "0.11" -blsful.workspace = true -blstrs_plus = { version = "0.8", features = ["serde"] } bulletproofs.workspace = true bs58 = "0.5.0" -cc = "1.2.22" +#cc = "1.2.34" ciborium = { version = "0.2" } chrono = "0.4" clap = { version = "4.5", features = ["cargo"] } -curve25519-dalek.workspace = true data-encoding.workspace = true -decaf377.workspace = true derive_builder = "0.20" derive_more.workspace = true digest = { version = "0.10", default-features = false, features = [ @@ -56,47 +52,35 @@ digest = { version = "0.10", default-features = false, features = [ dotenv = "0.15.0" ecdsa = { version = "0.16", features = ["arithmetic"] } ed25519-dalek.workspace = true -ed448-goldilocks.workspace = true -elliptic-curve.workspace = true ethabi.workspace = true ethers.workspace = true flume = "0.11" -frost-dkg = "0.3.3" +frost-dkg = "0.5.1" futures = "0.3" glob = "0.3.1" -hd-keys-curves = { git = "https://github.com/LIT-Protocol/hd-keys-curves-wasm", package = "hd-keys-curves-wasm", rev = "5e0dcc1a6d8d08f2328d4716dca806db87f93748", default-features = false, features = [ - "bls", - "k256", - "p256", - "p384", - "curve25519", - "ed448", - "jubjub", - "decaf377", -] } hex.workspace = true hex-literal = "0.4" indicatif = "=0.15" ipfs-hasher = "0.13.0" iri-string = "0.6" jsonpath-plus = "0.1.9" -jubjub.workspace = true -k256 = { version = "0.13", features = [ +lazy_static = "1.5.0" +libaes = { version = "0.7", optional = true } +libsecp256k1 = { git = "https://github.com/LIT-Protocol/libsecp256k1", branch = "master", version = "0.7.1" } +lit-fast-ecdsa = { path = "../../lit-core/lit-fast-ecdsa" } +lit-frost.workspace = true +lit-node-core = { path = "../lit-node-core" } +lit-rust-crypto = { workspace = true, features = [ "arithmetic", - "sha256", + "default", "ecdsa", - "serde", "ecdsa-core", "expose-field", "hash2curve", "schnorr", -], optional = false } -lazy_static = "1.5.0" -libaes = { version = "0.7", optional = true } -libsecp256k1 = { git = "https://github.com/LIT-Protocol/libsecp256k1", branch = "master", version = "0.7.1" } -lit-fast-ecdsa = { path = "../../lit-core/lit-fast-ecdsa" } -lit-frost = { git = "https://github.com/LIT-Protocol/lit-frost.git" } -lit-node-core = { path = "../lit-node-core" } + "sha", + "serde" +] } lit-sdk = { path = "../lit-sdk" } lit-vrf = { path = "../../lit-core/lit-vrf" } moka = { version = "0.12.7", features = ["future"] } @@ -115,22 +99,10 @@ rocket_cors = { version = "0.6.0" } # used to verify JWTs. must match the version in the crate overrides at the bottom of this file rsa = { git = "https://github.com/RustCrypto/RSA", tag = "v0.7.0-pre" } rusqlite = { version = "0.32.0", features = ["backup"] } -p256 = { version = "0.13", features = [ - "arithmetic", - "ecdsa-core", - "expose-field", - "hash2curve", - "sha256", - "serde", -], optional = false } -p384 = { version = "0.13", features = [ - "arithmetic", - "serde", -], optional = false } postcard = { version = "1.1.1", features = ["use-std"] } prost = "0.13" ripemd = "0.1.3" -scc = "2" +scc.workspace = true sdd.workspace = true semver = "1.0.22" serde.workspace = true @@ -160,9 +132,8 @@ tracing-opentelemetry = { version = "0.25" } tracing-subscriber = { version = "0.3" } ucan-capabilities-object = "0.1" url.workspace = true -verifiable-share-encryption = { version = "0.3.0", git = "https://github.com/LIT-Protocol/verifiable-share-encryption", rev = "7eddfbe736369db596d0f302c72f1d76b0fd332d" } +verifiable-share-encryption = { git = "https://github.com/LIT-Protocol/verifiable-share-encryption", branch = "pallas" } visibility = "0.1.1" -vsss-rs.workspace = true web3 = "0.19.0" webauthn-rs-core = { git = "https://github.com/LIT-Protocol/webauthn-rs" } webauthn-rs-proto = { git = "https://github.com/LIT-Protocol/webauthn-rs" } diff --git a/rust/lit-node/lit-node/src/access_control/cosmos.rs b/rust/lit-node/lit-node/src/access_control/cosmos.rs index fe1ff52..36597dd 100644 --- a/rust/lit-node/lit-node/src/access_control/cosmos.rs +++ b/rust/lit-node/lit-node/src/access_control/cosmos.rs @@ -402,19 +402,18 @@ async fn check_return_value( // need to check the type here. because if this is a string, we can concatenate for the "contains" operator. i suppose we shouldn't do that if it's a number. if filtered_vals.len() > 1 && condition.return_value_test.comparator == "contains" + && let serde_json::Value::String(_) = value_to_check { - if let serde_json::Value::String(_) = value_to_check { - // it's a string. concate all items - let mut concatenated_string = String::new(); - for item in filtered_vals { - concatenated_string.push_str( - item.as_str() - .expect_or_err("could not get string from item")?, - ); - concatenated_string.push(' '); - } - value_to_check = serde_json::Value::String(concatenated_string); + // it's a string. concate all items + let mut concatenated_string = String::new(); + for item in filtered_vals { + concatenated_string.push_str( + item.as_str() + .expect_or_err("could not get string from item")?, + ); + concatenated_string.push(' '); } + value_to_check = serde_json::Value::String(concatenated_string); } } } diff --git a/rust/lit-node/lit-node/src/access_control/evm_contract.rs b/rust/lit-node/lit-node/src/access_control/evm_contract.rs index b55740e..9602ac6 100644 --- a/rust/lit-node/lit-node/src/access_control/evm_contract.rs +++ b/rust/lit-node/lit-node/src/access_control/evm_contract.rs @@ -1,4 +1,4 @@ -use super::{rpc_call, substitute_special_params, validate_boolean_expression}; +use super::{eval_condition, rpc_call, substitute_special_params, validate_boolean_expression}; use crate::auth::auth_material::JsonAuthSigExtendedRef; use crate::error::{EC, Result, conversion_err_code, validation_err, validation_err_code}; use crate::utils::encoding; @@ -345,22 +345,11 @@ fn check_return_value_bool(condition: &EVMContractCondition, returned_value: boo returned_value, condition.return_value_test.comparator, valid_return_value ); - if condition.return_value_test.comparator == ">" { - Ok(returned_value > valid_return_value) - } else if condition.return_value_test.comparator == "<" { - return Ok(returned_value < valid_return_value); - } else if condition.return_value_test.comparator == ">=" { - return Ok(returned_value >= valid_return_value); - } else if condition.return_value_test.comparator == "<=" { - return Ok(returned_value <= valid_return_value); - } else if condition.return_value_test.comparator == "=" { - return Ok(returned_value == valid_return_value); - } else if condition.return_value_test.comparator == "!=" { - return Ok(returned_value != valid_return_value); - } else { - warn!("Error - unsupported return value test comparator"); - return Ok(false); - } + Ok(eval_condition( + &condition.return_value_test.comparator, + returned_value, + valid_return_value, + )) } fn check_return_value_string( @@ -376,24 +365,11 @@ fn check_return_value_string( returned_value, condition.return_value_test.comparator, valid_return_value ); - if condition.return_value_test.comparator == ">" { - Ok(returned_value > valid_return_value) - } else if condition.return_value_test.comparator == "<" { - return Ok(returned_value < valid_return_value); - } else if condition.return_value_test.comparator == ">=" { - return Ok(returned_value >= valid_return_value); - } else if condition.return_value_test.comparator == "<=" { - return Ok(returned_value <= valid_return_value); - } else if condition.return_value_test.comparator == "=" { - return Ok(returned_value == valid_return_value); - } else if condition.return_value_test.comparator == "!=" { - return Ok(returned_value != valid_return_value); - } else if condition.return_value_test.comparator == "contains" { - return Ok(returned_value.contains(&valid_return_value)); - } else { - warn!("Error - unsupported return value test comparator"); - return Ok(false); - } + Ok(eval_condition( + &condition.return_value_test.comparator, + returned_value, + valid_return_value, + )) } // fn check_return_value_int( @@ -447,22 +423,11 @@ fn check_return_value_uint(condition: &EVMContractCondition, returned_value: U25 returned_value, condition.return_value_test.comparator, valid_return_value ); - if condition.return_value_test.comparator == ">" { - Ok(returned_value > valid_return_value) - } else if condition.return_value_test.comparator == "<" { - return Ok(returned_value < valid_return_value); - } else if condition.return_value_test.comparator == ">=" { - return Ok(returned_value >= valid_return_value); - } else if condition.return_value_test.comparator == "<=" { - return Ok(returned_value <= valid_return_value); - } else if condition.return_value_test.comparator == "=" { - return Ok(returned_value == valid_return_value); - } else if condition.return_value_test.comparator == "!=" { - return Ok(returned_value != valid_return_value); - } else { - warn!("Error - unsupported return value test comparator"); - return Ok(false); - } + Ok(eval_condition( + &condition.return_value_test.comparator, + returned_value, + valid_return_value, + )) } async fn check_return_value_addr( @@ -491,20 +456,9 @@ async fn check_return_value_addr( returned_value, condition.return_value_test.comparator, valid_return_value ); - if condition.return_value_test.comparator == ">" { - Ok(returned_value > valid_return_value) - } else if condition.return_value_test.comparator == "<" { - return Ok(returned_value < valid_return_value); - } else if condition.return_value_test.comparator == ">=" { - return Ok(returned_value >= valid_return_value); - } else if condition.return_value_test.comparator == "<=" { - return Ok(returned_value <= valid_return_value); - } else if condition.return_value_test.comparator == "=" { - return Ok(returned_value == valid_return_value); - } else if condition.return_value_test.comparator == "!=" { - return Ok(returned_value != valid_return_value); - } else { - warn!("Error - unsupported return value test comparator"); - return Ok(false); - } + Ok(eval_condition( + &condition.return_value_test.comparator, + returned_value, + valid_return_value, + )) } diff --git a/rust/lit-node/lit-node/src/access_control/mod.rs b/rust/lit-node/lit-node/src/access_control/mod.rs index 3fcb8c9..7ffa2f9 100644 --- a/rust/lit-node/lit-node/src/access_control/mod.rs +++ b/rust/lit-node/lit-node/src/access_control/mod.rs @@ -544,10 +544,10 @@ async fn check_condition_via_poap( return Ok(true); } } - return Ok(false); + Ok(false) } else { warn!("Unsupported method for contract ABI: {}", condition.method); - return Ok(false); + Ok(false) } } @@ -861,7 +861,7 @@ async fn check_condition_via_contract_call( Ok(false) } } else if condition.standard_contract_type == "ERC1155" { - return if condition.method == "balanceOf" { + if condition.method == "balanceOf" { let subbed_param = substitute_special_params( &condition.parameters[0], auth_sig, @@ -967,7 +967,7 @@ async fn check_condition_via_contract_call( } else { warn!("Unsupported method for contract ABI"); Ok(false) - }; + } } else if condition.standard_contract_type == "ERC721" { return if condition.method == "ownerOf" { let token_id = match U256::from_dec_str(&condition.parameters[0]) { @@ -1025,7 +1025,7 @@ async fn check_condition_via_contract_call( Ok(false) }; } else if condition.standard_contract_type == "ERC20" { - return if condition.method == "balanceOf" { + if condition.method == "balanceOf" { let subbed_param = substitute_special_params( &condition.parameters[0], auth_sig, @@ -1050,9 +1050,9 @@ async fn check_condition_via_contract_call( } else { warn!("Unsupported method for contract ABI"); Ok(false) - }; + } } else if condition.standard_contract_type == "MolochDAOv2.1" { - return if condition.method == "members" { + if condition.method == "members" { let subbed_param = substitute_special_params( &condition.parameters[0], auth_sig, @@ -1085,9 +1085,9 @@ async fn check_condition_via_contract_call( } else { warn!("Unsupported method for contract ABI"); Ok(false) - }; + } } else if condition.standard_contract_type == "Creaton" { - return if condition.method == "subscribers" { + if condition.method == "subscribers" { let subbed_param = substitute_special_params( &condition.parameters[0], auth_sig, @@ -1114,9 +1114,9 @@ async fn check_condition_via_contract_call( } else { warn!("Unsupported method for contract ABI"); Ok(false) - }; + } } else if condition.standard_contract_type == "ProofOfHumanity" { - return if condition.method == "isRegistered" { + if condition.method == "isRegistered" { let subbed_param = substitute_special_params( &condition.parameters[0], auth_sig, @@ -1141,9 +1141,9 @@ async fn check_condition_via_contract_call( } else { warn!("Unsupported method for contract ABI"); Ok(false) - }; + } } else if condition.standard_contract_type == "CASK" { - return if condition.method == "getActiveSubscriptionCount" { + if condition.method == "getActiveSubscriptionCount" { let subbed_param = substitute_special_params( &condition.parameters[0], auth_sig, @@ -1191,10 +1191,10 @@ async fn check_condition_via_contract_call( } else { warn!("Unsupported method for contract ABI"); Ok(false) - }; + } } else { warn!("Error - unsupported access control condition method on contract."); - return Ok(false); + Ok(false) } } @@ -1218,18 +1218,18 @@ fn check_return_value_bool( if condition.return_value_test.comparator == ">" { Ok(returned_value > valid_return_value) } else if condition.return_value_test.comparator == "<" { - return Ok(returned_value < valid_return_value); + Ok(returned_value < valid_return_value) } else if condition.return_value_test.comparator == ">=" { - return Ok(returned_value >= valid_return_value); + Ok(returned_value >= valid_return_value) } else if condition.return_value_test.comparator == "<=" { - return Ok(returned_value <= valid_return_value); + Ok(returned_value <= valid_return_value) } else if condition.return_value_test.comparator == "=" { - return Ok(returned_value == valid_return_value); + Ok(returned_value == valid_return_value) } else if condition.return_value_test.comparator == "!=" { - return Ok(returned_value != valid_return_value); + Ok(returned_value != valid_return_value) } else { warn!("Error - unsupported return value test comparator"); - return Ok(false); + Ok(false) } } @@ -1258,18 +1258,18 @@ fn check_return_value_int( if condition.return_value_test.comparator == ">" { Ok(returned_value > valid_return_value) } else if condition.return_value_test.comparator == "<" { - return Ok(returned_value < valid_return_value); + Ok(returned_value < valid_return_value) } else if condition.return_value_test.comparator == ">=" { - return Ok(returned_value >= valid_return_value); + Ok(returned_value >= valid_return_value) } else if condition.return_value_test.comparator == "<=" { - return Ok(returned_value <= valid_return_value); + Ok(returned_value <= valid_return_value) } else if condition.return_value_test.comparator == "=" { - return Ok(returned_value == valid_return_value); + Ok(returned_value == valid_return_value) } else if condition.return_value_test.comparator == "!=" { - return Ok(returned_value != valid_return_value); + Ok(returned_value != valid_return_value) } else { warn!("Error - unsupported return value test comparator"); - return Ok(false); + Ok(false) } } @@ -1300,16 +1300,16 @@ async fn check_return_value_addr( if condition.return_value_test.comparator == ">" { Ok(returned_value > valid_return_value) } else if condition.return_value_test.comparator == "<" { - return Ok(returned_value < valid_return_value); + Ok(returned_value < valid_return_value) } else if condition.return_value_test.comparator == ">=" { - return Ok(returned_value >= valid_return_value); + Ok(returned_value >= valid_return_value) } else if condition.return_value_test.comparator == "<=" { - return Ok(returned_value <= valid_return_value); + Ok(returned_value <= valid_return_value) } else if condition.return_value_test.comparator == "=" { - return Ok(returned_value == valid_return_value); + Ok(returned_value == valid_return_value) } else { warn!("Error - unsupported return value test comparator"); - return Ok(false); + Ok(false) } } @@ -1328,22 +1328,22 @@ fn check_return_value_str( if condition.return_value_test.comparator == ">" { Ok(returned_value > valid_return_value) } else if condition.return_value_test.comparator == "<" { - return Ok(returned_value < valid_return_value); + Ok(returned_value < valid_return_value) } else if condition.return_value_test.comparator == ">=" { - return Ok(returned_value >= valid_return_value); + Ok(returned_value >= valid_return_value) } else if condition.return_value_test.comparator == "<=" { - return Ok(returned_value <= valid_return_value); + Ok(returned_value <= valid_return_value) } else if condition.return_value_test.comparator == "=" { - return Ok(returned_value == valid_return_value); + Ok(returned_value == valid_return_value) } else if condition.return_value_test.comparator == "!=" { - return Ok(returned_value != valid_return_value); + Ok(returned_value != valid_return_value) } else if condition.return_value_test.comparator == "contains" { - return Ok(returned_value.contains(&valid_return_value)); + Ok(returned_value.contains(&valid_return_value)) } else if condition.return_value_test.comparator == "!contains" { - return Ok(!returned_value.contains(&valid_return_value)); + Ok(!returned_value.contains(&valid_return_value)) } else { warn!("Error - unsupported return value test comparator"); - return Ok(false); + Ok(false) } } @@ -1363,10 +1363,10 @@ fn check_return_value_array( if condition.return_value_test.comparator == "contains" { Ok(returned_values.contains(&valid_return_value)) } else if condition.return_value_test.comparator == "!contains" { - return Ok(!returned_values.contains(&valid_return_value)); + Ok(!returned_values.contains(&valid_return_value)) } else { warn!("Error - unsupported return value test comparator"); - return Ok(false); + Ok(false) } } @@ -1554,3 +1554,25 @@ mod tests { ])); } } + +pub(crate) fn eval_condition

(comparator: &str, returned_value: P, valid_return_value: P) -> bool +where + P: Sized + Ord + PartialOrd + Eq + PartialEq, +{ + if comparator == ">" { + returned_value > valid_return_value + } else if comparator == "<" { + returned_value < valid_return_value + } else if comparator == ">=" { + returned_value >= valid_return_value + } else if comparator == "<=" { + returned_value <= valid_return_value + } else if comparator == "=" { + returned_value == valid_return_value + } else if comparator == "!=" { + returned_value != valid_return_value + } else { + warn!("Error - unsupported return value test comparator"); + false + } +} diff --git a/rust/lit-node/lit-node/src/access_control/sol_rpc.rs b/rust/lit-node/lit-node/src/access_control/sol_rpc.rs index 5aed85f..a4b5ad6 100644 --- a/rust/lit-node/lit-node/src/access_control/sol_rpc.rs +++ b/rust/lit-node/lit-node/src/access_control/sol_rpc.rs @@ -19,7 +19,7 @@ use std::collections::HashMap; use std::result::Result as StdResult; use std::str::FromStr; -use super::{substitute_special_params, validate_boolean_expression}; +use super::{eval_condition, substitute_special_params, validate_boolean_expression}; const VALID_CHAIN_NAMES: [&str; 3] = ["solana", "solanaDevnet", "solanaTestnet"]; @@ -468,22 +468,11 @@ fn check_return_value_uint(condition: &SolRpcConditionV2, returned_value: u64) - returned_value, condition.return_value_test.comparator, valid_return_value ); - if condition.return_value_test.comparator == ">" { - Ok(returned_value > valid_return_value) - } else if condition.return_value_test.comparator == "<" { - return Ok(returned_value < valid_return_value); - } else if condition.return_value_test.comparator == ">=" { - return Ok(returned_value >= valid_return_value); - } else if condition.return_value_test.comparator == "<=" { - return Ok(returned_value <= valid_return_value); - } else if condition.return_value_test.comparator == "=" { - return Ok(returned_value == valid_return_value); - } else if condition.return_value_test.comparator == "!=" { - return Ok(returned_value != valid_return_value); - } else { - warn!("Error - unsupported return value test comparator"); - return Ok(false); - } + Ok(eval_condition( + &condition.return_value_test.comparator, + returned_value, + valid_return_value, + )) } async fn check_return_value_string( @@ -511,18 +500,18 @@ async fn check_return_value_string( if condition.return_value_test.comparator == ">" { Ok(returned_value > valid_return_value) } else if condition.return_value_test.comparator == "<" { - return Ok(returned_value < valid_return_value); + Ok(returned_value < valid_return_value) } else if condition.return_value_test.comparator == ">=" { - return Ok(returned_value >= valid_return_value); + Ok(returned_value >= valid_return_value) } else if condition.return_value_test.comparator == "<=" { - return Ok(returned_value <= valid_return_value); + Ok(returned_value <= valid_return_value) } else if condition.return_value_test.comparator == "=" { - return Ok(returned_value == valid_return_value); + Ok(returned_value == valid_return_value) } else if condition.return_value_test.comparator == "!=" { - return Ok(returned_value != valid_return_value); + Ok(returned_value != valid_return_value) } else { warn!("Error - unsupported return value test comparator"); - return Ok(false); + Ok(false) } } @@ -596,10 +585,11 @@ fn check_balance_of_metaplex_collection( .to_string(); let metadata_result = get_metaplex_metadata(condition, token_address.clone()); if let Ok(metadata) = metadata_result { - if let Some(collection) = metadata.collection { - if collection.verified && collection.key == collection_address { - verified_token_count += 1; - } + if let Some(collection) = metadata.collection + && collection.verified + && collection.key == collection_address + { + verified_token_count += 1; } } else { debug!("Could not get metadata for {} - skipping", token_address); @@ -748,11 +738,11 @@ async fn check_balance_of_token( message, data, }) = &err.kind + && *code == -32602 + && message == "Invalid param: could not find account" { - if *code == -32602 && message == "Invalid param: could not find account" { - // the balance is zero, we couldn't find the acct. return false. - return Ok(false); - } + // the balance is zero, we couldn't find the acct. return false. + return Ok(false); } Err(validation_err_code( diff --git a/rust/lit-node/lit-node/src/auth/capabilities/recap.rs b/rust/lit-node/lit-node/src/auth/capabilities/recap.rs index 34dbd54..8b737b5 100644 --- a/rust/lit-node/lit-node/src/auth/capabilities/recap.rs +++ b/rust/lit-node/lit-node/src/auth/capabilities/recap.rs @@ -35,17 +35,17 @@ pub fn extract_and_verify_all_capabilities( // i do not understand how this verifies it // but it's what the siwe-recap crate does let expected = capability.to_statement(); - if let Some(statement) = &siwe_message.statement { - if !statement.ends_with(&expected) { - return Err(parser_err_code( - format!( - "Incorrect statement for capability object: expected '{}', got '{}'", - expected, statement - ), - EC::NodeSIWECapabilityInvalid, - None, - )); - } + if let Some(statement) = &siwe_message.statement + && !statement.ends_with(&expected) + { + return Err(parser_err_code( + format!( + "Incorrect statement for capability object: expected '{}', got '{}'", + expected, statement + ), + EC::NodeSIWECapabilityInvalid, + None, + )); } } diff --git a/rust/lit-node/lit-node/src/auth/validators/siwe.rs b/rust/lit-node/lit-node/src/auth/validators/siwe.rs index 5ab8a29..dd50d80 100644 --- a/rust/lit-node/lit-node/src/auth/validators/siwe.rs +++ b/rust/lit-node/lit-node/src/auth/validators/siwe.rs @@ -1,5 +1,5 @@ -use blsful::Bls12381G2Impl; use ethers::types::Address; +use lit_rust_crypto::blsful::{Bls12381G2Impl, PublicKey, Signature}; use rocket::time::OffsetDateTime; use siwe::{Message, VerificationOpts}; use tracing::debug; @@ -122,10 +122,10 @@ impl CapabilityAuthSigValidator for SiweValidator { }; let signed_data = siwe_hash_to_bls_session_hash(siwe_hash.into()); - let signature: blsful::Signature = serde_json::from_str(&auth_sig.sig) + let signature: Signature = serde_json::from_str(&auth_sig.sig) .map_err(|err| parser_err_code(err, EC::NodeSIWESigConversionError, None))?; - let bls_root_key = blsful::PublicKey::::try_from( + let bls_root_key = PublicKey::::try_from( &hex::decode(bls_root_pubkey).expect("Failed to decode root key"), ) .expect("Failed to convert bls public key from bytes"); @@ -257,10 +257,10 @@ impl SessionSigAuthSigValidator for SiweValidator { }; let signed_data = siwe_hash_to_bls_session_hash(siwe_hash.into()); - let signature: blsful::Signature = serde_json::from_str(&auth_sig.sig) + let signature: Signature = serde_json::from_str(&auth_sig.sig) .map_err(|err| parser_err_code(err, EC::NodeSIWESigConversionError, None))?; - let bls_root_key = blsful::PublicKey::::try_from( + let bls_root_key = PublicKey::::try_from( &hex::decode(bls_root_pubkey).expect("Failed to decode root key"), ) .expect("Failed to convert bls public key from bytes"); diff --git a/rust/lit-node/lit-node/src/common/key_helper.rs b/rust/lit-node/lit-node/src/common/key_helper.rs index 0328b69..6db0f4e 100644 --- a/rust/lit-node/lit-node/src/common/key_helper.rs +++ b/rust/lit-node/lit-node/src/common/key_helper.rs @@ -65,8 +65,9 @@ impl Default for KeyCache { impl Debug for KeyCache { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { let mut entries = Vec::with_capacity(self.0.len()); - self.0.scan(|key, value| { + self.0.iter_sync(|key, value| { entries.push(key.clone()); + true }); write!(f, "KeyCache {{ {:#?} }}", entries) } @@ -75,8 +76,9 @@ impl Debug for KeyCache { impl Display for KeyCache { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { let mut entries = Vec::with_capacity(self.0.len()); - self.0.scan(|key, value| { + self.0.iter_sync(|key, value| { entries.push(key.clone()); + true }); write!(f, "KeyCache {{ {} }}", entries.join(", ")) } diff --git a/rust/lit-node/lit-node/src/endpoints/admin/utils.rs b/rust/lit-node/lit-node/src/endpoints/admin/utils.rs index b895b46..ff5eaf2 100644 --- a/rust/lit-node/lit-node/src/endpoints/admin/utils.rs +++ b/rust/lit-node/lit-node/src/endpoints/admin/utils.rs @@ -14,17 +14,21 @@ use crate::tss::common::storage::{ }; use async_std::fs; use async_std::path::{Path, PathBuf}; -use blsful::inner_types::{G1Projective, GroupEncoding, InnerBls12381G1}; use bulletproofs::BulletproofCurveArithmetic as BCA; use chrono::{DateTime, Utc}; -use elliptic_curve::Group; use k256::Secp256k1; use lit_core::config::LitConfig; use lit_core::error::Unexpected; use lit_node_common::config::{LitNodeConfig, encrypted_key_path}; -use lit_node_core::CurveType; -use lit_node_core::JsonAuthSig; +use lit_node_core::{CurveType, JsonAuthSig}; use lit_recovery::models::{EncryptedKeyShare, OldEncryptedKeyShare}; +use lit_rust_crypto::{ + blsful::inner_types::{G1Projective, GroupEncoding, InnerBls12381G1}, + decaf377, ed448_goldilocks, + elliptic_curve::ScalarPrimitive, + group::Group, + jubjub, k256, p256, p384, pallas, vsss_rs, +}; use std::collections::HashMap; use std::sync::Arc; use tokio::io::{AsyncRead, AsyncReadExt}; @@ -291,6 +295,22 @@ pub(crate) async fn encrypt_and_tar_backup_keys( .await }); + let args = write_curve_recovery_data_args.clone(); + let pallas_encryption_key = recovery_party.pallas_encryption_key; + let pallas_blinder = blinders + .pallas_blinder + .ok_or(blinder_not_set_err(CurveType::RedPallas))?; + tasks.spawn(async move { + write_curve_recovery_data::( + args, + CurveType::RedPallas, + &pallas_encryption_key, + &pallas_blinder, + &(pallas::Point::generator() * pallas_blinder), + ) + .await + }); + while let Some(result) = tasks.join_next().await { match result { Ok(Ok(())) => {} @@ -440,7 +460,7 @@ pub(crate) async fn untar_keys_stream( blinders.bls_blinder, G1Projective::GENERATOR, CurveType::BLS, - &path.clone(), + &path, &key_cache, ) .await?; @@ -449,7 +469,7 @@ pub(crate) async fn untar_keys_stream( blinders.k256_blinder, k256::ProjectivePoint::GENERATOR, CurveType::K256, - &path.clone(), + &path, &key_cache, ) .await?; @@ -458,7 +478,7 @@ pub(crate) async fn untar_keys_stream( blinders.p256_blinder, p256::ProjectivePoint::GENERATOR, CurveType::P256, - &path.clone(), + &path, &key_cache, ) .await?; @@ -467,7 +487,7 @@ pub(crate) async fn untar_keys_stream( blinders.p384_blinder, p384::ProjectivePoint::GENERATOR, CurveType::P384, - &path.clone(), + &path, &key_cache, ) .await?; @@ -476,7 +496,7 @@ pub(crate) async fn untar_keys_stream( blinders.ed25519_blinder, vsss_rs::curve25519::WrappedEdwards::generator(), CurveType::Ed25519, - &path.clone(), + &path, &key_cache, ) .await?; @@ -485,7 +505,7 @@ pub(crate) async fn untar_keys_stream( blinders.ristretto25519_blinder, vsss_rs::curve25519::WrappedRistretto::generator(), CurveType::Ristretto25519, - &path.clone(), + &path, &key_cache, ) .await?; @@ -494,7 +514,7 @@ pub(crate) async fn untar_keys_stream( blinders.ed448_blinder, ed448_goldilocks::EdwardsPoint::GENERATOR, CurveType::Ed448, - &path.clone(), + &path, &key_cache, ) .await?; @@ -503,7 +523,16 @@ pub(crate) async fn untar_keys_stream( blinders.jubjub_blinder, jubjub::SubgroupPoint::generator(), CurveType::RedJubjub, - &path.clone(), + &path, + &key_cache, + ) + .await?; + + let pallas_recovery_data = read_curve_recovery_data::( + blinders.pallas_blinder, + pallas::Point::generator(), + CurveType::RedPallas, + &path, &key_cache, ) .await?; @@ -538,6 +567,7 @@ pub(crate) async fn untar_keys_stream( jubjub_recovery_data, decaf377_recovery_data, bls12381g1_recovery_data, + pallas_recovery_data, threshold, restored_key_cache: KeyCache::default(), }; @@ -825,10 +855,10 @@ fn parse_bls_blinder(blinder_str: &str) -> Result<::Scal match blinder.into_option() { Some(blinder) => Ok(blinder), None => Err(parser_err( - std::io::Error::new( - std::io::ErrorKind::Other, - format!("Could not convert to bls key blinder:{}", blinder_str), - ), + std::io::Error::other(format!( + "Could not convert to bls key blinder:{}", + blinder_str + )), None, )), } @@ -839,17 +869,16 @@ fn parse_k256_blinder(blinder_str: &str) -> Result<::Scalar> { // This is the error closure so we don't repeat it in the code. let error = |blinder_str| { parser_err( - std::io::Error::new( - std::io::ErrorKind::Other, - format!("Could not convert to ecdsa key blinder:{}", blinder_str), - ), + std::io::Error::other(format!( + "Could not convert to ecdsa key blinder:{}", + blinder_str + )), None, ) }; let bytes = hex::decode(blinder_str).map_err(|e| error(blinder_str))?; - let scalar_primitive = elliptic_curve::scalar::ScalarPrimitive::from_slice(&bytes) - .map_err(|e| error(blinder_str))?; + let scalar_primitive = ScalarPrimitive::from_slice(&bytes).map_err(|e| error(blinder_str))?; Ok(k256::Scalar::from(&scalar_primitive)) } @@ -873,21 +902,26 @@ mod test { use crate::tss::common::storage::{ read_key_share_from_disk, write_key_share_commitments_to_disk, write_key_share_to_disk, }; - use blsful::{ - Bls12381G1Impl, SecretKeyShare, - inner_types::{G1Projective, InnerBls12381G1}, - }; use bulletproofs::BulletproofCurveArithmetic as BCA; - use elliptic_curve::{Field, Group, PrimeField}; - use k256::{ProjectivePoint, PublicKey, Secp256k1}; - use lit_node_core::CurveType; - use lit_node_core::PeerId; + use lit_node_core::{CurveType, PeerId}; use lit_recovery::models::{EncryptedKeyShare, UploadedShareData}; + use lit_rust_crypto::vsss_rs::{DefaultShare, IdentifierPrimeField, ValuePrimeField}; + use lit_rust_crypto::{ + blsful::{ + Bls12381G1Impl, SecretKeyShare, + inner_types::{G1Projective, InnerBls12381G1}, + }, + decaf377, ed448_goldilocks, + ff::{Field, PrimeField}, + group::Group, + jubjub, + k256::{FieldBytes, ProjectivePoint, PublicKey, Scalar, Secp256k1}, + p256, p384, pallas, vsss_rs, + }; use semver::Version; use std::sync::Arc; use tokio::fs; use verifiable_share_encryption::DecryptionShare; - use vsss_rs::{DefaultShare, IdentifierPrimeField, ValuePrimeField}; #[tokio::test] async fn run_backup_tests() { @@ -895,8 +929,7 @@ mod test { test_untar_old_backup().await; } - type K256Share = - DefaultShare, ValuePrimeField>; + type K256Share = DefaultShare, ValuePrimeField>; #[cfg(any(feature = "testing", test))] pub fn get_test_recovery_party() -> RecoveryParty { @@ -904,7 +937,7 @@ mod test { let mut rng = rand_core::OsRng; let bls_encryption_key = ::Point::generator() * ::Scalar::random(&mut rng); - let k256_encryption_key = k256::ProjectivePoint::GENERATOR * k256::Scalar::random(&mut rng); + let k256_encryption_key = ProjectivePoint::GENERATOR * Scalar::random(&mut rng); let p256_encryption_key = p256::ProjectivePoint::GENERATOR * p256::Scalar::random(&mut rng); let p384_encryption_key = p384::ProjectivePoint::GENERATOR * p384::Scalar::random(&mut rng); let ed25519_encryption_key = vsss_rs::curve25519::WrappedEdwards::generator() @@ -918,6 +951,7 @@ mod test { let decaf377_encryption_key = decaf377::Element::GENERATOR * decaf377::Fr::random(&mut rng); let bls12381g1_encryption_key = G1Projective::GENERATOR * ::Scalar::random(&mut rng); + let pallas_encryption_key = pallas::Point::generator() * pallas::Scalar::random(&mut rng); // Mock recovery party members let mut party_members = vec![]; @@ -938,6 +972,7 @@ mod test { jubjub_encryption_key, decaf377_encryption_key, bls12381g1_encryption_key, + pallas_encryption_key, threshold: 2, } } @@ -971,7 +1006,7 @@ mod test { let k256_key: KeyShare = serde_json::from_str(TEST_ECDSA_KEY_SHARE).unwrap(); let bls_key_share_commitments: KeyShareCommitments<::Point> = serde_json::from_str(TEST_BLS_KEY_SHARE_COMMITMENT).unwrap(); - let k256_key_share_commitments: KeyShareCommitments = + let k256_key_share_commitments: KeyShareCommitments = serde_json::from_str(TEST_ECDSA_KEY_SHARE_COMMITMENT).unwrap(); // Make sure the key shares and key share commitments match @@ -984,7 +1019,7 @@ mod test { ) .unwrap(); - verify_decrypted_key_share::( + verify_decrypted_key_share::( k256_key_helper .secret_from_hex(&k256_key.hex_private_share) .unwrap(), @@ -1206,19 +1241,17 @@ mod test { let dec_key_share_1 = hex_to_k256_dec_key_share(TEST_ECDSA_PRI_KEY_SHARE_1, 1); let dec_key_share_2 = hex_to_k256_dec_key_share(TEST_ECDSA_PRI_KEY_SHARE_2, 2); - let key_share_1 = - k256::Scalar::from_repr(k256::FieldBytes::clone_from_slice(&dec_key_share_1[1..])) - .expect("Failed to create k256 scalar from bytes"); + let key_share_1 = Scalar::from_repr(FieldBytes::clone_from_slice(&dec_key_share_1[1..])) + .expect("Failed to create k256 scalar from bytes"); let dec_key_share_1 = K256Share { - identifier: IdentifierPrimeField(k256::Scalar::from(dec_key_share_1[0] as u64)), + identifier: IdentifierPrimeField(Scalar::from(dec_key_share_1[0] as u64)), value: IdentifierPrimeField(key_share_1), }; - let key_share_2 = - k256::Scalar::from_repr(k256::FieldBytes::clone_from_slice(&dec_key_share_2[1..])) - .expect("Failed to create k256 scalar from bytes"); + let key_share_2 = Scalar::from_repr(FieldBytes::clone_from_slice(&dec_key_share_2[1..])) + .expect("Failed to create k256 scalar from bytes"); let dec_key_share_2 = K256Share { - identifier: IdentifierPrimeField(k256::Scalar::from(dec_key_share_2[0] as u64)), + identifier: IdentifierPrimeField(Scalar::from(dec_key_share_2[0] as u64)), value: IdentifierPrimeField(key_share_2), }; @@ -1257,7 +1290,7 @@ mod test { let bls_helper = KeyPersistence::::new(CurveType::BLS); let bls_blinder = bls_helper.secret_from_hex(TEST_BLS_BLINDER).unwrap(); - let k256_helper = KeyPersistence::::new(CurveType::K256); + let k256_helper = KeyPersistence::::new(CurveType::K256); let k256_blinder = k256_helper.secret_from_hex(TEST_ECDSA_BLINDER).unwrap(); let cfg = crate::tests::common::get_backup_config(); @@ -1308,7 +1341,7 @@ mod test { .await .unwrap(); - let peer_id = PeerId::try_from(555 as usize).unwrap(); + let peer_id = PeerId::try_from(555usize).unwrap(); let epoch = 333; let restored_key_shares = restore_state .try_restore_key_shares(&peer_id, epoch, staker_address, realm_id) diff --git a/rust/lit-node/lit-node/src/endpoints/recovery/endpoints.rs b/rust/lit-node/lit-node/src/endpoints/recovery/endpoints.rs index 6d58ca8..9257c7f 100644 --- a/rust/lit-node/lit-node/src/endpoints/recovery/endpoints.rs +++ b/rust/lit-node/lit-node/src/endpoints/recovery/endpoints.rs @@ -77,7 +77,10 @@ pub async fn recovery_set_dec_share( } if let Err(e) = restore_state - .add_decryption_shares(&request.auth_sig.address, &[request.share_data.clone()]) + .add_decryption_shares( + &request.auth_sig.address, + std::slice::from_ref(&request.share_data), + ) .await { return e.handle(); diff --git a/rust/lit-node/lit-node/src/endpoints/recovery/mod.rs b/rust/lit-node/lit-node/src/endpoints/recovery/mod.rs index f04c1ef..f67e52e 100644 --- a/rust/lit-node/lit-node/src/endpoints/recovery/mod.rs +++ b/rust/lit-node/lit-node/src/endpoints/recovery/mod.rs @@ -4,23 +4,27 @@ use crate::endpoints::recovery::utils::delete_key_shares_from_disk; use crate::error::{config_err, conversion_err, unexpected_err}; use crate::peers::peer_state::models::SimplePeer; use crate::tss::common::tss_state::TssState; -use blsful::inner_types::G1Projective; -use ed448_goldilocks::EdwardsPoint; use ethers::{ middleware::SignerMiddleware, providers::{Http, Provider}, signers::Wallet, types::H160, }; -use jubjub::SubgroupPoint; -use k256::ecdsa::SigningKey; use lit_blockchain::contracts::backup_recovery::{BackupRecovery, NextStateDownloadable}; use lit_core::{config::LitConfig, utils::binary::bytes_to_hex}; use lit_node_common::config::LitNodeConfig as _; use lit_node_core::CurveType; use lit_recovery::models::DownloadedShareData; +use lit_rust_crypto::{ + blsful::inner_types::G1Projective, + decaf377, + ed448_goldilocks::EdwardsPoint, + jubjub::SubgroupPoint, + k256::{self, ecdsa::SigningKey}, + p256, p384, pallas, + vsss_rs::curve25519::{WrappedEdwards, WrappedRistretto}, +}; use std::sync::Arc; -use vsss_rs::curve25519::{WrappedEdwards, WrappedRistretto}; pub mod endpoints; mod models; @@ -133,25 +137,6 @@ pub async fn do_share_download_from_rec_dkg( }; // k256 and bls public points (public keys) - let bls_pub_key = recovery_shares.bls_encryption_share.public_key_as_bytes()?; - let k256_pub_key = recovery_shares.k256_signing_share.public_key_as_bytes()?; - let p256_pub_key = recovery_shares.p256_signing_share.public_key_as_bytes()?; - let p384_pub_key = recovery_shares.p384_signing_share.public_key_as_bytes()?; - let ed25519_pub_key = recovery_shares - .ed25519_signing_share - .public_key_as_bytes()?; - let ristretto25519_pub_key = recovery_shares - .ristretto25519_signing_share - .public_key_as_bytes()?; - let ed448_pub_key = recovery_shares.ed448_signing_share.public_key_as_bytes()?; - let jubjub_pub_key = recovery_shares.jubjub_signing_share.public_key_as_bytes()?; - let decaf377_pub_key = recovery_shares - .decaf377_signing_share - .public_key_as_bytes()?; - let bls12381g1_pub_key = recovery_shares - .bls12381g1_signing_share - .public_key_as_bytes()?; - let session_id = next_backup_state.session_id.to_string(); Ok(vec![ @@ -284,6 +269,18 @@ pub async fn do_share_download_from_rec_dkg( curve: CurveType::BLS12381G1.to_string(), subnet_id: subnet_id.clone(), }, + DownloadedShareData { + session_id: session_id.clone(), + encryption_key: recovery_shares.pallas_signing_share.hex_public_key.clone(), + decryption_key_share: serde_json::to_string( + &recovery_shares + .pallas_signing_share + .default_share::()?, + ) + .map_err(|e| unexpected_err(e, None))?, + curve: CurveType::RedPallas.to_string(), + subnet_id: subnet_id.clone(), + }, ]) } @@ -316,25 +313,16 @@ pub async fn do_delete_share_from_disk( }; trace!("reading staker address from config"); - let staking_address = match cfg.staker_address() { - Ok(addr) => addr, - Err(e) => { - return Err(config_err( - e, - Some("Error while loading staker address".into()), - )); - } - }; + let staking_address = cfg + .staker_address() + .map_err(|e| config_err(e, Some("Error while loading staker address".into())))?; - let staking_addr: H160 = match staking_address.parse() { - Ok(addr) => addr, - Err(e) => { - return Err(conversion_err( - e, - Some("Could not convert staking address to H160 type".into()), - )); - } - }; + let staking_addr = staking_address.parse::().map_err(|e| { + conversion_err( + e, + Some("Could not convert staking address to H160 type".into()), + ) + })?; let mut index: Option = None; for (i, addr) in recovery_peer_addresses.iter().enumerate() { @@ -391,7 +379,7 @@ pub fn get_staker_address(cfg: &LitConfig) -> crate::error::Result { Err(e) => return Err(unexpected_err(e, None)), }; - let staker_address: ethers::types::H160 = match staker_address.parse() { + let staker_address: H160 = match staker_address.parse() { Ok(addr) => addr, Err(e) => { return Err(conversion_err( diff --git a/rust/lit-node/lit-node/src/endpoints/recovery/models.rs b/rust/lit-node/lit-node/src/endpoints/recovery/models.rs index 40b0ba9..9e3e1b0 100644 --- a/rust/lit-node/lit-node/src/endpoints/recovery/models.rs +++ b/rust/lit-node/lit-node/src/endpoints/recovery/models.rs @@ -12,4 +12,5 @@ pub struct RecoveryShares { pub jubjub_signing_share: KeyShare, pub decaf377_signing_share: KeyShare, pub bls12381g1_signing_share: KeyShare, + pub pallas_signing_share: KeyShare, } diff --git a/rust/lit-node/lit-node/src/endpoints/recovery/utils.rs b/rust/lit-node/lit-node/src/endpoints/recovery/utils.rs index 743e3f6..511e41d 100644 --- a/rust/lit-node/lit-node/src/endpoints/recovery/utils.rs +++ b/rust/lit-node/lit-node/src/endpoints/recovery/utils.rs @@ -182,6 +182,9 @@ pub async fn resolve_key_shares_from_disk( bls12381g1_signing_share: shares .remove(&CurveType::BLS12381G1) .expect_or_err("BLS12381G1")?, + pallas_signing_share: shares + .remove(&CurveType::RedPallas) + .expect_or_err("RedPallas")?, }) } diff --git a/rust/lit-node/lit-node/src/endpoints/web_client.rs b/rust/lit-node/lit-node/src/endpoints/web_client.rs index fd6d138..b65132b 100644 --- a/rust/lit-node/lit-node/src/endpoints/web_client.rs +++ b/rust/lit-node/lit-node/src/endpoints/web_client.rs @@ -1295,19 +1295,19 @@ pub(crate) async fn sign_session_key( }; timing.insert("parsed siwe message".to_string(), before.elapsed()); - if let Some(statement) = &parsed_siwe.statement { - if statement.contains(LIT_RESOURCE_PREFIX_RAC) { - return client_session.json_encrypt_err_custom_response( - "missing resource prefix", - validation_err_code( - "Can't define Auth Context resources in capability", - EC::NodeInvalidAuthContextResource, - None, - ) - .add_msg_to_details() - .handle(), - ); - } + if let Some(statement) = &parsed_siwe.statement + && statement.contains(LIT_RESOURCE_PREFIX_RAC) + { + return client_session.json_encrypt_err_custom_response( + "missing resource prefix", + validation_err_code( + "Can't define Auth Context resources in capability", + EC::NodeInvalidAuthContextResource, + None, + ) + .add_msg_to_details() + .handle(), + ); } let origin_domain = match get_domain_from_request_origin( diff --git a/rust/lit-node/lit-node/src/functions/action_client.rs b/rust/lit-node/lit-node/src/functions/action_client.rs index 8eb4331..b5ddd11 100644 --- a/rust/lit-node/lit-node/src/functions/action_client.rs +++ b/rust/lit-node/lit-node/src/functions/action_client.rs @@ -25,15 +25,10 @@ use crate::utils::tracing::inject_tracing_metadata; use crate::utils::web::{get_bls_root_pubkey, hash_access_control_conditions}; use anyhow::{Context as _, Result, bail}; use base64_light::base64_decode; -use blsful::inner_types::GroupEncoding; -use blsful::{Bls12381G2Impl, SignatureShare}; use derive_builder::Builder; use ecdsa::SignatureSize; -use elliptic_curve::generic_array::ArrayLength; -use elliptic_curve::{CurveArithmetic, PrimeCurve}; use ethers::utils::keccak256; use futures::{FutureExt as _, TryFutureExt}; -use hd_keys_curves::{HDDerivable, HDDeriver}; use lit_actions_grpc::tokio_stream::StreamExt as _; use lit_actions_grpc::tonic::{ Code, Extensions, Request, Status, metadata::MetadataMap, transport::Error as TransportError, @@ -52,7 +47,16 @@ use lit_node_common::config::LitNodeConfig as _; use lit_node_core::{ AccessControlConditionResource, AuthSigItem, BeHex, CompressedBytes, CurveType, EndpointVersion, JsonAuthSig, LitActionPriceComponent, LitResource, NodeSet, PeerId, - SignableOutput, SignedData, SigningScheme, UnifiedAccessControlConditionItem, response, + SignableOutput, SignedData, SigningScheme, UnifiedAccessControlConditionItem, + hd_keys_curves_wasm::{HDDerivable, HDDeriver}, + response, +}; +use lit_rust_crypto::{ + blsful::{Bls12381G2Impl, PublicKey, SignatureShare, inner_types::G1Projective}, + decaf377, ed448_goldilocks, + elliptic_curve::{CurveArithmetic, PrimeCurve, generic_array::ArrayLength}, + group::GroupEncoding, + jubjub, k256, p256, p384, vsss_rs, }; use lit_sdk::signature::{SignedDataOutput, combine_and_verify_signature_shares}; @@ -915,7 +919,7 @@ impl Client { shares.push((PeerId::ONE, signature_share)); // lazy - it's not zero, but we don't seem to care! let network_pubkey = get_bls_root_pubkey(&tss_state).await?; - let network_pubkey = blsful::PublicKey::try_from(&hex::decode(&network_pubkey)?)?; + let network_pubkey = PublicKey::try_from(&hex::decode(&network_pubkey)?)?; let serialized_decryption_shares = shares.iter().map(|(_, share)| *share).collect::>(); @@ -1037,8 +1041,7 @@ impl Client { shares.push((PeerId::ONE, signature_share)); // lazy - it's not zero, but we don't seem to care! let network_pubkey = &get_bls_root_pubkey(&tss_state).await?; - let network_pubkey = - blsful::PublicKey::try_from(&hex::decode(network_pubkey)?)?; + let network_pubkey = PublicKey::try_from(&hex::decode(network_pubkey)?)?; let serialized_decryption_shares = shares.iter().map(|(_, share)| *share).collect::>(); @@ -1059,14 +1062,12 @@ impl Client { } }; - let result = match std::str::from_utf8(&decrypted) { + match std::str::from_utf8(&decrypted) { Ok(result) => result.to_string(), Err(e) => { bail!("Failed to convert decrypted bytes to string.") } - }; - - result + } } }; @@ -1255,6 +1256,7 @@ impl Client { | SigningScheme::SchnorrRistretto25519Sha512 | SigningScheme::SchnorrEd448Shake256 | SigningScheme::SchnorrRedJubjubBlake2b512 + | SigningScheme::SchnorrRedPallasBlake2b512 | SigningScheme::SchnorrRedDecaf377Blake2b512 | SigningScheme::SchnorrkelSubstrate => { let frost_signature: lit_frost::Signature = @@ -1362,7 +1364,7 @@ impl Client { }) => { let (tss_state, txn_prefix) = self.tss_state_and_txn_prefix()?; let network_pubkey = &get_bls_root_pubkey(&tss_state).await?; - let network_pubkey = blsful::PublicKey::try_from(&hex::decode(network_pubkey)?)?; + let network_pubkey = PublicKey::try_from(&hex::decode(network_pubkey)?)?; use sha2::{Digest, Sha256}; let mut hasher = Sha256::new(); @@ -1876,13 +1878,9 @@ impl Client { ) -> Result> { let pubkey = match signing_scheme { SigningScheme::Bls12381G1ProofOfPossession => CompressedBytes::to_compressed( - &derive_ipfs_keys::( - tss_state, - action_ipfs_id, - signing_scheme, - ) - .await? - .1, + &derive_ipfs_keys::(tss_state, action_ipfs_id, signing_scheme) + .await? + .1, ), SigningScheme::EcdsaK256Sha256 | SigningScheme::SchnorrK256Sha256 diff --git a/rust/lit-node/lit-node/src/git_info.rs b/rust/lit-node/lit-node/src/git_info.rs index 78d0b5b..edd4fbe 100644 --- a/rust/lit-node/lit-node/src/git_info.rs +++ b/rust/lit-node/lit-node/src/git_info.rs @@ -1 +1 @@ -pub const GIT_COMMIT_HASH: &str = "88603b5cb16f7acf54b06f856ec853a51c5671f1"; +pub const GIT_COMMIT_HASH: &str = "a14edde0837b9559ac52c2d43b45242b329f19e6"; diff --git a/rust/lit-node/lit-node/src/main.rs b/rust/lit-node/lit-node/src/main.rs index c036879..87b42d2 100644 --- a/rust/lit-node/lit-node/src/main.rs +++ b/rust/lit-node/lit-node/src/main.rs @@ -508,15 +508,15 @@ impl ObservabilityProviders { } fn shutdown(self) { - if let Some(meter_provider) = self.meter_provider { - if let Err(e) = meter_provider.shutdown() { - error!("Failed to shutdown metrics provider: {:?}", e); - } + if let Some(meter_provider) = self.meter_provider + && let Err(e) = meter_provider.shutdown() + { + error!("Failed to shutdown metrics provider: {:?}", e); } - if let Some(logger_provider) = self.logger_provider { - if let Err(e) = logger_provider.shutdown() { - error!("Failed to shutdown logger provider: {:?}", e); - } + if let Some(logger_provider) = self.logger_provider + && let Err(e) = logger_provider.shutdown() + { + error!("Failed to shutdown logger provider: {:?}", e); } } } diff --git a/rust/lit-node/lit-node/src/models/mod.rs b/rust/lit-node/lit-node/src/models/mod.rs index ea6e13f..5a1e505 100644 --- a/rust/lit-node/lit-node/src/models/mod.rs +++ b/rust/lit-node/lit-node/src/models/mod.rs @@ -8,9 +8,8 @@ use lit_blockchain::resolver::rpc::config::RpcConfig; #[cfg(feature = "lit-actions")] use lit_core::config::LitConfig; use lit_node_core::{ - AccessControlConditionItem, AuthMethod, AuthSigItem, Blinders, CurveType, - EVMContractConditionItem, JsonAuthSig, NodeSet, SolRpcConditionItem, - UnifiedAccessControlConditionItem, + AccessControlConditionItem, AuthMethod, AuthSigItem, CurveType, EVMContractConditionItem, + JsonAuthSig, NodeSet, SolRpcConditionItem, UnifiedAccessControlConditionItem, }; use lit_recovery::models::UploadedShareData; use moka::future::Cache; @@ -22,18 +21,8 @@ use std::sync::Arc; use std::time::{Duration, SystemTime}; use tokio::sync::RwLock; use web3::types::{Bytes, CallRequest}; -use webauthn_rs_core::proto::PublicKeyCredential; pub mod auth; -pub mod siwe; -pub mod webauthn_signature_verification_material; - -#[derive(Debug, Serialize, Deserialize, Clone)] -#[serde(rename_all = "camelCase")] -pub struct JsonAdminSetBlindersRequest { - pub auth_sig: JsonAuthSig, - pub blinders: Blinders, -} #[derive(Debug, Serialize, Deserialize, Clone)] #[serde(rename_all = "camelCase")] @@ -224,31 +213,6 @@ pub struct JwtSignedChainDataPayload { pub call_responses: Vec, } -#[derive(Debug, Serialize, Deserialize, Clone)] -#[serde(rename_all = "camelCase")] -pub struct JsonSigningResourceId { - pub base_url: String, - pub path: String, - pub org_id: String, - pub role: String, - pub extra_data: String, -} - -#[derive(Debug, Serialize, Deserialize, Clone)] -#[serde(rename_all = "camelCase")] -pub struct SigningAccessControlConditionRequest { - pub access_control_conditions: Option>, - pub evm_contract_conditions: Option>, - pub sol_rpc_conditions: Option>, - pub unified_access_control_conditions: Option>, - pub chain: Option, - pub auth_sig: AuthSigItem, - pub iat: u64, - pub exp: u64, - #[serde(default = "default_epoch")] - pub epoch: u64, -} - /* accessControlConditions looks like this: accessControlConditions: [ { @@ -304,16 +268,6 @@ pub struct JwtPayloadV2 { pub unified_access_control_conditions: Option>, } -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct RecoveryShare { - pub recovery_share: Vec, -} - -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct JsonRecoveryShareResponse { - pub result: String, -} - #[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, PartialOrd, Ord)] pub struct PeerValidator { pub ip: u32, @@ -333,14 +287,6 @@ pub struct PeerValidator { pub realm_id: U256, } -#[derive(Debug, Serialize, Deserialize, Clone)] -#[serde(rename_all = "camelCase")] -pub struct WebAuthnAuthenticationRequest { - pub credential: PublicKeyCredential, - pub session_pubkey: String, - pub siwe_message: String, -} - #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] pub struct EthBlock { pub blockhash: String, diff --git a/rust/lit-node/lit-node/src/models/siwe.rs b/rust/lit-node/lit-node/src/models/siwe.rs deleted file mode 100644 index d63ca7b..0000000 --- a/rust/lit-node/lit-node/src/models/siwe.rs +++ /dev/null @@ -1,11 +0,0 @@ -use std::collections::HashMap; - -use serde::{Deserialize, Serialize}; -use serde_json::Value; - -#[derive(Serialize, Deserialize, Debug, Clone)] -pub struct CapabilityObject { - pub def: Option>, - pub tar: Option>, - pub ext: Option>, -} diff --git a/rust/lit-node/lit-node/src/models/webauthn_signature_verification_material.rs b/rust/lit-node/lit-node/src/models/webauthn_signature_verification_material.rs deleted file mode 100644 index 1e602de..0000000 --- a/rust/lit-node/lit-node/src/models/webauthn_signature_verification_material.rs +++ /dev/null @@ -1,9 +0,0 @@ -use serde::{Deserialize, Serialize}; - -#[derive(Debug, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct WebAuthnSignatureVerificationMaterial { - pub signature: String, - pub signature_base: String, - pub credential_public_key: String, -} diff --git a/rust/lit-node/lit-node/src/p2p_comms/comms/wait.rs b/rust/lit-node/lit-node/src/p2p_comms/comms/wait.rs index e7a2c76..e5143b1 100644 --- a/rust/lit-node/lit-node/src/p2p_comms/comms/wait.rs +++ b/rust/lit-node/lit-node/src/p2p_comms/comms/wait.rs @@ -182,10 +182,10 @@ pub async fn node_share_await( // } // optionally exit early. - if let Some(exit_on_qty_recvd) = params.exit_on_qty_recvd { - if recvd_ans.len() >= exit_on_qty_recvd { - break 'waiting_loop; - }; + if let Some(exit_on_qty_recvd) = params.exit_on_qty_recvd + && recvd_ans.len() >= exit_on_qty_recvd + { + break 'waiting_loop; }; } diff --git a/rust/lit-node/lit-node/src/p2p_comms/web/chatter_server.rs b/rust/lit-node/lit-node/src/p2p_comms/web/chatter_server.rs index 5b95bd9..7669392 100644 --- a/rust/lit-node/lit-node/src/p2p_comms/web/chatter_server.rs +++ b/rust/lit-node/lit-node/src/p2p_comms/web/chatter_server.rs @@ -32,6 +32,7 @@ use tracing::{debug, error, info, instrument}; use xor_name::XorName; #[allow(clippy::unwrap_used)] +#[allow(dead_code)] pub mod chatter { tonic::include_proto!("chatter"); } diff --git a/rust/lit-node/lit-node/src/p2p_comms/web/mod.rs b/rust/lit-node/lit-node/src/p2p_comms/web/mod.rs index 7a37102..d69c650 100644 --- a/rust/lit-node/lit-node/src/p2p_comms/web/mod.rs +++ b/rust/lit-node/lit-node/src/p2p_comms/web/mod.rs @@ -1,3 +1,2 @@ pub mod chatter_server; pub mod internal; -pub mod models; diff --git a/rust/lit-node/lit-node/src/p2p_comms/web/models.rs b/rust/lit-node/lit-node/src/p2p_comms/web/models.rs deleted file mode 100644 index c12f773..0000000 --- a/rust/lit-node/lit-node/src/p2p_comms/web/models.rs +++ /dev/null @@ -1,43 +0,0 @@ -use lit_node_core::{ - AccessControlConditionItem, EVMContractConditionItem, JsonAuthSig, SolRpcConditionItem, -}; -use serde::{Deserialize, Serialize}; - -#[derive(Serialize, Deserialize)] -pub struct ValidateConditionRequest { - pub access_control_conditions: Option>, - pub evm_contract_conditions: Option>, - pub sol_rpc_conditions: Option>, - pub chain: String, - pub auth_sig: JsonAuthSig, - pub iat: u64, - pub exp: u64, -} - -#[derive(Clone, Serialize, Deserialize)] -pub struct PKPKeyRequest { - pub id: String, - pub chain: String, - pub key_type: String, - pub iat: u64, - pub exp: u64, -} - -#[derive(Clone, Serialize, Deserialize, Debug)] -pub struct PKPKeyResponse { - pub chain: String, - pub public_key: String, - pub signature: String, - pub key_type: String, - pub signature_r: ethers::types::U256, - pub signature_s: ethers::types::U256, - pub signature_v: u64, -} - -#[derive(Clone, Serialize, Deserialize, Debug)] -pub struct SignWithPublicHashRequest { - pub pubkey: Vec, - pub auth_sig: JsonAuthSig, - pub iat: u64, - pub exp: u64, -} diff --git a/rust/lit-node/lit-node/src/payment/payment_delegation.rs b/rust/lit-node/lit-node/src/payment/payment_delegation.rs index 546f03c..de94a3b 100644 --- a/rust/lit-node/lit-node/src/payment/payment_delegation.rs +++ b/rust/lit-node/lit-node/src/payment/payment_delegation.rs @@ -128,8 +128,7 @@ pub async fn check_for_payment_delegation( if let Ok(Some(delegation)) = check_verified_siwe_for_a_payment_delegator(user_address, signed_message) - { - if let Ok((true, spending_limit)) = validate_delegation_requirements( + && let Ok((true, spending_limit)) = validate_delegation_requirements( &delegation, required_scope, required_funds, @@ -138,9 +137,8 @@ pub async fn check_for_payment_delegation( ledger, ) .await - { - return Ok(Some((delegation.delegator, spending_limit))); - } + { + return Ok(Some((delegation.delegator, spending_limit))); }; } diff --git a/rust/lit-node/lit-node/src/peers/keys.rs b/rust/lit-node/lit-node/src/peers/keys.rs index 76da492..c0b6453 100644 --- a/rust/lit-node/lit-node/src/peers/keys.rs +++ b/rust/lit-node/lit-node/src/peers/keys.rs @@ -4,13 +4,13 @@ use ethers::middleware::SignerMiddleware; use ethers::providers::{Http, Provider}; use ethers::signers::Wallet; use ethers::types::Address; -use k256::ecdsa::SigningKey; use lit_blockchain::contracts::staking::Staking; use lit_core::config::LitConfig; use lit_core::utils::binary::bytes_to_hex; use lit_node_common::coms_keys::ComsKeys; use lit_node_common::config::LitNodeConfig; use lit_node_common::eth_wallet_keys::EthWalletKeys; +use lit_rust_crypto::k256::ecdsa::SigningKey; use std::sync::Arc; pub struct PeerKeys { diff --git a/rust/lit-node/lit-node/src/peers/peer_state/listener.rs b/rust/lit-node/lit-node/src/peers/peer_state/listener.rs index eea5cc4..2613cfe 100644 --- a/rust/lit-node/lit-node/src/peers/peer_state/listener.rs +++ b/rust/lit-node/lit-node/src/peers/peer_state/listener.rs @@ -4,7 +4,6 @@ use crate::error::{EC, Result, unexpected_err_code}; use crate::tasks::presign_manager::models::PresignMessage; use ethers::providers::StreamExt; use lit_blockchain::contracts::staking::StakingEvents; -use rocket::serde::{Deserialize, Serialize}; use std::sync::Arc; use tokio::sync::mpsc; @@ -150,11 +149,3 @@ impl PeerState { Ok(()) } } - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -pub enum PeerValidatorStatus { - Entering, // Not in current, but in locked next - Exiting, // in current, but not in locked next - Survivor, // in both - Unknown, -} diff --git a/rust/lit-node/lit-node/src/pkp/auth/mod.rs b/rust/lit-node/lit-node/src/pkp/auth/mod.rs index 1399261..642989a 100644 --- a/rust/lit-node/lit-node/src/pkp/auth/mod.rs +++ b/rust/lit-node/lit-node/src/pkp/auth/mod.rs @@ -340,7 +340,7 @@ pub async fn check_pkp_auth( required_scopes: &[usize], bls_root_pubkey: &str, ) -> Result { - use std::io::{Error, ErrorKind}; + use std::io::Error; debug!("auth_context- {:?}", auth_context); @@ -587,13 +587,10 @@ pub async fn check_pkp_auth( } return Err(validation_err_code( - Error::new( - ErrorKind::Other, - format!( - "None of the AuthMethods, AuthSig or Lit Actions meet the required scope {:?}.", - required_scopes - ), - ), + Error::other(format!( + "None of the AuthMethods, AuthSig or Lit Actions meet the required scope {:?}.", + required_scopes + )), EC::NodeAuthSigScopeTooLimited, None, )); diff --git a/rust/lit-node/lit-node/src/siwe_db/db.rs b/rust/lit-node/lit-node/src/siwe_db/db.rs index 70baa36..e4d49f9 100644 --- a/rust/lit-node/lit-node/src/siwe_db/db.rs +++ b/rust/lit-node/lit-node/src/siwe_db/db.rs @@ -439,7 +439,7 @@ mod siwe_db_tests { .query_row( "SELECT COUNT(*) FROM blockhash_timestamp", params![], - |row| (row.get::<_, i64>(0)), + |row| row.get::<_, i64>(0), ) .unwrap(); diff --git a/rust/lit-node/lit-node/src/tasks/fsm/mod.rs b/rust/lit-node/lit-node/src/tasks/fsm/mod.rs index 6cf90af..358643c 100644 --- a/rust/lit-node/lit-node/src/tasks/fsm/mod.rs +++ b/rust/lit-node/lit-node/src/tasks/fsm/mod.rs @@ -252,37 +252,38 @@ pub async fn node_fsm_worker( // Wait until the network is active again loop { - if let Ok(state) = peer_state.network_state(realm_id).await { - if state != NetworkState::Restore && state != NetworkState::Paused { - let recovered_peer_ids = match restore_state - .pull_recovered_peer_ids(&cfg.load_full()) - .await - { - Ok(ids) => ids, - Err(e) => { - error!( - "RestoredState: Failed to read the recovered peer ids: {}", - e - ); - // Try again - continue; - } - }; - let data = match standard_dkg_manager.next_dkg_after_restore.take() { - Some(mut data) => { - data.peers = recovered_peer_ids; - data - } - None => DkgAfterRestoreData { - peers: recovered_peer_ids, - ..Default::default() - }, - }; - standard_dkg_manager.next_dkg_after_restore = DkgAfterRestore::True(data); - - info!("RestoreState: Exiting recovery code, starting the fsm loop."); - break; - } + if let Ok(state) = peer_state.network_state(realm_id).await + && state != NetworkState::Restore + && state != NetworkState::Paused + { + let recovered_peer_ids = match restore_state + .pull_recovered_peer_ids(&cfg.load_full()) + .await + { + Ok(ids) => ids, + Err(e) => { + error!( + "RestoredState: Failed to read the recovered peer ids: {}", + e + ); + // Try again + continue; + } + }; + let data = match standard_dkg_manager.next_dkg_after_restore.take() { + Some(mut data) => { + data.peers = recovered_peer_ids; + data + } + None => DkgAfterRestoreData { + peers: recovered_peer_ids, + ..Default::default() + }, + }; + standard_dkg_manager.next_dkg_after_restore = DkgAfterRestore::True(data); + + info!("RestoreState: Exiting recovery code, starting the fsm loop."); + break; } } } diff --git a/rust/lit-node/lit-node/src/tasks/fsm/utils.rs b/rust/lit-node/lit-node/src/tasks/fsm/utils.rs index 6f8e33a..7d43374 100644 --- a/rust/lit-node/lit-node/src/tasks/fsm/utils.rs +++ b/rust/lit-node/lit-node/src/tasks/fsm/utils.rs @@ -153,10 +153,10 @@ pub(crate) async fn key_share_proofs_check( } let mut root_keys = Vec::new(); - if let Ok(rk) = root_key_res { - if !rk.is_empty() { - root_keys = rk.clone(); - } + if let Ok(rk) = root_key_res + && !rk.is_empty() + { + root_keys = rk.clone(); } if root_keys.is_empty() { root_keys = tss_state.chain_data_config_manager.root_keys(); diff --git a/rust/lit-node/lit-node/src/tasks/payment.rs b/rust/lit-node/lit-node/src/tasks/payment.rs index 9700f0c..27f462f 100644 --- a/rust/lit-node/lit-node/src/tasks/payment.rs +++ b/rust/lit-node/lit-node/src/tasks/payment.rs @@ -3,8 +3,8 @@ use ethers::middleware::SignerMiddleware; use ethers::providers::{Http, PendingTransaction, Provider}; use ethers::signers::{Signer, Wallet}; use ethers::types::{Bytes, TxHash, U256}; -use k256::ecdsa::SigningKey; use lit_blockchain::util::ether::middleware::EIP2771GasRelayerMiddleware; +use lit_rust_crypto::k256::ecdsa::SigningKey; use std::sync::Arc; use std::time::Duration; use tokio::sync::mpsc; diff --git a/rust/lit-node/lit-node/src/tasks/presign_manager/finder.rs b/rust/lit-node/lit-node/src/tasks/presign_manager/finder.rs index c1c1f37..23b7fb5 100644 --- a/rust/lit-node/lit-node/src/tasks/presign_manager/finder.rs +++ b/rust/lit-node/lit-node/src/tasks/presign_manager/finder.rs @@ -11,10 +11,10 @@ use crate::tss::common::storage::read_presign_from_disk_direct; use async_std::fs::{self, DirEntry}; use async_std::io::Error; use async_std::path::PathBuf; -use elliptic_curve::bigint::{self, U256}; use futures::StreamExt; use lit_node_common::config::presign_path; use lit_node_core::CurveType; +use lit_rust_crypto::elliptic_curve::bigint::{self, U256}; use xorf::Filter; impl PresignManager { @@ -81,13 +81,12 @@ impl PresignManager { let path = entry.path(); Box::pin(self.recurse_dirs(path, presign_list, peers, node_addr, curve_type)) .await?; - } else if filetype.is_file() { - if let Err(r) = self + } else if filetype.is_file() + && let Err(r) = self .attempt_load_presign(entry.clone(), presign_list, peers, node_addr, curve_type) .await - { - error!("Error loading presign {:?}: {:?}", entry, r); - } + { + error!("Error loading presign {:?}: {:?}", entry, r); } } Ok(()) @@ -108,7 +107,7 @@ impl PresignManager { Err(e) => { error!("Error reading filename: {:?}", e); return Err(unexpected_err( - Error::new(std::io::ErrorKind::Other, "file"), + Error::other("file"), Some("Presign filename read error.".into()), )); } @@ -120,7 +119,7 @@ impl PresignManager { None => { error!("Error reading filename: {:?}", entry.path()); return Err(unexpected_err( - Error::new(std::io::ErrorKind::Other, "file"), + Error::other("file"), Some("Presign filename read error.".into()), )); } @@ -194,14 +193,14 @@ impl PresignManager { } if found { // even if there is a peer_group, we need to check if it's empty - if let Some(s) = pregen_list.get(peer_group_id) { - if !s.is_empty() { - info!( - "Found peer group_id {} with threshold {}.", - peer_group_id, xor_filter_with_threshold.threshold - ); - return *peer_group_id; - } + if let Some(s) = pregen_list.get(peer_group_id) + && !s.is_empty() + { + info!( + "Found peer group_id {} with threshold {}.", + peer_group_id, xor_filter_with_threshold.threshold + ); + return *peer_group_id; } } } diff --git a/rust/lit-node/lit-node/src/tasks/presign_manager/listener.rs b/rust/lit-node/lit-node/src/tasks/presign_manager/listener.rs index ff1aa60..5b43be4 100644 --- a/rust/lit-node/lit-node/src/tasks/presign_manager/listener.rs +++ b/rust/lit-node/lit-node/src/tasks/presign_manager/listener.rs @@ -8,13 +8,14 @@ use crate::tasks::presign_manager::models::Presign; use crate::tss::common::storage::{delete_presign, read_presign_from_disk, write_presign_to_disk}; use crate::tss::ecdsa_damfast::DamFastState; use crate::version::DataVersionReader; -use elliptic_curve::bigint::{self, U256}; use flume::Sender; use lit_core::config::ReloadableLitConfig; use lit_node_common::config::{CFG_KEY_SIGNING_ROUND_TIMEOUT_MS_DEFAULT, LitNodeConfig}; -use lit_node_core::CurveType; -use lit_node_core::PeerId; -use lit_node_core::SigningScheme; +use lit_node_core::{CurveType, PeerId, SigningScheme}; +use lit_rust_crypto::{ + elliptic_curve::bigint::{self, U256}, + k256, p256, p384, +}; use std::num::NonZeroU64; use std::time::Duration; use tracing::instrument; @@ -1114,16 +1115,15 @@ impl PresignManager { } }; - if presign_leader_response.remaining_presigns < min_presigns { - if let Err(e) = local_tx + if presign_leader_response.remaining_presigns < min_presigns + && let Err(e) = local_tx .send_async(PresignMessage::InformNonParticipants( request_key_hash, nonparticipants, )) .await - { - error!("Error sending inform non participants message: {}", e); - } + { + error!("Error sending inform non participants message: {}", e); } let presign_message = PresignMessage::FullfillPresignRequest( diff --git a/rust/lit-node/lit-node/src/tasks/presign_manager/models.rs b/rust/lit-node/lit-node/src/tasks/presign_manager/models.rs index 5cfe145..c27a4b1 100644 --- a/rust/lit-node/lit-node/src/tasks/presign_manager/models.rs +++ b/rust/lit-node/lit-node/src/tasks/presign_manager/models.rs @@ -2,14 +2,17 @@ use crate::error::{Result, unexpected_err}; use crate::peers::peer_state::models::SimplePeerCollection; use crate::tss::common::tss_state::TssState; use crate::utils::traits::SignatureCurve; -use elliptic_curve::group::GroupEncoding; -use elliptic_curve::{CurveArithmetic, PrimeCurve}; use flume::{Receiver, Sender}; -use hd_keys_curves::{HDDerivable, HDDeriver}; use lit_fast_ecdsa::PreSignature; -use lit_node_core::CurveType; -use lit_node_core::PeerId; -use lit_node_core::SigningScheme; +use lit_node_core::{ + CurveType, PeerId, SigningScheme, + hd_keys_curves_wasm::{HDDerivable, HDDeriver}, +}; +use lit_rust_crypto::{ + elliptic_curve::{CurveArithmetic, PrimeCurve}, + group::GroupEncoding, + k256, p256, p384, +}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::collections::hash_map::DefaultHasher; diff --git a/rust/lit-node/lit-node/src/tss/blsful/mod.rs b/rust/lit-node/lit-node/src/tss/blsful/mod.rs index 264d719..4653fcc 100644 --- a/rust/lit-node/lit-node/src/tss/blsful/mod.rs +++ b/rust/lit-node/lit-node/src/tss/blsful/mod.rs @@ -5,15 +5,21 @@ use crate::tss::common::hd_keys::get_derived_keyshare; use crate::tss::common::key_share::KeyShare; use crate::tss::common::traits::signable::Signable; use crate::tss::common::{storage::read_key_share_from_disk, traits::cipherable::Cipherable}; -use blsful::{Pairing, SecretKeyShare, SignatureShare, vsss_rs::Share}; -use elliptic_curve::Group; -use hd_keys_curves::HDDeriver; use lit_core::error::Unexpected; use lit_core::utils::binary::bytes_to_hex; -use lit_node_core::PeerId; -use lit_node_core::{BlsSignedMessageShare, CurveType, NodeSet, SignableOutput, SigningScheme}; +use lit_node_core::{ + BlsSignedMessageShare, CurveType, NodeSet, PeerId, SignableOutput, SigningScheme, + hd_keys_curves_wasm::HDDeriver, +}; +use lit_rust_crypto::{ + blsful::{ + Bls12381G1Impl, Bls12381G2Impl, Pairing, SecretKeyShare, SignatureSchemes, SignatureShare, + inner_types::{G1Projective, Scalar}, + }, + group::Group, + vsss_rs::{IdentifierPrimeField, Share}, +}; use tracing::instrument; -use vsss_rs::IdentifierPrimeField; #[async_trait::async_trait] impl Cipherable for BlsState { @@ -22,7 +28,7 @@ impl Cipherable for BlsState { &self, message_bytes: &[u8], epoch: Option, - ) -> Result<(SignatureShare, PeerId)> { + ) -> Result<(SignatureShare, PeerId)> { let dkg_state = self.state.get_dkg_state(CurveType::BLS)?; let root_keys = dkg_state.root_keys().await; if root_keys.is_empty() { @@ -42,7 +48,7 @@ impl Cipherable for BlsState { message_bytes: &[u8], pub_key: &str, epoch: Option, - ) -> Result<(SignatureShare, PeerId)> { + ) -> Result<(SignatureShare, PeerId)> { trace!( "Encryption signing with pubkey: {:?} for epoch: {:?}", pub_key, epoch @@ -50,7 +56,7 @@ impl Cipherable for BlsState { let (secret_key_share, share_peer_id) = self.get_keyshare(pub_key, epoch).await?; let sks = secret_key_share - .sign(blsful::SignatureSchemes::ProofOfPossession, &message_bytes) + .sign(SignatureSchemes::ProofOfPossession, &message_bytes) .map_err(|e| unexpected_err(format!("Failed to sign message: {:?}", e), None))?; Ok((sks, share_peer_id)) @@ -111,13 +117,10 @@ impl Signable for BlsState { )); } let staker_address = &bytes_to_hex(self_peer.staker_address.as_bytes()); - let deriver = ::create( - &key_id, - self.signing_scheme.id_sign_ctx(), - ); + let deriver = ::create(&key_id, self.signing_scheme.id_sign_ctx()); match self.signing_scheme { SigningScheme::Bls12381G1ProofOfPossession => { - let (sk, vk) = get_derived_keyshare::( + let (sk, vk) = get_derived_keyshare::( deriver, &root_keys, CurveType::BLS12381G1, @@ -129,18 +132,17 @@ impl Signable for BlsState { ) .await?; - let identifier = - <::PublicKey as Group>::Scalar::from( - self_peer.peer_id, - ); + let identifier = <::PublicKey as Group>::Scalar::from( + self_peer.peer_id, + ); let secret_key_share = SecretKeyShare( - ::SecretKeyShare::with_identifier_and_value( + ::SecretKeyShare::with_identifier_and_value( IdentifierPrimeField(identifier), IdentifierPrimeField(sk), ), ); - let signature_share: SignatureShare = secret_key_share - .sign(blsful::SignatureSchemes::ProofOfPossession, message_bytes) + let signature_share: SignatureShare = secret_key_share + .sign(SignatureSchemes::ProofOfPossession, message_bytes) .map_err(|e| { unexpected_err(e, Some("unable to generate signature".to_string())) })?; @@ -151,10 +153,8 @@ impl Signable for BlsState { message: hex::encode(message_bytes), result: "success".to_string(), peer_id: self_peer.peer_id.to_string(), - share_id: serde_json::to_string(&blsful::inner_types::Scalar::from( - self_peer.peer_id, - )) - .expect_or_err("Error serializing share_id")?, + share_id: serde_json::to_string(&Scalar::from(self_peer.peer_id)) + .expect_or_err("Error serializing share_id")?, signature_share: serde_json::to_string(&signature_share) .expect_or_err("Error serializing signature_share")?, verifying_share: serde_json::to_string(&verifying_share) @@ -175,7 +175,7 @@ impl BlsState { &self, pubkey: &str, epoch: Option, - ) -> Result<(SecretKeyShare, PeerId)> { + ) -> Result<(SecretKeyShare, PeerId)> { let realm_id = self.state.peer_state.realm_id(); let self_epoch = self.state.peer_state.epoch(); @@ -214,13 +214,12 @@ impl BlsState { ) .await?; - let identifier = <::PublicKey as Group>::Scalar::from( - bls_key_share.peer_id, - ); - let value = bls_key_share.secret::<::PublicKey>()?; + let identifier = + <::PublicKey as Group>::Scalar::from(bls_key_share.peer_id); + let value = bls_key_share.secret::<::PublicKey>()?; let secret_key_share = SecretKeyShare( - ::SecretKeyShare::with_identifier_and_value( + ::SecretKeyShare::with_identifier_and_value( IdentifierPrimeField(identifier), IdentifierPrimeField(value), ), diff --git a/rust/lit-node/lit-node/src/tss/common/backup.rs b/rust/lit-node/lit-node/src/tss/common/backup.rs index 575bef9..fde7651 100644 --- a/rust/lit-node/lit-node/src/tss/common/backup.rs +++ b/rust/lit-node/lit-node/src/tss/common/backup.rs @@ -1,6 +1,4 @@ -use blsful::inner_types::{G1Projective, InnerBls12381G1}; use bulletproofs::{BulletproofCurveArithmetic as BCA, BulletproofCurveArithmetic}; -use elliptic_curve::bigint::{NonZero, U256}; use ethers::types::H160; use std::marker::PhantomData; use verifiable_share_encryption::VerifiableEncryption; @@ -13,10 +11,14 @@ use crate::utils::traits::SignatureCurve; use lit_blockchain::contracts::backup_recovery::RecoveryKey; use lit_core::config::LitConfig; use lit_node_common::config::LitNodeConfig; -use lit_node_core::CompressedBytes; -use lit_node_core::CurveType; -use lit_node_core::PeerId; +use lit_node_core::{CompressedBytes, CurveType, PeerId}; use lit_recovery::models::EncryptedKeyShare; +use lit_rust_crypto::{ + blsful::inner_types::{G1Projective, InnerBls12381G1}, + decaf377, ed448_goldilocks, + elliptic_curve::bigint::{NonZero, U256}, + jubjub, k256, p256, p384, pallas, vsss_rs, +}; /// Internally kept version #[derive(Default)] @@ -33,6 +35,7 @@ pub struct RecoveryParty { pub jubjub_encryption_key: jubjub::SubgroupPoint, pub decaf377_encryption_key: decaf377::Element, pub bls12381g1_encryption_key: ::Point, + pub pallas_encryption_key: pallas::Point, pub threshold: usize, } @@ -118,6 +121,10 @@ fn set_recovery_party_keys( trace!("Reading bls12381g1 encryption key"); recovery_party.bls12381g1_encryption_key = read_bls_pub_key(&recovery_key.pubkey)?; } + CurveType::RedPallas => { + trace!("Reading pallas encryption key"); + recovery_party.pallas_encryption_key = read_pallas_pub_key(&recovery_key.pubkey)?; + } } } Ok(()) @@ -217,6 +224,11 @@ fn read_decaf377_pub_key(bytes: &[u8]) -> Result { helper.pk_from_bytes(bytes) } +fn read_pallas_pub_key(bytes: &[u8]) -> Result { + let helper = KeyPersistence::::new(CurveType::RedPallas); + helper.pk_from_bytes(bytes) +} + #[cfg(test)] mod tests { use super::*; @@ -225,14 +237,13 @@ mod tests { use crate::tss::common::key_persistence::KeyPersistence; use crate::tss::common::key_share::KeyShare; use bulletproofs::BulletproofCurveArithmetic as BCA; - use elliptic_curve::Field; - use elliptic_curve::ff::PrimeFieldBits; - use lit_node_core::CompressedHex; - use lit_node_core::CurveType; - use lit_node_core::PeerId; + use lit_node_core::{CompressedHex, CurveType, PeerId}; + use lit_rust_crypto::{ + ff::{Field, PrimeFieldBits}, + vsss_rs::{DefaultShare, IdentifierPrimeField}, + }; use test_case::test_case; use verifiable_share_encryption::{VerifiableEncryption, VerifiableEncryptionDecryptor}; - use vsss_rs::{DefaultShare, IdentifierPrimeField}; fn get_enc_dec_key_pair() -> (::Point, C::Scalar) where diff --git a/rust/lit-node/lit-node/src/tss/common/hd_keys.rs b/rust/lit-node/lit-node/src/tss/common/hd_keys.rs index 56c628b..7f2506f 100644 --- a/rust/lit-node/lit-node/src/tss/common/hd_keys.rs +++ b/rust/lit-node/lit-node/src/tss/common/hd_keys.rs @@ -4,15 +4,13 @@ use crate::{ error::{Result, unexpected_err}, tss::common::storage::read_key_share_from_disk, }; -use elliptic_curve::group::GroupEncoding; -use hd_keys_curves::{HDDerivable, HDDeriver}; -use lit_node_core::CompressedBytes; -use lit_node_core::CurveType; -use lit_node_core::PeerId; +use lit_node_core::{ + CompressedBytes, CurveType, PeerId, + hd_keys_curves_wasm::{HDDerivable, HDDeriver}, +}; +use lit_rust_crypto::group::GroupEncoding; use tracing::instrument; -pub const ID_SIGN_CTX: &[u8] = b"LIT_HD_KEY_ID_K256_XMD:SHA-256_SSWU_RO_NUL_"; - #[allow(clippy::too_many_arguments)] #[instrument(level = "debug", skip_all)] pub async fn get_derived_keyshare( diff --git a/rust/lit-node/lit-node/src/tss/common/key_persistence.rs b/rust/lit-node/lit-node/src/tss/common/key_persistence.rs index 74820a3..4467bf0 100644 --- a/rust/lit-node/lit-node/src/tss/common/key_persistence.rs +++ b/rust/lit-node/lit-node/src/tss/common/key_persistence.rs @@ -3,10 +3,8 @@ use crate::error::{Result, unexpected_err}; use crate::peers::peer_state::models::SimplePeerCollection; use crate::tss::common::key_share::KeyShare; use crate::tss::common::storage::{read_key_share_from_disk, write_key_share_to_disk}; -use elliptic_curve::group::{Group, GroupEncoding}; -use lit_node_core::CurveType; -use lit_node_core::PeerId; -use lit_node_core::{CompressedBytes, CompressedHex}; +use lit_node_core::{CompressedBytes, CompressedHex, CurveType, PeerId}; +use lit_rust_crypto::group::{Group, GroupEncoding}; use std::fmt::Debug; pub const RECOVERY_DKG_EPOCH: u64 = 0; diff --git a/rust/lit-node/lit-node/src/tss/common/key_share.rs b/rust/lit-node/lit-node/src/tss/common/key_share.rs index d67affc..37c8d1d 100644 --- a/rust/lit-node/lit-node/src/tss/common/key_share.rs +++ b/rust/lit-node/lit-node/src/tss/common/key_share.rs @@ -1,14 +1,13 @@ use crate::error::{Result, parser_err}; use crate::peers::peer_state::models::SimplePeerCollection; use crate::tss::common::key_persistence::KeyPersistence; -use elliptic_curve::Group; -use elliptic_curve::group::GroupEncoding; -use lit_node_core::CompressedBytes; -use lit_node_core::CurveType; -use lit_node_core::PeerId; +use lit_node_core::{CompressedBytes, CurveType, PeerId}; +use lit_rust_crypto::{ + group::{Group, GroupEncoding}, + vsss_rs::{DefaultShare, IdentifierPrimeField}, +}; use serde::{Deserialize, Serialize}; use std::fmt::Debug; -use vsss_rs::{DefaultShare, IdentifierPrimeField}; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct KeyShare { diff --git a/rust/lit-node/lit-node/src/tss/common/key_share_commitment.rs b/rust/lit-node/lit-node/src/tss/common/key_share_commitment.rs index 9089166..c06c906 100644 --- a/rust/lit-node/lit-node/src/tss/common/key_share_commitment.rs +++ b/rust/lit-node/lit-node/src/tss/common/key_share_commitment.rs @@ -1,4 +1,4 @@ -use elliptic_curve::{Field, Group, group::GroupEncoding}; +use lit_rust_crypto::elliptic_curve::{Field, Group, group::GroupEncoding}; use serde::{Deserialize, Serialize}; /// KeyShareCommitment is a struct that holds the commitment of a key share. @@ -90,7 +90,7 @@ mod group { let bytes: Vec = Vec::deserialize(d)?; let repr = G::Repr::default(); let len = repr.as_ref().len(); - if bytes.len() % len != 0 { + if !bytes.len().is_multiple_of(len) { return Err(serde::de::Error::custom(format!( "Invalid group element length: expected multiple of {}, found {}", len, diff --git a/rust/lit-node/lit-node/src/tss/common/mod.rs b/rust/lit-node/lit-node/src/tss/common/mod.rs index 610d30b..bdd2491 100644 --- a/rust/lit-node/lit-node/src/tss/common/mod.rs +++ b/rust/lit-node/lit-node/src/tss/common/mod.rs @@ -10,7 +10,6 @@ pub mod models; pub mod peer_checker; pub mod peer_communication; pub mod restore; -pub mod signing_scheme; pub mod storage; pub mod traits; pub mod tss_state; diff --git a/rust/lit-node/lit-node/src/tss/common/models.rs b/rust/lit-node/lit-node/src/tss/common/models.rs index f6bc170..e1d08a4 100644 --- a/rust/lit-node/lit-node/src/tss/common/models.rs +++ b/rust/lit-node/lit-node/src/tss/common/models.rs @@ -2,6 +2,7 @@ use crate::peers::peer_reviewer::PeerComplaint; use crate::peers::peer_state::models::SimplePeer; use lit_node_core::PeerId; use lit_observability::channels::TracedSender; +use lit_rust_crypto::k256; use serde::{Deserialize, Serialize}; use std::{ fmt::{self, Debug, Formatter}, diff --git a/rust/lit-node/lit-node/src/tss/common/restore/eks_and_ds.rs b/rust/lit-node/lit-node/src/tss/common/restore/eks_and_ds.rs index ab1f5a9..62c289b 100644 --- a/rust/lit-node/lit-node/src/tss/common/restore/eks_and_ds.rs +++ b/rust/lit-node/lit-node/src/tss/common/restore/eks_and_ds.rs @@ -7,19 +7,19 @@ use crate::tss::common::key_share_commitment::KeyShareCommitments; use crate::tss::common::storage::write_key_share_to_cache_only; use crate::utils::traits::SignatureCurve; use bulletproofs::BulletproofCurveArithmetic as BCA; -use elliptic_curve::bigint::{NonZero, U256}; -use lit_node_core::CurveType; -use lit_node_core::PeerId; -use lit_node_core::{CompressedBytes, CompressedHex}; +use lit_node_core::{CompressedBytes, CompressedHex, CurveType, PeerId}; use lit_recovery::models::EncryptedKeyShare; +use lit_rust_crypto::{ + elliptic_curve::bigint::{NonZero, U256}, + vsss_rs::{ + DefaultShare, FeldmanVerifierSet, IdentifierPrimeField, Share, ValueGroup, + VecFeldmanVerifierSet, + }, +}; use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; use std::fmt::{Debug, Formatter}; use verifiable_share_encryption::VerifiableEncryptionDecryptor; -use vsss_rs::{ - DefaultShare, FeldmanVerifierSet, IdentifierPrimeField, Share, ValueGroup, - VecFeldmanVerifierSet, -}; /// Identifier for a Recovery Party member. pub type RecPartyMemberIdType = String; diff --git a/rust/lit-node/lit-node/src/tss/common/restore/point_reader.rs b/rust/lit-node/lit-node/src/tss/common/restore/point_reader.rs index 1a7e49e..d9dec0c 100644 --- a/rust/lit-node/lit-node/src/tss/common/restore/point_reader.rs +++ b/rust/lit-node/lit-node/src/tss/common/restore/point_reader.rs @@ -1,9 +1,12 @@ use crate::common::storage::{read_from_disk, write_to_disk}; use crate::error::Result; use async_std::path::PathBuf; -use blsful::inner_types::{G1Projective, InnerBls12381G1}; use bulletproofs::BulletproofCurveArithmetic as BCA; use lit_node_core::CompressedHex; +use lit_rust_crypto::{ + blsful::inner_types::{G1Projective, InnerBls12381G1}, + decaf377, ed448_goldilocks, jubjub, k256, p256, p384, pallas, vsss_rs, +}; #[allow(async_fn_in_trait)] pub trait PointReader: BCA { @@ -115,6 +118,20 @@ impl PointReader for bulletproofs::JubJub { } } +impl PointReader for pallas::Pallas { + async fn read_point(path: PathBuf, file_name: &str) -> Result { + read_from_disk::(path, file_name).await + } + + async fn write_point(path: PathBuf, file_name: &str, point: &Self::Point) -> Result<()> { + write_to_disk(path, file_name, point).await + } + + fn parse_old_backup_public_key(public_key_hex: &str) -> Option { + None + } +} + impl PointReader for bulletproofs::Decaf377 { async fn read_point(path: PathBuf, file_name: &str) -> Result { read_from_disk::(path, file_name).await diff --git a/rust/lit-node/lit-node/src/tss/common/restore/restore_state.rs b/rust/lit-node/lit-node/src/tss/common/restore/restore_state.rs index 273106e..dfe5607 100644 --- a/rust/lit-node/lit-node/src/tss/common/restore/restore_state.rs +++ b/rust/lit-node/lit-node/src/tss/common/restore/restore_state.rs @@ -1,11 +1,8 @@ -use blsful::inner_types::{G1Projective, InnerBls12381G1}; use bulletproofs::BulletproofCurveArithmetic as BCA; -use elliptic_curve::Field; -use elliptic_curve::bigint::{NonZero, U256}; use ethers::types::H160; use sdd::{AtomicShared, Shared}; use serde::{Deserialize, Serialize}; -use std::io::{Error, ErrorKind}; +use std::io::Error; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use tokio::sync::RwLock; @@ -24,10 +21,17 @@ use crate::utils::contract::get_backup_recovery_contract_with_signer; use crate::version::{DataVersionReader, DataVersionWriter}; use lit_blockchain::contracts::backup_recovery::{BackupRecoveryErrors, RecoveredPeerId}; use lit_core::config::LitConfig; -use lit_node_core::CurveType; -use lit_node_core::PeerId; -use lit_node_core::{Blinders, CompressedBytes, CompressedHex}; +use lit_node_core::{Blinders, CompressedBytes, CompressedHex, CurveType, PeerId}; use lit_recovery::models::UploadedShareData; +use lit_rust_crypto::{ + blsful::inner_types::{G1Projective, InnerBls12381G1}, + decaf377, ed448_goldilocks, + elliptic_curve::{ + Field, + bigint::{NonZero, U256}, + }, + jubjub, k256, p256, p384, pallas, vsss_rs, +}; use verifiable_share_encryption::{DecryptionShare, VerifiableEncryptionDecryptor}; // DATIL_BACKUP: Remove this type once old Datil backup is obsolete. @@ -59,6 +63,7 @@ pub(crate) struct InnerState { pub jubjub_recovery_data: Option>, pub decaf377_recovery_data: Option>, pub bls12381g1_recovery_data: Option>, + pub pallas_recovery_data: Option>, pub threshold: usize, pub restored_key_cache: KeyCache, } @@ -105,6 +110,7 @@ impl RestoreState { let jubjub_blinder = jubjub::Scalar::random(&mut rng); let decaf377_blinder = decaf377::Fr::random(&mut rng); let bls12381g1_blinder = ::Scalar::random(&mut rng); + let pallas_blinder = pallas::Scalar::random(&mut rng); Blinders { bls_blinder: Some(bls_blinder), k256_blinder: Some(k256_blinder), @@ -116,6 +122,7 @@ impl RestoreState { jubjub_blinder: Some(jubjub_blinder), decaf377_blinder: Some(decaf377_blinder), bls12381g1_blinder: Some(bls12381g1_blinder), + pallas_blinder: Some(pallas_blinder), } } @@ -140,7 +147,7 @@ impl RestoreState { Ok(curve) => curve, Err(e) => { let err_msg = format!("Not a valid curve: {}", share.curve); - return Err(parser_err(Error::new(ErrorKind::Other, err_msg), None)); + return Err(parser_err(Error::other(err_msg), None)); } }; @@ -227,6 +234,9 @@ impl RestoreState { CurveType::BLS12381G1 => { Self::add_decryption_share(&mut inner.bls12381g1_recovery_data, rpm_id, share)? } + CurveType::RedPallas => { + Self::add_decryption_share(&mut inner.pallas_recovery_data, rpm_id, share)? + } }; } Ok(()) @@ -380,6 +390,18 @@ impl RestoreState { ) .await; } + if let Some(recovery_data) = &state.pallas_recovery_data { + restored_key_shares.pallas_shares = recovery_data + .try_restore( + state.threshold, + peer_id, + epoch, + realm_id, + staker_address, + &state.restored_key_cache, + ) + .await; + } restored_key_shares } @@ -429,13 +451,16 @@ impl RestoreState { &restored_key_shares.bls12381g1_shares, ); } + if let Some(data) = &mut state.pallas_recovery_data { + EksAndDs::mark_keys_restored(&mut data.eks_and_ds, &restored_key_shares.pallas_shares); + } } pub fn get_blinders(&self) -> DataVersionReader { DataVersionReader::new_unchecked(&self.blinders) } - pub fn get_blinders_mut(&self) -> DataVersionWriter { + pub fn get_blinders_mut(&self) -> DataVersionWriter<'_, Blinders> { DataVersionWriter::new_unchecked(&self.blinders) } @@ -493,6 +518,10 @@ impl RestoreState { &state.bls12381g1_recovery_data, &root_key.public_key, ), + CurveType::RedPallas => CurveRecoveryData::are_all_keys_restored( + &state.pallas_recovery_data, + &root_key.public_key, + ), }; debug!( "Root key is restored: {} {} {}", @@ -520,10 +549,7 @@ impl RestoreState { pub fn assert_actively_restoring(&self) -> Result<()> { match self.actively_restoring.load(Ordering::Acquire) { true => Ok(()), - false => Err(unexpected_err( - Error::new(ErrorKind::Other, "Not in RESTORE state"), - None, - )), + false => Err(unexpected_err(Error::other("Not in RESTORE state"), None)), } } @@ -548,7 +574,8 @@ impl RestoreState { .or(inner.ed448_recovery_data.as_ref().and_then(|d| d.original_peer_id())) .or(inner.jubjub_recovery_data.as_ref().and_then(|d| d.original_peer_id())) .or(inner.decaf377_recovery_data.as_ref().and_then(|d| d.original_peer_id())) - .or(inner.bls12381g1_recovery_data.as_ref().and_then(|d| d.original_peer_id())); + .or(inner.bls12381g1_recovery_data.as_ref().and_then(|d| d.original_peer_id()) + .or(inner.pallas_recovery_data.as_ref().and_then(|d| d.original_peer_id()))); match peer_id { Some(peer_id) => Ok(PeerId(NonZero::::from_uint(peer_id))), @@ -748,10 +775,7 @@ impl RestoreState { } fn ciphertexts_not_set() -> crate::error::Error { - unexpected_err( - Error::new(ErrorKind::Other, "Ciphertexts are not yet set"), - None, - ) + unexpected_err(Error::other("Ciphertexts are not yet set"), None) } #[instrument(level = "debug", skip_all)] @@ -791,7 +815,7 @@ impl RestoreState { Some(rd) => rd, None => { let err_msg = format!("Curve is not being restored: {}", share_data.curve); - return Err(parser_err(Error::new(ErrorKind::Other, err_msg), None)); + return Err(parser_err(Error::other(err_msg), None)); } }; @@ -804,7 +828,7 @@ impl RestoreState { recovery_data.encryption_key.to_compressed_hex(), share_data.encryption_key, ); - return Err(unexpected_err(Error::new(ErrorKind::Other, err_msg), None)); + return Err(unexpected_err(Error::other(err_msg), None)); } for eks_and_ds in recovery_data.eks_and_ds.iter_mut() { @@ -824,7 +848,7 @@ impl RestoreState { "An encrypted key share with pub_key {} does not exist.", share_data.verification_key ); - Err(unexpected_err(Error::new(ErrorKind::Other, err_msg), None)) + Err(unexpected_err(Error::other(err_msg), None)) } } @@ -840,10 +864,11 @@ pub struct RestoredKeyShares { pub jubjub_shares: Vec, pub decaf377_shares: Vec, pub bls12381g1_shares: Vec, + pub pallas_shares: Vec, } /// Used to log the state of the disaster recovery. -#[derive(Debug, Serialize, Deserialize)] +#[derive(Debug, Default, Serialize, Deserialize)] pub struct RestoreStateLog { actively_restoring: bool, backups_loaded: bool, @@ -858,6 +883,7 @@ pub struct RestoreStateLog { jubjub_enc_key: Option, decaf377_enc_key: Option, bls12381g1_enc_key: Option, + pallas_enc_key: Option, bls_shares: Vec, k256_shares: Vec, p256_shares: Vec, @@ -868,6 +894,7 @@ pub struct RestoreStateLog { jubjub_shares: Vec, decaf377_shares: Vec, bls12381g1_shares: Vec, + pallas_shares: Vec, threshold: usize, } @@ -893,6 +920,7 @@ impl RestoreStateLog { bls12381g1_enc_key: CurveRecoveryData::encryption_key( &state.bls12381g1_recovery_data, ), + pallas_enc_key: CurveRecoveryData::encryption_key(&state.pallas_recovery_data), bls_shares: CurveRecoveryData::log_shares(&state.bls_recovery_data), k256_shares: CurveRecoveryData::log_shares(&state.k256_recovery_data), p256_shares: CurveRecoveryData::log_shares(&state.p256_recovery_data), @@ -905,33 +933,12 @@ impl RestoreStateLog { jubjub_shares: CurveRecoveryData::log_shares(&state.jubjub_recovery_data), decaf377_shares: CurveRecoveryData::log_shares(&state.decaf377_recovery_data), bls12381g1_shares: CurveRecoveryData::log_shares(&state.bls12381g1_recovery_data), + pallas_shares: CurveRecoveryData::log_shares(&state.pallas_recovery_data), threshold: state.threshold, }, None => Self { actively_restoring: restore_state.actively_restoring.load(Ordering::Acquire), - backups_loaded: false, - recovery_party_members: Default::default(), - bls_enc_key: Default::default(), - k256_enc_key: Default::default(), - p256_enc_key: Default::default(), - p384_enc_key: Default::default(), - ed25519_enc_key: Default::default(), - ristretto25519_enc_key: Default::default(), - ed448_enc_key: Default::default(), - jubjub_enc_key: Default::default(), - decaf377_enc_key: Default::default(), - bls12381g1_enc_key: Default::default(), - bls_shares: Default::default(), - k256_shares: Default::default(), - p256_shares: Default::default(), - p384_shares: Default::default(), - ed25519_shares: Default::default(), - ristretto25519_shares: Default::default(), - ed448_shares: Default::default(), - jubjub_shares: Default::default(), - decaf377_shares: Default::default(), - bls12381g1_shares: Default::default(), - threshold: 0, + ..Default::default() }, } } @@ -1006,14 +1013,13 @@ mod tests { StorageType, read_key_share_from_disk, read_recovery_data_from_disk, }; use async_std::path::PathBuf; - use blsful::inner_types::G1Projective; - use elliptic_curve::Group; - use elliptic_curve::group::GroupEncoding; use k256::Secp256k1; - use lit_node_core::CompressedBytes; - use lit_node_core::CompressedHex; - use lit_node_core::CurveType; + use lit_node_core::{CompressedBytes, CompressedHex, CurveType}; use lit_recovery::models::{EncryptedKeyShare, OldEncryptedKeyShare, UploadedShareData}; + use lit_rust_crypto::{ + blsful::inner_types::G1Projective, + group::{Group, GroupEncoding}, + }; use verifiable_share_encryption::VerifiableEncryption; use vsss_rs::{DefaultShare, IdentifierPrimeField}; @@ -1305,7 +1311,7 @@ mod tests { where C: VerifiableEncryption + VerifiableEncryptionDecryptor, { - use elliptic_curve::PrimeField; + use lit_rust_crypto::ff::PrimeField; let mut decryption_key_bytes = hex::decode(decryption_key_share).unwrap(); if curve_type == CurveType::BLS { decryption_key_bytes.reverse(); // Converting from Big Endian to Little Endian which is required by DecryptionShare diff --git a/rust/lit-node/lit-node/src/tss/common/signing_scheme.rs b/rust/lit-node/lit-node/src/tss/common/signing_scheme.rs deleted file mode 100644 index b39a27f..0000000 --- a/rust/lit-node/lit-node/src/tss/common/signing_scheme.rs +++ /dev/null @@ -1,26 +0,0 @@ -use crate::error::{Result, unexpected_err}; -use lit_node_core::SigningScheme; - -pub fn signing_scheme_to_frost_scheme(value: SigningScheme) -> Result { - match value { - SigningScheme::Bls12381 | SigningScheme::Bls12381G1ProofOfPossession => Err( - unexpected_err("BLS signatures are not supported by FROST", None), - ), - SigningScheme::EcdsaK256Sha256 - | SigningScheme::EcdsaP256Sha256 - | SigningScheme::EcdsaP384Sha384 => Err(unexpected_err( - "ECDSA signatures are not supported by FROST", - None, - )), - SigningScheme::SchnorrEd25519Sha512 => Ok(lit_frost::Scheme::Ed25519Sha512), - SigningScheme::SchnorrK256Sha256 => Ok(lit_frost::Scheme::K256Sha256), - SigningScheme::SchnorrP256Sha256 => Ok(lit_frost::Scheme::P256Sha256), - SigningScheme::SchnorrP384Sha384 => Ok(lit_frost::Scheme::P384Sha384), - SigningScheme::SchnorrRistretto25519Sha512 => Ok(lit_frost::Scheme::Ristretto25519Sha512), - SigningScheme::SchnorrEd448Shake256 => Ok(lit_frost::Scheme::Ed448Shake256), - SigningScheme::SchnorrRedJubjubBlake2b512 => Ok(lit_frost::Scheme::RedJubjubBlake2b512), - SigningScheme::SchnorrK256Taproot => Ok(lit_frost::Scheme::K256Taproot), - SigningScheme::SchnorrRedDecaf377Blake2b512 => Ok(lit_frost::Scheme::RedDecaf377Blake2b512), - SigningScheme::SchnorrkelSubstrate => Ok(lit_frost::Scheme::SchnorrkelSubstrate), - } -} diff --git a/rust/lit-node/lit-node/src/tss/common/storage.rs b/rust/lit-node/lit-node/src/tss/common/storage.rs index c4b64a0..bc85883 100644 --- a/rust/lit-node/lit-node/src/tss/common/storage.rs +++ b/rust/lit-node/lit-node/src/tss/common/storage.rs @@ -486,7 +486,7 @@ async fn delete_from_disk(path: PathBuf, key_cache: &KeyCache) -> Result<()> { .to_str() .expect("Could not convert path to string") .to_string(); - key_cache.as_ref().remove(&key_path); + key_cache.as_ref().remove_sync(&key_path); Ok(()) } @@ -743,15 +743,15 @@ impl StorableFile { ) })?; - if file_type.is_file() { - if let Some(file_name) = entry.file_name().to_str() { - let storable_file: StorableFile = file_name.parse()?; - if storable_file.realm_id == self.realm_id - && storable_file.epoch < self.epoch - && storable_file.epoch != RECOVERY_DKG_EPOCH - { - let _r = delete_from_disk(entry.path(), key_cache).await; - } + if file_type.is_file() + && let Some(file_name) = entry.file_name().to_str() + { + let storable_file: StorableFile = file_name.parse()?; + if storable_file.realm_id == self.realm_id + && storable_file.epoch < self.epoch + && storable_file.epoch != RECOVERY_DKG_EPOCH + { + let _r = delete_from_disk(entry.path(), key_cache).await; } } } @@ -771,9 +771,12 @@ mod test { delete_keyshares_older_than_epoch, read_key_share_commitments_from_disk, write_key_share_commitments_to_disk, }; - use elliptic_curve::Group; - use lit_node_core::PeerId; - use lit_node_core::{CompressedHex, CurveType}; + use lit_node_core::{CompressedHex, CurveType, PeerId}; + use lit_rust_crypto::{ + blsful::inner_types::{G1Projective, Scalar}, + group::Group, + k256, + }; use rand_core::SeedableRng; use semver::Version; @@ -792,16 +795,15 @@ mod test { #[tokio::test] async fn delete_key_shares_older_than_epoch_test() { let peer_id = PeerId::from_u8(7); - let sk = blsful::inner_types::Scalar::from_bytes_wide(&[1u8; 64]); - let pk = blsful::inner_types::G1Projective::GENERATOR * sk; + let sk = Scalar::from_bytes_wide(&[1u8; 64]); + let pk = G1Projective::GENERATOR * sk; let pubkey = pk.to_compressed_hex(); let stkr = k256::Scalar::from(137u64); let stkr_pub = k256::ProjectivePoint::GENERATOR * stkr; let staker_address = stkr_pub.to_compressed_hex(); - let key_persistence = - KeyPersistence::::new(CurveType::BLS); + let key_persistence = KeyPersistence::::new(CurveType::BLS); let key_cache = KeyCache::default(); let peers = dummy_peers(); diff --git a/rust/lit-node/lit-node/src/tss/common/traits/cipherable.rs b/rust/lit-node/lit-node/src/tss/common/traits/cipherable.rs index 26c7914..b41b753 100644 --- a/rust/lit-node/lit-node/src/tss/common/traits/cipherable.rs +++ b/rust/lit-node/lit-node/src/tss/common/traits/cipherable.rs @@ -1,6 +1,6 @@ use crate::error::Result; // EC , conversion_err_code -use blsful::{Bls12381G2Impl, SignatureShare}; use lit_node_core::PeerId; +use lit_rust_crypto::blsful::{Bls12381G2Impl, SignatureShare}; use std::fmt::Debug; #[async_trait::async_trait] diff --git a/rust/lit-node/lit-node/src/tss/common/traits/vrf.rs b/rust/lit-node/lit-node/src/tss/common/traits/vrf.rs index 5b13f96..3fce294 100644 --- a/rust/lit-node/lit-node/src/tss/common/traits/vrf.rs +++ b/rust/lit-node/lit-node/src/tss/common/traits/vrf.rs @@ -1,6 +1,6 @@ use crate::error::Result; use crate::tss::common::traits::dkg::BasicDkg; -use elliptic_curve::{Group, group::GroupEncoding}; +use lit_rust_crypto::elliptic_curve::{Group, group::GroupEncoding}; use lit_vrf::Proof; #[allow(dead_code)] diff --git a/rust/lit-node/lit-node/src/tss/common/tss_state.rs b/rust/lit-node/lit-node/src/tss/common/tss_state.rs index 05aea55..6f11849 100644 --- a/rust/lit-node/lit-node/src/tss/common/tss_state.rs +++ b/rust/lit-node/lit-node/src/tss/common/tss_state.rs @@ -153,6 +153,7 @@ impl TssState { | SigningScheme::SchnorrEd448Shake256 | SigningScheme::SchnorrRedJubjubBlake2b512 | SigningScheme::SchnorrRedDecaf377Blake2b512 + | SigningScheme::SchnorrRedPallasBlake2b512 | SigningScheme::SchnorrkelSubstrate => { Box::new(FrostState::new(state, signing_scheme)) as Box } @@ -161,7 +162,7 @@ impl TssState { } _ => { return Err(unexpected_err( - "Unsupported key type when for Signable.", + "Unsupported key type when creating signing state.", None, )); } @@ -292,7 +293,11 @@ impl TssState { return 0; } - let curve_type = CurveType::K256; + let root_keys = self.chain_data_config_manager.root_keys(); + let curve_type = root_keys + .first() + .map(|rk| rk.curve_type) + .unwrap_or(CurveType::K256); let epoch = self.get_keyshare_epoch().await; let rt = match self .get_threshold_using_current_epoch_realm_peers_for_curve( diff --git a/rust/lit-node/lit-node/src/tss/dkg/engine.rs b/rust/lit-node/lit-node/src/tss/dkg/engine.rs index 9983253..e67e987 100644 --- a/rust/lit-node/lit-node/src/tss/dkg/engine.rs +++ b/rust/lit-node/lit-node/src/tss/dkg/engine.rs @@ -15,21 +15,23 @@ use crate::tss::common::storage::{ }; use crate::tss::common::tss_state::TssState; use crate::tss::dkg::models::{DkgOutput, Mode}; -use elliptic_curve::group::GroupEncoding; -use frost_dkg::elliptic_curve_tools::SumOfProducts; +use elliptic_curve_tools::SumOfProducts; use frost_dkg::*; use lit_blockchain::contracts::backup_recovery::RecoveredPeerId; use lit_core::error::Unexpected; -use lit_node_core::CurveType; -use lit_node_core::PeerId; -use lit_node_core::{CompressedBytes, CompressedHex}; +use lit_node_core::{CompressedBytes, CompressedHex, CurveType, PeerId}; +use lit_rust_crypto::{ + blsful, decaf377, ed448_goldilocks, + group::GroupEncoding, + jubjub, k256, p256, p384, pallas, + vsss_rs::{self, DefaultShare, IdentifierPrimeField, ParticipantIdGeneratorType}, +}; use serde::{Deserialize, Serialize}; use std::collections::btree_map::Values; use std::collections::{BTreeMap, HashMap, HashSet}; use std::num::NonZeroUsize; use std::sync::Arc; use tracing::instrument; -use vsss_rs::{DefaultShare, IdentifierPrimeField, ParticipantIdGeneratorType}; const MIN_EPOCH_FOR_COMMITMENT_DELETION: u64 = 1; #[derive(Clone, Debug)] @@ -276,11 +278,20 @@ impl DkgEngine { let participant = self .create_participant::( &create_participant_args, - Some(lit_frost::red_jubjub_generator()), + Some(lit_rust_crypto::red_jubjub_signing_generator()), ) .await?; dkg_participants.push(DkgCurve::JubJub(participant)); } + CurveType::RedPallas => { + let participant = self + .create_participant::( + &create_participant_args, + Some(lit_rust_crypto::red_pallas_signing_generator()), + ) + .await?; + dkg_participants.push(DkgCurve::Pallas(participant)); + } CurveType::RedDecaf377 => { let participant = self .create_participant::(&create_participant_args, None) @@ -497,6 +508,10 @@ impl DkgEngine { self.create_dkg_result::(&args, p.as_ref()) .await?, ), + DkgCurve::Pallas(p) => DkgResult::Pallas( + self.create_dkg_result::(&args, p.as_ref()) + .await?, + ), DkgCurve::Decaf377(p) => DkgResult::Decaf377( self.create_dkg_result::(&args, p.as_ref()) .await?, @@ -988,6 +1003,7 @@ pub enum DkgScalar { Ed448(ed448_goldilocks::Scalar), JubJub(jubjub::Scalar), Decaf377(decaf377::Fr), + Pallas(pallas::Scalar), Bls12381G1ProofOfPossession(blsful::inner_types::Scalar), } @@ -1003,6 +1019,7 @@ impl std::fmt::Display for DkgScalar { Self::Ed448(scalar) => scalar.to_compressed_hex(), Self::JubJub(scalar) => scalar.to_compressed_hex(), Self::Decaf377(scalar) => scalar.to_compressed_hex(), + Self::Pallas(scalar) => scalar.to_compressed_hex(), Self::Bls12381G1ProofOfPossession(scalar) => scalar.to_compressed_hex(), }; write!(f, "{}", hex) @@ -1019,6 +1036,7 @@ pub enum DkgResult { Ristretto256(DkgOutput), Ed448(DkgOutput), JubJub(DkgOutput), + Pallas(DkgOutput), Decaf377(DkgOutput), Bls12381G1ProofOfPossession(DkgOutput), } @@ -1063,6 +1081,10 @@ impl DkgResult { let helper = KeyPersistence::::new(CurveType::RedJubjub); helper.pk_to_hex(&output.pk) } + Self::Pallas(output) => { + let helper = KeyPersistence::::new(CurveType::RedPallas); + helper.pk_to_hex(&output.pk) + } Self::Decaf377(output) => { let helper = KeyPersistence::::new(CurveType::RedDecaf377); helper.pk_to_hex(&output.pk) @@ -1138,6 +1160,13 @@ impl DkgResult { public_key: helper.pk_to_hex(&output.pk), } } + Self::Pallas(output) => { + let helper = KeyPersistence::::new(CurveType::RedPallas); + CachedRootKey { + curve_type: CurveType::RedPallas, + public_key: helper.pk_to_hex(&output.pk), + } + } Self::Decaf377(output) => { let helper = KeyPersistence::::new(CurveType::RedDecaf377); CachedRootKey { @@ -1168,6 +1197,7 @@ pub enum DkgCurve { Ed448(Box>), JubJub(Box>), Decaf377(Box>), + Pallas(Box>), Bls12381G1ProofOfPossession(Box>), } @@ -1182,6 +1212,7 @@ impl DkgCurve { Self::Ristretto25519(participant) => participant.get_round(), Self::Ed448(participant) => participant.get_round(), Self::JubJub(participant) => participant.get_round(), + Self::Pallas(participant) => participant.get_round(), Self::Decaf377(participant) => participant.get_round(), Self::Bls12381G1ProofOfPossession(participant) => participant.get_round(), } @@ -1262,6 +1293,15 @@ impl DkgCurve { })?; Ok(DkgRoundOutputGenerator::JubJub(output)) } + DkgCurve::Pallas(participant) => { + let output = participant.run().map_err(|e| { + unexpected_err( + e, + Some("an error occurred while computing next round".to_string()), + ) + })?; + Ok(DkgRoundOutputGenerator::Pallas(output)) + } DkgCurve::Decaf377(participant) => { let output = participant.run().map_err(|e| { unexpected_err( @@ -1294,6 +1334,7 @@ impl DkgCurve { DkgCurve::Ristretto25519(participant) => participant.completed(), DkgCurve::Ed448(participant) => participant.completed(), DkgCurve::JubJub(participant) => participant.completed(), + DkgCurve::Pallas(participant) => participant.completed(), DkgCurve::Decaf377(participant) => participant.completed(), DkgCurve::Bls12381G1ProofOfPossession(participant) => participant.completed(), } @@ -1345,6 +1386,12 @@ impl DkgCurve { ) => participant.receive(&participant_data.data).map_err(|e| { unexpected_err(e, Some("an error occurred while receiving".to_string())) }), + ( + DkgCurve::Pallas(participant), + DkgParticipantRoundOutput::Pallas(participant_data), + ) => participant.receive(&participant_data.data).map_err(|e| { + unexpected_err(e, Some("an error occurred while receiving".to_string())) + }), ( DkgCurve::Decaf377(participant), DkgParticipantRoundOutput::Decaf377(participant_data), @@ -1390,6 +1437,9 @@ impl DkgCurve { DkgCurve::JubJub(participant) => participant .get_public_key() .map(|pk| ::to_compressed(&pk)), + DkgCurve::Pallas(participant) => participant + .get_public_key() + .map(|pk| ::to_compressed(&pk)), DkgCurve::Decaf377(participant) => participant .get_public_key() .map(|pk| ::to_compressed(&pk)), @@ -1431,6 +1481,9 @@ impl DkgCurve { DkgCurve::JubJub(participant) => participant .get_secret_share() .map(|share| ::to_compressed(&share.value.0)), + DkgCurve::Pallas(participant) => participant + .get_secret_share() + .map(|share| ::to_compressed(&share.value.0)), DkgCurve::Decaf377(participant) => participant .get_secret_share() .map(|share| ::to_compressed(&share.value.0)), @@ -1453,6 +1506,7 @@ pub enum DkgRoundOutputGenerator { Ristretto25519(RoundOutputGenerator), Ed448(RoundOutputGenerator), JubJub(RoundOutputGenerator), + Pallas(RoundOutputGenerator), Decaf377(RoundOutputGenerator), Bls12381G1ProofOfPossession(RoundOutputGenerator), } @@ -1486,6 +1540,9 @@ impl DkgRoundOutputGenerator { DkgRoundOutputGenerator::JubJub(generator) => { Box::new(generator.iter().map(DkgParticipantRoundOutput::JubJub)) } + DkgRoundOutputGenerator::Pallas(generator) => { + Box::new(generator.iter().map(DkgParticipantRoundOutput::Pallas)) + } DkgRoundOutputGenerator::Decaf377(generator) => { Box::new(generator.iter().map(DkgParticipantRoundOutput::Decaf377)) } @@ -1514,6 +1571,7 @@ pub enum DkgParticipantRoundOutput { Ristretto25519(ParticipantRoundOutput), Ed448(ParticipantRoundOutput), JubJub(ParticipantRoundOutput), + Pallas(ParticipantRoundOutput), Decaf377(ParticipantRoundOutput), Bls12381G1ProofOfPossession(ParticipantRoundOutput), } @@ -1530,6 +1588,7 @@ impl DkgParticipantRoundOutput { Self::Ed448(data) => DkgScalar::Ed448(data.dst_id.0), Self::JubJub(data) => DkgScalar::JubJub(data.dst_id.0), Self::Decaf377(data) => DkgScalar::Decaf377(data.dst_id.0), + Self::Pallas(data) => DkgScalar::Pallas(data.dst_id.0), Self::Bls12381G1ProofOfPossession(data) => { DkgScalar::Bls12381G1ProofOfPossession(data.dst_id.0) } @@ -1546,6 +1605,7 @@ impl DkgParticipantRoundOutput { Self::Ristretto25519(data) => data.dst_ordinal, Self::Ed448(data) => data.dst_ordinal, Self::JubJub(data) => data.dst_ordinal, + Self::Pallas(data) => data.dst_ordinal, Self::Decaf377(data) => data.dst_ordinal, Self::Bls12381G1ProofOfPossession(data) => data.dst_ordinal, } @@ -1561,6 +1621,7 @@ impl DkgParticipantRoundOutput { Self::Ristretto25519(data) => data.data.clone(), Self::Ed448(data) => data.data.clone(), Self::JubJub(data) => data.data.clone(), + Self::Pallas(data) => data.data.clone(), Self::Decaf377(data) => data.data.clone(), Self::Bls12381G1ProofOfPossession(data) => data.data.clone(), } diff --git a/rust/lit-node/lit-node/src/tss/dkg/manager.rs b/rust/lit-node/lit-node/src/tss/dkg/manager.rs index 020e03d..fcd0343 100644 --- a/rust/lit-node/lit-node/src/tss/dkg/manager.rs +++ b/rust/lit-node/lit-node/src/tss/dkg/manager.rs @@ -112,21 +112,21 @@ impl DkgManager { "DKG {} with ID {} completed: {:?}", self.dkg_type, dkg_id, mode ); - if let Some(m) = mode { - if m == Mode::Initial { - for dkg in dkg_engine.get_dkgs() { - match dkg.result { - Some(ref result) => { - debug!( - "DKG for epoch change complete for {} {}.", - dkg.dkg_id, dkg.curve_type - ); - root_keys.push(result.dkg_root_key()); - } - None => { - error!("DKG failed!"); - return Err(unexpected_err("DKG failed", None)); - } + if let Some(m) = mode + && m == Mode::Initial + { + for dkg in dkg_engine.get_dkgs() { + match dkg.result { + Some(ref result) => { + debug!( + "DKG for epoch change complete for {} {}.", + dkg.dkg_id, dkg.curve_type + ); + root_keys.push(result.dkg_root_key()); + } + None => { + error!("DKG failed!"); + return Err(unexpected_err("DKG failed", None)); } } } diff --git a/rust/lit-node/lit-node/src/tss/dkg/models.rs b/rust/lit-node/lit-node/src/tss/dkg/models.rs index 4bf60ea..ed1c430 100644 --- a/rust/lit-node/lit-node/src/tss/dkg/models.rs +++ b/rust/lit-node/lit-node/src/tss/dkg/models.rs @@ -1,5 +1,5 @@ -use elliptic_curve::group::{Group, GroupEncoding}; use lit_node_core::PeerId; +use lit_rust_crypto::group::{Group, GroupEncoding}; use serde::{Deserialize, Serialize}; use std::fmt::{self, Display, Formatter}; diff --git a/rust/lit-node/lit-node/src/tss/ecdsa_damfast/mod.rs b/rust/lit-node/lit-node/src/tss/ecdsa_damfast/mod.rs index 35d6809..8d22e79 100644 --- a/rust/lit-node/lit-node/src/tss/ecdsa_damfast/mod.rs +++ b/rust/lit-node/lit-node/src/tss/ecdsa_damfast/mod.rs @@ -9,7 +9,6 @@ use crate::{ peers::peer_state::models::SimplePeerCollection, tss::common::{dkg_type::DkgType, tss_state::TssState}, }; -use elliptic_curve::{CurveArithmetic, FieldBytesSize, NonZeroScalar, PrimeCurve}; use lit_core::error::Unexpected; use lit_core::utils::binary::bytes_to_hex; use lit_fast_ecdsa::{ @@ -23,13 +22,19 @@ use tracing::trace; use super::common::traits::signable::Signable; use crate::tasks::utils::generate_hash; use crate::utils::traits::SignatureCurve; -use elliptic_curve::generic_array::ArrayLength; -use elliptic_curve::group::{Curve, GroupEncoding}; -use hd_keys_curves::{HDDerivable, HDDeriver}; -use k256::ecdsa::hazmat::DigestPrimitive; -use lit_node_core::PeerId; -use lit_node_core::SigningScheme; -use lit_node_core::{CompressedBytes, CompressedHex}; +use lit_node_core::{ + CompressedBytes, CompressedHex, PeerId, SigningScheme, + hd_keys_curves_wasm::{HDDerivable, HDDeriver}, +}; +use lit_rust_crypto::{ + elliptic_curve::{ + CurveArithmetic, FieldBytesSize, NonZeroScalar, PrimeCurve, ScalarPrimitive, + generic_array::ArrayLength, + }, + group::{Curve, GroupEncoding}, + k256::{self, ecdsa::hazmat::DigestPrimitive}, + p256, p384, +}; use serde::Serialize; use std::sync::Arc; use tracing::instrument; @@ -366,13 +371,12 @@ impl DamFastState { )); } - let scalar_primitive = elliptic_curve::ScalarPrimitive::::from_slice(message_bytes) - .map_err(|e| { - unexpected_err( - e, - Some("Could not convert message to sign into ScalarPrimitive".into()), - ) - })?; + let scalar_primitive = ScalarPrimitive::::from_slice(message_bytes).map_err(|e| { + unexpected_err( + e, + Some("Could not convert message to sign into ScalarPrimitive".into()), + ) + })?; let msg_digest = C::Scalar::from(scalar_primitive); let peer_id = Option::>::from(NonZeroScalar::::new(C::Scalar::from( diff --git a/rust/lit-node/lit-node/src/tss/frost/mod.rs b/rust/lit-node/lit-node/src/tss/frost/mod.rs index 03d3039..f13ba04 100644 --- a/rust/lit-node/lit-node/src/tss/frost/mod.rs +++ b/rust/lit-node/lit-node/src/tss/frost/mod.rs @@ -2,7 +2,6 @@ use crate::error::{EC, parser_err, unexpected_err, unexpected_err_code}; use crate::p2p_comms::CommsManager; use crate::peers::peer_state::models::SimplePeer; use crate::tss::common::hd_keys::get_derived_keyshare; -use crate::tss::common::signing_scheme::signing_scheme_to_frost_scheme; use crate::tss::common::traits::signable::Signable; use crate::{ error::Result, @@ -10,19 +9,22 @@ use crate::{ peers::peer_state::models::SimplePeerCollection, tss::common::{dkg_type::DkgType, tss_state::TssState}, }; -use blsful::inner_types::GroupEncoding; -use hd_keys_curves::{HDDerivable, HDDeriver}; use lit_core::error::Unexpected; use lit_core::utils::binary::bytes_to_hex; use lit_frost::{ Identifier, KeyPackage, Scheme, SignatureShare, SigningCommitments, SigningShare, VerifyingKey, VerifyingShare, }; -use lit_node_core::CompressedBytes; -use lit_node_core::CurveType; -use lit_node_core::NodeSet; -use lit_node_core::PeerId; -use lit_node_core::{FrostSignedMessageShare, SignableOutput, SigningAlgorithm, SigningScheme}; +use lit_node_core::{ + CompressedBytes, CurveType, FrostSignedMessageShare, NodeSet, PeerId, SignableOutput, + SigningAlgorithm, SigningScheme, + hd_keys_curves_wasm::{HDDerivable, HDDeriver}, +}; +use lit_rust_crypto::{ + curve25519_dalek, decaf377, ed448_goldilocks, group::GroupEncoding, jubjub, k256, p256, p384, + pallas, vsss_rs, +}; +use lit_sdk::signature::signing_scheme_to_frost_scheme; use std::{num::NonZeroU16, sync::Arc}; use verifiable_share_encryption::legacy_vsss_rs::ShareIdentifier; @@ -85,7 +87,8 @@ impl FrostState { // setup signing protocol let mut rng = rand::rngs::OsRng; let self_peer = peers.peer_at_address(&self.state.addr)?; - let scheme: Scheme = signing_scheme_to_frost_scheme(signature_scheme)?; + let scheme: Scheme = signing_scheme_to_frost_scheme(signature_scheme) + .map_err(|e| unexpected_err(e, None))?; let identifier = self.peer_id_to_frost_identifier(self_peer.peer_id)?; let verifying_share = scheme.verifying_share(secret_share).map_err(|e| { @@ -172,7 +175,8 @@ impl FrostState { ) .await?; - let scheme = signing_scheme_to_frost_scheme(self.signing_scheme)?; + let scheme = signing_scheme_to_frost_scheme(self.signing_scheme) + .map_err(|e| unexpected_err(e, None))?; let vk = VerifyingKey { scheme, value: pk.to_compressed(), @@ -197,6 +201,7 @@ impl FrostState { .to_vec(), CurveType::RedJubjub => jubjub::Scalar::from(peer_id).to_bytes().to_vec(), CurveType::RedDecaf377 => decaf377::Fr::from(peer_id).to_bytes().to_vec(), + CurveType::RedPallas => pallas::Scalar::from(peer_id).to_le_bytes().to_vec(), _ => { // Shouldn't happen but just in case return Err(unexpected_err( @@ -205,7 +210,8 @@ impl FrostState { )); } }; - let scheme = signing_scheme_to_frost_scheme(self.signing_scheme)?; + let scheme = signing_scheme_to_frost_scheme(self.signing_scheme) + .map_err(|e| unexpected_err(e, None))?; Ok(Identifier { scheme, id: bytes }) } } @@ -318,6 +324,16 @@ impl Signable for FrostState { ) .await? } + SigningScheme::SchnorrRedPallasBlake2b512 => { + let deriver = pallas::Scalar::create(&key_id, self.signing_scheme.id_sign_ctx()); + self.derive_frost_signing_components::( + deriver, + root_pubkeys, + &self_peer, + epoch, + ) + .await? + } _ => { return Err(unexpected_err( format!("Unsupported schnorr type: {}", self.signing_scheme), diff --git a/rust/lit-node/lit-node/src/utils/contract.rs b/rust/lit-node/lit-node/src/utils/contract.rs index 830c40b..0919f98 100644 --- a/rust/lit-node/lit-node/src/utils/contract.rs +++ b/rust/lit-node/lit-node/src/utils/contract.rs @@ -4,7 +4,6 @@ use crate::error::{Result, unexpected_err}; use ethers::middleware::SignerMiddleware; use ethers::providers::{Http, Provider}; use ethers::signers::Wallet; -use k256::ecdsa::SigningKey; use lit_blockchain::contracts::backup_recovery::BackupRecovery; use lit_blockchain::contracts::ledger::Ledger; use lit_blockchain::contracts::pkp_permissions::PKPPermissions; @@ -14,6 +13,7 @@ use lit_blockchain::contracts::pubkey_router::PubkeyRouter; use lit_blockchain::resolver::contract::ContractResolver; use lit_blockchain::util::ether::middleware::EIP2771GasRelayerMiddleware; use lit_core::config::LitConfig; +use lit_rust_crypto::k256::ecdsa::SigningKey; use std::sync::Arc; pub async fn get_pkp_permissions_contract( diff --git a/rust/lit-node/lit-node/src/utils/eth.rs b/rust/lit-node/lit-node/src/utils/eth.rs index 0ff2c86..09fe8ad 100644 --- a/rust/lit-node/lit-node/src/utils/eth.rs +++ b/rust/lit-node/lit-node/src/utils/eth.rs @@ -3,7 +3,7 @@ use crate::error::{Result, conversion_err}; use ethers::prelude::H160; use ethers::types::Address; -use k256::ecdsa::{SigningKey, VerifyingKey}; +use lit_rust_crypto::k256::ecdsa::{SigningKey, VerifyingKey}; use sha3::{Keccak256, digest::Digest}; pub trait EthereumAddress { diff --git a/rust/lit-node/lit-node/src/utils/key_share_proof.rs b/rust/lit-node/lit-node/src/utils/key_share_proof.rs index fa6b13d..ce351dd 100644 --- a/rust/lit-node/lit-node/src/utils/key_share_proof.rs +++ b/rust/lit-node/lit-node/src/utils/key_share_proof.rs @@ -10,13 +10,24 @@ use crate::{ storage::read_key_share_commitments_from_disk, }, }; -use blsful::{Pairing, SecretKeyShare, Signature}; -use elliptic_curve::Group; use futures::future::join_all; -use hd_keys_curves::{HDDerivable, HDDeriver}; use lit_core::error::Result; use lit_core::utils::binary::bytes_to_hex; -use lit_node_core::{CompressedBytes, CurveType, PeerId}; +use lit_node_core::{ + CompressedBytes, CurveType, PeerId, + hd_keys_curves_wasm::{HDDerivable, HDDeriver}, +}; +use lit_rust_crypto::{ + blsful::{ + Bls12381G2Impl, Pairing, PublicKey, SecretKey, SecretKeyShare, Signature, SignatureSchemes, + SignatureShare, + inner_types::{G1Projective, Scalar}, + }, + ed448_goldilocks, + group::Group, + k256, p256, p384, pallas, + vsss_rs::{IdentifierPrimeField, Share}, +}; use lit_vrf::*; use serde::{Deserialize, Serialize}; use std::collections::HashMap; @@ -25,7 +36,6 @@ use std::{ fmt::{self, Debug, Display, Formatter}, }; use tracing::instrument; -use vsss_rs::{IdentifierPrimeField, Share}; const VRF_KEY_SHARE_VALIDATION_PREFIX: &str = "vrf-key-share-validation-"; /// Proofs for key share validation @@ -181,23 +191,19 @@ pub async fn compute_key_share_proof( ) .await?; - let identifier = <::PublicKey as Group>::Scalar::from( - bls_key_share.peer_id, - ); - let value = bls_key_share.secret::<::PublicKey>()?; + let identifier = + <::PublicKey as Group>::Scalar::from(bls_key_share.peer_id); + let value = bls_key_share.secret::<::PublicKey>()?; - let secret_key_share: SecretKeyShare = SecretKeyShare( - ::SecretKeyShare::with_identifier_and_value( + let secret_key_share: SecretKeyShare = SecretKeyShare( + ::SecretKeyShare::with_identifier_and_value( IdentifierPrimeField(identifier), IdentifierPrimeField(value), ), ); let sks = secret_key_share - .sign( - blsful::SignatureSchemes::ProofOfPossession, - noonce.as_bytes(), - ) + .sign(SignatureSchemes::ProofOfPossession, noonce.as_bytes()) .map_err(|e| unexpected_err(format!("Failed to sign message: {:?}", e), None))?; return postcard::to_stdvec(&sks) @@ -230,13 +236,20 @@ pub async fn compute_key_share_proof( CurveType::RedJubjub => { compute_key_share_proof_internal::( &args, - Some(lit_frost::red_jubjub_generator()), + Some(lit_rust_crypto::red_jubjub_signing_generator()), ) .await } CurveType::RedDecaf377 => { compute_key_share_proof_internal::(&args, None).await } + CurveType::RedPallas => { + compute_key_share_proof_internal::( + &args, + Some(lit_rust_crypto::red_pallas_signing_generator()), + ) + .await + } CurveType::BLS12381G1 => { if root_keys.is_empty() { return Err(unexpected_err( @@ -247,12 +260,10 @@ pub async fn compute_key_share_proof( let vrf_deriver_id = format!("{}{}", VRF_KEY_SHARE_VALIDATION_PREFIX, curve_type.as_str()); - let deriver = ::create( - vrf_deriver_id.as_bytes(), - curve_type.vrf_ctx(), - ); + let deriver = + ::create(vrf_deriver_id.as_bytes(), curve_type.vrf_ctx()); let key_cache = KeyCache::default(); - let (sk, _) = get_derived_keyshare::( + let (sk, _) = get_derived_keyshare::( deriver, root_keys, curve_type, @@ -263,11 +274,8 @@ pub async fn compute_key_share_proof( &key_cache, ) .await?; - let signature: Signature = blsful::SecretKey(sk) - .sign( - blsful::SignatureSchemes::ProofOfPossession, - noonce.as_bytes(), - ) + let signature: Signature = SecretKey(sk) + .sign(SignatureSchemes::ProofOfPossession, noonce.as_bytes()) .map_err(|_| unexpected_err("cannot generate BLS proof".to_string(), None))?; postcard::to_stdvec(&signature) @@ -413,42 +421,37 @@ pub async fn verify_key_share_proofs( return Err(unexpected_err("No root keys found!".to_string(), None)); } let key_cache = KeyCache::default(); - let commitments = read_key_share_commitments_from_disk::< - KeyShareCommitments, - >( - curve_type, - &args.root_keys[0], - staker_address, - &self_peer.peer_id, - epoch, // this will possibly not be the same epoch as the node doing the request, and the results will be mismatched proofs. - realm_id, - &key_cache, - ) - .await?; - let sig_share = postcard::from_bytes::< - blsful::SignatureShare, - >(args.proof) - .map_err(|e| unexpected_err(e, Some("cannot deserialize BLS proof".to_string())))?; + let commitments = + read_key_share_commitments_from_disk::>( + curve_type, + &args.root_keys[0], + staker_address, + &self_peer.peer_id, + epoch, // this will possibly not be the same epoch as the node doing the request, and the results will be mismatched proofs. + realm_id, + &key_cache, + ) + .await?; + let sig_share = postcard::from_bytes::>(args.proof) + .map_err(|e| { + unexpected_err(e, Some("cannot deserialize BLS proof".to_string())) + })?; let signature_point = sig_share.as_raw_value().0.value.0; let signature = match sig_share { - blsful::SignatureShare::Basic(sig) => { - blsful::Signature::::Basic(signature_point) + SignatureShare::Basic(sig) => { + Signature::::Basic(signature_point) } - blsful::SignatureShare::MessageAugmentation(sig) => { - blsful::Signature::::MessageAugmentation( - signature_point, - ) + SignatureShare::MessageAugmentation(sig) => { + Signature::::MessageAugmentation(signature_point) } - blsful::SignatureShare::ProofOfPossession(sig) => { - blsful::Signature::::ProofOfPossession( - signature_point, - ) + SignatureShare::ProofOfPossession(sig) => { + Signature::::ProofOfPossession(signature_point) } }; - let key_share_commitment = commitments - .compute_key_share_commitment(&blsful::inner_types::Scalar::from(peer_id)); - let pub_key = blsful::PublicKey::(key_share_commitment); + let key_share_commitment = + commitments.compute_key_share_commitment(&Scalar::from(peer_id)); + let pub_key = PublicKey::(key_share_commitment); verification_checks.insert( curve_type, signature.verify(&pub_key, noonce.as_bytes()).map_err(|e| { @@ -498,7 +501,7 @@ pub async fn verify_key_share_proofs( curve_type, verify_key_share_proofs_internal::( &args, - Some(lit_frost::red_jubjub_generator()), + Some(lit_rust_crypto::red_jubjub_signing_generator()), ) .await, ); @@ -509,48 +512,52 @@ pub async fn verify_key_share_proofs( verify_key_share_proofs_internal::(&args, None).await, ); } + CurveType::RedPallas => { + verification_checks.insert( + curve_type, + verify_key_share_proofs_internal::( + &args, + Some(lit_rust_crypto::red_pallas_signing_generator()), + ) + .await, + ); + } CurveType::BLS12381G1 => { if args.root_keys.is_empty() { return Err(unexpected_err("No root keys found!".to_string(), None)); } - let peer_id_scalar = blsful::inner_types::Scalar::from(peer_id); + let peer_id_scalar = Scalar::from(peer_id); let mut key_share_commitments = Vec::with_capacity(root_keys.len()); let key_cache = KeyCache::default(); for (i, root_key) in args.root_keys.iter().enumerate() { - let commitments = read_key_share_commitments_from_disk::< - KeyShareCommitments, - >( - curve_type, - root_key, - staker_address, - &self_peer.peer_id, - epoch, // this will possibly not be the same epoch as the node doing the request, and the results will be mismatched proofs. - realm_id, - &key_cache, - ) - .await?; + let commitments = + read_key_share_commitments_from_disk::>( + curve_type, + root_key, + staker_address, + &self_peer.peer_id, + epoch, // this will possibly not be the same epoch as the node doing the request, and the results will be mismatched proofs. + realm_id, + &key_cache, + ) + .await?; let key_share_commitment = commitments.compute_key_share_commitment(&peer_id_scalar); key_share_commitments.push(key_share_commitment); } - let signature = postcard::from_bytes::>( - args.proof, - ) - .map_err(|e| unexpected_err(e, Some("cannot deserialize BLS proof".to_string())))?; + let signature = postcard::from_bytes::>(args.proof) + .map_err(|e| { + unexpected_err(e, Some("cannot deserialize BLS proof".to_string())) + })?; let vrf_deriver_id = format!("{}{}", VRF_KEY_SHARE_VALIDATION_PREFIX, curve_type.as_str()); - let deriver = ::create( - vrf_deriver_id.as_bytes(), - curve_type.vrf_ctx(), - ); + let deriver = + ::create(vrf_deriver_id.as_bytes(), curve_type.vrf_ctx()); let key_share_commitment = - ::hd_derive_public_key( - &deriver, - &key_share_commitments, - ); - let pub_key = blsful::PublicKey::(key_share_commitment); + ::hd_derive_public_key(&deriver, &key_share_commitments); + let pub_key = PublicKey::(key_share_commitment); verification_checks.insert( curve_type, signature.verify(&pub_key, noonce.as_bytes()).map_err(|e| { @@ -634,9 +641,11 @@ struct VerifyKeyShareProofArgs<'a> { #[cfg(test)] mod tests { use super::*; - use elliptic_curve::Field; + use lit_rust_crypto::{ + ff::Field, + vsss_rs::{DefaultShare, IdentifierPrimeField, shamir}, + }; use rand::{RngCore, SeedableRng}; - use vsss_rs::{DefaultShare, IdentifierPrimeField, shamir}; #[test] fn dkg_and_test_vrf() { diff --git a/rust/lit-node/lit-node/src/utils/traits.rs b/rust/lit-node/lit-node/src/utils/traits.rs index 7f18df0..ab97163 100644 --- a/rust/lit-node/lit-node/src/utils/traits.rs +++ b/rust/lit-node/lit-node/src/utils/traits.rs @@ -1,5 +1,8 @@ -use elliptic_curve::Group; use lit_node_core::CurveType; +use lit_rust_crypto::{ + blsful::inner_types, decaf377, ed448_goldilocks, group::Group, jubjub, k256, p256, p384, + pallas, vsss_rs, +}; pub trait SignatureCurve { const CURVE_TYPE: CurveType; @@ -67,7 +70,16 @@ impl SignatureCurve for bulletproofs::JubJub { type Point = jubjub::SubgroupPoint; fn signing_generator() -> Self::Point { - lit_frost::red_jubjub_generator() + lit_rust_crypto::red_jubjub_signing_generator() + } +} + +impl SignatureCurve for pallas::Pallas { + const CURVE_TYPE: CurveType = CurveType::RedPallas; + type Point = pallas::Point; + + fn signing_generator() -> Self::Point { + lit_rust_crypto::red_pallas_signing_generator() } } @@ -80,11 +92,11 @@ impl SignatureCurve for bulletproofs::Decaf377 { } } -impl SignatureCurve for blsful::inner_types::InnerBls12381G1 { +impl SignatureCurve for inner_types::InnerBls12381G1 { const CURVE_TYPE: CurveType = CurveType::BLS12381G1; - type Point = blsful::inner_types::G1Projective; + type Point = inner_types::G1Projective; fn signing_generator() -> Self::Point { - blsful::inner_types::G1Projective::GENERATOR + inner_types::G1Projective::GENERATOR } } diff --git a/rust/lit-node/lit-node/src/utils/web.rs b/rust/lit-node/lit-node/src/utils/web.rs index c59dcc0..2059a74 100644 --- a/rust/lit-node/lit-node/src/utils/web.rs +++ b/rust/lit-node/lit-node/src/utils/web.rs @@ -683,11 +683,11 @@ pub fn hash_access_control_conditions(req: RequestConditions) -> Result // hash differently if this is v1 or v2 conditions let mut is_v2 = false; for condition_item in sol_rpc_conditions { - if let SolRpcConditionItem::Condition(condition) = condition_item { - if condition.pda_params.is_some() { - is_v2 = true; - break; - } + if let SolRpcConditionItem::Condition(condition) = condition_item + && condition.pda_params.is_some() + { + is_v2 = true; + break; } } if is_v2 { diff --git a/rust/lit-node/lit-node/tests/acceptance/chain_interaction.rs b/rust/lit-node/lit-node/tests/acceptance/chain_interaction.rs index 1f92a6f..67483c5 100644 --- a/rust/lit-node/lit-node/tests/acceptance/chain_interaction.rs +++ b/rust/lit-node/lit-node/tests/acceptance/chain_interaction.rs @@ -34,6 +34,7 @@ use lit_node_core::{ CHAIN_LOCALCHAIN, }, }; +use lit_rust_crypto::blsful::PublicKey; use lit_node::models::RequestConditions; @@ -146,7 +147,7 @@ async fn test_encryption_decryption_eip1271( )) .get_resource_key() .into_bytes(); - let pubkey = blsful::PublicKey::try_from(&hex::decode(&network_pubkey).unwrap()).unwrap(); + let pubkey = PublicKey::try_from(&hex::decode(&network_pubkey).unwrap()).unwrap(); let ciphertext = lit_sdk::encryption::encrypt_time_lock(&pubkey, message_bytes, &identity_param) .expect("Unable to encrypt"); diff --git a/rust/lit-node/lit-node/tests/acceptance/payment.rs b/rust/lit-node/lit-node/tests/acceptance/payment.rs index baaf42a..a4956cb 100644 --- a/rust/lit-node/lit-node/tests/acceptance/payment.rs +++ b/rust/lit-node/lit-node/tests/acceptance/payment.rs @@ -48,7 +48,9 @@ async fn test_all_payment_methods_for_user() { let test_encryption_parameters = prepare_test_encryption_parameters(); let network_pubkey = get_network_pubkey(&actions).await; let message_bytes = test_encryption_parameters.to_encrypt.as_bytes(); - let pubkey = blsful::PublicKey::try_from(&hex::decode(&network_pubkey).unwrap()).unwrap(); + let pubkey = + lit_rust_crypto::blsful::PublicKey::try_from(&hex::decode(&network_pubkey).unwrap()) + .unwrap(); let ciphertext = lit_sdk::encryption::encrypt_time_lock( &pubkey, message_bytes, @@ -805,7 +807,9 @@ async fn test_all_payment_methods_for_pkp() { let network_pubkey = get_network_pubkey(&actions).await; let message_bytes = test_encryption_parameters.to_encrypt.as_bytes(); - let bls_pubkey = blsful::PublicKey::try_from(&hex::decode(&network_pubkey).unwrap()).unwrap(); + let bls_pubkey = + lit_rust_crypto::blsful::PublicKey::try_from(&hex::decode(&network_pubkey).unwrap()) + .unwrap(); let ciphertext = lit_sdk::encryption::encrypt_time_lock( &bls_pubkey, @@ -1212,7 +1216,9 @@ async fn test_pending_payments_block_usage() { let test_encryption_parameters = prepare_test_encryption_parameters(); let network_pubkey = get_network_pubkey(&actions).await; let message_bytes = test_encryption_parameters.to_encrypt.as_bytes(); - let pubkey = blsful::PublicKey::try_from(&hex::decode(&network_pubkey).unwrap()).unwrap(); + let pubkey = + lit_rust_crypto::blsful::PublicKey::try_from(&hex::decode(&network_pubkey).unwrap()) + .unwrap(); let ciphertext = lit_sdk::encryption::encrypt_time_lock( &pubkey, message_bytes, diff --git a/rust/lit-node/lit-node/tests/common/auth_sig.rs b/rust/lit-node/lit-node/tests/common/auth_sig.rs index 391650d..142b786 100644 --- a/rust/lit-node/lit-node/tests/common/auth_sig.rs +++ b/rust/lit-node/lit-node/tests/common/auth_sig.rs @@ -4,7 +4,6 @@ use std::ops::Add; use std::str::FromStr; use anyhow::Result; -use blsful::{Bls12381G2Impl, Signature, SignatureShare}; use chrono::{Duration, SecondsFormat}; use ed25519_dalek::Signer; use ethers::core::k256::ecdsa::SigningKey; @@ -16,12 +15,13 @@ use lit_core::config::LitConfig; use lit_node::models::auth::SessionKeySignedMessageV2; use lit_node::payment::payed_endpoint::PayedEndpoint; use lit_node::utils::encoding::{self, hex_to_bytes}; -use lit_node_core::CurveType; -use lit_node_core::response::JsonSignSessionKeyResponseV2; use lit_node_core::{ - AuthMethod, AuthSigItem, JsonAuthSig, LitResourceAbilityRequest, LitResourcePrefix, NodeSet, + AuthMethod, AuthSigItem, CurveType, JsonAuthSig, LitResourceAbilityRequest, LitResourcePrefix, + NodeSet, constants::{AUTH_SIG_DERIVED_VIA_SESSION_SIG, AUTH_SIG_SESSION_SIG_ALGO}, + response::JsonSignSessionKeyResponseV2, }; +use lit_rust_crypto::blsful::{Bls12381G2Impl, PublicKey, Signature, SignatureShare}; use serde_json::Value; use siwe::Message; use siwe_recap::Capability; @@ -38,6 +38,7 @@ use rand_core::RngCore; use super::session_sigs::SessionSigAndNodeSet; use lit_node_testnet::node_collection::NodeIdentityKey; +use lit_rust_crypto::k256; use lit_sdk::UrlPrefix; pub fn node_wallet(cfg: &LitConfig) -> Result> { @@ -387,7 +388,7 @@ pub async fn get_session_delegation_sig_for_pkp( let signature = Signature::from_shares(&shares)?; - let bls_root_key = blsful::PublicKey::::try_from( + let bls_root_key = PublicKey::::try_from( &hex::decode(&one_response_with_share.bls_root_pubkey).expect("Failed to decode root key"), ) .expect("Failed to convert bls public key from bytes"); diff --git a/rust/lit-node/lit-node/tests/common/interpolation.rs b/rust/lit-node/lit-node/tests/common/interpolation.rs index 5721214..50a9f40 100644 --- a/rust/lit-node/lit-node/tests/common/interpolation.rs +++ b/rust/lit-node/lit-node/tests/common/interpolation.rs @@ -1,5 +1,3 @@ -use elliptic_curve::group::GroupEncoding; -use elliptic_curve::{Group, PrimeField}; use lit_core::utils::binary::bytes_to_hex; use lit_node::common::key_helper::KeyCache; use lit_node::error::Result; @@ -7,12 +5,17 @@ use lit_node::peers::peer_state::models::{SimplePeer, SimplePeerCollection}; use lit_node::tss::common::key_persistence::KeyPersistence; use lit_node::tss::common::key_share::KeyShare; use lit_node::tss::common::storage::{read_key_share_from_disk, write_key_share_to_disk}; -use lit_node_core::CompressedBytes; -use lit_node_core::CurveType; -use lit_node_core::PeerId; -use vsss_rs::{ - DefaultShare, IdentifierPrimeField, ReadableShareSet, ValuePrimeField, - curve25519::{WrappedEdwards, WrappedRistretto, WrappedScalar}, +use lit_node_core::{CompressedBytes, CurveType, PeerId}; +use lit_rust_crypto::{ + blsful::inner_types::{G1Projective, Scalar}, + decaf377, ed448_goldilocks, + ff::PrimeField, + group::{Group, GroupEncoding}, + jubjub, k256, p256, p384, pallas, vsss_rs, + vsss_rs::{ + DefaultShare, IdentifierPrimeField, ReadableShareSet, ValuePrimeField, + curve25519::{WrappedEdwards, WrappedRistretto, WrappedScalar}, + }, }; pub async fn get_secret_and_shares( @@ -36,7 +39,7 @@ where #[derive(Copy, Clone, Debug)] pub enum CurveScalar { - Bls(blsful::inner_types::Scalar), + Bls(Scalar), K256(k256::Scalar), P256(p256::Scalar), P384(p384::Scalar), @@ -44,6 +47,7 @@ pub enum CurveScalar { Ristretto25519(WrappedScalar), Ed448(ed448_goldilocks::Scalar), Jubjub(jubjub::Scalar), + Pallas(pallas::Scalar), Decaf377(decaf377::Fr), Schnorrkel(WrappedScalar), } @@ -63,13 +67,14 @@ impl PartialEq for CurveScalar { (Self::Jubjub(a), Self::Jubjub(b)) => a == b, (Self::Decaf377(a), Self::Decaf377(b)) => a == b, (Self::Schnorrkel(a), Self::Schnorrkel(b)) => a == b, + (Self::Pallas(a), Self::Pallas(b)) => a == b, _ => false, } } } -impl From for CurveScalar { - fn from(scalar: blsful::inner_types::Scalar) -> Self { +impl From for CurveScalar { + fn from(scalar: Scalar) -> Self { Self::Bls(scalar) } } @@ -122,6 +127,7 @@ impl CurveScalar { Self::Ed448(scalar) => Box::new(scalar.to_repr()), Self::Jubjub(scalar) => Box::new(scalar.to_repr()), Self::Decaf377(scalar) => Box::new(scalar.to_repr()), + Self::Pallas(scalar) => Box::new(scalar.to_repr()), Self::Schnorrkel(scalar) => Box::new(scalar.to_repr()), }; (*repr).as_ref().to_vec() @@ -139,7 +145,7 @@ pub async fn remap_secret_to_new_peer_ids( let realm_id = 1; match curve_type { CurveType::BLS => { - remap_secret_helper::( + remap_secret_helper::( curve_type, old_peers, new_peers, @@ -247,7 +253,19 @@ pub async fn remap_secret_to_new_peer_ids( .await } CurveType::BLS12381G1 => { - remap_secret_helper::( + remap_secret_helper::( + curve_type, + old_peers, + new_peers, + pubkey, + read_epoch, + write_epoch, + realm_id, + ) + .await + } + CurveType::RedPallas => { + remap_secret_helper::( curve_type, old_peers, new_peers, @@ -336,10 +354,8 @@ pub async fn interpolate_secret( ) -> CurveScalar { match curve_type { CurveType::BLS => CurveScalar::Bls( - interpolate_secret_for_key::( - peers, pubkey, epoch, curve_type, realm_id, - ) - .await, + interpolate_secret_for_key::(peers, pubkey, epoch, curve_type, realm_id) + .await, ), CurveType::K256 => CurveScalar::K256( interpolate_secret_for_key::( @@ -390,10 +406,12 @@ pub async fn interpolate_secret( .await, ), CurveType::BLS12381G1 => CurveScalar::Bls( - interpolate_secret_for_key::( - peers, pubkey, epoch, curve_type, realm_id, - ) - .await, + interpolate_secret_for_key::(peers, pubkey, epoch, curve_type, realm_id) + .await, + ), + CurveType::RedPallas => CurveScalar::Pallas( + interpolate_secret_for_key::(peers, pubkey, epoch, curve_type, realm_id) + .await, ), } } @@ -422,6 +440,7 @@ pub fn splice_secret( CurveScalar::Schnorrkel(s) => { split_secret_with_peers(s, peers, threshold, CurveScalar::Schnorrkel) } + CurveScalar::Pallas(s) => split_secret_with_peers(s, peers, threshold, CurveScalar::Pallas), } } diff --git a/rust/lit-node/lit-node/tests/common/lit_actions.rs b/rust/lit-node/lit-node/tests/common/lit_actions.rs index e5f2db4..3aeffd2 100644 --- a/rust/lit-node/lit-node/tests/common/lit_actions.rs +++ b/rust/lit-node/lit-node/tests/common/lit_actions.rs @@ -19,6 +19,7 @@ use lit_node_core::{ request::JsonExecutionRequest, response::{GenericResponse, JsonExecutionResponse}, }; +use lit_rust_crypto::{k256, p256, p384}; use rand::Rng; use rand_core::OsRng; use std::collections::HashMap; diff --git a/rust/lit-node/lit-node/tests/common/pkp.rs b/rust/lit-node/lit-node/tests/common/pkp.rs index 5de0e7f..5fcbed8 100644 --- a/rust/lit-node/lit-node/tests/common/pkp.rs +++ b/rust/lit-node/lit-node/tests/common/pkp.rs @@ -7,26 +7,19 @@ use ethers::signers::Wallet; use lit_core::utils::binary::hex_to_bytes; use lit_node_core::{ AuthSigItem, LitAbility, LitResourceAbilityRequest, LitResourceAbilityRequestResource, - LitResourcePrefix, NodeSet, SignableOutput, SigningScheme, + LitResourcePrefix, NodeSet, SigningScheme, request::JsonPKPSigningRequest, response::{GenericResponse, JsonPKPSigningResponse}, }; use lit_node_testnet::end_user::EndUser; use lit_node_testnet::node_collection::NodeIdentityKey; +use lit_rust_crypto::k256; use lit_sdk::signature::combine_and_verify_signature_shares; use rand::Rng; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use tracing::{debug, info}; -#[derive(Debug, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -struct SignWithPKPReturn { - success: bool, - signed_data: Vec, - signature_share: SignableOutput, -} - // copied from lit_ecdsa_wasm_combine #[derive(Clone, Serialize, Deserialize, Debug)] pub struct SignedDatak256 { diff --git a/rust/lit-node/lit-node/tests/common/recovery_party.rs b/rust/lit-node/lit-node/tests/common/recovery_party.rs index 96644e5..d4a8f8a 100644 --- a/rust/lit-node/lit-node/tests/common/recovery_party.rs +++ b/rust/lit-node/lit-node/tests/common/recovery_party.rs @@ -1,7 +1,5 @@ -use blsful::inner_types::{G1Projective, InnerBls12381G1}; use bulletproofs::BulletproofCurveArithmetic as BCA; use ethers::types::{Address, H160}; -use k256::ecdsa::{RecoveryId, Signature, SigningKey, VerifyingKey}; use sha3::{Keccak256, digest::Digest}; use std::time::{SystemTime, UNIX_EPOCH}; @@ -13,9 +11,16 @@ use lit_blockchain::contracts::{ backup_recovery::BackupRecovery, staking::{AddressMapping, Staking, Validator}, }; -use lit_node_core::CompressedBytes; -use lit_node_core::JsonAuthSig; +use lit_node_core::{CompressedBytes, JsonAuthSig}; use lit_recovery::models::DownloadedShareData; +use lit_rust_crypto::{ + blsful::inner_types::{G1Projective, InnerBls12381G1}, + elliptic_curve::ScalarPrimitive, + k256::{ + self, + ecdsa::{RecoveryId, Signature, SigningKey, VerifyingKey}, + }, +}; use reqwest::Url; use std::sync::Arc; use tracing::info; @@ -284,9 +289,8 @@ pub fn check_share_data(mut share_data: Vec) { k256::ProjectivePoint::from_compressed(&hex::decode(&ecdsa_share.encryption_key).unwrap()) .unwrap(); // Parse ECDSA private key - let scalar_primitive = elliptic_curve::scalar::ScalarPrimitive::from_slice( - &hex::decode(&ecdsa_share.decryption_key_share).unwrap(), - ) - .unwrap(); + let scalar_primitive = + ScalarPrimitive::from_slice(&hex::decode(&ecdsa_share.decryption_key_share).unwrap()) + .unwrap(); let _ = k256::Scalar::from(&scalar_primitive); } diff --git a/rust/lit-node/lit-node/tests/common/web_user_tests.rs b/rust/lit-node/lit-node/tests/common/web_user_tests.rs index a2b87f4..43673e7 100644 --- a/rust/lit-node/lit-node/tests/common/web_user_tests.rs +++ b/rust/lit-node/lit-node/tests/common/web_user_tests.rs @@ -10,7 +10,6 @@ use std::collections::HashMap; use crate::common::auth_sig::generate_authsig; use anyhow::Result; -use blsful::Bls12381G2Impl; use ethers::signers::LocalWallet; use ethers::types::U256; use rand::Rng; @@ -23,16 +22,16 @@ use lit_node_core::{ EVMContractConditionItem, JsonAccessControlCondition, JsonAuthSig, JsonReturnValueTest, LitAbility, LitResource, LitResourceAbilityRequest, LitResourceAbilityRequestResource, NodeSet, SolRpcConditionItem, UnifiedAccessControlCondition, UnifiedAccessControlConditionItem, - constants::CHAIN_LOCALCHAIN, request::EncryptionSignRequest, response::EncryptionSignResponse, + constants::CHAIN_LOCALCHAIN, + request::EncryptionSignRequest, + response::{EncryptionSignResponse, GenericResponse, JsonExecutionResponse}, }; +use lit_rust_crypto::blsful::{Bls12381G2Impl, PublicKey, TimeCryptCiphertext}; use lit_node::models::RequestConditions; -use lit_node_core::response::JsonExecutionResponse; - use lit_node::utils::web::hash_access_control_conditions; use super::session_sigs::SessionSigAndNodeSet; -use lit_node_core::response::GenericResponse; use tracing::{debug, info}; #[derive(Debug, Clone)] @@ -174,9 +173,7 @@ pub async fn test_encryption_decryption_auth_sig( let message_bytes = test_encryption_parameters.to_encrypt.as_bytes(); let network_pubkey = get_network_pubkey_from_node_set(node_set.iter().map(|(n, _)| n)).await; - let pubkey = - lit_sdk::lit_node_core::blsful::PublicKey::try_from(hex::decode(network_pubkey).unwrap()) - .unwrap(); + let pubkey = PublicKey::try_from(hex::decode(network_pubkey).unwrap()).unwrap(); let ciphertext = lit_sdk::encryption::encrypt_time_lock( &pubkey, @@ -269,7 +266,7 @@ pub async fn test_encryption_decryption_session_sigs( .get_resource_key() .into_bytes(); - let pubkey = blsful::PublicKey::try_from(hex::decode(&network_pubkey).unwrap()).unwrap(); + let pubkey = PublicKey::try_from(hex::decode(&network_pubkey).unwrap()).unwrap(); let ciphertext = lit_sdk::encryption::encrypt_time_lock(&pubkey, message_bytes, &identity_param) .expect("Unable to encrypt"); @@ -398,10 +395,10 @@ pub async fn retrieve_decryption_key_session_sigs_with_version( } pub fn assert_decrypted( - network_pubkey: &blsful::PublicKey, + network_pubkey: &PublicKey, identity_param: Vec, expected_plaintext: &str, - ciphertext: &blsful::TimeCryptCiphertext, + ciphertext: &TimeCryptCiphertext, decryption_resp: Vec>, ) { // assert_eq!(decryption_resp.len(), num_staked as usize); diff --git a/rust/lit-node/lit-node/tests/component/dkg.rs b/rust/lit-node/lit-node/tests/component/dkg.rs index ab3d450..b2387ab 100644 --- a/rust/lit-node/lit-node/tests/component/dkg.rs +++ b/rust/lit-node/lit-node/tests/component/dkg.rs @@ -1,7 +1,5 @@ use super::utils::virtual_node_collection::{VirtualNode, VirtualNodeCollection}; use crate::common::interpolation::{get_secret_and_shares, interpolate_secret}; -use ed448_goldilocks::EdwardsPoint; -use elliptic_curve::{Group, group::GroupEncoding}; use ethers::types::{H160, U256}; use futures::future::join_all; use lit_blockchain::contracts::backup_recovery::RecoveredPeerId; @@ -18,14 +16,18 @@ use lit_node::tss::common::storage::{ use lit_node::tss::dkg::engine::{DkgAfterRestore, DkgAfterRestoreData, DkgEngine}; use lit_node::utils::key_share_proof::{compute_key_share_proofs, verify_key_share_proofs}; use lit_node::version::DataVersionWriter; -use lit_node_core::CompressedBytes; -use lit_node_core::CurveType; -use lit_node_core::PeerId; +use lit_node_core::{CompressedBytes, CurveType, PeerId}; +use lit_rust_crypto::{ + blsful, decaf377, + ed448_goldilocks::EdwardsPoint, + elliptic_curve::{Group, group::GroupEncoding}, + jubjub, k256, p256, p384, pallas, + vsss_rs::curve25519::{WrappedEdwards, WrappedRistretto}, +}; use std::collections::HashMap; use test_case::test_case; use tokio::task::JoinHandle; use tracing::{error, info}; -use vsss_rs::curve25519::{WrappedEdwards, WrappedRistretto}; // The following tests show how components can be tested in isolation. #[test_case(CurveType::K256; "K256 Key generation")] @@ -36,6 +38,7 @@ use vsss_rs::curve25519::{WrappedEdwards, WrappedRistretto}; #[test_case(CurveType::P256; "P256 Key generation")] #[test_case(CurveType::P384; "P384 Key generation")] #[test_case(CurveType::RedJubjub; "RedJubjub Key generation")] +#[test_case(CurveType::RedPallas; "RedPallas Key generation")] #[test_case(CurveType::RedDecaf377; "RedDecaf377 Key generation")] #[test_case(CurveType::BLS12381G1; "Bls12381G1 Key Generation")] #[tokio::test] @@ -52,6 +55,7 @@ pub async fn dkg_only(curve_type: CurveType) { #[test_case(CurveType::P256; "P256 Key Share Proofs")] #[test_case(CurveType::P384; "P384 Key Share Proofs")] #[test_case(CurveType::RedJubjub; "RedJubjub Key Share Proofs")] +#[test_case(CurveType::RedPallas; "RedPallas Key Share Proofs")] #[test_case(CurveType::RedDecaf377; "RedDecaf377 Key Share Proofs")] #[test_case(CurveType::BLS12381G1; "Bls12381G1 Key Share Proofs")] #[tokio::test] @@ -136,6 +140,7 @@ pub async fn dkg_and_key_share_proofs(curve_type: CurveType) { #[test_case(p256::ProjectivePoint::default(), CurveType::P256; "P256 Refresh")] #[test_case(p384::ProjectivePoint::default(), CurveType::P384; "P384 Refresh")] #[test_case(jubjub::SubgroupPoint::default(), CurveType::RedJubjub; "RedJubjub Refresh")] +#[test_case(pallas::Point::default(), CurveType::RedPallas; "RedPallas Refresh")] #[test_case(decaf377::Element::default(), CurveType::RedDecaf377; "RedDecaf377 Refresh")] #[test_case(blsful::inner_types::G1Projective::default(), CurveType::BLS12381G1; "Bls12381G1 Key Generation")] #[tokio::test] @@ -160,10 +165,11 @@ where #[test_case(blsful::inner_types::G1Projective::default(), CurveType::BLS12381G1, 3, [1, 0].to_vec(); "Bls12381G1 add node, keep threshold")] #[test_case(WrappedEdwards::default(), CurveType::Ed25519, 3, [1, 0].to_vec(); "Ed25519 add node, keep threshold")] #[test_case(WrappedRistretto::default(), CurveType::Ristretto25519, 3, [1, 0].to_vec(); "Ristretto25519 add node, keep threshold")] -#[test_case(ed448_goldilocks::EdwardsPoint::default(), CurveType::Ed448, 3, [1, 0].to_vec(); "Ed448 add node, keep threshold")] +#[test_case(EdwardsPoint::default(), CurveType::Ed448, 3, [1, 0].to_vec(); "Ed448 add node, keep threshold")] #[test_case(p256::ProjectivePoint::default(), CurveType::P256, 3, [1, 0].to_vec(); "P256 add node, keep threshold")] #[test_case(p384::ProjectivePoint::default(), CurveType::P384, 3, [1, 0].to_vec(); "P384 add node, keep threshold")] #[test_case(jubjub::SubgroupPoint::default(), CurveType::RedJubjub, 3, [1, 0].to_vec(); "RedJubjub add node, keep threshold")] +#[test_case(pallas::Point::default(), CurveType::RedPallas, 3, [1, 0].to_vec(); "RedPallas add node, keep threshold")] #[test_case(decaf377::Element::default(), CurveType::RedDecaf377, 3, [1, 0].to_vec(); "RedDecaf377 add node, keep threshold")] // #[test_case( CurveType::K256, 4, [-2,0].to_vec() ; "ECDSA remove node, keep threshold")] // #[test_case( CurveType::BLS, 4, [-2,0].to_vec() ; "BLS remove node, keep threshold")] @@ -261,11 +267,12 @@ pub async fn dkg_and_reshare( #[test_case(blsful::inner_types::G1Projective::default(), CurveType::BLS12381G1, 3, 3; "Bls12381G1 restore 3 nodes")] #[test_case(WrappedEdwards::default(), CurveType::Ed25519, 5, 4; "Ed25519 restore 5 nodes")] #[test_case(WrappedRistretto::default(), CurveType::Ristretto25519, 5, 3; "Ristretto25519 restore 5 nodes")] -#[test_case(ed448_goldilocks::EdwardsPoint::default(), CurveType::Ed448, 3, 3; "Ed448 restore 3 nodes")] +#[test_case(EdwardsPoint::default(), CurveType::Ed448, 3, 3; "Ed448 restore 3 nodes")] #[test_case(p256::ProjectivePoint::default(), CurveType::P256, 3, 3; "P256 restore 3 nodes")] #[test_case(p384::ProjectivePoint::default(), CurveType::P384, 3, 3; "P384 restore 3 nodes")] #[test_case(jubjub::SubgroupPoint::default(), CurveType::RedJubjub, 5, 4; "RedJubjub restore 5 nodes")] #[test_case(decaf377::Element::default(), CurveType::RedDecaf377, 3, 3; "RedDecaf377 restore 3 nodes")] +#[test_case(pallas::Point::default(), CurveType::RedPallas, 3, 3; "RedPallas restore 3 nodes")] #[tokio::test] pub async fn dkg_after_restore( _g: G, @@ -431,7 +438,7 @@ pub async fn dkg_only_all_curves() { let pubkeys = dkg_all_curves(&vnc, epoch, ¤t_peers).await; info!("Generated {} pubkeys", pubkeys.len()); - assert_eq!(pubkeys.len(), 20); + assert_eq!(pubkeys.len(), 22); } async fn restore( @@ -715,7 +722,7 @@ pub async fn dkg_all_curves( info!("change epoch result: {:?}", r); let _ = r.expect("error from dkg manager change epoch"); let root_keys = dkg_engine.get_dkgs().collect::>(); - assert_eq!(root_keys.len(), 20); + assert_eq!(root_keys.len(), 22); root_keys .iter() .map(|r| r.result().unwrap().public_key()) diff --git a/rust/lit-node/lit-node/tests/component/encryption/bls.rs b/rust/lit-node/lit-node/tests/component/encryption/bls.rs index ff4f8dd..983d360 100644 --- a/rust/lit-node/lit-node/tests/component/encryption/bls.rs +++ b/rust/lit-node/lit-node/tests/component/encryption/bls.rs @@ -1,8 +1,8 @@ use crate::component::{dkg::dkg, utils::virtual_node_collection::VirtualNodeCollection}; use core::panic; use lit_node::peers::peer_state::models::SimplePeerCollection; -use lit_node_core::CurveType; -use lit_node_core::SigningScheme; +use lit_node_core::{CurveType, SigningScheme}; +use lit_rust_crypto::blsful::{Bls12381G2Impl, PublicKey, Signature}; use tracing::info; #[tokio::test] @@ -19,9 +19,7 @@ pub async fn sign_min_threshold() { let peers = SimplePeerCollection::default(); let pubkey = dkg(&vnc, CurveType::BLS, epoch, None, &peers).await; - let pub_key = - blsful::PublicKey::::try_from(hex::decode(&pubkey).unwrap()) - .unwrap(); + let pub_key = PublicKey::::try_from(hex::decode(&pubkey).unwrap()).unwrap(); let epoch = 2; vnc.update_cdm_epoch(epoch).await; @@ -54,7 +52,7 @@ pub async fn sign_min_threshold() { signature_shares.push(signature_share); } - let sig = blsful::Signature::from_shares(&signature_shares); + let sig = Signature::from_shares(&signature_shares); assert!(sig.is_ok()); let sig = sig.unwrap(); assert!( @@ -107,7 +105,7 @@ pub async fn sign_with_pubkey() { signature_shares.push(signature_share); } - let sig = blsful::Signature::from_shares(&signature_shares); + let sig = Signature::from_shares(&signature_shares); assert!(sig.is_ok()); let _sig = sig.unwrap(); diff --git a/rust/lit-node/lit-node/tests/component/precompute/damfast_presignatures.rs b/rust/lit-node/lit-node/tests/component/precompute/damfast_presignatures.rs index 08f005f..9cd5823 100644 --- a/rust/lit-node/lit-node/tests/component/precompute/damfast_presignatures.rs +++ b/rust/lit-node/lit-node/tests/component/precompute/damfast_presignatures.rs @@ -3,9 +3,8 @@ use futures::future::join_all; use lit_fast_ecdsa::SignatureShare; use lit_node::peers::peer_state::models::SimplePeerCollection; use lit_node::tasks::presign_manager::models::PreSignatureValue; -use lit_node_core::CurveType; -use lit_node_core::NodeSet; -use lit_node_core::SigningScheme; +use lit_node_core::{CurveType, NodeSet, SigningScheme}; +use lit_rust_crypto::{k256, p256, p384}; use tokio::task::JoinHandle; #[tokio::test] diff --git a/rust/lit-node/lit-node/tests/component/sign/ecdsa_damfast.rs b/rust/lit-node/lit-node/tests/component/sign/ecdsa_damfast.rs index eea76fa..05cfc2f 100644 --- a/rust/lit-node/lit-node/tests/component/sign/ecdsa_damfast.rs +++ b/rust/lit-node/lit-node/tests/component/sign/ecdsa_damfast.rs @@ -1,11 +1,6 @@ use crate::component::{dkg::dkg, utils::virtual_node_collection::VirtualNodeCollection}; -use elliptic_curve::generic_array::ArrayLength; -use elliptic_curve::group::{Curve, GroupEncoding}; -use elliptic_curve::{CurveArithmetic, FieldBytesSize, NonZeroScalar, PrimeCurve}; use ethers::utils::keccak256; use futures::future::join_all; -use hd_keys_curves::{HDDerivable, HDDeriver}; -use k256::ecdsa::hazmat::DigestPrimitive; use lit_fast_ecdsa::SignatureShare; use lit_node::peers::peer_state::models::SimplePeerCollection; use lit_node::tasks::presign_manager::models::{PreSignatureValue, Presign}; @@ -13,9 +8,18 @@ use lit_node::tss::common::dkg_type::DkgType; use lit_node::tss::common::tss_state::TssState; use lit_node::tss::ecdsa_damfast::DamFastState; use lit_node::utils::traits::SignatureCurve; -use lit_node_core::CompressedBytes; -use lit_node_core::PeerId; -use lit_node_core::SigningScheme; +use lit_node_core::{ + CompressedBytes, PeerId, SigningScheme, + hd_keys_curves_wasm::{HDDerivable, HDDeriver}, +}; +use lit_rust_crypto::{ + elliptic_curve::{ + CurveArithmetic, FieldBytesSize, NonZeroScalar, PrimeCurve, generic_array::ArrayLength, + }, + group::{Curve, GroupEncoding}, + k256::{self, ecdsa::hazmat::DigestPrimitive}, + p256, p384, +}; use serde::Serialize; use std::ops::Add; use std::sync::Arc; diff --git a/rust/lit-node/lit-node/tests/component/sign/frost.rs b/rust/lit-node/lit-node/tests/component/sign/frost.rs index 3d9bfc3..5d8b448 100644 --- a/rust/lit-node/lit-node/tests/component/sign/frost.rs +++ b/rust/lit-node/lit-node/tests/component/sign/frost.rs @@ -7,10 +7,10 @@ use lit_frost::{ }; use lit_node::peers::peer_state::models::SimplePeer; use lit_node::tss::common::key_share::KeyShare; -use lit_node::tss::common::signing_scheme::signing_scheme_to_frost_scheme; use lit_node::tss::frost::FrostState; use lit_node_core::PeerId; use lit_node_core::SigningScheme; +use lit_sdk::signature::signing_scheme_to_frost_scheme; use test_case::test_case; use tokio::task::JoinHandle; use tracing::info; diff --git a/rust/lit-node/lit-node/tests/integration/backup.rs b/rust/lit-node/lit-node/tests/integration/backup.rs index 47c6e15..e142c13 100644 --- a/rust/lit-node/lit-node/tests/integration/backup.rs +++ b/rust/lit-node/lit-node/tests/integration/backup.rs @@ -1,6 +1,4 @@ use crate::common::peers::get_simple_peer_collection; -use elliptic_curve::Group; -use elliptic_curve::group::GroupEncoding; use ethers::abi::Address; use lit_core::utils::binary::bytes_to_hex; use lit_node::common::key_helper::KeyCache; @@ -14,6 +12,11 @@ use lit_node::tss::common::storage::{ use lit_node_core::ethers::prelude::U256; use lit_node_core::{CompressedBytes, CurveType}; use lit_node_testnet::TestSetupBuilder; +use lit_rust_crypto::{ + blsful, decaf377, ed448_goldilocks, + group::{Group, GroupEncoding}, + jubjub, k256, p256, p384, pallas, vsss_rs, +}; use tracing::info; /// Tests that decryption shares do not get deleted @@ -174,6 +177,15 @@ async fn verify_restore_decryption_shares_not_deleted() { ) .await; } + CurveType::RedPallas => { + check_for_restore_decryption_shares::( + curve_type, + &pubkey, + &peers, + realm_id.as_u64(), + ) + .await; + } } } } diff --git a/rust/lit-node/lit-node/tests/integration/backup_datil_long.rs b/rust/lit-node/lit-node/tests/integration/backup_datil_long.rs index cd96d8f..2e0d9f7 100644 --- a/rust/lit-node/lit-node/tests/integration/backup_datil_long.rs +++ b/rust/lit-node/lit-node/tests/integration/backup_datil_long.rs @@ -3,7 +3,6 @@ use chrono::{Duration, Utc}; use ethers::prelude::{H160, U256}; use ethers::types::Address; use hex::FromHex; -use k256::ecdsa::{SigningKey, VerifyingKey}; use lit_blockchain::contracts::pubkey_router::RootKey; use lit_core::config::CFG_ADMIN_OVERRIDE_NAME; use lit_node::auth::auth_material::JsonAuthSigExtended; @@ -14,6 +13,7 @@ use lit_node_core::JsonAuthSig; use lit_node_testnet::TestSetupBuilder; use lit_node_testnet::testnet::Testnet; use lit_node_testnet::validator::ValidatorCollection; +use lit_rust_crypto::k256::ecdsa::{SigningKey, VerifyingKey}; use reqwest::Client; use rocket::serde::Serialize; use sha3::{Keccak256, digest::Digest}; diff --git a/rust/lit-node/lit-node/tests/integration/backup_long.rs b/rust/lit-node/lit-node/tests/integration/backup_long.rs index 0e20506..be25ad7 100644 --- a/rust/lit-node/lit-node/tests/integration/backup_long.rs +++ b/rust/lit-node/lit-node/tests/integration/backup_long.rs @@ -1,10 +1,8 @@ use crate::common::ecdsa::simple_single_sign_with_hd_key; use crate::common::recovery_party::SiweSignature; -use blsful::inner_types::{Group, GroupEncoding}; use chrono::{Duration, Utc}; use ethers::prelude::{H160, LocalWallet, Signer, U256}; use ethers::types::Address; -use k256::ecdsa::{SigningKey, VerifyingKey}; use lit_blockchain::contracts::backup_recovery::BackupRecoveryState; use lit_core::config::CFG_ADMIN_OVERRIDE_NAME; use lit_core::utils::binary::bytes_to_hex; @@ -23,6 +21,16 @@ use lit_node_testnet::TestSetupBuilder; use lit_node_testnet::end_user::EndUser; use lit_node_testnet::testnet::Testnet; use lit_node_testnet::validator::ValidatorCollection; +use lit_rust_crypto::{ + blsful, decaf377, ed448_goldilocks, + group::{Group, GroupEncoding}, + jubjub, + k256::{ + self, + ecdsa::{SigningKey, VerifyingKey}, + }, + p256, p384, pallas, vsss_rs, +}; use reqwest::Client; use semver::Version; use sha3::{Keccak256, digest::Digest}; @@ -652,6 +660,15 @@ async fn download_decryption_key_shares_to_local_lit_recovery_tools( ) .await; } + CurveType::RedPallas => { + check_for_lingering_keys::( + curve_type, + &pubkey, + &peers, + realm_id.as_u64(), + ) + .await + } } } } diff --git a/rust/lit-node/lit-node/tests/integration/epoch_change_long.rs b/rust/lit-node/lit-node/tests/integration/epoch_change_long.rs index 07eeba5..70ab238 100644 --- a/rust/lit-node/lit-node/tests/integration/epoch_change_long.rs +++ b/rust/lit-node/lit-node/tests/integration/epoch_change_long.rs @@ -1,4 +1,3 @@ -use blsful::inner_types::{Group, GroupEncoding}; use lit_node_testnet::{ end_user::EndUser, testnet::{NodeAccount, Testnet, WhichTestnet, contracts::StakingContractRealmConfig}, @@ -15,6 +14,11 @@ use lit_node::tss::common::key_persistence::KeyPersistence; use lit_node::tss::common::key_share_commitment::KeyShareCommitments; use lit_node::tss::common::storage::read_key_share_commitments_from_disk; use lit_node_core::{CompressedBytes, CurveType, PeerId}; +use lit_rust_crypto::{ + blsful, decaf377, ed448_goldilocks, + group::{Group, GroupEncoding}, + jubjub, k256, p256, p384, pallas, vsss_rs, +}; use network_state::{NetworkState, get_next_random_network_state}; use semver::Version; use tracing::info; @@ -288,6 +292,15 @@ async fn test_many_epochs() { ) .await; } + CurveType::RedPallas => { + check_for_lingering_keys::( + curve_type, + pub_key, + &peers, + realm_id.as_u64(), + ) + .await; + } } } } diff --git a/rust/lit-node/lit-node/tests/integration/lit_actions.rs b/rust/lit-node/lit-node/tests/integration/lit_actions.rs index 0e1b6e8..0bbdefa 100644 --- a/rust/lit-node/lit-node/tests/integration/lit_actions.rs +++ b/rust/lit-node/lit-node/tests/integration/lit_actions.rs @@ -36,6 +36,7 @@ pub mod litactions { use lit_node_testnet::node_collection::{ get_identity_pubkeys_from_node_set, get_network_pubkey, }; + use lit_rust_crypto::k256; use lit_sdk::signature::SignedDataOutput; use rocket::form::validate::Contains; use serde_json::Value; @@ -392,10 +393,11 @@ pub mod litactions { k256::Scalar::ZERO }; - let scalar_primitive = elliptic_curve::ScalarPrimitive::::from_slice( - &hex::decode(&la_signed_data.digest).unwrap(), - ) - .unwrap(); + let scalar_primitive = + lit_rust_crypto::elliptic_curve::ScalarPrimitive::::from_slice( + &hex::decode(&la_signed_data.digest).unwrap(), + ) + .unwrap(); let data_signed = k256::Scalar::from(scalar_primitive); let signed_data: SignedDatak256 = SignedDatak256 { @@ -632,7 +634,9 @@ pub mod litactions { .into_bytes(); debug!("Identity parameter: {:?}", identity_param); - let pubkey = blsful::PublicKey::try_from(&hex::decode(&network_pubkey).unwrap()).unwrap(); + let pubkey = + lit_rust_crypto::blsful::PublicKey::try_from(&hex::decode(&network_pubkey).unwrap()) + .unwrap(); let ciphertext = lit_sdk::encryption::encrypt_time_lock(&pubkey, message_bytes, &identity_param) diff --git a/rust/lit-node/lit-node/tests/integration/session_sigs.rs b/rust/lit-node/lit-node/tests/integration/session_sigs.rs index 473aeb9..6bebbaf 100644 --- a/rust/lit-node/lit-node/tests/integration/session_sigs.rs +++ b/rust/lit-node/lit-node/tests/integration/session_sigs.rs @@ -943,7 +943,9 @@ async fn decrypt_with_lit_action_session_sig() { .get_resource_key() .into_bytes(); - let bls_pubkey = blsful::PublicKey::try_from(&hex::decode(&network_pubkey).unwrap()).unwrap(); + let bls_pubkey = + lit_rust_crypto::blsful::PublicKey::try_from(&hex::decode(&network_pubkey).unwrap()) + .unwrap(); // Encrypt let ciphertext = lit_sdk::encryption::encrypt_time_lock(&bls_pubkey, message_bytes, &identity_param) diff --git a/rust/lit-node/lit-node/tests/integration/shadow.rs b/rust/lit-node/lit-node/tests/integration/shadow.rs index 87ea0fa..d1f0227 100644 --- a/rust/lit-node/lit-node/tests/integration/shadow.rs +++ b/rust/lit-node/lit-node/tests/integration/shadow.rs @@ -162,7 +162,9 @@ async fn shadow_splicing_sign_encrypt() { .get_resource_key() .into_bytes(); - let pubkey = blsful::PublicKey::try_from(hex::decode(&network_pubkey).unwrap()).unwrap(); + let pubkey = + lit_rust_crypto::blsful::PublicKey::try_from(hex::decode(&network_pubkey).unwrap()) + .unwrap(); let ciphertext = lit_sdk::encryption::encrypt_time_lock( &pubkey, diff --git a/rust/lit-node/lit-node/tests/integration/signing.rs b/rust/lit-node/lit-node/tests/integration/signing.rs index dcfc04b..51bf59c 100644 --- a/rust/lit-node/lit-node/tests/integration/signing.rs +++ b/rust/lit-node/lit-node/tests/integration/signing.rs @@ -11,6 +11,7 @@ use lit_node_testnet::end_user::EndUser; use lit_node_core::SigningScheme; use lit_node_testnet::node_collection::get_identity_pubkeys_from_node_set; +use lit_rust_crypto::k256; use rand::Rng; use rand_core::OsRng; use std::str::FromStr; @@ -19,7 +20,7 @@ use std::{io::BufRead, time::Duration}; use test_case::test_case; use tracing::{error, info}; -const ALL_SIGNING_SCHEMES: [SigningScheme; 14] = [ +const ALL_SIGNING_SCHEMES: [SigningScheme; 15] = [ SigningScheme::Bls12381G1ProofOfPossession, SigningScheme::SchnorrEd25519Sha512, SigningScheme::SchnorrK256Sha256, @@ -28,6 +29,7 @@ const ALL_SIGNING_SCHEMES: [SigningScheme; 14] = [ SigningScheme::SchnorrRistretto25519Sha512, SigningScheme::SchnorrEd448Shake256, SigningScheme::SchnorrRedJubjubBlake2b512, + SigningScheme::SchnorrRedPallasBlake2b512, SigningScheme::SchnorrK256Taproot, SigningScheme::SchnorrRedDecaf377Blake2b512, SigningScheme::SchnorrkelSubstrate, diff --git a/rust/lit-node/lit-sdk/Cargo.toml b/rust/lit-node/lit-sdk/Cargo.toml index ba0a5a8..271ca2d 100644 --- a/rust/lit-node/lit-sdk/Cargo.toml +++ b/rust/lit-node/lit-sdk/Cargo.toml @@ -9,14 +9,13 @@ cait-sith = [] [dependencies] chrono = "0.4" -data-encoding.workspace = true ecdsa = { version = "0.16", features = ["arithmetic", "serde"] } elliptic-curve-tools = "0.1.2" futures = "0.3" hex = { version = "0.4", features = ["serde"] } ipfs-hasher = "0.13" lit-node-core = { path = "../lit-node-core" } -lit-frost = { git = "https://github.com/LIT-Protocol/lit-frost.git" } +lit-frost.workspace = true rand = "0.8" reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls", "stream"] } serde = "1.0" diff --git a/rust/lit-node/lit-sdk/src/encryption.rs b/rust/lit-node/lit-sdk/src/encryption.rs index a62a910..c68e79a 100644 --- a/rust/lit-node/lit-sdk/src/encryption.rs +++ b/rust/lit-node/lit-sdk/src/encryption.rs @@ -2,7 +2,7 @@ use crate::{EncryptedMulticastRequest, EndpointRequest, Response, SdkError, SdkResult, UrlPrefix}; use lit_node_core::{ - blsful::{ + lit_rust_crypto::blsful::{ Bls12381G2Impl, PublicKey, Signature, SignatureSchemes, SignatureShare, TimeCryptCiphertext, }, request::EncryptionSignRequest as InnerEncryptionSignRequest, diff --git a/rust/lit-node/lit-sdk/src/error.rs b/rust/lit-node/lit-sdk/src/error.rs index e7141c2..f7184a8 100644 --- a/rust/lit-node/lit-sdk/src/error.rs +++ b/rust/lit-node/lit-sdk/src/error.rs @@ -24,7 +24,7 @@ pub enum SdkError { EcdsaSignature(#[from] ecdsa::signature::Error), /// Bls errors from the blsful crate #[error("Bls error: {0}")] - Bls(#[from] lit_node_core::blsful::BlsError), + Bls(#[from] lit_node_core::lit_rust_crypto::blsful::BlsError), /// Errors from string parsing #[error("String parse error: {0}")] Parse(String), diff --git a/rust/lit-node/lit-sdk/src/handshake.rs b/rust/lit-node/lit-sdk/src/handshake.rs index d0b5c3f..3cc64e6 100644 --- a/rust/lit-node/lit-sdk/src/handshake.rs +++ b/rust/lit-node/lit-sdk/src/handshake.rs @@ -50,10 +50,10 @@ impl HandshakeRequestBuilder { )); } - if let Some(challenge) = &request.challenge { - if challenge.is_empty() { - return Err(SdkError::Build("No challenge is specified".to_string())); - } + if let Some(challenge) = &request.challenge + && challenge.is_empty() + { + return Err(SdkError::Build("No challenge is specified".to_string())); } } Ok(()) diff --git a/rust/lit-node/lit-sdk/src/signature.rs b/rust/lit-node/lit-sdk/src/signature.rs index decb38e..4bac5b1 100644 --- a/rust/lit-node/lit-sdk/src/signature.rs +++ b/rust/lit-node/lit-sdk/src/signature.rs @@ -10,19 +10,20 @@ use elliptic_curve_tools::{group, prime_field}; use lit_node_core::{ CompressedBytes, CompressedHex, CurveType, EcdsaSignedMessageShare, KeyFormatPreference, PeerId, SignableOutput, SigningAlgorithm, SigningScheme, - blsful::{self, Bls12381G2Impl, PublicKey, Signature}, - hd_keys_curves_wasm::{ - HDDerivable, HDDeriver, + hd_keys_curves_wasm::{HDDerivable, HDDeriver}, + lit_rust_crypto::{ + blsful::{self, Bls12381G2Impl, PublicKey, Signature}, + decaf377, ed448_goldilocks, elliptic_curve::{ self, Curve, CurveArithmetic, Field, FieldBytesSize, PrimeCurve, ScalarPrimitive, generic_array::ArrayLength, - group::GroupEncoding, ops::Reduce, pkcs8::AssociatedOid, point::{AffineCoordinates, DecompressPoint, PointCompression}, sec1::{FromEncodedPoint, ModulusSize, ToEncodedPoint}, }, - k256, p256, p384, + group::GroupEncoding, + jubjub, k256, p256, p384, pallas, vsss_rs, }, }; @@ -165,7 +166,7 @@ pub fn combine_and_verify_signature_shares( serde_json::from_str(&bls_msg_share.signature_share)?; let verifying_share: blsful::PublicKeyShare = serde_json::from_str(&bls_msg_share.verifying_share)?; - let public_key: blsful::PublicKey = + let public_key: PublicKey = serde_json::from_str(&bls_msg_share.public_key)?; let message = hex::decode(&bls_msg_share.message)?; bls_signing_package.push(( @@ -247,7 +248,7 @@ pub fn combine_and_verify_signature_shares( &verifying_shares, &first_entry.3, ); - if res.is_err() { + return if res.is_err() { let e = res.expect_err("frost signature from shares is invalid"); match e { lit_frost::Error::Cheaters(cheaters) => { @@ -261,25 +262,23 @@ pub fn combine_and_verify_signature_shares( cheater_peer_ids.push(peer_id); } } - return Err(SdkError::SignatureCombine(format!( + Err(SdkError::SignatureCombine(format!( "frost signature from shares is invalid. Invalid share peer ids: {}", cheater_peer_ids.join(", ") - ))); - } - _ => { - return Err(SdkError::SignatureCombine(e.to_string())); + ))) } + _ => Err(SdkError::SignatureCombine(e.to_string())), } } else { - return Ok(SignedDataOutput { + Ok(SignedDataOutput { signature: serde_json::to_string( &res.expect("frost signature from shares is valid"), )?, verifying_key: serde_json::to_string(&first_entry.3)?, signed_data: hex::encode(&first_entry.6), recovery_id: None, - }); - } + }) + }; } if bls_signing_package.len() > 1 { let first_entry = &bls_signing_package[0]; @@ -305,7 +304,7 @@ pub fn combine_and_verify_signature_shares( verifying_shares.push((entry.0, entry.5.clone(), entry.2)); } let public_key = first_entry.3; - let signature = blsful::Signature::::from_shares(&signature_shares) + let signature = Signature::::from_shares(&signature_shares) .expect("bls signature from shares"); if signature.verify(&public_key, &first_entry.4).is_err() { // Identify which shares are invalid @@ -427,6 +426,7 @@ pub fn verify_signature( | SigningScheme::SchnorrK256Taproot | SigningScheme::SchnorrEd448Shake256 | SigningScheme::SchnorrRedJubjubBlake2b512 + | SigningScheme::SchnorrRedPallasBlake2b512 | SigningScheme::SchnorrRedDecaf377Blake2b512 | SigningScheme::SchnorrkelSubstrate => { let scheme = signing_scheme_to_frost_scheme(signing_scheme)?; @@ -467,6 +467,7 @@ pub fn signing_scheme_to_frost_scheme(value: SigningScheme) -> SdkResult Ok(lit_frost::Scheme::Ristretto25519Sha512), SigningScheme::SchnorrEd448Shake256 => Ok(lit_frost::Scheme::Ed448Shake256), SigningScheme::SchnorrRedJubjubBlake2b512 => Ok(lit_frost::Scheme::RedJubjubBlake2b512), + SigningScheme::SchnorrRedPallasBlake2b512 => Ok(lit_frost::Scheme::RedPallasBlake2b512), SigningScheme::SchnorrK256Taproot => Ok(lit_frost::Scheme::K256Taproot), SigningScheme::SchnorrRedDecaf377Blake2b512 => Ok(lit_frost::Scheme::RedDecaf377Blake2b512), SigningScheme::SchnorrkelSubstrate => Ok(lit_frost::Scheme::SchnorrkelSubstrate), @@ -530,25 +531,28 @@ pub fn get_derived_public_key( CurveType::P384 => { derive_public_key::(signing_scheme, key_id, root_keys) } - CurveType::Ed25519 => { - derive_public_key::( - signing_scheme, - key_id, - root_keys, - ) + CurveType::Ed25519 => derive_public_key::( + signing_scheme, + key_id, + root_keys, + ), + CurveType::Ristretto25519 => derive_public_key::( + signing_scheme, + key_id, + root_keys, + ), + CurveType::Ed448 => { + derive_public_key::(signing_scheme, key_id, root_keys) + } + CurveType::RedJubjub => { + derive_public_key::(signing_scheme, key_id, root_keys) + } + CurveType::RedPallas => { + derive_public_key::(signing_scheme, key_id, root_keys) + } + CurveType::RedDecaf377 => { + derive_public_key::(signing_scheme, key_id, root_keys) } - CurveType::Ristretto25519 => derive_public_key::< - lit_node_core::vsss_rs::curve25519::WrappedRistretto, - >(signing_scheme, key_id, root_keys), - CurveType::Ed448 => derive_public_key::< - lit_node_core::hd_keys_curves_wasm::ed448_goldilocks_plus::EdwardsPoint, - >(signing_scheme, key_id, root_keys), - CurveType::RedJubjub => derive_public_key::< - lit_node_core::hd_keys_curves_wasm::jubjub::SubgroupPoint, - >(signing_scheme, key_id, root_keys), - CurveType::RedDecaf377 => derive_public_key::< - lit_node_core::hd_keys_curves_wasm::decaf377::Element, - >(signing_scheme, key_id, root_keys), } } diff --git a/rust/lit-node/rust-toolchain.toml b/rust/lit-node/rust-toolchain.toml index c8969b5..657737a 100644 --- a/rust/lit-node/rust-toolchain.toml +++ b/rust/lit-node/rust-toolchain.toml @@ -1,3 +1,3 @@ [toolchain] -channel = "1.86" +channel = "1.91" components = ['rustfmt', 'rust-src', 'clippy'] diff --git a/rust/lit-os/Cargo.lock b/rust/lit-os/Cargo.lock index 796330c..ed392a5 100644 --- a/rust/lit-os/Cargo.lock +++ b/rust/lit-os/Cargo.lock @@ -2596,7 +2596,7 @@ checksum = "b4ae4235e6dac0694637c763029ecea1a2ec9e4e06ec2729bd21ba4d9c863eb7" [[package]] name = "bulletproofs" version = "4.0.0" -source = "git+https://github.com/LIT-Protocol/bulletproofs?rev=ddf11c2f593e71f24c9a3d64c56f62d82f2b5099#ddf11c2f593e71f24c9a3d64c56f62d82f2b5099" +source = "git+https://github.com/LIT-Protocol/bulletproofs?branch=pallas#c355d31902966f394e9e34e7ddf9201413077a2a" dependencies = [ "blake2", "bls12_381_plus", @@ -2604,7 +2604,7 @@ dependencies = [ "byteorder", "curve25519-dalek-ml", "data-encoding", - "decaf377 0.10.1 (git+https://github.com/LIT-Protocol/decaf377?rev=1c5755b2b90e1969d47ce89cf2d35078984a0ee5)", + "decaf377 0.10.1 (git+https://github.com/LIT-Protocol/decaf377.git?rev=b2f76eda2e56bbaa818196d7c2d795312bbfbd92)", "digest 0.10.7", "ed448-goldilocks-plus", "elliptic-curve 0.13.8", @@ -2615,6 +2615,7 @@ dependencies = [ "merlin", "p256", "p384 0.13.1", + "pasta_curves 0.5.1 (git+https://github.com/LIT-Protocol/pasta_curves)", "rand 0.8.5", "rand_core 0.6.4", "serde", @@ -4252,7 +4253,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8d162beedaa69905488a8da94f5ac3edb4dd4788b732fadb7bd120b2625c1976" dependencies = [ "data-encoding", - "syn 2.0.106", + "syn 1.0.109", ] [[package]] @@ -4308,7 +4309,7 @@ dependencies = [ [[package]] name = "decaf377" version = "0.10.1" -source = "git+https://github.com/LIT-Protocol/decaf377?rev=1c5755b2b90e1969d47ce89cf2d35078984a0ee5#1c5755b2b90e1969d47ce89cf2d35078984a0ee5" +source = "git+https://github.com/LIT-Protocol/decaf377.git?rev=b2f76eda2e56bbaa818196d7c2d795312bbfbd92#b2f76eda2e56bbaa818196d7c2d795312bbfbd92" dependencies = [ "ark-bls12-377", "ark-ec", @@ -4319,7 +4320,7 @@ dependencies = [ "blake2", "cfg-if", "elliptic-curve 0.13.8", - "frost-dkg", + "frost-dkg 0.5.1", "gennaro-dkg", "hashbrown 0.15.5", "hex", @@ -4334,7 +4335,7 @@ dependencies = [ [[package]] name = "decaf377" version = "0.10.1" -source = "git+https://github.com/LIT-Protocol/decaf377.git#1c5755b2b90e1969d47ce89cf2d35078984a0ee5" +source = "git+https://github.com/LIT-Protocol/decaf377#1c5755b2b90e1969d47ce89cf2d35078984a0ee5" dependencies = [ "ark-bls12-377", "ark-ec", @@ -4345,7 +4346,7 @@ dependencies = [ "blake2", "cfg-if", "elliptic-curve 0.13.8", - "frost-dkg", + "frost-dkg 0.3.3", "gennaro-dkg", "hashbrown 0.15.5", "hex", @@ -4374,6 +4375,32 @@ dependencies = [ "zeroize", ] +[[package]] +name = "decaf377_plus" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "209f730dfc5f9d877c7549bebc93ea0ef4fe2915b4dbf5ffebc11e8b4c17c740" +dependencies = [ + "ark-bls12-377", + "ark-ec", + "ark-ed-on-bls12-377", + "ark-ff 0.4.2", + "ark-serialize 0.4.2", + "ark-std 0.4.0", + "blake2", + "cfg-if", + "elliptic-curve 0.13.8", + "frost-dkg 0.5.1", + "hashbrown 0.15.5", + "hex", + "num-bigint", + "once_cell", + "rand_core 0.6.4", + "serdect 0.3.0", + "subtle", + "zeroize", +] + [[package]] name = "default-env" version = "0.1.1" @@ -7244,8 +7271,8 @@ dependencies = [ [[package]] name = "frost-core" -version = "2.1.0" -source = "git+https://github.com/LIT-Protocol/frost.git?branch=2.1.0#272dd53869e7c82f7d5c72af73b5801e84c7b52e" +version = "2.2.0" +source = "git+https://github.com/LIT-Protocol/frost.git?branch=2.2.0#8743632bdd1f4af1bbf7a8cd27276f02182c3289" dependencies = [ "byteorder", "const-crc32-nostd", @@ -7267,12 +7294,12 @@ dependencies = [ [[package]] name = "frost-decaf377" -version = "2.1.0" -source = "git+https://github.com/LIT-Protocol/frost.git?branch=2.1.0#272dd53869e7c82f7d5c72af73b5801e84c7b52e" +version = "2.2.0" +source = "git+https://github.com/LIT-Protocol/frost.git?branch=2.2.0#8743632bdd1f4af1bbf7a8cd27276f02182c3289" dependencies = [ "ark-serialize 0.4.2", "blake2b_simd 1.0.3", - "decaf377 0.10.1 (git+https://github.com/LIT-Protocol/decaf377.git)", + "decaf377 0.10.1 (git+https://github.com/LIT-Protocol/decaf377)", "document-features", "frost-core", "frost-rerandomized", @@ -7287,6 +7314,22 @@ name = "frost-dkg" version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8176b54a998a04796e58b0ac3a6da08e5ab05aff5a7d92159619a652a29f63e8" +dependencies = [ + "elliptic-curve 0.13.8", + "elliptic-curve-tools", + "merlin", + "postcard", + "rand_core 0.6.4", + "serde", + "thiserror 2.0.16", + "vsss-rs 5.1.0", +] + +[[package]] +name = "frost-dkg" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00b59a575727037fbc977a68a2ace822b4b37f8f0647769946e307dc966ecfbb" dependencies = [ "blake2", "blsful", @@ -7294,6 +7337,7 @@ dependencies = [ "ed448-goldilocks-plus", "elliptic-curve 0.13.8", "elliptic-curve-tools", + "hex", "jubjub-plus", "k256 0.13.4", "merlin", @@ -7310,8 +7354,8 @@ dependencies = [ [[package]] name = "frost-ed25519" -version = "2.1.0" -source = "git+https://github.com/LIT-Protocol/frost.git?branch=2.1.0#272dd53869e7c82f7d5c72af73b5801e84c7b52e" +version = "2.2.0" +source = "git+https://github.com/LIT-Protocol/frost.git?branch=2.2.0#8743632bdd1f4af1bbf7a8cd27276f02182c3289" dependencies = [ "curve25519-dalek-ml", "document-features", @@ -7323,8 +7367,8 @@ dependencies = [ [[package]] name = "frost-ed448" -version = "2.1.0" -source = "git+https://github.com/LIT-Protocol/frost.git?branch=2.1.0#272dd53869e7c82f7d5c72af73b5801e84c7b52e" +version = "2.2.0" +source = "git+https://github.com/LIT-Protocol/frost.git?branch=2.2.0#8743632bdd1f4af1bbf7a8cd27276f02182c3289" dependencies = [ "document-features", "ed448-goldilocks-plus", @@ -7336,8 +7380,8 @@ dependencies = [ [[package]] name = "frost-p256" -version = "2.1.0" -source = "git+https://github.com/LIT-Protocol/frost.git?branch=2.1.0#272dd53869e7c82f7d5c72af73b5801e84c7b52e" +version = "2.2.0" +source = "git+https://github.com/LIT-Protocol/frost.git?branch=2.2.0#8743632bdd1f4af1bbf7a8cd27276f02182c3289" dependencies = [ "document-features", "frost-core", @@ -7349,8 +7393,8 @@ dependencies = [ [[package]] name = "frost-p384" -version = "2.1.0" -source = "git+https://github.com/LIT-Protocol/frost.git?branch=2.1.0#272dd53869e7c82f7d5c72af73b5801e84c7b52e" +version = "2.2.0" +source = "git+https://github.com/LIT-Protocol/frost.git?branch=2.2.0#8743632bdd1f4af1bbf7a8cd27276f02182c3289" dependencies = [ "document-features", "frost-core", @@ -7362,8 +7406,8 @@ dependencies = [ [[package]] name = "frost-redjubjub" -version = "2.1.0" -source = "git+https://github.com/LIT-Protocol/frost.git?branch=2.1.0#272dd53869e7c82f7d5c72af73b5801e84c7b52e" +version = "2.2.0" +source = "git+https://github.com/LIT-Protocol/frost.git?branch=2.2.0#8743632bdd1f4af1bbf7a8cd27276f02182c3289" dependencies = [ "blake2b_simd 1.0.3", "document-features", @@ -7375,10 +7419,24 @@ dependencies = [ "sha2 0.10.9", ] +[[package]] +name = "frost-redpallas" +version = "2.2.0" +source = "git+https://github.com/LIT-Protocol/frost.git?branch=2.2.0#8743632bdd1f4af1bbf7a8cd27276f02182c3289" +dependencies = [ + "blake2b_simd 1.0.3", + "document-features", + "frost-core", + "frost-rerandomized", + "group 0.13.0", + "pasta_curves 0.5.1 (git+https://github.com/LIT-Protocol/pasta_curves)", + "rand_core 0.6.4", +] + [[package]] name = "frost-rerandomized" -version = "2.1.0" -source = "git+https://github.com/LIT-Protocol/frost.git?branch=2.1.0#272dd53869e7c82f7d5c72af73b5801e84c7b52e" +version = "2.2.0" +source = "git+https://github.com/LIT-Protocol/frost.git?branch=2.2.0#8743632bdd1f4af1bbf7a8cd27276f02182c3289" dependencies = [ "derive-getters", "document-features", @@ -7389,8 +7447,8 @@ dependencies = [ [[package]] name = "frost-ristretto255" -version = "2.1.0" -source = "git+https://github.com/LIT-Protocol/frost.git?branch=2.1.0#272dd53869e7c82f7d5c72af73b5801e84c7b52e" +version = "2.2.0" +source = "git+https://github.com/LIT-Protocol/frost.git?branch=2.2.0#8743632bdd1f4af1bbf7a8cd27276f02182c3289" dependencies = [ "curve25519-dalek-ml", "document-features", @@ -7402,8 +7460,8 @@ dependencies = [ [[package]] name = "frost-schnorrkel25519" -version = "2.1.0" -source = "git+https://github.com/LIT-Protocol/frost.git?branch=2.1.0#272dd53869e7c82f7d5c72af73b5801e84c7b52e" +version = "2.2.0" +source = "git+https://github.com/LIT-Protocol/frost.git?branch=2.2.0#8743632bdd1f4af1bbf7a8cd27276f02182c3289" dependencies = [ "byte-strings", "curve25519-dalek-ml", @@ -7417,8 +7475,8 @@ dependencies = [ [[package]] name = "frost-secp256k1" -version = "2.1.0" -source = "git+https://github.com/LIT-Protocol/frost.git?branch=2.1.0#272dd53869e7c82f7d5c72af73b5801e84c7b52e" +version = "2.2.0" +source = "git+https://github.com/LIT-Protocol/frost.git?branch=2.2.0#8743632bdd1f4af1bbf7a8cd27276f02182c3289" dependencies = [ "document-features", "frost-core", @@ -7430,8 +7488,8 @@ dependencies = [ [[package]] name = "frost-taproot" -version = "2.1.0" -source = "git+https://github.com/LIT-Protocol/frost.git?branch=2.1.0#272dd53869e7c82f7d5c72af73b5801e84c7b52e" +version = "2.2.0" +source = "git+https://github.com/LIT-Protocol/frost.git?branch=2.2.0#8743632bdd1f4af1bbf7a8cd27276f02182c3289" dependencies = [ "document-features", "frost-core", @@ -8177,52 +8235,18 @@ dependencies = [ [[package]] name = "hd-keys-curves-wasm" -version = "1.0.3" -source = "git+https://github.com/LIT-Protocol/hd-keys-curves-wasm?rev=5e0dcc1a6d8d08f2328d4716dca806db87f93748#5e0dcc1a6d8d08f2328d4716dca806db87f93748" -dependencies = [ - "blake2", - "blsful", - "curve25519-dalek-ml", - "decaf377 0.10.1 (git+https://github.com/LIT-Protocol/decaf377?rev=1c5755b2b90e1969d47ce89cf2d35078984a0ee5)", - "digest 0.10.7", - "ecdsa 0.16.9", - "ed448-goldilocks-plus", - "elliptic-curve 0.13.8", - "elliptic-curve-tools", - "getrandom 0.2.16", - "jubjub-plus", - "k256 0.13.4", - "p256", - "p384 0.13.1", - "sha2 0.10.9", - "sha3 0.10.8", - "subtle", - "vsss-rs 5.1.0", -] - -[[package]] -name = "hd-keys-curves-wasm" -version = "1.0.3" -source = "git+https://github.com/LIT-Protocol/hd-keys-curves-wasm#5e0dcc1a6d8d08f2328d4716dca806db87f93748" +version = "1.0.5" +source = "git+https://github.com/LIT-Protocol/hd-keys-curves-wasm.git?branch=pallas#597a14b9cf4bafd4c778f1053ca4bbad0b3d249b" dependencies = [ "blake2", - "blsful", - "curve25519-dalek-ml", - "decaf377 0.10.1 (git+https://github.com/LIT-Protocol/decaf377?rev=1c5755b2b90e1969d47ce89cf2d35078984a0ee5)", "digest 0.10.7", "ecdsa 0.16.9", - "ed448-goldilocks-plus", - "elliptic-curve 0.13.8", "elliptic-curve-tools", "getrandom 0.2.16", - "jubjub-plus", - "k256 0.13.4", - "p256", - "p384 0.13.1", + "lit-rust-crypto", "sha2 0.10.9", "sha3 0.10.8", "subtle", - "vsss-rs 5.1.0", ] [[package]] @@ -9625,9 +9649,9 @@ dependencies = [ [[package]] name = "jubjub-plus" -version = "0.10.8" +version = "0.10.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c2c5e88d1ac6a903e693287073860ea35299b200273d5c2bd9d7845ec39f319" +checksum = "e8cd4e5cd65bb1390238c9e2e7dc98078a7b146c9d0d080cf3a7b1ac0d2348ac" dependencies = [ "bitvec 1.0.1", "bls12_381_plus", @@ -9674,6 +9698,7 @@ dependencies = [ "cfg-if", "ecdsa 0.16.9", "elliptic-curve 0.13.8", + "hex-literal", "once_cell", "serdect 0.2.0", "sha2 0.10.9", @@ -10414,32 +10439,28 @@ version = "0.2.0" dependencies = [ "digest 0.10.7", "ecdsa 0.16.9", - "elliptic-curve 0.13.8", "elliptic-curve-tools", - "hd-keys-curves-wasm 1.0.3 (git+https://github.com/LIT-Protocol/hd-keys-curves-wasm?rev=5e0dcc1a6d8d08f2328d4716dca806db87f93748)", + "hd-keys-curves-wasm", "hex", "lit-poly", + "lit-rust-crypto", "rand 0.8.5", "serde", "sha2 0.10.9", "subtle", "thiserror 2.0.16", - "vsss-rs 5.1.0", "zeroize", ] [[package]] name = "lit-frost" -version = "0.3.0" -source = "git+https://github.com/LIT-Protocol/lit-frost.git#60ad81f1f637f7042bfee0fd8cc29cee74d754b1" +version = "0.4.0" +source = "git+https://github.com/LIT-Protocol/lit-frost.git?branch=pallas#38ecfb7d037138b16b1bac675e53fa4ab8e4d960" dependencies = [ "anyhow", "ark-serialize 0.4.2", - "curve25519-dalek-ml", - "decaf377 0.10.1 (git+https://github.com/LIT-Protocol/decaf377?rev=1c5755b2b90e1969d47ce89cf2d35078984a0ee5)", "decaf377-rdsa", "ed25519-dalek 2.2.0", - "ed448-goldilocks-plus", "frost-core", "frost-decaf377", "frost-ed25519", @@ -10447,16 +10468,14 @@ dependencies = [ "frost-p256", "frost-p384", "frost-redjubjub", + "frost-redpallas", "frost-ristretto255", "frost-schnorrkel25519", "frost-secp256k1", "frost-taproot", "getrandom 0.2.16", "hex", - "jubjub-plus", - "k256 0.13.4", - "p256", - "p384 0.13.1", + "lit-rust-crypto", "rand_core 0.6.4", "reddsa", "schnorrkel", @@ -10465,7 +10484,6 @@ dependencies = [ "sha2 0.10.9", "subtle", "thiserror 2.0.16", - "vsss-rs 5.1.0", "zeroize", ] @@ -10546,7 +10564,7 @@ dependencies = [ "rand_chacha 0.3.1", "rand_core 0.6.4", "reqwest 0.11.27", - "sdd 3.0.10", + "sdd 4.2.4", "serde", "serde_json", "serdect 0.3.0", @@ -10563,23 +10581,15 @@ dependencies = [ name = "lit-node-core" version = "2.0.1" dependencies = [ - "blsful", - "curve25519-dalek-ml", - "decaf377 0.10.1 (git+https://github.com/LIT-Protocol/decaf377?rev=1c5755b2b90e1969d47ce89cf2d35078984a0ee5)", "ed25519-dalek 2.2.0", - "ed448-goldilocks-plus", "ethabi 16.0.0", "ethers", - "hd-keys-curves-wasm 1.0.3 (git+https://github.com/LIT-Protocol/hd-keys-curves-wasm)", + "hd-keys-curves-wasm", "hex", - "jubjub-plus", - "k256 0.13.4", - "p256", - "p384 0.13.1", + "lit-rust-crypto", "serde", "serde_json", "thiserror 2.0.16", - "vsss-rs 5.1.0", ] [[package]] @@ -10859,32 +10869,25 @@ dependencies = [ [[package]] name = "lit-recovery" -version = "0.2.0" +version = "0.3.0" dependencies = [ "arc-swap", "argon2", - "blsful", "bulletproofs", "byteorder", "ciborium", "clap 4.5.46", "colored", "cryptex", - "decaf377 0.10.1 (git+https://github.com/LIT-Protocol/decaf377?rev=1c5755b2b90e1969d47ce89cf2d35078984a0ee5)", "dirs 6.0.0", - "ed448-goldilocks-plus", - "elliptic-curve 0.13.8", "ethers", "generic-array 1.1.1", "glob", "hex", - "jubjub-plus", - "k256 0.13.4", "lit-blockchain", "lit-core", "lit-node-core", - "p256", - "p384 0.13.1", + "lit-rust-crypto", "path-clean 1.0.1", "rand 0.8.5", "reqwest 0.11.27", @@ -10900,16 +10903,34 @@ dependencies = [ "tiny-bip39 2.0.0", "tokio", "verifiable-share-encryption", - "vsss-rs 5.1.0", "winapi", ] +[[package]] +name = "lit-rust-crypto" +version = "0.6.0" +source = "git+https://github.com/LIT-Protocol/lit-rust-crypto?tag=0.6.0#9548fce521473f289ea1366249b782355e96507d" +dependencies = [ + "bls12_381_plus", + "blsful", + "blstrs_plus", + "curve25519-dalek-ml", + "decaf377_plus", + "ed448-goldilocks-plus", + "elliptic-curve 0.13.8", + "jubjub-plus", + "k256 0.13.4", + "p256", + "p384 0.13.1", + "pasta_curves_plus", + "vsss-rs 5.1.0", +] + [[package]] name = "lit-sdk" version = "2.0.1" dependencies = [ "chrono", - "data-encoding", "ecdsa 0.16.9", "elliptic-curve-tools", "futures", @@ -10935,21 +10956,13 @@ version = "0.2.0" dependencies = [ "blake2", "bulletproofs", - "curve25519-dalek-ml", - "decaf377 0.10.1 (git+https://github.com/LIT-Protocol/decaf377?rev=1c5755b2b90e1969d47ce89cf2d35078984a0ee5)", - "ed448-goldilocks-plus", - "elliptic-curve 0.13.8", "elliptic-curve-tools", - "jubjub-plus", - "k256 0.13.4", - "p256", - "p384 0.13.1", + "lit-rust-crypto", "rfc6979 0.4.0", "serde", "sha2 0.10.9", "sha3 0.10.8", "thiserror 2.0.16", - "vsss-rs 5.1.0", ] [[package]] @@ -10964,40 +10977,30 @@ dependencies = [ "async-trait", "base64_light", "bech32 0.11.0", - "blsful", - "blstrs_plus", "bs58 0.5.1", "bulletproofs", - "cc", "chrono", "ciborium", "clap 4.5.46", - "curve25519-dalek-ml", "data-encoding", - "decaf377 0.10.1 (git+https://github.com/LIT-Protocol/decaf377?rev=1c5755b2b90e1969d47ce89cf2d35078984a0ee5)", "derive_builder 0.20.2", "derive_more 2.0.1", "digest 0.10.7", "dotenv", "ecdsa 0.16.9", "ed25519-dalek 2.2.0", - "ed448-goldilocks-plus", - "elliptic-curve 0.13.8", "ethabi 16.0.0", "ethers", "flume", - "frost-dkg", + "frost-dkg 0.5.1", "futures", "glob", - "hd-keys-curves-wasm 1.0.3 (git+https://github.com/LIT-Protocol/hd-keys-curves-wasm?rev=5e0dcc1a6d8d08f2328d4716dca806db87f93748)", "hex", "hex-literal", "indicatif 0.15.0", "ipfs-hasher", "iri-string 0.6.0", "jsonpath-plus", - "jubjub-plus", - "k256 0.13.4", "lazy_static", "libaes", "libsecp256k1 0.7.1", @@ -11015,6 +11018,7 @@ dependencies = [ "lit-node-core", "lit-observability", "lit-recovery", + "lit-rust-crypto", "lit-sdk", "lit-vrf", "moka 0.12.10", @@ -11024,8 +11028,6 @@ dependencies = [ "opentelemetry 0.24.0 (registry+https://github.com/rust-lang/crates.io-index)", "opentelemetry-semantic-conventions 0.15.0", "opentelemetry_sdk 0.24.1", - "p256", - "p384 0.13.1", "postcard", "prost 0.13.5", "rand 0.8.5", @@ -11037,8 +11039,8 @@ dependencies = [ "rocket_cors", "rsa 0.7.0-pre", "rusqlite", - "scc 2.4.0", - "sdd 3.0.10", + "scc 3.3.2", + "sdd 4.2.4", "semver 1.0.26", "serde", "serde_bare", @@ -11066,7 +11068,6 @@ dependencies = [ "url", "verifiable-share-encryption", "visibility", - "vsss-rs 5.1.0", "web3", "webauthn-rs", "webauthn-rs-core", @@ -12904,6 +12905,45 @@ dependencies = [ "subtle", ] +[[package]] +name = "pasta_curves" +version = "0.5.1" +source = "git+https://github.com/LIT-Protocol/pasta_curves#2015f55d848e7f0a919bcf1d917ac46483849d81" +dependencies = [ + "blake2", + "blake2b_simd 1.0.3", + "elliptic-curve 0.13.8", + "ff 0.13.1", + "frost-dkg 0.5.1", + "group 0.13.0", + "hex", + "lazy_static", + "rand 0.8.5", + "serde", + "static_assertions", + "subtle", +] + +[[package]] +name = "pasta_curves_plus" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42e265b7ebdbfc61a8c0eeac79350cf3225cd390325dc91dd0edede5b6742d58" +dependencies = [ + "blake2", + "blake2b_simd 1.0.3", + "elliptic-curve 0.13.8", + "ff 0.13.1", + "frost-dkg 0.5.1", + "group 0.13.0", + "hex", + "lazy_static", + "rand 0.8.5", + "serde", + "static_assertions", + "subtle", +] + [[package]] name = "paste" version = "1.0.15" @@ -14125,7 +14165,7 @@ dependencies = [ "group 0.13.0", "hex", "jubjub", - "pasta_curves", + "pasta_curves 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)", "rand_core 0.6.4", "serde", "thiserror 1.0.69", @@ -19095,7 +19135,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "97fee6b57c6a41524a810daee9286c02d7752c4253064d0b05472833a438f675" dependencies = [ "cfg-if", - "rand 0.8.5", + "rand 0.7.3", "static_assertions", ] @@ -19560,8 +19600,8 @@ checksum = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191" [[package]] name = "verifiable-share-encryption" -version = "0.3.0" -source = "git+https://github.com/LIT-Protocol/verifiable-share-encryption?rev=7eddfbe736369db596d0f302c72f1d76b0fd332d#7eddfbe736369db596d0f302c72f1d76b0fd332d" +version = "0.4.0" +source = "git+https://github.com/LIT-Protocol/verifiable-share-encryption?branch=pallas#682fe9d3e0db44236ad582ee635c5a1b36b4472a" dependencies = [ "anyhow", "bulletproofs", diff --git a/rust/lit-os/lit-cli-os/src/cmd/os/guest/instance/create.rs b/rust/lit-os/lit-cli-os/src/cmd/os/guest/instance/create.rs index 2430777..5be3bc0 100644 --- a/rust/lit-os/lit-cli-os/src/cmd/os/guest/instance/create.rs +++ b/rust/lit-os/lit-cli-os/src/cmd/os/guest/instance/create.rs @@ -287,6 +287,7 @@ pub(crate) async fn handle_cmd_os_guest_instance_create( } #[allow(clippy::too_many_arguments)] +#[allow(clippy::collapsible_if)] pub(crate) async fn do_os_guest_instance_create( cfg: &LitConfig, opts: &CliGlobalOpts, instance_type: GuestType, common_args: GuestInstanceCreateArgsCommon, prov_args: Option, diff --git a/rust/lit-os/lit-cli-os/src/cmd/os/guest/template/create.rs b/rust/lit-os/lit-cli-os/src/cmd/os/guest/template/create.rs index ec8c986..489dcc0 100644 --- a/rust/lit-os/lit-cli-os/src/cmd/os/guest/template/create.rs +++ b/rust/lit-os/lit-cli-os/src/cmd/os/guest/template/create.rs @@ -164,6 +164,7 @@ pub(crate) async fn handle_cmd_os_guest_template_create( } } +#[allow(clippy::collapsible_if)] pub(crate) async fn do_os_guest_template_create( cfg: &LitConfig, opts: &CliGlobalOpts, build_type: GuestType, common_args: GuestTemplateCreateArgsCommon, _prov_args: Option, diff --git a/rust/lit-os/lit-cli-os/src/cmd/os/guest/template/release.rs b/rust/lit-os/lit-cli-os/src/cmd/os/guest/template/release.rs index 567f0c6..596d5b7 100644 --- a/rust/lit-os/lit-cli-os/src/cmd/os/guest/template/release.rs +++ b/rust/lit-os/lit-cli-os/src/cmd/os/guest/template/release.rs @@ -79,13 +79,14 @@ pub(crate) enum NetworkName { InternalDev, } -impl NetworkName { +impl std::fmt::Display for NetworkName { /// Converts the enum variant to its owned string representation. - pub fn to_string(&self) -> String { - self.to_possible_value() - .expect("All NetworkName variants have values") - .get_name() - .to_string() + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "{}", + self.to_possible_value().expect("All NetworkName variants have values").get_name() + ) } } @@ -116,6 +117,7 @@ pub(crate) struct GuestTemplateRelease { pub(crate) data_branch: String, } +#[allow(clippy::collapsible_if)] pub(crate) async fn handle_cmd_os_guest_template_release( cfg: LitConfig, opts: CliGlobalOpts, args: GuestTemplateRelease, ) -> bool { @@ -158,6 +160,7 @@ pub(crate) async fn handle_cmd_os_guest_template_release( /// attempts to authenticate using the `DOCKER_HUB_USERNAME` and `DOCKER_HUB_PASSWORD` /// environment variables. /// 3. Pushes the newly-tagged container image to the Docker Hub repository. +#[allow(clippy::collapsible_if)] async fn do_publish_image(image_repo: &str, build_id: &str, release_id: &str) -> Result<()> { println!("📦 Pushing build environment image to Docker Hub"); diff --git a/rust/lit-os/lit-cli-os/src/cmd/os/guest/template/release_publish.rs b/rust/lit-os/lit-cli-os/src/cmd/os/guest/template/release_publish.rs index b920d26..6a7eb8f 100644 --- a/rust/lit-os/lit-cli-os/src/cmd/os/guest/template/release_publish.rs +++ b/rust/lit-os/lit-cli-os/src/cmd/os/guest/template/release_publish.rs @@ -239,7 +239,7 @@ impl GitPublisher { let gpg_output = TokioCommand::new("gpg") .current_dir(parent_dir) - .args(&["--detach-sign", "--armor", "-u", gpg_key, file_str]) + .args(["--detach-sign", "--armor", "-u", gpg_key, file_str]) .output() .await .map_err(|e| generic_err(e, Some("Failed to execute gpg signing command".into())))?; @@ -264,7 +264,7 @@ impl Drop for GitPublisher { // We use a blocking `std::process::Command` here because `drop` cannot be async. let status = std::process::Command::new("git") .current_dir(&self.repo_path) - .args(&["checkout", &self.original_branch]) + .args(["checkout", &self.original_branch]) .status(); if let Err(e) = status { diff --git a/rust/lit-os/lit-cli-os/src/guest/instance/helper.rs b/rust/lit-os/lit-cli-os/src/guest/instance/helper.rs index ea37851..d58da60 100644 --- a/rust/lit-os/lit-cli-os/src/guest/instance/helper.rs +++ b/rust/lit-os/lit-cli-os/src/guest/instance/helper.rs @@ -37,9 +37,7 @@ impl GuestInstanceHelper for GuestInstanceEnv { /// we perform some other checks to attempt to detect failed creations. fn is_valid(&self) -> bool { if let Ok(exists) = self.service_exists() { - if exists { - return true; - } + return exists; } false @@ -300,10 +298,12 @@ impl GuestInstanceItemHelper for GuestInstanceItem { None, ); - let staking_contract = resolver.staking_contract(cfg).await.expect(&format!( - "Failed to get staking contract from resolver with subnet {:?}", - resolver.subnet_id() - )); + let staking_contract = resolver.staking_contract(cfg).await.unwrap_or_else(|_| { + panic!( + "Failed to get staking contract from resolver with subnet {:?}", + resolver.subnet_id() + ) + }); let staker_address = self.staker_address()?; @@ -313,18 +313,18 @@ impl GuestInstanceItemHelper for GuestInstanceItem { )?; let current_epoch_validators = - staking_contract.get_validators_in_current_epoch(realm_id).await.expect(&format!( - "Failed to get validators in current epoch for realm {} on staking contract {:?}", + staking_contract.get_validators_in_current_epoch(realm_id).await.unwrap_or_else(|_| panic!("Failed to get validators in current epoch for realm {} on staking contract {:?}", realm_id, - staking_contract.address() - )); + staking_contract.address())); let next_epoch_validators = - staking_contract.get_validators_in_next_epoch(realm_id).await.expect(&format!( - "Failed to get validators in next epoch for realm {} on staking contract {:?}", - realm_id, - staking_contract.address() - )); + staking_contract.get_validators_in_next_epoch(realm_id).await.unwrap_or_else(|_| { + panic!( + "Failed to get validators in next epoch for realm {} on staking contract {:?}", + realm_id, + staking_contract.address() + ) + }); let mut validators = Vec::new(); validators.extend(current_epoch_validators); diff --git a/rust/lit-os/lit-cli-os/src/guest/instance/mod.rs b/rust/lit-os/lit-cli-os/src/guest/instance/mod.rs index 53276c8..d0999ae 100644 --- a/rust/lit-os/lit-cli-os/src/guest/instance/mod.rs +++ b/rust/lit-os/lit-cli-os/src/guest/instance/mod.rs @@ -396,6 +396,7 @@ pub fn print_guest_instances( print!("{}", table.render()); } +#[allow(clippy::collapsible_if)] pub fn print_guest_instance_processes( cfg: &LitConfig, items: Vec, output: Option, ) { diff --git a/rust/lit-os/lit-logging-service/Cargo.toml b/rust/lit-os/lit-logging-service/Cargo.toml index 614991a..bab4ad1 100644 --- a/rust/lit-os/lit-logging-service/Cargo.toml +++ b/rust/lit-os/lit-logging-service/Cargo.toml @@ -3,6 +3,10 @@ name = "lit-logging-service" version = "0.1.0" edition.workspace = true +[features] +default = [] +proxy-collector = ["lit-observability/proxy-collector"] + [dependencies] async-trait = { version = "0.1.74" } derive_more = { version = "0.99.17" } diff --git a/rust/lit-os/lit-logging-service/src/config/mod.rs b/rust/lit-os/lit-logging-service/src/config/mod.rs index 994f477..ce547fb 100644 --- a/rust/lit-os/lit-logging-service/src/config/mod.rs +++ b/rust/lit-os/lit-logging-service/src/config/mod.rs @@ -6,8 +6,10 @@ use std::path::PathBuf; use crate::error::Result; +#[allow(dead_code)] pub(crate) const OTEL_SERVICE_DEVICE: &str = "/dev/virtio-ports/com.litprotocol.logging.port0"; +#[allow(dead_code)] pub trait LitLoggingServiceConfig { fn try_new() -> Result; fn must_new() -> LitConfig; diff --git a/rust/lit-os/lit-logging-service/src/metrics.rs b/rust/lit-os/lit-logging-service/src/metrics.rs index 266138a..018958a 100644 --- a/rust/lit-os/lit-logging-service/src/metrics.rs +++ b/rust/lit-os/lit-logging-service/src/metrics.rs @@ -1,6 +1,6 @@ // re export counter -pub use lit_observability::metrics::counter; +#[allow(dead_code)] pub mod grpc { //! Metrics for the gRPC service. @@ -33,6 +33,7 @@ pub mod grpc { } } +#[allow(dead_code)] pub mod device { //! Metrics for the serial devices. @@ -64,6 +65,7 @@ pub mod device { } } +#[allow(dead_code)] pub mod queue { //! Metrics for the queue. diff --git a/rust/lit-os/lit-logging-service/src/service/otel.rs b/rust/lit-os/lit-logging-service/src/service/otel.rs index 81af61d..30723bb 100644 --- a/rust/lit-os/lit-logging-service/src/service/otel.rs +++ b/rust/lit-os/lit-logging-service/src/service/otel.rs @@ -61,7 +61,7 @@ impl OTELService { })); // After starting the queue worker, update the queue size metric. - metrics::counter::add_value( + lit_observability::metrics::counter::add_value( metrics::queue::QueueMetrics::OtelServiceQueueSize, self.queue_rx.len() as u64, &[], @@ -139,7 +139,7 @@ async fn queue_worker(rx: Receiver, quit_rx: Receiver, d if let Err(e) = writeln!(unified_dev, "{json}") { eprintln!("{INTERNAL_LOG_PREFIX}: Failed to write log entry to device (dropping) - {e:?}") } - metrics::counter::add_value(metrics::device::DeviceMetrics::WriteSize, json.len() as u64, &[KeyValue::new( + lit_observability::metrics::counter::add_value(metrics::device::DeviceMetrics::WriteSize, json.len() as u64, &[KeyValue::new( "telemetry_type", "log", )]); @@ -158,7 +158,7 @@ async fn queue_worker(rx: Receiver, quit_rx: Receiver, d if let Err(e) = writeln!(unified_dev, "{json}") { eprintln!("{INTERNAL_LOG_PREFIX}: Failed to write log entry to device (dropping) - {e:?}") } - metrics::counter::add_value(metrics::device::DeviceMetrics::WriteSize, json.len() as u64, &[KeyValue::new( + lit_observability::metrics::counter::add_value(metrics::device::DeviceMetrics::WriteSize, json.len() as u64, &[KeyValue::new( "telemetry_type", "metric", )]); @@ -177,7 +177,7 @@ async fn queue_worker(rx: Receiver, quit_rx: Receiver, d if let Err(e) = writeln!(unified_dev, "{json}") { eprintln!("{INTERNAL_LOG_PREFIX}: Failed to write log entry to device (dropping) - {e:?}") } - metrics::counter::add_value(metrics::device::DeviceMetrics::WriteSize, json.len() as u64, &[KeyValue::new( + lit_observability::metrics::counter::add_value(metrics::device::DeviceMetrics::WriteSize, json.len() as u64, &[KeyValue::new( "telemetry_type", "trace", )]); @@ -193,7 +193,7 @@ async fn queue_worker(rx: Receiver, quit_rx: Receiver, d } // After reading the message, update the queue size metric. - metrics::counter::add_value(metrics::queue::QueueMetrics::OtelServiceQueueSize, rx.len() as u64, &[]); + lit_observability::metrics::counter::add_value(metrics::queue::QueueMetrics::OtelServiceQueueSize, rx.len() as u64, &[]); } } } diff --git a/rust/lit-os/lit-os-core/src/guest/cloud_init/network_config.rs b/rust/lit-os/lit-os-core/src/guest/cloud_init/network_config.rs index bec0fe5..c9d5130 100644 --- a/rust/lit-os/lit-os-core/src/guest/cloud_init/network_config.rs +++ b/rust/lit-os/lit-os-core/src/guest/cloud_init/network_config.rs @@ -78,6 +78,7 @@ impl CloudInitNetworkConfig { Ok(()) } + #[allow(clippy::collapsible_if)] // Generators pub fn to_network_interfaces(&self, path: &Path, skip_internal: bool) -> Result<()> { let mut contents = String::new(); diff --git a/rust/lit-os/lit-os-core/src/utils/validate.rs b/rust/lit-os/lit-os-core/src/utils/validate.rs index 970a0ca..487d036 100644 --- a/rust/lit-os/lit-os-core/src/utils/validate.rs +++ b/rust/lit-os/lit-os-core/src/utils/validate.rs @@ -46,6 +46,7 @@ pub static VALID_LABEL_RE: Lazy = Lazy::new(|| { Regex::new(r"^[a-zA-Z0-9:_-]+").expect("failed to construct regex for label validation") }); +#[allow(clippy::collapsible_if)] pub fn validate_host_name_part(part: &str, max_len: Option) -> Result<()> { if part.is_empty() { return Err(validation_err("invalid length for hostname part", None)); diff --git a/rust/lit-os/lit-os-guest-initrd/src/bin/init/main.rs b/rust/lit-os/lit-os-guest-initrd/src/bin/init/main.rs index aca062c..f1cac7d 100644 --- a/rust/lit-os/lit-os-guest-initrd/src/bin/init/main.rs +++ b/rust/lit-os/lit-os-guest-initrd/src/bin/init/main.rs @@ -2,7 +2,7 @@ use std::backtrace::Backtrace; use std::panic; use env_logger::Env; -use log::{as_error, as_serde, error}; +use log::error; use lit_core::error::{Error, Kind}; use lit_core::utils::backtrace::{backtrace_to_vec, extract_panic_msg}; @@ -32,7 +32,7 @@ async fn main() { None, ); - error!(error = as_error!(err), backtrace = as_serde!(backtrace); + error!(error:err = err, backtrace:serde = backtrace; "Unexpectedly panicked!: {}", msg); })); diff --git a/rust/lit-os/lit-os-guest-initrd/src/init/mod.rs b/rust/lit-os/lit-os-guest-initrd/src/init/mod.rs index c5e3577..9ebd290 100644 --- a/rust/lit-os/lit-os-guest-initrd/src/init/mod.rs +++ b/rust/lit-os/lit-os-guest-initrd/src/init/mod.rs @@ -1,4 +1,4 @@ -use log::{as_error, error, info}; +use log::{error, info}; use nix::unistd::Uid; use std::process::exit; @@ -16,7 +16,7 @@ pub async fn init() { // Init context let mut ctx = match InitContext::new(false) { Err(e) => { - error!(error = as_error!(e); "InitContext->new() failed"); + error!(error:err = e; "InitContext->new() failed"); exit(255); } Ok(ctx) => ctx, diff --git a/rust/lit-os/lit-os-guest-initrd/src/init/stage/attest/mod.rs b/rust/lit-os/lit-os-guest-initrd/src/init/stage/attest/mod.rs index b05691b..ecc322b 100644 --- a/rust/lit-os/lit-os-guest-initrd/src/init/stage/attest/mod.rs +++ b/rust/lit-os/lit-os-guest-initrd/src/init/stage/attest/mod.rs @@ -1,5 +1,5 @@ use lit_attestation::verification::Policy; -use log::{as_error, error, info}; +use log::{error, info}; use lit_os_core::error::{Result, validation_err}; use lit_os_core::guest::oneshot::config::ACTION_TYPE_BOOTSTRAP; @@ -9,7 +9,7 @@ use crate::init::stage::Outcome; pub(crate) async fn run(ctx: &mut InitContext) -> Result { if let Err(e) = verify_attestation(ctx).await { - error!(error = as_error!(e); "Attestation failed"); + error!(error:err = e; "Attestation failed"); return Ok(Outcome::Diagnose); } diff --git a/rust/lit-os/lit-os-guest-initrd/src/init/stage/cleanup/mod.rs b/rust/lit-os/lit-os-guest-initrd/src/init/stage/cleanup/mod.rs index fd89de5..d8d4bd2 100644 --- a/rust/lit-os/lit-os-guest-initrd/src/init/stage/cleanup/mod.rs +++ b/rust/lit-os/lit-os-guest-initrd/src/init/stage/cleanup/mod.rs @@ -40,10 +40,8 @@ pub(crate) fn unmount(mnt: PathBuf, force: bool, unlink: bool) { error!("error unmounting: {}", e); } - if unlink { - if let Err(e) = fs::remove_dir_all(mnt.as_path()) { - error!("error removing dir ({:?}): {}", mnt, e); - } + if unlink && let Err(e) = fs::remove_dir_all(mnt.as_path()) { + error!("error removing dir ({:?}): {}", mnt, e); } } } diff --git a/rust/lit-os/lit-os-guest-initrd/src/init/stage/debug/mod.rs b/rust/lit-os/lit-os-guest-initrd/src/init/stage/debug/mod.rs index 00080e4..42fe59f 100644 --- a/rust/lit-os/lit-os-guest-initrd/src/init/stage/debug/mod.rs +++ b/rust/lit-os/lit-os-guest-initrd/src/init/stage/debug/mod.rs @@ -70,10 +70,10 @@ async fn test_network(_ctx: &mut InitContext) -> Result<()> { ); } Ok(_) => { - error!("Failed to ping: {} ({}) (no response)", host, ip.to_string()) + error!("Failed to ping: {} ({}) (no response)", host, ip) } Err(e) => { - error!("Failed to ping: {} ({}) - {:?}", host, ip.to_string(), e) + error!("Failed to ping: {} ({}) - {:?}", host, ip, e) } } } diff --git a/rust/lit-os/lit-os-guest-initrd/src/init/stage/mod.rs b/rust/lit-os/lit-os-guest-initrd/src/init/stage/mod.rs index 0885105..212a6cb 100644 --- a/rust/lit-os/lit-os-guest-initrd/src/init/stage/mod.rs +++ b/rust/lit-os/lit-os-guest-initrd/src/init/stage/mod.rs @@ -2,7 +2,7 @@ use std::time::Duration; use std::{env, thread}; use futures::future::LocalBoxFuture; -use log::{as_error, error, info, warn}; +use log::{error, info, warn}; use lit_os_core::error::Result; @@ -75,7 +75,7 @@ pub(crate) async fn run_all(ctx: &mut InitContext) -> bool { Outcome::PowerOff => { // Poweroff if requested if let Err(e) = busybox_poweroff() { - error!(error = as_error!(e); "Failed to poweroff"); + error!(error:err = e; "Failed to poweroff"); }; } Outcome::Halt | Outcome::Diagnose => { @@ -96,7 +96,7 @@ async fn run(ctx: &mut InitContext, stage: &str, fun: StageHandler) -> Outcome { let res = fun(ctx).await; let outcome: Outcome; if let Err(e) = res { - error!(error = as_error!(e); "Stage '{}' failed", stage); + error!(error:err = e; "Stage '{}' failed", stage); outcome = Outcome::Break; } else { @@ -121,7 +121,7 @@ fn securely_handle_failure(ctx: &mut InitContext) { info!("Tearing down system due to failure"); if let Err(e) = deactivate_luks_volumes(ctx) { - error!(error = as_error!(e); "Failed to deactivate_luks_volumes, halting boot"); + error!(error:err = e; "Failed to deactivate_luks_volumes, halting boot"); thread::sleep(Duration::from_secs(u64::MAX)); } } diff --git a/rust/lit-os/lit-os-guest-initrd/src/init/stage/oneshot/action/bootstrap.rs b/rust/lit-os/lit-os-guest-initrd/src/init/stage/oneshot/action/bootstrap.rs index 6f85cae..d352086 100644 --- a/rust/lit-os/lit-os-guest-initrd/src/init/stage/oneshot/action/bootstrap.rs +++ b/rust/lit-os/lit-os-guest-initrd/src/init/stage/oneshot/action/bootstrap.rs @@ -103,7 +103,7 @@ async fn bootstrap_prov( dest.as_path(), ctx.build_env().guest_cpu_type()?, guest_vcpus, - &vec![id_block, auth_info], + &[id_block, auth_info], )?; // Push updates (if any). diff --git a/rust/lit-os/lit-os-guest-initrd/src/init/stage/oneshot/mod.rs b/rust/lit-os/lit-os-guest-initrd/src/init/stage/oneshot/mod.rs index 53d26c6..d5cb516 100644 --- a/rust/lit-os/lit-os-guest-initrd/src/init/stage/oneshot/mod.rs +++ b/rust/lit-os/lit-os-guest-initrd/src/init/stage/oneshot/mod.rs @@ -1,6 +1,6 @@ use std::{env, fs}; -use log::{as_error, error, info}; +use log::{error, info}; use lit_os_core::config::LitOsGuestConfig; use lit_os_core::error::{Result, config_err, io_err, validation_err}; @@ -64,7 +64,7 @@ pub(crate) async fn run(ctx: &mut InitContext) -> Result { Ok(ActionOutcome::Continue) => continue, Ok(ActionOutcome::Break) => break, Err(e) => { - error!(error = as_error!(e); "one shot action '{}' failed", action.action()); + error!(error:err = e; "one shot action '{}' failed", action.action()); unsafe { env::remove_var(ENV_LOG_INIT_SUB_STAGE); } diff --git a/rust/lit-os/lit-os-guest-initrd/src/init/stage/prepare/mod.rs b/rust/lit-os/lit-os-guest-initrd/src/init/stage/prepare/mod.rs index 8d142d3..3e21257 100644 --- a/rust/lit-os/lit-os-guest-initrd/src/init/stage/prepare/mod.rs +++ b/rust/lit-os/lit-os-guest-initrd/src/init/stage/prepare/mod.rs @@ -9,7 +9,7 @@ use lit_core::utils::option::bool_option_to_bool; use lit_os_core::config::LitOsGuestConfig; use lit_os_core::error::{Result, config_err, io_err, validation_err}; use lit_os_core::guest::types::GuestType; -use log::{as_error, error, info}; +use log::{error, info}; use std::path::Path; pub(crate) async fn run(ctx: &mut InitContext) -> Result { @@ -20,7 +20,7 @@ pub(crate) async fn run(ctx: &mut InitContext) -> Result { } if let Err(e) = verify_tee() { - error!(error = as_error!(e); "unable to proceed: TEE invalid"); + error!(error:err = e; "unable to proceed: TEE invalid"); return Ok(Outcome::Break); } @@ -30,7 +30,7 @@ pub(crate) async fn run(ctx: &mut InitContext) -> Result { match verify(ctx) { Err(e) => { - error!(error = as_error!(e); "unable to proceed: context verification failed"); + error!(error:err = e; "unable to proceed: context verification failed"); Ok(Outcome::Break) } @@ -151,7 +151,7 @@ fn check_dev_exists(path: &Path, label: &str) -> bool { if !path.exists() { let err = io_err(format!("{label} dev ({path:?}) does not exist!"), None); - error!(error = as_error!(err); "unable to proceed: required device missing"); + error!(error:err = err; "unable to proceed: required device missing"); return false; } diff --git a/rust/lit-os/lit-os-guest-initrd/src/init/stage/sync/mod.rs b/rust/lit-os/lit-os-guest-initrd/src/init/stage/sync/mod.rs index 27cbcee..077cd41 100644 --- a/rust/lit-os/lit-os-guest-initrd/src/init/stage/sync/mod.rs +++ b/rust/lit-os/lit-os-guest-initrd/src/init/stage/sync/mod.rs @@ -309,10 +309,10 @@ fn run_prepare(ctx: &mut InitContext, root_mnt: &Path, var_mnt: &Path) -> Result .arg("--fqdn") .arg(fqdn); - if let Some(allow_ssh) = ctx.build_env().build_opt_ssh.as_ref() { - if *allow_ssh { - cmd.arg("--init-ssh"); - } + if let Some(allow_ssh) = ctx.build_env().build_opt_ssh.as_ref() + && *allow_ssh + { + cmd.arg("--init-ssh"); } let out = cmd diff --git a/rust/lit-os/lit-os-guest-initrd/src/init/stage/unlock/mod.rs b/rust/lit-os/lit-os-guest-initrd/src/init/stage/unlock/mod.rs index 2fbaab0..d3ac645 100644 --- a/rust/lit-os/lit-os-guest-initrd/src/init/stage/unlock/mod.rs +++ b/rust/lit-os/lit-os-guest-initrd/src/init/stage/unlock/mod.rs @@ -2,7 +2,7 @@ use std::path::{Path, PathBuf}; use std::time::Duration; use std::{fs, thread}; -use log::{as_error, error, info}; +use log::{error, info}; use lit_core::error::Unexpected; use lit_core::utils::binary::bytes_to_hex; @@ -32,7 +32,7 @@ pub(crate) async fn run(ctx: &mut InitContext) -> Result { verify_hashes(ctx)?; if let Err(e) = maybe_resize_volumes(ctx) { - error!(error = as_error!(e); "unable to proceed: volume resize failed"); + error!(error:err = e; "unable to proceed: volume resize failed"); return Ok(Outcome::Diagnose); } @@ -220,10 +220,11 @@ fn verify_var_hash(ctx: &mut InitContext) -> Result<()> { })?; let var_dev_label = format!("{}:{:?}", "var", var_dev.as_path()); - if let Some(var_hash) = ctx.cmdline_env().build_varhhash.as_ref() { - if ctx.is_first_boot() && guest_type != GuestType::Prov { - verify_hash(ctx, &var_dev, var_hash, &var_dev_label)?; - } + if let Some(var_hash) = ctx.cmdline_env().build_varhhash.as_ref() + && ctx.is_first_boot() + && guest_type != GuestType::Prov + { + verify_hash(ctx, &var_dev, var_hash, &var_dev_label)?; } Ok(()) diff --git a/rust/lit-os/lit-os-guest-initrd/src/logging.rs b/rust/lit-os/lit-os-guest-initrd/src/logging.rs index 157de0b..9d4fcb6 100644 --- a/rust/lit-os/lit-os-guest-initrd/src/logging.rs +++ b/rust/lit-os/lit-os-guest-initrd/src/logging.rs @@ -63,8 +63,7 @@ impl LogFormatter { let kvs = record.key_values(); if kvs.count() > 0 { - kvs.visit(&mut FieldCollectorKVVisitor(&mut fields)) - .map_err(|e| io::Error::new(io::ErrorKind::Other, e))?; + kvs.visit(&mut FieldCollectorKVVisitor(&mut fields)).map_err(io::Error::other)?; if !fields.is_empty() { let mut fields_style = buf.style(); diff --git a/rust/lit-os/lit-os-metrics/src/lib.rs b/rust/lit-os/lit-os-metrics/src/lib.rs index 2e145a3..9e0d32f 100644 --- a/rust/lit-os/lit-os-metrics/src/lib.rs +++ b/rust/lit-os/lit-os-metrics/src/lib.rs @@ -1,4 +1,4 @@ -//! +//! Handles OS metrics //! #![deny(unsafe_code)] diff --git a/rust/lit-os/lit-os-prov-api-client/src/client.rs b/rust/lit-os/lit-os-prov-api-client/src/client.rs index e77facc..633791f 100644 --- a/rust/lit-os/lit-os-prov-api-client/src/client.rs +++ b/rust/lit-os/lit-os-prov-api-client/src/client.rs @@ -97,7 +97,7 @@ async fn lookup_api_domain(cfg: &LitConfig, resolver: &ContractResolver) -> Resu #[cfg(feature = "trust-dns")] fn create_http_client() -> Result { let mut client = Client::builder(); - client = client.trust_dns(true); + client = client.hickory_dns(true); let client = client .build() diff --git a/rust/lit-os/lit-os-prov-api/Cargo.toml b/rust/lit-os/lit-os-prov-api/Cargo.toml index 8723f5e..7974285 100644 --- a/rust/lit-os/lit-os-prov-api/Cargo.toml +++ b/rust/lit-os/lit-os-prov-api/Cargo.toml @@ -11,6 +11,7 @@ path = "./src/main.rs" [features] default = ["lit-attestation/generate-via-service"] +proxy-collector = ["lit-observability/proxy-collector"] [dependencies] config = { workspace = true } diff --git a/rust/lit-os/lit-os-prov-core/src/release/common/keys.rs b/rust/lit-os/lit-os-prov-core/src/release/common/keys.rs index 139c545..983b8bd 100644 --- a/rust/lit-os/lit-os-prov-core/src/release/common/keys.rs +++ b/rust/lit-os/lit-os-prov-core/src/release/common/keys.rs @@ -140,7 +140,7 @@ pub fn extract_host_identity_fingerprint(release_dir: &Path) -> Result> } pub fn write_identity_files( - dest_dir: &Path, guest_vcpu_type: GuestCpuType, guest_vcpus: u16, assets: &Vec, + dest_dir: &Path, guest_vcpu_type: GuestCpuType, guest_vcpus: u16, assets: &[String], ) -> Result<()> { let mut dest = dest_dir.to_path_buf(); dest.push("id"); @@ -158,7 +158,7 @@ pub fn write_identity_files( "failed to write AMD SEV-SNP identity files, assets len < 2", None, )); } - let id_block = assets.get(0).expect_or_err("expected assets.0 to exist")?; + let id_block = assets.first().expect_or_err("expected assets.0 to exist")?; let auth_info = assets.get(1).expect_or_err("expected assets.1 to exist")?; let mut auth_info_dest = dest.clone(); diff --git a/rust/lit-os/lit-os-prov-core/src/release/create/types.rs b/rust/lit-os/lit-os-prov-core/src/release/create/types.rs index 8d88c0a..029950c 100644 --- a/rust/lit-os/lit-os-prov-core/src/release/create/types.rs +++ b/rust/lit-os/lit-os-prov-core/src/release/create/types.rs @@ -62,10 +62,10 @@ impl CreateRelease { if self.manifest_cid.is_empty() { return Err(validation_err("missing required field: manifest_cid", None)); } - if self.password.len() == 0 { + if self.password.is_empty() { return Err(validation_err("missing required field: password", None)); } - if self.public_key.len() == 0 { + if self.public_key.is_empty() { return Err(validation_err("missing required field: public_key", None)); } @@ -75,19 +75,19 @@ impl CreateRelease { pub fn sha512(&self) -> Output { let mut hasher = Sha512::new(); hasher.update("release_id"); - hasher.update(&(self.release_id.len() as u64).to_be_bytes()); + hasher.update((self.release_id.len() as u64).to_be_bytes()); hasher.update(self.release_id.as_bytes()); hasher.update("manifest_cid"); - hasher.update(&(self.manifest_cid.len() as u64).to_be_bytes()); + hasher.update((self.manifest_cid.len() as u64).to_be_bytes()); hasher.update(self.manifest_cid.as_bytes()); hasher.update("password"); - hasher.update(&(self.password.len() as u64).to_be_bytes()); + hasher.update((self.password.len() as u64).to_be_bytes()); hasher.update(self.password.as_slice()); hasher.update("public_key"); - hasher.update(&(self.public_key.len() as u64).to_be_bytes()); + hasher.update((self.public_key.len() as u64).to_be_bytes()); hasher.update(self.public_key.as_slice()); hasher.finalize() } diff --git a/rust/lit-os/lit-os-prov-core/src/release/init/types.rs b/rust/lit-os/lit-os-prov-core/src/release/init/types.rs index 4c84f4d..bd1355c 100644 --- a/rust/lit-os/lit-os-prov-core/src/release/init/types.rs +++ b/rust/lit-os/lit-os-prov-core/src/release/init/types.rs @@ -37,7 +37,7 @@ impl InitRelease { pub fn sha512(&self) -> Output { let mut hasher = Sha512::new(); hasher.update("release_id"); - hasher.update(&(self.release_id.len() as u64).to_be_bytes()); + hasher.update((self.release_id.len() as u64).to_be_bytes()); hasher.update(self.release_id.as_bytes()); hasher.finalize() } diff --git a/rust/lit-os/lit-os-prov-core/src/release/issue/types.rs b/rust/lit-os/lit-os-prov-core/src/release/issue/types.rs index c648db4..6a6b771 100644 --- a/rust/lit-os/lit-os-prov-core/src/release/issue/types.rs +++ b/rust/lit-os/lit-os-prov-core/src/release/issue/types.rs @@ -4,7 +4,7 @@ use serde_json::json; use sha2::digest::Output; use sha2::{Digest, Sha512}; -use lit_attestation::attestation::{FromSystem, TryGenerate}; +use lit_attestation::attestation::TryGenerate; use lit_attestation::{Attestation, AttestedRequest}; use lit_core::config::LitConfig; pub use lit_os_core::guest::types::GuestCpuType; @@ -50,16 +50,16 @@ impl IssueRelease { pub fn sha512(&self) -> Output { let mut hasher = Sha512::new(); hasher.update("release_id"); - hasher.update(&(self.release_id.len() as u64).to_be_bytes()); + hasher.update((self.release_id.len() as u64).to_be_bytes()); hasher.update(self.release_id.as_bytes()); hasher.update("vcpu_type"); let vcpu_type_str = self.vcpu_type.to_string(); - hasher.update(&(vcpu_type_str.len() as u64).to_be_bytes()); + hasher.update((vcpu_type_str.len() as u64).to_be_bytes()); hasher.update(vcpu_type_str.as_bytes()); hasher.update("vcpus"); - hasher.update(&self.vcpus.to_le_bytes()); + hasher.update(self.vcpus.to_le_bytes()); hasher.finalize() } } diff --git a/rust/lit-os/rust-toolchain.toml b/rust/lit-os/rust-toolchain.toml index c8969b5..657737a 100644 --- a/rust/lit-os/rust-toolchain.toml +++ b/rust/lit-os/rust-toolchain.toml @@ -1,3 +1,3 @@ [toolchain] -channel = "1.86" +channel = "1.91" components = ['rustfmt', 'rust-src', 'clippy']