Skip to main content

zebra_chain/
value_balance.rs

1//! Balances in chain value pools and transaction value pools.
2
3use 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
21/// The number of bytes in a serialized [`ValueBalance`]: eight bytes per chain value pool.
22///
23/// Legacy records without trailing pools stay parsable, see [`ValueBalance::from_bytes`].
24pub const SERIALIZED_SIZE: usize = 56;
25
26/// A balance in each chain value pool or transaction value pool.
27#[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    /// The NSM value balance, `NSMValueBalance`: value removed from circulation and not yet
36    /// reissued through block subsidies.
37    ///
38    /// It is not in circulation and is excluded from the issued supply (see [`Self::total`]).
39    nsm: Amount<C>,
40}
41
42impl<C> ValueBalance<C>
43where
44    C: Constraint + Copy,
45{
46    /// Creates a [`ValueBalance`] from the given transparent amount.
47    pub fn from_transparent_amount(transparent_amount: Amount<C>) -> Self {
48        ValueBalance {
49            transparent: transparent_amount,
50            ..ValueBalance::zero()
51        }
52    }
53
54    /// Creates a [`ValueBalance`] from the given sprout amount.
55    pub fn from_sprout_amount(sprout_amount: Amount<C>) -> Self {
56        ValueBalance {
57            sprout: sprout_amount,
58            ..ValueBalance::zero()
59        }
60    }
61
62    /// Creates a [`ValueBalance`] from the given sapling amount.
63    pub fn from_sapling_amount(sapling_amount: Amount<C>) -> Self {
64        ValueBalance {
65            sapling: sapling_amount,
66            ..ValueBalance::zero()
67        }
68    }
69
70    /// Creates a [`ValueBalance`] from the given orchard amount.
71    pub fn from_orchard_amount(orchard_amount: Amount<C>) -> Self {
72        ValueBalance {
73            orchard: orchard_amount,
74            ..ValueBalance::zero()
75        }
76    }
77
78    /// Creates a [`ValueBalance`] from the given ironwood amount.
79    pub fn from_ironwood_amount(ironwood_amount: Amount<C>) -> Self {
80        ValueBalance {
81            ironwood: ironwood_amount,
82            ..ValueBalance::zero()
83        }
84    }
85
86    /// Get the transparent amount from the [`ValueBalance`].
87    pub fn transparent_amount(&self) -> Amount<C> {
88        self.transparent
89    }
90
91    /// Insert a transparent value balance into a given [`ValueBalance`]
92    /// leaving the other values untouched.
93    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    /// Get the sprout amount from the [`ValueBalance`].
102    pub fn sprout_amount(&self) -> Amount<C> {
103        self.sprout
104    }
105
106    /// Insert a sprout value balance into a given [`ValueBalance`]
107    /// leaving the other values untouched.
108    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    /// Get the sapling amount from the [`ValueBalance`].
114    pub fn sapling_amount(&self) -> Amount<C> {
115        self.sapling
116    }
117
118    /// Insert a sapling value balance into a given [`ValueBalance`]
119    /// leaving the other values untouched.
120    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    /// Get the orchard amount from the [`ValueBalance`].
126    pub fn orchard_amount(&self) -> Amount<C> {
127        self.orchard
128    }
129
130    /// Insert an orchard value balance into a given [`ValueBalance`]
131    /// leaving the other values untouched.
132    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    /// Returns the deferred amount.
138    pub fn deferred_amount(&self) -> Amount<C> {
139        self.deferred
140    }
141
142    /// Sets the deferred amount without affecting other amounts.
143    pub fn set_deferred_amount(&mut self, deferred_amount: Amount<C>) -> &Self {
144        self.deferred = deferred_amount;
145        self
146    }
147
148    /// Get the ironwood amount from the [`ValueBalance`].
149    pub fn ironwood_amount(&self) -> Amount<C> {
150        self.ironwood
151    }
152
153    /// Insert an ironwood value balance into a given [`ValueBalance`]
154    /// leaving the other values untouched.
155    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    /// Returns the Network Sustainability Mechanism amount, `NSMValueBalance`.
161    pub fn nsm_amount(&self) -> Amount<C> {
162        self.nsm
163    }
164
165    /// Sets the Network Sustainability Mechanism amount without affecting other amounts.
166    pub fn set_nsm_amount(&mut self, nsm_amount: Amount<C>) -> &Self {
167        self.nsm = nsm_amount;
168        self
169    }
170
171    /// Creates a [`ValueBalance`] where all the pools are zero.
172    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    /// Returns the sum of all chain value pool balances, `IssuedSupply`.
186    ///
187    /// The NSM value balance is not a chain value pool: it counts value that is not in circulation,
188    /// so it is excluded here and from the `MAX_MONEY` check on the issued supply.
189    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    /// Convert this value balance to a different ValueBalance type,
206    /// if it satisfies the new constraint
207    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    /// Assumes that this value balance is a non-coinbase transaction value balance,
225    /// and returns the remaining value in the transaction value pool.
226    ///
227    /// # Consensus
228    ///
229    /// > The remaining value in the transparent transaction value pool MUST be nonnegative.
230    ///
231    /// <https://zips.z.cash/protocol/protocol.pdf#transactions>
232    ///
233    /// This rule applies to Block and Mempool transactions.
234    ///
235    /// Design: <https://github.com/ZcashFoundation/zebra/blob/main/book/src/dev/rfcs/0012-value-pools.md#definitions>
236    pub fn remaining_transaction_value(&self) -> Result<Amount<NonNegative>, amount::Error> {
237        // Calculated by summing the transparent, sprout, sapling, orchard, and ironwood value
238        // balances, as specified in:
239        // https://zebra.zfnd.org/dev/rfcs/0012-value-pools.html#definitions
240        //
241        // The ironwood bundle (NU6.3 onward) contributes to the transaction value pool exactly
242        // like the orchard bundle; it is zero for transactions without an ironwood bundle.
243        //
244        // This will error if the remaining value in the transaction value pool is negative.
245        (self.transparent + self.sprout + self.sapling + self.orchard + self.ironwood)?
246            .constrain::<NonNegative>()
247    }
248}
249
250impl ValueBalance<NonNegative> {
251    /// Returns the sum of this value balance, and the chain value pool changes in `transaction`.
252    ///
253    /// `outputs` must contain the [`transparent::Output`]s of every input in this transaction,
254    /// including UTXOs created by earlier transactions in its block.
255    ///
256    /// Note: the chain value pool has the opposite sign to the transaction
257    /// value pool.
258    ///
259    /// # Consensus
260    ///
261    /// > If any of the "Sprout chain value pool balance", "Sapling chain value pool balance", or
262    /// > "Orchard chain value pool balance" would become negative in the block chain created
263    /// > as a result of accepting a block, then all nodes MUST reject the block as invalid.
264    /// >
265    /// > Nodes MAY relay transactions even if one or more of them cannot be mined due to the
266    /// > aforementioned restriction.
267    ///
268    /// <https://zips.z.cash/zip-0209#specification>
269    ///
270    /// Since this consensus rule is optional for mempool transactions,
271    /// Zebra does not check it in the mempool transaction verifier.
272    #[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        // the chain pool (unspent outputs) has the opposite sign to
281        // transaction value balances (inputs - outputs)
282        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    /// Returns the sum of this value balance, and the chain value pool change in `input`.
294    ///
295    /// `outputs` must contain the [`transparent::Output`] spent by `input`,
296    /// (including UTXOs created by earlier transactions in its block).
297    ///
298    /// Note: the chain value pool has the opposite sign to the transaction
299    /// value pool. Inputs remove value from the chain value pool.
300    #[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        // the chain pool (unspent outputs) has the opposite sign to
309        // transaction value balances (inputs - outputs)
310        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    /// Returns the sum of this value balance, and the given `chain_value_pool_change`.
318    ///
319    /// Note that the chain value pool has the opposite sign to the transaction value pool.
320    ///
321    /// # Consensus
322    ///
323    /// > If the Sprout chain value pool balance would become negative in the block chain
324    /// > created as a result of accepting a block, then all nodes MUST reject the block as invalid.
325    ///
326    /// <https://zips.z.cash/protocol/protocol.pdf#joinsplitbalance>
327    ///
328    /// > If the Sapling chain value pool balance would become negative in the block chain
329    /// > created as a result of accepting a block, then all nodes MUST reject the block as invalid.
330    ///
331    /// <https://zips.z.cash/protocol/protocol.pdf#saplingbalance>
332    ///
333    /// > If the Orchard chain value pool balance would become negative in the block chain
334    /// > created as a result of accepting a block , then all nodes MUST reject the block as invalid.
335    ///
336    /// <https://zips.z.cash/protocol/protocol.pdf#orchardbalance>
337    ///
338    /// > If any of the "Sprout chain value pool balance", "Sapling chain value pool balance", or
339    /// > "Orchard chain value pool balance" would become negative in the block chain created
340    /// > as a result of accepting a block, then all nodes MUST reject the block as invalid.
341    ///
342    /// <https://zips.z.cash/zip-0209#specification>
343    ///
344    /// Zebra also checks that the transparent value pool is non-negative.
345    /// In Zebra, we define this pool as the sum of all unspent transaction outputs.
346    /// (Despite their encoding as an `int64`, transparent output values must be non-negative.)
347    ///
348    /// This is a consensus rule derived from Bitcoin:
349    ///
350    /// > because a UTXO can only be spent once,
351    /// > the full value of the included UTXOs must be spent or given to a miner as a transaction fee.
352    ///
353    /// <https://developer.bitcoin.org/devguide/transactions.html#transaction-fees-and-change>
354    ///
355    /// We implement the consensus rules above by constraining the returned value balance to
356    /// [`ValueBalance<NonNegative>`].
357    #[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        // # Consensus
368        //
369        // > [NU7 onward] If NSMValueBalance(height) would become negative in the block chain created
370        // > as a result of accepting a block at height, then all nodes MUST reject the block as
371        // > invalid.
372        //
373        // https://zips.z.cash/zip-0237
374        //
375        // The `nsm` balance is constrained non-negative here with the pools. The additional block
376        // subsidy is at most the balance it is calculated from, so this cannot fail by construction.
377        let chain_value_pool = chain_value_pool.constrain::<NonNegative>()?;
378
379        // The sum of all chain value pools is the total monetary base, which consensus caps at
380        // `MAX_MONEY`. Reject any change that would push the chain value pool total over that cap.
381        chain_value_pool.total().map_err(ValueBalanceError::Total)?;
382
383        Ok(chain_value_pool)
384    }
385
386    /// Create a fake value pool for testing purposes.
387    ///
388    /// The resulting [`ValueBalance`] has `MAX_MONEY / 8` on the transparent, Sprout, Sapling,
389    /// Orchard, and Ironwood pools; the deferred pool is zero. This keeps the total within the
390    /// valid `Amount` range (see [`ValueBalance::total`]), while leaving headroom for value pool
391    /// changes that tests commit on top of it.
392    #[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    /// To byte array.
417    ///
418    /// Each new pool is appended after the previous ones, so records written by earlier Zebra
419    /// versions (32 bytes without `deferred`, 40 bytes with it, or 48 bytes with `ironwood`)
420    /// remain parsable by [`Self::from_bytes`].
421    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    /// From byte array.
438    ///
439    /// Accepts 32-byte (pre-`deferred`), 40-byte (pre-`ironwood`), 48-byte (pre-`nsm`),
440    /// and 56-byte records; missing trailing pools default to zero.
441    #[allow(clippy::unwrap_in_result)]
442    pub fn from_bytes(bytes: &[u8]) -> Result<ValueBalance<NonNegative>, ValueBalanceError> {
443        let bytes_length = bytes.len();
444
445        // Return an error early if bytes don't have the right length instead of panicking later.
446        // Each pool is 8 bytes, and records start at the 32-byte pre-`deferred` width.
447        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)]
522/// Errors that can be returned when validating a [`ValueBalance`]
523pub enum ValueBalanceError {
524    /// transparent amount error {0}
525    Transparent(amount::Error),
526
527    /// sprout amount error {0}
528    Sprout(amount::Error),
529
530    /// sapling amount error {0}
531    Sapling(amount::Error),
532
533    /// orchard amount error {0}
534    Orchard(amount::Error),
535
536    /// deferred amount error {0}
537    Deferred(amount::Error),
538
539    /// ironwood amount error {0}
540    Ironwood(amount::Error),
541
542    /// NSM amount error {0}
543    Nsm(amount::Error),
544
545    /// total amount error {0}
546    Total(amount::Error),
547
548    /// ValueBalance is unparsable
549    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}