Przeglądaj źródła

Head a journal entry with the caller's own reference

A transfer carried a label the dashboard threw away. Every entry was
headed by its content-address hash alone, so a reader could see that an
entry balanced without seeing what it was for. The reference is not an
application convention the dashboard would be guessing at: the library
reserves the key, TransferBuilder::reference writes it, and it is part
of the content address, so an entry is identified by it as much as by
its hash. An entry now leads with it and keeps the hash underneath as
the audit key, falling back to the hash as the headline when a caller
set no reference.

Two neighbouring fields were unread the same way. The value date is the
day an entry takes effect and changes its identity; the book is its
policy scope. Both show only when they carry something, so a ledger
that uses neither looks no busier than before.

A metadata value is caller-controlled bytes with no length limit, and
need not be text at all: the other reserved key holds CBOR. So a value
reaches the page as text only when it decodes as UTF-8 with no control
characters, and otherwise as its length with a hex sample behind the
hover. A reference that fails that test is still shown, as an ordinary
pair, because the stricter headline must not be a way for data to
disappear. Safety against markup in a reference rests on Tera
autoescaping a template named .html, which a test now pins rather than
leaving to assumption.

Envelope::reference reads the key back. It was public and its writer was
public, but a reader had to know to look the key up by hand. It returns
bytes, since a caller writing the metadata map directly is not held to
the UTF-8 the builder writes.

The demo seeder set no reference, which left the whole feature invisible
under --seed. Giving each seeded transfer one also demonstrates what the
key is for: a deposit consumes nothing, so two of the same amount to the
same account are byte-identical and the second is discarded as a replay
unless a reference separates them.
C 3 dni temu
rodzic
commit
84b91a42e4

+ 17 - 0
CHANGELOG.md

@@ -26,6 +26,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
 - `Ledger::get_postings(ids)` reads postings by id from the immutable record. A
 - `Ledger::get_postings(ids)` reads postings by id from the immutable record. A
   committed envelope stores consumed ids alone, so without it a reader could
   committed envelope stores consumed ids alone, so without it a reader could
   not recover the owner or the value of anything a transfer spent.
   not recover the owner or the value of anything a transfer spent.
+- `Envelope::reference()` reads the caller's reference out of the reserved
+  metadata key. The key was public and the writer was public, but nothing could
+  read one back without knowing to look the key up by hand. It returns bytes,
+  because a caller writing the metadata map directly is not held to the UTF-8
+  that `TransferBuilder::reference` writes.
 
 
 ### Fixed
 ### Fixed
 
 
@@ -44,6 +49,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
   dashboard is now a link to its own page; none of them were. The dashboard's
   dashboard is now a link to its own page; none of them were. The dashboard's
   transfer JSON changed shape with the view: `legs` and `consumes` give way to
   transfer JSON changed shape with the view: `legs` and `consumes` give way to
   per-asset `debits`, `credits` and totals.
   per-asset `debits`, `credits` and totals.
+- The dashboard headed every journal entry with its content-address hash and
+  nothing else, so a reader could not tell what an entry was for. A transfer
+  carries the caller's own label under the reserved reference key, and three
+  fields were going unread: the reference, the rest of the metadata map, and
+  the value date and book. An entry now leads with its reference and keeps the
+  hash underneath as its audit key. A metadata value is caller-controlled bytes
+  with no length limit and need not be text at all, the reserved `inflight` key
+  holding CBOR, so a value is shown as text only when it decodes as UTF-8 with
+  no control characters, and otherwise as its byte count with a hex sample
+  behind the hover. The demo seeder now gives every transfer a reference, which
+  is also what lets two deposits of the same amount to the same account be two
+  transfers rather than a replay.
 
 
 ## [0.4.0] - 2026-12-02
 ## [0.4.0] - 2026-12-02
 
 

+ 1 - 1
crates/kuatia-dashboard/README.md

@@ -52,7 +52,7 @@ format them using the decimals from `/api/assets`.
 | `GET /api/overview`     | Account count, transfer count, total issued per asset |
 | `GET /api/overview`     | Account count, transfer count, total issued per asset |
 | `GET /api/accounts`     | All accounts with policy, flags, and balances         |
 | `GET /api/accounts`     | All accounts with policy, flags, and balances         |
 | `GET /api/accounts/:id` | One account plus its postings and journal entries     |
 | `GET /api/accounts/:id` | One account plus its postings and journal entries     |
-| `GET /api/transfers`    | Recent transfers as journal entries, both sides        |
+| `GET /api/transfers`    | Recent transfers as journal entries, both sides, each with the caller's reference, metadata, value date and book |
 | `GET /api/events`       | The append-only ledger event log                      |
 | `GET /api/events`       | The append-only ledger event log                      |
 
 
 ## Configuration
 ## Configuration

+ 279 - 2
crates/kuatia-dashboard/src/data.rs

@@ -7,6 +7,7 @@
 use std::cmp::Reverse;
 use std::cmp::Reverse;
 use std::collections::HashMap;
 use std::collections::HashMap;
 use std::fmt;
 use std::fmt;
+use std::str;
 use std::sync::Arc;
 use std::sync::Arc;
 
 
 use axum::{
 use axum::{
@@ -17,7 +18,8 @@ use axum::{
 use kuatia::error::LedgerError;
 use kuatia::error::LedgerError;
 use kuatia::ledger::Ledger;
 use kuatia::ledger::Ledger;
 use kuatia_core::{
 use kuatia_core::{
-    Account, AccountId, Amount, Asset, AssetId, NewPosting, Posting, PostingId, PostingState,
+    Account, AccountId, Amount, Asset, AssetId, DEFAULT_BOOK, Envelope, NewPosting, Posting,
+    PostingId, PostingState, REFERENCE_KEY,
 };
 };
 use kuatia_storage::events::{LedgerEvent, LedgerEventKind};
 use kuatia_storage::events::{LedgerEvent, LedgerEventKind};
 use kuatia_storage::store::{TransferQuery, TransferRecord};
 use kuatia_storage::store::{TransferQuery, TransferRecord};
@@ -128,11 +130,48 @@ pub struct EntryAssetDto {
     pub balanced: bool,
     pub balanced: bool,
 }
 }
 
 
+/// A metadata value as far as it could be read. An enum rather than an
+/// optional string beside an optional hex, so "neither" cannot be expressed.
+#[derive(Debug, Serialize, PartialEq, Eq)]
+#[serde(rename_all = "snake_case")]
+pub enum MetadataValueDto {
+    /// Readable text.
+    Text(String),
+    /// Not text: its length, and a hex sample of its head.
+    Bytes {
+        /// Byte length, so a value that is not text still reports something
+        /// true about itself.
+        len: usize,
+        /// Capped lowercase hex.
+        hex: String,
+    },
+}
+
+/// One metadata pair, decoded for display.
+#[derive(Debug, Serialize, PartialEq, Eq)]
+pub struct MetadataPairDto {
+    pub key: String,
+    pub value: MetadataValueDto,
+}
+
 /// One committed envelope as a journal entry.
 /// One committed envelope as a journal entry.
 #[derive(Serialize)]
 #[derive(Serialize)]
 pub struct EntryDto {
 pub struct EntryDto {
     pub id: String,
     pub id: String,
     pub created_at: i64,
     pub created_at: i64,
+    /// The caller's own label for this entry, from the reserved metadata key.
+    /// Part of the content address, so an entry is identified by it as much as
+    /// by `id`. `None` when the caller set none, and `None` too when the bytes
+    /// are not text, in which case the pair appears in `metadata` instead.
+    pub reference: Option<String>,
+    /// Every other metadata pair, the reference excluded.
+    pub metadata: Vec<MetadataPairDto>,
+    /// The day the entry takes effect, when the caller set one. The commit
+    /// instant is `created_at` and is always the ledger's own clock.
+    pub value_date: Option<String>,
+    /// `None` for the default book, which every transfer is in unless an
+    /// application uses books.
+    pub book: Option<i64>,
     pub assets: Vec<EntryAssetDto>,
     pub assets: Vec<EntryAssetDto>,
 }
 }
 
 
@@ -198,6 +237,65 @@ async fn account_dto(state: &AppState, account: &Account) -> Result<AccountDto,
     })
     })
 }
 }
 
 
+/// Longest metadata value rendered as hex, in bytes. Metadata carries no size
+/// limit, and the reserved `inflight` key holds a CBOR blob, so a value is
+/// sampled rather than printed whole.
+const HEX_SAMPLE_BYTES: usize = 32;
+
+/// A metadata value as text, or `None` when the bytes are not text.
+///
+/// A caller may write any bytes and the reserved `inflight` key holds CBOR, so
+/// invalid UTF-8 is an ordinary input here rather than a failure. A control
+/// character disqualifies a value too, because a binary payload can decode as
+/// UTF-8 and still be unreadable.
+fn metadata_text(value: &[u8]) -> Option<String> {
+    let text = match str::from_utf8(value) {
+        Ok(text) => text,
+        Err(_) => return None,
+    };
+    if text.is_empty() || text.chars().any(char::is_control) {
+        return None;
+    }
+    Some(text.to_string())
+}
+
+/// A sample of a value's bytes as lowercase hex, truncated with an ellipsis so
+/// an unbounded blob cannot flood the page.
+fn metadata_hex(value: &[u8]) -> String {
+    let head: String = value
+        .iter()
+        .take(HEX_SAMPLE_BYTES)
+        .map(|b| format!("{b:02x}"))
+        .collect();
+    if value.len() > HEX_SAMPLE_BYTES {
+        return format!("{head}\u{2026}");
+    }
+    head
+}
+
+/// The metadata pairs for display.
+///
+/// The reference is held back only when it reached the entry head, so a
+/// reference whose bytes are not text still appears here rather than vanishing
+/// between the two.
+fn metadata_pairs(envelope: &Envelope, reference_shown: bool) -> Vec<MetadataPairDto> {
+    envelope
+        .metadata()
+        .iter()
+        .filter(|(key, _)| !(reference_shown && key.as_str() == REFERENCE_KEY))
+        .map(|(key, value)| MetadataPairDto {
+            key: key.clone(),
+            value: match metadata_text(value) {
+                Some(text) => MetadataValueDto::Text(text),
+                None => MetadataValueDto::Bytes {
+                    len: value.len(),
+                    hex: metadata_hex(value),
+                },
+            },
+        })
+        .collect()
+}
+
 /// Classify a created posting from the shape the resolver gave it: a payer is
 /// Classify a created posting from the shape the resolver gave it: a payer is
 /// set only for a movement output between two accounts, and change and offset
 /// set only for a movement output between two accounts, and change and offset
 /// differ by sign alone.
 /// differ by sign alone.
@@ -333,9 +431,22 @@ fn entry_dto(
         });
         });
     }
     }
 
 
+    let book = envelope.book();
+    let reference = envelope.reference().and_then(metadata_text);
     Ok(EntryDto {
     Ok(EntryDto {
         id: hex32(&record.receipt.transfer_id.0),
         id: hex32(&record.receipt.transfer_id.0),
         created_at: record.created_at,
         created_at: record.created_at,
+        metadata: metadata_pairs(envelope, reference.is_some()),
+        reference,
+        value_date: envelope.value_date().map(|d| {
+            let (year, month, day) = d.civil();
+            format!("{year:04}-{month:02}-{day:02}")
+        }),
+        book: if book == DEFAULT_BOOK {
+            None
+        } else {
+            Some(book.0)
+        },
         assets: out,
         assets: out,
     })
     })
 }
 }
@@ -562,7 +673,7 @@ impl IntoResponse for ApiError {
 #[cfg(test)]
 #[cfg(test)]
 mod tests {
 mod tests {
     use super::*;
     use super::*;
-    use kuatia_core::{EnvelopeBuilder, Receipt, TransferId};
+    use kuatia_core::{BookId, EnvelopeBuilder, Metadata, Receipt, TransferId, ValueDate};
 
 
     fn pyg() -> Arc<Asset> {
     fn pyg() -> Arc<Asset> {
         Arc::new(Asset::new(AssetId::new(1), "PYG", "\u{20b2}", 0))
         Arc::new(Asset::new(AssetId::new(1), "PYG", "\u{20b2}", 0))
@@ -608,6 +719,40 @@ mod tests {
         }
         }
     }
     }
 
 
+    /// A record whose envelope carries metadata, so the entry head has
+    /// something to show.
+    fn record_with(
+        metadata: Metadata,
+        book: BookId,
+        value_date: Option<ValueDate>,
+    ) -> TransferRecord {
+        let pyg = pyg();
+        let mut envelope = EnvelopeBuilder::new()
+            .creates(vec![
+                created(2, 100, &pyg, Some(1)),
+                created(1, -100, &pyg, None),
+            ])
+            .metadata(metadata)
+            .book(book);
+        if let Some(value_date) = value_date {
+            envelope = envelope.value_date(value_date);
+        }
+        TransferRecord {
+            envelope: envelope.build(),
+            receipt: Receipt {
+                transfer_id: TransferId([9u8; 32]),
+            },
+            created_at: 0,
+        }
+    }
+
+    fn meta(pairs: &[(&str, &[u8])]) -> Metadata {
+        pairs
+            .iter()
+            .map(|(k, v)| (k.to_string(), v.to_vec()))
+            .collect()
+    }
+
     fn index(postings: Vec<Posting>) -> HashMap<PostingId, Posting> {
     fn index(postings: Vec<Posting>) -> HashMap<PostingId, Posting> {
         postings.into_iter().map(|p| (p.id, p)).collect()
         postings.into_iter().map(|p| (p.id, p)).collect()
     }
     }
@@ -765,4 +910,136 @@ mod tests {
             .is_err()
             .is_err()
         );
         );
     }
     }
+
+    #[test]
+    fn a_reference_reaches_the_entry_head() {
+        let metadata = meta(&[(REFERENCE_KEY, b"sale_document:121753171608473607")]);
+        let entry = entry_dto(&record_with(metadata, DEFAULT_BOOK, None), &HashMap::new()).unwrap();
+
+        assert_eq!(
+            entry.reference.as_deref(),
+            Some("sale_document:121753171608473607")
+        );
+        // The reference has its own field, so it is not repeated as a pair.
+        assert!(entry.metadata.is_empty());
+    }
+
+    #[test]
+    fn a_non_reference_key_stays_a_pair() {
+        let metadata = meta(&[(REFERENCE_KEY, b"payment:7"), ("note", b"second till")]);
+        let entry = entry_dto(&record_with(metadata, DEFAULT_BOOK, None), &HashMap::new()).unwrap();
+
+        assert_eq!(entry.reference.as_deref(), Some("payment:7"));
+        assert_eq!(entry.metadata.len(), 1);
+        assert_eq!(entry.metadata[0].key, "note");
+        assert_eq!(
+            entry.metadata[0].value,
+            MetadataValueDto::Text("second till".to_string())
+        );
+    }
+
+    #[test]
+    fn a_binary_value_reports_its_length_and_hex_instead_of_text() {
+        // The shape of the reserved `inflight` key, which holds CBOR.
+        let metadata = meta(&[("inflight", &[0xa1, 0x64, 0xff, 0x00, 0xfe])]);
+        let entry = entry_dto(&record_with(metadata, DEFAULT_BOOK, None), &HashMap::new()).unwrap();
+
+        assert_eq!(entry.metadata.len(), 1);
+        assert_eq!(
+            entry.metadata[0].value,
+            MetadataValueDto::Bytes {
+                len: 5,
+                hex: "a164ff00fe".to_string()
+            }
+        );
+    }
+
+    #[test]
+    fn valid_utf8_carrying_a_control_character_is_not_text() {
+        let metadata = meta(&[("note", b"one\0two")]);
+        let entry = entry_dto(&record_with(metadata, DEFAULT_BOOK, None), &HashMap::new()).unwrap();
+
+        assert!(matches!(
+            entry.metadata[0].value,
+            MetadataValueDto::Bytes { .. }
+        ));
+    }
+
+    #[test]
+    fn a_binary_reference_falls_through_to_the_pairs() {
+        // The head only takes text, and nothing may vanish because of that.
+        let metadata = meta(&[(REFERENCE_KEY, &[0xff, 0x00])]);
+        let entry = entry_dto(&record_with(metadata, DEFAULT_BOOK, None), &HashMap::new()).unwrap();
+
+        assert_eq!(entry.reference, None);
+        assert_eq!(entry.metadata.len(), 1);
+        assert_eq!(entry.metadata[0].key, REFERENCE_KEY);
+        assert_eq!(
+            entry.metadata[0].value,
+            MetadataValueDto::Bytes {
+                len: 2,
+                hex: "ff00".to_string()
+            }
+        );
+    }
+
+    #[test]
+    fn a_long_value_is_sampled_rather_than_printed_whole() {
+        let long = vec![0xffu8; HEX_SAMPLE_BYTES * 4];
+        let hex = metadata_hex(&long);
+
+        assert_eq!(hex.chars().count(), HEX_SAMPLE_BYTES * 2 + 1);
+        assert!(hex.ends_with('\u{2026}'));
+    }
+
+    #[test]
+    fn only_a_non_default_book_is_reported() {
+        let default = entry_dto(
+            &record_with(Metadata::new(), DEFAULT_BOOK, None),
+            &HashMap::new(),
+        )
+        .unwrap();
+        assert_eq!(default.book, None);
+
+        let named = entry_dto(
+            &record_with(Metadata::new(), BookId::new(42), None),
+            &HashMap::new(),
+        )
+        .unwrap();
+        assert_eq!(named.book, Some(42));
+    }
+
+    #[test]
+    fn a_value_date_renders_as_a_calendar_day() {
+        let date = ValueDate::new(2026, 3, 9).expect("a real date");
+        let entry = entry_dto(
+            &record_with(Metadata::new(), DEFAULT_BOOK, Some(date)),
+            &HashMap::new(),
+        )
+        .unwrap();
+
+        assert_eq!(entry.value_date.as_deref(), Some("2026-03-09"));
+    }
+
+    #[test]
+    fn an_unset_value_date_is_absent() {
+        let entry = entry_dto(
+            &record_with(Metadata::new(), DEFAULT_BOOK, None),
+            &HashMap::new(),
+        )
+        .unwrap();
+
+        assert_eq!(entry.value_date, None);
+    }
+
+    #[test]
+    fn a_reference_is_carried_raw_for_the_template_to_escape() {
+        let metadata = meta(&[(REFERENCE_KEY, b"<script>alert(1)</script>")]);
+        let entry = entry_dto(&record_with(metadata, DEFAULT_BOOK, None), &HashMap::new()).unwrap();
+
+        assert_eq!(
+            entry.reference.as_deref(),
+            Some("<script>alert(1)</script>")
+        );
+    }
 }
 }

+ 55 - 10
crates/kuatia-dashboard/src/seed.rs

@@ -76,27 +76,66 @@ pub async fn populate(ledger: &Arc<Ledger>) -> Result<(), Box<dyn Error>> {
 
 
     // Fund accounts from the external boundary. Each string is parsed at its
     // Fund accounts from the external boundary. Each string is parsed at its
     // asset's own scale, so the 8-decimal BTC amount needs no special case.
     // asset's own scale, so the 8-decimal BTC amount needs no special case.
-    deposit(ledger, ALICE, ("1000.00", &usd)).await?;
-    deposit(ledger, BOB, ("500.00", &eur)).await?;
-    deposit(ledger, ALICE, ("0.50000000", &btc)).await?;
-    deposit(ledger, CAROL, ("200.00", &usd)).await?;
+    // Each carries a distinct reference, which is what a deposit needs to be
+    // its own transfer: one consumes nothing, so two of the same amount to the
+    // same account would otherwise be byte-identical and the second a replay.
+    deposit(ledger, ALICE, ("1000.00", &usd), "funding:alice-usd").await?;
+    deposit(ledger, BOB, ("500.00", &eur), "funding:bob-eur").await?;
+    deposit(ledger, ALICE, ("0.50000000", &btc), "funding:alice-btc").await?;
+    deposit(ledger, CAROL, ("200.00", &usd), "funding:carol-usd").await?;
 
 
     // Ordinary payments between held balances.
     // Ordinary payments between held balances.
-    pay(ledger, ALICE, BOB, ("150.00", &usd)).await?;
-    pay(ledger, BOB, MERCHANT, ("80.00", &eur)).await?;
-    pay(ledger, ALICE, MERCHANT, ("0.10000000", &btc)).await?;
+    pay(
+        ledger,
+        ALICE,
+        BOB,
+        ("150.00", &usd),
+        "payment:alice-bob-usd",
+    )
+    .await?;
+    pay(
+        ledger,
+        BOB,
+        MERCHANT,
+        ("80.00", &eur),
+        "payment:bob-merchant-eur",
+    )
+    .await?;
+    pay(
+        ledger,
+        ALICE,
+        MERCHANT,
+        ("0.10000000", &btc),
+        "payment:alice-merchant-btc",
+    )
+    .await?;
 
 
     // Carol spends past her balance, into overdraft.
     // Carol spends past her balance, into overdraft.
-    pay(ledger, CAROL, MERCHANT, ("250.00", &usd)).await?;
+    pay(
+        ledger,
+        CAROL,
+        MERCHANT,
+        ("250.00", &usd),
+        "payment:carol-merchant-usd",
+    )
+    .await?;
 
 
     // Alice earmarks part of her balance into her savings subaccount. The two
     // Alice earmarks part of her balance into her savings subaccount. The two
     // balances stay segregated under the same base id.
     // balances stay segregated under the same base id.
-    pay(ledger, ALICE, ALICE_SAVINGS, ("300.00", &usd)).await?;
+    pay(
+        ledger,
+        ALICE,
+        ALICE_SAVINGS,
+        ("300.00", &usd),
+        "earmark:alice-savings",
+    )
+    .await?;
 
 
     // Atomic multi-asset trade: Alice buys EUR from Bob with USD.
     // Atomic multi-asset trade: Alice buys EUR from Bob with USD.
     let trade = TransferBuilder::new()
     let trade = TransferBuilder::new()
         .pay(ALICE, BOB, ("100.00", &usd))
         .pay(ALICE, BOB, ("100.00", &usd))
         .pay(BOB, ALICE, ("90.00", &eur))
         .pay(BOB, ALICE, ("90.00", &eur))
+        .reference("trade:alice-bob-usd-eur")
         .build()?;
         .build()?;
     ledger.commit(trade).await?;
     ledger.commit(trade).await?;
 
 
@@ -121,9 +160,11 @@ async fn deposit(
     ledger: &Arc<Ledger>,
     ledger: &Arc<Ledger>,
     to: AccountId,
     to: AccountId,
     amount: (&str, &Arc<Asset>),
     amount: (&str, &Arc<Asset>),
+    reference: &str,
 ) -> Result<(), Box<dyn Error>> {
 ) -> Result<(), Box<dyn Error>> {
     let transfer = TransferBuilder::new()
     let transfer = TransferBuilder::new()
         .deposit(to, amount, EXTERNAL)
         .deposit(to, amount, EXTERNAL)
+        .reference(reference)
         .build()?;
         .build()?;
     ledger.commit(transfer).await?;
     ledger.commit(transfer).await?;
     Ok(())
     Ok(())
@@ -134,8 +175,12 @@ async fn pay(
     from: AccountId,
     from: AccountId,
     to: AccountId,
     to: AccountId,
     amount: (&str, &Arc<Asset>),
     amount: (&str, &Arc<Asset>),
+    reference: &str,
 ) -> Result<(), Box<dyn Error>> {
 ) -> Result<(), Box<dyn Error>> {
-    let transfer = TransferBuilder::new().pay(from, to, amount).build()?;
+    let transfer = TransferBuilder::new()
+        .pay(from, to, amount)
+        .reference(reference)
+        .build()?;
     ledger.commit(transfer).await?;
     ledger.commit(transfer).await?;
     Ok(())
     Ok(())
 }
 }

+ 139 - 1
crates/kuatia-dashboard/src/ui.rs

@@ -19,7 +19,7 @@ use tera::{Context, Tera};
 
 
 use crate::data::{
 use crate::data::{
     self, AccountDto, ApiError, AppState, EntryDto, EntryLineDto, EntryLineKind, EntrySide,
     self, AccountDto, ApiError, AppState, EntryDto, EntryLineDto, EntryLineKind, EntrySide,
-    EventDto, OverviewDto, PostingDto,
+    EventDto, MetadataPairDto, MetadataValueDto, OverviewDto, PostingDto,
 };
 };
 use crate::seed::account_label;
 use crate::seed::account_label;
 
 
@@ -176,11 +176,33 @@ struct EntryAssetView {
     balanced: bool,
     balanced: bool,
 }
 }
 
 
+/// A caller-supplied string shown short, with the whole of it in `title`.
+/// Metadata carries no length limit, so a long one would break the row.
+#[derive(Serialize)]
+struct TruncatedView {
+    short: String,
+    full: String,
+}
+
+#[derive(Serialize)]
+struct MetadataPairView {
+    key: String,
+    /// The text, or a byte count when the value is not text.
+    value: String,
+    /// Hover text: the whole value, or its hex when it is not text.
+    title: String,
+}
+
 #[derive(Serialize)]
 #[derive(Serialize)]
 struct EntryView {
 struct EntryView {
     short_id: String,
     short_id: String,
     full_id: String,
     full_id: String,
     time: String,
     time: String,
+    /// The caller's label for this entry, which heads it when present.
+    reference: Option<TruncatedView>,
+    metadata: Vec<MetadataPairView>,
+    value_date: Option<String>,
+    book: Option<i64>,
     assets: Vec<EntryAssetView>,
     assets: Vec<EntryAssetView>,
 }
 }
 
 
@@ -263,6 +285,39 @@ fn short_hex(hex: &str) -> String {
     format!("{}…{}", &hex[..8], &hex[hex.len() - 6..])
     format!("{}…{}", &hex[..8], &hex[hex.len() - 6..])
 }
 }
 
 
+/// Longest caller-supplied string shown in a row, in characters.
+const TEXT_DISPLAY_CHARS: usize = 48;
+
+/// Shorten a caller-supplied string for display, keeping the whole of it for
+/// the `title` attribute. Counts characters, not bytes, so a multi-byte
+/// character is never cut in half.
+fn truncate(text: &str) -> TruncatedView {
+    let short = if text.chars().count() > TEXT_DISPLAY_CHARS {
+        let head: String = text.chars().take(TEXT_DISPLAY_CHARS).collect();
+        format!("{head}\u{2026}")
+    } else {
+        text.to_string()
+    };
+    TruncatedView {
+        short,
+        full: text.to_string(),
+    }
+}
+
+/// A metadata pair as a row: its text when it has any, else its size, with the
+/// hex sample behind the hover so a value that is not text stays inspectable.
+fn metadata_pair_view(dto: &MetadataPairDto) -> MetadataPairView {
+    let (value, title) = match &dto.value {
+        MetadataValueDto::Text(text) => (truncate(text).short, text.clone()),
+        MetadataValueDto::Bytes { len, hex } => (format!("{len} bytes"), hex.clone()),
+    };
+    MetadataPairView {
+        key: dto.key.clone(),
+        value,
+        title,
+    }
+}
+
 /// Format unix milliseconds as `YYYY-MM-DD HH:MM:SS UTC` without a date crate.
 /// Format unix milliseconds as `YYYY-MM-DD HH:MM:SS UTC` without a date crate.
 fn fmt_millis(ms: i64) -> String {
 fn fmt_millis(ms: i64) -> String {
     let secs = ms.div_euclid(1000);
     let secs = ms.div_euclid(1000);
@@ -393,6 +448,10 @@ fn entry_view(dto: &EntryDto, viewpoint: Option<AccountId>) -> EntryView {
         short_id: short_hex(&dto.id),
         short_id: short_hex(&dto.id),
         full_id: dto.id.clone(),
         full_id: dto.id.clone(),
         time: fmt_millis(dto.created_at),
         time: fmt_millis(dto.created_at),
+        reference: dto.reference.as_deref().map(truncate),
+        metadata: dto.metadata.iter().map(metadata_pair_view).collect(),
+        value_date: dto.value_date.clone(),
+        book: dto.book,
         assets: dto
         assets: dto
             .assets
             .assets
             .iter()
             .iter()
@@ -600,3 +659,82 @@ async fn htmx_js() -> Response {
     )
     )
         .into_response()
         .into_response()
 }
 }
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    fn entry(reference: Option<&str>) -> EntryView {
+        EntryView {
+            short_id: "5f128a19\u{2026}d0cad6".to_string(),
+            full_id: "5f128a197488cc1e".to_string(),
+            time: "2026-12-02 23:23:38 UTC".to_string(),
+            reference: reference.map(truncate),
+            metadata: Vec::new(),
+            value_date: None,
+            book: None,
+            assets: Vec::new(),
+        }
+    }
+
+    fn render_feed(entries: Vec<EntryView>) -> String {
+        let tera = build_tera().expect("templates compile");
+        let mut ctx = Context::new();
+        ctx.insert("entries", &entries);
+        tera.render("partials/transfers.html", &ctx)
+            .expect("the feed renders")
+    }
+
+    #[test]
+    fn a_reference_heads_the_entry_and_the_hash_sits_under_it() {
+        let html = render_feed(vec![entry(Some("sale_document:7"))]);
+
+        let head = html
+            .split("entry-sub")
+            .next()
+            .expect("the head precedes the sub-row");
+        assert!(head.contains("sale_document:7"));
+        assert!(!head.contains("5f128a19"));
+        assert!(html.contains("entry-sub"));
+    }
+
+    #[test]
+    fn without_a_reference_the_hash_heads_the_entry() {
+        let html = render_feed(vec![entry(None)]);
+
+        let head = html
+            .split("entry-sub")
+            .next()
+            .expect("the head precedes the sub-row");
+        assert!(head.contains("5f128a19"));
+        assert!(!html.contains("class=\"reference\""));
+    }
+
+    #[test]
+    fn a_reference_carrying_markup_is_escaped() {
+        // Metadata is caller-controlled, so the feed's safety rests on Tera
+        // autoescaping a template named `.html`. This is that guarantee.
+        let html = render_feed(vec![entry(Some("<script>alert(1)</script>"))]);
+
+        assert!(!html.contains("<script>"));
+        assert!(html.contains("&lt;script&gt;"));
+    }
+
+    #[test]
+    fn a_long_reference_is_shortened_for_the_row_and_kept_for_the_hover() {
+        let long = "sale_document:".to_string() + &"9".repeat(80);
+        let view = truncate(&long);
+
+        assert_eq!(view.short.chars().count(), TEXT_DISPLAY_CHARS + 1);
+        assert!(view.short.ends_with('\u{2026}'));
+        assert_eq!(view.full, long);
+    }
+
+    #[test]
+    fn a_multibyte_reference_is_cut_between_characters() {
+        let text = "\u{e1}".repeat(TEXT_DISPLAY_CHARS + 10);
+        let view = truncate(&text);
+
+        assert_eq!(view.short.chars().count(), TEXT_DISPLAY_CHARS + 1);
+    }
+}

+ 28 - 0
crates/kuatia-dashboard/static/dashboard.css

@@ -265,6 +265,34 @@ table.grid tbody tr:hover {
   color: var(--muted);
   color: var(--muted);
 }
 }
 
 
+/* Plain text, because the hash beside it is the monospace element. */
+.reference {
+  font-weight: 600;
+  overflow-wrap: anywhere;
+}
+
+.entry-sub {
+  display: flex;
+  flex-wrap: wrap;
+  align-items: baseline;
+  gap: 0.2rem 0.6rem;
+  font-size: 0.75rem;
+  margin-top: 0.15rem;
+}
+
+.entry-sub .chip {
+  display: inline-block;
+  padding: 0.05rem 0.4rem;
+  border-radius: 999px;
+  background: var(--chip);
+  white-space: nowrap;
+}
+
+.meta b {
+  color: var(--text);
+  font-weight: 600;
+}
+
 .entry-asset {
 .entry-asset {
   display: flex;
   display: flex;
   align-items: baseline;
   align-items: baseline;

+ 11 - 1
crates/kuatia-dashboard/templates/partials/entry.html

@@ -1,9 +1,19 @@
 {% macro item(e) %}
 {% macro item(e) %}
 <div class="entry">
 <div class="entry">
   <div class="entry-head">
   <div class="entry-head">
+    {% if e.reference %}
+    <span class="reference" title="{{ e.reference.full }}">{{ e.reference.short }}</span>
+    {% else %}
     <code class="hash" title="{{ e.full_id }}">{{ e.short_id }}</code>
     <code class="hash" title="{{ e.full_id }}">{{ e.short_id }}</code>
+    {% endif %}
     <span class="moved">{% for a in e.assets %}{{ a.moved.text }} {% endfor %}moved</span>
     <span class="moved">{% for a in e.assets %}{{ a.moved.text }} {% endfor %}moved</span>
-    <span class="muted">{{ e.time }}</span>
+  </div>
+  <div class="entry-sub muted">
+    {% if e.reference %}<code class="hash" title="{{ e.full_id }}">{{ e.short_id }}</code>{% endif %}
+    {% if e.value_date %}<span class="chip">value {{ e.value_date }}</span>{% endif %}
+    {% if e.book %}<span class="chip">book {{ e.book }}</span>{% endif %}
+    {% for m in e.metadata %}<span class="meta" title="{{ m.title }}">{{ m.key }} <b>{{ m.value }}</b></span>{% endfor %}
+    <span>{{ e.time }}</span>
   </div>
   </div>
   {% for a in e.assets %}
   {% for a in e.assets %}
   <div class="entry-asset">
   <div class="entry-asset">

+ 60 - 0
crates/kuatia-types/src/envelope.rs

@@ -2,6 +2,7 @@
 
 
 use crate::ids::{AccountId, AccountSnapshotId, BookId, PostingId};
 use crate::ids::{AccountId, AccountSnapshotId, BookId, PostingId};
 use crate::posting::NewPosting;
 use crate::posting::NewPosting;
+use crate::transfer::REFERENCE_KEY;
 use crate::value_date::ValueDate;
 use crate::value_date::ValueDate;
 use serde::{Deserialize, Serialize};
 use serde::{Deserialize, Serialize};
 use std::collections::BTreeMap;
 use std::collections::BTreeMap;
@@ -59,6 +60,15 @@ impl Envelope {
         &self.metadata
         &self.metadata
     }
     }
 
 
+    /// The caller's reference for this entry, under the reserved
+    /// [`REFERENCE_KEY`](crate::REFERENCE_KEY). Bytes rather than a string: a
+    /// caller writing the map directly is not held to the UTF-8 that
+    /// [`TransferBuilder::reference`](crate::TransferBuilder::reference)
+    /// writes.
+    pub fn reference(&self) -> Option<&[u8]> {
+        self.metadata.get(REFERENCE_KEY).map(Vec::as_slice)
+    }
+
     /// Deduplicated, sorted list of account references in the created postings.
     /// Deduplicated, sorted list of account references in the created postings.
     pub fn referenced_accounts(&self) -> Vec<AccountId> {
     pub fn referenced_accounts(&self) -> Vec<AccountId> {
         let mut ids: Vec<AccountId> = self.creates.iter().map(|p| p.owner).collect();
         let mut ids: Vec<AccountId> = self.creates.iter().map(|p| p.owner).collect();
@@ -126,3 +136,53 @@ impl EnvelopeBuilder {
         self.envelope
         self.envelope
     }
     }
 }
 }
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use crate::TransferBuilder;
+    use crate::asset::Asset;
+    use crate::ids::AssetId;
+    use std::sync::Arc;
+
+    fn usd() -> Arc<Asset> {
+        Arc::new(Asset::new(AssetId::new(1), "USD", "$", 2))
+    }
+
+    #[test]
+    fn reference_reads_back_what_the_builder_wrote() {
+        let transfer = TransferBuilder::new()
+            .pay(AccountId::new(1), AccountId::new(2), (100, &usd()))
+            .reference("sale_document:7")
+            .build()
+            .expect("amounts convert");
+        let envelope = EnvelopeBuilder::new()
+            .metadata(transfer.metadata.clone())
+            .build();
+
+        assert_eq!(envelope.reference(), Some(&b"sale_document:7"[..]));
+    }
+
+    #[test]
+    fn no_reference_set_is_none() {
+        assert_eq!(EnvelopeBuilder::new().build().reference(), None);
+    }
+
+    #[test]
+    fn a_reference_written_as_raw_bytes_still_reads_back() {
+        let mut metadata = Metadata::new();
+        metadata.insert(REFERENCE_KEY.to_string(), vec![0xff, 0x00, 0xfe]);
+        let envelope = EnvelopeBuilder::new().metadata(metadata).build();
+
+        assert_eq!(envelope.reference(), Some(&[0xff, 0x00, 0xfe][..]));
+    }
+
+    #[test]
+    fn an_unrelated_metadata_key_is_not_a_reference() {
+        let mut metadata = Metadata::new();
+        metadata.insert("note".to_string(), b"hello".to_vec());
+        let envelope = EnvelopeBuilder::new().metadata(metadata).build();
+
+        assert_eq!(envelope.reference(), None);
+    }
+}

+ 1 - 0
doc/crates.md

@@ -37,6 +37,7 @@ dependencies (`sha2`, `serde`, `bitflags`).
 | `Transfer` | Atomic unit: consumes postings + creates postings + metadata |
 | `Transfer` | Atomic unit: consumes postings + creates postings + metadata |
 | `EnvelopeBuilder` | Fluent builder for `Envelope` construction (the resolved form; `TransferBuilder` builds the intent) |
 | `EnvelopeBuilder` | Fluent builder for `Envelope` construction (the resolved form; `TransferBuilder` builds the intent) |
 | `REFERENCE_KEY` | Reserved metadata key for a caller's transfer reference, set via `TransferBuilder::reference` |
 | `REFERENCE_KEY` | Reserved metadata key for a caller's transfer reference, set via `TransferBuilder::reference` |
+| `Envelope::reference()` | The caller's reference bytes from the reserved key, or `None`. Bytes, not a string: a caller writing the metadata map directly is not held to UTF-8 |
 | `ValueDate` | The day an entry takes effect, as days since 1970-01-01. A calendar day rather than an instant, so no timezone shifts it. `ValueDate::new(y, m, d)` rejects a date that does not exist |
 | `ValueDate` | The day an entry takes effect, as days since 1970-01-01. A calendar day rather than an instant, so no timezone shifts it. `ValueDate::new(y, m, d)` rejects a date that does not exist |
 | `Account` | Versioned entity with flags, book, metadata. `Account::new(id)` allows overdraft by default; `Account::debit_must_not_exceed_credit(id)` forbids it; `Account::forbids_overdraft()` queries the constraint |
 | `Account` | Versioned entity with flags, book, metadata. `Account::new(id)` allows overdraft by default; `Account::debit_must_not_exceed_credit(id)` forbids it; `Account::forbids_overdraft()` queries the constraint |
 | `AccountFlags` | Bitflags: `FROZEN`, `CLOSED`, `DEBIT_MUST_NOT_EXCEED_CREDIT` (when set, the account's debits may not exceed its credits: balance stays `>= 0`, no negative postings) |
 | `AccountFlags` | Bitflags: `FROZEN`, `CLOSED`, `DEBIT_MUST_NOT_EXCEED_CREDIT` (when set, the account's debits may not exceed its credits: balance stays `>= 0`, no negative postings) |