//! Payment states, requests, acknowledgements, receipts, and challenges. use super::{Amount, Amounts, Epoch, InvalidOpening, Lookup, Namespace, Opening, amounts::leaf}; use bytes::BufMut; use commonware_codec::{ Buf, Encode, EncodeSize, Error as CodecError, FixedSize, RangeCfg, Read, ReadExt, Write, }; use commonware_cryptography::{Digest, Hasher, PublicKey, Signer}; use commonware_storage::bmt::Proof; use thiserror::Error; /// Why a request is refused. #[derive(Debug, Error)] pub enum RequestError { /// The request has no state for the epoch. #[error("wrong epoch: expected {expected}, found {found}")] WrongEpoch { /// The epoch the operator admits in. expected: Epoch, /// The epoch of the request. found: Epoch, }, /// The batch pays no receiver. #[error("no receiver paid")] NoReceivers, /// The sender's signature does not verify, or covers a state the operator would not /// countersign. #[error("invalid signature")] InvalidSignature, /// The next epoch, an amount, or the payment map does not fit while deriving the states. #[error("arithmetic overflow")] Overflow, /// The latest state's root is that of its map with the batch already added, so both states /// derived from the pair could settle. #[error("latest state already holds the batch")] InvalidLatest, /// The request builds on a root other than the one its latest state builds on. #[error("previous root is not the latest state's")] InvalidPrevious, } /// Why a challenge is refused. #[derive(Debug, Error)] pub enum ChallengeError { /// The receipt is for another epoch. #[error("wrong epoch: expected {expected}, found {found}")] WrongEpoch { /// The epoch of the posted close. expected: Epoch, /// The epoch of the receipt. found: Epoch, }, /// The opening does not verify. #[error("invalid opening")] InvalidOpening, /// The close credits at least what the receipt promises. #[error("challenge does not contradict the close")] NoContradiction, /// The receipt does not verify. #[error("invalid receipt")] InvalidReceipt, } impl From for ChallengeError { fn from(InvalidOpening: InvalidOpening) -> Self { Self::InvalidOpening } } /// A sender's commitment to its payment map in one epoch. /// /// The sender signs it to authorize the debit, the operator countersigns it to preconfirm the /// payments, and a close settles it only on top of the sender's row in the close before. #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct State { /// Epoch of the payments. pub epoch: Epoch, /// Account paying. pub account: P, /// Root of the sender's payment map in `epoch`. pub payments: D, /// Root of the sender's payment map in the previous epoch. pub previous: D, } impl State { /// Signs the state as its sender. pub(crate) fn sign>( &self, signer: &S, namespace: &Namespace, ) -> P::Signature { signer.sign(&namespace.state, &self.encode()) } /// Returns whether `signature` is the sender's signature over the state. pub(crate) fn verify(&self, namespace: &Namespace, signature: &P::Signature) -> bool { self.account .verify(&namespace.state, &self.encode(), signature) } /// Countersigns the state as the operator. pub fn acknowledge(&self, signer: &S, namespace: &Namespace) -> S::Signature { signer.sign(&namespace.acknowledgement, &self.encode()) } /// Returns whether `signature` is `operator`'s countersignature over the state. pub fn verify_acknowledgement( &self, namespace: &Namespace, operator: &O, signature: &O::Signature, ) -> bool { operator.verify(&namespace.acknowledgement, &self.encode(), signature) } } impl Write for State { fn write(&self, buf: &mut impl BufMut) { self.epoch.write(buf); self.account.write(buf); self.payments.write(buf); self.previous.write(buf); } } impl FixedSize for State { const SIZE: usize = Epoch::SIZE + P::SIZE + 2 * D::SIZE; } impl Read for State { type Cfg = (); fn read_cfg(buf: &mut impl Buf, _: &()) -> Result { Ok(Self { epoch: Epoch::read(buf)?, account: P::read(buf)?, payments: D::read(buf)?, previous: D::read(buf)?, }) } } #[cfg(feature = "arbitrary")] impl arbitrary::Arbitrary<'_> for State where P: for<'a> arbitrary::Arbitrary<'a>, D: for<'a> arbitrary::Arbitrary<'a>, { fn arbitrary(u: &mut arbitrary::Unstructured<'_>) -> arbitrary::Result { Ok(Self { epoch: u.arbitrary()?, account: u.arbitrary()?, payments: u.arbitrary()?, previous: u.arbitrary()?, }) } } /// A sender's signatures over the two states of a [Request], each over its state's encoding in /// [Namespace::state]. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Signatures { /// Over the state of the request's epoch. pub current: P::Signature, /// Over the state of the next epoch. pub next: P::Signature, } impl Write for Signatures

{ fn write(&self, buf: &mut impl BufMut) { self.current.write(buf); self.next.write(buf); } } impl FixedSize for Signatures

{ const SIZE: usize = 2 * P::Signature::SIZE; } impl Read for Signatures

{ type Cfg = (); fn read_cfg(buf: &mut impl Buf, _: &()) -> Result { Ok(Self { current: P::Signature::read(buf)?, next: P::Signature::read(buf)?, }) } } #[cfg(feature = "arbitrary")] impl arbitrary::Arbitrary<'_> for Signatures

where P::Signature: for<'a> arbitrary::Arbitrary<'a>, { fn arbitrary(u: &mut arbitrary::Unstructured<'_>) -> arbitrary::Result { Ok(Self { current: u.arbitrary()?, next: u.arbitrary()?, }) } } /// A sender's request to pay a batch of receivers in its epoch, or in the next if its epoch closes /// first. /// /// It carries the roots its two states claim, so each signature verifies from the request alone. /// The state of the request's epoch adds the batch to the sender's latest countersigned map of /// that epoch, on top of `previous`, and the state of the next epoch pays only the batch on top of /// that map. The sender's row in the close of the request's epoch decides which of the two can /// settle. /// /// ```text /// close(epoch - 1) close(epoch) close(epoch + 1) signatures /// /// state(epoch) previous <-------- payments current /// state(epoch + 1) latest <--------- root(batch) next /// ``` #[derive(Clone, Debug, PartialEq, Eq)] pub struct Request { /// Epoch the request is for. pub epoch: Epoch, /// Account paying. pub account: P, /// Amount paid to each receiver. pub batch: Amounts, /// Root of the sender's payment map in the epoch before `epoch`. pub previous: D, /// Root of the sender's latest countersigned payment map in `epoch`. pub latest: D, /// Root of the sender's payment map in `epoch` with the batch added. pub payments: D, /// Sender's signatures over its states. The state in `epoch` pays `payments` on top of /// `previous`, and the state in the next epoch pays only the batch on top of `latest`. pub signatures: Signatures

, } impl Request { /// Derives the states of `account`'s request to pay `batch` in `epoch`. `latest` is its latest /// countersigned state of `epoch` with the map that state commits to, or `None` if it has paid /// nothing in `epoch`. The state of `epoch` adds `batch` to that map, or to the empty map, on /// top of `previous`, and the state of the next epoch pays only `batch` on top of that map. /// When `latest` is given, `previous` must be the root that state builds on (S1), and any other /// root is refused. /// /// The latest state's root is taken as its map's root. A root that already holds the batch is /// refused, because both states derived from it could settle. #[allow(clippy::type_complexity)] pub fn states>( epoch: Epoch, account: P, batch: Amounts, latest: Option<(&State, &Amounts)>, previous: &D, ) -> Result, RequestError> { if batch.is_empty() { return Err(RequestError::NoReceivers); } // Extending a countersigned map on another root could settle its payments again after a // post that conflicts with its state. if latest.is_some_and(|(state, _)| state.previous != *previous) { return Err(RequestError::InvalidPrevious); } // The latest state holds the root of its map, and a map that starts with the batch has the // batch's root, so each map is hashed at most once. let next = State { epoch: epoch.checked_add(1).ok_or(RequestError::Overflow)?, account: account.clone(), payments: batch.root::(), previous: latest.map_or_else( || Amounts::::empty().root::(), |(state, _)| state.payments, ), }; let (payments, root) = match latest { Some((_, payments)) => { let payments = payments .combine(&batch) .map_err(|_| RequestError::Overflow)?; let root = payments.root::(); (payments, root) } None => (batch.clone(), next.payments), }; // A next state that builds on the map the current state pays could settle after it and // pay the batch twice. if next.previous == root { return Err(RequestError::InvalidLatest); } Ok(States { batch, current: State { epoch, account, payments: root, previous: *previous, }, payments, next, }) } /// Verifies the sender's signature over the request's state for `epoch`, either its state of /// its own epoch or its state of the next. pub fn verify>( &self, namespace: &Namespace, epoch: Epoch, ) -> Result, RequestError> { let (payments, previous, signature) = if epoch == self.epoch { (self.payments, self.previous, &self.signatures.current) } else if self.epoch.checked_add(1) == Some(epoch) { (self.batch.root::(), self.latest, &self.signatures.next) } else { return Err(RequestError::WrongEpoch { expected: epoch, found: self.epoch, }); }; if self.batch.is_empty() { return Err(RequestError::NoReceivers); } let state = State { epoch, account: self.account.clone(), payments, previous, }; if !state.verify(namespace, signature) { return Err(RequestError::InvalidSignature); } Ok(Verified { request: self, state, signature, }) } } impl Write for Request { fn write(&self, buf: &mut impl BufMut) { self.epoch.write(buf); self.account.write(buf); self.batch.write(buf); self.previous.write(buf); self.latest.write(buf); self.payments.write(buf); self.signatures.write(buf); } } impl EncodeSize for Request { fn encode_size(&self) -> usize { Epoch::SIZE + P::SIZE + self.batch.encode_size() + 3 * D::SIZE + Signatures::

::SIZE } } impl Read for Request { /// The maximum number of receivers in a batch. type Cfg = usize; fn read_cfg(buf: &mut impl Buf, receivers: &usize) -> Result { Ok(Self { epoch: Epoch::read(buf)?, account: P::read(buf)?, batch: Amounts::read_cfg(buf, &RangeCfg::new(1..=*receivers))?, previous: D::read(buf)?, latest: D::read(buf)?, payments: D::read(buf)?, signatures: Signatures::read(buf)?, }) } } #[cfg(feature = "arbitrary")] impl arbitrary::Arbitrary<'_> for Request where P: for<'a> arbitrary::Arbitrary<'a>, P::Signature: for<'a> arbitrary::Arbitrary<'a>, D: for<'a> arbitrary::Arbitrary<'a>, A: for<'a> arbitrary::Arbitrary<'a>, { fn arbitrary(u: &mut arbitrary::Unstructured<'_>) -> arbitrary::Result { let batch = super::amounts::arbitrary_nonempty(u)?; Ok(Self { epoch: u.arbitrary()?, account: u.arbitrary()?, batch, previous: u.arbitrary()?, latest: u.arbitrary()?, payments: u.arbitrary()?, signatures: u.arbitrary()?, }) } } /// The states of one request, the batch it pays, and the payment map its state of the request's /// epoch commits to. #[derive(Clone, Debug, PartialEq, Eq)] pub struct States { /// The batch the request pays. pub batch: Amounts, /// The state for the request's epoch. pub current: State, /// The payment map `current` commits to, the sender's map with the batch added. pub payments: Amounts, /// The state for the next epoch. It commits to `batch` alone. pub next: State, } impl States { /// Returns the request carrying these states, their claimed roots, and `signatures` over /// them. Each signature covers its state's encoding in [Namespace::state]. pub fn request(&self, signatures: Signatures

) -> Request { Request { epoch: self.current.epoch, account: self.current.account.clone(), batch: self.batch.clone(), previous: self.current.previous, latest: self.next.previous, payments: self.current.payments, signatures, } } /// Signs both states with `signer` in [Namespace::state], and returns the request as /// [States::request] does. pub fn sign(&self, signer: &S, namespace: &Namespace) -> Request where S: Signer, { self.request(Signatures { current: self.current.sign(signer, namespace), next: self.next.sign(signer, namespace), }) } } /// A request whose state for one epoch carries a valid sender signature. #[derive(Debug)] pub struct Verified<'a, P: PublicKey, D: Digest, A: Amount> { request: &'a Request, state: State, signature: &'a P::Signature, } impl Verified<'_, P, D, A> { /// Admits the verified state against the operator's record of its sender. `latest` is the /// sender's latest countersigned state in the state's epoch with its map, if any. `previous` is /// the root of the sender's row in the close of the epoch before, or the empty map's root. /// /// Returns [Admission::Retry] if the state is `latest`'s, and [Admission::New] if it pays /// `latest`'s map plus the batch on top of `previous`. Any other state is refused as one /// the operator would not countersign, including one whose batch overflows the map. #[allow(clippy::type_complexity)] pub fn admit>( self, latest: Option<(&State, &Amounts)>, previous: &D, ) -> Result, RequestError> { if latest.is_some_and(|(state, _)| *state == self.state) { return Ok(Admission::Retry(self.state)); } if self.state.previous != *previous { return Err(RequestError::InvalidSignature); } let empty = Amounts::empty(); let payments = latest.map_or(&empty, |(_, payments)| payments); let extended = payments .combine(&self.request.batch) .map_err(|_| RequestError::InvalidSignature)?; if extended.root::() != self.state.payments { return Err(RequestError::InvalidSignature); } Ok(Admission::New { state: self.state, payments: extended, signature: self.signature.clone(), }) } } /// What the operator may countersign for a verified request. #[derive(Clone, Debug, PartialEq, Eq)] pub enum Admission { /// The request repeats the sender's latest countersigned state. Countersigning it again pays /// nothing twice. Retry(State), /// A new state extending the sender's latest map by the batch. New { /// The state to countersign. state: State, /// The payment map `state` commits to. payments: Amounts, /// The sender's signature over `state`. signature: P::Signature, }, } /// A preconfirmation that `state`'s sender paid `receiver` a cumulative `amount` in the state's /// epoch. /// /// The close of that epoch must credit the receiver at least `amount` from the sender, or the /// receiver can halt the ledger with a [Challenge]. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Receipt { /// The sender's state. pub state: State, /// The sender's signature over `state`. pub signature: P::Signature, /// The operator's countersignature over `state`. pub acknowledgement: O::Signature, /// Account paid. pub receiver: P, /// Cumulative amount paid to `receiver` in the state's payment map. pub amount: A, /// Position of `receiver` in the state's payment map. pub position: u32, /// Opening of `receiver`'s entry under the state's payment map root. pub proof: Proof, } impl Receipt { /// Returns a receipt for each of `receivers` from `state`, the sender's `signature` over it, /// the operator's `acknowledgement` countersigning it, and `payments`, the map it commits to, /// or `None` if `payments` does not commit to `state` or holds no amount for a receiver. The /// receipts verify exactly when both signatures do. pub fn issue>( state: &State, signature: &P::Signature, acknowledgement: &O::Signature, payments: &Amounts, receivers: impl IntoIterator, ) -> Option> { let tree = payments.tree::(); if tree.root() != state.payments { return None; } receivers .into_iter() .map(|receiver| { let Lookup::Member { position, value: amount, proof, } = payments.lookup(&tree, &receiver) else { return None; }; Some(Self { state: state.clone(), signature: signature.clone(), acknowledgement: acknowledgement.clone(), receiver, amount, position, proof, }) }) .collect() } /// Returns whether both signatures cover the state and its payment map holds the receipt's /// entry. pub fn verify>(&self, namespace: &Namespace, operator: &O) -> bool { self.state.verify(namespace, &self.signature) && self .state .verify_acknowledgement(namespace, operator, &self.acknowledgement) && self .proof .verify_element_inclusion::( self.position, &leaf::(&self.receiver, self.amount), &self.state.payments, ) .is_ok() } } impl Write for Receipt { fn write(&self, buf: &mut impl BufMut) { self.state.write(buf); self.signature.write(buf); self.acknowledgement.write(buf); self.receiver.write(buf); self.amount.write(buf); self.position.write(buf); self.proof.write(buf); } } impl EncodeSize for Receipt { fn encode_size(&self) -> usize { State::::SIZE + P::Signature::SIZE + O::Signature::SIZE + P::SIZE + A::SIZE + u32::SIZE + self.proof.encode_size() } } impl Read for Receipt { type Cfg = (); fn read_cfg(buf: &mut impl Buf, _: &()) -> Result { Ok(Self { state: State::read(buf)?, signature: P::Signature::read(buf)?, acknowledgement: O::Signature::read(buf)?, receiver: P::read(buf)?, amount: A::read(buf)?, position: u32::read(buf)?, proof: Proof::read_cfg(buf, &1)?, }) } } #[cfg(feature = "arbitrary")] impl arbitrary::Arbitrary<'_> for Receipt where P: for<'a> arbitrary::Arbitrary<'a>, P::Signature: for<'a> arbitrary::Arbitrary<'a>, O::Signature: for<'a> arbitrary::Arbitrary<'a>, D: for<'a> arbitrary::Arbitrary<'a>, A: for<'a> arbitrary::Arbitrary<'a>, { fn arbitrary(u: &mut arbitrary::Unstructured<'_>) -> arbitrary::Result { Ok(Self { state: u.arbitrary()?, signature: u.arbitrary()?, acknowledgement: u.arbitrary()?, receiver: u.arbitrary()?, amount: u.arbitrary()?, position: u.arbitrary()?, proof: super::lookup::arbitrary_proof(u)?, }) } } /// Evidence that a posted close credits a receiver less than a receipt promised. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Challenge { /// The receipt the close contradicts. pub receipt: Receipt, /// Opening of the receipt's entry in the matrix of the posted close of its epoch. pub opening: Opening, } impl Challenge { /// Checks that the posted close of `epoch` with payment matrix root `matrix` credits the /// receipt's receiver less from its sender than the receipt promises. The receipt is checked /// last. pub fn verify>( &self, namespace: &Namespace, operator: &O, epoch: Epoch, matrix: &D, ) -> Result<(), ChallengeError> { let receipt = &self.receipt; if receipt.state.epoch != epoch { return Err(ChallengeError::WrongEpoch { expected: epoch, found: receipt.state.epoch, }); } let credited = self.opening .verify::(matrix, &receipt.state.account, &receipt.receiver)?; if credited >= receipt.amount { return Err(ChallengeError::NoContradiction); } if !receipt.verify::(namespace, operator) { return Err(ChallengeError::InvalidReceipt); } Ok(()) } } impl Write for Challenge { fn write(&self, buf: &mut impl BufMut) { self.receipt.write(buf); self.opening.write(buf); } } impl EncodeSize for Challenge { fn encode_size(&self) -> usize { self.receipt.encode_size() + self.opening.encode_size() } } impl Read for Challenge { type Cfg = (); fn read_cfg(buf: &mut impl Buf, _: &()) -> Result { Ok(Self { receipt: Receipt::read(buf)?, opening: Opening::read(buf)?, }) } } #[cfg(feature = "arbitrary")] impl arbitrary::Arbitrary<'_> for Challenge where P: for<'a> arbitrary::Arbitrary<'a>, P::Signature: for<'a> arbitrary::Arbitrary<'a>, O::Signature: for<'a> arbitrary::Arbitrary<'a>, D: for<'a> arbitrary::Arbitrary<'a>, A: for<'a> arbitrary::Arbitrary<'a>, { fn arbitrary(u: &mut arbitrary::Unstructured<'_>) -> arbitrary::Result { Ok(Self { receipt: u.arbitrary()?, opening: u.arbitrary()?, }) } } #[cfg(test)] mod tests { use super::*; use crate::bajillion::{ Matrix, tests::{account, amounts, empty_root, namespace, operator_key, user}, }; use commonware_codec::{Decode as _, DecodeExt as _}; use commonware_cryptography::{Sha256, ed25519::PublicKey, sha256::Digest}; type TestRequest = Request; type TestStates = States; /// Returns alice's countersigned state of epoch 2 committing to `payments` on top of /// `previous`, or `None` if `payments` is empty. fn latest( payments: &Amounts, previous: Digest, ) -> Option> { (!payments.is_empty()).then(|| State { epoch: 2, account: account(0), payments: payments.root::(), previous, }) } /// Returns the states alice signs to pay `batch` in epoch 2 on top of `previous`, where /// `payments` is her latest countersigned map of epoch 2. fn states( batch: &[(u64, u64)], payments: &Amounts, previous: Digest, ) -> TestStates { let latest = latest(payments, previous); let latest = latest.as_ref().map(|state| (state, payments)); TestRequest::states::(2, account(0), amounts(batch), latest, &previous).unwrap() } /// Returns a receipt from a payment map paying two receivers. fn receipt() -> Receipt { let namespace = namespace(); let states = states(&[(2, 4), (3, 5)], &Amounts::empty(), empty_root()); Receipt::<_, PublicKey, _, _>::issue::( &states.current, &states.current.sign(&user(0), &namespace), &states.current.acknowledge(&operator_key(), &namespace), &states.payments, [account(3)], ) .unwrap() .pop() .unwrap() } /// A request signed from its states verifies in each epoch it has a state for, and the operator /// admits the state the sender derived, with or without earlier payments in the epoch. #[test] fn test_signed_states_are_admitted() { let namespace = namespace(); let previous = amounts(&[(4, 1)]).root::(); for payments in [Amounts::empty(), amounts(&[(1, 3), (2, 4)])] { let states = states(&[(1, 5), (3, 6)], &payments, previous); let signed = states.sign(&user(0), &namespace); assert_eq!(states.payments, payments.combine(&states.batch).unwrap()); assert_eq!(states.current.payments, states.payments.root::()); assert_eq!(states.next.payments, states.batch.root::()); assert_eq!(states.next.previous, payments.root::()); // The request crosses the wire with its distinct claimed roots intact. Decoding // refuses a batch beyond the receiver limit and a truncated encoding. let encoded = signed.encode(); let request = TestRequest::decode_cfg(encoded.clone(), &2).unwrap(); assert_eq!(request, signed); assert_ne!(request.payments, request.previous); assert_ne!(request.payments, request.latest); assert!(TestRequest::decode_cfg(encoded.clone(), &1).is_err()); assert!(TestRequest::decode_cfg(encoded.slice(..encoded.len() - 1), &2).is_err()); // In its own epoch, the request extends the sender's latest map. let latest = latest(&payments, previous); let admission = request .verify::(&namespace, 2) .unwrap() .admit::(latest.as_ref().map(|state| (state, &payments)), &previous) .unwrap(); assert_eq!( admission, Admission::New { state: states.current.clone(), payments: states.payments.clone(), signature: request.signatures.current.clone(), } ); // A retry of the countersigned state is admitted as one, whatever its batch. let mut retried = request.clone(); retried.batch = amounts(&[(7, 1)]); let admission = retried .verify::(&namespace, 2) .unwrap() .admit::(Some((&states.current, &states.payments)), &previous) .unwrap(); assert_eq!(admission, Admission::Retry(states.current.clone())); // In the next epoch, the request pays only its batch on top of the map the close of // its epoch settles. The admission carries the signature over the next state. let admission = request .verify::(&namespace, 3) .unwrap() .admit::(None, &payments.root::()) .unwrap(); assert_ne!(request.signatures.next, request.signatures.current); assert_eq!( admission, Admission::New { state: states.next.clone(), payments: states.batch.clone(), signature: request.signatures.next.clone(), } ); // If the close of its epoch settles the map with the batch added, the next state does // not build on the sender's row, so it is never admitted. assert!(matches!( request .verify::(&namespace, 3) .unwrap() .admit::(None, &states.current.payments), Err(RequestError::InvalidSignature) )); } } /// A key outside the process signs each state's encoding in the state namespace, and the /// request filled from those signatures is the one an in-process signer produces. #[test] fn test_external_signatures_fill_the_same_request() { let namespace = namespace(); let signer = user(0); let states = states(&[(1, 5)], &amounts(&[(2, 1)]), empty_root()); let current = signer.sign(&namespace.state, &states.current.encode()); let next = signer.sign(&namespace.state, &states.next.encode()); assert_eq!( states.request(Signatures { current, next }), states.sign(&signer, &namespace) ); } /// States do not derive from an empty batch, an epoch with no successor, an overflowing map, a /// previous root other than the latest state's, or a latest state whose root already holds the /// batch. #[test] fn test_states_refuse_unpayable_batches() { assert!(matches!( TestRequest::states::(2, account(0), Amounts::empty(), None, &empty_root()), Err(RequestError::NoReceivers) )); assert!(matches!( TestRequest::states::( Epoch::MAX, account(0), amounts(&[(1, 1)]), None, &empty_root(), ), Err(RequestError::Overflow) )); let full = amounts(&[(1, u64::MAX)]); let state = latest(&full, empty_root()).unwrap(); assert!(matches!( TestRequest::states::( 2, account(0), amounts(&[(1, 1)]), Some((&state, &full)), &empty_root(), ), Err(RequestError::Overflow) )); // A request that extends a countersigned map on another root could settle that map's // payments again. let (paid, batch) = (amounts(&[(1, 2)]), amounts(&[(1, 3)])); let state = latest(&paid, empty_root()).unwrap(); assert!(matches!( TestRequest::states::( 2, account(0), batch.clone(), Some((&state, &paid)), &batch.root::(), ), Err(RequestError::InvalidPrevious) )); // A state that commits to the map with the batch added, given with the map before it, would // make the next state build on the map the current state pays. let state = latest(&paid.combine(&batch).unwrap(), empty_root()).unwrap(); assert!(matches!( TestRequest::states::( 2, account(0), batch, Some((&state, &paid)), &empty_root(), ), Err(RequestError::InvalidLatest) )); } /// A request is checked against its own signature before any record of its sender is needed. #[test] fn test_verify_refuses_requests_the_sender_did_not_sign() { let namespace = namespace(); let states = states(&[(1, 5)], &Amounts::empty(), empty_root()); let request = states.sign(&user(0), &namespace); // The request has states for its epoch and the next only. for epoch in [1, 4] { assert!(matches!( request.verify::(&namespace, epoch), Err(RequestError::WrongEpoch { expected, found: 2 }) if expected == epoch )); } // A request paying no one is refused, even though its state for its own epoch carries a // valid signature. let empty = TestRequest { batch: Amounts::empty(), ..request.clone() }; assert!(matches!( empty.verify::(&namespace, 2), Err(RequestError::NoReceivers) )); // The signatures cover the account, the claimed roots, the next state's batch, and the // deployment. let other = amounts(&[(9, 9)]).root::(); for (epoch, request) in [ ( 2, TestRequest { account: account(1), ..request.clone() }, ), ( 2, TestRequest { payments: other, ..request.clone() }, ), ( 2, TestRequest { previous: other, ..request.clone() }, ), ( 3, TestRequest { batch: amounts(&[(1, 6)]), ..request.clone() }, ), ( 3, TestRequest { latest: other, ..request.clone() }, ), ] { assert!(matches!( request.verify::(&namespace, epoch), Err(RequestError::InvalidSignature) )); } for epoch in [2, 3] { assert!(matches!( request.verify::(&Namespace::new(b"other"), epoch), Err(RequestError::InvalidSignature) )); } } /// The operator admits only the state it would countersign itself. #[test] fn test_admit_refuses_states_off_the_record() { let namespace = namespace(); let paid = amounts(&[(1, 3)]); let latest = State { epoch: 2, account: account(0), payments: paid.root::(), previous: empty_root(), }; let admit = |states: &TestStates, latest: Option<(&State<_, _>, &Amounts<_, _>)>, previous| { states .sign(&user(0), &namespace) .verify::(&namespace, 2) .unwrap() .admit::(latest, &previous) }; // A state built on another previous map, a state that does not extend the latest map, and // a batch that would overflow the latest map are all refused. let elsewhere = states(&[(1, 5)], &paid, amounts(&[(4, 1)]).root::()); let stale = states(&[(1, 5)], &Amounts::empty(), empty_root()); for (states, latest) in [ (&elsewhere, Some((&latest, &paid))), (&stale, Some((&latest, &paid))), ] { assert!(matches!( admit(states, latest, empty_root()), Err(RequestError::InvalidSignature) )); } let full = amounts(&[(1, u64::MAX)]); let fresh = states(&[(1, 1)], &Amounts::empty(), empty_root()); let at_limit = State { payments: full.root::(), ..latest.clone() }; assert!(matches!( admit(&fresh, Some((&at_limit, &full)), empty_root()), Err(RequestError::InvalidSignature) )); // The state extending the latest map is admitted. let next = states(&[(1, 5)], &paid, empty_root()); assert!(matches!( admit(&next, Some((&latest, &paid)), empty_root()), Ok(Admission::New { .. }) )); } /// A receipt issued from a countersigned state verifies and round-trips. #[test] fn test_issued_receipts_verify() { let namespace = namespace(); let receipt = receipt(); let operator = operator_key().public_key(); assert!(receipt.verify::(&namespace, &operator)); assert_eq!(receipt.amount, 5); assert_eq!( Receipt::::decode(receipt.encode()).unwrap(), receipt ); } /// Issuing refuses a map the state does not commit to and a receiver the map does not pay. #[test] fn test_issue_refuses_maps_that_do_not_commit_to_the_state() { let namespace = namespace(); let states = states(&[(2, 4), (3, 5)], &Amounts::empty(), empty_root()); let signature = states.current.sign(&user(0), &namespace); let acknowledgement = states.current.acknowledge(&operator_key(), &namespace); let issue = |payments: &Amounts, receiver| { Receipt::<_, PublicKey, _, _>::issue::( &states.current, &signature, &acknowledgement, payments, [account(receiver)], ) }; assert!(issue(&amounts(&[(2, 4)]), 2).is_none()); assert!(issue(&states.payments, 1).is_none()); assert_eq!(issue(&states.payments, 2).unwrap()[0].amount, 4); } /// A receipt verifies only with its own fields, operator key, and namespace. #[test] fn test_receipt_rejects_tampering() { let namespace = namespace(); let receipt = receipt(); let operator = operator_key().public_key(); let other = account(9); let mut state = receipt.state.clone(); state.epoch += 1; let tampered = vec![ Receipt { amount: receipt.amount + 1, ..receipt.clone() }, Receipt { amount: 0, ..receipt.clone() }, Receipt { receiver: other.clone(), ..receipt.clone() }, Receipt { position: receipt.position ^ 1, ..receipt.clone() }, Receipt { acknowledgement: receipt.signature.clone(), ..receipt.clone() }, Receipt { state, ..receipt.clone() }, ]; for tampered in tampered { assert!(!tampered.verify::(&namespace, &operator)); } assert!(!receipt.verify::(&namespace, &other)); assert!(!receipt.verify::(&Namespace::new(b"other"), &operator)); } /// A receipt signed by another account does not verify, even with a valid countersignature. #[test] fn test_receipt_needs_the_sender_signature() { let namespace = namespace(); let mut receipt = receipt(); let operator = operator_key().public_key(); receipt.signature = receipt.state.sign(&user(9), &namespace); assert!(receipt.state.verify_acknowledgement( &namespace, &operator, &receipt.acknowledgement )); assert!(!receipt.verify::(&namespace, &operator)); } /// The operator's countersignature never verifies as the sender's signature, even when the /// operator signs with the sender's key. #[test] fn test_signatures_are_domain_separated() { let namespace = namespace(); let receipt = receipt(); let countersignature = receipt.state.acknowledge(&user(0), &namespace); assert!(!receipt.state.verify(&namespace, &countersignature)); assert!(receipt.state.verify(&namespace, &receipt.signature)); } /// A challenge is checked against the posted close of its own epoch, and every refusal before /// the receipt's signatures costs only hashes. #[test] fn test_challenge_checks_the_close_before_the_signatures() { let namespace = namespace(); let receipt = receipt(); let operator = operator_key().public_key(); let sender = receipt.state.account.clone(); let matrix_of = |payments: Amounts| { let root = payments.root::(); Matrix::<_, Sha256, _>::from_sorted(vec![(sender.clone(), payments, root)]) }; let underpaying = matrix_of(amounts(&[(3, 4)])); let paying = matrix_of(amounts(&[(3, 5)])); let challenge = |receipt: &Receipt<_, _, _, _>, matrix: &Matrix<_, _, _>| Challenge { receipt: receipt.clone(), opening: matrix.open(&sender, &receipt.receiver), }; // A receipt the close credits in part contradicts it, and the challenge round-trips. let valid = challenge(&receipt, &underpaying); valid .verify::(&namespace, &operator, 2, &underpaying.root()) .unwrap(); assert_eq!(Challenge::decode(valid.encode()).unwrap(), valid); // Neither an earlier nor a later epoch's close is the receipt's. for other in [0, 1, 3, Epoch::MAX] { assert!(matches!( valid.verify::(&namespace, &operator, other, &underpaying.root()), Err(ChallengeError::WrongEpoch { expected, found: 2 }) if expected == other )); } // A receipt whose signatures do not verify is refused only once its opening verifies and // the close contradicts it. let mut forged = receipt; forged.signature = user(9).sign(b"forged", b"receipt"); let mut misopened = challenge(&forged, &underpaying); misopened.opening = underpaying.open(&sender, &account(2)); assert!(matches!( misopened.verify::(&namespace, &operator, 2, &underpaying.root()), Err(ChallengeError::InvalidOpening) )); assert!(matches!( challenge(&forged, &underpaying).verify::( &namespace, &operator, 2, &paying.root() ), Err(ChallengeError::InvalidOpening) )); assert!(matches!( challenge(&forged, &paying).verify::(&namespace, &operator, 2, &paying.root()), Err(ChallengeError::NoContradiction) )); assert!(matches!( challenge(&forged, &underpaying).verify::( &namespace, &operator, 2, &underpaying.root() ), Err(ChallengeError::InvalidReceipt) )); } #[cfg(feature = "arbitrary")] mod conformance { use super::*; use commonware_codec::conformance::CodecConformance; commonware_conformance::conformance_tests! { CodecConformance>, CodecConformance>, CodecConformance>, CodecConformance>, CodecConformance>, } } }