Skip to content

Commit

Permalink
more work
Browse files Browse the repository at this point in the history
  • Loading branch information
QuantumExplorer committed Oct 19, 2024
1 parent 33d6420 commit 91cbe4a
Show file tree
Hide file tree
Showing 16 changed files with 134 additions and 105 deletions.
28 changes: 16 additions & 12 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 2 additions & 3 deletions packages/rs-dpp/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,13 @@ chrono = { version = "0.4.35", default-features = false, features = [
"clock",
] }
ciborium = { git = "https://github.com/qrayven/ciborium", branch = "feat-ser-null-as-undefined", optional = true }
blsful = { version = "3.0.0-pre6" , optional = true }
dashcore = { git = "https://github.com/dashpay/rust-dashcore", features = [
"std",
"secp-recovery",
"rand",
"signer",
"serde"
], default-features = false, tag = "0.32.0" }
], default-features = false, tag = "0.33.1" }
env_logger = { version = "0.11" }
getrandom = { version = "0.2", features = ["js"] }
hex = { version = "0.4" }
Expand Down Expand Up @@ -74,7 +73,7 @@ once_cell = "1.7"

[features]
default = ["platform-value", "state-transitions"]
bls-signatures = ["dashcore/bls", "blsful"]
bls-signatures = ["dashcore/bls"]
ed25519-dalek = ["dashcore/eddsa"]
all_features = [
"json-object",
Expand Down
46 changes: 32 additions & 14 deletions packages/rs-dpp/src/bls/native_bls.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
use crate::bls_signatures::{
Bls12381G2Impl, Pairing, PublicKey, SecretKey, Signature, SignatureSchemes,
};
use crate::{BlsModule, ProtocolError, PublicKeyValidationError};
use anyhow::anyhow;
use dashcore::bls_signatures::{self, PrivateKey, PublicKey};

#[derive(Default)]
pub struct NativeBlsModule;
impl BlsModule for NativeBlsModule {
fn validate_public_key(&self, pk: &[u8]) -> Result<(), PublicKeyValidationError> {
match PublicKey::from_bytes(pk) {
match PublicKey::<Bls12381G2Impl>::try_from(pk) {
Ok(_) => Ok(()),
Err(e) => Err(PublicKeyValidationError::new(e.to_string())),
}
Expand All @@ -18,31 +20,47 @@ impl BlsModule for NativeBlsModule {
data: &[u8],
public_key: &[u8],
) -> Result<bool, ProtocolError> {
let public_key = PublicKey::from_bytes(public_key).map_err(anyhow::Error::msg)?;
let signature =
bls_signatures::Signature::from_bytes(signature).map_err(anyhow::Error::msg)?;
match public_key.verify(&signature, data) {
true => Ok(true),
// TODO change to specific error type
false => Err(anyhow!("Verification failed").into()),
let public_key =
PublicKey::<Bls12381G2Impl>::try_from(public_key).map_err(anyhow::Error::msg)?;
let signature_96_bytes = signature
.try_into()
.map_err(|_| anyhow!("signature wrong size"))?;
let g2_element =
<Bls12381G2Impl as Pairing>::Signature::from_compressed(&signature_96_bytes)
.into_option()
.ok_or(anyhow!("signature derivation failed"))?;

let signature = Signature::Basic(g2_element);

match signature.verify(&public_key, data) {
Ok(_) => Ok(true),
Err(_) => Err(anyhow!("Verification failed").into()),
}
}

fn private_key_to_public_key(&self, private_key: &[u8]) -> Result<Vec<u8>, ProtocolError> {
let fixed_len_key: [u8; 32] = private_key
.try_into()
.map_err(|_| anyhow!("the BLS private key must be 32 bytes long"))?;
let pk = PrivateKey::from_bytes(&fixed_len_key, false).map_err(anyhow::Error::msg)?;
let public_key = pk.g1_element().map_err(anyhow::Error::msg)?;
let public_key_bytes = public_key.to_bytes().to_vec();
let pk = SecretKey::<Bls12381G2Impl>::from_be_bytes(&fixed_len_key)
.into_option()
.ok_or(anyhow!("Incorrect Priv Key"))?;
let public_key = pk.public_key();
let public_key_bytes = public_key.0.to_compressed().to_vec();
Ok(public_key_bytes)
}

fn sign(&self, data: &[u8], private_key: &[u8]) -> Result<Vec<u8>, ProtocolError> {
let fixed_len_key: [u8; 32] = private_key
.try_into()
.map_err(|_| anyhow!("the BLS private key must be 32 bytes long"))?;
let pk = PrivateKey::from_bytes(&fixed_len_key, false).map_err(anyhow::Error::msg)?;
Ok(pk.sign(data).to_bytes().to_vec())
let pk = SecretKey::<Bls12381G2Impl>::from_be_bytes(&fixed_len_key)
.into_option()
.ok_or(anyhow!("Incorrect Priv Key"))?;
Ok(pk
.sign(SignatureSchemes::Basic, data)?
.as_raw_value()
.to_compressed()
.to_vec())
}
}
3 changes: 1 addition & 2 deletions packages/rs-dpp/src/core_types/validator/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use crate::bls_signatures::PublicKey as BlsPublicKey;
use crate::bls_signatures::{Bls12381G2Impl, PublicKey as BlsPublicKey};
use crate::core_types::validator::v0::{ValidatorV0, ValidatorV0Getters, ValidatorV0Setters};
use blsful::Bls12381G2Impl;
use dashcore::{ProTxHash, PubkeyHash};
#[cfg(feature = "core-types-serde-conversion")]
use serde::{Deserialize, Serialize};
Expand Down
5 changes: 2 additions & 3 deletions packages/rs-dpp/src/core_types/validator/v0/mod.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
use dashcore::{ProTxHash, PubkeyHash};
use std::fmt::{Debug, Formatter};

use crate::bls_signatures::PublicKey as BlsPublicKey;
use blsful::Bls12381G2Impl;
use crate::bls_signatures::{Bls12381G2Impl, PublicKey as BlsPublicKey};
#[cfg(feature = "core-types-serde-conversion")]
use serde::{Deserialize, Serialize};

Expand Down Expand Up @@ -261,7 +260,7 @@ impl ValidatorV0Setters for ValidatorV0 {
mod tests {
use super::*;
use bincode::config;
use blsful::SecretKey;
use dashcore::blsful::SecretKey;
use rand::prelude::StdRng;
use rand::SeedableRng;

Expand Down
3 changes: 1 addition & 2 deletions packages/rs-dpp/src/core_types/validator_set/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::bls_signatures::PublicKey as BlsPublicKey;
use crate::bls_signatures::{Bls12381G2Impl, PublicKey as BlsPublicKey};
use crate::core_types::validator::v0::ValidatorV0;
use crate::core_types::validator_set::v0::{
ValidatorSetV0, ValidatorSetV0Getters, ValidatorSetV0Setters,
Expand All @@ -7,7 +7,6 @@ use crate::core_types::validator_set::v0::{
use crate::ProtocolError;
#[cfg(feature = "core-types-serialization")]
use bincode::{Decode, Encode};
use blsful::Bls12381G2Impl;
use dashcore::{ProTxHash, QuorumHash};
#[cfg(feature = "core-types-serialization")]
use platform_serialization_derive::{PlatformDeserialize, PlatformSerialize};
Expand Down
4 changes: 2 additions & 2 deletions packages/rs-dpp/src/core_types/validator_set/v0/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use bincode::enc::Encoder;
use bincode::error::EncodeError;
#[cfg(feature = "core-types-serialization")]
use bincode::{BorrowDecode, Decode, Encode};
use blsful::Bls12381G2Impl;
use dashcore::blsful::Bls12381G2Impl;
use dashcore::hashes::Hash;
use dashcore::{ProTxHash, QuorumHash};
use itertools::Itertools;
Expand Down Expand Up @@ -289,7 +289,7 @@ impl ValidatorSetV0Setters for ValidatorSetV0 {
mod tests {
use super::*;
use bincode::config;
use blsful::SecretKey;
use dashcore::blsful::SecretKey;
use dashcore::PubkeyHash;
use rand::rngs::StdRng;
use rand::SeedableRng;
Expand Down
5 changes: 5 additions & 0 deletions packages/rs-dpp/src/errors/protocol_error.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use dashcore::blsful::BlsError;
use thiserror::Error;

use crate::consensus::basic::state_transition::InvalidStateTransitionTypeError;
Expand Down Expand Up @@ -247,6 +248,10 @@ pub enum ProtocolError {
/// Invalid CBOR error
#[error("invalid cbor error: {0}")]
InvalidCBOR(String),

/// Invalid CBOR error
#[error(transparent)]
BlsError(#[from] BlsError),
}

impl From<&str> for ProtocolError {
Expand Down
50 changes: 21 additions & 29 deletions packages/rs-dpp/src/identity/identity_public_key/key_type.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,14 @@ use dashcore::secp256k1::rand::rngs::StdRng as EcdsaRng;
#[cfg(feature = "random-public-keys")]
use dashcore::secp256k1::rand::SeedableRng;
use dashcore::secp256k1::Secp256k1;
use dashcore::{bls_signatures, ed25519_dalek, Network};
use dashcore::{blsful, ed25519_dalek, Network};

Check warning on line 11 in packages/rs-dpp/src/identity/identity_public_key/key_type.rs

View workflow job for this annotation

GitHub Actions / Rust packages (wasm-dpp) / Linting

unused import: `blsful`

warning: unused import: `blsful` --> packages/rs-dpp/src/identity/identity_public_key/key_type.rs:11:16 | 11 | use dashcore::{blsful, ed25519_dalek, Network}; | ^^^^^^ | = note: `#[warn(unused_imports)]` on by default
use itertools::Itertools;
use lazy_static::lazy_static;

use crate::bls_signatures::{Bls12381G2Impl, BlsError};
use crate::fee::Credits;
use crate::version::PlatformVersion;
use crate::{InvalidVectorSizeError, ProtocolError};
use blsful::Bls12381G2Impl;
use crate::{bls_signatures, ProtocolError};
#[cfg(feature = "random-public-keys")]
use rand::rngs::StdRng;
#[cfg(feature = "random-public-keys")]
Expand Down Expand Up @@ -166,13 +166,8 @@ impl KeyType {
private_key.public_key(&secp).to_bytes()
}
KeyType::BLS12_381 => {
let private_key = bls_signatures::PrivateKey::generate_dash(rng)
.expect("expected to generate a bls private key"); // we assume this will never error
private_key
.g1_element()
.expect("expected to get a public key from a bls private key")
.to_bytes()
.to_vec()
let private_key = bls_signatures::SecretKey::<Bls12381G2Impl>::random(rng);
private_key.public_key().0.to_compressed().to_vec()
}
KeyType::ECDSA_HASH160 | KeyType::BIP13_SCRIPT_HASH | KeyType::EDDSA_25519_HASH160 => {
(0..self.default_size()).map(|_| rng.gen::<u8>()).collect()
Expand Down Expand Up @@ -205,13 +200,13 @@ impl KeyType {
/// Gets the public key data for a private key depending on the key type
pub fn public_key_data_from_private_key_data(
&self,
private_key_bytes: &[u8],
private_key_bytes: &[u8; 32],
network: Network,
) -> Result<Vec<u8>, ProtocolError> {
match self {
KeyType::ECDSA_SECP256K1 => {
let secp = Secp256k1::new();
let secret_key = dashcore::secp256k1::SecretKey::from_slice(private_key_bytes)
let secret_key = dashcore::secp256k1::SecretKey::from_byte_array(private_key_bytes)
.map_err(|e| ProtocolError::Generic(e.to_string()))?;
let private_key = dashcore::PrivateKey::new(secret_key, network);

Expand All @@ -220,14 +215,18 @@ impl KeyType {
KeyType::BLS12_381 => {
#[cfg(feature = "bls-signatures")]
{
let private_key =
bls_signatures::PrivateKey::from_bytes(private_key_bytes, false)
.map_err(|e| ProtocolError::Generic(e.to_string()))?;
let public_key_bytes = private_key
.g1_element()
.expect("expected to get a public key from a bls private key")
.to_bytes()
.to_vec();
let private_key: Option<bls_signatures::SecretKey<Bls12381G2Impl>> =
bls_signatures::SecretKey::<Bls12381G2Impl>::from_be_bytes(
private_key_bytes,
)
.into();
if private_key.is_none() {
return Err(ProtocolError::BlsError(BlsError::DeserializationError(
"private key bytes not a valid secret key".to_string(),
)));
}
let private_key = private_key.expect("expected private key");
let public_key_bytes = private_key.public_key().0.to_compressed().to_vec();
Ok(public_key_bytes)
}
#[cfg(not(feature = "bls-signatures"))]
Expand All @@ -237,7 +236,7 @@ impl KeyType {
}
KeyType::ECDSA_HASH160 => {
let secp = Secp256k1::new();
let secret_key = dashcore::secp256k1::SecretKey::from_slice(private_key_bytes)
let secret_key = dashcore::secp256k1::SecretKey::from_byte_array(private_key_bytes)
.map_err(|e| ProtocolError::Generic(e.to_string()))?;
let private_key = dashcore::PrivateKey::new(secret_key, network);

Expand All @@ -246,14 +245,7 @@ impl KeyType {
KeyType::EDDSA_25519_HASH160 => {
#[cfg(feature = "ed25519-dalek")]
{
let key_pair = ed25519_dalek::SigningKey::from_bytes(
&private_key_bytes.try_into().map_err(|_| {
ProtocolError::InvalidVectorSizeError(InvalidVectorSizeError::new(
32,
private_key_bytes.len(),
))
})?,
);
let key_pair = ed25519_dalek::SigningKey::from_bytes(&private_key_bytes);
Ok(ripemd160_sha256(key_pair.verifying_key().to_bytes().as_slice()).to_vec())
}
#[cfg(not(feature = "ed25519-dalek"))]
Expand Down
Loading

0 comments on commit 91cbe4a

Please sign in to comment.