Skip to content

Commit

Permalink
fix: commit reveal test passing again
Browse files Browse the repository at this point in the history
  • Loading branch information
gluax committed May 7, 2024
1 parent 1da43f1 commit e96efbd
Show file tree
Hide file tree
Showing 21 changed files with 638 additions and 455 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions packages/common/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ edition = "2021"
cosmwasm-schema = { workspace = true }
cosmwasm-std = { workspace = true }
cw-utils = { workspace = true }
k256 = { workspace = true }
schemars = { workspace = true }
serde = { workspace = true }
thiserror = { workspace = true }
Expand Down
18 changes: 18 additions & 0 deletions packages/common/src/crypto.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
use k256::ecdsa::{RecoveryId, Signature, VerifyingKey};

use crate::types::{Secpk256k1PublicKey, Signature as Sig};

pub fn recover_pubkey(msg_hash: [u8; 32], signature: Sig) -> Secpk256k1PublicKey {
let rs = signature.0[0..64].into();
let id = match signature.0[64] {
0 => RecoveryId::new(false, false),
1 => RecoveryId::new(true, false),
_ => todo!("ERROR"),
};

let sig = Signature::from_bytes(rs).expect("TODO");

// Recover
let pubkey = VerifyingKey::recover_from_msg(&msg_hash, &sig, id).expect("TODO");
pubkey.to_sec1_bytes().to_vec()
}
1 change: 1 addition & 0 deletions packages/common/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
pub mod consts;
pub mod crypto;
pub mod error;
pub mod msg;
pub mod state;
Expand Down
14 changes: 7 additions & 7 deletions packages/common/src/msg.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::state::{DataRequest, DataRequestExecutor, DataResult, RevealBody, StakingConfig};
use crate::types::{Bytes, Commitment, Hash, Memo, Secpk256k1PublicKey};
use crate::types::{Bytes, Commitment, Hash, Memo, Secpk256k1PublicKey, Signature};
use cosmwasm_schema::{cw_serde, QueryResponses};
use cosmwasm_std::Addr;
use semver::Version;
Expand Down Expand Up @@ -35,7 +35,7 @@ pub enum DataRequestsExecuteMsg {
RevealDataResult {
dr_id: Hash,
reveal: RevealBody,
signature: Vec<u8>,
signature: Signature,
sender: Option<String>,
},
}
Expand All @@ -44,29 +44,29 @@ pub enum DataRequestsExecuteMsg {
pub enum StakingExecuteMsg {
RegisterDataRequestExecutor {
public_key: Secpk256k1PublicKey,
signature: Vec<u8>,
signature: Signature,
memo: Option<String>,
sender: Option<String>,
},
UnregisterDataRequestExecutor {
public_key: Secpk256k1PublicKey,
signature: Vec<u8>,
signature: Signature,
sender: Option<String>,
},
DepositAndStake {
public_key: Secpk256k1PublicKey,
signature: Vec<u8>,
signature: Signature,
sender: Option<String>,
},
Unstake {
public_key: Secpk256k1PublicKey,
signature: Vec<u8>,
signature: Signature,
amount: u128,
sender: Option<String>,
},
Withdraw {
public_key: Secpk256k1PublicKey,
signature: Vec<u8>,
signature: Signature,
amount: u128,
sender: Option<String>,
},
Expand Down
87 changes: 87 additions & 0 deletions packages/common/src/types.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,92 @@
use schemars::{
gen::SchemaGenerator,
schema::{Schema, SchemaObject, SingleOrVec},
JsonSchema,
};
use serde::{
de::{SeqAccess, Visitor},
ser::SerializeTuple,
Deserialize, Deserializer, Serialize, Serializer,
};

pub type Bytes = Vec<u8>;
pub type Commitment = Hash;
pub type Memo = Vec<u8>;
pub type Hash = [u8; 32];
pub type Secpk256k1PublicKey = Vec<u8>;

#[derive(Clone, Debug, PartialEq)]
pub struct Signature(pub(crate) [u8; 65]);

impl Signature {
pub fn new(signature: [u8; 65]) -> Self {
Self(signature)
}
}

impl Serialize for Signature {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut seq = serializer.serialize_tuple(65)?;
for byte in &self.0 {
seq.serialize_element(byte)?;
}
seq.end()
}
}

impl<'de> Deserialize<'de> for Signature {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct ArrayVisitor;

impl<'de> Visitor<'de> for ArrayVisitor {
type Value = Signature;

fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("a byte array of length 65")
}

fn visit_seq<V>(self, mut seq: V) -> Result<Signature, V::Error>
where
V: SeqAccess<'de>,
{
let mut array = [0u8; 65];
for (i, byte) in array.iter_mut().enumerate() {
*byte = seq
.next_element()?
.ok_or_else(|| serde::de::Error::invalid_length(i, &self))?;
}
Ok(Signature(array))
}
}

deserializer.deserialize_tuple(65, ArrayVisitor)
}
}

impl JsonSchema for Signature {
fn schema_name() -> String {
"Signature65".to_string()
}

fn json_schema(gen: &mut SchemaGenerator) -> Schema {
let schema = SchemaObject {
instance_type: Some(schemars::schema::InstanceType::Array.into()),
array: Some(Box::new(schemars::schema::ArrayValidation {
items: Some(SingleOrVec::Single(Box::new(gen.subschema_for::<u8>()))),
min_items: Some(65),
max_items: Some(65),
unique_items: Some(false),
additional_items: None,
contains: None,
})),
..Default::default()
};
schema.into()
}
}
8 changes: 2 additions & 6 deletions packages/data-requests/src/data_request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -188,14 +188,10 @@ mod dr_tests {

// expect an error when trying to post it again
let res = execute(deps.as_mut(), mock_env(), info, msg);
assert_eq!(
res.is_err_and(|x| x == ContractError::DataRequestAlreadyExists),
true
);
assert!(res.is_err_and(|x| x == ContractError::DataRequestAlreadyExists));

// should be able to fetch data request with id 0x69...
let received_value: GetDataRequestResponse =
get_dr(deps.as_mut(), constructed_dr_id.clone());
let received_value: GetDataRequestResponse = get_dr(deps.as_mut(), constructed_dr_id);

let (constructed_dr_id, dr_args) = calculate_dr_id_and_args(1, 3);

Expand Down
9 changes: 4 additions & 5 deletions packages/data-requests/src/data_request_result.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use cosmwasm_crypto::secp256k1_recover_pubkey;
#[cfg(not(feature = "library"))]
use cosmwasm_std::{Deps, DepsMut, MessageInfo, Response, StdResult};

Expand All @@ -7,6 +6,7 @@ use common::types::Hash;

pub mod data_request_results {

use common::crypto::recover_pubkey;
use common::error::ContractError::{
self, AlreadyCommitted, AlreadyRevealed, IneligibleExecutor, NotCommitted, RevealMismatch,
RevealNotStarted, RevealStarted,
Expand All @@ -19,7 +19,7 @@ pub mod data_request_results {
GetResolvedDataResultResponse, GetRevealedDataResultsResponse,
};
use common::state::{DataResult, RevealBody};
use common::types::{Bytes, Secpk256k1PublicKey};
use common::types::{Bytes, Secpk256k1PublicKey, Signature};

use crate::contract::CONTRACT_VERSION;
use crate::state::DATA_REQUESTS_POOL;
Expand Down Expand Up @@ -84,7 +84,7 @@ pub mod data_request_results {
env: Env,
dr_id: Hash,
reveal_body: RevealBody,
signature: Vec<u8>,
signature: Signature,
sender: Option<String>,
) -> Result<Response, ContractError> {
let sender = validate_sender(&deps, info.sender, sender)?;
Expand All @@ -98,8 +98,7 @@ pub mod data_request_results {
let reveal_body_hash = compute_hash(reveal_body.clone());

// recover public key from signature
let public_key: Secpk256k1PublicKey =
secp256k1_recover_pubkey(&reveal_body_hash, &signature, 0).unwrap();
let public_key: Secpk256k1PublicKey = recover_pubkey(reveal_body_hash, signature);

// find the data request from the committed pool (if it exists, otherwise error)
let mut dr = DATA_REQUESTS_POOL.load(deps.storage, dr_id)?;
Expand Down
8 changes: 4 additions & 4 deletions packages/data-requests/src/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,8 @@ pub fn calculate_dr_id_and_args(

let constructed_dr_input = PostDataRequestArgs {
version: version.clone(),
dr_binary_id: dr_binary_id.clone(),
tally_binary_id: tally_binary_id.clone(),
dr_binary_id,
tally_binary_id,
dr_inputs: dr_inputs.clone(),
tally_inputs: tally_inputs.clone(),
memo: memo.clone(),
Expand Down Expand Up @@ -130,7 +130,7 @@ pub fn get_dr(deps: DepsMut, dr_id: Hash) -> GetDataRequestResponse {
common::msg::DataRequestsQueryMsg::GetDataRequest { dr_id },
)
.unwrap();
let value: GetDataRequestResponse = from_json(&res).unwrap();
let value: GetDataRequestResponse = from_json(res).unwrap();
value
}

Expand All @@ -145,6 +145,6 @@ pub fn get_drs_from_pool(
common::msg::DataRequestsQueryMsg::GetDataRequestsFromPool { position, limit },
)
.unwrap();
let value: GetDataRequestsFromPoolResponse = from_json(&res).unwrap();
let value: GetDataRequestsFromPoolResponse = from_json(res).unwrap();
value
}
6 changes: 2 additions & 4 deletions packages/integration-tests/src/data_request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ fn post_data_request() {
let posted_dr = calculate_dr_id_and_args(1, 3);
// post the data request
let msg = ProxyExecuteMsg::PostDataRequest {
posted_dr: posted_dr,
posted_dr,
seda_payload: "".into(),
payback_address: "".into(),
};
Expand All @@ -27,9 +27,7 @@ fn post_data_request() {
// should be able to fetch data request
let dr_id = get_dr_id(res);

let msg = ProxyQueryMsg::GetDataRequest {
dr_id: dr_id.clone(),
};
let msg = ProxyQueryMsg::GetDataRequest { dr_id };
let res: GetDataRequestResponse = app
.wrap()
.query_wasm_smart(proxy_contract.addr(), &msg)
Expand Down
Loading

0 comments on commit e96efbd

Please sign in to comment.