1use crate::amount::{self, Amount, Constraint, NegativeAllowed, NonNegative};
4
5use core::fmt;
6
7#[cfg(any(test, feature = "proptest-impl"))]
8use std::{borrow::Borrow, collections::HashMap};
9
10#[cfg(any(test, feature = "proptest-impl"))]
11use crate::{amount::MAX_MONEY, transaction::Transaction, transparent};
12
13#[cfg(any(test, feature = "proptest-impl"))]
14mod arbitrary;
15
16#[cfg(test)]
17mod tests;
18
19use ValueBalanceError::*;
20
21pub const SERIALIZED_SIZE: usize = 56;
25
26#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
28pub struct ValueBalance<C> {
29 transparent: Amount<C>,
30 sprout: Amount<C>,
31 sapling: Amount<C>,
32 orchard: Amount<C>,
33 deferred: Amount<C>,
34 ironwood: Amount<C>,
35 nsm: Amount<C>,
40}
41
42impl<C> ValueBalance<C>
43where
44 C: Constraint + Copy,
45{
46 pub fn from_transparent_amount(transparent_amount: Amount<C>) -> Self {
48 ValueBalance {
49 transparent: transparent_amount,
50 ..ValueBalance::zero()
51 }
52 }
53
54 pub fn from_sprout_amount(sprout_amount: Amount<C>) -> Self {
56 ValueBalance {
57 sprout: sprout_amount,
58 ..ValueBalance::zero()
59 }
60 }
61
62 pub fn from_sapling_amount(sapling_amount: Amount<C>) -> Self {
64 ValueBalance {
65 sapling: sapling_amount,
66 ..ValueBalance::zero()
67 }
68 }
69
70 pub fn from_orchard_amount(orchard_amount: Amount<C>) -> Self {
72 ValueBalance {
73 orchard: orchard_amount,
74 ..ValueBalance::zero()
75 }
76 }
77
78 pub fn from_ironwood_amount(ironwood_amount: Amount<C>) -> Self {
80 ValueBalance {
81 ironwood: ironwood_amount,
82 ..ValueBalance::zero()
83 }
84 }
85
86 pub fn transparent_amount(&self) -> Amount<C> {
88 self.transparent
89 }
90
91 pub fn set_transparent_value_balance(
94 &mut self,
95 transparent_value_balance: ValueBalance<C>,
96 ) -> &Self {
97 self.transparent = transparent_value_balance.transparent;
98 self
99 }
100
101 pub fn sprout_amount(&self) -> Amount<C> {
103 self.sprout
104 }
105
106 pub fn set_sprout_value_balance(&mut self, sprout_value_balance: ValueBalance<C>) -> &Self {
109 self.sprout = sprout_value_balance.sprout;
110 self
111 }
112
113 pub fn sapling_amount(&self) -> Amount<C> {
115 self.sapling
116 }
117
118 pub fn set_sapling_value_balance(&mut self, sapling_value_balance: ValueBalance<C>) -> &Self {
121 self.sapling = sapling_value_balance.sapling;
122 self
123 }
124
125 pub fn orchard_amount(&self) -> Amount<C> {
127 self.orchard
128 }
129
130 pub fn set_orchard_value_balance(&mut self, orchard_value_balance: ValueBalance<C>) -> &Self {
133 self.orchard = orchard_value_balance.orchard;
134 self
135 }
136
137 pub fn deferred_amount(&self) -> Amount<C> {
139 self.deferred
140 }
141
142 pub fn set_deferred_amount(&mut self, deferred_amount: Amount<C>) -> &Self {
144 self.deferred = deferred_amount;
145 self
146 }
147
148 pub fn ironwood_amount(&self) -> Amount<C> {
150 self.ironwood
151 }
152
153 pub fn set_ironwood_value_balance(&mut self, ironwood_value_balance: ValueBalance<C>) -> &Self {
156 self.ironwood = ironwood_value_balance.ironwood;
157 self
158 }
159
160 pub fn nsm_amount(&self) -> Amount<C> {
162 self.nsm
163 }
164
165 pub fn set_nsm_amount(&mut self, nsm_amount: Amount<C>) -> &Self {
167 self.nsm = nsm_amount;
168 self
169 }
170
171 pub fn zero() -> Self {
173 let zero = Amount::zero();
174 Self {
175 transparent: zero,
176 sprout: zero,
177 sapling: zero,
178 orchard: zero,
179 deferred: zero,
180 ironwood: zero,
181 nsm: zero,
182 }
183 }
184
185 pub fn total(self) -> Result<Amount<C>, amount::Error> {
190 let total: i128 = [
191 self.transparent,
192 self.sprout,
193 self.sapling,
194 self.orchard,
195 self.deferred,
196 self.ironwood,
197 ]
198 .into_iter()
199 .map(|amount| i128::from(amount.zatoshis()))
200 .sum();
201
202 Amount::try_from(total)
203 }
204
205 pub fn constrain<C2>(self) -> Result<ValueBalance<C2>, ValueBalanceError>
208 where
209 C2: Constraint,
210 {
211 Ok(ValueBalance::<C2> {
212 transparent: self.transparent.constrain().map_err(Transparent)?,
213 sprout: self.sprout.constrain().map_err(Sprout)?,
214 sapling: self.sapling.constrain().map_err(Sapling)?,
215 orchard: self.orchard.constrain().map_err(Orchard)?,
216 deferred: self.deferred.constrain().map_err(Deferred)?,
217 ironwood: self.ironwood.constrain().map_err(Ironwood)?,
218 nsm: self.nsm.constrain().map_err(Nsm)?,
219 })
220 }
221}
222
223impl ValueBalance<NegativeAllowed> {
224 pub fn remaining_transaction_value(&self) -> Result<Amount<NonNegative>, amount::Error> {
237 (self.transparent + self.sprout + self.sapling + self.orchard + self.ironwood)?
246 .constrain::<NonNegative>()
247 }
248}
249
250impl ValueBalance<NonNegative> {
251 #[cfg(any(test, feature = "proptest-impl"))]
273 pub fn add_transaction(
274 self,
275 transaction: impl Borrow<Transaction>,
276 utxos: &HashMap<transparent::OutPoint, transparent::Output>,
277 ) -> Result<ValueBalance<NonNegative>, ValueBalanceError> {
278 use std::ops::Neg;
279
280 let tx = transaction.borrow();
283 let transparent = tx.transparent_value_balance_from_outputs(utxos)?;
284 let sprout = tx.sprout_value_balance()?;
285 let sapling = tx.sapling_value_balance();
286 let orchard = tx.orchard_value_balance();
287 let ironwood = tx.ironwood_value_balance();
288 let chain_value_pool_change = (transparent + sprout + sapling + orchard + ironwood)?.neg();
289
290 self.add_chain_value_pool_change(chain_value_pool_change)
291 }
292
293 #[cfg(any(test, feature = "proptest-impl"))]
301 pub fn add_transparent_input(
302 self,
303 input: impl Borrow<transparent::Input>,
304 utxos: &HashMap<transparent::OutPoint, transparent::Output>,
305 ) -> Result<ValueBalance<NonNegative>, ValueBalanceError> {
306 use std::ops::Neg;
307
308 let transparent_value_pool_change = input.borrow().value_from_outputs(utxos).neg();
311 let transparent_value_pool_change =
312 ValueBalance::from_transparent_amount(transparent_value_pool_change);
313
314 self.add_chain_value_pool_change(transparent_value_pool_change)
315 }
316
317 #[allow(clippy::unwrap_in_result)]
358 pub fn add_chain_value_pool_change(
359 self,
360 chain_value_pool_change: ValueBalance<NegativeAllowed>,
361 ) -> Result<ValueBalance<NonNegative>, ValueBalanceError> {
362 let mut chain_value_pool = self
363 .constrain::<NegativeAllowed>()
364 .expect("conversion from NonNegative to NegativeAllowed is always valid");
365 chain_value_pool = (chain_value_pool + chain_value_pool_change)?;
366
367 let chain_value_pool = chain_value_pool.constrain::<NonNegative>()?;
378
379 chain_value_pool.total().map_err(ValueBalanceError::Total)?;
382
383 Ok(chain_value_pool)
384 }
385
386 #[cfg(any(test, feature = "proptest-impl"))]
393 pub fn fake_populated_pool() -> ValueBalance<NonNegative> {
394 let mut fake_value_pool = ValueBalance::zero();
395
396 let fake_transparent_value_balance =
397 ValueBalance::from_transparent_amount(Amount::try_from(MAX_MONEY / 8).unwrap());
398 let fake_sprout_value_balance =
399 ValueBalance::from_sprout_amount(Amount::try_from(MAX_MONEY / 8).unwrap());
400 let fake_sapling_value_balance =
401 ValueBalance::from_sapling_amount(Amount::try_from(MAX_MONEY / 8).unwrap());
402 let fake_orchard_value_balance =
403 ValueBalance::from_orchard_amount(Amount::try_from(MAX_MONEY / 8).unwrap());
404 let fake_ironwood_value_balance =
405 ValueBalance::from_ironwood_amount(Amount::try_from(MAX_MONEY / 8).unwrap());
406
407 fake_value_pool.set_transparent_value_balance(fake_transparent_value_balance);
408 fake_value_pool.set_sprout_value_balance(fake_sprout_value_balance);
409 fake_value_pool.set_sapling_value_balance(fake_sapling_value_balance);
410 fake_value_pool.set_orchard_value_balance(fake_orchard_value_balance);
411 fake_value_pool.set_ironwood_value_balance(fake_ironwood_value_balance);
412
413 fake_value_pool
414 }
415
416 pub fn to_bytes(self) -> [u8; SERIALIZED_SIZE] {
422 let mut bytes = [0; SERIALIZED_SIZE];
423 for (destination, amount) in bytes.as_chunks_mut::<8>().0.iter_mut().zip([
424 self.transparent,
425 self.sprout,
426 self.sapling,
427 self.orchard,
428 self.deferred,
429 self.ironwood,
430 self.nsm,
431 ]) {
432 *destination = amount.to_bytes();
433 }
434 bytes
435 }
436
437 #[allow(clippy::unwrap_in_result)]
442 pub fn from_bytes(bytes: &[u8]) -> Result<ValueBalance<NonNegative>, ValueBalanceError> {
443 let bytes_length = bytes.len();
444
445 if !(32..=SERIALIZED_SIZE).contains(&bytes_length) || !bytes_length.is_multiple_of(8) {
448 return Err(Unparsable);
449 }
450
451 let transparent = Amount::from_bytes(
452 bytes[0..8]
453 .try_into()
454 .expect("transparent amount should be parsable"),
455 )
456 .map_err(Transparent)?;
457
458 let sprout = Amount::from_bytes(
459 bytes[8..16]
460 .try_into()
461 .expect("sprout amount should be parsable"),
462 )
463 .map_err(Sprout)?;
464
465 let sapling = Amount::from_bytes(
466 bytes[16..24]
467 .try_into()
468 .expect("sapling amount should be parsable"),
469 )
470 .map_err(Sapling)?;
471
472 let orchard = Amount::from_bytes(
473 bytes[24..32]
474 .try_into()
475 .expect("orchard amount should be parsable"),
476 )
477 .map_err(Orchard)?;
478
479 let deferred = match bytes_length {
480 32 => Amount::zero(),
481 _ => Amount::from_bytes(
482 bytes[32..40]
483 .try_into()
484 .expect("deferred amount should be parsable"),
485 )
486 .map_err(Deferred)?,
487 };
488
489 let ironwood = match bytes_length {
490 32 | 40 => Amount::zero(),
491 _ => Amount::from_bytes(
492 bytes[40..48]
493 .try_into()
494 .expect("ironwood amount should be parsable"),
495 )
496 .map_err(Ironwood)?,
497 };
498
499 let nsm = match bytes_length {
500 56 => Amount::from_bytes(
501 bytes[48..56]
502 .try_into()
503 .expect("NSM amount should be parsable"),
504 )
505 .map_err(Nsm)?,
506 _ => Amount::zero(),
507 };
508
509 Ok(ValueBalance {
510 transparent,
511 sprout,
512 sapling,
513 orchard,
514 deferred,
515 ironwood,
516 nsm,
517 })
518 }
519}
520
521#[derive(thiserror::Error, Debug, Clone, PartialEq, Eq)]
522pub enum ValueBalanceError {
524 Transparent(amount::Error),
526
527 Sprout(amount::Error),
529
530 Sapling(amount::Error),
532
533 Orchard(amount::Error),
535
536 Deferred(amount::Error),
538
539 Ironwood(amount::Error),
541
542 Nsm(amount::Error),
544
545 Total(amount::Error),
547
548 Unparsable,
550}
551
552impl fmt::Display for ValueBalanceError {
553 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
554 f.write_str(&match self {
555 Transparent(e) => format!("transparent amount err: {e}"),
556 Sprout(e) => format!("sprout amount err: {e}"),
557 Sapling(e) => format!("sapling amount err: {e}"),
558 Orchard(e) => format!("orchard amount err: {e}"),
559 Deferred(e) => format!("deferred amount err: {e}"),
560 Ironwood(e) => format!("ironwood amount err: {e}"),
561 Nsm(e) => format!("NSM amount err: {e}"),
562 Total(e) => format!("total amount err: {e}"),
563 Unparsable => "value balance is unparsable".to_string(),
564 })
565 }
566}
567
568impl<C> std::ops::Add for ValueBalance<C>
569where
570 C: Constraint,
571{
572 type Output = Result<ValueBalance<C>, ValueBalanceError>;
573 fn add(self, rhs: ValueBalance<C>) -> Self::Output {
574 Ok(ValueBalance::<C> {
575 transparent: (self.transparent + rhs.transparent).map_err(Transparent)?,
576 sprout: (self.sprout + rhs.sprout).map_err(Sprout)?,
577 sapling: (self.sapling + rhs.sapling).map_err(Sapling)?,
578 orchard: (self.orchard + rhs.orchard).map_err(Orchard)?,
579 deferred: (self.deferred + rhs.deferred).map_err(Deferred)?,
580 ironwood: (self.ironwood + rhs.ironwood).map_err(Ironwood)?,
581 nsm: (self.nsm + rhs.nsm).map_err(Nsm)?,
582 })
583 }
584}
585
586impl<C> std::ops::Add<ValueBalance<C>> for Result<ValueBalance<C>, ValueBalanceError>
587where
588 C: Constraint,
589{
590 type Output = Result<ValueBalance<C>, ValueBalanceError>;
591 fn add(self, rhs: ValueBalance<C>) -> Self::Output {
592 self? + rhs
593 }
594}
595
596impl<C> std::ops::Add<Result<ValueBalance<C>, ValueBalanceError>> for ValueBalance<C>
597where
598 C: Constraint,
599{
600 type Output = Result<ValueBalance<C>, ValueBalanceError>;
601
602 fn add(self, rhs: Result<ValueBalance<C>, ValueBalanceError>) -> Self::Output {
603 self + rhs?
604 }
605}
606
607impl<C> std::ops::AddAssign<ValueBalance<C>> for Result<ValueBalance<C>, ValueBalanceError>
608where
609 ValueBalance<C>: Copy,
610 C: Constraint,
611{
612 fn add_assign(&mut self, rhs: ValueBalance<C>) {
613 if let Ok(lhs) = *self {
614 *self = lhs + rhs;
615 }
616 }
617}
618
619impl<C> std::ops::Sub for ValueBalance<C>
620where
621 C: Constraint,
622{
623 type Output = Result<ValueBalance<C>, ValueBalanceError>;
624 fn sub(self, rhs: ValueBalance<C>) -> Self::Output {
625 Ok(ValueBalance::<C> {
626 transparent: (self.transparent - rhs.transparent).map_err(Transparent)?,
627 sprout: (self.sprout - rhs.sprout).map_err(Sprout)?,
628 sapling: (self.sapling - rhs.sapling).map_err(Sapling)?,
629 orchard: (self.orchard - rhs.orchard).map_err(Orchard)?,
630 deferred: (self.deferred - rhs.deferred).map_err(Deferred)?,
631 ironwood: (self.ironwood - rhs.ironwood).map_err(Ironwood)?,
632 nsm: (self.nsm - rhs.nsm).map_err(Nsm)?,
633 })
634 }
635}
636impl<C> std::ops::Sub<ValueBalance<C>> for Result<ValueBalance<C>, ValueBalanceError>
637where
638 C: Constraint,
639{
640 type Output = Result<ValueBalance<C>, ValueBalanceError>;
641 fn sub(self, rhs: ValueBalance<C>) -> Self::Output {
642 self? - rhs
643 }
644}
645
646impl<C> std::ops::Sub<Result<ValueBalance<C>, ValueBalanceError>> for ValueBalance<C>
647where
648 C: Constraint,
649{
650 type Output = Result<ValueBalance<C>, ValueBalanceError>;
651
652 fn sub(self, rhs: Result<ValueBalance<C>, ValueBalanceError>) -> Self::Output {
653 self - rhs?
654 }
655}
656
657impl<C> std::ops::SubAssign<ValueBalance<C>> for Result<ValueBalance<C>, ValueBalanceError>
658where
659 ValueBalance<C>: Copy,
660 C: Constraint,
661{
662 fn sub_assign(&mut self, rhs: ValueBalance<C>) {
663 if let Ok(lhs) = *self {
664 *self = lhs - rhs;
665 }
666 }
667}
668
669impl<C> std::iter::Sum<ValueBalance<C>> for Result<ValueBalance<C>, ValueBalanceError>
670where
671 C: Constraint + Copy,
672{
673 fn sum<I: Iterator<Item = ValueBalance<C>>>(mut iter: I) -> Self {
674 iter.try_fold(ValueBalance::zero(), |acc, value_balance| {
675 acc + value_balance
676 })
677 }
678}
679
680impl<'amt, C> std::iter::Sum<&'amt ValueBalance<C>> for Result<ValueBalance<C>, ValueBalanceError>
681where
682 C: Constraint + std::marker::Copy + 'amt,
683{
684 fn sum<I: Iterator<Item = &'amt ValueBalance<C>>>(iter: I) -> Self {
685 iter.copied().sum()
686 }
687}
688
689impl<C> std::ops::Neg for ValueBalance<C>
690where
691 C: Constraint,
692{
693 type Output = ValueBalance<NegativeAllowed>;
694
695 fn neg(self) -> Self::Output {
696 ValueBalance::<NegativeAllowed> {
697 transparent: self.transparent.neg(),
698 sprout: self.sprout.neg(),
699 sapling: self.sapling.neg(),
700 orchard: self.orchard.neg(),
701 deferred: self.deferred.neg(),
702 ironwood: self.ironwood.neg(),
703 nsm: self.nsm.neg(),
704 }
705 }
706}