validate.rs 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425
  1. //! Pure, sync validation — the auditable heart of the ledger.
  2. //!
  3. //! [`validate_and_plan`] enforces every invariant (conservation, double-spend,
  4. //! account state, overdraft, book policy) and produces a [`Plan`] describing the
  5. //! effects to apply. It takes no IO, no clock, and no randomness, so it is deterministic
  6. //! and testable with golden vectors. The caller provides pre-loaded state via
  7. //! [`PlanInput`]; this module never touches storage.
  8. use std::collections::{HashMap, HashSet};
  9. use std::error::Error;
  10. use std::fmt;
  11. use crate::hash::{account_hash, envelope_id};
  12. use kuatia_types::internals;
  13. use kuatia_types::internals::{Cent, OverflowError};
  14. use kuatia_types::*;
  15. // ---------------------------------------------------------------------------
  16. // Input / Output
  17. // ---------------------------------------------------------------------------
  18. /// Pre-loaded state the caller must supply. Borrowing avoids copies on the
  19. /// hot path and keeps this module allocation-free for the validation itself.
  20. pub struct PlanInput<'a> {
  21. /// The envelope to validate.
  22. pub envelope: &'a Envelope,
  23. /// Postings referenced by `transfer.consumes`.
  24. pub consumed_postings: &'a [Posting],
  25. /// All accounts referenced by the transfer.
  26. pub accounts: &'a HashMap<AccountId, Account>,
  27. /// Current balances keyed by (account, asset).
  28. pub balances: &'a HashMap<(AccountId, AssetId), Cent>,
  29. /// The book gating this transfer, if one is loaded. `Some` enforces the
  30. /// book's [`BookPolicy`] (allowed assets/accounts/flags); `None` means the
  31. /// implicit unrestricted default book. The async layer is responsible for
  32. /// rejecting a *named* book id that has no row before reaching here.
  33. pub book: Option<&'a Book>,
  34. }
  35. /// The validated effects to apply atomically. Produced only when every
  36. /// invariant holds, so the store can apply it without re-checking.
  37. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
  38. pub struct Plan {
  39. /// Content-addressed id of the validated transfer.
  40. pub transfer_id: TransferId,
  41. /// Postings the consumer must spend (mark `Spent`).
  42. pub postings_to_deactivate: Vec<PostingId>,
  43. /// New postings to persist.
  44. pub postings_to_create: Vec<Posting>,
  45. }
  46. // ---------------------------------------------------------------------------
  47. // Required state: the single source of truth for what the loader must fetch
  48. // ---------------------------------------------------------------------------
  49. /// The exact stored state [`validate_and_plan`] reads for a given envelope.
  50. ///
  51. /// Validation's correctness rests on being handed *complete* state: a missing
  52. /// balance key silently defaults to zero and would flip an overdraft decision.
  53. /// Deriving the key-set here, in the pure core, gives that "load everything
  54. /// validation reads" rule one home and one test surface. The async loader
  55. /// iterates these keys rather than re-deriving its own, so it cannot
  56. /// under-fetch.
  57. #[derive(Debug, Clone, PartialEq, Eq)]
  58. pub struct RequiredState {
  59. /// Posting ids validation reads: exactly `envelope.consumes()`.
  60. pub consumed_postings: Vec<PostingId>,
  61. /// Accounts validation reads: owners of created and consumed postings, plus
  62. /// every snapshot-pinned account.
  63. pub accounts: Vec<AccountId>,
  64. /// Balance keys validation reads: `(owner, asset)` of every consumed and
  65. /// created posting.
  66. pub balances: Vec<(AccountId, AssetId)>,
  67. }
  68. /// Accounts and balance keys implied purely by the postings an envelope touches:
  69. /// owners of its created and consumed postings, plus the `(owner, asset)` balance
  70. /// key for each. This is the one walk [`required_state`] (what the loader fetches)
  71. /// and [`validate_and_plan`] (what it reads) both derive from, so the load set and
  72. /// the read set cannot drift.
  73. struct PostingKeys {
  74. owners: Vec<AccountId>,
  75. balances: Vec<(AccountId, AssetId)>,
  76. }
  77. /// Add `amount` to its asset's bucket, starting the bucket at zero of that
  78. /// asset. The add refuses a mismatch, so the bucket cannot end up holding a
  79. /// sum of two assets even if the key were wrong.
  80. fn fold_by_asset(
  81. buckets: &mut HashMap<AssetId, Amount>,
  82. amount: &Amount,
  83. ) -> Result<(), AmountError> {
  84. let asset = amount.asset_id();
  85. let running = match buckets.remove(&asset) {
  86. Some(sum) => sum.checked_add(amount)?,
  87. None => amount.clone(),
  88. };
  89. buckets.insert(asset, running);
  90. Ok(())
  91. }
  92. /// The bucket's sum, or nothing of that asset when the side is empty. Compared
  93. /// by value, since the two sides are the same asset by construction and a
  94. /// missing side has no asset handle to build a zero from.
  95. fn sum_of(buckets: &HashMap<AssetId, Amount>, asset: &AssetId) -> Cent {
  96. buckets
  97. .get(asset)
  98. .map(internals::cent)
  99. .unwrap_or(Cent::ZERO)
  100. }
  101. fn posting_keys(envelope: &Envelope, consumed_postings: &[Posting]) -> PostingKeys {
  102. let mut owners: Vec<AccountId> = Vec::new();
  103. let mut balances: Vec<(AccountId, AssetId)> = Vec::new();
  104. for np in envelope.creates() {
  105. owners.push(np.owner);
  106. balances.push((np.owner, np.asset()));
  107. }
  108. for p in consumed_postings {
  109. owners.push(p.owner);
  110. balances.push((p.owner, p.asset()));
  111. }
  112. owners.sort();
  113. owners.dedup();
  114. balances.sort();
  115. balances.dedup();
  116. PostingKeys { owners, balances }
  117. }
  118. /// Derive the state key-set [`validate_and_plan`] will read.
  119. ///
  120. /// The consumed postings must be passed in because their owner and asset (which
  121. /// drive the account and balance key-sets) live in the store, not the envelope.
  122. /// The loader therefore fetches `envelope.consumes()` first, then calls this to
  123. /// own every remaining key. Both this and [`validate_and_plan`] derive their
  124. /// account and balance keys from one shared `posting_keys` walk, so they cannot
  125. /// drift; the only
  126. /// extra keys named here are the snapshot-pinned accounts (validated in step 5b),
  127. /// which the loader must fetch even when they own no posting.
  128. pub fn required_state(envelope: &Envelope, consumed_postings: &[Posting]) -> RequiredState {
  129. let PostingKeys {
  130. mut owners,
  131. balances,
  132. } = posting_keys(envelope, consumed_postings);
  133. for snap in envelope.account_snapshots() {
  134. owners.push(snap.account);
  135. }
  136. owners.sort();
  137. owners.dedup();
  138. RequiredState {
  139. consumed_postings: envelope.consumes().to_vec(),
  140. accounts: owners,
  141. balances,
  142. }
  143. }
  144. // ---------------------------------------------------------------------------
  145. // Errors
  146. // ---------------------------------------------------------------------------
  147. /// An invariant violation detected during transfer validation.
  148. #[derive(Debug, Clone, PartialEq, Eq)]
  149. pub enum ValidationError {
  150. /// Transfer has no consumptions and no creations.
  151. EmptyTransfer,
  152. /// The same posting id appears more than once in `consumes`.
  153. DuplicateConsumedPosting(PostingId),
  154. /// A consumed posting id does not exist in the store.
  155. PostingNotFound(PostingId),
  156. /// A consumed posting is not owned by the expected account.
  157. OwnershipViolation {
  158. /// The posting that failed the ownership check.
  159. posting_id: PostingId,
  160. /// The account that should own the posting.
  161. expected: AccountId,
  162. /// The account that actually owns the posting.
  163. actual: AccountId,
  164. },
  165. /// A referenced account does not exist.
  166. AccountNotFound(AccountId),
  167. /// A referenced account is frozen.
  168. AccountFrozen(AccountId),
  169. /// A referenced account is closed.
  170. AccountClosed(AccountId),
  171. /// Per-asset conservation law violated: consumed sum != created sum.
  172. ConservationViolation {
  173. /// The asset whose sums differ.
  174. asset: AssetId,
  175. /// Total value of consumed postings for this asset.
  176. consumed_sum: Cent,
  177. /// Total value of created postings for this asset.
  178. created_sum: Cent,
  179. },
  180. /// Projected balance would go negative on an account that forbids overdraft.
  181. /// The model is binary: an account either permits unbounded overdraft or
  182. /// forbids any negative balance, so there is no configurable floor to report.
  183. OverdraftExceeded {
  184. /// The account that would be overdrawn.
  185. account: AccountId,
  186. /// The asset involved.
  187. asset: AssetId,
  188. /// The negative balance that would result from this transfer.
  189. projected: Cent,
  190. },
  191. /// Account snapshot hash does not match current state (stale read).
  192. AccountVersionMismatch {
  193. /// The account whose version was stale.
  194. account: AccountId,
  195. /// The snapshot hash the transfer expected.
  196. expected: [u8; 32],
  197. /// The actual current snapshot hash.
  198. actual: [u8; 32],
  199. },
  200. /// A negative posting targets an account that forbids overdraft.
  201. NegativePostingOnNonSystemAccount {
  202. /// The account that would receive the negative posting.
  203. account: AccountId,
  204. /// The asset involved.
  205. asset: AssetId,
  206. /// The negative value.
  207. value: Cent,
  208. },
  209. /// An asset is not permitted by the transfer's book policy.
  210. BookAssetNotAllowed {
  211. /// The book whose policy rejected the asset.
  212. book: BookId,
  213. /// The disallowed asset.
  214. asset: AssetId,
  215. },
  216. /// An account is not permitted to participate by the transfer's book policy.
  217. BookAccountNotAllowed {
  218. /// The book whose policy rejected the account.
  219. book: BookId,
  220. /// The disallowed account.
  221. account: AccountId,
  222. },
  223. /// An arithmetic operation overflowed.
  224. Overflow,
  225. /// Two amounts of different assets were combined while folding a side of
  226. /// the conservation check, which means a bucket key lost its asset.
  227. Amount(AmountError),
  228. }
  229. impl fmt::Display for ValidationError {
  230. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  231. match self {
  232. Self::EmptyTransfer => write!(f, "transfer has no postings"),
  233. Self::DuplicateConsumedPosting(id) => write!(f, "duplicate consumed posting {id:?}"),
  234. Self::PostingNotFound(id) => write!(f, "posting not found: {id:?}"),
  235. Self::OwnershipViolation {
  236. posting_id,
  237. expected,
  238. actual,
  239. } => {
  240. write!(
  241. f,
  242. "ownership violation on {posting_id:?}: expected {expected:?}, got {actual:?}"
  243. )
  244. }
  245. Self::AccountNotFound(id) => write!(f, "account not found: {id:?}"),
  246. Self::AccountFrozen(id) => write!(f, "account frozen: {id:?}"),
  247. Self::AccountClosed(id) => write!(f, "account closed: {id:?}"),
  248. Self::ConservationViolation {
  249. asset,
  250. consumed_sum,
  251. created_sum,
  252. } => {
  253. write!(
  254. f,
  255. "conservation violated for {asset:?}: consumed {consumed_sum}, created {created_sum}"
  256. )
  257. }
  258. Self::OverdraftExceeded {
  259. account,
  260. asset,
  261. projected,
  262. } => {
  263. write!(
  264. f,
  265. "overdraft forbidden for {account:?}/{asset:?}: projected {projected}"
  266. )
  267. }
  268. Self::AccountVersionMismatch {
  269. account,
  270. expected,
  271. actual,
  272. } => {
  273. write!(
  274. f,
  275. "account version mismatch for {account:?}: expected {expected:02x?}, got {actual:02x?}"
  276. )
  277. }
  278. Self::NegativePostingOnNonSystemAccount {
  279. account,
  280. asset,
  281. value,
  282. } => {
  283. write!(
  284. f,
  285. "negative posting ({value}) on account {account:?}/{asset:?} that forbids overdraft"
  286. )
  287. }
  288. Self::BookAssetNotAllowed { book, asset } => {
  289. write!(f, "asset {asset:?} not allowed by book {book:?}")
  290. }
  291. Self::BookAccountNotAllowed { book, account } => {
  292. write!(f, "account {account:?} not allowed by book {book:?}")
  293. }
  294. Self::Overflow => write!(f, "monetary amount overflow"),
  295. Self::Amount(e) => write!(f, "amount: {e}"),
  296. }
  297. }
  298. }
  299. impl Error for ValidationError {}
  300. impl From<OverflowError> for ValidationError {
  301. fn from(_: OverflowError) -> Self {
  302. Self::Overflow
  303. }
  304. }
  305. impl From<AmountError> for ValidationError {
  306. fn from(e: AmountError) -> Self {
  307. match e {
  308. AmountError::Overflow => Self::Overflow,
  309. other => Self::Amount(other),
  310. }
  311. }
  312. }
  313. // ---------------------------------------------------------------------------
  314. // The pure decision function
  315. // ---------------------------------------------------------------------------
  316. /// The single entry point for all ledger invariant checks.
  317. ///
  318. /// Pure, sync, deterministic — no IO, no clock, no randomness — so the
  319. /// invariants are testable with golden vectors and replay deterministically.
  320. /// Returns a [`Plan`] only when every invariant holds; otherwise returns the
  321. /// specific [`ValidationError`] that was violated.
  322. pub fn validate_and_plan(input: PlanInput<'_>) -> Result<Plan, ValidationError> {
  323. let envelope = input.envelope;
  324. // 1. Non-empty
  325. if envelope.consumes().is_empty() && envelope.creates().is_empty() {
  326. return Err(ValidationError::EmptyTransfer);
  327. }
  328. // 2. No duplicate consumed PostingIds
  329. {
  330. let mut seen = HashSet::with_capacity(envelope.consumes().len());
  331. for pid in envelope.consumes() {
  332. if !seen.insert(pid) {
  333. return Err(ValidationError::DuplicateConsumedPosting(*pid));
  334. }
  335. }
  336. }
  337. // Index consumed postings by id for lookup
  338. let consumed_by_id: HashMap<PostingId, &Posting> =
  339. input.consumed_postings.iter().map(|p| (p.id, p)).collect();
  340. // 3. Every consumed posting exists. Whether it is still unspent is not
  341. // decidable here: a `Posting` carries no state and this check is a
  342. // snapshot-in-time read. The authoritative double-spend guard is the
  343. // commit transaction's own delete (ADR-0021 maps the full commit-safety
  344. // invariant).
  345. for pid in envelope.consumes() {
  346. consumed_by_id
  347. .get(pid)
  348. .ok_or(ValidationError::PostingNotFound(*pid))?;
  349. }
  350. // 5. Every referenced account exists, not FROZEN, not CLOSED. The account
  351. // and balance key-sets come from the same `posting_keys` walk `required_state`
  352. // hands the loader, so what validation reads here is structurally what was
  353. // fetched. Snapshot-pinned accounts are handled separately in 5b, so this set
  354. // deliberately excludes snapshot-only accounts.
  355. let all_account_ids = posting_keys(envelope, input.consumed_postings).owners;
  356. for aid in &all_account_ids {
  357. let account = input
  358. .accounts
  359. .get(aid)
  360. .ok_or(ValidationError::AccountNotFound(*aid))?;
  361. if account.is_frozen() {
  362. return Err(ValidationError::AccountFrozen(*aid));
  363. }
  364. if account.is_closed() {
  365. return Err(ValidationError::AccountClosed(*aid));
  366. }
  367. }
  368. // 5b. Snapshot pinning: each account_snapshot must match current state.
  369. for snap in envelope.account_snapshots() {
  370. let account = input
  371. .accounts
  372. .get(&snap.account)
  373. .ok_or(ValidationError::AccountNotFound(snap.account))?;
  374. let actual = account_hash(account);
  375. if snap.snapshot_id != actual {
  376. return Err(ValidationError::AccountVersionMismatch {
  377. account: snap.account,
  378. expected: snap.snapshot_id,
  379. actual,
  380. });
  381. }
  382. }
  383. // 5c. Book policy: gate which assets and accounts may participate. Enforced
  384. // only when a book is loaded; an empty policy field means "no restriction".
  385. if let Some(book) = input.book {
  386. let policy = &book.policy;
  387. if !policy.allowed_assets.is_empty() {
  388. let mut referenced_assets: HashSet<AssetId> = HashSet::new();
  389. for pid in envelope.consumes() {
  390. referenced_assets.insert(consumed_by_id[pid].asset());
  391. }
  392. for np in envelope.creates() {
  393. referenced_assets.insert(np.asset());
  394. }
  395. for asset in &referenced_assets {
  396. if !policy.allowed_assets.contains(asset) {
  397. return Err(ValidationError::BookAssetNotAllowed {
  398. book: book.id,
  399. asset: *asset,
  400. });
  401. }
  402. }
  403. }
  404. let no_account_restriction =
  405. policy.allowed_accounts.is_empty() && policy.allowed_flags.is_empty();
  406. if !no_account_restriction {
  407. for aid in &all_account_ids {
  408. let account = &input.accounts[aid];
  409. // Book membership is scoped by base account: a book that lists a
  410. // base account admits all of that account's subaccounts.
  411. let listed = policy.allowed_accounts.contains(&aid.base());
  412. let flag_match = !policy.allowed_flags.is_empty()
  413. && account.flags.intersects(policy.allowed_flags);
  414. if !(listed || flag_match) {
  415. return Err(ValidationError::BookAccountNotAllowed {
  416. book: book.id,
  417. account: *aid,
  418. });
  419. }
  420. }
  421. }
  422. }
  423. // 6. Per-asset conservation: Σ consumed == Σ created
  424. // Summed as amounts, not values: an amount refuses to add across assets, so
  425. // the bucket key is now a second line of defence rather than the only one.
  426. // A key that lost its asset leg would fail here instead of quietly netting
  427. // one asset against another.
  428. let mut consumed_by_asset: HashMap<AssetId, Amount> = HashMap::new();
  429. for pid in envelope.consumes() {
  430. let posting = consumed_by_id[pid];
  431. fold_by_asset(&mut consumed_by_asset, &posting.amount)?;
  432. }
  433. let mut created_by_asset: HashMap<AssetId, Amount> = HashMap::new();
  434. for np in envelope.creates() {
  435. fold_by_asset(&mut created_by_asset, &np.amount)?;
  436. }
  437. // All assets must appear in both sides (or have sum 0 on the missing side)
  438. let mut all_assets: HashSet<AssetId> = HashSet::new();
  439. all_assets.extend(consumed_by_asset.keys());
  440. all_assets.extend(created_by_asset.keys());
  441. for asset in &all_assets {
  442. let consumed_sum = sum_of(&consumed_by_asset, asset);
  443. let created_sum = sum_of(&created_by_asset, asset);
  444. if consumed_sum != created_sum {
  445. return Err(ValidationError::ConservationViolation {
  446. asset: *asset,
  447. consumed_sum,
  448. created_sum,
  449. });
  450. }
  451. }
  452. // 7. A negative posting (offset position) is only allowed on an account
  453. // that permits overdraft. Only DEBIT_MUST_NOT_EXCEED_CREDIT forbids it.
  454. for np in envelope.creates() {
  455. if internals::cent(&np.amount).is_negative() {
  456. let account = input
  457. .accounts
  458. .get(&np.owner)
  459. .ok_or(ValidationError::AccountNotFound(np.owner))?;
  460. if account.forbids_overdraft() {
  461. return Err(ValidationError::NegativePostingOnNonSystemAccount {
  462. account: np.owner,
  463. asset: np.asset(),
  464. value: internals::cent(&np.amount),
  465. });
  466. }
  467. }
  468. }
  469. // 8. An account that forbids overdraft must not project to a negative
  470. // balance. Accounts that permit overdraft are unbounded below.
  471. let mut deltas: HashMap<(AccountId, AssetId), Cent> = HashMap::new();
  472. for pid in envelope.consumes() {
  473. let posting = consumed_by_id[pid];
  474. let entry = deltas
  475. .entry((posting.owner, posting.asset()))
  476. .or_insert(Cent::ZERO);
  477. *entry = entry.checked_sub(internals::cent(&posting.amount))?;
  478. }
  479. for np in envelope.creates() {
  480. let entry = deltas.entry((np.owner, np.asset())).or_insert(Cent::ZERO);
  481. *entry = entry.checked_add(internals::cent(&np.amount))?;
  482. }
  483. for ((account_id, asset_id), delta) in &deltas {
  484. let account = &input.accounts[account_id];
  485. if !account.forbids_overdraft() {
  486. continue;
  487. }
  488. let current_balance = input
  489. .balances
  490. .get(&(*account_id, *asset_id))
  491. .copied()
  492. .unwrap_or(Cent::ZERO);
  493. let projected = current_balance.checked_add(*delta)?;
  494. if projected.is_negative() {
  495. return Err(ValidationError::OverdraftExceeded {
  496. account: *account_id,
  497. asset: *asset_id,
  498. projected,
  499. });
  500. }
  501. }
  502. // 8. Build the plan
  503. let tid = envelope_id(envelope);
  504. let postings_to_deactivate: Vec<PostingId> = envelope.consumes().to_vec();
  505. let postings_to_create: Vec<Posting> = envelope
  506. .creates
  507. .iter()
  508. .enumerate()
  509. .map(|(i, np)| {
  510. Posting::new(
  511. PostingId {
  512. transfer: tid,
  513. index: i as u16,
  514. },
  515. np.owner,
  516. np.amount.clone(),
  517. )
  518. })
  519. .collect();
  520. Ok(Plan {
  521. transfer_id: tid,
  522. postings_to_deactivate,
  523. postings_to_create,
  524. })
  525. }
  526. #[cfg(test)]
  527. mod tests {
  528. use super::*;
  529. use std::collections::BTreeMap;
  530. use std::sync::Arc;
  531. /// An amount of `asset` in minor units. These tests assert on ids and
  532. /// values, and an amount compares by asset id, so the metadata is filler.
  533. fn money<V>(asset: AssetId, value: V) -> Amount
  534. where
  535. Amount: From<(V, Arc<Asset>)>,
  536. {
  537. Amount::from((value, Arc::new(Asset::new(asset, "TEST", "$", 2))))
  538. }
  539. fn make_account(id: i64, flags: AccountFlags) -> Account {
  540. Account {
  541. id: AccountId::new(id),
  542. version: 1,
  543. flags,
  544. book: BookId(0),
  545. metadata: BTreeMap::new(),
  546. }
  547. }
  548. fn accounts_map(accs: Vec<Account>) -> HashMap<AccountId, Account> {
  549. accs.into_iter().map(|a| (a.id, a)).collect()
  550. }
  551. // -- Deposit: external(-100) + account1(+100) --------------------------
  552. fn deposit_envelope() -> Envelope {
  553. Envelope {
  554. consumes: vec![],
  555. creates: vec![
  556. NewPosting {
  557. owner: AccountId::new(1),
  558. amount: money(AssetId::new(1), Cent::from(100)),
  559. payer: None,
  560. },
  561. NewPosting {
  562. owner: AccountId::new(99),
  563. amount: money(AssetId::new(1), Cent::from(-100)),
  564. payer: None,
  565. },
  566. ],
  567. book: BookId(0),
  568. account_snapshots: vec![],
  569. value_date: None,
  570. metadata: BTreeMap::new(),
  571. }
  572. }
  573. #[test]
  574. fn valid_deposit() {
  575. let envelope = deposit_envelope();
  576. let accounts = accounts_map(vec![
  577. make_account(1, AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT),
  578. make_account(99, AccountFlags::empty()),
  579. ]);
  580. let balances = HashMap::new();
  581. let input = PlanInput {
  582. envelope: &envelope,
  583. consumed_postings: &[],
  584. accounts: &accounts,
  585. balances: &balances,
  586. book: None,
  587. };
  588. let plan = validate_and_plan(input).unwrap();
  589. assert_eq!(plan.postings_to_create.len(), 2);
  590. assert!(plan.postings_to_deactivate.is_empty());
  591. }
  592. #[test]
  593. fn empty_transfer_rejected() {
  594. let envelope = Envelope {
  595. consumes: vec![],
  596. creates: vec![],
  597. book: BookId(0),
  598. account_snapshots: vec![],
  599. value_date: None,
  600. metadata: BTreeMap::new(),
  601. };
  602. let accounts = HashMap::new();
  603. let balances = HashMap::new();
  604. let input = PlanInput {
  605. envelope: &envelope,
  606. consumed_postings: &[],
  607. accounts: &accounts,
  608. balances: &balances,
  609. book: None,
  610. };
  611. assert_eq!(
  612. validate_and_plan(input).unwrap_err(),
  613. ValidationError::EmptyTransfer
  614. );
  615. }
  616. #[test]
  617. fn conservation_violation() {
  618. let envelope = Envelope {
  619. consumes: vec![],
  620. creates: vec![NewPosting {
  621. owner: AccountId::new(1),
  622. amount: money(AssetId::new(1), Cent::from(100)),
  623. payer: None,
  624. }],
  625. book: BookId(0),
  626. account_snapshots: vec![],
  627. value_date: None,
  628. metadata: BTreeMap::new(),
  629. };
  630. let accounts = accounts_map(vec![make_account(
  631. 1,
  632. AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT,
  633. )]);
  634. let balances = HashMap::new();
  635. let input = PlanInput {
  636. envelope: &envelope,
  637. consumed_postings: &[],
  638. accounts: &accounts,
  639. balances: &balances,
  640. book: None,
  641. };
  642. match validate_and_plan(input) {
  643. Err(ValidationError::ConservationViolation { .. }) => {}
  644. other => panic!("expected ConservationViolation, got {other:?}"),
  645. }
  646. }
  647. #[test]
  648. fn posting_not_found() {
  649. let missing_pid = PostingId {
  650. transfer: TransferId([0; 32]),
  651. index: 0,
  652. };
  653. let envelope = Envelope {
  654. consumes: vec![missing_pid],
  655. creates: vec![],
  656. book: BookId(0),
  657. account_snapshots: vec![],
  658. value_date: None,
  659. metadata: BTreeMap::new(),
  660. };
  661. let accounts = HashMap::new();
  662. let balances = HashMap::new();
  663. let input = PlanInput {
  664. envelope: &envelope,
  665. consumed_postings: &[],
  666. accounts: &accounts,
  667. balances: &balances,
  668. book: None,
  669. };
  670. assert_eq!(
  671. validate_and_plan(input).unwrap_err(),
  672. ValidationError::PostingNotFound(missing_pid)
  673. );
  674. }
  675. #[test]
  676. fn account_frozen_rejected() {
  677. let envelope = deposit_envelope();
  678. let mut acc = make_account(1, AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT);
  679. acc.flags = AccountFlags::FROZEN;
  680. let accounts = accounts_map(vec![acc, make_account(99, AccountFlags::empty())]);
  681. let balances = HashMap::new();
  682. let input = PlanInput {
  683. envelope: &envelope,
  684. consumed_postings: &[],
  685. accounts: &accounts,
  686. balances: &balances,
  687. book: None,
  688. };
  689. assert_eq!(
  690. validate_and_plan(input).unwrap_err(),
  691. ValidationError::AccountFrozen(AccountId::new(1))
  692. );
  693. }
  694. #[test]
  695. fn account_closed_rejected() {
  696. let envelope = deposit_envelope();
  697. let mut acc = make_account(1, AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT);
  698. acc.flags = AccountFlags::CLOSED;
  699. let accounts = accounts_map(vec![acc, make_account(99, AccountFlags::empty())]);
  700. let balances = HashMap::new();
  701. let input = PlanInput {
  702. envelope: &envelope,
  703. consumed_postings: &[],
  704. accounts: &accounts,
  705. balances: &balances,
  706. book: None,
  707. };
  708. assert_eq!(
  709. validate_and_plan(input).unwrap_err(),
  710. ValidationError::AccountClosed(AccountId::new(1))
  711. );
  712. }
  713. #[test]
  714. fn no_overdraft_exceeded() {
  715. let pid = PostingId {
  716. transfer: TransferId([1; 32]),
  717. index: 0,
  718. };
  719. let posting = Posting {
  720. id: pid,
  721. owner: AccountId::new(1),
  722. amount: money(AssetId::new(1), Cent::from(50)),
  723. };
  724. // Try to send 50 but create 100 for recipient (conservation will fail first,
  725. // but let's test overdraft with a valid conservation)
  726. let envelope = Envelope {
  727. consumes: vec![pid],
  728. creates: vec![NewPosting {
  729. owner: AccountId::new(2),
  730. amount: money(AssetId::new(1), Cent::from(50)),
  731. payer: None,
  732. }],
  733. book: BookId(0),
  734. account_snapshots: vec![],
  735. value_date: None,
  736. metadata: BTreeMap::new(),
  737. };
  738. let accounts = accounts_map(vec![
  739. make_account(1, AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT),
  740. make_account(2, AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT),
  741. ]);
  742. // account1 has balance 50, consuming 50 leaves 0, that's fine.
  743. // Let's test when balance is insufficient: balance=30, consuming 50-value posting
  744. let mut balances = HashMap::new();
  745. balances.insert((AccountId::new(1), AssetId::new(1)), Cent::from(30));
  746. // projected = 30 - 50 = -20 < 0 → overdraft
  747. let input = PlanInput {
  748. envelope: &envelope,
  749. consumed_postings: &[posting],
  750. accounts: &accounts,
  751. balances: &balances,
  752. book: None,
  753. };
  754. match validate_and_plan(input) {
  755. Err(ValidationError::OverdraftExceeded { account, .. }) => {
  756. assert_eq!(account, AccountId::new(1));
  757. }
  758. other => panic!("expected OverdraftExceeded, got {other:?}"),
  759. }
  760. }
  761. #[test]
  762. fn overdraft_may_spend_past_positive_balance() {
  763. let pid = PostingId {
  764. transfer: TransferId([1; 32]),
  765. index: 0,
  766. };
  767. let posting = Posting {
  768. id: pid,
  769. owner: AccountId::new(1),
  770. amount: money(AssetId::new(1), Cent::from(100)),
  771. };
  772. let envelope = Envelope {
  773. consumes: vec![pid],
  774. creates: vec![NewPosting {
  775. owner: AccountId::new(2),
  776. amount: money(AssetId::new(1), Cent::from(100)),
  777. payer: None,
  778. }],
  779. book: BookId(0),
  780. account_snapshots: vec![],
  781. value_date: None,
  782. metadata: BTreeMap::new(),
  783. };
  784. let accounts = accounts_map(vec![
  785. // Overdraft allowed (the default): no floor.
  786. make_account(1, AccountFlags::empty()),
  787. make_account(2, AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT),
  788. ]);
  789. // balance=80, consuming 100 → projected = 80 - 100 = -20, allowed with no floor
  790. let mut balances = HashMap::new();
  791. balances.insert((AccountId::new(1), AssetId::new(1)), Cent::from(80));
  792. let input = PlanInput {
  793. envelope: &envelope,
  794. consumed_postings: &[posting],
  795. accounts: &accounts,
  796. balances: &balances,
  797. book: None,
  798. };
  799. // An overdraft account spending into a negative balance validates.
  800. let plan = validate_and_plan(input).unwrap();
  801. assert!(!plan.postings_to_create.is_empty());
  802. }
  803. #[test]
  804. fn debit_must_not_exceed_credit_rejects_negative_projection() {
  805. let pid = PostingId {
  806. transfer: TransferId([1; 32]),
  807. index: 0,
  808. };
  809. let posting = Posting {
  810. id: pid,
  811. owner: AccountId::new(1),
  812. amount: money(AssetId::new(1), Cent::from(100)),
  813. };
  814. let envelope = Envelope {
  815. consumes: vec![pid],
  816. creates: vec![NewPosting {
  817. owner: AccountId::new(2),
  818. amount: money(AssetId::new(1), Cent::from(100)),
  819. payer: None,
  820. }],
  821. book: BookId(0),
  822. account_snapshots: vec![],
  823. value_date: None,
  824. metadata: BTreeMap::new(),
  825. };
  826. let accounts = accounts_map(vec![
  827. make_account(1, AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT),
  828. make_account(2, AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT),
  829. ]);
  830. // balance=30, consuming 100 → projected = 30 - 100 = -70 < 0 → FAIL
  831. let mut balances = HashMap::new();
  832. balances.insert((AccountId::new(1), AssetId::new(1)), Cent::from(30));
  833. let input = PlanInput {
  834. envelope: &envelope,
  835. consumed_postings: &[posting],
  836. accounts: &accounts,
  837. balances: &balances,
  838. book: None,
  839. };
  840. match validate_and_plan(input) {
  841. Err(ValidationError::OverdraftExceeded { projected, .. }) => {
  842. assert_eq!(projected, Cent::from(-70));
  843. }
  844. other => panic!("expected OverdraftExceeded, got {other:?}"),
  845. }
  846. }
  847. #[test]
  848. fn overdraft_allows_negative_balance() {
  849. let pid = PostingId {
  850. transfer: TransferId([1; 32]),
  851. index: 0,
  852. };
  853. let posting = Posting {
  854. id: pid,
  855. owner: AccountId::new(1),
  856. amount: money(AssetId::new(1), Cent::from(100)),
  857. };
  858. let envelope = Envelope {
  859. consumes: vec![pid],
  860. creates: vec![NewPosting {
  861. owner: AccountId::new(2),
  862. amount: money(AssetId::new(1), Cent::from(100)),
  863. payer: None,
  864. }],
  865. book: BookId(0),
  866. account_snapshots: vec![],
  867. value_date: None,
  868. metadata: BTreeMap::new(),
  869. };
  870. let accounts = accounts_map(vec![
  871. make_account(1, AccountFlags::empty()),
  872. make_account(2, AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT),
  873. ]);
  874. // balance=10, consuming 100 → projected = 10 - 100 = -90 → allowed
  875. let mut balances = HashMap::new();
  876. balances.insert((AccountId::new(1), AssetId::new(1)), Cent::from(10));
  877. let input = PlanInput {
  878. envelope: &envelope,
  879. consumed_postings: &[posting],
  880. accounts: &accounts,
  881. balances: &balances,
  882. book: None,
  883. };
  884. // UncappedOverdraft permits the negative projection; the plan validates.
  885. let plan = validate_and_plan(input).unwrap();
  886. assert!(!plan.postings_to_create.is_empty());
  887. }
  888. #[test]
  889. fn duplicate_consumed_posting_rejected() {
  890. let pid = PostingId {
  891. transfer: TransferId([1; 32]),
  892. index: 0,
  893. };
  894. let envelope = Envelope {
  895. consumes: vec![pid, pid], // duplicate
  896. creates: vec![],
  897. book: BookId(0),
  898. account_snapshots: vec![],
  899. value_date: None,
  900. metadata: BTreeMap::new(),
  901. };
  902. let accounts = HashMap::new();
  903. let balances = HashMap::new();
  904. let input = PlanInput {
  905. envelope: &envelope,
  906. consumed_postings: &[],
  907. accounts: &accounts,
  908. balances: &balances,
  909. book: None,
  910. };
  911. assert_eq!(
  912. validate_and_plan(input).unwrap_err(),
  913. ValidationError::DuplicateConsumedPosting(pid)
  914. );
  915. }
  916. #[test]
  917. fn internal_transfer_with_change() {
  918. // account1 has a 100 posting, sends 60 to account2, gets 40 change
  919. let pid = PostingId {
  920. transfer: TransferId([1; 32]),
  921. index: 0,
  922. };
  923. let posting = Posting {
  924. id: pid,
  925. owner: AccountId::new(1),
  926. amount: money(AssetId::new(1), Cent::from(100)),
  927. };
  928. let envelope = Envelope {
  929. consumes: vec![pid],
  930. creates: vec![
  931. NewPosting {
  932. owner: AccountId::new(2),
  933. amount: money(AssetId::new(1), Cent::from(60)),
  934. payer: Some(AccountId::new(1)),
  935. },
  936. NewPosting {
  937. owner: AccountId::new(1),
  938. amount: money(AssetId::new(1), Cent::from(40)),
  939. payer: None,
  940. },
  941. ],
  942. book: BookId(0),
  943. account_snapshots: vec![],
  944. value_date: None,
  945. metadata: BTreeMap::new(),
  946. };
  947. let accounts = accounts_map(vec![
  948. make_account(1, AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT),
  949. make_account(2, AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT),
  950. ]);
  951. let mut balances = HashMap::new();
  952. balances.insert((AccountId::new(1), AssetId::new(1)), Cent::from(100));
  953. let input = PlanInput {
  954. envelope: &envelope,
  955. consumed_postings: &[posting],
  956. accounts: &accounts,
  957. balances: &balances,
  958. book: None,
  959. };
  960. let plan = validate_and_plan(input).unwrap();
  961. assert_eq!(plan.postings_to_deactivate.len(), 1);
  962. assert_eq!(plan.postings_to_create.len(), 2);
  963. // account1 projected: 100 - 100 + 40 = 40 >= 0 ✓
  964. // account2 projected: 0 + 60 = 60 >= 0 ✓
  965. }
  966. fn make_subaccount(id: i64, sub: i64, flags: AccountFlags) -> Account {
  967. Account {
  968. id: AccountId::with_sub(id, sub),
  969. version: 1,
  970. flags,
  971. book: BookId(0),
  972. metadata: BTreeMap::new(),
  973. }
  974. }
  975. #[test]
  976. fn subaccount_carries_own_overdraft_flag() {
  977. // Base (1,0) forbids overdraft but subaccount (1,7) allows it. A negative
  978. // posting on the subaccount is allowed because the check keys on the full
  979. // owner and uses the subaccount's own flags.
  980. let sub = AccountId::with_sub(1, 7);
  981. let envelope = Envelope {
  982. consumes: vec![],
  983. creates: vec![
  984. NewPosting {
  985. owner: AccountId::new(2),
  986. amount: money(AssetId::new(1), Cent::from(100)),
  987. payer: Some(sub),
  988. },
  989. NewPosting {
  990. owner: sub,
  991. amount: money(AssetId::new(1), Cent::from(-100)),
  992. payer: None,
  993. },
  994. ],
  995. book: BookId(0),
  996. account_snapshots: vec![],
  997. value_date: None,
  998. metadata: BTreeMap::new(),
  999. };
  1000. let accounts = accounts_map(vec![
  1001. make_account(1, AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT),
  1002. make_subaccount(1, 7, AccountFlags::empty()),
  1003. make_account(2, AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT),
  1004. ]);
  1005. let balances = HashMap::new();
  1006. let input = PlanInput {
  1007. envelope: &envelope,
  1008. consumed_postings: &[],
  1009. accounts: &accounts,
  1010. balances: &balances,
  1011. book: None,
  1012. };
  1013. let plan = validate_and_plan(input).unwrap();
  1014. assert_eq!(plan.postings_to_create.len(), 2);
  1015. }
  1016. #[test]
  1017. fn subaccount_floor_is_segregated_from_base() {
  1018. // Base (1,0) holds 100, but the overdraft-forbidding subaccount (1,7)
  1019. // holds nothing. The base's balance must not rescue the subaccount: a
  1020. // negative posting on the subaccount is rejected on its own flags.
  1021. let sub = AccountId::with_sub(1, 7);
  1022. let envelope = Envelope {
  1023. consumes: vec![],
  1024. creates: vec![
  1025. NewPosting {
  1026. owner: AccountId::new(2),
  1027. amount: money(AssetId::new(1), Cent::from(100)),
  1028. payer: Some(sub),
  1029. },
  1030. NewPosting {
  1031. owner: sub,
  1032. amount: money(AssetId::new(1), Cent::from(-100)),
  1033. payer: None,
  1034. },
  1035. ],
  1036. book: BookId(0),
  1037. account_snapshots: vec![],
  1038. value_date: None,
  1039. metadata: BTreeMap::new(),
  1040. };
  1041. let accounts = accounts_map(vec![
  1042. make_account(1, AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT),
  1043. make_subaccount(1, 7, AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT),
  1044. make_account(2, AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT),
  1045. ]);
  1046. let mut balances = HashMap::new();
  1047. balances.insert((AccountId::new(1), AssetId::new(1)), Cent::from(100));
  1048. let input = PlanInput {
  1049. envelope: &envelope,
  1050. consumed_postings: &[],
  1051. accounts: &accounts,
  1052. balances: &balances,
  1053. book: None,
  1054. };
  1055. assert_eq!(
  1056. validate_and_plan(input).unwrap_err(),
  1057. ValidationError::NegativePostingOnNonSystemAccount {
  1058. account: sub,
  1059. asset: AssetId::new(1),
  1060. value: Cent::from(-100),
  1061. },
  1062. );
  1063. }
  1064. #[test]
  1065. fn account_not_found() {
  1066. let envelope = Envelope {
  1067. consumes: vec![],
  1068. creates: vec![
  1069. NewPosting {
  1070. owner: AccountId::new(999),
  1071. amount: money(AssetId::new(1), Cent::from(100)),
  1072. payer: None,
  1073. },
  1074. NewPosting {
  1075. owner: AccountId::new(99),
  1076. amount: money(AssetId::new(1), Cent::from(-100)),
  1077. payer: None,
  1078. },
  1079. ],
  1080. book: BookId(0),
  1081. account_snapshots: vec![],
  1082. value_date: None,
  1083. metadata: BTreeMap::new(),
  1084. };
  1085. // Only external account exists, account 999 doesn't
  1086. let accounts = accounts_map(vec![make_account(99, AccountFlags::empty())]);
  1087. let balances = HashMap::new();
  1088. let input = PlanInput {
  1089. envelope: &envelope,
  1090. consumed_postings: &[],
  1091. accounts: &accounts,
  1092. balances: &balances,
  1093. book: None,
  1094. };
  1095. assert_eq!(
  1096. validate_and_plan(input).unwrap_err(),
  1097. ValidationError::AccountNotFound(AccountId::new(999))
  1098. );
  1099. }
  1100. #[test]
  1101. fn negative_posting_rejected_on_regular_account() {
  1102. let envelope = Envelope {
  1103. consumes: vec![],
  1104. creates: vec![
  1105. NewPosting {
  1106. owner: AccountId::new(1),
  1107. amount: money(AssetId::new(1), Cent::from(-100)),
  1108. payer: None,
  1109. },
  1110. NewPosting {
  1111. owner: AccountId::new(1),
  1112. amount: money(AssetId::new(1), Cent::from(100)),
  1113. payer: None,
  1114. },
  1115. ],
  1116. book: BookId(0),
  1117. account_snapshots: vec![],
  1118. value_date: None,
  1119. metadata: BTreeMap::new(),
  1120. };
  1121. let accounts = accounts_map(vec![make_account(
  1122. 1,
  1123. AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT,
  1124. )]);
  1125. let balances = HashMap::new();
  1126. let input = PlanInput {
  1127. envelope: &envelope,
  1128. consumed_postings: &[],
  1129. accounts: &accounts,
  1130. balances: &balances,
  1131. book: None,
  1132. };
  1133. assert_eq!(
  1134. validate_and_plan(input).unwrap_err(),
  1135. ValidationError::NegativePostingOnNonSystemAccount {
  1136. account: AccountId::new(1),
  1137. asset: AssetId::new(1),
  1138. value: Cent::from(-100),
  1139. }
  1140. );
  1141. }
  1142. #[test]
  1143. fn negative_posting_allowed_on_system_account() {
  1144. let envelope = deposit_envelope();
  1145. let accounts = accounts_map(vec![
  1146. make_account(1, AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT),
  1147. make_account(99, AccountFlags::empty()),
  1148. ]);
  1149. let balances = HashMap::new();
  1150. let input = PlanInput {
  1151. envelope: &envelope,
  1152. consumed_postings: &[],
  1153. accounts: &accounts,
  1154. balances: &balances,
  1155. book: None,
  1156. };
  1157. let plan = validate_and_plan(input).unwrap();
  1158. assert_eq!(plan.postings_to_create.len(), 2);
  1159. }
  1160. // -- required_state golden vectors -------------------------------------
  1161. //
  1162. // The key-set required_state names must equal exactly what validate_and_plan
  1163. // reads. These pin the derivation for the shapes load exercises.
  1164. #[test]
  1165. fn required_state_deposit_nets_to_system_account() {
  1166. // A deposit consumes nothing; it creates on account 1 and the system
  1167. // account 99. No consumed postings, so no owners come from the store.
  1168. let envelope = deposit_envelope();
  1169. let required = required_state(&envelope, &[]);
  1170. assert!(required.consumed_postings.is_empty());
  1171. assert_eq!(
  1172. required.accounts,
  1173. vec![AccountId::new(1), AccountId::new(99)]
  1174. );
  1175. assert_eq!(
  1176. required.balances,
  1177. vec![
  1178. (AccountId::new(1), AssetId::new(1)),
  1179. (AccountId::new(99), AssetId::new(1)),
  1180. ]
  1181. );
  1182. }
  1183. #[test]
  1184. fn required_state_internal_transfer_with_change() {
  1185. // account1 spends a 100 posting, sends 60 to account2, keeps 40 change.
  1186. // account1's key is only reachable through the consumed posting, so it
  1187. // must appear even though the envelope's creates never name it as a
  1188. // debit source directly.
  1189. let pid = PostingId {
  1190. transfer: TransferId([1; 32]),
  1191. index: 0,
  1192. };
  1193. let posting = Posting {
  1194. id: pid,
  1195. owner: AccountId::new(1),
  1196. amount: money(AssetId::new(1), Cent::from(100)),
  1197. };
  1198. let envelope = Envelope {
  1199. consumes: vec![pid],
  1200. creates: vec![
  1201. NewPosting {
  1202. owner: AccountId::new(2),
  1203. amount: money(AssetId::new(1), Cent::from(60)),
  1204. payer: Some(AccountId::new(1)),
  1205. },
  1206. NewPosting {
  1207. owner: AccountId::new(1),
  1208. amount: money(AssetId::new(1), Cent::from(40)),
  1209. payer: None,
  1210. },
  1211. ],
  1212. book: BookId(0),
  1213. account_snapshots: vec![],
  1214. value_date: None,
  1215. metadata: BTreeMap::new(),
  1216. };
  1217. let required = required_state(&envelope, std::slice::from_ref(&posting));
  1218. assert_eq!(required.consumed_postings, vec![pid]);
  1219. assert_eq!(
  1220. required.accounts,
  1221. vec![AccountId::new(1), AccountId::new(2)]
  1222. );
  1223. assert_eq!(
  1224. required.balances,
  1225. vec![
  1226. (AccountId::new(1), AssetId::new(1)),
  1227. (AccountId::new(2), AssetId::new(1)),
  1228. ]
  1229. );
  1230. }
  1231. #[test]
  1232. fn required_state_multi_asset() {
  1233. // Two consumed postings of different assets from account 1, creating on
  1234. // accounts 2 and 3. Balance keys are per (owner, asset), so account 1
  1235. // contributes one key per asset it spends.
  1236. let pid_a = PostingId {
  1237. transfer: TransferId([1; 32]),
  1238. index: 0,
  1239. };
  1240. let pid_b = PostingId {
  1241. transfer: TransferId([2; 32]),
  1242. index: 0,
  1243. };
  1244. let consumed = vec![
  1245. Posting {
  1246. id: pid_a,
  1247. owner: AccountId::new(1),
  1248. amount: money(AssetId::new(1), Cent::from(100)),
  1249. },
  1250. Posting {
  1251. id: pid_b,
  1252. owner: AccountId::new(1),
  1253. amount: money(AssetId::new(2), Cent::from(50)),
  1254. },
  1255. ];
  1256. let envelope = Envelope {
  1257. consumes: vec![pid_a, pid_b],
  1258. creates: vec![
  1259. NewPosting {
  1260. owner: AccountId::new(2),
  1261. amount: money(AssetId::new(1), Cent::from(100)),
  1262. payer: Some(AccountId::new(1)),
  1263. },
  1264. NewPosting {
  1265. owner: AccountId::new(3),
  1266. amount: money(AssetId::new(2), Cent::from(50)),
  1267. payer: Some(AccountId::new(1)),
  1268. },
  1269. ],
  1270. book: BookId(0),
  1271. account_snapshots: vec![],
  1272. value_date: None,
  1273. metadata: BTreeMap::new(),
  1274. };
  1275. let required = required_state(&envelope, &consumed);
  1276. assert_eq!(required.consumed_postings, vec![pid_a, pid_b]);
  1277. assert_eq!(
  1278. required.accounts,
  1279. vec![AccountId::new(1), AccountId::new(2), AccountId::new(3)]
  1280. );
  1281. assert_eq!(
  1282. required.balances,
  1283. vec![
  1284. (AccountId::new(1), AssetId::new(1)),
  1285. (AccountId::new(1), AssetId::new(2)),
  1286. (AccountId::new(2), AssetId::new(1)),
  1287. (AccountId::new(3), AssetId::new(2)),
  1288. ]
  1289. );
  1290. }
  1291. #[test]
  1292. fn required_state_includes_snapshot_only_accounts() {
  1293. // A snapshot may pin an account that appears in neither creates nor any
  1294. // consumed posting. validate_and_plan reads it (step 5b), so
  1295. // required_state must name it or the loader would miss it.
  1296. let envelope = Envelope {
  1297. consumes: vec![],
  1298. creates: vec![
  1299. NewPosting {
  1300. owner: AccountId::new(1),
  1301. amount: money(AssetId::new(1), Cent::from(100)),
  1302. payer: None,
  1303. },
  1304. NewPosting {
  1305. owner: AccountId::new(99),
  1306. amount: money(AssetId::new(1), Cent::from(-100)),
  1307. payer: None,
  1308. },
  1309. ],
  1310. book: BookId(0),
  1311. account_snapshots: vec![AccountSnapshotId {
  1312. account: AccountId::new(7),
  1313. snapshot_id: [0; 32],
  1314. }],
  1315. value_date: None,
  1316. metadata: BTreeMap::new(),
  1317. };
  1318. let required = required_state(&envelope, &[]);
  1319. assert_eq!(
  1320. required.accounts,
  1321. vec![AccountId::new(1), AccountId::new(7), AccountId::new(99)]
  1322. );
  1323. }
  1324. }