use std::sync::Arc;
use rand::RngCore;
use crate::error::SdkError;
use crate::signer::Signer;
use crate::tx::{commitment_hash, encode, tx_hash, TxBuilder};
use crate::types::{Receipt, Tx, TxHash};
use super::pending::PendingTx;
use super::provider_trait::{Provider, RootProvider};
use super::transport::Transport;
const COMMIT_GAS_LIMIT: u64 = 100_000;
const REVEAL_BASE_GAS: u64 = 21_000;
const REVEAL_GAS_PER_BYTE: u64 = 16;
fn reveal_gas_limit(inner_len: usize) -> u64 {
let charged =
REVEAL_BASE_GAS.saturating_add(REVEAL_GAS_PER_BYTE.saturating_mul(inner_len as u64));
charged.saturating_add(REVEAL_BASE_GAS) }
#[derive(Clone)]
pub struct PrivateSendHandle {
commit_hash: TxHash,
reveal_hash: TxHash,
inner_hash: TxHash,
provider: Arc<dyn Provider>,
}
impl PrivateSendHandle {
#[must_use]
pub fn commit_hash(&self) -> TxHash {
self.commit_hash
}
#[must_use]
pub fn reveal_hash(&self) -> TxHash {
self.reveal_hash
}
#[must_use]
pub fn inner_hash(&self) -> TxHash {
self.inner_hash
}
pub async fn await_receipt(&self) -> Result<Receipt, SdkError> {
PendingTx::new(self.inner_hash, self.provider.clone())
.wait_for_receipt()
.await
}
}
impl std::fmt::Debug for PrivateSendHandle {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("PrivateSendHandle")
.field("commit_hash", &self.commit_hash)
.field("reveal_hash", &self.reveal_hash)
.field("inner_hash", &self.inner_hash)
.finish_non_exhaustive()
}
}
impl<T: Transport + 'static> RootProvider<T> {
pub async fn send_private<S: Signer + ?Sized>(
self: &Arc<Self>,
signer: &S,
mut inner: Tx,
) -> Result<PrivateSendHandle, SdkError> {
let committer = signer.address();
if inner.from != committer {
return Err(SdkError::InvalidArgument(format!(
"send_private: inner.from ({}) must equal signer address ({}); \
use TxBuilder::commit / TxBuilder::reveal for the relay case",
inner.from, committer
)));
}
let base = self.get_nonce(&committer).await?;
let chain_id = inner.chain_id;
inner.nonce = base.saturating_add(2);
signer.sign_tx(&mut inner).await?;
let inner_bytes = encode(&inner)?;
let inner_hash = tx_hash(&inner);
let mut salt = [0u8; 32];
rand::thread_rng().fill_bytes(&mut salt);
let commitment = commitment_hash(&inner_bytes, &salt);
let value_ceiling = inner.value;
let mut commit_tx = TxBuilder::new()
.from(committer)
.chain_id(chain_id)
.nonce(base)
.commit(commitment, value_ceiling)?
.gas_limit(COMMIT_GAS_LIMIT)
.build()?;
signer.sign_tx(&mut commit_tx).await?;
let commit_hash = self.send_raw_transaction(&commit_tx).await?;
let provider: Arc<dyn Provider> = self.clone();
let commit_receipt = PendingTx::new(commit_hash, provider.clone())
.wait_for_receipt()
.await?;
if !commit_receipt.is_success() {
return Err(SdkError::Rpc(format!(
"commit {} did not succeed (status {:?}); reveal not sent",
commit_receipt.tx_hash, commit_receipt.status
)));
}
let mut reveal_tx = TxBuilder::new()
.from(committer)
.chain_id(chain_id)
.nonce(base.saturating_add(1))
.reveal(commitment, salt, inner_bytes.clone())?
.gas_limit(reveal_gas_limit(inner_bytes.len()))
.build()?;
signer.sign_tx(&mut reveal_tx).await?;
let reveal_hash = self.send_raw_transaction(&reveal_tx).await?;
Ok(PrivateSendHandle {
commit_hash,
reveal_hash,
inner_hash,
provider,
})
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
#[test]
fn reveal_gas_scales_with_payload() {
assert_eq!(reveal_gas_limit(0), REVEAL_BASE_GAS + REVEAL_BASE_GAS);
assert_eq!(
reveal_gas_limit(1000),
REVEAL_BASE_GAS + REVEAL_GAS_PER_BYTE * 1000 + REVEAL_BASE_GAS
);
}
}