validate.rs 47 KB

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