1use std::io::{self, Write};
5
6use crypto_api_chachapoly::ChachaPolyIetf;
7use group::GroupEncoding;
8use rand::{CryptoRng, RngCore};
9use sha2::{Digest, Sha256};
10use zcash_primitives::{
11 consensus,
12 keys::OutgoingViewingKey,
13 legacy::{Script, TransparentAddress},
14 memo::MemoBytes as Memo,
15 merkle_tree::MerklePath,
16 note_encryption::SaplingNoteEncryption,
17 primitives::{Diversifier, Note, PaymentAddress, ProofGenerationKey, Rseed},
18 sapling::Node,
19 transaction::{
20 components::{Amount, OutPoint, TxIn, TxOut, GROTH_PROOF_SIZE},
21 signature_hash_data, SignableInput, TransactionData, SIGHASH_ALL,
22 },
23};
24
25use crate::{data::HashSeed, errors::Error, txprover::HsmTxProver};
26
27const OUT_PLAINTEXT_SIZE: usize = 32 + 32; const OUT_CIPHERTEXT_SIZE: usize = OUT_PLAINTEXT_SIZE + 16;
30
31#[derive(Clone)]
32pub struct SpendDescriptionInfo {
33 pub diversifier: Diversifier,
35 pub note: Note,
36 pub alpha: jubjub::Fr,
37 pub merkle_path: MerklePath<Node>,
39 pub proofkey: ProofGenerationKey,
40 pub rcv: jubjub::Fr,
42}
43
44#[derive(Clone)]
45pub struct SaplingOutput {
46 pub ovk: Option<OutgoingViewingKey>,
48 pub to: PaymentAddress,
50 pub note: Note,
51 pub memo: Memo,
52 pub rcv: jubjub::Fr, pub hashseed: Option<HashSeed>,
54}
55
56impl SaplingOutput {
57 pub fn new<R: RngCore + CryptoRng, P: consensus::Parameters>(
58 ovk: Option<OutgoingViewingKey>,
59 to: PaymentAddress,
60 value: Amount,
61 memo: Option<Memo>,
62 rcv: jubjub::Fr,
63 rseed: Rseed,
64 hashseed: Option<HashSeed>,
65 ) -> Result<Self, Error> {
66 let g_d = match to.g_d() {
67 Some(g_d) => g_d,
68 None => return Err(Error::InvalidAddress),
69 };
70 if value.is_negative() {
71 return Err(Error::InvalidAmount);
72 }
73
74 let note = Note {
77 g_d,
78 pk_d: *to.pk_d(),
79 value: value.into(),
80 rseed,
81 };
82
83 Ok(SaplingOutput {
84 ovk,
85 to,
86 note,
87 memo: memo.unwrap_or_else(Memo::empty),
88 rcv,
89 hashseed,
90 })
91 }
92
93 pub fn build<P: HsmTxProver, R: RngCore + CryptoRng>(
94 self,
95 prover: &P,
96 ctx: &mut P::SaplingProvingContext,
97 rng: &mut R,
98 ) -> zcash_primitives::transaction::components::OutputDescription {
99 let mut encryptor = SaplingNoteEncryption::new(
100 self.ovk,
101 self.note.clone(),
102 self.to.clone(),
103 self.memo,
104 rng,
105 );
106
107 let (zkproof, cv) = prover.output_proof(
108 ctx,
109 *encryptor.esk(),
110 self.to,
111 self.note.rcm(),
112 self.note.value,
113 self.rcv,
114 );
115
116 let cmu = self.note.cmu();
117
118 let enc_ciphertext = encryptor.encrypt_note_plaintext();
119 let mut out_ciphertext;
120 if self.ovk.is_some() {
121 out_ciphertext = encryptor.encrypt_outgoing_plaintext(&cv, &cmu);
122 } else {
123 let seed = self.hashseed.unwrap().0;
124 let mut randbytes = [0u8; 32 + OUT_PLAINTEXT_SIZE];
125 for i in 0..3 {
126 let mut sha256 = Sha256::new();
127 sha256.update([i as u8]);
128 sha256.update(seed);
129 let h = sha256.finalize();
130 randbytes[i * 32..(i + 1) * 32].copy_from_slice(&h);
131 }
132 let mut ock = [0u8; 32];
133 ock.copy_from_slice(&randbytes[0..32]);
134 let mut input = [0u8; OUT_PLAINTEXT_SIZE];
135 input.copy_from_slice(&randbytes[32..]);
136 out_ciphertext = [0u8; OUT_CIPHERTEXT_SIZE];
137 assert_eq!(
138 ChachaPolyIetf::aead_cipher()
139 .seal_to(&mut out_ciphertext, &input, &[], ock.as_ref(), &[0u8; 12])
140 .unwrap(),
141 OUT_CIPHERTEXT_SIZE
142 );
143 }
144
145 let ephemeral_key = (*encryptor.epk()).into();
146
147 zcash_primitives::transaction::components::OutputDescription {
148 cv,
149 cmu,
150 ephemeral_key,
151 enc_ciphertext,
152 out_ciphertext,
153 zkproof,
154 }
155 }
156}
157
158pub struct TransparentInputInfo {
159 pub pubkey: secp256k1::PublicKey,
160 pub coin: TxOut,
161}
162
163pub struct TransparentInputs {
164 pub secp: secp256k1::Secp256k1<secp256k1::VerifyOnly>,
165 pub inputs: Vec<TransparentInputInfo>,
166}
167
168impl Default for TransparentInputs {
169 fn default() -> Self {
170 TransparentInputs {
171 secp: secp256k1::Secp256k1::gen_new(),
172 inputs: Default::default(),
173 }
174 }
175}
176
177impl TransparentInputs {
178 pub fn push(
179 &mut self,
180 mtx: &mut TransactionData,
181 pubkey: secp256k1::PublicKey,
182 utxo: OutPoint,
183 coin: TxOut,
184 ) -> Result<(), Error> {
185 if coin.value.is_negative() {
186 return Err(Error::InvalidAmount);
187 }
188 match coin.script_pubkey.address() {
189 Some(TransparentAddress::PublicKey(hash)) => {
190 use ripemd160::Ripemd160;
191 use sha2::{Digest, Sha256};
192 if hash[..] != Ripemd160::digest(&Sha256::digest(&pubkey.serialize()))[..] {
193 return Err(Error::InvalidAddressHash);
194 }
195 }
196 _ => return Err(Error::InvalidAddressFormat),
197 }
198
199 mtx.vin.push(TxIn::new(utxo));
200 self.inputs.push(TransparentInputInfo { pubkey, coin });
201
202 Ok(())
203 }
204
205 pub fn value_sum(&self) -> Amount {
206 {
207 self.inputs
208 .iter()
209 .map(|input| input.coin.value)
210 .sum::<Amount>()
211 }
212 }
213
214 pub fn apply_signatures(
215 &self,
216 signatures: Vec<secp256k1::Signature>,
217 mtx: &mut TransactionData,
218 consensus_branch_id: consensus::BranchId,
219 ) -> Result<(), Error> {
220 if signatures.len() != self.inputs.len() {
221 return Err(Error::TranspararentSig);
222 }
223 let mut sighash = [0u8; 32];
224
225 for (i, info) in self.inputs.iter().enumerate() {
226 sighash.copy_from_slice(&signature_hash_data(
227 mtx,
228 consensus_branch_id,
229 SIGHASH_ALL,
230 SignableInput::transparent(i, &info.coin.script_pubkey, info.coin.value),
231 ));
232
233 let msg = secp256k1::Message::from_slice(&sighash).expect("32 bytes");
234 let sig = signatures[i];
235 let pk = info.pubkey;
236 if self.secp.verify(&msg, &sig, &pk).is_err() {
237 return Err(Error::TranspararentSig);
238 }
239 let mut sig_bytes: Vec<u8> = sig.serialize_der()[..].to_vec();
241 sig_bytes.extend(&[SIGHASH_ALL as u8]);
242
243 mtx.vin[i].script_sig =
245 Script::default() << &sig_bytes[..] << &info.pubkey.serialize()[..];
246 }
247 Ok(())
248 }
249}
250
251#[derive(Debug, PartialEq, Clone, Default)]
253pub struct TransactionMetadata {
254 pub(crate) spend_indices: Vec<usize>,
255 pub(crate) output_indices: Vec<usize>,
256}
257
258impl TransactionMetadata {
259 pub fn new() -> Self {
260 Default::default()
261 }
262
263 pub fn spend_index(&self, n: usize) -> Option<usize> {
271 self.spend_indices.get(n).copied()
272 }
273
274 pub fn output_index(&self, n: usize) -> Option<usize> {
282 self.output_indices.get(n).copied()
283 }
284}
285
286#[derive(Clone)]
287pub struct NullifierInput {
288 pub rcm_old: [u8; 32],
289 pub notepos: [u8; 8],
290}
291
292impl NullifierInput {
293 pub fn write<W: Write>(&self, mut writer: W) -> io::Result<()> {
294 writer.write_all(&self.rcm_old)?;
295 writer.write_all(&self.notepos)
296 }
297}
298
299#[derive(Clone)]
300pub struct TransparentScriptData {
301 pub prevout: [u8; 36],
302 pub script_pubkey: [u8; 26],
303 pub value: [u8; 8],
304 pub sequence: [u8; 4],
305}
306
307impl TransparentScriptData {
308 pub fn write<W: Write>(&self, mut writer: W) -> io::Result<()> {
309 writer.write_all(&self.prevout)?;
310 writer.write_all(&self.script_pubkey)?;
311 writer.write_all(&self.value)?;
312 writer.write_all(&self.sequence)
313 }
314}
315
316#[derive(Clone)]
317pub struct SpendDescription {
318 pub cv: [u8; 32],
319 pub anchor: [u8; 32],
320 pub nullifier: [u8; 32],
321 pub rk: [u8; 32],
322 pub zkproof: [u8; GROTH_PROOF_SIZE],
323}
324
325impl SpendDescription {
326 pub fn from(
327 info: &zcash_primitives::transaction::components::SpendDescription,
328 ) -> SpendDescription {
329 SpendDescription {
330 cv: info.cv.to_bytes(),
331 anchor: info.anchor.to_bytes(),
332 nullifier: info.nullifier.0,
333 rk: info.rk.0.to_bytes(),
334 zkproof: info.zkproof,
335 }
336 }
337
338 pub fn write<W: Write>(&self, mut writer: W) -> io::Result<()> {
339 writer.write_all(&self.cv)?;
340 writer.write_all(&self.anchor)?;
341 writer.write_all(&self.nullifier)?;
342 writer.write_all(&self.rk)?;
343 writer.write_all(&self.zkproof)
344 }
345}
346
347#[derive(Clone)]
348pub struct OutputDescription {
349 pub cv: [u8; 32],
350 pub cmu: [u8; 32],
351 pub ephemeral_key: [u8; 32],
352 pub enc_ciphertext: [u8; 580],
353 pub out_ciphertext: [u8; 80],
354 pub zkproof: [u8; GROTH_PROOF_SIZE],
355}
356
357impl From<&zcash_primitives::transaction::components::OutputDescription> for OutputDescription {
358 fn from(from: &zcash_primitives::transaction::components::OutputDescription) -> Self {
359 Self {
360 cv: from.cv.to_bytes(),
361 cmu: from.cmu.to_bytes(),
362 ephemeral_key: from.ephemeral_key.to_bytes(),
363 enc_ciphertext: from.enc_ciphertext,
364 out_ciphertext: from.out_ciphertext,
365 zkproof: from.zkproof,
366 }
367 }
368}
369
370impl OutputDescription {
371 pub fn write<W: Write>(&self, mut writer: W) -> io::Result<()> {
372 writer.write_all(&self.cv)?;
373 writer.write_all(&self.cmu)?;
374 writer.write_all(&self.ephemeral_key)?;
375 writer.write_all(&self.enc_ciphertext)?;
376 writer.write_all(&self.out_ciphertext)?;
377 writer.write_all(&self.zkproof)
378 }
379}
380
381pub fn spend_data_hms_fromtx(
383 input: &[zcash_primitives::transaction::components::SpendDescription],
384) -> Vec<SpendDescription> {
385 let mut data = Vec::new();
386 for info in input.iter() {
387 let description = SpendDescription::from(info);
388 data.push(description);
389 }
390 data
391}
392
393pub fn output_data_hsm_fromtx(
395 input: &[zcash_primitives::transaction::components::OutputDescription],
396) -> Vec<OutputDescription> {
397 let mut data = Vec::new();
398 for info in input.iter() {
399 let description = OutputDescription::from(info);
400 data.push(description);
401 }
402 data
403}
404
405pub fn spend_old_data_fromtx(data: &[SpendDescriptionInfo]) -> Vec<NullifierInput> {
407 let mut v = Vec::new();
408 for info in data.iter() {
409 let n = NullifierInput {
410 rcm_old: info.note.rcm().to_bytes(),
411 notepos: info.merkle_path.position.to_le_bytes(),
412 };
413 v.push(n);
414 }
415 v
416}
417
418pub fn transparent_script_data_fromtx(
421 tx: &TransactionData,
422 inputs: &[TransparentInputInfo],
423) -> Result<Vec<TransparentScriptData>, Error> {
424 let mut data = Vec::new();
425 for (i, info) in inputs.iter().enumerate() {
426 let mut prevout = [0u8; 36];
427 prevout[0..32].copy_from_slice(tx.vin[i].prevout.hash().as_ref());
428 prevout[32..36].copy_from_slice(&tx.vin[i].prevout.n().to_le_bytes());
429
430 let mut script_pubkey = [0u8; 26];
431 info.coin.script_pubkey.write(&mut script_pubkey[..])?;
432
433 let mut value = [0u8; 8];
434 value.copy_from_slice(&info.coin.value.to_i64_le_bytes());
435
436 let mut sequence = [0u8; 4];
437 sequence.copy_from_slice(&tx.vin[i].sequence.to_le_bytes());
438
439 let ts = TransparentScriptData {
440 prevout,
441 script_pubkey,
442 value,
443 sequence,
444 };
445 data.push(ts);
446 }
447 Ok(data)
448}