Skip to main content

af_price_updates/
aftermath.rs

1//! Aftermath signed price update format and feed identifiers.
2
3pub use crate::aftermath_id_set::PriceFeedIdSet;
4pub use crate::aftermath_writer::UnsignedPriceUpdates;
5pub use crate::pyth_lazer::MarketSession;
6use crate::{
7    keccak::keccak256,
8    reader::{Reader, decode_base64},
9    sorted_set::SortedSetSlice,
10};
11use bytes::{Bytes, BytesMut};
12use serde::{Deserialize, Serialize};
13use std::io::{Error, ErrorKind};
14
15/// Aftermath price feed ID.
16#[derive(
17    Clone, Copy, Debug, Default, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize,
18)]
19#[repr(transparent)]
20pub struct PriceFeedId(pub u32);
21
22impl std::fmt::Display for PriceFeedId {
23    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
24        <u32 as std::fmt::Display>::fmt(&self.0, f)
25    }
26}
27
28impl std::str::FromStr for PriceFeedId {
29    type Err = std::num::ParseIntError;
30    fn from_str(s: &str) -> Result<Self, Self::Err> {
31        s.parse::<u32>().map(PriceFeedId)
32    }
33}
34
35/// Little-endian bytes spell "AFUP" (Aftermath feed update protocol).
36pub(crate) const UPDATE_MAGIC: u32 = u32::from_le_bytes(*b"AFUP");
37
38/// Length of the recoverable secp256k1 signature trailing an update: the 64-byte compact
39/// signature `r ‖ s` followed by the recovery ID.
40pub const SIGNATURE_LEN: usize = 65;
41
42/// An Aftermath price update: a payload of feeds followed by its signature.
43///
44/// The last 65 bytes are the signature and everything before them is the payload, which are
45/// passed separately to `af_verifier::verifier::verify_and_parse` on-chain.
46///
47/// Constructors check the layout, including that feed IDs are strictly increasing (sorted and
48/// duplicate-free). They never verify the signature, which is left to
49/// `af_verifier::verifier::verify_and_parse`.
50///
51/// To serialize and sign an update, see [`UnsignedPriceUpdates`].
52#[derive(Clone, Debug, Eq, Hash, PartialEq)]
53pub struct PriceUpdates(Bytes);
54
55impl TryFrom<BytesMut> for PriceUpdates {
56    type Error = Error;
57    /// Copies the bytes, like [`PriceUpdates::from_slice`], so the update does not keep a
58    /// larger buffer that `bytes` may share alive.
59    fn try_from(bytes: BytesMut) -> Result<Self, Self::Error> {
60        Self::from_slice(&bytes)
61    }
62}
63
64impl PriceUpdates {
65    /// Checks and copies an update.
66    pub fn from_slice(bytes: &[u8]) -> Result<Self, Error> {
67        check_bytes(bytes)?;
68        Ok(Self(Bytes::copy_from_slice(bytes)))
69    }
70    /// Checks an update and keeps `bytes` without copying.
71    ///
72    /// Use [`Self::from_slice`] instead to copy the update out of a larger buffer.
73    pub fn from_bytes(bytes: Bytes) -> Result<Self, Error> {
74        check_bytes(&bytes)?;
75        Ok(Self(bytes))
76    }
77    /// Decodes a standard, padded base64 update and checks it.
78    ///
79    /// Decodes in place when `base64` is the only owner of its buffer, such as a `String`, a
80    /// `Vec<u8>` or the bytes of an unshared `bytestring::ByteString`, and copies it otherwise.
81    pub fn from_base64(base64: impl Into<Bytes>) -> Result<Self, Error> {
82        Self::from_bytes(decode_base64(base64.into(), "Aftermath")?)
83    }
84    /// The whole update, including its signature.
85    pub fn as_bytes(&self) -> &[u8] {
86        &self.0
87    }
88    /// The whole update, including its signature, to share without copying.
89    pub const fn bytes(&self) -> &Bytes {
90        &self.0
91    }
92    /// The whole update, including its signature, without copying.
93    pub fn into_bytes(self) -> Bytes {
94        self.0
95    }
96    /// The signed payload, without the trailing signature.
97    pub fn payload(&self) -> &[u8] {
98        self.split().0
99    }
100    /// The recoverable secp256k1 signature over [`Self::payload`].
101    pub fn signature(&self) -> &[u8; SIGNATURE_LEN] {
102        self.split().1
103    }
104    /// Keccak-256 of [`Self::payload`]: the prehash that the signer signed, and that
105    /// `af_verifier` recovers the signer's public key from.
106    pub fn digest(&self) -> [u8; 32] {
107        keccak256(self.payload())
108    }
109    /// Timestamp of the update in microseconds.
110    pub fn timestamp(&self) -> u64 {
111        let mut reader = Reader(self.payload());
112        // Skip magic.
113        reader.skip(4).expect("checked on construction");
114        reader.take_u64().expect("checked on construction")
115    }
116    /// Number of feeds in the update.
117    pub fn feed_count(&self) -> usize {
118        self.feeds().len()
119    }
120    /// Feeds of this update in strictly increasing feed ID order.
121    ///
122    /// Construction guarantees that the IDs are sorted and duplicate-free.
123    pub fn feeds(&self) -> impl Clone + ExactSizeIterator<Item = Feed> {
124        let mut reader = Reader(self.payload());
125        // Skip magic, timestamp.
126        reader.skip(4 + 8).expect("checked on construction");
127        let feed_count = reader.take_vec_length().expect("checked on construction");
128        (0..feed_count).map(move |_| take_feed(&mut reader).expect("checked on construction"))
129    }
130    /// The feed with `feed_id`, if any.
131    ///
132    /// Stops parsing at the first feed with a greater ID, since feed IDs are strictly increasing.
133    pub fn feed(&self, feed_id: PriceFeedId) -> Option<Feed> {
134        self.feeds()
135            .find(|feed| feed.feed_id >= feed_id)
136            .filter(|feed| feed.feed_id == feed_id)
137    }
138    /// Returns whether the feeds in this update exactly match `feed_ids`.
139    ///
140    /// Pass a reference to a [`PriceFeedIdSet`], [`SortedSet`](crate::sorted_set::SortedSet), or
141    /// [`ArcSortedSet`](crate::sorted_set::ArcSortedSet); deref coercion borrows its
142    /// [`SortedSetSlice`] view. Both the update and `feed_ids` are guaranteed to be sorted and
143    /// duplicate-free, so this method compares them directly without allocating.
144    pub fn matches_set(&self, feed_ids: &SortedSetSlice<PriceFeedId>) -> bool {
145        self.feeds()
146            .map(|feed| feed.feed_id)
147            .eq(feed_ids.iter().copied())
148    }
149    fn split(&self) -> (&[u8], &[u8; SIGNATURE_LEN]) {
150        self.0.split_last_chunk().expect("checked on construction")
151    }
152}
153
154/// A parsed Aftermath feed.
155///
156/// Optional properties are `None` when they were **not reported** in this update, which is
157/// semantically distinct from a value of zero.
158#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
159pub struct Feed {
160    /// ID of the feed.
161    pub feed_id: PriceFeedId,
162    /// Aggregate market price (mantissa). Use with exponent for actual price.
163    pub price: i64,
164    /// Decimal exponent: `actual_price = mantissa * 10^exponent`.
165    pub exponent: i16,
166    /// Timestamp when price was last generated for this feed (μs).
167    pub feed_update_timestamp: u64,
168    /// Number of contributing publishers.
169    pub publisher_count: u16,
170    /// Session: regular, preMarket, postMarket, overNight, closed.
171    pub market_session: MarketSession,
172    /// Price uncertainty; higher = more disagreement.
173    pub confidence: Option<i64>,
174    /// Highest bid across publishers.
175    pub best_bid_price: Option<i64>,
176    /// Lowest ask across publishers.
177    pub best_ask_price: Option<i64>,
178    /// Exponential moving average of the price.
179    pub ema_price: Option<i64>,
180    /// Exponential moving average of the confidence.
181    pub ema_confidence: Option<u64>,
182    /// Funding rate (perpetual futures).
183    pub funding_rate: Option<i64>,
184    /// When funding rate was last calculated (μs).
185    pub funding_timestamp: Option<u64>,
186    /// Interval between funding updates (μs).
187    pub funding_rate_interval: Option<u64>,
188}
189
190impl Feed {
191    /// Returns `true` when the market session is reported as [`MarketSession::Closed`].
192    pub fn is_market_closed(&self) -> bool {
193        self.market_session == MarketSession::Closed
194    }
195}
196
197/// Mirrors `af_verifier::feed::parse_from_cursor`.
198fn take_feed(reader: &mut Reader<'_>) -> Result<Feed, Error> {
199    let mut feed = Feed {
200        feed_id: PriceFeedId(reader.take_u32()?),
201        price: reader.take_i64()?,
202        exponent: reader.take_i16()?,
203        feed_update_timestamp: reader.take_u64()?,
204        publisher_count: reader.take_u16()?,
205        market_session: MarketSession::from(reader.take_u16()?),
206        ..Default::default()
207    };
208    let property_count = reader.take_u8()?;
209    for _ in 0..property_count {
210        let property_id = reader.take_u8()?;
211        match property_id {
212            0 => feed.confidence = Some(reader.take_i64()?),
213            1 => feed.best_bid_price = Some(reader.take_i64()?),
214            2 => feed.best_ask_price = Some(reader.take_i64()?),
215            3 => feed.ema_price = Some(reader.take_i64()?),
216            4 => feed.ema_confidence = Some(reader.take_u64()?),
217            5 => feed.funding_rate = Some(reader.take_i64()?),
218            6 => feed.funding_timestamp = Some(reader.take_u64()?),
219            7 => feed.funding_rate_interval = Some(reader.take_u64()?),
220            _ => {
221                return Err(Error::new(
222                    ErrorKind::InvalidData,
223                    format!("Aftermath invalid property ID: {property_id}"),
224                ));
225            }
226        }
227    }
228    Ok(feed)
229}
230
231/// Mirrors `af_verifier::update::parse`.
232fn check_bytes(bytes: &[u8]) -> Result<(), Error> {
233    let (update, _signature) = bytes.split_last_chunk::<SIGNATURE_LEN>().ok_or_else(|| {
234        Error::new(
235            ErrorKind::UnexpectedEof,
236            "Aftermath signed price updates are shorter than a signature",
237        )
238    })?;
239    let mut reader = Reader(update);
240    if reader.take_u32()? != UPDATE_MAGIC {
241        return Err(Error::new(
242            ErrorKind::InvalidData,
243            "Aftermath invalid update magic number",
244        ));
245    }
246    let _timestamp = reader.take_u64()?;
247    let feed_count = reader.take_vec_length()?;
248    let mut prev_feed_id = None;
249    for _ in 0..feed_count {
250        let feed = take_feed(&mut reader)?;
251        // Strict increase makes the feeds a sorted set and supports early-exit lookup by ID.
252        if prev_feed_id.is_some_and(|prev_feed_id| feed.feed_id <= prev_feed_id) {
253            return Err(Error::new(
254                ErrorKind::InvalidData,
255                "Aftermath feed IDs are not strictly increasing",
256            ));
257        }
258        prev_feed_id = Some(feed.feed_id);
259    }
260    reader.assert_eof()?;
261    Ok(())
262}
263
264#[cfg(test)]
265pub(crate) mod tests {
266    use super::*;
267    use crate::sorted_set::{ArcSortedSet, SortedSet};
268    use base64ct::{Base64, Encoding as _};
269
270    pub(crate) const TIMESTAMP: u64 = 1_700_000_000_123_456;
271    pub(crate) const SIGNATURE: [u8; SIGNATURE_LEN] = [0xab; SIGNATURE_LEN];
272
273    /// Serializes a signed update, taking the ULEB128 feed count as raw bytes.
274    pub(crate) fn signed_update(feed_count: &[u8], feeds: &[u8]) -> Vec<u8> {
275        let mut bytes = b"AFUP".to_vec();
276        bytes.extend_from_slice(&TIMESTAMP.to_le_bytes());
277        bytes.extend_from_slice(feed_count);
278        bytes.extend_from_slice(feeds);
279        bytes.extend_from_slice(&SIGNATURE);
280        bytes
281    }
282
283    /// Serializes a feed without optional properties.
284    pub(crate) fn mandatory_feed(
285        feed_id: u32,
286        price: i64,
287        exponent: i16,
288        market_session: u16,
289    ) -> Vec<u8> {
290        let mut bytes = Vec::new();
291        bytes.extend_from_slice(&feed_id.to_le_bytes());
292        bytes.extend_from_slice(&price.to_le_bytes());
293        bytes.extend_from_slice(&exponent.to_le_bytes());
294        bytes.extend_from_slice(&TIMESTAMP.to_le_bytes());
295        bytes.extend_from_slice(&42u16.to_le_bytes());
296        bytes.extend_from_slice(&market_session.to_le_bytes());
297        bytes.push(0);
298        bytes
299    }
300
301    /// Serializes a feed with every optional property, valued `100 + property ID`.
302    pub(crate) fn feed_with_all_properties() -> Vec<u8> {
303        let mut bytes = mandatory_feed(1, 1, 0, 0);
304        *bytes.last_mut().unwrap() = 8;
305        for property_id in 0..8u8 {
306            bytes.push(property_id);
307            bytes.extend_from_slice(&(u64::from(property_id) + 100).to_le_bytes());
308        }
309        bytes
310    }
311
312    fn signed_update_with_feed_ids(feed_ids: &[u32]) -> Vec<u8> {
313        let feeds: Vec<u8> = feed_ids
314            .iter()
315            .flat_map(|&feed_id| mandatory_feed(feed_id, 1, 0, 0))
316            .collect();
317        signed_update(&[feed_ids.len() as u8], &feeds)
318    }
319
320    #[test]
321    fn parse_mandatory_fields() {
322        let bytes = signed_update(&[1], &mandatory_feed(0x7856_3412, -10, -8, 4));
323        let updates = PriceUpdates::from_slice(&bytes).unwrap();
324
325        assert_eq!(updates.timestamp(), TIMESTAMP);
326        assert_eq!(updates.feed_count(), 1);
327        let feed = updates.feeds().next().unwrap();
328        assert_eq!(
329            feed,
330            Feed {
331                feed_id: PriceFeedId(0x7856_3412),
332                price: -10,
333                exponent: -8,
334                feed_update_timestamp: TIMESTAMP,
335                publisher_count: 42,
336                market_session: MarketSession::Closed,
337                ..Default::default()
338            },
339        );
340        assert!(feed.is_market_closed());
341    }
342
343    #[test]
344    fn parse_optional_properties() {
345        let bytes = signed_update(&[1], &feed_with_all_properties());
346        let feed = PriceUpdates::from_slice(&bytes)
347            .unwrap()
348            .feeds()
349            .next()
350            .unwrap();
351
352        assert_eq!(feed.confidence, Some(100));
353        assert_eq!(feed.best_bid_price, Some(101));
354        assert_eq!(feed.best_ask_price, Some(102));
355        assert_eq!(feed.ema_price, Some(103));
356        assert_eq!(feed.ema_confidence, Some(104));
357        assert_eq!(feed.funding_rate, Some(105));
358        assert_eq!(feed.funding_timestamp, Some(106));
359        assert_eq!(feed.funding_rate_interval, Some(107));
360    }
361
362    #[test]
363    fn parse_uleb128_feed_count() {
364        let feeds: Vec<u8> = (0..128)
365            .flat_map(|feed_id| mandatory_feed(feed_id, 1, 0, 0))
366            .collect();
367        // 128 encoded as ULEB128, proving the count is not a single u8.
368        let bytes = signed_update(&[0x80, 0x01], &feeds);
369        let updates = PriceUpdates::from_slice(&bytes).unwrap();
370
371        assert_eq!(updates.feed_count(), 128);
372        assert!(updates.matches_set(&(0..128).map(PriceFeedId).collect::<SortedSet<_>>()));
373        assert!(!updates.matches_set(&(0..127).map(PriceFeedId).collect::<SortedSet<_>>()));
374        assert!(!updates.matches_set(&(0..129).map(PriceFeedId).collect::<SortedSet<_>>()));
375    }
376
377    #[test]
378    fn update_bytes_and_signature() {
379        let bytes = signed_update_with_feed_ids(&[1, 5]);
380        let updates = PriceUpdates::from_bytes(Bytes::from(bytes.clone())).unwrap();
381
382        assert_eq!(updates.as_bytes(), bytes);
383        assert_eq!(updates.payload(), &bytes[..bytes.len() - SIGNATURE_LEN]);
384        assert_eq!(updates.signature(), &SIGNATURE);
385        assert!(updates.matches_set(&PriceFeedIdSet::from([PriceFeedId(5), PriceFeedId(1)])));
386    }
387
388    #[test]
389    fn bytes_are_shared() {
390        let bytes = Bytes::from(signed_update_with_feed_ids(&[1, 5]));
391        let updates = PriceUpdates::from_bytes(bytes.clone()).unwrap();
392
393        assert_eq!(updates.bytes().as_ptr(), bytes.as_ptr());
394        assert_eq!(updates.into_bytes(), bytes);
395    }
396
397    #[test]
398    fn feed_by_id() {
399        let updates = PriceUpdates::from_slice(&signed_update_with_feed_ids(&[1, 5, 9])).unwrap();
400
401        assert_eq!(
402            updates.feed(PriceFeedId(5)).unwrap().feed_id,
403            PriceFeedId(5)
404        );
405        assert_eq!(
406            updates.feed(PriceFeedId(9)).unwrap().feed_id,
407            PriceFeedId(9)
408        );
409        for missing in [0, 4, 6, 10] {
410            assert_eq!(updates.feed(PriceFeedId(missing)), None, "{missing}");
411        }
412    }
413
414    #[test]
415    fn parse_unknown_market_session() {
416        let bytes = signed_update(&[1], &mandatory_feed(1, 1, 0, 5));
417        let feed = PriceUpdates::from_slice(&bytes)
418            .unwrap()
419            .feeds()
420            .next()
421            .unwrap();
422
423        assert_eq!(feed.market_session, MarketSession::Unknown(5));
424        assert!(!feed.is_market_closed());
425    }
426
427    #[test]
428    fn from_base64() {
429        let bytes = signed_update_with_feed_ids(&[1, 5]);
430        let base64 = Base64::encode_string(&bytes);
431        let updates = PriceUpdates::from_base64(base64).unwrap();
432
433        assert_eq!(updates, PriceUpdates::from_slice(&bytes).unwrap());
434    }
435
436    #[test]
437    fn reject_duplicate_feed_ids() {
438        let bytes = signed_update_with_feed_ids(&[1, 5, 5]);
439        let err = PriceUpdates::from_slice(&bytes).unwrap_err();
440
441        assert_eq!(err.kind(), ErrorKind::InvalidData);
442        assert_eq!(
443            err.to_string(),
444            "Aftermath feed IDs are not strictly increasing"
445        );
446    }
447
448    #[test]
449    fn matches_set_with_sorted_set_and_checked_slice() {
450        let updates = PriceUpdates::from_slice(&signed_update_with_feed_ids(&[1, 5])).unwrap();
451        let requested = SortedSet::from([PriceFeedId(5), PriceFeedId(1)]);
452
453        assert!(updates.matches_set(&requested));
454        assert!(updates.matches_set(&ArcSortedSet::from([PriceFeedId(5), PriceFeedId(1)])));
455        let ids = [PriceFeedId(1), PriceFeedId(5)];
456        assert!(updates.matches_set(SortedSetSlice::try_from_slice(&ids).unwrap()));
457    }
458
459    #[test]
460    fn reject_invalid_updates() {
461        let valid = signed_update_with_feed_ids(&[1, 5]);
462        let update_len = valid.len() - SIGNATURE_LEN;
463
464        let mut invalid_magic = valid.clone();
465        invalid_magic[0] = b'X';
466
467        let mut trailing_data = valid[..update_len].to_vec();
468        trailing_data.push(0);
469        trailing_data.extend_from_slice(&SIGNATURE);
470
471        let mut feed_count_too_large = valid.clone();
472        feed_count_too_large[12] = 3;
473
474        let mut invalid_property = mandatory_feed(1, 1, 0, 0);
475        *invalid_property.last_mut().unwrap() = 1;
476        invalid_property.push(8);
477        invalid_property.extend_from_slice(&0u64.to_le_bytes());
478
479        let cases = [
480            ("unsorted", signed_update_with_feed_ids(&[1, 5, 4])),
481            ("invalid magic", invalid_magic),
482            ("trailing data", trailing_data),
483            ("truncated", valid[..valid.len() - 1].to_vec()),
484            ("no signature", valid[..SIGNATURE_LEN - 1].to_vec()),
485            ("feed count too large", feed_count_too_large),
486            ("invalid property", signed_update(&[1], &invalid_property)),
487        ];
488        for (name, bytes) in cases {
489            assert!(PriceUpdates::from_slice(&bytes).is_err(), "{name}");
490        }
491    }
492}