use std::convert::TryFrom;
use moonproof_ledger::base_crypto::time::Timestamp;
use moonproof_ledger::coin_structure::coin::{UnshieldedTokenType, UserAddress, NIGHT};
use moonproof_ledger::ledger::error::TransactionProvingError;
use moonproof_ledger::ledger::structure::{
Intent, IntentHash, ProofMarker, ProofPreimageMarker, Transaction, UnshieldedOffer, UtxoOutput,
UtxoSpend,
};
use moonproof_ledger::onchain_runtime::cost_model::INITIAL_COST_MODEL;
use moonproof_ledger::serialize::tagged_serialize;
use moonproof_ledger::signatures::{Signature, SigningKey, VerifyingKey};
use moonproof_ledger::storage::db::InMemoryDB;
use moonproof_ledger::storage::storage::HashMap as StorageHashMap;
use moonproof_ledger::transient_crypto::commitment::{PedersenRandomness, PureGeneratorPedersen};
use moonproof_ledger::transient_crypto::hash::HashOutput;
use moonproof_ledger::transient_crypto::proofs::{Proof, ProofPreimage, ProvingProvider};
use rand::rngs::OsRng;
use rand::{CryptoRng, RngCore};
use crate::error::{Result, WalletError};
use crate::types::TokenType;
use crate::unshielded::state::UtxoWithMeta;
use crate::unshielded::transacting::{TransferRecipe, UnshieldedOutputSpec};
pub type Db = InMemoryDB;
pub type UnshieldedIntent = Intent<Signature, ProofPreimageMarker, PedersenRandomness, Db>;
pub type SignedTransaction = Transaction<Signature, ProofPreimageMarker, PedersenRandomness, Db>;
pub type FinalizedTransaction = Transaction<Signature, ProofMarker, PureGeneratorPedersen, Db>;
#[derive(Debug, Clone, Copy)]
pub struct NoopProvingProvider;
impl ProvingProvider for NoopProvingProvider {
fn check(
&self,
_preimage: &ProofPreimage,
) -> impl std::future::Future<Output = std::result::Result<Vec<Option<usize>>, anyhow::Error>>
{
std::future::ready(Err(anyhow::anyhow!(
"NoopProvingProvider: cannot check proof preimage — \
this provider is only valid for unshielded-only transactions"
)))
}
fn prove(
self,
_preimage: &ProofPreimage,
_overwrite_binding_input: Option<moonproof_ledger::transient_crypto::curve::Fr>,
) -> impl std::future::Future<Output = std::result::Result<Proof, anyhow::Error>> {
std::future::ready(Err(anyhow::anyhow!(
"NoopProvingProvider: cannot produce a real proof — \
this provider is only valid for unshielded-only transactions"
)))
}
#[cfg(not(feature = "ledger8"))]
fn resolver(&self) -> &impl moonproof_prover::Resolver {
static EMPTY: std::sync::OnceLock<moonproof_prover::ContractKeyResolver> =
std::sync::OnceLock::new();
EMPTY.get_or_init(moonproof_prover::ContractKeyResolver::default)
}
fn split(&mut self) -> Self {
NoopProvingProvider
}
}
const NATIVE_ALIASES: &[&str] = &["native", "night", "NIGHT", "Night", "NATIVE"];
pub fn to_ledger_token_type(token: &TokenType) -> Result<UnshieldedTokenType> {
let s = token.as_str();
if NATIVE_ALIASES.iter().any(|a| s.eq_ignore_ascii_case(a)) {
return Ok(NIGHT);
}
let bytes = hex::decode(s).map_err(|e| {
WalletError::InvalidTokenType(format!("token type `{s}` is not valid hex: {e}"))
})?;
let arr = <[u8; 32]>::try_from(bytes.as_slice()).map_err(|_| {
WalletError::InvalidTokenType(format!(
"token type `{s}` decoded to {} bytes; expected 32",
bytes.len()
))
})?;
Ok(UnshieldedTokenType(HashOutput(arr)))
}
#[inline]
#[must_use]
pub fn to_ledger_user_address(owner: [u8; 32]) -> UserAddress {
UserAddress(HashOutput(owner))
}
#[inline]
#[must_use]
pub fn to_ledger_intent_hash(intent_hash: [u8; 32]) -> IntentHash {
IntentHash(HashOutput(intent_hash))
}
pub fn signing_key_from_bytes(bytes: &[u8]) -> Result<SigningKey> {
moonproof_ledger::signatures::schnorr_signing_key(bytes)
.map_err(|e| WalletError::SigningFailed(format!("invalid signing key bytes: {e}")))
}
fn utxo_to_spend(utxo: &UtxoWithMeta, spender_verifying_key: &VerifyingKey) -> Result<UtxoSpend> {
Ok(UtxoSpend {
value: utxo.utxo.value,
owner: spender_verifying_key.clone(),
type_: to_ledger_token_type(&utxo.utxo.token_type)?,
intent_hash: to_ledger_intent_hash(utxo.utxo.id.intent_hash),
output_no: utxo.utxo.id.output_no,
})
}
fn spec_to_output(spec: &UnshieldedOutputSpec) -> Result<UtxoOutput> {
Ok(UtxoOutput {
value: spec.value,
owner: to_ledger_user_address(spec.owner),
type_: to_ledger_token_type(&spec.token_type)?,
})
}
#[derive(Debug, Clone)]
pub struct IntentParams {
pub spender_verifying_key: VerifyingKey,
pub ttl: Timestamp,
}
pub fn build_intent<R: RngCore + CryptoRng>(
recipe: &TransferRecipe,
params: &IntentParams,
rng: &mut R,
) -> Result<Option<UnshieldedIntent>> {
if recipe.inputs.is_empty()
&& recipe.recipient_outputs.is_empty()
&& recipe.change_outputs.is_empty()
{
return Ok(None);
}
let inputs: Vec<UtxoSpend> = recipe
.inputs
.iter()
.map(|u| utxo_to_spend(u, ¶ms.spender_verifying_key))
.collect::<Result<_>>()?;
let mut outputs: Vec<UtxoOutput> = Vec::with_capacity(recipe.total_output_count());
for o in &recipe.recipient_outputs {
outputs.push(spec_to_output(o)?);
}
for o in &recipe.change_outputs {
outputs.push(spec_to_output(o)?);
}
let offer: UnshieldedOffer<Signature, Db> = UnshieldedOffer {
inputs: inputs.into(),
outputs: outputs.into(),
signatures: Vec::<Signature>::new().into(),
};
let intent: UnshieldedIntent = Intent::new(
rng,
Some(offer),
None, vec![], vec![], vec![], None, params.ttl,
);
Ok(Some(intent))
}
pub fn merge_into_offer(
existing: Option<&UnshieldedOffer<Signature, Db>>,
recipe: &TransferRecipe,
spender_verifying_key: &VerifyingKey,
) -> Result<UnshieldedOffer<Signature, Db>> {
let (mut inputs, mut outputs): (Vec<UtxoSpend>, Vec<UtxoOutput>) = match existing {
Some(offer) => {
if !offer.signatures.is_empty() {
return Err(WalletError::SigningFailed(
"cannot add inputs or outputs to an unshielded offer that is already signed"
.to_owned(),
));
}
(Vec::from(&offer.inputs), Vec::from(&offer.outputs))
}
None => (Vec::new(), Vec::new()),
};
for utxo in &recipe.inputs {
inputs.push(utxo_to_spend(utxo, spender_verifying_key)?);
}
for spec in recipe.all_outputs() {
outputs.push(spec_to_output(spec)?);
}
inputs.sort();
outputs.sort();
Ok(UnshieldedOffer {
inputs: inputs.into(),
outputs: outputs.into(),
signatures: Vec::<Signature>::new().into(),
})
}
pub fn sign_intent<R: RngCore + CryptoRng>(
intent: UnshieldedIntent,
segment_id: u16,
guaranteed_signing_keys: &[SigningKey],
rng: &mut R,
) -> Result<UnshieldedIntent> {
let input_count = intent
.guaranteed_unshielded_offer
.as_ref()
.map_or(0, |offer| offer.inputs.len());
if guaranteed_signing_keys.len() != input_count {
return Err(WalletError::SigningFailed(format!(
"guaranteed signing keys count ({}) does not match input count ({})",
guaranteed_signing_keys.len(),
input_count
)));
}
intent
.sign(rng, segment_id, guaranteed_signing_keys, &[], &[])
.map_err(|e| WalletError::SigningFailed(format!("Intent::sign: {e:?}")))
}
#[must_use]
pub fn build_transaction(
intent: UnshieldedIntent,
segment_id: u16,
network_id: impl Into<String>,
) -> SignedTransaction {
let mut intents: StorageHashMap<u16, UnshieldedIntent, Db> = StorageHashMap::new();
intents = intents.insert(segment_id, intent);
Transaction::from_intents(network_id, intents)
}
pub fn serialize_transaction(tx: &SignedTransaction) -> Result<Vec<u8>> {
let mut bytes = Vec::with_capacity(1024);
tagged_serialize(tx, &mut bytes)
.map_err(|e| WalletError::Serialization(format!("tagged_serialize: {e}")))?;
Ok(bytes)
}
pub fn finalize_unshielded_transaction(tx: &SignedTransaction) -> Result<FinalizedTransaction> {
let post_prove = futures::executor::block_on(tx.prove(NoopProvingProvider, &INITIAL_COST_MODEL))
.map_err(|e: TransactionProvingError<Db>| {
WalletError::Serialization(format!(
"finalize_unshielded_transaction: prove step failed — transaction likely \
contains contract actions or Zswap offers that require a real proving provider: {e:?}"
))
})?;
Ok(post_prove.seal(OsRng))
}
pub fn serialize_finalized_transaction(tx: &FinalizedTransaction) -> Result<Vec<u8>> {
let mut bytes = Vec::with_capacity(1024);
tagged_serialize(tx, &mut bytes)
.map_err(|e| WalletError::Serialization(format!("tagged_serialize(finalized): {e}")))?;
Ok(bytes)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn native_aliases_resolve_to_night() {
for alias in NATIVE_ALIASES {
let t = TokenType::new(*alias);
let resolved = to_ledger_token_type(&t).expect("alias should resolve");
assert_eq!(
format!("{resolved:?}"),
format!("{NIGHT:?}"),
"alias `{alias}` did not resolve to NIGHT (got {resolved:?})"
);
}
}
#[test]
fn hex_token_type_is_parsed_into_unshielded() {
let bytes = [0xABu8; 32];
let token = TokenType::new(hex::encode(bytes));
let resolved = to_ledger_token_type(&token).expect("32-byte hex parses");
assert_eq!(resolved.0 .0, bytes);
}
#[test]
fn invalid_hex_token_type_errors() {
let token = TokenType::new("not-hex!!");
assert!(matches!(
to_ledger_token_type(&token),
Err(WalletError::InvalidTokenType(_))
));
}
#[test]
fn wrong_length_hex_token_type_errors() {
let token = TokenType::new(hex::encode([0xAA; 16])); assert!(matches!(
to_ledger_token_type(&token),
Err(WalletError::InvalidTokenType(_))
));
}
#[test]
fn user_address_round_trips_bytes() {
let bytes = [0x55u8; 32];
let addr = to_ledger_user_address(bytes);
assert_eq!(addr.0 .0, bytes);
}
#[test]
fn intent_hash_round_trips_bytes() {
let bytes = [0x77u8; 32];
let h = to_ledger_intent_hash(bytes);
assert_eq!(h.0 .0, bytes);
}
}