|
@@ -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>")
|
|
|
|
|
+ );
|
|
|
|
|
+ }
|
|
|
}
|
|
}
|