lib.rs 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372
  1. //! Domain types for the ledger.
  2. //!
  3. //! These types model the UTXO-style ledger where value is held as **postings** —
  4. //! signed amounts owned by exactly one account. An account's balance is simply the
  5. //! sum of its active postings, which eliminates the need for running balance fields
  6. //! and makes the system trivially auditable by replaying the transfer log.
  7. pub mod autoid;
  8. use serde::{Deserialize, Serialize};
  9. use std::collections::BTreeMap;
  10. use std::fmt;
  11. use std::sync::atomic::{AtomicU64, Ordering};
  12. // ---------------------------------------------------------------------------
  13. // ToBytes trait
  14. // ---------------------------------------------------------------------------
  15. /// Deterministic binary serialization. Every domain type can produce its
  16. /// canonical byte representation.
  17. pub trait ToBytes {
  18. /// Returns the canonical byte representation of this value.
  19. fn to_bytes(&self) -> Vec<u8>;
  20. }
  21. // ---------------------------------------------------------------------------
  22. // Binary encoding helpers — big-endian, deterministic
  23. // ---------------------------------------------------------------------------
  24. /// Version byte prepended to canonical serializations for forward compatibility.
  25. /// Bumped to 2 when `Cent` moved to a fixed 16-byte canonical encoding (ADR-0011).
  26. /// Bumped to 3 when `AccountId` gained a `subaccount` leg folded into its
  27. /// canonical bytes (ADR-0012).
  28. pub const CANONICAL_VERSION: u8 = 3;
  29. /// Append a `u16` in big-endian to `buf`.
  30. pub fn write_u16(buf: &mut Vec<u8>, v: u16) {
  31. buf.extend_from_slice(&v.to_be_bytes());
  32. }
  33. /// Append a `u32` in big-endian to `buf`.
  34. pub fn write_u32(buf: &mut Vec<u8>, v: u32) {
  35. buf.extend_from_slice(&v.to_be_bytes());
  36. }
  37. /// Append a `u64` in big-endian to `buf`.
  38. pub fn write_u64(buf: &mut Vec<u8>, v: u64) {
  39. buf.extend_from_slice(&v.to_be_bytes());
  40. }
  41. /// Append an `i64` in big-endian to `buf`.
  42. pub fn write_i64(buf: &mut Vec<u8>, v: i64) {
  43. buf.extend_from_slice(&v.to_be_bytes());
  44. }
  45. /// Append a `u128` in big-endian to `buf`.
  46. pub fn write_u128(buf: &mut Vec<u8>, v: u128) {
  47. buf.extend_from_slice(&v.to_be_bytes());
  48. }
  49. // ---------------------------------------------------------------------------
  50. // Identifiers
  51. // ---------------------------------------------------------------------------
  52. /// Stable account identity. Used in all public APIs.
  53. ///
  54. /// An account is a base `id` plus a `subaccount`. `sub = 0` is the main account
  55. /// (the default when subaccounts are not used); a non-zero `sub` is a
  56. /// subaccount of the same base id. `sub` is an opaque id (an `i64`, like the
  57. /// base id), so the whole range is usable. Each `(id, sub)` is a full account
  58. /// record with its own policy and lifecycle. See ADR-0012.
  59. #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
  60. pub struct AccountId {
  61. /// Base account id.
  62. pub id: i64,
  63. /// Subaccount id; `0` is the main account.
  64. pub sub: i64,
  65. }
  66. /// Pairs an [`AccountId`] with a snapshot hash — the double-SHA256 of the
  67. /// account's state at a point in time. Stored on [`Transfer`] to record which
  68. /// account versions a transfer was executed against. Internal type — the
  69. /// public API uses [`AccountId`].
  70. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
  71. pub struct AccountSnapshotId {
  72. /// The account (subaccount) this snapshot belongs to.
  73. pub account: AccountId,
  74. /// Double-SHA256 of the account's state at the time of the snapshot.
  75. pub snapshot_id: [u8; 32],
  76. }
  77. /// Identifies an asset (USD, EUR, BTC, …). Conservation is enforced per asset,
  78. /// so each asset is an independent conservation boundary.
  79. #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
  80. pub struct AssetId(pub u32);
  81. /// Content-addressed transfer identifier — the double-SHA256 of the canonical
  82. /// serialization. This makes the id both the idempotency key and the
  83. /// tamper-evidence artifact.
  84. #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
  85. pub struct EnvelopeId(pub [u8; 32]);
  86. /// Uniquely identifies a posting within the ledger. The `(transfer, index)` pair
  87. /// ties every posting back to the transfer that created it, which is the basis
  88. /// of the provenance graph.
  89. #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
  90. pub struct PostingId {
  91. /// The transfer that created this posting.
  92. pub transfer: EnvelopeId,
  93. /// Zero-based position within the transfer's created postings.
  94. pub index: u16,
  95. }
  96. // ---------------------------------------------------------------------------
  97. // Cent — re-exported from kuatia-money (swappable integer backing)
  98. // ---------------------------------------------------------------------------
  99. pub use kuatia_money::{Amount, Cent, OverflowError, ParseAmountError};
  100. impl ToBytes for Cent {
  101. fn to_bytes(&self) -> Vec<u8> {
  102. self.to_canonical_bytes().to_vec()
  103. }
  104. }
  105. // ---------------------------------------------------------------------------
  106. // Debug / Display impls for identifiers
  107. // ---------------------------------------------------------------------------
  108. impl fmt::Debug for AccountId {
  109. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  110. if self.sub == 0 {
  111. write!(f, "AccountId({})", self.id)
  112. } else {
  113. write!(f, "AccountId({}.{})", self.id, self.sub)
  114. }
  115. }
  116. }
  117. impl fmt::Display for AccountId {
  118. /// IBAN-style machine format: two ISO 7064 mod-97 check digits, then a
  119. /// 26-character base-36 body. There is no country code. The `(id, sub)` pair
  120. /// is run through a keyed 128-bit Feistel permutation (see [`set_id_seed`])
  121. /// before encoding, so the body does not reveal the raw ids. Round-trips via
  122. /// [`FromStr`](std::str::FromStr); [`to_grouped`](AccountId::to_grouped) adds
  123. /// the presentation spacing.
  124. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  125. let (l, r) = feistel(self.id as u64, self.sub as u64, id_seed());
  126. let body = format!("{}{}", base36_u64(l), base36_u64(r));
  127. write!(f, "{:02}{body}", check_digits(&body))
  128. }
  129. }
  130. impl fmt::Debug for AssetId {
  131. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  132. write!(f, "AssetId({:#010x})", self.0)
  133. }
  134. }
  135. impl fmt::Debug for EnvelopeId {
  136. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  137. write!(f, "EnvelopeId({})", hex(&self.0))
  138. }
  139. }
  140. impl fmt::Debug for PostingId {
  141. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  142. f.debug_struct("PostingId")
  143. .field("transfer", &self.transfer)
  144. .field("index", &self.index)
  145. .finish()
  146. }
  147. }
  148. fn hex(bytes: &[u8]) -> String {
  149. bytes.iter().map(|b| format!("{b:02x}")).collect()
  150. }
  151. // ---------------------------------------------------------------------------
  152. // IBAN-style string view for AccountId (ADR-0012)
  153. // ---------------------------------------------------------------------------
  154. /// Encode a `u64` as exactly 13 base-36 digits (`0-9A-Z`), zero-padded on the
  155. /// left. 13 digits is the widest a `u64` needs (`36^13 > u64::MAX`), so this
  156. /// never truncates.
  157. fn base36_u64(mut v: u64) -> String {
  158. const D: &[u8; 36] = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  159. let mut out = [b'0'; 13];
  160. let mut i = out.len();
  161. while v > 0 && i > 0 {
  162. i -= 1;
  163. out[i] = D[(v % 36) as usize];
  164. v /= 36;
  165. }
  166. out.iter().map(|&b| b as char).collect()
  167. }
  168. /// Expand an IBAN string to its numeric form for the checksum: digits stay,
  169. /// letters `A-Z` become `10..35`.
  170. fn iban_expand(s: &str) -> String {
  171. let mut out = String::with_capacity(s.len() * 2);
  172. for c in s.bytes() {
  173. if c.is_ascii_digit() {
  174. out.push(c as char);
  175. } else {
  176. let v = (c - b'A') as u32 + 10;
  177. out.push_str(&v.to_string());
  178. }
  179. }
  180. out
  181. }
  182. /// ISO 7064 mod-97-10 over a decimal string, computed iteratively so the input
  183. /// length is unbounded.
  184. fn mod97(digits: &str) -> u32 {
  185. let mut rem = 0u32;
  186. for b in digits.bytes() {
  187. rem = (rem * 10 + (b - b'0') as u32) % 97;
  188. }
  189. rem
  190. }
  191. /// The two mod-97 check digits for a base-36 body, IBAN-style but with no
  192. /// country code: `98 - (expand(body ++ "00") mod 97)`.
  193. fn check_digits(body: &str) -> u32 {
  194. 98 - mod97(&iban_expand(&format!("{body}00")))
  195. }
  196. // ---------------------------------------------------------------------------
  197. // Account-code obfuscation (ADR-0012)
  198. //
  199. // The account code's body is a base-36 rendering of the two i64 legs. Without
  200. // mixing, small ids render as long runs of zeros that reveal their value and
  201. // sequence. To hide that from outsiders, the (id, sub) pair is run through a
  202. // keyed 128-bit Feistel permutation before encoding, and inverted on parse.
  203. // This is obfuscation, not security: anyone with the seed can decode it, so it
  204. // is not a substitute for authorization. The seed has a default and can be set
  205. // once at startup via `set_id_seed`; changing it changes every code, so it must
  206. // be stable across a deployment.
  207. // ---------------------------------------------------------------------------
  208. /// Default seed for the account-code obfuscation permutation. Override at
  209. /// startup with [`set_id_seed`], before any code is issued or parsed.
  210. pub const DEFAULT_ID_SEED: u64 = 0x9E37_79B9_7F4A_7C15;
  211. /// Process-global seed keying the account-code permutation.
  212. static ID_SEED: AtomicU64 = AtomicU64::new(DEFAULT_ID_SEED);
  213. /// Set the process-global seed that keys the account-code obfuscation. Call once
  214. /// at startup: every [`AccountId`] string form depends on it, so changing it
  215. /// after codes are issued invalidates the previously issued ones.
  216. pub fn set_id_seed(seed: u64) {
  217. ID_SEED.store(seed, Ordering::Relaxed);
  218. }
  219. /// The current process-global account-code seed.
  220. pub fn id_seed() -> u64 {
  221. ID_SEED.load(Ordering::Relaxed)
  222. }
  223. /// Number of Feistel rounds. Four rounds of a strong round function give a
  224. /// strong pseudo-random permutation (Luby-Rackoff), which is ample for
  225. /// obfuscation.
  226. const FEISTEL_ROUNDS: usize = 4;
  227. /// SplitMix64 finalizer: a strong 64-bit avalanche mixer.
  228. fn mix64(mut z: u64) -> u64 {
  229. z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
  230. z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
  231. z ^ (z >> 31)
  232. }
  233. /// Per-round subkey derived from the seed and round index.
  234. fn round_key(seed: u64, round: usize) -> u64 {
  235. mix64(seed ^ (round as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15))
  236. }
  237. /// Keyed 128-bit Feistel permutation over the two halves `(l, r)`.
  238. fn feistel(mut l: u64, mut r: u64, seed: u64) -> (u64, u64) {
  239. for round in 0..FEISTEL_ROUNDS {
  240. let next = l ^ mix64(r ^ round_key(seed, round));
  241. l = r;
  242. r = next;
  243. }
  244. (l, r)
  245. }
  246. /// Inverse of [`feistel`] under the same seed.
  247. fn feistel_inv(mut l: u64, mut r: u64, seed: u64) -> (u64, u64) {
  248. for round in (0..FEISTEL_ROUNDS).rev() {
  249. let prev = r ^ mix64(l ^ round_key(seed, round));
  250. r = l;
  251. l = prev;
  252. }
  253. (l, r)
  254. }
  255. // ---------------------------------------------------------------------------
  256. // Identifier constructors
  257. // ---------------------------------------------------------------------------
  258. impl Default for AccountId {
  259. fn default() -> Self {
  260. // Process-global generator: a per-thread one could mint the same id on
  261. // two threads within a millisecond, yielding duplicate account ids.
  262. static GEN: crate::autoid::AutoId = crate::autoid::AutoId::new();
  263. Self {
  264. id: GEN.next(),
  265. sub: 0,
  266. }
  267. }
  268. }
  269. impl AccountId {
  270. /// Create the main account (`sub = 0`) for a base `id`.
  271. pub const fn new(id: i64) -> Self {
  272. Self { id, sub: 0 }
  273. }
  274. /// Create a specific subaccount of a base `id`.
  275. pub const fn with_sub(id: i64, sub: i64) -> Self {
  276. Self { id, sub }
  277. }
  278. /// Return the main account of this id (`sub` set to `0`).
  279. pub const fn base(&self) -> Self {
  280. Self {
  281. id: self.id,
  282. sub: 0,
  283. }
  284. }
  285. /// Whether this is the main account (`sub == 0`).
  286. pub const fn is_main(&self) -> bool {
  287. self.sub == 0
  288. }
  289. /// IBAN-style presentation format: the machine [`Display`](fmt::Display)
  290. /// form grouped into blocks of four with a single space
  291. /// (e.g. `9200 0000 0000 0050 0000 0000 07`).
  292. pub fn to_grouped(&self) -> String {
  293. let machine = self.to_string();
  294. let mut out = String::with_capacity(machine.len() + machine.len() / 4);
  295. for (i, c) in machine.chars().enumerate() {
  296. if i > 0 && i % 4 == 0 {
  297. out.push(' ');
  298. }
  299. out.push(c);
  300. }
  301. out
  302. }
  303. }
  304. impl From<AccountSnapshotId> for AccountId {
  305. fn from(snap: AccountSnapshotId) -> Self {
  306. snap.account
  307. }
  308. }
  309. /// Returned when a string is not a valid [`AccountId`] code: wrong structure,
  310. /// non-base-36 body, or a failed mod-97 checksum.
  311. #[derive(Debug, Clone, PartialEq, Eq)]
  312. pub struct ParseAccountIdError;
  313. impl fmt::Display for ParseAccountIdError {
  314. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  315. write!(f, "invalid AccountId: not a checksum-valid account code")
  316. }
  317. }
  318. impl std::error::Error for ParseAccountIdError {}
  319. impl std::str::FromStr for AccountId {
  320. type Err = ParseAccountIdError;
  321. /// Parse an IBAN-style account code back into the two i64 legs. Any spaces
  322. /// (grouped display format) and dashes (URL-safe separator) are ignored and
  323. /// the input is upper-cased first, so `5000...`, `5000 0000 ...`, and
  324. /// `5000-0000-...` all parse to the same id. The value must reduce to two
  325. /// check digits followed by a 26-character base-36 body, and the ISO 7064
  326. /// mod-97 checksum must pass — so a mistyped or otherwise invalid id is
  327. /// rejected here rather than reaching the store. Each 13-char half is read as
  328. /// a `u64` bit pattern and reinterpreted as `i64`.
  329. fn from_str(s: &str) -> Result<Self, Self::Err> {
  330. let cleaned: String = s
  331. .chars()
  332. .filter(|c| !c.is_whitespace() && *c != '-')
  333. .map(|c| c.to_ascii_uppercase())
  334. .collect();
  335. // 2 check digits + 26-char base-36 body.
  336. if cleaned.len() != 28 {
  337. return Err(ParseAccountIdError);
  338. }
  339. let check = &cleaned[0..2];
  340. let body = &cleaned[2..28];
  341. let is_base36 = |b: u8| b.is_ascii_digit() || b.is_ascii_uppercase();
  342. if !check.bytes().all(|b| b.is_ascii_digit()) || !body.bytes().all(is_base36) {
  343. return Err(ParseAccountIdError);
  344. }
  345. // Checksum-valid iff the expanded (body ++ check) reduces to 1 under
  346. // mod-97.
  347. if mod97(&iban_expand(&format!("{body}{check}"))) != 1 {
  348. return Err(ParseAccountIdError);
  349. }
  350. // Decode the two halves, then invert the Feistel permutation to recover
  351. // the raw legs.
  352. let l = u64::from_str_radix(&body[0..13], 36).map_err(|_| ParseAccountIdError)?;
  353. let r = u64::from_str_radix(&body[13..26], 36).map_err(|_| ParseAccountIdError)?;
  354. let (id, sub) = feistel_inv(l, r, id_seed());
  355. Ok(Self {
  356. id: id as i64,
  357. sub: sub as i64,
  358. })
  359. }
  360. }
  361. impl AssetId {
  362. /// Create an `AssetId` from a `u32`.
  363. pub const fn new(id: u32) -> Self {
  364. Self(id)
  365. }
  366. }
  367. /// Identifies a book — a named scope for transfers.
  368. #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
  369. pub struct BookId(pub i64);
  370. impl fmt::Debug for BookId {
  371. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  372. write!(f, "BookId({})", self.0)
  373. }
  374. }
  375. /// The implicit book used when a transfer does not name one. Fixed so that two
  376. /// otherwise-identical transfers hash to the same [`EnvelopeId`] — a random
  377. /// default would break content-addressed idempotency.
  378. pub const DEFAULT_BOOK: BookId = BookId(0);
  379. impl Default for BookId {
  380. /// Deterministic: returns [`DEFAULT_BOOK`]. Use [`BookId::generate`] to mint
  381. /// a fresh unique id for a real book.
  382. fn default() -> Self {
  383. DEFAULT_BOOK
  384. }
  385. }
  386. impl BookId {
  387. /// Create a `BookId` from an `i64`.
  388. pub const fn new(id: i64) -> Self {
  389. Self(id)
  390. }
  391. /// Mint a fresh, process-unique book id. Unlike [`Default`], this is not
  392. /// stable across calls — use it when creating a new [`Book`], never for the
  393. /// implicit book of a transfer.
  394. pub fn generate() -> Self {
  395. // Process-global so the "process-unique" contract holds across threads;
  396. // a per-thread generator can repeat an id on another thread.
  397. static GEN: crate::autoid::AutoId = crate::autoid::AutoId::new();
  398. Self(GEN.next())
  399. }
  400. }
  401. /// Identifies a reservation — the owner token stamped on a posting while it is
  402. /// `PendingInactive`, so only the saga that reserved it may finalize or release it.
  403. #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
  404. pub struct ReservationId(pub i64);
  405. impl fmt::Debug for ReservationId {
  406. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  407. write!(f, "ReservationId({})", self.0)
  408. }
  409. }
  410. impl ReservationId {
  411. /// Create a `ReservationId` from an `i64`.
  412. pub const fn new(id: i64) -> Self {
  413. Self(id)
  414. }
  415. }
  416. impl Default for ReservationId {
  417. fn default() -> Self {
  418. // One process-global generator, not one per thread: its atomic counter
  419. // makes every reservation id unique across threads. A `thread_local`
  420. // generator lets two sagas on different threads mint the same id within
  421. // a millisecond, which collapses the reservation-ownership check and
  422. // allows a double-spend under concurrency.
  423. static GEN: crate::autoid::AutoId = crate::autoid::AutoId::new();
  424. Self(GEN.next())
  425. }
  426. }
  427. // ---------------------------------------------------------------------------
  428. // Book
  429. // ---------------------------------------------------------------------------
  430. /// A Book is a transfer policy scope: it gates which accounts and assets may
  431. /// participate in a transfer. It is **not** the chronological entry log (the
  432. /// transfer log plays that role), and it does **not** partition balances —
  433. /// balances are global; a Book only gates participation.
  434. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
  435. pub struct Book {
  436. /// Stable identity for this book.
  437. pub id: BookId,
  438. /// Human-readable name.
  439. pub name: String,
  440. /// Participation rules for this book.
  441. pub policy: BookPolicy,
  442. }
  443. /// The participation rules for a [`Book`]. An empty field means "no restriction".
  444. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
  445. pub struct BookPolicy {
  446. /// If non-empty, only these assets may appear in movements.
  447. pub allowed_assets: Vec<AssetId>,
  448. /// If non-empty, accounts with ANY of these flags may participate.
  449. pub allowed_flags: AccountFlags,
  450. /// If non-empty, these specific accounts may participate (in addition to flag matches).
  451. pub allowed_accounts: Vec<AccountId>,
  452. }
  453. /// Builder for constructing [`Book`] values.
  454. pub struct BookBuilder {
  455. book: Book,
  456. }
  457. impl BookBuilder {
  458. /// Create a new book builder with the given name.
  459. pub fn new(name: impl Into<String>) -> Self {
  460. Self {
  461. book: Book {
  462. id: BookId::generate(),
  463. name: name.into(),
  464. policy: BookPolicy {
  465. allowed_assets: Vec::new(),
  466. allowed_flags: AccountFlags::empty(),
  467. allowed_accounts: Vec::new(),
  468. },
  469. },
  470. }
  471. }
  472. /// Set the book id explicitly.
  473. pub fn id(mut self, id: BookId) -> Self {
  474. self.book.id = id;
  475. self
  476. }
  477. /// Add an allowed asset.
  478. pub fn allow_asset(mut self, asset: AssetId) -> Self {
  479. self.book.policy.allowed_assets.push(asset);
  480. self
  481. }
  482. /// Set allowed account flags — accounts with ANY of these flags may participate.
  483. pub fn allow_flags(mut self, flags: AccountFlags) -> Self {
  484. self.book.policy.allowed_flags = flags;
  485. self
  486. }
  487. /// Add a specific allowed account.
  488. pub fn allow_account(mut self, account: AccountId) -> Self {
  489. self.book.policy.allowed_accounts.push(account);
  490. self
  491. }
  492. /// Consume the builder and return the [`Book`].
  493. pub fn build(self) -> Book {
  494. self.book
  495. }
  496. }
  497. // ---------------------------------------------------------------------------
  498. // Posting
  499. // ---------------------------------------------------------------------------
  500. /// Lifecycle state of a [`Posting`].
  501. ///
  502. /// ```text
  503. /// Active ──reserve──▶ PendingInactive ──finalize──▶ Inactive (void)
  504. /// ▲ ▲ │
  505. /// │ └─── release (no-op) ┘
  506. /// └────── release ────────┘ (compensation)
  507. /// ```
  508. ///
  509. /// `reserve_postings` and `release_postings` are batch operations:
  510. /// - **reserve**: all postings must be Active, otherwise the batch fails.
  511. /// - **release**: Active is a no-op, PendingInactive reverts to Active,
  512. /// Inactive (void) fails the batch.
  513. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
  514. pub enum PostingStatus {
  515. /// Available for consumption and counted in balance.
  516. Active,
  517. /// Reserved for a transfer; not available for other consumption.
  518. /// Reverts to `Active` on compensation via `release_postings`.
  519. PendingInactive,
  520. /// Consumed by a committed transfer. Kept for audit trail (void).
  521. /// Cannot be released.
  522. Inactive,
  523. }
  524. /// A signed amount of one asset, owned by exactly one account.
  525. ///
  526. /// A positive posting is value controlled by the account; a negative posting is
  527. /// an offset position (issuance, external flow, overdraft, or system balancing).
  528. /// Negative postings are allowed on every policy except `NoOverdraft`.
  529. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
  530. pub struct Posting {
  531. /// Unique identifier derived from the creating transfer.
  532. pub id: PostingId,
  533. /// The account (subaccount) that owns this posting.
  534. pub owner: AccountId,
  535. /// The asset this posting denominates.
  536. pub asset: AssetId,
  537. /// Signed: positive = value controlled by the account, negative = offset position.
  538. pub value: Cent,
  539. /// Lifecycle state — only `Active` postings count toward balance.
  540. pub status: PostingStatus,
  541. /// Owner token while `PendingInactive`. `Some(rid)` iff reserved by saga
  542. /// `rid`; `None` when `Active` or `Inactive`. Only the holder of a matching
  543. /// `ReservationId` may finalize or release a reserved posting.
  544. pub reservation: Option<ReservationId>,
  545. }
  546. impl Posting {
  547. /// Construct an `Active`, unreserved posting.
  548. pub fn new(id: PostingId, owner: AccountId, asset: AssetId, value: Cent) -> Self {
  549. Self {
  550. id,
  551. owner,
  552. asset,
  553. value,
  554. status: PostingStatus::Active,
  555. reservation: None,
  556. }
  557. }
  558. /// Returns `true` if this posting's status is [`PostingStatus::Active`].
  559. pub fn is_active(&self) -> bool {
  560. self.status == PostingStatus::Active
  561. }
  562. }
  563. /// A posting to be created — carries no id yet because the [`PostingId`] depends
  564. /// on the [`EnvelopeId`], which is computed during validation.
  565. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
  566. pub struct NewPosting {
  567. /// The account (subaccount) that will own the created posting.
  568. pub owner: AccountId,
  569. /// The asset this posting denominates.
  570. pub asset: AssetId,
  571. /// Signed amount: positive = value controlled by the account, negative = offset position.
  572. pub value: Cent,
  573. /// Informational provenance — who funded this posting.
  574. pub payer: Option<AccountId>,
  575. }
  576. // ---------------------------------------------------------------------------
  577. // Transfer
  578. // ---------------------------------------------------------------------------
  579. /// Fixed-width secondary identifiers.
  580. #[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
  581. pub struct UserData {
  582. /// 128-bit user-defined slot (e.g. external UUID).
  583. pub d128: u128,
  584. /// 64-bit user-defined slot (e.g. correlation id).
  585. pub d64: u64,
  586. /// 32-bit user-defined slot (e.g. category code).
  587. pub d32: u32,
  588. }
  589. /// Free-form key→value metadata.
  590. pub type Metadata = BTreeMap<String, Vec<u8>>;
  591. /// The unit of atomicity — all of its consumptions and creations apply together
  592. /// or not at all. This is the resolved, internal form produced by the saga
  593. /// pipeline from a [`Transfer`] intent.
  594. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
  595. pub struct Envelope {
  596. /// Posting ids consumed (spent) by this envelope.
  597. pub consumes: Vec<PostingId>,
  598. /// New postings created by this envelope.
  599. pub creates: Vec<NewPosting>,
  600. /// Account version pins for optimistic concurrency.
  601. pub account_snapshots: Vec<AccountSnapshotId>,
  602. /// Book this envelope belongs to.
  603. pub book: BookId,
  604. /// Fixed-width secondary identifiers.
  605. pub user_data: UserData,
  606. /// Free-form key-value metadata.
  607. pub metadata: Metadata,
  608. }
  609. impl Envelope {
  610. /// Posting ids consumed (spent) by this envelope.
  611. pub fn consumes(&self) -> &[PostingId] {
  612. &self.consumes
  613. }
  614. /// New postings created by this envelope.
  615. pub fn creates(&self) -> &[NewPosting] {
  616. &self.creates
  617. }
  618. /// Account version pins for optimistic concurrency.
  619. pub fn account_snapshots(&self) -> &[AccountSnapshotId] {
  620. &self.account_snapshots
  621. }
  622. /// Book this envelope belongs to.
  623. pub fn book(&self) -> BookId {
  624. self.book
  625. }
  626. /// Fixed-width secondary identifiers.
  627. pub fn user_data(&self) -> &UserData {
  628. &self.user_data
  629. }
  630. /// Free-form key-value metadata.
  631. pub fn metadata(&self) -> &Metadata {
  632. &self.metadata
  633. }
  634. /// Deduplicated, sorted list of account references in the created postings.
  635. pub fn referenced_accounts(&self) -> Vec<AccountId> {
  636. let mut ids: Vec<AccountId> = self.creates.iter().map(|p| p.owner).collect();
  637. ids.sort();
  638. ids.dedup();
  639. ids
  640. }
  641. /// Set account snapshots.
  642. pub fn set_account_snapshots(&mut self, snapshots: Vec<AccountSnapshotId>) {
  643. self.account_snapshots = snapshots;
  644. }
  645. }
  646. // ---------------------------------------------------------------------------
  647. // EnvelopeBuilder
  648. // ---------------------------------------------------------------------------
  649. /// Builder for constructing [`Envelope`] values.
  650. #[derive(Default)]
  651. pub struct EnvelopeBuilder {
  652. envelope: Envelope,
  653. }
  654. impl EnvelopeBuilder {
  655. /// Create an empty builder.
  656. pub fn new() -> Self {
  657. Self::default()
  658. }
  659. /// Set the posting ids to consume.
  660. pub fn consumes(mut self, ids: Vec<PostingId>) -> Self {
  661. self.envelope.consumes = ids;
  662. self
  663. }
  664. /// Set the new postings to create.
  665. pub fn creates(mut self, postings: Vec<NewPosting>) -> Self {
  666. self.envelope.creates = postings;
  667. self
  668. }
  669. /// Set the book.
  670. pub fn book(mut self, book: BookId) -> Self {
  671. self.envelope.book = book;
  672. self
  673. }
  674. /// Set the fixed-width secondary identifiers.
  675. pub fn user_data(mut self, user_data: UserData) -> Self {
  676. self.envelope.user_data = user_data;
  677. self
  678. }
  679. /// Set the account version pins.
  680. pub fn account_snapshots(mut self, snapshots: Vec<AccountSnapshotId>) -> Self {
  681. self.envelope.account_snapshots = snapshots;
  682. self
  683. }
  684. /// Set the free-form metadata.
  685. pub fn metadata(mut self, metadata: Metadata) -> Self {
  686. self.envelope.metadata = metadata;
  687. self
  688. }
  689. /// Consume the builder and return the [`Envelope`].
  690. pub fn build(self) -> Envelope {
  691. self.envelope
  692. }
  693. }
  694. // ---------------------------------------------------------------------------
  695. // Account
  696. // ---------------------------------------------------------------------------
  697. /// Controls how much an account can spend beyond its posting-backed balance.
  698. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
  699. pub enum AccountPolicy {
  700. /// Balance must stay >= 0.
  701. NoOverdraft,
  702. /// Balance must stay >= `floor` (floor < 0).
  703. CappedOverdraft {
  704. /// Minimum allowed balance (must be negative).
  705. floor: Cent,
  706. },
  707. /// No floor — the account can go arbitrarily negative.
  708. UncappedOverdraft,
  709. /// Fees, settlement, market-making, minting. No balance constraints.
  710. SystemAccount,
  711. /// Boundary account representing value entering/leaving the ledger; holds
  712. /// the offset (negative) side of deposits.
  713. ExternalAccount,
  714. }
  715. bitflags::bitflags! {
  716. /// Lifecycle and user-defined flags for an [`Account`].
  717. ///
  718. /// Bits 0–7 are reserved for system flags. Bits 8–31 are available for
  719. /// user-defined flags, which can be used with [`BookPolicy::allowed_flags`]
  720. /// to scope which accounts may participate in a book.
  721. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
  722. pub struct AccountFlags: u32 {
  723. /// Account may not be the source or destination of any transfer.
  724. const FROZEN = 1 << 0;
  725. /// Terminal — no further activity.
  726. const CLOSED = 1 << 1;
  727. /// Holding account for an inflight (authorize/confirm/void) transaction.
  728. /// Parks funds between authorize and settlement; closed once drained.
  729. const INFLIGHT = 1 << 2;
  730. // Bits 3–7: reserved for future system flags.
  731. // Bits 8–31: user-defined.
  732. /// User-defined flag 0.
  733. const USER_0 = 1 << 8;
  734. /// User-defined flag 1.
  735. const USER_1 = 1 << 9;
  736. /// User-defined flag 2.
  737. const USER_2 = 1 << 10;
  738. /// User-defined flag 3.
  739. const USER_3 = 1 << 11;
  740. /// User-defined flag 4.
  741. const USER_4 = 1 << 12;
  742. /// User-defined flag 5.
  743. const USER_5 = 1 << 13;
  744. /// User-defined flag 6.
  745. const USER_6 = 1 << 14;
  746. /// User-defined flag 7.
  747. const USER_7 = 1 << 15;
  748. }
  749. }
  750. /// A registered entity that must exist before it can transact.
  751. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
  752. pub struct Account {
  753. /// Stable identity for this account (base account plus subaccount).
  754. pub id: AccountId,
  755. /// Monotonically increasing version, starts at 1 on creation.
  756. pub version: u64,
  757. /// Overdraft / balance policy.
  758. pub policy: AccountPolicy,
  759. /// Lifecycle flags (frozen, closed).
  760. pub flags: AccountFlags,
  761. /// Book this entity belongs to.
  762. pub book: BookId,
  763. /// Fixed-width secondary identifiers.
  764. pub user_data: UserData,
  765. /// Free-form key-value metadata.
  766. pub metadata: Metadata,
  767. }
  768. impl Account {
  769. /// Create a version-1 main-subaccount account with the given policy: no flags,
  770. /// the default book, and empty user data / metadata. Convenience for the common
  771. /// case — set the other fields explicitly when you need them.
  772. pub fn new(id: AccountId, policy: AccountPolicy) -> Self {
  773. Self::new_ref(id, policy)
  774. }
  775. /// Like [`Account::new`] but for a specific subaccount reference.
  776. pub fn new_ref(id: AccountId, policy: AccountPolicy) -> Self {
  777. Self {
  778. id,
  779. version: 1,
  780. policy,
  781. flags: AccountFlags::empty(),
  782. book: DEFAULT_BOOK,
  783. user_data: UserData::default(),
  784. metadata: Metadata::new(),
  785. }
  786. }
  787. /// Returns `true` if the account has the `FROZEN` flag set.
  788. pub fn is_frozen(&self) -> bool {
  789. self.flags.contains(AccountFlags::FROZEN)
  790. }
  791. /// Returns `true` if the account has the `CLOSED` flag set.
  792. pub fn is_closed(&self) -> bool {
  793. self.flags.contains(AccountFlags::CLOSED)
  794. }
  795. }
  796. // ---------------------------------------------------------------------------
  797. // Receipt
  798. // ---------------------------------------------------------------------------
  799. /// Confirmation of a committed transfer, carrying its content-addressed id.
  800. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
  801. pub struct Receipt {
  802. /// Content-addressed id of the committed transfer.
  803. pub transfer_id: EnvelopeId,
  804. }
  805. // ---------------------------------------------------------------------------
  806. // Transfer — intent-based API
  807. // ---------------------------------------------------------------------------
  808. /// A single movement within a transfer: move value from one account to another.
  809. ///
  810. /// Every operation (pay, deposit, withdraw) is expressed as one or more
  811. /// movements. The resolve step aggregates net debits per account and selects
  812. /// postings only for accounts with a positive net debit.
  813. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
  814. pub struct Movement {
  815. /// Account (subaccount) being debited.
  816. pub from: AccountId,
  817. /// Account (subaccount) being credited.
  818. pub to: AccountId,
  819. /// Asset to transfer.
  820. pub asset: AssetId,
  821. /// Amount to transfer (may be negative for offset postings).
  822. pub amount: Cent,
  823. }
  824. /// A transfer intent — one or more movements to execute atomically.
  825. ///
  826. /// The saga pipeline resolves movements into concrete postings ([`Envelope`])
  827. /// during execution. Callers express *what* should happen, not *which postings*
  828. /// to consume.
  829. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
  830. pub struct Transfer {
  831. /// Movements to execute atomically.
  832. pub movements: Vec<Movement>,
  833. /// Book this entity belongs to.
  834. pub book: BookId,
  835. /// Fixed-width secondary identifiers.
  836. pub user_data: UserData,
  837. /// Free-form key-value metadata.
  838. pub metadata: Metadata,
  839. }
  840. /// Builder for constructing [`Transfer`] values.
  841. #[derive(Default)]
  842. pub struct TransferBuilder {
  843. transfer: Transfer,
  844. }
  845. impl TransferBuilder {
  846. /// Create an empty builder.
  847. pub fn new() -> Self {
  848. Self::default()
  849. }
  850. /// Add a raw movement between main subaccounts.
  851. pub fn movement(self, from: AccountId, to: AccountId, asset: AssetId, amount: Cent) -> Self {
  852. self.movement_ref(from, to, asset, amount)
  853. }
  854. /// Add a raw movement between specific subaccounts.
  855. pub fn movement_ref(
  856. mut self,
  857. from: AccountId,
  858. to: AccountId,
  859. asset: AssetId,
  860. amount: Cent,
  861. ) -> Self {
  862. self.transfer.movements.push(Movement {
  863. from,
  864. to,
  865. asset,
  866. amount,
  867. });
  868. self
  869. }
  870. /// Add a pay movement between main subaccounts.
  871. pub fn pay(self, from: AccountId, to: AccountId, asset: AssetId, amount: Cent) -> Self {
  872. self.movement(from, to, asset, amount)
  873. }
  874. /// Add a pay movement between two specific subaccounts. See
  875. /// [`movement_ref`](Self::movement_ref).
  876. pub fn pay_ref(self, from: AccountId, to: AccountId, asset: AssetId, amount: Cent) -> Self {
  877. self.movement_ref(from, to, asset, amount)
  878. }
  879. /// Add a deposit: creates an offset posting on the external account and
  880. /// credits the target account. Pushes two movements whose net debit on the
  881. /// external account is zero.
  882. pub fn deposit(
  883. self,
  884. to: AccountId,
  885. asset: AssetId,
  886. amount: Cent,
  887. external: AccountId,
  888. ) -> Result<Self, OverflowError> {
  889. let neg = amount.checked_neg()?;
  890. Ok(self
  891. .movement(external, external, asset, neg)
  892. .movement(external, to, asset, amount))
  893. }
  894. /// Add a withdrawal: move value from an account to an external destination.
  895. pub fn withdraw(
  896. self,
  897. from: AccountId,
  898. asset: AssetId,
  899. amount: Cent,
  900. external: AccountId,
  901. ) -> Self {
  902. self.movement(from, external, asset, amount)
  903. }
  904. /// Set the book.
  905. pub fn book(mut self, book: BookId) -> Self {
  906. self.transfer.book = book;
  907. self
  908. }
  909. /// Set the fixed-width secondary identifiers.
  910. pub fn user_data(mut self, user_data: UserData) -> Self {
  911. self.transfer.user_data = user_data;
  912. self
  913. }
  914. /// Set the free-form metadata.
  915. pub fn metadata(mut self, metadata: Metadata) -> Self {
  916. self.transfer.metadata = metadata;
  917. self
  918. }
  919. /// Consume the builder and return the [`Transfer`].
  920. pub fn build(self) -> Transfer {
  921. self.transfer
  922. }
  923. }
  924. // ---------------------------------------------------------------------------
  925. // ToBytes implementations
  926. // ---------------------------------------------------------------------------
  927. impl ToBytes for AccountId {
  928. fn to_bytes(&self) -> Vec<u8> {
  929. // Base id then subaccount, both big-endian, so the subaccount is folded
  930. // into every content hash (envelope ids, posting ids, snapshots).
  931. let mut buf = Vec::with_capacity(16);
  932. buf.extend_from_slice(&self.id.to_be_bytes());
  933. buf.extend_from_slice(&self.sub.to_be_bytes());
  934. buf
  935. }
  936. }
  937. impl ToBytes for AccountSnapshotId {
  938. fn to_bytes(&self) -> Vec<u8> {
  939. let mut buf = Vec::with_capacity(48);
  940. buf.extend_from_slice(&self.account.to_bytes());
  941. buf.extend_from_slice(&self.snapshot_id);
  942. buf
  943. }
  944. }
  945. impl ToBytes for AssetId {
  946. fn to_bytes(&self) -> Vec<u8> {
  947. self.0.to_be_bytes().to_vec()
  948. }
  949. }
  950. impl ToBytes for EnvelopeId {
  951. fn to_bytes(&self) -> Vec<u8> {
  952. self.0.to_vec()
  953. }
  954. }
  955. impl ToBytes for PostingId {
  956. fn to_bytes(&self) -> Vec<u8> {
  957. let mut buf = Vec::with_capacity(34);
  958. buf.extend_from_slice(&self.transfer.0);
  959. write_u16(&mut buf, self.index);
  960. buf
  961. }
  962. }
  963. impl ToBytes for UserData {
  964. fn to_bytes(&self) -> Vec<u8> {
  965. let mut buf = Vec::with_capacity(28);
  966. write_u128(&mut buf, self.d128);
  967. write_u64(&mut buf, self.d64);
  968. write_u32(&mut buf, self.d32);
  969. buf
  970. }
  971. }
  972. impl ToBytes for AccountPolicy {
  973. fn to_bytes(&self) -> Vec<u8> {
  974. let mut buf = Vec::with_capacity(9);
  975. match self {
  976. Self::NoOverdraft => buf.push(0),
  977. Self::CappedOverdraft { floor } => {
  978. buf.push(1);
  979. buf.extend(floor.to_bytes());
  980. }
  981. Self::UncappedOverdraft => buf.push(2),
  982. Self::SystemAccount => buf.push(3),
  983. Self::ExternalAccount => buf.push(4),
  984. }
  985. buf
  986. }
  987. }
  988. impl ToBytes for AccountFlags {
  989. fn to_bytes(&self) -> Vec<u8> {
  990. self.bits().to_be_bytes().to_vec()
  991. }
  992. }
  993. impl ToBytes for BookId {
  994. fn to_bytes(&self) -> Vec<u8> {
  995. self.0.to_be_bytes().to_vec()
  996. }
  997. }
  998. impl ToBytes for NewPosting {
  999. fn to_bytes(&self) -> Vec<u8> {
  1000. let mut buf = Vec::new();
  1001. buf.extend(self.owner.to_bytes());
  1002. buf.extend_from_slice(&self.asset.0.to_be_bytes());
  1003. buf.extend(self.value.to_bytes());
  1004. match &self.payer {
  1005. Some(p) => {
  1006. buf.push(1);
  1007. buf.extend(p.to_bytes());
  1008. }
  1009. None => buf.push(0),
  1010. }
  1011. buf
  1012. }
  1013. }
  1014. impl ToBytes for Posting {
  1015. fn to_bytes(&self) -> Vec<u8> {
  1016. let mut buf = Vec::new();
  1017. buf.extend(self.id.to_bytes());
  1018. buf.extend(self.owner.to_bytes());
  1019. buf.extend_from_slice(&self.asset.0.to_be_bytes());
  1020. buf.extend(self.value.to_bytes());
  1021. buf.push(match self.status {
  1022. PostingStatus::Active => 0,
  1023. PostingStatus::PendingInactive => 1,
  1024. PostingStatus::Inactive => 2,
  1025. });
  1026. buf
  1027. }
  1028. }
  1029. impl ToBytes for Envelope {
  1030. fn to_bytes(&self) -> Vec<u8> {
  1031. let mut buf = Vec::new();
  1032. buf.push(CANONICAL_VERSION);
  1033. write_u32(&mut buf, self.consumes.len() as u32);
  1034. for pid in &self.consumes {
  1035. buf.extend(pid.to_bytes());
  1036. }
  1037. write_u32(&mut buf, self.creates.len() as u32);
  1038. for np in &self.creates {
  1039. buf.extend(np.to_bytes());
  1040. }
  1041. write_u32(&mut buf, self.account_snapshots.len() as u32);
  1042. for snap in &self.account_snapshots {
  1043. buf.extend(snap.to_bytes());
  1044. }
  1045. buf.extend(self.book.to_bytes());
  1046. buf.extend(self.user_data.to_bytes());
  1047. write_u32(&mut buf, self.metadata.len() as u32);
  1048. for (key, value) in &self.metadata {
  1049. let key_bytes = key.as_bytes();
  1050. write_u32(&mut buf, key_bytes.len() as u32);
  1051. buf.extend_from_slice(key_bytes);
  1052. write_u32(&mut buf, value.len() as u32);
  1053. buf.extend_from_slice(value);
  1054. }
  1055. buf
  1056. }
  1057. }
  1058. impl ToBytes for Account {
  1059. fn to_bytes(&self) -> Vec<u8> {
  1060. let mut buf = Vec::new();
  1061. buf.push(CANONICAL_VERSION);
  1062. buf.extend(self.id.to_bytes());
  1063. write_u64(&mut buf, self.version);
  1064. buf.extend(self.policy.to_bytes());
  1065. buf.extend(self.flags.to_bytes());
  1066. buf.extend(self.book.to_bytes());
  1067. buf.extend(self.user_data.to_bytes());
  1068. write_u32(&mut buf, self.metadata.len() as u32);
  1069. for (key, value) in &self.metadata {
  1070. let key_bytes = key.as_bytes();
  1071. write_u32(&mut buf, key_bytes.len() as u32);
  1072. buf.extend_from_slice(key_bytes);
  1073. write_u32(&mut buf, value.len() as u32);
  1074. buf.extend_from_slice(value);
  1075. }
  1076. buf
  1077. }
  1078. }
  1079. impl ToBytes for Receipt {
  1080. fn to_bytes(&self) -> Vec<u8> {
  1081. self.transfer_id.0.to_vec()
  1082. }
  1083. }
  1084. #[cfg(test)]
  1085. mod account_id_tests {
  1086. use super::*;
  1087. use std::str::FromStr;
  1088. #[test]
  1089. fn code_structure() {
  1090. let s = AccountId::with_sub(5, 7).to_string();
  1091. // 2 check digits + 26-char base-36 body. No country code.
  1092. assert_eq!(s.len(), 28);
  1093. assert!(s[0..2].bytes().all(|b| b.is_ascii_digit()));
  1094. // The body is Feistel-permuted, so it does NOT expose the raw legs the
  1095. // way an unmixed base-36 rendering (all zeros then "5"/"7") would.
  1096. assert_ne!(&s[2..], "00000000000050000000000007");
  1097. }
  1098. #[test]
  1099. fn code_round_trips() {
  1100. for acc in [
  1101. AccountId::new(0),
  1102. AccountId::new(100),
  1103. AccountId::with_sub(5, 7),
  1104. // High-bit subaccount: exercises the u64-bit-pattern reinterpretation.
  1105. AccountId::with_sub(1, -1),
  1106. AccountId::with_sub(i64::MAX, i64::MIN),
  1107. ] {
  1108. let s = acc.to_string();
  1109. assert_eq!(AccountId::from_str(&s).unwrap(), acc, "round-trip {s}");
  1110. }
  1111. }
  1112. #[test]
  1113. fn parses_a_fixed_vector() {
  1114. // A hardcoded, checksum-valid code (under DEFAULT_ID_SEED) pins the
  1115. // exact encoding, permutation, and checksum, so an accidental change to
  1116. // any of them is caught by a failing parse.
  1117. let code = "123PER2Q81K52QL1HA26CYE1IZH5";
  1118. let expected = AccountId::with_sub(987654321, 12345);
  1119. assert_eq!(AccountId::from_str(code).unwrap(), expected);
  1120. // The grouped (spaced, lower-cased) form parses to the same value.
  1121. assert_eq!(
  1122. AccountId::from_str("123p er2q 81k5 2ql1 ha26 cye1 izh5").unwrap(),
  1123. expected
  1124. );
  1125. // Display reproduces the exact machine form.
  1126. assert_eq!(expected.to_string(), code);
  1127. }
  1128. #[test]
  1129. fn feistel_is_invertible_across_seeds() {
  1130. for &seed in &[0u64, 1, DEFAULT_ID_SEED, u64::MAX] {
  1131. for &(l, r) in &[(0u64, 0u64), (5, 7), (u64::MAX, 1), (42, u64::MAX)] {
  1132. let (el, er) = feistel(l, r, seed);
  1133. assert_eq!(feistel_inv(el, er, seed), (l, r), "seed={seed} l={l} r={r}");
  1134. }
  1135. }
  1136. }
  1137. #[test]
  1138. fn obfuscation_hides_structure() {
  1139. // The default seed is in force.
  1140. assert_eq!(id_seed(), DEFAULT_ID_SEED);
  1141. // Sequential base ids do not produce visibly related codes (avalanche).
  1142. let a = AccountId::new(100).to_string();
  1143. let b = AccountId::new(101).to_string();
  1144. let shared = a.bytes().zip(b.bytes()).take_while(|(x, y)| x == y).count();
  1145. assert!(shared < 4, "codes share too long a prefix: {a} vs {b}");
  1146. // A base account and its subaccount are likewise not obviously related.
  1147. let main = AccountId::new(100).to_string();
  1148. let sub = AccountId::with_sub(100, 1).to_string();
  1149. assert_ne!(main, sub);
  1150. }
  1151. #[test]
  1152. fn grouped_format_groups_by_four_and_re_parses() {
  1153. let acc = AccountId::with_sub(5, 7);
  1154. let grouped = acc.to_grouped();
  1155. assert!(grouped.contains(' '));
  1156. assert!(grouped.split(' ').all(|g| g.len() <= 4));
  1157. // Grouped format (with spaces) and lower case both parse back.
  1158. assert_eq!(AccountId::from_str(&grouped).unwrap(), acc);
  1159. assert_eq!(AccountId::from_str(&grouped.to_lowercase()).unwrap(), acc);
  1160. }
  1161. #[test]
  1162. fn parses_with_spaces_or_dashes_for_url_safety() {
  1163. let acc = AccountId::with_sub(987654321, 12345);
  1164. let machine = acc.to_string(); // 28 chars, no separators (URL-safe)
  1165. // The same code grouped with spaces (display) or dashes (URL-safe
  1166. // separator) parses back to the same id, as does a mixed/irregular form.
  1167. let spaced = acc.to_grouped();
  1168. let dashed = spaced.replace(' ', "-");
  1169. let mixed = format!("{}-{} {}", &machine[0..4], &machine[4..20], &machine[20..]);
  1170. for s in [&machine, &spaced, &dashed, &mixed] {
  1171. assert_eq!(AccountId::from_str(s).unwrap(), acc, "parse {s}");
  1172. }
  1173. }
  1174. #[test]
  1175. fn from_str_rejects_bad_checksum_and_junk() {
  1176. let good = AccountId::with_sub(5, 7).to_string();
  1177. assert!(AccountId::from_str(&good).is_ok());
  1178. // A helper to overwrite one character while keeping the length.
  1179. let with_char_at = |i: usize, c: char| {
  1180. let mut v: Vec<char> = good.chars().collect();
  1181. v[i] = c;
  1182. v.into_iter().collect::<String>()
  1183. };
  1184. // Flip the last body digit: still base-36 and right length, but the
  1185. // checksum no longer matches, so it is rejected.
  1186. let last = good.len() - 1;
  1187. let flipped = with_char_at(last, if good.ends_with('8') { '9' } else { '8' });
  1188. assert!(AccountId::from_str(&flipped).is_err(), "bad checksum");
  1189. // Structurally malformed inputs are all rejected.
  1190. assert!(AccountId::from_str("").is_err(), "empty");
  1191. assert!(AccountId::from_str("not-a-code").is_err(), "junk");
  1192. assert!(AccountId::from_str(&good[..27]).is_err(), "too short");
  1193. assert!(
  1194. AccountId::from_str(&format!("{good}0")).is_err(),
  1195. "too long"
  1196. );
  1197. // A check digit that is not a digit.
  1198. assert!(
  1199. AccountId::from_str(&with_char_at(0, 'A')).is_err(),
  1200. "alpha check"
  1201. );
  1202. // A non-base-36 character in the body (survives space/dash stripping).
  1203. assert!(
  1204. AccountId::from_str(&with_char_at(5, '*')).is_err(),
  1205. "non-base36 body"
  1206. );
  1207. }
  1208. }