use std::sync::Arc;
use std::time::Duration as StdDuration;
use anyhow::{anyhow, Context, Result};
use moonproof_ledger::base_crypto::time::{Duration as MidnightDuration, Timestamp};
use moonproof_node_client::{SubmissionEvent, SubmissionStage};
use moonproof_prover::{EngineProvingProvider, HttpProvingProvider, ProverEngine};
use crate::facade::{
finalize_recipe as finalize_facade_recipe, serialize_finalized, sign_recipe, submit_finalized,
};
use crate::{SubmissionOptions, TokenType, UnprovenTransactionRecipe, WalletError};
#[derive(Debug, Clone, Default)]
pub enum ProvingBackend {
#[default]
InProcess,
HttpServer { base_url: String },
}
impl ProvingBackend {
#[must_use]
pub fn for_network(network: &super::network::NetworkConfig) -> Self {
match &network.proof_server_url {
Some(base_url) => Self::HttpServer {
base_url: base_url.clone(),
},
None => Self::InProcess,
}
}
}
use super::connect::WalletSession;
use super::sync::{resolve_indexer_sync_timeout, sync_wallet_fresh, sync_wallet_resumable};
use crate::facade::FacadeState;
pub const TRANSACTION_TTL_SECS: u64 = 3600;
#[must_use]
pub fn ttl_from(block_ts: Timestamp) -> Timestamp {
block_ts + MidnightDuration::from_secs(i128::from(TRANSACTION_TTL_SECS))
}
#[must_use]
pub fn default_submission_stage(network: &super::network::NetworkConfig) -> SubmissionStage {
if network.is_fund_class() {
SubmissionStage::Finalized
} else {
SubmissionStage::InBlock
}
}
pub fn build_engine_provider() -> Result<EngineProvingProvider> {
let engine = ProverEngine::from_env().context("init ProverEngine (MIDNIGHT_PP)")?;
Ok(EngineProvingProvider::new(Arc::new(engine)))
}
pub async fn finalize_with_backend(
recipe: UnprovenTransactionRecipe,
backend: &ProvingBackend,
) -> Result<crate::FinalizedTransactionRecipe> {
match backend {
ProvingBackend::InProcess => {
#[cfg(target_arch = "wasm32")]
{
let _ = recipe;
Err(anyhow!(
"in-process proving is not supported on wasm32; configure an HTTP proofServerUrl"
))
}
#[cfg(not(target_arch = "wasm32"))]
{
let engine = build_engine_provider()?;
finalize_facade_recipe(&recipe, engine)
.await
.map_err(|e| anyhow!("finalize_recipe (in-process): {e}"))
}
}
ProvingBackend::HttpServer { base_url } => {
let engine = HttpProvingProvider::new(base_url.clone());
finalize_facade_recipe(&recipe, engine)
.await
.map_err(|e| anyhow!("finalize_recipe (remote {base_url}): {e}"))
}
}
}
pub struct SubmissionOutcome {
pub event: SubmissionEvent,
pub raw_tx_bytes: Vec<u8>,
}
pub async fn submit_signed_recipe(
session: &WalletSession,
recipe: UnprovenTransactionRecipe,
stage: SubmissionStage,
) -> Result<SubmissionOutcome> {
submit_signed_recipe_with_backend(session, recipe, stage, &ProvingBackend::InProcess).await
}
pub async fn submit_signed_recipe_with_backend(
session: &WalletSession,
recipe: UnprovenTransactionRecipe,
stage: SubmissionStage,
backend: &ProvingBackend,
) -> Result<SubmissionOutcome> {
let finalized = prove_signed_recipe(session, recipe, backend).await?;
let bytes = serialize_finalized(&finalized).map_err(|e| anyhow!("serialize_finalized: {e}"))?;
let bytes_for_record = bytes.clone();
let event = submit_finalized(session.node.as_ref(), bytes, SubmissionOptions { stage })
.await
.map_err(|e| translate_submission_error(&e, &session.network.name))?;
wait_until_indexed(&session.network.indexer_http, &event).await?;
Ok(SubmissionOutcome {
event,
raw_tx_bytes: bytes_for_record,
})
}
const INDEXING_TIMEOUT: StdDuration = StdDuration::from_secs(180);
pub async fn wait_until_indexed(indexer_http: &str, event: &SubmissionEvent) -> Result<()> {
use moonproof_indexer_client::{BlockOffset, HttpIndexerClient, PublicDataProvider};
let block_hash = match event {
SubmissionEvent::Submitted { .. } => return Ok(()),
SubmissionEvent::InBlock { block_hash, .. }
| SubmissionEvent::Finalized { block_hash, .. } => {
block_hash.trim_start_matches("0x").to_ascii_lowercase()
}
};
let indexer =
HttpIndexerClient::new(indexer_http).map_err(|e| anyhow!("indexer URL parse: {e}"))?;
let deadline = moonproof_utils::rt::Instant::now() + INDEXING_TIMEOUT;
loop {
match indexer
.block(Some(BlockOffset::Hash(block_hash.clone())))
.await
{
Ok(Some(_)) => return Ok(()),
Ok(None) => {}
Err(e) => tracing::debug!("indexer block lookup for {block_hash}: {e}"),
}
if moonproof_utils::rt::Instant::now() >= deadline {
return Err(anyhow!(
"transaction {} landed in block {block_hash}, but the indexer at {indexer_http} \
had not indexed that block after {}s",
event.tx_hash(),
INDEXING_TIMEOUT.as_secs()
));
}
moonproof_utils::rt::sleep(StdDuration::from_millis(500)).await;
}
}
pub async fn prove_signed_recipe(
session: &WalletSession,
recipe: UnprovenTransactionRecipe,
backend: &ProvingBackend,
) -> Result<crate::FinalizedTransactionRecipe> {
let signed_recipe = {
let mut rng = rand::rngs::OsRng;
sign_recipe(recipe, &session.wallet.signing_key, &mut rng)
.map_err(|e| anyhow!("sign_recipe: {e}"))?
};
finalize_with_backend(signed_recipe, backend).await
}
pub fn translate_submission_error(err: &WalletError, network: &str) -> anyhow::Error {
let rendered = err.to_string();
match extract_custom_error_code(&rendered).and_then(describe_node_error_code) {
Some(name) => anyhow!("submission to {network} failed: {rendered} [{name}]"),
None => anyhow!("submission to {network} failed: {rendered}"),
}
}
pub(crate) fn extract_custom_error_code(s: &str) -> Option<u16> {
let idx = s.find("custom error:")?;
s[idx + "custom error:".len()..]
.trim_start()
.split(|c: char| !c.is_ascii_digit())
.next()?
.parse()
.ok()
}
const RETIRED_ERROR_CODE: &str =
"retired error code — node and wallet ledger versions likely disagree, \
or wallet state is stale for this chain";
const NODE_ERROR_CODES: &[(u16, &str)] = &[
(100, "EffectsMismatch"),
(101, "ContractAlreadyDeployed"),
(102, "ContractNotPresent"),
(103, "Zswap::Unknown"),
(104, "Transcript"),
(105, "InsufficientClaimable"),
(106, "VerifierKeyNotFound"),
(107, "VerifierKeyAlreadyPresent"),
(108, "ReplayCounterMismatch"),
(109, "UnknownError"),
(110, "VerifierKeyNotSet"),
(111, "TransactionTooLarge"),
(112, "VerifierKeyTooLarge"),
(113, "VerifierKeyNotPresent"),
(114, "ContractNotPresent"),
(115, "InvalidProof"),
(116, "BindingCommitmentOpeningInvalid"),
(117, "NotNormalized"),
(118, "FallibleWithoutCheckpoint"),
(119, "ClaimReceiveFailed"),
(120, "ClaimSpendFailed"),
(121, "ClaimNullifierFailed"),
(122, "ClaimCallFailed"),
(123, "InvalidSchnorrProof"),
(124, "UnclaimedCoinCom"),
(125, "UnclaimedNullifier"),
(126, "Unbalanced — transaction inputs/outputs don't balance"),
(127, "Zswap::Unknown"),
(128, "BuiltinDecode"),
(129, "GuaranteedLimit"),
(130, "MergingContracts"),
(131, "CantMergeTypes"),
(132, "ClaimOverflow"),
(133, "ClaimCoinMismatch"),
(134, "KeyNotInCommittee"),
(135, "InvalidCommitteeSignature"),
(136, "ThresholdMissed"),
(137, "TooManyZswapEntries"),
(138, "BalanceCheckOverspend — spending more than available"),
(139, "UnknownError"),
(140, "SystemTransaction::NotAllowedForCaller"),
(141, "ContractDustTransfer"),
(142, "RepeatedCommitteeSignature"),
(143, "RepeatedDustRegistration"),
(144, "FeeCalculation::RepeatedEntries"),
(145, "FeeCalculation::Unknown"),
(146, "MalformedContractDeploy::TooManyOperations"),
(150, "LedgerApi::LedgerCacheError"),
(151, "LedgerApi::NoLedgerState"),
(152, "LedgerApi::LedgerStateScaleDecodingError"),
(153, "LedgerApi::ContractCallCostError"),
(154, "LedgerApi::BlockLimitExceededError"),
(155, "LedgerApi::FeeCalculationError"),
(156, "LedgerApi::ContractNotPresent"),
(157, "LedgerApi::BeneficiaryNotFound"),
(165, "LedgerApi::GetTransactionContextError"),
(166, "InvalidNetworkId"),
(167, "IllegallyDeclaredGuaranteed"),
(168, RETIRED_ERROR_CODE),
(169, "InvalidDustRegistrationSignature"),
(170, "InvalidDustSpendProof"),
(171, "OutOfDustValidityWindow"),
(172, "MultipleDustRegistrationsForKey"),
(173, "InsufficientDustForRegistrationFee"),
(174, "MalformedContractDeploy::Unknown"),
(175, "IntentSignatureVerificationFailure"),
(176, "IntentSignatureKeyMismatch"),
(177, "IntentSegmentIdCollision"),
(178, "IntentAtGuaranteedSegmentId"),
(179, "UnsupportedProofVersion"),
(180, "GuaranteedTranscriptVersion"),
(181, "FallibleTranscriptVersion"),
(182, RETIRED_ERROR_CODE),
(183, "BalanceCheckOutOfBounds"),
(184, "BalanceCheckConversionFailure"),
(185, "PedersenCheckFailure"),
(186, RETIRED_ERROR_CODE),
(187, RETIRED_ERROR_CODE),
(188, RETIRED_ERROR_CODE),
(189, "InputsNotSorted"),
(190, "OutputsNotSorted"),
(191, "DuplicateInputs"),
(192, "InputsSignaturesLengthMismatch"),
(193, RETIRED_ERROR_CODE),
(194, "BalanceCheckOutOfBounds"),
(
195,
"InputNotInUtxos — spending a UTXO the chain doesn't have (stale wallet state?)",
),
(196, "DustDoubleSpend"),
(197, "DustDeregistrationNotRegistered"),
(198, "GenerationInfoAlreadyPresent"),
(199, "InvariantViolation"),
(200, "RewardTooSmall"),
(201, "SystemTransaction::IllegalPayout"),
(202, "SystemTransaction::InsufficientTreasuryFunds"),
(203, "SystemTransaction::CommitmentAlreadyPresent"),
(204, "SystemTransaction::UnknownError"),
(205, RETIRED_ERROR_CODE),
(206, "SystemTransaction::IllegalReserveDistribution"),
(207, "SystemTransaction::GenerationInfoAlreadyPresent"),
(208, "SystemTransaction::InvalidBasisPoints"),
(209, "SystemTransaction::InvariantViolation"),
(210, "SystemTransaction::TreasuryDisabled"),
(211, "SystemTransaction::MerkleTreeError"),
(212, "EffectsCheck::RealCallsSubsetCheckFailure"),
(213, "EffectsCheck::AllCommitmentsSubsetCheckFailure"),
(214, "EffectsCheck::RealUnshieldedSpendsSubsetCheckFailure"),
(
215,
"EffectsCheck::ClaimedUnshieldedSpendsUniquenessFailure",
),
(216, "EffectsCheck::ClaimedCallsUniquenessFailure"),
(217, "EffectsCheck::NullifiersNeqClaimedNullifiers"),
(218, "EffectsCheck::CommitmentsNeqClaimedShieldedReceives"),
(219, "SequencingCheck::CallSequencingViolation"),
(220, "SequencingCheck::SequencingCorrelationViolation"),
(221, "SequencingCheck::GuaranteedInFallibleContextViolation"),
(222, "SequencingCheck::FallibleInGuaranteedContextViolation"),
(223, "SequencingCheck::CausalityConstraintViolation"),
(224, "SequencingCheck::CallHasEmptyTranscripts"),
(225, "DisjointCheck::ShieldedInputsDisjointFailure"),
(226, "DisjointCheck::ShieldedOutputsDisjointFailure"),
(227, "DisjointCheck::UnshieldedInputsDisjointFailure"),
(228, "IntentTtlExpired"),
(229, "IntentTtlTooFarInFuture"),
(230, "IntentAlreadyExists"),
(231, "FeeCalculation::OutsideTimeToDismiss"),
(232, "FeeCalculation::BlockLimitExceeded"),
(233, "MalformedContractDeploy::NonZeroBalance"),
(234, "MalformedContractDeploy::IncorrectChargedState"),
(235, "MalformedZswap::InvalidProof"),
(236, "MalformedZswap::ContractSentCiphertext"),
(237, "MalformedZswap::NonDisjointCoinMerge"),
(238, "MalformedZswap::NotNormalized"),
(
239,
"Zswap::NullifierAlreadyPresent — double spend of a shielded coin",
),
(240, "Zswap::CommitmentAlreadyPresent"),
(
241,
"Zswap::UnknownMerkleRoot — wallet state out of sync with chain",
),
(242, "IntentTtlExpired"),
(243, "IntentTtlTooFarInFuture"),
(244, "IntentAlreadyExists"),
(245, "IntentTtlExpired"),
(246, "IntentTtlTooFarInFuture"),
(247, "IntentAlreadyExists"),
(248, "DivideByZero"),
(249, "MerkleTreeError"),
(250, "MerkleTreeError"),
(251, "BridgeClaimTooSmall"),
(
252,
"ContractTooManyOperations — a contract holds at most 256 operations",
),
(253, "TooManyPublicInputs"),
(254, "TranscriptGasExceedsBlockLimits"),
(255, "LedgerApi::HostApiError"),
];
#[must_use]
pub fn describe_node_error_code(code: u16) -> Option<&'static str> {
NODE_ERROR_CODES
.iter()
.find(|(c, _)| *c == code)
.map(|&(_, name)| name)
}
const WAIT_POLL_INTERVAL: StdDuration = StdDuration::from_secs(2);
pub async fn wait_for_native_balance(
session: &WalletSession,
min_amount: u128,
) -> Result<FacadeState> {
let native = TokenType::new("native");
let timeout = resolve_indexer_sync_timeout(&session.network);
let deadline = moonproof_utils::rt::Instant::now() + timeout;
let mut last = sync_wallet_fresh(session).await?;
loop {
let avail = last.unshielded.available_balance(&native);
if avail >= min_amount {
return Ok(last);
}
if moonproof_utils::rt::Instant::now() >= deadline {
anyhow::bail!(
"timed out after {}s waiting for {min_amount} NIGHT to land at {}",
timeout.as_secs(),
session.wallet.bech32_address
);
}
moonproof_utils::rt::sleep(WAIT_POLL_INTERVAL).await;
last = sync_wallet_resumable(session, Some(last)).await?;
}
}
pub async fn wait_for_dust_balance(
session: &WalletSession,
min_amount: u128,
) -> Result<FacadeState> {
let timeout = resolve_indexer_sync_timeout(&session.network);
let deadline = moonproof_utils::rt::Instant::now() + timeout;
let mut last = sync_wallet_fresh(session).await?;
loop {
let avail = crate::dust_wallet_balance(&last.dust, last.chain_tip_ts());
if avail >= min_amount {
return Ok(last);
}
if moonproof_utils::rt::Instant::now() >= deadline {
anyhow::bail!(
"timed out after {}s waiting for DUST to accrue at {}",
timeout.as_secs(),
session.wallet.bech32_address
);
}
moonproof_utils::rt::sleep(WAIT_POLL_INTERVAL).await;
last = sync_wallet_resumable(session, Some(last)).await?;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn extracts_the_code_from_a_node_rejection() {
assert_eq!(
extract_custom_error_code("Invalid transaction with custom error: 170"),
Some(170)
);
assert_eq!(extract_custom_error_code("rejected"), None);
}
#[test]
fn names_the_ledger_9_1_codes() {
for code in [
140, 141, 142, 143, 144, 146, 150, 157, 201, 211, 251, 252, 253, 254, 255,
] {
assert!(
describe_node_error_code(code).is_some(),
"code {code} unnamed"
);
}
assert_eq!(
describe_node_error_code(254),
Some("TranscriptGasExceedsBlockLimits")
);
assert_eq!(describe_node_error_code(999), None);
}
}