ids.rs 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. //! Identifier newtypes for the ledger domain.
  2. //!
  3. //! Each id is a thin wrapper over an integer or byte array with its own
  4. //! `Debug`, constructors, and (where minted) a snowflake-backed `Default`.
  5. use crate::autoid::AutoId;
  6. use serde::{Deserialize, Serialize};
  7. use std::fmt;
  8. // ---------------------------------------------------------------------------
  9. // Identifiers
  10. // ---------------------------------------------------------------------------
  11. /// Stable account identity. Used in all public APIs.
  12. ///
  13. /// An account is a base `id` plus a `subaccount`. `sub = 0` is the main account
  14. /// (the default when subaccounts are not used); a non-zero `sub` is a
  15. /// subaccount of the same base id. Each `(id, sub)` is a full account record
  16. /// with its own flags and lifecycle. See ADR-0012 and ADR-0015.
  17. ///
  18. /// Both legs are stored as `i64`, and they hash and persist as a full `i64`.
  19. /// The IBAN-style string form ([`Display`](fmt::Display) /
  20. /// [`FromStr`](std::str::FromStr)) encodes the low `ID_BITS` of `id` and the
  21. /// low `SUB_BITS` of `sub` alone. A 63-bit snowflake never sets the sign bit.
  22. /// That is what lets the code fit in a fixed 20 characters. A value outside
  23. /// those ranges still hashes, persists and compares correctly, and it does not
  24. /// round-trip through the string form.
  25. #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
  26. pub struct AccountId {
  27. /// Base account id (a 63-bit snowflake; the sign bit is always 0).
  28. pub id: i64,
  29. /// Subaccount id; `0` is the main account. The string form encodes the low
  30. /// [`SUB_BITS`](crate::SUB_BITS) bits, so a subaccount id must fit in that
  31. /// range to round-trip.
  32. pub sub: i64,
  33. }
  34. /// Pairs an [`AccountId`] with a snapshot hash, which is the double-SHA256 of
  35. /// the state of that account at a point in time. Stored on
  36. /// [`Transfer`](crate::Transfer), to record the account versions a transfer ran
  37. /// against. An internal type: the public API uses [`AccountId`].
  38. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
  39. pub struct AccountSnapshotId {
  40. /// The account (subaccount) this snapshot belongs to.
  41. pub account: AccountId,
  42. /// Double-SHA256 of the state of the account when the snapshot was taken.
  43. pub snapshot_id: [u8; 32],
  44. }
  45. /// Identifies an asset (USD, EUR, BTC, …). Conservation is enforced per asset,
  46. /// so each asset is an independent conservation boundary.
  47. #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
  48. pub struct AssetId(pub u32);
  49. /// Content-addressed transfer identifier: the double-SHA256 of the canonical
  50. /// serialization. That makes the id both the idempotency key and the
  51. /// tamper-evidence artifact.
  52. #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
  53. pub struct TransferId(pub [u8; 32]);
  54. /// Uniquely identifies a posting within the ledger. The `(transfer, index)`
  55. /// pair ties every posting back to the transfer that created it, which is what
  56. /// the provenance graph is built on.
  57. #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
  58. pub struct PostingId {
  59. /// The transfer that created this posting.
  60. pub transfer: TransferId,
  61. /// Zero-based position among the postings the transfer created.
  62. pub index: u16,
  63. }
  64. /// Identifies a book, which is a named scope for transfers.
  65. #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
  66. pub struct BookId(pub i64);
  67. // ---------------------------------------------------------------------------
  68. // Debug impls for identifiers
  69. // ---------------------------------------------------------------------------
  70. impl fmt::Debug for AccountId {
  71. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  72. if self.sub == 0 {
  73. write!(f, "AccountId({})", self.id)
  74. } else {
  75. write!(f, "AccountId({}.{})", self.id, self.sub)
  76. }
  77. }
  78. }
  79. impl fmt::Debug for AssetId {
  80. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  81. write!(f, "AssetId({:#010x})", self.0)
  82. }
  83. }
  84. impl fmt::Debug for TransferId {
  85. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  86. write!(f, "TransferId({})", hex(&self.0))
  87. }
  88. }
  89. impl fmt::Debug for PostingId {
  90. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  91. f.debug_struct("PostingId")
  92. .field("transfer", &self.transfer)
  93. .field("index", &self.index)
  94. .finish()
  95. }
  96. }
  97. impl fmt::Debug for BookId {
  98. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  99. write!(f, "BookId({})", self.0)
  100. }
  101. }
  102. fn hex(bytes: &[u8]) -> String {
  103. bytes.iter().map(|b| format!("{b:02x}")).collect()
  104. }
  105. // ---------------------------------------------------------------------------
  106. // Identifier constructors
  107. // ---------------------------------------------------------------------------
  108. impl Default for AccountId {
  109. fn default() -> Self {
  110. // Process-global generator: a per-thread one could mint the same id on
  111. // two threads within a millisecond, yielding duplicate account ids.
  112. static GEN: AutoId = AutoId::new();
  113. Self {
  114. id: GEN.next(),
  115. sub: 0,
  116. }
  117. }
  118. }
  119. impl AccountId {
  120. /// Create the main account (`sub = 0`) for a base `id`.
  121. pub const fn new(id: i64) -> Self {
  122. Self { id, sub: 0 }
  123. }
  124. /// Create a specific subaccount of a base `id`.
  125. pub const fn with_sub(id: i64, sub: i64) -> Self {
  126. Self { id, sub }
  127. }
  128. /// Return the main account of this id (`sub` set to `0`).
  129. pub const fn base(&self) -> Self {
  130. Self {
  131. id: self.id,
  132. sub: 0,
  133. }
  134. }
  135. /// Whether this is the main account (`sub == 0`).
  136. pub const fn is_main(&self) -> bool {
  137. self.sub == 0
  138. }
  139. }
  140. impl From<AccountSnapshotId> for AccountId {
  141. fn from(snap: AccountSnapshotId) -> Self {
  142. snap.account
  143. }
  144. }
  145. impl AssetId {
  146. /// Create an `AssetId` from a `u32`.
  147. pub const fn new(id: u32) -> Self {
  148. Self(id)
  149. }
  150. }
  151. /// The implicit book a transfer takes when it names none. Fixed, so that two
  152. /// otherwise-identical transfers hash to the same [`TransferId`]. A random
  153. /// default would break content-addressed idempotency.
  154. pub const DEFAULT_BOOK: BookId = BookId(0);
  155. impl Default for BookId {
  156. /// Deterministic: returns [`DEFAULT_BOOK`]. Use [`BookId::generate`] to
  157. /// mint a fresh unique id for a real book.
  158. fn default() -> Self {
  159. DEFAULT_BOOK
  160. }
  161. }
  162. impl BookId {
  163. /// Create a `BookId` from an `i64`.
  164. pub const fn new(id: i64) -> Self {
  165. Self(id)
  166. }
  167. /// Mint a fresh, process-unique book id. This is not stable across calls,
  168. /// where [`Default`] is. Use it for a new [`Book`](crate::Book), and never
  169. /// for the implicit book of a transfer.
  170. pub fn generate() -> Self {
  171. // Process-global so the "process-unique" contract holds across threads;
  172. // a per-thread generator can repeat an id on another thread.
  173. static GEN: AutoId = AutoId::new();
  174. Self(GEN.next())
  175. }
  176. }