| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203 |
- //! Identifier newtypes for the ledger domain.
- //!
- //! Each id is a thin wrapper over an integer or byte array with its own
- //! `Debug`, constructors, and (where minted) a snowflake-backed `Default`.
- use crate::autoid::AutoId;
- use serde::{Deserialize, Serialize};
- use std::fmt;
- // ---------------------------------------------------------------------------
- // Identifiers
- // ---------------------------------------------------------------------------
- /// Stable account identity. Used in all public APIs.
- ///
- /// An account is a base `id` plus a `subaccount`. `sub = 0` is the main account
- /// (the default when subaccounts are not used); a non-zero `sub` is a
- /// subaccount of the same base id. Each `(id, sub)` is a full account record
- /// with its own flags and lifecycle. See ADR-0012 and ADR-0015.
- ///
- /// Both legs are stored as `i64`, and they hash and persist as a full `i64`.
- /// The IBAN-style string form ([`Display`](fmt::Display) /
- /// [`FromStr`](std::str::FromStr)) encodes the low `ID_BITS` of `id` and the
- /// low `SUB_BITS` of `sub` alone. A 63-bit snowflake never sets the sign bit.
- /// That is what lets the code fit in a fixed 20 characters. A value outside
- /// those ranges still hashes, persists and compares correctly, and it does not
- /// round-trip through the string form.
- #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
- pub struct AccountId {
- /// Base account id (a 63-bit snowflake; the sign bit is always 0).
- pub id: i64,
- /// Subaccount id; `0` is the main account. The string form encodes the low
- /// [`SUB_BITS`](crate::SUB_BITS) bits, so a subaccount id must fit in that
- /// range to round-trip.
- pub sub: i64,
- }
- /// Pairs an [`AccountId`] with a snapshot hash, which is the double-SHA256 of
- /// the state of that account at a point in time. Stored on
- /// [`Transfer`](crate::Transfer), to record the account versions a transfer ran
- /// against. An internal type: the public API uses [`AccountId`].
- #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
- pub struct AccountSnapshotId {
- /// The account (subaccount) this snapshot belongs to.
- pub account: AccountId,
- /// Double-SHA256 of the state of the account when the snapshot was taken.
- pub snapshot_id: [u8; 32],
- }
- /// Identifies an asset (USD, EUR, BTC, …). Conservation is enforced per asset,
- /// so each asset is an independent conservation boundary.
- #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
- pub struct AssetId(pub u32);
- /// Content-addressed transfer identifier: the double-SHA256 of the canonical
- /// serialization. That makes the id both the idempotency key and the
- /// tamper-evidence artifact.
- #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
- pub struct TransferId(pub [u8; 32]);
- /// Uniquely identifies a posting within the ledger. The `(transfer, index)`
- /// pair ties every posting back to the transfer that created it, which is what
- /// the provenance graph is built on.
- #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
- pub struct PostingId {
- /// The transfer that created this posting.
- pub transfer: TransferId,
- /// Zero-based position among the postings the transfer created.
- pub index: u16,
- }
- /// Identifies a book, which is a named scope for transfers.
- #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
- pub struct BookId(pub i64);
- // ---------------------------------------------------------------------------
- // Debug impls for identifiers
- // ---------------------------------------------------------------------------
- impl fmt::Debug for AccountId {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- if self.sub == 0 {
- write!(f, "AccountId({})", self.id)
- } else {
- write!(f, "AccountId({}.{})", self.id, self.sub)
- }
- }
- }
- impl fmt::Debug for AssetId {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- write!(f, "AssetId({:#010x})", self.0)
- }
- }
- impl fmt::Debug for TransferId {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- write!(f, "TransferId({})", hex(&self.0))
- }
- }
- impl fmt::Debug for PostingId {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- f.debug_struct("PostingId")
- .field("transfer", &self.transfer)
- .field("index", &self.index)
- .finish()
- }
- }
- impl fmt::Debug for BookId {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- write!(f, "BookId({})", self.0)
- }
- }
- fn hex(bytes: &[u8]) -> String {
- bytes.iter().map(|b| format!("{b:02x}")).collect()
- }
- // ---------------------------------------------------------------------------
- // Identifier constructors
- // ---------------------------------------------------------------------------
- impl Default for AccountId {
- fn default() -> Self {
- // Process-global generator: a per-thread one could mint the same id on
- // two threads within a millisecond, yielding duplicate account ids.
- static GEN: AutoId = AutoId::new();
- Self {
- id: GEN.next(),
- sub: 0,
- }
- }
- }
- impl AccountId {
- /// Create the main account (`sub = 0`) for a base `id`.
- pub const fn new(id: i64) -> Self {
- Self { id, sub: 0 }
- }
- /// Create a specific subaccount of a base `id`.
- pub const fn with_sub(id: i64, sub: i64) -> Self {
- Self { id, sub }
- }
- /// Return the main account of this id (`sub` set to `0`).
- pub const fn base(&self) -> Self {
- Self {
- id: self.id,
- sub: 0,
- }
- }
- /// Whether this is the main account (`sub == 0`).
- pub const fn is_main(&self) -> bool {
- self.sub == 0
- }
- }
- impl From<AccountSnapshotId> for AccountId {
- fn from(snap: AccountSnapshotId) -> Self {
- snap.account
- }
- }
- impl AssetId {
- /// Create an `AssetId` from a `u32`.
- pub const fn new(id: u32) -> Self {
- Self(id)
- }
- }
- /// The implicit book a transfer takes when it names none. Fixed, so that two
- /// otherwise-identical transfers hash to the same [`TransferId`]. A random
- /// default would break content-addressed idempotency.
- pub const DEFAULT_BOOK: BookId = BookId(0);
- impl Default for BookId {
- /// Deterministic: returns [`DEFAULT_BOOK`]. Use [`BookId::generate`] to
- /// mint a fresh unique id for a real book.
- fn default() -> Self {
- DEFAULT_BOOK
- }
- }
- impl BookId {
- /// Create a `BookId` from an `i64`.
- pub const fn new(id: i64) -> Self {
- Self(id)
- }
- /// Mint a fresh, process-unique book id. This is not stable across calls,
- /// where [`Default`] is. Use it for a new [`Book`](crate::Book), and never
- /// for the implicit book of a transfer.
- pub fn generate() -> Self {
- // Process-global so the "process-unique" contract holds across threads;
- // a per-thread generator can repeat an id on another thread.
- static GEN: AutoId = AutoId::new();
- Self(GEN.next())
- }
- }
|