1mod address;
4mod keys;
5mod opcodes;
6mod script;
7pub(crate) mod serialize;
8mod utxo;
9
10use std::{collections::HashMap, fmt, ops::AddAssign};
11
12use zcash_script::{opcode::Evaluable as _, pattern::push_num};
13use zcash_transparent::{address::TransparentAddress, bundle::TxOut};
14
15use crate::{
16 amount::{Amount, NonNegative},
17 block,
18 parameters::Network,
19 serialization::ZcashSerialize,
20 transaction,
21 transparent::serialize::GENESIS_COINBASE_SCRIPT_SIG,
22};
23
24pub use address::Address;
25pub use script::Script;
26pub use utxo::{
27 new_ordered_outputs, new_outputs, outputs_from_utxos, utxos_from_ordered_utxos,
28 CoinbaseSpendRestriction, OrderedUtxo, Utxo,
29};
30
31#[cfg(any(test, feature = "proptest-impl"))]
32pub use utxo::{
33 new_ordered_outputs_with_height, new_outputs_with_height, new_transaction_ordered_outputs,
34};
35
36#[cfg(any(test, feature = "proptest-impl"))]
37mod arbitrary;
38
39#[cfg(test)]
40mod tests;
41
42#[cfg(any(test, feature = "proptest-impl"))]
43use proptest_derive::Arbitrary;
44
45pub const MIN_TRANSPARENT_COINBASE_MATURITY: u32 = 100;
55
56pub const ONE_THIRD_DUST_THRESHOLD_RATE: u32 = 100;
60
61#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
65#[cfg_attr(any(test, feature = "proptest-impl"), derive(Arbitrary))]
66#[cfg_attr(any(test, feature = "proptest-impl"), derive(Serialize))]
67pub struct OutPoint {
68 #[cfg_attr(any(test, feature = "proptest-impl"), serde(with = "hex"))]
75 pub hash: transaction::Hash,
76
77 pub index: u32,
81}
82
83impl OutPoint {
84 pub fn from_usize(hash: transaction::Hash, index: usize) -> OutPoint {
90 OutPoint {
91 hash,
92 index: index
93 .try_into()
94 .expect("valid in-memory output indexes fit in a u32"),
95 }
96 }
97}
98
99#[derive(Clone, Debug, Eq, PartialEq)]
101#[cfg_attr(any(test, feature = "proptest-impl"), derive(Serialize))]
102pub enum Input {
103 PrevOut {
105 outpoint: OutPoint,
107 unlock_script: Script,
109 sequence: u32,
111 },
112 Coinbase {
114 height: block::Height,
116 data: Vec<u8>,
119 sequence: u32,
121 },
122}
123
124impl fmt::Display for Input {
125 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
126 match self {
127 Input::PrevOut {
128 outpoint,
129 unlock_script,
130 ..
131 } => {
132 let mut fmter = f.debug_struct("transparent::Input::PrevOut");
133
134 fmter.field("unlock_script_len", &unlock_script.as_raw_bytes().len());
135 fmter.field("outpoint", outpoint);
136
137 fmter.finish()
138 }
139 Input::Coinbase { height, data, .. } => {
140 let mut fmter = f.debug_struct("transparent::Input::Coinbase");
141
142 fmter.field("height", height);
143 fmter.field("data_len", &data.len());
144
145 fmter.finish()
146 }
147 }
148 }
149}
150
151impl Input {
152 pub fn miner_data(&self) -> Option<&Vec<u8>> {
154 match self {
155 Input::Coinbase { data, .. } => Some(data),
156 _ => None,
157 }
158 }
159
160 pub fn coinbase_script(&self) -> Option<Vec<u8>> {
164 match self {
165 Input::PrevOut { .. } => None,
166 Input::Coinbase { height, data, .. } => {
167 if height.is_min() {
168 (data.as_slice() == GENESIS_COINBASE_SCRIPT_SIG)
169 .then_some(GENESIS_COINBASE_SCRIPT_SIG.to_vec())
170 } else {
171 let mut script = push_num(height.into()).to_bytes();
172 script.extend_from_slice(data);
173
174 Some(script)
175 }
176 }
177 }
178 }
179
180 pub fn sequence(&self) -> u32 {
182 match self {
183 Input::PrevOut { sequence, .. } | Input::Coinbase { sequence, .. } => *sequence,
184 }
185 }
186
187 #[cfg(any(test, feature = "proptest-impl"))]
191 pub fn set_sequence(&mut self, new_sequence: u32) {
192 match self {
193 Input::PrevOut { sequence, .. } | Input::Coinbase { sequence, .. } => {
194 *sequence = new_sequence
195 }
196 }
197 }
198
199 pub fn outpoint(&self) -> Option<OutPoint> {
202 if let Input::PrevOut { outpoint, .. } = self {
203 Some(*outpoint)
204 } else {
205 None
206 }
207 }
208
209 #[cfg(any(test, feature = "proptest-impl"))]
217 pub fn set_outpoint(&mut self, new_outpoint: OutPoint) {
218 if let Input::PrevOut {
219 ref mut outpoint, ..
220 } = self
221 {
222 *outpoint = new_outpoint;
223 } else {
224 unreachable!("unexpected variant: Coinbase Inputs do not have OutPoints");
225 }
226 }
227
228 pub(crate) fn value_from_outputs(
235 &self,
236 outputs: &HashMap<OutPoint, Output>,
237 ) -> Amount<NonNegative> {
238 match self {
239 Input::PrevOut { outpoint, .. } => {
240 outputs
241 .get(outpoint)
242 .unwrap_or_else(|| {
243 panic!(
244 "provided Outputs (length {:?}) don't have spent {:?}",
245 outputs.len(),
246 outpoint
247 )
248 })
249 .value
250 }
251 Input::Coinbase { .. } => Amount::zero(),
252 }
253 }
254
255 pub fn value<U: AsRef<Utxo>>(&self, utxos: &HashMap<OutPoint, U>) -> Amount<NonNegative> {
263 self.outpoint().map_or(Amount::zero(), |outpoint| {
264 utxos
265 .get(&outpoint)
266 .unwrap_or_else(|| panic!("provided Utxos don't have spent {outpoint:?}"))
267 .as_ref()
268 .output
269 .value()
270 })
271 }
272}
273
274#[derive(Clone, Debug, Eq, PartialEq, Hash)]
287#[cfg_attr(any(test, feature = "proptest-impl"), derive(Arbitrary, Deserialize))]
288#[cfg_attr(any(test, feature = "proptest-impl"), derive(Serialize))]
289pub struct Output {
290 pub value: Amount<NonNegative>,
293
294 pub lock_script: Script,
296}
297
298impl Output {
299 pub fn new(amount: Amount<NonNegative>, lock_script: Script) -> Output {
301 Output {
302 value: amount,
303 lock_script,
304 }
305 }
306
307 pub fn value(&self) -> Amount<NonNegative> {
310 self.value
311 }
312
313 pub fn address(&self, net: &Network) -> Option<Address> {
317 match TxOut::try_from(self).ok()?.recipient_address()? {
318 TransparentAddress::PublicKeyHash(pkh) => {
319 Some(Address::from_pub_key_hash(net.t_addr_kind(), pkh))
320 }
321 TransparentAddress::ScriptHash(sh) => {
322 Some(Address::from_script_hash(net.t_addr_kind(), sh))
323 }
324 }
325 }
326
327 pub fn is_dust(&self) -> bool {
329 let output_size: u32 = self
330 .zcash_serialized_size()
331 .try_into()
332 .expect("output size should fit in u32");
333
334 let threshold = 3 * (ONE_THIRD_DUST_THRESHOLD_RATE * (output_size + 148) / 1000);
336
337 self.value.zatoshis() < threshold as i64
339 }
340}
341
342#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
344pub struct OutputIndex(u32);
345
346impl OutputIndex {
347 pub const fn from_index(output_index: u32) -> OutputIndex {
351 OutputIndex(output_index)
352 }
353
354 pub const fn index(&self) -> u32 {
356 self.0
357 }
358
359 #[allow(dead_code)]
361 pub fn from_usize(output_index: usize) -> OutputIndex {
362 OutputIndex(
363 output_index
364 .try_into()
365 .expect("the maximum valid index fits in the inner type"),
366 )
367 }
368
369 #[allow(dead_code)]
371 pub fn as_usize(&self) -> usize {
372 self.0
373 .try_into()
374 .expect("the maximum valid index fits in usize")
375 }
376
377 #[allow(dead_code)]
379 pub fn from_u64(output_index: u64) -> OutputIndex {
380 OutputIndex(
381 output_index
382 .try_into()
383 .expect("the maximum u64 index fits in the inner type"),
384 )
385 }
386
387 #[allow(dead_code)]
389 pub fn as_u64(&self) -> u64 {
390 self.0.into()
391 }
392}
393
394impl AddAssign<u32> for OutputIndex {
395 fn add_assign(&mut self, rhs: u32) {
396 self.0 += rhs
397 }
398}