From 7c4ba383dd14fe8c8e3435d40422c1ea3a5a4d10 Mon Sep 17 00:00:00 2001 From: Serhii Volovyk Date: Mon, 22 Jul 2024 21:54:52 +0300 Subject: [PATCH] Contract refactoring, API, README, etc (#706) * fix contract tests, add attached and required to errors * error and error messages naming * return more specific errors in user facing functions * fix error conversion issue * separate user facing functions into one impl block * move some of the contract structs to primitives * API and envs README * revert MpcError -> SignError * fmt * Update chain-signatures/contract/src/errors.rs Co-authored-by: DavidM-D * Update chain-signatures/contract/src/errors.rs Co-authored-by: DavidM-D * Update chain-signatures/contract/src/errors.rs Co-authored-by: DavidM-D * Update chain-signatures/contract/src/errors.rs Co-authored-by: DavidM-D * ignore RUSTSEC-2024-0357 * make sign_helper private --------- Co-authored-by: DavidM-D --- .github/workflows/unit.yml | 4 +- chain-signatures/README.md | 55 ++++ chain-signatures/contract/src/errors.rs | 54 +-- chain-signatures/contract/src/lib.rs | 308 ++++++++---------- chain-signatures/contract/src/primitives.rs | 39 ++- chain-signatures/contract/tests/tests.rs | 13 +- .../node/src/protocol/signature.rs | 2 +- .../chain-signatures/tests/actions/mod.rs | 5 +- 8 files changed, 273 insertions(+), 207 deletions(-) create mode 100644 chain-signatures/README.md diff --git a/.github/workflows/unit.yml b/.github/workflows/unit.yml index 4151f4766..7acadc911 100644 --- a/.github/workflows/unit.yml +++ b/.github/workflows/unit.yml @@ -77,10 +77,10 @@ jobs: - name: Run Audit (FastAuth) working-directory: integration-tests/fastauth run: | - cargo audit --ignore RUSTSEC-2020-0071 --ignore RUSTSEC-2023-0052 --ignore RUSTSEC-2022-0093 --ignore RUSTSEC-2023-0071 --ignore RUSTSEC-2024-0019 --ignore RUSTSEC-2024-0344 + cargo audit --ignore RUSTSEC-2020-0071 --ignore RUSTSEC-2023-0052 --ignore RUSTSEC-2022-0093 --ignore RUSTSEC-2023-0071 --ignore RUSTSEC-2024-0019 --ignore RUSTSEC-2024-0344 --ignore RUSTSEC-2024-0357 - name: Run Audit (Chain Signatures) # even if previous audit step fails, run this audit step to ensure all crates are audited if: always() working-directory: integration-tests/chain-signatures run: | - cargo audit --ignore RUSTSEC-2020-0071 --ignore RUSTSEC-2023-0052 --ignore RUSTSEC-2022-0093 --ignore RUSTSEC-2023-0071 --ignore RUSTSEC-2024-0019 --ignore RUSTSEC-2024-0344 --ignore RUSTSEC-2022-0093 --ignore RUSTSEC-2024-0346 --ignore RUSTSEC-2024-0347 + cargo audit --ignore RUSTSEC-2020-0071 --ignore RUSTSEC-2023-0052 --ignore RUSTSEC-2022-0093 --ignore RUSTSEC-2023-0071 --ignore RUSTSEC-2024-0019 --ignore RUSTSEC-2024-0344 --ignore RUSTSEC-2022-0093 --ignore RUSTSEC-2024-0346 --ignore RUSTSEC-2024-0347 --ignore RUSTSEC-2024-0357 diff --git a/chain-signatures/README.md b/chain-signatures/README.md new file mode 100644 index 000000000..da9562239 --- /dev/null +++ b/chain-signatures/README.md @@ -0,0 +1,55 @@ +# Chain Signatures API + +## `sign()` +This is the main function of the contract API. It is used to sign a request with the MPC service. +```rust +pub fn sign(&mut self, request: SignRequest) -> Result +``` +Arguments and return type: +```rust +pub struct SignRequest { + pub payload: [u8; 32], + pub path: String, + pub key_version: u32, +} + +pub struct SignResult { + pub big_r: String, + pub s: String, +} +``` +- `key_version` must be less than or equal to the value at `latest_key_version`. +- `path` is a derivation path for the key that will be used to sign the payload. +- To avoid overloading the network with too many requests, we ask for a small deposit for each signature request. The fee changes based on how busy the network is. + +## `public_key()` +This is the root public key combined from all the public keys of the participants. +```rust +pub fn public_key(&self) -> Result +``` + +## `derived_public_key()` +This is the derived public key of the caller given path and predecessor. If the predecessor is not provided, it will be the caller of the contract. +```rust +pub fn derived_public_key( + &self, + path: String, + predecessor: Option, + ) -> Result +``` + +## `latest_key_version()` +Key versions refer new versions of the root key that we may choose to generate on cohort changes. Older key versions will always work but newer key versions were never held by older signers. Newer key versions may also add new security features, like only existing within a secure enclave. Currently only 0 is a valid key version. +```rust +pub const fn latest_key_version(&self) -> u32 +``` + +For more details check `User contract API` impl block in the [chain-signatures/contracts/src/lib.rs](./chain-signatures/contracts/src/lib.rs) file. + +# Environments +Currently, we have 3 environments: +1. Mainnet: `v1.multichain-mpc.near` // TODO: set when available +2. Testnet: `v2.multichain-mpc.testnet` +3. Dev: `v5.multichain-mpc-dev.testnet` + +Contracts can be changed from v1 to v2, etc. Older contracts should continue functioning. \ No newline at end of file diff --git a/chain-signatures/contract/src/errors.rs b/chain-signatures/contract/src/errors.rs index af3e6404b..09a4d773c 100644 --- a/chain-signatures/contract/src/errors.rs +++ b/chain-signatures/contract/src/errors.rs @@ -1,36 +1,40 @@ +use near_sdk::Gas; + #[derive(Debug, thiserror::Error)] pub enum SignError { #[error("Signature request has timed out.")] Timeout, - #[error("Signature request has already been submitted. Please, try again later.")] + #[error("Signature request has already been submitted. Please try again later.")] PayloadCollision, - #[error("Payload hash cannot be convereted to Scalar.")] - PayloadMalform, - #[error("Contract version is greater than allowed.")] - VersionTooHigh, - #[error("Attached deposit is lower than required: {0}.")] - DepositInsufficient(String), - #[error("Provided gas is lower than required: {0}.")] - GasInsufficient(String), - #[error("Too many pending requests. Please, try again later.")] + #[error("Malformed payload: {0}")] + MalformedPayload(String), + #[error( + "This key version is not supported. Call latest_key_version() to get the latest supported version." + )] + UnsupportedKeyVersion, + #[error("Attached deposit is lower than required. Attached: {0}, Required: {1}.")] + InsufficientDeposit(u128, u128), + #[error("Provided gas is lower than required. Provided: {0}, required {1}.")] + InsufficientGas(Gas, Gas), + #[error("Too many pending requests. Please try again later.")] RequestLimitExceeded, - #[error("This sign request was removed from pending requests: timed out or completed.")] - RequestNotInPending, + #[error("This sign request has timed out, was completed, or never existed.")] + RequestNotFound, } #[derive(Debug, thiserror::Error)] pub enum RespondError { - #[error("This sign request was removed from pending requests: timed out or completed.")] - RequestNotInPending, - #[error("Signature could not be verified.")] - SignatureNotVerified, - #[error("Protocol state is not running.")] - ProtocolStateNotRunning, + #[error("This sign request has timed out, was completed, or never existed.")] + RequestNotFound, + #[error("The provided signature is invalid.")] + InvalidSignature, + #[error("The protocol is not Running.")] + ProtocolNotInRunningState, } #[derive(Debug, thiserror::Error)] pub enum JoinError { - #[error("Protocol state is not running")] + #[error("The protocol is not Running.")] ProtocolStateNotRunning, } @@ -50,20 +54,20 @@ pub enum InitError { #[derive(Debug, thiserror::Error)] pub enum VoteError { - #[error("Voting account is not not in the participant set.")] + #[error("Voting account is not in the participant set.")] VoterNotParticipant, - #[error("Account to be kicked is not not in the participant set.")] + #[error("Account to be kicked is not in the participant set.")] KickNotParticipant, - #[error("Account to join is not not in the candidates set.")] + #[error("Account to join is not in the candidate set.")] JoinNotCandidate, #[error("Account to join is already in the participant set.")] JoinAlreadyParticipant, #[error("Mismatched epoch.")] - MismatchedEpoch, + EpochMismatch, #[error("Number of participants cannot go below threshold.")] ParticipantsBelowThreshold, - #[error("Protocol state is not the expected: {0}")] - ProtocolStateNotExpected(String), + #[error("Unexpected protocol state: {0}")] + UnexpectedProtocolState(String), } #[derive(Debug, thiserror::Error)] diff --git a/chain-signatures/contract/src/lib.rs b/chain-signatures/contract/src/lib.rs index f927647e0..21e1cffe7 100644 --- a/chain-signatures/contract/src/lib.rs +++ b/chain-signatures/contract/src/lib.rs @@ -3,7 +3,7 @@ pub mod primitives; use crypto_shared::{ derive_epsilon, derive_key, kdf::check_ec_signature, near_public_key_to_affine_point, - types::SignatureResponse, ScalarExt as _, SerializableScalar, + types::SignatureResponse, ScalarExt as _, }; use k256::Scalar; use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize}; @@ -11,8 +11,8 @@ use near_sdk::collections::LookupMap; use near_sdk::serde::{Deserialize, Serialize}; use near_sdk::{ - env, log, near_bindgen, AccountId, BorshStorageKey, CryptoHash, Gas, GasWeight, NearToken, - PromiseError, PublicKey, + env, log, near_bindgen, AccountId, CryptoHash, Gas, GasWeight, NearToken, PromiseError, + PublicKey, }; use errors::{ @@ -21,7 +21,7 @@ use errors::{ use k256::elliptic_curve::sec1::ToEncodedPoint; use primitives::{ CandidateInfo, Candidates, ParticipantInfo, Participants, PkVotes, SignRequest, - SignaturePromiseError, SignatureResult, Votes, + SignaturePromiseError, SignatureRequest, SignatureResult, StorageKey, Votes, YieldIndex, }; use std::collections::{BTreeMap, HashSet}; @@ -73,12 +73,6 @@ pub enum ProtocolContractState { Resharing(ResharingContractState), } -#[derive(BorshSerialize, BorshDeserialize, BorshStorageKey, Hash, Clone, Debug, PartialEq, Eq)] -#[borsh(crate = "near_sdk::borsh")] -pub enum StorageKey { - PendingRequests, -} - #[near_bindgen] #[derive(BorshDeserialize, BorshSerialize, Debug)] pub enum VersionedMpcContract { @@ -91,35 +85,6 @@ impl Default for VersionedMpcContract { } } -/// The index into calling the YieldResume feature of NEAR. This will allow to resume -/// a yield call after the contract has been called back via this index. -#[derive(BorshDeserialize, BorshSerialize, Serialize, Deserialize, Debug, Clone)] -#[borsh(crate = "near_sdk::borsh")] -pub struct YieldIndex { - data_id: CryptoHash, -} - -#[derive(BorshDeserialize, BorshSerialize, Serialize, Deserialize, Debug, Clone)] -#[borsh(crate = "near_sdk::borsh")] -pub struct SignatureRequest { - pub epsilon: SerializableScalar, - pub payload_hash: SerializableScalar, -} - -impl SignatureRequest { - pub fn new(payload_hash: Scalar, predecessor_id: &AccountId, path: &str) -> Self { - let epsilon = derive_epsilon(predecessor_id, path); - let epsilon = SerializableScalar { scalar: epsilon }; - let payload_hash = SerializableScalar { - scalar: payload_hash, - }; - SignatureRequest { - epsilon, - payload_hash, - } - } -} - #[derive(BorshDeserialize, BorshSerialize, Debug)] pub struct MpcContract { protocol_state: ProtocolContractState, @@ -143,7 +108,7 @@ impl MpcContract { self.request_counter -= 1; Ok(()) } else { - Err(MpcContractError::SignError(SignError::RequestNotInPending)) + Err(MpcContractError::SignError(SignError::RequestNotFound)) } } @@ -179,23 +144,28 @@ impl VersionedMpcContract { let latest_key_version: u32 = self.latest_key_version(); // It's important we fail here because the MPC nodes will fail in an identical way. // This allows users to get the error message - let payload = Scalar::from_bytes(payload) - .ok_or(MpcContractError::SignError(SignError::PayloadMalform))?; + let payload = Scalar::from_bytes(payload).ok_or(MpcContractError::SignError( + SignError::MalformedPayload("Payload hash cannot be convereted to Scalar".to_string()), + ))?; if key_version > latest_key_version { - return Err(MpcContractError::SignError(SignError::VersionTooHigh)); + return Err(MpcContractError::SignError( + SignError::UnsupportedKeyVersion, + )); } // Check deposit let deposit = env::attached_deposit(); let required_deposit = self.signature_deposit(); if deposit.as_yoctonear() < required_deposit { - return Err(MpcContractError::SignError(SignError::DepositInsufficient( - "{required_deposit}".to_string(), + return Err(MpcContractError::SignError(SignError::InsufficientDeposit( + deposit.as_yoctonear(), + required_deposit, ))); } // Make sure sign call will not run out of gas doing recursive calls because the payload will never be removed if env::prepaid_gas() < GAS_FOR_SIGN_CALL { - return Err(MpcContractError::SignError(SignError::GasInsufficient( - "{GAS_FOR_SIGN_CALL}".to_string(), + return Err(MpcContractError::SignError(SignError::InsufficientGas( + env::prepaid_gas(), + GAS_FOR_SIGN_CALL, ))); } @@ -219,75 +189,51 @@ impl VersionedMpcContract { } } - pub fn sign_helper(&mut self, request: SignatureRequest) { - match self { - Self::V0(mpc_contract) => { - let yield_promise = env::promise_yield_create( - "clear_state_on_finish", - &serde_json::to_vec(&(&request,)).unwrap(), - CLEAR_STATE_ON_FINISH_CALL_GAS, - GasWeight(0), - DATA_ID_REGISTER, - ); - - // Store the request in the contract's local state - let data_id: CryptoHash = env::read_register(DATA_ID_REGISTER) - .expect("read_register failed") - .try_into() - .expect("conversion to CryptoHash failed"); - - mpc_contract.add_request(&request, data_id); - - // NOTE: there's another promise after the clear_state_on_finish to avoid any errors - // that would rollback the state. - let final_yield_promise = env::promise_then( - yield_promise, - env::current_account_id(), - "return_signature_on_finish", - &[], - NearToken::from_near(0), - RETURN_SIGNATURE_ON_FINISH_CALL_GAS, - ); - // The return value for this function call will be the value - // returned by the `sign_on_finish` callback. - env::promise_return(final_yield_promise); - } + /// This is the root public key combined from all the public keys of the participants. + #[handle_result] + pub fn public_key(&self) -> Result { + match self.state() { + ProtocolContractState::Running(state) => Ok(state.public_key.clone()), + ProtocolContractState::Resharing(state) => Ok(state.public_key.clone()), + _ => Err(MpcContractError::PublicKeyError( + PublicKeyError::ProtocolStateNotRunningOrResharing, + )), } } - #[private] + /// This is the derived public key of the caller given path and predecessor + /// if predecessor is not provided, it will be the caller of the contract #[handle_result] - pub fn return_signature_on_finish( - &mut self, - #[callback_unwrap] signature: SignatureResult, - ) -> Result { - match self { - Self::V0(_) => match signature { - SignatureResult::Ok(signature) => Ok(signature), - SignatureResult::Err(_) => Err(MpcContractError::SignError(SignError::Timeout)), - }, - } + pub fn derived_public_key( + &self, + path: String, + predecessor: Option, + ) -> Result { + let predecessor = predecessor.unwrap_or_else(env::predecessor_account_id); + let epsilon = derive_epsilon(&predecessor, &path); + let derived_public_key = + derive_key(near_public_key_to_affine_point(self.public_key()?), epsilon); + let encoded_point = derived_public_key.to_encoded_point(false); + let slice: &[u8] = &encoded_point.as_bytes()[1..65]; + let mut data: Vec = vec![near_sdk::CurveType::SECP256K1 as u8]; + data.extend(slice.to_vec()); + PublicKey::try_from(data).map_err(|_| { + MpcContractError::PublicKeyError(PublicKeyError::DerivedKeyConversionFailed) + }) } - #[private] - #[handle_result] - pub fn clear_state_on_finish( - &mut self, - request: SignatureRequest, - #[callback_result] signature: Result, - ) -> Result, MpcContractError> { - match self { - Self::V0(mpc_contract) => { - // Clean up the local state - mpc_contract.remove_request(request)?; - match signature { - Ok(signature) => Ok(SignatureResult::Ok(signature)), - Err(_) => Ok(SignatureResult::Err(SignaturePromiseError::Failed)), - } - } - } + /// Key versions refer new versions of the root key that we may choose to generate on cohort changes + /// Older key versions will always work but newer key versions were never held by older signers + /// Newer key versions may also add new security features, like only existing within a secure enclave + /// Currently only 0 is a valid key version + pub const fn latest_key_version(&self) -> u32 { + 0 } +} +// Node API +#[near_bindgen] +impl VersionedMpcContract { #[handle_result] pub fn respond( &mut self, @@ -307,10 +253,9 @@ impl VersionedMpcContract { ); // generate the expected public key - let expected_public_key = derive_key( - near_public_key_to_affine_point(self.public_key()?), - request.epsilon.scalar, - ); + let pk = self.public_key()?; + let expected_public_key = + derive_key(near_public_key_to_affine_point(pk), request.epsilon.scalar); // Check the signature is correct if check_ec_signature( @@ -323,7 +268,7 @@ impl VersionedMpcContract { .is_err() { return Err(MpcContractError::RespondError( - RespondError::SignatureNotVerified, + RespondError::InvalidSignature, )); } @@ -339,64 +284,18 @@ impl VersionedMpcContract { Ok(()) } else { Err(MpcContractError::RespondError( - RespondError::RequestNotInPending, + RespondError::RequestNotFound, )) } } } } else { Err(MpcContractError::RespondError( - RespondError::ProtocolStateNotRunning, + RespondError::ProtocolNotInRunningState, )) } } - /// This is the root public key combined from all the public keys of the participants. - #[handle_result] - pub fn public_key(&self) -> Result { - match self.state() { - ProtocolContractState::Running(state) => Ok(state.public_key.clone()), - ProtocolContractState::Resharing(state) => Ok(state.public_key.clone()), - _ => Err(MpcContractError::PublicKeyError( - PublicKeyError::ProtocolStateNotRunningOrResharing, - )), - } - } - - /// This is the derived public key of the caller given path and predecessor - /// if predecessor is not provided, it will be the caller of the contract - #[handle_result] - pub fn derived_public_key( - &self, - path: String, - predecessor: Option, - ) -> Result { - let predecessor = predecessor.unwrap_or_else(env::predecessor_account_id); - let epsilon = derive_epsilon(&predecessor, &path); - let derived_public_key = - derive_key(near_public_key_to_affine_point(self.public_key()?), epsilon); - let encoded_point = derived_public_key.to_encoded_point(false); - let slice: &[u8] = &encoded_point.as_bytes()[1..65]; - let mut data: Vec = vec![near_sdk::CurveType::SECP256K1 as u8]; - data.extend(slice.to_vec()); - PublicKey::try_from(data).map_err(|_| { - errors::MpcContractError::PublicKeyError(PublicKeyError::DerivedKeyConversionFailed) - }) - } - - /// Key versions refer new versions of the root key that we may choose to generate on cohort changes - /// Older key versions will always work but newer key versions were never held by older signers - /// Newer key versions may also add new security features, like only existing within a secure enclave - /// Currently only 0 is a valid key version - pub const fn latest_key_version(&self) -> u32 { - 0 - } - - // contract version - pub fn version(&self) -> String { - env!("CARGO_PKG_VERSION").to_string() - } - #[handle_result] pub fn join( &mut self, @@ -486,7 +385,7 @@ impl VersionedMpcContract { } } _ => Err(MpcContractError::VoteError( - VoteError::ProtocolStateNotExpected("running".to_string()), + VoteError::UnexpectedProtocolState("running".to_string()), )), } } @@ -539,7 +438,7 @@ impl VersionedMpcContract { } } _ => Err(MpcContractError::VoteError( - VoteError::ProtocolStateNotExpected("running".to_string()), + VoteError::UnexpectedProtocolState("running".to_string()), )), } } @@ -582,7 +481,7 @@ impl VersionedMpcContract { ProtocolContractState::Running(state) if state.public_key == public_key => Ok(true), ProtocolContractState::Resharing(state) if state.public_key == public_key => Ok(true), _ => Err(MpcContractError::VoteError( - VoteError::ProtocolStateNotExpected( + VoteError::UnexpectedProtocolState( "initializing or running/resharing with the same public key".to_string(), ), )), @@ -607,7 +506,7 @@ impl VersionedMpcContract { finished_votes, }) => { if *old_epoch + 1 != epoch { - return Err(MpcContractError::VoteError(VoteError::MismatchedEpoch)); + return Err(MpcContractError::VoteError(VoteError::EpochMismatch)); } let signer_account_id = env::signer_account_id(); if !old_participants.contains_key(&signer_account_id) { @@ -634,12 +533,12 @@ impl VersionedMpcContract { Ok(true) } else { Err(MpcContractError::VoteError( - VoteError::ProtocolStateNotExpected("resharing".to_string()), + VoteError::UnexpectedProtocolState("resharing".to_string()), )) } } _ => Err(MpcContractError::VoteError( - VoteError::ProtocolStateNotExpected("resharing".to_string()), + VoteError::UnexpectedProtocolState("resharing".to_string()), )), } } @@ -712,6 +611,81 @@ impl VersionedMpcContract { } } + // contract version + pub fn version(&self) -> String { + env!("CARGO_PKG_VERSION").to_string() + } + + #[private] + pub fn sign_helper(&mut self, request: SignatureRequest) { + match self { + Self::V0(mpc_contract) => { + let yield_promise = env::promise_yield_create( + "clear_state_on_finish", + &serde_json::to_vec(&(&request,)).unwrap(), + CLEAR_STATE_ON_FINISH_CALL_GAS, + GasWeight(0), + DATA_ID_REGISTER, + ); + + // Store the request in the contract's local state + let data_id: CryptoHash = env::read_register(DATA_ID_REGISTER) + .expect("read_register failed") + .try_into() + .expect("conversion to CryptoHash failed"); + + mpc_contract.add_request(&request, data_id); + + // NOTE: there's another promise after the clear_state_on_finish to avoid any errors + // that would rollback the state. + let final_yield_promise = env::promise_then( + yield_promise, + env::current_account_id(), + "return_signature_on_finish", + &[], + NearToken::from_near(0), + RETURN_SIGNATURE_ON_FINISH_CALL_GAS, + ); + // The return value for this function call will be the value + // returned by the `sign_on_finish` callback. + env::promise_return(final_yield_promise); + } + } + } + + #[private] + #[handle_result] + pub fn return_signature_on_finish( + &mut self, + #[callback_unwrap] signature: SignatureResult, + ) -> Result { + match self { + Self::V0(_) => match signature { + SignatureResult::Ok(signature) => Ok(signature), + SignatureResult::Err(_) => Err(MpcContractError::SignError(SignError::Timeout)), + }, + } + } + + #[private] + #[handle_result] + pub fn clear_state_on_finish( + &mut self, + request: SignatureRequest, + #[callback_result] signature: Result, + ) -> Result, MpcContractError> { + match self { + Self::V0(mpc_contract) => { + // Clean up the local state + mpc_contract.remove_request(request)?; + match signature { + Ok(signature) => Ok(SignatureResult::Ok(signature)), + Err(_) => Ok(SignatureResult::Err(SignaturePromiseError::Failed)), + } + } + } + } + #[private] #[init(ignore_state)] pub fn clean(keys: Vec) -> Self { diff --git a/chain-signatures/contract/src/primitives.rs b/chain-signatures/contract/src/primitives.rs index 354b2143e..1e5c066d6 100644 --- a/chain-signatures/contract/src/primitives.rs +++ b/chain-signatures/contract/src/primitives.rs @@ -1,12 +1,49 @@ +use crypto_shared::{derive_epsilon, SerializableScalar}; +use k256::Scalar; use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize}; use near_sdk::serde::{Deserialize, Serialize}; -use near_sdk::{AccountId, PublicKey}; +use near_sdk::{AccountId, BorshStorageKey, CryptoHash, PublicKey}; use std::collections::{BTreeMap, HashSet}; pub mod hpke { pub type PublicKey = [u8; 32]; } +#[derive(BorshSerialize, BorshDeserialize, BorshStorageKey, Hash, Clone, Debug, PartialEq, Eq)] +#[borsh(crate = "near_sdk::borsh")] +pub enum StorageKey { + PendingRequests, +} + +/// The index into calling the YieldResume feature of NEAR. This will allow to resume +/// a yield call after the contract has been called back via this index. +#[derive(BorshDeserialize, BorshSerialize, Serialize, Deserialize, Debug, Clone)] +#[borsh(crate = "near_sdk::borsh")] +pub struct YieldIndex { + pub data_id: CryptoHash, +} + +#[derive(BorshDeserialize, BorshSerialize, Serialize, Deserialize, Debug, Clone)] +#[borsh(crate = "near_sdk::borsh")] +pub struct SignatureRequest { + pub epsilon: SerializableScalar, + pub payload_hash: SerializableScalar, +} + +impl SignatureRequest { + pub fn new(payload_hash: Scalar, predecessor_id: &AccountId, path: &str) -> Self { + let epsilon = derive_epsilon(predecessor_id, path); + let epsilon = SerializableScalar { scalar: epsilon }; + let payload_hash = SerializableScalar { + scalar: payload_hash, + }; + SignatureRequest { + epsilon, + payload_hash, + } + } +} + #[derive( Serialize, Deserialize, diff --git a/chain-signatures/contract/tests/tests.rs b/chain-signatures/contract/tests/tests.rs index 5e4c0850a..0ee6122d5 100644 --- a/chain-signatures/contract/tests/tests.rs +++ b/chain-signatures/contract/tests/tests.rs @@ -8,8 +8,8 @@ use k256::elliptic_curve::ops::Reduce; use k256::elliptic_curve::point::DecompressPoint; use k256::elliptic_curve::sec1::ToEncodedPoint; use k256::{AffinePoint, FieldBytes, Scalar, Secp256k1}; -use mpc_contract::primitives::{CandidateInfo, ParticipantInfo, SignRequest}; -use mpc_contract::{errors, SignatureRequest}; +use mpc_contract::errors; +use mpc_contract::primitives::{CandidateInfo, ParticipantInfo, SignRequest, SignatureRequest}; use near_sdk::NearToken; use near_workspaces::network::Sandbox; use near_workspaces::{AccountId, Contract, Worker}; @@ -298,17 +298,14 @@ async fn test_contract_sign_request_deposits() -> anyhow::Result<()> { .await?; dbg!(&respond); assert!(respond.into_result().unwrap_err().to_string().contains( - &errors::MpcContractError::RespondError(errors::RespondError::RequestNotInPending) - .to_string() + &errors::MpcContractError::RespondError(errors::RespondError::RequestNotFound).to_string() )); let execution = status.await?; dbg!(&execution); assert!(execution.into_result().unwrap_err().to_string().contains( - &errors::MpcContractError::SignError(errors::SignError::DepositInsufficient( - "1".to_string() - )) - .to_string() + &errors::MpcContractError::SignError(errors::SignError::InsufficientDeposit(0, 1)) + .to_string() )); Ok(()) diff --git a/chain-signatures/node/src/protocol/signature.rs b/chain-signatures/node/src/protocol/signature.rs index c0f09df1b..a5ad25a29 100644 --- a/chain-signatures/node/src/protocol/signature.rs +++ b/chain-signatures/node/src/protocol/signature.rs @@ -12,7 +12,7 @@ use chrono::Utc; use crypto_shared::SerializableScalar; use crypto_shared::{derive_key, PublicKey}; use k256::{Scalar, Secp256k1}; -use mpc_contract::SignatureRequest; +use mpc_contract::primitives::SignatureRequest; use rand::rngs::StdRng; use rand::seq::{IteratorRandom, SliceRandom}; use rand::SeedableRng; diff --git a/integration-tests/chain-signatures/tests/actions/mod.rs b/integration-tests/chain-signatures/tests/actions/mod.rs index 3a6ede8c2..00f0db451 100644 --- a/integration-tests/chain-signatures/tests/actions/mod.rs +++ b/integration-tests/chain-signatures/tests/actions/mod.rs @@ -15,8 +15,8 @@ use k256::elliptic_curve::ProjectivePoint; use k256::{AffinePoint, EncodedPoint, Scalar, Secp256k1}; use mpc_contract::errors; use mpc_contract::primitives::SignRequest; +use mpc_contract::primitives::SignatureRequest; use mpc_contract::RunningContractState; -use mpc_contract::SignatureRequest; use mpc_recovery_node::kdf::into_eth_sig; use near_crypto::InMemorySigner; use near_jsonrpc_client::methods::broadcast_tx_async::RpcBroadcastTxAsyncRequest; @@ -113,8 +113,7 @@ pub async fn single_signature_rogue_responder( let err = wait_for::rogue_message_responded(ctx, rogue_hash).await?; assert!(err.contains( - &errors::MpcContractError::RespondError(errors::RespondError::SignatureNotVerified) - .to_string() + &errors::MpcContractError::RespondError(errors::RespondError::InvalidSignature).to_string() )); let signature = wait_for::signature_responded(ctx, tx_hash).await?;