Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: cleanup jsonrpc client in integration tests #828

Merged
merged 3 commits into from
Sep 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions chain-signatures/Cargo.lock

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

2 changes: 1 addition & 1 deletion chain-signatures/node/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ url = { version = "2.4.0", features = ["serde"] }

near-account-id = "1.0.0"
near-crypto = "0.23.0"
near-fetch = "0.5.0"
near-fetch = "0.5.1"
near-lake-framework = { git = "https://github.com/near/near-lake-framework-rs", branch = "node/1.40-and-async-run" }
near-lake-primitives = { git = "https://github.com/near/near-lake-framework-rs", branch = "node/1.40-and-async-run" }
near-primitives = "0.23.0"
Expand Down
2 changes: 1 addition & 1 deletion chain-signatures/node/src/protocol/cryptography.rs
Original file line number Diff line number Diff line change
Expand Up @@ -427,7 +427,7 @@ impl CryptographicProtocol for RunningState {
// block height is up to date, such that they too can process signature requests. If they cannot
// then they are considered unstable and should not be a part of signature generation this round.
let stable = ctx.mesh().stable_participants().await;
tracing::info!(?stable, "stable participants");
ChaoticTempest marked this conversation as resolved.
Show resolved Hide resolved
tracing::trace!(?stable, "stable participants");

let mut sign_queue = self.sign_queue.write().await;
crate::metrics::SIGN_QUEUE_SIZE
Expand Down
4 changes: 2 additions & 2 deletions integration-tests/chain-signatures/Cargo.lock

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

2 changes: 1 addition & 1 deletion integration-tests/chain-signatures/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ k256 = { version = "0.13.1", features = ["sha256", "ecdsa", "serde"] }
# near dependencies
near-account-id = "1"
near-crypto = "0.23.0"
near-fetch = "0.5.0"
near-fetch = "0.5.1"
near-jsonrpc-client = "0.10.1"
near-primitives = "0.23.0"
near-lake-framework = { git = "https://github.com/near/near-lake-framework-rs", branch = "node/1.40" }
Expand Down
137 changes: 43 additions & 94 deletions integration-tests/chain-signatures/tests/actions/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,8 @@ use mpc_contract::primitives::SignatureRequest;
use mpc_contract::RunningContractState;
use mpc_node::kdf::into_eth_sig;
use near_crypto::InMemorySigner;
use near_jsonrpc_client::methods::broadcast_tx_async::RpcBroadcastTxAsyncRequest;
use near_lake_primitives::CryptoHash;
use near_primitives::transaction::{Action, FunctionCallAction, Transaction};
use near_fetch::ops::AsyncTransactionStatus;
use near_workspaces::types::NearToken;
use near_workspaces::Account;
use rand::Rng;
use secp256k1::XOnlyPublicKey;
Expand All @@ -40,7 +39,7 @@ use serde_json::json;

pub async fn request_sign(
ctx: &MultichainTestContext<'_>,
) -> anyhow::Result<([u8; 32], [u8; 32], Account, CryptoHash)> {
) -> anyhow::Result<([u8; 32], [u8; 32], Account, AsyncTransactionStatus)> {
let worker = &ctx.nodes.ctx().worker;
let account = worker.dev_create_account().await?;
let payload: [u8; 32] = rand::thread_rng().gen();
Expand All @@ -51,39 +50,24 @@ pub async fn request_sign(
public_key: account.secret_key().public_key().to_string().parse()?,
secret_key: account.secret_key().to_string().parse()?,
};
let (nonce, block_hash, _) = ctx
.rpc_client
.fetch_nonce(&signer.account_id, &signer.public_key)
.await?;

let request = SignRequest {
payload: payload_hashed,
path: "test".to_string(),
key_version: 0,
};
let tx_hash = ctx
.jsonrpc_client
.call(&RpcBroadcastTxAsyncRequest {
signed_transaction: Transaction {
nonce,
block_hash,
signer_id: signer.account_id.clone(),
public_key: signer.public_key.clone(),
receiver_id: ctx.nodes.ctx().mpc_contract.id().clone(),
actions: vec![Action::FunctionCall(Box::new(FunctionCallAction {
method_name: "sign".to_string(),
args: serde_json::to_vec(&serde_json::json!({
"request": request,
}))?,
gas: 300_000_000_000_000,
deposit: 1,
}))],
}
.sign(&signer),
})
let status = ctx
.rpc_client
.call(&signer, ctx.nodes.ctx().mpc_contract.id(), "sign")
.args_json(serde_json::json!({
"request": request,
}))
.max_gas()
.deposit(NearToken::from_yoctonear(1))
.transact_async()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice enhancement, i've seen concurrent tests fail due to invalid nonce

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah hopefully this resolves that a bit. It won't retry though since near-fetch requires explicit .retry_expoential(...)

.await?;
tokio::time::sleep(Duration::from_secs(1)).await;
Ok((payload, payload_hashed, account, tx_hash))
Ok((payload, payload_hashed, account, status))
}

pub async fn assert_signature(
Expand All @@ -104,16 +88,15 @@ pub async fn single_signature_rogue_responder(
ctx: &MultichainTestContext<'_>,
state: &RunningContractState,
) -> anyhow::Result<()> {
let (_, payload_hash, account, tx_hash) = request_sign(ctx).await?;
let (_, payload_hash, account, status) = request_sign(ctx).await?;

// We have to use seperate transactions because one could fail.
// This leads to a potential race condition where this transaction could get sent after the signature completes, but I think that's unlikely
let rogue_hash = rogue_respond(ctx, payload_hash, account.id(), "test").await?;

let err = wait_for::rogue_message_responded(ctx, rogue_hash).await?;
let rogue_status = rogue_respond(ctx, payload_hash, account.id(), "test").await?;
let err = wait_for::rogue_message_responded(rogue_status).await?;

assert!(err.contains(&errors::RespondError::InvalidSignature.to_string()));
let signature = wait_for::signature_responded(ctx, tx_hash).await?;
let signature = wait_for::signature_responded(status).await?;

let mut mpc_pk_bytes = vec![0x04];
mpc_pk_bytes.extend_from_slice(&state.public_key.as_bytes()[1..]);
Expand All @@ -135,8 +118,8 @@ pub async fn single_signature_production(
ctx: &MultichainTestContext<'_>,
state: &RunningContractState,
) -> anyhow::Result<()> {
let (_, payload_hash, account, tx_hash) = request_sign(ctx).await?;
let signature = wait_for::signature_responded(ctx, tx_hash).await?;
let (_, payload_hash, account, status) = request_sign(ctx).await?;
let signature = wait_for::signature_responded(status).await?;

let mut mpc_pk_bytes = vec![0x04];
mpc_pk_bytes.extend_from_slice(&state.public_key.as_bytes()[1..]);
Expand All @@ -150,7 +133,7 @@ pub async fn rogue_respond(
payload_hash: [u8; 32],
predecessor: &near_workspaces::AccountId,
path: &str,
) -> anyhow::Result<CryptoHash> {
) -> anyhow::Result<AsyncTransactionStatus> {
let worker = &ctx.nodes.ctx().worker;
let account = worker.dev_create_account().await?;

Expand All @@ -159,10 +142,6 @@ pub async fn rogue_respond(
public_key: account.secret_key().public_key().clone().into(),
secret_key: account.secret_key().to_string().parse()?,
};
let (nonce, block_hash, _) = ctx
.rpc_client
.fetch_nonce(&signer.account_id, &signer.public_key)
.await?;
let epsilon = derive_epsilon(predecessor, path);

let request = SignatureRequest {
Expand All @@ -185,40 +164,27 @@ pub async fn rogue_respond(
recovery_id: 0,
};

let json = &serde_json::json!({
"request": request,
"response": response,
});
let hash = ctx
.jsonrpc_client
.call(&RpcBroadcastTxAsyncRequest {
signed_transaction: Transaction {
nonce,
block_hash,
signer_id: signer.account_id.clone(),
public_key: signer.public_key.clone(),
receiver_id: ctx.nodes.ctx().mpc_contract.id().clone(),
actions: vec![Action::FunctionCall(Box::new(FunctionCallAction {
method_name: "respond".to_string(),
args: serde_json::to_vec(json)?,
gas: 300_000_000_000_000,
deposit: 0,
}))],
}
.sign(&signer),
})
let status = ctx
.rpc_client
.call(&signer, ctx.nodes.ctx().mpc_contract.id(), "respond")
.args_json(serde_json::json!({
"request": request,
"response": response,
}))
.max_gas()
.transact_async()
.await?;

tokio::time::sleep(Duration::from_secs(1)).await;
Ok(hash)
Ok(status)
}

pub async fn request_sign_non_random(
ctx: &MultichainTestContext<'_>,
account: Account,
payload: [u8; 32],
payload_hashed: [u8; 32],
) -> Result<([u8; 32], [u8; 32], Account, CryptoHash), WaitForError> {
) -> Result<([u8; 32], [u8; 32], Account, AsyncTransactionStatus), WaitForError> {
let signer = InMemorySigner {
account_id: account.id().clone(),
public_key: account
Expand All @@ -233,51 +199,34 @@ pub async fn request_sign_non_random(
.parse()
.map_err(|_| WaitForError::Parsing)?,
};
let (nonce, block_hash, _) = ctx
.rpc_client
.fetch_nonce(&signer.account_id, &signer.public_key)
.await
.map_err(|error| WaitForError::Fetch(format!("{error:?}")))?;

let request = SignRequest {
payload: payload_hashed,
path: "test".to_string(),
key_version: 0,
};

let tx_hash = ctx
.jsonrpc_client
.call(&RpcBroadcastTxAsyncRequest {
signed_transaction: Transaction {
nonce,
block_hash,
signer_id: signer.account_id.clone(),
public_key: signer.public_key.clone(),
receiver_id: ctx.nodes.ctx().mpc_contract.id().clone(),
actions: vec![Action::FunctionCall(Box::new(FunctionCallAction {
method_name: "sign".to_string(),
args: serde_json::to_vec(&serde_json::json!({
"request": request,
}))
.map_err(|error| WaitForError::SerdeJson(format!("{error:?}")))?,
gas: 300_000_000_000_000,
deposit: 1,
}))],
}
.sign(&signer),
})
let status = ctx
.rpc_client
.call(&signer, ctx.nodes.ctx().mpc_contract.id(), "sign")
.args_json(serde_json::json!({
"request": request,
}))
.max_gas()
.deposit(NearToken::from_yoctonear(1))
.transact_async()
.await
.map_err(|error| WaitForError::JsonRpc(format!("{error:?}")))?;
tokio::time::sleep(Duration::from_secs(1)).await;
Ok((payload, payload_hashed, account, tx_hash))
Ok((payload, payload_hashed, account, status))
}

pub async fn single_payload_signature_production(
ctx: &MultichainTestContext<'_>,
state: &RunningContractState,
) -> anyhow::Result<()> {
let (payload, payload_hash, account, tx_hash) = request_sign(ctx).await?;
let first_tx_result = wait_for::signature_responded(ctx, tx_hash).await;
let (payload, payload_hash, account, status) = request_sign(ctx).await?;
let first_tx_result = wait_for::signature_responded(status).await;
let signature = match first_tx_result {
Ok(sig) => sig,
Err(error) => {
Expand Down
Loading
Loading