1use crate::sha512_half;
20use crate::shamap::Hash;
21use crate::stobject::{self, FieldId, types};
22
23pub const LEDGER_HASHES: u16 = 0x0068;
25pub const HASHES: FieldId = FieldId::new(types::VECTOR256, 2);
27const SPACE: [u8; 2] = [0x00, 0x73];
29
30pub fn short_key() -> Hash {
32 sha512_half(&SPACE)
33}
34
35pub fn long_key(seq: u32) -> Hash {
38 let mut b = SPACE.to_vec();
39 b.extend_from_slice(&(seq >> 16).to_be_bytes());
40 sha512_half(&b)
41}
42
43pub fn covering(seq: u32) -> u32 {
46 seq.div_ceil(256) * 256
47}
48
49pub fn hashes(object: &[u8]) -> Result<Vec<Hash>, String> {
51 let fields = stobject::fields(object).map_err(|e| e.to_string())?;
52 let kind = stobject::find(&fields, stobject::fields::LEDGER_ENTRY_TYPE)
53 .and_then(|v| v.try_into().ok())
54 .map(u16::from_be_bytes);
55 if kind != Some(LEDGER_HASHES) {
56 return Err("object is not a LedgerHashes entry".into());
57 }
58 let v = stobject::find(&fields, HASHES).ok_or("LedgerHashes has no Hashes field")?;
59 match v.as_chunks::<32>() {
60 (hashes, []) => Ok(hashes.to_vec()),
61 _ => Err("Hashes is not a list of 32-byte hashes".into()),
62 }
63}
64
65#[cfg(test)]
66mod tests {
67 use super::*;
68
69 #[test]
70 fn keys_and_covering_ledger() {
71 assert_eq!(
73 hex::encode_upper(short_key()),
74 "B4979A36CDC7F3D3D5C31A4EAE2AC7D7209DDA877588B9AFC66799692AB0D66B"
75 );
76 assert_eq!(long_key(87_000_064), long_key(86_966_272));
77 assert_ne!(long_key(87_000_064), long_key(87_031_808));
78 assert_eq!(covering(86_994_501), 86_994_688);
79 assert_eq!(covering(86_994_688), 86_994_688);
80 }
81
82 #[test]
83 fn hashes_of_an_object() {
84 let mut o = vec![0x11, 0x00, 0x68];
85 o.extend([0x02, 0x13, 64]);
86 o.extend([1u8; 32]);
87 o.extend([2u8; 32]);
88 assert_eq!(hashes(&o).unwrap(), vec![[1u8; 32], [2u8; 32]]);
89 o[2] = 0x61;
90 assert!(hashes(&o).is_err());
91 }
92}