Skip to content

Commit

Permalink
revert rust contract debug print
Browse files Browse the repository at this point in the history
  • Loading branch information
ailisp committed Oct 31, 2024
1 parent 87d7414 commit 8da137c
Show file tree
Hide file tree
Showing 6 changed files with 9 additions and 121 deletions.
8 changes: 2 additions & 6 deletions .github/workflows/unit.yml
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,8 @@ jobs:
( cd test-oidc-provider ; cargo fmt -- --check )
( cd integration-tests/chain-signatures ; cargo fmt -- --check )
( cd integration-tests/fastauth ; cargo fmt -- --check )
- name: Unit tests
run: ( cd mpc-recovery && cargo test )
- name: Test clippy
run: |
( cd chain-signatures ; cargo clippy --tests -- -Dclippy::all )
Expand All @@ -69,12 +71,6 @@ jobs:
( cd test-oidc-provider ; cargo clippy --tests -- -Dclippy::all )
( cd integration-tests/chain-signatures ; cargo clippy --tests -- -Dclippy::all )
( cd integration-tests/fastauth ; cargo clippy --tests -- -Dclippy::all )
- name: Unit tests (FastAuth)
working-directory: mpc-recovery
run: cargo test
- name: Unit tests (Chain Signatures)
working-directory: chain-signatures
run: cargo test
audit:
name: Audit
Expand Down
2 changes: 1 addition & 1 deletion chain-signatures/contract/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,4 @@ digest = "0.10.7"

# near dependencies
near-crypto = "0.26.0"
near-workspaces = "0.14.1"
near-workspaces = { git = "https://github.com/near/near-workspaces-rs", branch = "phuong/tmp-node-2.3.0" }
41 changes: 0 additions & 41 deletions chain-signatures/contract/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -853,44 +853,3 @@ impl VersionedMpcContract {
Ok(voter)
}
}

#[cfg(test)]
mod tests {
use crate::config::Config;

#[test]
fn test_load_config2() {
let config_macro = serde_json::json!({
"protocol": {
"message_timeout": 10000,
"garbage_timeout": 20000,
"max_concurrent_introduction": 10,
"max_concurrent_generation": 10,
"triple": {
"min_triples": 10,
"max_triples": 100,
"generation_timeout": 10000
},
"presignature": {
"min_presignatures": 10,
"max_presignatures": 100,
"generation_timeout": 10000
},
"signature": {
"generation_timeout": 10000,
"generation_timeout_total": 1000000,
"garbage_timeout": 10000000
},
"string": "value",
"integer": 1000
},
"string": "value2",
"integer": 20
});

let config: Config = serde_json::from_value(config_macro).unwrap();
assert_eq!(config.protocol.message_timeout, 10000);
assert_eq!(config.get("integer").unwrap(), serde_json::json!(20));
assert_eq!(config.get("string").unwrap(), serde_json::json!("value2"));
}
}
28 changes: 3 additions & 25 deletions chain-signatures/contract/tests/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ use k256::elliptic_curve::ops::Reduce;
use k256::elliptic_curve::point::DecompressPoint as _;
use k256::elliptic_curve::sec1::ToEncodedPoint;
use k256::{AffinePoint, FieldBytes, Scalar, Secp256k1};
use k256::pkcs8::EncodePrivateKey;
use mpc_contract::primitives::{
CandidateInfo, ParticipantInfo, Participants, SignRequest, SignatureRequest,
};
Expand Down Expand Up @@ -70,9 +69,7 @@ pub async fn accounts(
pub async fn init() -> (Worker<Sandbox>, Contract) {
let worker = near_workspaces::sandbox().await.unwrap();
let wasm = std::fs::read(CONTRACT_FILE_PATH).unwrap();
let contract = worker.dev_deploy(&wasm).await;
println!("{:?}", contract);
let contract = contract.unwrap();
let contract = worker.dev_deploy(&wasm).await.unwrap();
(worker, contract)
}

Expand Down Expand Up @@ -127,15 +124,8 @@ pub async fn init_with_candidates(
}

pub async fn init_env() -> (Worker<Sandbox>, Contract, Vec<Account>, k256::SecretKey) {
let bt = FieldBytes::from_slice(&[138, 168, 39, 233, 27, 207, 102, 142, 255, 136, 108, 126, 68, 146, 218, 135, 233, 113, 121, 137, 188, 188, 173, 100, 83, 107, 18, 35, 18, 99, 192, 136]);
let sk = k256::SecretKey::from_bytes(&bt).unwrap();
println!("init_env sk bytes {:?}", bt);
// let sk = k256::SecretKey::random(&mut rand::thread_rng());
let sk = k256::SecretKey::random(&mut rand::thread_rng());
let pk = sk.public_key();
use k256::elliptic_curve::group::GroupEncoding;
println!("init_env pk {:?}\n{:?}\n{:?}\n{:?}", pk, pk.as_affine(), pk.to_sec1_bytes(), pk.as_affine().to_bytes());
let pt = pk.to_encoded_point(false);
println!("uncompressed: {:?}\n{:?}", pt, pt.to_bytes());
let (worker, contract, accounts) =
init_with_candidates(Some(near_crypto::PublicKey::SECP256K1(
near_crypto::Secp256K1PublicKey::try_from(
Expand Down Expand Up @@ -170,15 +160,10 @@ pub async fn create_response(
) -> ([u8; 32], SignatureRequest, SignatureResponse) {
let (digest, scalar_hash, payload_hash) = process_message(msg).await;
let pk = sk.public_key();
println!("create_response public_key: {:?}", pk);

let epsilon = derive_epsilon(predecessor_id, path);
let derived_sk = derive_secret_key(sk, epsilon);
println!("epsilon: {:?} {:?}", epsilon, epsilon.to_bytes());
let derived_pk = derive_key(pk.into(), epsilon);
println!("derived_pk: {:?} {:?}", derived_pk, derived_pk.to_encoded_point(false).to_bytes());
let p1 = AccountId::new_unvalidated("0x70997970C51812dc3A010C7d01b50e0d17dc79C8".to_string().to_lowercase());
let path = "test";
println!("derive_epsilon({}, {}) = {:?}", p1, path, derive_epsilon(&p1, path));
let signing_key = k256::ecdsa::SigningKey::from(&derived_sk);
let verifying_key =
k256::ecdsa::VerifyingKey::from(&k256::PublicKey::from_affine(derived_pk).unwrap());
Expand All @@ -195,16 +180,9 @@ pub async fn create_response(
AffinePoint::decompress(&r_bytes, k256::elliptic_curve::subtle::Choice::from(0)).unwrap();
let s: k256::Scalar = *s.as_ref();

println!("=== derived_pk {:?} {:?}\nbig_r {:?} {:?}\ns {:?}\nscalar_hash {:?}", derived_pk,
derived_pk.to_encoded_point(false).to_bytes(),
big_r,
big_r.to_encoded_point(false).to_bytes(),
s, scalar_hash);
let recovery_id = if check_ec_signature(&derived_pk, &big_r, &s, scalar_hash, 0).is_ok() {
println!("0 is ok");
0
} else if check_ec_signature(&derived_pk, &big_r, &s, scalar_hash, 1).is_ok() {
println!("1 is ok");
1
} else {
panic!("unable to use recovery id of 0 or 1");
Expand Down
38 changes: 0 additions & 38 deletions chain-signatures/contract/tests/sign.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,44 +8,6 @@ use near_workspaces::types::{AccountId, NearToken};
use crypto_shared::SignatureResponse;
use std::collections::HashMap;

#[tokio::test]
async fn test_contract_sign_simple() -> anyhow::Result<()> {
let (_, contract, _, sk) = init_env().await;
let predecessor_id = contract.id();
let path = "test";

let msg = "hello world";
let (payload_hash, respond_req, respond_resp) =
create_response(predecessor_id, msg, path, &sk).await;
let request = SignRequest {
payload: payload_hash,
path: path.into(),
key_version: 0,
};

sign_and_validate(&request, Some((&respond_req, &respond_resp)), &contract).await?;
Ok(())
}

#[tokio::test]
async fn test_contract_sign_eth() -> anyhow::Result<()> {
let (_, contract, _, sk) = init_env().await;
let predecessor_id = AccountId::new_unvalidated("0x70997970C51812dc3A010C7d01b50e0d17dc79C8".to_string().to_lowercase());
let path = "test";

let msg = "hello world";
let (payload_hash, respond_req, respond_resp) =
create_response(&predecessor_id, msg, path, &sk).await;
let request = SignRequest {
payload: payload_hash,
path: path.into(),
key_version: 0,
};

sign_and_validate(&request, Some((&respond_req, &respond_resp)), &contract).await?;
Ok(())
}

#[tokio::test]
async fn test_contract_sign_request() -> anyhow::Result<()> {
let (_, contract, _, sk) = init_env().await;
Expand Down
13 changes: 3 additions & 10 deletions chain-signatures/crypto-shared/src/kdf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@ use k256::{
Scalar, Secp256k1, SecretKey,
};
use near_account_id::AccountId;
use sha3::{Digest, Keccak256, Sha3_256};
use sha3::{Digest, Sha3_256};

// Constant prefix that ensures epsilon derivation values are used specifically for
// near-mpc-recovery with key derivation protocol vX.Y.Z.
const EPSILON_DERIVATION_PREFIX: &str = "near-mpc-recovery v0.2.0 epsilon derivation:";
const EPSILON_DERIVATION_PREFIX: &str = "near-mpc-recovery v0.1.0 epsilon derivation:";

pub fn derive_epsilon(predecessor_id: &AccountId, path: &str) -> Scalar {
// TODO: Use a key derivation library instead of doing this manually.
Expand All @@ -22,8 +22,7 @@ pub fn derive_epsilon(predecessor_id: &AccountId, path: &str) -> Scalar {
// Do not reuse this hash function on anything that isn't an account
// ID or it'll be vunerable to Hash Melleability/extention attacks.
let derivation_path = format!("{EPSILON_DERIVATION_PREFIX}{},{}", predecessor_id, path);
println!("derivation_path: \n{}", derivation_path);
let mut hasher = Keccak256::new();
let mut hasher = Sha3_256::new();
hasher.update(derivation_path);
let hash: [u8; 32] = hasher.finalize().into();
Scalar::from_non_biased(hash)
Expand Down Expand Up @@ -53,21 +52,15 @@ pub fn check_ec_signature(
msg_hash: Scalar,
recovery_id: u8,
) -> anyhow::Result<()> {
println!("---");
let public_key = expected_pk.to_encoded_point(false);
println!("public_key {}", public_key.to_string());
let signature = k256::ecdsa::Signature::from_scalars(x_coordinate(big_r), s)
.context("cannot create signature from cait_sith signature")?;
println!("signature {} {}", signature.r(), signature.s());
println!("msg_hash {:?}", msg_hash);
let found_pk = recover(
&msg_hash.to_bytes(),
&signature,
RecoveryId::try_from(recovery_id).context("invalid recovery ID")?,
)?
.to_encoded_point(false);
println!("found_pk {}", found_pk.to_string());

if public_key == found_pk {
return Ok(());
}
Expand Down

0 comments on commit 8da137c

Please sign in to comment.